r/PiCodingAgent • • 18d ago

Plugin I no longer compact or handoff. Context paging has been running my long sessions for weeks

Hey all, I wanted to share an extension I've developed called pi-context-paging.

https://www.npmjs.com/package/@rochecompaan/pi-context-paging

Instead of compacting your session into a summary when the context fills up, it treats the context window like a rolling window over the full history. When a request goes over a token budget (128k by default), the oldest turns move out of the window. The session file on disk is never changed. The model gets a short paging notice and a few recovery tools to search, browse and load older history when it needs it.

It has made my workflow a lot smoother. I don't get a surprise compaction in the middle of a long-running task and I don't have to write handoffs that inevitably loses important detail. It has been running very stably for me for a couple of weeks now. It is especially useful for agents doing long-running tasks unattended.

It's lossless. Nothing is summarized or compressed. The recent window is sent exactly as stored, and anything older can be loaded back as the original text.

Tony Mason wrote a good paper on this: The Missing Memory Hierarchy: Demand Paging for LLM Context Windows (https://arxiv.org/abs/2603.09023). It treats the context window like RAM and the full history like disk, and pages content in and out on demand. The extension is a practical version of that idea for Pi.

"But what about prompt caching?" I know this is the first thing a lot of you will ask, so here's how it works:

  • It doesn't drop messages one at a time. That would change the start of the prompt on every request and break the cache constantly.
  • When the window hits the budget, it pages out one large block at once, trimming down to about 80k by default. After that cut, the start of the prompt stays the same over many turns, so you get normal cache hits until the next cut.
  • Each cut costs one cache rewrite. In practice that's rare, and whatever you lose in cache efficiency you get back in continuity. There's no summary step, no re-explaining, and no "the agent forgot what we were doing" moments.

Some real numbers from my sessions (Opus 5.5, Fable 5.1 and GPT 6.1, with zero compactions in any of them):

Each of these is millions of tokens of history in a single continuous session, and every request still stayed at or below the 128k budget. Cache hit rates stayed above 90% even with the paging cuts.

You can set the budget in settings. I'd suggest setting it below the point where your model starts to get worse, so it stays out of the "dumb zone." You can also run `/context-paging stats` during a session to see what's going on.

This extension works well with https://github.com/elidickinson/pi-claude-bridge too if you want to use you Anthropic subscription. I submitted patches to it specifically to make pi-context-paging work.

PS. My current defaults are set to higher than what is documented.

"contextPaging": {
    "enabled": true,
    "tokenBudget": 200000,
    "trimToTokens": 140000
  },

Play around and give me feedback as to what works for you.

229 Upvotes

117 comments sorted by

51

u/ohthetrees 18d ago

My intuition is that this is a bad approach. I’m willing to be wrong, but the rolling context window approach has been tried many times with bad results, and it seems to me that your main innovation is offering tools to search earlier parts of the context window. Separate from agent performance, A big problem is it busts cache inherently. You say 90% cache hit. Well, A that isn’t very good and B I have a hard time seeing how that is possible on long sessions.

12

u/Upstairs_Addendum148 18d ago

Each cut disrupts caching, but the window does not slide every turn. Between cuts, its starting point stays fixed and requests grow normally. This allows high cache reuse across long sessions, though each cut comes at a real cost.

Tony Mason’s demand-paging research (https://arxiv.org/abs/2603.09023) and related work such as MemGPT (https://arxiv.org/abs/2310.08560) and LongMem (https://arxiv.org/abs/2306.07174 report promising results too. These are different implementations, but they support exploring memory and retrieval beyond the active context window.,

The README also includes a recall eval. Before compaction, both approaches recovered 5/5 facts. After baseline Pi compacted, it recovered 0/5; paging recovered 5/5, with matching recovery-tool evidence. Each question ran in a separate restored conversation. It is a small pilot, not proof of general superiority, but there is evidence beyond my day-to-day experience.

6

u/Ang_Drew 17d ago

yes, indeed its a bad practice since it will break the cache every certain level. that's the reason cache hit rate only at 90% not 98%.. and that's very huge gap if you pay as you go..

for context, set a compaction at 272k, then do a very long coding sessions.. you can reach 98.8% if you code intensely on the same sessions.

and also 128k is too small window it will gets filled really quick, if it is auto compact stuff i will make context window at least 272k or 320k. and with this setup i have average 95% cache hit rate

6

u/Upstairs_Addendum148 17d ago

Cache hit rate is a ratio, not the actual cost. A longer stored prefix raises the ratio and raises the cost. At Anthropic prices (cache read 0.1x, cache write 1.25x), a turn with 4k new tokens on a 100k prefix is a 96% hit. It costs the same as about 15k uncached tokens. The same turn on a 320k prefix is a 98.8% hit and costs about 37k. Your 98.8% costs 2.5 times my 96%.

Cost per turn is better measure. With the same prices and 4k new history per turn, paging at 128k costs about 24k per turn. Compaction at 272k costs about 21k, and at 320k about 24k. That is close, but it still ignores two costs. First, lost work. In my recall test, baseline Pi recovered 0 of 5 facts after compaction. Paging recovered 5 of 5. Each file you read again after compaction is input at full price. Each turn based on a wrong summary is wasted. Second, worse answers. NoLiMa (https://arxiv.org/abs/2502.05167) tested 13 models with 128k+ windows. At 32k, 11 fell below half their short-context score. Chroma's Context Rot study (https://research.trychroma.com/context-rot) found the same across 18 models. A 272k setup averages 150k of context. You pay more for a worse model.

The 128k budget does not fill up. The window rolls. Set the budget below the point where your model gets worse. 128k is only the default.

"Tried many times with bad results": which systems, and what results? Blind truncation is not a lossless window with exact recovery. The research on the second says the opposite. Mason's demand paging paper (https://arxiv.org/abs/2603.09023) measured 21.8% waste across 857 production sessions. His system cut context by up to 93% in production, with a 0.0254% fault rate. Recursive Language Models (https://arxiv.org/abs/2512.24601) use the same idea: the model inspects the prompt with tools. On GPT-5 they beat compaction by a median 26% at similar cost. MemGPT (https://arxiv.org/abs/2310.08560) built the virtual memory framing in 2023. Anthropic's own guide (https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) warns that compaction loses "subtle but critical context whose importance only becomes apparent later".

Post your cost per completed task, not your hit rate. Run the recall harness in the repo on your 272k setup and report how many facts survive. If rolling windows failed many times, link the attempts and the results. My evidence is the four papers above and the recall test in the README.

1

u/Ang_Drew 17d ago edited 17d ago

how do you decide 128k context window is enough?

so i have usecase hiding all tools and skills to reduce the initial context. only expose find tools and necessary tools like bash read write edit.

the context will be added when tools activated. and never leave the context unless uts compacted. this is why cache rate can be high.. i cant measure the stupid aspect because it performs just fine

3

u/Upstairs_Addendum148 17d ago

When I picked 128k, I went by the long-context studies I had read, such as NoLiMa and Chroma's Context Rot. They showed quality dropping well before the advertised window. For the frontier models of that time, the common mark was around 100k. So I set the budget at 128k and the trim target at 80k. That keeps every request between 80k and 128k, close to that mark.

The latest models hold up longer. I noted in the post that my own settings are higher than the documented defaults. I now run a 200k budget with a 140k trim target. The right value depends on the model. I'm still experimenting and busy updating evals, but I found the best way to tweak this is to ask a model to analyze your own session files and recommend defaults that matches your type of work.

1

u/Ang_Drew 17d ago

ahh i get it.. thanks for the nice insights! i might look into this and try with my usecase and see if my cost vs performance can really be improved

1

u/LowDesigner1330 17d ago

Most of these papers predate prevalence of 1M models and recent cache developments

1

u/Upstairs_Addendum148 17d ago

MemGPT is from 2023. The rest are not: Context Rot (July 2025) tested GPT-4.1 and Gemini 2.5, both 1M-window models, and found the decline on them. NoLiMa names 1M models in its abstract.

RLM and Mason were written this year, Mason was in March. Opus and Sonnet 4.6 launched in February, both with 1M in beta. Tony Mason is still actively researching this page and published regular updates on his blog and on LinkedIn.

A bigger window does not remove the decline. It gives the decline more room. What cache developments are you talking about?

2

u/ohthetrees 17d ago

Middle 2025 might as well be 50 years ago. Not relevant.

1

u/Upstairs_Addendum148 16d ago

Do you have a 2026 measurement where quality stops dropping as the prompt gets longer? That drop is the whole point of those papers. Dismissing a finding because it is a year old is the appeal to novelty. Newton is from 1687 and still lands probes on Mars.

34

u/Karmak0ma 18d ago

If there is no summary of the paged out context, how does the model know there is useful information there to retrieve? How do you ensure it uses the search tools? Does the model not repeat work it already did because it's not aware the info is already in the paged out blocks?

2

u/Upstairs_Addendum148 18d ago

There is a paging notice inserted at the beginning of the context window telling the model to use the context history tools to retrieve older history. So the results of work that has already been done can be retrieved by the model. There is no guarantee that the model will pay attention to the paging notice but in my evals, recall was really good using the context history tools.

10

u/mars332 18d ago

so, a handoff

1

u/Upstairs_Addendum148 18d ago

No, a handoff starts a new session, and you transfer context to it in a lossy way. Context paging stays in the same session, and the conversation history is paged out of the context but retrievable with tools.

9

u/Nullhaunt 18d ago

How is this different from billion-context-pi?

4

u/Upstairs_Addendum148 18d ago

It's lossless and needs no extra model calls to write summaries. The window prefix stays stable between cuts, so caching works well. The cost is that the model only sees old detail when it goes looking for it.

with billion-context the model sees a condensed version of everything all the time. The cost is that summaries are lossy and spend model calls, and the model has to guess in advance which details will matter.

Which one is better probably depends on how you work. I wanted a guarantee that nothing gets rewritten.

3

u/cosmicnag 18d ago

with billion-context the model sees a condensed version of everything all the time. The cost is that summaries are lossy and spend model calls, and the model has to guess in advance which details will matter.

But even a condensed version of everything all the time has a purpose - it gives the model atleast a rough overall picture and hence overall orientation. I have not (yet) checked out your extension, but conceptually isnt it better to atleast have a condensed version of what happened over a long session?

2

u/Upstairs_Addendum148 18d ago

It retains some orientation in the paging notice. It copies earlier user messages and the final public replies from the three most recent fully evicted turns. These are excerpts from the original conversation, not a model-generated summary.

That section is bounded: at most 32,000 characters, or roughly 10% of the token budget, whichever is smaller. It prioritizes newer entries. Clipped entries include references to their full text, and the notice says when earlier user messages were omitted and how to find them.

It also includes recovery references for the most recently evicted history and tool output. This prevents the model from facing an unexplained gap. It retains some task context and pointers to the details, though not a condensed account of everything that happened.

1

u/cosmicnag 18d ago

I see, trying out your extension for some time. Thanks for the clarification.

8

u/mrgreatheart 18d ago

So this means your original prompt is guaranteed to be entirely lost as soon as the window shifts. Do you use plan and todo files to solve that?

1

u/Upstairs_Addendum148 18d ago

The original user prompt can eventually leave the active window, but it is not deleted. The paging notice copies earlier user messages within a size limit and includes recovery references. That does not guarantee the original prompt stays visible indefinitely.

Plan and todo files help keep durable task state. The notice explicitly directs the model to consult plans or notes before searching older history. System instructions remain separate from the conversation history being paged.

3

u/mrgreatheart 18d ago

I would not trust a model to retrieve the original instructions periodically so I would expect this approach to negatively impact single prompt long running tasks without a documented plan and todo list. Have you found this to be the case?

To be clear, I like the idea a lot. I’m certainly interested in trying it. I’m just wondering whether you’ve tested it with large and complex tasks as well as long running chat conversations with relatively short turns.

0

u/Upstairs_Addendum148 18d ago

It works especially well with single-prompt, long-running tasks. I leave agents working for hours on multi-task plans generated by Superpowers and come back to solid implementations.

I use the extension across 40 agent sessions, short- and long-running, and feed session logs from both to keep improving it. Check the changelog at the bottom of the README to see how it has evolved.

4

u/jaegernut 18d ago

How does the model know when it needs to do a history search? 

1

u/Upstairs_Addendum148 18d ago

It decides for itself, the same way it decides when to grep a codebase. The paging notice at the top of the window tells it that older context exists, that it can be recovered word for word, and which tools to use.

2

u/Glum-Drop-5724 18d ago

Very intersting. But how does it know when to search the old paged context in a session? Say I have a long conversation where somehwere in it I say "I don't like apples". This eventually goes into the paged context and is out of the active context. If I then ask later "Should I bake an apple pie or a carrot cake?", will the model know to search trough all the paged context to find out that I don't like apples and should in fact bake a carrot cake? Or does it simply always search through the paged context for every prompt?

0

u/Upstairs_Addendum148 18d ago

The extension inserts a paging notice at the beginning of the context, telling the model that the history is paged and which tools to use to retrieve it.

2

u/No-Reason-6767 18d ago

Sorry but that doesn't answer the question asked. I like your idea and am inclined to see it work. I've also been experimenting with context management patterns.

The question (especially the example) is astute. Certain highly relevant facts may not be distinctive enough to reasonably trigger a model to search at all, e.g. previously stated preferences about apples.

OTOH, if we prompt or force the model to always consider searching back, this just quickly starts packing the context with an unordered and brittle history that we just paged out.

I'm even more concerned about this effect given your default guidance. Between 128K and 80K limits, I'm essentially only left with about ~50K effective working context which feels too small and would lead to a lot of 'swappiness'.

Lastly, a parameterized summary (e.g. user goal/starting brief, files read/modified etc.) plus a search notice might be even more useful than just a search notice.

Yes, it will be more token hungry but I don't think the model dB zones are as early as 128K. I personally use 275Kish but anecdotally the modern models seem to not become noticeably & more frequently dumb past even 500K.

I'd probably approach this plugin by leaving the first 75K as search notice + the parameterized summary and the overlap target and leave another 200K for the working context.

1

u/Upstairs_Addendum148 18d ago

See my reply above: It retains orientation in the paging notice. It copies earlier user messages and the final public replies from the three most recent fully evicted turns. These are excerpts from the original conversation, not a model-generated summary.

Wrt to context size, I ended my post saying that I'm currently using a 200k token budget with a 140k trim target, but I haven't updated my evals to test that yet.

This is configurable, so tweak it to what works best. I'm still experimenting.

2

u/wikitopian 18d ago

Still feels like this is going to result in sharp reductions in orientation after each sliding event, with the model facing a rumsfeldian "not knowing what it no longer knows?"

What's the smallest window you would recommend benchmarking it with? My own harness goes in a similar direction, but has the model itself decide which chunks to page out, and when.

github.com/plurnk/plurnk

1

u/Upstairs_Addendum148 18d ago

I've been pleasantly surprised by how easily the models stay on track and retrieve history. They are a bit shocked at first when the conversation disappears, but I've fine-tuned the paging notice at the beginning of the context window to orient them and point them to the tools for context retrieval.

The evaluated configuration is 128k with an 80k trim target, so that is my evidence-backed starting point. I do not yet have a validated minimum. Smaller windows would be useful stress tests. Mine uses oldest-first eviction rather than model-selected chunks, so your harness would make an interesting comparison.

I've started experiments with much smaller context but don't have results ready yet.

2

u/firebat-66 18d ago

Can you compare plurnk and u/Upstairs_Addendum148 app together?

4

u/bitzap_sr 18d ago

There are two parts to this.

1 - tools to search session text past the compression event.

2 - the compression algorithm.

It is not true that you don't compress. Yes you do. You just compress it all down to a single sentence.

You could take your session search tools from #1 and mix with the standard compression algo too.

0

u/Upstairs_Addendum148 18d ago

I'd push back on calling this compression. Compression means the original gets altered and sized down: you swap the data for a smaller version of it and work from that version from then on. That isn't what happens here.

With context paging, the original is never touched. Every message, tool call and tool output stays in the session file exactly as it was written, byte for byte. Nothing is rewritten, merged or replaced with a shorter version. The only thing that changes is which part of that history goes to the model on a given request.

It's the same difference as between zipping a file and scrolling a window over it. When you scroll down a long document, you haven't compressed the top of it. It's still there and you can scroll back. Paging works the same way: old turns leave the window, and the model can search, browse and load them back as the original text whenever it needs them.

1

u/bitzap_sr 18d ago

> "I'd push back on calling this compression. Compression means the original gets altered and sized down: you swap the data for a smaller version of it and work from that version from then on. That isn't what happens here."

But it is. First, compression is lossy, and compression ratio is a range. So it's like you compress a jpeg so much that all you get is a black image.

And also, from your own package: "The notice also copies the removed conversation from the stored session. It shows each removed user message and the final reply of the 3 newest removed turns. ... The copied conversation is at most 32,000 characters, or 10% of the budget at 4 characters per token if that is smaller. ..."

That's deterministic compaction.

And then, if you don't include a regular compression of the part of the context that you elide, then the model won't know what is there, and therefore won't know on its own what to search for. So you must be stearing it "we discussed this ealier, go check" or something like that.

Really the interesting part is the context search tools. If you combined those with regular compression, then the model will most probably think to search for the pre-compression info more on its own. BTW, Hermes has a built-in session_search doing that: https://hermes-agent.nousresearch.com/docs/user-guide/sessions#session-search-tool and there's at least one pi extension exposing something similar https://pi.dev/packages/pi-session-search . They're not exactly the same as they allow searching in random sessions, not just the current one.

No joke, just yesterday I was chatting with Opus 5.5 in a long session, and I asked it about a design decision that we done much earlier, and the model went and grepped for a pre-compaction part of the chat in the jsonl files. I thought that it's curious that Anthropic hasn't added a session_search-like tool to Claude yet.

2

u/sigmoia 18d ago

Observe this:

prompt
tool call 
tool call result

---- snip everything before this ---

---- only send this portion in the next turn ---
tool call 
tool call result

Now apply a rolling window function and chop off the prompt and the first tool call. Then all you are sending to the model is the last tool call and its result.

Models are stateless. So how will it know what it's supposed to do from that lobotomized prompt?

2

u/Upstairs_Addendum148 18d ago

That would be a lobotomy, agreed but that's not how it works.

The prompt that started the current turn is never removed. The extension protects the active request. Inside a long turn, it can page out older tool calls and results, but the user message that started the turn always stays in the window. So in your example, the model would see the prompt plus the latest tool call and result, not the tool call on its own.

It doesn't cut down to the last exchange. When a request goes over the budget (128k by default), it trims to a target of about 80k, not to one tool call. The model still sees roughly 80k tokens of the most recent work, exactly as it was. The system prompt and tool definitions are always sent and never paged.

The model is told what left the window. The start of the window gets a paging notice. It says that older context was paged out and nothing was summarized, and it tells the model to continue the current task. It also copies the paged-out user messages and the last few assistant replies word for word, and it includes handles to load the most recent paged-out tool output directly.

1

u/zebedeolo 18d ago

I do something similar, but with multiple parts, so this is interesting and I'll definitely check it out. currently I use an extension that stops at a certain threshold (I currently use 200k). then another extension that runs pi-vcc when the threshold is reached and then continues. it's been working really well for me, but your solution seems simpler. 

1

u/Upstairs_Addendum148 18d ago

Thanks! Your setup sounds close in spirit. The main difference is that paging has no separate step at the threshold. When a request goes over the budget, the oldest turns leave the window as one block and the session just keeps going. Nothing gets generated, so there's no extra model call and no pause.

If you try it, you can keep your threshold. Set `tokenBudget` to 200000 in settings and it will page at the same point you stop now. I'd be curious how it compares with your pi-vcc setup.

1

u/zebedeolo 18d ago

pi-vcc works really well, it kept the last x rounds without compression and summarizes the very old, mostly unnecessary stuff. but not lost, which could help.

1

u/philip_laureano 18d ago

Interesting. Is this on the same single-threaded agent loop? How is this different from say, the Star Wars opening crawl where context falls off the cliff?

Truncating the tail end of the context window makes sense, but how do you get it to remember the important things that matter if they fall off the visible context?

Yes, I see that it is lossless in the sense that it can be recovered from disk, but what happens when a critical piece of information drops off the edge and an agent forgets about it and does something they wouldn't have done if they knew about the information was lost?

1

u/Upstairs_Addendum148 18d ago

It's the same single agent loop. The extension only changes which part of the history gets sent on each request. There's no second agent or background process.

The difference from the Star Wars crawl is that when text scrolls off here, the model is told about it and can scroll back. With paging, the start of the window always has a notice that says older context exists, copies the paged-out user messages word for word (as many as fit), and gives the model the tools and IDs to load the rest.

Wrt critical info getting paged out, any approach with a finite window has to leave something out. With compaction, a critical detail can be dropped from the summary, and then it's gone for good. The model can't even suspect it was there.

So it can still happen, but the failure is "the model didn't look something up," not "the information no longer exists." The first one you can fix with a nudge. The second one you can't fix at all.

1

u/philip_laureano 18d ago

Yes, I am well aware of how compaction works. So when something gets paged out of context in this case, how do you pull it back in? Does the agent ask for a specific page or get a page look up if it searches for a specific text?

1

u/Upstairs_Addendum148 18d ago

the extension gives the agent additional tools it uses to search and browse the full conversation history.

1

u/philip_laureano 18d ago

Sounds simple enough. Thanks for the search idea

1

u/civilian_discourse 18d ago

How is this different than pi-observational-memory? 

0

u/Upstairs_Addendum148 18d ago

I don't know the extension but my agent tells me it is a smarter form of compaction, runs in the background and maintains a memory. context paging doesn't compact and is lossless.

2

u/civilian_discourse 18d ago

Did some more digging... It seems like pi-observational-memory is effectively the same thing except that it generates a sort of table of contents of the history. Without that, the agent is blind to what the history even contains. I think you should check it out, I think it is going to work better than what you have. 

1

u/nescedral 16d ago

I think a problem with pi-observational-memory is that the table, while more concise than the original text, is still a record that grows in an unbounded fashion, gradually eating up context. I could be wrong, though.

1

u/civilian_discourse 16d ago

it's not unbounded. It goes like this:

OM...

  1. generates "observations" from session activity frequently
  2. generates "reflections" from accumulated observations
  3. drops observations that are irrelevant or covered by reflections
  4. reflections are never dropped but are truncated in context once they hit their token budget

...

So, the way reflections are handled is similar to context paging, but instead of the session being paged, it's dense list of reflections that can be used to lookup observations which can be used to lookup session entries. It's basically the same idea but with a nice memory gradient between the current activity and previous activity.

1

u/nescedral 15d ago

Thanks for the clarification. I already had good vibes about observational and this makes me like it even more.

I do wonder about the longterm consequences of never dropping reflections (even if they are paged out) at least in the sense that they could also become irrelevant, stale, or superseded by later reflections. But overall, I like the tiers and that gradient of detail.

My worry with the “plain” full pagination approach is when models don’t know what they don’t know, and therefore don’t go digging through the old pages, or perhaps get distracted by paying attention to something super old that is out of date with something that gets said later. I feel like having some kind of “map” of the info, like chapters in a book, would be helpful, and that feels similar in flavor to what OM is doing in with its tiered system.

1

u/Upstairs_Addendum148 15d ago

Note that context paging keeps user messages in the paging notice. I'm busy adding an eval to test if models use paging tools to look up tool results that were paged out since it was the most common concern raised.

1

u/civilian_discourse 15d ago

Yeah, I have long sessions but I never have infinite sessions. I have another layer for formalizing various things into documentation for cross-session context.

For a true infinite session, those two things would need to talk to one another or feed into one another... I know there are versions of this out there, but I haven't seen one that has really moved me to try it. The main problem is that no one has solved the second part of your critique which is stale memory that steers the agent in the wrong direction. Unless you have a human in-between the session memory and the long term memory to recognize when the memory needs to be refactored or changed in some dramatic way, it's guaranteed that the agent will eventually degrade.

1

u/GoingOnYourTomb 18d ago

I feel like this could be genius for local models. Thank you I will investigate

1

u/Upstairs_Addendum148 18d ago

My 2nd hand rtx 3090 arrived today and I can't wait to try on small local models!

1

u/ImagineSquirr3l 18d ago

Isn't it the same thing than pi-vcc?

0

u/Upstairs_Addendum148 18d ago

I don't know pi-vcc but it looks like it compacts, context paging doesn't. I motivate why in the README.

1

u/ImagineSquirr3l 18d ago

No it's lossless too, keep full history with a search tool. Instead of a fixed ten size, you decide how many turn you keep.

1

u/mpread-it 18d ago

no summarization, no additional LLM calling, if that's what you mean. it's almost instantaneous. sometimes i don't even realize that it triggered.

1

u/jinnyjuice 18d ago

Any benchmarks for intelligence/needle-in-haystack/correctness/accuracy/etc.?

1

u/Upstairs_Addendum148 18d ago

check out the recall evaluation in the README: https://github.com/rochecompaan/pi-context-paging#recall-evaluation

1

u/jinnyjuice 18d ago

Ah thanks, seems like it's work in progress. You will definitely need to explode that number by multiple fold, say 20 facts as starters, eventually expanding the benchmark to 100 to 1000 facts for multiple orthogonal scenarios. I think it's good to mention maximum context length of your LLM config also, say 256k or 1M.

1

u/Pbd1194 18d ago

i do sth similar where i drop tool calls nd responses on demand. so my cache takes a one time hit every few turns but net net my ctx remains small. user asst messages are always retained. only tools like bash logs python executions are deleted on demand.

1

u/Upstairs_Addendum148 18d ago

yes, sounds similar. do you give your agent tools to search/browse history?

1

u/Pbd1194 18d ago

yes. https://github.com/kenn-io/agentsview — i use this tool. cli allows semantic search. so my agent knows how to use this tool. so it recovers knowledge from here.

also i have that obsidian wiki thingy. so every 7 days agents look at most recent 7 days of work and distill into the wiki. plus wiki is defragmented every 15 days.

1

u/wegster 18d ago edited 18d ago

Did you happen to do some simpler tests simply measuring wall time and tokens used with and without your extension for a moderate complexity job? (along with quality of output)

I was experimenting with something similar, focused on ensuring the original prompt and latest results remained lossless through compaction, but so far, have mostly seen longer execution times and token use. Still early testing though.

1

u/Upstairs_Addendum148 18d ago

Wall time and token usage are very similar. I can do a better job of documenting this. The README has an eval section, but it focuses more on recall and accuracy. Generally, I would say the value is the continuity you have in long-running sessions. I hope sessions stay more coherent for longer because you keep your agent from spending a lot of time in the dumb zone, but I don't have benchmarks to back that up yet.

1

u/wegster 18d ago

Yeah, this is exactly where I ran into issues (early days yet though), as logically it makes sense, but if it's not leading to improved quality of results, AND is generally increasing wall time/token use, then it's a seemingly good idea that doesn't work in reality.

I'm not saying yours doesn't - I'm saying my initial experiments on something similar versus a small number of real work benchmarks hasn't proven then benefit, possibly - as of yet. Thus the comment/questions. Will take a look but also if you happen to run some more testing etc. pls add to the thread.

1

u/Immediate_Theory_467 18d ago

Interesting for sure. However, what if you want to store this for long term context / memory for recall?

1

u/Upstairs_Addendum148 18d ago

It's not really the use case it's targeting, unless you want to treat the full conversation history as long-term memory.

1

u/isty2e 18d ago

Cache hit rate of <95% does not seem promising to me. I usually hit >99.5%, so I feel like this will be detrimental to me costwise.

1

u/Upstairs_Addendum148 18d ago

At 99.5%, paging could cost you more in uncached input. But cache efficiency is only part of total task cost. When work spans multiple sessions, reconstructing context can mean rereading files, repeating searches, redoing analysis, and explaining earlier decisions again. That costs tokens and human time too.

Paging aims to reduce that repeated work by keeping the original history accessible. Whether those savings outweigh the cache penalty depends on the workflow. I don't yet have a controlled comparison showing it is cheaper overall.

1

u/mooky-bear 18d ago

Curious if you’ve measured the performance difference of cache loss on every page eviction vs normal compaction at 90% context

2

u/Upstairs_Addendum148 18d ago

The eval mentioned in the README records token use, cache reads/writes, estimated cost, and timing for paging versus native compaction, including compaction overhead. But the current pilot is too small to establish a cost or speed advantage, and it is not a dedicated comparison against compaction at exactly 90%. Your question and others are good pointers to areas I should include in the benchmarks.

1

u/juanfnavarror 18d ago

does the paged context LLM also help you write these comments?

1

u/runnystool 18d ago

Interesting. Did you experiment with large compaction summaries? If you have 128k context and chop out 80k, that mean it leaves 48k in context. What if you triggered compaction with a 40k-50k budget? I wonder if it would retain more relevant stuff than this drop approach. Combine that with the search and lossless history. 

1

u/Upstairs_Addendum148 18d ago

One correction: the defaults trim from 128k down to 80k, so roughly 48k leaves the window, not 80k.

The published eval compares against native compaction, not a custom 40–50k summary. A larger summary combined with searchable original history is a useful comparison. My results do not rule out that hybrid working better.

1

u/runnystool 18d ago

A good summary, with references for where to look up key information (file:line reference for jsonl chat logs) could be more powerful. 

1

u/firebat-66 18d ago

Thank you for including the paper. Just for a gist, do you follow the c9nventions in that paper?

1

u/Upstairs_Addendum148 18d ago

The same broad memory-hierarchy idea, but with a different implementation. Mason’s Pichay works as a proxy and pins content based on recovery requests. Mine integrates with Pi, uses oldest-first eviction with stable cut points, and gives the model explicit history-recovery tools.

1

u/firebat-66 16d ago

Thanks for the reply! Have you had a chance to look into ranxianglei's "preprint" paper that relates to long context persistence? https://github.com/ranxianglei/billion-context/blob/master/paper/model-driven-incremental-hierarchical-compression-training-free-multi-generational-context-management-for-long-lived-coding-agents.md

If you do get a change to read it, I would love to hear your opinion on it!

1

u/Upstairs_Addendum148 15d ago

It supports the same idea that a bounded context below the range where the model gets worse is better than filling a huge window, and one-shot summarizing compaction destroys detail. The tradeoffs are different. billion-context accepts some detail loss so that the model always keeps a short version of the past in view. pi-context-paging keeps every word exact and recoverable, but the model sees older history only when it asks for it. billion-context needs extra model calls to write summaries, a roughly 2K-token rules prompt in every request, and a large kernel. pi-context-paging needs no extra calls and adds only the notice and tool descriptions. the paper says models rarely use restore tools unprompted in their design. I don't find that - I see models using recall tools regularly.

I'm expanding my evals to answer many of the concerns raised in reply to my post and would love to measure my extension, billion-context and pi-observational-memory it to have more concrete evidence as to what works best. Generally all three these extensions are aligned on the core idea and should give anybody using them a lot more continuity and coherence in long-running sessions.

1

u/johnzadok 18d ago

Will this break kv caching and need to prefill from scratch every time window rolls?

1

u/Upstairs_Addendum148 17d ago

yes, that's why its best to configure a big token budget. you have the same challenge when your session fills context normally and you're forced to compact or start a new session. my extension just ensure betters continuity with exact recall of facts without pointing your model to old session files.

1

u/Imanari 18d ago

> When the window hits the budget, it pages out one large block at once

How does this not have a negative impact on performance? This is the moment you would write a summary of the part you are cutting off. How is not writing the summary better? I am genuinely curious, nobody has solved memory so appreciate you putting your ideas out here.

3

u/Upstairs_Addendum148 17d ago

see my other comments where I explain what is in the paging notice. writing a summary may lose important information, whereas paging gives the model a way to check the facts unmodified. when you read a book and want to recall a specific quote you read 10 pages back, you just page back and re-read it. if you only rely on a summary and the quote is missing from it, you have no way to recall it.

1

u/Imanari 16d ago

I see. So providing a summary is kind of the "cheap way out" and instead you provide a retrieval mechanism on original chat history. Makes sense. You might be onto something.

1

u/nescedral 18d ago

I've thought about doing this very thing, and it seems reasonable. I might try your implementation.

I have this nervous feeling that the rambling and chaotic nature of the way my ADHD brain works in a project is going to dump way too much information into this "endless" context book, though. I can't help but feel like keeping *everything* is overkill? And potentially destructive to the ability to find "relevant" and insightful information. But maybe I'm overblowing that angle.

1

u/Upstairs_Addendum148 17d ago

you're right, keeping everything IS overkill and that's why I think it is a good idea to remove old context, with the difference that there is a constant hint to the model in the paging notice on how to find it. see my other comments where I explain what is in the paging notice.

1

u/jumski 18d ago

Very interesting idea! I'm using pi-blackhole and I'm mostly satisfied with it. Its a little bit different, merging two ideas - determinictic compaction (pattern matching, rulex, regexes) with refined observations (facts) with a recall tool.

Isn't it missign critical facts, session goals etc when they go out of the page window? Model must explicitely ask for them, and given it is not aware of those facts, it does not know what to ask for?

I like this about blackhole - i often read what it collected after deterministic compaction or observer/reflector runs and it is really substantial stuff.

I need to test your plugin as i think there is merit in simplicity. Also, pi-blackhole will run into a really long memory and facts list after lot of turns, just much much later than regular summarization compaction.

2

u/Upstairs_Addendum148 17d ago

see my replies in the comments where I explain how the paging notice works. user responses are included in the paging notice, so critical facts remain in the context window. my evals test exact recall across a compaction boundary too, and recall is 100%, but as some pointed out my evals need to span longer sessions.

1

u/DaShrub 18d ago

Magic-context takes a good approach to something similar with refined context compaction and retention/search tools and built in memory promotion. One major issue in pi with this approach is that long session files will bloat your memory usage hugely especially on stock pi with node. This means that long running sessions with aggressive context management inevitably slow down and take gigabytes of RAM and slow down UX... Pi-Bolt helps a lot but the fundamental problem remains.

1

u/Upstairs_Addendum148 17d ago

Fair point about RAM growth, but it’s not a concern on my setup yet. One session ran for six days and accumulated 80 MB and 12.4 million tokens of saved history. At an earlier checkpoint, with ~30 MB of history, the Pi process used about 930 MB of resident RAM and it peaked at 1.6 GB.

Paging doesn’t solve unbounded memory growth, but I’m not seeing a pressing reason to change the approach yet.

Magic-context’s memory promotion looks fascinating, though. Thanks for the pointer!

1

u/petter_s 17d ago

You should perhaps keep all user messages. Those could contain important information

1

u/noferengi 17d ago

Thanks for trying to tackle a shitty problem.

Do you cut along vLLM memory block sizes, so removing the front still allows later blocks without recompute, or is it a full prompt processing cycle every time you shift? I've seen some models really not like prefix caching because of SWA or something and I'm exhausted by all this.

If I'm reading your post, for a 200k prompt you shift the first 60k tokens out of it roughly and treat it as a continuous byte stream for your tools and searching. At 1k PP that's a little over two minutes very heavy wattage and recomputing. And you do that every 60k tokens. Hmm.

One of the things I was recently surprised by was the visual compaction in OhMyPi isn't actually tuned for Qwen 3.8 27B, in my own recall tests it was absolutely garbage as a method. Compaction sucks, you're just sitting there token generating maybe for 30k context or up to 9 minutes just writing summary. (In practice I'm seeing much less than that but bleck). So yeah I'll actually go back down to 25% used context and have all the way up to 80% again before I need to compact. But then sometimes it'll spend time rebuilding what it lost from compaction.

So yeah, it's a shitty problem.

1

u/Upstairs_Addendum148 16d ago

Thanks. On the cache: no, and nothing above the inference engine can. vLLM hashes each block with its parent's hash, so a block only matches when everything before it matches. Drop the front and every later block misses. Hosted caches work the same way. So each cut is a full prefill of the new window. Between cuts the prefix is fixed and caching works as normal. Cuts land on message boundaries, not token boundaries.

With 200k/140k a cut reprocesses 140k, about 140 seconds at 1k tok/s, once every 60k new tokens. Two settings control it. The trim target sets how much is reprocessed. The gap between budget and trim target sets how often. 200k/80k gives 80 seconds per cut every 120k tokens.

Compaction on the same box also prefills after the summary, and first it generates the summary at generation speed, which is the minutes you describe. Paging never generates. The prefill is the whole cost, but nothing is lost.

1

u/noferengi 16d ago

I gotta say, it's refreshing to talk to a human about this stuff.

Thanks for taking the time to explain all of that, from vLLM to your algorithm. It all makes total sense. Your compaction strategy is definitely something any LLM could understand and keep working with, based on that shift amount obv, and just fantastic.

I give you my updoot and I investigate your code and look at using your project in my own work.

Thank you for posting and for sharing!!

Ramble below, please stop reading \\\|\/

I really want to minimize that prompt processing time by laying out the KV cache differently. Minimize PP and maximize TG doing *actual work*. Minimal time thinking about the task or figuring out what to do, just doing it. When I get high and think about this, the *ideal* seems to be some sort of "Matryoshka doll" context, small tools to add a layer (and perform a task) and shed a layer (confirm the task is completed), so basically push and pop, and during work: as small tasks are completed, the outer layers shed, and then some inner layer at some point decides to create new outer layer(s) for additional tasks. Maybe it ultimately has to make five or fifty layers before it finishes it's task. Ideally the LLM would keep the task size for each layer low, under a dozen, breaking things down into as many recursive layers as.. this is a crazy prompt at this point.

Could current models even work that way, or are they **RL**ed too heavily?

I'm frustrated because I want to create these aforementioned push pop tools and throw them in a harness and test it with Qwen 3.8 27B and some of my ideas (like referencing data, only using variable names/references during tool calls, not allowing the LLM to full in even primitives during tool calls, and little toy things like Gemma 4 12B "unified" completely fall apart. I'm not going to finetune a model because I had an *idea*, like, if it was a good idea the LLM would have got it. Although they are trained pretty heavily about specific tool usage and maybe that works against my idea here?

1

u/davblaster 16d ago

I’m assuming this would take some proper work to port to pi-durable. Have you considered what’d be involved?

2

u/Upstairs_Addendum148 16d ago

Support for pi-durable would be neat! I'll put it on the roadmap.

1

u/wadamek65 16d ago

I've been trying out the extension for the past 3 days, with one session I had running for ~200M tokens total. It seems to be working well, didn't have any issues with agents drifting during implementation, the extension works fine. It also seems to be rather cost-efficient, usually with a workload like this I'd expect to pay much more in API costs using my usual manual handoffs and compactions.

One issue I had is that the automatic message to the agent made it confused. It thought it was about to reach context budget and will be unable to work, so it continuously refused to keep going because it thought it'd run out of context and I had to instruct it that it's not a problem for it. Is it possible to fix that?

1

u/Upstairs_Addendum148 16d ago

Glad it's working for you, thanks for trying it!

Please ask an agent to analyze the session and create an issue reporting the confusion it had as well as how it would recommend we give more clarity to the model on the context budget.

1

u/davblaster 6d ago

This works really well.

1

u/Upstairs_Addendum148 6d ago

Glad to hear it!

1

u/adamshand 18d ago

This seems like a .... remarkably obvious solution. Why isn't everyone doing this? The only downside seems like you loose the compressed older history, but with a note to the agent and a search tool, that seems reasonable?

Do you know if it'll work with: https://github.com/earendil-works/pi-claude-code

2

u/Upstairs_Addendum148 18d ago

I think a few things explain why it's not common. Compaction is simpler to build. It needs one summary call and nothing else. Paging needs an index over the session, recovery tools, and a notice the model trusts.

Models used to be bad at using tools like this. Current models are much better at it, so the approach has only recently become practical.

People worry about prompt caching. If you drop messages one at a time, you break the cache on every request. Paging gets around that by cutting one large block at a time and then keeping the start of the prompt stable for many turns.

One small correction: you don't actually lose the older history. Nothing gets compressed in the first place. The full session stays on disk exactly as it was, and the model can load any part of it back word for word.

On pi-claude-code: it should work in principle, but I haven't tested that combination.

1

u/adamshand 17d ago

thanks for the reply, will give it a try!

1

u/whiterose0000001 18d ago

Same kind of thing t3 code usesage for context handoff

1

u/adcostanza 18d ago

I do this but on demand as an /offload command and I use it sparingly. Like other people said paging context isn’t really a great approach because you loose your input tokens prefix cache every time you paginate and the session is likely to degrade a lot if you do that a ton of times.

I personally only offload when I have a old session I want to come back to without having to start a new one - I use it more as a mechanism to not take the hit of resending all the cold uncached input tokens to the model but still giving it the basic context of where we were (ie the last 1-2 turns depending on what fits) and a tool that enables it to search the offloaded history. I would only do this if I’m at 15%+ of my context window and am coming back to a many hours old session.

1

u/Antitesla 18d ago

Port to opencode please

1

u/Kiedrola 18d ago

Tomorrow I am going to give a try. Thanks

1

u/zephyr_33 18d ago

na. if u sit and see. u will notice that 80% of ur context is eaten by - 1. reasoning tokens. 2. tool output.

simply replace them with reasoning summaries and tool / tool outcome summaries and u save a tonne with a very little context loss.

1

u/Laicbeias 18d ago

I kinda have the llm collect just whats open and then move that into a new chat. Splitting it into multiple main tasks and sub tasks.

With all the techniques going around for compressing or dropping stuff it seems to just work. The worst is when the llm doesnt know anymore whats in and then has to reload some files mid conversation.

The ground truth also does change when you move forward and you also see what fell off on the sides. For me thats the easiest way. You get tasks posted and you can later just pick off from there. And for main stuff you can just continue and you know whats loaded. Cache hit is around 97% with this and

1

u/LordMoridin84 17d ago

Compared to other compact systems, this is a longer tail, no summary and better search right?

The problem is that you are going to get more compaction events because the agent has less context to work with after compaction.

I am not sure that keeping more of the tail is better since agents seem pretty good at continuing from a summary now.

0

u/[deleted] 18d ago

[deleted] — view deleted comment

1

u/MoonlightSyncopate 18d ago

I see that in a later thread, you claim you can still achieve a 90% prompt cache hit, but what I want to tell you is that math will fool you in percentages.

So for a regular pi session I can hit 98-99% prompt cache rate easily without problem. And you are thinking a 90% prompt cache hit is very close to 98%~99%, and that the difference is only 8-9%? No, that is completely wrong. The absolute number of cached token hit will be much more different the larger the tokens you consume in your session.