Skip to content

refactor: typed item metadata and a response snapshot column (2/5) - #502

Merged
maralbahari merged 13 commits into
mainfrom
refactor/storage-schema
Nov 4, 2026
Merged

maralbahari merged 13 commits into
mainfrom
refactor/storage-schema

Conversation

@maralbahari

Copy link
Copy Markdown
Collaborator

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

Summary

This PR changes what is stored. Item rows record their kind in a typed metadata column instead of hidden keys inside the item JSON, every item row carries its public ID, and the retrievable response moves out of the continuation metadata into its own column. Databases holding data written by earlier releases are not migrated: the default SQLite database is recreated, and any other database is rejected until its operator resets it.

Before After
The input/output kind and the code-interpreter origin were stored as hidden _agentic_* keys inside items.data items.metadata holds typed ItemMetadata { kind }; items.data is the item's plain serde JSON
items.public_id was nullable and lookups used COALESCE(public_id, reference_id, id); reference_id was unused public_id is NOT NULL on every row, lookups match it directly, and reference_id is dropped
The terminal response was stored inside responses.metadata (response_snapshot), so continuations decoded it and then discarded it responses.snapshot holds it; ResponseMetadata holds only what a continuation needs
GET /v1/responses/{id}/input_items decoded the whole stored response to find its output One row read; the output is counted without decoding the response
Read-time fallbacks for rows written by earlier releases (untyped reasoning, missing kind markers, pre-rename snapshot fields) Removed; startup recreates or rejects a database holding such rows
CodeInterpreterCallOrigin told gateway-executed and upstream calls apart Removed: a code_interpreter_call is the gateway's public projection and is never replayed upstream; the model sees the code_interpreter function call and its output
Lenient ingestion projected reasoning items with untyped fields ReasoningOutput is the only reasoning shape; lenient JSON ingestion drops an item the typed schema rejects and logs its type

Schema (migration 0008_typed_item_metadata.sql)

DROP INDEX idx_items_public_identity;
DROP INDEX idx_items_conversation_reference;
ALTER TABLE items DROP COLUMN reference_id;
ALTER TABLE items DROP COLUMN public_id;
ALTER TABLE items ADD COLUMN public_id TEXT NOT NULL;
CREATE INDEX idx_items_tenant_public_id ON items (tenant_id, public_id);
ALTER TABLE items ADD COLUMN metadata TEXT NOT NULL;
ALTER TABLE responses ADD COLUMN snapshot TEXT;

Migrations 0001 to 0007 are unchanged. 0008 alters the tables instead of rebuilding them, and its NOT NULL columns without defaults are valid because it only ever runs on empty tables (see below). The same file runs on SQLite and PostgreSQL.

Databases written by earlier releases

MINIMUM_SUPPORTED_MIGRATION = 8 (storage/schema/outdated.rs). Before migrating, startup checks whether a database migrated by an earlier release holds any conversations, items or responses:

  • The default SQLite database ($AGENTIC_API_HOME/agentic_api.db, used when no database URL is set) is dropped and recreated at the latest schema in one transaction, and a warning is logged.
  • Any other database (PostgreSQL, or an explicit DATABASE_URL) is rejected with an error telling the operator to reset it. Its data is left untouched. Supervisor mode (AGENTIC_API_SCHEMA_READY) rejects it too.
  • A database an earlier release migrated but never wrote to migrates normally.

ExecutionContext::from_config decides which database is the default one, so the gateway, llm-d and other library callers behave the same.

Redundancy removed

  • The item kind stored twice: as hidden _agentic_item_kind keys inside items.data and implied by how the row was written. Now only the typed items.metadata; items.data is the item's plain JSON.
  • Three identity columns resolved on every lookup: COALESCE(public_id, reference_id, id), with reference_id never written. Now public_id NOT NULL is the one public identity and reference_id is dropped.
  • The response payload carried by every continuation: stored inside responses.metadata, decoded by each continuation and stripped again at several call sites. Now a separate responses.snapshot column that only retrieval reads.
  • Two reasoning shapes: LegacyReasoning (from_legacy_value, opaque_state) beside ReasoningOutput. Now only ReasoningOutput.
  • Read-time fallbacks doing a migration's job on every read: legacy kind markers and pre-rename snapshot fields. Removed; startup recreates or rejects such databases once.
  • CodeInterpreterCallOrigin and its manual PartialEq, tracking a distinction the item type already carries. Removed.
  • input_items decoding the whole stored response only to count its output items. Now counted without decoding.

Changes

  • Migrations and schema
    • migrations/0008_typed_item_metadata.sql as above.
    • storage/schema/outdated.rs: outdated-data detection, the atomic SQLite drop (PRAGMA defer_foreign_keys inside one transaction), and the reset error.
    • Supervisor-mode verification requires items.public_id NOT NULL, items.metadata and responses.snapshot.
  • Storage models and types
    • Item gains public_id: String and metadata; the model no longer generates IDs or timestamps. storage/types::encode builds the row (row ID, public ID, kind) and TryFrom<&Item> for InOutItem reads it back by kind.
    • Response gains snapshot; TryFrom<&ResponsePayload> for String (which strips request-scoped MCP credentials) and TryFrom<&str> for ResponsePayload convert it, and snapshot_output_count counts its outputs without decoding them.
    • ResponseMetadata.response_snapshot is removed.
  • Stores
    • ResponseStore::persist(…, snapshot: Option<&ResponsePayload>, metadata) and ConversationStore::persist(…, snapshot, metadata) write the snapshot column.
    • ResponseStore::get_snapshot reads it, and get_input_items returns the history without the response's own output in one row read (None when the response has no snapshot).
  • Executor
    • ResponseHandler::get_snapshot and list_input_items read the snapshot column. Continuations no longer have to strip a snapshot from the parent's metadata or from session checkpoints.
    • persist.rs passes the snapshot to the handlers' persist beside the turn metadata.
  • Types and ingestion
    • CodeInterpreterCallOrigin and its manual PartialEq are removed; OutputItem::to_input_item never replays a code_interpreter_call.
    • types/io/reasoning/legacy.rs (LegacyReasoning, from_legacy_value, opaque_state) is removed. Lenient JSON ingestion logs the type of an output item it drops; streamed completions keep the item as it was opened.
  • Docs
    • ARCHITECTURE.md: the storage section is updated, with a new "Schema, migrations, and where data goes" subsection: one connection layer with portable model SQL, migration rules, incompatible-data handling, and when data gets its own column instead of going into metadata.
    • .agents/skills/storage-schema-change/SKILL.md, referenced from AGENTS.md and the engineering skill, is a checklist for schema and persistence changes.
    • docs/deploying/container.md and kubernetes.md describe how databases from earlier releases are handled and how to upgrade.

Behaviour changes

  • Upgrading. A database holding data from an earlier release is recreated (default SQLite, contents discarded) or rejected (PostgreSQL or an explicit DATABASE_URL). Stop every older replica first, then point DATABASE_URL at an empty database or drop the persistence tables; back up first if the data must be kept. See the deployment docs.
  • Stored code_interpreter_call items are no longer replayed to the model, including any an upstream returned natively. The gateway's own calls were already replayed as their code_interpreter function call and output.
  • A reasoning item that doesn't match the typed schema is dropped by lenient JSON ingestion (with a warning naming its type) and kept as it was opened in a stream; strict ingestion still rejects it.
  • GET /v1/responses/{id} and input_items return the same payloads as before.

Known limitations

  • Outdated data is detected from the SQLx migration history. A schema altered by hand without recording the migration is judged by that history.
  • The first stored occurrence of a public ID keeps that ID as its row ID, so a public ID already stored by one tenant can't be stored as a new item by another. This predates this PR.

Size

Measured against PR1. 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 31 +784 −971 −187
Tests and benches 22 +153 −630 −477
Cassettes 0 0 0 0
Docs 6 +159 −55 +104
Total 59 +1,096 −1,656 −560

Stack

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

PR Branch Carries Leaves for later
1 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 (this PR) 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.

Benchmarks

cargo bench -p agentic-server-core --bench benches -- '^(response|conversation)_(rehydrate|persist)/' on a SQLite file database, median of 100 samples; refactor/storage-layer saved as the criterion baseline and this PR compared against it.

Operation History Previous PR This PR Change
Response rehydrate 3 items 220 µs 227 µs no change
30 items 713 µs 748 µs no change
300 items 5.55 ms 4.94 ms −11%
Conversation rehydrate 3 items 150 µs 151 µs +5%
30 items 744 µs 736 µs −2%
300 items 6.20 ms 6.45 ms +4%
Response persist 3 / 30 / 300 items 1.79 / 2.32 / 3.19 ms 1.69 / 1.85 / 2.21 ms noise
Conversation persist 3 / 30 / 300 items 9.72 / 5.10 / 4.80 ms 3.58 / 4.85 / 9.41 ms noise

Response rehydration of long histories is faster because item rows decode as plain serde. Conversation rehydration moves within a few percent, from parsing the metadata column per item. Persist timings are dominated by SQLite write and sync variance, with overlapping confidence intervals.

Test Plan

  • cargo clippy --all-targets -- -D warnings
  • cargo test --no-fail-fast (workspace): 2965 passed, 0 failed, 18 ignored (PostgreSQL-only)
  • cargo +1.98.1 check --workspace --all-targets --all-features --locked (MSRV)
  • cargo fmt -- --check, Rust file sizes (scripts/check_rust_file_sizes.py), git diff --check
  • PostgreSQL 17 with TEST_POSTGRES_URL and --ignored: schema tests (3 passed), postgres_storage_integration (5 passed), postgres_tenant_isolation_test (6 passed)
  • New tests: outdated default database recreated (with items, responses and conversation links), outdated configured database rejected in embedded and supervisor mode, empty earlier database migrates, snapshot round trip with MCP credentials stripped, untyped reasoning rejected by every ingestion path
  • responses_api_test (29 passed) and conversations_api_cassette_test (10 passed) replay the committed recordings
  • Gateway lifecycle re-recorded through release builds of main, the previous PR and this PR against vLLM (Qwen/Qwen3.8-27B-FP8): all 11 Responses and 9 Conversations gateway scenarios. This PR matches main and the previous PR on every turn (method, path, status, error type/code/param, output and input item types and statuses, page shape), apart from model and concurrency variance in two tool-items turns. The re-recordings are not committed.

@maralbahari
maralbahari added this pull request to stack #504 November 3, 2026 12:43
@maralbahari
maralbahari marked this pull request as ready for review November 4, 2026 14:15

@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.

Found one data-safety issue in the outdated-schema reset gate.

@maralbahari
maralbahari marked this pull request as draft November 4, 2026 14:20
Signed-off-by: maral <[email protected]>
Base automatically changed from refactor/storage-layer to main November 4, 2026 14:37
@maralbahari
maralbahari marked this pull request as ready for review November 4, 2026 16:49
@maralbahari
maralbahari merged commit cb0de59 into main Nov 4, 2026
25 of 27 checks passed
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