<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by sai on Medium]]></title>
        <description><![CDATA[Stories by sai on Medium]]></description>
        <link>https://medium.com/@forswayamnptelcourse?source=rss-ca1017950450------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b5rdDUER2dGgVOX_</url>
            <title>Stories by sai on Medium</title>
            <link>https://medium.com/@forswayamnptelcourse?source=rss-ca1017950450------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:06:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@forswayamnptelcourse/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[llm prompts for 365]]></title>
            <link>https://medium.com/@forswayamnptelcourse/llm-prompts-for-365-3bde31745ac9?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bde31745ac9</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 06:47:14 GMT</pubDate>
            <atom:updated>2026-12-04T06:53:06.196Z</atom:updated>
            <content:encoded><![CDATA[<pre>Act as a candid skip-level manager doing my performance review. Your job is to find my weaknesses, not reassure me. No praise unless backed by specific evidence.<br><br>CONTEXT: I&#39;m Sai Charan, AI Engineer at State Street, promoted to Emerging Lead in April 2026. My work: LLM observability, agentic AI, RAG pipelines, LLM evaluation, AI Control Plane, Ask SS chatbot.<br>[Paste your level expectations / competency framework here]<br><br>PERIOD: [1 Apr 2026 – 30 Jun 2026]<br>SOURCES: My Outlook (sent and received), Teams chats and channels, meeting transcripts and recaps, calendar, and documents I authored or edited.<br><br>ACCURACY RULES (non-negotiable):<br>- Only state what you can point to in a specific email, chat, meeting or document. Cite it: date + subject/chat/meeting name.<br>- No source = don&#39;t say it. Write &quot;insufficient evidence&quot; instead.<br>- Never invent quotes, dates, names, numbers or outcomes. Quote exact words only if they appear in the source.<br>- Label every point as OBSERVED (directly in the source) or INFERRED (your interpretation). Keep inferences minimal.<br>- If sources conflict, show both. Don&#39;t pick one silently.<br>- Don&#39;t soften criticism or pad with generic career advice.<br>- Give more weight to feedback from my manager, leadership and stakeholders than to peer chatter.<br>- At the end, list what you could NOT access or check.<br><br>SEARCH STRATEGY (be efficient, not shallow):<br>- Start with high-signal sources: emails/chats from my manager and leadership, meeting recaps with action items assigned to me, threads where I&#39;m @mentioned, and messages containing words like &quot;feedback&quot;, &quot;follow up&quot;, &quot;pending&quot;, &quot;delay&quot;, &quot;escalation&quot;, &quot;thanks&quot;, &quot;great work&quot;.<br>- Then sample my sent emails and Teams messages to judge tone, clarity and response time.<br>- Skip automated notifications, calendar spam, newsletters and FYI-only threads.<br>- Don&#39;t repeat the same evidence under multiple headings. Cite it once and refer back to it.<br>- Keep the output tight: bullets, no filler, no restating my question.<br><br>ASSESS ME ON:<br>1. Delivery &amp; ownership – what I shipped, what slipped, deadlines missed<br>2. Reliability – commitments/action items I took on vs. actually closed<br>3. Communication – clarity, response time, tone, over/under-communicating<br>4. Meetings – preparedness, contribution, whether I drive or just attend<br>5. Stakeholder management – how I handle escalations, pushback, expectations<br>6. Leadership – mentoring, unblocking others, decisions I drove<br>7. Visibility &amp; influence – is my work known beyond my immediate team?<br>8. Time management – calendar load, focus time, after-hours work patterns<br>9. Feedback received – praise, criticism, repeated asks, and whether I acted on them<br><br>OUTPUT:<br>- 3-line brutally honest summary<br>- Top 3 strengths (with evidence)<br>- Top 3 weaknesses (with evidence)<br>- Dropped balls: things I said I&#39;d do with no visible follow-through<br>- Recurring patterns others noticed that I may not have<br>- Sources you could not access or verify</pre><p>second</p><pre>Using ONLY the three quarterly reviews above, give me the following. Do not add new claims without a citation. If something isn&#39;t supported by the evidence, say &quot;insufficient evidence&quot;.<br><br>1. Trend: what improved, what got worse, what stayed stuck from Apr to now<br>2. START doing (max 5) – specific, observable behaviours<br>3. STOP doing (max 5) – with the evidence that it&#39;s hurting me<br>4. CONTINUE but do better (max 5)<br>5. Where I stand: am I performing at Emerging Lead, below it, or already at the next level? Gaps to the next level, ranked by impact.<br>6. 90-day plan: 3 measurable goals, each with a metric I can track monthly<br>7. 5 questions I should ask my manager to check what you couldn&#39;t see<br><br>Be direct. If I&#39;m not ready for the next level, say so and why. Label each point OBSERVED or INFERRED.</pre><p>last</p><p>Review your previous answer. For each claim, check whether the cited source actually supports it. List any claim that is unsupported, exaggerated or inferred without labelling, and correct it.</p><p>final</p><pre>===== PROMPT 1: Commitments &amp; action items =====<br>Search my Outlook, Teams chats, and meeting recaps/transcripts from 1 Apr 2026 to 30 Jun 2026. List every action item or commitment assigned to me or that I agreed to do. For each: date, source (meeting/email/chat name), what I committed to, and whether you can find evidence it was completed. Only include items you actually found. If you find nothing, say so — do not guess.<br><br>===== PROMPT 2: Feedback received =====<br>Search my emails and Teams messages from 1 Apr 2026 to 30 Jun 2026 for feedback I received from my manager, leadership, or stakeholders — appreciation, concerns, change requests, or follow-ups. List each with date, sender, source, and a short factual summary. Only include what you actually found. Do not paraphrase in a way that changes meaning.<br><br>===== PROMPT 3: Work delivered =====<br>From my emails, Teams chats and meeting recaps between 1 Apr 2026 and 30 Jun 2026, list the main work items I delivered or contributed to (e.g. LLM observability, AI Control Plane, Ask SS, RAG pipelines, LLM evaluation). For each: date, source, what I did, and outcome if mentioned. Only include what you actually found.<br><br>===== PROMPT 4: Meetings &amp; time =====<br>From my calendar and meetings between 1 Apr 2026 and 30 Jun 2026: summarize my meeting load, meetings I organized vs. attended, meetings where I presented or led discussion, and any recurring follow-ups or reminders sent to me. Cite sources for each point.<br><br>===== PROMPT 5: Follow-ups, delays, escalations =====<br>Find threads between 1 Apr 2026 and 30 Jun 2026 where someone followed up with me more than once, mentioned a delay, or escalated something involving my work. List date, source, and a factual summary. Only include what you actually found.<br><br>&gt;&gt;&gt; Repeat Prompts 1–5 for: 1 Jul 2026 – 30 Sep 2026, then 1 Oct 2026 – today &lt;&lt;&lt;<br><br>===== PROMPT 6: Self-development reflection =====<br>I want to grow in my career and take on more responsibility. Using ONLY the facts you found above across all periods, help me reflect on my own work for self-development:<br><br>1. Patterns that show where I&#39;m consistently strong (with source references)<br>2. Patterns that suggest areas I could develop (with source references)<br>3. What I should START, STOP, and CONTINUE doing — each tied to specific evidence<br>4. How my work changed from April to now — what improved, what stayed the same<br>5. Skills or behaviours to build to handle bigger responsibilities as a lead<br>6. A practical 90-day development plan with 3 measurable goals<br>7. Questions I should ask my manager to fill gaps you couldn&#39;t see<br><br>Rules: Use only the evidence above. Mark interpretations as INFERRED. If evidence is missing, say so rather than guessing. Be honest and specific — don&#39;t soften or pad.<br><br>===== PROMPT 7: Self-check =====<br>Review your previous answer. For each claim, confirm the cited source actually supports it. List any claim that is unsupported, exaggerated, or an unlabelled inference, and correct it.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bde31745ac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TrueFoundry Teardown: AI Gateway & Control Plane Analysis]]></title>
            <link>https://medium.com/@forswayamnptelcourse/truefoundry-teardown-ai-gateway-control-plane-analysis-8a59f79864d4?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a59f79864d4</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 01:42:58 GMT</pubDate>
            <atom:updated>2026-11-10T01:42:58.213Z</atom:updated>
            <content:encoded><![CDATA[<h3>Executive summary</h3><p>TrueFoundry is a split-plane AI control plane: a central control plane holds identity, policy and configuration, and stateless gateways for LLMs, MCP tools and agents enforce it in memory on every call. What’s worth taking for anyone building an enterprise AI control plane is the design, not the feature count:</p><ul><li><strong>One subject model.</strong> Users, teams, virtual accounts and agents are all subjects. Models, MCP servers and agents are all resources with Manager / User roles.</li><li><strong>One policy shape.</strong> Guardrails, rate limits, budgets, logging, tool approvals and data access are all named YAML with a when block and an enforce or audit mode.</li><li><strong>Metadata header as the slicing key.</strong> One request header drives routing, budgets per project, data access and dashboards.</li><li><strong>Metrics vs traces split.</strong> Metrics are always on; prompt bodies are stored only by policy, redacted at write time, and visible only through access rules.</li></ul><p>Their weak spots are where an in-house build can lead: agent governance is mostly roadmap (discovery, per-hop token exchange, attribute-based policy, kill switch), output guardrails don’t run on streaming, alerting is thin, and there is no built-in quality evaluation.</p><p>Scope: the AI Gateway, MCP Gateway, Agent Registry, policies, access and monitoring, from TrueFoundry’s public docs as of today. Their model-deployment platform is left out. Menu labels come from doc paths and may differ slightly in the live UI.</p><h3>Product map</h3><p>TrueFoundry sells two product families on one control plane: a <strong>Gateway suite</strong> (LLM, MCP, Agent gateways plus prompts and governance) and an <strong>AI Engineering platform</strong> (deploy, serve and fine-tune models on your own Kubernetes). For an AI control plane, the Gateway suite is the part to study; the deployment side is optional and not needed to run the gateway. (<a href="https://www.truefoundry.com/">source</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6_cmYH1cdmBjgB7t6d2jQ.png" /></figure><p>Every object above can be managed from the UI or as YAML through tfy apply, so the whole control plane can be run as GitOps. (<a href="https://www.truefoundry.com/docs/change-announcements/simplified-gitops-cicd-v0.132.md">source</a>)</p><h3>Architecture</h3><p>TrueFoundry separates the <strong>control plane</strong> (where policy and configuration live) from the <strong>gateway plane</strong> (where requests are enforced). The gateway never calls out on the hot path: config is pushed to it, and logs flow back asynchronously. (<a href="https://www.truefoundry.com/docs/platform/architecture.md">source</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzxq_tkAajwpNubF9IBWGw.png" /></figure><p>Callers hit one of three gateways; the control plane pushes the full config over NATS and receives usage events and traces back. A compute plane (your Kubernetes) is needed only for the model-deployment product, not for the gateway.</p><h3>What lives where</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8o38H0Kpw7_7LpqK6sm7Q.png" /></figure><h3>How config and data move</h3><ul><li><strong>Config sync:</strong> on start, a gateway pulls the full config (models, users, VAs, limits, routing, SSO keys). It then subscribes to NATS; the control plane republishes the whole state every 10 minutes so a missed message self-heals. HTTP fallback if NATS is down; readiness fails if both are down. (<a href="https://www.truefoundry.com/docs/platform/gateway-plane-architecture.md">source</a>)</li><li><strong>Hot path:</strong> JWTs verified locally with cached keys; user-to-model grants in memory; rate limits as 5-second buckets summed over a window; budget and latency-routing decisions use aggregates pushed back from the control plane.</li><li><strong>Telemetry:</strong> after each call the gateway publishes an event (tokens, cost, latency, model). An aggregator computes per-user, per-team and per-model numbers and pushes them back to gateways. Traces go through an OTel collector and ingestor to blob storage. Logging never fails a request.</li><li><strong>Air-gapped:</strong> gateways can reach providers through an HTTP proxy; TrueFoundry ships a Squid proxy chart.</li></ul><h3>Personas and RBAC</h3><p>TrueFoundry has no “Gateway Owner” or “Developer” persona as a named role. Personas come from three layers of RBAC stacked together: a tenant role, a team role, and resource-level roles on each model account, MCP server or agent. Any of these can also be replaced by a custom role built from a permission catalog. (<a href="https://www.truefoundry.com/docs/platform/manage-user-roles-and-permissions">source</a>)</p><h3>Who can be granted access (subjects)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqLspW5kzpHMWDGsrbeGaQ.png" /></figure><p>Role layers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYLK45ljlT-a8svduZwF7Q.png" /></figure><p>Access to models is granted on the provider account, not model by model by default: a team granted an account gets every model in it, including ones added later. A model-level grant exists for finer control. Only an account Manager or a tenant admin can grant access; a User trying to grant gets a 403. (<a href="https://www.truefoundry.com/docs/ai-gateway/gateway-access-control">source</a>)</p><h3>Custom-role permission catalog</h3><p>Custom roles live under <strong>Access → Custom Roles</strong> and are tenant-wide. The permission keys show what TrueFoundry treats as governable objects:</p><ul><li><strong>AI resources:</strong> provider-account (Create, Delete, Manage, Read, UseIntegrations) · mcp-server (Create, Delete, Manage, Read, Use, Approve) · agent (Create, Delete, Manage, Read, Use)</li><li><strong>Gateway governance:</strong> gateway-controls (List, Manage) · policy (List, Manage) · role (List, Manage) · tenant (AssignRole, ReadAuditLogs)</li><li><strong>Identity:</strong> user (List, Manage) · team (Create, Delete, Manage, Read) · virtual-account (Create, Read, Manage, Delete)</li><li><strong>Platform:</strong> cluster · workspace · application · environment · repository · secret-group · settings</li></ul><h3>How this maps to common control-plane personas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEaSlkV9Wmjq7VeOp_zKfA.png" /></figure><p>Two tokens matter for callers: personal access tokens for development, and VA tokens for production. Admins see when each token was last used, which helps find abandoned integrations. (<a href="https://www.truefoundry.com/docs/platform/virtual-account-management">source</a>)</p><h3>User journey and UI navigation</h3><p>A new user lands in the <strong>AI Gateway</strong> section, adds a provider account, tests in the Playground, then copies a code snippet with a token. Everything else (policies, access, monitoring) is layered on by admins afterwards. (<a href="https://www.truefoundry.com/docs/ai-gateway/quick-start.md">source</a>)</p><h3>Developer journey: signup to first request</h3><ol><li><strong>Sign up / SSO login</strong> and land on the home page.</li><li><strong>AI Gateway → Models → Add Model → To New Provider Account.</strong> Pick a provider, name the account, enter keys, select models, then <strong>Test Credentials</strong> or <strong>Save</strong>.</li><li>Click a model → <strong>Try in Playground.</strong> The LLM Playground calls any connected model.</li><li>Open the Playground’s <strong>Code Snippet</strong> tab: gateway base URL (https://gateway.truefoundry.ai on SaaS), model id, and snippets for OpenAI SDK, LangChain, LangGraph, LlamaIndex, Google ADK, Node.js and cURL.</li><li><strong>Access → create a token:</strong> a PAT for development or a virtual account token for an app.</li><li>Point any OpenAI-compatible client at the gateway. Add X-TFY-METADATA headers (app, env, project) so policies, budgets and dashboards can slice the traffic.</li><li>See your own usage via <strong>Metrics → My Usage</strong> and your own traces in <strong>Request Traces</strong>.</li></ol><h3>Admin / gateway-owner journey</h3><ol><li>Configure SSO, then <strong>Provisioning</strong> (SCIM, JIT or invite-only).</li><li>Create <strong>teams</strong> and <strong>virtual accounts</strong>; set VA owners to the team that runs the app.</li><li>Register providers and models; grant <strong>Manager</strong> or <strong>User</strong> on each provider account.</li><li>Build <strong>virtual models</strong> for routing and fallback; register <strong>MCP servers</strong> and curate <strong>virtual MCP servers</strong>.</li><li>Register <strong>guardrails</strong>, then write <strong>Policies</strong>: guardrails, rate limits, budgets, logging, MCP tool approval.</li><li>Set <strong>data access rules</strong> (who sees traces vs metrics) and <strong>data routing</strong> (where traces are stored, retention).</li><li>Register <strong>agents</strong> with identity and owner.</li><li>Monitor through <strong>Metrics</strong> and <strong>Request Traces</strong>; export OTel and Prometheus metrics to the existing stack.</li></ol><h3>UI navigation map</h3><p>This map is assembled from the menu paths cited across the docs; TrueFoundry does not publish one complete nav tree, so exact labels may differ in the live product.</p><ul><li><strong>AI Gateway</strong></li><li><strong>Models</strong>: Add Model, Manage Accounts, per-account Access Control, Virtual Models</li><li><strong>MCP Servers</strong>: register servers, Collaborators, tool enable or disable, Revoke all tokens, Activity Logs</li><li><strong>Agent Registry</strong>: Create New Agent, Get Token, Access Control, Activity Logs</li><li><strong>Guardrails</strong>: guardrail groups and integrations</li><li><strong>Policies</strong>: Guardrails · Rate Limiting v2 · Budget Limiting · Logging Config · MCP Tool Approval (with Pending Requests)</li><li><strong>Controls</strong>: Data Routing (destinations, retention)</li><li><strong>Metrics</strong>: Overview · Models · MCP · Agents · Guardrails, plus Classic view</li><li><strong>Request Traces</strong></li><li><strong>Playground</strong>: chat, Code Snippet tab</li><li><strong>Prompts / Prompt Registry</strong>: Create Prompt, Try Prompt, Version History, Use via SDK or Gateway</li><li><strong>Access</strong></li><li>Users · Teams · Virtual Accounts (Manage Permissions, Tokens) · Custom Roles · Identity Providers · Provisioning</li><li><strong>Gateway Metrics/Traces → Access Rules</strong></li><li><strong>Platform → Integrations</strong>: storage buckets, secret stores, notification channels</li><li><strong>Deployments</strong> (AI Engineering side): clusters, workspaces, services, jobs</li></ul><p>Two UI patterns repeat on every screen and are worth copying: an <strong>Apply using YAML</strong> / <strong>Edit as YAML</strong> toggle on every form, and a <strong>Code Snippet</strong> button that hands the user a working client call.</p><h3>AI Gateway deep dive</h3><p>The LLM gateway’s core abstraction is the <strong>provider account</strong> (one set of keys, many models) plus the <strong>virtual model</strong> (one stable name, many targets). Apps call account/model or group/virtual-model on one OpenAI-compatible API, and everything else is driven by headers and policies.</p><h3>Model catalog and provider accounts</h3><ul><li>Several accounts per provider, each with its own keys (e.g. openai-prod, openai-dev). Access is granted on the account; a model-level grant exists for exceptions. (<a href="https://www.truefoundry.com/docs/ai-gateway/gateway-access-control">source</a>)</li><li>The /models endpoint returns only what the calling token can use.</li><li>Supported operations include chat, /messages, responses, completions, embeddings, rerank, moderation, image, text-to-speech, transcription and batch.</li></ul><h3>Virtual models (routing)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e31GQ7e1PAicTBA2v-KK0w.png" /></figure><p>Per target you can set: retries (default codes 429, 500, 502, 503), fallback status codes, fallback_candidate, parameter overrides, header overrides, metadata_match (e.g. route EU traffic only to EU targets), and a prompt version. A target is marked unhealthy after 2 failures in 2 minutes and moved to the back. The x-tfy-resolved-model response header tells the caller which target served it. (<a href="https://www.truefoundry.com/docs/ai-gateway/virtual-model">source</a>)</p><h3>Rate limiting v2</h3><ul><li>Two families: <strong>model</strong> (requests and tokens per minute, hour, day) and <strong>MCP</strong> (tool calls per minute, hour, day). (<a href="https://www.truefoundry.com/docs/ai-gateway/ratelimiting-v2.md">source</a>)</li><li>Scope by users, teams, virtual accounts, agents, models, provider accounts, metadata, MCP server or server:tool; in / not_in; * wildcard.</li><li><strong>Apply limit as:</strong> aggregate, per-user, per-model, per-virtual-account, per metadata value, per-MCP server. Per-entity overrides (e.g. one model gets 2,000 rpm).</li><li><strong>Modes:</strong> enforce, soft_enforce (block only when no other matching limit has room), audit.</li><li>Blocks return HTTP 429 with x-tfy-applied-rules; MCP blocks return a JSON-RPC error result so the model can see the refusal.</li></ul><h3>Budget limiting</h3><ul><li>Dollar caps per day, week or month (v2 adds quarterly, lifetime, multiple periods per rule, tenant and team budgets). (<a href="https://www.truefoundry.com/docs/ai-gateway/budgetlimiting.md">source</a>)</li><li>Scope by subject, model, metadata; split per user, model, VA or metadata key (e.g. metadata.project_id for project chargeback).</li><li>Enforce or audit; alerts at thresholds such as 75/90/100% to email or Slack, checked every 20 minutes.</li><li>Each rule card shows usage, limit, remaining budget and a per-entity breakdown.</li></ul><h3>Caching</h3><ul><li>Opt-in per request via x-tfy-cache-config: exact-match or semantic (cosine similarity, threshold around 0.9 suggested), TTL, and namespace. (<a href="https://www.truefoundry.com/docs/ai-gateway/caching.md">source</a>)</li><li>Cache is isolated per user or VA automatically. Self-hosting needs Redis plus an embedding model.</li></ul><h3>Headers that drive behaviour</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U916vkbNjokKe2tIKkHgwg.png" /></figure><h3>Performance</h3><p>TrueFoundry’s own benchmark: one 1-vCPU / 1 GB pod handles about 250 RPS with roughly 7 ms added latency, rising to 8–12 ms with full tracing at 350 RPS. All auth, rate and budget checks run in memory with no external call on the request path. (<a href="https://www.truefoundry.com/docs/platform/gateway-plane-architecture.md">source</a>)</p><h3>Policies and guardrails</h3><p>Every policy in TrueFoundry has the same shape: a named YAML document with a when block (who is calling, what they are calling, which metadata) and an action. Learning that one pattern covers guardrails, rate limits, budgets, logging, MCP approvals and data access. This is the single most reusable design idea for your control plane.</p><h3>The policy types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjByglJUBHW9O27wr1lQRA.png" /></figure><h3>Guardrails: how they work</h3><p>Guardrails run at four hooks: <strong>LLM input</strong>, <strong>LLM output</strong>, <strong>MCP pre-tool</strong> and <strong>MCP post-tool</strong>. Each guardrail is either <strong>Validate</strong> (block only) or <strong>Mutate</strong> (rewrite, e.g. redact, and can block). (<a href="https://www.truefoundry.com/docs/ai-gateway/guardrails-overview.md">source</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGHrhExIzztrir9KeMo7ww.png" /></figure><p><strong>Enforcement strategy</strong> per guardrail: Enforce (block on violation and on guardrail error), Enforce But Ignore On Error (fail open), or Audit (log only). TrueFoundry’s recommended rollout is Audit → Enforce-but-ignore-on-error → Enforce.</p><p>Limits to know: output guardrails are <strong>skipped on streaming</strong> responses; guardrails don’t run on speech or realtime calls; system prompts are excluded by default.</p><h3>Guardrail catalog</h3><ul><li><strong>Built-in:</strong> content moderation, PII/PHI detection, prompt injection (these three use Azure AI services and are SaaS-only), secrets detection, code-safety linter, SQL sanitizer, regex, <strong>Cedar</strong> and <strong>OPA</strong> policy guardrails for MCP tool authorization.</li><li><strong>Third-party (29 listed):</strong> Akto, AWS Bedrock Guardrails, Azure Content Safety / PII / Prompt Shield, CrowdStrike, Cisco AI Defense, Enkrypt AI, F5 (CalypsoAI), Fiddler, Google Model Armor, GraySwan, HiddenLayer, Fireworks, OpenAI Moderations, Palo Alto Prisma AIRS, Patronus, Pillar, Straiker, TrojAI, Zscaler, Cato, Noma, Arthur, DeepKeep, Guardrails AI, Lasso, NVIDIA NeMo, Verra.</li><li><strong>Custom:</strong> bring your own via a template repo, Guardrails AI or a plain Python function.</li></ul><h3>Setup flow</h3><ol><li><strong>AI Gateway → Guardrails:</strong> create a guardrail group and register integrations. Registration alone enforces nothing.</li><li><strong>AI Gateway → Policies → Guardrails → Add New Guardrail Rule:</strong> name, <em>When Request Goes To</em> (models / MCP), <em>From Subjects</em>, <em>With Metadata</em>, <em>Apply on Hooks</em>, optional custom error message. (<a href="https://www.truefoundry.com/docs/ai-gateway/guardrails-configuration.md">source</a>)</li><li>For a baseline on all traffic, target * with no subject filter; layer stricter policies for specific teams or models on top.</li></ol><pre>type: gateway-guardrails-config<br>name: prod-chat-safety<br>when:<br>  target:<br>    operator: or<br>    conditions:<br>      model: {values: [openai-main/gpt-4o], condition: in}<br>  subjects:<br>    operator: and<br>    conditions:<br>      in: [team:engineering]<br>      not_in: [user:external@partner.com]<br>llm_input_guardrails: [pii/pii-detection]<br>llm_output_guardrails: [prisma-airs/prisma-airs-dev-profile]<br>mcp_tool_pre_invoke_guardrails: []<br>mcp_tool_post_invoke_guardrails: []<br>custom_error_message: &quot;Blocked by {{failed_guardrails}}: {{guardrail_message}}&quot;</pre><p>From v0.179 each policy is its own named document; the older single rules[] file is removed on 15 November 2026. (<a href="https://www.truefoundry.com/docs/change-announcements/named-guardrails-config-v0.179.md">source</a>)</p><h3>Monitoring: gateway, MCP, agents, guardrails</h3><p>Monitoring is one dashboard with five tabs over a single event stream: every LLM call, tool call, agent run and guardrail check is attributed to a user, team, virtual account or agent, plus any metadata tags. Request bodies are a separate, access-controlled layer (traces) on top of always-on metrics. (<a href="https://www.truefoundry.com/docs/ai-gateway/analytics">source</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwUAlRFsjMPU_qgJzcIdXA.png" /></figure><p>Common controls on every tab: time range, search by user, team, VA, conversation id or any metadata key; saved and pinned filters (<strong>My Usage</strong>, <strong>My Teams Usage</strong>); click any row to drill into a team or user; <strong>Export Data</strong> to CSV. A <strong>Classic view</strong> keeps detailed charts for routing, rate limits, budgets and semantic cache.</p><h3>Request traces (AI Gateway → Request Traces)</h3><ul><li>One trace per request, with spans for routing, each guardrail (hook, pass/fail, latency, findings, mutations), the model call and tool calls. Blocked requests are traced too.</li><li>The root span records which logging policy applied (tfy.logging.matched_config_names), so admins can audit why a body was or wasn&#39;t stored. (<a href="https://www.truefoundry.com/docs/ai-gateway/logging-config.md">source</a>)</li><li>Traces are OpenTelemetry-compliant and can be exported over OTLP to Datadog, Grafana, Langfuse, Arize and others.</li></ul><h3>Who sees what (Access → Gateway Metrics/Traces → Access Rules)</h3><ul><li>Scopes: own data, team applications data (VAs owned by your teams), team data, all data (with metadata or created-by filters).</li><li>Traces and metrics are granted separately, so a team can see cost dashboards without prompt content.</li><li>Defaults: everyone sees own data and team data; tenant admins see all. TrueFoundry itself advises tightening the team default. (<a href="https://www.truefoundry.com/docs/ai-gateway/data-access">source</a>)</li></ul><h3>Where data is stored (AI Gateway → Controls → Data Routing)</h3><p>Traces can be routed by metadata, caller or gateway region to TrueFoundry-managed storage in a chosen region (US, Australia, India) or to your own S3, GCS or Azure Blob. Retention is set separately for traces and metrics, minimum 7 days. (<a href="https://www.truefoundry.com/docs/ai-gateway/data-routing.md">source</a>)</p><h3>Alerting</h3><ul><li><strong>Built in:</strong> budget threshold alerts (email, Slack) and MCP approval notifications (email, Slack, PagerDuty, Teams, webhook); VA token expiry and rotation notices.</li><li><strong>Everything else</strong> is via Prometheus metrics you alert on yourself: ai_gateway_request_model_inference_failure_total, ai_gateway_first_token_latency_ms, ai_gateway_inter_token_latency_ms, ai_gateway_request_cost_total, ai_gateway_rate_limit_applied_total, ai_gateway_budget_applied_total, ai_gateway_guardrail_requests_total, among others. (<a href="https://truefoundry.com/docs/ai-gateway/alerting">source</a>)</li><li>No general-purpose alert rule builder (latency, error rate) was found in the docs.</li></ul><h3>What is not there</h3><p>No built-in online evaluation, LLM-as-judge scoring or quality drift monitoring appeared in the gateway docs reviewed. TrueFoundry leans on partners (Arize, Langfuse, Fiddler, Patronus) for that, which is where a mature in-house observability stack can be deeper.</p><h3>MCP Gateway and agent governance</h3><p>TrueFoundry treats tools and agents as first-class governed resources, the same as models: each has an owner, collaborators with roles, policies and metrics. The agent side is the youngest part; several controls are marked “coming soon”.</p><h3>MCP Gateway</h3><p><strong>Register servers</strong> as remote (HTTP), hosted stdio (command, args, env and credentials managed by TrueFoundry), or <strong>OpenAPI-to-MCP</strong> (turn an existing REST spec into tools without writing a server). (<a href="https://truefoundry.com/docs/gateway/mcp-overview">source</a>)</p><p><strong>Curate tools:</strong> enable or disable individual tools, bulk-edit access, override tool descriptions and annotations. <strong>Virtual MCP servers</strong> bundle selected tools from several servers into one endpoint for a team or app.</p><p><strong>Inbound auth</strong> (who calls): PAT, VA token, your IdP’s JWT, or TrueFoundry OAuth for IDEs (Cursor, Claude Code, VS Code). (<a href="https://www.truefoundry.com/docs/ai-gateway/mcp-gateway-auth-security">source</a>)</p><p><strong>Outbound auth</strong> (how the gateway calls the server):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqBz0oL-4okn7-bmDMLCkg.png" /></figure><p><strong>Controls:</strong> per-server and per-tool access via Collaborators; tool-call rate limits; pre/post-tool guardrails including Cedar and OPA; <strong>human approval</strong> on named, destructive (destructiveHint) or all tools, valid once or for N minutes, approved by tenant admins or the server&#39;s <strong>MCP Server Approver</strong>, with notifications to email, Slack, PagerDuty, Teams or webhook. (<a href="https://www.truefoundry.com/docs/ai-gateway/mcp/mcp-tool-approval.md">source</a>)</p><p><strong>Response and audit:</strong> activity logs per server record the real user even when the downstream sees a shared identity; <strong>Revoke all tokens</strong> wipes every stored credential for a server instantly.</p><h3>Agent Registry and Agent Gateway</h3><p>Registration is a four-step wizard (<strong>Agent Registry → Create New Agent → Integrate a Remote Agent</strong>): (<a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/agent-registry.md">source</a>)</p><ol><li><strong>Metadata:</strong> unique name, description.</li><li><strong>Agent identity:</strong> TrueFoundry-issued token, or IdP-backed (Okta, Entra, any OIDC, SPIFFE/SPIRE, or workload identity from Kubernetes, GitHub, AWS, GCP).</li><li><strong>Config:</strong> <em>Proxy via Gateway</em> (A2A with agent card, or custom HTTP) or <em>Embedded</em> (governance-only, for copilots inside SaaS with no URL); outbound credential to reach the agent.</li><li><strong>Access control:</strong> collaborators with Agent Manager or Agent Access; owner team.</li></ol><p><strong>How a governed agent call works:</strong> the user’s token goes in Authorization and the agent&#39;s token in x-tfy-agent-authorization. At each hop in a chain the agent swaps in its own identity and passes the user token along, so the gateway checks every hop against the agent actually calling. Access is allow-list: an agent reaches a model or MCP server only if agent:&lt;name&gt; is a collaborator, else 403. Agents can&#39;t use OAuth authorization-code MCP servers, because no human is present to consent. (<a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/truefoundry-implementation.md">source</a>)</p><h3>Governance maturity: what exists vs what’s promised</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlf8ehIXhe4qxNQF-mLBYQ.png" /></figure><p>Their published maturity model is a useful roadmap template: <strong>Level 1 Inventoried</strong> (every agent registered with owner; gateway rejects unregistered) → <strong>Level 2 Least-privileged</strong> (per-agent grants, guardrails) → <strong>Level 3 Fully attributed</strong> (token exchange each hop, kill switch, certification). (<a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/governance-blueprint.md">source</a>)</p><h3>Gap analysis and implementation recommendations</h3><p>Don’t try to replicate TrueFoundry’s whole surface. Most of its breadth (29 guardrail vendors, 4 routing strategies, deployment platform) exists because it sells to many tenants; a single firm needs the <strong>data model and policy pattern</strong>, not the catalog. Copy the skeleton, buy or integrate the leaves.</p><h3>What to copy (high value, transferable)</h3><ol><li><strong>One identity model for everything.</strong> Users, teams, virtual accounts and agents are all “subjects”; models, MCP servers, agents and prompts are all “resources” with Manager / User / Approver roles. One grant API, one audit log.</li><li><strong>One policy shape.</strong> Every policy = named YAML with when (subjects, targets, metadata) + action + mode (enforce / audit). Same evaluator for guardrails, rate limits, budgets, logging, approvals, data access. Each policy ships with an <strong>audit mode</strong> so owners can dry-run before enforcing.</li><li><strong>Metadata header as the slicing key.</strong> X-TFY-METADATA (app, env, project, cost centre) drives routing, policy targeting, budgets per project, data access filters and dashboards. In most enterprises this maps naturally to an application id or use-case id.</li><li><strong>Hot-path design.</strong> Config pushed from control plane to stateless gateways (NATS, full snapshot every 10 min, HTTP fallback); auth, authorization, rate and budget checks fully in memory; logging async and never allowed to fail a request.</li><li><strong>Split metrics from traces.</strong> Metrics always on and broadly visible; bodies only where a logging policy allows, redacted at write time, visible only through data-access rules. This is the cleanest answer to a regulator asking who can read prompts.</li><li><strong>Ownership on every non-human identity.</strong> VA and agent owners, token last-used timestamps, auto-rotation with grace period, secret-store sync.</li><li><strong>YAML + UI parity.</strong> Every form has “Apply as YAML”; everything can be GitOps’d with one apply command.</li></ol><h3>Where TrueFoundry is weak (don’t inherit these)</h3><ul><li><strong>Agent governance is mostly roadmap.</strong> Discovery, per-hop token exchange, Cedar ABAC, one-click suspend and certification are all “coming soon”. If you build these first, you’re ahead, not behind.</li><li><strong>Output guardrails are skipped on streaming.</strong> For a bank, decide upfront whether streaming apps get chunked output checks or are forced non-streaming for high-risk use cases.</li><li><strong>Built-in PII, prompt-injection and moderation are SaaS-only</strong> (Azure services). Self-hosted needs a third-party or your own models; in-house detectors are an advantage here.</li><li><strong>No quality evaluation.</strong> No LLM-as-judge, gold-set A/B or drift in the gateway; a dedicated observability and eval platform is the differentiator.</li><li><strong>Thin alerting.</strong> Only budget and approval alerts are built in; latency and error alerts are left to Prometheus.</li><li><strong>Global auth/licensing server cannot be self-hosted.</strong> If you are evaluating them to buy, that is a data-flow question a risk team will raise.</li></ul><h3>Capability checklist</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAbr4WliGg4ip-Q66gqVXw.png" /></figure><h3>Suggested build order for the control plane</h3><ol><li><strong>Foundation:</strong> identity model (subjects, resources, roles), metadata convention, policy evaluator with audit mode, config push to gateways.</li><li><strong>Gateway controls:</strong> provider accounts and grants, virtual models, rate limits, budgets, guardrail hooks (reuse existing detectors).</li><li><strong>Visibility:</strong> metrics vs traces split, logging policies with redaction, data-access rules; feed the existing observability pipeline rather than building a second one.</li><li><strong>Tools and agents:</strong> MCP registry with OBO auth, tool approval, agent registry with dual tokens, then the roadmap items TrueFoundry hasn’t shipped (discovery, token exchange, kill switch, certification).</li></ol><h3>Sources</h3><ul><li><a href="https://www.truefoundry.com/">TrueFoundry home: product list</a></li><li><a href="https://www.truefoundry.com/docs/platform/architecture.md">Platform architecture</a></li><li><a href="https://www.truefoundry.com/docs/platform/gateway-plane-architecture.md">Gateway plane architecture</a></li><li><a href="https://www.truefoundry.com/docs/platform/control-plane-architecture.md">Control plane architecture</a></li><li><a href="https://www.truefoundry.com/docs/platform/manage-user-roles-and-permissions.md">User roles and permissions</a></li><li><a href="https://www.truefoundry.com/docs/change-announcements/identity-and-access-revamp-v0.143.md">Identity and access revamp v0.143</a></li><li><a href="https://www.truefoundry.com/docs/platform/virtual-account-management.md">Virtual account management</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/gateway-access-control.md">Gateway access control</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/quick-start.md">AI Gateway quick start</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/virtual-model.md">Virtual models</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/ratelimiting-v2.md">Rate limiting v2</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/budgetlimiting.md">Budget limiting</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/caching.md">Caching</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/guardrails-overview.md">Guardrails overview</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/guardrails-configuration.md">Guardrails configuration</a></li><li><a href="https://www.truefoundry.com/docs/change-announcements/named-guardrails-config-v0.179.md">Named guardrail policies v0.179</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/logging-config.md">Logging config</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/data-access">Data access rules</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/data-routing.md">Data routing</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/analytics">Metrics dashboard</a></li><li><a href="https://truefoundry.com/docs/ai-gateway/alerting">Alerting / Prometheus metrics</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/prompt-management">Prompt management</a></li><li><a href="https://truefoundry.com/docs/gateway/mcp-overview">MCP Gateway overview</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/mcp-gateway-auth-security">MCP auth and security</a></li><li><a href="https://www.truefoundry.com/docs/ai-gateway/mcp/mcp-tool-approval.md">MCP tool approval</a></li><li><a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/agent-registry.md">Agent registry</a></li><li><a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/truefoundry-implementation.md">Agent governance implementation</a></li><li><a href="https://www.truefoundry.com/docs/agent-platform/agent-governance/governance-blueprint.md">Agent governance blueprint</a></li><li><a href="https://www.truefoundry.com/docs/llms.txt">Docs index (llms.txt)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a59f79864d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code]]></title>
            <link>https://medium.com/@forswayamnptelcourse/code-b7d4d339f9c4?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d4d339f9c4</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 13:05:05 GMT</pubDate>
            <atom:updated>2026-11-09T13:05:05.252Z</atom:updated>
            <content:encoded><![CDATA[<pre>import asyncio<br>import logging<br>import os<br>from typing import Optional, Union<br><br>from fastapi import APIRouter, Request, Query, HTTPException, Depends<br><br>from obs_telemetry_svcs import configure_loggers<br>from obs_telemetry_svcs.common.models.schemas import (<br>    OtelSearchResponse,<br>    OtelEvalResponse,<br>    SpanStatus,<br>    OpenInferenceSpanKind,<br>)<br>from obs_telemetry_svcs.services.key_mgmt_util import (<br>    enforce_project_access,<br>    validate_client_auth_for_traces,<br>    validate_integration_client_auth,<br>)<br>from obs_telemetry_svcs.services.otel_service import OtelService<br>from obs_telemetry_svcs.util.handlers_v3 import (<br>    TraceDispatcher,<br>    BlobHandler,<br>    CollectorEndpointRegistry,<br>    CredentialProvider,<br>    CredsResolver,<br>    _format_bytes,<br>)<br><br>configure_loggers()<br>logger = logging.getLogger(__name__)<br><br>otel_trace = APIRouter(tags=[&quot;Otel Trace Collector API&quot;])<br><br># ─── Handler toggles ──────────────────────────────────────────────<br><br>ENABLE_BLOB = os.environ.get(&quot;ENABLE_BLOB_HANDLER&quot;, &quot;true&quot;).lower() == &quot;true&quot;<br># NOTE: there is no ENABLE_ARIZE-style toggle anymore -- destinations (Arize,<br># Cribl, future ones) are entirely config-driven from the collector_endpoints<br># Postgres table (owned/managed by obs_mgmt_svcs), not hardcoded here. To stop<br># sending to a destination, disable its row there -- see CollectorEndpointRegistry.<br><br>_MAX_CONCURRENT_DISPATCHES = int(os.environ.get(&quot;MAX_CONCURRENT_DISPATCHES&quot;, 500))<br>_dispatch_semaphore = asyncio.Semaphore(_MAX_CONCURRENT_DISPATCHES)<br><br># ─── Initialize components ────────────────────────────────────────<br><br>_blob_file_path = os.environ.get(&quot;OTEL_TRACES_FILE_PATH&quot;, &quot;RAP/otel_traces/azure&quot;)<br>_blob_handler = BlobHandler(blob_file_path=_blob_file_path) if ENABLE_BLOB else None<br>_credential_provider = CredentialProvider()<br>_collector_registry = CollectorEndpointRegistry()<br><br>trace_dispatcher = TraceDispatcher(<br>    registry=_collector_registry,<br>    blob_handler=_blob_handler,<br>    creds_resolver=CredsResolver(_credential_provider),<br>)<br><br><br># ─── POST: Receive Traces ─────────────────────────────────────────<br><br>@otel_trace.post(&quot;&quot;, status_code=200)<br>async def start_otel_trace(<br>    request: Request,<br>    client_info: dict = Depends(validate_client_auth_for_traces),<br>):<br>    &quot;&quot;&quot;<br>    Receive OpenTelemetry traces and dispatch to handlers.<br><br>    Accepts protobuf-encoded OTLP trace data and forwards it to Blob storage<br>    (always) plus whichever destinations are ACTIVE in the collector_endpoints<br>    table (config-driven, managed by obs_mgmt_svcs -- see CollectorEndpointRegistry).<br><br>    Required Header:<br>        X-OBS-CLIENT-ID: Client identifier (used as project name)<br>    &quot;&quot;&quot;<br>    raw_body = await request.body()<br>    if not raw_body:<br>        logger.info(&quot;Empty Trace Received&quot;)<br>        return {&quot;message&quot;: &quot;Empty Trace Received&quot;}<br><br>    client_id = client_info.get(&quot;client_id&quot;, &quot;unknown&quot;) if client_info else &quot;unknown&quot;<br>    space_id = client_info.get(&quot;space_id&quot;) if client_info else None<br>    space_type = client_info.get(&quot;space_type&quot;, &quot;&quot;) if client_info else &quot;&quot;<br><br>    # Fire-and-forget — respond immediately, dispatch in background<br>    asyncio.create_task(_safe_dispatch(raw_body, client_id, space_id, space_type))<br><br>    return {&quot;message&quot;: &quot;Trace Received&quot;}<br><br><br>async def _safe_dispatch(raw_body: bytes, client_id: str, space_id: str, space_type: str) -&gt; None:<br>    async with _dispatch_semaphore:<br>        try:<br>            await trace_dispatcher.dispatch(raw_body, client_id, space_id, space_type)<br>        except Exception as e:<br>            logger.error(<br>                f&quot;Trace dispatch failed | client={client_id} space_id={space_id} &quot;<br>                f&quot;body_size={_format_bytes(len(raw_body))} &quot;<br>                f&quot;error={type(e).__name__}: {e}&quot;,<br>                exc_info=True,<br>            )<br><br><br># ─── GET: Search Traces ───────────────────────────────────────────<br><br>@otel_trace.get(&quot;&quot;, status_code=200, response_model=OtelSearchResponse)<br>async def search_otel_traces(<br>    from_datetime: Optional[str] = Query(<br>        None, alias=&quot;from_date&quot;,<br>        description=&quot;Start datetime for filtering (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or ISO format)&quot;,<br>    ),<br>    to_datetime: Optional[str] = Query(<br>        None, alias=&quot;to_date&quot;,<br>        description=&quot;End datetime for filtering (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or ISO format)&quot;,<br>    ),<br>    trace_id: Optional[str] = Query(None, description=&quot;Trace ID filter&quot;),<br>    project_name: Optional[str] = Query(None, description=&quot;Project name filter&quot;),<br>    service_name: Optional[str] = Query(None, description=&quot;Service name filter&quot;),<br>    span_kind: Union[OpenInferenceSpanKind, None] = Query(<br>        None, description=&quot;Span Kind filter&quot;<br>    ),<br>    span_status: Union[SpanStatus, None] = Query(<br>        None, description=&quot;Span Status filter&quot;<br>    ),<br>    span_name: Optional[str] = Query(<br>        None, description=&quot;Span name filter (partial match)&quot;<br>    ),<br>    session_id: Optional[str] = Query(None, description=&quot;Session ID filter&quot;),<br>    user_id: Optional[str] = Query(None, description=&quot;User ID filter&quot;),<br>    offset: int = Query(0, ge=0, description=&quot;offset&quot;),<br>    limit: int = Query(5, ge=1, le=100, description=&quot;limit (max 100)&quot;),<br>    include_evals: Optional[bool] = False,<br>    client_info: dict = Depends(validate_integration_client_auth),<br>) -&gt; OtelSearchResponse:<br>    &quot;&quot;&quot;Search OpenTelemetry traces with optional filters and datetime range.<br><br>    Only integration clients (X-OBS-CLIENT-ID + X-OBS-CLIENT-KEY) are permitted.<br>    &quot;&quot;&quot;<br>    try:<br>        caller_id = client_info[&quot;client_id&quot;]<br>        enforce_project_access(client_info, project_name)<br><br>        otel_service = OtelService()<br>        result = otel_service.search_otel_traces(<br>            from_datetime=from_datetime,<br>            to_datetime=to_datetime,<br>            trace_id=trace_id,<br>            span_name=span_name,<br>            span_kind=span_kind,<br>            project_name=project_name,<br>            service_name=service_name,<br>            status_code=span_status,<br>            session_id=session_id,<br>            user_id=user_id,<br>            offset=offset,<br>            limit=limit,<br>            include_eval=include_evals,<br>        )<br>        return OtelSearchResponse(**result)<br><br>    except HTTPException:<br>        raise<br>    except ValueError as ve:<br>        raise HTTPException(status_code=400, detail=str(ve))<br>    except Exception as e:<br>        logger.error(f&quot;OTel search failed: {e}&quot;, exc_info=True)<br>        raise HTTPException(status_code=502, detail=&quot;Bad Request&quot;)<br><br><br># ─── GET: Fetch Eval Results ──────────────────────────────────────<br><br>@otel_trace.get(&quot;/evals&quot;, status_code=200, response_model=OtelEvalResponse)<br>async def fetch_eval_results(<br>    from_datetime: Optional[str] = Query(<br>        None, alias=&quot;from_date&quot;,<br>        description=&quot;Start datetime for filtering (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or ISO format)&quot;,<br>    ),<br>    to_datetime: Optional[str] = Query(<br>        None, alias=&quot;to_date&quot;,<br>        description=&quot;End datetime for filtering (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or ISO format)&quot;,<br>    ),<br>    trace_id: Optional[str] = Query(None, description=&quot;Trace ID filter&quot;),<br>    project_name: Optional[str] = Query(None, description=&quot;Project name filter&quot;),<br>    evaluation_id: Optional[str] = Query(None, description=&quot;Evaluation ID filter&quot;),<br>    offset: int = Query(0, ge=0, description=&quot;offset&quot;),<br>    limit: int = Query(5, ge=1, le=100, description=&quot;limit (max 100)&quot;),<br>    client_info: dict = Depends(validate_integration_client_auth),<br>) -&gt; OtelEvalResponse:<br>    &quot;&quot;&quot;Fetch evaluation results only (trace_id + evals) from eval_results table.<br><br>    Only integration clients (X-OBS-CLIENT-ID + X-OBS-CLIENT-KEY) are permitted.<br>    Returns only traces that have associated evaluations.<br>    &quot;&quot;&quot;<br>    try:<br>        caller_id = client_info[&quot;client_id&quot;]<br>        enforce_project_access(client_info, project_name)<br><br>        otel_service = OtelService()<br>        result = otel_service.search_eval_results(<br>            from_datetime=from_datetime,<br>            to_datetime=to_datetime,<br>            trace_id=trace_id,<br>            project_name=project_name,<br>            evaluation_id=evaluation_id,<br>            offset=offset,<br>            limit=limit,<br>        )<br><br>        return OtelEvalResponse(**result)<br><br>    except HTTPException:<br>        raise<br>    except ValueError as ve:<br>        raise HTTPException(status_code=400, detail=str(ve))<br>    except Exception as e:<br>        logger.error(f&quot;Eval fetch failed: {e}&quot;, exc_info=True)<br>        raise HTTPException(status_code=502, detail=&quot;Bad Request&quot;)<br><br>&quot;&quot;&quot;<br>handlers_v3.py<br><br>Config-driven, throttle-safe trace dispatcher for the OpenTelemetry trace<br>collection service. Supersedes handlers_v2.py&#39;s hardcoded Arize/Cribl dual-send<br>with a generic, DB-backed routing design (see docs/arize_cribl_throttle_optimization_design.md<br>and docs/new_router.py for the full design rationale and a runnable illustration).<br><br>Architecture:<br>    FastAPI endpoint -&gt; TraceDispatcher<br>        ├── BlobHandler            (queue + background thread -&gt; Azure Blob Storage, unchanged, unconditional)<br>        └── N x SinkRoute          (one per `collector_endpoints` row, loaded from Postgres)<br>                ├── routing_rule       -- OpenInference-based JSON predicate (RuleEvaluator)<br>                ├── creds_resolution   -- SPACE_ID_LOOKUP | SPACE_NAME_LOOKUP | STATIC (CredsResolver)<br>                └── ResilientBatchSink -- batching + drop-oldest backpressure + circuit breaker + retry<br>                        └── TraceSinkClient -- OtlpGrpcExporterClient | OtlpHttpExporterClient<br><br>Ownership split (confirmed):<br>    - obs_mgmt_svcs owns the `collector_endpoints` CRUD admin API (create/update/<br>      disable a destination). This service NEVER writes to that table.<br>    - This service only reads ACTIVE rows, on a polling interval<br>      (COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS, default 900s / 15min) --<br>      see CollectorEndpointRegistry. There is no &quot;refresh on write&quot; shortcut<br>      here since the write never happens in this service&#39;s process.<br><br>Logging conventions (enhanced for debuggability -- &quot;why wasn&#39;t my trace sent&quot;):<br>    INFO  -- normal lifecycle: request received, registry refresh summary, flush success<br>    WARNING -- recoverable/expected-to-happen issues: no creds resolved for a route,<br>               drop-oldest overflow, circuit breaker opened, malformed collector_endpoints row skipped<br>    ERROR -- a trace was actually dropped: decode failure, all retries exhausted,<br>             registry failed to load from Postgres<br>&quot;&quot;&quot;<br><br>import asyncio<br>import hashlib<br>import logging<br>import os<br>import queue<br>import random<br>import threading<br>import time<br>from abc import ABC, abstractmethod<br>from collections import deque<br>from dataclasses import dataclass, field<br>from datetime import datetime, timezone<br>from typing import Any, Callable, Deque, Dict, List, Optional, Set, Tuple<br>from urllib.parse import urlparse<br>from urllib.parse import urlparse<br><br>import grpc<br>import grpc.aio<br>import httpx<br>from google.protobuf.json_format import MessageToDict<br>from google.protobuf.message import DecodeError<br>from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import (<br>    ExportTraceServiceRequest,<br>)<br>from opentelemetry.proto.collector.trace.v1.trace_service_pb2_grpc import (<br>    TraceServiceStub,<br>)<br>from openinference.semconv.resource import ResourceAttributes<br>from openinference.semconv.trace import SpanAttributes<br><br>from obs_telemetry_svcs.common.blob_storage.blob_client import BlobStorageClient<br>from obs_telemetry_svcs.common.blob_storage.storage_config import (<br>    BlobLocation,<br>    StorageObjectType,<br>)<br>from obs_telemetry_svcs.common.config.config_store import BlobConfig<br>from obs_telemetry_svcs.common.util.utils import generate_unique_number<br><br>try:<br>    from aiolimiter import AsyncLimiter<br>except ImportError:  # pragma: no cover -- aiolimiter is a new dependency, see requirements.txt<br>    AsyncLimiter = None  # type: ignore[assignment,misc]<br><br>_logger = logging.getLogger(__name__)<br><br># ─── Configuration ─────────────────────────────────────────────────────────<br><br># Blob (unchanged from handlers_v2.py)<br>BLOB_BATCH_SIZE = int(os.environ.get(&quot;BLOB_BATCH_SIZE&quot;, 500))<br>BLOB_FLUSH_INTERVAL = int(os.environ.get(&quot;BLOB_FLUSH_INTERVAL&quot;, 30))<br>BLOB_QUEUE_MAX_SIZE = int(os.environ.get(&quot;BLOB_QUEUE_MAX_SIZE&quot;, 100000))<br>_blob_config = BlobConfig()<br>BLOB_CONTAINER_NAME = _blob_config.BLOB_CONTAINER_NAME or &quot;txt-eff-rai-data1&quot;<br><br># Credentials (unchanged from handlers_v2.py -- used by CredsResolver&#39;s SPACE_ID_LOOKUP/SPACE_NAME_LOOKUP)<br>CREDENTIAL_CACHE_TTL = int(os.environ.get(&quot;CREDENTIAL_CACHE_TTL&quot;, 900))<br><br># Resource-attribute labeling fallback only -- NOT a routing decision (routing lives in the DB, section 12 of the design doc)<br>DEFAULT_PROJECT_NAME = os.environ.get(&quot;DEFAULT_PROJECT_NAME&quot;, &quot;unknown-traces&quot;)<br><br># collector_endpoints registry refresh -- the ONLY sync mechanism this service has,<br># since obs_mgmt_svcs (a different service/process) owns all writes to that table.<br>COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS = int(<br>    os.environ.get(&quot;COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS&quot;, 900)<br>)<br><br># Sink send timeout (per attempt)<br>SINK_SEND_TIMEOUT = float(os.environ.get(&quot;SINK_SEND_TIMEOUT&quot;, 30.0))<br><br># gRPC keepalive: pings keep the HTTP/2 connection alive so proxies/LBs don&#39;t<br># idle-close it and send GOAWAY (same rationale as handlers_v2.py).<br>SINK_GRPC_KEEPALIVE_TIME_MS = int(os.environ.get(&quot;SINK_GRPC_KEEPALIVE_TIME_MS&quot;, 20000))<br>SINK_GRPC_KEEPALIVE_TIMEOUT_MS = int(os.environ.get(&quot;SINK_GRPC_KEEPALIVE_TIMEOUT_MS&quot;, 3000))<br><br># OpenInference semantic conventions (real package, not hand-copied string literals)<br>OPENINFERENCE_SPAN_KIND_KEY = SpanAttributes.OPENINFERENCE_SPAN_KIND<br>OPENINFERENCE_PROJECT_NAME_KEY = ResourceAttributes.PROJECT_NAME<br><br># Preserves the original caller&#39;s client_id as a span attribute on fixed-<br># project destinations (SPACE_NAME_LOOKUP, e.g. agent-forge) where the<br># resource-level project name is overridden to a shared constant instead of<br># the caller&#39;s own client_id.<br>RAI_CLIENT_ID_KEY = &quot;rai_client_id&quot;<br><br><br># ─── Utilities ───────────────────────────────────────────────────────────<br><br>def _format_bytes(n: int) -&gt; str:<br>    &quot;&quot;&quot;Format a byte count as a human-readable size string.&quot;&quot;&quot;<br>    if n &lt; 1024:<br>        return f&quot;{n}B&quot;<br>    elif n &lt; 1024 * 1024:<br>        return f&quot;{n / 1024:.1f}KB&quot;<br>    else:<br>        return f&quot;{n / (1024 * 1024):.1f}MB&quot;<br><br><br>def _parse_grpc_endpoint(endpoint: str) -&gt; str:<br>    &quot;&quot;&quot;Extract host:port from a URL or passthrough a bare host:port for gRPC<br>    channel creation. gRPC channel targets must be a bare authority<br>    (host:port), not a URL with scheme/path -- real `spaces` table rows can<br>    store a full OTLP endpoint URL (e.g. https://raiobs-dev.statestr.com/v1/traces),<br>    which gRPC would otherwise try to resolve literally (DNS lookup for &quot;https&quot;).&quot;&quot;&quot;<br>    if &quot;://&quot; in endpoint:<br>        parsed = urlparse(endpoint)<br>        host = parsed.hostname or &quot;&quot;<br>        port = parsed.port or (443 if parsed.scheme in (&quot;https&quot;, &quot;grpcs&quot;) else 80)<br>        return f&quot;{host}:{port}&quot;<br>    return endpoint<br><br><br># ─── Protobuf Utilities ───────────────────────────────────────────────────<br><br>def _inject_resource_attribute(request: ExportTraceServiceRequest, key: str, value: str) -&gt; None:<br>    &quot;&quot;&quot;Set a string attribute on all resource_spans&#39; resource. In-place mutation.&quot;&quot;&quot;<br>    for resource_span in request.resource_spans:<br>        attrs = resource_span.resource.attributes<br>        for attr in attrs:<br>            if attr.key == key:<br>                attr.value.string_value = value<br>                break<br>        else:<br>            new_attr = attrs.add()<br>            new_attr.key = key<br>            new_attr.value.string_value = value<br><br><br>def _inject_span_attribute(request: ExportTraceServiceRequest, key: str, value: str) -&gt; None:<br>    &quot;&quot;&quot;Set a string attribute on every span in the request. In-place mutation.&quot;&quot;&quot;<br>    for rs in request.resource_spans:<br>        for ss in rs.scope_spans:<br>            for span in ss.spans:<br>                for attr in span.attributes:<br>                    if attr.key == key:<br>                        attr.value.string_value = value<br>                        break<br>                else:<br>                    new_attr = span.attributes.add()<br>                    new_attr.key = key<br>                    new_attr.value.string_value = value<br><br><br>def _build_trace_request(entries: List[Tuple]) -&gt; ExportTraceServiceRequest:<br>    &quot;&quot;&quot;Build an ExportTraceServiceRequest from a flat list of (rs, ss, span) tuples.<br><br>    Preserves resource/scope hierarchy: each unique (rs, ss) pair maps to<br>    exactly one ScopeSpans in the output, avoiding duplication.<br>    &quot;&quot;&quot;<br>    trace_request = ExportTraceServiceRequest()<br>    rs_map: Dict[int, Any] = {}<br>    ss_map: Dict[Tuple[int, int], Any] = {}<br><br>    for rs, ss, span in entries:<br>        rs_id = id(rs)<br>        ss_key = (rs_id, id(ss))<br><br>        if rs_id not in rs_map:<br>            new_rs = trace_request.resource_spans.add()<br>            new_rs.resource.CopyFrom(rs.resource)<br>            rs_map[rs_id] = new_rs<br><br>        if ss_key not in ss_map:<br>            new_ss = rs_map[rs_id].scope_spans.add()<br>            new_ss.scope.CopyFrom(ss.scope)<br>            ss_map[ss_key] = new_ss<br><br>        ss_map[ss_key].spans.add().CopyFrom(span)<br><br>    return trace_request<br><br><br># ─── Dispatch Context (single O(spans) pass per request) ─────────────────<br><br>@dataclass<br>class TraceChunk:<br>    &quot;&quot;&quot;One whole trace&#39;s worth of spans, plus a quick-lookup index used by RuleEvaluator.&quot;&quot;&quot;<br>    trace_id_hex: str<br>    request: ExportTraceServiceRequest<br>    span_kinds: Set[str] = field(default_factory=set)<br>    resource_attrs: Dict[str, str] = field(default_factory=dict)<br><br><br>@dataclass<br>class DispatchContext:<br>    client_id: str<br>    space_id: str<br>    space_type: str<br>    trace_chunks: List[TraceChunk]<br><br><br>def build_dispatch_context(<br>    request: ExportTraceServiceRequest, client_id: str, space_id: str, space_type: str<br>) -&gt; DispatchContext:<br>    &quot;&quot;&quot;Single pass: group spans by trace_id, collect span-kinds + resource attrs per trace.<br><br>    Replaces handlers_v2.py&#39;s _partition_request -- same O(spans) single-scan<br>    cost, generalized so routing isn&#39;t hardcoded to &quot;AGENT span kind&quot; alone.<br>    &quot;&quot;&quot;<br>    grouped: Dict[bytes, List[Tuple]] = {}<br>    kinds_by_tid: Dict[bytes, Set[str]] = {}<br>    resource_attrs_by_tid: Dict[bytes, Dict[str, str]] = {}<br><br>    for rs in request.resource_spans:<br>        resource_attr_map = {<br>            a.key: a.value.string_value for a in rs.resource.attributes if a.value.HasField(&quot;string_value&quot;)<br>        }<br>        for ss in rs.scope_spans:<br>            for span in ss.spans:<br>                tid = bytes(span.trace_id)<br>                grouped.setdefault(tid, []).append((rs, ss, span))<br>                kinds = kinds_by_tid.setdefault(tid, set())<br>                resource_attrs_by_tid.setdefault(tid, {}).update(resource_attr_map)<br>                for attr in span.attributes:<br>                    if attr.key == OPENINFERENCE_SPAN_KIND_KEY and attr.value.HasField(&quot;string_value&quot;):<br>                        kinds.add(attr.value.string_value)<br><br>    trace_chunks = [<br>        TraceChunk(<br>            trace_id_hex=tid.hex(),<br>            request=_build_trace_request(entries),<br>            span_kinds=kinds_by_tid.get(tid, set()),<br>            resource_attrs=resource_attrs_by_tid.get(tid, {}),<br>        )<br>        for tid, entries in grouped.items()<br>    ]<br>    return DispatchContext(client_id=client_id, space_id=space_id, space_type=space_type, trace_chunks=trace_chunks)<br><br><br># ─── Rule Evaluator (data-only JSON predicate DSL, never eval()&#39;d) ───────<br><br>class RuleEvaluator:<br>    &quot;&quot;&quot;The ONLY place the rule-based routing check happens. ResilientBatchSink<br>    and TraceSinkClient have no knowledge of routing rules at all.&quot;&quot;&quot;<br><br>    _PREDICATES: Dict[str, Callable[[dict, DispatchContext, TraceChunk], bool]] = {}<br><br>    @classmethod<br>    def register(cls, rule_type: str):<br>        def _wrap(fn):<br>            cls._PREDICATES[rule_type] = fn<br>            return fn<br>        return _wrap<br><br>    @classmethod<br>    def evaluate(cls, rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>        predicate = cls._PREDICATES.get(rule.get(&quot;type&quot;))<br>        if predicate is None:<br>            _logger.error(&quot;RuleEvaluator: unknown routing_rule type=%s -- treating as non-match&quot;, rule.get(&quot;type&quot;))<br>            return False<br>        return predicate(rule, ctx, chunk)<br><br><br>@RuleEvaluator.register(&quot;ALWAYS&quot;)<br>def _rule_always(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return True<br><br><br>@RuleEvaluator.register(&quot;SPAN_ATTR_EXISTS&quot;)<br>def _rule_span_attr_exists(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    if rule.get(&quot;key&quot;) != OPENINFERENCE_SPAN_KIND_KEY:<br>        return False<br>    return rule.get(&quot;value&quot;) in chunk.span_kinds<br><br><br>@RuleEvaluator.register(&quot;SPAN_ATTR_EQUALS&quot;)<br>def _rule_span_attr_equals(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    if rule.get(&quot;key&quot;) != OPENINFERENCE_SPAN_KIND_KEY:<br>        return False<br>    return chunk.span_kinds == {rule.get(&quot;value&quot;)}<br><br><br>@RuleEvaluator.register(&quot;RESOURCE_ATTR_EQUALS&quot;)<br>def _rule_resource_attr_equals(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return chunk.resource_attrs.get(rule.get(&quot;key&quot;)) == rule.get(&quot;value&quot;)<br><br><br>@RuleEvaluator.register(&quot;RESOURCE_ATTR_PREFIX&quot;)<br>def _rule_resource_attr_prefix(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    value = chunk.resource_attrs.get(rule.get(&quot;key&quot;), &quot;&quot;)<br>    return value.startswith(rule.get(&quot;prefix&quot;, &quot;&quot;))<br><br><br>@RuleEvaluator.register(&quot;CLIENT_ID_PREFIX&quot;)<br>def _rule_client_id_prefix(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return ctx.client_id.startswith(rule.get(&quot;prefix&quot;, &quot;&quot;))<br><br><br>@RuleEvaluator.register(&quot;SPACE_TYPE_EQUALS&quot;)<br>def _rule_space_type_equals(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return ctx.space_type == rule.get(&quot;value&quot;)<br><br><br>@RuleEvaluator.register(&quot;ALL&quot;)<br>def _rule_all(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return all(RuleEvaluator.evaluate(r, ctx, chunk) for r in rule.get(&quot;rules&quot;, []))<br><br><br>@RuleEvaluator.register(&quot;ANY&quot;)<br>def _rule_any(rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:<br>    return any(RuleEvaluator.evaluate(r, ctx, chunk) for r in rule.get(&quot;rules&quot;, []))<br><br><br># ─── Credential Provider (unchanged from handlers_v2.py) ─────────────────<br><br>class CredentialProvider:<br>    &quot;&quot;&quot;Thread-safe cached credential lookups for Arize-style spaces, used by<br>    CredsResolver&#39;s SPACE_ID_LOOKUP / SPACE_NAME_LOOKUP strategies.&quot;&quot;&quot;<br><br>    def __init__(self, cache_ttl: int = CREDENTIAL_CACHE_TTL):<br>        self._cache_ttl = cache_ttl<br>        self._cache: Dict[str, tuple] = {}<br>        self._lock = threading.Lock()<br><br>    def get_by_space_id(self, space_id: str) -&gt; Optional[Dict]:<br>        if not space_id:<br>            return None<br>        return self._cached_lookup(f&quot;id:{space_id}&quot;, lambda: self._fetch_by_id(space_id))<br><br>    def get_by_space_name(self, space_name: str) -&gt; Optional[Dict]:<br>        if not space_name:<br>            return None<br>        return self._cached_lookup(f&quot;name:{space_name}&quot;, lambda: self._fetch_by_name(space_name))<br><br>    def _cached_lookup(self, key: str, fetch_fn) -&gt; Optional[Dict]:<br>        now = time.monotonic()<br>        with self._lock:<br>            entry = self._cache.get(key)<br>            if entry is not None:<br>                creds, cached_at = entry<br>                if (now - cached_at) &lt; self._cache_ttl:<br>                    return creds<br><br>        creds = fetch_fn()<br>        if creds and self._is_valid(creds):<br>            with self._lock:<br>                self._cache[key] = (creds, time.monotonic())<br>            return creds<br>        return None<br><br>    @staticmethod<br>    def _is_valid(creds: Dict) -&gt; bool:<br>        return all(k in creds for k in (&quot;space_id&quot;, &quot;api_key&quot;, &quot;endpoint&quot;))<br><br>    @staticmethod<br>    def _fetch_by_id(space_id: str) -&gt; Optional[Dict]:<br>        try:<br>            from obs_telemetry_svcs.services.client_mgmt import ClientMgmtService<br>            return ClientMgmtService.get_space_creds_by_id(space_id)<br>        except Exception as e:<br>            _logger.error(f&quot;CredentialProvider: space_id lookup failed: {e}&quot;)<br>            return None<br><br>    @staticmethod<br>    def _fetch_by_name(space_name: str) -&gt; Optional[Dict]:<br>        try:<br>            from obs_telemetry_svcs.services.client_mgmt import ClientMgmtService<br>            return ClientMgmtService.get_space_creds_by_name(space_name)<br>        except Exception as e:<br>            _logger.error(f&quot;CredentialProvider: space_name lookup failed: {e}&quot;)<br>            return None<br><br><br># ─── Credentials Resolution (where to send + what headers) ──────────────<br><br>class CredsResolver:<br>    &quot;&quot;&quot;Resolves {&quot;endpoint&quot;, &quot;headers&quot;} for a route, per request. SPACE_ID_LOOKUP/<br>    SPACE_NAME_LOOKUP are dynamic, per-tenant (Arize-style); STATIC is a fixed<br>    destination baked into the collector_endpoints row (e.g. Cribl).&quot;&quot;&quot;<br><br>    def __init__(self, credential_provider: CredentialProvider):<br>        self._creds = credential_provider<br><br>    def resolve(self, creds_resolution: dict, ctx: DispatchContext, row: dict) -&gt; Optional[Dict[str, Any]]:<br>        kind = creds_resolution.get(&quot;type&quot;)<br>        if kind == &quot;SPACE_ID_LOOKUP&quot;:<br>            creds = self._creds.get_by_space_id(ctx.space_id)<br>            if not creds:<br>                return None<br>            _logger.info(<br>                &quot;CredsResolver: SPACE_ID_LOOKUP | client_id=%s requested_space_id=%s resolved_space_id=%s endpoint=%s&quot;,<br>                ctx.client_id, ctx.space_id, creds.get(&quot;space_id&quot;), creds.get(&quot;endpoint&quot;),<br>            )<br>            # Matches handlers_v2.py&#39;s primary handler exactly -- project name<br>            # stays the raw client_id, same as every other destination (no<br>            # override here; that&#39;s reserved for fixed-project routes like<br>            # SPACE_NAME_LOOKUP/agent-forge below).<br>            return {&quot;endpoint&quot;: creds[&quot;endpoint&quot;], &quot;headers&quot;: _arize_metadata_headers(creds)}<br>        if kind == &quot;SPACE_NAME_LOOKUP&quot;:<br>            creds = self._creds.get_by_space_name(creds_resolution.get(&quot;name&quot;, &quot;&quot;))<br>            if not creds:<br>                return None<br>            # Matches handlers_v2.py&#39;s agent-forge handler: this destination&#39;s<br>            # project name is the fixed configured name (e.g. &quot;agent-forge&quot;),<br>            # not the caller&#39;s client_id -- client identity is preserved<br>            # separately via the rai_client_id span attribute (see dispatch()).<br>            return {<br>                &quot;endpoint&quot;: creds[&quot;endpoint&quot;],<br>                &quot;headers&quot;: _arize_metadata_headers(creds),<br>                &quot;project_name&quot;: creds_resolution.get(&quot;name&quot;, &quot;&quot;),<br>            }<br>        if kind == &quot;STATIC&quot;:<br>            return {&quot;endpoint&quot;: row[&quot;endpoint_url&quot;], &quot;headers&quot;: row.get(&quot;headers&quot;) or {}}<br>        _logger.error(&quot;CredsResolver: unknown creds_resolution type=%s for row=%s&quot;, kind, row.get(&quot;name&quot;))<br>        return None<br><br><br>def _arize_metadata_headers(creds: Dict[str, str]) -&gt; Dict[str, str]:<br>    &quot;&quot;&quot;Matches handlers_v2.py&#39;s exact gRPC metadata set for Arize -- Arize&#39;s<br>    collector requires `authorization` (and/or `arize-space-id`), not just<br>    `api_key`/`space_id` alone (confirmed: PERMISSION_DENIED &quot;request headers<br>    must include api key&quot; when those two were missing).&quot;&quot;&quot;<br>    return {<br>        &quot;space_id&quot;: creds[&quot;space_id&quot;],<br>        &quot;api_key&quot;: creds[&quot;api_key&quot;],<br>        &quot;arize-space-id&quot;: creds[&quot;space_id&quot;],<br>        &quot;authorization&quot;: creds[&quot;api_key&quot;],<br>    }<br><br><br># ─── TraceSinkClient (Strategy interface) + 2 generic implementations ────<br><br>class NonRetryableSendError(Exception):<br>    &quot;&quot;&quot;Raised by TraceSinkClient.send() for errors that must never be retried<br>    (auth, invalid argument, etc.) -- ResilientBatchSink drops the batch immediately.&quot;&quot;&quot;<br><br><br>class TraceSinkClient(ABC):<br>    &quot;&quot;&quot;Pure transport. No knowledge of batching, routing, retry policy, or<br>    circuit breaking -- single attempt per call, those concerns live in<br>    ResilientBatchSink.&quot;&quot;&quot;<br><br>    @abstractmethod<br>    async def send(self, request: ExportTraceServiceRequest, endpoint: str, headers: Dict[str, str],<br>                    trace_ids: Optional[List[str]] = None, label: str = &quot;&quot;) -&gt; bool:<br>        &quot;&quot;&quot;Returns True on success, False on a transient/retryable failure.<br>        Raises NonRetryableSendError on a failure that must not be retried.&quot;&quot;&quot;<br>        ...<br><br>    @property<br>    @abstractmethod<br>    def stats(self) -&gt; Dict[str, int]: ...<br><br>    @abstractmethod<br>    async def close(self) -&gt; None: ...<br><br><br># gRPC status codes that are not worth retrying (client-side errors).<br>_GRPC_NON_RETRYABLE_CODES = frozenset({<br>    grpc.StatusCode.INVALID_ARGUMENT,<br>    grpc.StatusCode.NOT_FOUND,<br>    grpc.StatusCode.PERMISSION_DENIED,<br>    grpc.StatusCode.UNAUTHENTICATED,<br>    grpc.StatusCode.ALREADY_EXISTS,<br>    grpc.StatusCode.UNIMPLEMENTED,<br>})<br><br># 4xx except 429 (rate-limit) are non-retryable: credentials/payload won&#39;t change.<br>_HTTP_NON_RETRYABLE_STATUSES = frozenset(range(400, 500)) - {429}<br><br><br>class OtlpGrpcExporterClient(TraceSinkClient):<br>    &quot;&quot;&quot;Generic gRPC OTLP exporter -- configured per collector_endpoints row<br>    (TLS verify + cert), reused by every destination that speaks OTLP/gRPC<br>    (Arize, Cribl, and any future gRPC destination).&quot;&quot;&quot;<br><br>    def __init__(self, tls_verify: bool = True, tls_cert_bytes: Optional[bytes] = None,<br>                 timeout: float = SINK_SEND_TIMEOUT, ssl_target_name_override: Optional[str] = None):<br>        self._tls_verify = tls_verify<br>        self._tls_cert_bytes = tls_cert_bytes<br>        self._timeout = timeout<br>        self._ssl_target_name_override = ssl_target_name_override<br>        self._channels: Dict[str, grpc.aio.Channel] = {}<br>        self._stubs: Dict[str, TraceServiceStub] = {}<br>        self._channel_lock = asyncio.Lock()<br>        self._success = 0<br>        self._failure = 0<br>        self._stats_lock = threading.Lock()<br><br>    async def _get_stub(self, endpoint: str) -&gt; TraceServiceStub:<br>        stub = self._stubs.get(endpoint)<br>        if stub is not None:<br>            return stub<br>        async with self._channel_lock:<br>            if endpoint not in self._stubs:<br>                options = (<br>                    (&quot;grpc.keepalive_time_ms&quot;, SINK_GRPC_KEEPALIVE_TIME_MS),<br>                    (&quot;grpc.keepalive_timeout_ms&quot;, SINK_GRPC_KEEPALIVE_TIMEOUT_MS),<br>                    (&quot;grpc.keepalive_permit_without_calls&quot;, 1),<br>                    (&quot;grpc.http2.max_pings_without_data&quot;, 0),<br>                )<br>                # Needed when connecting by IP while the cert SAN is a DNS name<br>                # (confirmed real-world case: Cribl use2 10.76.44.180:7001, cert<br>                # issued for cribl-dev-agent-ue2.statestr.com).<br>                if self._ssl_target_name_override:<br>                    options += ((&quot;grpc.ssl_target_name_override&quot;, self._ssl_target_name_override),)<br>                # gRPC channel targets must be bare host:port, not a URL -- real<br>                # `spaces` rows can store a full OTLP URL (scheme + path).<br>                host_port = _parse_grpc_endpoint(endpoint)<br>                if self._tls_verify:<br>                    creds = grpc.ssl_channel_credentials(root_certificates=self._tls_cert_bytes)<br>                    channel = grpc.aio.secure_channel(host_port, creds, options=options)<br>                else:<br>                    channel = grpc.aio.insecure_channel(host_port, options=options)<br>                self._channels[endpoint] = channel<br>                self._stubs[endpoint] = TraceServiceStub(channel)<br>                _logger.info(&quot;OtlpGrpcExporterClient: opened gRPC channel to %s&quot;, host_port)<br>            return self._stubs[endpoint]<br><br>    async def _evict_stub(self, endpoint: str) -&gt; None:<br>        &quot;&quot;&quot;Close and drop a cached channel so the next send() opens a fresh one.&quot;&quot;&quot;<br>        async with self._channel_lock:<br>            channel = self._channels.pop(endpoint, None)<br>            self._stubs.pop(endpoint, None)<br>        if channel is not None:<br>            try:<br>                await channel.close()<br>            except Exception as e:<br>                _logger.warning(&quot;OtlpGrpcExporterClient: error closing evicted channel for %s: %s&quot;, endpoint, e)<br><br>    async def send(self, request, endpoint, headers, trace_ids=None, label=&quot;&quot;) -&gt; bool:<br>        try:<br>            stub = await self._get_stub(endpoint)<br>            metadata = tuple(headers.items())<br>            await stub.Export(request, metadata=metadata, timeout=self._timeout)<br>            with self._stats_lock:<br>                self._success += 1<br>            return True<br>        except grpc.aio.AioRpcError as e:<br>            status_code = e.code()<br>            with self._stats_lock:<br>                self._failure += 1<br>            if status_code == grpc.StatusCode.UNAVAILABLE:<br>                # Channel likely got GOAWAY&#39;d by a proxy/LB; drop it so the next<br>                # attempt opens a fresh one instead of retrying a dead stream.<br>                await self._evict_stub(endpoint)<br>            if status_code in _GRPC_NON_RETRYABLE_CODES:<br>                raise NonRetryableSendError(<br>                    f&quot;gRPC {status_code.name} from {endpoint} | label={label} trace_ids={trace_ids}: {e.details()}&quot;<br>                ) from e<br>            _logger.warning(<br>                &quot;OtlpGrpcExporterClient: transient send failure | endpoint=%s label=%s trace_ids=%s | gRPC %s: %s&quot;,<br>                endpoint, label, trace_ids, status_code.name, e.details(),<br>            )<br>            return False<br>        except Exception as e:<br>            with self._stats_lock:<br>                self._failure += 1<br>            _logger.warning(<br>                &quot;OtlpGrpcExporterClient: send failed | endpoint=%s label=%s trace_ids=%s | %s: %s&quot;,<br>                endpoint, label, trace_ids, type(e).__name__, e,<br>            )<br>            return False<br><br>    @property<br>    def stats(self) -&gt; Dict[str, int]:<br>        with self._stats_lock:<br>            return {&quot;success&quot;: self._success, &quot;failure&quot;: self._failure}<br><br>    async def close(self) -&gt; None:<br>        for ep, channel in list(self._channels.items()):<br>            try:<br>                await channel.close()<br>            except Exception as e:<br>                _logger.warning(f&quot;OtlpGrpcExporterClient: error closing channel for {ep}: {e}&quot;)<br>        self._channels.clear()<br>        self._stubs.clear()<br><br><br>class OtlpHttpExporterClient(TraceSinkClient):<br>    &quot;&quot;&quot;Generic HTTP OTLP exporter (protobuf-over-HTTP) -- configured per<br>    collector_endpoints row, reused by every destination using HTTP transport.&quot;&quot;&quot;<br><br>    def __init__(self, tls_verify: bool = True, tls_cert_bytes: Optional[bytes] = None,<br>                 timeout: float = SINK_SEND_TIMEOUT):<br>        self._tls_verify = tls_verify<br>        self._tls_cert_bytes = tls_cert_bytes<br>        self._timeout = timeout<br>        self._client: Optional[httpx.AsyncClient] = None<br>        self._client_lock = asyncio.Lock()<br>        self._success = 0<br>        self._failure = 0<br>        self._stats_lock = threading.Lock()<br><br>    async def _get_client(self) -&gt; httpx.AsyncClient:<br>        if self._client is not None:<br>            return self._client<br>        async with self._client_lock:<br>            if self._client is None:<br>                if self._tls_verify and self._tls_cert_bytes:<br>                    import ssl<br>                    ctx = ssl.create_default_context()<br>                    ctx.load_verify_locations(cadata=self._tls_cert_bytes.decode(&quot;utf-8&quot;))<br>                    verify: Any = ctx<br>                else:<br>                    verify = self._tls_verify  # True = system CA bundle, False = no verification<br>                self._client = httpx.AsyncClient(timeout=self._timeout, verify=verify)<br>            return self._client<br><br>    async def send(self, request, endpoint, headers, trace_ids=None, label=&quot;&quot;) -&gt; bool:<br>        client = await self._get_client()<br>        try:<br>            resp = await client.post(<br>                endpoint, content=request.SerializeToString(),<br>                headers={**headers, &quot;Content-Type&quot;: &quot;application/x-protobuf&quot;},<br>            )<br>            resp.raise_for_status()<br>            with self._stats_lock:<br>                self._success += 1<br>            return True<br>        except httpx.HTTPStatusError as e:<br>            status_code = e.response.status_code<br>            with self._stats_lock:<br>                self._failure += 1<br>            if status_code in _HTTP_NON_RETRYABLE_STATUSES:<br>                raise NonRetryableSendError(<br>                    f&quot;HTTP {status_code} from {endpoint} | label={label} trace_ids={trace_ids}: {e.response.reason_phrase}&quot;<br>                ) from e<br>            _logger.warning(<br>                &quot;OtlpHttpExporterClient: transient send failure | endpoint=%s label=%s trace_ids=%s | HTTP %d %s&quot;,<br>                endpoint, label, trace_ids, status_code, e.response.reason_phrase,<br>            )<br>            return False<br>        except Exception as e:<br>            with self._stats_lock:<br>                self._failure += 1<br>            _logger.warning(<br>                &quot;OtlpHttpExporterClient: send failed | endpoint=%s label=%s trace_ids=%s | %s: %s&quot;,<br>                endpoint, label, trace_ids, type(e).__name__, e,<br>            )<br>            return False<br><br>    @property<br>    def stats(self) -&gt; Dict[str, int]:<br>        with self._stats_lock:<br>            return {&quot;success&quot;: self._success, &quot;failure&quot;: self._failure}<br><br>    async def close(self) -&gt; None:<br>        if self._client is not None:<br>            await self._client.aclose()<br><br><br># ─── TLS certificate loading (per collector_endpoints row, cached per row id) ─<br><br>_tls_cert_cache: Dict[str, Optional[bytes]] = {}<br>_tls_cert_cache_lock = threading.Lock()<br><br><br>def _load_tls_cert_bytes(row: dict) -&gt; Optional[bytes]:<br>    &quot;&quot;&quot;Downloads the PEM certificate from Azure Blob Storage for one collector_endpoints<br>    row, cached per row id so a config change to one destination never re-downloads<br>    or disturbs another&#39;s cached cert. Returns None (system CA bundle) if the row<br>    doesn&#39;t specify a blob path or the download fails.&quot;&quot;&quot;<br>    row_id = row[&quot;id&quot;]<br>    with _tls_cert_cache_lock:<br>        if row_id in _tls_cert_cache:<br>            return _tls_cert_cache[row_id]<br><br>    blob_path = row.get(&quot;tls_cert_blob_path&quot;)<br>    if not blob_path:<br>        with _tls_cert_cache_lock:<br>            _tls_cert_cache[row_id] = None<br>        return None<br><br>    container = row.get(&quot;tls_cert_blob_container&quot;) or BLOB_CONTAINER_NAME<br>    try:<br>        azure_client = BlobStorageClient().blob_service_client<br>        blob_client = azure_client.get_blob_client(container=container, blob=blob_path)<br>        cert_bytes: bytes = blob_client.download_blob().readall()<br>        with _tls_cert_cache_lock:<br>            _tls_cert_cache[row_id] = cert_bytes<br>        _logger.info(<br>            &quot;SinkClientFactory: loaded TLS certificate for endpoint=%s from blob %s/%s (%d bytes)&quot;,<br>            row[&quot;name&quot;], container, blob_path, len(cert_bytes),<br>        )<br>        return cert_bytes<br>    except Exception as e:<br>        _logger.error(<br>            &quot;SinkClientFactory: failed to read PEM from blob %s/%s for endpoint=%s: %s -- falling back to system CA bundle&quot;,<br>            container, blob_path, row[&quot;name&quot;], e,<br>        )<br>        with _tls_cert_cache_lock:<br>            _tls_cert_cache[row_id] = None<br>        return None<br><br><br>class SinkClientFactory:<br>    &quot;&quot;&quot;Builds the right TraceSinkClient for a collector_endpoints row. Adding a<br>    transport neither generic client supports is the only case requiring a new<br>    TraceSinkClient implementation registered here.&quot;&quot;&quot;<br><br>    @staticmethod<br>    def build(row: dict) -&gt; TraceSinkClient:<br>        tls_verify = bool(row.get(&quot;tls_verify&quot;, True))<br>        tls_cert_bytes = _load_tls_cert_bytes(row) if tls_verify else None<br>        transport = row.get(&quot;transport_type&quot;)<br>        if transport == &quot;grpc&quot;:<br>            return OtlpGrpcExporterClient(<br>                tls_verify=tls_verify, tls_cert_bytes=tls_cert_bytes,<br>                ssl_target_name_override=row.get(&quot;grpc_ssl_target_name_override&quot;),<br>            )<br>        if transport == &quot;http&quot;:<br>            return OtlpHttpExporterClient(tls_verify=tls_verify, tls_cert_bytes=tls_cert_bytes)<br>        raise ValueError(f&quot;Unsupported transport_type={transport!r} for endpoint={row.get(&#39;name&#39;)!r}&quot;)<br><br><br># ─── Circuit Breaker (tiny, async-native, one instance per sink) ─────────<br><br>class CircuitBreaker:<br>    def __init__(self, fail_threshold: int = 5, cooldown: float = 30.0):<br>        self._fail_threshold = fail_threshold<br>        self._cooldown = cooldown<br>        self._consecutive_failures = 0<br>        self._opened_at: Optional[float] = None<br><br>    @property<br>    def is_open(self) -&gt; bool:<br>        if self._opened_at is None:<br>            return False<br>        if time.monotonic() - self._opened_at &gt;= self._cooldown:<br>            self._opened_at = None  # half-open: allow the next attempt through<br>            self._consecutive_failures = 0<br>            return False<br>        return True<br><br>    def record_success(self) -&gt; None:<br>        self._consecutive_failures = 0<br>        self._opened_at = None<br><br>    def record_failure(self, sink_name: str) -&gt; None:<br>        self._consecutive_failures += 1<br>        if self._consecutive_failures &gt;= self._fail_threshold and self._opened_at is None:<br>            self._opened_at = time.monotonic()<br>            _logger.warning(<br>                &quot;%s: circuit breaker OPENED after %d consecutive failures, cooling down %.0fs&quot;,<br>                sink_name, self._consecutive_failures, self._cooldown,<br>            )<br><br><br># ─── SinkConfig + ResilientBatchSink (the reusable &quot;optimized connection&quot;) ─<br><br>@dataclass(frozen=True)<br>class SinkConfig:<br>    &quot;&quot;&quot;All tunables come from a collector_endpoints row&#39;s batch_config JSONB<br>    column (not environment variables) -- every destination is independently<br>    configurable, with sane Python-level defaults for anything the row omits.&quot;&quot;&quot;<br>    max_batch_bytes: int = 3_145_728       # 3MB default -- operator-tunable per destination<br>    flush_interval: float = 1.0<br>    queue_max_bytes: int = 30_000_000<br>    send_concurrency: int = 8<br>    rate_limit_qps: Optional[float] = None<br>    max_retry_attempts: int = 3<br>    circuit_fail_threshold: int = 5<br>    circuit_cooldown: float = 30.0<br><br>    @classmethod<br>    def from_row(cls, batch_config: dict) -&gt; &quot;SinkConfig&quot;:<br>        return cls(<br>            max_batch_bytes=batch_config.get(&quot;max_batch_bytes&quot;, cls.max_batch_bytes),<br>            flush_interval=batch_config.get(&quot;flush_interval&quot;, cls.flush_interval),<br>            queue_max_bytes=batch_config.get(&quot;queue_max_bytes&quot;, cls.queue_max_bytes),<br>            send_concurrency=batch_config.get(&quot;send_concurrency&quot;, cls.send_concurrency),<br>            rate_limit_qps=batch_config.get(&quot;rate_limit_qps&quot;),<br>            max_retry_attempts=batch_config.get(&quot;max_retry_attempts&quot;, cls.max_retry_attempts),<br>            circuit_fail_threshold=batch_config.get(&quot;circuit_fail_threshold&quot;, cls.circuit_fail_threshold),<br>            circuit_cooldown=batch_config.get(&quot;circuit_cooldown&quot;, cls.circuit_cooldown),<br>        )<br><br><br>class _SinkBuffer:<br>    &quot;&quot;&quot;Per-(endpoint, headers) buffer. collections.deque + asyncio.Lock,<br>    deliberately not queue.Queue: the consumer here is natively async (gRPC/HTTP),<br>    so there&#39;s no blocking I/O to isolate onto a dedicated thread the way<br>    BlobHandler&#39;s queue.Queue + threading.Thread legitimately needs.<br><br>    endpoint/headers are fixed at creation: spaces share one endpoint but differ in<br>    credentials, so a buffer must never hold traces destined for different spaces.&quot;&quot;&quot;<br><br>    def __init__(self, endpoint: str, headers: Dict[str, str]) -&gt; None:<br>        self.endpoint: str = endpoint<br>        self.headers: Dict[str, str] = headers<br>        self.entries: Deque[ExportTraceServiceRequest] = deque()<br>        self.trace_ids: Deque[str] = deque()<br>        self.byte_size: int = 0<br>        self.lock = asyncio.Lock()<br>        self.last_flush_ts: float = time.monotonic()<br><br><br>class ResilientBatchSink:<br>    &quot;&quot;&quot;One instance per destination (one per ACTIVE collector_endpoints row).<br>    Owns batching, drop-oldest backpressure, bounded concurrency, optional rate<br>    limiting, circuit breaking, and retry -- so no destination-specific<br>    throttling code is ever duplicated when a new destination is added.&quot;&quot;&quot;<br><br>    def __init__(self, name: str, client: TraceSinkClient, config: SinkConfig):<br>        self._name = name<br>        self._client = client<br>        self._config = config<br>        self._buffers: Dict[str, _SinkBuffer] = {}<br>        self._registry_lock = asyncio.Lock()<br>        self._send_semaphore = asyncio.Semaphore(config.send_concurrency)<br>        self._rate_limiter = (<br>            AsyncLimiter(config.rate_limit_qps, 1.0)<br>            if (config.rate_limit_qps and AsyncLimiter is not None) else None<br>        )<br>        self._breaker = CircuitBreaker(config.circuit_fail_threshold, config.circuit_cooldown)<br>        self._dropped_overflow = 0<br>        self._closed = False<br>        self._ticker_task: Optional[asyncio.Task] = None<br><br>    def start(self) -&gt; None:<br>        self._ticker_task = asyncio.create_task(self._flush_ticker())<br><br>    @staticmethod<br>    def _buffer_key(endpoint: str, headers: Dict[str, str]) -&gt; str:<br>        # Hashed so API keys are not held as dict keys / appear in logs.<br>        digest = hashlib.sha256(repr(sorted(headers.items())).encode(&quot;utf-8&quot;)).hexdigest()<br>        return f&quot;{endpoint}|{digest}&quot;<br><br>    async def _get_or_create_buffer(self, endpoint: str, headers: Dict[str, str]) -&gt; _SinkBuffer:<br>        key = self._buffer_key(endpoint, headers)<br>        async with self._registry_lock:<br>            if key not in self._buffers:<br>                self._buffers[key] = _SinkBuffer(endpoint, dict(headers))<br>            return self._buffers[key]<br><br>    async def submit(self, trace_chunks: List[ExportTraceServiceRequest], *,<br>                      endpoint: str, headers: Dict[str, str], trace_ids: List[str]) -&gt; None:<br>        &quot;&quot;&quot;ENQUEUE -- awaited by TraceDispatcher.dispatch(), never touches the network.<br>        O(spans), non-blocking: returns as soon as the buffer lock is released.&quot;&quot;&quot;<br>        buffer = await self._get_or_create_buffer(endpoint, headers)<br>        async with buffer.lock:<br>            for chunk, tid in zip(trace_chunks, trace_ids):<br>                size = chunk.ByteSize()<br>                if buffer.byte_size + size &gt; self._config.queue_max_bytes:<br>                    self._evict_oldest_locked(buffer, make_room_for=size)<br>                buffer.entries.append(chunk)<br>                buffer.trace_ids.append(tid)<br>                buffer.byte_size += size<br>            should_flush_now = buffer.byte_size &gt;= self._config.max_batch_bytes<br>        if should_flush_now:<br>            asyncio.create_task(self._flush(buffer, buffer.endpoint, buffer.headers))<br><br>    def _evict_oldest_locked(self, buffer: _SinkBuffer, make_room_for: int) -&gt; None:<br>        &quot;&quot;&quot;Drop-oldest overflow policy (confirmed). Caller already holds buffer.lock.&quot;&quot;&quot;<br>        while buffer.entries and buffer.byte_size + make_room_for &gt; self._config.queue_max_bytes:<br>            dropped = buffer.entries.popleft()<br>            dropped_tid = buffer.trace_ids.popleft()<br>            buffer.byte_size -= dropped.ByteSize()<br>            self._dropped_overflow += 1<br>            _logger.warning(<br>                &quot;%s: dropped oldest trace due to buffer overflow | trace_id=%s total_dropped=%d&quot;,<br>                self._name, dropped_tid, self._dropped_overflow,<br>            )<br><br>    async def _flush(self, buffer: _SinkBuffer, endpoint: str, headers: Dict[str, str]) -&gt; None:<br>        &quot;&quot;&quot;DEQUEUE -- pops oldest-first off the FIFO until the batch cap, merges, sends.&quot;&quot;&quot;<br>        async with buffer.lock:<br>            popped, popped_tids, popped_bytes = [], [], 0<br>            while buffer.entries and popped_bytes &lt; self._config.max_batch_bytes:<br>                item = buffer.entries.popleft()<br>                popped.append(item)<br>                popped_tids.append(buffer.trace_ids.popleft())<br>                popped_bytes += item.ByteSize()<br>            buffer.byte_size -= popped_bytes<br>            buffer.last_flush_ts = time.monotonic()<br>        if not popped:<br>            return<br><br>        merged = _build_trace_request(<br>            [(rs, ss, span) for req in popped for rs in req.resource_spans for ss in rs.scope_spans for span in ss.spans]<br>        )<br><br>        if self._breaker.is_open:<br>            _logger.warning(<br>                &quot;%s: circuit open, dropping batch without attempting send | trace_ids=%s payload_size=%s&quot;,<br>                self._name, popped_tids, _format_bytes(popped_bytes),<br>            )<br>            return<br><br>        async with self._send_semaphore:<br>            if self._rate_limiter is not None:<br>                async with self._rate_limiter:<br>                    ok = await self._send_with_retry(merged, endpoint, headers, popped_tids)<br>            else:<br>                ok = await self._send_with_retry(merged, endpoint, headers, popped_tids)<br><br>        if ok:<br>            self._breaker.record_success()<br>            _logger.info(<br>                &quot;%s: flush succeeded | trace_ids=%s payload_size=%s&quot;,<br>                self._name, popped_tids, _format_bytes(popped_bytes),<br>            )<br>        else:<br>            self._breaker.record_failure(self._name)<br><br>    async def _send_with_retry(self, request, endpoint, headers, trace_ids) -&gt; bool:<br>        &quot;&quot;&quot;Exponential backoff + full jitter, same retry shape verified in<br>        docs/new_router.py. Non-retryable failures (NonRetryableSendError) are<br>        not retried at all -- fail fast, drop immediately.&quot;&quot;&quot;<br>        delay = 1.0<br>        for attempt in range(1, self._config.max_retry_attempts + 1):<br>            try:<br>                ok = await self._client.send(request, endpoint, headers, trace_ids=trace_ids, label=self._name)<br>            except NonRetryableSendError as e:<br>                _logger.error(<br>                    &quot;%s: non-retryable failure, trace(s) dropped | trace_ids=%s | %s&quot;,<br>                    self._name, trace_ids, e,<br>                )<br>                return False<br>            if ok:<br>                return True<br>            if attempt &lt; self._config.max_retry_attempts:<br>                await asyncio.sleep(delay + random.uniform(0, delay))<br>                delay *= 2<br>        _logger.error(<br>            &quot;%s: all %d attempts exhausted, trace(s) dropped | trace_ids=%s&quot;,<br>            self._name, self._config.max_retry_attempts, trace_ids,<br>        )<br>        return False<br><br>    async def _flush_ticker(self) -&gt; None:<br>        &quot;&quot;&quot;Background asyncio task (not a thread) -- time-based flush trigger,<br>        runs every flush_interval so low-traffic destinations aren&#39;t held indefinitely.&quot;&quot;&quot;<br>        while not self._closed:<br>            await asyncio.sleep(self._config.flush_interval)<br>            for buffer in list(self._buffers.values()):<br>                async with buffer.lock:<br>                    due = bool(buffer.entries) and (time.monotonic() - buffer.last_flush_ts) &gt;= self._config.flush_interval<br>                if due:<br>                    await self._flush(buffer, buffer.endpoint, headers=buffer.headers)<br><br>    @property<br>    def stats(self) -&gt; Dict[str, Any]:<br>        return {<br>            &quot;client_stats&quot;: self._client.stats,<br>            &quot;dropped_overflow&quot;: self._dropped_overflow,<br>            &quot;breaker_open&quot;: self._breaker.is_open,<br>        }<br><br>    async def close(self) -&gt; None:<br>        &quot;&quot;&quot;Graceful drain (confirmed): flush whatever remains buffered before<br>        stopping, rather than silently discarding it on shutdown.&quot;&quot;&quot;<br>        self._closed = True<br>        if self._ticker_task is not None:<br>            self._ticker_task.cancel()<br>        for buffer in list(self._buffers.values()):<br>            if buffer.entries:<br>                await self._flush(buffer, buffer.endpoint, headers=buffer.headers)<br>        await self._client.close()<br><br><br># ─── SinkRoute + CollectorEndpointRegistry (DB-backed, poll-only) ────────<br><br>@dataclass<br>class SinkRoute:<br>    name: str<br>    routing_rule: dict<br>    creds_resolution: dict<br>    row: dict           # full collector_endpoints row -- used by CredsResolver&#39;s STATIC branch<br>    sink: ResilientBatchSink<br><br><br>class CollectorEndpointRegistry:<br>    &quot;&quot;&quot;Loads ACTIVE collector_endpoints rows on a polling interval<br>    (COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS, default 900s). This service<br>    never writes to that table -- obs_mgmt_svcs owns the admin CRUD API, a<br>    separate service/process, so there is no &quot;refresh on write&quot; shortcut here.<br><br>    After a load FAILURE (DB permission error, connection issue, etc.) the next<br>    retry uses a short, exponentially-growing backoff (capped at poll_interval)<br>    instead of blindly waiting the full steady-state interval -- so fixing the<br>    underlying issue (e.g. granting table permission) takes effect in seconds/<br>    minutes, not up to 15 minutes later.<br>    &quot;&quot;&quot;<br><br>    _FAILURE_RETRY_BASE_SECONDS = 15.0<br><br>    def __init__(self, poll_interval: float = COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS):<br>        self._poll_interval = poll_interval<br>        self.routes: List[SinkRoute] = []<br>        self._routes_by_id: Dict[str, Tuple[SinkRoute, Any]] = {}  # id -&gt; (route, modified_ts)<br>        self._poll_task: Optional[asyncio.Task] = None<br>        self._closed = False<br>        self._consecutive_failures = 0<br><br>    async def bootstrap(self) -&gt; None:<br>        &quot;&quot;&quot;Initial load at service startup -- must succeed enough to produce at<br>        least an empty (not crashed) routing table; failures are logged, never raised.&quot;&quot;&quot;<br>        await self._refresh_once()<br>        self._poll_task = asyncio.create_task(self._poll_loop())<br><br>    async def _poll_loop(self) -&gt; None:<br>        while not self._closed:<br>            if self._consecutive_failures &gt; 0:<br>                delay = min(<br>                    self._poll_interval,<br>                    self._FAILURE_RETRY_BASE_SECONDS * (2 ** (self._consecutive_failures - 1)),<br>                )<br>            else:<br>                delay = self._poll_interval<br>            jitter = random.uniform(0, min(5.0, delay * 0.1))<br>            await asyncio.sleep(delay + jitter)<br>            await self._refresh_once()<br><br>    async def _refresh_once(self) -&gt; None:<br>        from obs_telemetry_svcs.services.collector_endpoint_service import CollectorEndpointService<br><br>        try:<br>            rows = await asyncio.to_thread(CollectorEndpointService.get_active_endpoints)<br>        except Exception as e:<br>            self._consecutive_failures += 1<br>            next_retry = min(<br>                self._poll_interval,<br>                self._FAILURE_RETRY_BASE_SECONDS * (2 ** (self._consecutive_failures - 1)),<br>            )<br>            _logger.error(<br>                &quot;CollectorEndpointRegistry: failed to load collector_endpoints (consecutive failures=%d, &quot;<br>                &quot;retrying in ~%.0fs), keeping existing routes: %s&quot;,<br>                self._consecutive_failures, next_retry, e, exc_info=True,<br>            )<br>            return<br>        self._consecutive_failures = 0<br><br>        new_routes_by_id: Dict[str, Tuple[SinkRoute, Any]] = {}<br>        seen_ids: Set[str] = set()<br>        changed = 0<br><br>        for row in rows:<br>            row_id = row[&quot;id&quot;]<br>            seen_ids.add(row_id)<br>            existing = self._routes_by_id.get(row_id)<br>            if existing is not None and existing[1] == row.get(&quot;modified_ts&quot;):<br>                new_routes_by_id[row_id] = existing  # unchanged -- reuse the sink untouched (buffer/cert cache preserved)<br>                continue<br>            try:<br>                client = SinkClientFactory.build(row)<br>                sink = ResilientBatchSink(row[&quot;name&quot;], client, SinkConfig.from_row(row.get(&quot;batch_config&quot;) or {}))<br>                sink.start()<br>                route = SinkRoute(<br>                    name=row[&quot;name&quot;], routing_rule=row[&quot;routing_rule&quot;],<br>                    creds_resolution=row[&quot;creds_resolution&quot;], row=row, sink=sink,<br>                )<br>                new_routes_by_id[row_id] = (route, row.get(&quot;modified_ts&quot;))<br>                changed += 1<br>                _logger.info(&quot;CollectorEndpointRegistry: activated endpoint=%s transport=%s&quot;, row[&quot;name&quot;], row[&quot;transport_type&quot;])<br>            except Exception as e:<br>                _logger.warning(<br>                    &quot;CollectorEndpointRegistry: skipping malformed collector_endpoints row id=%s name=%s: %s&quot;,<br>                    row_id, row.get(&quot;name&quot;), e,<br>                )<br>                if existing is not None:<br>                    new_routes_by_id[row_id] = existing  # keep the last-known-good route rather than dropping traffic<br><br>        # Graceful drain for rows that disappeared or were disabled (confirmed: finish buffer, then stop)<br>        removed_ids = set(self._routes_by_id) - seen_ids<br>        for row_id in removed_ids:<br>            route, _ = self._routes_by_id[row_id]<br>            _logger.info(&quot;CollectorEndpointRegistry: draining and removing endpoint=%s&quot;, route.name)<br>            asyncio.create_task(route.sink.close())<br>            changed += 1<br><br>        self._routes_by_id = new_routes_by_id<br>        self.routes = [route for route, _ in new_routes_by_id.values()]  # atomic swap -- list reassignment under the GIL<br>        _logger.info(<br>            &quot;CollectorEndpointRegistry: refresh complete | active=%d changed=%d&quot;,<br>            len(self.routes), changed,<br>        )<br><br>    async def close(self) -&gt; None:<br>        self._closed = True<br>        if self._poll_task is not None:<br>            self._poll_task.cancel()<br>        for route, _ in self._routes_by_id.values():<br>            await route.sink.close()<br><br><br># ─── Blob Handler (Queue-Based, unchanged from handlers_v2.py) ──────────<br><br>class BlobHandler:<br>    &quot;&quot;&quot;<br>    Queue-based batching handler for Azure Blob Storage.<br><br>    Records are enqueued synchronously via enqueue(). A background consumer<br>    thread drains the queue and flushes to blob storage when batch_size is<br>    reached or flush_interval elapses. Always runs, unconditionally, for every<br>    trace -- independent of the routing table above.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        blob_file_path: str,<br>        batch_size: int = BLOB_BATCH_SIZE,<br>        flush_interval: int = BLOB_FLUSH_INTERVAL,<br>        max_queue_size: int = BLOB_QUEUE_MAX_SIZE,<br>        container_name: str = BLOB_CONTAINER_NAME,<br>    ):<br>        self._file_path_prefix = blob_file_path<br>        self._batch_size = batch_size<br>        self._flush_interval = flush_interval<br>        self._container = container_name<br><br>        self._queue: queue.Queue = queue.Queue(maxsize=max_queue_size)<br>        self._shutdown = threading.Event()<br>        self._blob_client: Optional[BlobStorageClient] = None<br>        self._client_lock = threading.Lock()<br><br>        self._thread = threading.Thread(<br>            target=self._consume_loop,<br>            name=&quot;BlobHandler-consumer&quot;,<br>            daemon=True,<br>        )<br>        self._thread.start()<br>        _logger.info(<br>            f&quot;BlobHandler initialized | path={blob_file_path} &quot;<br>            f&quot;batch={batch_size} flush={flush_interval}s queue_max={max_queue_size}&quot;<br>        )<br><br>    def enqueue(self, trace_dict: Dict) -&gt; None:<br>        &quot;&quot;&quot;Enqueue a trace dict for blob storage. Drops oldest on overflow.&quot;&quot;&quot;<br>        try:<br>            self._queue.put_nowait(trace_dict)<br>        except queue.Full:<br>            try:<br>                self._queue.get_nowait()<br>            except queue.Empty:<br>                pass<br>            try:<br>                self._queue.put_nowait(trace_dict)<br>            except queue.Full:<br>                _logger.warning(&quot;BlobHandler: queue full after drop, record lost&quot;)<br><br>    def _get_blob_client(self) -&gt; BlobStorageClient:<br>        with self._client_lock:<br>            if self._blob_client is None:<br>                self._blob_client = BlobStorageClient()<br>            return self._blob_client<br><br>    def _consume_loop(self) -&gt; None:<br>        buffer: List[Dict] = []<br>        last_flush = time.monotonic()<br><br>        while not self._shutdown.is_set():<br>            try:<br>                remaining = self._flush_interval - (time.monotonic() - last_flush)<br>                try:<br>                    buffer.append(self._queue.get(timeout=max(0.1, remaining)))<br>                except queue.Empty:<br>                    pass<br><br>                while len(buffer) &lt; self._batch_size:<br>                    try:<br>                        buffer.append(self._queue.get_nowait())<br>                    except queue.Empty:<br>                        break<br><br>                elapsed = time.monotonic() - last_flush<br>                if (<br>                    len(buffer) &gt;= self._batch_size<br>                    or (buffer and elapsed &gt;= self._flush_interval)<br>                ):<br>                    self._write_batch(buffer)<br>                    buffer = []<br>                    last_flush = time.monotonic()<br><br>            except Exception as e:<br>                _logger.error(f&quot;BlobHandler: consumer error: {e}&quot;, exc_info=True)<br><br>        while not self._queue.empty():<br>            try:<br>                buffer.append(self._queue.get_nowait())<br>            except queue.Empty:<br>                break<br>        if buffer:<br>            self._write_batch(buffer)<br><br>    def _write_batch(self, batch: List[Dict]) -&gt; None:<br>        if not batch:<br>            return<br><br>        start = time.monotonic()<br>        try:<br>            import json<br>            serialized = json.dumps(batch, default=str)<br>            now = datetime.now(timezone.utc)<br>            file_path = (<br>                f&quot;{self._file_path_prefix}/{now.strftime(&#39;%Y-%m-%d&#39;)}/&quot;<br>                f&quot;{now.strftime(&#39;%Y%m%dT%H%M%S%f&#39;)}_{generate_unique_number()}.json&quot;<br>            )<br><br>            loc = BlobLocation()<br>            loc.container_name = self._container<br>            loc.absolute_path = file_path<br><br>            self._get_blob_client().save_file(<br>                serialized, loc, StorageObjectType.utf_8.value<br>            )<br><br>            ms = int((time.monotonic() - start) * 1000)<br>            _logger.info(<br>                f&quot;BlobHandler: wrote {len(batch)} records in {ms}ms -&gt; {file_path}&quot;<br>            )<br>        except Exception as e:<br>            _logger.error(f&quot;BlobHandler: write failed: {e}&quot;, exc_info=True)<br><br>    def close(self) -&gt; None:<br>        _logger.info(&quot;BlobHandler: shutting down&quot;)<br>        self._shutdown.set()<br>        self._thread.join(timeout=60)<br>        _logger.info(&quot;BlobHandler: shutdown complete&quot;)<br><br><br># ─── Trace Dispatcher (Orchestrator) ─────────────────────────────────────<br><br>class TraceDispatcher:<br>    &quot;&quot;&quot;<br>    Central orchestrator for trace processing.<br><br>    Parses protobuf once, builds a DispatchContext, then:<br>        1. All traces -&gt; BlobHandler (enqueued for batched blob writes, unconditional)<br>        2. For each registered route: evaluate its routing_rule per trace-chunk,<br>           resolve credentials, submit matching chunks to that route&#39;s sink<br><br>    The routes list is owned and kept current by CollectorEndpointRegistry --<br>    this class has zero knowledge of individual destinations.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        registry: CollectorEndpointRegistry,<br>        blob_handler: Optional[BlobHandler] = None,<br>        creds_resolver: Optional[CredsResolver] = None,<br>        default_project: str = DEFAULT_PROJECT_NAME,<br>    ):<br>        self._registry = registry<br>        self._blob = blob_handler<br>        self._creds_resolver = creds_resolver or CredsResolver(CredentialProvider())<br>        self._default_project = default_project<br>        _logger.info(<br>            f&quot;TraceDispatcher initialized | blob={&#39;enabled&#39; if blob_handler else &#39;disabled&#39;} &quot;<br>            f&quot;collector_endpoint_refresh_interval={COLLECTOR_ENDPOINT_REFRESH_INTERVAL_SECONDS}s&quot;<br>        )<br><br>    async def dispatch(<br>        self, raw_body: bytes, client_id: str, space_id: str, space_type: str = &quot;&quot;<br>    ) -&gt; None:<br>        request = ExportTraceServiceRequest()<br>        try:<br>            request.ParseFromString(raw_body)<br>        except DecodeError as e:<br>            _logger.error(&quot;TraceDispatcher: protobuf decode failed, request rejected | client=%s error=%s&quot;, client_id, e)<br>            return<br>        except Exception as e:<br>            _logger.error(&quot;TraceDispatcher: unexpected parse error, request rejected | client=%s error=%s&quot;, client_id, e)<br>            return<br><br>        if not request.resource_spans:<br>            _logger.info(&quot;TraceDispatcher: empty payload (no resource_spans), nothing to send | client=%s&quot;, client_id)<br>            return<br><br>        span_count = sum(len(ss.spans) for rs in request.resource_spans for ss in rs.scope_spans)<br>        _logger.info(<br>            &quot;TraceDispatcher: received | client=%s span_count=%d body_size=%s&quot;,<br>            client_id, span_count, _format_bytes(len(raw_body)),<br>        )<br><br>        project_name = client_id or self._default_project<br>        _inject_resource_attribute(request, OPENINFERENCE_PROJECT_NAME_KEY, project_name)<br><br>        ctx = build_dispatch_context(request, client_id, space_id, space_type)<br><br>        # Blob always runs, unconditionally -- no rule check, no routing table involved.<br>        if self._blob:<br>            try:<br>                for chunk in ctx.trace_chunks:<br>                    self._blob.enqueue(MessageToDict(chunk.request, preserving_proto_field_name=True))<br>                _logger.info(<br>                    &quot;TraceDispatcher: blob enqueued | client=%s count=%d trace_ids=%s&quot;,<br>                    client_id, len(ctx.trace_chunks), [c.trace_id_hex for c in ctx.trace_chunks],<br>                )<br>            except Exception as e:<br>                _logger.error(&quot;TraceDispatcher: blob enqueue failed | client=%s error=%s&quot;, client_id, e)<br><br>        routes = self._registry.routes  # snapshot -- the registry may atomically swap this list concurrently<br>        for route in routes:<br>            matching = [c for c in ctx.trace_chunks if RuleEvaluator.evaluate(route.routing_rule, ctx, c)]<br>            if not matching:<br>                continue<br>            creds = self._creds_resolver.resolve(route.creds_resolution, ctx, route.row)<br>            if not creds:<br>                _logger.warning(<br>                    &quot;TraceDispatcher: no credentials resolved for route=%s, trace(s) not sent | client=%s trace_ids=%s&quot;,<br>                    route.name, client_id, [c.trace_id_hex for c in matching],<br>                )<br>                continue<br>            # Fixed-project destinations (SPACE_NAME_LOOKUP, e.g. agent-forge)<br>            # override the resource-level project name on a clone -- never<br>            # mutate the shared chunk, since other routes still need the<br>            # default client_id stamp. Client identity is preserved on that<br>            # same clone via the rai_client_id span attribute (matches<br>            # handlers_v2.py&#39;s agent-forge handler exactly).<br>            route_project_name = creds.get(&quot;project_name&quot;)<br>            if route_project_name and route_project_name != project_name:<br>                route_requests = []<br>                for c in matching:<br>                    cloned = ExportTraceServiceRequest()<br>                    cloned.CopyFrom(c.request)<br>                    _inject_resource_attribute(cloned, OPENINFERENCE_PROJECT_NAME_KEY, route_project_name)<br>                    _inject_span_attribute(cloned, RAI_CLIENT_ID_KEY, project_name)<br>                    route_requests.append(cloned)<br>            else:<br>                route_requests = [c.request for c in matching]<br>            await route.sink.submit(<br>                route_requests,<br>                endpoint=creds[&quot;endpoint&quot;], headers=creds[&quot;headers&quot;],<br>                trace_ids=[c.trace_id_hex for c in matching],<br>            )<br><br>    async def close(self) -&gt; None:<br>        _logger.info(&quot;TraceDispatcher closing&quot;)<br>        if self._blob:<br>            self._blob.close()<br>        await self._registry.close()<br>        _logger.info(&quot;TraceDispatcher closed&quot;)<br><br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d4d339f9c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Otel collector]]></title>
            <link>https://medium.com/@forswayamnptelcourse/otel-collector-9892354ca894?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/9892354ca894</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 13:03:56 GMT</pubDate>
            <atom:updated>2026-11-09T13:03:56.278Z</atom:updated>
            <content:encoded><![CDATA[<p><strong># Trace Collector Throttle-Safe Dispatch — Design Doc</strong></p><p>Status: <strong>**Proposed**</strong> (pending team review)</p><p>Owner: obs_telemetry_svcs</p><p>Scope: `src/obs_telemetry_svcs/util/handlers_v2.py` (`TraceDispatcher`, Arize clients, Cribl client)</p><p>— -</p><p><strong>## 1. Problem Statement</strong></p><p>Load test at QPM 3900 (Arize UAT `BUAT` space, client `39e7c1a3–18dc-49dc-8786–5009a83a4f1d`), identical script/load against two targets:</p><p>| Target | Requests | Dropped (missing in Arize) | Drop % | Time to land in Arize |</p><p>| — -| — -| — -| — -| — -|</p><p>| Direct to Arize (`/v1/traces`) | 39,896 | 436 | <strong>**1.09%**</strong> | ~5 min |</p><p>| Via OBS collector (`/api/v2/trace`) | 39,958 | 20,168 | <strong>**50.47%**</strong> | ~5 min |</p><p>Traffic mix (both runs): 60% `trace_llm_50KB`, 40% `trace_agent_1024KB` (contains `AGENT`-kind spans).</p><p>The collector’s HTTP layer shows <strong>**zero failures**</strong> in Locust (`# Fails = 0` both endpoints) — the collector always returns `200` immediately (fire-and-forget ingestion). The 50% drop is invisible at the HTTP layer; it only surfaces downstream, when traces never arrive at Arize.</p><p><strong>## 2. Root Cause Analysis</strong></p><p>Traced through `otel_telemetry.py` → `handlers_v2.py`:</p><p>1. <strong>**Fan-out amplification**</strong>: any request containing `AGENT` spans (the 40% / 1MB payload slice — the largest traffic by bytes) triggers <strong>**two**</strong> separate outbound Arize `Export()` calls from one inbound request: one to Arize-primary (full request) and one to Arize-agent-forge (agent-only subset). The direct-to-Arize baseline sends once. This roughly doubles outbound call count/bytes for the heaviest slice of traffic against the same Arize tenant.</p><p>2. <strong>**Retry storm, no jitter**</strong>: `RESOURCE_EXHAUSTED` / `UNAVAILABLE` / HTTP `429` are retried with <strong>**linear backoff (1s/2s/3s), no jitter**</strong>. Once Arize starts throttling under the doubled load, every concurrent dispatch (up to `MAX_CONCURRENT_DISPATCHES=500`) retries at near-identical offsets — a self-reinforcing retry storm that keeps re-hitting an already-struggling Arize until the 3 attempts are exhausted and the trace is dropped.</p><p>3. <strong>**No batching/coalescing for Arize**</strong> — unlike `BlobHandler` (queue + size/time-based flush, already correct), every inbound request synchronously maps 1:1 to an outbound Arize call. Outbound rate == inbound rate, with no decoupling.</p><p>4. <strong>**No circuit breaker**</strong> — nothing stops the collector from continuing to hammer an unhealthy Arize/Cribl endpoint.</p><p>5. <strong>**Cribl forwarding has zero concurrency bound**</strong> — `asyncio.create_task(self._send(request))` with no semaphore at all; the task also escapes the dispatch semaphore’s lifetime once `dispatch()` returns.</p><p>6. <strong>**Single global semaphore**</strong> (`_dispatch_semaphore`) bounds whole `dispatch()` calls but not individual downstream calls (Arize-primary, Arize-agent, Cribl) independently.</p><p>7. <strong>**Multi-process blind spot**</strong>: `WORKER_COUNT=5` gunicorn workers per pod + N pod replicas — any in-process limiter is a per-worker-process budget; true aggregate load on Arize = budget × workers × replicas.</p><p><strong>## 3. Goals / Non-Goals</strong></p><p><strong>**Goals**</strong></p><p>- Near-zero trace drop under sustained high load.</p><p>- Never exceed a safe, configurable request rate to Arize or Cribl (no over-throttling downstream).</p><p>- One reusable mechanism so future destinations (new Arize projects, new forwarding targets) get the same protection with zero bespoke throttling code.</p><p>- Async-first, low CPU/memory overhead, safe under multi-worker/multi-replica deployment.</p><p><strong>**Non-goals**</strong></p><p>- Changing the ingestion contract (`200 OK` fire-and-forget stays as-is).</p><p>- Changing `BlobHandler` (already correct).</p><p>- Guaranteeing <em>*exactly-once*</em> delivery to Arize — this design targets <em>*at-least-effort, near-zero-drop*</em>, not transactional delivery.</p><p><strong>## 4. Architecture</strong></p><p>```mermaid</p><p>flowchart LR</p><p>A[“POST /api/v2/trace”] →|fire-and-forget task| B[“TraceDispatcher.dispatch()”]</p><p>B → C[“BlobHandler queue (unchanged)”]</p><p>B → D[“SinkRoute: arize_primary”]</p><p>B → E[“SinkRoute: arize_agent_forge”]</p><p>B → F[“SinkRoute: cribl”]</p><p>D → G1[“ResilientBatchSink #1”]</p><p>E → G2[“ResilientBatchSink #2”]</p><p>F → G3[“ResilientBatchSink #3”]</p><p>G1 &amp; G2 &amp; G3 → H[“flush: size(per-sink limit) OR time(per-sink interval), whichever first”]</p><p>H → I[“semaphore -&gt; rate limiter -&gt; circuit breaker -&gt; tenacity retry”]</p><p>I → J[“TraceSinkClient.send() (OtlpGrpcExporterClient / OtlpHttpExporterClient, configured per DB row)”]</p><p>```</p><p><strong>### 4.1 `TraceSinkClient` (interface, generalized from `ArizeClientBase`)</strong></p><p>```python</p><p>class TraceSinkClient(ABC):</p><p>async def send(self, request, endpoint, headers=None, trace_ids=None, label=””) -&gt; bool: …</p><p>@property</p><p>def stats(self) -&gt; Dict[str, int]: …</p><p>async def close(self) -&gt; None: …</p><p>```</p><p>Implemented by exactly <strong>**two generic classes**</strong> — `OtlpGrpcExporterClient` and `OtlpHttpExporterClient` (section 12.1) — not bespoke per-vendor classes. Both Arize and Cribl (and any future destination) are <strong>**configured instances**</strong> of these two, parameterized entirely from a `collector_endpoints` DB row (transport, TLS, headers) — see 12.9.</p><p><strong>### 4.2 `ResilientBatchSink` (the reusable “optimized connection”)</strong></p><p>One instance per destination (`arize_primary`, `arize_agent_forge`, `cribl`, any future one). Wraps one `TraceSinkClient` and owns every throttle-protection concern so it never needs re-implementing:</p><p>```python</p><p>@dataclass(frozen=True)</p><p>class SinkConfig:</p><p>max_batch_bytes: int = 3_145_728 # per-sink cap — NOT a shared constant</p><p>flush_interval: float = 1.0</p><p>queue_max_bytes: int = 30_000_000</p><p>send_concurrency: int = 8</p><p>rate_limit_qps: Optional[float] = None</p><p>max_retry_attempts: int = 3</p><p>circuit_fail_threshold: int = 5</p><p>circuit_cooldown: float = 30.0</p><p>@classmethod</p><p>def from_row(cls, batch_config: dict) -&gt; “SinkConfig”:</p><p>“””Builds from a collector_endpoints row’s batch_config JSONB column (section 12.9),</p><p>falling back to the dataclass defaults above for any key the row omits.”””</p><p>return cls(</p><p>max_batch_bytes=batch_config.get(“max_batch_bytes”, cls.max_batch_bytes),</p><p>flush_interval=batch_config.get(“flush_interval”, cls.flush_interval),</p><p>queue_max_bytes=batch_config.get(“queue_max_bytes”, cls.queue_max_bytes),</p><p>send_concurrency=batch_config.get(“send_concurrency”, cls.send_concurrency),</p><p>rate_limit_qps=batch_config.get(“rate_limit_qps”),</p><p>max_retry_attempts=batch_config.get(“max_retry_attempts”, cls.max_retry_attempts),</p><p>circuit_fail_threshold=batch_config.get(“circuit_fail_threshold”, cls.circuit_fail_threshold),</p><p>circuit_cooldown=batch_config.get(“circuit_cooldown”, cls.circuit_cooldown),</p><p>)</p><p>class ResilientBatchSink:</p><p>def __init__(self, name: str, client: TraceSinkClient, config: SinkConfig): …</p><p>def submit(self, trace_chunks: List[ExportTraceServiceRequest], *,</p><p>endpoint: str, headers: Dict[str, str], trace_ids: List[str]) -&gt; None: …</p><p>```</p><p>Each destination’s `SinkConfig` is built from its own `collector_endpoints` row’s `batch_config` JSONB column (section 12.9/12.10) — no shared constant is ever hardcoded across destinations, and nothing is read from the environment:</p><p>```python</p><p># built by CollectorEndpointRegistry / SinkClientFactory from DB rows — see 12.5, 12.9</p><p>sink = ResilientBatchSink(row.name, SinkClientFactory.build(row), SinkConfig.from_row(row.batch_config))</p><p>```</p><p>If Cribl’s deployed instance accepts 2MB or 6MB instead of Arize’s ~3MB-safe cap, that’s purely `{“max_batch_bytes”: 2000000}` (or `6000000`) in that row’s `batch_config` column via the API/UI — no code change, no redeploy, and it can never accidentally force Arize’s limit onto Cribl or vice versa.</p><p><strong>**Internal buffer**</strong> — keyed by `(endpoint, space_id)` (collector is multi-tenant; spans for different Arize spaces/accounts must never be merged): a `Dict[key, _SinkBuffer]`, where each `_SinkBuffer` wraps a `deque[ExportTraceServiceRequest]` (already-built per-trace requests, reusing existing `_partition_request`/`_build_trace_request` output) — <strong>**`collections.deque` + `asyncio.Lock`, deliberately not `queue.Queue`**</strong> (see below for why, contrasted with `BlobHandler`’s actual mechanism).</p><p><strong>**Enqueue/dequeue mechanics:**</strong></p><p>```python</p><p>class _SinkBuffer:</p><p>def __init__(self):</p><p>self._entries: Deque[ExportTraceServiceRequest] = deque()</p><p>self._byte_size: int = 0</p><p>self._lock = asyncio.Lock() # guards coroutine interleaving, not OS threads — no thread here at all</p><p>self._last_flush_ts: float = time.monotonic()</p><p>class ResilientBatchSink:</p><p>def __init__(self, name, client, config):</p><p>self._buffers: Dict[str, _SinkBuffer] = {}</p><p>self._registry_lock = asyncio.Lock()</p><p>async def submit(self, trace_chunks, *, endpoint, headers, trace_ids, key=None) -&gt; None:</p><p>“””ENQUEUE — awaited by dispatch(), never touches the network.”””</p><p>buffer = await self._get_or_create_buffer(key or endpoint)</p><p>async with buffer._lock:</p><p>for chunk in trace_chunks:</p><p>buffer._entries.append(chunk) # deque.append — O(1)</p><p>buffer._byte_size += chunk.ByteSize()</p><p>should_flush_now = buffer._byte_size &gt;= self._config.max_batch_bytes</p><p>if should_flush_now:</p><p>asyncio.create_task(self._flush(key, buffer, endpoint, headers))</p><p>async def _flush(self, key, buffer, endpoint, headers) -&gt; None:</p><p>“””DEQUEUE — pops oldest-first off the FIFO until the batch cap, merges, sends.”””</p><p>async with buffer._lock:</p><p>popped, popped_bytes = [], 0</p><p>while buffer._entries and popped_bytes &lt; self._config.max_batch_bytes:</p><p>item = buffer._entries.popleft() # deque.popleft — O(1), FIFO order preserved</p><p>popped.append(item)</p><p>popped_bytes += item.ByteSize()</p><p>buffer._byte_size -= popped_bytes</p><p>buffer._last_flush_ts = time.monotonic()</p><p>if popped:</p><p>async with self._send_semaphore:</p><p>await self._send_with_resilience(_merge_trace_requests(popped), endpoint, headers)</p><p>```</p><p><strong>**Why not `queue.Queue` (unlike `BlobHandler`)**</strong>: `BlobHandler` correctly uses `queue.Queue` + a dedicated `threading.Thread` because `BlobStorageClient.save_file()` is a <strong>**synchronous, blocking**</strong> Azure SDK call — it must run off the event loop, and `queue.Queue`’s `threading.Lock`/`Condition` is the right tool for safely handing data across that thread boundary. `ResilientBatchSink`’s downstream calls (`grpc.aio`, `httpx.AsyncClient`) are <strong>**natively async**</strong> — there is no blocking I/O to isolate onto a thread. Using `queue.Queue` here would mean either (a) calling its blocking `get(timeout=…)` directly inside a coroutine, freezing the entire event loop for every other in-flight request, or (b) running it via `loop.run_in_executor(…)`, i.e. spinning up a thread anyway for zero benefit. `asyncio.Lock` is the cooperative, userspace-only equivalent — correct because the only hazard here is coroutine interleaving at `await` points, not true OS-thread parallelism. `deque` also gives direct O(1) access to the front (oldest, for age-based flush and drop-oldest) and running byte-size tracking that `queue.Queue`/`asyncio.Queue` don’t expose natively — needed regardless for the dual size/time flush trigger, so there’s no simplicity trade-off being given up either.</p><p><strong>**Flush — whichever happens first:**</strong></p><p>1. `byte_size &gt;= max_batch_bytes` → flush immediately (shown above).</p><p>2. Background <strong>**`asyncio` task**</strong> (not a thread — `_flush_ticker`, one per sink) wakes every `flush_interval` and flushes any key whose oldest entry age ≥ `flush_interval` (1s default), even under the size cap — so low-traffic clients aren’t held indefinitely and batches stay reasonably sized.</p><p><strong>**Overflow — drop-oldest:**</strong> if `byte_size &gt; queue_max_bytes` (buffer growing faster than it drains, e.g. circuit open), `deque.popleft()` repeatedly (oldest == front of deque) until back under cap. O(1) per pop, bounded memory, logged as `dropped_overflow` per key — visible, never silent.</p><p><strong>**Oversized single request:**</strong> if one incoming chunk alone exceeds `max_batch_bytes`, it is flushed standalone (split further by trace boundary if still oversized) rather than blocking the buffer.</p><p><strong>**Idle key eviction:**</strong> `_flush_ticker` also drops empty, long-idle `(endpoint, space_id)` buffer entries (TTL-based) so the `_buffers` dict doesn’t grow unbounded across a long-lived multi-tenant process.</p><p><strong>**On flush (identical code path for every destination):**</strong></p><p>```</p><p>semaphore (send_concurrency) -&gt; rate limiter (optional) -&gt; circuit breaker -&gt; tenacity retry (exp backoff + full jitter) -&gt; client.send(merged_request, …)</p><p>```</p><p><strong>### 4.3 `TraceDispatcher` becomes a thin, declarative router — routes are rows, not code</strong></p><p>```python</p><p>class SinkRoute:</p><p>name: str</p><p>routing_rule: dict # JSON predicate DSL, section 12.4 — loaded from the DB row</p><p>creds_resolution: dict # SPACE_ID_LOOKUP | SPACE_NAME_LOOKUP | STATIC, section 12.3 — loaded from the DB row</p><p>sink: ResilientBatchSink</p><p># self._routes is built and kept up to date by CollectorEndpointRegistry (section 12.5),</p><p># not hardcoded in this class — TraceDispatcher only ever reads self._routes</p><p>for route in self._routes:</p><p>if RuleEvaluator.evaluate(route.routing_rule, ctx):</p><p>creds = CredsResolver.resolve(route.creds_resolution, ctx)</p><p>if creds:</p><p>route.sink.submit(ctx.trace_chunks_for(route), **creds, trace_ids=…)</p><p>```</p><p><strong>**Adding a future destination = inserting one new row in `collector_endpoints` via the API/UI — zero code, zero redeploy**</strong>, as long as its `routing_rule`/`creds_resolution` reuse the already-registered condition/resolver types (section 12.3/12.4). A genuinely <em>*new kind*</em> of condition or creds-resolution strategy (not just a new value) is the only case needing a small code change — one new registered function, nothing else.</p><p><strong>### 4.4 Per-destination tuning (same class, different DB row — not different code)</strong></p><p>| Sink | Configured via | max_batch_bytes default | max_retry_attempts | Notes |</p><p>| — -| — -| — -| — -| — -|</p><p>| `arize_primary` | `batch_config` JSONB on its row | 3MB | 3 | Full retry/backoff, own buffer + breaker |</p><p>| `arize_agent_forge` | `batch_config` JSONB on its row | 3MB | 3 | Separate buffer/breaker — one space throttling doesn’t affect the other |</p><p>| `cribl` | `batch_config` JSONB on its row — <strong>**not forced to 3MB**</strong>; set to whatever the deployed Cribl instance accepts (e.g. 2MB or 6MB) | independently configurable | <strong>**1**</strong> (effectively no retry) | Preserves existing “best-effort, never retried, never blocks ingestion” intent |</p><p>Every tunable in `SinkConfig` (batch size, flush interval, queue cap, concurrency, rate limit, retry attempts, circuit breaker thresholds) is resolved independently per sink from its own row’s `batch_config` column (section 12.9/12.10) — no shared constant, no environment variable, hardcoded across destinations.</p><p><strong>## 5. Class Reference, Initialization, Routing &amp; Extensibility</strong></p><p>```mermaid</p><p>classDiagram</p><p>class TraceSinkClient {</p><p>&lt;&lt;abstract&gt;&gt;</p><p>+send(request, endpoint, headers, trace_ids, label) bool</p><p>+stats() dict</p><p>+close()</p><p>}</p><p>class OtlpGrpcExporterClient</p><p>class OtlpHttpExporterClient</p><p>TraceSinkClient &lt;| — OtlpGrpcExporterClient</p><p>TraceSinkClient &lt;| — OtlpHttpExporterClient</p><p>class SinkConfig {</p><p>+int max_batch_bytes</p><p>+float flush_interval</p><p>+int queue_max_bytes</p><p>+int send_concurrency</p><p>+float rate_limit_qps</p><p>+int max_retry_attempts</p><p>+int circuit_fail_threshold</p><p>+float circuit_cooldown</p><p>+from_row(batch_config) SinkConfig</p><p>}</p><p>class ResilientBatchSink {</p><p>-str name</p><p>-TraceSinkClient client</p><p>-SinkConfig config</p><p>-dict buffers</p><p>+submit(trace_chunks, endpoint, headers, trace_ids)</p><p>+stats() dict</p><p>+close()</p><p>}</p><p>ResilientBatchSink → TraceSinkClient : wraps</p><p>ResilientBatchSink → SinkConfig : configured by</p><p>class CollectorEndpointTbl {</p><p>+id</p><p>+transport_type</p><p>+routing_rule</p><p>+creds_resolution</p><p>+batch_config</p><p>+status</p><p>}</p><p>class SinkClientFactory {</p><p>+build(row CollectorEndpointTbl) TraceSinkClient</p><p>}</p><p>SinkClientFactory → TraceSinkClient : creates</p><p>class CollectorEndpointRegistry {</p><p>+refresh_now(endpoint_id)</p><p>}</p><p>CollectorEndpointRegistry → CollectorEndpointTbl : reads</p><p>CollectorEndpointRegistry → SinkClientFactory</p><p>CollectorEndpointRegistry → ResilientBatchSink : builds</p><p>class SinkRoute {</p><p>+str name</p><p>+dict routing_rule</p><p>+dict creds_resolution</p><p>+ResilientBatchSink sink</p><p>}</p><p>SinkRoute → ResilientBatchSink</p><p>CollectorEndpointRegistry → SinkRoute : builds</p><p>class BlobHandler</p><p>class TraceDispatcher {</p><p>-routes</p><p>-BlobHandler blob</p><p>+dispatch(raw_body, client_id, space_id, space_type)</p><p>}</p><p>TraceDispatcher → SinkRoute : routes list</p><p>TraceDispatcher → BlobHandler</p><p>```</p><p><strong>### 5.1 The abstract class</strong></p><p><strong>**`TraceSinkClient`**</strong> (ABC) is the only abstract class in the design — a minimal Strategy interface: `send()`, `stats`, `close()`. `OtlpGrpcExporterClient` and `OtlpHttpExporterClient` are its <strong>**two**</strong> concrete implementations (section 12.1) — Arize-primary, Arize-agent-forge, Cribl, and any future destination are all configured <em>*instances*</em> of these two classes, built by `SinkClientFactory.build(row)` from a `collector_endpoints` row, never bespoke subclasses. `ResilientBatchSink` and `TraceDispatcher` never reference a concrete transport class directly — only `TraceSinkClient`.</p><p><strong>### 5.2 Initialization (service startup) — driven entirely by the DB, not hardcoded wiring</strong></p><p>```python</p><p># At startup: CollectorEndpointRegistry loads every ACTIVE row from collector_endpoints</p><p># and builds one TraceSinkClient + ResilientBatchSink + SinkRoute per row. There is no</p><p># hardcoded arize_primary_sink/cribl_sink construction anywhere in the codebase —</p><p># the 3 confirmed rows (arize_primary, arize_agent_forge, cribl) are DATA, seeded via</p><p># the DDL in section 12.9, not Python.</p><p>registry = CollectorEndpointRegistry(poll_interval=30.0)</p><p>await registry.bootstrap() # SELECT * FROM collector_endpoints WHERE status=’ACTIVE’, build all sinks/routes</p><p>trace_dispatcher = TraceDispatcher(</p><p>blob_handler=_blob_handler,</p><p>routes=registry.routes, # List[SinkRoute], owned and kept current by the registry (section 12.5)</p><p>)</p><p>```</p><p>Arize-primary and Arize-agent-forge both resolve their real endpoint/credentials <strong>**per request**</strong>, not at startup, via `creds_resolution` (`SPACE_ID_LOOKUP`/`SPACE_NAME_LOOKUP`, section 12.3) calling the existing, unchanged `CredentialProvider`. Only Cribl (and future `STATIC` rows) have a fixed endpoint/creds resolved once at sink-build time.</p><p><strong>### 5.3 Where the rule-based check happens — precisely, with complete code</strong></p><p><strong>**It happens in `TraceDispatcher`, via a separate `RuleEvaluator` class — never in `ResilientBatchSink`, never in `TraceSinkClient`.**</strong> Those two have no knowledge of routing rules at all; they only ever receive data already decided to belong to them. One precision point: the check must run <strong>**per trace-chunk, not once per request**</strong> — `arize_agent_forge`’s rule (`SPAN_ATTR_EXISTS` kind=`AGENT`) must match only the specific traces that actually contain an agent span, not “all traces if any one has an agent span” or “none.” `arize_primary` (`ALWAYS`) and `cribl` (request-level `ALL`/`CLIENT_ID_PREFIX`+`SPACE_TYPE_EQUALS`) happen to be chunk-independent, but the mechanism is the same for all three.</p><p>```python</p><p># Built once per dispatch() call, reusing _partition_request’s existing single pass.</p><p>@dataclass</p><p>class TraceChunk:</p><p>trace_id_hex: str</p><p>request: ExportTraceServiceRequest # single-trace request, from _build_trace_request</p><p>span_kinds: Set[str] # e.g. {“AGENT”, “LLM”} seen anywhere in this trace</p><p>resource_attrs: Dict[str, str] # e.g. {“openinference.project.name”: “…”}</p><p>@dataclass</p><p>class DispatchContext:</p><p>client_id: str</p><p>space_id: str</p><p>space_type: str</p><p>trace_chunks: List[TraceChunk] # one per trace_id in this request</p><p>class RuleEvaluator:</p><p>“””The rule-based check lives here, and only here.”””</p><p>_PREDICATES: Dict[str, Callable] = {}</p><p>@classmethod</p><p>def register(cls, rule_type: str):</p><p>def _wrap(fn):</p><p>cls._PREDICATES[rule_type] = fn</p><p>return fn</p><p>return _wrap</p><p>@classmethod</p><p>def evaluate(cls, rule: dict, ctx: DispatchContext, chunk: TraceChunk) -&gt; bool:</p><p>predicate = cls._PREDICATES.get(rule[“type”])</p><p>if predicate is None:</p><p>logger.error(“Unknown routing_rule type=%s — treating as non-match”, rule[“type”])</p><p>return False</p><p>return predicate(rule, ctx, chunk)</p><p>@RuleEvaluator.register(“ALWAYS”)</p><p>def _always(rule, ctx, chunk) -&gt; bool:</p><p>return True</p><p>@RuleEvaluator.register(“SPAN_ATTR_EXISTS”)</p><p>def _span_attr_exists(rule, ctx, chunk) -&gt; bool:</p><p>return rule[“value”] in chunk.span_kinds if rule[“key”] == SpanAttributes.OPENINFERENCE_SPAN_KIND else False</p><p>@RuleEvaluator.register(“RESOURCE_ATTR_EQUALS”)</p><p>def _resource_attr_equals(rule, ctx, chunk) -&gt; bool:</p><p>return chunk.resource_attrs.get(rule[“key”]) == rule[“value”]</p><p>@RuleEvaluator.register(“CLIENT_ID_PREFIX”)</p><p>def _client_id_prefix(rule, ctx, chunk) -&gt; bool:</p><p>return ctx.client_id.startswith(rule[“prefix”])</p><p>@RuleEvaluator.register(“SPACE_TYPE_EQUALS”)</p><p>def _space_type_equals(rule, ctx, chunk) -&gt; bool:</p><p>return ctx.space_type == rule[“value”]</p><p>@RuleEvaluator.register(“ALL”)</p><p>def _all(rule, ctx, chunk) -&gt; bool:</p><p>return all(RuleEvaluator.evaluate(r, ctx, chunk) for r in rule[“rules”])</p><p>@RuleEvaluator.register(“ANY”)</p><p>def _any(rule, ctx, chunk) -&gt; bool:</p><p>return any(RuleEvaluator.evaluate(r, ctx, chunk) for r in rule[“rules”])</p><p>class TraceDispatcher:</p><p>async def dispatch(self, raw_body: bytes, client_id: str, space_id: str, space_type: str = “”) -&gt; None:</p><p>request = ExportTraceServiceRequest()</p><p>request.ParseFromString(raw_body)</p><p>if not request.resource_spans:</p><p>return</p><p>project_name = client_id or self._default_project</p><p>_inject_resource_attribute(request, ResourceAttributes.PROJECT_NAME, project_name)</p><p># unchanged: single O(spans) pass building per-trace chunks + span-kind/resource-attr index</p><p>ctx = self._build_dispatch_context(request, client_id, space_id, space_type)</p><p>if self._blob:</p><p>self._blob.enqueue_all(ctx.trace_chunks) # unchanged, always runs, no rule check</p><p>for route in self._routes:</p><p># THE rule-based check — per trace-chunk, happens here and only here</p><p>matching = [c for c in ctx.trace_chunks if RuleEvaluator.evaluate(route.routing_rule, ctx, c)]</p><p>if not matching:</p><p>continue</p><p>creds = CredsResolver.resolve(route.creds_resolution, ctx)</p><p>if not creds:</p><p>logger.warning(“TraceDispatcher: no creds for route=%s, skipping”, route.name)</p><p>continue</p><p>await route.sink.submit(</p><p>[c.request for c in matching],</p><p>endpoint=creds[“endpoint”], headers=creds[“headers”],</p><p>trace_ids=[c.trace_id_hex for c in matching],</p><p>)</p><p>```</p><p><strong>**Confirming the boundary**</strong>: `ResilientBatchSink.submit()` receives only the already-`matching` chunks — no `routing_rule` field, no OpenInference knowledge anywhere inside it. `TraceSinkClient.send()` receives only a merged, already-decided `ExportTraceServiceRequest` — pure transport. Neither class has, or needs, any awareness that a rule exists.</p><p>For the 3 confirmed rows: `arize_primary` (`ALWAYS`) → `matching` = every chunk, identical to today. `arize_agent_forge` (`SPAN_ATTR_EXISTS` kind=`AGENT`) → `matching` = only trace-chunks that actually contain an agent span, exactly replicating today’s `_partition_request`’s `agent_tids` filtering. `cribl` (`ALL` of `SPACE_TYPE_EQUALS`+`CLIENT_ID_PREFIX`) → chunk-independent, so `matching` is either every chunk or none, matching today’s behavior.</p><p>This is the single mechanism that makes adding a destination purely additive — nothing inside `dispatch()` changes no matter how many routes are registered, and routing on a <em>*different*</em> OpenInference attribute/value needs a new DB row, not new code.</p><p><strong>### 5.4 Changes required for a brand-new endpoint</strong></p><p>1. <strong>**If it reuses existing condition/creds-resolution types**</strong> (e.g. another `SPAN_ATTR_EQUALS` rule, or a `STATIC` fixed-target sink): <strong>**zero code changes**</strong> — `POST /collector-endpoints` with its transport, TLS, headers, `routing_rule`, `creds_resolution`, `batch_config`. The registry picks it up via the CRUD handler’s immediate in-process refresh plus the other workers’ next poll (section 12.5).</p><p>2. <strong>**If it needs a genuinely new condition type or creds-resolution strategy**</strong> (not just a new value): implement one new function in `RuleEvaluator`/`CredsResolver`’s registry (section 12.3/12.4) — the only case that touches code.</p><p>3. <strong>**If it needs a transport neither generic client supports**</strong> (not plain OTLP grpc/http): implement one new `TraceSinkClient`, register it in `SinkClientFactory`.</p><p><strong>**Zero changes**</strong>, in every case, to `ResilientBatchSink`, the `dispatch()` loop body, retry/circuit-breaker/rate-limiter logic, or any existing sink/route.</p><p><strong>### 5.5 SOLID mapping</strong></p><p>| Principle | How it’s satisfied |</p><p>| — -| — -|</p><p>| <strong>**S**</strong>RP | `TraceSinkClient` impls only transmit bytes; `ResilientBatchSink` only batches/throttles/retries; `TraceDispatcher` only parses+mutates+routes; `SinkRoute`/DB row only decides “when + with what creds”; `CollectorEndpointRegistry` only keeps routes in sync with the DB |</p><p>| <strong>**O**</strong>CP | New destinations added via a new DB row; genuinely new condition/creds-resolution <em>*types*</em> via one new registered function; no existing class is modified |</p><p>| <strong>**L**</strong>SP | Any `TraceSinkClient` (`OtlpGrpcExporterClient`/`OtlpHttpExporterClient`, future) is fully substitutable wherever `ResilientBatchSink` expects one — identical `send`/`stats`/`close` contract |</p><p>| <strong>**I**</strong>SP | `TraceSinkClient` is minimal (3 methods); Cribl isn’t forced to implement auth-specific members it doesn’t need |</p><p>| <strong>**D**</strong>IP | `ResilientBatchSink` depends on the `TraceSinkClient` abstraction, never on `OtlpGrpcExporterClient`/`OtlpHttpExporterClient` concretely; `TraceDispatcher` depends on `SinkRoute`/`ResilientBatchSink` abstractions, never on transport or DB details |</p><p><strong>### 5.6 Design patterns used</strong></p><p>| Pattern | Where |</p><p>| — -| — -|</p><p>| Strategy | `TraceSinkClient` implementations (`OtlpGrpcExporterClient`/`OtlpHttpExporterClient`) — interchangeable “how to transmit” |</p><p>| Factory | `SinkClientFactory.build(row)` (transport selection from DB data); `SinkConfig.from_row(batch_config)` |</p><p>| Decorator/Facade | `ResilientBatchSink` wraps a `TraceSinkClient`, adding batching/resilience without changing the caller’s mental model |</p><p>| Circuit Breaker | explicit resilience pattern, one instance per sink |</p><p>| Rule table / Router | `SinkRoute` list (data-driven from `collector_endpoints`, section 12) evaluated per request — <strong>**all**</strong> matching routes fire (not “first match wins”), since a trace can legitimately go to multiple destinations at once |</p><p>| Interpreter (data-only) | `RuleEvaluator`/`CredsResolver` evaluate a closed JSON DSL (section 12.3/12.4) — never `eval()`’d code, by design |</p><p><strong>## 6. Multi-Process / Distributed Deployment</strong></p><p>`WORKER_COUNT=5` gunicorn workers per pod, N pod replicas — each worker process builds its own sink instances from the same DB rows (no shared in-memory state, consistent with today’s per-process channel/credential caches). Configured budgets (`rate_limit_qps`, `send_concurrency`, from each row’s `batch_config`) are <strong>**per-worker-process**</strong>; real aggregate ceiling to Arize = `value × WORKER_COUNT × replicas`. This is documented in the API/UI so operators don’t silently assume single-process when setting a value. How every process stays in sync with the DB (immediate in-process refresh + per-worker poll) is covered in section 12.5. No external/shared-state coordination (e.g. Redis) is introduced — not needed unless a hard global cap is required later.</p><p><strong>## 7. Observability</strong></p><p>`ResilientBatchSink.stats` — uniform fields for every destination, including future ones:</p><p>- `success` / `failure` counts</p><p>- current buffer depth (bytes + chunk count) per key</p><p>- `dropped_overflow` count</p><p>- circuit breaker state (`closed` / `open` / `half_open`)</p><p><strong>## 8. What Stays Unchanged</strong></p><p>- `BlobHandler` — untouched.</p><p>- `_partition_request`, `_build_trace_request`, protobuf attribute injection helpers — reused as the chunk source for every sink.</p><p>- Ingestion endpoint contract (`200 OK`, fire-and-forget, `MAX_CONCURRENT_DISPATCHES` semaphore).</p><p>- Cribl’s “single attempt, never retried, never blocks ingestion” philosophy — only gains batching + a concurrency ceiling it currently lacks entirely.</p><p><strong>## 9. New Dependencies</strong></p><p>- `tenacity` — exponential backoff + full jitter retry, replaces hand-rolled retry loops in all sinks.</p><p>- `aiolimiter` — async token-bucket rate limiting per destination.</p><p>- `obs_common` — reused for `authz`/`AuthEnum`/`fetch_user_entitlements` (platform-owner RBAC on the `collector-endpoints` admin API, section 12.11); not previously a dependency of `obs_telemetry_svcs`.</p><p>- `openinference-semantic-conventions` — reused for routing-rule attribute keys/values (section 12.4); already a dependency of sibling services, not yet of `obs_telemetry_svcs`.</p><p>- Circuit breaker — hand-rolled (~50 lines), no mature async-native library broadly adopted; not worth a new dependency.</p><p><strong>## 10. Validation Plan (pre-rollout)</strong></p><p>- Re-run the same Locust script/mix against the OBS endpoint with the new sinks enabled; compare drop % against the 50.47% baseline and the 1.09% direct-Arize baseline.</p><p>- Inject synthetic `RESOURCE_EXHAUSTED`/`UNAVAILABLE` failures to confirm circuit breaker opens/recovers and retry jitter de-synchronizes.</p><p>- Burst test: single request &gt; `max_batch_bytes` (oversized chunk path), and sustained overload (drop-oldest overflow path) — confirm bounded memory and non-blocking `submit()`.</p><p>- Confirm idle multi-tenant keys are evicted after TTL (no unbounded registry growth) over an extended soak test.</p><p><strong>## 11. Open Items</strong></p><p>- Confirm Arize’s actual max payload size with Arize team (currently assumed ~4MB default gRPC limit; using 3MB client-side cap for headroom).</p><p>- Final sign-off on `tenacity` / `aiolimiter` as new dependencies.</p><p><strong>## 12. Database-Backed Configuration, Table &amp; API Schema</strong></p><p>The `collector_endpoints` table, `CollectorEndpointRegistry`, and the generic `OtlpGrpcExporterClient`/`OtlpHttpExporterClient` referenced throughout sections 1–11 are defined here in full — there is no separate static/hardcoded version of this design; sections 1–11 already assume configuration lives in this table, not in code or environment variables.</p><p><strong>### 12.1 Two generic exporter clients replace the per-vendor classes</strong></p><p>`ArizeGrpcClient` / `ArizeHttpClient` / `CriblForwardClient` collapse into exactly two config-driven classes — both Arize and Cribl (and any future destination) speak OTLP, so one generic client per transport is sufficient:</p><p>```python</p><p>class OtlpGrpcExporterClient(TraceSinkClient):</p><p>def __init__(self, endpoint: str, tls_verify: bool,</p><p>tls_cert_bytes: Optional[bytes], headers: Dict[str, str]): …</p><p>class OtlpHttpExporterClient(TraceSinkClient):</p><p>def __init__(self, endpoint: str, tls_verify: bool,</p><p>tls_cert_bytes: Optional[bytes], headers: Dict[str, str]): …</p><p>```</p><p>Both still implement `TraceSinkClient` — `ResilientBatchSink`, circuit breaker, and retry wrap them exactly as before.</p><p><strong>### 12.2 Table — 3 initial rows (confirmed): `arize_primary`, `arize_agent_forge`, `cribl`</strong></p><p>```python</p><p>class CollectorEndpointTbl(Base, TimeStampMixin, UserActivityMixin):</p><p>__tablename__ = “collector_endpoints”</p><p>id = mapped_column(String(64), primary_key=True) # uuid string</p><p>name = mapped_column(String(100), unique=True, nullable=False)</p><p>transport_type = mapped_column(String(10), nullable=False) # ‘grpc’ | ‘http’</p><p>endpoint_url = mapped_column(Text, nullable=False)</p><p>tls_verify = mapped_column(Boolean, nullable=False, default=True)</p><p>tls_cert_blob_container = mapped_column(String(200))</p><p>tls_cert_blob_path = mapped_column(Text)</p><p>headers = mapped_column(JSONB, default=dict) # static, non-secret headers</p><p>creds = mapped_column(JSONB, default=dict) # static secrets (used only when creds_resolution.type == STATIC)</p><p>creds_resolution = mapped_column(JSONB, nullable=False) # see 12.3 — reconciles Arize’s dynamic per-tenant creds with this table</p><p>routing_rule = mapped_column(JSONB, nullable=False) # see 12.4 — OpenInference-based predicate DSL</p><p>batch_config = mapped_column(JSONB, default=dict) # max_batch_bytes, flush_interval, send_concurrency, rate_limit_qps, max_retry_attempts, circuit_fail_threshold, circuit_cooldown</p><p>status = mapped_column(String(20), nullable=False, default=”ACTIVE”) # ACTIVE | DISABLED</p><p>```</p><p><strong>### 12.3 Reconciling Arize’s per-tenant dynamic creds with one unified table</strong></p><p>Arize-primary/agent-forge resolve `endpoint`/`space_id`/`api_key` <strong>**per request**</strong> via the existing `CredentialProvider` → `ObsSpaceTbl` (multi-tenant — different clients route to different Arize spaces). Cribl (and any future fixed-target sink) uses one static, known destination. Both fit the same table via a `creds_resolution` descriptor, so there’s still only one registry/refresh mechanism:</p><p>```json</p><p>// arize_primary row</p><p>“creds_resolution”: {“type”: “SPACE_ID_LOOKUP”}</p><p>// arize_agent_forge row</p><p>“creds_resolution”: {“type”: “SPACE_NAME_LOOKUP”, “name”: “agent-forge”}</p><p>// cribl row (and any future fixed-target sink)</p><p>“creds_resolution”: {“type”: “STATIC”} // use this row’s own headers/creds columns directly</p><p>```</p><p>`SPACE_ID_LOOKUP`/`SPACE_NAME_LOOKUP` call the <strong>**existing, unchanged**</strong> `CredentialProvider.get_by_space_id()`/`get_by_space_name()` at submit-time; `STATIC` reads `row.headers`/`row.creds` directly. One registry, one refresh loop, no special-casing in `TraceDispatcher`.</p><p><strong>### 12.4 Routing rule DSL — grounded in real OpenInference semantic conventions, not ad-hoc strings</strong></p><p>Conditions are data-only (never `eval()`’d — see the RCE risk flagged in section 11/earlier). Attribute-based conditions reference the actual `openinference-semantic-conventions` package constants (already a dependency of `obs_otel_sdk` and `obs_eval_mgmt_svcs`, confirmed installed: `openinference.semconv.trace.SpanAttributes.OPENINFERENCE_SPAN_KIND = “openinference.span.kind”`, `openinference.semconv.resource.ResourceAttributes.PROJECT_NAME = “openinference.project.name”`, `OpenInferenceSpanKindValues.AGENT = “AGENT”`):</p><p>```json</p><p>{“type”: “SPAN_ATTR_EXISTS”, “key”: “openinference.span.kind”, “value”: “AGENT”}</p><p>{“type”: “SPAN_ATTR_EQUALS”, “key”: “openinference.span.kind”, “value”: “LLM”}</p><p>{“type”: “RESOURCE_ATTR_EQUALS”, “key”: “openinference.project.name”, “value”: “my-client”}</p><p>{“type”: “ALL”, “rules”: [ {“…”: “…”} ]}</p><p>{“type”: “ANY”, “rules”: [ {“…”: “…”} ]}</p><p>```</p><p>Request-metadata conditions (not part of OpenInference semconv — specific to this collector) stay as their own small family:</p><p>```json</p><p>{“type”: “ALWAYS”}</p><p>{“type”: “CLIENT_ID_PREFIX”, “prefix”: “rai-”}</p><p>{“type”: “SPACE_TYPE_EQUALS”, “value”: “platform”}</p><p>```</p><p>`arize_agent_forge`’s routing rule becomes `{“type”: “SPAN_ATTR_EXISTS”, “key”: “openinference.span.kind”, “value”: “AGENT”}` — generic by key+value, so routing on a <strong>**different**</strong> OpenInference attribute/value in the future needs zero new code, just a new JSON row.</p><p>Server-side validation (API layer, on create/update) checks `key` against the real package’s declared attributes and `value` (when the key is `SpanAttributes.OPENINFERENCE_SPAN_KIND`) against `OpenInferenceSpanKindValues` — catches typos before they silently become a no-op routing rule. `OPENINFERENCE_SPAN_KIND_KEY`/`OPENINFERENCE_PROJECT_NAME_KEY`/`AGENT_SPAN_KIND` string literals in `handlers_v2.py` are replaced with imports from `openinference.semconv.trace.SpanAttributes` / `openinference.semconv.resource.ResourceAttributes` / `OpenInferenceSpanKindValues` — add `openinference-semantic-conventions` to `obs_telemetry_svcs/requirements.txt` (already used elsewhere in this repo at `&gt;=0.1.5`/`==0.1.21`).</p><p><strong>### 12.5 Registry refresh — in-process refresh on write + per-worker poll (no Event Hub, no LISTEN/NOTIFY)</strong></p><p><strong>**The real constraint isn’t “the API and collector are in different services” — they’re the same service, but deployed as multiple separate OS processes.**</strong> `WORKER_COUNT=5` in this service’s own `Dockerfile` means gunicorn pre-forks 5 independent processes, each with its own memory, plus however many Kubernetes pod replicas run per environment. A CRUD write lands on exactly one of those processes; an in-process-only cache refresh fixes only that one process — every other worker/pod still holds the old routes until something else tells them. That is the one thing that genuinely needs solving here, nothing more.</p><p>Simplest correct fix, matching this codebase’s existing `ClientCache`/`SpaceCache` convention (TTL-based, lazy refresh, no push infrastructure) — <strong>**no Event Hub, no `asyncpg`, no Postgres LISTEN/NOTIFY**</strong>:</p><p>1. <strong>**Immediate in-process refresh**</strong>: the worker that handles the CRUD write refreshes its own registry synchronously, right there in the request handler — zero delay for that one process.</p><p>2. <strong>**Every worker independently polls**</strong> `collector_endpoints` on a short interval (default 30s, env-configurable via `COLLECTOR_ENDPOINT_POLL_INTERVAL` — same pattern as the existing `CLIENT_CACHE_TTL`/`SPACE_CACHE_TTL`), diffs by `modified_ts`, and rebuilds only the sinks that changed — this is what converges the <em>*other*</em> workers/pods that didn’t handle the write, within a bounded delay. No new dependency, no new Azure resource, no DB trigger.</p><p><strong>**Impact assessment (why 30s is safe)**</strong>: `collector_endpoints` is a tiny, fixed-size table (3 rows to start). At `WORKER_COUNT=5` × N pod replicas, even 10 replicas = 50 processes polling independently every 30s ≈ 1.7 queries/sec against Postgres — trivial next to this service’s existing `ClientCache`/`SpaceCache` DB traffic. This is a different caching shape than `ClientCache`/`SpaceCache`’s 2h TTL (those are large-cardinality, lazy-load-on-miss; this is small, fixed-size, and needs every row reflected, not just looked-up ones), so a much shorter interval here doesn’t imply changing those. The poll runs as its own background `asyncio` task — same category as the existing `BlobHandler` background thread / batch-flush ticker — fully decoupled from the `dispatch()` hot path, zero added latency to trace ingestion. Each worker’s poll timing gets a small random jitter (e.g. `30s + random(0, 5s)`) purely to avoid synchronized polling bursts in DB metrics, not because the query itself is expensive.</p><p>```python</p><p>class CollectorEndpointRegistry:</p><p>def __init__(self, poll_interval: float = 30.0): …</p><p>def refresh_now(self, endpoint_id: str) -&gt; None:</p><p># called synchronously from the CRUD handler right after commit —</p><p># immediate effect on this one worker process</p><p>self._apply_row(self._fetch_one(endpoint_id))</p><p>async def _poll_loop(self) -&gt; None:</p><p># every poll_interval (+ small random jitter), on every worker process independently:</p><p># SELECT * FROM collector_endpoints, diff by modified_ts against</p><p># the currently-active sinks in THIS process</p><p># unchanged -&gt; leave that sink, its TLS cert cache, and its buffer untouched</p><p># new/changed -&gt; SinkClientFactory.build(row) [re-downloads TLS cert only for THIS row] -&gt; new ResilientBatchSink -&gt; new SinkRoute</p><p># removed/disabled -&gt; mark draining (see 12.7)</p><p># malformed row (bad URL/cert) -&gt; log + skip, never blocks the rest</p><p># atomically swap: self._dispatcher.routes = new_list # list reassignment is atomic under the GIL</p><p>```</p><p>This matches “when the TLS loads it loads the existing data into cache and when the data is changed in the table the cache resets — only the sinks [that changed]”: the TLS cert cache is keyed <strong>**per endpoint id**</strong>, so a config change to Cribl never touches Arize-primary’s cached cert/channel, and vice versa. The worker that made the change sees it instantly; every other worker/pod converges within one poll interval.</p><p><strong>### 12.6 Test-connection flow (confirmed in scope)</strong></p><p>A synchronous, stateless validation endpoint — operates on the <strong>**draft**</strong> config (not yet saved), bypasses batching/circuit breaker/retry entirely for immediate UI feedback:</p><p>```python</p><p>@router.post(“/collector-endpoints/test-connection”)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def test_connection(request: CollectorEndpointDraft, …):</p><p># request: transport_type, endpoint_url, tls_verify, tls_cert (if tls_verify=True), headers</p><p>client = SinkClientFactory.build_transient(request) # throwaway client, not registered anywhere</p><p>mock_request = build_mock_otlp_trace() # single synthetic span, e.g. name=”obs-collector-connection-test”</p><p>try:</p><p>ok = await client.send(mock_request, endpoint=request.endpoint_url, headers=request.headers, label=”test”)</p><p>return {“success”: ok, “latency_ms”: …}</p><p>except Exception as e:</p><p>return {“success”: False, “error”: str(e)}</p><p>finally:</p><p>await client.close()</p><p>```</p><p>`build_mock_otlp_trace()` constructs a minimal `ExportTraceServiceRequest` (one resource span, one span) — sent as protobuf-over-gRPC or protobuf-over-HTTP depending on `transport_type`, matching whatever the real traffic would use, so the test faithfully exercises the exact code path (TLS handshake, cert validation, auth headers) the real sink will use once saved.</p><p><strong>### 12.7 Graceful drain on disable/delete (confirmed: finish buffer, then stop)</strong></p><p>Distinct from the already-agreed “buffer full → drop oldest” overflow policy. Example: an operator clicks “stop sending to Cribl” while Cribl’s `ResilientBatchSink` currently has unflushed spans buffered (not overflowing, just not yet due for its next scheduled flush). Confirmed behavior: mark the row inactive for <em>*new*</em> traffic immediately, but let the existing buffer’s next scheduled flush (bounded by its own `flush_interval`, e.g. ≤1s) complete before tearing down and calling `.close()`. No data loss from the stop action itself — a disable is therefore not instantaneous, bounded by at most one flush interval.</p><p><strong>### 12.8 Where secrets live (confirmed: JSONB in Postgres)</strong></p><p>New endpoint `creds` (for `STATIC` rows like Cribl) follow the existing `ObsSpaceTbl.space_creds` precedent — plaintext JSONB in the `collector_endpoints` table, consistent with how Arize space credentials are already stored today. No Key Vault indirection for this table.</p><p><strong>### 12.9 Table DDL &amp; ORM model</strong></p><p>`obs_telemetry_svcs` has its <strong>**own local**</strong> copy of `ObsClientTbl`/`ObsSpaceTbl` in `obs_telemetry_svcs/models/db_model.py` (plain `mapped_column`s, no mixins — distinct from the separate `obs_common` copy used by `obs_mgmt_svcs`). The new table follows that exact style, in the same file:</p><p>```python</p><p># obs_telemetry_svcs/models/db_model.py (addition)</p><p>class CollectorEndpointTbl(Base):</p><p>__tablename__ = “collector_endpoints”</p><p>id = mapped_column(String(64), primary_key=True) # uuid string</p><p>name = mapped_column(String(100), nullable=False, unique=True)</p><p>transport_type = mapped_column(String(10), nullable=False) # ‘grpc’ | ‘http’</p><p>endpoint_url = mapped_column(Text, nullable=False)</p><p>tls_verify = mapped_column(Boolean, nullable=False, default=True)</p><p>tls_cert_blob_container = mapped_column(String(200), nullable=True)</p><p>tls_cert_blob_path = mapped_column(Text, nullable=True)</p><p>headers = mapped_column(JSONB, default=dict) # static, non-secret headers</p><p>creds = mapped_column(JSONB, default=dict) # used only when creds_resolution.type == STATIC</p><p>creds_resolution = mapped_column(JSONB, nullable=False) # {“type”: “SPACE_ID_LOOKUP” | “SPACE_NAME_LOOKUP” | “STATIC”, …}</p><p>routing_rule = mapped_column(JSONB, nullable=False) # OpenInference-based predicate DSL, see 12.4</p><p>batch_config = mapped_column(JSONB, default=dict) # max_batch_bytes, flush_interval, send_concurrency, rate_limit_qps, max_retry_attempts, circuit_fail_threshold, circuit_cooldown</p><p>status = mapped_column(String(20), nullable=False, default=”ACTIVE”) # ACTIVE | DISABLED</p><p>created_by = mapped_column(String(64), nullable=False)</p><p>created_ts = mapped_column(DateTime, nullable=False)</p><p>modified_by = mapped_column(String(64))</p><p>modified_ts = mapped_column(DateTime)</p><p>def to_pydantic(self) -&gt; “CollectorEndpointResponse”:</p><p>return CollectorEndpointResponse(</p><p>id=self.id, name=self.name, transport_type=self.transport_type, endpoint_url=self.endpoint_url,</p><p>tls_verify=self.tls_verify, tls_cert_blob_container=self.tls_cert_blob_container,</p><p>tls_cert_blob_path=self.tls_cert_blob_path, headers=self.headers, creds_resolution=self.creds_resolution,</p><p>routing_rule=self.routing_rule, batch_config=self.batch_config, status=self.status,</p><p>created_by=self.created_by, created_ts=self.created_ts,</p><p>modified_by=self.modified_by, modified_ts=self.modified_ts,</p><p>) # note: `creds` deliberately omitted from the response — never echo secrets back over the API</p><p>```</p><p>Raw DDL, matching this repo’s `db_scripts/Release{N}/[ENV]/NN_description.sql` convention and `txteff.` schema prefix (placed in the next release folder, e.g. `Release7/DEV/01_create_collector_endpoints.sql`):</p><p>```sql</p><p>CREATE TABLE IF NOT EXISTS txteff.collector_endpoints</p><p>(</p><p>id character varying(64) NOT NULL,</p><p>name character varying(100) NOT NULL,</p><p>transport_type character varying(10) NOT NULL,</p><p>endpoint_url text NOT NULL,</p><p>tls_verify boolean NOT NULL DEFAULT true,</p><p>tls_cert_blob_container character varying(200),</p><p>tls_cert_blob_path text,</p><p>headers jsonb DEFAULT ‘{}’::jsonb,</p><p>creds jsonb DEFAULT ‘{}’::jsonb,</p><p>creds_resolution jsonb NOT NULL,</p><p>routing_rule jsonb NOT NULL,</p><p>batch_config jsonb DEFAULT ‘{}’::jsonb,</p><p>status character varying(20) NOT NULL DEFAULT ‘ACTIVE’,</p><p>created_by character varying(64) NOT NULL,</p><p>created_ts timestamp without time zone NOT NULL DEFAULT now(),</p><p>modified_by character varying(64),</p><p>modified_ts timestamp without time zone,</p><p>CONSTRAINT collector_endpoints_pkey PRIMARY KEY (id),</p><p>CONSTRAINT collector_endpoints_name_key UNIQUE (name),</p><p>CONSTRAINT collector_endpoints_transport_type_check CHECK (transport_type IN (‘grpc’, ‘http’)),</p><p>CONSTRAINT collector_endpoints_status_check CHECK (status IN (‘ACTIVE’, ‘DISABLED’))</p><p>);</p><p>— seed the 3 confirmed initial rows</p><p>INSERT INTO txteff.collector_endpoints</p><p>(id, name, transport_type, endpoint_url, tls_verify, creds_resolution, routing_rule, status, created_by, created_ts)</p><p>VALUES</p><p>(gen_random_uuid()::text, ‘arize_primary’, ‘grpc’, ‘&lt;resolved per-request&gt;’, true, ‘{“type”:”SPACE_ID_LOOKUP”}’, ‘{“type”:”ALWAYS”}’, ‘ACTIVE’, ‘system’, now()),</p><p>(gen_random_uuid()::text, ‘arize_agent_forge’, ‘grpc’, ‘&lt;resolved per-request&gt;’, true, ‘{“type”:”SPACE_NAME_LOOKUP”,”name”:”agent-forge”}’, ‘{“type”:”SPAN_ATTR_EXISTS”,”key”:”openinference.span.kind”,”value”:”AGENT”}’, ‘ACTIVE’, ‘system’, now()),</p><p>(gen_random_uuid()::text, ‘cribl’, ‘grpc’, ‘&lt;cribl collector url&gt;’, true, ‘{“type”:”STATIC”}’, ‘{“type”:”ALL”,”rules”:[{“type”:”SPACE_TYPE_EQUALS”,”value”:”platform”},{“type”:”CLIENT_ID_PREFIX”,”prefix”:”rai-”}]}’, ‘ACTIVE’, ‘system’, now());</p><p>```</p><p>Note `arize_primary`/`arize_agent_forge` don’t have a real static `endpoint_url` (their endpoint is resolved per-request via `creds_resolution`) — stored as a placeholder string for row completeness; the registry ignores `endpoint_url` entirely when `creds_resolution.type` is `SPACE_ID_LOOKUP`/`SPACE_NAME_LOOKUP`.</p><p><strong>### 12.10 Pydantic request/response schemas</strong></p><p>Matching this service’s own `models/schemas.py` convention exactly (`CamelCaseConfig` with `to_camel` alias generator, `from_attributes=True`, snake_case field names on the Python side, camelCase over the wire):</p><p>```python</p><p># obs_telemetry_svcs/models/schemas.py (addition)</p><p>from typing import Literal, Optional, Dict, Any</p><p>from pydantic import BaseModel, Field</p><p>class CollectorEndpointCreate(BaseModel):</p><p>name: str = Field(…, min_length=1, max_length=100, description=”Unique destination name”)</p><p>transport_type: Literal[“grpc”, “http”] = Field(…, description=”Wire protocol”)</p><p>endpoint_url: str = Field(…, description=”Destination URL (ignored when creds_resolution is a lookup type)”)</p><p>tls_verify: bool = Field(True, description=”Verify TLS; if true, a cert must be supplied”)</p><p>tls_cert_blob_container: Optional[str] = Field(None, description=”Blob container for the TLS cert, required if tls_verify=true and no system CA”)</p><p>tls_cert_blob_path: Optional[str] = Field(None, description=”Blob path to the PEM cert”)</p><p>headers: Optional[Dict[str, str]] = Field(default_factory=dict, description=”Static, non-secret headers”)</p><p>creds: Optional[Dict[str, Any]] = Field(default_factory=dict, description=”Secrets, used only when creds_resolution.type == STATIC”)</p><p>creds_resolution: Dict[str, Any] = Field(…, description=’{“type”: “SPACE_ID_LOOKUP”|”SPACE_NAME_LOOKUP”|”STATIC”, …}’)</p><p>routing_rule: Dict[str, Any] = Field(…, description=”OpenInference-based predicate DSL, see section 12.4&quot;)</p><p>batch_config: Optional[Dict[str, Any]] = Field(default_factory=dict, description=”max_batch_bytes, flush_interval, send_concurrency, rate_limit_qps, max_retry_attempts, circuit_fail_threshold, circuit_cooldown”)</p><p>class Config(CamelCaseConfig):</p><p>from_attributes = True</p><p>class CollectorEndpointUpdate(BaseModel):</p><p>transport_type: Optional[Literal[“grpc”, “http”]] = None</p><p>endpoint_url: Optional[str] = None</p><p>tls_verify: Optional[bool] = None</p><p>tls_cert_blob_container: Optional[str] = None</p><p>tls_cert_blob_path: Optional[str] = None</p><p>headers: Optional[Dict[str, str]] = None</p><p>creds: Optional[Dict[str, Any]] = None</p><p>creds_resolution: Optional[Dict[str, Any]] = None</p><p>routing_rule: Optional[Dict[str, Any]] = None</p><p>batch_config: Optional[Dict[str, Any]] = None</p><p>class Config(CamelCaseConfig):</p><p>from_attributes = True</p><p>class CollectorEndpointStatusUpdate(BaseModel):</p><p>status: Literal[“ACTIVE”, “DISABLED”] = Field(…, description=”Set to DISABLED to gracefully drain and stop (section 12.7)”)</p><p>class CollectorEndpointResponse(BaseModel):</p><p>id: str</p><p>name: str</p><p>transport_type: Literal[“grpc”, “http”]</p><p>endpoint_url: str</p><p>tls_verify: bool</p><p>tls_cert_blob_container: Optional[str] = None</p><p>tls_cert_blob_path: Optional[str] = None</p><p>headers: Dict[str, str] = {}</p><p># `creds` intentionally excluded — secrets are never echoed back over the API</p><p>creds_resolution: Dict[str, Any]</p><p>routing_rule: Dict[str, Any]</p><p>batch_config: Dict[str, Any] = {}</p><p>status: Literal[“ACTIVE”, “DISABLED”]</p><p>created_by: str</p><p>created_ts: datetime</p><p>modified_by: Optional[str] = None</p><p>modified_ts: Optional[datetime] = None</p><p>class Config(CamelCaseConfig):</p><p>from_attributes = True</p><p>class CollectorEndpointTestConnectionRequest(BaseModel):</p><p>“””Draft config, not yet saved — used only by POST /collector-endpoints/test-connection (section 12.6).”””</p><p>transport_type: Literal[“grpc”, “http”]</p><p>endpoint_url: str</p><p>tls_verify: bool = True</p><p>tls_cert_pem: Optional[str] = Field(None, description=”Raw PEM content for the test call only, not persisted”)</p><p>headers: Optional[Dict[str, str]] = Field(default_factory=dict)</p><p>class Config(CamelCaseConfig):</p><p>from_attributes = True</p><p>class CollectorEndpointTestConnectionResponse(BaseModel):</p><p>success: bool</p><p>latency_ms: Optional[float] = None</p><p>error: Optional[str] = None</p><p>```</p><p><strong>### 12.11 API router</strong></p><p>`obs_telemetry_svcs` has no existing human/platform-owner RBAC today — its current APIs (`otel_telemetry.py`, `v3_export.py`) use machine client-id/client-key auth (`validate_client_auth_for_traces` in `services/key_mgmt_util.py`), which is the wrong tool for an admin surface that controls where all trace data is forwarded. The only proper RBAC mechanism in this monorepo is `obs_common.auth.auth_svc.authz` + `AuthEnum` + `fetch_user_entitlements` (used today by `obs_mgmt_svcs`). Since you’ve confirmed these APIs live in `obs_telemetry_svcs` itself, this means <strong>**adding `obs_common` as a new dependency**</strong> to this service — flagging this explicitly since it’s a new cross-package dependency, not previously present.</p><p>```python</p><p># obs_telemetry_svcs/api/collector_endpoints.py</p><p>from fastapi import APIRouter, Depends</p><p>from obs_common.auth.auth_svc import authz, fetch_user_entitlements</p><p>from obs_common.schemas.enums import AuthEnum</p><p>from obs_common.schemas.user_model import UserModel</p><p>from obs_telemetry_svcs.models.schemas import (</p><p>CollectorEndpointCreate, CollectorEndpointUpdate, CollectorEndpointStatusUpdate,</p><p>CollectorEndpointResponse, CollectorEndpointTestConnectionRequest, CollectorEndpointTestConnectionResponse,</p><p>)</p><p>from obs_telemetry_svcs.services.collector_endpoint_service import CollectorEndpointService</p><p>collector_endpoints = APIRouter(tags=[“Collector Endpoint Management APIs”])</p><p>@collector_endpoints.get(“/collector-endpoints”, response_model=list[CollectorEndpointResponse])</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def list_endpoints(user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>return CollectorEndpointService(user_model).list_endpoints()</p><p>@collector_endpoints.post(“/collector-endpoints”, response_model=CollectorEndpointResponse, status_code=201)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def create_endpoint(request: CollectorEndpointCreate, user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>response = CollectorEndpointService(user_model).create_endpoint(request)</p><p>registry.refresh_now(response.id) # immediate effect on this worker, section 12.5</p><p>return response</p><p>@collector_endpoints.put(“/collector-endpoints/{endpoint_id}”, response_model=CollectorEndpointResponse)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def update_endpoint(endpoint_id: str, request: CollectorEndpointUpdate, user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>response = CollectorEndpointService(user_model).update_endpoint(endpoint_id, request)</p><p>registry.refresh_now(endpoint_id)</p><p>return response</p><p>@collector_endpoints.patch(“/collector-endpoints/{endpoint_id}/status”, response_model=CollectorEndpointResponse)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def set_endpoint_status(endpoint_id: str, request: CollectorEndpointStatusUpdate, user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>response = CollectorEndpointService(user_model).set_status(endpoint_id, request.status)</p><p>registry.refresh_now(endpoint_id) # DISABLED -&gt; triggers graceful drain (12.7) on this worker; others converge within one poll</p><p>return response</p><p>@collector_endpoints.delete(“/collector-endpoints/{endpoint_id}”, status_code=204)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def delete_endpoint(endpoint_id: str, user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>CollectorEndpointService(user_model).delete_endpoint(endpoint_id)</p><p>registry.refresh_now(endpoint_id) # same graceful drain path as disable</p><p>return None</p><p>@collector_endpoints.post(“/collector-endpoints/test-connection”, response_model=CollectorEndpointTestConnectionResponse)</p><p>@authz(auth_grp=[AuthEnum.IS_PLATFORMOWNER])</p><p>async def test_connection(request: CollectorEndpointTestConnectionRequest, user_model: UserModel = Depends(fetch_user_entitlements)):</p><p>return await CollectorEndpointService(user_model).test_connection(request) # transient client, section 12.6 — never touches the registry</p><p>```</p><p>Every mutating endpoint calls `registry.refresh_now(endpoint_id)` right after the Postgres commit — this is the “immediate effect on this worker” half of section 12.5; the periodic poll (every 30s + jitter) on every <em>*other*</em> worker/pod is what converges the rest.</p><p><strong>### 12.12 End-to-end flow</strong></p><p>```mermaid</p><p>sequenceDiagram</p><p>participant UI</p><p>participant API as Collector Endpoint API (worker A)</p><p>participant PG as Postgres (collector_endpoints)</p><p>participant RegA as Registry (worker A, in-process)</p><p>participant RegB as Registry (worker B / other pod)</p><p>participant Dispatch as TraceDispatcher</p><p>UI-&gt;&gt;API: POST /collector-endpoints (new Cribl-like sink)</p><p>API-&gt;&gt;PG: INSERT … RETURNING id</p><p>PG →&gt;API: row committed</p><p>API-&gt;&gt;RegA: refresh_now(id)</p><p>RegA-&gt;&gt;PG: SELECT this one row</p><p>RegA-&gt;&gt;RegA: SinkClientFactory.build(row) -&gt; ResilientBatchSink -&gt; SinkRoute</p><p>RegA-&gt;&gt;Dispatch: atomically swap routes list (worker A only)</p><p>Note over RegB: worker B / other pod still on old routes</p><p>loop every 30s + jitter</p><p>RegB-&gt;&gt;PG: SELECT * FROM collector_endpoints</p><p>RegB-&gt;&gt;RegB: diff by modified_ts — this row is new</p><p>RegB-&gt;&gt;RegB: SinkClientFactory.build(row) -&gt; ResilientBatchSink -&gt; SinkRoute</p><p>RegB-&gt;&gt;Dispatch: atomically swap routes list (worker B)</p><p>end</p><p>Note over Dispatch: all workers now route matching traffic to the new sink</p><p>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnH8fC-mgDlRKYIgB-K73A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Jj1EDibgG-2TKaFZZvQ5w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9892354ca894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parsing and Chunking]]></title>
            <link>https://medium.com/@forswayamnptelcourse/parsing-and-chunking-bfb84bcafd6f?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb84bcafd6f</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 16:09:52 GMT</pubDate>
            <atom:updated>2026-09-05T16:09:52.800Z</atom:updated>
            <content:encoded><![CDATA[<p>At query time:</p><p>User question</p><p>-&gt; Query embedding</p><p>-&gt; Retrieve top candidate chunks</p><p>-&gt; Optional filtering / hybrid search / reranking</p><p>-&gt; Prompt construction</p><p>-&gt; LLM generation</p><h3>1. What Is Parsing?</h3><h3>Interview Answer</h3><blockquote><em>“Parsing is the process of extracting usable text, tables, images, metadata, or structure from a source file. A PDF, Excel workbook, email, or PowerPoint file cannot be embedded directly in its raw binary form, so we first convert it into a normalized representation that the chunking layer can process.”</em></blockquote><p>For example:</p><p>PDF binary file</p><p>-&gt; extracted text with page information</p><p>Excel file</p><p>-&gt; dictionary of sheet names and DataFrames</p><p>CSV file</p><p>-&gt; cleaned DataFrame</p><p>PPTX file</p><p>-&gt; slide text, tables, charts, and image descriptions</p><p>Email file</p><p>-&gt; sender, recipient, subject, body, and attachments</p><p>The parser is responsible for understanding the document format. The chunker is responsible for deciding how to divide the parsed content.</p><h3>Parser Versus Chunker</h3><p>Component Responsibility Parser Understands the file format and extracts content Chunker Divides extracted content into searchable units Metadata enrichment Adds source, document, page, sheet, and business metadata Embedding Converts each chunk into a vector</p><p>A parser answers:</p><blockquote><em>“What content is inside this file?”</em></blockquote><p>A chunker answers:</p><blockquote><em>“How should that content be divided for retrieval?”</em></blockquote><h3>2. Parser Strategies in This Repository</h3><p>The platform uses IngestionHelper.create_parser() to select a parser from the configured ingestion strategy.</p><h3>Q1. What does the PDF parser do?</h3><p>The PyPDFParser uses PyPDF2.PdfReader, iterates through the pages, and concatenates extracted text.</p><p>Conceptually:</p><p>reader = PdfReader(input)</p><p>for page in reader.pages:</p><p>text += page.extract_text()</p><h3>Best for</h3><ul><li>Text-based PDFs.</li><li>Simple reports.</li><li>PDFs where exact page-level structure is not essential.</li></ul><h3>Limitations</h3><ul><li>It may not extract text from scanned PDFs.</li><li>It may lose layout.</li><li>Tables may become poorly structured text.</li><li>Page numbers are not automatically preserved in this parser’s returned string.</li></ul><h3>Interview answer</h3><blockquote><em>“For ordinary text-based PDFs, we use the PyPDF parser because it is relatively fast and simple. For scanned or layout-heavy PDFs, we use the Form Recognizer or multimodal path because standard PDF text extraction may not recover the actual content or document structure.”</em></blockquote><h3>Q2. What does Azure Form Recognizer parsing do?</h3><p>The AFRParser calls the shared afr_service, waits for the analysis result, converts it to a dictionary, and cleans the returned content.</p><p>It is intended to preserve more document structure than basic PDF extraction.</p><h3>Best for</h3><ul><li>Scanned PDFs.</li><li>OCR.</li><li>Tables.</li><li>Documents with complex layout.</li><li>Documents where page or figure structure matters.</li></ul><h3>Tradeoff</h3><p>Benefit Cost Better layout and OCR External service latency Better table and figure handling Service cost and quotas Better scanned-document support Possible timeout or dependency failure</p><h3>Interview answer</h3><blockquote><em>“We selected Form Recognizer when document structure mattered, particularly for scanned documents, tables, and figures. The tradeoff was additional latency and dependency on an external document-intelligence service.”</em></blockquote><h3>Q3. What does the CSV parser do?</h3><p>The CsvParser:</p><ol><li>Reads the file bytes.</li><li>Uses chardet to detect encoding.</li><li>Tries detected encoding and fallback encodings.</li><li>Uses Pandas to read the CSV.</li><li>Cleans the resulting DataFrame.</li></ol><p>The fallback encodings include UTF-8, Latin-1, and Windows-1252.</p><h3>Why is encoding detection important?</h3><p>CSV files may be created by different systems and may not use UTF-8. Without fallback handling, a valid file could fail because of a UnicodeDecodeError.</p><h3>Cleaning performed</h3><p>The parser:</p><ul><li>Replaces null values with empty strings.</li><li>Removes Unnamed columns.</li><li>Normalizes column names.</li><li>Replaces spaces with underscores.</li><li>Removes unsupported characters.</li></ul><h3>Interview answer</h3><blockquote><em>“For CSV ingestion, we parse into a DataFrame rather than plain text because the tabular structure is valuable. We also normalize encoding and column names so downstream chunking and structured retrieval are more predictable.”</em></blockquote><h3>Q4. What does the Excel parser do?</h3><p>The ExcelParser reads all worksheets into a dictionary:</p><p>{</p><p>“Sheet1”: DataFrame,</p><p>“Sheet2”: DataFrame</p><p>}</p><p>It skips blank sheets and cleans each valid sheet.</p><p>If every sheet is empty, it raises a NoDataException.</p><h3>Why preserve sheet names?</h3><p>The sheet name is useful for:</p><ul><li>Citations.</li><li>Filtering.</li><li>Debugging.</li><li>Telling the LLM where a value came from.</li></ul><p>The Excel chunkers attach sheet_name to chunk metadata.</p><h3>Q5. What does the URL parser do?</h3><p>The URLParser:</p><ol><li>Sends an HTTP request.</li><li>Parses the response with BeautifulSoup.</li><li>Removes HTML structure.</li><li>Returns visible text.</li></ol><h3>Limitations to mention</h3><p>The implementation is a relatively simple HTML text extractor. It does not, by itself, guarantee:</p><ul><li>JavaScript-rendered content.</li><li>Web crawling.</li><li>Robots-policy handling.</li><li>Authentication to protected pages.</li><li>Website change tracking.</li></ul><h3>Q6. What does the text parser do?</h3><p>The TxtParser:</p><ol><li>Reads bytes.</li><li>Detects encoding using chardet.</li><li>Decodes the bytes.</li><li>Returns a string.</li></ol><p>This is necessary because text files can use different encodings.</p><h3>Q7. What does the Markdown parser do?</h3><p>The MdParser decodes Markdown as UTF-8 and returns the Markdown text.</p><p>The Markdown structure is then useful to the recursive or paragraph chunker because headings and paragraph boundaries can be preserved.</p><h3>Q8. What does the multimodal parser do?</h3><p>The MultimodalParser handles PDFs, images, and PowerPoint files using document intelligence and a multimodal RAI model.</p><p>It can:</p><ul><li>Extract text.</li><li>Extract figures.</li><li>Save figure images.</li><li>Generate image descriptions.</li><li>Extract slide text.</li><li>Extract PowerPoint tables and charts.</li><li>Add image descriptions to the content.</li></ul><h3>Interview answer</h3><blockquote><em>“For multimodal documents, text-only parsing is insufficient. The parser extracts textual content and sends images or figures to a multimodal model to produce descriptions. Those descriptions are then included in the searchable content so a question about an image or chart can retrieve it.”</em></blockquote><h3>Q9. What about audio and video?</h3><p>The repository contains AudioParser and VideoParser classes, but their inspected execute() methods are placeholders with pass.</p><p>So the accurate interview answer is:</p><blockquote><em>“The platform defines extension points for audio and video parsing, but in this repository version the implementations are not complete. The intended design would transcribe audio or video first and then apply normal text chunking.”</em></blockquote><p>Do not say that full audio/video ingestion is implemented unless you confirm another implementation path in the deployed version.</p><h3>Q10. What does email parsing do?</h3><p>The EmailParser handles .msg files using extract_msg. It preserves email boundaries using start and end tags so the email chunker does not split individual messages incorrectly.</p><p>This is useful for:</p><ul><li>Email threads.</li><li>Support cases.</li><li>Mailbox exports.</li><li>Historical communication archives.</li></ul><h3>3. Why Parsing Quality Matters</h3><p>If parsing is wrong, chunking and retrieval are wrong even if the embedding model is excellent.</p><p>Examples:</p><p>Bad PDF extraction</p><p>-&gt; missing table values</p><p>-&gt; wrong answer</p><p>Bad Excel parsing</p><p>-&gt; lost column names</p><p>-&gt; unclear chunk meaning</p><p>Bad OCR</p><p>-&gt; incorrect numbers</p><p>-&gt; incorrect retrieval</p><p>Bad email parsing</p><p>-&gt; broken thread boundaries</p><p>-&gt; unrelated messages merged</p><p>A strong interview sentence is:</p><blockquote><em>“RAG quality starts before embeddings. If parsing loses the content or structure, the retriever cannot recover it later.”</em></blockquote><h3>4. What Is Chunking?</h3><h3>Interview Answer</h3><blockquote><em>“Chunking divides parsed content into smaller units that can be embedded and retrieved independently. A full document is usually too large and too broad to send to the embedding model or LLM, so we create chunks that are small enough for processing but large enough to retain meaning.”</em></blockquote><p>A chunk should ideally contain:</p><ul><li>A complete idea.</li><li>Enough surrounding context.</li><li>Useful metadata.</li><li>A manageable number of tokens.</li><li>A meaningful citation boundary.</li></ul><h3>Why Not Embed the Whole Document?</h3><p>Embedding entire documents creates several problems:</p><ul><li>The embedding represents too many unrelated topics.</li><li>Retrieval becomes less precise.</li><li>Long documents may exceed model limits.</li><li>The LLM receives too much irrelevant context.</li><li>Citations become too broad.</li><li>Cost and latency increase.</li></ul><h3>Why Not Make Chunks Extremely Small?</h3><p>Very small chunks can:</p><ul><li>Lose context.</li><li>Separate a question from its answer.</li><li>Make pronouns ambiguous.</li><li>Increase the number of vectors.</li><li>Increase database size.</li><li>Require more retrieval results to reconstruct meaning.</li></ul><h3>5. Chunking Strategies in This Repository</h3><h3>Q11. What is recursive character chunking?</h3><p>RecursiveCharacterTextChunking uses LangChain’s RecursiveCharacterTextSplitter.</p><p>It attempts to split text using meaningful separators rather than cutting arbitrarily. If the language is Markdown, it obtains Markdown-specific separators.</p><p>It uses:</p><ul><li>min_chunk_size as the configured chunk size.</li><li>chunk_overlap.</li><li>Language-aware separators for Markdown.</li></ul><h3>Good for</h3><ul><li>Plain text.</li><li>Markdown.</li><li>General prose.</li><li>Documents without highly specialized structure.</li></ul><h3>Interview answer</h3><blockquote><em>“Recursive splitting is a strong general-purpose strategy. It tries larger semantic boundaries first, such as paragraphs or lines, and falls back to smaller separators when necessary. For Markdown, it uses language-aware separators so headings and structure are better preserved.”</em></blockquote><h3>Q12. What is character splitting?</h3><p>CharacterTextChunking uses a configured separator, represented in the schema by sentence_split_regex.</p><p>It is simpler than recursive splitting.</p><h3>Good for</h3><ul><li>Highly regular text.</li><li>Simple documents.</li><li>Cases where a known delimiter is reliable.</li></ul><h3>Limitation</h3><p>It can produce poor chunks if the chosen separator does not reflect document structure.</p><h3>Q13. What is semantic chunking?</h3><p>SemanticChunking uses embeddings to identify semantic boundaries.</p><p>The process is approximately:</p><ol><li>Split the input into sentences.</li><li>Create embeddings for sentence groups.</li><li>Compare semantic similarity.</li><li>Identify meaningful changes.</li><li>Break the document at those boundaries.</li><li>Enforce minimum chunk size.</li></ol><h3>Good for</h3><ul><li>Long prose.</li><li>Reports.</li><li>Policy documents.</li><li>Documents where paragraph boundaries are unreliable.</li></ul><h3>Tradeoff</h3><p>Semantic chunking uses embedding calls during ingestion, so it increases:</p><ul><li>Ingestion latency.</li><li>Model usage.</li><li>Cost.</li><li>Dependency on the embedding service.</li></ul><h3>Q14. What does buffer_size mean in semantic chunking?</h3><p>buffer_size controls how many neighboring sentences are considered together when calculating semantic relationships.</p><p>A larger buffer can make the semantic boundary decision more stable, but it may blur boundaries between separate topics.</p><p>A smaller buffer is more sensitive to local changes but can over-split.</p><p>The schema default is:</p><p>buffer_size = 1</p><h3>Q15. What is breakpoint_threshold_type?</h3><p>This tells the semantic splitter how to decide that a semantic break is significant.</p><p>The schema default is:</p><p>breakpoint_threshold_type = “percentile”</p><p>Conceptually:</p><ul><li>A threshold that is too sensitive creates too many small chunks.</li><li>A threshold that is too loose creates large mixed-topic chunks.</li></ul><h3>Q16. What is min_chunk_size?</h3><p>min_chunk_size prevents chunks from becoming too small.</p><p>In the schema:</p><p>minimum = 1000</p><p>maximum = 8000</p><p>default = 1000</p><p>In recursive chunking, the code passes it as the splitter’s chunk_size.</p><h3>Effect of increasing it</h3><ul><li>Fewer chunks.</li><li>More context per chunk.</li><li>Lower vector count.</li><li>Potentially lower retrieval precision.</li><li>More tokens passed to the LLM.</li></ul><h3>Effect of decreasing it</h3><ul><li>More focused chunks.</li><li>More vectors.</li><li>Potentially better precision.</li><li>Greater risk of lost context.</li><li>More database and embedding cost.</li></ul><p>Important repository nuance:</p><blockquote><em>The name is </em><em>min_chunk_size, but in </em><em>RecursiveCharacterTextChunking it is directly passed as </em><em>chunk_size. In table-aware and paragraph chunkers, it behaves more like a minimum-size constraint.</em></blockquote><h3>Q17. What is max_chunk_size?</h3><p>max_chunk_size prevents a chunk from becoming too large.</p><p>The schema defines:</p><p>minimum = 2000</p><p>maximum = 10000</p><p>default = 8000</p><p>It is used by:</p><ul><li>Table-aware chunking.</li><li>Page-number chunking.</li><li>Paragraph chunking.</li></ul><p>If adding another paragraph would exceed the maximum, the chunker finalizes the current chunk.</p><h3>Q18. What is chunk_overlap?</h3><p>Chunk overlap repeats part of one chunk in the following chunk.</p><p>Example without overlap:</p><p>Chunk 1: The trade process starts with validation…</p><p>Chunk 2: Settlement occurs after confirmation…</p><p>Example with overlap:</p><p>Chunk 1: The trade process starts with validation…</p><p>Chunk 2: …starts with validation. Settlement occurs after confirmation…</p><p>The schema range is:</p><p>minimum = 400</p><p>maximum = 1000</p><p>default = 500</p><h3>Why use overlap?</h3><p>Overlap prevents important context from being lost at chunk boundaries.</p><h3>Too little overlap</h3><ul><li>A sentence may be separated from its explanation.</li><li>Follow-up references may become unclear.</li><li>Retrieval may return incomplete information.</li></ul><h3>Too much overlap</h3><ul><li>Duplicate content in search results.</li><li>More storage.</li><li>More embedding cost.</li><li>More redundant prompt context.</li><li>More chance of exceeding the LLM context window.</li></ul><h3>Q19. What is paragraph chunking?</h3><p>ParagraphChunking:</p><ol><li>Splits content into sections based on Markdown-style headings.</li><li>Separates tables from normal paragraphs.</li><li>Groups paragraphs until the maximum size.</li><li>Ensures chunks reach an appropriate minimum size.</li><li>Keeps tables as separate chunks.</li></ol><h3>Good for</h3><ul><li>Reports.</li><li>Markdown documentation.</li><li>Policy documents.</li><li>Heading-based business documents.</li></ul><h3>Q20. What is table-aware chunking?</h3><p>TableAwareChunker treats &lt;table&gt;...&lt;/table&gt; blocks specially.</p><p>It:</p><ul><li>Splits regular sections by paragraphs.</li><li>Keeps table blocks intact.</li><li>Combines small neighboring sections.</li><li>Applies overlap only to normal text.</li><li>Avoids merging tables into unrelated text.</li></ul><h3>Why is this important?</h3><p>Splitting a table arbitrarily can destroy:</p><ul><li>Column-to-value relationships.</li><li>Headers.</li><li>Row meaning.</li><li>Financial or operational data relationships.</li></ul><p>Interview answer:</p><blockquote><em>“Tables need special handling because normal text splitting can separate headers from rows or mix unrelated cells. Our table-aware chunker preserves table blocks and applies overlap only to surrounding prose.”</em></blockquote><h3>Q21. What is page-number chunking?</h3><p>PageNumberChunker applies table-aware chunking separately to each page and attaches:</p><p>metadata={“page_number”: page_number}</p><p>This supports source citations such as:</p><p>policy.pdf, Page 4</p><p>It also prevents overlap from crossing page boundaries.</p><h3>Q22. What is CSV row chunking?</h3><p>CsvRowChunking creates one chunk per CSV row.</p><p>Example:</p><p>Customer_ID: 101, Status: Active, Region: US</p><p>Customer_ID: 102, Status: Closed, Region: UK</p><h3>Good for</h3><ul><li>Row-level lookup.</li><li>Small records.</li><li>Questions asking about a specific entity.</li></ul><h3>Limitation</h3><p>If a question requires patterns across many rows, individual-row chunks may not provide enough context.</p><h3>Q23. What is grouped CSV chunking?</h3><p>CsvChunking groups a configured number of rows and converts the group to Markdown.</p><p>The configuration is:</p><p>num_of_records_per_chunk</p><p>default = 100</p><p>minimum = 10</p><p>maximum = 100</p><h3>Why group rows?</h3><p>A group gives the model more context and is better for:</p><ul><li>Comparing records.</li><li>Understanding table structure.</li><li>Questions involving multiple rows.</li></ul><h3>Tradeoff</h3><p>Larger groups improve context but reduce retrieval precision and create larger chunks.</p><h3>Q24. What is Excel row chunking?</h3><p>ExcelRowChunking creates one chunk per row and attaches the worksheet name as metadata.</p><h3>Good for</h3><ul><li>Entity-level lookups.</li><li>Specific row retrieval.</li><li>Spreadsheet records where each row is an independent item.</li></ul><h3>Q25. What is grouped Excel chunking?</h3><p>ExcelChunking groups rows within each worksheet and converts each group to Markdown. It retains:</p><p>metadata = {“sheet_name”: sheet_name}</p><p>This is useful when questions require multiple rows from the same sheet.</p><h3>Q26. What is PowerPoint chunking?</h3><p>The multimodal parser creates slide-separated content using a slide delimiter. PowerPointChunking splits on that delimiter and creates one chunk per slide.</p><h3>Why one slide per chunk?</h3><p>A slide usually represents one presentation idea. It also makes citations and debugging easier.</p><p>PowerPoint parsing can include:</p><ul><li>Text.</li><li>Tables.</li><li>Charts.</li><li>Image descriptions.</li></ul><h3>Q27. What is email chunking?</h3><p>EmailChunking identifies complete emails using start and end tags and distributes complete messages into a configured number of chunks.</p><p>It deliberately avoids breaking an individual email.</p><p>The chunk metadata includes:</p><ul><li>Chunk index.</li><li>Total number of emails.</li><li>Number of emails in the chunk.</li></ul><h3>Why not split emails by character count?</h3><p>Splitting an email can separate:</p><ul><li>Subject from body.</li><li>Question from response.</li><li>Sender from content.</li><li>Important thread context.</li></ul><h3>Q28. What is structured CSV chunking?</h3><p>CsvStructuredChunker does not simply create normal text chunks. It calls build_semantic_layer() to create metadata for structured-data retrieval.</p><p>This is used by the structured retriever, which later generates SQL and queries DuckDB.</p><p>The distinction is:</p><p>Normal CSV RAG:</p><p>rows -&gt; text chunks -&gt; embeddings -&gt; vector search</p><p>Structured CSV retrieval:</p><p>CSV -&gt; semantic layer + DuckDB -&gt; generated SQL -&gt; query results</p><h3>6. What Is Metadata Enrichment?</h3><p>After chunking, insert_metadata() merges:</p><ul><li>File metadata.</li><li>Document ID.</li><li>Datasource ID.</li><li>Headers selected in configuration.</li><li>Page number.</li><li>Sheet name.</li><li>Figure identifiers.</li><li>Other parser-produced metadata.</li></ul><p>This is important because embeddings alone do not tell the system:</p><ul><li>Which document a chunk came from.</li><li>Which datasource owns it.</li><li>Which page contains it.</li><li>Which sheet contains it.</li><li>Which tenant or classification applies to it.</li></ul><p>Interview answer:</p><blockquote><em>“We do not embed anonymous text. We enrich each chunk with source metadata before insertion so retrieval can filter it and the final response can cite it.”</em></blockquote><h3>7. What Is top_k?</h3><h3>Interview Answer</h3><blockquote><em>“</em><em>top_k is the number of candidate chunks returned by retrieval for a query. If </em><em>top_k is 10, the vector retriever attempts to return the 10 most relevant chunks, subject to filters and score thresholds.”</em></blockquote><p>The request model defaults to:</p><p>top_k = 10</p><p>The retrieval code passes it as:</p><p>search_kwargs={“k”: ret_config.get(RetrieverConfig.TOP_K)}</p><p>This is used directly by several retrievers, including:</p><ul><li>Naive vector retrieval.</li><li>Multi-query retrieval.</li><li>Ensemble retrieval.</li></ul><h3>What happens if top_k is too low?</h3><p>The system may miss supporting evidence.</p><p>Example:</p><p>Question requires three sections.</p><p>top_k = 1.</p><p>Only one section is returned.</p><p>Answer is incomplete.</p><h3>What happens if top_k is too high?</h3><p>The system may retrieve:</p><ul><li>Irrelevant chunks.</li><li>Duplicate chunks.</li><li>Contradictory chunks.</li><li>Excessive context.</li></ul><p>This can increase:</p><ul><li>Prompt size.</li><li>LLM cost.</li><li>Latency.</li><li>Hallucination risk from noisy context.</li></ul><h3>Is higher top_k always better?</h3><p>No.</p><p>The correct value depends on:</p><ul><li>Chunk quality.</li><li>Corpus size.</li><li>Question complexity.</li><li>Retriever quality.</li><li>Reranking.</li><li>Model context window.</li><li>Desired latency.</li></ul><p>A common approach is:</p><p>Retrieve a broader candidate set</p><p>-&gt; rerank or compress</p><p>-&gt; send a smaller final context to the LLM</p><h3>top_k versus number_of_reranked_results</h3><p>These are different:</p><p>top_k = initial retrieval candidate count</p><p>number_of_reranked_results = final number retained after reranking</p><p>For example:</p><p>top_k = 20</p><p>reranked results = 5</p><p>The system initially finds 20 candidates, then keeps the best 5.</p><h3>top_k versus score threshold</h3><p>top_k limits the number of results.</p><p>A score threshold limits the minimum acceptable relevance.</p><p>top_k = maximum number of results</p><p>score_threshold = minimum quality boundary</p><p>If the score threshold is too high, relevant documents may be rejected. If too low, noisy documents may be included.</p><h3>8. What Is Search Type?</h3><p>The retriever configuration includes search_type, for example:</p><p>similarity</p><p>mmr</p><h3>Similarity search</h3><p>Returns the chunks most similar to the query vector.</p><h3>Advantage</h3><ul><li>Simple.</li><li>Fast.</li><li>Good for direct factual lookup.</li></ul><h3>Limitation</h3><p>It may return several nearly identical chunks.</p><h3>MMR search</h3><p>Maximal Marginal Relevance balances:</p><ul><li>Similarity to the question.</li><li>Diversity among returned chunks.</li></ul><h3>Advantage</h3><p>It reduces duplicate context.</p><h3>Useful for</h3><ul><li>Broad questions.</li><li>Questions requiring multiple aspects.</li><li>Documents with repetitive content.</li></ul><h3>9. What Is Temperature?</h3><h3>General Meaning</h3><p>Temperature controls how deterministic or variable the LLM output is.</p><p>Low temperature</p><p>-&gt; more deterministic</p><p>-&gt; conservative wording</p><p>-&gt; better for factual extraction</p><p>High temperature</p><p>-&gt; more variation</p><p>-&gt; more creative wording</p><p>-&gt; greater risk of unsupported variation</p><p>The RAI schema defines temperature in RaiModelParams:</p><p>temperature: Optional[float]</p><p>It appears in model configuration examples such as:</p><p>{</p><p>“temperature”: 0.7</p><p>}</p><h3>What temperature should be used for RAG?</h3><p>For enterprise factual RAG:</p><p>low to moderate temperature</p><p>is usually preferable because the goal is grounded accuracy, not creativity.</p><p>Typical conceptual guidance:</p><p>Use case Temperature Exact factual answer Low Summarization Low to moderate Rewriting a query Low to moderate Creative writing from retrieved material Higher Brainstorming Higher Structured SQL generation Low</p><h3>Important repository-specific nuance</h3><p>The schema supports temperature, but in the inspected RaiModels.get_ssrai_chat_model() implementation, the model is created with:</p><p>model_kwargs={}</p><p>The configured temperature is not visibly passed into model_kwargs in that method.</p><p>Therefore, the accurate interview answer is:</p><blockquote><em>“Temperature is represented in the RAI model configuration schema, but I would verify whether the deployed RAI client or another configuration layer applies it. In the inspected model-construction method, the wrapper is currently called with an empty </em><em>model_kwargs dictionary.”</em></blockquote><p>This is much safer than claiming that the configured temperature definitely affects runtime generation.</p><h3>10. What Is Few-Shot Prompting?</h3><h3>General Meaning</h3><p>Few-shot prompting means providing the LLM with a few examples of the desired input-output behavior.</p><p>Example:</p><p>Example:</p><p>Question: What is the policy effective date?</p><p>Answer: The policy is effective from 1 January 2025.</p><p>Question: What is the approval owner?</p><p>Answer:</p><p>The examples teach the model:</p><ul><li>Expected format.</li><li>Level of detail.</li><li>Reasoning pattern.</li><li>Terminology.</li><li>Output style.</li></ul><h3>Does this repository have a configurable few_shot parameter?</h3><p>Not visibly.</p><p>There is no clearly defined configuration field named:</p><p>few_shot</p><p>few_shot_examples</p><p>examples</p><p>However, the prompt code contains example interactions, especially in REASON_PROMPT for deep research. It shows the model how to:</p><ul><li>Generate search queries.</li><li>Read search results.</li><li>Continue reasoning.</li><li>Perform multiple searches.</li></ul><p>That is few-shot-like prompt guidance.</p><p>Evidence: prompts.py.</p><h3>How should you describe it in an interview?</h3><p>Say:</p><blockquote><em>“The platform uses examples inside some prompt templates, particularly the deep-research reasoning prompt. Those examples demonstrate how the model should issue search queries and use returned search results. I would describe that as prompt-level few-shot guidance, not as a separate configurable few-shot subsystem.”</em></blockquote><h3>How does few-shot prompting affect the system?</h3><h3>Benefits</h3><ul><li>More consistent output format.</li><li>Better adherence to special markers.</li><li>Better query-reformulation behavior.</li><li>More predictable structured responses.</li></ul><h3>Costs</h3><ul><li>More prompt tokens.</li><li>Higher latency.</li><li>Higher model cost.</li><li>Less room for retrieved context.</li><li>Potentially more accidental bias from the examples.</li></ul><h3>11. Parsing and Chunking Strategy by Document Type</h3><p>Document type Parser Recommended chunker Reason Plain text TxtParser Recursive or paragraph Preserve readable prose Markdown MdParser Recursive with Markdown language or paragraph Preserve headings Text PDF PyPDFParser Recursive or paragraph Simple text extraction Scanned PDF AFRParser Page-number or table-aware OCR and structure Complex PDF with figures MultimodalParser Multimodal or page-aware Include image descriptions CSV CsvParser Row or grouped CSV Entity lookup versus multi-row questions Structured CSV CsvStructuredParser CsvStructuredChunker SQL and semantic-layer retrieval Excel ExcelParser Row or grouped Excel Preserve worksheet metadata PowerPoint Multimodal parser PowerPoint chunker One logical chunk per slide Email EmailParser Email chunker Avoid breaking messages Web page URLParser Recursive or paragraph Convert HTML to text Audio AudioParser Intended transcription then text chunking Current implementation is incomplete Video VideoParser Intended transcription then text chunking Current implementation is incomplete</p><h3>12. How Do You Choose a Strategy?</h3><p>Use these questions:</p><h3>Q: What kind of content is this?</h3><ul><li>Prose?</li><li>Tables?</li><li>Slides?</li><li>Emails?</li><li>Structured records?</li><li>Images?</li><li>Scanned pages?</li></ul><h3>Q: What kind of questions will users ask?</h3><ul><li>Specific record lookup?</li><li>Cross-record comparison?</li><li>Summary?</li><li>Exact identifier search?</li><li>Page-specific question?</li><li>Calculation?</li><li>Multi-step research?</li></ul><h3>Q: What citation granularity is required?</h3><ul><li>Document-level?</li><li>Page-level?</li><li>Sheet-level?</li><li>Row-level?</li><li>Slide-level?</li></ul><h3>Q: What are the cost and latency constraints?</h3><ul><li>Semantic and multimodal parsing are more expensive.</li><li>Simple character splitting is cheaper.</li><li>Deep research uses more model calls.</li><li>Higher top_k increases context and processing.</li></ul><h3>13. Example Strategy Decisions</h3><h3>Example 1: Employee policy PDF</h3><p>Requirement:</p><blockquote><em>“Which approvals are required for international transfers?”</em></blockquote><p>Recommended:</p><p>Parser: Azure Form Recognizer</p><p>Chunker: paragraph or page-number-aware</p><p>Retriever: vector or hybrid</p><p>top_k: moderate</p><p>Temperature: low</p><p>Reason:</p><ul><li>The PDF may have headings, tables, and page references.</li><li>Page metadata is valuable for citations.</li><li>The answer should be factual and deterministic.</li></ul><h3>Example 2: Customer-support CSV</h3><p>Requirement:</p><blockquote><em>“What is the resolution for ticket T1024?”</em></blockquote><p>Recommended:</p><p>Parser: CSV parser</p><p>Chunker: row chunking</p><p>Retriever: hybrid or vector</p><p>top_k: small</p><p>Reason:</p><ul><li>A ticket row is an independent entity.</li><li>Exact ticket identifiers benefit from keyword search.</li><li>Returning many unrelated rows adds noise.</li></ul><h3>Example 3: Financial Excel workbook</h3><p>Requirement:</p><blockquote><em>“Compare revenue across regions for 2023.”</em></blockquote><p>Recommended:</p><p>Parser: Excel parser</p><p>Chunker: grouped Excel chunking or structured retrieval</p><p>Retriever: StructureDataRetriever if calculations are required</p><p>Reason:</p><ul><li>The question requires multiple rows and possibly aggregation.</li><li>SQL/DuckDB retrieval is safer for calculations than asking vector search to infer totals.</li></ul><h3>Example 4: PowerPoint presentation</h3><p>Requirement:</p><blockquote><em>“What did slide 12 say about operational risk?”</em></blockquote><p>Recommended:</p><p>Parser: multimodal/PPT parser</p><p>Chunker: PowerPoint chunker</p><p>Metadata: slide number</p><p>Retriever: vector or hybrid</p><p>Reason:</p><ul><li>One slide is a natural semantic unit.</li><li>Image and chart descriptions need to be searchable.</li><li>Slide metadata supports citation.</li></ul><h3>Example 5: Email archive</h3><p>Requirement:</p><blockquote><em>“What decision was made in the approval thread?”</em></blockquote><p>Recommended:</p><p>Parser: Email parser</p><p>Chunker: email chunker</p><p>Retriever: multi-query or hybrid</p><p>Reason:</p><ul><li>Do not split individual emails.</li><li>Threads may need multiple reformulated queries.</li><li>Exact names and phrases benefit from keyword search.</li></ul><h3>14. Common Interview Questions and Strong Answers</h3><h3>Q: What is the biggest mistake people make with chunking?</h3><blockquote><em>“They choose a single chunk size for every document type. A table, email, slide, policy document, and CSV row have different semantic boundaries. In our platform, the ingestion strategy is configurable so the parser and chunker can be selected according to the data type and expected questions.”</em></blockquote><h3>Q: How does chunk size affect retrieval?</h3><blockquote><em>“Smaller chunks improve precision because each vector represents a narrower concept, but they may lose context and increase vector count. Larger chunks preserve context but may mix unrelated topics, reduce retrieval precision, and increase prompt size.”</em></blockquote><h3>Q: How does overlap help?</h3><blockquote><em>“Overlap preserves boundary context. If a sentence or definition is split between chunks, overlap gives the next chunk some of the preceding context. Too much overlap, however, produces duplicate results and increases cost.”</em></blockquote><h3>Q: How do you tune top_k?</h3><blockquote><em>“I would start with a validation dataset and compare recall, answer faithfulness, token usage, and latency at different values. I would usually retrieve enough candidates for recall, then use score thresholds, compression, or reranking to reduce the final context.”</em></blockquote><h3>Q: Is a higher score threshold always better?</h3><blockquote><em>“No. A high threshold improves precision but can remove relevant documents. A low threshold improves recall but increases noise. The right value depends on embedding quality, corpus characteristics, and whether reranking is applied.”</em></blockquote><h3>Q: How does temperature affect factual RAG?</h3><blockquote><em>“Lower temperature generally makes output more deterministic, which is desirable for factual enterprise answers. It does not fix bad retrieval, though. If the correct context is missing, lowering temperature cannot make the model know the missing information.”</em></blockquote><h3>Q: Is temperature used during embedding?</h3><blockquote><em>“Temperature is a generation parameter. Embedding models do not normally use it in the same way. In this repository, temperature is part of the RAI model configuration schema, while embedding creation uses a separate embedding model.”</em></blockquote><h3>Q: What is few-shot prompting used for?</h3><blockquote><em>“Few-shot prompting provides examples of desired behavior. In this repository, the deep-research prompt includes example search-and-reasoning interactions. These examples guide the model’s tool-like search format. There is not a clearly separate configurable few-shot field.”</em></blockquote><h3>Q: Should you use few-shot examples in every prompt?</h3><blockquote><em>“No. Examples consume tokens and can bias the model. I would use them where output format or behavior is difficult to express through instructions alone, such as query rewriting or structured output.”</em></blockquote><h3>Q: Why not always use semantic chunking?</h3><blockquote><em>“Semantic chunking can improve boundaries, but it requires embedding calls during ingestion and may increase latency and cost. For simple text or structured records, recursive, paragraph, row, or grouped chunking may be more predictable and cheaper.”</em></blockquote><h3>Q: What if a table is split across chunks?</h3><blockquote><em>“The model may lose the relationship between headers and values. That is why the platform has table-aware chunking and structured-data retrieval. If the question requires calculations or aggregation, I would prefer the structured path rather than ordinary vector search.”</em></blockquote><h3>Q: What happens if parsing loses page numbers?</h3><blockquote><em>“The answer may still be generated, but citation quality is reduced. The page-number parser and page-aware chunker preserve page metadata so the final source can identify the page.”</em></blockquote><h3>Q: What is more important, parser quality or embedding model quality?</h3><blockquote><em>“Both matter, but parser quality is foundational. If content, tables, or metadata are lost during parsing, no embedding model can retrieve information that was never represented correctly.”</em></blockquote><h3>15. A Complete Interview Answer About Parsing and Chunking</h3><p>You can say:</p><blockquote><em>“In our platform, parsing and chunking are separate configurable stages. Parsing converts each source format into a normalized representation. For example, PDFs become extracted text, Excel files become sheet-to-DataFrame mappings, CSVs become cleaned DataFrames, and PowerPoint files become slide text with table, chart, and image descriptions.</em></blockquote><blockquote><em>“Chunking then creates the units that will be embedded and retrieved. We support general-purpose recursive and character splitting, semantic chunking, paragraph and table-aware chunking, page-number chunking, row-based CSV and Excel chunking, grouped tabular chunks, slide-level chunks, email-preserving chunks, and structured CSV processing.</em></blockquote><blockquote><em>“The choice depends on the document type and user questions. For example, row-level chunks are suitable for ticket lookup, grouped chunks are better for comparing records, page-aware chunks improve PDF citations, and structured retrieval is better when users need calculations. We tune minimum and maximum chunk size, overlap, semantic thresholds, and records per chunk based on retrieval quality, token usage, and latency.”</em></blockquote><h3>16. Important Codebase Caveats</h3><p>Be accurate about these points:</p><ol><li>top_k is actively used by several vector-based retrievers through search_kwargs[&quot;k&quot;].</li><li>The default request value for top_k is 10.</li><li>score_threshold defaults to 0.8 in retriever logic when not configured.</li><li>temperature exists in the RAI schema, but the inspected model-construction method passes model_kwargs={}.</li><li>Few-shot behavior exists as examples inside prompts, especially deep research, but there is no clearly defined standalone few-shot configuration object.</li><li>AudioParser and VideoParser are present but their inspected implementations are placeholders.</li><li>Structured CSV is not ordinary vector-only RAG; it builds a semantic layer and uses DuckDB/SQL retrieval.</li><li>The name min_chunk_size is used as chunk_size by recursive splitting, so explain the behavior rather than relying only on the name.</li><li>Metadata is inserted after chunking and before embeddings.</li><li>The final answer is generated from retrieved context through RETRIEVER_PROMPT.</li></ol><p>The central explanation to remember is:</p><blockquote><em>“Parsing determines what the system understands from a file. Chunking determines the retrieval units. Metadata determines how those units can be filtered and cited. </em><em>top_k determines how many candidates are retrieved. Temperature controls generation variability. Few-shot examples guide the model’s behavior and format, but they are not a replacement for good parsing, chunking, or retrieval.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb84bcafd6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAGaaS questions]]></title>
            <link>https://medium.com/@forswayamnptelcourse/ragaas-questions-25c814280987?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c814280987</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 15:45:41 GMT</pubDate>
            <atom:updated>2026-09-05T15:45:41.335Z</atom:updated>
            <content:encoded><![CDATA[<p>I understood the request. I reviewed the repository architecture, service entry points, APIs, ingestion and retrieval code, database models, authentication, scheduling, deployment, UI calls, CI/CD, and tests.</p><p>The main areas that are unclear from code alone are external systems such as the exact RAI Gateway implementation, Azure AD/SailPoint behavior, production PostgreSQL configuration, and some production Helm values. I have marked those as “verify with the team” instead of presenting assumptions as facts.</p><p># 1. One-Minute Platform Explanation</p><p>**RAGaaS is an enterprise Retrieval-Augmented Generation platform exposed as a SaaS-style service.**</p><p>Users or client applications can:</p><p>1. Create and configure a knowledge base.<br>2. Attach data sources such as Blob Storage, SharePoint, Jira, Confluence, Box, FTP, web pages, ServiceNow, CSV, Excel, PDFs, email, audio, and video.<br>3. Upload or discover documents.<br>4. Select parsing, chunking, embedding, and ingestion strategies.<br>5. Store document chunks and embeddings in PostgreSQL with pgvector.<br>6. Query a knowledge base through retrieval-only or retrieve-and-generate APIs.<br>7. Use different retrieval strategies such as vector, hybrid, multi-query, self-query, compression, ensemble, deep research, or structured-data retrieval.<br>8. Receive generated answers with source documents, page information, and observability trace IDs.<br>9. Enforce access using Azure AD, service principals, client applications, roles, and KB-level entitlements.</p><p>The major services are:</p><p>- `rag_mgmt`: knowledge bases, data sources, retriever configuration, ingestion strategy configuration, onboarding, approvals, clients, metrics.<br>- `rag_ingestion`: uploads, parsing, chunking, ingestion requests, document status, de-ingestion, scheduling APIs.<br>- `rag_model_serv`: background batch processing and scheduled ingestion.<br>- `rag_retrieval`: retrieval, filtering, generation, streaming, citations.<br>- `rag_auth`: authentication-related and entitlement-related APIs.<br>- `rag_common`: shared models, database utilities, vector store, RAI integration, authentication helpers, prompts, exceptions.<br>- `rag_ui`: React frontend.<br>- `nginx`: reverse proxy.<br>- Helm and Harness: deployment and CI/CD.</p><p>Important source files:</p><p>- `README.md`<br>- `docker-compose.yml`<br>- `dbmodel.py`<br>- `ingestion_helper.py`<br>- `retriever_service.py`<br>- `retriever_utils.py`<br>- `auth_service.py`</p><p># 2. Architecture Questions</p><p>## Q1. What problem does RAGaaS solve?</p><p>It provides a reusable enterprise platform for building knowledge-base applications without every team implementing its own document ingestion, embedding, vector search, model integration, authorization, citation, and observability stack.</p><p>## Q2. Why build RAG as a service?</p><p>A centralized service provides:</p><p>- Common security controls.<br>- Reusable ingestion pipelines.<br>- Standardized APIs.<br>- Centralized model and embedding integration.<br>- Shared monitoring and traceability.<br>- Consistent document and knowledge-base lifecycle management.<br>- Lower duplication across application teams.</p><p>## Q3. Why is the platform split into multiple services?</p><p>The services have different responsibilities and scaling characteristics:</p><p>- Management is CRUD and configuration-heavy.<br>- Ingestion is file and CPU/memory intensive.<br>- Retrieval is latency-sensitive.<br>- Batch ingestion is asynchronous and worker-oriented.<br>- Authentication is security-sensitive.<br>- UI has a separate frontend lifecycle.</p><p>This allows each component to be independently deployed and scaled.</p><p>## Q4. What is the main data hierarchy?</p><p>The hierarchy is:</p><p>```text<br>Knowledge Base<br> -&gt; Data Source<br> -&gt; Document<br> -&gt; Chunk<br> -&gt; Embedding<br>```</p><p>A knowledge base owns its configuration and collection. A data source describes where data came from. A document represents an uploaded or discovered source file. Chunks are the searchable units, and embeddings are stored for similarity search.</p><p>## Q5. Why not store everything as one flat collection?</p><p>The hierarchy enables:</p><p>- Data-source-level filtering.<br>- Document-level filtering.<br>- Different parsing strategies per source.<br>- Different security and classification metadata.<br>- Re-ingestion and de-ingestion at document or source level.<br>- Operational status tracking.</p><p>## Q6. What is the role of Nginx?</p><p>Nginx exposes a unified external entry point and routes paths such as:</p><p>```text<br>/rag/mgmt -&gt; management service<br>/rag/igs -&gt; ingestion service<br>/rag/rts -&gt; retrieval service<br>/rag/auth -&gt; authentication service<br>```</p><p>The individual backend services can remain independently deployed.</p><p>## Q7. What is the difference between synchronous and asynchronous work?</p><p>Management requests, uploads, and retrieval APIs are synchronous from the caller’s perspective.</p><p>Document ingestion is asynchronous:</p><p>1. The document is uploaded.<br>2. A document record is created.<br>3. The ingest API changes the document status to a queue state.<br>4. The batch processor later claims and processes the document.<br>5. The caller checks status separately.</p><p>Generation may stream asynchronously over Server-Sent Events, but it is still initiated through an API request.</p><p>## Q8. What are the main external dependencies?</p><p>The code integrates with:</p><p>- PostgreSQL.<br>- pgvector.<br>- Azure Blob Storage.<br>- Azure AD / Microsoft Graph.<br>- SailPoint or entitlement services.<br>- Responsible AI Gateway.<br>- Azure Form Recognizer.<br>- Event Hub and observability sinks.<br>- Optional structured-data processing through DuckDB.</p><p># 3. Knowledge Base and Management Questions</p><p>## Q9. What is a knowledge base?</p><p>A knowledge base is a logical collection of enterprise data with:</p><p>- A unique ID and name.<br>- RAI Gateway configuration.<br>- Embedding model configuration.<br>- Generative model configuration.<br>- Retriever configuration.<br>- Default prompt.<br>- Entitlements and roles.<br>- Organization metadata.<br>- Data classification.<br>- Vector-store configuration.</p><p>## Q10. What can be configured per knowledge base?</p><p>The main configurable items are:</p><p>- Generative model.<br>- Embedding model.<br>- Cloud provider.<br>- Default prompt.<br>- Retriever type.<br>- Retriever parameters.<br>- Data classification.<br>- Entitlements.<br>- Client attributes.<br>- Vector-store collection.<br>- Time-to-live metadata.</p><p>## Q11. Why store model configuration with the knowledge base?</p><p>Different knowledge bases may require different:</p><p>- Embedding models.<br>- Generative models.<br>- Cloud providers.<br>- Temperature settings.<br>- Responsible AI client credentials.<br>- Model quality or cost profiles.</p><p>The configuration makes the platform multi-tenant and application-independent.</p><p>## Q12. Why are retriever configurations separate from knowledge bases?</p><p>A reusable retriever configuration can be created once and assigned to multiple knowledge bases. This separates:</p><p>- Knowledge-base data and ownership.<br>- Search behavior and algorithm configuration.</p><p>It also allows administrators to standardize approved retriever configurations.</p><p>## Q13. What is a data source?</p><p>A data source identifies the origin and ingestion configuration for documents. Supported types include Blob, SharePoint, Jira, Confluence, Box, FTP, web, sitemap, and ServiceNow, depending on configured connectors.</p><p>A source contains:</p><p>- Source type.<br>- Connection configuration.<br>- Ingestion strategy.<br>- Access level.<br>- Data classification.<br>- Metadata.<br>- Status.</p><p>## Q14. How is a document represented?</p><p>The document table stores:</p><p>- Document ID.<br>- File name.<br>- Fully qualified path.<br>- KB ID.<br>- Data-source ID.<br>- File type.<br>- Status.<br>- Status message.<br>- Metadata.<br>- Checksum.<br>- Classification.<br>- Audit fields.</p><p>## Q15. How is duplicate content handled?</p><p>The document model contains a checksum field, and the status enum contains `DUPLICATE`. The exact duplicate-detection logic should be confirmed in the upload service, but the intended design is to detect the same document or content before creating another ingestion workload.</p><p>## Q16. What is de-ingestion?</p><p>De-ingestion removes the searchable representation of a document. In practice, the document’s embeddings are deleted from the vector store and the document status is updated to `DEINGESTED`.</p><p>## Q17. What happens when a knowledge base is deleted?</p><p>The database models define cascading foreign-key deletion from knowledge bases to data sources, documents, and entitlements. Embedding cleanup and active batch-job handling should be verified carefully before claiming deletion is fully transactional.</p><p># 4. Ingestion Questions</p><p>## Q18. Walk through document ingestion end to end.</p><p>A strong answer is:</p><p>1. The UI or client uploads a file.<br>2. The ingestion service stores it in Blob Storage.<br>3. A `rag_documents` row is created with metadata and an initial status.<br>4. The caller invokes the ingest endpoint.<br>5. The document status becomes `INGESTION_IN_QUEUE`.<br>6. `rag_model_serv` polls for queued documents.<br>7. A worker claims the document using a database lock.<br>8. The connector retrieves the file.<br>9. The parser converts it into a normalized representation.<br>10. The chunker splits it into searchable units.<br>11. Metadata is added to each chunk.<br>12. The embedding model creates vectors.<br>13. Vectors and text are inserted into PostgreSQL/pgvector.<br>14. The document becomes `INGESTED`.<br>15. On failure, embeddings are removed and the document becomes `FAILED`.</p><p>Relevant implementation: `scheduler_service.py` and `ingestion_helper.py`.</p><p>## Q19. What are the document status transitions?</p><p>Important states include:</p><p>```text<br>UPLOADED<br>INGESTION_IN_QUEUE<br>INGESTION_STARTED<br>PARSING_COMPLETED<br>CHUNKING_COMPLETED<br>CREATING_EMBEDDINGS<br>INGESTED<br>FAILED<br>DEINGESTED<br>REINGESTION_IN_QUEUE<br>REINGESTION_STARTED<br>DUPLICATE<br>```</p><p>The exact transitions vary for normal ingestion, re-ingestion, structured data, and failures.</p><p>## Q20. Why is ingestion asynchronous?</p><p>Parsing and embedding may take a long time, especially for large PDFs, scanned documents, media, or large batches. Asynchronous processing prevents the upload request from blocking and allows:</p><p>- Retries or status inspection.<br>- Parallel workers.<br>- File-size-based scheduling.<br>- Memory-aware processing.<br>- Better operational control.</p><p>## Q21. How does the batch processor select documents?</p><p>It queries documents in queued states and uses file-size categories. The code has separate processing paths for extra-small, small, medium, and large files.</p><p>It also uses:</p><p>```python<br>with_for_update(skip_locked=True)<br>```</p><p>This helps multiple workers avoid claiming the same row.</p><p>## Q22. Why use `skip_locked`?</p><p>When multiple workers query the queue concurrently, `skip_locked` allows one worker to skip rows already being processed instead of waiting on database locks. This improves throughput and reduces duplicate processing.</p><p>## Q23. What are the file-size categories?</p><p>The code defines categories approximately as:</p><p>- Less than 5 MB.<br>- 5 MB to 50 MB.<br>- 50 MB to 100 MB.<br>- Greater than 100 MB.</p><p>The exact boundary values should be presented as implementation configuration rather than a universal product rule.</p><p>## Q24. What happens when ingestion fails?</p><p>The ingestion worker:</p><p>1. Logs the exception.<br>2. Marks the document as `FAILED`.<br>3. Deletes embeddings associated with the document.<br>4. Stores a failure message.</p><p>This prevents partially indexed documents from remaining searchable.</p><p>## Q25. How does re-ingestion work?</p><p>For a re-ingestion status, the worker first deletes existing embeddings for the document. It then re-fetches, parses, chunks, embeds, and stores the new representation.</p><p>This avoids stale chunks remaining alongside the new version.</p><p>## Q26. What happens if the embedding call fails halfway through?</p><p>The exception path marks the document as failed and calls embedding deletion for the document. This is intended to avoid partial vector data.</p><p>A good production improvement would be stronger transactional or batch-level cleanup guarantees, especially if embedding insertion and status updates occur in separate transactions.</p><p>## Q27. How are parsers selected?</p><p>The parser is selected from the configured parsing strategy:</p><p>```text<br>AzureFormRecognizer<br>Audio<br>Video<br>Pdf<br>Csv<br>Excel<br>Multimodal<br>Weblink<br>Txt<br>Md<br>Email<br>CsvStructuredParser<br>```</p><p>`IngestionHelper.create_parser()` maps the configured parser name to a concrete parser class.</p><p>## Q28. Which parser should be used for scanned PDFs?</p><p>Azure Form Recognizer is appropriate for scanned documents because it can perform document intelligence and extract structure. Standard PDF parsing is faster but may fail to recover text from image-only pages.</p><p>## Q29. What are the tradeoffs between PyPDF and Form Recognizer?</p><p>PyPDF:</p><p>- Faster.<br>- Less expensive.<br>- Suitable for text-based PDFs.<br>- May lose layout, tables, figures, or scanned text.</p><p>Form Recognizer:</p><p>- Better for scanned or structurally complex documents.<br>- Can preserve layout and figures.<br>- Adds network latency and external service dependency.<br>- May have quota and cost implications.</p><p>## Q30. How are CSV and Excel files handled?</p><p>The platform has specialized parsers and chunkers:</p><p>- CSV row chunking.<br>- CSV multi-row chunking.<br>- Structured CSV parsing.<br>- Excel row chunking.<br>- Excel sheet-aware chunking.<br>- Blank-sheet handling.</p><p>Structured CSV ingestion additionally creates a DuckDB representation for structured-data querying.</p><p>## Q31. How are web pages handled?</p><p>The web parser retrieves the page and extracts content, typically using HTML parsing. The source URL and related metadata should be retained so citations can point back to the original source.</p><p>## Q32. How are audio, video, images, and multimodal documents handled?</p><p>The platform includes audio, video, multimodal parsers, and multimodal chunking. The exact transcription and image-understanding behavior depends on the configured RAI multimodal model and parser implementation.</p><p>## Q33. What happens when a file type is unsupported?</p><p>The parser factory raises an entity-not-found or parser configuration error. The document should ultimately be marked failed or unsupported, depending on the API path.</p><p>## Q34. What is chunking?</p><p>Chunking converts a parsed document into smaller units that can be embedded and retrieved independently.</p><p>Good chunks should:</p><p>- Preserve enough context.<br>- Be small enough for embedding and generation limits.<br>- Avoid splitting important semantic relationships.<br>- Retain metadata such as source, page, sheet, and section.</p><p>## Q35. Which chunking strategies are implemented?</p><p>The code supports:</p><p>- Character text splitting.<br>- Recursive character splitting.<br>- Semantic splitting.<br>- CSV row chunking.<br>- CSV multi-row chunking.<br>- Excel row chunking.<br>- Excel chunking.<br>- Multimodal chunking.<br>- Table-aware chunking.<br>- Paragraph chunking.<br>- PowerPoint chunking.<br>- Page-number chunking.<br>- Email chunking.<br>- Structured CSV chunking.</p><p>## Q36. What is semantic chunking?</p><p>Semantic chunking uses embeddings to detect semantic boundaries between sections or sentences. It can produce more meaningful chunks than fixed character splitting, but it requires additional embedding calls and depends on threshold configuration.</p><p>## Q37. What are the semantic chunking parameters?</p><p>The schema exposes parameters such as:</p><p>- `buffer_size`.<br>- `breakpoint_threshold_type`.<br>- `min_chunk_size`.<br>- `sentence_split_regex`.<br>- Embedding model configuration.</p><p>## Q38. How would you choose chunk size?</p><p>I would evaluate:</p><p>- Typical document structure.<br>- Embedding model context length.<br>- Query complexity.<br>- Citation granularity.<br>- Expected answer length.<br>- Retrieval precision and recall.</p><p>Large chunks preserve context but reduce precision and consume more generation tokens. Small chunks improve pinpoint retrieval but can lose context.</p><p>## Q39. Why preserve metadata on every chunk?</p><p>Metadata enables:</p><p>- Source citations.<br>- Page and slide references.<br>- Data-source filtering.<br>- Document filtering.<br>- Tenant and access checks.<br>- Structured-data routing.<br>- Debugging and observability.</p><p># 5. Embedding and Vector Database Questions</p><p>## Q40. Where are embeddings stored?</p><p>The primary vector store is PostgreSQL with the pgvector extension. The relevant tables are:</p><p>- `rag_kb_collections`.<br>- `rag_kb_embeddings`.</p><p>The embedding row includes the vector, text content, collection ID, data-source ID, document ID, metadata, and roles.</p><p>## Q41. Why use PostgreSQL with pgvector?</p><p>It provides:</p><p>- Relational metadata and vector data in one system.<br>- SQL filtering combined with vector similarity.<br>- Existing enterprise database controls.<br>- Transactional document and embedding lifecycle.<br>- JSONB metadata querying.<br>- Easier operational integration than a separate vector database.</p><p>## Q42. What is a collection?</p><p>A collection represents the vector namespace for a knowledge base. The vector store uses the KB ID as the collection name in the retrieval setup.</p><p>## Q43. How is metadata stored?</p><p>Chunk metadata is stored in JSONB, including information such as:</p><p>- File name.<br>- Document ID.<br>- Data-source ID.<br>- Page number.<br>- Sheet name.<br>- Headers.<br>- Figure identifiers.<br>- Extracted keywords.<br>- Classification information.</p><p>## Q44. What index is used for metadata?</p><p>The custom vector-store model defines a GIN index for JSONB metadata. This supports efficient metadata filtering.</p><p>## Q45. How does vector search work?</p><p>At query time:</p><p>1. The query is embedded using the configured embedding model.<br>2. pgvector compares the query vector with stored chunk vectors.<br>3. The configured search strategy selects top candidates.<br>4. Metadata filters are applied.<br>5. Optional keyword retrieval, compression, or reranking is performed.<br>6. The resulting context is sent to the generative model.</p><p>## Q46. What causes a vector dimension mismatch?</p><p>If documents were embedded with one model and queries use another model with a different dimension, pgvector cannot compare them. The retrieval error definitions include a specific vector dimension mismatch error.</p><p>The operational solution is to use a consistent embedding model per collection or re-embed the entire collection when changing dimensions.</p><p>## Q47. How do you handle an embedding model change?</p><p>Do not silently mix vectors from incompatible models. Use one of these strategies:</p><p>- Create a new collection.<br>- Re-embed all existing chunks.<br>- Version the embedding model in KB configuration.<br>- Switch traffic only after re-indexing completes.</p><p>## Q48. How are long texts embedded?</p><p>The shared embedding wrapper tokenizes long content, splits it into smaller token-safe segments, embeds those segments, and combines or normalizes the results.</p><p>The relevant implementation is `rai_embed_service.py`.</p><p>## Q49. How are embedding requests batched?</p><p>The ingestion code uses a configurable chunks-per-batch setting. The embedding service also has a configurable embedding chunk size.</p><p>Batching reduces request overhead but must be balanced against:</p><p>- Gateway limits.<br>- Memory usage.<br>- Timeout risk.<br>- Retry blast radius.</p><p># 6. Retrieval Questions</p><p>## Q50. What is the difference between retrieval and generation?</p><p>`/retrieve` returns relevant source documents or chunks.</p><p>`/generate` retrieves context and passes it to the LLM to produce an answer.</p><p>Separating them allows:</p><p>- Debugging retrieval quality.<br>- Building custom generation flows.<br>- Evaluating search independently.<br>- Avoiding LLM cost when only context is required.</p><p>## Q51. What happens when a generation request arrives?</p><p>The retrieval service:</p><p>1. Authenticates and authorizes the caller.<br>2. Loads KB configuration.<br>3. Validates the RAI configuration.<br>4. Validates the prompt if one is supplied.<br>5. Checks document ingestion status.<br>6. Parses data filters.<br>7. Creates the vector store.<br>8. Creates embedding and chat models.<br>9. Instantiates the configured retriever.<br>10. Retrieves documents.<br>11. Applies optional hybrid search and reranking.<br>12. Builds the grounded prompt.<br>13. Calls the LLM.<br>14. Returns the answer, sources, and trace ID.</p><p>## Q52. Which retrievers are supported?</p><p>The enum defines:</p><p>- `NaiveRetriever`.<br>- `SelfQueryRetriever`.<br>- `ContextualCompressionRetriever`.<br>- `MultiQueryRetriever`.<br>- `EnsembleRetriever`.<br>- `DeepResearchRetriever`.<br>- `StructureDataRetriever`.</p><p>The factory implementation is in `retriever_factory.py`.</p><p>## Q53. What is the naive vector retriever?</p><p>It performs direct vector similarity search using the configured top-K, search type, and score threshold.</p><p>It is simple and fast, but it does not reformulate the query or combine keyword search.</p><p>## Q54. What is Maximal Marginal Relevance?</p><p>MMR balances relevance and diversity. Instead of returning several highly similar chunks, it attempts to return documents that are both relevant to the question and less redundant.</p><p>## Q55. What is contextual compression?</p><p>Contextual compression first retrieves candidate documents and then compresses or filters them to retain only content relevant to the query.</p><p>The code supports:</p><p>- Embedding-based filtering.<br>- LLM-based extraction.</p><p>Embedding filters are generally cheaper and faster. LLM extraction can be more expressive but adds latency and model cost.</p><p>## Q56. What is self-query retrieval?</p><p>Self-query retrieval uses an LLM to translate a natural-language request into:</p><p>- A semantic query.<br>- Structured metadata filters.</p><p>For example:</p><p>&gt; “Show documents about Apple from 2024”</p><p>could become a semantic search plus metadata conditions for company and year.</p><p>The risk is that the LLM may misunderstand metadata field descriptions or produce invalid filters.</p><p>## Q57. What is multi-query retrieval?</p><p>The LLM generates multiple reformulations of the original query. Each reformulated query is searched, and the results are combined.</p><p>It improves recall when the original wording does not match the wording used in the source documents, but it increases model calls and latency.</p><p>## Q58. What is ensemble retrieval?</p><p>Ensemble retrieval combines multiple retrieval methods, typically:</p><p>- Semantic vector retrieval.<br>- BM25 keyword retrieval.</p><p>Weights control the contribution of each method. This is useful when exact terms, identifiers, or names matter alongside semantic meaning.</p><p>## Q59. Why is hybrid search useful in enterprise data?</p><p>Enterprise queries often include:</p><p>- Contract IDs.<br>- Account numbers.<br>- Product names.<br>- Regulatory terms.<br>- Exact policy phrases.</p><p>Keyword search handles exact lexical matches better, while vector search handles paraphrases and conceptual similarity.</p><p>## Q60. What is reranking?</p><p>Reranking takes an initial candidate set and orders it again using a stronger relevance model or LLM-based logic.</p><p>It improves precision but adds latency and cost, so it is typically applied to a limited number of candidates.</p><p>## Q61. What is deep research retrieval?</p><p>Deep research iteratively:</p><p>1. Generates search queries.<br>2. Retrieves results.<br>3. Evaluates whether the results are sufficient.<br>4. Reformulates or expands the search.<br>5. Repeats until a step or quality limit is reached.<br>6. Generates a final answer.</p><p>The code includes global-step and per-query limits to prevent uncontrolled loops.</p><p>## Q62. Why is deep research unavailable for `/retrieve`?</p><p>Deep research is implemented as an answer-generation workflow involving iterative reasoning. The retrieval-only path explicitly rejects it because it cannot return a simple, single context result from that process.</p><p>## Q63. What is structure-data retrieval?</p><p>It supports structured sources such as CSV data. The system uses metadata and semantic-layer information to generate SQL-like queries, then executes them through DuckDB.</p><p>## Q64. How is generated SQL secured?</p><p>The code includes a SQL validation layer intended to:</p><p>- Permit read-only `SELECT` or `WITH` statements.<br>- Reject destructive operations.<br>- Limit SQL size.<br>- Prevent commands such as drop, delete, or update.</p><p>A good interview answer should also acknowledge that generated SQL requires defense in depth, parameterization where possible, strict database permissions, and query timeouts.</p><p>## Q65. What is the purpose of a semantic layer?</p><p>A semantic layer maps business concepts to technical tables, columns, relationships, and definitions. It helps the model generate meaningful structured-data queries rather than guessing raw database structure.</p><p># 7. Filtering Questions</p><p>## Q66. What filters are supported?</p><p>Filtering can include:</p><p>- Data-source IDs.<br>- Document IDs.<br>- Metadata expressions.<br>- Data filters.<br>- Structured comparison operators.</p><p>## Q67. Which operators are supported?</p><p>The filter conversion supports operators such as:</p><p>```text<br>eq<br>ne<br>lt<br>lte<br>gt<br>gte<br>in<br>nin<br>between<br>like<br>ilike<br>```</p><p>These are converted into pgvector/LangChain-compatible filter expressions.</p><p>## Q68. Why are filters important for multi-tenant RAG?</p><p>Filtering ensures that retrieval is restricted to:</p><p>- The requested knowledge base.<br>- Authorized data sources.<br>- Requested documents.<br>- Relevant metadata.<br>- Appropriate classifications.</p><p>A vector similarity score alone must never be treated as an authorization mechanism.</p><p>## Q69. What happens if no data filter is supplied?</p><p>The retrieval API adds global data sources for the knowledge base as defaults. If a datasource ID is supplied as a query parameter, it is added to the request filter.</p><p>This behavior should be explained carefully because source-level access and global-source behavior are part of the product design.</p><p>## Q70. What happens if a document is not fully ingested?</p><p>The retrieval service checks file status before searching. If there are no valid ingested documents, it returns a retrieval error rather than silently generating from incomplete data.</p><p># 8. Prompt and Generation Questions</p><p>## Q71. What is in the generation prompt?</p><p>The prompt contains:</p><p>- Retrieved context.<br>- User question.<br>- Optional user-provided prompt.<br>- Conversation history.<br>- System instructions.<br>- Citation/source formatting guidance.<br>- Guardrail instructions.</p><p>The prompt templates are in `prompts.py`.</p><p>## Q72. How are sources presented?</p><p>Retrieved documents are returned as source objects. The prompt formats source information using file names and, where available, page numbers or other metadata.</p><p>The final response also includes source documents separately from the generated answer.</p><p>## Q73. How does the platform reduce hallucination?</p><p>The main mechanisms are:</p><p>- Retrieval-grounded prompting.<br>- Restricting the prompt to retrieved context.<br>- Citation instructions.<br>- Retrieval-only endpoint for debugging.<br>- RAI gateway guardrails.<br>- Prompt validation.<br>- Source metadata returned to the client.<br>- Observability traces.</p><p>These reduce hallucination but cannot guarantee perfect factuality.</p><p>## Q74. How is conversation history handled?</p><p>Conversation history is converted into role/content lines and included in the prompt. It can help resolve follow-up questions, but excessive history increases token usage and may distract retrieval or generation.</p><p>A production improvement would be history summarization or separate query rewriting.</p><p>## Q75. Can users override the prompt?</p><p>The request model supports an optional prompt. If present, the retrieval service validates and uses it; otherwise it falls back to the knowledge base prompt.</p><p>Prompt overrides should be governed carefully because they can change grounding behavior and introduce prompt injection risk.</p><p>## Q76. Can users override the model?</p><p>The retrieval service checks whether a model is supplied in the request’s RAI configuration. Otherwise, it uses the knowledge base’s configured model.</p><p>This is useful for experimentation but should be restricted by authorization and approved model policies.</p><p>## Q77. How are guardrail and jailbreak failures handled?</p><p>The RAI invocation helpers catch specific exceptions such as:</p><p>- Guardrail violations.<br>- Jailbreak attempts.<br>- Token-limit failures.<br>- RAI service errors.</p><p>These are converted into platform-level exceptions and returned using the service’s error handling conventions.</p><p># 9. Streaming Questions</p><p>## Q78. How does streaming work?</p><p>For a streaming request:</p><p>1. The retrieval service creates an async generator.<br>2. The LLM streams output chunks.<br>3. Each chunk is wrapped in the response model.<br>4. The API sends the chunks as Server-Sent Events.<br>5. A final message contains the full answer, sources, trace ID, and `streamingFinished`.</p><p>## Q79. Why use Server-Sent Events instead of polling?</p><p>SSE provides incremental output over one HTTP connection and is simpler than bidirectional WebSockets for server-to-client answer streaming.</p><p>It improves perceived latency because users see the answer while generation is still running.</p><p>## Q80. What happens if streaming fails after HTTP 200?</p><p>The endpoint tries to inspect the first streamed chunk and determine an error status before returning the response. Errors occurring later may need to be represented as an error event because the HTTP status can no longer be changed after streaming begins.</p><p>This is an important interview scenario.</p><p>## Q81. What is a limitation of streaming?</p><p>The server may have already sent partial content when a failure occurs. Clients must therefore understand:</p><p>- Partial answers.<br>- Error events.<br>- The final completion marker.<br>- Retry behavior.<br>- Duplicate answers after reconnect.</p><p>## Q82. How are citations handled during streaming?</p><p>Intermediate answer chunks have empty source lists. The final completion event includes the consolidated sources and observability trace ID.</p><p># 10. Authentication and Authorization Questions</p><p>## Q83. How is a user authenticated?</p><p>The platform is designed around Azure AD and Microsoft identity tokens. User information is propagated into a `UserModel`, which includes:</p><p>- User ID.<br>- Name.<br>- Email.<br>- Groups.<br>- Headers.<br>- Client attributes.<br>- Entitlements.<br>- Role flags.</p><p>## Q84. How is authorization performed?</p><p>The `<a href="http://twitter.com/authz">@authz</a>` decorator:</p><p>1. Receives the authenticated user model.<br>2. Loads current user entitlements.<br>3. Checks platform-owner access.<br>4. Determines whether the caller is a user or client application.<br>5. Checks KB access through the authorization service.<br>6. Verifies the role required by the endpoint.<br>7. Allows or rejects the request.</p><p>## Q85. Which roles exist?</p><p>The code references roles including:</p><p>- Platform owner.<br>- Administrator.<br>- User.<br>- Contributor.<br>- Application.<br>- Knowledge-base owner.</p><p>Not every role is active in every endpoint.</p><p>## Q86. How are client applications authorized?</p><p>Client applications use client identity information and are checked against client-to-KB access endpoints. The client must have an allowed role, typically the application role, for the requested knowledge base.</p><p>## Q87. How are entitlements retrieved?</p><p>Entitlements are retrieved from an external authorization or entitlement service configured through environment-specific settings. Access is checked at KB level and sometimes through role-specific rules.</p><p>## Q88. Is authorization cached?</p><p>The broader platform includes in-memory caches for some entitlement and client-access lookups. Cache invalidation and stale-entitlement behavior should be confirmed with the team.</p><p>## Q89. How is multi-tenancy implemented?</p><p>The system has:</p><p>- KB-level isolation.<br>- Entitlement checks.<br>- Client-to-KB mappings.<br>- Organization metadata.<br>- Data-source and document filters.</p><p>However, the `org` field by itself is not sufficient isolation. Every data access path must enforce tenant and entitlement restrictions.</p><p>## Q90. What security issue should you be prepared to discuss?</p><p>The authentication code contains areas that deserve careful review:</p><p>- Some HTTP requests use `verify=False`.<br>- The exact JWT signature-validation path is not visible in the inspected `auth_service.py`.<br>- A contributor entitlement helper appears syntactically suspect and the contributor check is currently commented out in one authorization path.<br>- Authorization depends on external entitlement services.<br>- Cache staleness could create access-control risk.</p><p>Do not claim these are production vulnerabilities without verifying deployment behavior, but mention them as review items.</p><p># 11. Database Questions</p><p>## Q91. Why use SQLAlchemy?</p><p>SQLAlchemy provides:</p><p>- ORM models.<br>- Database sessions.<br>- Relationships.<br>- Transactions.<br>- PostgreSQL-specific types.<br>- JSONB support.<br>- Integration with pgvector.</p><p>## Q92. Which PostgreSQL features are used?</p><p>The model uses:</p><p>- JSONB.<br>- Arrays.<br>- Foreign keys.<br>- Cascading deletes.<br>- Server timestamps.<br>- PostgreSQL schemas.<br>- pgvector columns.<br>- GIN metadata indexes.</p><p>## Q93. How is configuration stored?</p><p>Flexible configurations such as RAI gateway, retriever settings, ingestion strategy, metadata, and vector-store settings are stored in JSONB columns.</p><p>This supports evolving configuration without adding a new relational column for every model parameter.</p><p>## Q94. What is the downside of JSONB configuration?</p><p>JSONB provides flexibility but weakens:</p><p>- Compile-time validation.<br>- Database-level constraints.<br>- Query simplicity.<br>- Migration visibility.<br>- Configuration discoverability.</p><p>Pydantic validation compensates at API boundaries, but database-level validation is still limited.</p><p>## Q95. How are timestamps and audit fields handled?</p><p>Most major entities include:</p><p>- `created_by`.<br>- `modified_by`.<br>- `created_ts`.<br>- `modified_ts`.</p><p>Timestamps use database defaults and update behavior.</p><p>## Q96. Is there a migration framework?</p><p>The inspected repository does not clearly show an Alembic migration setup. The database initialization and schema-management approach should be verified before the interview.</p><p>A mature production answer should include versioned migrations and backward-compatible rollout practices.</p><p>## Q97. How does the system handle database connection pooling?</p><p>The common database layer uses SQLAlchemy connection pooling with configurable pool sizing. The exact production pool settings should be verified against environment configuration.</p><p># 12. Scheduling and Batch Questions</p><p>## Q98. What scheduler is used?</p><p>The platform uses APScheduler and persists scheduler job state through an `apscheduler_jobs` table.</p><p>## Q99. What can be scheduled?</p><p>Scheduling supports multiple levels:</p><p>- Knowledge-base level.<br>- Data-source level.<br>- Document level.</p><p>It supports cron-like schedules, priorities, time zones, start and end dates, and override behavior.</p><p>## Q100. How are scheduled executions audited?</p><p>The system stores schedule execution information including:</p><p>- Status.<br>- Documents processed.<br>- Documents updated.<br>- Errors.<br>- Execution context.</p><p>## Q101. How does the scheduler avoid duplicate work?</p><p>The document queue uses database row locking with `skip_locked`, and document statuses are moved into started states before processing.</p><p>However, multi-pod scheduler coordination must be verified. A strong design requires only one active scheduler leader or a distributed coordination mechanism.</p><p>## Q102. What happens if a scheduled job fails?</p><p>The code tracks failed execution state. Automatic retry or recovery behavior is limited or should be verified. A good improvement would be configurable retry with exponential backoff and dead-letter handling.</p><p>## Q103. Why use multiprocessing for ingestion?</p><p>Parsing, file processing, and embedding preparation can be CPU- or memory-intensive. Multiprocessing can improve throughput and isolate large document work.</p><p>The tradeoff is greater memory consumption, process startup cost, and more complex error handling.</p><p>## Q104. How does the system protect against memory pressure?</p><p>The batch service checks memory availability before starting ingestion and has separate processing paths by file size. Large files can use fewer workers or dedicated handling.</p><p># 13. Deployment Questions</p><p>## Q105. How is the platform packaged?</p><p>Each service has:</p><p>- `Dockerfile`.<br>- `Dockerfile.Lab`.<br>- Python packaging files.<br>- Requirements.<br>- Startup scripts.</p><p>The UI has its own Node/Vite build.</p><p>## Q106. How is it deployed to Kubernetes?</p><p>Helm charts define:</p><p>- Deployments.<br>- Services.<br>- Ingress.<br>- HPAs.<br>- Secret Provider Classes.<br>- Workload identity or pod identity bindings.<br>- Environment-specific values.</p><p>## Q107. How are secrets managed?</p><p>The deployment integrates with Azure Key Vault through the CSI Secret Store provider and workload identity or managed identity. This avoids embedding credentials directly in source code or container images.</p><p>## Q108. What does the CI/CD pipeline do?</p><p>Harness pipelines build Docker images, run security and quality scans, push images and Helm charts, and deploy or uninstall Helm releases.</p><p>The pipelines reference tools such as:</p><p>- SonarQube.<br>- Black Duck.<br>- Wiz.<br>- Docker build templates.<br>- Helm push/install steps.</p><p>## Q109. How does horizontal scaling work?</p><p>The Helm charts define HPAs based primarily on CPU and memory. Each pod can also run multiple Gunicorn/Uvicorn workers.</p><p>Retrieval and ingestion have different scaling needs:</p><p>- Retrieval scales based on request latency and concurrency.<br>- Ingestion scales based on queue depth, memory, CPU, and external-service capacity.</p><p>## Q110. What is the risk of scaling the model-service scheduler horizontally?</p><p>Multiple scheduler instances may pick up the same scheduled work unless a leader-election or distributed locking strategy exists. Row-level document locks help with document claiming, but scheduler-level duplication still needs explicit coordination.</p><p>## Q111. What are the main production bottlenecks?</p><p>Likely bottlenecks include:</p><p>- Embedding gateway throughput.<br>- Azure Form Recognizer latency and quotas.<br>- PostgreSQL connection pool capacity.<br>- pgvector search latency as collections grow.<br>- LLM generation latency.<br>- Large-document memory consumption.<br>- Blob Storage throughput.<br>- SSE connection duration.<br>- Database locks during queue pickup.</p><p># 14. Reliability and Failure Scenarios</p><p>## Q112. What if Blob Storage is unavailable?</p><p>The connector or blob service fails. The document should be marked failed, and retry behavior depends on the configured retry decorator and caller workflow.</p><p>A stronger production design would include:</p><p>- Exponential backoff.<br>- Circuit breaking.<br>- Dead-letter state.<br>- Retry count and next retry timestamp.<br>- Alerting.</p><p>## Q113. What if the RAI Gateway is unavailable?</p><p>Embedding or generation fails. The service catches RAI exceptions and returns a platform error. Ingestion should mark the document failed and clean up partial embeddings.</p><p>## Q114. What if the vector database is unavailable?</p><p>Retrieval fails before generation. The client should receive a clear dependency error rather than a fabricated answer.</p><p>## Q115. What if the embedding model changes unexpectedly?</p><p>Queries may have incompatible dimensions or reduced relevance. Model identity and vector dimensionality should be versioned, and existing collections should be re-embedded.</p><p>## Q116. What if no documents are ingested?</p><p>The retrieval service checks file status and returns an explicit error such as “no ingested files” rather than generating without evidence.</p><p>## Q117. What if a filter is malformed?</p><p>The filter parser or Pydantic validation should reject it before executing vector search. The retrieval error definitions include filter validation errors.</p><p>## Q118. What if a user attempts prompt injection?</p><p>The platform relies on prompt design and RAI guardrails, but retrieved documents themselves can contain malicious instructions. A robust answer should say:</p><p>- Treat retrieved content as untrusted data.<br>- Separate system instructions from document text.<br>- Do not let documents override policy.<br>- Use model guardrails.<br>- Log and evaluate suspicious requests.<br>- Test indirect prompt injection scenarios.</p><p>## Q119. What if a user asks for information from an unauthorized data source?</p><p>Authorization must be enforced before retrieval, and data-source/document filters must be applied to the vector query. The system must never rely only on the LLM to avoid revealing unauthorized context.</p><p>## Q120. What if streaming fails halfway through?</p><p>The client may receive partial output followed by an error event. The protocol should include a completion marker and a client retry policy. The server cannot reliably change the HTTP status after bytes have already been sent.</p><p># 15. Observability Questions</p><p>## Q121. What does the platform trace?</p><p>The observability metadata can include:</p><p>- KB ID.<br>- Data-source IDs.<br>- Document IDs.<br>- Model name.<br>- User email.<br>- Organization.<br>- Prompt.<br>- Retrieved context.<br>- Generated answer.<br>- Token usage.<br>- Latency.<br>- Error information.</p><p>## Q122. What is the purpose of the trace ID?</p><p>The trace ID allows an answer to be correlated with model calls, retrieval context, logs, and observability systems. It is especially important when debugging a hallucinated or low-quality answer.</p><p>## Q123. How is latency measured?</p><p>The retrieval code records nanosecond timestamps around retrieval/generation processing and sends latency to observability processing.</p><p>## Q124. How would you measure RAG quality?</p><p>I would track:</p><p>- Retrieval recall.<br>- Precision of top-K chunks.<br>- MRR or nDCG.<br>- Citation correctness.<br>- Answer faithfulness.<br>- Answer relevance.<br>- No-answer accuracy.<br>- Latency.<br>- Token usage.<br>- Cost per request.<br>- Error rate.<br>- User feedback.</p><p>## Q125. How would you debug a bad answer?</p><p>I would inspect:</p><p>1. The exact user query.<br>2. The selected KB and data-source filters.<br>3. Document ingestion status.<br>4. The selected retriever.<br>5. Query embedding model.<br>6. Retrieved chunks and scores.<br>7. Reranker output.<br>8. Final prompt.<br>9. Model and temperature.<br>10. Guardrail or truncation events.<br>11. Observability trace.<br>12. Whether the source document itself contains the answer.</p><p>## Q126. What observability gaps should you mention?</p><p>Potential gaps visible in the repository include:</p><p>- Limited distributed tracing middleware.<br>- Limited metrics around queue depth and dependency latency.<br>- Lack of clear SLO definitions.<br>- Incomplete request-level correlation across services.<br>- Need for better structured logging.<br>- Need for alerts on stuck ingestion states.</p><p># 16. Testing Questions</p><p>## Q127. What kinds of tests exist?</p><p>The repository contains:</p><p>- Unit tests.<br>- Service tests.<br>- Integration-style tests.<br>- BDD feature tests.<br>- Retrieval tests.<br>- Management tests.<br>- Ingestion tests.<br>- Common-service tests.</p><p>## Q128. What behavior is tested?</p><p>Tests cover areas such as:</p><p>- Knowledge-base listing and pagination.<br>- KB CRUD.<br>- Duplicate slugs.<br>- Data-source operations.<br>- File upload.<br>- Ingestion and de-ingestion.<br>- Document status.<br>- Filter parsing.<br>- pgvector filter conversion.<br>- Retrieval service helpers.</p><p>## Q129. What is missing from the tests?</p><p>Important gaps include:</p><p>- Cross-tenant access tests.<br>- Unauthorized KB access.<br>- Entitlement-service failures.<br>- Streaming failure after partial output.<br>- Large-volume ingestion.<br>- Concurrent batch workers.<br>- Vector dimension mismatch.<br>- RAI Gateway outage.<br>- Blob Storage outage.<br>- SQL injection attempts in structured retrieval.<br>- Prompt injection through documents.<br>- Cache invalidation.<br>- Large collection performance.</p><p>## Q130. How would you test retrieval quality?</p><p>I would create a benchmark set containing:</p><p>- Questions.<br>- Expected source documents.<br>- Expected page or chunk references.<br>- Expected answer facts.<br>- “No answer” questions.<br>- Ambiguous questions.<br>- Cross-document questions.</p><p>Then evaluate retrieval and generation separately.</p><p>## Q131. How would you test ingestion idempotency?</p><p>Upload or ingest the same document repeatedly and verify:</p><p>- Duplicate detection.<br>- Stable document identity.<br>- No duplicate embeddings.<br>- Correct re-ingestion behavior.<br>- Correct cleanup after failure.<br>- Consistent final status.</p><p>## Q132. How would you test authorization?</p><p>For every endpoint, test:</p><p>- Platform owner.<br>- Admin.<br>- User.<br>- Contributor.<br>- Application client.<br>- Unauthorized user.<br>- User with access to another KB.<br>- User with stale entitlement.<br>- Missing token.<br>- Invalid token.<br>- Missing client credentials.</p><p># 17. Design and Tradeoff Questions</p><p>## Q133. Why use multiple retriever types instead of one “best” retriever?</p><p>Different datasets and queries need different strategies:</p><p>- Vector retrieval for conceptual questions.<br>- BM25 for exact terms.<br>- Hybrid retrieval for enterprise search.<br>- Self-query for metadata-aware questions.<br>- Compression for reducing noisy context.<br>- Deep research for broad multi-step questions.<br>- Structured retrieval for tabular data.</p><p>No single retriever is optimal for every workload.</p><p>## Q134. What is the main precision/recall tradeoff?</p><p>Higher top-K and multi-query search improve recall but can add irrelevant context, latency, and token cost.</p><p>Lower top-K improves latency and precision but may miss supporting evidence.</p><p>## Q135. Why not send the entire document to the LLM?</p><p>Because of:</p><p>- Context-window limits.<br>- Higher cost.<br>- Higher latency.<br>- Increased distraction.<br>- Greater hallucination risk.<br>- Poor scalability.</p><p>RAG retrieves only relevant portions.</p><p>## Q136. Why not use only vector search?</p><p>Vector search can miss:</p><p>- Exact identifiers.<br>- Acronyms.<br>- Product names.<br>- Policy phrases.<br>- Numeric values.</p><p>That is why keyword and hybrid retrieval are valuable.</p><p>## Q137. Why not use only an LLM?</p><p>An LLM’s pretrained knowledge may be stale or lack access to private enterprise data. RAG grounds the answer in current internal sources and provides citations.</p><p>## Q138. What is the biggest quality risk?</p><p>The biggest risk is not the LLM alone. It is retrieval failure:</p><p>- Wrong parser.<br>- Bad chunking.<br>- Missing metadata.<br>- Incorrect filters.<br>- Poor embedding model.<br>- Low-quality top-K results.<br>- Stale or incomplete ingestion.</p><p>If the correct context is not retrieved, generation cannot reliably recover.</p><p>## Q139. How would you improve answer quality?</p><p>I would improve the system in this order:</p><p>1. Validate ingestion quality.<br>2. Improve chunking and metadata.<br>3. Build retrieval evaluation datasets.<br>4. Tune top-K and score thresholds.<br>5. Add hybrid retrieval.<br>6. Add reranking.<br>7. Improve query rewriting.<br>8. Improve prompt grounding.<br>9. Add answer faithfulness evaluation.<br>10. Add user feedback loops.</p><p># 18. Questions About Code Quality</p><p>## Q140. What design patterns are used?</p><p>The code uses:</p><p>- Factory pattern for parsers, chunkers, retrievers, vector stores, and data-source connectors.<br>- Strategy pattern for ingestion and retrieval behavior.<br>- Abstract base classes for ingestion and retrievers.<br>- Dependency injection through FastAPI.<br>- Repository-like helper services around database access.<br>- Configuration-driven behavior using JSON and Pydantic models.</p><p>## Q141. Why use a retriever factory?</p><p>The retrieval API should not need to know how each retriever is constructed. It passes configuration to the factory, which creates the selected implementation.</p><p>This makes adding retriever types easier and reduces endpoint complexity.</p><p>## Q142. Why use Pydantic?</p><p>Pydantic validates:</p><p>- API request bodies.<br>- RAI Gateway configuration.<br>- Retrieval configuration.<br>- Ingestion strategy configuration.<br>- Response serialization.</p><p>It catches invalid configuration early.</p><p>## Q143. What code smells would you mention carefully?</p><p>Potential review topics include:</p><p>- Broad `except Exception` blocks.<br>- Some duplicated imports.<br>- Long-running operations mixed with request handling.<br>- Configuration stored as loosely typed dictionaries.<br>- In-memory caches in a horizontally scaled service.<br>- Some commented-out code.<br>- Possible inconsistencies between status names in different modules.<br>- Need for stronger transaction boundaries.<br>- Need for more explicit type validation around dynamic retriever configuration.</p><p># 19. Production Improvement Questions</p><p>## Q144. How would you improve reliability?</p><p>I would add:</p><p>- Exponential backoff with jitter.<br>- Circuit breakers around RAI, Blob, and entitlement services.<br>- Dead-letter handling for failed ingestion.<br>- Retry counters and retry timestamps.<br>- Idempotency keys.<br>- Distributed scheduler leadership.<br>- Queue-depth monitoring.<br>- Dependency-aware health checks.<br>- Explicit database transaction boundaries.</p><p>## Q145. How would you improve security?</p><p>I would add or verify:</p><p>- Strict TLS certificate validation.<br>- JWT signature and issuer validation.<br>- Short-lived credentials.<br>- Centralized secret rotation.<br>- Strong tenant predicates on every query.<br>- Document-level ACL enforcement.<br>- Audit logging for reads and deletes.<br>- Prompt injection defenses.<br>- SQL query isolation and timeouts.<br>- Data masking and classification enforcement.</p><p>## Q146. How would you improve scalability?</p><p>I would consider:</p><p>- A durable queue instead of database polling for very high volume.<br>- Separate ingestion workers by parser type.<br>- Autoscaling based on queue depth.<br>- Vector index tuning.<br>- Partitioning large embedding tables.<br>- Caching query embeddings or KB configuration.<br>- Connection-pool monitoring.<br>- Rate limits for model calls.<br>- Bulk embedding APIs.<br>- Dedicated structured-data workers.</p><p>## Q147. How would you handle a million documents?</p><p>I would avoid a single unpartitioned workload. I would use:</p><p>- Durable work queues.<br>- Partitioned document processing.<br>- Per-KB or per-source indexing isolation.<br>- Batch embedding.<br>- Backpressure.<br>- Queue-depth autoscaling.<br>- Incremental status updates.<br>- Retry and dead-letter queues.<br>- Vector-table partitioning or a dedicated vector service if PostgreSQL becomes a bottleneck.</p><p># 20. A Strong End-to-End Interview Answer</p><p>You can say:</p><p>&gt; “We designed RAGaaS as a multi-service enterprise platform. Management owns knowledge bases, data sources, retriever configurations, and ingestion strategies. Ingestion handles upload, connector access, parsing, chunking, metadata enrichment, and embedding. The model service processes ingestion asynchronously using status-driven workers and database row locking. Embeddings and chunk text are stored in PostgreSQL with pgvector, while documents remain in Blob Storage.<br>&gt;<br>&gt; “At query time, retrieval loads the KB configuration, validates authorization and document status, embeds the user’s question, applies data-source and metadata filters, and invokes the configured retriever. We support direct vector retrieval, MMR, BM25/vector hybrid search, multi-query, self-query, contextual compression, ensemble, deep research, and structured-data retrieval. Retrieved chunks are inserted into a grounded prompt and sent to the configured RAI model. The API supports both complete responses and SSE streaming. The final response contains the answer, source documents, and an observability trace ID.<br>&gt;<br>&gt; “Security is enforced through Azure AD, service principals, application clients, external entitlement services, and KB-level authorization. The platform is containerized, deployed with Helm, and delivered through Harness pipelines. The key engineering challenges are retrieval quality, large-document ingestion, model and embedding consistency, tenant isolation, dependency failures, and observing the complete path from user query to source documents and generated answer.”</p><p># 21. Things You Should Verify Before the Interview</p><p>These are the areas where the repository alone does not fully establish production behavior:</p><p>1. Exact production RAI Gateway architecture and model names.<br>2. Whether JWT signature, issuer, audience, and expiry are validated upstream or inside another dependency.<br>3. Exact Azure AD and SailPoint entitlement flow.<br>4. Production PostgreSQL version, pgvector indexes, and table partitioning.<br>5. Whether production uses one active scheduler pod or distributed coordination.<br>6. Exact Nginx configuration used in Kubernetes.<br>7. Production retry and timeout values.<br>8. Whether client secrets are always retrieved from Key Vault.<br>9. Exact observability backend and dashboards.<br>10. Production data-retention and deletion policies.<br>11. Whether organization-level filtering is enforced on every query path.<br>12. Whether the structured-data SQL path has production database isolation and query timeouts.<br>13. Exact duplicate-document and checksum behavior.<br>14. Whether all parser and chunker types listed in configuration are enabled in production.<br>15. Retrieval-quality metrics and evaluation datasets.</p><p># 22. High-Probability Interview Questions to Memorize First</p><p>If time is limited, prepare these especially well:</p><p>1. Walk me through document upload to final answer.<br>2. Why is ingestion asynchronous?<br>3. How do you prevent duplicate ingestion?<br>4. How do you handle failed ingestion?<br>5. Why PostgreSQL plus pgvector?<br>6. How do you choose chunk size?<br>7. What is semantic chunking?<br>8. Explain vector search versus hybrid search.<br>9. Explain reranking.<br>10. Explain multi-query retrieval.<br>11. Explain self-query retrieval.<br>12. Explain deep research retrieval.<br>13. How are filters applied?<br>14. How do you prevent unauthorized document retrieval?<br>15. How are citations generated?<br>16. How does streaming work?<br>17. What happens if streaming fails midway?<br>18. How do you handle prompt injection?<br>19. How do you handle a changed embedding model?<br>20. How does the system scale?<br>21. How do background workers avoid processing the same document?<br>22. How are secrets managed?<br>23. How do you monitor retrieval quality?<br>24. What are the biggest production risks?<br>25. What would you improve in the current design?</p><p>The most important message to communicate is that this platform is not merely “an LLM connected to a vector database.” It is an enterprise ingestion, authorization, retrieval, generation, observability, and deployment platform where retrieval quality and access control are equally important.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c814280987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[prompt]]></title>
            <link>https://medium.com/@forswayamnptelcourse/prompt-2e0feb8849a2?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0feb8849a2</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Tue, 05 May 2026 03:06:21 GMT</pubDate>
            <atom:updated>2026-05-05T03:06:21.392Z</atom:updated>
            <content:encoded><![CDATA[<pre>Act as a senior software engineer responsible for building production-ready features.<br><br>Before writing any code:<br>- Analyze the requirements thoroughly<br>- Identify all edge cases (positive and negative)<br>- Define the architecture<br>- Formulate a plan<br><br>Then return:<br>- Architecture summary<br>- Folder structure (layered: api → service → util)<br>- Data flow<br>- Complete implementation<br>- Error and exception handling<br>- Performance evaluation<br><br>---<br><br>Follow Python best practices, PEP standards, and clean code principles.<br>Apply appropriate software design patterns (SOLID, DRY, separation of concerns).<br>Use a layered architecture: API layer → Service layer → Util layer.<br>No redundant code. Use libraries wherever possible to reduce boilerplate.<br>Nothing should be hardcoded — all values must be configurable.<br><br>---<br><br>Optimize as if you are a performance engineer. Goals: speed, low memory usage, high capability.<br><br>- Use async/await wherever possible to avoid blocking<br>- No CPU-heavy or memory-heavy operations<br>- Minimize latency at every layer<br>- Avoid unnecessary rendering or redundant computation<br>- Identify and eliminate bottlenecks before they happen<br>- Code must be compatible with distributed systems and high concurrency<br>- Design for high throughput — assume 1000+ concurrent users<br><br>---<br><br>Handle database interactions carefully:<br>- Use connection pooling properly — no DB crashes due to exhausted connections<br>- Avoid complex, nested, or blocking queries<br>- Be explicit when querying the DB (comment or annotate DB calls clearly)<br>- Handle resource cleanup and context managers properly<br>- No long-held locks or unbounded result sets<br><br>---<br><br>Handle all exceptions properly — never swallow errors silently.<br>- Use specific exception types, not bare except clauses<br>- Log errors with enough context to debug in production<br>- Gracefully degrade when downstream services fail<br>- The app must not crash under any foreseeable condition<br>- Cover both happy path and all failure/edge cases<br><br>---<br><br>Design with scale in mind from the start:<br>- Assume large datasets (e.g. 1000+ entities, 3000+ sub-entities)<br>- Use pagination, cursor-based or offset, for any list queries<br>- Avoid loading full datasets into memory<br>- Use caching strategies where reads are frequent<br>- Batch operations where possible instead of row-by-row processing<br><br>---<br><br>Do not assume missing context or hallucinate implementation details.<br>If you see a gap in the requirements, call it out explicitly before writing code.<br>Ask clarifying questions if needed rather than guessing.<br>Only implement what is clearly specified or logically implied.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0feb8849a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt]]></title>
            <link>https://medium.com/@forswayamnptelcourse/prompt-ee1cf1c5b8fd?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1cf1c5b8fd</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Tue, 05 May 2026 01:59:30 GMT</pubDate>
            <atom:updated>2026-05-05T02:20:13.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Follow python best practises and logic</p><p>Follow best design and software principles</p><p>My app should not have performance issues</p><p>Have very low latency and don’t make it cpu or memory heavy</p><p>Handle all the cases and properly give me the production grade code</p><p>Don’t hardcode any values, everything is configurable</p><p>Also handle resource management and throughput , it should not crash</p><p>Handle the exceptions properly</p><p>Don’t make the code go in complex query and block</p><p>Also be clear when you are quering the DB (I don’t want DB crash to happen bcoz of connection pooling)</p><p>Let me know if you need any more details or see any gaps in data, don’t assume or hallucinate</p><p>Make sure you think ahead of the feature users (where around 1000+ stadiums are there and 3000+ courts are there and to handle you have a large data) so handle the code with all the best practises and covering all edge cases with no bug</p><p>==========================</p><p>Follow python best coding practices and standards</p><p>Code implementation should be done following Software principles and design patterns</p><p>Handle exception handling</p><p>Handle errors properly</p><p>Don’t make the code memory or cpu heavy</p><p>Avoid latency in the code</p><p>Use async where ever possible</p><p>The code should be scalable, reliable and best performing</p><p>Don’t have redundant code</p><p>Follow layered code (api layer, service layer and util layer)</p><p>Use libraries wherever possible to avoid more code</p><p>Cover all the edge cases and write the code and test it end to end for all negative and positive cases and see where it may fail</p><p>My code should also be compatible when deployed in a distributed systems, and a lot of users start using it</p><p>Make it available for high throughput</p><p>Optimize the code, as if you were a performance engineer</p><p>Objective</p><ul><li>Speed</li><li>Memory usage</li><li>Capability</li></ul><p>Identify</p><ul><li>Bottle neck</li><li>In efficient logs</li><li>Unnecessary rendering</li></ul><p>Return the description and code of the optimized diversion</p><p>Act as a senior software engineer, responsible for developing production ready features.</p><p>Your goal is to design and develop features with a clear architecture scale and maintainable.</p><p>Before the code, analyze the requirements identify each cases, define the architecture, formulate the plan.</p><p>The return must include</p><ul><li>Architecture summary</li><li>Folder structure</li><li>Data flow</li><li>Complete implementation</li><li>Each case handling</li><li>Error management</li><li>Performance evaluation</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1cf1c5b8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extra Arize Queries]]></title>
            <link>https://medium.com/@forswayamnptelcourse/extra-arize-queries-8eac1cad2c64?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eac1cad2c64</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 08:16:27 GMT</pubDate>
            <atom:updated>2025-11-17T08:16:27.413Z</atom:updated>
            <content:encoded><![CDATA[<p>IntegrationsContextQuery</p><pre>query IntegrationsContextQuery(<br>  $accountOrganizationId: ID!<br>) {<br>  node(id: $accountOrganizationId) {<br>    __typename<br>    id<br>    ... on AccountOrganization {<br>      opsgenieIntegrations: integrations(providerName: opsgenie) {<br>        id<br>        name<br>        alertSeverity<br>        creator {<br>          id<br>          name<br>        }<br>      }<br>      pagerdutyIntegrations: integrations(providerName: pagerduty) {<br>        id<br>        name<br>        alertSeverity<br>        creator {<br>          id<br>          name<br>        }<br>      }<br>      slackIntegrations: integrations(providerName: slack) {<br>        id<br>        name<br>        channelName<br>        creator {<br>          id<br>          name<br>        }<br>      }<br>      externalLlmApiKeyIntegration: externalLlmApiKeys {<br>        id<br>        creator {<br>          id<br>          name<br>        }<br>        provider<br>      }<br>      googleCloudIntegration {<br>        id<br>        creator {<br>          id<br>          name<br>        }<br>        projectId<br>        projectAccessLabel<br>        location<br>      }<br>      awsIntegration {<br>        id<br>        creator {<br>          id<br>          name<br>        }<br>        roleArn<br>        externalId<br>      }<br>      customLlmEndpoints {<br>        id<br>        name<br>        modelName<br>        baseUrl<br>        hasApiKey<br>        headers {<br>          key<br>          value<br>        }<br>        creator {<br>          id<br>          name<br>        }<br>        compatibleFormat<br>      }<br>    }<br>  }<br>}<br><br>{<br>  &quot;accountOrganizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;<br>}<br></pre><p>IntegrationTabContentAppServerCloudProviderConfigQuery</p><pre>query IntegrationsTabContentAppServerCloudProviderConfigQuery(<br>  $organizationId: ID!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      googleCloudProjectId<br>      arizeAppAwsIamRole<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;<br>}</pre><p>CostConfigsPageQuery</p><pre>query CostConfigsPageQuery(<br>  $accountOrganizationId: ID!<br>  $search: String<br>  $isDefault: Boolean<br>) {<br>  node(id: $accountOrganizationId) {<br>    __typename<br>    id<br>    ... on AccountOrganization {<br>      ...CostConfigsPage_costConfigs_3MsB4h<br>    }<br>  }<br>}<br><br>fragment CostConfigsPage_costConfigs_3MsB4h on AccountOrganization {<br>  costConfigs(first: 100, search: $search, isDefault: $isDefault) {<br>    edges {<br>      node {<br>        id<br>        modelName<br>        modelRegex<br>        llmProvider<br>        createdAt<br>        tokenConfigs {<br>          tokenName<br>          tokenCostDollars<br>          id<br>        }<br>        isDefault<br>        __typename<br>      }<br>      cursor<br>    }<br>    pageInfo {<br>      endCursor<br>      hasNextPage<br>    }<br>  }<br>  id<br>}<br><br>{<br>  &quot;accountOrganizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;search&quot;: null,<br>  &quot;isDefault&quot;: null<br>}</pre><p>SummaryDashboardPageQuery</p><pre>query SummaryDashboardPageQuery(<br>  $organizationId: ID!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      ...SummaryDashboardPage_summaryDashboardConfig<br>    }<br>    id<br>  }<br>}<br><br>fragment SummaryDashboardPage_summaryDashboardConfig on AccountOrganization {<br>  summaryDashboardConfig {<br>    id<br>    accountOrganizationId<br>    visibleWidgets<br>    updatedAt<br>  }<br>  id<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;<br>}</pre><p>ModelCountBarChartQuery</p><pre>query ModelCountBarChartQuery(<br>  $organizationId: ID!<br>  $ignoreDemoModels: Boolean!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      modelCount(ignoreDemoModels: $ignoreDemoModels) {<br>        modelType<br>        count<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;ignoreDemoModels&quot;: true<br>}</pre><p>ModelInterfaceCountBarChartQuery</p><pre>query ModelInferencesCountBarChartQuery(<br>  $organizationId: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      modelInferencesCount(startDate: $startDate, endDate: $endDate) {<br>        date<br>        count<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T18:29:59.999Z&quot;<br>}</pre><p>ModelsTriggredBarChartQuery</p><pre>query ModelsTriggeredBarChartQuery(<br>  $organizationId: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      modelTriggeredCount(startDate: $startDate, endDate: $endDate) {<br>        date<br>        count<br>        topModels {<br>          modelId<br>          modelName<br>          spaceId<br>          count<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T18:29:59.999Z&quot;<br>}</pre><p>LLMSpansCountBarChartQuery</p><pre>query LLMSpansCountBarChartQuery(<br>  $organizationId: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>) {<br>  node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      llmSpansCount(startDate: $startDate, endDate: $endDate) {<br>        date<br>        count<br>      }<br>    }<br>    id<br>  }<br>}<br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T18:29:59.999Z&quot;<br>}</pre><p>LLMModelCostsLineChartQuery</p><pre>query LLMModelCostsLineChartQuery(<br>  $accountOrganizationId: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>) {<br>  node(id: $accountOrganizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      llmModelCosts(startDate: $startDate, endDate: $endDate) {<br>        date<br>        llmModelName<br>        cost<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;accountOrganizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T18:29:59.999Z&quot;<br>}</pre><p>LLMModelCostsBySpaceBarChart</p><pre>query LLMModelCostsBySpaceBarChartQuery(<br>  $accountOrganizationId: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>) {<br>  node(id: $accountOrganizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      llmModelCostsBySpace(startDate: $startDate, endDate: $endDate) {<br>        spaceName<br>        spaceId<br>        llmModelName<br>        cost<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;accountOrganizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T18:29:59.999Z&quot;<br>}</pre><p>LLMIntegrationTableQuery</p><pre>query LLMIntegrationsTableQuery {<br>  account {<br>    llmIntegrations {<br>      id<br>      name<br>      provider<br>      apiKey<br>      hasApiKey<br>      baseUrl<br>      modelNames<br>      headers<br>      compatibleFormat<br>      enableDefaultModels<br>      functionCallingEnabled<br>      createdAt<br>      creator {<br>        id<br>        name<br>        email<br>      }<br>      scopings {<br>        accountOrganizationId<br>        spaceId<br>      }<br>      providerMetadata<br>    }<br>    id<br>  }<br>}<br></pre><p>LLMIntegrationsTableOrgSpacesQuery</p><pre>query LLMIntegrationsTableOrgsSpacesQuery {<br>  account {<br>    organizations(first: 200) {<br>      edges {<br>        node {<br>          id<br>          name<br>          spaces(first: 500) {<br>            edges {<br>              node {<br>                id<br>                name<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}</pre><p>TracesStatsBarQuery</p><pre>query LLMIntegrationsTableOrgsSpacesQuery {<br>  account {<br>    organizations(first: 200) {<br>      edges {<br>        node {<br>          id<br>          name<br>          spaces(first: 500) {<br>            edges {<br>              node {<br>                id<br>                name<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;traceDataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-11-17T18:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;parent_id = null&quot;<br>  },<br>  &quot;baseDataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-11-17T18:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;&quot;<br>  },<br>  &quot;timeZone&quot;: &quot;Asia/Calcutta&quot;,<br>  &quot;modelId&quot;: &quot;TW9kZWw6NTA0NzEwOTE3ODo4dExB&quot;<br>}</pre><p>SpanContextQuery</p><pre>query SpansContentQuery(<br>  $id: ID!<br>  $dataset: ModelDatasetInput!<br>  $sort: SpanSort!<br>  $count: Int!<br>  $cursor: String<br>  $columnNames: [String!]!<br>  $includeRootSpans: Boolean!<br>  $includeTotalTokenCount: Boolean!<br>  $includeTotalCost: Boolean!<br>  $truncateStringLength: Int<br>) {<br>  node(id: $id) {<br>    __typename<br>    ... on Model {<br>      spans: spanRecords(first: $count, after: $cursor, dataset: $dataset, sort: $sort, columnNames: $columnNames, includeRootSpans: $includeRootSpans, truncateStringLength: $truncateStringLength) {<br>        pageInfo {<br>          hasNextPage<br>          endCursor<br>        }<br>        edges {<br>          span: node {<br>            name<br>            spanKind<br>            statusCode<br>            startTime<br>            parentId<br>            latencyMs<br>            traceId<br>            sessionId<br>            spanId<br>            traceTokenCounts @include(if: $includeTotalTokenCount) {<br>              aggregateCompletionTokenCount<br>              aggregatePromptTokenCount<br>              aggregateTotalTokenCount<br>            }<br>            totalCost @include(if: $includeTotalCost) {<br>              aggregateTotalCost<br>              aggregatePromptCost<br>              aggregateCompletionCost<br>            }<br>            columns {<br>              name<br>              value {<br>                __typename<br>                ... on CategoricalDimensionValue {<br>                  stringValue: value<br>                }<br>                ... on NumericDimensionValue {<br>                  numericValue: value<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;id&quot;: &quot;TW9kZWw6NTA0NzEwOTE3ODo4dExB&quot;,<br>  &quot;dataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-11-09T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-11-17T18:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;&quot;<br>  },<br>  &quot;sort&quot;: {<br>    &quot;column&quot;: &quot;start_time&quot;,<br>    &quot;dir&quot;: &quot;DESC&quot;<br>  },<br>  &quot;count&quot;: 20,<br>  &quot;cursor&quot;: null,<br>  &quot;columnNames&quot;: [<br>    &quot;attributes.openinference.span.kind&quot;,<br>    &quot;name&quot;,<br>    &quot;attributes.input.value&quot;,<br>    &quot;attributes.output.value&quot;,<br>    &quot;start_time&quot;,<br>    &quot;latency_ms&quot;,<br>    &quot;attributes.llm.token_count.total&quot;,<br>    &quot;attributes.llm.token_count.prompt&quot;,<br>    &quot;:arize-computed:tokenization.prompt.encoder&quot;,<br>    &quot;:arize-computed:tokenization.prompt.method&quot;,<br>    &quot;attributes.llm.token_count.completion&quot;,<br>    &quot;:arize-computed:tokenization.completion.encoder&quot;,<br>    &quot;:arize-computed:tokenization.completion.method&quot;,<br>    &quot;status_code&quot;<br>  ],<br>  &quot;includeRootSpans&quot;: true,<br>  &quot;includeTotalTokenCount&quot;: true,<br>  &quot;includeTotalCost&quot;: false,<br>  &quot;truncateStringLength&quot;: null<br>}</pre><p>TracingCardCountQuery</p><pre>query TracingCardCountQuery(<br>  $traceDataset: ModelDatasetInput!<br>  $baseDataset: ModelDatasetInput!<br>  $timeZone: String!<br>  $modelId: ID!<br>) {<br>  node(id: $modelId) {<br>    __typename<br>    ... on Model {<br>      totalTrafficTraces: totalTraffic(timeZone: $timeZone, dataset: $traceDataset)<br>      totalTrafficBase: totalTraffic(timeZone: $timeZone, dataset: $baseDataset)<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;traceDataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-08-31T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-09-08T07:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;parent_id = null&quot;<br>  },<br>  &quot;baseDataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-08-31T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-09-08T07:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;&quot;<br>  },<br>  &quot;timeZone&quot;: &quot;Asia/Calcutta&quot;,<br>  &quot;modelId&quot;: &quot;TW9kZWw6NTA0NzEwOTE3ODo4dExB&quot;<br>}</pre><p>SessionContextQuery</p><pre>query SessionsContentQuery(<br>  $id: ID!<br>  $dataset: ModelDatasetInput!<br>  $sessionSort: LLMSessionSort<br>) {<br>  node(id: $id) {<br>    __typename<br>    ... on Model {<br>      ...SessionsContent_llmSessions_3V7koc<br>    }<br>    id<br>  }<br>}<br><br>fragment SessionsContent_llmSessions_3V7koc on Model {<br>  llmSessions(first: 10, dataset: $dataset, sort: $sessionSort) {<br>    edges {<br>      node {<br>        firstInput {<br>          value<br>        }<br>        lastOutput {<br>          value<br>        }<br>        userIds<br>        traceCount<br>        sessionId<br>        traceTokenCounts {<br>          aggregatePromptTokenCount<br>          aggregateCompletionTokenCount<br>          aggregateTotalTokenCount<br>        }<br>        sessionDurationMs<br>        sessionStartTime<br>        customAggregations {<br>          name<br>          value {<br>            __typename<br>            ... on CategoricalDimensionValue {<br>              stringValue: value<br>            }<br>          }<br>        }<br>        __typename<br>      }<br>      cursor<br>    }<br>    pageInfo {<br>      endCursor<br>      hasNextPage<br>    }<br>  }<br>  id<br>}<br><br>{<br>  &quot;id&quot;: &quot;TW9kZWw6NTA0NzEwOTE3ODo4dExB&quot;,<br>  &quot;dataset&quot;: {<br>    &quot;startTime&quot;: &quot;2025-08-30T18:30:00.000Z&quot;,<br>    &quot;endTime&quot;: &quot;2025-09-09T07:29:59.999Z&quot;,<br>    &quot;externalModelVersionIds&quot;: [],<br>    &quot;externalBatchIds&quot;: [],<br>    &quot;environmentName&quot;: &quot;tracing&quot;,<br>    &quot;queryFilter&quot;: &quot;&quot;<br>  },<br>  &quot;sessionSort&quot;: {<br>    &quot;column&quot;: &quot;sessionStartTime&quot;,<br>    &quot;dir&quot;: &quot;DESC&quot;<br>  }<br>}</pre><p>ModelOverviewPageQuery</p><pre>query ModelOverviewPageQuery(<br>  $id: ID!<br>) {<br>  node(id: $id) {<br>    __typename<br>    ... on Model {<br>      modelAutoBaselineConfig {<br>        id<br>        environmentName<br>      }<br>      modelEnvironments {<br>        id<br>        name<br>        environmentId<br>        startDate<br>        endDate<br>      }<br>      modelPrimaryBaseline {<br>        userId<br>        id<br>        referenceType<br>        baselineType<br>        modelVersionEnvironmentBatch {<br>          id<br>          externalBatchId<br>          startDate<br>          endDate<br>          modelVersionEnvironment {<br>            name<br>            modelVersion<br>            id<br>          }<br>        }<br>        filteredBaseline {<br>          modelEnvironmentName<br>          filteredMovingWindowSeconds<br>          filteredMovingWindowDelaySeconds<br>          filteredStartDate<br>          filteredEndDate<br>        }<br>      }<br>      modelReferenceDataset {<br>        referenceSource<br>        referenceBaselineId<br>        referenceValue {<br>          __typename<br>          ... on ModelDataset {<br>            startTime<br>            endTime<br>            environmentName<br>            externalModelVersionIds<br>            externalBatchIds<br>          }<br>          ... on MovingModelDataset {<br>            movingWindowMs<br>            movingWindowDelayMs<br>            environmentName<br>            externalModelVersionIds<br>            externalBatchIds<br>          }<br>        }<br>      }<br>      modelCorpusDataset {<br>        __typename<br>        startTime<br>        endTime<br>        environmentName<br>        externalModelVersionIds<br>        externalBatchIds<br>      }<br>      performanceConfigs {<br>        performanceMetric<br>        predictionValueClass {<br>          id<br>          name<br>          __typename<br>        }<br>        threshold<br>        operator<br>        defaultAtKValue<br>        customMetric {<br>          id<br>          name<br>          description<br>          metric<br>          requiresPositiveClass<br>          __typename<br>        }<br>        useDefaultActuals<br>      }<br>      customMetrics {<br>        edges {<br>          node {<br>            id<br>            name<br>            description<br>            metric<br>            requiresPositiveClass<br>            __typename<br>          }<br>        }<br>      }<br>      driftConfigs {<br>        evaluationWindowLengthMs<br>      }<br>      ...ModelOverviewPageDatasetsCard_datasets<br>    }<br>    id<br>  }<br>}<br><br>fragment ModelOverviewPageDatasetsCard_datasets on Model {<br>  id<br>  production: modelVersionEnvironmentBatches(modelEnvironmentName: production, sort: [{column: updatedAt, dir: DESC}], first: 1) {<br>    ...ModelOverviewPageDatasetsCard_modelLineageInfo<br>    id<br>  }<br>  training: modelVersionEnvironmentBatches(modelEnvironmentName: training, sort: [{column: updatedAt, dir: DESC}], first: 1) {<br>    ...ModelOverviewPageDatasetsCard_modelLineageInfo<br>    id<br>  }<br>  validation: modelVersionEnvironmentBatches(modelEnvironmentName: validation, sort: [{column: updatedAt, dir: DESC}], first: 1) {<br>    ...ModelOverviewPageDatasetsCard_modelLineageInfo<br>    id<br>  }<br>}<br><br>fragment ModelOverviewPageDatasetsCard_modelLineageInfo on ModelLineageEntity {<br>  environmentName<br>  startDate<br>  endDate<br>  externalBatchId<br>  externalVersionId<br>  modelVersionId<br>  updatedAt<br>}<br><br>{<br>  &quot;id&quot;: &quot;TW9kZWw6NTA4NTY4NzEzNzpkT0hL&quot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eac1cad2c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arize GraphQL Queries]]></title>
            <link>https://medium.com/@forswayamnptelcourse/arize-graphql-queries-1665b49f9596?source=rss-ca1017950450------2</link>
            <guid isPermaLink="false">https://medium.com/p/1665b49f9596</guid>
            <dc:creator><![CDATA[sai]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 07:53:50 GMT</pubDate>
            <atom:updated>2025-11-17T07:53:50.372Z</atom:updated>
            <content:encoded><![CDATA[<p>AppQuery &amp; OrgSpaceMenuButtonQuery</p><pre>query AppQuery {<br>  viewer {<br>    id<br>    user {<br>      id<br>      name<br>      email<br>      accountRole<br>      permissions<br>      graphQLApiKey<br>    }<br>  }<br>  account {<br>    id<br>    name<br>    pricingTier<br>  }<br>}<br></pre><pre><br>query OrgSpaceMenuButtonQuery {<br>  account {<br>    organizations(first: 100) {<br>      edges {<br>        node {<br>          id<br>          name<br>          ...OrgSpaceMenuButtonFragment<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>fragment OrgSpaceMenuButtonFragment on AccountOrganization {<br>  id<br>  name<br>  spaces(first: 500) {<br>    edges {<br>      node {<br>        id<br>        name<br>      }<br>    }<br>  }<br>}</pre><p>SpaceRootQuery</p><pre>query SpaceRootProviderQuery(<br>  $spaceId: ID!<br>) {<br>  currentSpace: node(id: $spaceId) {<br>    __typename<br>    ... on Space {<br>      liveEnabled<br>      dataFabricEnabledSpace<br>      models(first: 50) {<br>        edges {<br>          node {<br>            modelType<br>            id<br>          }<br>        }<br>      }<br>      demoModels: models(first: 50, filter: {include: {isDemoModel: true}}) {<br>        edges {<br>          node {<br>            modelType<br>            id<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;spaceId&quot;: &quot;U3BhY2U6MjMwMTk6ZTMxeg==&quot;<br>}</pre><p>useOrganizationalLimit</p><pre>query useOrganizationLimitWarningNotificationQuery(<br>  $enableLimits: Boolean!<br>) {<br>  account @include(if: $enableLimits) {<br>    id<br>    tierLimits {<br>      gateType<br>      limitValue<br>      belowLimit<br>    }<br>  }<br>}<br><br>{<br>  &quot;enableLimits&quot;: true<br>}</pre><p>CreateOrgModalQuery</p><pre>query CreateOrganizationModalQuery {<br>  viewer {<br>    user {<br>      id<br>    }<br>    id<br>  }<br>  account {<br>    id<br>    ...CreateOrganizationModal_users<br>    organizations {<br>      edges {<br>        node {<br>          name<br>          id<br>        }<br>      }<br>    }<br>  }<br>}<br><br>fragment CreateOrganizationModal_users on Account {<br>  users(first: 50, search: &quot;&quot;) {<br>    edges {<br>      node {<br>        accountRole<br>        id<br>        email<br>        __typename<br>      }<br>      cursor<br>    }<br>    pageInfo {<br>      endCursor<br>      hasNextPage<br>    }<br>  }<br>  id<br>}</pre><p>CreateSpaceModalQuery</p><pre>query CreateSpaceModalQuery(<br>  $accountOrganizationId: ID!<br>) {<br>  viewer {<br>    user {<br>      id<br>    }<br>    id<br>  }<br>  node(id: $accountOrganizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      ...CreateSpaceModal_orgMembers<br>      spaces {<br>        edges {<br>          node {<br>            name<br>            id<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>fragment CreateSpaceModal_orgMembers on AccountOrganization {<br>  accountOrganizationMembers(first: 50, search: &quot;&quot;) {<br>    edges {<br>      node {<br>        user {<br>          id<br>          email<br>          accountRole<br>        }<br>        role<br>        id<br>        __typename<br>      }<br>      cursor<br>    }<br>    totalCount<br>    pageInfo {<br>      endCursor<br>      hasNextPage<br>    }<br>  }<br>  id<br>}<br><br>{<br>  &quot;accountOrganizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;<br>}</pre><p>OrganizationAuthContextQuery</p><pre>query OrganizationAuthContextQuery(<br>  $organizationId: ID!<br>) {<br>  currentOrganization: node(id: $organizationId) {<br>    __typename<br>    ... on AccountOrganization {<br>      viewerAccess: _access {<br>        permissions<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;organizationId&quot;: &quot;QWNjb3VudE9yZ2FuaXphdGlvbjoyMjAzNTpGZ09l&quot;<br>}</pre><p>DashboardPageRootQuery</p><pre>query DashboardPageRootQuery(<br>  $id: ID!<br>) {<br>  dashboard: node(id: $id) {<br>    __typename<br>    ... on Dashboard {<br>      id<br>      name<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;id&quot;: &quot;RGFzaGJvYXJkOjIzODEyOk80NlE=&quot;<br>}</pre><p>SpaceAuthContextQuery</p><pre>query SpaceAuthContextQuery(<br>  $spaceId: ID!<br>) {<br>  currentSpace: node(id: $spaceId) {<br>    __typename<br>    ... on Space {<br>      credentials {<br>        apiKey<br>      }<br>      viewerAccess: _access {<br>        permissions<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;spaceId&quot;: &quot;U3BhY2U6MjMwMTk6ZTMxeg==&quot;<br>}</pre><p>AuthContextQuery</p><pre>query AuthContextQuery {<br>  viewer {<br>    user {<br>      accountRole<br>      id<br>    }<br>    id<br>  }<br>}</pre><p>DashboardPageQuery</p><pre>query DashboardPageQuery(<br>  $id: ID!<br>  $spaceId: ID!<br>) {<br>  typeaheadRoot(spaceId: $spaceId) {<br>    id<br>  }<br>  dashboard: node(id: $id) {<br>    __typename<br>    ... on Dashboard {<br>      id<br>      name<br>      status<br>      creator {<br>        id<br>        name<br>      }<br>      models {<br>        edges {<br>          node {<br>            id<br>            externalModelId<br>            modelType<br>            modelEnvironments {<br>              name<br>              id<br>            }<br>            modelCapabilities {<br>              hasActuals<br>            }<br>          }<br>        }<br>      }<br>      statisticWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            customStatisticText<br>          }<br>        }<br>      }<br>      barChartWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            performanceMetric<br>            yMin<br>            yMax<br>            sortOrder<br>            yAxisLabel<br>            topN<br>            showLegend<br>            legendPlacement<br>            xAxisLabel<br>            xAxisTilt<br>            overwriteGlobalTime<br>            timeRangeKey<br>            timezone<br>            startTime<br>            endTime<br>            timeSeriesDataGranularity<br>            fontSize<br>          }<br>        }<br>      }<br>      lineChartWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            yMin<br>            yMax<br>            yAxisLabel<br>            showLegend<br>            legendPlacement<br>            xAxisLabel<br>            xAxisTilt<br>            overwriteGlobalTime<br>            timeRangeKey<br>            timezone<br>            startTime<br>            endTime<br>            timeSeriesDataGranularity<br>            fontSize<br>          }<br>        }<br>      }<br>      driftLineChartWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            yMin<br>            yMax<br>            showLegend<br>            legendPlacement<br>            xAxisLabel<br>            xAxisTilt<br>            overwriteGlobalTime<br>            timeRangeKey<br>            timezone<br>            startTime<br>            endTime<br>            timeSeriesDataGranularity<br>            fontSize<br>          }<br>        }<br>      }<br>      textWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            content<br>          }<br>        }<br>      }<br>      experimentChartWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            fontSize<br>            showLegend<br>            legendPlacement<br>            xAxisLabel<br>            xAxisTilt<br>          }<br>        }<br>      }<br>      monitorLineChartWidgets {<br>        edges {<br>          node {<br>            id<br>            title<br>            gridPosition<br>            creationStatus<br>            yMin<br>            yMax<br>            monitor {<br>              __typename<br>              ... on WidgetMonitor {<br>                id<br>                name<br>                monitorTypeGlobalId<br>              }<br>              ... on MonitorEntityState {<br>                code<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;id&quot;: &quot;RGFzaGJvYXJkOjIzODEyOk80NlE=&quot;,<br>  &quot;spaceId&quot;: &quot;U3BhY2U6MjMwMTk6ZTMxeg==&quot;<br>}</pre><p>VoulmeLimitWarningAlertQuery</p><pre>query VolumeLimitWarningAlertQuery {<br>  account {<br>    id<br>    tierLimits {<br>      gateType<br>      currentValue<br>      limitValue<br>    }<br>  }<br>}</pre><p>DashboardModelSelectorQuery</p><pre>query DashboardModelSelectorQuery(<br>  $spaceId: ID!<br>  $dashboardId: ID!<br>) {<br>  typeaheadRoot(spaceId: $spaceId) {<br>    id<br>    ...DashboardModelSelector_typeaheadRoot_3DRocR<br>  }<br>}<br><br>fragment DashboardModelSelector_typeaheadRoot_3DRocR on TypeaheadRoot {<br>  dashboardModels(first: 50, dashboardId: $dashboardId, searchTerm: &quot;&quot;) {<br>    edges {<br>      node {<br>        id<br>        externalModelId<br>        modelType<br>        modelCapabilities {<br>          hasActuals<br>        }<br>        __typename<br>      }<br>      cursor<br>    }<br>    pageInfo {<br>      endCursor<br>      hasNextPage<br>    }<br>  }<br>  id<br>}<br><br>{<br>  &quot;spaceId&quot;: &quot;U3BhY2U6MjMwMTk6ZTMxeg==&quot;,<br>  &quot;dashboardId&quot;: &quot;RGFzaGJvYXJkOjIzODEyOk80NlE=&quot;<br>}</pre><p>JumpToLatestDashboardDataQuery</p><pre>query JumpToLatestDashboardDataQuery(<br>  $dashboardId: ID!<br>) {<br>  dashboard: node(id: $dashboardId) {<br>    __typename<br>    ... on Dashboard {<br>      models {<br>        edges {<br>          node {<br>            modelEnvironments {<br>              name<br>              startDate<br>              endDate<br>              modelVersionEnvironmentMetadataBookends {<br>                startDate<br>                endDate<br>              }<br>              id<br>            }<br>            id<br>          }<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>{<br>  &quot;dashboardId&quot;: &quot;RGFzaGJvYXJkOjIzODEyOk80NlE=&quot;<br>}<br></pre><p>LineChartWidgetQuery</p><pre>query LineChartWidgetQuery(<br>  $id: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>  $filters: [DashboardWidgetFilterItem!]!<br>  $timeZone: String!<br>  $isMonitorWidget: Boolean!<br>  $timeSeriesDataGranularity: DataGranularity!<br>) {<br>  widget: node(id: $id) {<br>    __typename<br>    ... on LineChartWidget {<br>      id<br>      title<br>      yMin<br>      yMax<br>      yAxisLabel<br>      monitor {<br>        __typename<br>        ... on WidgetMonitor {<br>          id<br>          name<br>          monitorTypeGlobalId<br>        }<br>        ... on MonitorEntityState {<br>          code<br>        }<br>      }<br>      gridPosition<br>      creationStatus<br>      ...EditLineChartWidgetForm_widget<br>      ...LineChartWidget_widget_WVXNE<br>      ...EditMonitorLineChartWidgetForm_widget<br>    }<br>    id<br>  }<br>}<br><br>fragment EditLineChartWidgetForm_widget on LineChartWidget {<br>  id<br>  title<br>  gridPosition<br>  creationStatus<br>  timeSeriesMetricType<br>  yMin<br>  yMax<br>  yAxisLabel<br>  startTime<br>  endTime<br>  timezone<br>  timeSeriesDataGranularity<br>  overwriteGlobalTime<br>  xAxisLabel<br>  xAxisTilt<br>  fontSize<br>  showLegend<br>  legendPlacement<br>  timeRangeKey<br>  plots {<br>    title<br>    position<br>    splitByEnabled<br>    splitByDimension<br>    splitByDimensionCategory<br>    splitByOverallMetricEnabled<br>    cohorts<br>    colors<br>    model {<br>      id<br>      externalModelId<br>      modelType<br>      __typename<br>      modelPrimaryBaseline {<br>        userId<br>        id<br>        referenceType<br>        baselineType<br>        modelVersionEnvironmentBatch {<br>          id<br>          externalBatchId<br>          startDate<br>          endDate<br>          modelVersionEnvironment {<br>            name<br>            modelVersion<br>            id<br>          }<br>        }<br>        filteredBaseline {<br>          modelEnvironmentName<br>          filteredMovingWindowSeconds<br>          filteredMovingWindowDelaySeconds<br>          filteredStartDate<br>          filteredEndDate<br>        }<br>      }<br>    }<br>    modelVersions {<br>      id<br>      externalVersionId<br>      createdAt<br>      __typename<br>    }<br>    modelEnvironmentName<br>    modelVersionEnvironmentBatches {<br>      id<br>      externalBatchId<br>      startDate<br>      endDate<br>      __typename<br>      externalVersionId<br>      environmentName<br>    }<br>    dimension {<br>      id<br>      name<br>      dataType<br>      category<br>      __typename<br>    }<br>    dimensionCategory<br>    customMetric {<br>      id<br>      name<br>      description<br>      metric<br>      requiresPositiveClass<br>      __typename<br>    }<br>    metric<br>    predictionValueClass {<br>      id<br>      name<br>      __typename<br>    }<br>    filters {<br>      id<br>      filterType<br>      operator<br>      dimension {<br>        id<br>        name<br>        dataType<br>        category<br>        __typename<br>      }<br>      dimensionValues {<br>        id<br>        value<br>        __typename<br>      }<br>      binaryValues<br>      numericValues<br>      categoricalValues<br>    }<br>    rankingAtK<br>    comparisonDataset {<br>      referenceSource<br>      referenceBaselineId<br>      referenceValue {<br>        __typename<br>        ... on ModelDataset {<br>          startTime<br>          endTime<br>          environmentName<br>          externalModelVersionIds<br>          externalBatchIds<br>          modelVersionEnvironmentMetadataId<br>        }<br>        ... on MovingModelDataset {<br>          movingWindowMs<br>          movingWindowDelayMs<br>          environmentName<br>          externalModelVersionIds<br>          externalBatchIds<br>          modelVersionEnvironmentMetadataId<br>        }<br>      }<br>    }<br>    id<br>  }<br>}<br><br>fragment EditMonitorLineChartWidgetForm_widget on LineChartWidget {<br>  id<br>  title<br>  gridPosition<br>  creationStatus<br>  timeSeriesMetricType<br>  yMin<br>  yMax<br>  yAxisLabel<br>  startTime<br>  endTime<br>  timezone<br>  timeSeriesDataGranularity<br>  overwriteGlobalTime<br>  xAxisLabel<br>  xAxisTilt<br>  fontSize<br>  showLegend<br>  legendPlacement<br>  timeRangeKey<br>  config {<br>    axisBottom {<br>      legend<br>    }<br>    axisLeft {<br>      legend<br>    }<br>    curve<br>    xScale {<br>      max<br>      min<br>      scaleType<br>      format<br>      precision<br>    }<br>    yScale {<br>      max<br>      min<br>      scaleType<br>      stacked<br>    }<br>  }<br>  monitor {<br>    __typename<br>    ... on WidgetMonitor {<br>      id<br>      monitorTypeGlobalId<br>      name<br>      model {<br>        id<br>        externalModelId<br>        modelType<br>        __typename<br>        modelPrimaryBaseline {<br>          userId<br>          id<br>          referenceType<br>          baselineType<br>          modelVersionEnvironmentBatch {<br>            id<br>            externalBatchId<br>            startDate<br>            endDate<br>            modelVersionEnvironment {<br>              name<br>              modelVersion<br>              id<br>            }<br>          }<br>          filteredBaseline {<br>            modelEnvironmentName<br>            filteredMovingWindowSeconds<br>            filteredMovingWindowDelaySeconds<br>            filteredStartDate<br>            filteredEndDate<br>          }<br>        }<br>      }<br>    }<br>    ... on MonitorEntityState {<br>      code<br>    }<br>  }<br>}<br><br>fragment LineChartWidget_widget_WVXNE on LineChartWidget {<br>  id<br>  title<br>  gridPosition<br>  creationStatus<br>  yMin<br>  yMax<br>  yAxisLabel<br>  startTime<br>  endTime<br>  timezone<br>  timeSeriesDataGranularity<br>  overwriteGlobalTime<br>  xAxisLabel<br>  xAxisTilt<br>  fontSize<br>  showLegend<br>  legendPlacement<br>  timeRangeKey<br>  plots {<br>    model {<br>      id<br>      modelType<br>      externalModelId<br>    }<br>    position<br>    metric<br>    dimension {<br>      name<br>      category<br>      dataType<br>      id<br>    }<br>    predictionValueClass {<br>      name<br>      id<br>    }<br>    cohorts<br>    splitByEnabled<br>    splitByDimensionCategory<br>    splitByOverallMetricEnabled<br>    customMetric {<br>      id<br>      name<br>    }<br>    modelEnvironmentName<br>    colors<br>    filters {<br>      id<br>      filterType<br>      operator<br>      dimension {<br>        id<br>        name<br>        dataType<br>        category<br>        __typename<br>      }<br>      dimensionValues {<br>        id<br>        value<br>        __typename<br>      }<br>      binaryValues<br>      numericValues<br>      categoricalValues<br>    }<br>    id<br>  }<br>  lines(startDate: $startDate, endDate: $endDate, filters: $filters, timeZone: $timeZone, timeSeriesDataGranularity: $timeSeriesDataGranularity) @skip(if: $isMonitorWidget) {<br>    key<br>    dataWindows {<br>      metricDisplayDate<br>      metricValue<br>      calculationWindowStart<br>      calculationWindowEnd<br>    }<br>  }<br>  driftDistribution(startDate: $startDate, endDate: $endDate, timeZone: $timeZone, filters: $filters, first: 30, barsStartCursor: 0) {<br>    edges {<br>      node {<br>        keysAndValues {<br>          k<br>          v<br>          vType<br>          secondaryValue<br>          secondaryValueType<br>          secondaryValueColorIndex<br>          plotKey<br>        }<br>        evalMetricMin<br>        evalMetricMax<br>        __typename<br>      }<br>      cursor<br>    }<br>    total<br>    pageInfo {<br>      startCursor<br>      endCursor<br>      hasNextPage<br>      hasPreviousPage<br>    }<br>  }<br>  monitor @include(if: $isMonitorWidget) {<br>    __typename<br>    ... on WidgetMonitor {<br>      id<br>      monitorTypeGlobalId<br>      primaryMetricWindow {<br>        windowLengthMs<br>        startDelaySeconds<br>        id<br>      }<br>      metricHistory(startTime: $startDate, endTime: $endDate, timeZone: $timeZone, timeSeriesDataGranularity: $timeSeriesDataGranularity) {<br>        __typename<br>        ... on TimeSeriesWithThresholdDataType {<br>          key<br>          dataWindows {<br>            metricDisplayDate<br>            metricValue<br>            calculationWindowStart<br>            calculationWindowEnd<br>          }<br>          thresholdDataWindows {<br>            metricDisplayDate<br>            metricValue<br>            calculationWindowStart<br>            calculationWindowEnd<br>          }<br>        }<br>        ... on DriftCalculationError {<br>          errorCode: code<br>        }<br>      }<br>      dynamicAutoThresholdEnabled<br>      threshold<br>      threshold2<br>      operator2<br>      thresholdMode<br>      autoThresholdLookbackSeconds<br>      thresholdCalculationType<br>      manualEvaluationEnabled<br>      operator<br>      metric<br>      model {<br>        id<br>        externalModelId<br>      }<br>    }<br>    ... on MonitorEntityState {<br>      code<br>    }<br>  }<br>}<br><br>{<br>  &quot;id&quot;: &quot;TGluZUNoYXJ0V2lkZ2V0OjI5NzU1NjpURnJR&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-10T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T23:59:59.000Z&quot;,<br>  &quot;filters&quot;: [],<br>  &quot;timeZone&quot;: &quot;Asia/Calcutta&quot;,<br>  &quot;isMonitorWidget&quot;: false,<br>  &quot;timeSeriesDataGranularity&quot;: &quot;hour&quot;<br>}<br></pre><p>StaticWidgetQuery</p><pre>query StatisticWidgetQuery(<br>  $id: ID!<br>  $startDate: DateTime!<br>  $endDate: DateTime!<br>  $filters: [DashboardWidgetFilterItem!]!<br>) {<br>  widget: node(id: $id) {<br>    __typename<br>    ... on StatisticWidget {<br>      id<br>      title<br>      creationStatus<br>      gridPosition<br>      ...EditStatisticWidgetForm_widget<br>      ...StatisticWidget_widget_38s3uv<br>    }<br>    id<br>  }<br>}<br><br>fragment EditStatisticWidgetForm_widget on StatisticWidget {<br>  id<br>  creationStatus<br>  gridPosition<br>  title<br>  model {<br>    id<br>    externalModelId<br>    modelType<br>    __typename<br>  }<br>  filters {<br>    id<br>    filterType<br>    operator<br>    dimension {<br>      id<br>      name<br>      dataType<br>      category<br>      __typename<br>    }<br>    dimensionValues {<br>      id<br>      value<br>      __typename<br>    }<br>    binaryValues<br>    numericValues<br>    categoricalValues<br>  }<br>  modelVersions {<br>    id<br>    externalVersionId<br>    createdAt<br>    __typename<br>  }<br>  modelEnvironmentName<br>  modelVersionEnvironmentBatches {<br>    id<br>    externalBatchId<br>    startDate<br>    endDate<br>    __typename<br>    externalVersionId<br>    environmentName<br>  }<br>  dimension {<br>    id<br>    name<br>    dataType<br>    category<br>    __typename<br>  }<br>  dimensionCategory<br>  performanceMetric<br>  aggregation<br>  predictionValueClass {<br>    id<br>    name<br>    __typename<br>  }<br>  timeSeriesMetricType<br>  customMetric {<br>    id<br>    name<br>    description<br>    metric<br>    requiresPositiveClass<br>    __typename<br>  }<br>  rankingAtK<br>  customStatisticText<br>}<br><br>fragment StatisticWidget_widget_38s3uv on StatisticWidget {<br>  id<br>  title<br>  gridPosition<br>  creationStatus<br>  timeSeriesMetricType<br>  dimensionCategory<br>  aggregation<br>  customStatisticText<br>  dimension {<br>    id<br>    name<br>    dataType<br>    category<br>    __typename<br>  }<br>  performanceMetric<br>  predictionValueClass {<br>    id<br>    name<br>    __typename<br>  }<br>  modelEnvironmentName<br>  model {<br>    id<br>    externalModelId<br>    modelType<br>    modelCapabilities {<br>      hasActuals<br>    }<br>    __typename<br>  }<br>  customMetric {<br>    id<br>    name<br>    description<br>    metric<br>    requiresPositiveClass<br>    __typename<br>  }<br>  statisticValue(startDate: $startDate, endDate: $endDate, filters: $filters)<br>}<br><br>{<br>  &quot;id&quot;: &quot;U3RhdGlzdGljV2lkZ2V0OjE4NDE0NzplalEx&quot;,<br>  &quot;startDate&quot;: &quot;2025-11-10T18:30:00.000Z&quot;,<br>  &quot;endDate&quot;: &quot;2025-11-17T23:59:59.000Z&quot;,<br>  &quot;filters&quot;: []<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1665b49f9596" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>