Repository navigation
fix: reject stale conversation turns - #162
Merged
Merged
Conversation
franciscojavierarceo
requested review from
bbrowning,
jiahuei,
leseb,
maralbahari,
noobHappylife,
qandrew and
tjtanaa
as code owners
August 2, 2026 14:36
Collaborator
|
@franciscojavierarceo can retarget to main? |
franciscojavierarceo
changed the base branch from
codex/issue-102-postgres-pool-config
to
main
August 3, 2026 14:13
franciscojavierarceo
force-pushed
the
codex/issue-102-conversation-version-check
branch
from
August 3, 2026 14:13
88da78c to
1aaff97
Compare
maralbahari
reviewed
Aug 3, 2026
| .await | ||
| .map_err(ExecutorError::Storage) | ||
| .map_err(|error| match error { | ||
| StorageError::ConversationConflict { .. } => ExecutorError::ConversationLocked, |
Collaborator
There was a problem hiding this comment.
converts StorageError::ConversationConflict { conversation_id } into the unit-like ExecutorError::ConversationLocked. Consequently, persist.rs (line 30) logs only a generic message, and Error::source() cannot reach the original typed error. This makes concurrent-write incidents impossible to correlate with a conversation. Preserve StorageError as a #[source] while keeping the client-safe response.
Capture the persisted conversation version during rehydration and verify it under the existing storage lock before appending. Return conversation_locked consistently across HTTP, SSE, and WebSocket when the history changes, with SQLite and PostgreSQL race coverage. Signed-off-by: Francisco Javier Arceo <[email protected]>
franciscojavierarceo
force-pushed
the
codex/issue-102-conversation-version-check
branch
from
August 3, 2026 16:07
1aaff97 to
228de23
Compare
maralbahari
approved these changes
Aug 4, 2026
5 tasks done
haoshan98
pushed a commit
that referenced
this pull request
Nov 5, 2026
…them (3/5) (#503) 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. ```sql 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 - [x] `pre-commit run --all-files`, `cargo clippy --all-targets -- -D warnings`, MSRV (`cargo +1.98.1 check --workspace --all-targets --all-features --locked`) - [x] `cargo test --workspace --no-fail-fast`: 2958 passed, 0 failed, 18 ignored - [x] PostgreSQL 17 with `TEST_POSTGRES_URL` and `--ignored`: schema (3), `postgres_storage_integration` (5), `postgres_tenant_isolation_test` (6) - [x] Launchers, CLI end-to-end, OpenTelemetry fixtures, embedded code interpreter clippy, build and characterization - [x] `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 --------- Signed-off-by: maral <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
conversation_lockederror over HTTP, SSE, and WebSocket, includinggenerate: falseprevious_response_idfork behavior and the existing unchecked storage APIThis builds on the PostgreSQL persistence foundation merged in #142.
This implements optimistic conflict detection at persistence time. A pre-inference distributed lease or queue that also suppresses external tool side effects remains separate policy work.
Test Plan
cargo fmt --all -- --checkcargo clippy --all-targets -- -D warningscargo testpre-commit run --all-filespostgres_concurrent_conversation_writes_have_contiguous_sequencesagainst PostgreSQL 17postgres_optimistic_conversation_conflictagainst PostgreSQL 17postgres_lock_wait_is_bounded_without_blocking_other_conversationsagainst PostgreSQL 17