Skip to content

refactor: append conversation turns like OpenAI instead of rejecting them (3/5) - #503

Merged
haoshan98 merged 23 commits into
mainfrom
refactor/append-only-turns
Nov 5, 2026
Merged

haoshan98 merged 23 commits into
mainfrom
refactor/append-only-turns

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

A conversation turn no longer fails when its conversation changes while it runs. As on OpenAI, the turn is stored after whatever the conversation holds when it finishes, and its response keeps the history the turn started from. The version check behind 400 conversation_locked, the conversation revision that fed it, and the error plumbing for it are removed; the row lock that gives concurrent writers distinct sequence numbers stays.

The turn's stored history comes from the rehydration checkpoint planned for PR5, brought forward here so that input_items match OpenAI when the conversation changes mid-turn.

Before After
Rehydration captured ConversationVersion { last_sequence, response_id, revision } and carried it on RequestContext Nothing is captured for the check; ConversationVersion and RequestContext::conversation_version are removed
Persist locked the conversation, re-read MAX(seq) and compared the version; a mismatch failed the turn with 400 conversation_locked (an error event on SSE and WebSocket) and stored nothing Persist locks the conversation, appends the turn's items and stores the response
Every item write bumped conversations.revision (create with items, add items, delete an item, persist) No revision; conversations.revision is dropped
Persist re-read every item ID of the conversation and stored them as the turn's history: the conversation at commit, including an item added mid-turn and without an item deleted mid-turn Persist stores the history rows rehydration read (ResponseCheckpoint::history_item_ids) followed by the turn's own items: the history the turn started from, as OpenAI's input_items show
The session kept its own ResponseCheckpoint type One ResponseCheckpoint in storage, from rehydration to persist; the session keeps the history items in it

Schema

A new migration, 0010_drop_conversation_revision.sql. 0009 is on main and stays byte for byte unchanged: a database records each applied migration's checksum, so editing 0009 would stop every database main created from starting.

ALTER TABLE conversations DROP COLUMN revision;

OpenAI behaviour

Verified against gpt-4.1 while a streamed turn B was running on the conversation (recorded in conversations-concurrent-writes-openai.yaml):

  • An item added to the conversation: B completes; the conversation lists the earlier items, the added item, then B's input and output.
  • One of the conversation's items deleted: B completes; the conversation lists the remaining items, then B's items.
  • The conversation's latest response deleted: the delete succeeds, B completes and is stored, the deleted response returns 404, and a following turn still sees the history.

The gateway now does the same (conversations-concurrent-writes-gateway.yaml), including B's input_items: the history B started from, without the item added mid-turn and still with the item deleted mid-turn.

The conflict was added in #162 ("reject stale conversation turns") as optimistic conflict detection, and extended to item writes with revision in #351. It reused OpenAI's conversation_locked code, but OpenAI raises that code only as a short busy lock between overlapping turns, never for item writes or response deletion (see Known limitations).

Redundancy removed

  • A conversation version captured, carried and re-read for every turn: ConversationVersion built at rehydration, carried on RequestContext::conversation_version, and rebuilt under the lock at persist with last_conversation_sequence_in_tx. Removed.
  • The conversation's item IDs read again at persist: ids_for_conversation_in_tx re-read every item of the conversation that rehydration had just read. Persist now extends the checkpoint's rows. Removed.
  • Two checkpoint types: the session's ResponseCheckpoint and the conversation snapshot's latest_response_id and turn_metadata. One storage ResponseCheckpoint replaces them.
  • A revision kept in step on four write paths: bump_revision_in_tx in create (with items), create_items, delete_item and persist, for a column only the version check read. Removed with the column.
  • Error plumbing that existed only for the conflict: StorageError::ConversationConflict and is_conversation_conflict, ExecutorError::ConversationLocked, the client_visible_error unwrapping through Persistence, the conversation_locked telemetry category, and the HTTP, SSE and WebSocket mappings. Removed.

Changes

  • Storage
    • migrations/0010_drop_conversation_revision.sql drops conversations.revision; supervisor-mode verification expects 47 columns (with main's file search tables) and 4 integer columns, and the PostgreSQL integer widening no longer touches revision.
    • models::conversation: Conversation loses revision; bump_revision_in_tx is removed; get_with_items tells its header row apart by the conversation ID. models::item::last_conversation_sequence_in_tx and ids_for_conversation_in_tx are removed.
    • ResponseCheckpoint moves from the session to storage::types::response and carries the continued turn's ID and metadata and its history rows (history_item_ids). ConversationStore::rehydrate returns the conversation's items and that checkpoint; ConversationStore::persist(id, checkpoint, response_id, items, snapshot, metadata) no longer takes a version: it locks the conversation, appends the items, and stores the response with the checkpoint's rows followed by its own. create, create_items and delete_item no longer bump a revision.
  • Executor
    • RequestContext::conversation_version and ExecutorError::ConversationLocked are removed; ConversationHandler::persist maps storage errors directly.
    • The conversation_locked telemetry category is removed.
  • Server: the WebSocket conflict mapping and its test are removed.
  • Tests: the conflict tests now assert OpenAI's behaviour (storage, PostgreSQL two-pool races, HTTP JSON and SSE, WebSocket, WebSocket generate: false): the turn completes and is stored after the competing write, and racing turns both commit with contiguous sequence numbers. merged_migrations_are_unchanged pins the checksums of the migrations on main, and database_migrated_by_main_upgrades_and_keeps_its_data upgrades a database at 0009 to 0010.
  • Cassettes: a concurrent-writes scenario in record_cassette.py and record_conversations_api_cassettes.sh, recorded against OpenAI and the gateway. The recorder now numbers each request in send order (an x-recording-turn header the proxy strips), so a side request that finishes before the streamed turn it overlaps keeps its place. conversations_api_cassette_test.rs checks both recordings, including B's input_items on both providers, and compares them; the existing scenarios are unchanged.
  • Docs: ARCHITECTURE.md; docs/deploying/container.md loses the conversation_locked paragraph and the revision widening statement; observability.md loses the conversation_locked category.

Behaviour changes

  • A conversation turn whose conversation gained or lost items, got another stored turn, or lost its latest response while the turn ran used to fail with 400 conversation_locked and store nothing. It now completes and is stored after the conversation's current items, as on OpenAI.
  • error.type no longer reports conversation_locked.

Known limitations

  • OpenAI also rejects overlapping turns with 400 conversation_locked ("Another process is currently operating on this conversation. Please retry in a few seconds."), depending on timing: a turn started while a non-streamed turn runs is rejected at once, while a turn started during another turn's streaming usually succeeds. The gateway accepts both turns and stores them in commit order; it does not reproduce that busy lock.
  • Turns that overlap on multi-agent state, or compaction during a concurrent turn, are not handled here. These concurrency checks, with their edge cases, belong to PR5; multi-agent parity is left to PR4 and PR5.

Size

Measured against main, which now includes PR2. 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 24 +65 −348 −283
Tests and benches 22 +287 −714 −427
Cassettes 5 +21,075 −17 +21,058
Docs 4 +10 −9 +1
Total 54 +21,435 −1,087 +20,348

Stack

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

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 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 0009). Conversation turns still use the version check and revision.
3 (this PR) refactor/append-only-turns Conversation turns never fail with conversation_locked when the conversation changes while they run; a turn stores the history it started from (one ResponseCheckpoint from rehydration to persist); conversations.revision is dropped (migration 0010); the concurrent-writes cassette records OpenAI and the gateway. Concurrency edge cases with multi-agent state or compaction (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. Multi-agent parity (with PR5).
5 refactor/typed-request The checkpoint extended to response chains and sessions, fewer reads and statements per turn, typed request metadata, concurrency edge cases with multi-agent state and compaction. Nothing from this RFC; tenant on RequestContext stays a follow-up.

Test Plan

  • pre-commit run --all-files, cargo clippy --all-targets -- -D warnings, MSRV (cargo +1.98.1 check --workspace --all-targets --all-features --locked)
  • cargo test --workspace --no-fail-fast: 2958 passed, 0 failed, 18 ignored
  • PostgreSQL 17 with TEST_POSTGRES_URL and --ignored: schema (3), postgres_storage_integration (5), postgres_tenant_isolation_test (6)
  • Launchers, CLI end-to-end, OpenTelemetry fixtures, embedded code interpreter clippy, build and characterization
  • conversations-concurrent-writes recorded against OpenAI (gpt-4.1) and the gateway (vLLM, Qwen/Qwen3.8-27B-FP8), 22 turns each with driver-assigned turn numbers; conversations_api_cassette_test: 11 passed

@maralbahari
maralbahari added this pull request to stack #504 November 3, 2026 12:43
@maralbahari maralbahari changed the title refactor: append conversation turns like OpenAI refactor: append conversation turns like OpenAI instead of rejecting them (3/5) Nov 3, 2026
Base automatically changed from refactor/storage-schema to main November 4, 2026 18:31

@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 two correctness issues involving upgrades and concurrent multi-agent turns.

@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 concurrency cases still need protection before stale turns can safely append.

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

One session checkpoint retention issue remains.

@haoshan98 haoshan98 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the work!

@haoshan98
haoshan98 merged commit beb97e7 into main Nov 5, 2026
17 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