Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions src/crates/assembly/core/src/agentic/core/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,28 @@ pub struct ModelExecutionMetadata {
pub effective_model_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub routing: Option<openbitfun_events::agentic::ModelRoutingDecision>,
/// Accepted-attempt timing of the model round that produced this message.
/// Durable Turn rounds are rebuilt from the generation journal, so the
/// Runtime keeps these facts here instead of relying on a client checkpoint
/// of `ModelRoundCompleted` having landed before the Turn completes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timing: Option<ModelRoundTimingMetadata>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelRoundTimingMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub first_chunk_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub first_visible_output_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stream_duration_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttft_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attempt_count: Option<u32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -836,18 +858,34 @@ mod tests {
latency_ms: 10,
fallback_reason: None,
}),
timing: Some(super::ModelRoundTimingMetadata {
duration_ms: Some(1200),
ttft_ms: Some(300),
attempt_count: Some(1),
..Default::default()
}),
});
let value = serde_json::to_value(&message).unwrap();
let restored: Message = serde_json::from_value(value.clone()).unwrap();
assert_eq!(
restored.metadata.ptc_loaded_deferred_tool_specs,
message.metadata.ptc_loaded_deferred_tool_specs
);
let execution = restored.metadata.model_execution.unwrap();
assert_eq!(execution.model_config_id, "economy");
assert_eq!(
restored.metadata.model_execution.unwrap().model_config_id,
"economy"
execution.timing.and_then(|timing| timing.ttft_ms),
Some(300)
);
let mut legacy = value;
// Journals written before round timing existed still deserialize.
let mut untimed = legacy.clone();
untimed["metadata"]["model_execution"]
.as_object_mut()
.unwrap()
.remove("timing");
let untimed: Message = serde_json::from_value(untimed).unwrap();
assert!(untimed.metadata.model_execution.unwrap().timing.is_none());
let metadata = legacy["metadata"].as_object_mut().unwrap();
metadata.remove("ptc_loaded_deferred_tool_specs");
metadata.remove("model_execution");
Expand Down
24 changes: 18 additions & 6 deletions src/crates/assembly/core/src/agentic/execution/round_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1851,21 +1851,31 @@ impl RoundExecutor {
!stream_result.tool_calls.is_empty()
);

// The same facts ride on the assistant message so the durable Turn
// round keeps them even when no client checkpointed this event.
let round_timing = crate::agentic::core::message::ModelRoundTimingMetadata {
duration_ms: Some(elapsed_ms_u64(round_started_at)),
first_chunk_ms: stream_result.first_chunk_ms,
first_visible_output_ms: stream_result.first_visible_output_ms,
stream_duration_ms: Some(stream_processing_ms),
ttft_ms,
attempt_count: Some(lifecycle.attempts_started()),
};
self.emit_event(
AgenticEvent::ModelRoundCompleted {
session_id: context.session_id.clone(),
turn_id: context.dialog_turn_id.clone(),
round_id: round_id.clone(),
has_tool_calls: !stream_result.tool_calls.is_empty(),
duration_ms: Some(elapsed_ms_u64(round_started_at)),
duration_ms: round_timing.duration_ms,
provider_id: None,
model_config_id: context.model_config_id.clone(),
effective_model_name: context.effective_model_name.clone(),
first_chunk_ms: stream_result.first_chunk_ms,
first_visible_output_ms: stream_result.first_visible_output_ms,
stream_duration_ms: Some(stream_processing_ms),
ttft_ms,
attempt_count: Some(lifecycle.attempts_started()),
first_chunk_ms: round_timing.first_chunk_ms,
first_visible_output_ms: round_timing.first_visible_output_ms,
stream_duration_ms: round_timing.stream_duration_ms,
ttft_ms: round_timing.ttft_ms,
attempt_count: round_timing.attempt_count,
failure_category: None,
token_details: stream_result
.usage
Expand Down Expand Up @@ -1922,6 +1932,7 @@ impl RoundExecutor {
model_config_id: context.model_config_id.clone(),
effective_model_name: context.effective_model_name.clone(),
routing: lifecycle.routing.clone(),
timing: Some(round_timing),
});

debug!("Returning RoundResult: has_more_rounds=false");
Expand Down Expand Up @@ -1998,6 +2009,7 @@ impl RoundExecutor {
model_config_id: context.model_config_id.clone(),
effective_model_name: context.effective_model_name.clone(),
routing: lifecycle.routing.clone(),
timing: Some(round_timing),
});

// Publish the semantic assistant response before tool execution so
Expand Down
114 changes: 102 additions & 12 deletions src/crates/assembly/core/src/agentic/session/session_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8140,6 +8140,14 @@ impl SessionManager {
|| !tool_items.is_empty()
|| !thinking_items.is_empty()
{
// Messages written before the Runtime recorded round
// timing leave these unknown rather than claiming 0 ms.
let timing = msg
.metadata
.model_execution
.as_ref()
.and_then(|facts| facts.timing)
.unwrap_or_default();
rounds.push(ModelRoundData {
id: round_id,
turn_id: turn_id.to_string(),
Expand All @@ -8151,7 +8159,7 @@ impl SessionManager {
thinking_items,
start_time: timestamp,
end_time: Some(timestamp),
duration_ms: Some(0),
duration_ms: timing.duration_ms,
provider_id: None,
model_config_id: msg
.metadata
Expand All @@ -8168,11 +8176,11 @@ impl SessionManager {
.model_execution
.as_ref()
.and_then(|facts| facts.routing.clone()),
first_chunk_ms: None,
first_visible_output_ms: None,
stream_duration_ms: None,
ttft_ms: None,
attempt_count: None,
first_chunk_ms: timing.first_chunk_ms,
first_visible_output_ms: timing.first_visible_output_ms,
stream_duration_ms: timing.stream_duration_ms,
ttft_ms: timing.ttft_ms,
attempt_count: timing.attempt_count,
attempt_diagnostics: vec![],
failure_category: None,
token_details: None,
Expand Down Expand Up @@ -8814,7 +8822,15 @@ impl SessionManager {
round.timestamp = existing.timestamp;
round.start_time = existing.start_time;
round.end_time = existing.end_time.or(round.end_time);
round.duration_ms = existing.duration_ms.or(round.duration_ms);
// Round timing is a Runtime fact carried by the generation
// journal. The client checkpoint only mirrors
// `ModelRoundCompleted`, and for the last round it routinely
// loses the race with Turn completion, so it is a fallback for
// journals written before the Runtime recorded timing. Older
// completion writers persisted `0` for unknown durations.
round.duration_ms = round
.duration_ms
.or(existing.duration_ms.filter(|duration_ms| *duration_ms > 0));
round.provider_id = existing.provider_id.clone();
round.model_config_id = round
.model_config_id
Expand All @@ -8823,11 +8839,13 @@ impl SessionManager {
.effective_model_name
.or_else(|| existing.effective_model_name.clone());
round.routing = round.routing.or_else(|| existing.routing.clone());
round.first_chunk_ms = existing.first_chunk_ms;
round.first_visible_output_ms = existing.first_visible_output_ms;
round.stream_duration_ms = existing.stream_duration_ms;
round.ttft_ms = existing.ttft_ms;
round.attempt_count = existing.attempt_count;
round.first_chunk_ms = round.first_chunk_ms.or(existing.first_chunk_ms);
round.first_visible_output_ms = round
.first_visible_output_ms
.or(existing.first_visible_output_ms);
round.stream_duration_ms = round.stream_duration_ms.or(existing.stream_duration_ms);
round.ttft_ms = round.ttft_ms.or(existing.ttft_ms);
round.attempt_count = round.attempt_count.or(existing.attempt_count);
round.attempt_diagnostics = existing.attempt_diagnostics.clone();
round.failure_category = existing.failure_category.clone();
round.token_details = existing.token_details.clone();
Expand Down Expand Up @@ -10787,6 +10805,7 @@ mod tests {
latency_ms: 17,
fallback_reason: None,
}),
timing: None,
});
let restored: Message =
serde_json::from_value(serde_json::to_value(routed).unwrap()).unwrap();
Expand All @@ -10801,6 +10820,77 @@ mod tests {
assert_eq!(rounds[1].routing.as_ref().unwrap().latency_ms, 17);
}

#[test]
fn completion_merge_keeps_runtime_round_timing_over_stale_client_checkpoint() {
let timed_message = |round_id: &str, timing| {
let mut message = Message::assistant("answer".into()).with_round_id(round_id.into());
message.metadata.model_execution =
Some(crate::agentic::core::message::ModelExecutionMetadata {
model_config_id: "model".into(),
effective_model_name: "model".into(),
routing: None,
timing,
});
message
};
let mut turn = DialogTurnData::new(
"turn".into(),
0,
"session".into(),
UserMessageData {
id: "input".into(),
content: "hi".into(),
timestamp: 1,
metadata: None,
},
);
// The client checkpointed the final round before its
// `ModelRoundCompleted` arrived, and a checkpoint from an older writer
// recorded an unknown duration as 0.
let mut stale = SessionManager::build_model_rounds_from_messages(
&[timed_message("final", None)],
"turn",
1,
);
stale[0].duration_ms = Some(0);
// A legacy journal without timing keeps the client's real facts.
let mut checkpointed = SessionManager::build_model_rounds_from_messages(
&[timed_message("legacy", None)],
"turn",
1,
);
checkpointed[0].duration_ms = Some(900);
checkpointed[0].ttft_ms = Some(150);
turn.model_rounds = vec![checkpointed.remove(0), stale.remove(0)];

let runtime_timing = crate::agentic::core::message::ModelRoundTimingMetadata {
duration_ms: Some(2172),
first_chunk_ms: Some(10),
first_visible_output_ms: Some(20),
stream_duration_ms: Some(1500),
ttft_ms: Some(690),
attempt_count: Some(1),
};
SessionManager::append_generation_rounds(
&mut turn,
"turn",
&[
timed_message("legacy", None),
timed_message("final", Some(runtime_timing)),
],
2,
);

let legacy = &turn.model_rounds[0];
assert_eq!(legacy.duration_ms, Some(900));
assert_eq!(legacy.ttft_ms, Some(150));
let last = &turn.model_rounds[1];
assert_eq!(last.duration_ms, Some(2172));
assert_eq!(last.ttft_ms, Some(690));
assert_eq!(last.stream_duration_ms, Some(1500));
assert_eq!(last.attempt_count, Some(1));
}

#[test]
fn classified_edit_history_preserves_detail_and_readable_error() {
let assistant = Message::assistant_with_tools(
Expand Down
71 changes: 71 additions & 0 deletions src/crates/assembly/core/src/product_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,30 @@ fn merge_runtime_owned_turn_facts(
) -> DialogTurnData {
let mut merged = projected.clone();
merged.agent_type = persisted.agent_type.clone();
// Round timing comes from the Runtime's accepted attempt. A projection
// saved by a window that missed (or had not yet applied) that round's
// `ModelRoundCompleted` must not erase it from the durable record.
for round in &mut merged.model_rounds {
let Some(persisted_round) = persisted
.model_rounds
.iter()
.find(|candidate| candidate.id == round.id)
else {
continue;
};
if round.duration_ms.is_none_or(|duration_ms| duration_ms == 0) {
round.duration_ms = persisted_round.duration_ms.or(round.duration_ms);
}
round.first_chunk_ms = round.first_chunk_ms.or(persisted_round.first_chunk_ms);
round.first_visible_output_ms = round
.first_visible_output_ms
.or(persisted_round.first_visible_output_ms);
round.stream_duration_ms = round
.stream_duration_ms
.or(persisted_round.stream_duration_ms);
round.ttft_ms = round.ttft_ms.or(persisted_round.ttft_ms);
round.attempt_count = round.attempt_count.or(persisted_round.attempt_count);
}

let Some(persisted_metadata) = persisted
.user_message
Expand Down Expand Up @@ -3314,6 +3338,53 @@ mod tests {
);
}

#[test]
fn projected_turn_saves_keep_runtime_round_timing() {
let mut persisted = DialogTurnData::new(
"turn-1".to_string(),
0,
"session-1".to_string(),
UserMessageData {
id: "user-1".to_string(),
content: "hi".to_string(),
timestamp: 1,
metadata: None,
},
);
let round = |id: &str| {
SessionManager::build_model_rounds_from_messages(
&[crate::agentic::core::Message::assistant("answer".into())
.with_round_id(id.into())],
"turn-1",
1,
)
.remove(0)
};
let mut timed = round("round-1");
timed.duration_ms = Some(2172);
timed.stream_duration_ms = Some(1500);
timed.ttft_ms = Some(690);
timed.attempt_count = Some(1);
let mut projected_timed = round("round-0");
projected_timed.duration_ms = Some(900);
let mut persisted_timed = projected_timed.clone();
persisted_timed.duration_ms = Some(800);
persisted.model_rounds = vec![persisted_timed, timed];
let mut projected = persisted.clone();
// The window checkpointed the last round before its completion event.
let mut untimed = round("round-1");
untimed.duration_ms = Some(0);
projected.model_rounds = vec![projected_timed, untimed];

let merged = merge_runtime_owned_turn_facts(&persisted, &projected);
assert_eq!(merged.model_rounds[0].duration_ms, Some(900));
let last = &merged.model_rounds[1];
assert_eq!(last.duration_ms, Some(2172));
assert_eq!(last.stream_duration_ms, Some(1500));
assert_eq!(last.ttft_ms, Some(690));
assert_eq!(last.attempt_count, Some(1));
}

#[tokio::test]
async fn product_event_queue_owner_broadcasts_while_draining_the_legacy_queue() {
let queue = Arc::new(EventQueue::new(EventQueueConfig {
Expand Down
Loading
Loading