Skip to content

refactor: unify checkpoints and fix compaction parity gaps - #506

Merged
maralbahari merged 44 commits into
mainfrom
refactor/typed-request
Nov 10, 2026
Merged

maralbahari merged 44 commits into
mainfrom
refactor/typed-request

Conversation

@maralbahari

@maralbahari maralbahari commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part 5 of the storage/refactoring stack (#500), following the merged PRs 1–4.

Cleanup

  • Carry the typed ResponseCheckpoint from rehydration into persistence. Response persistence extends the row IDs already loaded, and session checkpoints retain the IDs they stored. Split commit reuses its checkpoint or loads only the parent response row through typed get; the shared rehydration path still runs before inference.
  • Read an existing conversation once during rehydration. Remove the duplicate get/get_or_create read, creating a missing conversation only when required for a stored turn.
  • Batch public-ID lookups while preserving the original-item selection already used by main. The query selects the earliest (created_at, id) row per requested ID inside bounded batches, avoiding both one query per ID and loading every repeated occurrence. Repeated-ID support itself predates PR5.
  • Decode ResponseData inside the store and remove unused DbResponse exports. Type request metadata, consolidate reasoning normalization, and use one typed validator for complete upstream responses.
  • Use CompactedWindow instead of recovering the compaction item from the end of a list. Keep compact_response as the public endpoint and one shared summary operation; remove forwarding wrappers, the unreachable multi-agent branch, and repeated summary-settings/threshold selection. Keep private write_turn to separate storage work from persistence timing and error handling.

OpenAI parity gaps fixed in PR5

  • Automatic compaction output: expose compaction items in the public response and SSE lifecycle. Single-agent execution can compact before inference and again after a completed answer when the threshold is crossed, including store: false. Evidence: the in-turn-chain, in-turn-chain-stream, and store-false OpenAI/gateway captures.
  • History after automatic compaction: retain the compacting turn's original input instead of replacing or storing it again as a compacted window. The next single-agent continuation starts at the latest public compaction item and retains that item's identity. Evidence: in-turn-chain and its streaming variant, plus the tool-loop captures and live gateway replays.
  • Concurrent conversation compaction: preserve each compacting response's original input snapshot while retaining the concurrent turn's output in the conversation. A later continuation uses the last committed compaction. Evidence: the paired stale captures and their replay with the concurrent commit interleaved.
  • MCP discovery on ordinary follow-ups: reuse the successful initial listing, including an empty listing, unrestricted tools, and widened/removed allowlists. These follow-ups no longer issue another tools/list request merely because the current declaration is broader. Evidence: compaction-mcp captures and integration tests that count actual discovery calls.
  • MCP discovery after compaction: omit old mcp_list_tools records from compacted output and invalidate them for later context, so the next turn discovers tools again. Evidence: the standalone and automatic compaction cases in compaction-mcp, with gateway integration coverage for stored and session continuations.

Earlier public tool-item ID/status fixes and repeated-ID support are preserved; they are not counted as new parity fixes here. OpenAI's opaque compaction contents were not inspected.

Remaining observed differences

  • OpenAI rejects an async result immediately after automatic compaction; the gateway accepts it. Both reject it after an intervening continuation.
  • OpenAI performs a final multi-agent compaction after the answer; the gateway currently omits it.
  • OpenAI requires multi_agent.enabled explicitly on continuation; the gateway inherits it. PR5 fixes history trimming for inherited settings without changing that admission behavior.

Benchmarks

Rerun on 2026-11-09: this PR at a342815 versus main at f410869 (the PR base). These measurements isolate PR5 from the already-merged stack.

Fresh SQLite files, 100 samples per case, 3-second warmup and 5-second target measurement. Two passes per revision in the order main → this PR → this PR → main; each cell is the median of its two run medians. Store-only persistence timings exclude setup; this PR receives the parent checkpoint already loaded during setup, as it does after normal rehydration.

Operation History main (ms) This PR (ms) Observed change
Response rehydrate 3 items 0.220 0.218 -0.9%
Response rehydrate 30 items 0.766 0.761 -0.7%
Response rehydrate 300 items 5.680 5.781 +1.8%
Response persist 3 items 1.310 1.067 -18.6%
Response persist 30 items 1.369 1.180 -13.8%
Response persist 300 items 1.596 1.380 -13.5%
Conversation rehydrate 3 items 0.157 0.137 -13.0%
Conversation rehydrate 30 items 0.718 0.771 +7.3%
Conversation rehydrate 300 items 6.068 6.235 +2.7%
Conversation persist 3 items 1.295 1.237 -4.5%
Conversation persist 30 items 1.451 1.444 -0.5%
Conversation persist 300 items 1.900 1.898 -0.1%
Executor rehydrate 1 stored turn 0.207 0.208 +0.6%

Response-persistence latency measured 13.5–18.6% lower across the three history sizes; both PR passes were faster than both main passes. Conversation persistence and executor rehydration were broadly unchanged within run variation. Read timings varied substantially between passes—for example, conversation rehydration at 300 items ranged from 5.331–6.805 ms on main and 5.668–6.802 ms on this PR—so these measurements do not establish an overall rehydration speedup.

Only executor depth 1 is reported: the existing higher-depth benchmark cases do not extend their seeded chain, so they cannot establish depth scaling. These are local storage/rehydration measurements, not model-inference or compaction-throughput measurements.

Test Plan

  • The full workspace run passed 3,126 tests, 0 failures, 26 ignored before the final helper rollback and test pruning. The earlier recovery-timeout failures also passed in that full run. A second full workspace run was not performed after the final cleanup.
  • Final working tree: 1,411 core unit tests passed (8 ignored), plus 107 integration tests passed across compaction, sessions, stateful Responses/reasoning, tool-search projection, split execution, and HTTP/WebSocket recovery. Workspace Clippy, release build, pre-commit, formatting, and diff checks passed.
  • SQLite and PostgreSQL public-ID lookup regression passed, including 1,000 repeated occurrences and multiple bind batches; PostgreSQL storage (5) and Messages schema (2) tests passed. Embedded-runtime Clippy and MSRV 1.98.1 all-target/all-feature checks passed before the helper restoration.
  • Earlier Linux CI-equivalent validation passed all 44 job groups, including PostgreSQL/schema/tenant checks, SQLite vector support, embedded runtime, CLI/telemetry smoke tests, Claude Code/Codex harness replays, Python 3.10–3.13 wheels, and website checks. Separate manylinux wheel and container build/restart checks passed. Those artifact jobs preceded the final review fixes; affected Rust/storage/build checks were rerun afterward.
  • Validated 43 retained Responses/compaction cassettes, 602 HTTP turns. Existing OpenAI captures remain the behavioral reference; refresh-only YAML changes were discarded. Existing reasoning and MCP integration coverage remains; the moved reasoning unit tests and added tool-search/registry unit tests were removed.

The compaction replays execute current Rust gateway code with fresh SQLite storage and scripted inference. Responses management replays run against the release gateway. Existing OpenAI captures establish the wire behavior; MCP integration tests also assert actual discovery-call counts. No new YAML refresh is included, and no duplicate unit tests were added for the helper restoration.

These are local results. macOS jobs and remote GitHub Actions were not run as part of this validation; publication/deployment workflows were not run. The retained lifecycle fixture passed; separate fresh OpenAI probes showed inconsistent immediate post-deletion history, which is not treated as a new persistence contract in this PR.

@maralbahari
maralbahari added this pull request to stack #504 November 3, 2026 12:47
@maralbahari maralbahari changed the title refactor: one checkpoint from rehydrate to persist (5/5) refactor: typed checkpoint, request metadata and upstream responses (5/5) Nov 4, 2026
@maralbahari maralbahari changed the title refactor: unify checkpoints and fix compaction parity gaps (5/5) refactor: unify checkpoints and fix compaction parity gaps Nov 9, 2026

@tjtanaa tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two compaction and session-retention issues need attention.

@tjtanaa tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two additional compaction issues on the updated revision.

@tjtanaa tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two further issues in the updated storage and compaction paths.

None => Vec::new(),
};
let previous_response_id = parent.and_then(|parent| parent.response_id.as_deref());
let mut item_ids = parent.map(|parent| parent.history_item_ids.clone()).unwrap_or_default();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we reconcile or validate this cached history against the durable parent before committing? For example, store A → B, let C rehydrate B, then delete A before C persists. Deletion removes A's IDs from B, but C now copies its stale A+B IDs and commits successfully because B still exists. A later continuation of C can therefore read A's deleted context again. Current main reloads B during persistence, so this completed-delete-before-persist ordering does not restore A. Please add an interleaved deletion regression and reject or refresh a stale checkpoint.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this. I checked it on OpenAI first with your order: store A ("Reply with only SAPPHIRE.") → B ("Reply with only ORCHID."), start C from B as a streamed turn, delete A while C streams, then list C's input items and continue C asking for the word the first user message asked for. I ran it four times and OpenAI was not consistent:

Run C's input items Next turn's answer Next turn's input items Deleted A came back
1 A gone ORCHID A gone no
2 A still listed SAPPHIRE A gone yes, the model saw it
3 A gone SAPPHIRE A listed again yes
4 A gone ORCHID A gone no

So OpenAI has the same race and does not guarantee either result. Since main reloads the parent during persistence and OpenAI's clean runs drop A, I kept that behavior: persist now re-reads the parent's current history and keeps only the cached IDs that are still in it, so a deletion during the turn is never undone. The compaction trim on the cached IDs is kept, and if the parent itself was deleted the turn fails as on main. deleting_an_ancestor_during_a_turn_does_not_restore_its_history covers your order. I did not add these OpenAI recordings because the result is not deterministic. The session checkpoint case will be covered with WebSocket cassettes in the follow-up PR.

@maralbahari
maralbahari merged commit 47e9a71 into main Nov 10, 2026
17 checks passed
haoshan98 pushed a commit that referenced this pull request Nov 10, 2026
### Summary

`messages_test` failed on CI after #506 merged, in two tests at once:

- `messages_returns_anthropic_error_for_unreachable_upstream` got `200`
instead of `502`.
- `messages_provider_tools_preserve_proxy_body_and_stream_events`
counted 2 upstream requests instead of 1.

Both come from one flaky setup, not from #506. The two "unreachable
upstream" tests bound `127.0.0.1:0`, read the address, and dropped the
listener to free the port. Tests in the file run in parallel, so the OS
could hand that port to another test's mock upstream. The "unreachable"
request then reached that mock: it answered `200`, and the other test
saw an extra request.

The tests now keep the port reserved for their whole run with a socket
that is bound but never listens. Connections to it are refused, which is
the `502` path the tests check, and no other test can take the port
while the socket is alive. The new `refused_upstream()` helper is shared
by both tests.

`health_test.rs` (two tests) and `agentic_process/tests.rs` use the same
drop-the-listener pattern and could flake the same way. This PR leaves
them unchanged to stay a quick fix.

### Test Plan

- `cargo test -p agentic-server --test messages_test`: 16 passed, and 20
consecutive runs passed with no failure.
- `cargo clippy -p agentic-server --tests -- -D warnings` and pre-commit
passed.


🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: maral <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@maralbahari
maralbahari deleted the refactor/typed-request branch November 10, 2026 13:16
franciscojavierarceo added a commit that referenced this pull request Nov 14, 2026
### Summary

The [#500](#500) stack
(#501, #502, #503, #505, #506) changed what the gateway stores: history
now holds only client-facing items, and model-facing shapes are built at
one lowering point for each request. This PR writes that contract down
where contributors and coding agents will read it, brings the roadmap up
to date with what has merged since October, and removes API docs that
still describe behavior main no longer has.

- `ARCHITECTURE.md`: a new "What a turn persists" section under
`storage/`. It states the rule (client-facing items only; model-facing
shapes are never stored), the rehydrate, persist and session flow around
`ResponseCheckpoint`, and the recorded OpenAI behavior a continuation
follows for compaction, a compaction sent back as input, items sent back
by ID, deletion, and conversations. It also replaces a stale paragraph
that still described model-facing calls being persisted as input items,
and names `file_search` as the one remaining exception
([#482](#482)).
- `AGENTS.md` and the `storage-schema-change` skill point to the new
section and add the client-facing history rule to the checklist, so a
change to persisted data starts from it.
- `ROADMAP.md`:
- The Responses goal now describes client-facing persistence and the
#500 stack, with `input_items`/`DELETE` (#466) and HTTP `store: false`
running through the gateway (#475).
- Shipped capabilities are marked "shipped" with what remains:
multi-agent (#405 remaining; `last_task_message` waits on observed
OpenAI behavior, #395), single-agent WebSocket steering (approval-aware
steering depends on #145), file search (#356, #482), async tools, hosted
tool search and web search providers, Messages threads and native server
tool calls, rate limiting, and observability.
- The closed `store=false` follow-up (#433) is removed, and the closed
#244 is cited as delivered.
- The website copies the root roadmap at build time, so only
`ROADMAP.md` changes; strikethrough is not used because the roadmap page
renders without GFM.
- `docs/api/index.md` (and its website snapshot): removes the "direct
HTTP pass-through" description of `/v1/responses`, which #475 replaced
with gateway execution for every request; multi-agent is documented over
WebSocket as well (#407); replayed `mcp_call`, `web_search_call` and
`code_interpreter_call` items are described as lowered for the model,
with parity recordings tracked in
[#492](#492).
- `README.md`: the "Roadmap at a Glance" checklist marks multi-agent and
file search as shipped.

### Test Plan

- Docs only; no code changes.
- Every roadmap item marked as shipped was checked against its merged PR
or closed issue; items whose issue is still open stay listed as
remaining (#330, #356, #395, #405, #482, #145).
- Each statement in "What a turn persists" was checked against the code
on `main` (`ResponseCheckpoint`, `write_turn`, `ResponseStore::persist`,
`continue_from_compaction`, `filter_for_compaction`,
`resolve_input_items`, `delete_in_tx`); the removed pass-through text
was checked against `handler/http/responses.rs`, where every request
goes through `ExecuteRequest`.
- `pre-commit` hooks pass on the changed files.


🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: maral <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Francisco Javier Arceo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants