<?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 venkatesh babu sekar on Medium]]></title>
        <description><![CDATA[Stories by venkatesh babu sekar on Medium]]></description>
        <link>https://medium.com/@ve.sekar?source=rss-957b4eb4985d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RfK9W6nYFcGV-CIU</url>
            <title>Stories by venkatesh babu sekar on Medium</title>
            <link>https://medium.com/@ve.sekar?source=rss-957b4eb4985d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:04:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ve.sekar/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[One Surface, Many Engines: Designing a Desktop AI Workspace]]></title>
            <link>https://medium.com/@ve.sekar/one-surface-many-engines-designing-a-desktop-ai-workspace-5500d00ce9d5?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5500d00ce9d5</guid>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 01:42:39 GMT</pubDate>
            <atom:updated>2026-07-20T01:42:39.461Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The model is not the product. The composition is: a thin desktop surface, an orchestrator that picks capabilities, engines behind stable contracts, and security decided exactly once. The design, with the honest ledger.</em></p><p><em>A capstone to my two earlier series: four parts on building a conversational analytics engine, two on building memory for AI agents. This is the surface that composes them. ~11 min read.</em></p><p>Count the AI tools in your working day. A chat assistant in a browser tab. A coding agent in the terminal. A BI tool that answers data questions. An automation platform gluing your SaaS apps together. Maybe an email plugin.</p><p>Each one is impressive alone. Together they are a mess: five subscriptions, five contexts that do not share what they know, five places your preferences have to be re-learned, and zero of them able to finish a task that crosses two of their territories. Ask “pull last quarter’s numbers and draft a follow-up to the customer who slipped” and you become the integration layer, copy-pasting between tools that will never meet.</p><p>For this class of composed work, the models stopped being the bottleneck a while ago. <strong>The composition is the bottleneck.</strong> This article is the design for that composition: a desktop workspace where one chat surface routes work to specialized engines, the engines share one memory and one security model, and the whole thing degrades honestly when a piece fails.</p><p>The honesty box first, as always in this series.</p><p><strong>Where this stands, up front:</strong></p><ul><li>The <strong>analytics engine</strong> (my first series): <strong>ships today</strong>.</li><li>The <strong>memory engine</strong> (my second series): <strong>design complete, build under way</strong>.</li><li>The <strong>desktop surface in this article</strong>: <strong>design complete, early build</strong>, being built against frozen contracts with stand-ins for the engines that land later.</li><li>I publish the architecture while building it. Design review in public is a feature, not a risk, when the writing stays at the level of decisions and trade-offs. That is the level of this article.</li></ul><p><strong>TL;DR</strong></p><ul><li>The desktop is a <strong>thin surface</strong>: it holds no source data, no database drivers, no enterprise credentials. Data is queried where it lives.</li><li>An <strong>orchestrator</strong> picks a tool or skill per turn <strong>by description</strong>. There is no central intent classifier, on purpose: I built one once, and it became the bottleneck that degraded everything it routed.</li><li>Engines sit <strong>behind stable contracts</strong> over a standard protocol, with document retrieval riding behind the analytics engine’s contract. Adding an engine adds a contract, not a rewrite.</li><li><strong>Security is decided once</strong>, by an identity layer that issues a signed pass; every engine enforces it and none re-computes it. Denial is a typed answer, never a silently empty result.</li><li><strong>Skills are files.</strong> Capabilities arrive as readable, versioned markdown, proposed never auto-saved, and the system grows its own from repeated successful work.</li><li>Every request carries <strong>one trace id</strong> across every hop, and every seam has a defined failure behavior. No silent wrong answers.</li></ul><h3>Why a desktop app, and why thin</h3><p>Two decisions before any boxes get drawn.</p><p><strong>Why the desktop at all?</strong> Because that is where work actually happens: the files, the terminal, the editor, the clipboard, the meeting in the next window. A browser tab can chat; it cannot sit beside your repository, run a local model over your private notes, or keep your memory on hardware you control. The memory series made the privacy case: raw personal material should be distilled locally. A desktop app is how that promise is kept structurally.</p><p><strong>Why thin?</strong> Because the alternative is a fat client that accumulates credentials, cached data, and one-off integrations until it is a security liability with an update problem. The rule here is strict:</p><ul><li>The desktop holds <strong>no source data, no database drivers, no enterprise credentials, and no admin keys</strong>.</li><li>Data is <strong>queried in place</strong> (a file through an embedded query engine, a database through a connector, an enterprise source server-side) and only results flow back.</li><li>The user’s own model key lives in the <strong>operating system keychain</strong>, never in a config file.</li><li>The UI process cannot reach the network at all; every call goes through one audited path.</li></ul><p>A thin surface is also what makes the deployment story boring, in the good way: the same desktop talks to engines running locally first, in a company’s cloud later, or in an air-gapped environment eventually. What moves is the backends, never the app.</p><h3>The rules before the boxes</h3><p>Six principles do most of the architectural work. Everything in the diagrams below is a consequence of one of these.</p><ul><li><strong>Layered, not monolithic.</strong> Every piece talks to the next through a stable contract, and every piece is swappable: the model provider, the connector adapter, the storage engine. Swap a box, never rebuild the house.</li><li><strong>The LLM orchestrates capability; it never decides security.</strong> Choosing which tool fits a request is model work. Deciding who may see what is deterministic code, always.</li><li><strong>Decide access once, enforce it everywhere.</strong> One identity layer computes and signs an access pass; every engine verifies and applies it; no engine re-computes policy. One decider, many enforcers.</li><li><strong>Standards over inventions.</strong> Tools speak an open tool protocol (MCP). Skills are a portable markdown format. Auth is OAuth. Inventing a protocol is a tax every future integration pays.</li><li><strong>Fail visibly, never fabricate.</strong> Errors surface with a cause and a next step. Degradation is explicit, a caveat on the answer, never a guessed substitute for the answer.</li><li><strong>Production-grade from day one.</strong> Designed at the weight of a hundred users and a thousand tables, then built as a deliberately small slice of that design.</li></ul><blockquote>The one-line summary of the whole architecture: <strong>the orchestrator composes capability; the identity layer decides visibility; the engines do the work; and nothing pretends, when something fails, that it did not.</strong></blockquote><h3>The map</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPNa-AeqTylsdd94ye05tQ.png" /><figcaption><strong>Desktop Composition</strong></figcaption></figure><p><strong>How to read it: four planes.</strong></p><ul><li><strong>The surface</strong> (blue): the chat and coding panes, a generative UI that can render tables and forms instead of walls of text, and the orchestrator that owns each turn.</li><li><strong>The engines</strong> (green): the analytics engine from my first series, its document-retrieval companion, and the memory engine from my second. Each is a separate product behind a contract; the desktop is just their first consumer. Note the one asymmetry: document questions route <strong>through</strong> the analytics engine, not around it, because hybrid questions (“what does the deck say, and what are the actual numbers”) need both halves joined on the same entities. That decision came out of the first series.</li><li><strong>The security spine</strong> (red): one identity layer signs a pass; every engine independently honours it. No callbacks, no engine with special trust.</li><li><strong>The edges</strong> (amber): one connector port for every app and data source, a configurable model layer (your key, your endpoint, or a bundled local model), and a hand-off to a dedicated coding agent for deep multi-file work, because re-inventing a mature coding agent inside a chat app is how you ship a worse one.</li></ul><h3>Routing without a god-classifier</h3><p>The orchestrator’s job each turn: decide which capability this request needs. The tempting design is a central intent classifier, one model call that buckets every message. I am not building one, and the reason is a scar, not a theory: an earlier system of mine routed everything through a central classifier, and it became the single choke point that every new capability had to renegotiate. Adding a feature meant retraining the gatekeeper. Accuracy decayed as categories multiplied.</p><p>The design here inverts it. <strong>Routing is the model picking a tool by its description</strong>, the same way it picks any tool. Two stages, each owning a narrow decision:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJjB-vNXIb_RgunxoKOUOQ.png" /><figcaption><strong>Two Stage Intent</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Stage 1 lives in the orchestrator</strong> and is not a classifier: every tool and skill publishes a name and a description, and the model picks among them per turn. Adding a capability means <strong>adding a described tool</strong>, not retraining a router. At scale, retrieval narrows the candidate list before the model chooses.</li><li><strong>Stage 2 lives inside the analytics engine</strong> and owns only its own narrow decision: is this question structured, document-shaped, hybrid, or ambiguous? That keeps the engine’s expertise where the engine is.</li><li><strong>Clarify is a first-class outcome.</strong> An ambiguous question returns a disambiguation prompt, not an error and not a guess. Readers of my first series will recognize this as the same rule that governed entity resolution: ambiguity surfaces; it is never papered over.</li><li>Two execution styles coexist: an <strong>agentic path</strong> (the orchestrator’s loop, flexible and slower) and a <strong>deterministic path</strong> (the analytics engine’s fixed pipeline, fast and reproducible). Simple data questions take the fast path; open-ended work takes the loop. Choosing per request, instead of forcing everything through one style, is a large share of the latency story.</li></ul><h3>Skills: capabilities as files</h3><p>The second series ended with memory growing skills. Here is the other half: how the workspace stores, picks, and runs them.</p><p>A skill is a <strong>folder with a markdown file</strong> in an emerging cross-agent format: a name, a description, instructions, optionally some scripts. That mundane choice carries a lot:</p><ul><li><strong>Readable and diffable.</strong> A capability you can open, read, and version-control beats one buried in a fine-tune or a database row.</li><li><strong>Progressive disclosure.</strong> Only names and descriptions stay loaded; a skill’s body loads when it matches. Hundreds of skills cost almost nothing until used.</li><li><strong>Portable.</strong> The same file format works across the desktop and external coding agents, so a skill grown here is not locked in here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyXwE6kg6lBzGuPGAjJywA.png" /><figcaption><strong>Skill Lifecycle</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Create</strong> has three sources: the memory engine noticing a repeated successful procedure (the loop from my second series), an explicit “save this as a skill,” or a brain-dump a user dictates. All three end the same way: <strong>a proposed diff the user confirms. Nothing that changes future behavior saves itself.</strong></li><li><strong>Execute</strong> runs a skill’s scripts in a sandbox with two standing guardrails: <strong>draft, don’t send</strong> (anything outward-facing stops at a draft until a human approves) and <strong>no destructive surprises</strong> (the system cannot delete what it did not create without confirmation).</li><li><strong>Refine and graduate</strong> follow the maturity ladder from the memory series; improvement of a skill’s text is an offline, gated process whose output arrives as a reviewed change, never a silent hot-swap.</li><li><strong>Ownership matters in teams:</strong> a user owns their personal skills outright; shared skills can be toggled on or off but not silently edited by the people they were shared with.</li></ul><h3>Security decided once</h3><p>The first series established the rule inside one engine: the model never enforces access; deterministic code does. The workspace generalizes it to the whole system, because the moment several engines answer one request, per-engine security models stop composing.</p><p>The design: <strong>one identity layer is the only place access is computed.</strong> It resolves who is asking and what they may currently see, and issues a <strong>signed, short-lived pass</strong>. Every engine verifies the signature locally and applies the pass. No engine calls home to re-check, and no engine invents its own policy.</p><p>What that buys, concretely:</p><ul><li><strong>A regional sales manager</strong> asks for top accounts: the pass carries her row-level scope, the analytics engine compiles it into the query itself, and she sees her region. Her colleague without CRM access asks the same question and gets a <strong>typed denial</strong>, not an empty table that reads like “you have no accounts.” The difference between those two outcomes is the difference between a security model and a security accident.</li><li><strong>Revocation propagates.</strong> When a grant is pulled, the next request carries a pass without it, and every engine, including memory, stops surfacing what depended on it. The memory series covered why that matters: remembered derivatives of revoked data are the leak nobody tests for.</li><li><strong>Connected apps narrow the blast radius.</strong> The tools available to any turn are the intersection of three sets: what the user connected, what scopes they granted, and what the pass allows. An agent cannot touch an app you never connected, and credentials are fetched only when a tool is actually invoked.</li><li><strong>Fail closed.</strong> If the identity layer is unreachable, the system serves only the user’s own ungated data and says why the rest is unavailable. Absence of a pass always means less data, never a bypass.</li></ul><blockquote>Security here is an architecture property, not a feature checkbox: one decider, many enforcers, typed denials, and gates that default to deny. The model is never in that loop.</blockquote><h3>One request, traced end to end</h3><p>The composition test: a request that touches everything. <em>“Show my top five accounts this quarter and draft a check-in email to the biggest one.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWcBt9vhMSJazpeEyG6IKA.png" /><figcaption><strong>One Traced Request</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li>The pass is fetched <strong>once</strong> and threaded to every engine; each one enforces it independently. The memory engine personalizes the draft’s voice; the analytics engine scopes the rows; the connector stops at a draft.</li><li><strong>One trace id</strong> rides every hop, and every engine logs it with the operation, the latency, and the outcome. When a user asks “why did it answer that,” the answer is a query, not an archaeology dig.</li><li>And the part I consider the real test of seniority in any architecture, <strong>what happens when a piece is missing</strong>:</li><li><strong>Identity layer unreachable</strong>: fail closed: own ungated data only, shared data denied with a visible notice</li><li><strong>Memory engine down</strong>: answer proceeds <strong>without personalization</strong>, with a caveat. Memory loss degrades quality, never correctness</li><li><strong>Analytics engine down</strong>: a typed failure and a retry offer. <strong>Never</strong> a model-improvised answer in place of real data</li><li><strong>Connector down</strong>: the error is reported and <strong>the draft is not created</strong>. A failure never sends anything</li></ul><blockquote>A system earns trust by how it behaves when a piece is missing. Every seam in this design has a written answer to “and what if you’re down?”, and none of the answers is “guess.”</blockquote><h3>Where it runs</h3><p>The deployment story is a straight line, and the desktop never changes along it:</p><ul><li><strong>Local first.</strong> Everything on one machine: the engines bundled, a local model available for private work, the user’s own key for heavier lifting. This is what is being built now.</li><li><strong>Then a company’s cloud.</strong> The engines move server-side into the customer’s environment; the data still never leaves their control.</li><li><strong>Eventually air-gapped.</strong> No external egress at all, for the environments where that is the requirement.</li></ul><p>The discipline that makes this a line instead of three rewrites: <strong>no early choice may hardcode an assumption that blocks the air-gapped end of the line.</strong> Connectors, model endpoints, and storage all sit behind swappable adapters from the first commit. Sandboxing for skill execution climbs the same ladder, from process isolation locally to stronger isolation as the deployment hardens.</p><h3>What it takes to extend it</h3><p>The extensibility test for any composed system: what does adding something touch?</p><ul><li><strong>A new skill</strong> (You do: drop a folder with a markdown file; Touches the runtime?: no)</li><li><strong>A new app or data source</strong> (You do: add an adapter behind the connector port; Touches the runtime?: no)</li><li><strong>A new model or provider</strong> (You do: change a setting; Touches the runtime?: no)</li><li><strong>A new engine</strong> (You do: expose a contract; honour the pass; Touches the runtime?: no new policy, no rewrite)</li><li><strong>A new UI component</strong> (You do: register one component; Touches the runtime?: one file)</li></ul><p>If a row in that table ever says “and then modify the orchestrator,” the architecture has failed at its one job. Capabilities are data; the runtime is fixed plumbing.</p><h3>The status ledger</h3><ul><li><strong>Analytics engine</strong>: <strong>shipping</strong> (series one)</li><li><strong>Document engine</strong>: structured half ships; document retrieval built, the hybrid fusion <strong>designed and scoped</strong> (series one, part four)</li><li><strong>Memory engine</strong>: <strong>design complete, build under way</strong> (series two)</li><li><strong>Contracts between desktop and engines</strong>: <strong>frozen first</strong>, deliberately: build to the contract, swap stand-ins for engines as they land</li><li><strong>Desktop shell: chat surface + orchestrator + tool loop</strong>: <strong>early build</strong>, against those contracts</li><li><strong>Skills lifecycle (create, register, dispatch, refine)</strong>: <strong>designed</strong>; the grow-skills half ships with the memory engine</li><li><strong>Identity layer and the signed pass</strong>: <strong>designed as the security spine</strong>: the contract is frozen and carried by every call from day one; a contract-conformant stand-in exercises it before the full layer lands with organization-scale deployments</li><li><strong>Generative UI, connected-app actions</strong>: <strong>designed, sequenced</strong> behind the core loop</li></ul><p>Freezing the contracts before building the parties to them is the one decision I would defend hardest: it is what lets three tracks (surface, engines, security) proceed in parallel and converge by composition instead of by merge conflict.</p><h3>Key takeaways</h3><ul><li><strong>The composition is the product.</strong> Models are interchangeable parts; the leverage is in one surface that routes work across engines which share memory and security.</li><li><strong>Thin client, always.</strong> No data, no drivers, no credentials on the surface. Query in place; results flow back; keys live in the keychain.</li><li><strong>Route by description, not by classifier.</strong> A central intent classifier is a bottleneck with a retraining bill. Tools and skills that describe themselves compose; gatekeepers do not.</li><li><strong>Skills are files.</strong> Readable, versioned, proposed never auto-saved, cheap until used, portable across agents.</li><li><strong>Decide access once.</strong> One identity layer signs a pass; every engine enforces it; denials are typed; gates default to deny; revocation reaches even memory.</li><li><strong>Design the failure modes, not just the happy path.</strong> Every seam has a written degradation behavior, and “fabricate something plausible” is never one of them.</li><li><strong>Freeze contracts first.</strong> Parallel tracks converge by composition when the seams are non-negotiable from day one.</li></ul><p>This closes the arc: an engine that answers questions about your data (series one), an engine that remembers and grows skills (series two), and the surface that composes them (this piece). The build continues; the next write-ups will be about what running it taught me, which is where the real lessons usually hide.</p><p><em>Further reading on the standards this leans on:</em> the <a href="https://modelcontextprotocol.io/">Model Context Protocol</a> (the tool contract between surface and engines), the <a href="https://agentskills.io/">agent skills format</a> (portable skills as markdown), and NIST’s <a href="https://csrc.nist.gov/pubs/sp/800/162/upd2/final">ABAC guidance</a> (the decide-once, enforce-everywhere access model, in its original enterprise form).</p><p><em>Series map: four parts on the conversational analytics engine, two parts on memory, and this capstone on the workspace that composes them.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5500d00ce9d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Pools, One Record: The Architecture of a Memory Engine for AI Agents]]></title>
            <link>https://pub.towardsai.net/two-pools-one-record-the-architecture-of-a-memory-engine-for-ai-agents-7080c6ca4a30?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7080c6ca4a30</guid>
            <category><![CDATA[ai-memory]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 23:01:01 GMT</pubDate>
            <atom:updated>2026-06-23T23:01:01.604Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Personal memory and project memory, joined by a pointer. Async writes, three read depths, time as a first-class citizen, and memory that grows skills. The blueprint, with the honest line between designed and built.</em></p><p><em>Part 2 of 2 on building memory for AI agents. Part 1 was the “why”: the seven problems. This part is the architecture that answers them. ~12 min read.</em></p><p>Part 1 ended with a claim: memory is seven problems wearing one name, and most of them are data-model, time, and governance problems rather than retrieval problems.</p><p>This part is the design that answers them, one by one. It is the memory layer of a desktop AI workspace I am building: one chat surface that handles general work, coding, connected apps, and questions over your own data (the analytics engine from my earlier series is the structured-data half of that same system). The memory engine is designed <strong>standalone</strong>: a local-first library with a CLI and an MCP server, usable from any agent that speaks the protocol, with the desktop app as just another consumer.</p><p>Before the architecture, the honesty box. I did this in my earlier series and readers told me it was the most useful part.</p><p><strong>Where this stands, up front:</strong></p><ul><li>The <strong>analytics engine</strong> from my earlier series: <strong>ships today</strong>; the desktop shell now being built wires it in as its first engine.</li><li>The <strong>memory engine in this article</strong>: <strong>design complete, build under way.</strong> The design is grounded in a research pass over the published field (the memory products, the agent frameworks, and the academic line of work), and every load-bearing choice below cites the evidence that earned it.</li><li>Nothing in this article is speculative hand-waving, but it is a <strong>blueprint being executed</strong>, not a retrospective. I describe the design in the present tense throughout, the normal register for an architecture; the <strong>status ledger at the end</strong> is the record of what actually runs today.</li></ul><p><strong>TL;DR</strong></p><ul><li><strong>Two pools, never merged:</strong> personal memory (about <em>you</em>) and project memory (about <em>a codebase</em>), joined by a <strong>pointer</strong>. Coding reads both; neither leaks into the other.</li><li><strong>One typed record</strong> with five kinds, <strong>two timelines on every row</strong>, and provenance stamped from day one.</li><li><strong>All model work is asynchronous, on the write path.</strong> The read path is pure search in <strong>three depths</strong>: an always-on profile (about 50 ms), on-demand recall, and a deep dive into the raw archive.</li><li><strong>Forgetting is a reversible score</strong>, configurable per kind and volatility, with new memories quarantined until reinforced.</li><li><strong>Memory enforces access but never decides it</strong>: it is handed a pass, honours it on every read, and drops memories whose sources you lost.</li><li><strong>Project memory rides the repo itself</strong> (an op-log on a git ref), so a team gets shared memory with no server.</li><li>The payoff: memory does not just recall facts, it <strong>grows skills</strong>, and keeps only a reference to them.</li></ul><h3>Where memory sits in the desktop</h3><p>The workspace composes a small number of engines behind stable contracts. The memory engine is one of them, and the diagram below is the map of how the pieces connect. Everything else in this article zooms into the memory box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ka64xB6VbVZWOiKYpph6xA.png" /><figcaption><strong>Desktop engine composition</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li>The desktop is a <strong>thin surface</strong>: it holds no source data and no enterprise credentials. The orchestrator picks tools per turn and calls every engine over the same protocol (MCP).</li><li>The memory engine is <strong>not a feature of the app</strong>. It is a standalone product the app embeds. The same gateway serves the desktop, a terminal CLI, and external coding agents. One core, many adapters: a lesson learned from watching a memory vendor sunset its separate server in favor of one unified one.</li><li>The red box matters most: an <strong>identity layer signs an access pass</strong> (who is asking, what they may currently see), and every engine honours it. Memory <em>consumes</em> this pass; it never computes policy. More on that below, because it is the most opinionated boundary in the design.</li><li>Model access is a <strong>configurable provider layer</strong>: your own key, your own endpoint, or a bundled local model. Memory’s neutrality is structural, not a promise.</li></ul><h3>Two pools, one pointer</h3><p>The spine of the whole design. Memory is not one undifferentiated blob; it is <strong>two pools with different owners, different privacy, and different lifecycles</strong>, and they never merge.</p><ul><li><strong>Personal memory</strong> is about <em>you</em>: your style, your preferences, your drafts, the way you like reports formatted. It is built from your chats and your connected-app work, it lives in a store you own, and it follows you.</li><li><strong>Project memory</strong> is about <em>a codebase</em>: its decisions, conventions, and gotchas (“uses Snowflake,” “auth is fragile,” “tests live in /spec”). It is built when a coding agent works in the repo, and it belongs with the repo and the team who share it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2w6oBa-EPWur5Z3aql0cg.png" /><figcaption><strong>Two pools one pointer</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li>The two pools are joined by a <strong>pointer</strong>: a graph edge in your personal pool that says <em>you work on repo X</em>. A coding turn resolves both pools through the pointer and merges results at read time, with your own facts ranked above generic project facts.</li><li><strong>Why not one store?</strong> Different owners (you versus the repo), different privacy (private versus team-shared), different lifecycles. When you leave a project, the project memory stays for the team and your personal memory leaves with you. A merged store can do neither cleanly. This was problem seven from Part 1, answered structurally.</li><li>A detail that took real thought: the project pool is keyed by <strong>the repo’s own identity</strong>, chosen deliberately so that a teammate cloning the same repo shares the pool while a <strong>fork starts clean</strong> instead of silently inheriting (and leaking back into) the upstream team’s memory.</li></ul><h3>One typed record</h3><p>Everything in both pools is <strong>one record shape</strong>. A kind selector picks the class; everything downstream (decay, sharing, audit, access) is written once against the one shape.</p><p>In sketch form (the conceptual shape, not the schema):</p><pre>a memory item =<br>  a kind        (one of five: fact, note, edge, procedure reference, persona)<br>  the content   plus a model-written one-line description, which is the retrieval key<br>  two timelines (true-in-the-world from/until · learned/retired by the system)<br>  provenance    (who wrote it · which source it came from)<br>  signal        (how much it mattered at write time · whether use keeps reinforcing it)</pre><p>The five kinds, and why five rather than one:</p><ul><li><strong>exact fact</strong> (What goes in it: stable exact attributes: timezone, “uses Vim”; How it is retrieved: exact key lookup, hash-deduplicated)</li><li><strong>semantic note</strong> (What goes in it: long-tail prose preferences and notes; How it is retrieved: vector search, hybrid with keyword)</li><li><strong>relationship edge</strong> (What goes in it: anything relational or true-over-time: works on, switched from, decided; How it is retrieved: graph traversal, plus the cross-pool pointer)</li><li><strong>procedure reference</strong> (What goes in it: a <em>pointer plus stats</em> for a learned procedure (feeds skills); How it is retrieved: by tags and usage stats)</li><li><strong>persona block</strong> (What goes in it: the always-on identity and tone block; How it is retrieved: never searched; injected)</li></ul><p>Three design notes that carry more weight than they look like they do:</p><ul><li><strong>The embedding key is the enriched one-line description</strong>, not the raw content. This comes straight from the agentic-memory research line, where embedding enriched text measurably improved recall.</li><li><strong>The relation vocabulary is deliberately tiny</strong>: a handful of predicates (prefers, works on, decided, and a few peers), and each one exists because a feature reads it. I am not building an ontology. The field’s evidence is blunt here: one major memory product removed its heavy graph store entirely, and the schema-light systems kept winning. Heavy ontology belongs in my analytics engine’s schema graph, which is a different graph for a different job.</li><li><strong>Provenance is not optional metadata.</strong> Who wrote a memory makes multi-author merge possible; which source it came from is what access revocation queries. Sharing and security are built on those two facts, and retrofitting them later would mean rewriting the store.</li></ul><h3>The write path: the model works the night shift</h3><p>All model intelligence runs <strong>asynchronously</strong>, triggered at session end, on idle, near context-window pressure, or on an explicit “remember this.” The only synchronous writes are a cheap raw append (the safety net) and a tiny profile delta, so personalization stays fresh without the user ever waiting on a model.</p><p>The pipeline: <strong>extract</strong> typed salient facts, <strong>enrich</strong> (description, keywords, importance, world-time), <strong>embed</strong> the enriched text, <strong>route</strong> to one of the five kinds, <strong>stamp provenance</strong>, check for <strong>skill candidates</strong> (a repeated successful procedure), then <strong>reconcile</strong>.</p><p>Reconcile is where the design earns its keep, because it is <strong>asymmetric by realm</strong>:</p><ul><li><strong>Local (personal or private project):</strong> retrieve the nearest neighbors and make one decision per candidate: <strong>add, update, invalidate, or no-op</strong>. A conservative writer, because the benchmark evidence says over-retention hurts.</li><li><strong>Shared (a team repo):</strong> <strong>append-or-invalidate only</strong>, never an in-place edit. Every write is an operation: add this fact, or invalidate that one by id. This single property is why multiple authors merge without conflicts, and it pairs with the storage model below.</li></ul><p>A deterministic <strong>security scan</strong> (injection patterns, secrets, invisible Unicode) gates every write, and every operation lands in a journal. The journal is the audit trail and the cache invalidation signal at once.</p><h3>The read path: three depths, zero model calls</h3><p>Reads are pure search. Three escalating depths:</p><ul><li><strong>HOT</strong> (When: every turn, automatic; Cost: zero model calls, ~50 ms; What it returns: a cached ~500-token profile (static + dynamic))</li><li><strong>WARM</strong> (When: on demand, the recall tool; Cost: zero model calls, fast search; What it returns: ranked facts and edges relevant to the query)</li><li><strong>DEEP</strong> (When: explicit, rare; Cost: heavier: graph walk + archive read; What it returns: a memory neighborhood, the original transcript, the as-of history)</li><li><strong>HOT</strong> answers the “agent may not search” failure from Part 1 by removing the choice: the profile is injected every turn by a hook, deterministically. It sits at the stable prompt prefix, so it is prompt-cache friendly, and it is re-injected from the durable store after every compaction. Inside a project, the budget splits roughly half personal, half project summary.</li><li><strong>WARM</strong> is hybrid retrieval: vector candidates, boosted by keyword match and graph proximity, reranked with decay applied, merged across the personal pool and the active project pool through the pointer, <strong>access-checked before ranking</strong>.</li><li><strong>DEEP</strong> is the double-click: walk the graph around a memory, open the original transcript it came from, see what was believed when.</li></ul><p>One honesty-driven mechanism sits in front of all three: a <strong>corpus-size router</strong>. The Salesforce ConvoMem results showed naive context stuffing beats structured memory below roughly 150 conversations. So on a small corpus this engine deliberately does the dumb thing (recent turns, cheap scan) and engages the full machinery only as the corpus grows past the point where brute force stops winning. Building sophisticated machinery and then <em>not using it</em> when simple wins is, I have come to believe, what production-grade actually means.</p><p>Under the reads sits a three-store flow, and it is the same pattern git uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M85wurfo2FWNT3UPZjQjnw.png" /><figcaption><strong>Memory lifecycle three reads</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li>The <strong>op-log is the truth and the sync unit</strong>; the <strong>database is a disposable projection</strong> rebuilt by replaying it; the <strong>raw archive</strong> is local-only fuel for deep dives and for the curator. Reads never touch the log directly.</li><li>Git users will recognize the shape: the commit log is truth, the working tree is the fast view built from it. That resemblance is not cosmetic, and the sharing section below cashes it in.</li></ul><h3>Time and forgetting: the two unglamorous pillars</h3><p><strong>Time.</strong> Every record carries both timelines from Part 1: world time (true from, true until) and system time (learned at, retired at). On contradiction, the old fact is <strong>invalidated, never deleted</strong>: it keeps its history, the new fact takes over, and the store can answer both “what was true in March” and “what did the agent believe in March.” Hard deletion exists for exactly one purpose: an explicit “forget this” (and its regulatory cousins).</p><p><strong>Forgetting</strong> is a score, not a delete. Each memory’s effective salience is its relevance multiplied by an exponential decay over age and last access, by its importance, and by a reinforcement term: memories that keep getting used resist decay.</p><p>The configuration surface is deliberately small: half-lives set per volatility (months for stable preferences like “writes British English,” weeks for situational facts like “busy with the Q3 launch”), a first-session quarantine, kinds that never time-decay, a reversible archive sweep at a floor, and one switch to turn the whole thing off per pool.</p><p>Three details I consider load-bearing:</p><ul><li><strong>First-session quarantine.</strong> Onboarding brain-dumps and inherited defaults are down-weighted until reinforced by real use. Day-one enthusiasm should not masquerade as long-term signal.</li><li><strong>Skills never time-decay.</strong> A procedure that worked fifty times does not become false by sitting unused. Skills <strong>retire on evidence</strong> (unused <em>and</em> success rate dropped), with proposed retirement, not silent deletion.</li><li><strong>The honesty note:</strong> these half-lives are design defaults, not measured truths. As Part 1 showed, no public benchmark scores forgetting, so an <strong>in-house evaluation harness ships as a build item, not a someday</strong>: accuracy, latency, and token cost as a Pareto triple, with explicit credit for abstention, contradiction handling, and correct forgetting. The first gate is deliberately tool-free: bootstrap the engine on my own history, review 50 extractions by hand, require at least 45 correct and zero fabricated.</li></ul><p>The design gives the desktop a <strong>native memory panel</strong> to surface all of this: the profile in plain language (editable, edits write back through the gateway), an interactive graph of your memory with an <strong>as-of time slider</strong> (drag to see what the store believed at any date, powered by the bitemporal model), a decay view with a “what will be forgotten soon” preview, and a consent inbox for anything proposed to be shared. Memory you cannot inspect is memory you will not trust.</p><h3>The boundary I refuse to cross: memory does not do access control</h3><p>This is the most opinionated decision in the design, and I think the most defensible.</p><p>The memory engine <strong>does not implement permissions</strong>. It is handed a signed <strong>access pass</strong> by the identity layer (who is asking, what they may currently see), verifies it locally, and honours it. Two mechanical rules fall out:</p><ul><li><strong>No laundering on write.</strong> A fact derived from a source a person could not see never enters a pool wider than that source. Unknown provenance fails closed: it stays personal-only, never shareable.</li><li><strong>Re-check on every recall.</strong> Every record carries the source it came from. When a grant is revoked, everything derived from that source is quarantined in one pass at the revocation event, and recall re-checks cheaply from then on. The property this buys is worth stating plainly: <strong>memory never outlives a grant.</strong> Disconnect a data source and the memories distilled from it stop surfacing.</li></ul><p>The same structural humility applies to the learning itself. <strong>Where the model runs is tiered by data sensitivity, not by task difficulty</strong>: raw, undistilled content (transcripts, mailboxes) is processed by a <strong>small local model on infrastructure the user controls</strong>, full stop. A larger cloud model is used only for already-cleaned, consented material. Extraction is a narrow task; a small model is good enough exactly where it matters. The field has already produced a cautionary tale here: a recent tool marketed as local-first was found uploading file contents and shell history to its cloud. Trust in a memory product is structural or it is nothing.</p><p>And one flag I keep open because intellectual honesty demands it: per-item visibility checks cannot stop a model from <em>blending</em> several individually-allowed memories into a conclusion the person was never cleared for. That is a synthesis-governance problem above the memory layer, and anyone who claims their memory store solves it is selling something.</p><h3>Memory grows skills</h3><p>Here is where memory stops being a notebook. Most memory products remember <strong>facts</strong>. The more valuable thing to remember is <strong>how you do things</strong>.</p><p>The engine watches the trace of what you and your agents actually did. When it sees a <strong>repeated, successful procedure</strong>, it distills it into a candidate skill: a plain-markdown skill file (the emerging cross-agent SKILL.md format), proposed to the user as a diff, <strong>never auto-saved</strong>. Memory keeps a procedure reference: the pointer plus success statistics. The skill body lives in a skill folder as a real file; <strong>memory holds the reference, never the body</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CblmpzFkh8ysv5ghQqoRoA.png" /><figcaption><strong>Memory grows skills</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li>Skills follow the <strong>two-pool spine</strong>: a personal habit graduates into your personal skill folder; a repo pattern graduates into the project’s folder and travels with the repo to the whole team.</li><li>Maturity is a ladder (candidate, verified, honed, tuned), and the top rung is mechanical: an <strong>offline skill optimizer</strong> that proposes bounded text edits accepted <strong>only if a held-out score strictly improves</strong>, landing as a reviewed pull request affecting new sessions only. Published work on exactly this loop reports gains around twenty points on coding-agent harnesses, which is why the optimizer is a port in the design with two interchangeable implementations behind it.</li><li>The same no-laundering rule applies to graduation: a skill distilled from private context never auto-promotes into a shared folder. And precedence on a name clash (personal beats project beats organization) applies to <em>how-to</em> skills only; <strong>policy is never an overridable skill</strong>.</li></ul><p>Candor about the competitive landscape, because pretending otherwise would be silly: the capture-a-pattern-grow-a-skill loop is rapidly becoming <strong>table stakes</strong>; large open-source agent ecosystems ship versions of it today. So the interesting engineering is not the loop. It is <strong>governing</strong> it: local-first distillation, no laundering, evidence-based retirement, auditable history, and one engine growing skills across every surface instead of a separate learner per tool.</p><h3>Sharing without a server: memory rides the repo</h3><p>The last piece, and my favorite, because it converts infrastructure into a property of something teams already have.</p><p>Personal memory never syncs to anyone else. But project memory is only useful if the team shares it, and standing up a memory server for a five-person repo is friction nobody wants. The answer falls out of the storage model: the project pool’s op-log <strong>lives on a dedicated git ref in the repo itself</strong> and travels on push and pull, exactly like the code. (Precedent: the git-bug project has run an operation-based store over git refs for years, serverless.)</p><ul><li><strong>Writes are per-author:</strong> each contributor appends only to their own partition file, so git never sees a merge conflict.</li><li><strong>Reading is the merge:</strong> recall loads the union of every author’s partition and searches across all of it. A departed teammate’s still-true facts remain; wrong ones get invalidated by a newer op on the corrector’s own partition; unused ones fade by decay.</li><li><strong>Access control at this level is the repo’s own permission</strong>, deterministically: whoever the git host lets fetch the repo gets the pool. The signed access pass takes over in organization-scale deployments, where an identity layer actually exists.</li><li>One caveat I will not hide: revocation here is <strong>git-grade, exactly like the code itself</strong>. A removed collaborator stops receiving new operations but keeps what they already pulled. Grant-grade drop-on-revoke is precisely what the identity layer adds at organization scale, and pretending the repo level already has it would be the kind of dishonesty this series exists to avoid.</li></ul><p>Onboarding to a codebase stops being “read the wiki and bother the senior engineer.” Clone the repo, and the team’s accumulated memory of <em>why</em> arrives with it.</p><h3>The status ledger: designed versus building</h3><p>The same honesty as Part 1 of my earlier series, in one table.</p><ul><li><strong>The analytics engine (earlier series)</strong>: <strong>shipping</strong>; its desktop integration is the next milestone</li><li><strong>The memory blueprint (record, pools, paths, decay, access model)</strong>: <strong>design complete</strong>, grounded in the published evidence, frozen as the build contract</li><li><strong>The spine: record + store + gateway + journal, round-tripping a fact</strong>: <strong>in build now</strong> (the walking skeleton, with CI and tests from day one)</li><li><strong>Bootstrap: distilling my own coding history into day-one memory</strong>: <strong>next</strong>, with the hand-graded 50-extraction gate (at least 45 correct, zero fabricated)</li><li><strong>Bitemporal contradiction handling, decay, the evaluation harness</strong>: <strong>designed, sequenced</strong> behind the spine</li><li><strong>Skills graduation, repo-ref sharing, the memory panel</strong>: <strong>designed, sequenced</strong> further out</li><li><strong>Organization-scale deployment (team synthesis, signed-pass enforcement end to end)</strong>: <strong>designed as placeholders</strong>: the foundations exist day one; they activate later without a rewrite</li></ul><p>That last row reflects the build philosophy in one line: <strong>architect for the team and the org, build for the solo user first</strong>, and make every later stage a matter of filling fields and pointing ports at new backends rather than rewriting foundations.</p><h3>Key takeaways</h3><ul><li><strong>Two pools, one pointer.</strong> Personal and project memory have different owners, privacy, and lifecycles. Keep them separate, join them with a graph edge, and read both at coding time.</li><li><strong>One typed record, five kinds, two timelines, provenance from day one.</strong> Every downstream mechanism is written once. Retrofitting bitemporality or provenance later is the expensive path.</li><li><strong>Model on the write path, never the read path.</strong> Async curation writes; deterministic search serves. The always-on profile removes the “agent may not search” failure; the corpus-size router keeps the machinery honest on small data.</li><li><strong>Forgetting is a reversible, configurable score</strong>, and the evaluation harness for it has to be built in-house, because public benchmarks reward hoarding.</li><li><strong>Memory honours access, never computes it.</strong> No laundering on write, re-gate on recall, memory never outlives a grant in pass-enforced deployments, and raw content never leaves infrastructure the user controls for distillation.</li><li><strong>Facts are table stakes; skills are the payoff.</strong> Repeated successful procedures graduate into portable skill files, proposed never auto-saved, governed by the same provenance rules as everything else.</li><li><strong>The repo is the team’s memory server.</strong> An append-only op-log on a git ref gives a team shared project memory with zero infrastructure.</li></ul><p>This closes the two-part memory series. With the analytics series (the four parts on conversational analytics) and this pair, the written record now covers two of the engines behind the workspace: the one that answers questions about your data, and the one that remembers. The connective tissue between them, the desktop surface that composes the engines and routes every request, gets its own write-up next.</p><p><em>Further reading on the mechanisms borrowed here:</em> Zep’s <a href="https://arxiv.org/abs/2501.13956">bitemporal memory graph</a> (invalidate-don’t-delete), the <a href="https://arxiv.org/abs/2502.12110">A-MEM paper</a> (embed enriched descriptions), Salesforce’s <a href="https://arxiv.org/abs/2511.10523">ConvoMem</a> (when naive beats structured), the <a href="https://arxiv.org/abs/2605.23904">SkillOpt paper</a> (validation-gated skill optimization), and <a href="https://github.com/git-bug/git-bug">git-bug</a> (operation logs on git refs, the sharing precedent).</p><p><em>Part 1 of this pair covered the why: the measurable cliff, the seven problems, and why a bigger context window is the wrong layer.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7080c6ca4a30" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/two-pools-one-record-the-architecture-of-a-memory-engine-for-ai-agents-7080c6ca4a30">Two Pools, One Record: The Architecture of a Memory Engine for AI Agents</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents Have Amnesia. A Bigger Context Window Won’t Cure It.]]></title>
            <link>https://pub.towardsai.net/ai-agents-have-amnesia-a-bigger-context-window-wont-cure-it-dea937c4a58e?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dea937c4a58e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-memory]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-06-23T13:31:01.175Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Why memory is the missing layer of the agent stack, the seven problems any real memory system has to solve, and the shape of an architecture that survives them.</em></h4><p><em>Part 1 of 2 on building memory for AI agents. This part is the “why.” Part 2 is the architecture. ~10 min read.</em></p><p>On Monday you tell your coding agent that your team uses pnpm, not npm. It apologizes, fixes the command, and carries on. On Thursday it runs npm install again.</p><p>You explain to your AI assistant, for the third time this month, that you write British English, that “the migration” means the Postgres-to-Snowflake project, and that your weekly report goes out Friday morning. It nods. Tomorrow it will be a stranger again.</p><p>Here is the uncomfortable part: the model is not the problem. The model got smarter every quarter. What never changed is that <strong>every session starts from zero</strong>, because the layer that should carry what the model learned about you, your project, and your decisions simply does not exist in most agent stacks.</p><p>I spent the last several months designing that layer for an AI workspace I am building, after shipping a production conversational analytics engine (my earlier four-part series). This pair of articles is the memory half of that work. Before I show the architecture in Part 2, I want to convince you that memory is a real engineering problem with sharp edges, not a vector database you bolt on in a weekend.</p><p><strong>TL;DR</strong></p><ul><li>Agents without durable memory measurably degrade: on the LongMemEval benchmark, assistants drop <strong>around 30 percent</strong> (up to roughly 60 on the hardest abilities) when answers hide in a long history instead of a short one.</li><li>The obvious fixes fall short. A bigger context window is a <strong>buffer, not a memory</strong>. Instruction files <strong>rot silently</strong>. A bolted-on vector store returns <strong>stale facts with confidence</strong> and has no idea what is still true.</li><li>Memory is really <strong>seven distinct problems</strong>: the unit of memory, when to write, what to keep, how to change your mind, what was true when, when to forget, and where memory lives (and who may see it).</li><li>The shape of the answer: a <strong>typed, time-aware record</strong> instead of a blob, an <strong>asynchronous model-powered write path</strong> with a <strong>deterministic read path</strong>, and <strong>forgetting and privacy designed in as structure</strong>, not patched on.</li></ul><h3>The drop is measurable</h3><p>You do not have to take the amnesia anecdotes on faith. The benchmarks already show the cliff, and it rhymes with the text-to-SQL cliff from my earlier series: the demo conditions hide the hard part.</p><ul><li><strong>LongMemEval</strong> (ICLR 2025) asks 500 questions whose answers are buried in long chat histories. It isolates five abilities: information extraction, multi-session reasoning, temporal reasoning, knowledge updates, and abstention. Commercial assistants and long-context models drop <strong>about 30 percent</strong> versus being handed just the relevant sessions, and <strong>up to about 60 percent</strong> on the hardest abilities.</li><li><strong>Temporal reasoning is a headline failure.</strong> Systems confuse <em>when a fact was stored</em> with <em>when it was true</em>, so “what database do we use now” happily returns the answer from before the migration.</li><li>The effect is not hypothetical product polish. Anthropic reported a <strong>39 percent</strong> improvement on an agentic evaluation from adding a memory tool plus context editing.</li><li>And a warning while we are here: memory benchmark scores are fragile. The same memory system has been scored at <strong>84, 75, and 58 percent</strong> on the same benchmark by different evaluators, because LLM-as-judge setups disagree. Whatever you build, you end up needing your own evaluation harness. Hold that thought for Part 2.</li></ul><blockquote>The model did not get dumber as the history grew. The environment changed: the signal it needed was buried in noise it could not organize. That is not an intelligence problem. It is a systems problem.</blockquote><h3>“Just use a bigger context window” is the wrong layer</h3><p>The most common objection first. Context windows are now a million tokens. Why build anything?</p><p>Four reasons, and each one is structural.</p><ul><li><strong>Cost and latency scale with everything you re-read.</strong> Stuffing history into every call means paying for it on every call. Production memory systems report <strong>about 90 percent token savings</strong> and <strong>around 90 percent lower p95 latency</strong> versus full-context stuffing (vendor-run numbers, the usual caveat). One published system compresses a 115k-token history into roughly 1.6k tokens of retrieved facts. And even on benchmarks where brute-force context stuffing wins on raw accuracy, it pays roughly ten times the tokens and latency to do it.</li><li><strong>Long context degrades.</strong> The same LongMemEval results above are partly a long-context story: models lose precision in the middle of huge prompts. More window is more haystack.</li><li><strong>The window ends, and the agent forgets at the boundary.</strong> Long sessions hit compaction: the runtime summarizes old turns to make room, and detail dies in the summary. Every heavy user of coding agents has watched an agent forget a constraint it acknowledged an hour earlier. One open-source agent ingests its instruction file on every loop iteration with no size guard; a real-world 331 KB instructions file consumed about 81 percent of a 128k window before any work began.</li><li><strong>A window is a buffer, not a model of truth.</strong> Even infinite context cannot tell you which of two contradictory statements is current, what changed since last sprint, or what you are no longer allowed to see. Those need a data model, not more tokens.</li></ul><blockquote>A context window is RAM. Memory is the file system plus the database. Nobody argues their laptop needs no disk because it has a lot of RAM.</blockquote><h3>What agents do today, and how it decays</h3><p>The field is not empty. It is fragmented, and each fragment fails a different way.</p><p><strong>[ IMAGE PLACEHOLDER, upload diagrams/part5-where-agent-memory-breaks.png ]</strong><br>Diagram: what agents use for memory today, and how each one decays. In Medium, add an image here, upload that file, then delete this line.</p><p><strong>How to read it:</strong> each column is a coping mechanism in real use today, and each red box is the way it decays in production. None of the four is wrong. Each is a partial answer that was never designed to be the whole one.</p><ul><li><strong>Static instruction files</strong> (CLAUDE.md, AGENTS.md, editor rules) are the workhorse of coding agents, and they are genuinely useful. But they are human-curated, so they <strong>rot silently</strong>: nothing updates them when reality changes, and the official guidance is to “review periodically to remove outdated or conflicting instructions.” They are also delivered as suggestions, not enforced state.</li><li><strong>Compaction</strong> keeps long sessions alive by summarizing old turns. It is lossy by design. What the summary drops is gone, and the GitHub issues of every major coding agent are full of “it forgot what we agreed” reports at exactly that boundary.</li><li><strong>A vector database bolted on</strong> gives you semantic recall and three new problems: it returns facts that are <em>similar</em> but <strong>stale</strong>, it cannot represent “this was true until March,” and contradictory facts coexist until retrieval becomes a coin flip. Worse, tool-based recall only works <strong>when the agent chooses to search</strong>, which it often does not.</li><li><strong>Hosted assistant memory</strong> (the memory features inside consumer assistants) is real progress and the right instinct, but it is opaque, lives on someone else’s server, is scoped to one product, and cannot follow you into your terminal, your editor, and your other tools.</li></ul><p>Researchers who study agent context describe four recurring failure modes, and a memory layer has to answer all four: <strong>poisoning</strong> (a wrong fact gets in and persists), <strong>distraction</strong> (history outweighs the task), <strong>confusion</strong> (irrelevant detail leaks into answers), and <strong>clash</strong> (contradictory facts coexist).</p><p>There are also dedicated memory products (Mem0, Zep, Letta, Supermemory, and others), and they are serious work; my design borrows tested ideas from each. But each solves a slice. One ships clean write-time fact extraction but pushed contradiction resolution out to the application. One ships a strong temporal graph but no real forgetting. One ships elegant in-context memory blocks but leaves long-term structure to you. And while some ship access-control lists around memory, none of the open engines makes <strong>source-level visibility</strong>, and what happens when a grant is revoked, a first-class axis of the memory model itself. For anything beyond a single user, that turns out to be the hardest part.</p><h3>Memory is seven problems wearing one name</h3><p>“Add memory” sounds like one feature. When I sat down to design it properly, it decomposed into <strong>seven questions</strong>, and every one of them changes the architecture. This decomposition is the backbone of Part 2, so I will take them in order.</p><h3>1. What is the unit of memory?</h3><p>A transcript is not a memory. If you store raw chat logs and embed them, you have built search over noise.</p><ul><li>The unit has to be a <strong>distilled, typed record</strong>: a fact (“uses pnpm”), a preference (“terse PR descriptions”), a relationship (“Priya owns the auth service”), a procedure (“how we cut a release”), an identity trait (“writes British English”).</li><li>Different types need different storage and retrieval: exact-lookup facts, semantically searched notes, graph edges you can traverse, procedures you can execute.</li><li>One schema with a type field beats five stores. Every downstream mechanism (decay, sharing, audit) gets written once.</li></ul><h3>2. When do you write?</h3><p>Write everything every turn and you get noise, latency, and cost. Write only when the user says “remember this” and you get almost nothing.</p><ul><li>The pattern that works across the research corpus: <strong>asynchronous curation</strong>. A background pass reads the session and extracts what mattered, off the hot path.</li><li>Be conservative. Benchmarks built on growing histories show <strong>over-retention actively hurts accuracy</strong>: more memories means more retrieval noise.</li><li>The strongest implicit signal is not what the user said. It is what they <strong>did</strong>: accepted, edited, rejected, repeated.</li></ul><h3>3. What do you keep?</h3><p>The fact, not the transcript. The decision, not the meeting.</p><ul><li>Extraction is model work: read the session, emit salient, self-contained statements with metadata (importance, keywords, a one-line description).</li><li>A finding from the agentic-memory research line that I adopted directly: <strong>embed the enriched note</strong> (the content plus a model-written description, keywords, and tags), not the bare transcript. Retrieval precision improves measurably, and my design keys retrieval on the one-line description.</li><li>Keep the raw log too, but as a separate, decaying archive you can drill into, never as the thing you search by default.</li></ul><h3>4. How do you change your mind?</h3><p>You switched from Postgres to Snowflake. A naive store now holds both “we use Postgres” and “we use Snowflake,” and your agent alternates between them.</p><ul><li>On contradiction, the prior fact must be <strong>invalidated, not deleted</strong>: marked superseded with a timestamp, kept for history.</li><li>Deleting feels tidy and destroys the audit trail. Invalidation gives you “what did we believe in March” for free, plus undo.</li><li>This is the single clearest divide in the field: destructive updates versus temporal invalidation. I side with invalidation, and Part 2 shows the mechanics.</li></ul><h3>5. What was true when?</h3><p>There are two timelines and most systems track neither cleanly.</p><ul><li><strong>World time:</strong> when the fact was true in reality (“Postgres until March 2026”).</li><li><strong>System time:</strong> when the memory layer learned it (maybe in May, from an old document).</li><li>You need both on every record to answer both “what was true at T” and “what did the agent <em>believe</em> at T.” The first is correctness; the second is audit, and you will want it the first time an agent acts on stale knowledge and someone asks why.</li><li>The published system that took this seriously (a bitemporal knowledge graph) reported the strongest temporal-reasoning numbers published so far (vendor-run, so apply the caveat from earlier). The lesson generalizes either way: <strong>stamp both timelines from day one, because retrofitting is brutal.</strong></li></ul><h3>6. When do you forget?</h3><p>Forgetting sounds like a bug. It is a feature, and an under-built one.</p><ul><li>Stale and low-value memories are <strong>retrieval noise</strong>; dropping them from candidate sets raises accuracy. Forgetting is a quality lever, not hygiene.</li><li>Forgetting must be <strong>reversible</strong>: a retrieval-time down-weight that decays with age and disuse, plus an archive sweep, never silent destruction.</li><li>Not everything decays alike. “Prefers British English” should outlive “busy with the Q3 launch” by an order of magnitude. Decay needs to be configurable per kind of memory, per volatility.</li><li>And here is the research gap that surprised me most: <strong>the public benchmarks cannot see any of this.</strong> Their scoring is recall-monotonic: remembering more never costs points. A system that hoards everything can top the leaderboard while degrading the real product. Nobody scores forgetting; almost nobody scores personalization. If you build memory seriously, you are building your own evaluation harness, because the public ones reward the wrong behavior.</li></ul><h3>7. Where does it live, and who may see it?</h3><p>The question the benchmarks skip entirely, and the one that dominated my design.</p><ul><li>Memory about <em>you</em> and memory about <em>a project</em> have different owners, different privacy expectations, and different lifecycles. You leave a project; the project’s knowledge should stay with the team, and your personal memory should leave with you. A store that mixes them cannot do either.</li><li>Raw conversations are the most sensitive data an agent touches. Distilling them with a model is exactly the step you do not want running on someone else’s server.</li><li>The moment memory is shared (a team, a company), access control collides with it: a fact you learned from a source a colleague cannot see must not surface to them through the side door of “memory.” And when your access to a source is revoked, memories derived from it should stop surfacing too. Almost nothing in the field even attempts this.</li></ul><blockquote>Read the seven again and notice what they are not. Only two are retrieval problems. The rest are <strong>data-model, time, and governance problems</strong>, and that is precisely why “we added a vector database” keeps failing as a memory strategy.</blockquote><h3>Why the obvious fixes don’t clear the walls</h3><p>The same table I built for text-to-SQL in my earlier series, redrawn for memory. Every common fix helps; none of them, alone, answers more than two of the seven questions.</p><ul><li><strong>Bigger context window</strong> (What it helps: short-term continuity within a session; What it does not solve: cost, long-context degradation, contradictions, time, privacy: a buffer, not a record)</li><li><strong>Instruction files (CLAUDE.md and friends)</strong> (What it helps: stable, human-vetted preferences; What it does not solve: rots silently; no extraction, no time model, no scoping; guidance, not state)</li><li><strong>Vector store bolted on</strong> (What it helps: semantic recall over past text; What it does not solve: stale-but-similar wins, no invalidation, no decay, recall only if the agent searches)</li><li><strong>Fine-tuning on your data</strong> (What it helps: style, vocabulary; What it does not solve: facts change weekly; retraining is the slowest possible write path; nothing is auditable or revocable)</li></ul><p>Notice the pattern, because it is the same one from the text-to-SQL series: every fix tries to make the <strong>model</strong> better, but most of the seven problems are not model problems. They are <strong>structure</strong> problems, and structure is something you design.</p><h3>The shape of an answer</h3><p>Here is the thesis Part 2 builds out, in three ideas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7xHjHR3uMVST98eJ8APPg.png" /><figcaption><strong>The shape of a memory system</strong></figcaption></figure><p><strong>How to read it:</strong> model work (purple) happens once, asynchronously, on the write side. The record (green) travels with its two governors: decay (blue, deterministic), which shapes what surfaces, and the access pass (red), which gates every read. The two reads on the right are what the user actually waits on: deterministic search, checked against both governors, every time.</p><p><strong>1. Memory is a typed, time-aware system of record, not a blob.</strong></p><ul><li>One uniform record with a small set of kinds: exact facts, semantic notes, graph relationships, procedure references, and an identity block.</li><li>Every record carries <strong>both timelines</strong> (world time, system time) and <strong>provenance</strong> (who wrote it, which source it came from). Contradictions invalidate; nothing silently disappears.</li></ul><p><strong>2. Split the write path from the read path, hard.</strong></p><ul><li>All model intelligence lives on the <strong>asynchronous write path</strong>: extract, enrich, reconcile against neighbors, decide add-update-invalidate-or-ignore.</li><li>The <strong>read path runs zero model calls</strong>. Every turn gets a cached, roughly 500-token profile injected automatically; deeper recall is a deterministic hybrid search (semantic, keyword, graph) with ranking. This is what makes memory fast enough to be ambient: the published systems that did this report retrieval latencies in the low seconds versus tens of seconds for context stuffing, at a tiny fraction of the tokens.</li><li>If you read my earlier series, you have seen this move before: it is the same hard line that made text-to-SQL safe, applied to memory. The model proposes on the slow path; deterministic code serves on the fast path.</li></ul><p><strong>3. Forgetting and privacy are structural, not features.</strong></p><ul><li>Decay is a <strong>score, not a delete</strong>: relevance multiplied by age, importance, and reinforcement, with per-kind half-lives, fully reversible, swept to an archive at the floor.</li><li>Personal memory is <strong>local-first</strong>: the raw material never leaves infrastructure the user controls for distillation, and the distilled store lives where the user can read, edit, and export it.</li><li>Access is <strong>honoured on every read</strong>: memory is handed the caller’s current entitlements and filters against them at recall time, so a revoked source means the derived memories stop surfacing. Memory never outlives a grant.</li></ul><h3>Key takeaways</h3><ul><li><strong>Agents without memory measurably degrade</strong>, around 30 percent on long-history benchmarks and worse on temporal questions, and users feel it as re-explaining themselves forever.</li><li><strong>A context window is a buffer, not a memory.</strong> Cost, degradation, compaction loss, and the absence of any model of truth make “bigger window” the wrong layer for the job.</li><li><strong>Today’s coping mechanisms each decay differently</strong>: instruction files rot, compaction forgets at the boundary, vector stores serve stale facts confidently, hosted memory is opaque and siloed.</li><li><strong>Memory decomposes into seven problems</strong>, and most are not retrieval: unit, write policy, distillation, contradiction, time, forgetting, and placement plus access. The last three are where the field is thinnest.</li><li><strong>The benchmarks reward hoarding.</strong> Recall-monotonic scoring cannot see forgetting or personalization, so building memory seriously means building your own evaluation harness too.</li><li><strong>The shape of the answer:</strong> a typed bitemporal record, async model-powered writes, a deterministic model-free read path, decay as reversible ranking, and access checked at every recall.</li></ul><p>In Part 2, I get concrete: the two-pool architecture (personal memory versus project memory, and the pointer that joins them), the write and read paths in detail, how memory rides a git repo to become a team brain, why my memory engine refuses to do access control, and the part I find most interesting: how memory stops being a notebook and starts growing <strong>skills</strong>.</p><p><em>Further reading on the problem space:</em> the <a href="https://arxiv.org/abs/2410.10813">LongMemEval benchmark</a> (the five abilities and the cliff), Salesforce’s <a href="https://arxiv.org/abs/2511.10523">ConvoMem analysis</a> of when naive context beats memory systems, Zep’s <a href="https://arxiv.org/abs/2501.13956">bitemporal memory-graph paper</a>, and the <a href="https://arxiv.org/abs/2502.12110">A-MEM paper</a> on agentic memory notes.</p><p><em>Next, Part 2: the architecture. Two pools, one record, three read depths, and memory that grows skills.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dea937c4a58e" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/ai-agents-have-amnesia-a-bigger-context-window-wont-cure-it-dea937c4a58e">AI Agents Have Amnesia. A Bigger Context Window Won’t Cure It.</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Question, a Number and a Paragraph]]></title>
            <link>https://pub.towardsai.net/one-question-a-number-and-a-paragraph-bd124324e750?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd124324e750</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 20:01:00 GMT</pubDate>
            <atom:updated>2026-06-16T20:01:00.853Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>One question often needs a number AND a paragraph. Here is the design for answering both at once, and an honest map of what ships today versus what is still roadmap.</em></h4><p><em>Part 4 of 4 on building a conversational analytics engine. ~10 min read.</em></p><p>Every system I build eventually hits the same wall, and it is always the same shape.</p><p>The structured side gets good. Users ask <em>“how many orders did Bike World place last quarter”</em> and get a correct, access-controlled number (that was Parts 2 and 3). Then someone asks:</p><blockquote>“What did the Q3 board deck say about churn, and how does that compare to the actual numbers?”</blockquote><p>That question has two halves. <strong>“What did the deck say”</strong> is a paragraph from a PDF. <strong>“The actual numbers”</strong> is a SQL query. A system that does only one half answers half the question, which in practice means it answers the wrong question.</p><p>The interesting work is not retrieving documents, and it is not generating SQL. Both are reasonably well-trodden. The interesting work is <strong>tying them together</strong> so one answer draws on both, with one set of permissions and one trail of provenance.</p><p>I am going to be candid about the line between built and designed, because I chose honesty over a clean story for this series.</p><p><strong>What ships vs. what does not, up front:</strong></p><ul><li>The <strong>structured pipeline</strong> (Parts 2 and 3): <strong>ships.</strong></li><li>The <strong>document retrieval stack</strong> in this article: <strong>built, and works as retrieval.</strong></li><li>The <strong>fusion</strong> of the two (one question fanning out to both, joined on a shared entity): <strong>designed and partly scaffolded.</strong> I will mark exactly where the code stops.</li></ul><p><strong>TL;DR</strong></p><ul><li>Three knowledge graphs: <strong>Domain</strong> (schema), <strong>Subject</strong> (entities, the shared hub), <strong>Lexical</strong> (documents). Identity is a <strong>bridge</strong>, not a fourth graph.</li><li>Built today: <strong>hybrid retrieval</strong> (vector + keyword, fused with Reciprocal Rank Fusion) and <strong>fail-closed document RBAC</strong>.</li><li>The design: a question is classified <strong>structured / rag / hybrid / clarify</strong>; a hybrid question runs both pipelines and <strong>joins them on the subject graph</strong>.</li><li>The honest gap: the cross-graph links that make fusion work exist as scaffolding with <strong>test-only callers</strong>. Wiring them is real work, not research.</li></ul><h3>Three graphs, and a bridge that is not a graph</h3><p>The fusion design rests on the substrate, so a quick recap. (Part 2 noted that every node carries a layer label precisely so these can coexist in one store.)</p><ul><li><strong>Domain graph:</strong> the schema and its meaning. Tables, columns, join paths, metrics. The map of the structured world.</li><li><strong>Subject graph:</strong> the canonical entities. “Bike World” resolved to a real key, with source links. The thing from Part 3 that turns a name into a key.</li><li><strong>Lexical graph:</strong> the documents. Each one broken into chunks, with the structure of which chunk came from where.</li></ul><p>And then <strong>identity</strong>, which I deliberately do not call a fourth graph. Identity is the <strong>bridge</strong>: it produces the access scope that gates every read across all three graphs. Calling it a graph would imply another silo to query. It is better understood as the function that wraps every query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNA3FKec2-qxSZ8dTOu3Wg.png" /><figcaption><strong>Two pipeline fusion</strong></figcaption></figure><p><strong>How to read it (the one idea that matters):</strong> look at the middle. <strong>The subject graph is the shared hub.</strong> The structured pipeline reads Domain plus Subject. The RAG pipeline reads Lexical plus Subject. Subject is the overlap, so when both halves come back, a given customer is the <em>same entity object</em> in both. That shared identity is what lets me join a database row to a document passage.</p><blockquote>The join key for structured-plus-unstructured fusion is <strong>a resolved entity.</strong> Hold onto that. It is the whole trick, and it is where the honest gap lives.</blockquote><h3>What is actually built: the retrieval stack</h3><p>Let me ground this in running code before the vision.</p><p>A document goes through a pipeline: load, chunk, embed, and index <strong>two ways</strong>.</p><ul><li><strong>Chunking:</strong> character-based, sentence-aware, around 500 characters with a small overlap so a sentence split across a boundary is not lost.</li><li><strong>Embedding:</strong> the same model as the rest of the system, OpenAI text-embedding-3-small, into 1536-dimension vectors, cosine distance. Vectors go to Qdrant.</li><li><strong>The second index:</strong> the chunk text also goes into a <strong>BM25 keyword index</strong>. This is the part people forget.</li></ul><p>Why hybrid and not pure vector search?</p><ul><li><strong>Vector search</strong> is great at meaning, weak on specifics. It knows “churn” and “attrition” are neighbors (good) but shrugs at an exact product code (bad).</li><li><strong>BM25</strong> is the opposite: literal, exact, unbothered by synonyms.</li><li>Running both and fusing covers each one’s blind spot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-rop7bibHbqwGIyAapZgQ.png" /><figcaption><strong>Rag retrieval stack</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Reciprocal Rank Fusion</strong> is the merge, and it is almost embarrassingly simple: for each result, add weight / (k + rank), with k set to <strong>60</strong>. You never have to make a cosine score and a BM25 score comparable (they are not). You just trust the orderings.</li><li>A chunk that ranks high in <strong>both</strong> lists rises to the top.</li><li>The <strong>optional reranker</strong> uses an LLM as a judge, scoring each candidate. It is <strong>off by default</strong>, because hybrid retrieval is usually good enough and the judge costs a model call per chunk. Pay for it only when you decide you need it.</li></ul><blockquote><strong>Shipped vs. next:</strong> the stack above runs, but <strong>document ingestion is not wired into startup.</strong> A fresh process has an empty index until something explicitly ingests a corpus. So “the RAG pipeline works” is true for the machinery and not-yet-true for a loaded corpus. I would rather you know that than assume documents that are not there.</blockquote><h3>Security for documents is its own problem</h3><p>Access control for structured data (Part 3) was about rows and columns. For documents it is about <strong>which files you may see</strong>. A leaked paragraph from a board deck is every bit as bad as a leaked salary row.</p><p>The model reuses the <strong>same access-scope object</strong> from the structured side. That reuse is the point: one notion of “who may see what,” applied to two very different shapes of data.</p><p>After retrieval, before any chunk is returned:</p><ul><li>Look up the document the chunk came from.</li><li>Find its file path, derive the folder.</li><li>Ask the scope whether this user may read that folder. Yes, it passes. No, it is dropped.</li></ul><blockquote><strong>The failure behavior is the part I care about.</strong> If the system cannot find the document’s metadata for a chunk (a cold start, an unloaded doc), it does <strong>not</strong> serve the chunk and hope. It drops it. The default on uncertainty is <strong>deny</strong>, not allow. Same fail-closed instinct as the SQL side, and, as there, <strong>no language model anywhere in the decision.</strong></blockquote><h3>The fusion design, and the honest gap in the middle</h3><p>Now the part that is mostly design. A question gets classified two ways: which capability it needs, and then the <strong>data path</strong>: structured, rag, hybrid, or clarify.</p><p>A <strong>hybrid</strong> question (the churn example) runs both pipelines:</p><ul><li>The <strong>structured leg</strong> plans and generates SQL exactly as in Part 3, reading Domain and Subject, and produces the actual churn numbers, scoped to what the user may see.</li><li>The <strong>unstructured leg</strong> retrieves the relevant passages, reading Lexical and Subject, scoped by the same access decision.</li><li>Then the two <strong>fuse on the subject graph</strong>: because both legs resolved their entities through the same canonical hub, the customer in the SQL row and the customer in the deck passage are the <strong>same entity</strong>, and that shared identity is the join.</li></ul><p>The result is one envelope: the rows and the SQL, the document passages with citations, the caveats from both pipelines, a confidence, and a trace id.</p><blockquote>I find the <strong>symmetry</strong> satisfying. The structured tool reads Domain plus Subject. The RAG tool reads Lexical plus Subject. Subject is the shared cache in the middle, and the hybrid join happens there. Two pipelines that look completely different turn out to be mirror images that meet at the entity hub.</blockquote><p><strong>Now the gap, stated plainly, because it is the center of this article:</strong></p><ul><li>The two cross-graph links that fusion depends on (entity-to-table, entity-to-chunk) are <strong>defined but not alive</strong>. The schema exists. The methods exist. But today they have <strong>only test callers</strong>, and nothing in the running system creates the document-chunk nodes they would point at.</li><li>The lexical graph as currently coded is an in-memory structure that nothing populates in production, <strong>separate</strong> from the Qdrant index the live retrieval actually uses.</li></ul><p>So there are effectively <strong>two unstructured stacks</strong> right now: the working retrieval path (Qdrant plus BM25), and a graph-shaped representation of documents that is scaffolding, not yet load-bearing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJ7K6m4XiMPHUKD8onK5Rg.png" /><figcaption><strong>Built vs designed ledger</strong></figcaption></figure><p><strong>How to read it:</strong> green is real and running. Yellow is designed and scoped. <em>“The subject graph is the shared cache across structured and RAG”</em> is a true description of the <strong>design</strong> and a false description of the current <strong>wiring</strong>, and the difference between those two sentences is the work: create the chunk nodes, wire the link methods, stand up the fusion. None of it is research. A reader deciding whether I understand my own system is better served by this ledger than by a demo video.</p><h3>Static documents and volatile documents</h3><p>One more design distinction, because it changes the architecture more than it looks.</p><ul><li><strong>Static documents</strong> change rarely: last quarter’s board deck, a signed contract. Index once. That is exactly the Qdrant-plus-BM25 path that runs today.</li><li><strong>Volatile documents</strong> change constantly: a wiki, a ticketing system. Re-embedding the world on every change is the wrong model. The better approach is to <strong>not copy them at all</strong> and query the source in place at question time, the same “data does not move” principle as the structured side.</li></ul><blockquote>The volatile path is the cleaner design, and it is <strong>not built.</strong> It is an open decision, deliberately left as a seam rather than filled with code I would have to rip out later. I would rather name the seam than pretend the static path covers a case it does not.</blockquote><h3>One access decision for two pipelines</h3><p>The thread I most want to tie off is access control, because it is where the fusion design is most opinionated.</p><p>In a system with two retrieval pipelines, the dangerous failure mode is <strong>two access-control implementations that drift apart.</strong> So the design is a single decision both pipelines honor in their own idiom:</p><ul><li>One component <strong>computes and signs</strong> the effective scope (the intersection of what the user’s identity grants and what this query is allowed to reach).</li><li>Every pipeline <strong>verifies the signature and applies the scope locally</strong>, without phoning home per check.</li><li>The structured pipeline applies it by <strong>compiling row filters and column masks into the SQL syntax tree</strong> (Part 3). The RAG pipeline applies it by <strong>filtering folders and chunks.</strong> Same decision, two enforcement styles.</li><li>It <strong>fails closed</strong>: an unreachable policy component means serve only your own ungated data and deny anything shared; an invalid scope is a denial, never a bypass.</li></ul><blockquote><strong>Shipped vs. next:</strong> what runs today is the <strong>per-pipeline enforcement</strong> (the SQL AST rewriting from Part 3, the folder filter above), each correct on its own. The single signed scope that formally unifies them is <strong>roadmap</strong>. But I built both enforcers against the same scope object on purpose, so unifying them later is a consolidation, not a rewrite. The shape was chosen in advance to make the future cheap.</blockquote><h3>Walking the blended question end to end</h3><p>Here is the churn question as the target design answers it, with built and designed labeled as I go.</p><ol><li>The question arrives with the user’s identity. The bridge mints a signed scope. <strong>(designed)</strong></li><li>The classifier returns <strong>hybrid</strong>. Both legs start. <strong>(designed)</strong></li><li>Each resolves its entities through the <strong>same</strong> subject graph and the cascade from Part 3, so both legs talk about the same canonical entities. <strong>(cascade built; resolving the RAG leg through it, designed)</strong></li><li>The structured leg reads schema from the in-memory cache, builds SQL with graph joins, compiles the scope into the WHERE, and runs in place for the actual churn numbers. <strong>(built)</strong></li><li>The unstructured leg retrieves the deck passages by hybrid search and filters by the scope. <strong>(retrieval built; scope-as-signed-pass, designed)</strong></li><li>The two fuse on the shared entities. One answer: the numbers, the passages, citations to both, caveats, confidence, a trace id. <strong>(fusion designed)</strong></li></ol><p>One question, two pipelines, three graphs, one access decision, one answer.</p><h3>Key takeaways</h3><ul><li><strong>Make the entity hub shared before you make the pipelines smart.</strong> Fusion is tractable only because both sides resolve through the same canonical entities. If your SQL side and your document side invent their own notion of “customer,” you can never join them, and you find out late.</li><li><strong>Use hybrid retrieval, and fuse by rank, not by score.</strong> Vector and keyword search fail in opposite directions; RRF combines them without the false precision of normalizing incomparable scores.</li><li><strong>Reuse one access-scope object across every retrieval shape,</strong> even if you enforce it differently in each. The unification can come later; the shared object cannot.</li><li><strong>Be candid about the seams.</strong> Honest scaffolding is more credible than a polished illusion. The edges are where someone can tell whether you actually built the thing.</li></ul><p>That is the series. <strong>A map</strong> (Part 2) that lets a model reason about a database it has never seen. <strong>A conversation</strong> (Part 3) that turns a sentence into a safe answer. And <strong>a reach</strong> (this part) past the database into documents, joined at the entity hub, governed by one access decision.</p><p>The hard problem from Part 1 was never that the model was not smart enough. It was that the parts that matter most (joins, cardinality, security, fusion) are not language problems, and you do not solve them by making the model smarter. You solve them with structure. Thanks for reading all four.</p><p><em>Back to the start: Part 1, </em>Text-to-SQL Looks Solved. It Isn’t<em>. Part 2, </em>Your LLM Needs a Map<em>. Part 3, </em>Never Let the LLM Write the Joins<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd124324e750" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/one-question-a-number-and-a-paragraph-bd124324e750">One Question, a Number and a Paragraph</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never Let the LLM Write the Joins]]></title>
            <link>https://pub.towardsai.net/never-let-the-llm-write-the-joins-fe5d1f1ccbe0?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5d1f1ccbe0</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 19:01:00 GMT</pubDate>
            <atom:updated>2026-06-16T19:01:00.754Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The subject graph, and the one architectural line that made me comfortable putting “talk to your database” in front of real users with real permissions.</em></h4><p><em>Part 3 of 4 on building a conversational analytics engine. ~11 min read.</em></p><p>Part 2 built a map: three databases introspected and enriched into a domain graph. Tables, columns, join paths, business meaning, and the security rules, all sitting in a graph with a fast in-memory snapshot in front of it.</p><p>A map answers nothing on its own.</p><p>Nobody asks <em>“describe the schema.”</em> They ask <em>“how many orders did Bike World place last quarter, in my territory,”</em> and they expect a number, computed from data they are actually allowed to see. This article is the machine that does that.</p><p>Back in Part 1, I listed seven walls that break text-to-SQL on real data. <strong>This is where four of them fall:</strong> the fan-out trap (Wall 3), ambiguity (Wall 4), security (Wall 6), reproducibility (Wall 7), plus the cross-source half of Wall 5. If Part 2 was the “why a map,” this is the “why a particular shape of pipeline.”</p><p>And I want to lead with that shape, because it is the single most important idea in this entire series.</p><p><strong>The big idea:</strong> a query is <strong>not</strong> “hand the question to an LLM and let it call some tools.” I split it in two.</p><ul><li><strong>Phase A is deterministic planning.</strong> It decides <em>what</em> to do (tables, entities, filters), scoped to who is asking. One LLM call, for reading intent. Everything else is code.</li><li><strong>Phase B is LLM-driven execution.</strong> It <em>does</em> the plan (writes SQL, runs it, recovers, answers).</li><li><strong>The line between them is the product.</strong> Security is never the model’s job. Joins are never the model’s job. The model does the creative parts; code does the parts that must be safe and reproducible.</li></ul><p><strong>TL;DR</strong></p><ul><li>The <strong>subject graph</strong> resolves the specific things a user names (“Bike World” becomes StoreID 620). It is a cache, not a copy.</li><li><strong>Phase A</strong> plans deterministically and produces a frozen plan. <strong>Phase B</strong> is a bounded ReAct loop that executes it.</li><li>The LLM writes only the SELECT and WHERE. <strong>Joins come from the graph. Security is injected by rewriting the SQL. Cardinality is fixed by a planner.</strong> None of those are left to the model.</li><li>Honest limit: today the conversation is <strong>single-shot</strong>. Follow-up memory is built but not wired.</li></ul><p>Throughout, one example: a sales rep I will call <strong>Dana</strong>, scoped to the Southwest territory, allowed to see sales data, asks <strong>“Show orders for customer Bike World.”</strong> Watch what each stage does to that sentence.</p><h3>The subject graph: concepts vs. actual things</h3><p>The domain graph from Part 2 knows about <strong>types</strong>. It knows CUSTOMER is a concept that lives in a table with a name column.</p><p>It does not know that <strong>“Bike World” is a specific store</strong> with the key StoreID 620. That is an instance, and instances live in the <strong>subject graph</strong>.</p><p>A canonical entity in the subject graph has:</p><ul><li>a stable <strong>id</strong> (something like entity:organization:bikeworld_a1b2c3d4)</li><li>a <strong>name</strong> and <strong>type</strong></li><li>a set of <strong>aliases</strong></li><li>a list of <strong>source links</strong>, each pointing at exactly where the entity lives: StoreID 620, in the StoreID column, of Sales.Store, in the SQL Server source</li><li>an <strong>access level</strong>, so resolved entities are protected by the same machinery as tables</li></ul><blockquote><strong>The defining property: it is a cache, not a copy.</strong> It is not pre-loaded with every customer. That would be copying the data, the one thing I refuse to do. It starts essentially empty and <strong>fills lazily</strong>, remembering only the names real users actually ask about. The rows stay in the source database. The subject graph just remembers the mapping from “a name a human typed” to “a key the database understands.”</blockquote><h3>Resolving a name (the cascade)</h3><p>When the pipeline needs to turn “Bike World” into a key, it runs a cascade, ordered from cheapest-and-most-certain to most-expensive-and-least-certain. It stops as soon as it is confident.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*OIonCJhCmziLIBXvCZXayQ.png" /><figcaption><strong>entity-resolution-cascade</strong></figcaption></figure><p><strong>How to read it (with the real numbers, because the numbers are the design):</strong></p><ul><li><strong>Cache</strong> keyed on the name. Stores <em>unfiltered</em> results; RBAC applies after, so users with different permissions can share an entry.</li><li><strong>Exact</strong> match: canonical name scores <strong>0.95</strong>, an alias <strong>0.90</strong>. One clean hit above the <strong>0.70</strong> threshold short-circuits the whole thing.</li><li><strong>Fuzzy</strong> match: the rapidfuzz ratio scorer at a threshold of <strong>80/100</strong>, with tiered confidence so it never pretends to be as sure as an exact match (<strong>0.65 to 0.85</strong>).</li><li><strong>Semantic</strong> match: I will be straight with you. <strong>It is a placeholder.</strong> It sits in the right position in the cascade and returns nothing today. The plan is embedding similarity; the wiring is not done. Wherever you read “exact, fuzzy, semantic, source,” know the semantic rung is a stub.</li><li><strong>Source-DB</strong> lookup: hit the real table. An exact name scores <strong>0.95</strong>, and a success gets <strong>written back</strong> into the subject graph so the next person skips to a cache hit. That is the lazy cache filling.</li></ul><p><strong>Two design choices I would defend in any review:</strong></p><ul><li><strong>“Ambiguous” is a first-class outcome.</strong> Two close candidates returns <em>“did you mean the Seattle or the Dallas store”</em>, not a coin flip. (This is the fix for Wall 4.)</li><li><strong>Resolution is fail-closed.</strong> The cascade runs and caches unfiltered, but nothing returns until it passes RBAC: can this user see the entity, its links, and any restricted properties. No scope and no trusted-caller flag means <strong>deny</strong>, not leak.</li></ul><h3>Phase A: planning, stage by stage</h3><p>Dana’s question comes in. Phase A turns it into a plan without writing one character of SQL.</p><ul><li><strong>User context assembly.</strong> Load who Dana is: role (sales rep), territory (Southwest), permissions (sales schema), saved vocabulary and preferences. Everything downstream is scoped by this.</li><li><strong>Intent classification</strong> (the one LLM call). Returns a structured verdict: intent type (a SQL query), entity types (CUSTOMER and the order entity), confidence, and a default join type. A second focused call pulls “Bike World” out as a value tied to CUSTOMER. A type gate then throws out any extracted value that does not fit the column’s type.</li><li><strong>Semantic resolution</strong> (the 2-pass vector search from Part 2). Turns “orders” into the order entity <strong>by meaning, not spelling</strong>, and flags ambiguity when two concepts score within a hair of each other.</li><li><strong>Scope resolution.</strong> Turns words like “my team” into row-filter hints, on pre-derived rules, in a few milliseconds. One subtlety I am careful about: this produces <em>relevance</em> hints, <strong>not security</strong>. Convenience and access control are different things, and conflating them is how you build something convenient and insecure.</li><li><strong>Routing</strong> (the deterministic core). Maps entity types to real tables, assigns each entity a role (the order entity is the subject, CUSTOMER is a filter) using a four-rule scoring system with <strong>no LLM</strong>, finds the foreign-key join path by traversing the domain graph, grounds “Bike World” to StoreID 620, and detects whether the query spans sources.</li><li><strong>RBAC Checkpoint 1.</strong> The first of two security gates. Coarse and early: drop any table the user may not see <em>before the model ever sees the schema</em>. Dana keeps her sales tables. Had she asked about HR salaries, that table would vanish here, and the model would never learn its column names.</li></ul><blockquote><strong>The output of Phase A is a frozen plan</strong> plus a warm entity cache. No SQL exists yet. Phase A decides everything that has to be decided safely, and hands the model a plan it would have to work hard to misuse.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_tmjIpMlNID-y_BK7jlog.png" /><figcaption><strong>Two phase pipeline</strong></figcaption></figure><p><strong>How to read it:</strong> the question flows top to bottom through Phase A (all blue, deterministic, except the one purple intent call), produces a frozen plan, and only then enters the Phase B loop where the model actually works. The two red boxes are the security gates, one per phase.</p><h3>Phase B: where the model actually works</h3><p>Phase B is a small state machine with three nodes:</p><ul><li><strong>agent</strong> node: the LLM reasons and decides the next action</li><li><strong>tools</strong> node: executes exactly one tool, appends the result</li><li><strong>synthesize</strong> node: writes the final answer</li></ul><p>It loops between thinking and acting, then synthesizes. And it is <strong>bounded</strong>: at most <strong>10 reasoning iterations</strong> and <strong>15 tool calls</strong> per query, with a 30-second timeout per tool.</p><blockquote>Those limits are not decoration. They are the difference between “the agent retries a failed query once and succeeds” and “the agent burns your budget in an infinite loop of slightly-wrong SQL.” (This is part of the fix for Wall 7.)</blockquote><p>The agent has 11 tools but most queries touch two or three. A nice detail: resolve_entity <em>looks</em> like a live tool, but because Phase A already resolved Bike World into the warm cache, it usually just returns the cached answer if the confidence is above 0.5. The same operation is both &quot;a tool the agent can call&quot; and &quot;something Phase A already did.&quot;</p><h3>Generating SQL without letting the model touch the dangerous parts</h3><p>This is where the two-phase philosophy pays off most concretely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftxNPlB8sf56Vhs_0IEYCQ.png" /><figcaption><strong>Sql generate and execute</strong></figcaption></figure><p><strong>How to read it:</strong> the model (the one purple box) writes only a slice of the query. Everything else is deterministic.</p><ul><li><strong>The joins come from the graph,</strong> not the model. A join-tree builder traverses the foreign-key edges. No path between two tables means a loud error, never a guessed join. (This is the fix for Wall 2.)</li><li><strong>The model gets a whitelist</strong> of real columns and writes only the SELECT, WHERE, GROUP BY, and limit. Every column it returns is validated. A made-up or unqualified column rejects the whole generation. <strong>Unvalidated SQL never reaches the database.</strong></li><li><strong>Filters get merged in by code,</strong> not the model.</li></ul><blockquote>The load-bearing rule, again: the LLM never writes the joins. A made-up join is a silently wrong answer, and silently wrong is the worst failure an analytics system has.</blockquote><h3>The fan-out trap (Wall 3, finally solved)</h3><p>Let me tell you about the bug that taught me to respect cardinality.</p><p>Ask for total revenue per customer. The query joins customers to orders to line-items. The moment you SUM across a <strong>one-to-many</strong> join, the value repeats once per child row.</p><ul><li>A customer with one $100 order and five line items reports <strong>$500</strong>.</li><li>The SQL is perfect. The number is garbage. <strong>Nobody notices.</strong></li></ul><p>So I built a deterministic planner that rewrites the SQL to prevent it. It keys entirely on the cardinality_class metadata from Part 2 (the PRESERVING vs MULTIPLYING tags), touches no table names, never calls the model, and <strong>fails open</strong> (if it cannot reason safely, it returns the original).</p><p>Its strategies, picked by what the query actually references:</p><ul><li><strong>Prune</strong> a multiplying join that is joined but never used (transitively, so chains collapse).</li><li><strong>Semi-join</strong>: a child used only in the WHERE becomes an EXISTS subquery, which filters without multiplying.</li><li><strong>Per-grain subqueries</strong>: two measures at two different grains get computed separately and joined back with a full outer join and null-safe matching.</li><li><strong>Count anchoring</strong> so a plain row count does not lie either.</li></ul><blockquote>Why is this in deterministic code and not the prompt? Because “be careful about fan-out” is right most of the time, and “most of the time” is not a number you put on a financial dashboard. Cardinality correctness is provable from graph metadata, so I prove it.</blockquote><h3>The second security gate (Wall 6)</h3><p>When the agent calls execute_sql, the SQL is correct but not yet safe. <strong>RBAC Checkpoint 2</strong> runs here, and it is the fine-grained one.</p><ul><li>Where Checkpoint 1 decided <em>which tables</em>, Checkpoint 2 decides <em>which rows and columns</em>.</li><li>It rewrites the SQL’s syntax tree: it <strong>injects mandatory and row-level filters</strong> straight into the WHERE. Dana&#39;s query silently gains a Southwest-territory constraint.</li><li>A failed access check injects <strong>WHERE 1=0</strong>, a silent deny that returns zero rows rather than leaking the existence of restricted data.</li><li>Restricted columns are <strong>masked</strong> on the way out.</li></ul><blockquote>The entire RBAC path is deterministic. There is <strong>no LLM anywhere in it</strong>, by design. Access control you cannot reproduce is access control you cannot defend.</blockquote><p>Then the agent synthesizes: it writes “Bike World placed 8 orders last quarter,” with any caveats (like “limited to your territory”) and a confidence, plus the SQL and rows underneath.</p><h3>The validation mesh</h3><p>Threaded through both phases is a layer I think of as a mesh, not a stage: <strong>eight validators, forty-four checks</strong>, firing at hook points all over the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q0G5xnpU1oEi1MtrI6Lkw.png" /><figcaption><strong>Validation mesh</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Three validators run in Phase A,</strong> and two of them (route, entity) can <strong>hard-abort</strong> the query before the agent loop ever starts. No point generating SQL for a query that was never going to work.</li><li><strong>The rest run in Phase B,</strong> guarding execution and the answer. Most checks are deterministic; a few are LLM calls (does the answer follow from the data), and those get a strict budget of <strong>three LLM validation calls per query</strong>.</li></ul><p>Two choices that matter:</p><ul><li><strong>Every validator is wrapped in try/except.</strong> A validator that crashes, or is disabled, never blocks a query. Safety code that can take down the system it protects is a liability, so it is built to fail safe.</li><li><strong>Checks have severity tiers:</strong> block, warn (becomes a caveat, lowers confidence), or log-only. Not every problem should stop a query. Some just attach a footnote.</li></ul><blockquote><strong>Shipped vs. next (an honest naming note):</strong> the “memory validator” in this mesh has nothing to do with conversation memory. It checks whether a cached result went stale. The actual conversation is <strong>single-shot today</strong>. The read side of memory is wired (the system loads your saved vocabulary and scope on every query), but the write-back that would let Dana ask “and the quarter before that?” and have it understand “that” is built and <strong>not yet connected</strong>. Ask a follow-up today and it is treated as a brand-new question. I would rather say that than imply a multi-turn experience I have not finished.</blockquote><h3>When the data lives in two databases at once (Wall 5)</h3><p>Some questions span sources: SQL Server sales joined to Postgres production. There is <strong>no cross-database </strong><strong>JOIN</strong> here, and no copying one source into the other.</p><ul><li>A federated executor <strong>decomposes</strong> the query by source.</li><li>It generates and runs a <strong>separate, independently RBAC-enforced</strong> query against each source, pulling only the rows that survive each source’s own rules.</li><li>It <strong>joins the results in the application layer</strong>, in memory, by matching on entity keys.</li><li>The requested join type (inner, left, right, full outer) is honored by deciding which side’s unmatched rows to keep.</li></ul><blockquote>Each database only ever sees a query for its own data, scoped to what the user may see. The rows are stitched together only after each has been cleared. <strong>The data never leaves its home system.</strong> That property is non-negotiable.</blockquote><h3>Why keep both a plan and a loop?</h3><p>Fair question: if Phase A plans everything, what is the loop for? They fail in different ways, and I wanted coverage on both.</p><ul><li><strong>Job</strong> (<strong>Deterministic plan (Phase A)</strong>: decide <em>what</em>: tables, entities, filters; <strong>ReAct loop (Phase B)</strong>: <em>do</em> it: write SQL, run, answer, recover)</li><li><strong>LLM?</strong> (<strong>Deterministic plan (Phase A)</strong>: only intent classification; <strong>ReAct loop (Phase B)</strong>: yes: SQL text + prose)</li><li><strong>Gives you</strong> (<strong>Deterministic plan (Phase A)</strong>: safety, reproducibility, auditability, speed; <strong>ReAct loop (Phase B)</strong>: execution, self-correction, tool choice)</li><li><strong>Costs you</strong> (<strong>Deterministic plan (Phase A)</strong>: adaptability (the plan is frozen); <strong>ReAct loop (Phase B)</strong>: nondeterminism (must be fenced))</li><li><strong>The loop earns its keep</strong> when the model generates SQL with a wrong column, the database errors, and the agent reads the error, regenerates, and succeeds. A straight pipeline cannot self-heal.</li><li><strong>The plan earns its keep</strong> by making sure the model can retry SQL all it wants but can never retry its way into a forbidden table or an invented join.</li></ul><blockquote><strong>The honest current limit:</strong> today the agent is locked into Phase A’s plan. It can fix a bad query, but not a bad plan. If routing picked the wrong table, retrying SQL will not help, because the agent cannot re-route mid-flight. The roadmap is to make the planning steps themselves into tools the agent can re-call inside the loop. That is the difference between a system shaped like an agent and one that is fully agentic, and it is the next real piece of work.</blockquote><h3>Key takeaways</h3><ul><li><strong>Split the stochastic from the deterministic, and be ruthless about which is which.</strong> The model understands questions and writes creative SQL well. It is unaccountable at deciding access and inventing joins. Opposite sides of a hard line.</li><li><strong>Resolve the things a user names through a cheap-to-expensive cascade,</strong> and let “ambiguous” ask a question instead of guessing. A confident wrong answer is worse than an honest “which one?”</li><li><strong>Prove what you can prove with metadata</strong> instead of asking the model to be careful. Cardinality and access control are both provable from the graph, so they live in code, never in a prompt.</li><li><strong>Make your safety layer unable to take down the thing it protects.</strong> Wrap it, budget it, tier it.</li></ul><p>In <strong>Part 4</strong>, I pick up the thread I keep deferring: documents. Everything here was structured data. Real questions often need a number <em>and</em> a paragraph from a PDF. The subject graph is meant to be the hub that ties the two together, and that is the most forward-looking, and most honest, story of the four.</p><p><em>Next up, Part 4: Two Pipelines, Three Graphs, on fusing structured and unstructured retrieval with RAG.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5d1f1ccbe0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/never-let-the-llm-write-the-joins-fe5d1f1ccbe0">Never Let the LLM Write the Joins</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your LLM Needs a Map!]]></title>
            <link>https://pub.towardsai.net/your-llm-needs-a-map-f145583abf61?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f145583abf61</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 21:01:00 GMT</pubDate>
            <atom:updated>2026-06-13T21:01:00.721Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Before I built the chatbot, I built the map. Here is how I turn three messy databases into one graph an LLM can actually reason about.</em></h4><p><em>Part 2 of 4 on building a conversational analytics engine. ~9 min read.</em></p><p>Point a language model at a raw database schema and ask it a real business question.</p><p>Watch it guess.</p><p>It sees Sales.SalesOrderHeader, Person.BusinessEntity, and three hundred columns named things like rowguid and TerritoryID. It has no idea that &quot;customer&quot; is one table, &quot;orders&quot; is another, and the two connect through a key it would never find on its own. So it invents a join. The SQL runs. A number comes back.</p><p>The number is wrong, and nobody notices.</p><p>That single failure mode, <strong>the confident wrong answer</strong>, is the reason this whole system exists. In Part 1, I called it the most dangerous of the seven walls that break text-to-SQL on real data. This article builds the first half of the fix.</p><p>And it is why I spent most of my time not on the chatbot, but on the unglamorous thing that comes before it: a metadata map I call the <strong>domain graph</strong>.</p><p><strong>TL;DR</strong></p><ul><li>information_schema tells an LLM the <em>shape</em> of your data. It says nothing about the <em>meaning</em>. Meaning is the whole game.</li><li>I build a domain graph <strong>offline</strong>: introspect the databases, enrich the schema with an LLM once, store the result as a graph plus a vector index.</li><li>The graph holds <strong>metadata only</strong>. The actual rows never move. Queries run in place.</li><li>The payoff: at runtime, the hard thinking is already done and frozen, so answers are <strong>fast, reproducible, and safe</strong>.</li></ul><h3>The setup: three databases that disagree with each other</h3><p>The system runs on an AdventureWorks dataset (Microsoft’s public sample, so you can verify every name here) spread across three engines:</p><ul><li><strong>PostgreSQL</strong> for production and purchasing</li><li><strong>SQL Server</strong> for sales and person data</li><li><strong>A CSV-backed store</strong> for HR</li></ul><p>Different engines. Different SQL dialects. Different conventions. And the numbers that should worry you:</p><ul><li><strong>Tables</strong>: 71</li><li><strong>Columns</strong>: 472</li><li><strong>Foreign keys actually declared</strong>: 44</li></ul><p>That last row is the problem in miniature. Real databases are full of relationships that live in someone’s head and in the application code but were <strong>never written down as constraints</strong>. The CSV source had zero declared keys, because CSV files have no constraints at all.</p><p>So when a user asks <em>“show me orders for the customer Bike World,”</em> the planner needs to know, reliably and ahead of time:</p><ul><li>that <strong>“customer” and “orders”</strong> map to specific tables in a specific source,</li><li>that those tables <strong>join on a specific column</strong>,</li><li>that <strong>“Bike World”</strong> is a value it can resolve to a key,</li><li>and that the person asking is <strong>even allowed</strong> to see sales data.</li></ul><p>None of that is safely derivable at query time by a model staring at a schema dump. All of it is derivable <strong>once, offline</strong>. That offline derivation is the domain graph build.</p><h3>The whole pipeline in one picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7c4CY1cl8GjvSquwx3QHQ.png" /><figcaption><strong>Domain graph bootstrap</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Left side, cheap and deterministic.</strong> Introspection just reads the databases.</li><li><strong>Middle, expensive and fuzzy.</strong> The LLM enrichment runs <strong>once, offline</strong>, never on the hot path.</li><li><strong>Right side, the artifacts.</strong> A graph (for structure) and a vector index (for meaning).</li><li><strong>The takeaway:</strong> by the time a user shows up, the hard thinking is already done and frozen.</li></ul><p>The rest of this article is just those five steps, in order.</p><h3>Step 1: Introspection, and the attributes that actually matter</h3><p>Introspection is the deterministic read of each database. One introspector per engine, all returning the same typed structure.</p><p><strong>One rule I enforced from day one:</strong> introspectors <em>read</em> databases and hand back plain data. They never write to the graph. Keeping the reader and the writer separate saved me later, when the graph build became its own concern.</p><p>The leverage is in the <strong>per-column record</strong>. For every column, I keep:</p><ul><li>name and data_type: the obvious ones</li><li>nullable: later decides whether a join is INNER or LEFT</li><li>is_primary_key / is_foreign_key</li><li>pk_source: either database or heuristic</li><li>pk_confidence: a number from 0 to 1</li><li>cardinality: distinct value count</li><li>null_percentage</li><li>sample_values: real values pulled from the column</li></ul><p>Two of those are where a naive introspector quietly fails.</p><h3>Primary keys, when the database refuses to tell you</h3><p>Plenty of tables (especially the CSV ones) have <strong>no declared primary key</strong>. A planner that gives up there is useless. So when there is no database key, I score every column and pick the best candidate.</p><p>The heuristic is deliberately boring, because <strong>boring is auditable</strong>:</p><ol><li><strong>Exclusion gate.</strong> Throw out columns that look like keys but are not: rowguid, *_guid, *_uuid, modifieddate, *_hash, *_version, and friends.</li><li><strong>Hard requirements.</strong> The column must be <strong>unique</strong> (distinct count equals row count) and <strong>complete</strong> (zero nulls). Fail either, rejected, no matter how key-like the name.</li><li><strong>Score what survives:</strong></li></ol><ul><li>Unique and complete: <strong>+0.70</strong> (the base)</li><li>Identifier-style name (*id, *_id, id): <strong>+0.15</strong></li><li>Softer pattern (*_key, *_pk, *_seq): <strong>+0.10</strong></li><li>Integer / serial type: <strong>+0.10</strong>, UUID / string: <strong>+0.05</strong></li><li>First column in the table: <strong>+0.05</strong></li></ul><ol><li><strong>Accept</strong> anything scoring <strong>0.70 or higher</strong>.</li></ol><p>An accepted guess gets pk_source = &quot;heuristic&quot; and pk_confidence set to its score. A declared key gets pk_source = &quot;database&quot; and confidence exactly 1.0.</p><blockquote><strong>Why I like this:</strong> it never lies about its certainty. A guessed key carries its own doubt in a field you can read downstream.</blockquote><h3>The sampling trick that finds hidden relationships</h3><p>Here is the non-obvious one. For most columns I grab a capped sample. But when a column’s cardinality is <strong>low</strong>, I fetch <em>every</em> distinct value, not a sample.</p><p>Why pull all of them?</p><ul><li>Those complete value sets are how I later <strong>discover the foreign keys nobody declared</strong>.</li><li>With the full set of values in a CSV column, and the full set of primary-key values in a candidate target, I can compute <strong>exactly how much they overlap</strong>.</li><li>High overlap is strong evidence of a real relationship. You cannot get that from a 5-row sample.</li></ul><p>The introspector spends a little more on low-cardinality columns <em>specifically</em> to make the next step possible. Everything that comes out gets written to raw_schema.json, the contract between the deterministic world and the LLM world.</p><h3>Step 2: Letting an LLM do the one thing only it can do</h3><p>The schema is captured, but it is still just structure. It does not know that SalesOrderHeader is what a human means by &quot;orders,&quot; that a salesperson calls revenue &quot;rev,&quot; or that &quot;last quarter&quot; is a date range.</p><p>This is where an LLM comes in. And the single most important decision in the whole system is <strong>when</strong>.</p><blockquote><strong>I bring the LLM in offline, at build time. Never on the hot path for this work.</strong></blockquote><p>The model enriches the schema into business knowledge <strong>once</strong>, the output gets written to versioned files, and at query time everything reads those frozen files. The intelligence is precomputed. That is the trade that makes the system both smart and fast.</p><p>Several generators run in order, each feeding the next:</p><ul><li><strong>Relationship inference</strong> (Reads: sample-value overlaps; Produces: foreign keys nobody declared; LLM?: Yes (verified by overlap))</li><li><strong>Entity discovery</strong> (Reads: schema + relationships; Produces: which tables are real business entities; LLM?: No (pure heuristic))</li><li><strong>Entity analysis</strong> (Reads: discovered entities; Produces: descriptions, synonyms, name expressions, sample questions; LLM?: Yes)</li><li><strong>Business domains</strong> (Reads: entities; Produces: groupings like HR, purchasing, production; LLM?: Yes)</li><li><strong>Metrics catalog</strong> (Reads: numeric columns; Produces: named measures as real SQL (total revenue, AOV); LLM?: Yes)</li><li><strong>Glossary</strong> (Reads: everything above; Produces: “last quarter,” “top,” status filters; LLM?: Yes)</li></ul><p>A few things worth pulling out:</p><ul><li><strong>Relationship inference does not trust the model alone.</strong> A candidate is accepted only if the LLM’s confidence is <strong>at least 0.80</strong> <em>and</em> the measured value overlap is <strong>at least 0.50</strong>. The model proposes; ground-truth overlap disposes. On this dataset that turned 40 candidates into 34 accepted relationships.</li><li><strong>Entity discovery is deliberately <em>not</em> an LLM step.</strong> Deciding what your core nouns are is too important to leave to a sampling temperature. It scores tables instead: a primary join key scores 0.95, a table referenced by 3+ foreign keys scores 0.90, and so on.</li><li><strong>Entity analysis is where the LLM earns its seat.</strong> For a person entity, it generates the name expression FirstName || &#39; &#39; || LastName. It writes the synonyms that let &quot;client&quot; find CUSTOMER. It drafts the sample questions a real user would ask.</li><li><strong>The glossary stores meaning, never SQL.</strong> “Last quarter” becomes a <em>relative date range</em>, not a dialect-specific date function. That keeps meaning portable across three SQL engines.</li></ul><h3>The trick that makes regeneration safe</h3><p>There is an operational trap hiding in all this generated config:</p><ul><li>The LLM gets you ~90% of the way.</li><li>A human expert fixes the other ~10%.</li><li>Then you regenerate, and <strong>their work is gone</strong>.</li></ul><p>I have watched teams “solve” this by never regenerating, and living with stale config forever. My answer is an ownership split enforced at the file level:</p><ul><li><strong>system_owned/</strong> holds generated files. Treated as disposable. Delete them, rerun the build, they come back.</li><li><strong>user_owned/</strong> holds human corrections as small <strong>override files</strong>.</li><li>At load time, a loader reads the generated base, reads the override, and <strong>deep-merges</strong> them. The override wins on any conflict.</li></ul><blockquote><strong>The payoff, from a real incident:</strong> an expert once added a couple of synonyms through an override file. Months later the entire base config got regenerated from scratch, and those synonyms simply <strong>re-merged on top, untouched</strong>. Nobody had to remember anything. That is the difference between config you can maintain and config you are afraid to touch.</blockquote><h3>Step 3: Materializing the graph</h3><p>Now the build turns all that validated config into an actual graph in Neo4j. This is the heart of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7M29taUIIbLhBJGkCni9w.png" /><figcaption><strong>Domain graph node and edge</strong></figcaption></figure><p><strong>How to read it (the four design decisions that matter):</strong></p><ul><li><strong>Every node wears two labels.</strong> A table is Domain:Table, a column is Domain:Column. The first label is the layer, the second is the type. This is what lets one Neo4j database hold three graphs (domain, subject, lexical) side by side. The layer label is the namespace.</li><li><strong>The edges carry the relationships an LLM should never invent.</strong> FOREIGN_KEY edges hold the real join key plus a confidence. ENTITY_LINK edges carry a cardinality_class (PRESERVING or MULTIPLYING) that records whether following the link fans out rows. The SQL pipeline traverses these for its joins.</li><li><strong>Foreign keys have provenance.</strong> A single FK can come from four places (declared, inferred, cross-source, override), merged with a strict precedence, each tagged with where it came from. Deleting a wrong relationship requires a written reason, because a removed join path deserves an audit trail.</li><li><strong>Security lives on the nodes.</strong> A table carries its access_level, its restricted_properties, whether it requires_mandatory_filter, and its row-security policies. This is the raw material the runtime uses to enforce access by rewriting SQL.</li></ul><blockquote><strong>The load-bearing rule:</strong> the LLM never writes the joins. It gets them from the graph, deterministically, or the query fails loudly with “no path found” rather than hallucinating a relationship. A made-up join is a silently wrong answer, and silently wrong is the worst failure an analytics system has.</blockquote><p>Two engineering footnotes: Neo4j properties must be flat scalars, so lists get JSON-serialized in and parsed out. And every insert is an idempotent MERGE on a stable id, so I can <strong>rerun the build over an existing graph</strong> without creating duplicates. Rebuilds are routine, not surgery.</p><h3>Step 4: The semantic index, because a graph cannot read minds</h3><p>The graph is perfect at one kind of question: <em>given a concept, how does it connect?</em> Given CUSTOMER, what table is it, how does it reach ORDERS? That is exact-key lookup and traversal.</p><p>It is hopeless at the question that actually shows up first: <em>the user typed “orders,” so which concept did they mean?</em> That is similarity, not traversal. A graph has no notion of “close.”</p><p>So I built a second index in <strong>Qdrant</strong> that does nothing but answer “what did this phrase most likely mean.” Six collections:</p><ul><li><strong>C1 semantic entities</strong> (One point is: an entity type + its description + synonyms; Queried at runtime?: Yes)</li><li><strong>C2 semantic metrics</strong> (One point is: a named metric; Queried at runtime?: Yes)</li><li><strong>C3 glossary</strong> (One point is: a glossary term; Queried at runtime?: Yes)</li><li><strong>C4 columns</strong> (One point is: a single column; Queried at runtime?: <strong>Built, not yet queried</strong>)</li><li><strong>C5 entity values</strong> (One point is: a sample value; Queried at runtime?: <strong>Built, not yet queried</strong>)</li><li><strong>C6 vocabulary</strong> (One point is: a user’s personal alias; Queried at runtime?: Yes)</li></ul><p>Each point is text embedded into a 1536-dimension vector (OpenAI text-embedding-3-small, cosine distance). The clever one is <strong>C1</strong>, where the embedded text is built from a template:</p><blockquote>&quot;{ENTITY_TYPE}: {description}. Also known as: {synonyms}. Common questions: {sample questions}&quot;</blockquote><p>That template is <strong>exactly why “orders” finds </strong><strong>SALESORDERHEADER</strong> at runtime. The user&#39;s word is cosine-closest to that blob of description and synonyms, so the match happens <strong>by meaning, not by spelling</strong>. The graph then does the exact lookup to the real table.</p><p>The two stores form a pipeline, and neither can do the other’s job:</p><blockquote><strong>Qdrant maps language to concept. Neo4j maps concept to structure.</strong> &quot;orders&quot; → (similarity) → SALESORDERHEADER → (exact lookup) → Sales.SalesOrderHeader + columns + FK to Customer</blockquote><blockquote><strong>Shipped vs. next:</strong> I will be straight about this, because pretending otherwise is the wrong kind of credibility. <strong>Four of the six collections are live</strong> (entities, metrics, glossary, vocabulary). <strong>Two are built on every bootstrap but not yet read</strong> (columns, entity values). They are deferred, with a note in the code. The build is cheap and wiring them in is a small, isolated change for later. If you assumed every collection was on the hot path, it is not, and I would rather tell you.</blockquote><h3>Step 5: Making the runtime never pay for any of this</h3><p>When a real query runs, it does <strong>not</strong> query Neo4j for schema metadata. It reads an in-memory snapshot loaded <strong>once</strong> at startup, then served entirely from RAM.</p><p>The cache is blunt about its contract, and I wrote it that way:</p><ul><li>Neo4j is the single source of truth. <strong>No YAML fallback.</strong></li><li>It <strong>fails fast and loud</strong> if Neo4j is missing at startup.</li><li>After it loads, there is <strong>no per-query I/O</strong>. Every lookup is a dictionary read.</li><li>It <strong>preserves the security fields</strong> (access_level, restricted_properties), because dropping them would quietly reopen an access-control gap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qX23RsmG8SIi_k_54R6xA.png" /><figcaption><strong>Domain graph runtime read</strong></figcaption></figure><p><strong>How to read it:</strong></p><ul><li><strong>Two read surfaces, not one.</strong> The in-RAM snapshot is the hot path. A live Cypher reader handles the rare, occasional schema lookups.</li><li><strong>The hot path never touches the network.</strong> Schema reads happen in the <em>tightest loops</em> of the planner, sometimes dozens of times per question.</li><li><strong>Why it matters:</strong> if each of those were a round-trip to the graph, every query would crawl. This one placement decision quietly determines whether the whole system feels instant or sluggish.</li></ul><p>The rule: <strong>the graph is the source of truth and gets read in bulk at startup; the hot path reads a local snapshot.</strong> The domain graph is immutable between builds, so the snapshot never goes stale mid-session.</p><h3>Key takeaways</h3><p>If you build one of these, steal the sequence. The ordering <em>is</em> the insight.</p><ul><li><strong>Introspect deterministically, and keep the reader honest about its own confidence.</strong> A guessed key should carry a number that says it was guessed.</li><li><strong>Spend your LLM budget offline.</strong> The language-to-meaning work belongs at build time, written to versioned files. An LLM in your hot path for things you could precompute is a bug, not a feature.</li><li><strong>Separate what a machine generates from what a human corrects</strong>, and merge them at load time. It is the only way to keep config both fresh and trustworthy.</li><li><strong>Use a graph for structure and a vector index for meaning.</strong> Let them form a pipeline, not a competition: language to concept, then concept to structure.</li><li><strong>Put security metadata in the graph at build time</strong>, so enforcement at query time has nothing to negotiate with a language model about.</li></ul><p>That is the map. In <strong>Part 3</strong>, I get to the part everyone actually asks about: how a plain-English question becomes a safe query end to end, how the system resolves the specific things a user names (“Bike World,” “my team”), and the one architectural line that made me comfortable putting this in front of real users with real permissions.</p><p><em>Next up, Part 3: From Schema to Conversation, building the subject graph and the query pipeline.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f145583abf61" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/your-llm-needs-a-map-f145583abf61">Your LLM Needs a Map!</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text-to-SQL Looks Solved. It Isn’t]]></title>
            <link>https://pub.towardsai.net/text-to-sql-looks-solved-it-isnt-bf076b9a4356?source=rss-957b4eb4985d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf076b9a4356</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[text-to-sql-generative-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[text-to-sql]]></category>
            <dc:creator><![CDATA[venkatesh babu sekar]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 16:00:48 GMT</pubDate>
            <atom:updated>2026-06-15T07:22:06.040Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Why text-to-SQL breaks the moment it meets a real schema, and the shape of an architecture that survives it.</em></h4><p><em>Part 1 of 4 on building a conversational analytics engine. This part is the “why.” The next three are the “how.” ~10 min read.</em></p><p>Every text-to-SQL demo goes the same way.</p><p>Someone connects a language model to a database and types a question: <em>“who are my top 10 customers by revenue this year.”</em> A clean SQL query appears, the rows come back, the room nods. Text-to-SQL: solved. Ship it.</p><p>Now point that same system at a real company’s data.</p><p>Suddenly there are 4,000 tables instead of 12. Column names are things like STAT_CD and ORG_LVL_3. Half the relationships between tables were never written down. Three different teams have three different definitions of &quot;revenue.&quot; The data lives in four databases that speak three SQL dialects. And every row is wrapped in permissions, because the intern asking about salaries is not allowed to see them.</p><p>The demo does not survive contact with that world. And the gap between the two is not a bug you patch later. <strong>The gap is the actual problem.</strong> This series is about closing it. Before I show you the architecture I built, I want to convince you that the problem is real and specific, because the solution only makes sense once the problem does.</p><p><strong>TL;DR</strong></p><ul><li>Text-to-SQL demos look solved. On real enterprise data, accuracy falls off a cliff.</li><li>The reason is not “the model needs to be smarter.” It is that several of the hardest parts are not language problems at all. They are <strong>structure, safety, and correctness</strong> problems.</li><li>I will walk through <strong>seven walls</strong> every serious system hits, and why the obvious fixes (bigger prompt, few-shot, fine-tuning, a pure agent) do not fully clear them.</li><li>Then the thesis for the whole series: <strong>give the model a map, draw a hard line between what’s deterministic and what’s generated, and keep the data in place.</strong></li></ul><h3>The benchmark cliff: proof the demo is lying</h3><p>You do not have to take my word that real schemas are different. The benchmarks already show it.</p><ul><li><strong>Spider 1.0</strong>, the long-standing academic benchmark, has top systems scoring in the <strong>mid-80s</strong> for execution accuracy. But its databases are tidy: roughly 10 to 20 tables, clean names, simple logic.</li><li><strong>Spider 2.0</strong> rebuilt the test on real enterprise databases. The same class of frontier models fell into the <strong>teens and low twenties</strong>. Same models, same week, a drop of <strong>more than sixty points</strong>.</li><li><strong>BIRD</strong>, built on real and deliberately messy databases, sits around the <strong>low 50s</strong> even for strong models, with accuracy sliding further as questions get harder.</li><li>And your production numbers land <strong>5 to 15 points below</strong> any benchmark, because real users ask messier, more ambiguous questions than benchmark authors write.</li></ul><blockquote>A model that looks like an A-student on the demo schema is a coin flip on a real one. The intelligence did not change. The environment did.</blockquote><p>So the interesting question is not “why is the model not smart enough.” The interesting question is: <strong>what specifically is different about a real database that the model cannot handle?</strong> Here is the map of where it breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8UCPteNaYrzZhC3oW6Xkw.png" /><figcaption><strong>Where naive text-to-sql breaks</strong></figcaption></figure><p><strong>How to read it:</strong> one innocent-looking question runs straight into seven different walls, and only one of them is really about understanding language. Let me take them in order.</p><h3>The seven walls</h3><h3>Wall 1: The model doesn’t know what your columns mean</h3><p>A schema tells you a column is named STAT_CD and holds a string. It does not tell you that STAT_CD = &#39;A&#39; means &quot;active,&quot; or that &quot;active employee&quot; actually requires a filter on three columns that someone encoded in application logic a decade ago.</p><ul><li>Real business meaning lives <strong>outside the schema</strong>: in tribal knowledge, in dashboards, in someone’s head.</li><li>The model sees the names and the types. It does not see the meaning, because the meaning was never written down where it could read it.</li></ul><p>This is called <strong>schema linking</strong>, and it is widely considered the single hardest part of text-to-SQL: connecting a word in the question to the right table and column out of thousands. A model guessing in the dark gets it right on a 12-table toy and wrong on a real warehouse.</p><h3>Wall 2: It invents joins that don’t exist</h3><p>Ask for orders by customer, and the model has to join the orders table to the customer table. On what key? If the foreign key was declared, fine. Often it was not.</p><ul><li>In the dataset I work with, <strong>only 44 of the relationships were actually declared</strong> as foreign keys. The rest are real but invisible.</li><li>A model faced with a missing relationship does not stop. It <strong>guesses a join</strong>. Sometimes the guess is plausible and wrong.</li></ul><p>And a wrong join does not throw an error. It returns rows. Which brings us to the failure mode that should scare you the most.</p><h3>Wall 3: The fan-out trap (a wrong number that looks perfect)</h3><p>This one is my favorite, because it is invisible even to a careful human reviewer.</p><p>Ask for total revenue per customer. The query joins customers to orders to line-items. The moment you SUM a value across a <strong>one-to-many</strong> join, that value gets repeated once per child row.</p><ul><li>A customer with one $100 order and five line items reports <strong>$500</strong> in revenue.</li><li>The SQL is syntactically perfect. The number is garbage.</li><li>Nobody notices, because nothing failed.</li></ul><blockquote>This is the defining danger of text-to-SQL: small mistakes don’t crash. They return plausible, confident, wrong answers. A system that is wrong 5% of the time, silently, is more dangerous than one that fails loudly 50% of the time. You can’t trust any of it.</blockquote><p>Cardinality correctness is not a language problem. You cannot prompt your way to certainty about it. It is a property you have to <em>prove</em> from the structure of the data.</p><h3>Wall 4: Ambiguity, in both the things and the metrics</h3><p>Two more places the question is underspecified:</p><ul><li><strong>Entities.</strong> “Bike World” might be two different stores. The honest answer is <em>“which one did you mean,”</em> not a coin flip that produces a confident wrong number.</li><li><strong>Metrics.</strong> “Revenue” might mean gross, net, booked, or recognized, and finance will fight about it. If the system silently picks one, it is wrong for whoever meant another.</li></ul><p>A real system needs to <strong>resolve</strong> the specific things a user names, and treat “ambiguous” as a first-class outcome that asks a question, not a problem to paper over.</p><h3>Wall 5: Dialect drift and data that lives in many places</h3><ul><li>Postgres, SQL Server, Snowflake, and friends all speak <strong>different SQL</strong>. Date functions, quoting, LIMIT versus TOP. A query that runs on one fails on another.</li><li>And the data the question needs is often <strong>split across systems</strong>. “Compare sales to production output” might mean joining two databases that have no ability to join each other.</li></ul><p>You cannot run a cross-database JOIN that does not exist, and you cannot move all the data into one place every time someone asks a question.</p><h3>Wall 6: Security, the wall you cannot get wrong</h3><p>This is where “democratizing data access” turns dangerous.</p><ul><li>The same system that lets anyone ask a question can let anyone ask the <strong>wrong</strong> question and get an answer they should never see.</li><li>Salaries, PII, another region’s numbers: all one cleverly-worded prompt away.</li></ul><p>Here is the part that matters most: <strong>the language model can never be the thing that enforces access control.</strong> A stochastic model that “usually” applies the permission filter is not a security boundary. It is a liability with good intentions.</p><h3>Wall 7: Cost, latency, and the reproducibility problem</h3><p>Even when it works, the naive approach is expensive in three ways:</p><ul><li><strong>Money.</strong> In a warehouse like Snowflake or BigQuery, one inefficient generated query can cost hundreds of dollars.</li><li><strong>Latency.</strong> Calling a large model for every step of every query is slow.</li><li><strong>Reproducibility.</strong> Ask the same question twice and a non-deterministic model can route two different ways. On a financial dashboard, <em>“it depends what the model felt like”</em> is not an acceptable answer.</li></ul><h3>Why the obvious fixes don’t fully work</h3><p>When people hit these walls, they reach for four tools. Each helps. None of them, alone, clears the walls that matter most.</p><ul><li><strong>Bigger prompt</strong> (dump the whole schema in). Helps a little with schema linking. Does not solve: it blows past context limits on real schemas, still invents joins, and still has no grain or security.</li><li><strong>Few-shot examples.</strong> Helps mimic query patterns. Does not solve: brittle, does not generalize to new questions, no safety guarantees.</li><li><strong>Fine-tuning.</strong> Helps with dialect and style. Does not solve: you often <em>cannot</em> train on proprietary data, it is expensive, it still hallucinates joins, and still no RBAC.</li><li><strong>A pure LLM agent.</strong> Helps with flexibility and self-correction. Does not solve: non-deterministic exactly where you need determinism (security, joins, routing).</li></ul><p>Notice the pattern. Every one of these is aimed at making the model <strong>understand better</strong>. But understanding was never the whole problem.</p><blockquote>Joins, cardinality, security, and reproducibility are not things you make a model better at. They are things you must take out of the model’s hands and prove with structure and code.</blockquote><p>That realization is the entire design philosophy of what I built.</p><h3>The shape of an answer</h3><p>So what does a system that survives a real schema actually look like? Three ideas, and they are the spine of the rest of this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6W4QZ-54kiE28BSaNHgq6g.png" /><figcaption><strong>The shape of the answer</strong></figcaption></figure><p><strong>1. Give the model a map.</strong></p><ul><li>An LLM cannot reason about what it cannot see. So before it answers anything, I build a <strong>knowledge graph plus a semantic index</strong> that captures what the tables mean, how they connect, and what is sensitive.</li><li>This is a <strong>semantic layer</strong> between the question and the SQL, and it is the single biggest lever for schema linking. A graph can traverse the multi-hop relationships that vector search alone cannot find, which is exactly how you get joins right.</li><li>Crucially, this map is built <strong>offline, once</strong>. The expensive thinking is precomputed, so the runtime is fast and deterministic.</li></ul><p><strong>2. Draw a hard line between deterministic and generated.</strong></p><ul><li>The model is genuinely great at the fuzzy parts: understanding what a question means, writing the creative slice of a query, summarizing results in prose.</li><li>The model is genuinely unaccountable at the parts that must be exact: which tables you may touch, how two tables join, whether a SUM fans out.</li><li>So I put those on <strong>opposite sides of a hard line</strong>. Code does routing, joins, security, and cardinality. The model does intent and the SELECT and the words. Security is never the model’s job. Joins are never the model’s job.</li></ul><p><strong>3. Keep the data in place.</strong></p><ul><li>The map holds <strong>metadata only</strong>. The actual rows never move into it.</li><li>Queries run <strong>where the data lives</strong>, and cross-source questions get stitched together after each source has answered for itself, under its own permissions.</li></ul><h3>What’s coming in this series</h3><p>Each of the next three parts builds one piece of that answer.</p><ul><li><strong>Part 2: The domain graph.</strong> How I introspect three databases and enrich them, offline, into the map: the meaning, the join paths, and the security rules. (This is the fix for Walls 1, 2, and the schema half of 5.)</li><li><strong>Part 3: The subject graph and the query pipeline.</strong> How a plain-English question becomes a safe query: resolving the specific things a user names, the deterministic-plan / generate split, the planner that defuses the fan-out trap, and access control enforced by rewriting SQL. (Walls 3, 4, 6, 7, and the cross-source half of 5.)</li><li><strong>Part 4: RAG fusion.</strong> The forward-looking piece: extending all of this past the database into documents, so one question can draw on both a number and a paragraph.</li></ul><h3>Key takeaways</h3><ul><li><strong>The demo is the easy 80%. Production is the hard 20%, and the hard 20% is where all the danger lives.</strong> Benchmarks built on real databases show frontier models dropping from the mid-80s to the teens.</li><li><strong>The scariest failure mode is the silent wrong answer.</strong> Bad joins and fan-out do not crash. They return confident, plausible, incorrect numbers.</li><li><strong>Most of text-to-SQL’s hardest walls are not language problems.</strong> They are structure, correctness, and safety problems, and you do not solve those by making the model smarter.</li><li><strong>The answer is architectural:</strong> a semantic map the model can reason over, a hard line between what is deterministic and what is generated, and a “data stays in place” rule.</li></ul><p>That is the problem, and the shape of the solution. In Part 2, I start building it, with the map.</p><p><em>Further reading on the problem space: the </em><a href="https://spider2-sql.github.io/"><em>Spider 2.0 enterprise benchmark</em></a><em>, the </em><a href="https://bird-bench.github.io/"><em>BIRD benchmark</em></a><em> on real databases, and a good field overview in </em><a href="https://arxiv.org/html/2410.01066v1"><em>this Text-to-SQL survey</em></a><em>.</em></p><p><em>Next up, Part 2: </em>Your LLM Needs a Map !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf076b9a4356" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/text-to-sql-looks-solved-it-isnt-bf076b9a4356">Text-to-SQL Looks Solved. It Isn’t</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>