You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/14 06:59:32 UTC
(maka) branch feat/runtime-host-rust updated: feat(agent): execute safe lineage continuations
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/runtime-host-rust by this push:
new 0730d0f882 feat(agent): execute safe lineage continuations
0730d0f882 is described below
commit 0730d0f88275dec473856241618aec52a263cba4
Author: Wang <m4...@gmail.com>
AuthorDate: Mon Sep 14 14:59:25 2026 +0800
feat(agent): execute safe lineage continuations
Generated-by: OpenAI Codex
---
crates/agent/src/auto_context.rs | 3 +-
crates/agent/src/compact.rs | 12 +-
crates/agent/src/continuation.rs | 165 +++++++++++++
crates/agent/src/history.rs | 4 +
crates/agent/src/history/images.rs | 13 ++
crates/agent/src/history/projection.rs | 23 +-
crates/agent/src/history/replay.rs | 254 ++++++++++++++++++++
crates/agent/src/lib.rs | 26 ++-
crates/agent/src/model_attempt.rs | 258 ++++++++++++++-------
crates/agent/src/runner.rs | 31 ++-
crates/agent/src/steps.rs | 51 +++-
.../agent/tests/integration/model_interruption.rs | 95 +++++++-
crates/event-log/src/context/safety.rs | 17 +-
.../tests/context_compaction/active_safety.rs | 39 +++-
crates/runtime/src/event.rs | 3 +
docs/rust-runtime.md | 5 +-
docs/rust-runtime.zh-CN.md | 3 +-
17 files changed, 883 insertions(+), 119 deletions(-)
diff --git a/crates/agent/src/auto_context.rs b/crates/agent/src/auto_context.rs
index ad4bcfd248..e0877c1634 100644
--- a/crates/agent/src/auto_context.rs
+++ b/crates/agent/src/auto_context.rs
@@ -80,6 +80,7 @@ pub(super) async fn attempt(
source: &ModelContextSource,
mid_turn: bool,
cancellation: &CancellationToken,
+ continuation_base: Option<u64>,
) -> Result<bool, RunError> {
let opening = source
.anchor
@@ -104,7 +105,7 @@ pub(super) async fn attempt(
} else {
CheckpointMode::PreTurn
};
- let result = compact::run(inner, input, &mode, cancellation).await;
+ let result = compact::run(inner, input, &mode, cancellation, continuation_base).await;
let (_, checkpoint) = match result {
Ok(result) => result,
Err(RunError::Model(
diff --git a/crates/agent/src/compact.rs b/crates/agent/src/compact.rs
index bf63ddc479..d3b8c4da1c 100644
--- a/crates/agent/src/compact.rs
+++ b/crates/agent/src/compact.rs
@@ -35,6 +35,7 @@ pub(super) async fn run(
input: &RunInput,
mode: &CheckpointMode,
cancellation: &CancellationToken,
+ continuation_base: Option<u64>,
) -> Result<(CompactOutcome, Option<RuntimeEvent>), RunError> {
let source = match inner
.log
@@ -76,8 +77,15 @@ pub(super) async fn run(
None,
));
}
- let prompt =
- model_attempt::prompt(inner, input, &source, ModelPurpose::Summary, cancellation).await?;
+ let prompt = model_attempt::prompt(
+ inner,
+ input,
+ &source,
+ ModelPurpose::Summary,
+ cancellation,
+ continuation_base,
+ )
+ .await?;
let base = format!(
"You are a context summarization assistant.\nRead the conversation between a user and an AI assistant, then produce a structured summary another LLM will use to continue the same task.\nDo NOT continue the conversation. Do NOT answer questions in it. ONLY output the structured summary.\n\nUse this exact format:\n\n{SUMMARY_FORMAT_TEMPLATE}\n\nKeep each section concise. Preserve exact file paths, function names, commands, and error messages."
);
diff --git a/crates/agent/src/continuation.rs b/crates/agent/src/continuation.rs
new file mode 100644
index 0000000000..36b75ffe14
--- /dev/null
+++ b/crates/agent/src/continuation.rs
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::{Inner, RunError, RunInput, model_attempt};
+use maka_model::prompt::{AssistantPart, Message};
+use maka_runtime::{
+ context::ModelPurpose,
+ continuation::{ContinuationClaim, REPLAY_VERSION, ReplayEvidence, RunBoundary, SessionBase},
+ event::Fact,
+ input::InvocationInput,
+};
+use std::sync::Arc;
+use tokio_util::sync::CancellationToken;
+
+/// Derive admission evidence from the exact sealed source. The caller supplies
+/// only its boundary, never a replay digest or a pre-authorized claim.
+pub(super) async fn prepare(
+ inner: &Arc<Inner>,
+ input: &RunInput,
+ source: &RunBoundary,
+ catalog: &maka_tools::ToolCatalog,
+ cancellation: &CancellationToken,
+) -> Result<ContinuationClaim, RunError> {
+ let prefix = inner
+ .log
+ .run_prefix(
+ &source.invocation.session_id,
+ &source.invocation.run_id,
+ None,
+ 10_000,
+ 8 * 1024 * 1024,
+ )
+ .await?
+ .ok_or_else(|| invalid("continuation source is missing"))?;
+ if prefix.invocation != source.invocation
+ || prefix.high_water != source.high_water
+ || prefix.digest != source.digest
+ || !matches!(
+ prefix.events.last().map(|s| &s.event.fact),
+ Some(Fact::InvocationEnded { .. })
+ )
+ {
+ return Err(invalid(
+ "continuation source is not its exact sealed boundary",
+ ));
+ }
+ let Fact::InvocationOpened {
+ input: opening,
+ configuration: Some(configuration),
+ } = &prefix
+ .events
+ .first()
+ .ok_or_else(|| invalid("continuation source is empty"))?
+ .event
+ .fact
+ else {
+ return Err(invalid("continuation source has no observed configuration"));
+ };
+ if input.configuration.workspace_identity.is_none()
+ || input.configuration.workspace_identity != configuration.workspace_identity
+ {
+ return Err(invalid("continuation workspace identity changed"));
+ }
+ let base = match opening {
+ InvocationInput::Message { .. } => {
+ let base = inner
+ .log
+ .context_before_run(&source.invocation, 10_000, 8 * 1024 * 1024)
+ .await?;
+ SessionBase {
+ high_water: base.source_evidence.high_water,
+ digest: base.source_evidence.digest,
+ }
+ }
+ InvocationInput::Continuation { claim, .. } => claim.base.clone(),
+ _ => return Err(invalid("source is not a resumable model Run")),
+ };
+ let context = inner
+ .log
+ .read_lineage_context(source, 10_000, 8 * 1024 * 1024)
+ .await?;
+ let prompt = model_attempt::prompt(
+ inner,
+ input,
+ &context,
+ ModelPurpose::Main,
+ cancellation,
+ Some(base.high_water),
+ )
+ .await?;
+ if !matches!(
+ prompt.iter().find(|m| !matches!(m, Message::System { .. })),
+ Some(Message::User { .. })
+ ) || !matches!(
+ prompt.last(),
+ Some(Message::User { .. } | Message::Tool { .. })
+ ) && !matches!(prompt.last(), Some(Message::Assistant { content, .. }) if matches!(content.last(), Some(AssistantPart::ToolResult { .. })))
+ {
+ return Err(invalid(
+ "continuation requires stable user/tool replay boundaries",
+ ));
+ }
+ let tools = maka_tools::RunTools::new(
+ inner.log.clone(),
+ input.invocation.clone(),
+ catalog.clone(),
+ input.configuration.tool_mode,
+ inner.cells.clone(),
+ );
+ let definitions = tools.definitions();
+ let mut available: std::collections::HashSet<_> = catalog.names().into_iter().collect();
+ available.extend(definitions.iter().map(|definition| definition.name.clone()));
+ for message in &prompt {
+ if let Message::Assistant { content, .. } = message {
+ for part in content {
+ if let AssistantPart::ToolCall {
+ tool_name,
+ provider_executed,
+ ..
+ } = part
+ && *provider_executed != Some(true)
+ && !available.contains(tool_name)
+ {
+ return Err(invalid("continuation requires an unavailable tool"));
+ }
+ }
+ }
+ }
+ let request = model_attempt::prepare_request(input, prompt, definitions, ModelPurpose::Main)?;
+ let claim = ContinuationClaim {
+ id: uuid::Uuid::new_v4().to_string(),
+ source: source.clone(),
+ base,
+ replay: ReplayEvidence {
+ version: REPLAY_VERSION,
+ digest: request.input_digest,
+ route_identity: request.route_identity,
+ },
+ };
+ claim.validate(&input.invocation).map_err(invalid)?;
+ if cancellation.is_cancelled() {
+ return Err(RunError::Cancelled);
+ }
+ Ok(claim)
+}
+
+fn invalid(reason: &str) -> RunError {
+ RunError::ReconciliationRequired(reason.into())
+}
diff --git a/crates/agent/src/history.rs b/crates/agent/src/history.rs
index d744be5783..84d16cafb0 100644
--- a/crates/agent/src/history.rs
+++ b/crates/agent/src/history.rs
@@ -28,6 +28,8 @@ pub(super) use chat::project as project_chat;
pub(super) use compatible::project as project_compatible;
mod output;
mod projection;
+mod replay;
+pub(super) use replay::Replay;
mod user;
#[derive(Clone, Copy)]
@@ -53,6 +55,7 @@ impl<'a> From<&'a maka_event_log::context::ContextEvent> for EventRef<'a> {
}
mod references;
pub(super) use images::materialize;
+pub(super) use images::materialize_replay;
use projection::build;
pub fn operation_id(step_id: &str, call_id: &str) -> String {
@@ -77,6 +80,7 @@ pub fn project(prefix: &LogPrefix, session: &str) -> Result<Vec<Message>, RunErr
session,
&mut Vec::new(),
false,
+ None,
)
}
diff --git a/crates/agent/src/history/images.rs b/crates/agent/src/history/images.rs
index 77d4e9313b..6a42c4b81c 100644
--- a/crates/agent/src/history/images.rs
+++ b/crates/agent/src/history/images.rs
@@ -61,6 +61,18 @@ pub(crate) async fn materialize(
session: &str,
vision: bool,
cancellation: &CancellationToken,
+) -> Result<Vec<Message>, RunError> {
+ materialize_replay(log, events, anchor, session, vision, cancellation, None).await
+}
+
+pub(crate) async fn materialize_replay(
+ log: &EventLog,
+ events: &[maka_event_log::context::ContextEvent],
+ anchor: Option<&StoredEvent>,
+ session: &str,
+ vision: bool,
+ cancellation: &CancellationToken,
+ replay: Option<super::Replay<'_>>,
) -> Result<Vec<Message>, RunError> {
let mut targets = Vec::new();
let mut messages = super::build(
@@ -71,6 +83,7 @@ pub(crate) async fn materialize(
session,
&mut targets,
vision,
+ replay,
)?;
let mut remaining = IMAGE_BUDGET;
let mut omitted = BTreeMap::<usize, usize>::new();
diff --git a/crates/agent/src/history/projection.rs b/crates/agent/src/history/projection.rs
index 528e6415ed..8a3da33926 100644
--- a/crates/agent/src/history/projection.rs
+++ b/crates/agent/src/history/projection.rs
@@ -32,7 +32,9 @@ pub(super) fn build<'a>(
session: &str,
images: &mut Vec<images::Target<'a>>,
vision: bool,
+ replay: Option<super::Replay<'a>>,
) -> Result<Vec<Message>, RunError> {
+ let cuts = replay.map(|policy| super::replay::Cuts::new(events.clone(), policy));
let mut messages = Vec::new();
let mut calls = HashMap::new();
let mut dispatched = HashSet::new();
@@ -157,7 +159,7 @@ pub(super) fn build<'a>(
}
}
let mut content = Vec::new();
- for part in &output.parts {
+ for (index, part) in output.parts.iter().enumerate() {
let value = match part {
ModelPart::Text {
text_kind,
@@ -205,12 +207,21 @@ pub(super) fn build<'a>(
provider_options: provider_options.clone(),
},
};
- content.push(value);
+ if cuts
+ .as_ref()
+ .map(|cuts| cuts.allows(stored, step_id, index, part))
+ .transpose()?
+ .unwrap_or(true)
+ {
+ content.push(value);
+ }
+ }
+ if !content.is_empty() {
+ messages.push(Message::Assistant {
+ content,
+ provider_options: None,
+ });
}
- messages.push(Message::Assistant {
- content,
- provider_options: None,
- });
}
Fact::ToolDispatched {
operation_id: operation,
diff --git a/crates/agent/src/history/replay.rs b/crates/agent/src/history/replay.rs
new file mode 100644
index 0000000000..7b130d8d17
--- /dev/null
+++ b/crates/agent/src/history/replay.rs
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::EventRef;
+use crate::RunError;
+use maka_runtime::{
+ event::{Fact, StoredEvent},
+ input::InvocationInput,
+ model::{ModelPart, TextKind},
+ tool_call::ToolOrigin,
+};
+use std::collections::{HashMap, HashSet};
+
+/// Admission supplies the authenticated Session base, never a shortened log cut.
+#[derive(Clone, Copy)]
+pub(crate) struct Replay<'a> {
+ pub base: u64,
+ pub current: &'a str,
+ pub route: &'a str,
+ pub model: &'a str,
+}
+
+pub(super) struct Cuts<'a> {
+ policy: Replay<'a>,
+ stable: HashMap<&'a str, (u64, usize)>,
+ routes: HashMap<(&'a str, &'a str), (&'a str, &'a str)>,
+}
+
+impl<'a> Cuts<'a> {
+ pub fn new(events: impl Iterator<Item = EventRef<'a>> + Clone, policy: Replay<'a>) -> Self {
+ let provider_operations: HashSet<_> = events
+ .clone()
+ .filter_map(EventRef::canonical)
+ .filter_map(|stored| match &stored.event.fact {
+ Fact::ToolDispatched {
+ operation_id, call, ..
+ } if matches!(call.origin, ToolOrigin::Provider { .. }) => {
+ Some(operation_id.as_str())
+ }
+ _ => None,
+ })
+ .collect();
+ let mut result = Self {
+ policy,
+ stable: HashMap::new(),
+ routes: HashMap::new(),
+ };
+ for event in events {
+ let (sequence, invocation) = match event {
+ EventRef::Canonical(stored) => (stored.sequence, &stored.event.invocation),
+ EventRef::Archived(archived) => (archived.sequence, &archived.invocation),
+ };
+ let inherited = sequence > policy.base && invocation.invocation_id != policy.current;
+ if inherited {
+ result.stable.entry(&invocation.invocation_id).or_default();
+ }
+ let cut = match event {
+ EventRef::Archived(_) => Some(usize::MAX),
+ EventRef::Canonical(stored) => match &stored.event.fact {
+ Fact::InvocationOpened {
+ input: InvocationInput::Message { .. },
+ ..
+ }
+ | Fact::MessageSteered { .. } => Some(usize::MAX),
+ Fact::ToolRejected { call, .. }
+ if matches!(call.origin, ToolOrigin::Provider { .. }) =>
+ {
+ Some(usize::MAX)
+ }
+ Fact::ToolSettled { operation_id, .. }
+ if provider_operations.contains(operation_id.as_str()) =>
+ {
+ Some(usize::MAX)
+ }
+ Fact::ModelCompleted { output, .. } => output
+ .parts
+ .iter()
+ .rposition(|part| matches!(part, ModelPart::ToolResult { .. }))
+ .map(|index| index + 1),
+ Fact::ModelRequested {
+ step_id,
+ model_id,
+ route_identity,
+ ..
+ } => {
+ result.routes.insert(
+ (&invocation.invocation_id, step_id),
+ (model_id, route_identity),
+ );
+ None
+ }
+ _ => None,
+ },
+ };
+ if inherited && let Some(part) = cut {
+ result
+ .stable
+ .insert(&invocation.invocation_id, (sequence, part));
+ }
+ }
+ result
+ }
+
+ /// Call pairing is still validated against all facts by the history builder;
+ /// this gate controls only the emitted model parts, including event-internal cuts.
+ pub fn allows(
+ &self,
+ stored: &StoredEvent,
+ step: &str,
+ index: usize,
+ part: &ModelPart,
+ ) -> Result<bool, RunError> {
+ if stored.sequence > self.policy.base
+ && stored.event.invocation.invocation_id != self.policy.current
+ {
+ let cut = self
+ .stable
+ .get(stored.event.invocation.invocation_id.as_str())
+ .copied()
+ .unwrap_or_default();
+ if (stored.sequence, index) >= cut {
+ return Ok(false);
+ }
+ }
+ if matches!(
+ part,
+ ModelPart::Text {
+ text_kind: TextKind::Thinking,
+ ..
+ }
+ ) && self
+ .routes
+ .get(&(stored.event.invocation.invocation_id.as_str(), step))
+ .copied()
+ != Some((self.policy.model, self.policy.route))
+ {
+ return Err(RunError::ReconciliationRequired(
+ "continuation reasoning belongs to another provider route or model".into(),
+ ));
+ }
+ Ok(true)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use maka_runtime::event::{Invocation, RuntimeEvent};
+ use serde_json::json;
+
+ #[test]
+ fn cuts_preserve_event_internal_tool_results_and_do_not_trim_base_or_current_run() {
+ let invocation = Invocation {
+ session_id: "session".into(),
+ turn_id: "source".into(),
+ run_id: "source".into(),
+ invocation_id: "source".into(),
+ };
+ let events: Vec<_> = [
+ Fact::InvocationOpened { configuration: None, input: InvocationInput::Message {
+ content: "question".into(), request_fingerprint: None, source_messages: Vec::new(), skill_invocation: None,
+ }},
+ Fact::ModelRequested { step_id: "step".into(), model_id: "old".into(), route_identity: "old".into(),
+ purpose: None, context: None, source_scope: maka_runtime::event::LogScope::Root, source_high_water: 1,
+ source_digest: "fixture".into(), input_digest: "fixture".into(), checkpoint_event_id: None, effective_source_digest: None },
+ Fact::ModelCompleted { step_id: "step".into(), output: serde_json::from_value(json!({
+ "parts":[
+ {"kind":"tool_result","id":"remote","name":"search","output":{},"is_error":false,"provider_options":null},
+ {"kind":"text","text_kind":"text","text":"trailing text","provider_options":null},
+ {"kind":"text","text_kind":"thinking","text":"old reasoning","provider_options":{"signature":"old"}}
+ ], "finish_reason":"stop","usage":{}
+ })).unwrap() },
+ ].into_iter().enumerate().map(|(i, fact)| StoredEvent {
+ sequence: i as u64 + 1, event: RuntimeEvent::new(invocation.clone(), fact),
+ }).collect();
+ let policy = Replay {
+ base: 0,
+ current: "child",
+ route: "new",
+ model: "new",
+ };
+ let Fact::ModelCompleted { output, .. } = &events[2].event.fact else {
+ unreachable!()
+ };
+ let cuts = Cuts::new(events.iter().map(EventRef::Canonical), policy);
+ for (index, expected) in [true, false, false].into_iter().enumerate() {
+ assert_eq!(
+ cuts.allows(&events[2], "step", index, &output.parts[index])
+ .unwrap(),
+ expected
+ );
+ }
+ for policy in [
+ Replay { base: 3, ..policy },
+ Replay {
+ current: "source",
+ ..policy
+ },
+ ] {
+ let cuts = Cuts::new(events.iter().map(EventRef::Canonical), policy);
+ assert!(
+ cuts.allows(&events[2], "step", 1, &output.parts[1])
+ .unwrap()
+ );
+ assert!(
+ cuts.allows(&events[2], "step", 2, &output.parts[2])
+ .is_err(),
+ "retained reasoning cannot cross provider identity"
+ );
+ }
+ let archived = maka_event_log::context::ArchivedToolResult {
+ sequence: 4,
+ event_id: "archive".into(),
+ invocation,
+ operation_id: "local-call".into(),
+ replacement: maka_runtime::tool_output::DurableToolProjection::Json {
+ value: json!({"page":"retained"}),
+ },
+ is_error: false,
+ };
+ let cuts = Cuts::new(
+ events
+ .iter()
+ .map(EventRef::Canonical)
+ .chain(std::iter::once(EventRef::Archived(&archived))),
+ policy,
+ );
+ assert!(
+ cuts.allows(&events[2], "step", 1, &output.parts[1])
+ .unwrap(),
+ "a later archived tool result is a stable boundary, not an omitted effect"
+ );
+ assert!(
+ cuts.allows(&events[2], "step", 2, &output.parts[2])
+ .is_err()
+ );
+ }
+}
diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs
index da4d9e327d..c3b8e33a21 100644
--- a/crates/agent/src/lib.rs
+++ b/crates/agent/src/lib.rs
@@ -19,6 +19,7 @@
mod auto_context;
mod compact;
+mod continuation;
mod history;
mod model_attempt;
pub use history::project as project_model_history;
@@ -84,6 +85,11 @@ pub struct RunInput {
}
pub enum RunWork {
+ Continuation {
+ source: maka_runtime::continuation::RunBoundary,
+ tools: ToolCatalog,
+ max_steps: usize,
+ },
Message {
message: MessageInput,
source_messages: Vec<maka_runtime::message::RootSourceMessage>,
@@ -158,6 +164,22 @@ impl Engine {
} if *max_steps == 0 || *max_steps > 256 || message.text_bytes() > 64 * 1024 => {
return Err(RunError::InvalidInput("step or message limit".into()));
}
+ RunWork::Continuation {
+ source, max_steps, ..
+ } => {
+ if *max_steps == 0
+ || *max_steps > 256
+ || source.invocation.session_id != input.invocation.session_id
+ || input
+ .request_fingerprint
+ .as_ref()
+ .is_none_or(|s| !maka_runtime::archive::valid_projection_digest(s))
+ {
+ return Err(RunError::InvalidInput(
+ "invalid continuation request".into(),
+ ));
+ }
+ }
RunWork::ContextCompact
if input
.request_fingerprint
@@ -215,7 +237,9 @@ impl Engine {
let inner = self.0.clone();
let invocation = input.invocation.clone();
let tool_names = Arc::new(match &input.work {
- RunWork::Message { tools, .. } => tools.names().into_iter().collect(),
+ RunWork::Message { tools, .. } | RunWork::Continuation { tools, .. } => {
+ tools.names().into_iter().collect()
+ }
RunWork::ContextCompact => Default::default(),
});
let worker_cancellation = cancellation.clone();
diff --git a/crates/agent/src/model_attempt.rs b/crates/agent/src/model_attempt.rs
index e71cad027b..5a3896e981 100644
--- a/crates/agent/src/model_attempt.rs
+++ b/crates/agent/src/model_attempt.rs
@@ -35,7 +35,10 @@ use tokio_util::sync::CancellationToken;
use uuid::Uuid;
pub(super) enum Attempt {
- Main(maka_model::ResponsesLane),
+ Main {
+ lane: maka_model::ResponsesLane,
+ continuation_base: Option<u64>,
+ },
Summary,
}
@@ -45,14 +48,23 @@ pub(super) async fn prompt(
source: &ModelContextSource,
purpose: ModelPurpose,
cancellation: &CancellationToken,
+ continuation_base: Option<u64>,
) -> Result<Vec<Message>, RunError> {
- let mut prompt = history::materialize(
+ let route = route_identity(input)?;
+ let replay = continuation_base.map(|base| history::Replay {
+ base,
+ current: &input.invocation.invocation_id,
+ route: &route,
+ model: &input.provider.model,
+ });
+ let mut prompt = history::materialize_replay(
&inner.log,
&source.tail,
source.anchor.as_ref(),
&input.invocation.session_id,
input.supports_vision,
cancellation,
+ replay,
)
.await?;
if let Some(baseline) = &source.baseline {
@@ -91,7 +103,11 @@ pub(super) async fn execute(
attempt: Attempt,
cancellation: &CancellationToken,
) -> Result<(String, ModelStep), RunError> {
- let Attempt::Main(lane) = attempt else {
+ let Attempt::Main {
+ lane,
+ continuation_base,
+ } = attempt
+ else {
return execute_once(
inner,
input,
@@ -104,16 +120,20 @@ pub(super) async fn execute(
.await;
};
let mut failures = 0;
+ let mut refreshed = None;
loop {
// Each physical request gets a new step and the same frozen inputs.
// Never reuse a request shortened by Responses continuation preparation.
let result = execute_once(
inner,
input,
- source,
+ refreshed.as_ref().unwrap_or(source),
prompt.clone(),
definitions.clone(),
- Attempt::Main(lane.clone()),
+ Attempt::Main {
+ lane: lane.clone(),
+ continuation_base,
+ },
cancellation,
)
.await;
@@ -136,6 +156,32 @@ pub(super) async fn execute(
_ = cancellation.cancelled() => return Err(RunError::Cancelled),
_ = tokio::time::sleep(delay) => {}
}
+ if continuation_base.is_some() {
+ let next = inner
+ .log
+ .read_model_context(
+ &input.invocation.session_id,
+ Some(&input.invocation.invocation_id),
+ 10_000,
+ 8 * 1024 * 1024,
+ )
+ .await?;
+ let replay = self::prompt(
+ inner,
+ input,
+ &next,
+ ModelPurpose::Main,
+ cancellation,
+ continuation_base,
+ )
+ .await?;
+ if replay != prompt {
+ return Err(RunError::ReconciliationRequired(
+ "continuation retry changed frozen model input".into(),
+ ));
+ }
+ refreshed = Some(next);
+ }
}
}
@@ -149,39 +195,13 @@ async fn execute_once(
cancellation: &CancellationToken,
) -> Result<(String, ModelStep), RunError> {
let (purpose, lane) = match attempt {
- Attempt::Main(lane) => (ModelPurpose::Main, Some(lane)),
+ Attempt::Main { lane, .. } => (ModelPurpose::Main, Some(lane)),
Attempt::Summary => (ModelPurpose::Summary, None),
};
if cancellation.is_cancelled() {
return Err(RunError::Cancelled);
}
- let max_output_tokens = match purpose {
- ModelPurpose::Main => input.main_output_limit,
- ModelPurpose::Summary => Some(8000),
- };
- let prompt = if input.supports_vision
- && matches!(
- &input.provider.kind,
- maka_model::ProviderKind::OpenaiChat
- | maka_model::ProviderKind::OpenaiCompatible { .. }
- ) {
- history::project_chat(prompt)
- } else {
- prompt
- };
- let prompt = history::project_compatible(prompt, &input.provider.kind);
- let mut evidence = json!({"projection":"maka.model-history.v1","prompt":prompt,
- "tools":definitions,"providerOptions":input.provider_options});
- if let Some(limit) = max_output_tokens {
- evidence["maxOutputTokens"] = json!(limit);
- }
- let input_digest = digest(
- &serde_json::to_vec(&evidence).map_err(|error| RunError::Internal(error.to_string()))?,
- );
- let route_identity = digest(
- &serde_json::to_vec(&input.provider)
- .map_err(|error| RunError::Internal(error.to_string()))?,
- );
+ let prepared = prepare_request(input, prompt, definitions, purpose)?;
let step_id = Uuid::new_v4().to_string();
append(
inner,
@@ -200,8 +220,8 @@ async fn execute_once(
source_scope: source.source_evidence.scope.clone(),
source_high_water: source.source_evidence.high_water,
source_digest: source.source_evidence.digest.clone(),
- input_digest,
- route_identity,
+ input_digest: prepared.input_digest,
+ route_identity: prepared.route_identity,
checkpoint_event_id: source
.baseline
.as_ref()
@@ -210,64 +230,127 @@ async fn execute_once(
)
.await?;
let result: Result<_, RunError> = async {
- let mut stream = inner
+ let stream = inner
.model
- .stream_in_lane(
- ModelRequest {
- provider: input.provider.clone(),
- prompt,
- tools: definitions,
- provider_options: input.provider_options.clone(),
- max_output_tokens,
+ .stream_in_lane(prepared.request, cancellation.clone(), lane)
+ .await?;
+ receive(inner, input, &step_id, purpose, stream).await
+ }
+ .await;
+ finish(inner, input, step_id, result, cancellation).await
+}
+
+pub(super) struct PreparedRequest {
+ pub request: ModelRequest,
+ pub input_digest: String,
+ pub route_identity: String,
+}
+
+pub(super) fn route_identity(input: &RunInput) -> Result<String, RunError> {
+ Ok(digest(
+ &serde_json::to_vec(&input.provider)
+ .map_err(|error| RunError::Internal(error.to_string()))?,
+ ))
+}
+
+pub(super) fn prepare_request(
+ input: &RunInput,
+ prompt: Vec<Message>,
+ definitions: Vec<ToolDefinition>,
+ purpose: ModelPurpose,
+) -> Result<PreparedRequest, RunError> {
+ let max_output_tokens = match purpose {
+ ModelPurpose::Main => input.main_output_limit,
+ ModelPurpose::Summary => Some(8000),
+ };
+ let prompt = if input.supports_vision
+ && matches!(
+ &input.provider.kind,
+ maka_model::ProviderKind::OpenaiChat
+ | maka_model::ProviderKind::OpenaiCompatible { .. }
+ ) {
+ history::project_chat(prompt)
+ } else {
+ prompt
+ };
+ let prompt = history::project_compatible(prompt, &input.provider.kind);
+ let mut evidence = json!({"projection":"maka.model-history.v1","prompt":prompt,
+ "tools":definitions,"providerOptions":input.provider_options});
+ if let Some(limit) = max_output_tokens {
+ evidence["maxOutputTokens"] = json!(limit);
+ }
+ let input_digest = digest(
+ &serde_json::to_vec(&evidence).map_err(|error| RunError::Internal(error.to_string()))?,
+ );
+ Ok(PreparedRequest {
+ request: ModelRequest {
+ provider: input.provider.clone(),
+ prompt,
+ tools: definitions,
+ provider_options: input.provider_options.clone(),
+ max_output_tokens,
+ },
+ input_digest,
+ route_identity: route_identity(input)?,
+ })
+}
+
+async fn receive(
+ inner: &Arc<Inner>,
+ input: &RunInput,
+ step_id: &str,
+ purpose: ModelPurpose,
+ mut stream: maka_model::ModelStream,
+) -> Result<ModelStep, RunError> {
+ let mut builder = StepBuilder::for_step(step_id)?;
+ let result: Result<_, RunError> = async {
+ while let Some(event) = stream.next().await {
+ let event = event?;
+ builder.push(event.clone())?;
+ append(
+ inner,
+ &input.invocation,
+ Fact::ModelObserved {
+ step_id: step_id.to_owned(),
+ event,
},
- cancellation.clone(),
- lane,
)
.await?;
- let mut builder = StepBuilder::for_step(&step_id)?;
- let result: Result<_, RunError> = async {
- while let Some(event) = stream.next().await {
- let event = event?;
- builder.push(event.clone())?;
- append(
- inner,
- &input.invocation,
- Fact::ModelObserved {
- step_id: step_id.clone(),
- event,
- },
- )
- .await?;
- }
- builder.finish().map_err(Into::into)
- }
- .await;
- stream.cancel_and_wait().await;
- let output = result?;
- if purpose == ModelPurpose::Main
- && output.finish_reason == maka_runtime::model::ModelFinishReason::Length
- {
- return Err(maka_model::ModelError::Adapter(
- "unsupported model finish reason: length".into(),
- )
- .into());
- }
- if purpose == ModelPurpose::Summary
- && output.parts.iter().any(|part| {
- matches!(
- part,
- maka_runtime::model::ModelPart::ToolCall { .. }
- | maka_runtime::model::ModelPart::ToolResult { .. }
- )
- })
- {
- return Err(
- maka_model::ModelError::Adapter("summary contains tool content".into()).into(),
- );
}
- Ok(output)
+ builder.finish().map_err(Into::into)
}
.await;
+ stream.cancel_and_wait().await;
+ let output = result?;
+ if purpose == ModelPurpose::Main
+ && output.finish_reason == maka_runtime::model::ModelFinishReason::Length
+ {
+ return Err(maka_model::ModelError::Adapter(
+ "unsupported model finish reason: length".into(),
+ )
+ .into());
+ }
+ if purpose == ModelPurpose::Summary
+ && output.parts.iter().any(|part| {
+ matches!(
+ part,
+ maka_runtime::model::ModelPart::ToolCall { .. }
+ | maka_runtime::model::ModelPart::ToolResult { .. }
+ )
+ })
+ {
+ return Err(maka_model::ModelError::Adapter("summary contains tool content".into()).into());
+ }
+ Ok(output)
+}
+
+async fn finish(
+ inner: &Arc<Inner>,
+ input: &RunInput,
+ step_id: String,
+ result: Result<ModelStep, RunError>,
+ cancellation: &CancellationToken,
+) -> Result<(String, ModelStep), RunError> {
let output = match result {
Ok(output) => output,
Err(RunError::Model(error)) => {
@@ -276,6 +359,9 @@ async fn execute_once(
maka_model::ModelError::TimedOut => ModelInterruption::TimedOut,
maka_model::ModelError::Adapter(_) => ModelInterruption::Failed,
maka_model::ModelError::ContextOverflow { .. } => ModelInterruption::Failed,
+ maka_model::ModelError::Provider(ref failure) if failure.replay_safe() => {
+ ModelInterruption::RetryableFailure
+ }
maka_model::ModelError::Provider(_) => ModelInterruption::Failed,
};
append(
diff --git a/crates/agent/src/runner.rs b/crates/agent/src/runner.rs
index 3d32859d44..d1e8ba4c94 100644
--- a/crates/agent/src/runner.rs
+++ b/crates/agent/src/runner.rs
@@ -47,7 +47,21 @@ pub async fn run(
}
Err(error) => return Err(error.into()),
}
+ let claim = match &input.work {
+ RunWork::Continuation { source, tools, .. } => {
+ Some(crate::continuation::prepare(&inner, &input, source, tools, &cancellation).await?)
+ }
+ _ => None,
+ };
+ let continuation_base = claim.as_ref().map(|claim| claim.base.high_water);
let opening = match &input.work {
+ RunWork::Continuation { .. } => InvocationInput::Continuation {
+ claim: Box::new(claim.expect("prepared continuation")),
+ request_fingerprint: input
+ .request_fingerprint
+ .clone()
+ .expect("validated continuation fingerprint"),
+ },
RunWork::Message {
message,
source_messages,
@@ -81,14 +95,25 @@ pub async fn run(
match &input.work {
RunWork::Message {
tools, max_steps, ..
- } => steps::run(&inner, &input, tools, *max_steps, &cancellation)
- .await
- .map(|()| (InvocationOutcome::Completed, None)),
+ }
+ | RunWork::Continuation {
+ tools, max_steps, ..
+ } => steps::run(
+ &inner,
+ &input,
+ tools,
+ *max_steps,
+ &cancellation,
+ continuation_base,
+ )
+ .await
+ .map(|()| (InvocationOutcome::Completed, None)),
RunWork::ContextCompact => compact::run(
&inner,
&input,
&maka_runtime::context::CheckpointMode::Standalone,
&cancellation,
+ None,
)
.await
.map(|(outcome, checkpoint)| {
diff --git a/crates/agent/src/steps.rs b/crates/agent/src/steps.rs
index 53d0272055..784f1eb4e3 100644
--- a/crates/agent/src/steps.rs
+++ b/crates/agent/src/steps.rs
@@ -30,6 +30,7 @@ pub(super) async fn run(
catalog: &maka_tools::ToolCatalog,
max_steps: usize,
cancellation: &CancellationToken,
+ continuation_base: Option<u64>,
) -> Result<(), RunError> {
let lane = maka_model::ResponsesLane::default();
let tools = RunTools::new(
@@ -57,7 +58,16 @@ pub(super) async fn run(
.await?;
if !attempted && auto_context::due(input, &source) {
attempted = true;
- if auto_context::attempt(inner, input, &source, completed_step, cancellation).await? {
+ if auto_context::attempt(
+ inner,
+ input,
+ &source,
+ completed_step,
+ cancellation,
+ continuation_base,
+ )
+ .await?
+ {
tools.clear_loaded();
}
source = inner
@@ -70,15 +80,25 @@ pub(super) async fn run(
)
.await?;
}
- let prompt =
- model_attempt::prompt(inner, input, &source, ModelPurpose::Main, cancellation).await?;
+ let prompt = model_attempt::prompt(
+ inner,
+ input,
+ &source,
+ ModelPurpose::Main,
+ cancellation,
+ continuation_base,
+ )
+ .await?;
let result = model_attempt::execute(
inner,
input,
&source,
prompt,
tools.definitions(),
- model_attempt::Attempt::Main(lane.clone()),
+ model_attempt::Attempt::Main {
+ lane: lane.clone(),
+ continuation_base,
+ },
cancellation,
)
.await;
@@ -90,8 +110,15 @@ pub(super) async fn run(
}),
) if !attempted && step + 1 < max_steps && !cancellation.is_cancelled() => {
attempted = true;
- if auto_context::attempt(inner, input, &source, completed_step, cancellation)
- .await?
+ if auto_context::attempt(
+ inner,
+ input,
+ &source,
+ completed_step,
+ cancellation,
+ continuation_base,
+ )
+ .await?
{
tools.clear_loaded();
continue;
@@ -133,9 +160,15 @@ pub(super) async fn run(
8 * 1024 * 1024,
)
.await?;
- let replay =
- model_attempt::prompt(inner, input, &source, ModelPurpose::Main, cancellation)
- .await?;
+ let replay = model_attempt::prompt(
+ inner,
+ input,
+ &source,
+ ModelPurpose::Main,
+ cancellation,
+ continuation_base,
+ )
+ .await?;
let ids: Vec<_> = local_calls.iter().map(|call| call.id.as_str()).collect();
lane.confirm(&replay, &ids, output.response_id.as_deref());
}
diff --git a/crates/agent/tests/integration/model_interruption.rs b/crates/agent/tests/integration/model_interruption.rs
index d010910e74..f6f9d534b8 100644
--- a/crates/agent/tests/integration/model_interruption.rs
+++ b/crates/agent/tests/integration/model_interruption.rs
@@ -138,7 +138,7 @@ async fn safe_retry_preserves_failed_evidence_and_cancellation_stops_backoff() {
loop {
let prefix = log.prefix(100, 128 * 1024).await.unwrap();
if prefix.events.iter().any(|event| matches!(event.event.fact,
- Fact::ModelInterrupted { status: ModelInterruption::Failed, .. })) { break; }
+ Fact::ModelInterrupted { status: ModelInterruption::RetryableFailure, .. })) { break; }
commits.changed().await.unwrap();
}
cancellation.cancel();
@@ -159,7 +159,7 @@ async fn safe_retry_preserves_failed_evidence_and_cancellation_stops_backoff() {
assert_eq!(requested.len(), requests.len());
if !cancel { assert_ne!(requested[0].0, requested[1].0); assert_eq!(requested[0].1, requested[1].1); }
assert_eq!(prefix.events.iter().filter(|event| matches!(event.event.fact,
- Fact::ModelInterrupted { status: ModelInterruption::Failed, .. })).count(), 1);
+ Fact::ModelInterrupted { status: ModelInterruption::RetryableFailure, .. })).count(), 1);
assert!(prefix.events.iter().any(|event| matches!(&event.event.fact,
Fact::ModelObserved { event: ModelEvent::PartDelta { text, .. }, .. } if text == "unfinished-secret-fragment")));
assert!(!prefix.events.iter().any(|event| matches!(event.event.fact,
@@ -168,6 +168,97 @@ async fn safe_retry_preserves_failed_evidence_and_cancellation_stops_backoff() {
}).await.expect("retry and cancellation must settle within their bounds");
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn continuation_claim_replays_only_its_lineage_and_retries_at_fresh_boundaries() {
+ use maka_runtime::{
+ continuation::RunBoundary,
+ event::{EventWrite, LogScope, RuntimeEvent},
+ input::InvocationInput,
+ };
+ tokio::time::timeout(Duration::from_secs(20), async {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let directory = tempfile::tempdir().unwrap();
+ let log = Arc::new(EventLog::open(&directory.path().join("events.sqlite")).await.unwrap());
+ let mut source = input(&base, "source");
+ source.configuration.workspace_identity = Some(
+ maka_runtime::execution::WorkspaceIdentity::from_marker_id("c193cd58-f929-4ba2-bfb5-6887beaf8132").unwrap());
+ let opening = |text: &str| Fact::InvocationOpened {
+ configuration: Some(source.configuration.clone()),
+ input: InvocationInput::Message { content: text.into(), request_fingerprint: None,
+ source_messages: Vec::new(), skill_invocation: None },
+ };
+ let route = format!("sha256:{:x}", Sha256::digest(serde_json::to_vec(&source.provider).unwrap()));
+ for fact in [
+ opening("question source"),
+ Fact::ModelRequested { step_id: "old".into(), model_id: "test".into(), purpose: None, context: None,
+ source_scope: LogScope::Session { id: "session".into() }, source_high_water: 1,
+ source_digest: "fixture".into(), input_digest: "fixture".into(), route_identity: route,
+ checkpoint_event_id: None, effective_source_digest: None },
+ Fact::ModelCompleted { step_id: "old".into(), output: serde_json::from_value(json!({
+ "parts":[{"kind":"text","text_kind":"text","text":"trimmed old tail","provider_options":null}],
+ "finish_reason":"stop","usage":{}
+ })).unwrap() },
+ Fact::InvocationEnded { outcome: InvocationOutcome::Cancelled { source: "user".into() } },
+ ] {
+ log.append(&EventWrite::plain(RuntimeEvent::new(source.invocation.clone(), fact)).unwrap()).await.unwrap();
+ }
+ let prefix = log.run_prefix("session", &source.invocation.run_id, None, 100, 128 * 1024).await.unwrap().unwrap();
+ let boundary = RunBoundary { invocation: prefix.invocation, high_water: prefix.high_water, digest: prefix.digest };
+ for fact in [opening("unrelated later branch"), Fact::InvocationEnded { outcome: InvocationOutcome::Completed }] {
+ log.append(&EventWrite::plain(RuntimeEvent::new(input(&base, "branch").invocation, fact)).unwrap()).await.unwrap();
+ }
+ let continuation = |id: &str| {
+ let mut child = input(&base, id);
+ child.configuration = source.configuration.clone();
+ child.request_fingerprint = Some(maka_runtime::artifact::content_digest(id.as_bytes()));
+ child.work = maka_agent::RunWork::Continuation { source: boundary.clone(), tools: Default::default(), max_steps: 2 };
+ child
+ };
+ let server = tokio::spawn(async move {
+ let mut requests = Vec::new();
+ for partial in [true, false] {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ requests.push(read_request(&mut socket).await);
+ respond(&mut socket, partial).await;
+ }
+ (requests, listener)
+ });
+ let worker = engine(log.clone());
+ worker.run(continuation("child"), CancellationToken::new()).await.unwrap();
+ let (requests, listener) = server.await.unwrap();
+ assert_eq!(requests[0], requests[1]);
+ let prompt = serde_json::to_string(&requests[0]["messages"]).unwrap();
+ assert!(prompt.contains("question source"));
+ for excluded in ["trimmed old tail", "unrelated later branch", "question child", "unfinished-secret-fragment"] {
+ assert!(!prompt.contains(excluded), "{excluded}: {prompt}");
+ }
+ let mut moved = continuation("moved");
+ moved.configuration.workspace_identity = None;
+ assert!(worker.run(moved, CancellationToken::new()).await.is_err());
+ assert!(worker.run(continuation("duplicate"), CancellationToken::new()).await.is_err());
+ worker.drain().await;
+ assert!(tokio::time::timeout(Duration::from_millis(20), listener.accept()).await.is_err());
+ let facts = log.prefix(100, 128 * 1024).await.unwrap();
+ let claims: Vec<_> = facts.events.iter().filter_map(|s| match &s.event.fact {
+ Fact::InvocationOpened { input: InvocationInput::Continuation { claim, .. }, .. } => Some(claim),
+ _ => None,
+ }).collect();
+ assert_eq!(claims.len(), 1, "only one canonical claim may acquire the sealed source");
+ let attempts: Vec<_> = facts.events.iter().filter_map(|s| match &s.event.fact {
+ Fact::ModelRequested { source_high_water, input_digest, .. } if s.event.invocation.run_id == "run-child" =>
+ Some((*source_high_water, input_digest)),
+ _ => None,
+ }).collect();
+ assert_eq!(attempts.len(), 2);
+ assert!(attempts[1].0 > attempts[0].0, "retry authenticates the advanced canonical cut");
+ assert_eq!(attempts[0].1, &claims[0].replay.digest);
+ assert_eq!(attempts[0].1, attempts[1].1);
+ assert_eq!(facts.events.iter().filter(|s| matches!(s.event.fact,
+ Fact::ModelInterrupted { status: ModelInterruption::RetryableFailure, .. })).count(), 1);
+ }).await.expect("continuation must settle");
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn model_timeout_cause_survives_reopening_the_log() {
tokio::time::timeout(Duration::from_secs(10), async {
diff --git a/crates/event-log/src/context/safety.rs b/crates/event-log/src/context/safety.rs
index efff50444a..21a9486946 100644
--- a/crates/event-log/src/context/safety.rs
+++ b/crates/event-log/src/context/safety.rs
@@ -72,7 +72,13 @@ pub(super) async fn require_safe_through(
WHERE json_extract(p.value, '$.kind') = 'tool_call' AND json_extract(p.value, '$.call.provider_executed') = 0
AND NOT EXISTS(SELECT 1 FROM runtime_events d WHERE d.invocation_id = e.invocation_id
AND d.operation_id = e.operation_id || ':' || json_extract(p.value, '$.call.id')
- AND d.kind IN ('tool_dispatched','tool_rejected'))))))",
+ AND d.kind IN ('tool_dispatched','tool_rejected'))))
+ OR (e.kind = 'model_completed' AND EXISTS(SELECT 1 FROM json_each(e.event_json, '$.fact.output.parts') p
+ WHERE json_extract(p.value, '$.kind') = 'tool_call' AND json_extract(p.value, '$.call.provider_executed') = 1
+ AND NOT EXISTS(SELECT 1 FROM json_each(e.event_json, '$.fact.output.parts') result
+ WHERE json_extract(result.value, '$.kind') = 'tool_result'
+ AND json_extract(result.value, '$.id') = json_extract(p.value, '$.call.id')
+ AND json_extract(result.value, '$.name') = json_extract(p.value, '$.call.name'))))))",
).bind(session).bind(current).bind(through as i64).fetch_one(&mut *connection).await?;
if unsafe_history {
return Err(invalid(
@@ -167,6 +173,15 @@ async fn execution_boundary(
AND d.operation_id = e.operation_id || ':' || json_extract(p.value, '$.call.id')
AND d.kind IN ('tool_dispatched','tool_rejected') AND d.sequence <= ?2)))
OR (e.kind = 'model_interrupted'
+ AND (json_extract(e.event_json, '$.fact.status') != 'retryable_failure'
+ OR EXISTS(SELECT 1 FROM runtime_events barrier WHERE barrier.invocation_id=e.invocation_id
+ AND json_extract(barrier.event_json, '$.fact.step_id')=e.operation_id
+ AND barrier.kind='model_observed' AND barrier.sequence <= ?2
+ AND (json_extract(barrier.event_json, '$.fact.event.kind') IN ('provider_tool_result','finished')
+ OR (json_extract(barrier.event_json, '$.fact.event.kind')='tool_call'
+ AND json_extract(barrier.event_json, '$.fact.event.data.provider_executed')=1)
+ OR (json_extract(barrier.event_json, '$.fact.event.data.provider_options') IS NOT NULL
+ AND json_extract(barrier.event_json, '$.fact.event.data.provider_options') != '{}'))))
AND NOT (?3 AND EXISTS(SELECT 1 FROM runtime_events r WHERE r.invocation_id=e.invocation_id AND r.operation_id=e.operation_id
AND r.kind='model_requested' AND json_extract(r.event_json,'$.fact.purpose')='summary')
AND NOT EXISTS(SELECT 1 FROM runtime_events o WHERE o.invocation_id=e.invocation_id
diff --git a/crates/event-log/tests/context_compaction/active_safety.rs b/crates/event-log/tests/context_compaction/active_safety.rs
index e3b17cdbfe..6f5aa19986 100644
--- a/crates/event-log/tests/context_compaction/active_safety.rs
+++ b/crates/event-log/tests/context_compaction/active_safety.rs
@@ -20,8 +20,13 @@
use super::*;
#[tokio::test]
-async fn partial_and_unsettled_provider_steps_are_not_active_cut_boundaries() {
- for provider in [false, true] {
+async fn active_cuts_require_settled_effects_or_explicit_retry_safety() {
+ for (provider, retryable, barrier, safe) in [
+ (false, false, false, false),
+ (false, true, false, true),
+ (false, true, true, false),
+ (true, false, false, false),
+ ] {
let directory = tempfile::tempdir().unwrap();
let log = EventLog::open(&directory.path().join("provider.sqlite"))
.await
@@ -50,7 +55,7 @@ async fn partial_and_unsettled_provider_steps_are_not_active_cut_boundaries() {
event: ModelEvent::PartDelta {
id: "partial".into(),
text: "visible".into(),
- provider_options: None,
+ provider_options: barrier.then(|| json!({"signature":"provider state"})),
},
},
))
@@ -60,7 +65,11 @@ async fn partial_and_unsettled_provider_steps_are_not_active_cut_boundaries() {
"active",
Fact::ModelInterrupted {
step_id: "main".into(),
- status: maka_runtime::event::ModelInterruption::Failed,
+ status: if retryable {
+ maka_runtime::event::ModelInterruption::RetryableFailure
+ } else {
+ maka_runtime::event::ModelInterruption::Failed
+ },
},
))
.await
@@ -69,11 +78,29 @@ async fn partial_and_unsettled_provider_steps_are_not_active_cut_boundaries() {
let mode = CheckpointMode::MidTurn {
anchor_event_id: anchor.event().id.clone(),
};
- assert!(
+ assert_eq!(
log.prepare_context_compaction("session", Some("active"), 100, 8192, &mode)
.await
- .is_err()
+ .is_ok(),
+ safe,
+ "a retryable classification cannot override observed replay barriers",
);
+ if provider {
+ log.append(&event(
+ "active",
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Completed,
+ },
+ ))
+ .await
+ .unwrap();
+ assert!(
+ log.read_model_context("session", None, 100, 8192)
+ .await
+ .is_err(),
+ "closing an invocation does not settle a provider tool effect",
+ );
+ }
log.close().await.unwrap();
}
}
diff --git a/crates/runtime/src/event.rs b/crates/runtime/src/event.rs
index c147e02e6f..aad562d0a9 100644
--- a/crates/runtime/src/event.rs
+++ b/crates/runtime/src/event.rs
@@ -192,6 +192,9 @@ pub enum ModelInterruption {
Cancelled,
TimedOut,
Failed,
+ /// Trusted ingress classified a transient failure with no raw replay barrier.
+ /// This records safety evidence, not an instruction to retry.
+ RetryableFailure,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
diff --git a/docs/rust-runtime.md b/docs/rust-runtime.md
index 3787e814ad..b5795b5224 100644
--- a/docs/rust-runtime.md
+++ b/docs/rust-runtime.md
@@ -94,6 +94,8 @@ Do not run untrusted code or point test instances at existing user data.
preferences and source updates without reading baselines or claiming Run advertisement.
Pages are revision-bound; Plan and Skill mutations remain unavailable.
- Rust owns storage, network routing, tools and native process/PTY lifetimes.
+ Future plugins must enter through catalogs and scoped Host services, sharing
+ journaled effects, permissions and draining rather than replacing the Engine.
One lazy, long-lived V8 serves concurrent model requests and terminal parsers.
Code Mode cells use separate short-lived isolates. Count and byte limits provide
backpressure; V8 heap limits are not process-memory containment.
@@ -153,4 +155,5 @@ Skill mutations and update previews,
safe resume/reconciliation, orchestration,
some capability services, managed upgrades and other protocol domains remain incomplete. Full Desktop
acceptance and release packaging across Linux, macOS and Windows are still
-required. Plugins and OS sandboxing are deferred; content redaction is omitted.
+required. Plugins and OS sandboxing are deferred. Memory is excluded pending a
+separate redesign; its existing implementation is not ported. Content redaction is omitted.
diff --git a/docs/rust-runtime.zh-CN.md b/docs/rust-runtime.zh-CN.md
index dda36ce8f3..c773520f3b 100644
--- a/docs/rust-runtime.zh-CN.md
+++ b/docs/rust-runtime.zh-CN.md
@@ -83,6 +83,7 @@ Windows 使用私有 named pipe。可选 `--websocket 127.0.0.1:0` 监听需要
- Rust 管理存储、网络路由、工具和原生进程/PTY。一个惰性启动的长期 V8 并发处理模型
请求与终端解析;Code Mode 使用独立短生命周期 isolate。数量与字节限制提供背压,
V8 heap 限制不等于进程内存隔离。
+- 插件后续须通过目录注册和有作用域的 Host 服务接入,复用日志、权限与排空机制,不替换 Engine。
- Code Mode 限制累计 VM 执行时间,不计异步工具等待或收尾时间。
- 请求的代理策略同时覆盖 HTTP 与 Responses WebSocket。WS 握手失败后指数退避重试
5 次,再经同一网络策略降级 HTTP。主模型请求另对已识别的临时 provider 故障最多尝试
@@ -130,4 +131,4 @@ Grep 差分测试需要 PATH 中有 `rg`;runtime 本身不依赖该可执行
Skills 变更与更新预览、安全 resume/恢复协调、
编排、部分 capability 服务、受管升级及其它协议域
仍未完成。完整 Desktop 验收和 Linux、macOS、Windows 发布打包仍待完成。
-插件与 OS 沙箱暂缓,内容脱敏不实现。
+插件与 OS 沙箱暂缓;Memory 留待单独重做,不移植旧实现,也不纳入本次重写。内容脱敏不实现。
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org