Skip to content

feat: add OpenAI-compatible Conversations API - #351

Merged
franciscojavierarceo merged 7 commits into
vllm-project:mainfrom
avinashsingh77:complete_conv_api
Sep 23, 2026
Merged

franciscojavierarceo merged 7 commits into
vllm-project:mainfrom
avinashsingh77:complete_conv_api

Conversation

@avinashsingh77

@avinashsingh77 avinashsingh77 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add conversation and item CRUD endpoints, including metadata updates, batch item creation, retrieval, deletion, and cursor pagination. Requests use an items array; returned items expose their typed fields directly; listing supports ascending and descending order; deleting an item returns its conversation.

Conversation ownership governs item access, including items written by Responses persistence. Item creation shares the existing conversation lock and sequence allocator. Deletion detaches items so stored response history survives, and a persisted conversation revision rejects turns prepared before an item mutation. Conversation creation and its initial items commit atomically.

Add migration 0005_conversation_revision.sql, update supervisor-managed PostgreSQL upgrade instructions, and run PostgreSQL conversation CRUD and tenant-isolation tests in CI.

Authentication integration remains a follow-up: HTTP handlers currently use default_tenant. Storage operations enforce the supplied tenant; these endpoints do not yet derive it from the authenticated principal.

Fixes: #155

Test Plan

  • Conversation HTTP tests cover batch and flattened wire formats, ordering, cursor pagination, stored Responses item visibility, deletion responses, tenant isolation, and validation.
  • Regression tests cover output-item preservation, concurrent SQLite appends, deletion conflict detection, and retained response history.
  • PostgreSQL coverage checks concurrent appends, tenant isolation, item visibility, and retained response history; the PostgreSQL CI job now runs this suite.
  • Local validation: full workspace Rust tests, Clippy with warnings denied, formatting, and all pre-commit hooks. Local Rust commands use the existing agentic-server/vendored-openssl feature because this host lacks system OpenSSL headers.

@maralbahari maralbahari 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 working on the Conversations API support! I’ve left inline comments covering the application/storage boundary, OpenAI compatibility, and cassette coverage. Please take a look and address those before we move forward. Some revisit feedback from #166, which I’ve linked for context. Happy to clarify anything that’s unclear.

/// Request to create a new item in a conversation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct CreateItemRequest {

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.

The item API contract does not match OpenAI. CreateItemRequest requires {"item": {...}}, and the endpoint returns a single ItemResponse. OpenAI accepts {"items": [...]} and returns a list of typed conversation items. Returned items expose their fields directly, without an additional item wrapper. See the OpenAI reference.

A valid OpenAI request therefore fails deserialization here. The new tests assert the same incompatible structure, so passing them does not establish compatibility.

As requested in my review of #166, please record these operations against OpenAI and the gateway, then use those recordings to define the request/response types and compatibility assertions. Preserve a canonical item ID across creation, listing, retrieval, and Responses output.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated as per OpenAI API contract.

/// Returns `DbResult::Err` if the database query fails.
pub async fn get_item_by_tenant(pool: &DbPool, tenant_id: &str, item_id: &str) -> DbResult<Option<Item>> {
sqlx::query_as::<_, Item>("SELECT * FROM items WHERE id = $1 AND tenant_id = $2")
.bind(item_id)

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.

The new item operations and existing Responses persistence do not agree on tenant ownership. These queries require tenant_id, but ConversationStore::persist_impl() still calls item::create_in_tx(), which inserts items without it.

Consequently, creating a conversation and completing a /v1/responses turn leaves persisted items that the new listing endpoint cannot see. Retrieval and deletion also exclude those rows.

Please extend the existing persistence APIs and update their callers instead of introducing a separate creation path with different tenant semantics. Add an integration test that creates a conversation, executes a response, then lists and retrieves the persisted items through the conversation endpoints.

The hard-coded "default_tenant" must also be resolved consistently across these paths. Storage-level tenant tests alone do not verify tenant isolation at the HTTP boundary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The tenant_id now flows consistently from HTTP extraction → ExecuteRequest → rehydrate → RequestContext → execute_turn → persist → storage, ensuring items created via /v1/responses will be visible to the onversations items API endpoints.


/// Returns a reference to the underlying conversation store.
#[must_use]
pub fn store(&self) -> &ConversationStore {

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.

This repeats the architectural feedback I left on #166. Adding store() here and making ConversationStore::pool() public lets the HTTP handlers reach through ExecutionContext and bypass the application boundary.

Please preserve this layering:

HTTP handler
    → typed operations on exec_ctx.conv_handler
ConversationHandler
    → ConversationStore
Storage
    → database models and queries

The new entrypoints need corresponding typed operations on ConversationHandler, following the existing Responses and conversation pattern. Request validation, item identity, storage conversion, and StorageError → ExecutorError translation should happen behind that boundary. Axum should extract the request, call the operation, and serialize its typed result.

Currently, conversation_items.rs imports database models, accesses the raw pool, generates item IDs, serializes storage payloads, and handles database failures directly. conversations.rs also deserializes stored metadata.

Please move these responsibilities behind ConversationHandler and remove the new public store/pool accessors. Referencing exec_ctx in the call chain does not preserve the boundary when the handler immediately reaches through it to storage.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

All the layering violations have been fixed.

@maralbahari maralbahari Sep 23, 2026 •

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.

@avinashsingh77 unfortunately I still see the ConversationStore being exposed and dont see the preserved layers either and PR has been merged. Perhaps could help to address this in another PR along with the cassettes recording in #351 (comment) to ensure correct compatibility with OpenAI conversation items contract?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sorry @maralbahari I am yet to push latest changes.
I am not sure how this PR was merged.
I will file a follow up PR to address all 4 review comments and cassettes recording .

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.

@avinashsingh77 no worries. Thanks for the help. once open the PR let me know

@@ -0,0 +1,211 @@
use std::sync::Arc;

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.

This PR adds local CRUD tests, but no OpenAI reference recordings, matching gateway recordings, or replay assertions for the new routes.

Please extend the recorder with scenarios covering conversation create/retrieve/update/delete and item create/list/retrieve/delete. Record each scenario against OpenAI and against the gateway with its database and vLLM running. Cover supported item formats, generated-ID reuse, pagination, include, invalid requests, and error responses.

The recordings also need to cover the stateful behavior described in my earlier comment:

  • Manually added items affect subsequent model context.
  • Deleting an item affects continuation through the conversation ID versus a previously created previous_response_id.
  • Branching from responses created before and after manually adding an item preserves the recorded history behavior.

Use equivalent requests and prompts, normalize dynamic IDs and timestamps, and compare status codes, response shapes, ordering, pagination, ID relationships, and history visibility. For streaming Responses calls, also compare the SSE lifecycle.

The existing conv recorder mode does not exercise these management routes. Please add repeatable recording scripts and Rust integration assertions using the recorded OpenAI behavior as the reference. Captured cassette YAML must be generated by the recorder, not hand-authored.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I believe you are are talking about building a comprehensive testing infrastructure addition that goes significantly beyond the current PR scope. Here's what would need to be built:

Required Work as per my understanding:

  1. New Specialized Recorder:

The existing record_cassette.py only handles /v1/responses and /v1/messages. The Conversations API requires a new recorder that:

  • Makes HTTP calls to multiple endpoints (conversations, items)
  • Chains responses correctly (conversation IDs, item IDs)
  • Interleaves CRUD operations with inference calls
  • Normalizes dynamic IDs/timestamps for comparison
  1. Recording Scenarios (~10-15 cassettes)

Basic CRUD (8 cassettes):

  • Conversation create/retrieve/update/delete × streaming/non-streaming
  • Items create/list/retrieve/delete × streaming/non-streaming

Stateful Behavior (6+ cassettes):

  • Manual items → model context (the critical test)
  • Item deletion → continuation divergence
  • Branching before/after manual item addition
  1. Replay Tests

Integration tests that:

  • Load OpenAI reference cassettes
  • Load gateway cassettes
  • Compare status codes, shapes, ordering, pagination, ID relationships
  • Assert history visibility matches
  1. Recording Scripts

Similar to record_web_search_cassettes.sh, record_custom_tool_cassettes.sh, etc

@maralbahari Should I add basic integration tests now (using real DB but no cassettes), defer cassette infrastructure to a follow-up PR.

) -> DbResult<Vec<Item>> {
if let Some(after_id) = after {
sqlx::query_as::<_, Item>(
"SELECT * FROM items \

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.

Moving the limit into SQL addresses part of my earlier feedback, but the cursor predicate does not match the ordering: after filters by id > cursor, while results are ordered by seq, id. IDs are generated before insertion, so their order can differ from insertion order and cause pagination to skip or repeat items.

Please resolve the cursor within the same conversation and tenant, then paginate using the actual ordering keys.

ListItemsQuery also omits order and include. The query always returns ascending order, whereas OpenAI defaults to descending order. Please implement the recorded behavior and explicitly reject unsupported include values instead of silently ignoring them. See the OpenAI list reference.

Finally, the HTTP handler uses filter_map with db_item.as_inout(), silently dropping malformed stored items after calculating has_more. This can return an incomplete or empty page with misleading pagination metadata. Please perform a fallible typed conversion behind the application boundary and propagate conversion errors.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Tenant isolation remains hard-coded to default_tenant, and Responses integration is incomplete.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity · 4 Medium severity

Open (6)
What changed in this PR

Adds OpenAI-compatible conversation and item CRUD APIs with tenant-scoped storage, pagination, schemas, and integration tests. Approval is blocked by unresolved tenant isolation and incomplete Responses integration.

Changes:

  • Added conversation and item HTTP handlers and routes.
  • Added persistence, metadata, pagination, and deletion support.
  • Added SQLite/PostgreSQL tenant-isolation tests and OpenAPI definitions.
File Summary
scripts/​setup-postgres-test.sh PostgreSQL test setup
crates/​agentic-server/​tests/​conversations_test.rs Conversation API integration tests
crates/​agentic-server/​tests/​common/​mod.rs Test helper annotations
crates/​agentic-server/​src/​openapi.rs OpenAPI registrations
crates/​agentic-server/​src/​handler/​mod.rs Handler exports
crates/​agentic-server/​src/​handler/​http/​mod.rs HTTP module exports
crates/​agentic-server/​src/​handler/​http/​conversations.rs Conversation CRUD handlers
crates/​agentic-server/​src/​handler/​http/​conversation_items.rs Item handlers and pagination
crates/​agentic-server/​src/​handler/​common.rs JSON and error helpers
crates/​agentic-server/​src/​app.rs Conversation route registration
crates/​agentic-server-core/​tests/​tenant_isolation_test.rs SQLite tenant-isolation tests
crates/​agentic-server-core/​tests/​postgres_tenant_isolation_test.rs PostgreSQL tenant-isolation tests
crates/​agentic-server-core/​src/​types/​mod.rs Type exports
crates/​agentic-server-core/​src/​types/​conversations.rs Conversation API schemas
crates/​agentic-server-core/​src/​storage/​types/​conversation.rs Tenant conversation data
crates/​agentic-server-core/​src/​storage/​models/​item.rs Tenant item persistence and queries
crates/​agentic-server-core/​src/​storage/​models/​conversation.rs Tenant conversation queries
crates/​agentic-server-core/​src/​storage/​conversation.rs Conversation store operations
crates/​agentic-server-core/​src/​executor/​modes/​conversation.rs Store access for handlers

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +17 to +21
fn extract_tenant_id(_req: &Request) -> Result<String, Response> {
// For now, return a placeholder until we wire up authentication
// In production, this would extract from the AuthenticatedPrincipal extension
// and return Err(response) for authentication failures
Ok("default_tenant".to_string())
Comment on lines +17 to +21
fn extract_tenant_id(_req: &Request) -> Result<String, Response> {
// For now, return a placeholder until we wire up authentication
// In production, this would extract from the AuthenticatedPrincipal extension
// and return Err(response) for authentication failures
Ok("default_tenant".to_string())
Comment on lines +257 to +273
let row =
conversation::create_with_metadata(pool, &conversation_id, tenant_id, metadata_str.as_deref()).await?;

// If initial_items provided, persist them
if !initial_items.is_empty() {
let items: Vec<(String, String)> = initial_items
.into_iter()
.map(|item| {
let item_id = uuid7_str("item_");
let data = String::try_from(&item)?;
Ok((item_id, data))
})
.collect::<Result<_, StorageError>>()?;

if let Some(tid) = tenant_id {
item::create_items_for_conversation(pool, tid, &conversation_id, items).await?;
}
Comment on lines +38 to +40

/// Tenant identifier for multi-tenancy isolation.
pub tenant_id: Option<String>,
Comment on lines +94 to +103
/// A conversation item (input or output).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub enum ConversationItem {
/// Input item (message, tool call, etc.).
Input(InputItem),
/// Output item (message, tool result, etc.).
Output(OutputItem),
}
};
let protected_routes = Router::new()
.route("/v1/conversations", post(conversations))
.route("/v1/conversations", post(create_conversation))
@franciscojavierarceo
franciscojavierarceo merged commit fb94457 into vllm-project:main Sep 23, 2026
19 checks passed
maralbahari added a commit that referenced this pull request Sep 25, 2026
…#370)

## Summary

1. Fixed architectural layering and pagination issues from review
comments from #351
2. Added cassette testing infrastructure (shell script, Python recorder,
Rust replay tests)
3. Documented cassette recording requirements.

**Note:** Actual cassette recording requires OpenAI API access or a
running gateway instance, which were not available to me at the time of
development.
 The infrastructure is complete and ready for recording

---------

Signed-off-by: Avinash Singh <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: Avinash Singh  <[email protected]>
Co-authored-by: Claude Sonnet 4.5 <[email protected]>
Co-authored-by: maral <[email protected]>
haoshan98 added a commit that referenced this pull request Sep 30, 2026
## Summary

Several user-facing docs had fallen behind `main` or contradicted each
other and the code. This PR brings them in line with what has shipped.
It changes documentation only.


**Corrected claims**
- README listed the Messages API as "🚧 Planned" while another README
section documents `/v1/messages`. It is now listed as shipped; only
stateful Messages stays planned.
- README and `docs/index.md` advertised "Background execution" and
gateway-executed file search. Neither exists yet: background mode is
#357, and `file_search` declarations parse but are dropped before
inference (`tool/normalize.rs`). Both claims are removed.
- `docs/api/index.md` quoted fixed WebSocket and executor limits (256
KiB SSE lines, 1 MiB events and response budget). These now come from
the configurable `[responses]` settings, which default to 16 MiB and 8
MiB.
- `docs/api/index.md` listed only some of the conditions that route a
Responses request through the executor. The list now also includes
non-function tools, `multi_agent.enabled`, and tool-search state,
matching `handler/http/responses.rs`.
- CHANGELOG listed Tavily under 0.8.0, but it merged on Sep 28, after
the Sep 19 release. The two Tavily entries move to `[Unreleased]`.

**Newly documented features**
- README: a multi-agent Responses section with an example and the
gateway's limits (`store: true`, HTTP/SSE only, default of 3 concurrent
subagents, no `max_tool_calls` or reasoning summaries). Also new rows in
the API table for `/v1/responses/compact`, the full Conversations
routes, `/v1/messages` with `/v1/messages/count_tokens`, and
Swagger/OpenAPI (`ENABLE_OPENAPI_DOCS`). The features list, diagram, and
tool ownership table now include MCP, the code interpreter, Claude Code,
compaction, and OpenTelemetry.
- `docs/api/index.md`: new sections for `GET
/v1/responses/{response_id}`, multi-agent, Conversations, and Messages.
- CHANGELOG `[Unreleased]` was empty. It now has entries for #345, #347,
#349, #351/#370, #354, #368, #369, #372/#373, #380, and #387.

**Roadmap**
- ROADMAP.md marks multi-agent HTTP execution as shipped, with WebSocket
injection (#300) and stateless requests (#393) still open. It adds a
status note for Messages, a code interpreter entry, and a file search
item linking #34 and #356.
- README "Roadmap at a Glance" checks off Messages and Conversations and
adds unchecked items for multi-agent, file search, and stateful
Messages.

**Smaller fixes**
- The repository layout in README and AGENTS.md now lists
`agentic-llm-d`, `agentic-cli-docs`, and `python/agentic_api/`.
- ARCHITECTURE.md's list of multi-agent rejections now includes
`max_tool_calls`, matching `executor/rehydrate.rs`.
- `mkdocs.yaml` adds the existing but unlinked `design/shell-tool.md` to
the nav.

**Not changed:** the README's "Rust 1.85+" badge is wrong (1.85 cannot
build the lockfile, see #377), but #379 already updates it to 1.88 along
with `rust-version` and a CI check, so this PR leaves it alone to avoid
a conflict.

Signed-off-by: haoshan98 <[email protected]>
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]>
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.

Conversations API: match OpenAI for unknown conversation ids (currently created implicitly)

4 participants