<?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 Samarth vinayaka on Medium]]></title>
        <description><![CDATA[Stories by Samarth vinayaka on Medium]]></description>
        <link>https://medium.com/@samarthvinayaka?source=rss-97d4d0573942------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y0JuF4iseWDgwEXvmVSs1g.jpeg</url>
            <title>Stories by Samarth vinayaka on Medium</title>
            <link>https://medium.com/@samarthvinayaka?source=rss-97d4d0573942------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:54:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samarthvinayaka/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[Your RAG App Has Citations. Are They Actually Supporting the Answer?]]></title>
            <link>https://medium.com/@samarthvinayaka/your-rag-app-has-citations-are-they-actually-supporting-the-answer-6607b2c83d23?source=rss-97d4d0573942------2</link>
            <guid isPermaLink="false">https://medium.com/p/6607b2c83d23</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Samarth vinayaka]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 23:01:34 GMT</pubDate>
            <atom:updated>2026-06-03T23:01:34.783Z</atom:updated>
            <content:encoded><![CDATA[<p>RAG systems often fail in a subtle way: the answer looks cited, but the cited source does not actually support the claim.</p><p>That is a dangerous failure mode because it looks reliable at a glance. The answer has a citation. The source exists. The formatting looks professional. But when you read the cited text closely, the evidence chain breaks.</p><p>Here is a simple example.</p><p>Retrieved source:</p><pre>Customers may request refunds within 30 days of purchase.</pre><p>Generated answer:</p><pre>Refunds are allowed within 30 days. Refunds are processed within 5 business days.</pre><p>The first claim is supported. The second claim is not. The model added a processing-time detail that was not in the retrieved evidence.</p><p>Most RAG debugging tools make it easy to inspect traces, latency, token usage, and retrieval scores. Those are useful, but they do not always answer the question that matters most:</p><p><strong><em>Is each generated claim actually supported by the retrieved evidence?</em></strong></p><p>That is the problem ContextTrace v0.2.0 is built around.</p><h3>What ContextTrace v0.2.0 Adds</h3><p>ContextTrace is a local-first Python SDK and CLI for debugging RAG and AI agent reliability issues. The v0.2.0 release adds claim-level evidence verification for portable RAG traces.</p><p>The verifier checks the evidence chain:</p><pre>query -&gt; retrieved contexts -&gt; answer -&gt; claims -&gt; citations -&gt; support verdicts</pre><p>It works with the artifacts most RAG systems already have:</p><ul><li>query</li><li>answer</li><li>retrieved contexts</li><li>optional citations</li><li>metadata</li></ul><p>No hosted dashboard is required. No API key is required for the default verifier.</p><p>Install it:</p><pre>pip install contexttrace</pre><p>Run a bundled demo:</p><pre>contexttrace verify-demo unsupported_claim --report</pre><p>That command writes a local HTML report showing which claims were extracted, which claim was unsupported, what evidence was retrieved, whether the system should have abstained, and what fix to try next.</p><h3>Portable JSON Input</h3><p>You can also verify your own RAG artifact directly:</p><pre>contexttrace verify trace.json --report</pre><p>Example input:</p><pre>{<br>  &quot;query&quot;: &quot;How long does refund processing take?&quot;,<br>  &quot;answer&quot;: &quot;Refunds are processed within 5 business days.&quot;,<br>  &quot;contexts&quot;: [<br>    {<br>      &quot;id&quot;: &quot;policy_2026&quot;,<br>      &quot;text&quot;: &quot;Customers may request refunds within 30 days of purchase.&quot;,<br>      &quot;metadata&quot;: {<br>        &quot;source&quot;: &quot;refund_policy.pdf&quot;,<br>        &quot;page&quot;: 2<br>      }<br>    }<br>  ]<br>}</pre><p>The verifier extracts the answer claim:</p><pre>Refunds are processed within 5 business days.</pre><p>Then it compares that claim against the retrieved context. Since the context mentions only the refund request window and not the processing time, the claim is marked as unsupported.</p><p>The JSON output includes a summary like this:</p><pre>{<br>  &quot;summary&quot;: {<br>    &quot;total_claims&quot;: 1,<br>    &quot;supported&quot;: 0,<br>    &quot;partially_supported&quot;: 0,<br>    &quot;unsupported&quot;: 1,<br>    &quot;support_rate&quot;: 0.0,<br>    &quot;unsupported_claim_rate&quot;: 1.0,<br>    &quot;citation_mismatches&quot;: 1,<br>    &quot;should_abstain&quot;: true,<br>    &quot;failure_type&quot;: &quot;should_have_abstained&quot;<br>  }<br>}</pre><p>Instead of only saying the answer is low quality, ContextTrace shows where the evidence chain broke.</p><h3>Verdicts</h3><p>ContextTrace v0.2.0 classifies each claim as one of:</p><ul><li>supported: retrieved evidence supports the claim</li><li>partially_supported: Evidence supports part of the claim, but not every detail</li><li>unsupported: No retrieved context has enough evidence for the claim</li><li>contradicted: Evidence appears to conflict with the claim</li><li>unverifiable: Evidence is too weak or ambiguous</li></ul><p>It also checks citation status:</p><ul><li>citation_ok</li><li>cited_source_missing</li><li>cited_source_does_not_support_claim</li><li>claim_has_no_citation</li></ul><p>This is useful because a claim can be factually correct yet cite the wrong source.</p><p>Run the citation mismatch demo:</p><pre>contexttrace verify-demo citation_mismatch --report</pre><p>That demo has a correct claim, but the citation points to an archived policy chunk instead of the current refund policy. The report shows the cited source and the best supporting source side by side.</p><h3>Should the Model Have Abstained?</h3><p>Another common RAG failure is answering when the retrieved context does not contain the requested information.</p><p>Example:</p><pre>Question: What refund exception applies to VIP customers?<br>Retrieved context: Standard shipping takes 3 to 5 business days.<br>Answer: VIP customers receive cash refunds up to 90 days after purchase.</pre><p>There is no evidence for the VIP refund exception. ContextTrace marks the claim unsupported and sets:</p><pre>{<br>  &quot;should_abstain&quot;: true<br>}</pre><p>The report also gives a suggested fix:</p><pre>Add an abstention rule: when retrieved contexts do not support the requested fact,<br>say the information is unavailable instead of generating a factual answer.</pre><h3>Local Semantic Mode</h3><p>The default verifier is deterministic and lexical. It is fast, local, and dependency-light.</p><p>v0.2.0 also includes a local semantic mode:</p><pre>contexttrace verify trace.json --mode semantic</pre><p>This mode uses local paraphrase-aware normalization for common support cases, such as:</p><ul><li>“money back” -&gt; “refund”</li><li>“thirty” -&gt; “30”</li><li>“order ID” -&gt; “order number”</li></ul><p>It is not an embedding model, and it is not an LLM judge. It is a pragmatic middle ground: better than exact lexical overlap, but still local and predictable.</p><h3>CI Gates</h3><p>You can also fail CI on evidence problems:</p><pre>contexttrace verify trace.json \<br>  --fail-on unsupported \<br>  --fail-on citation_mismatch</pre><p>Supported gates include:</p><ul><li>unsupported</li><li>partial_support</li><li>citation_mismatch</li><li>should_abstain</li><li>contradicted</li><li>unverifiable</li><li>no_citation</li><li>any_failure</li></ul><p>This makes ContextTrace useful not only for manual debugging but also for regression checks when you change prompts, retrievers, chunking, rerankers, or context selection logic.</p><h3>Bundled Benchmark</h3><p>v0.2.0 also includes a small bundled benchmark:</p><pre>contexttrace verify-benchmark --mode semantic</pre><p>It reports exact-match rate plus per-label precision, recall, and F1 for supported, unsupported, partial-support, citation-mismatch, abstention, and contradiction cases.</p><p>This benchmark is intentionally small. It is not a leaderboard. It is a transparency tool so users can see how the local verifier behaves on known examples.</p><h3>Why Local First?</h3><p>Many teams use RAG on private documents: support policies, contracts, internal handbooks, financial records, customer notes, medical documents, or legal research.</p><p>For those workflows, uploading traces to a hosted service may be unacceptable.</p><p>ContextTrace keeps the default workflow local:</p><pre>contexttrace verify trace.json --report</pre><p>The report is written as a local HTML file. The verifier does not require a hosted dashboard or external judge.</p><h3>Limitations</h3><p>This release is useful, but it is not magic.</p><ul><li>Claim extraction is rule-based.</li><li>Contradiction detection is conservative.</li><li>Default verification is lexical.</li><li>Semantic mode uses local normalization, not embeddings or LLM reasoning.</li><li>It is a debugging tool, not a replacement for human review in high-stakes domains.</li></ul><p>That honesty matters. A verifier should not overclaim certainty. If evidence is weak or ambiguous, ContextTrace should say so.</p><h3>Try It</h3><pre>pip install contexttrace<br>contexttrace verify-demo unsupported_claim --report<br>contexttrace verify-demo citation_mismatch --report<br>contexttrace verify-benchmark --mode semantic</pre><p>Project: <a href="https://pypi.org/project/contexttrace/0.2.0/">https://pypi.org/project/contexttrace/0.2.0/</a></p><p>The main idea is simple:</p><blockquote>Citations are not grounding, Evidence is.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-8yTmy1N3XWuqd7K0WczA.png" /></figure><p>ContextTrace v0.2.0 helps you inspect whether your RAG system actually has that evidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6607b2c83d23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Fails Silently: Debugging Retrieval, Citations, and Unsupported Claims]]></title>
            <link>https://pub.towardsai.net/rag-fails-silently-debugging-retrieval-citations-and-unsupported-claims-aa6f730b730a?source=rss-97d4d0573942------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6f730b730a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Samarth vinayaka]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 02:22:54 GMT</pubDate>
            <atom:updated>2026-06-02T05:11:34.455Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A practical look at debugging the evidence chain in RAG systems: retrieval, context selection, answer claims, citation support, and local failure reports.</em></h4><p>RAG systems often fail in a way that is hard to see.</p><p>The answer looks reasonable. The citations look official. The retrieved chunks look vaguely related.</p><p>Then a user asks a question where the model combines one supported fact with one invented detail, and nobody notices until the answer is wrong in production.</p><p>That failure mode is what I wanted to debug better.</p><p>I built <strong><em>ContextTrace</em></strong>, a local-first Python SDK and CLI for tracing RAG and agent applications. The goal is not to replace eval frameworks or observability platforms. The goal is narrower:</p><p>&gt; <em>Show the failure path from retrieved evidence to selected context to answer the claim to citation support.</em></p><p>I made it local-first because RAG traces often contain private documents, retrieved chunks, customer data, or internal policies.</p><p>GitHub: <a href="https://github.com/samarth1412/Context-Trace">https://github.com/samarth1412/Context-Trace</a></p><p>PyPI: <a href="https://pypi.org/project/contexttrace/">https://pypi.org/project/contexttrace/</a></p><h4><strong>The Problem: RAG Answers Can Look Grounded While Being Unsupported</strong></h4><p>A typical RAG pipeline has a few steps:</p><pre>user query<br>-&gt; retrieval<br>-&gt; context selection<br>-&gt; answer generation<br>-&gt; citations</pre><p>When something goes wrong, we usually see only the final answer.</p><p>But the real failure may have happened earlier:</p><pre>retrieved weak evidence<br>-&gt; selected incomplete context<br>-&gt; generated unsupported claim<br>-&gt; cited the wrong source<br>-&gt; returned a plausible answer</pre><p>The dangerous part is that the answer may still look grounded.</p><p>For example:</p><p><strong><em>Query:</em></strong></p><pre>How long does refund processing take?</pre><p><strong><em>Retrieved source chunk:</em></strong></p><pre>Customers may request a refund within 30 days of purchase.</pre><p><strong><em>Bad RAG answer:</em></strong></p><pre>Customers can request refunds within 30 days, <br>and refunds are processed within 5 business days.</pre><p>The first part is supported. The second part is not.</p><p>A normal user may not catch that. A basic citation display may not catch that either. The answer cites a refund policy, and the answer is about refunds, so it looks fine.</p><p>But at the claim level, the citation does not support the processing-time claim.</p><p>That is the kind of silent failure ContextTrace is designed to expose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0-1oqDp8Em-uQpnGM8a7A.png" /></figure><p><strong>Why Scores Alone Are Not Enough</strong></p><p>RAG evaluation tools are useful. Aggregate scores matter.</p><p>But when an eval says:</p><pre>faithfulness: 0.72<br>citation support: 0.65</pre><p>The next question is:</p><p><strong><em>What broke?</em></strong></p><p>Was it retrieval? Was it chunking? Was the selected context incomplete? Did the model ignore the context? Did the citation point to the wrong source? Should the system have abstained?</p><p>Scores are good for tracking quality over time. They are less useful when you are trying to debug one bad answer.</p><p>For debugging, I wanted the report to say something more concrete:</p><pre>Claim 1: directly_supported<br>Claim 2: unsupported<br>Failure type: unsupported_answer<br><br>Root cause:<br>The answer added a processing-time claim that was not present in the retrieved evidence.<br><br>Suggested fix:<br>Require sentence-level citation support before returning the final answer.</pre><p>That is the core idea behind ContextTrace.</p><h4><strong>What ContextTrace Does</strong></h4><p>ContextTrace records the parts of a RAG pipeline that usually disappear after the response is returned: <strong><em>query, retrieved chunks, selected context, answer, citations, token usage, latency, metadata, and agent/tool events.</em></strong></p><p>It works through SDK instrumentation, a CLI for existing RAG endpoints, and integrations for LangChain, LlamaIndex, FastAPI, and LangGraph.</p><p>The architecture is intentionally boring:</p><pre>User RAG app / agent / endpoint<br>-&gt; SDK / CLI / integrations<br>-&gt; local SQLite trace store<br>-&gt; citation verifier + failure analyzer<br>-&gt; local HTML report / viewer</pre><p>The hard part is not orchestration. It is making the evidence chain inspectable.</p><h4><strong>SDK</strong></h4><p>The SDK wraps an existing RAG flow:</p><pre>from contexttrace import ContextTrace<br><br>ct = ContextTrace(project=&quot;support-rag&quot;)<br>with ct.trace(query=&quot;What is the refund policy?&quot;) as trace:<br>chunks = retriever.search(&quot;What is the refund policy?&quot;)<br>trace.log_retrieval(chunks)<br>trace.log_context(chunks[:5])<br>answer = llm.generate(&quot;What is the refund policy?&quot;, chunks[:5])<br><br>trace.log_answer(answer, usage={&quot;total_tokens&quot;: 1200})<br>trace.log_citations([<br>{<br>&quot;claim&quot;: &quot;Refunds are available within 30 days.&quot;,<br>&quot;source_chunk_id&quot;: &quot;chunk_12&quot;}])<br><br>result = trace.evaluate()<br>print(result[&quot;failure&quot;][&quot;failure_type&quot;])<br>print(result[&quot;failure&quot;][&quot;suggested_fix&quot;])</pre><h4><strong>Local Evaluation</strong></h4><p>ContextTrace checks whether an answer claim is supported by its cited source chunk.</p><p>Citation verdicts include `<em>directly_supported</em>`, `<em>partially_supported</em>`, `<em>unsupported</em>`, `<em>contradicted</em>`, and `<em>not_enough_info</em>`.</p><p>Failure labels include<em> `retrieval_miss`, `citation_mismatch`, `unsupported_answer`, `conflicting_sources`, `should_have_abstained`,</em> and<em> `query_needs_decomposition`.</em></p><p>The labels are not meant to be perfect. They are meant to make debugging more concrete than “the answer was bad.”</p><h4><strong>Demo: Refund Policy Failure</strong></h4><p>Here is the canonical example.</p><p><strong><em>Query:</em></strong></p><pre>How long does refund processing take?</pre><p><strong><em>Source chunk:</em></strong></p><pre>Customers may request a refund within 30 days of purchase.</pre><p><strong><em>Bad answer:</em></strong></p><pre>Customers can request refunds within 30 days, and refunds are processed within 5 business days.</pre><p>ContextTrace evaluates the claims separately:</p><pre>Claim 1: Customers can request refunds within 30 days.<br>Verdict: directly_supported<br><br>Claim 2: Refunds are processed within 5 business days.<br>Verdict: unsupported</pre><p>Then it gives a diagnosis:</p><pre>Failure type: unsupported_answer<br><br>Root cause: The answer added a processing-time claim that was not present in the retrieved evidence.<br><br>Suggested fix: Require sentence-level citation support before returning the final answer.</pre><p>This is the difference between a score and a failure path.</p><p><strong>What the Report Shows</strong></p><p>A local report summarizes the <strong><em>reliability score, failure rate, citation support, unsupported claims, worst traces, root cause, and suggested fixes.</em></strong></p><p>Example:</p><pre>Reliability score: 72/100<br>Failure rate: 0.30<br>Citation support: 0.81<br>Worst trace:<br>Failure: unsupported_answer<br>Root cause: The model added a processing-time claim that was not present in the retrieved evidence.<br>Suggested fix: Require sentence-level citation support before returning the answer.</pre><h4><strong>Running It From PyPI</strong></h4><p>Install:</p><pre>pip install contexttrace</pre><p>Run the demo:</p><pre>contexttrace init<br>contexttrace demo - dataset refund_policy<br>contexttrace report - last - open</pre><p>This creates a local trace database and opens an HTML report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvxhrbKijuxkmTP9L2LWkw.png" /></figure><p>You can also inspect the status:</p><pre>contexttrace doctor</pre><p>Or list traces:</p><pre>contexttrace traces list</pre><h4><strong>Testing Your Own RAG API</strong></h4><p>You do not have to install the SDK into your application.</p><p>If you already have a RAG endpoint like:</p><pre>POST http://localhost:8000/query</pre><p>You can run ContextTrace against it:</p><pre>contexttrace eval \<br> - dataset evals/questions.json \<br> - endpoint http://localhost:8000/query \<br> - method POST \<br> - input-key question \<br> - answer-path $.answer \<br> - contexts-path $.contexts \<br> - citations-path $.citations \<br> - fail-on &quot;failure_rate&gt;0.25&quot;</pre><p>Expected response shape:</p><pre>{<br>&quot;answer&quot;: &quot;Refunds are available within 30 days.&quot;,<br>&quot;contexts&quot;: [<br>{<br>&quot;id&quot;: &quot;refund_policy_1&quot;,<br>&quot;text&quot;: &quot;Customers may request a refund within 30 days of purchase.&quot;,<br>&quot;source&quot;: &quot;refund_policy.md&quot;<br>}<br>],<br>&quot;citations&quot;: [<br>{<br>&quot;claim&quot;: &quot;Refunds are available within 30 days.&quot;,<br>&quot;source_chunk_id&quot;: &quot;refund_policy_1&quot; } ] }</pre><p>ContextTrace maps the response, creates local traces, evaluates the result, and writes a report.</p><p>This is useful if you want to test a RAG service without modifying the code first. The same CLI can also be used in CI with thresholds such as <em>failure_rate&gt;0.25</em> or <em>citation_support&lt;0.80</em>.</p><h4><strong>Local-First Privacy</strong></h4><p>Many RAG debugging tools assume you are comfortable sending traces somewhere.</p><p>For many teams, that is not the default assumption.</p><p>RAG traces can include private documents, customer support content, legal text, internal policies, retrieved chunks, final answers, tool outputs, and memory reads.</p><p>ContextTrace defaults to local storage.</p><p>By default:</p><pre>No hosted dashboard is required.<br>No account is required.<br>Traces are stored in .contexttrace/contexttrace.db.<br>Reports are generated locally.</pre><p>Network calls happen only if you configure an LLM judge provider or point ContextTrace at a RAG endpoint.</p><h4><strong>Where This Fits</strong></h4><p>ContextTrace is not meant to replace broader tools.</p><p>It complements them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNjT2oMBVrrWDW32NmfZnA.png" /></figure><p>If you already use one of those tools, ContextTrace can still be useful as a local debugging layer.</p><h4><strong>Limitations</strong></h4><p>This is v0.1.0.</p><p>Some important caveats:</p><p>- ContextTrace is diagnostic. It does not guarantee correctness.</p><p>- LLM judge outputs should be reviewed for high-stakes workflows.</p><p>- Local heuristic evaluation is intentionally simple.</p><p>- Failure labels are meant to guide debugging, not replace human review.</p><p>- The local viewer and reports will improve over time.</p><p>- Agent tracing is early and intentionally basic.</p><p>I would not use this as the only quality gate for a high-stakes production system.</p><p>I would use it to find failure patterns faster.</p><h4><strong>Who This Is For</strong></h4><p>ContextTrace is most useful if you already have a RAG or agent system and want to debug it locally. It is not a RAG builder. It is meant for:</p><p>- RAG APIs</p><p>- support bots</p><p>- internal knowledge assistants</p><p>- policy/document QA systems</p><p>- agent workflows that use retrieval or memory</p><p>- teams adding CI checks for prompt/retrieval changes</p><p>I am especially looking for feedback on:</p><p>- whether the failure labels are useful</p><p>- whether the CLI workflow is simple enough</p><p>- What fields are missing from the trace/report</p><p>- What integrations matter most</p><p><strong>GitHub</strong>: <a href="https://github.com/samarth1412/Context-Trace">https://github.com/samarth1412/Context-Trace</a></p><p><strong>PyPI</strong>: <a href="https://pypi.org/project/contexttrace/">https://pypi.org/project/contexttrace/</a></p><p><strong>Release</strong>: <a href="https://github.com/samarth1412/Context-Trace/releases/tag/v0.1.0">https://github.com/samarth1412/Context-Trace/releases/tag/v0.1.0</a></p><p>If you are building RAG systems and have feedback, I&#39;d like to hear what breaks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6f730b730a" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/rag-fails-silently-debugging-retrieval-citations-and-unsupported-claims-aa6f730b730a">RAG Fails Silently: Debugging Retrieval, Citations, and Unsupported Claims</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[Sliding Windows Forget: Why Long-Running LLM Apps Need Memory Policy]]></title>
            <link>https://pub.towardsai.net/sliding-windows-forget-why-long-running-llm-apps-need-memory-policy-8d24a80038fd?source=rss-97d4d0573942------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d24a80038fd</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Samarth vinayaka]]></dc:creator>
            <pubDate>Mon, 25 May 2026 00:23:18 GMT</pubDate>
            <atom:updated>2026-05-25T04:06:21.518Z</atom:updated>
            <content:encoded><![CDATA[<p>Most long-running LLM failures are not pure reasoning failures. They are state-selection failures: the next model call gets incomplete, stale, or irrelevant context.</p><p>In short chats, appending recent messages often works. In persistent sessions, that breaks down because durable facts vanish, stale updates return, and routine traffic consumes the prompt budget.</p><p>The real question becomes:</p><blockquote>Which pieces of prior state deserve to be in the next model call?</blockquote><p>I built <a href="https://github.com/samarth1412/LLM-Context-Optimization-Engine">LLM-Context-Optimization-Engine</a> to explore that question. It is a prototype that compares full history, sliding windows, summaries, retrieval, hybrid context, adaptive context selection, and importance-based memory retention.</p><p>The contribution here is not a new memory architecture. It is an inspectable benchmark harness that compares context policies before the model call and exposes how each one fails.</p><p>This problem is becoming more important as agent platforms move toward persistent memory. Once agents can remember across sessions, the hard question is not whether memory exists, but how stored state is selected, invalidated, trusted, and injected at inference time.</p><p>The short version:</p><ul><li>Sliding windows are cheap, but they forget durable facts.</li><li>Full history maximizes recall, but carries stale and noisy evidence.</li><li>Retrieval improves recall, but high recall can still poison the prompt if stale facts come with it.</li><li>In a synthetic 10k-turn benchmark, importance-based selection retained 90.7% of current critical facts under a 600-message budget; sliding window retained 10.8%.</li><li>The key lesson: long-running LLM apps need memory policy, not just memory storage.</li></ul><p>This does not claim to solve long-term memory. It provides a controlled benchmark harness for comparing context policies and inspecting how they fail under limited prompt budgets.</p><h3>Why Long-Running LLM Apps Fail</h3><p>Before getting into implementation, the core problem is that different kinds of state compete for the same limited prompt budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXpToSxRltqwKoaY1UeKfA.png" /><figcaption><em>Long-running LLM apps do not just need more memory. They need a policy for deciding which state to enter for the next model call.</em></figcaption></figure><p>Old does not mean irrelevant. Recent does not mean sufficient.</p><p>A user preference from 200 turns ago can matter more than a recent routine message. A recent update can invalidate an older fact. A retrieved memory can be relevant and still dangerous if it brings stale evidence with it.</p><p>That is why long-running LLM systems need context policy, not just context storage.</p><h3>A Concrete Failure Example</h3><p>Imagine a long-running assistant session for project planning.</p><p>Early in the session:</p><p>Turn 18: The user&#39;s preferred lunch option for offsites is vegetarian.</p><p>Later:</p><p>Turn 142: Updated preference: the user is now vegan, not just vegetarian.</p><p>Later still:</p><p>Turn 260: Project Atlas launch moved from Wednesday to Friday.</p><p>At turn 310, the user asks:</p><p>Can you plan the Friday launch lunch for Atlas?</p><p>The evidence needed for the answer is split across time. One fact is old but still valid, one fact supersedes an older preference, and one fact updates the current launch state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nB-QRvnUXmFjcmvT5Db_kw.png" /><figcaption><em>The correct answer depends on both an older durable preference and a newer project update. A memory policy must preserve both while ignoring stale evidence.</em></figcaption></figure><p>Different policies fail differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4GaVw-fbUqL5g4orvKFTQ.png" /></figure><p>This is the core issue: a fact can be old and still important, while a recent fact can be irrelevant. A memory policy has to rank facts, not just turns.</p><h3>Why Common Policies Fail</h3><p>Full history looks safe because it maximizes recall, but it can also carry stale and noisy evidence into the prompt.</p><p>Sliding windows are cheap and predictable, but they confuse recency with importance.</p><p>Summaries reduce token load, but compression can drift. A summary that drops a constraint has silently changed the application’s state.</p><p>Retrieval recovers older facts, but it is not automatically safe. A retriever can return the right fact and a nearby wrong fact in the same top-k set.</p><p><em>High recall is not enough if the prompt also contains stale evidence.</em></p><h3>How State Becomes Context</h3><p>The engine is organized around a single runtime path: store messages, index memories, decide which context sources to use, assemble the prompt, call the model, and record usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRyn_yUZthVl-qV_-4C0nA.png" /><figcaption><em>Stored history is indexed and summarized, then the context builder combines the current request, recent messages, retrieved facts, and memory metadata before the next model call.</em></figcaption></figure><p>For a long session, the context builder can use recent messages, an incremental summary, retrieved prior facts, pinned source context, memory metadata, and the current user query.</p><p>The default configuration keeps 15 recent messages, retrieves up to 6 prior snippets, uses a minimum retrieval score of 0.08, and caps summaries at 2,000 tokens. SQLite keeps the benchmark reproducible. Production would need a different storage and latency profile.</p><h3>How Memories Were Scored</h3><p>Every stored message is indexed and scored. The scorer is deterministic and rule-based, so the benchmark is easy to inspect.</p><p>The scoring function combines recency, durable wording, user preferences, entity mentions, retrieval frequency, update terms, episodic-event terms, length, role, stale markers, and noise markers.</p><p>The simplified scoring formula looks like this:</p><pre>recency = exp(-age / 500)<br>retrieval_frequency = log1p(retrieval_count) / log(10)<br><br>score = role_signal * (<br>    0.13 * recency<br>  + 0.18 * persistence<br>  + 0.18 * preference<br>  + 0.15 * entity_importance<br>  + 0.14 * retrieval_frequency<br>  + 0.12 * contradiction_risk<br>  + 0.06 * episodic_event<br>  + 0.04 * length_signal<br>)<br><br>score -= 0.22 * noise<br>score -= 0.32 * stale_marker * (1.0 - retrieval_frequency)</pre><p>The weights are manually chosen, not optimized. The scorer is intentionally brittle: useful because it is inspectable, not because these weights should be deployed unchanged.</p><p>That caveat matters. If a synthetic benchmark generates critical facts with recognizable preference, update, and entity patterns, then a rule-based scorer that looks for those signals has an advantage. A production evolution would likely feed these features into a lightweight reranker or classifier trained on real user corrections.</p><p>Action and layer assignment are also rule-based: preserve high-scoring durable memories, compress mid-value entity/event memories, evict low-value memories, and place items into working, episodic, semantic, or archived layers.</p><h3>Benchmark 1: Token And Cost Growth</h3><p>The first benchmark simulated a 100-turn conversation with 200 messages. Costs were estimated with the configured x-ai/grok-4-fast pricing in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGRSwSHpvJwAAByKn-IMwQ.png" /></figure><p>This benchmark is not an interesting result. It only establishes the cost pressure that forces context selection. The harder question is what each policy forgets or pollutes.</p><h3>Benchmark 2: Evidence Quality Before The Model Call</h3><p>The memory-quality benchmark uses eight deterministic stress cases: long-range preference recall, temporal updates, multi-hop project state recall, abstention, distractor retrieval, similar-entity disambiguation, recent overrides, and summary drift.</p><p>This is not a human evaluation, nor is it LLM-as-judge. The scoring is deterministic:</p><pre>quality = required_term_recall - 0.35 * conflict_pressure</pre><p><strong><em>required_term_recall</em> </strong>checks whether the assembled context includes the required evidence.</p><p><strong><em>conflict_pressure</em> </strong>checks whether known stale or conflicting evidence is also present.</p><p><strong><em>The benchmark evaluates the context package before the model call.</em></strong></p><p>That matters because if the assembled context is wrong, the answer is already compromised.</p><p>Rounded results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2LzvwURUCTF0rEzT0OatA.png" /></figure><p>The useful part is the failure pattern: full history had high recall but carried stale evidence; sliding windows were cheap but lost long-range facts; summary failed when compression omitted an early constraint; retrieval recovered old facts but could bring stale evidence back.</p><h3>Benchmark 3: 10k-Turn Memory Scaling</h3><p>The strongest result came from the memory-scaling benchmark.</p><p>The synthetic session generator creates routine filler plus durable facts, evolving preferences, entity drift, retrieval noise, forgotten constraints, and stale updates. I tested 1k, 5k, and 10k turns across three policies: full archive, sliding window, and importance-based selection.</p><p>At 10k turns, the benchmark had roughly 200 current critical facts, 500 stale facts, 9.3k noise messages, and a 600-message budget for both sliding window and importance selection.</p><p>Rounded 10k-turn results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpiwCUd8XmBCzVvPxNdI6A.png" /></figure><p><strong>In a controlled synthetic benchmark designed to test structural state drift, importance-based selection retained 90.7% of current critical facts under the same 600-message budget, where sliding window retained 10.8%.</strong></p><p>I treat that result narrowly. The synthetic generator created facts with recognizable preference, update, and entity patterns, and the rule-based scorer explicitly used similar signals. So this is not evidence that the exact scorer generalizes to messy real-world conversations. It is evidence that pure recency is a weak baseline when durable state, stale updates, and routine noise are spread across a long session.</p><p>The limitation is also visible: the important selection retained too many stale facts. It did much better than recency on critical recall and noise suppression, but stale memory still needs better contradiction handling, supersession tracking, and explicit invalidation.</p><h3>Retrieval: Recall Helps, But Conflict Still Matters</h3><p>The retrieval benchmark is smaller, so I treat it as supporting evidence rather than the main claim. It uses ten cases, including semantic paraphrase retrieval, entity abbreviation, stale launch-region evidence, near-name entity collisions, and distractor badge-color snippets.</p><p>Retrieval supports lexical BM25, embedding-only retrieval, and a weighted hybrid. For tests and CI, the project can use deterministic hash embeddings. For stronger retrieval checks, it can use local embedding models or OpenAI embeddings.</p><p>On the current suite:</p><ul><li>BM25 and the deterministic hash baseline recovered most relevant evidence, but missed some semantic cases.</li><li>BGE and OpenAI embedding-only retrieval achieved 100% Recall@6 on this synthetic benchmark suite.</li><li>Precision@6 was still low, around 18.5%, because the top six often included extra non-relevant snippets.</li><li>Hybrid retrieval did not beat BGE embedding-only with the current weights.</li></ul><p><strong>The retrieval failure is usually not “nothing was found.” It is often “the right fact was found together with a nearby wrong fact.”</strong></p><p>One typical failure pattern looks like this:</p><p>Query:<br>Which launch region belongs to Project Atlas?</p><p>Relevant memory: <br>Project Atlas launches in the north region.</p><p>Potential distractor: <br>Project Atala launches in the south region.</p><p>Failure mode:<br>A lexical or weak entity match can pull both Atlas and Atala into context.</p><p>The correct fact is present, but the prompt now also contains a nearby conflicting entity.</p><p>“Hybrid” is not automatically better. Weighting lexical and vector signals needs tuning, and retrieval quality should be measured separately from generation quality. In production, I would not dump top-k retrieval directly into the prompt; I would add stale-aware reranking, entity matching, and contradiction checks before context assembly.</p><h3>Lightweight Query-Aware Routing</h3><p>The router is intentionally lightweight. It is not an LLM router, a trained classifier, or an agentic planner. It uses keyword hints plus retrieval confidence.</p><pre>MEMORY_QUERY_HINTS = (<br>    &quot;remember&quot;, &quot;recall&quot;, &quot;earlier&quot;, &quot;previous&quot;, &quot;mentioned&quot;,<br>    &quot;favorite&quot;, &quot;prefer&quot;, &quot;who is&quot;, &quot;what is&quot;, &quot;when did&quot;<br>)<br><br>BROAD_QUERY_HINTS = (<br>    &quot;summarize&quot;, &quot;recap&quot;, &quot;so far&quot;, &quot;overall&quot;,<br>    &quot;state&quot;, &quot;status&quot;, &quot;current&quot;, &quot;all&quot;<br>)<br><br>CURRENT_STATE_HINTS = (&quot;current&quot;, &quot;latest&quot;, &quot;now&quot;, &quot;today&quot;, &quot;updated&quot;)</pre><p>The rule is simple: current-state queries avoid broad retrieval because retrieval can pull stale state; memory/fact queries use retrieval when evidence is strong; broad recap queries can combine summary and retrieval.</p><h3>Production Recommendations</h3><p>A production memory system should not have one memory mode. It should route between recent context, summaries, retrieval, pinned facts, and invalidation metadata based on query intent.</p><p>One practical mapping looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulFNWzhC3RYDRQ_DjIHWsA.png" /></figure><p>In production, I would separate the system into four paths: synchronous context assembly, asynchronous memory extraction, background embedding/index refresh, and offline evaluation. The online path should only do cheap routing, top-k retrieval, stale-aware reranking, and final prompt assembly. Expensive summarization and memory consolidation should happen asynchronously.</p><p>The likely cost centers are retrieval, reranking, summary refresh, and full request assembly. SQLite vector scanning is fine for this benchmark, but a production system would need an ANN-backed vector store such as pgvector or Qdrant, Redis or another cache layer, background workers, and latency measurements for each stage.</p><p>For some memory types, retrieval is the wrong abstraction. Durable user attributes such as dietary restrictions, timezone, role, or account preferences may belong in a structured state, not only in semantic memory. A production system should combine structured profiles, summaries, retrieval, and invalidation metadata rather than relying on one memory store.</p><h3>Threats To Validity</h3><p>The biggest threat to validity is that the synthetic generator and the rule-based scorer may reward the same signals. If critical facts are written with preference, update, and entity markers, a rule-based scorer can recover them more easily than it would recover messy real-world memories.</p><p>That is why I treat the 91% result as evidence that recency is weak, not proof that this scorer generalizes.</p><p>The benchmark conversations are synthetic, the quality metric is intentionally simple, the retrieval suite is small, and SQLite vector scanning is not production retrieval infrastructure. Those limitations are real, but the result was still useful: context selection needs to account for importance, staleness, retrieval quality, and query intent.</p><h3><strong>Takeaway</strong></h3><p>Long-running LLM systems need a memory policy, not just memory storage.</p><p>Storing everything is easy. Deciding what should enter the next model call is the hard part.</p><p>For factual memory questions, retrieval may be worth the risk. For current-state questions, recent messages and summaries may be safer. For durable preferences, importance-based selection can beat pure recency under a fixed budget.</p><p>The larger lesson is that context assembly changes model behavior. If the system gives the model stale, missing, or conflicting evidence, the answer is already compromised before generation starts.</p><p><strong>In long-running LLM apps, context assembly is not plumbing. It is application logic.</strong></p><blockquote><strong>References</strong></blockquote><ul><li><a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic: Effective Context Engineering for AI Agents</a></li><li><a href="https://www.anthropic.com/news/context-management">Anthropic: Managing Context on the Claude Developer Platform</a></li><li><a href="https://arxiv.org/abs/2307.03172">Lost in the Middle: How Language Models Use Long Contexts</a></li><li><a href="https://www.trychroma.com/research/context-rot">Chroma: Context Rot</a></li><li><a href="https://arxiv.org/abs/2310.08560">MemGPT: Towards LLMs as Operating Systems</a></li><li><a href="https://docs.langchain.com/oss/python/concepts/memory">LangChain Memory Overview</a></li><li><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></li><li><a href="https://arxiv.org/abs/2310.05736">LLMLingua: Compressing Prompts for Accelerated Inference</a></li></ul><p>Code and benchmark scripts: <a href="https://github.com/samarth1412/LLM-Context-Optimization-Engine">GitHub link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d24a80038fd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/sliding-windows-forget-why-long-running-llm-apps-need-memory-policy-8d24a80038fd">Sliding Windows Forget: Why Long-Running LLM Apps Need Memory Policy</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>