Skip to content

refactor: one typed storage layer for rehydration and persistence (1/5) - #501

Merged
franciscojavierarceo merged 6 commits into
mainfrom
refactor/storage-layer
Nov 4, 2026
Merged

franciscojavierarceo merged 6 commits into
mainfrom
refactor/storage-layer

Conversation

@maralbahari

@maralbahari maralbahari commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Part of the RFC #500 (one typed path for rehydrating and persisting history).

Summary

This PR simplifies how history is rehydrated and persisted. It does not change what is stored on disk; the schema is the next PR in this stack.

Before After
Item and metadata JSON converted in several places: Item::as_input/as_output/as_inout, decode_metadata, Response::metadata_as, three copies of the item encoder, and conversation metadata parsed in the HTTP layer One conversion pair per column in storage/types; each item row is parsed once
Overlapping store entry points: persist, persist_if_version, persist_with_conversation_id, rehydrate, rehydrate_snapshot, create, create_with_metadata_and_items One typed function per operation: create, get, get_or_create, rehydrate, persist
Handlers and the executor decoded item rows themselves Stores return InOutItem and storage types, never rows
A previous_response_id turn read the parent response row three times ResponseHandler::rehydrate returns the response and its history in one call (two queries)
Conversation rehydration ran a snapshot query and then a separate metadata query One statement returns the version, the latest turn's metadata and the items
Conversation persist had a version-checked mode and an unchecked mode used only by tests Persist always checks the version captured at rehydration
Duplicate SQL helpers (get and get_in_tx, get_item_ids, get_snapshot, get_items_by_conversation) One SQL function per table operation
Handlers had overlapping write paths: execute_turn, execute_turn_with_metadata and commit_tree (plus a CommittedResponse receipt) Each handler has one rehydrate and one persist; persist.rs builds the turn's ResponseMetadata (including any multi-agent tree) in one place
After rehydration, tool preparation read the parent response or the conversation turn again (response_metadata_at_version, ResponseHandler::get) to restore tool-search state after compaction Rehydration keeps the continued turn on RequestContext::checkpoint; prepare_request_tools(ctx) reads it and makes no storage query
Conversation turns wrote a previous_response_id they can never have, and the code kept checks for that impossible case Conversation turns write previous_response_id = NULL; ConversationStore::persist no longer takes it
Storage benchmarks timed setup work and a growing history Each benchmark times one store call at fixed history sizes

Layering after this PR

server handler -> ExecutionContext -> executor -> ConversationHandler / ResponseHandler
                                                   -> ConversationStore / ResponseStore  (typed in, typed out; owns the pool and transactions)
                                                      -> storage/models   (row structs, one SQL function per table operation)
                                                      -> storage/types    (the only place stored JSON is read or written)

Redundancy removed

  • Item rows decoded in four places: Item::as_input, Item::as_output, Item::as_inout and ad-hoc decoding in the handlers. Now one TryFrom<&Item> for InOutItem in storage/types.
  • Three item encoders: the response store, the conversation store and the Items API each built rows their own way. Now one encode.
  • Response metadata decoded in several places: decode_metadata and Response::metadata_as. Now one conversion pair for the column.
  • Conversation metadata parsed twice: once in the HTTP layer and again in storage. Now only in storage/types.
  • Overlapping store entry points: persist / persist_if_version / persist_with_conversation_id, rehydrate / rehydrate_snapshot, create / create_with_metadata_and_items. Now one function per operation.
  • Overlapping handler write paths: execute_turn, execute_turn_with_metadata and commit_tree with a CommittedResponse receipt. Now one persist per handler.
  • Duplicate SQL helpers: get beside get_in_tx, plus get_item_ids, get_snapshot and get_items_by_conversation. Now one SQL function per table operation.
  • The parent response read three times per previous_response_id turn. Now twice: rehydrate returns the response with its history.
  • Two queries for conversation rehydration (the snapshot, then the latest turn's metadata). Now one statement.
  • Turn metadata read again after compaction (response_metadata_at_version, ResponseHandler::get) although rehydration had loaded it. Now read from the checkpoint on RequestContext.
  • Dead branches: an unchecked conversation-persist mode used only by tests, and checks for a previous_response_id a conversation turn can never have. Removed.

Changes

  • storage/types: one conversion pair per column
    • TryFrom<&Item> for InOutItem and TryFrom<&InOutItem> for String for items.data. Each row is parsed once; before, it could be parsed up to four times.
    • TryFrom<&str> for ResponseMetadata and TryFrom<&ResponseMetadata> for String for responses.metadata, replacing decode_metadata and Response::metadata_as.
    • ConversationData.metadata is now typed ConversationMetadata, so the HTTP layer no longer parses JSON.
    • The item kind and code-interpreter origin markers are written and read through serde on ItemKind and CodeInterpreterCallOrigin, instead of string constants and hand-written matching.
  • storage/models: one SQL function per operation
    • response::get works with either a pool or a transaction, replacing get plus get_in_tx.
    • Removed: response::get_item_ids, conversation::create, item::get_items_by_conversation, conversation::get_snapshot and its two row structs.
    • conversation::get_with_items reads the conversation's version, the latest turn's metadata and every item in one portable UNION ALL statement, returned as one ConversationHistory struct. It selects only the header values rehydration needs, and orders items in Rust so the database doesn't sort item data.
    • response::get_conversation_turn is removed, and response::delete_in_tx no longer checks a child's conversation: children are found by previous_response_id, so none is a conversation turn.
  • Stores: one typed function per operation, and no rows returned to callers
    • ConversationStore: create(tenant_id, metadata, items), get, get_or_create, rehydrate (items, version and turn_metadata in one query), and persist(…, expected_version: ConversationVersion, …). The latest turn's metadata is decoded in storage/types (decode_turn_metadata). list_items looks the conversation up only for an empty page or an unknown cursor, instead of on every call.
    • persist always checks the captured version; the unchecked mode existed only for tests.
    • Item CRUD returns public InOutItems.
    • ResponseStore: get, rehydrate (the response and its history), get_items (the response and its public items), persist, delete.
    • Removed: persist_if_version, persist_with_conversation_id (ResponseHandler can never have a conversation id, since conversation and previous_response_id are mutually exclusive), rehydrate_snapshot, create_with_metadata_and_items.
  • Handlers and executor
    • ConversationHandler::rehydrate(ctx) returns the snapshot, and from_conversation makes that one call.
    • ResponseHandler::rehydrate(ctx) returns the parent response and its history together, so from_response and from_session_response no longer call get first. A continuation now makes two storage queries instead of three.
    • Each handler persists through one persist(ctx, output_items, metadata). execute_turn, execute_turn_with_metadata, commit_tree and CommittedResponse are removed. persist.rs builds the metadata in a private prepare_metadata and attaches the multi-agent tree there.
    • RequestContext::checkpoint holds the turn the request continues, using the session's existing ResponseCheckpoint type (response ID, metadata, durability; its history stays empty outside a session): rehydration fills it from a stored response, a conversation's latest turn, or a session's parent. prepare_request_tools(ctx) takes only the context, and ConversationHandler::response_metadata_at_version and ConversationStore::response_metadata_at_version are removed.
    • ResponseHandler::retrieve is renamed get_snapshot.
    • ConversationHandler::create(tenant_id, metadata, items) replaces create() and create_with_metadata_and_items.
    • ResponseHandler::list_input_items reads the response and its items in one store call and takes the snapshot from it, instead of decoding the response metadata twice.
    • ResponseCheckpoint.conversation_id is removed; it was written but never read.
    • engine::create_conversation() is removed; only tests used it, and it created conversations with no tenant.
  • Benchmarks. benches/storage_crud.rs is rewritten. The old rehydrate benchmarks timed a persist call inside the measured section (the setup returned an unawaited future), and the response benchmarks chained every iteration onto a growing history. Each benchmark now times exactly one store call, at 3, 30 and 300 history items. BENCH_DATABASE_URL selects another database.
  • ARCHITECTURE.md describes the new storage layering.

Behaviour changes

  • ConversationStore::persist requires the version captured at rehydration. The executor already passed it, so production behaviour is unchanged. Tests that need concurrent same-conversation writes use create_items, which allocates sequences through the same lock.
  • Conversation rehydration is one statement again, so the captured version is always consistent with the items read.
  • Tool-search state after compaction is restored from the metadata rehydration already loaded, so a compacted continuation makes no extra storage read.
  • Public API: engine::create_conversation is removed; ConversationHandler::create takes the tenant, metadata and items; handler persistence is persist; ResponseHandler::retrieve is get_snapshot; prepare_request_tools takes only the context.

Size

Measured against main. Production code excludes integration tests (tests/, *tests.rs), cassettes, benches and docs; unit tests inside src files count as production code.

Files Added Deleted Net
Production code 35 +988 −1,530 −542
Tests and benches 42 +1,216 −1,128 +88
Cassettes 0 0 0 0
Docs 1 +38 −26 +12
Total 78 +2,242 −2,684 −442

Stack

The cleanup is split into five stacked PRs; each builds on the previous one and passes CI on its own. This is PR1.

PR Branch Carries Leaves for later
1 (this PR) refactor/storage-layer One typed storage layer: one conversion pair per column, one store function per operation, one rehydrate and one persist per handler. Stored data is unchanged.
2 refactor/storage-schema What is stored: typed items.metadata, public_id NOT NULL, the responses.snapshot column, recreate/reject for databases from earlier releases (migration 0008). Conversation turns still use the version check and revision.
3 refactor/append-only-turns Conversation turns never fail with conversation_locked when the conversation changes while they run; conversations.revision is dropped (in 0008); the concurrent-writes cassette records OpenAI and the gateway. A conversation turn's stored history is still the conversation at commit, so its input_items differ from OpenAI's when items change mid-turn (PR5).
4 refactor/public-history History stores public items only; one lowering point for the model; one persist path in persist.rs; input_items match OpenAI for gateway tools. Same as PR3 for mid-turn input_items.
5 refactor/typed-request One ResponseCheckpoint from rehydrate to persist: a turn stores the history it started from (completing PR3's behaviour), fewer reads and statements per turn, typed request metadata. Nothing from this RFC; tenant on RequestContext stays a follow-up.

This is the first PR of a stack:

Benchmarks

cargo bench -p agentic-server-core --bench benches -- '^(response|conversation)_(rehydrate|persist)/' on a SQLite file database, median of 100 samples. main is measured with the same benchmark adapted to its API, timing the reads main performs per turn (get + rehydrate for responses, rehydrate_snapshot + response_metadata_at_version for conversations).

Operation History main This PR Change
Response rehydrate 3 items 350 µs 220 µs −37%
30 items 1.02 ms 713 µs −30%
300 items 6.17 ms 5.55 ms −10%
Conversation rehydrate 3 items 212 µs 150 µs −29%
30 items 845 µs 744 µs −12%
300 items 7.70 ms 6.20 ms −19%
Response persist 3 items 1.85 ms 1.79 ms noise
30 items 4.43 ms 2.32 ms noise
300 items 4.90 ms 3.19 ms noise
Conversation persist 3 items 4.59 ms 9.72 ms noise
30 items 6.22 ms 5.10 ms noise
300 items 7.83 ms 4.80 ms noise

Rehydrate timings are stable (tight confidence intervals). The persist SQL is unchanged in this PR; persist timings are dominated by SQLite write and sync variance, with overlapping confidence intervals between runs, so they show no meaningful difference.

Test Plan

  • cargo clippy --all-targets -- -D warnings
  • cargo test --no-fail-fast (workspace): 2976 passed, 0 failed, 19 ignored (PostgreSQL-only)
  • cargo +1.98.1 check --workspace --all-targets --all-features --locked (MSRV)
  • scripts/tests/agentic-launchers-test.sh, scripts/tests/agentic-cli-e2e-test.py, test_otel_fixtures.py
  • cargo fmt -- --check, Rust file sizes (scripts/check_rust_file_sizes.py), git diff --check
  • PostgreSQL 17 with TEST_POSTGRES_URL and --ignored: postgres_storage_integration (6 passed), postgres_tenant_isolation_test (6 passed) and the schema tests (3 passed)

@franciscojavierarceo
franciscojavierarceo merged commit 7b2feb5 into main Nov 4, 2026
15 checks passed
@maralbahari
maralbahari deleted the refactor/storage-layer branch November 4, 2026 14:37
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.

2 participants