Prevent duplicate initial context when injection races the first turn (#62206)

## Why

A first user turn and a concurrent raw response-item injection can both
observe that the session has no reference context. Both can then append
the initial prompt prefix and persist a full world-state snapshot.

## What changed

Allow context preparation to run concurrently, then serialize publication
of the initial prefix and its checkpoints. If injection publishes first,
the user turn computes its context updates against the published baseline.
If the user turn publishes first, injection appends only the
caller-provided items.

## Testing

Add an integration test that forces the overlap in both preparation
orders. It checks the first request's world-state updates, verifies that
the follow-up request contains the initial instructions and injected
content once each, and checks that history contains one full snapshot.

GitOrigin-RevId: b66f9c6ccc5d42a2be0e852b4d83b78adbc9e5b2
This commit is contained in:
Ruslan Nigmatullin
2026-11-18 06:35:41 +00:00
committed by copyberry
parent a4495dd5c9
commit 86d0e458e3
5 changed files with 231 additions and 45 deletions
+3
View File
@@ -82,6 +82,8 @@ pub(crate) struct Session {
pub(crate) parent_observer_event_tx: OnceLock<Sender<Event>>,
pub(super) agent_status: watch::Sender<AgentStatus>,
pub(super) state: Mutex<SessionState>,
/// Serializes initial prefix publication until its reference context is installed.
pub(super) initial_context_publication: Semaphore,
/// Orders accepted settings commits and their persisted events with compaction checkpoints.
/// Keep this separate from `state` so storage I/O does not block runtime state access.
pub(super) thread_settings_persistence: Semaphore,
@@ -2001,6 +2003,7 @@ impl Session {
parent_observer_event_tx: OnceLock::new(),
agent_status,
state: Mutex::new(state),
initial_context_publication: Semaphore::new(/*permits*/ 1),
thread_settings_persistence: Semaphore::new(/*permits*/ 1),
code_mode_message_tasks: CodeModeMessageTasks::default(),
managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1),