Skip to content

Commit b83bf12

Browse files
authored
Merge pull request #3893 from bobleer/bob/fix-peer-stale-running-session
fix(remote,flow-chat): settle stale running sessions and keep turn settlement under event floods
2 parents 6c00f83 + 5203e1a commit b83bf12

25 files changed

Lines changed: 1061 additions & 111 deletions

File tree

‎src/crates/assembly/core/src/agentic/coordination/coordinator.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10168,6 +10168,44 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
1016810168
self.reconcile_restored_session(session_id, session).await
1016910169
}
1017010170

10171+
/// Load a persisted user session back into this runtime before accepting
10172+
/// user work for it. Idle sessions may be released from memory while a
10173+
/// remote controller keeps showing them; its next message must find the
10174+
/// same session instead of being refused.
10175+
///
10176+
/// The storage binding committed when this process admitted the session
10177+
/// wins. Without one (e.g. after a host restart) the persisted workspace
10178+
/// binding selects storage and takes runtime ownership, exactly as a
10179+
/// mobile remote submission does.
10180+
pub(crate) async fn restore_unloaded_session_for_admission(
10181+
&self,
10182+
session_id: &str,
10183+
) -> OpenBitFunResult<()> {
10184+
if self.session_manager.get_session(session_id).is_some() {
10185+
return Ok(());
10186+
}
10187+
if let Some(storage_path) = self
10188+
.session_manager
10189+
.committed_session_storage_path_for(session_id)
10190+
{
10191+
self.restore_session_from_storage_path(&storage_path, session_id)
10192+
.await?;
10193+
return Ok(());
10194+
}
10195+
let binding = self
10196+
.session_manager
10197+
.resolve_session_workspace_binding(session_id)
10198+
.await
10199+
.ok_or_else(|| {
10200+
OpenBitFunError::NotFound(format!(
10201+
"Session workspace is unavailable on this host: {session_id}"
10202+
))
10203+
})?;
10204+
self.restore_session_for_workspace_binding(&binding, session_id)
10205+
.await?;
10206+
Ok(())
10207+
}
10208+
1017110209
/// Restore a persisted session through its resolved workspace binding.
1017210210
pub async fn restore_session_for_workspace_binding(
1017310211
&self,

‎src/crates/assembly/core/src/agentic/coordination/host_message_queue.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -369,18 +369,34 @@ impl DialogScheduler {
369369
// that may not be restored on this execution host yet, e.g. right after
370370
// a local <-> remote workspace switch. Reads may degrade: the scheduler
371371
// keeps its own receipts, so report that state without failing every
372-
// poll. Mutations keep failing — accepting user work against a session
373-
// this runtime cannot vouch for would silently lose it.
374-
let session_unloaded = self.session_manager.get_session(session).is_none();
372+
// poll and without loading the session.
373+
//
374+
// A mutation is user intent. An idle session may have been released
375+
// from memory while a remote controller still shows it, so load it
376+
// back from persistence first. Only a session this runtime cannot
377+
// restore is refused — accepting user work against a session it cannot
378+
// vouch for would silently lose it.
375379
if !matches!(
376380
request.action,
377381
DialogQueueAction::List | DialogQueueAction::Get { .. }
378-
) && session_unloaded
382+
) && self.session_manager.get_session(session).is_none()
379383
{
380-
return Err(PortError::new(
381-
PortErrorKind::NotFound,
382-
"Session is not loaded on the execution host",
383-
));
384+
if let Err(restore_error) = self
385+
.coordinator
386+
.restore_unloaded_session_for_admission(session)
387+
.await
388+
{
389+
warn!(
390+
"Host queue mutation refused: session could not be restored on the execution host: session_id={}, error={}",
391+
session, restore_error
392+
);
393+
}
394+
if self.session_manager.get_session(session).is_none() {
395+
return Err(PortError::new(
396+
PortErrorKind::NotFound,
397+
"Session is not loaded on the execution host",
398+
));
399+
}
384400
}
385401
let snapshot = self.queue_snapshot(session, None);
386402
if !matches!(request.action, DialogQueueAction::List)

‎src/crates/assembly/core/src/agentic/coordination/host_message_queue_tests.rs‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ async fn host_queue_reads_degrade_for_a_session_not_loaded_on_the_host() {
7979
Some("queued-a")
8080
);
8181

82-
// A mutation still refuses to accept user work for an unloaded session.
82+
// Nothing was persisted here, so the session cannot be restored and a
83+
// mutation still refuses to accept user work for it.
8384
let submit = scheduler
8485
.manage_host_queue(request(
8586
Some(&epoch),
@@ -110,6 +111,65 @@ async fn host_queue_reads_degrade_for_a_session_not_loaded_on_the_host() {
110111
);
111112
}
112113

114+
/// An idle session released from host memory is still the session a remote
115+
/// controller shows. Its next queued message restores it from persistence
116+
/// instead of failing (and failing again on every retry).
117+
#[tokio::test]
118+
async fn host_queue_mutation_restores_an_idle_session_released_from_memory() {
119+
let (scheduler, sessions, _, root) = test_scheduler_with_persistence(true);
120+
let session_id = "host-queue-session";
121+
let workspace = fixture_workspace_dir(root.path().join("released-workspace"));
122+
sessions
123+
.create_session_with_id(
124+
Some(session_id.to_string()),
125+
"Released".to_string(),
126+
"Standard".to_string(),
127+
SessionConfig {
128+
tool_presentation_mode: Default::default(),
129+
workspace_path: Some(workspace.to_string_lossy().into_owned()),
130+
..Default::default()
131+
},
132+
)
133+
.await
134+
.expect("create session");
135+
assert!(sessions
136+
.unload_session_from_memory(session_id)
137+
.await
138+
.expect("unload idle session"));
139+
assert!(sessions.get_session(session_id).is_none());
140+
141+
// Passive reads answer without loading the session.
142+
let list = scheduler
143+
.manage_host_queue(request(None, Action::List))
144+
.await
145+
.unwrap();
146+
assert_eq!(list.active_turn_id, None);
147+
assert!(
148+
sessions.get_session(session_id).is_none(),
149+
"a queue poll must not load the session"
150+
);
151+
152+
// Keep the accepted message parked so the test does not execute a model.
153+
scheduler
154+
.active_turns
155+
.insert(session_id.into(), desktop_active_turn("parking-turn"));
156+
let accepted = scheduler
157+
.manage_host_queue(request(
158+
Some(&list.queue_epoch),
159+
Action::Submit {
160+
message: message("after-release"),
161+
},
162+
))
163+
.await
164+
.expect("a released idle session is restored before admission");
165+
assert!(sessions.get_session(session_id).is_some());
166+
assert_eq!(accepted.queue_epoch, list.queue_epoch);
167+
assert_eq!(
168+
accepted.receipt.as_ref().map(|item| item.turn_id.as_str()),
169+
Some("after-release")
170+
);
171+
}
172+
113173
#[tokio::test]
114174
async fn host_queue_subagent_conversation_admission_precedes_receipts_and_queue_mutation() {
115175
use openbitfun_core_types::{SessionContinuationPolicy, SessionKind};

‎src/crates/assembly/core/src/agentic/session/session_manager.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1248,6 +1248,12 @@ impl SessionManager {
12481248
.map(|binding| binding.path.clone())
12491249
}
12501250

1251+
/// Storage binding committed by an earlier create/restore admission, kept
1252+
/// after the session is unloaded from memory.
1253+
pub(crate) fn committed_session_storage_path_for(&self, session_id: &str) -> Option<PathBuf> {
1254+
Self::committed_session_storage_path(&self.session_storage_path_index, session_id)
1255+
}
1256+
12511257
/// Reuse the storage binding admitted when this session was created/restored.
12521258
/// A workspace path is an execution projection, never a replacement for this
12531259
/// binding. In particular, a later same-path SSH record or runtime-layout

‎src/crates/execution/agent-runtime/src/event_queue.rs‎

Lines changed: 99 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,24 @@ enum LegacyQueuePolicy {
128128
AuthoritativeControl,
129129
}
130130

131+
/// Turn lifecycle facts a consumer cannot reconstruct from later stream data.
132+
/// Losing one leaves a projection running forever, or settled without the
133+
/// durable history fence that makes it reconcile canonical content, until a
134+
/// full reload. Text and tool stream data stay best-effort: a delivered
135+
/// lifecycle fence repairs them. Each turn emits only a handful of these, so
136+
/// admitting them past the data budget stays bounded.
137+
fn is_turn_lifecycle_fact(event: &AgenticEvent) -> bool {
138+
matches!(
139+
event,
140+
AgenticEvent::DialogTurnStarted { .. }
141+
| AgenticEvent::DialogTurnCompleted { .. }
142+
| AgenticEvent::DialogTurnCancelled { .. }
143+
| AgenticEvent::DialogTurnFailed { .. }
144+
| AgenticEvent::SessionStateChanged { .. }
145+
| AgenticEvent::SessionHistoryChanged { .. }
146+
)
147+
}
148+
131149
fn interrupted_control_identity(event: &AgenticEvent) -> Option<(&str, &str, u32)> {
132150
match event {
133151
AgenticEvent::DialogTurnInterrupted {
@@ -309,6 +327,14 @@ impl EventQueue {
309327
priority: Option<EventPriority>,
310328
legacy_policy: LegacyQueuePolicy,
311329
) -> EventBusResult<(String, Option<LegacyDequeueAck>)> {
330+
// A best-effort producer cannot know that the queue is full; never let
331+
// that silently discard a lifecycle fact (see `is_turn_lifecycle_fact`).
332+
let legacy_policy = match legacy_policy {
333+
LegacyQueuePolicy::BestEffort if is_turn_lifecycle_fact(&event) => {
334+
LegacyQueuePolicy::AuthoritativeControl
335+
}
336+
policy => policy,
337+
};
312338
let priority = priority.unwrap_or_else(|| event.default_priority());
313339
let envelope = EventEnvelope::new(event, priority);
314340
let event_id = envelope.id.clone();
@@ -1038,9 +1064,13 @@ mod tests {
10381064
for session_id in ["first", "second"] {
10391065
queue
10401066
.enqueue(
1041-
AgenticEvent::SessionStateChanged {
1067+
AgenticEvent::TextChunk {
10421068
session_id: session_id.to_string(),
1043-
new_state: "idle".to_string(),
1069+
turn_id: "turn".to_string(),
1070+
round_id: "round".to_string(),
1071+
attempt_id: None,
1072+
attempt_index: None,
1073+
text: "data".to_string(),
10441074
},
10451075
None,
10461076
)
@@ -1069,6 +1099,73 @@ mod tests {
10691099
);
10701100
}
10711101

1102+
#[tokio::test]
1103+
async fn full_queue_keeps_turn_lifecycle_facts_of_another_session() {
1104+
let queue = EventQueue::new(EventQueueConfig {
1105+
max_queue_size: 2,
1106+
batch_size: 16,
1107+
});
1108+
let chunk = |session_id: &str, text: &str| AgenticEvent::TextChunk {
1109+
session_id: session_id.to_string(),
1110+
turn_id: "turn".to_string(),
1111+
round_id: "round".to_string(),
1112+
attempt_id: None,
1113+
attempt_index: None,
1114+
text: text.to_string(),
1115+
};
1116+
// Another session floods the data budget.
1117+
for text in ["flood-1", "flood-2"] {
1118+
queue.enqueue(chunk("busy", text), None).await.unwrap();
1119+
}
1120+
// This session's last chunk is best-effort data and may be skipped...
1121+
queue.enqueue(chunk("quiet", "tail"), None).await.unwrap();
1122+
// ...but its settlement and history fence must reach the consumer.
1123+
queue
1124+
.enqueue(
1125+
AgenticEvent::DialogTurnCompleted {
1126+
session_id: "quiet".to_string(),
1127+
turn_id: "turn".to_string(),
1128+
total_rounds: 1,
1129+
total_tools: 0,
1130+
duration_ms: 1,
1131+
partial_recovery_reason: None,
1132+
success: Some(true),
1133+
finish_reason: None,
1134+
has_final_response: Some(true),
1135+
background_delivery: None,
1136+
},
1137+
None,
1138+
)
1139+
.await
1140+
.unwrap();
1141+
queue
1142+
.enqueue(
1143+
AgenticEvent::SessionHistoryChanged {
1144+
session_id: "quiet".to_string(),
1145+
settled_turn_id: Some("turn".to_string()),
1146+
},
1147+
None,
1148+
)
1149+
.await
1150+
.unwrap();
1151+
1152+
let delivered = queue.dequeue_batch(16).await;
1153+
let quiet: Vec<_> = delivered
1154+
.iter()
1155+
.filter(|envelope| envelope.event.session_id() == Some("quiet"))
1156+
.map(|envelope| &envelope.event)
1157+
.collect();
1158+
assert!(quiet
1159+
.iter()
1160+
.any(|event| matches!(event, AgenticEvent::DialogTurnCompleted { .. })));
1161+
assert!(quiet
1162+
.iter()
1163+
.any(|event| matches!(event, AgenticEvent::SessionHistoryChanged { .. })));
1164+
assert!(!quiet
1165+
.iter()
1166+
.any(|event| matches!(event, AgenticEvent::TextChunk { .. })));
1167+
}
1168+
10721169
#[tokio::test]
10731170
async fn default_sized_broadcast_preserves_bursts_above_legacy_1024_limit() {
10741171
let queue = EventQueue::new(EventQueueConfig::default());

‎src/mobile-web/src/services/SessionSynchronizer.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ export class SessionSynchronizer {
6060
private async connect():Promise<void> {
6161
if(this.stopped||this.connecting||this.unsubscribe)return;
6262
this.connecting=true;
63+
// A new subscription may land on a host stream rebuilt with lower revisions;
64+
// its records must supersede what an earlier attempt delivered.
65+
this.replica.rebaseRevisions();
6366
try {
6467
const unsubscribe=await this.sessionMgr.subscribeSessionStream(this.sessionId,{onEvent:event=>{
6568
if(this.stopped)return;

‎src/shared/dialog-queue/HostDialogQueue.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ const newId = (): string => {
7575
const hex = Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
7676
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
7777
};
78+
/** A stable queue Turn ID a caller can hold before submitting. */
79+
export const newQueueTurnId = (): string => newId();
7880
function messageIdentity(message: Omit<QueueMessage, 'turnId'>): string {
7981
// Reopening the composer can allocate fresh image IDs. An ambiguous retry
8082
// must send the stored payload, including its original IDs, unchanged.
@@ -178,18 +180,22 @@ export class HostDialogQueue {
178180
|| (preparedSnapshot && this.view.snapshot?.queueEpoch !== snapshot.queueEpoch)) {
179181
throw new Error('queue_scope_expired: refresh the host queue; do not automatically resend');
180182
}
181-
const identity = messageIdentity(message);
182-
const previous = this.view.pending.find(record => {
183-
if (record.restoreIntent || record.request.action !== 'submit') return false;
184-
const { turnId: _id, ...payload } = record.request.message;
185-
return messageIdentity(payload) === identity;
186-
});
183+
const previous = this.pendingSubmission(message);
187184
if (previous) return this.retryRecord(previous, snapshot);
188185
const turnId = requestedTurnId?.trim() || newId();
189186
return this.transmit({ scope: this.scope, key: JSON.stringify([this.scope, turnId]), draft,
190187
request: { sessionId: this.sessionId, queueEpoch: snapshot.queueEpoch, action: 'submit', message: { ...message, turnId } } });
191188
});
192189
}
190+
/** The unresolved outbox record that submitting this payload would retry instead. */
191+
pendingSubmission(message: Omit<QueueMessage, 'turnId'>): QueueOutboxRecord | undefined {
192+
const identity = messageIdentity(message);
193+
return this.view.pending.find(record => {
194+
if (record.restoreIntent || record.request.action !== 'submit') return false;
195+
const { turnId: _id, ...payload } = record.request.message;
196+
return messageIdentity(payload) === identity;
197+
});
198+
}
193199
act(item: QueueItem, action: 'cancel' | 'promote'): Promise<QueueSnapshot> {
194200
const observed = this.view;
195201
return this.serialize(async () => {

‎src/shared/relay-transport/SessionRecordReplica.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,40 @@ export class SessionRecordReplica {
104104
return turnId;
105105
}
106106

107+
/**
108+
* Prepare for a new subscription of the same session. A host stream rebuilt
109+
* after it expired restarts its revisions and may stamp a fresh snapshot at
110+
* or below revisions held here, so a turn that settled meanwhile would be
111+
* rejected and stay running. Held revisions move below any revision a stream
112+
* issues (always >= 1) while keeping their relative order, so held content
113+
* and tombstones keep their meaning and whatever the new subscription sends
114+
* supersedes them. Ranks are recomputed each time, so repeated rebases never
115+
* lose precision.
116+
*/
117+
rebaseRevisions(): void {
118+
const held = new Set<number>([...this.records.values(), ...this.deleted.values()]);
119+
for (const turn of this.turns.values()) {
120+
held.add(turn.header.revision);
121+
for (const round of turn.rounds.values()) {
122+
held.add(round.header.revision);
123+
for (const item of round.items.values()) held.add(item.revision);
124+
}
125+
}
126+
if (held.size === 0) return;
127+
const ordered = [...held].sort((a, b) => a - b);
128+
const rank = new Map(ordered.map((revision, index) => [revision, (index + 1) / (ordered.length + 1)]));
129+
const rebase = (revision: number): number => rank.get(revision)!;
130+
for (const [id, revision] of this.records) this.records.set(id, rebase(revision));
131+
for (const [id, revision] of this.deleted) this.deleted.set(id, rebase(revision));
132+
for (const turn of this.turns.values()) {
133+
turn.header.revision = rebase(turn.header.revision);
134+
for (const round of turn.rounds.values()) {
135+
round.header.revision = rebase(round.header.revision);
136+
for (const item of round.items.values()) item.revision = rebase(item.revision);
137+
}
138+
}
139+
}
140+
107141
/** The turn's current state; `turn` is null once it was tombstoned or never seen. */
108142
snapshot(turnId: string): SessionRecordChange {
109143
const turn = this.turns.get(turnId);

0 commit comments

Comments
 (0)