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/16 01:18:25 UTC
(maka) 06/29: feat(runtime-host): cancel sealed handoffs without provider recovery
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
commit d046fbf3b55d9f957850b075bb5402465001ead4
Author: Wang <m4...@gmail.com>
AuthorDate: Tue Sep 15 14:32:35 2026 +0800
feat(runtime-host): cancel sealed handoffs without provider recovery
Freeze successor admission evidence before sealing and independently verify it at continuation. Claim and cancel an unowned pause atomically, preserving public identity and reserving terminal capacity.
Generated-by: Codex
---
crates/agent/src/cancellation.rs | 24 +--
crates/agent/src/compact.rs | 1 +
crates/agent/src/continuation.rs | 54 +++--
crates/agent/src/handoff.rs | 6 +-
crates/agent/src/lib.rs | 3 +-
crates/agent/src/model_attempt.rs | 4 +-
crates/agent/src/steps.rs | 34 +++-
crates/agent/tests/integration/handoff.rs | 42 +++-
crates/event-log/src/context/frozen.rs | 24 ++-
crates/event-log/src/handoff.rs | 1 +
crates/event-log/src/handoff/budget.rs | 39 +++-
crates/event-log/src/handoff/cancel.rs | 116 +++++++++++
crates/event-log/tests/continuation.rs | 2 +
crates/event-log/tests/continuation/handoff.rs | 6 +-
.../event-log/tests/continuation/handoff_budget.rs | 9 +-
.../event-log/tests/continuation/handoff_cancel.rs | 190 ++++++++++++++++++
crates/presentation/tests/projection.rs | 6 +-
crates/runtime-host/src/execution.rs | 27 ++-
crates/runtime-host/tests/integration/handoff.rs | 222 +++++++++++++++++++++
crates/runtime-host/tests/integration/main.rs | 1 +
crates/runtime/src/continuation.rs | 17 +-
crates/runtime/src/event.rs | 19 ++
crates/runtime/src/handoff.rs | 2 +-
crates/runtime/src/handoff/execution.rs | 7 +-
docs/rust-runtime.md | 1 +
docs/rust-runtime.zh-CN.md | 1 +
26 files changed, 781 insertions(+), 77 deletions(-)
diff --git a/crates/agent/src/cancellation.rs b/crates/agent/src/cancellation.rs
index 782ea6e502..061048b18c 100644
--- a/crates/agent/src/cancellation.rs
+++ b/crates/agent/src/cancellation.rs
@@ -17,17 +17,10 @@
* under the License.
*/
-use maka_runtime::workhub::ActionId;
+pub use maka_runtime::event::CancellationCause;
use std::sync::{Arc, Mutex};
use tokio_util::sync::CancellationToken;
-#[derive(Clone, Debug)]
-pub enum CancellationCause {
- Runtime,
- WorkhubStop { action_id: ActionId },
- WorkhubCorrection { action_id: ActionId },
-}
-
#[derive(Clone)]
pub struct RunCancellation {
token: CancellationToken,
@@ -69,15 +62,12 @@ impl RunCancellation {
}
pub(crate) fn source(&self) -> String {
- match self.cause.lock().unwrap().as_ref() {
- Some(CancellationCause::WorkhubCorrection { action_id }) => {
- maka_runtime::workhub::correction_abort_source(action_id)
- }
- Some(CancellationCause::WorkhubStop { action_id }) => {
- maka_runtime::workhub::stop_abort_source(action_id)
- }
- Some(CancellationCause::Runtime) | None => "runtime_cancellation".into(),
- }
+ self.cause
+ .lock()
+ .unwrap()
+ .as_ref()
+ .unwrap_or(&CancellationCause::Runtime)
+ .source()
}
}
diff --git a/crates/agent/src/compact.rs b/crates/agent/src/compact.rs
index d3b8c4da1c..5749bf4b07 100644
--- a/crates/agent/src/compact.rs
+++ b/crates/agent/src/compact.rs
@@ -84,6 +84,7 @@ pub(super) async fn run(
ModelPurpose::Summary,
cancellation,
continuation_base,
+ &input.invocation.invocation_id,
)
.await?;
let base = format!(
diff --git a/crates/agent/src/continuation.rs b/crates/agent/src/continuation.rs
index e67220a27f..587e16a710 100644
--- a/crates/agent/src/continuation.rs
+++ b/crates/agent/src/continuation.rs
@@ -153,20 +153,9 @@ pub(super) async fn inspect(
crate::RunWork::Handoff { pause, .. } => pause.execution.replay_base,
_ => Some(base.high_water),
},
+ &input.invocation.invocation_id,
)
.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(),
@@ -201,18 +190,43 @@ pub(super) async fn inspect(
}
}
}
+ let replay = replay(input, prompt, definitions, cancellation)?;
+ if let crate::RunWork::Handoff { pause, .. } = &input.work
+ && replay != pause.execution.replay
+ {
+ return Err(invalid("handoff admission replay changed after sealing"));
+ }
+ Ok((base, replay))
+}
+
+/// Shared by reversible handoff preparation and independently verified admission.
+pub(super) fn replay(
+ input: &RunInput,
+ prompt: Vec<Message>,
+ definitions: Vec<maka_model::ToolDefinition>,
+ cancellation: &CancellationToken,
+) -> Result<ReplayEvidence, RunError> {
+ 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 request = model_attempt::prepare_request(input, prompt, definitions, ModelPurpose::Main)?;
if cancellation.is_cancelled() {
return Err(RunError::Cancelled);
}
- Ok((
- base,
- ReplayEvidence {
- version: REPLAY_VERSION,
- digest: request.input_digest,
- route_identity: request.route_identity,
- },
- ))
+ Ok(ReplayEvidence {
+ version: REPLAY_VERSION,
+ digest: request.input_digest,
+ route_identity: request.route_identity,
+ })
}
fn invalid(reason: &str) -> RunError {
diff --git a/crates/agent/src/handoff.rs b/crates/agent/src/handoff.rs
index 7c0f0ad891..45256964db 100644
--- a/crates/agent/src/handoff.rs
+++ b/crates/agent/src/handoff.rs
@@ -256,7 +256,11 @@ mod tests {
intent,
remaining_steps: std::num::NonZeroU16::new(2).unwrap(),
execution: Box::new(HandoffExecution {
- route_identity: format!("sha256:{}", "b".repeat(64)),
+ replay: maka_runtime::continuation::ReplayEvidence {
+ version: maka_runtime::continuation::REPLAY_VERSION,
+ digest: format!("sha256:{}", "a".repeat(64)),
+ route_identity: format!("sha256:{}", "b".repeat(64)),
+ },
context: None,
provider_options: serde_json::json!({}),
main_output_limit: None,
diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs
index 7003fc2dcf..6a1a5436b8 100644
--- a/crates/agent/src/lib.rs
+++ b/crates/agent/src/lib.rs
@@ -198,7 +198,8 @@ impl Engine {
|| input.provider_options != pause.execution.provider_options
|| input.main_output_limit != pause.execution.main_output_limit
|| input.supports_vision != pause.execution.supports_vision
- || model_attempt::route_identity(&input)? != pause.execution.route_identity
+ || model_attempt::route_identity(&input)?
+ != pause.execution.replay.route_identity
{
return Err(RunError::InvalidInput(
"handoff execution settings changed".into(),
diff --git a/crates/agent/src/model_attempt.rs b/crates/agent/src/model_attempt.rs
index c79a585e95..e905636524 100644
--- a/crates/agent/src/model_attempt.rs
+++ b/crates/agent/src/model_attempt.rs
@@ -49,11 +49,12 @@ pub(super) async fn prompt(
purpose: ModelPurpose,
cancellation: &CancellationToken,
continuation_base: Option<u64>,
+ current: &str,
) -> Result<Vec<Message>, RunError> {
let route = route_identity(input)?;
let replay = continuation_base.map(|base| history::Replay {
base,
- current: &input.invocation.invocation_id,
+ current,
route: &route,
model: &input.provider.model,
});
@@ -176,6 +177,7 @@ pub(super) async fn execute(
ModelPurpose::Main,
cancellation,
continuation_base,
+ &input.invocation.invocation_id,
)
.await?;
if replay != prompt {
diff --git a/crates/agent/src/steps.rs b/crates/agent/src/steps.rs
index 5ee315a11e..4360e39dd1 100644
--- a/crates/agent/src/steps.rs
+++ b/crates/agent/src/steps.rs
@@ -56,12 +56,42 @@ pub(super) async fn run(
inner.log.commit_pending_steering(&input.invocation).await?;
if let Some(pause) = handoff
.boundary(cancellation, |intent| async {
+ let source = inner
+ .log
+ .read_model_context(
+ &input.invocation.session_id,
+ Some(&input.invocation.invocation_id),
+ 10_000,
+ 8 * 1024 * 1024,
+ )
+ .await
+ .ok()?;
+ // Read the live source, but project from the successor's point of
+ // view: manual replay cuts distinguish current from inherited work.
+ let prompt = model_attempt::prompt(
+ inner,
+ input,
+ &source,
+ ModelPurpose::Main,
+ cancellation,
+ continuation_base,
+ &intent.successor_invocation_id,
+ )
+ .await
+ .ok()?;
+ let replay = crate::continuation::replay(
+ input,
+ prompt,
+ tools.capture().definitions(),
+ cancellation,
+ )
+ .ok()?;
let pause = maka_runtime::handoff::HandoffPause {
intent,
remaining_steps: std::num::NonZeroU16::new((max_steps - step) as u16)
.expect("validated step budget"),
execution: Box::new(maka_runtime::handoff::HandoffExecution {
- route_identity: model_attempt::route_identity(input).ok()?,
+ replay,
context: input.context.clone(),
provider_options: input.provider_options.clone(),
main_output_limit: input.main_output_limit,
@@ -126,6 +156,7 @@ pub(super) async fn run(
ModelPurpose::Main,
cancellation,
continuation_base,
+ &input.invocation.invocation_id,
)
.await?;
let result = model_attempt::execute(
@@ -206,6 +237,7 @@ pub(super) async fn run(
ModelPurpose::Main,
cancellation,
continuation_base,
+ &input.invocation.invocation_id,
)
.await?;
let ids: Vec<_> = local_calls.iter().map(|call| call.id.as_str()).collect();
diff --git a/crates/agent/tests/integration/handoff.rs b/crates/agent/tests/integration/handoff.rs
index cfb824ffd3..dd03bb220b 100644
--- a/crates/agent/tests/integration/handoff.rs
+++ b/crates/agent/tests/integration/handoff.rs
@@ -26,7 +26,7 @@ use maka_event_log::EventLog;
use maka_js_runtime::{CellLimits, CodeExecutor};
use maka_model::ModelExecutor;
use maka_runtime::{
- event::{Fact, InvocationOutcome, TerminalStatus},
+ event::{EventWrite, Fact, InvocationInput, InvocationOutcome, RuntimeEvent, TerminalStatus},
handoff::HandoffIntent,
};
use std::{
@@ -53,7 +53,8 @@ fn intent(id: &str) -> HandoffIntent {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn handoff_waits_for_settlement_rollback_keeps_run_and_seal_survives_reopen() {
- tokio::time::timeout(Duration::from_secs(20), async {
+ for manual in [false, true] {
+ tokio::time::timeout(Duration::from_secs(20), async {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("events.sqlite");
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -88,6 +89,36 @@ async fn handoff_waits_for_settlement_rollback_keeps_run_and_seal_survives_reope
run.configuration.workspace_identity = Some(maka_runtime::execution::WorkspaceIdentity::from_marker_id(
"ef751105-55b5-4d65-a364-646281586a17").unwrap());
run.main_output_limit = Some(120);
+ if manual {
+ run.request_fingerprint = Some(maka_runtime::artifact::content_digest(b"manual-resume"));
+ let mut source = run.invocation.clone();
+ source.turn_id = "turn-source".into();
+ source.run_id = "run-source".into();
+ source.invocation_id = "invocation-source".into();
+ for (invocation, text) in [(source.clone(), "question source"), ({
+ let mut branch = source.clone();
+ branch.turn_id = "turn-branch".into();
+ branch.run_id = "run-branch".into();
+ branch.invocation_id = "invocation-branch".into();
+ branch
+ }, "unrelated branch")] {
+ for fact in [
+ Fact::InvocationOpened { configuration: Some(run.configuration.clone()),
+ input: InvocationInput::Message { content: text.into(), request_fingerprint: None,
+ source_messages: Vec::new(), skill_invocation: None } },
+ Fact::InvocationEnded { outcome: InvocationOutcome::Cancelled { source: "user".into() } },
+ ] {
+ log.append(&EventWrite::plain(RuntimeEvent::new(invocation.clone(), fact)).unwrap()).await.unwrap();
+ }
+ }
+ let prefix = log.run_prefix("session", &source.run_id, None, 100, 128 * 1024).await.unwrap().unwrap();
+ let maka_agent::RunWork::Message { tools, max_steps, .. } = run.work else { unreachable!() };
+ run.work = maka_agent::RunWork::Continuation {
+ source: maka_runtime::continuation::RunBoundary {
+ invocation: source, high_water: prefix.high_water, digest: prefix.digest,
+ }, workhub_resume: None, tools, max_steps,
+ };
+ }
let configuration = run.configuration.clone();
let running = engine.start(run, CancellationToken::new()).await.unwrap();
first.await.unwrap();
@@ -111,6 +142,7 @@ async fn handoff_waits_for_settlement_rollback_keeps_run_and_seal_survives_reope
let held = next.ready().await.unwrap();
assert_eq!(held.preview().remaining_steps.get(), 1);
let expected = held.preview().clone();
+ assert_eq!(expected.execution.replay_base.is_some(), manual);
let receipt = held.commit().unwrap().wait().await.unwrap();
assert_eq!(receipt, expected);
running.wait().await.unwrap();
@@ -119,7 +151,7 @@ async fn handoff_waits_for_settlement_rollback_keeps_run_and_seal_survives_reope
assert!(tokio::time::timeout(Duration::from_millis(30), &mut third).await.is_err(),
"no model request follows the committed hold");
let before = log.prefix(100, 128 * 1024).await.unwrap();
- assert_eq!(before.events.iter().filter(|e| matches!(e.event.fact, Fact::InvocationOpened { .. })).count(), 1);
+ assert_eq!(before.events.iter().filter(|e| matches!(e.event.fact, Fact::InvocationOpened { .. })).count(), if manual { 3 } else { 1 });
assert!(matches!(&before.events.last().unwrap().event.fact,
Fact::InvocationEnded { outcome: InvocationOutcome::HandoffPaused { pause } } if pause == &expected));
let effect = Arc::new(Effect { log: log.clone(), count: count.clone() });
@@ -176,10 +208,14 @@ async fn handoff_waits_for_settlement_rollback_keeps_run_and_seal_survives_reope
let messages = requests[2]["messages"].as_array().unwrap();
assert_eq!(messages.iter().filter(|m| m["role"] == "user").count(), 1);
assert_eq!(messages.iter().filter(|m| m["role"] == "tool").count(), 2);
+ let prompt = serde_json::to_string(messages).unwrap();
+ assert!(prompt.contains(if manual { "question source" } else { "question first" }));
+ assert!(!prompt.contains("unrelated branch"));
assert_eq!(count.load(Ordering::SeqCst), 1, "settled effects are replayed as facts, never executed");
let finished = reopened.prefix(100, 128 * 1024).await.unwrap();
assert_eq!(finished.project_invocation("invocation-committed").terminal, Some(TerminalStatus::Completed));
assert!(!serde_json::to_string(&finished.events).unwrap().contains("do-not-persist-this-secret"));
reopened.shutdown().await.unwrap();
}).await.unwrap();
+ }
}
diff --git a/crates/event-log/src/context/frozen.rs b/crates/event-log/src/context/frozen.rs
index f20581d3c3..7a2fa46e33 100644
--- a/crates/event-log/src/context/frozen.rs
+++ b/crates/event-log/src/context/frozen.rs
@@ -195,15 +195,23 @@ pub(crate) async fn verify_base(
opening_sequence: u64,
expected: &maka_runtime::continuation::SessionBase,
) -> Result<(), StoreError> {
- let session = &invocation.session_id;
- let through = evidence::high_water(connection, session, opening_sequence as i64).await?;
- if through != expected.high_water
- || evidence::evidence(connection, session, through)
- .await?
- .digest
- != expected.digest
- {
+ if fresh_base(connection, invocation, opening_sequence).await? != *expected {
return Err(invalid("continuation's fresh Session base changed"));
}
Ok(())
}
+
+pub(crate) async fn fresh_base(
+ connection: &mut SqliteConnection,
+ invocation: &Invocation,
+ opening_sequence: u64,
+) -> Result<maka_runtime::continuation::SessionBase, StoreError> {
+ let session = &invocation.session_id;
+ let through = evidence::high_water(connection, session, opening_sequence as i64).await?;
+ Ok(maka_runtime::continuation::SessionBase {
+ high_water: through,
+ digest: evidence::evidence(connection, session, through)
+ .await?
+ .digest,
+ })
+}
diff --git a/crates/event-log/src/handoff.rs b/crates/event-log/src/handoff.rs
index d2d8e17e8d..897c1307ac 100644
--- a/crates/event-log/src/handoff.rs
+++ b/crates/event-log/src/handoff.rs
@@ -22,6 +22,7 @@ use maka_runtime::event::{Fact, InvocationInput, InvocationOutcome, RuntimeEvent
use sqlx::{Connection, SqliteConnection};
mod budget;
+mod cancel;
impl EventLog {
/// Eligibility only. The source still owns execution until its seal commits.
diff --git a/crates/event-log/src/handoff/budget.rs b/crates/event-log/src/handoff/budget.rs
index 73a92af124..f2ebf099c8 100644
--- a/crates/event-log/src/handoff/budget.rs
+++ b/crates/event-log/src/handoff/budget.rs
@@ -20,10 +20,9 @@
use crate::StoreError;
use maka_runtime::{
continuation::{
- ContinuationClaim, MAX_SOURCE_BYTES, MAX_SOURCE_EVENTS, REPLAY_VERSION, ReplayEvidence,
- RunBoundary, SessionBase,
+ ContinuationClaim, MAX_SOURCE_BYTES, MAX_SOURCE_EVENTS, RunBoundary, SessionBase,
},
- event::{Fact, InvocationInput, RuntimeEvent},
+ event::{CancellationCause, Fact, InvocationInput, InvocationOutcome, RuntimeEvent},
handoff::HandoffPause,
};
use sqlx::SqliteConnection;
@@ -53,7 +52,7 @@ pub(super) async fn check(
));
};
// Sizing only: no claim is acquired and no guessed proof is persisted.
- // Reserve the widest ordinals, fixed-width digests and both new envelopes.
+ // Reserve both new envelopes and room to cancel the successor immediately.
let digest = format!("sha256:{}", "0".repeat(64));
let successor = RuntimeEvent::new(
pause.intent.successor(&seal.invocation),
@@ -72,19 +71,37 @@ pub(super) async fn check(
high_water: u64::MAX,
digest: digest.clone(),
},
- replay: ReplayEvidence {
- version: REPLAY_VERSION,
- digest,
- route_identity: pause.execution.route_identity.clone(),
- },
+ replay: pause.execution.replay.clone(),
}),
},
},
);
+ // Attribution strings are fixed prefixes plus fixed-width digests, regardless
+ // of the action ID. Size every supported cause, never a guessed byte allowance.
+ let action_id = maka_runtime::workhub::ActionId::new(pause.intent.claim_id.clone())
+ .map_err(super::invalid)?;
+ let mut cancelled_bytes = 0;
+ for cause in [
+ CancellationCause::Runtime,
+ CancellationCause::WorkhubStop {
+ action_id: action_id.clone(),
+ },
+ CancellationCause::WorkhubCorrection { action_id },
+ ] {
+ let cancelled = RuntimeEvent::new(
+ successor.invocation.clone(),
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Cancelled {
+ source: cause.source(),
+ },
+ },
+ );
+ cancelled_bytes = cancelled_bytes.max(envelope_bytes(&cancelled)?);
+ }
let bytes = MAX_SOURCE_BYTES
- .checked_sub(seal_bytes + envelope_bytes(&successor)?)
+ .checked_sub(seal_bytes + envelope_bytes(&successor)? + cancelled_bytes)
.ok_or(StoreError::PrefixTooLarge)?;
- crate::context::read::check_handoff_capacity(tx, opening, MAX_SOURCE_EVENTS - 2, bytes).await
+ crate::context::read::check_handoff_capacity(tx, opening, MAX_SOURCE_EVENTS - 3, bytes).await
}
fn envelope_bytes(event: &RuntimeEvent) -> Result<usize, StoreError> {
diff --git a/crates/event-log/src/handoff/cancel.rs b/crates/event-log/src/handoff/cancel.rs
new file mode 100644
index 0000000000..b6d71bc707
--- /dev/null
+++ b/crates/event-log/src/handoff/cancel.rs
@@ -0,0 +1,116 @@
+/*
+ * 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::{EventLog, StoreError, turns::TurnBoundary};
+use maka_runtime::{
+ continuation::{ContinuationClaim, MAX_SOURCE_BYTES, MAX_SOURCE_EVENTS, RunBoundary},
+ event::{
+ CancellationCause, EventWrite, Fact, Invocation, InvocationInput, InvocationOutcome,
+ RuntimeEvent,
+ },
+};
+use sqlx::Connection;
+
+impl EventLog {
+ /// Settle an unclaimed seal without loading a provider or replaying effects.
+ /// If another actor already claimed it, return the current physical owner;
+ /// stopping that live execution remains the caller's responsibility.
+ pub async fn cancel_handoff(
+ &self,
+ source: &Invocation,
+ cause: CancellationCause,
+ ) -> Result<TurnBoundary, StoreError> {
+ self.validate_root()?;
+ for id in [
+ &source.session_id,
+ &source.turn_id,
+ &source.run_id,
+ &source.invocation_id,
+ ] {
+ crate::sessions::validate_id(id)?;
+ }
+ let source = source.clone();
+ let commits = self.commits.clone();
+ self.connection.run(move |connection| Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ let prefix = crate::run_prefix::read(
+ &mut tx, &source.session_id, &source.run_id, &source.invocation_id,
+ i64::MAX, MAX_SOURCE_EVENTS, MAX_SOURCE_BYTES,
+ ).await?;
+ if prefix.invocation != source {
+ return Err(super::invalid("handoff cancellation source changed"));
+ }
+ let Some(seal) = prefix.events.last() else {
+ return Err(super::invalid("handoff cancellation source is missing"));
+ };
+ let Fact::InvocationEnded { outcome: InvocationOutcome::HandoffPaused { pause } } = &seal.event.fact else {
+ return Err(super::invalid("handoff cancellation requires a sealed pause"));
+ };
+ let claimed: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM runtime_events WHERE invocation_id=? AND kind='invocation_opened')"
+ ).bind(&pause.intent.successor_invocation_id).fetch_one(&mut *tx).await?;
+ if claimed {
+ return crate::turns::read(&mut tx, &source.session_id, Some(&source.turn_id)).await?
+ .ok_or_else(|| super::invalid("claimed handoff has no Turn"));
+ }
+ let opening = prefix.events.first().expect("checked nonempty prefix");
+ let Fact::InvocationOpened { input, configuration: Some(configuration) } = &opening.event.fact else {
+ return Err(super::invalid("handoff source has no admitted configuration"));
+ };
+ let base = match input {
+ InvocationInput::Message { .. } => {
+ crate::context::frozen::fresh_base(&mut tx, &source, opening.sequence).await?
+ }
+ InvocationInput::Handoff { claim, .. } | InvocationInput::Continuation { claim, .. } => claim.base.clone(),
+ _ => return Err(super::invalid("handoff source is not a model Run")),
+ };
+ let invocation = pause.intent.successor(&source);
+ let opening = RuntimeEvent::new(invocation.clone(), Fact::InvocationOpened {
+ configuration: Some(configuration.clone()),
+ input: InvocationInput::Handoff {
+ pause: Box::new(pause.clone()),
+ claim: Box::new(ContinuationClaim {
+ id: pause.intent.claim_id.clone(),
+ source: RunBoundary { invocation: source, high_water: prefix.high_water, digest: prefix.digest },
+ base,
+ replay: pause.execution.replay.clone(),
+ }),
+ },
+ });
+ let writes = [
+ EventWrite::plain(opening.clone()),
+ EventWrite::plain(RuntimeEvent::new(invocation, Fact::InvocationEnded {
+ outcome: InvocationOutcome::Cancelled { source: cause.source() },
+ })),
+ ].into_iter().collect::<Result<Vec<_>, _>>().map_err(|e| super::invalid(&e.to_string()))?;
+ let mut last = 0;
+ for write in &writes {
+ last = match EventLog::append_in_transaction(&mut tx, write).await? {
+ crate::append::AppendResult::Existing(sequence)
+ | crate::append::AppendResult::Inserted(sequence) => sequence,
+ };
+ }
+ crate::context::validate_batch(&mut tx, &writes).await?;
+ let boundary = crate::turns::project(&mut tx, opening).await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)?;
+ commits.send_replace(last);
+ Ok(boundary)
+ })).await
+ }
+}
diff --git a/crates/event-log/tests/continuation.rs b/crates/event-log/tests/continuation.rs
index c150636d9b..50f4f02cd9 100644
--- a/crates/event-log/tests/continuation.rs
+++ b/crates/event-log/tests/continuation.rs
@@ -35,6 +35,8 @@ mod fixtures;
mod handoff;
#[path = "continuation/handoff_budget.rs"]
mod handoff_budget;
+#[path = "continuation/handoff_cancel.rs"]
+mod handoff_cancel;
#[path = "continuation/handoff_claim.rs"]
mod handoff_claim;
#[path = "continuation/handoff_consumers.rs"]
diff --git a/crates/event-log/tests/continuation/handoff.rs b/crates/event-log/tests/continuation/handoff.rs
index c8ebd3efef..b1ba90ccac 100644
--- a/crates/event-log/tests/continuation/handoff.rs
+++ b/crates/event-log/tests/continuation/handoff.rs
@@ -29,7 +29,11 @@ use std::num::NonZeroU16;
pub(super) fn execution() -> Box<maka_runtime::handoff::HandoffExecution> {
use maka_runtime::handoff::{HandoffExecution, HandoffTools};
Box::new(HandoffExecution {
- route_identity: digest('b'),
+ replay: ReplayEvidence {
+ version: REPLAY_VERSION,
+ digest: digest('a'),
+ route_identity: digest('b'),
+ },
context: None,
provider_options: serde_json::json!({}),
main_output_limit: None,
diff --git a/crates/event-log/tests/continuation/handoff_budget.rs b/crates/event-log/tests/continuation/handoff_budget.rs
index 40f7a813d9..4534cb51b7 100644
--- a/crates/event-log/tests/continuation/handoff_budget.rs
+++ b/crates/event-log/tests/continuation/handoff_budget.rs
@@ -29,7 +29,7 @@ use std::{
};
#[tokio::test]
-async fn handoff_reserves_both_envelopes_before_sealing_a_near_capacity_context() {
+async fn handoff_reserves_successor_and_cancellation_before_sealing_a_near_capacity_context() {
for reserve_successor in [false, true] {
let directory = tempfile::tempdir().unwrap();
let log = EventLog::open(&directory.path().join("capacity.sqlite"))
@@ -110,6 +110,13 @@ async fn handoff_reserves_both_envelopes_before_sealing_a_near_capacity_context(
});
if reserve_successor {
reserved_bytes += serde_json::to_vec(&future).unwrap().len();
+ let mut cancelled = future.clone();
+ cancelled["fact"] = serde_json::json!({"kind":"invocation_ended", "outcome":{
+ "kind":"cancelled", "source": maka_runtime::event::CancellationCause::WorkhubCorrection {
+ action_id: pause.intent.claim_id.parse().unwrap(),
+ }.source(),
+ }});
+ reserved_bytes += serde_json::to_vec(&cancelled).unwrap().len();
}
let mut completed = RuntimeEvent::new(
source.invocation.clone(),
diff --git a/crates/event-log/tests/continuation/handoff_cancel.rs b/crates/event-log/tests/continuation/handoff_cancel.rs
new file mode 100644
index 0000000000..509c40d3db
--- /dev/null
+++ b/crates/event-log/tests/continuation/handoff_cancel.rs
@@ -0,0 +1,190 @@
+/*
+ * 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::*;
+use maka_event_log::turns::InvocationState;
+use maka_runtime::{
+ event::CancellationCause,
+ handoff::{HandoffIntent, HandoffPause},
+};
+use std::num::NonZeroU16;
+
+#[tokio::test]
+async fn paused_cancellation_claim_is_atomic_idempotent_and_never_cancels_an_existing_owner() {
+ for already_claimed in [false, true] {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("events.sqlite");
+ let log = EventLog::open(&path).await.unwrap();
+ let source = opening("source", None);
+ append(&log, &source).await;
+ let before = log
+ .context_before_run(&source.invocation, 100, 65536)
+ .await
+ .unwrap();
+ let pause = HandoffPause {
+ intent: HandoffIntent {
+ handoff_id: "handoff".into(),
+ host_epoch: "host".into(),
+ root_run_id: source.invocation.run_id.clone(),
+ successor_run_id: "next-run".into(),
+ successor_invocation_id: "next-invocation".into(),
+ claim_id: "claim".into(),
+ },
+ remaining_steps: NonZeroU16::new(2).unwrap(),
+ execution: super::handoff::execution(),
+ };
+ append(
+ &log,
+ &RuntimeEvent::new(
+ source.invocation.clone(),
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::HandoffPaused {
+ pause: pause.clone(),
+ },
+ },
+ ),
+ )
+ .await;
+ let frozen = log
+ .run_prefix("session", "source", None, 100, 65536)
+ .await
+ .unwrap()
+ .unwrap();
+ if already_claimed {
+ let mut target = opening("unused", None);
+ target.invocation = pause.intent.successor(&source.invocation);
+ let Fact::InvocationOpened { input, .. } = &mut target.fact else {
+ unreachable!()
+ };
+ *input = InvocationInput::Handoff {
+ claim: Box::new(
+ claim(
+ &log,
+ "claim",
+ &source,
+ SessionBase {
+ high_water: before.source_evidence.high_water,
+ digest: before.source_evidence.digest,
+ },
+ )
+ .await,
+ ),
+ pause: Box::new(pause.clone()),
+ };
+ append(&log, &target).await;
+ let before = log.prefix(100, 65536).await.unwrap();
+ let result = log
+ .cancel_handoff(&source.invocation, CancellationCause::Runtime)
+ .await
+ .unwrap();
+ assert_eq!(result.invocation, target.invocation);
+ assert!(
+ !matches!(result.state, InvocationState::Ended { .. }),
+ "the existing worker still owns cancellation"
+ );
+ assert_eq!(log.prefix(100, 65536).await.unwrap().digest, before.digest);
+ close(&log, &target).await;
+ } else {
+ let database = rusqlite::Connection::open(&path).unwrap();
+ database.execute_batch(
+ "CREATE TRIGGER reject_cancel BEFORE INSERT ON event_log
+ WHEN NEW.kind='invocation_ended' AND json_extract(NEW.event_json,'$.fact.outcome.kind')='cancelled'
+ BEGIN SELECT RAISE(ABORT, 'cancel fault'); END;"
+ ).unwrap();
+ let before = log.prefix(100, 65536).await.unwrap();
+ assert!(
+ log.cancel_handoff(&source.invocation, CancellationCause::Runtime)
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ log.prefix(100, 65536).await.unwrap().digest,
+ before.digest,
+ "failed terminal must roll back its opening and claim"
+ );
+ database
+ .execute_batch("DROP TRIGGER reject_cancel")
+ .unwrap();
+ let (first, retry) = tokio::join!(
+ log.cancel_handoff(&source.invocation, CancellationCause::Runtime),
+ log.cancel_handoff(
+ &source.invocation,
+ CancellationCause::WorkhubStop {
+ action_id: "stop".parse().unwrap()
+ }
+ ),
+ );
+ let first = first.unwrap();
+ let retry = retry.unwrap();
+ assert_eq!(first.invocation, pause.intent.successor(&source.invocation));
+ assert_eq!(first.root_invocation(), &source.invocation);
+ assert_eq!(first.invocation, retry.invocation);
+ let InvocationState::Ended { event_id, outcome } = first.state else {
+ panic!("cancellation did not settle")
+ };
+ let InvocationState::Ended {
+ event_id: retried_id,
+ outcome: retried_outcome,
+ } = retry.state
+ else {
+ panic!("retry lost cancellation")
+ };
+ assert_eq!(event_id, retried_id);
+ assert_eq!(
+ outcome, retried_outcome,
+ "the first cancellation retains its attribution"
+ );
+ assert!(matches!(outcome, InvocationOutcome::Cancelled { .. }));
+ let prefix = log
+ .run_prefix("session", "next-run", None, 100, 65536)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ prefix.events.len(),
+ 2,
+ "cancel requires neither model request nor tool dispatch"
+ );
+ }
+ assert_eq!(
+ log.run_prefix("session", "source", None, 100, 65536)
+ .await
+ .unwrap()
+ .unwrap()
+ .digest,
+ frozen.digest
+ );
+ let later = opening("later-turn", None);
+ append(&log, &later).await;
+ close(&log, &later).await;
+ let before = log.prefix(100, 65536).await.unwrap().digest;
+ log.close().await.unwrap();
+ let log = EventLog::open(&path).await.unwrap();
+ let replay = log
+ .cancel_handoff(&source.invocation, CancellationCause::Runtime)
+ .await
+ .unwrap();
+ assert_eq!(
+ replay.invocation.turn_id, source.invocation.turn_id,
+ "a later Session Turn is not the claim owner"
+ );
+ assert_eq!(log.prefix(100, 65536).await.unwrap().digest, before);
+ log.close().await.unwrap();
+ }
+}
diff --git a/crates/presentation/tests/projection.rs b/crates/presentation/tests/projection.rs
index 4d7c61b01d..eec3ed42aa 100644
--- a/crates/presentation/tests/projection.rs
+++ b/crates/presentation/tests/projection.rs
@@ -173,7 +173,11 @@ fn completed_and_interrupted_rows_keep_overlay_identity_time_and_original_decode
},
remaining_steps: std::num::NonZeroU16::new(2).unwrap(),
execution: Box::new(maka_runtime::handoff::HandoffExecution {
- route_identity: format!("sha256:{}", "b".repeat(64)),
+ replay: maka_runtime::continuation::ReplayEvidence {
+ version: maka_runtime::continuation::REPLAY_VERSION,
+ digest: format!("sha256:{}", "a".repeat(64)),
+ route_identity: format!("sha256:{}", "b".repeat(64)),
+ },
context: None,
provider_options: serde_json::json!({}),
main_output_limit: None,
diff --git a/crates/runtime-host/src/execution.rs b/crates/runtime-host/src/execution.rs
index 45b5407009..9078f25bea 100644
--- a/crates/runtime-host/src/execution.rs
+++ b/crates/runtime-host/src/execution.rs
@@ -186,11 +186,32 @@ impl Executions {
.await
.map_err(internal)?
.ok_or_else(|| failure(Code::NotFound, "Turn does not exist"))?;
- let invocation = boundary.invocation.clone();
- let snapshot = snapshot::project(boundary).snapshot;
- if snapshot.run_id != input.run_id {
+ if boundary.root_invocation().run_id != input.run_id {
return Err(failure(Code::OperationConflict, "Run identity changed"));
}
+ let boundary = if matches!(
+ boundary.state,
+ maka_event_log::turns::InvocationState::Ended {
+ outcome: maka_runtime::event::InvocationOutcome::HandoffPaused { .. },
+ ..
+ }
+ ) {
+ self.log
+ .cancel_handoff(&boundary.invocation, maka_agent::CancellationCause::Runtime)
+ .await
+ .map_err(|error| match error {
+ StoreError::CommitUnknown(_) | StoreError::OperationUnknown => {
+ self.begin_drain();
+ // turn.stop has no commit_outcome_unknown wire outcome.
+ // Fence admission without inventing a client protocol code.
+ failure(Code::HostDraining, &error.to_string())
+ }
+ _ => internal(error),
+ })?
+ } else {
+ boundary
+ };
+ let invocation = boundary.invocation;
let cancellation = self
.active
.lock()
diff --git a/crates/runtime-host/tests/integration/handoff.rs b/crates/runtime-host/tests/integration/handoff.rs
new file mode 100644
index 0000000000..5eeef215c6
--- /dev/null
+++ b/crates/runtime-host/tests/integration/handoff.rs
@@ -0,0 +1,222 @@
+/*
+ * 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::support::{client_probe::ClientFixture, peer::Peer};
+use maka_protocol::session::{PermissionMode, WorkspaceProjection, WorkspaceTarget};
+use maka_runtime::{
+ artifact::content_digest,
+ continuation::{REPLAY_VERSION, ReplayEvidence},
+ event::{EventWrite, Fact, Invocation, InvocationInput, InvocationOutcome, RuntimeEvent},
+ execution::ToolMode,
+ handoff::{HandoffExecution, HandoffIntent, HandoffPause, HandoffTools},
+};
+use maka_runtime_host::{
+ server::{Host, local::LocalListener},
+ session::{PreparedSession, SessionModel},
+};
+use serde_json::json;
+use std::{num::NonZeroU16, time::Duration};
+use tokio_util::sync::CancellationToken;
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn stop_sealed_turn_uses_public_identity_without_provider_and_survives_restart() {
+ let fixture = ClientFixture::new("maka-handoff-stop-");
+ let log = fixture.log().await;
+ let cwd = fixture.workspace.to_string_lossy().into_owned();
+ let configuration = PreparedSession::new(
+ serde_json::from_value(json!({
+ "sessionId":"session", "workspace":{"kind":"host_path", "path":cwd},
+ "modelTarget":{"kind":"default"}
+ }))
+ .unwrap(),
+ )
+ .unwrap()
+ .bind(
+ WorkspaceProjection {
+ target: WorkspaceTarget::HostPath { path: cwd.clone() },
+ host_cwd: cwd,
+ },
+ SessionModel {
+ connection_id: "removed-provider".into(),
+ connection_slug: "removed".into(),
+ model: "unavailable".into(),
+ },
+ PermissionMode::Explore,
+ ToolMode::Direct,
+ );
+ log.create_session("session", "fixture", &configuration, 1)
+ .await
+ .unwrap();
+ let invocation = Invocation {
+ session_id: "session".into(),
+ turn_id: "turn".into(),
+ run_id: "public-run".into(),
+ invocation_id: "source-invocation".into(),
+ };
+ let pause = HandoffPause {
+ intent: HandoffIntent {
+ handoff_id: "handoff".into(),
+ host_epoch: "old-host".into(),
+ root_run_id: invocation.run_id.clone(),
+ successor_run_id: "physical-successor".into(),
+ successor_invocation_id: "successor-invocation".into(),
+ claim_id: "claim".into(),
+ },
+ remaining_steps: NonZeroU16::new(1).unwrap(),
+ execution: Box::new(HandoffExecution {
+ replay: ReplayEvidence {
+ version: REPLAY_VERSION,
+ digest: content_digest(b"admission"),
+ route_identity: content_digest(b"missing-provider"),
+ },
+ context: None,
+ provider_options: json!({}),
+ main_output_limit: None,
+ supports_vision: false,
+ tools: HandoffTools {
+ catalog_digest: content_digest(b"unavailable-tools"),
+ loaded: Default::default(),
+ },
+ compaction_attempted: false,
+ replay_base: None,
+ }),
+ };
+ for fact in [
+ Fact::InvocationOpened {
+ configuration: Some(configuration.invocation_configuration().await.unwrap()),
+ input: InvocationInput::Message {
+ content: "stop this task".into(),
+ request_fingerprint: None,
+ source_messages: Vec::new(),
+ skill_invocation: None,
+ },
+ },
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::HandoffPaused { pause },
+ },
+ ] {
+ log.append(&EventWrite::plain(RuntimeEvent::new(invocation.clone(), fact)).unwrap())
+ .await
+ .unwrap();
+ }
+ let sealed = log.prefix(100, 128 * 1024).await.unwrap();
+ log.close().await.unwrap();
+ let mut result = None;
+ let mut settled = None;
+ for reopened in [false, true] {
+ let host = Host::open(fixture.owner()).await.unwrap();
+ #[cfg(unix)]
+ let endpoint = fixture.workspace.parent().unwrap().join("handoff.sock");
+ #[cfg(windows)]
+ let endpoint =
+ std::path::PathBuf::from(format!(r"\\.\pipe\maka-handoff-{}", uuid::Uuid::new_v4()));
+ let cancel = CancellationToken::new();
+ let server = tokio::spawn(
+ LocalListener::bind(&endpoint)
+ .unwrap()
+ .serve(host.clone(), cancel.clone()),
+ );
+ let mut peer = Peer::new(host.clone(), "handoff-stop").await;
+ let turn = peer
+ .rpc(
+ "turn.query",
+ json!({"sessionId":"session", "turnId":"turn"}),
+ )
+ .await;
+ assert_eq!(turn["result"]["runId"], "public-run", "{turn}");
+ assert_eq!(
+ turn["result"]["status"],
+ if reopened { "cancelled" } else { "running" },
+ "{turn}"
+ );
+ let wrong = peer
+ .rpc(
+ "turn.stop",
+ json!({
+ "sessionId":"session", "turnId":"turn", "runId":"physical-successor"
+ }),
+ )
+ .await;
+ assert_eq!(wrong["error"]["code"], "operation_conflict", "{wrong}");
+ let after_wrong = peer
+ .rpc(
+ "turn.query",
+ json!({"sessionId":"session", "turnId":"turn"}),
+ )
+ .await;
+ assert_eq!(
+ after_wrong, turn,
+ "wrong public identity must not claim or cancel the seal"
+ );
+ for _ in 0..2 {
+ let stopped = peer
+ .rpc(
+ "turn.stop",
+ json!({
+ "sessionId":"session", "turnId":"turn", "runId":"public-run"
+ }),
+ )
+ .await;
+ assert_eq!(stopped["ok"], true, "{stopped}");
+ assert_eq!(stopped["result"]["status"], "cancelled", "{stopped}");
+ assert_eq!(stopped["result"]["runId"], "public-run", "{stopped}");
+ if let Some(expected) = &result {
+ assert_eq!(&stopped, expected);
+ } else {
+ result = Some(stopped);
+ }
+ }
+ peer.close().await;
+ cancel.cancel();
+ tokio::time::timeout(Duration::from_secs(10), server)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ drop(host);
+ let log = fixture.log().await;
+ let prefix = log.prefix(100, 128 * 1024).await.unwrap();
+ assert_eq!(
+ prefix.events.len(),
+ 4,
+ "only one claim and one cancellation are added"
+ );
+ assert_eq!(
+ serde_json::to_value(&prefix.events[..2]).unwrap(),
+ serde_json::to_value(&sealed.events).unwrap()
+ );
+ assert!(matches!(
+ &prefix.events[2].event.fact,
+ Fact::InvocationOpened {
+ input: InvocationInput::Handoff { .. },
+ ..
+ }
+ ));
+ assert!(
+ matches!(&prefix.events[3].event.fact, Fact::InvocationEnded {
+ outcome: InvocationOutcome::Cancelled { source }
+ } if source == "runtime_cancellation")
+ );
+ if let Some(expected) = &settled {
+ assert_eq!(&prefix.digest, expected);
+ } else {
+ settled = Some(prefix.digest);
+ }
+ log.close().await.unwrap();
+ }
+}
diff --git a/crates/runtime-host/tests/integration/main.rs b/crates/runtime-host/tests/integration/main.rs
index 96ce6c3248..e0a08bac8b 100644
--- a/crates/runtime-host/tests/integration/main.rs
+++ b/crates/runtime-host/tests/integration/main.rs
@@ -44,6 +44,7 @@ mod connection_multiplex;
mod context_compaction;
mod execution_boundary;
mod execution_drain;
+mod handoff;
mod host_drain;
mod large_outputs;
mod live_pipes;
diff --git a/crates/runtime/src/continuation.rs b/crates/runtime/src/continuation.rs
index 4458d92912..2eb50fb1ac 100644
--- a/crates/runtime/src/continuation.rs
+++ b/crates/runtime/src/continuation.rs
@@ -63,6 +63,18 @@ pub const MAX_ANCESTRY: usize = 64;
pub const MAX_SOURCE_EVENTS: usize = 10_000;
pub const MAX_SOURCE_BYTES: usize = 8 * 1024 * 1024;
+impl ReplayEvidence {
+ pub(crate) fn validate(&self) -> Result<(), &'static str> {
+ if self.version != REPLAY_VERSION
+ || !valid_projection_digest(&self.digest)
+ || !valid_projection_digest(&self.route_identity)
+ {
+ return Err("invalid provider replay evidence");
+ }
+ Ok(())
+ }
+}
+
impl ContinuationClaim {
pub fn validate(&self, target: &Invocation) -> Result<(), &'static str> {
self.validate_boundary(target)?;
@@ -96,12 +108,9 @@ impl ContinuationClaim {
|| self.base.high_water >= i64::MAX as u64
|| !valid_projection_digest(&self.source.digest)
|| !valid_projection_digest(&self.base.digest)
- || self.replay.version != REPLAY_VERSION
- || !valid_projection_digest(&self.replay.digest)
- || !valid_projection_digest(&self.replay.route_identity)
{
return Err("invalid continuation boundary or replay evidence");
}
- Ok(())
+ self.replay.validate()
}
}
diff --git a/crates/runtime/src/event.rs b/crates/runtime/src/event.rs
index 8078cd9332..a99e570c87 100644
--- a/crates/runtime/src/event.rs
+++ b/crates/runtime/src/event.rs
@@ -61,6 +61,25 @@ pub enum InvocationOutcome {
},
}
+#[derive(Clone, Debug)]
+pub enum CancellationCause {
+ Runtime,
+ WorkhubStop { action_id: crate::workhub::ActionId },
+ WorkhubCorrection { action_id: crate::workhub::ActionId },
+}
+
+impl CancellationCause {
+ pub fn source(&self) -> String {
+ match self {
+ Self::Runtime => "runtime_cancellation".into(),
+ Self::WorkhubStop { action_id } => crate::workhub::stop_abort_source(action_id),
+ Self::WorkhubCorrection { action_id } => {
+ crate::workhub::correction_abort_source(action_id)
+ }
+ }
+ }
+}
+
impl InvocationOutcome {
pub fn status(&self) -> TerminalStatus {
match self {
diff --git a/crates/runtime/src/handoff.rs b/crates/runtime/src/handoff.rs
index f4a5d6e6b2..82286b0f10 100644
--- a/crates/runtime/src/handoff.rs
+++ b/crates/runtime/src/handoff.rs
@@ -88,7 +88,7 @@ impl HandoffPause {
claim.validate_boundary(target)?;
self.validate(&claim.source.invocation)?;
if claim.id != self.intent.claim_id
- || claim.replay.route_identity != self.execution.route_identity
+ || claim.replay != self.execution.replay
|| self
.execution
.replay_base
diff --git a/crates/runtime/src/handoff/execution.rs b/crates/runtime/src/handoff/execution.rs
index db3a5adf4c..6ee5c3cfd8 100644
--- a/crates/runtime/src/handoff/execution.rs
+++ b/crates/runtime/src/handoff/execution.rs
@@ -26,7 +26,8 @@ use std::collections::BTreeSet;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HandoffExecution {
- pub route_identity: String,
+ /// Admission projection, before any successor-side automatic compaction.
+ pub replay: crate::continuation::ReplayEvidence,
pub context: Option<ModelRequestContext>,
/// Provider-specific options intentionally retain their extensible JSON shape.
pub provider_options: Value,
@@ -50,8 +51,8 @@ pub struct HandoffTools {
impl HandoffExecution {
pub(super) fn validate(&self) -> Result<(), &'static str> {
- if !valid_projection_digest(&self.route_identity)
- || !valid_projection_digest(&self.tools.catalog_digest)
+ self.replay.validate()?;
+ if !valid_projection_digest(&self.tools.catalog_digest)
|| self
.main_output_limit
.is_some_and(|n| n == 0 || n > 10_000_000_000)
diff --git a/docs/rust-runtime.md b/docs/rust-runtime.md
index 120d44f161..5adc1f12e6 100644
--- a/docs/rust-runtime.md
+++ b/docs/rust-runtime.md
@@ -70,6 +70,7 @@ Do not run untrusted code or point test instances at existing user data.
- A State Root has one writer and execution authority. Session, Turn, Run and
invocation identities remain distinct. Cooperative continuation preserves the
public Run identity; claims and cleanup still address exact physical Runs.
+ Sealed work can be cancelled without loading a provider or repeating effects.
- Host diagnostics and retirement share active-work accounting, including pending
OAuth authorization. Retirement targets an exact Host epoch and retains authority
through response flush and resource cleanup. Cooperative step handoff is not yet
diff --git a/docs/rust-runtime.zh-CN.md b/docs/rust-runtime.zh-CN.md
index 050ac03d02..1b31aeb5c6 100644
--- a/docs/rust-runtime.zh-CN.md
+++ b/docs/rust-runtime.zh-CN.md
@@ -62,6 +62,7 @@ Windows 使用私有 named pipe。可选 `--websocket 127.0.0.1:0` 监听需要
工具 JSON、schema 和厂商扩展保留开放结构。
- 每个 State Root 只有一个写入与执行 authority;Session、Turn、Run、invocation
身份保持独立。协作续接保留对外 Run 身份;恢复凭证与清理仍绑定精确物理 Run。
+ 已封口的任务可直接取消,无需加载 provider,也不重做副作用。
- Host 诊断与退出共用活动工作统计,包含等待授权的 OAuth 登录。退出绑定精确 Host epoch,
回复发送与资源清理完成前不释放 authority。尚未公布协作步骤交接能力;旧协议字段
`nodeVersion` 如实返回 `not applicable (Rust)`。
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org