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/23 09:34:04 UTC
(maka) 01/09: feat(session): retire families with durable scoped receipts
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 a17237fd9635dfaa007f084c39423ffe58031612
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 23 14:43:18 2026 +0800
feat(session): retire families with durable scoped receipts
Generated-by: Codex
---
.../runtime-host-client-operations.test.ts | 21 +-
apps/desktop/src/main/runtime-host-client.ts | 34 +-
crates/agent/src/runner.rs | 5 +-
crates/event-log/migrations/0001_runtime.sql | 21 ++
crates/event-log/src/append.rs | 22 +-
crates/event-log/src/effects.rs | 2 +-
crates/event-log/src/handoff.rs | 2 +
crates/event-log/src/interactions.rs | 2 +
crates/event-log/src/lib.rs | 2 +
crates/event-log/src/message_admissions/insert.rs | 2 +-
crates/event-log/src/sessions.rs | 19 +-
crates/event-log/src/sessions/admission.rs | 50 +++
crates/event-log/src/sessions/copy.rs | 4 +
crates/event-log/src/sessions/copy/lifecycle.rs | 17 -
crates/event-log/src/sessions/metadata.rs | 6 +
crates/event-log/src/sessions/origin.rs | 2 +-
crates/event-log/src/sessions/processes.rs | 67 ++++
crates/event-log/src/sessions/removal.rs | 310 +++++++++++++++++++
crates/event-log/src/sessions/removal/plan.rs | 298 ++++++++++++++++++
crates/event-log/src/shell_runs.rs | 2 +-
crates/event-log/src/steering_delivery.rs | 1 +
crates/event-log/src/workspace.rs | 26 ++
crates/event-log/tests/archive.rs | 88 ++++++
crates/event-log/tests/message_queue.rs | 187 +++++++++++
crates/event-log/tests/session_copy.rs | 343 ++++++++++++++++++++-
crates/fs-tools/src/worktree.rs | 3 +
crates/fs-tools/src/worktree/ownership.rs | 2 +-
crates/fs-tools/src/worktree/removal.rs | 132 ++++++++
crates/fs-tools/tests/worktree.rs | 60 ++++
crates/js-runtime/src/plugin/sdk.js | 3 +
crates/plugins/src/execution.rs | 19 ++
crates/plugins/src/execution/removal.rs | 62 ++++
crates/protocol/src/authority.rs | 1 +
crates/protocol/src/operation.rs | 1 +
crates/protocol/src/session.rs | 21 ++
crates/runtime-host/src/execution.rs | 15 +-
crates/runtime-host/src/execution/control.rs | 56 ++++
crates/runtime-host/src/execution/plugins.rs | 53 +++-
.../runtime-host/src/execution/plugins/children.rs | 16 +-
.../runtime-host/src/execution/plugins/removal.rs | 158 ++++++++++
crates/runtime-host/src/execution/plugins/root.rs | 4 +-
.../src/execution/plugins/workspace.rs | 2 +-
crates/runtime-host/src/execution/processes.rs | 130 ++++++++
crates/runtime-host/src/execution/removal.rs | 233 ++++++++++++++
crates/runtime-host/src/execution/workspaces.rs | 45 ++-
.../runtime-host/src/plugins/javascript/bridge.rs | 12 +
.../src/plugins/javascript/bridge/wire.rs | 6 +
crates/runtime-host/src/plugins/process.rs | 21 +-
crates/runtime-host/src/server.rs | 1 +
crates/runtime-host/src/server/authority.rs | 3 +
crates/runtime-host/src/server/operations.rs | 3 +
crates/runtime-host/src/server/sessions.rs | 45 ++-
crates/runtime-host/src/server/sessions/copy.rs | 1 +
crates/runtime-host/src/server/sessions/create.rs | 1 +
crates/runtime-host/src/server/sessions/removal.rs | 101 ++++++
.../runtime-host/src/server/sessions/workspace.rs | 3 +
.../tests/fixtures/background-plugin.mjs | 41 +++
crates/runtime-host/tests/integration/main.rs | 1 +
.../tests/integration/session_removal.rs | 204 ++++++++++++
crates/runtime/src/event.rs | 3 +
crates/runtime/src/tools/journal.rs | 7 +-
docs/rust-parity.md | 4 +-
docs/rust-parity.zh-CN.md | 4 +-
docs/rust-runtime.md | 12 +
docs/rust-runtime.zh-CN.md | 9 +
packages/plugin-sdk/src/execution.ts | 18 ++
packages/runtime-host/src/protocol/operations.ts | 1 +
.../src/protocol/session-retirement.ts | 48 +++
.../src/server/operation-dispatcher.ts | 5 +-
69 files changed, 2985 insertions(+), 118 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts b/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts
index ed6cbe7994..bc9f4d4a8b 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-client-operations.test.ts
@@ -144,7 +144,9 @@ test('settles cleanup when its copy target is already absent', async () => {
test('settles branch cleanup when its target disappears between catalog reads', async () => {
const { client } = clientWithResponses([
{ kind: 'session', session: session('branch-copy', 1) },
+ { kind: 'missing' },
{ kind: 'session', session: null },
+ { kind: 'missing' },
]);
assert.equal(await client.removeSessionCopy('branch-copy'), 'removed');
@@ -263,6 +265,7 @@ test('abandons a remove whose task was restored under it', async () => {
// and replaying the delete at the fresh revision destroys a task somebody
// just pulled back out of the archive.
const { client, requests } = clientWithResponses([
+ { kind: 'missing' },
{ kind: 'session', session: session('session-1', 4, { isArchived: true }) },
{ kind: 'revision_conflict', expectedRevision: 4, actualRevision: 5 },
{ kind: 'session', session: session('session-1', 5, { isArchived: false }) },
@@ -276,7 +279,7 @@ test('abandons a remove whose task was restored under it', async () => {
});
assert.deepEqual(
requests.map(({ operation }) => operation),
- ['session.catalog.query', 'session.remove', 'session.catalog.query'],
+ ['session.remove.query', 'session.catalog.query', 'session.remove', 'session.catalog.query'],
);
});
@@ -284,6 +287,7 @@ test('retries a remove through revision churn that left the task archived', asyn
// Not every conflict is a restore. A task still archived at the fresh
// revision was only written around, and the delete still means what it did.
const { client, requests } = clientWithResponses([
+ { kind: 'missing' },
{ kind: 'session', session: session('session-1', 4, { isArchived: true }) },
{ kind: 'revision_conflict', expectedRevision: 4, actualRevision: 5 },
{ kind: 'session', session: session('session-1', 5, { isArchived: true }) },
@@ -308,6 +312,7 @@ test('removes a task that was never archived when no premise was stated', async
// Deleting an active task from the rail has no archived premise to lose, so
// the precondition is the caller's to ask for, not the client's to assume.
const { client } = clientWithResponses([
+ { kind: 'missing' },
{ kind: 'session', session: session('session-1', 4) },
{ kind: 'removed' },
]);
@@ -318,6 +323,20 @@ test('removes a task that was never archived when no premise was stated', async
});
});
+test('recovers a removed Session receipt without recreating a delete request', async () => {
+ for (const raced of [false, true]) {
+ const { client, requests } = clientWithResponses([
+ ...(raced ? [{ kind: 'missing' }, { kind: 'session', session: null }] : []),
+ { kind: 'removed', sessionId: 'session-1', archivedSubtaskCount: 3 },
+ ]);
+ assert.deepEqual(await client.removeSession('session-1', { requireArchived: true }), {
+ disposition: 'removed',
+ archivedSubtaskCount: 3,
+ });
+ assert.equal(requests.some(({ operation }) => operation === 'session.remove'), false);
+ }
+});
+
test('rebuilds a Runtime Policy mutation from each fresh CAS projection', async () => {
const initial = createDefaultRuntimePolicy();
const concurrent = {
diff --git a/apps/desktop/src/main/runtime-host-client.ts b/apps/desktop/src/main/runtime-host-client.ts
index 9e8f346e40..f4fc8da5d0 100644
--- a/apps/desktop/src/main/runtime-host-client.ts
+++ b/apps/desktop/src/main/runtime-host-client.ts
@@ -1027,28 +1027,30 @@ export class DesktopRuntimeHostClient {
/**
* Removes a Session, optionally only while it is still archived.
- *
- * Replaying a rejected write at the fresh revision is right for a rename or a
- * configuration patch — the write means the same thing either way. It is
- * wrong for a remove: a lifecycle write bumps the revision, so a conflict can
- * be the task being restored, and replaying then destroys a task whose
- * deletion nobody asked for any more.
- *
- * `requireArchived` states the premise the caller decided on. Re-asserting it
- * against each fresh read is enough to hold it through the commit, because
- * the Host serializes the two writes that could disagree: `session.remove`
- * and `session.lifecycle.set` both enter `#withStableFamily`, which queues
- * per Session id through the admission gate, and the remove compares the
- * revision on the way in. So a restore either lands before that comparison —
- * bumping `metadataVersion` and rejecting the remove — or waits until the
- * retirement has finished. It cannot land between the check and the delete.
+ * The receipt survives catalog removal. Fresh writes recheck the caller's
+ * archived premise at each CAS revision, so a concurrent restore wins.
*/
async removeSession(
sessionId: string,
options: { requireArchived?: boolean } = {},
): Promise<SessionRemoveOutcome> {
+ const receipt = await this.request('session.remove.query', { sessionId });
+ if (receipt.kind === 'removed') {
+ return { disposition: 'removed', archivedSubtaskCount: receipt.archivedSubtaskCount };
+ }
for (let attempt = 0; attempt < MAX_SESSION_REVISION_ATTEMPTS; attempt += 1) {
- const current = await this.#requireSession(sessionId);
+ const current = await this.getSession(sessionId);
+ if (current === null) {
+ // A removal may have committed after the first receipt read.
+ const settled = await this.request('session.remove.query', { sessionId });
+ if (settled.kind === 'removed') {
+ return { disposition: 'removed', archivedSubtaskCount: settled.archivedSubtaskCount };
+ }
+ throw new DesktopRuntimeHostClientError(
+ 'session_not_found',
+ `Runtime Host Session not found: ${sessionId}`,
+ );
+ }
if (options.requireArchived && !current.isArchived) {
return { disposition: "restored", archivedSubtaskCount: 0 };
}
diff --git a/crates/agent/src/runner.rs b/crates/agent/src/runner.rs
index cba47a8ec6..6c8f322890 100644
--- a/crates/agent/src/runner.rs
+++ b/crates/agent/src/runner.rs
@@ -148,8 +148,9 @@ pub async fn run(
}
}
.await;
- let result = if matches!(&result, Ok((outcome, _)) if !matches!(outcome, InvocationOutcome::HandoffPaused { .. }))
- && cancellation.is_cancelled()
+ let result = if matches!(&result, Err(RunError::Commit(CommitError::Retired)))
+ || (matches!(&result, Ok((outcome, _)) if !matches!(outcome, InvocationOutcome::HandoffPaused { .. }))
+ && cancellation.is_cancelled())
{
Err(RunError::Cancelled)
} else {
diff --git a/crates/event-log/migrations/0001_runtime.sql b/crates/event-log/migrations/0001_runtime.sql
index 490566e053..bb912a6bc2 100644
--- a/crates/event-log/migrations/0001_runtime.sql
+++ b/crates/event-log/migrations/0001_runtime.sql
@@ -44,6 +44,27 @@ CREATE TABLE session_catalog_revision (
revision INTEGER NOT NULL CHECK(revision >= 0)
);
+-- Retirement fences new admissions before asynchronous resource cleanup. Keep
+-- its identity after cleanup so a lost reply cannot resurrect the Session.
+CREATE TABLE session_retirements (
+ session_id TEXT PRIMARY KEY,
+ remove_session INTEGER NOT NULL DEFAULT 1 CHECK(remove_session IN (0, 1)),
+ completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1))
+);
+
+CREATE TABLE session_removal_receipts (
+ session_id TEXT PRIMARY KEY,
+ plan_json TEXT NOT NULL
+);
+
+-- A Host crash loses native handles, not proof that a process may still write.
+CREATE TABLE session_processes (
+ id TEXT PRIMARY KEY,
+ session_id TEXT NOT NULL,
+ cleaned INTEGER NOT NULL DEFAULT 0 CHECK(cleaned IN (0, 1))
+);
+CREATE INDEX session_processes_pending ON session_processes(session_id) WHERE cleaned=0;
+
CREATE TABLE session_read_state (
session_id TEXT PRIMARY KEY REFERENCES session_control(id),
has_unread INTEGER NOT NULL CHECK(has_unread IN (0, 1)),
diff --git a/crates/event-log/src/append.rs b/crates/event-log/src/append.rs
index 1289bed51b..4899832d89 100644
--- a/crates/event-log/src/append.rs
+++ b/crates/event-log/src/append.rs
@@ -26,7 +26,8 @@ use crate::{EventLog, StoreError, sequence_number};
impl EventLog {
/// Commit ordered facts atomically, validating each against the preceding
- /// facts in this transaction. Exact replays return their original sequence.
+ /// facts in this transaction. Exact replays return their original sequence
+ /// until Session removal completes, after which all writes are rejected.
/// This must not enclose effects: live dispatch and outcome remain separate.
pub async fn append_batch(&self, events: &[EventWrite]) -> Result<Vec<u64>, CommitError> {
self.append_batch_checked(events)
@@ -34,6 +35,7 @@ impl EventLog {
.map_err(|error| match error {
StoreError::CommitUnknown(error) => CommitError::OutcomeUnknown(error.to_string()),
StoreError::OperationUnknown => CommitError::OutcomeUnknown(error.to_string()),
+ StoreError::SessionRetired => CommitError::Retired,
other => CommitError::Rejected(other.to_string()),
})
}
@@ -80,6 +82,11 @@ impl EventLog {
write: &EventWrite,
) -> Result<AppendResult, StoreError> {
let event = write.event();
+ let removal =
+ crate::sessions::removal::read(transaction, &event.invocation.session_id).await?;
+ if removal == Some(crate::sessions::SessionRetirement::Removed) {
+ return Err(StoreError::SessionRetired);
+ }
let json = serde_json::to_string(event)?;
let previous: Option<(i64, String)> =
sqlx::query_as("SELECT sequence, event_json FROM runtime_events WHERE event_id = ?")
@@ -95,6 +102,17 @@ impl EventLog {
crate::archive::verify_replay(transaction, event).await?;
return Ok(AppendResult::Existing(sequence_number(sequence)?));
}
+ if removal.is_some()
+ && matches!(
+ event.fact,
+ Fact::ModelRequested { .. }
+ | Fact::ToolDispatched { .. }
+ | Fact::ExecutorStarted { .. }
+ | Fact::MessageSteered { .. }
+ )
+ {
+ return Err(StoreError::SessionRetired);
+ }
let id = &event.invocation.invocation_id;
let sealed: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM runtime_events WHERE invocation_id = ? AND kind = 'invocation_ended')",
@@ -107,7 +125,7 @@ impl EventLog {
).bind(id).fetch_optional(&mut *transaction).await?;
match (&event.fact, opening) {
(Fact::InvocationOpened { .. }, None) => {
- crate::sessions::copy::retain(transaction, &event.invocation.session_id).await?;
+ crate::sessions::retain(transaction, &event.invocation.session_id).await?;
let archived: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM session_control WHERE id = ? AND archived = 1)",
)
diff --git a/crates/event-log/src/effects.rs b/crates/event-log/src/effects.rs
index 288301ddc6..ccc4e24c8b 100644
--- a/crates/event-log/src/effects.rs
+++ b/crates/event-log/src/effects.rs
@@ -103,7 +103,7 @@ impl EventLog {
self.connection.run(move |connection| {
Box::pin(async move {
let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
- if let Some(session) = session { crate::sessions::copy::retain(&mut tx, &session).await?; }
+ if let Some(session) = session { crate::sessions::retain(&mut tx, &session).await?; }
sqlx::query("INSERT INTO host_effects (id, package_id, scope_id, request) VALUES (?, ?, ?, ?)")
.bind(id.to_string()).bind(namespace.package()).bind(String::from(namespace.scope().clone())).bind(raw)
.execute(&mut *tx).await?;
diff --git a/crates/event-log/src/handoff.rs b/crates/event-log/src/handoff.rs
index b780d23dd5..a08c7adaba 100644
--- a/crates/event-log/src/handoff.rs
+++ b/crates/event-log/src/handoff.rs
@@ -45,6 +45,8 @@ impl EventLog {
json_extract(pause.event_json,'$.fact.outcome.pause.intent.host_epoch')
FROM runtime_events pause
WHERE pause.sequence > ? AND pause.kind='invocation_ended'
+ AND NOT EXISTS (SELECT 1 FROM session_retirements r
+ WHERE r.session_id=json_extract(pause.event_json,'$.invocation.session_id'))
AND json_extract(pause.event_json,'$.fact.outcome.kind')='handoff_paused'
AND NOT EXISTS (SELECT 1 FROM runtime_events successor
WHERE successor.kind='invocation_opened'
diff --git a/crates/event-log/src/interactions.rs b/crates/event-log/src/interactions.rs
index c089b2d7b3..e68bdf60f8 100644
--- a/crates/event-log/src/interactions.rs
+++ b/crates/event-log/src/interactions.rs
@@ -60,6 +60,8 @@ impl EventLog {
record.outcome = outcome;
return Ok(InteractionCommit { matches, record });
}
+ crate::sessions::removal::require_accepting(&mut tx, &request.session_id)
+ .await?;
permissions::require_revision(&mut tx, &request).await?;
sqlx::query("INSERT INTO interaction_requests VALUES (?, ?, ?, ?)")
.bind(&request.request_id)
diff --git a/crates/event-log/src/lib.rs b/crates/event-log/src/lib.rs
index 860642c2a1..79ce202419 100644
--- a/crates/event-log/src/lib.rs
+++ b/crates/event-log/src/lib.rs
@@ -89,6 +89,8 @@ pub enum StoreError {
ShellNotFound,
#[error("session not found")]
SessionNotFound,
+ #[error("session retired")]
+ SessionRetired,
#[error("session has an unsealed invocation")]
SessionBusy,
#[error("catalog revision changed from {expected} to {actual}")]
diff --git a/crates/event-log/src/message_admissions/insert.rs b/crates/event-log/src/message_admissions/insert.rs
index dceed493db..56f4a4f915 100644
--- a/crates/event-log/src/message_admissions/insert.rs
+++ b/crates/event-log/src/message_admissions/insert.rs
@@ -112,6 +112,6 @@ pub(crate) async fn insert(
}
sqlx::query("INSERT INTO message_admissions (session_id, message_id, position, record_json) VALUES (?, ?, ?, ?)")
.bind(session).bind(message).bind(position).bind(encoded).execute(&mut *tx).await?;
- crate::sessions::copy::retain(tx, session).await?;
+ crate::sessions::retain(tx, session).await?;
crate::message_queue::bump(tx, session).await.map(Some)
}
diff --git a/crates/event-log/src/sessions.rs b/crates/event-log/src/sessions.rs
index 1b60b9932c..6bbde2cd48 100644
--- a/crates/event-log/src/sessions.rs
+++ b/crates/event-log/src/sessions.rs
@@ -20,12 +20,19 @@
//! Durable session control metadata. Execution history remains in runtime_events.
mod activity;
+mod admission;
+pub(crate) use admission::retain;
pub(crate) mod copy;
pub use copy::{AbandonRevision, SessionCopy, SessionCopyResult};
mod execution;
mod metadata;
mod origin;
+mod processes;
+pub(crate) mod removal;
pub use origin::PluginSession;
+pub use removal::{
+ RemovalAuthority, RemovalPlan, RemoveFamilyResult, SessionRemovalResult, SessionRetirement,
+};
pub(crate) mod read_state;
pub(crate) use activity::{initialize_execution, project_execution, register_functions};
pub(crate) use execution::advance_revision;
@@ -178,6 +185,12 @@ impl EventLog {
.run(move |connection| {
Box::pin(async move {
let mut tx = connection.begin().await?;
+ if removal::read(&mut tx, &id)
+ .await?
+ .is_some_and(SessionRetirement::removes)
+ {
+ return Ok(None);
+ }
read(&mut tx, &id).await
})
})
@@ -265,6 +278,7 @@ impl EventLog {
}
let ids = sqlx::query_scalar::<_, String>(
"SELECT id FROM session_control WHERE id > ?
+ AND NOT EXISTS (SELECT 1 FROM session_retirements WHERE session_id=id AND remove_session=1)
AND (? = 0 OR archived = 0)
AND (? IS NULL OR id = ?)
AND (? IS NULL OR json_extract(configuration, '$.workspace.hostCwd') = ?)
@@ -327,7 +341,8 @@ pub(crate) async fn insert(
let inserted = sqlx::query(
"INSERT INTO session_control SELECT ?, ?, 1, ?, ?, 0, ?
WHERE NOT EXISTS (SELECT 1 FROM session_control WHERE id = ?)
- AND NOT EXISTS (SELECT 1 FROM session_history_copies WHERE session_id = ?)",
+ AND NOT EXISTS (SELECT 1 FROM session_history_copies WHERE session_id = ?)
+ AND NOT EXISTS (SELECT 1 FROM session_retirements WHERE session_id = ?)",
)
.bind(id)
.bind(fingerprint)
@@ -336,6 +351,7 @@ pub(crate) async fn insert(
.bind(configuration)
.bind(id)
.bind(id)
+ .bind(id)
.execute(&mut *tx)
.await?;
if inserted.rows_affected() != 1 {
@@ -450,6 +466,7 @@ async fn probe<T: DeserializeOwned>(
id: &str,
fingerprint: &str,
) -> Result<Option<SessionRecord<T>>, StoreError> {
+ removal::require_accepting(connection, id).await?;
if fingerprint.is_empty() || fingerprint.len() > 512 {
return Err(invalid("invalid session fingerprint length"));
}
diff --git a/crates/event-log/src/sessions/admission.rs b/crates/event-log/src/sessions/admission.rs
new file mode 100644
index 0000000000..ebbfc992e9
--- /dev/null
+++ b/crates/event-log/src/sessions/admission.rs
@@ -0,0 +1,50 @@
+/*
+ * 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};
+use sqlx::{Connection, SqliteConnection};
+
+/// Shares the accepted work's transaction: a retiring Session cannot accept new
+/// work, and an accepted use makes a preparing revision no longer disposable.
+pub(crate) async fn retain(
+ connection: &mut SqliteConnection,
+ session: &str,
+) -> Result<(), StoreError> {
+ super::removal::require_accepting(connection, session).await?;
+ super::copy::retain(connection, session).await
+}
+
+impl EventLog {
+ /// Native process acceptance has no canonical invocation. The Host pins its
+ /// admission gate through this commit and actual launch.
+ pub async fn retain_session(&self, session: &str) -> Result<(), StoreError> {
+ self.validate_root()?;
+ super::validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ retain(&mut tx, &session).await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)
+ })
+ })
+ .await
+ }
+}
diff --git a/crates/event-log/src/sessions/copy.rs b/crates/event-log/src/sessions/copy.rs
index 779db70005..86448082f4 100644
--- a/crates/event-log/src/sessions/copy.rs
+++ b/crates/event-log/src/sessions/copy.rs
@@ -146,6 +146,7 @@ impl EventLog {
).bind(&request.target_session_id).fetch_optional(&mut *tx).await?;
if let Some(previous) = previous {
if previous != encoded { return Err(StoreError::SessionConflict); }
+ super::removal::require_mutable(&mut tx, &request.target_session_id).await?;
super::origin::check(&mut tx, &request.target_session_id, origin.as_ref()).await?;
let session = super::read(&mut tx, &request.target_session_id).await?
.ok_or(StoreError::SessionNotFound)?;
@@ -217,6 +218,9 @@ impl EventLog {
if retained.rows_affected() == 0 { return Err(super::invalid("revision Turn has no editable input")); }
crate::artifacts::history::retain_revision(&mut tx, &request.source_session_id, &request.target_session_id, now).await?;
}
+ // History ownership is not execution admission: a fully archived
+ // source can seed a branch without becoming executable again.
+ super::removal::require_mutable(&mut tx, &request.source_session_id).await?;
retain(&mut tx, &request.source_session_id).await?;
let session = super::read(&mut tx, &request.target_session_id).await?
.ok_or(StoreError::SessionNotFound)?;
diff --git a/crates/event-log/src/sessions/copy/lifecycle.rs b/crates/event-log/src/sessions/copy/lifecycle.rs
index f022ed9200..42d65e882a 100644
--- a/crates/event-log/src/sessions/copy/lifecycle.rs
+++ b/crates/event-log/src/sessions/copy/lifecycle.rs
@@ -59,23 +59,6 @@ async fn state(
}
impl EventLog {
- /// Host-owned native process acceptance has no canonical invocation. The
- /// caller pins the admission gate through this commit and actual launch.
- pub async fn retain_session(&self, session: &str) -> Result<(), StoreError> {
- self.validate_root()?;
- sessions::validate_id(session)?;
- let session = session.to_owned();
- self.connection
- .run(move |connection| {
- Box::pin(async move {
- let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
- retain(&mut tx, &session).await?;
- tx.commit().await.map_err(StoreError::CommitUnknown)
- })
- })
- .await
- }
-
/// Only unused revisions can disappear. Acceptance, dependent creation and
/// this decision serialize on the same durable writer; replies are replayable.
pub async fn abandon_revision(&self, session: &str) -> Result<AbandonRevision, StoreError> {
diff --git a/crates/event-log/src/sessions/metadata.rs b/crates/event-log/src/sessions/metadata.rs
index 0a9d72dd90..9bdf16f5ca 100644
--- a/crates/event-log/src/sessions/metadata.rs
+++ b/crates/event-log/src/sessions/metadata.rs
@@ -44,6 +44,7 @@ impl EventLog {
let id = id.to_owned();
self.connection.run(move |connection| Box::pin(async move {
let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ super::removal::require_mutable(&mut tx, &id).await?;
let record: SessionRecord<T> = read(&mut tx, &id).await?.ok_or(StoreError::SessionNotFound)?;
let active: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM runtime_events AS opening
@@ -58,6 +59,10 @@ impl EventLog {
if record.archived == archived {
return Ok(record);
}
+ if !archived {
+ sqlx::query("DELETE FROM session_retirements WHERE session_id=? AND remove_session=0 AND completed=1")
+ .bind(&id).execute(&mut *tx).await?;
+ }
let changed = sqlx::query(
"UPDATE session_control SET archived = ?, revision = revision + 1, updated_at = ? WHERE id = ? AND revision < ?",
).bind(archived).bind(now.max(record.updated_at) as i64).bind(&id)
@@ -126,6 +131,7 @@ impl EventLog {
.run(move |connection| {
Box::pin(async move {
let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ super::removal::require_mutable(&mut tx, &id).await?;
let mut record: SessionRecord<T> = read(&mut tx, &id)
.await?
.ok_or(StoreError::SessionNotFound)?;
diff --git a/crates/event-log/src/sessions/origin.rs b/crates/event-log/src/sessions/origin.rs
index 4959b5959a..bd882b28e4 100644
--- a/crates/event-log/src/sessions/origin.rs
+++ b/crates/event-log/src/sessions/origin.rs
@@ -98,7 +98,7 @@ pub(super) async fn insert(
if !exists {
return Err(StoreError::SessionNotFound);
}
- super::copy::retain(connection, source).await?;
+ super::retain(connection, source).await?;
}
sqlx::query("INSERT INTO plugin_sessions VALUES (?, ?, ?, ?, ?, ?)")
.bind(&origin.session_id)
diff --git a/crates/event-log/src/sessions/processes.rs b/crates/event-log/src/sessions/processes.rs
new file mode 100644
index 0000000000..8ab318725e
--- /dev/null
+++ b/crates/event-log/src/sessions/processes.rs
@@ -0,0 +1,67 @@
+/*
+ * 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};
+use sqlx::Connection;
+use uuid::Uuid;
+
+impl EventLog {
+ /// The native owner holds Host admission through this commit and spawn.
+ /// Incomplete records survive restart: a lost handle is not proof of exit.
+ pub async fn admit_session_process(&self, session: &str, id: Uuid) -> Result<(), StoreError> {
+ self.validate_root()?;
+ super::validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ super::retain(&mut tx, &session).await?;
+ sqlx::query("INSERT INTO session_processes(id,session_id) VALUES (?,?)")
+ .bind(id.to_string())
+ .bind(session)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)
+ })
+ })
+ .await
+ }
+
+ /// Call only after the owned process group/Job and native resources drained.
+ pub async fn clean_session_process(&self, id: Uuid) -> Result<(), StoreError> {
+ self.validate_root()?;
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ let changed = sqlx::query("UPDATE session_processes SET cleaned=1 WHERE id=?")
+ .bind(id.to_string())
+ .execute(&mut *tx)
+ .await?
+ .rows_affected();
+ if changed != 1 {
+ return Err(StoreError::EventConflict);
+ }
+ tx.commit().await.map_err(StoreError::CommitUnknown)
+ })
+ })
+ .await
+ }
+}
diff --git a/crates/event-log/src/sessions/removal.rs b/crates/event-log/src/sessions/removal.rs
new file mode 100644
index 0000000000..879c9e2090
--- /dev/null
+++ b/crates/event-log/src/sessions/removal.rs
@@ -0,0 +1,310 @@
+/*
+ * 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::{MAX_SAFE_INTEGER, advance_catalog, invalid, validate_id};
+use crate::{EventLog, StoreError};
+use sqlx::{Connection, SqliteConnection};
+
+mod plan;
+pub use plan::{RemovalAuthority, RemovalPlan, RemoveFamilyResult};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SessionRetirement {
+ Removing,
+ Removed,
+ Archiving,
+ Archived,
+}
+
+impl SessionRetirement {
+ pub fn removes(self) -> bool {
+ matches!(self, Self::Removing | Self::Removed)
+ }
+
+ pub fn pending(self) -> bool {
+ matches!(self, Self::Removing | Self::Archiving)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SessionRemovalResult {
+ Accepted(SessionRetirement),
+ RevisionConflict { expected: u64, actual: u64 },
+}
+
+/// A durable admission fence, not a ban on settling already accepted effects.
+pub(crate) async fn require_accepting(
+ connection: &mut SqliteConnection,
+ session: &str,
+) -> Result<(), StoreError> {
+ if read(connection, session).await?.is_some() {
+ return Err(StoreError::SessionRetired);
+ }
+ Ok(())
+}
+
+pub(crate) async fn require_mutable(
+ connection: &mut SqliteConnection,
+ session: &str,
+) -> Result<(), StoreError> {
+ match read(connection, session).await? {
+ None | Some(SessionRetirement::Archived) => Ok(()),
+ Some(SessionRetirement::Archiving) => Err(StoreError::SessionBusy),
+ Some(_) => Err(StoreError::SessionRetired),
+ }
+}
+
+pub(crate) async fn read(
+ connection: &mut SqliteConnection,
+ session: &str,
+) -> Result<Option<SessionRetirement>, StoreError> {
+ Ok(sqlx::query_as::<_, (bool, bool)>(
+ "SELECT remove_session, completed FROM session_retirements WHERE session_id=?",
+ )
+ .bind(session)
+ .fetch_optional(connection)
+ .await?
+ .map(|(remove, completed)| match (remove, completed) {
+ (true, false) => SessionRetirement::Removing,
+ (true, true) => SessionRetirement::Removed,
+ (false, false) => SessionRetirement::Archiving,
+ (false, true) => SessionRetirement::Archived,
+ }))
+}
+
+impl EventLog {
+ /// Check durable owners before deleting external resources, not just before
+ /// deleting their metadata. The removal fence prevents new owners appearing.
+ pub async fn session_retirement_ready(&self, session: &str) -> Result<bool, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin().await?;
+ Ok(read(&mut tx, &session)
+ .await?
+ .is_some_and(SessionRetirement::pending)
+ && settled(&mut tx, &session).await?)
+ })
+ })
+ .await
+ }
+
+ /// Private cleanup metadata remains until resources are released. Ordinary
+ /// Session queries no longer expose a logically removed Session.
+ pub async fn retiring_session<T: serde::de::DeserializeOwned + Send + 'static>(
+ &self,
+ session: &str,
+ ) -> Result<Option<super::SessionRecord<T>>, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin().await?;
+ if !read(&mut tx, &session)
+ .await?
+ .is_some_and(SessionRetirement::pending)
+ {
+ return Ok(None);
+ }
+ super::read(&mut tx, &session).await
+ })
+ })
+ .await
+ }
+
+ /// Retrying an accepted removal observes its receipt before today's revision.
+ /// The caller must authorize this exact Session independently of the receipt.
+ pub async fn begin_session_removal(
+ &self,
+ session: &str,
+ expected: u64,
+ ) -> Result<SessionRemovalResult, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ if expected == 0 || expected > MAX_SAFE_INTEGER {
+ return Err(invalid("invalid expected Session revision"));
+ }
+ let session = session.to_owned();
+ let commits = self.commits.clone();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ if let Some(state) = read(&mut tx, &session).await? {
+ match state {
+ SessionRetirement::Removing | SessionRetirement::Removed => {
+ return Ok(SessionRemovalResult::Accepted(state));
+ }
+ SessionRetirement::Archiving => return Err(StoreError::SessionBusy),
+ SessionRetirement::Archived => {}
+ }
+ }
+ let actual: i64 =
+ sqlx::query_scalar("SELECT revision FROM session_control WHERE id=?")
+ .bind(&session)
+ .fetch_optional(&mut *tx)
+ .await?
+ .ok_or(StoreError::SessionNotFound)?;
+ if actual as u64 != expected {
+ return Ok(SessionRemovalResult::RevisionConflict {
+ expected,
+ actual: actual as u64,
+ });
+ }
+ plan::fence(&mut tx, &session, plan::Action::Remove).await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)?;
+ commits.send_modify(|_| {});
+ Ok(SessionRemovalResult::Accepted(SessionRetirement::Removing))
+ })
+ })
+ .await
+ }
+
+ pub async fn session_retirement(
+ &self,
+ session: &str,
+ ) -> Result<Option<SessionRetirement>, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| Box::pin(async move { read(connection, &session).await }))
+ .await
+ }
+
+ /// Bounded recovery scan; the fence is durable even if its requester vanished.
+ pub async fn pending_session_retirements(
+ &self,
+ after: Option<&str>,
+ ) -> Result<Vec<String>, StoreError> {
+ self.validate_root()?;
+ if let Some(after) = after {
+ validate_id(after)?;
+ }
+ let after = after.map(str::to_owned);
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ Ok(sqlx::query_scalar(
+ "SELECT session_id FROM session_retirements WHERE completed=0
+ AND (?1 IS NULL OR session_id>?1) ORDER BY session_id LIMIT 32",
+ )
+ .bind(after)
+ .fetch_all(connection)
+ .await?)
+ })
+ })
+ .await
+ }
+
+ /// The Host has drained in-memory owners and cleaned owned workspace resources.
+ /// Recheck durable settlement before dropping control metadata. Original log
+ /// evidence stays available to copies; history ownership is not execution authority.
+ pub async fn finish_session_retirement(
+ &self,
+ session: &str,
+ ) -> Result<SessionRetirement, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ let state = read(&mut tx, &session)
+ .await?
+ .ok_or(StoreError::SessionNotFound)?;
+ if !state.pending() {
+ return Ok(state);
+ }
+ if !settled(&mut tx, &session).await? {
+ return Ok(state);
+ }
+ if state == SessionRetirement::Archiving {
+ sqlx::query(
+ "UPDATE session_retirements SET completed=1 WHERE session_id=?",
+ )
+ .bind(&session)
+ .execute(&mut *tx)
+ .await?;
+ advance_catalog(&mut tx).await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)?;
+ return Ok(SessionRetirement::Archived);
+ }
+ // Membership is retained proof, not a disposable UI projection:
+ // descendants may pin an archive whose writer inherited its target.
+ // Verifying that archive/checkpoint still needs the writer's cut.
+ for statement in [
+ "DELETE FROM session_history_artifacts WHERE session_id=?",
+ "DELETE FROM session_revision_sources WHERE session_id=?",
+ "DELETE FROM transcript_rows WHERE session_id=?",
+ "DELETE FROM transcript_text WHERE session_id=?",
+ "DELETE FROM transcript_progress WHERE session_id=?",
+ "DELETE FROM catalog_messages WHERE session_id=?",
+ "DELETE FROM session_read_state WHERE session_id=?",
+ "DELETE FROM artifacts WHERE session_id=?",
+ "DELETE FROM artifact_catalog WHERE session_id=?",
+ "DELETE FROM shell_runs WHERE session_id=?",
+ "DELETE FROM session_processes WHERE session_id=?",
+ "DELETE FROM message_queue_state WHERE session_id=?",
+ "DELETE FROM session_control WHERE id=?",
+ ] {
+ sqlx::query(statement)
+ .bind(&session)
+ .execute(&mut *tx)
+ .await?;
+ }
+ sqlx::query("UPDATE session_retirements SET completed=1 WHERE session_id=?")
+ .bind(&session)
+ .execute(&mut *tx)
+ .await?;
+ advance_catalog(&mut tx).await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)?;
+ Ok(SessionRetirement::Removed)
+ })
+ })
+ .await
+ }
+}
+
+async fn settled(connection: &mut SqliteConnection, session: &str) -> Result<bool, StoreError> {
+ let unsettled: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM runtime_events o WHERE o.kind='invocation_opened'
+ AND json_extract(o.event_json, '$.invocation.session_id')=?1
+ AND NOT EXISTS(SELECT 1 FROM runtime_events t
+ WHERE t.invocation_id=o.invocation_id AND t.kind='invocation_ended'))
+ OR EXISTS(SELECT 1 FROM shell_runs WHERE session_id=?1 AND
+ (active=1 OR json_extract(record_json, '$.state.outcome.kind')='orphaned'))
+ OR EXISTS(SELECT 1 FROM session_processes WHERE session_id=?1 AND cleaned=0)
+ OR EXISTS(SELECT 1 FROM host_effects WHERE outcome IS NULL
+ AND json_extract(request, '$.boundary.boundary.sessionId')=?1)
+ OR EXISTS(SELECT 1 FROM interaction_requests r WHERE session_id=?1
+ AND NOT EXISTS(SELECT 1 FROM interaction_outcomes o WHERE o.request_id=r.request_id))
+ OR EXISTS(SELECT 1 FROM message_admissions WHERE session_id=?1)",
+ )
+ .bind(session)
+ .fetch_one(connection)
+ .await?;
+ Ok(!unsettled)
+}
diff --git a/crates/event-log/src/sessions/removal/plan.rs b/crates/event-log/src/sessions/removal/plan.rs
new file mode 100644
index 0000000000..e83ccc15b1
--- /dev/null
+++ b/crates/event-log/src/sessions/removal/plan.rs
@@ -0,0 +1,298 @@
+/*
+ * 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::{EventLog, MAX_SAFE_INTEGER, StoreError, invalid, validate_id};
+use serde::{Deserialize, Serialize};
+use sqlx::{Connection, Row, SqliteConnection};
+use std::collections::BTreeSet;
+
+/// A frozen lifecycle plan; only Host-owned lineage and authority dependencies
+/// participate. Plugin business identifiers and display labels are irrelevant.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RemovalPlan {
+ pub remove: Vec<String>,
+ pub archive: Vec<String>,
+ pub archived_subtask_count: u64,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum RemoveFamilyResult {
+ Accepted(RemovalPlan),
+ RevisionConflict { expected: u64, actual: u64 },
+}
+
+/// Host-issued authority, checked against every directly removed family member
+/// in the commit transaction. Dependency archival is a consequence of retirement.
+pub enum RemovalAuthority {
+ Unmanaged,
+ Granted {
+ namespace: maka_plugins::storage::Namespace,
+ sessions: BTreeSet<String>,
+ },
+}
+
+impl RemovalAuthority {
+ async fn check(
+ &self,
+ connection: &mut SqliteConnection,
+ plan: &RemovalPlan,
+ ) -> Result<(), StoreError> {
+ for session in &plan.remove {
+ let manager: Option<(String, String)> = sqlx::query_as(
+ "SELECT package_id,scope_id FROM plugin_sessions WHERE session_id=? AND managed=1",
+ )
+ .bind(session)
+ .fetch_optional(&mut *connection)
+ .await?;
+ let allowed = match self {
+ Self::Unmanaged => manager.is_none(),
+ Self::Granted {
+ namespace,
+ sessions,
+ } => {
+ sessions.contains(session)
+ && manager.is_none_or(|(package, scope)| {
+ package == namespace.package()
+ && scope == String::from(namespace.scope().clone())
+ })
+ }
+ };
+ if !allowed {
+ return Err(StoreError::SessionConflict);
+ }
+ }
+ Ok(())
+ }
+}
+
+pub(super) enum Action {
+ Remove,
+ Archive,
+}
+
+impl EventLog {
+ /// Read an accepted removal without requiring the removed catalog record.
+ pub async fn session_removal_receipt(
+ &self,
+ session: &str,
+ ) -> Result<Option<RemovalPlan>, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin().await?;
+ receipt(&mut tx, &session).await
+ })
+ })
+ .await
+ }
+
+ /// Preview is advisory; commit recomputes this plan inside its CAS transaction.
+ pub async fn preview_session_removal(&self, session: &str) -> Result<RemovalPlan, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ let session = session.to_owned();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin().await?;
+ read(&mut tx, &session).await
+ })
+ })
+ .await
+ }
+
+ /// Remove the revision family and archive its dependent families atomically.
+ /// A retry reads the accepted plan before checking any current metadata.
+ pub async fn remove_session_family(
+ &self,
+ session: &str,
+ expected: u64,
+ authority: RemovalAuthority,
+ ) -> Result<RemoveFamilyResult, StoreError> {
+ self.validate_root()?;
+ validate_id(session)?;
+ if expected == 0 || expected > MAX_SAFE_INTEGER {
+ return Err(invalid("invalid expected Session revision"));
+ }
+ let session = session.to_owned();
+ let commits = self.commits.clone();
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
+ if let Some(plan) = receipt(&mut tx, &session).await? {
+ return Ok(RemoveFamilyResult::Accepted(plan));
+ }
+ super::require_mutable(&mut tx, &session).await?;
+ let actual: i64 =
+ sqlx::query_scalar("SELECT revision FROM session_control WHERE id=?")
+ .bind(&session)
+ .fetch_optional(&mut *tx)
+ .await?
+ .ok_or(StoreError::SessionNotFound)?;
+ if actual as u64 != expected {
+ return Ok(RemoveFamilyResult::RevisionConflict {
+ expected,
+ actual: actual as u64,
+ });
+ }
+ let plan = read(&mut tx, &session).await?;
+ authority.check(&mut tx, &plan).await?;
+ for target in &plan.remove {
+ fence(&mut tx, target, Action::Remove).await?;
+ }
+ for target in &plan.archive {
+ fence(&mut tx, target, Action::Archive).await?;
+ }
+ sqlx::query("INSERT INTO session_removal_receipts VALUES (?,?)")
+ .bind(&session)
+ .bind(serde_json::to_string(&plan)?)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await.map_err(StoreError::CommitUnknown)?;
+ commits.send_modify(|_| {});
+ Ok(RemoveFamilyResult::Accepted(plan))
+ })
+ })
+ .await
+ }
+}
+
+async fn receipt(
+ connection: &mut SqliteConnection,
+ session: &str,
+) -> Result<Option<RemovalPlan>, StoreError> {
+ let receipt: Option<String> =
+ sqlx::query_scalar("SELECT plan_json FROM session_removal_receipts WHERE session_id=?")
+ .bind(session)
+ .fetch_optional(&mut *connection)
+ .await?;
+ if let Some(receipt) = receipt {
+ return Ok(Some(serde_json::from_str(&receipt)?));
+ }
+ // Another member's removal may already have retired this identity.
+ Ok(super::read(connection, session)
+ .await?
+ .filter(|state| state.removes())
+ .map(|_| RemovalPlan {
+ remove: vec![session.to_owned()],
+ archive: Vec::new(),
+ archived_subtask_count: 0,
+ }))
+}
+
+async fn read(connection: &mut SqliteConnection, session: &str) -> Result<RemovalPlan, StoreError> {
+ let rows = sqlx::query(
+ "WITH RECURSIVE families AS (
+ SELECT s.id, s.archived, COALESCE(c.state,'committed') AS copy_state,
+ CASE WHEN json_extract(c.lineage_json,'$.kind')='revision'
+ THEN json_extract(c.lineage_json,'$.root_session_id') ELSE s.id END AS family,
+ p.authority_session_id AS parent
+ FROM session_control s
+ LEFT JOIN session_history_copies c ON c.session_id=s.id
+ LEFT JOIN plugin_sessions p ON p.session_id=s.id
+ WHERE NOT EXISTS(SELECT 1 FROM session_retirements r
+ WHERE r.session_id=s.id AND r.remove_session=1)
+ ), root AS (SELECT family FROM families WHERE id=?1), dependents(id) AS (
+ SELECT id FROM families WHERE family=(SELECT family FROM root)
+ UNION SELECT child.id FROM families child JOIN dependents d
+ ON child.parent=d.id OR child.family=d.id
+ ) SELECT f.id, f.family, f.archived, f.family=(SELECT family FROM root) AS removes
+ FROM families f JOIN dependents d ON f.id=d.id
+ WHERE f.copy_state<>'preparing' OR f.id=?1
+ ORDER BY removes DESC, f.id LIMIT 4097",
+ )
+ .bind(session)
+ .fetch_all(connection)
+ .await?;
+ if rows.is_empty() {
+ return Err(StoreError::SessionNotFound);
+ }
+ if rows.len() > 4096 {
+ return Err(StoreError::PrefixTooLarge);
+ }
+ let mut plan = RemovalPlan {
+ remove: Vec::new(),
+ archive: Vec::new(),
+ archived_subtask_count: 0,
+ };
+ let mut archived_families = BTreeSet::new();
+ for row in rows {
+ let id: String = row.try_get("id")?;
+ if row.try_get::<bool, _>("removes")? {
+ plan.remove.push(id);
+ } else {
+ plan.archive.push(id);
+ if !row.try_get::<bool, _>("archived")? {
+ archived_families.insert(row.try_get::<String, _>("family")?);
+ }
+ }
+ }
+ plan.archived_subtask_count = archived_families.len() as u64;
+ Ok(plan)
+}
+
+pub(super) async fn fence(
+ connection: &mut SqliteConnection,
+ session: &str,
+ action: Action,
+) -> Result<(), StoreError> {
+ if let Some(previous) = super::read(connection, session).await? {
+ match action {
+ Action::Archive => return Ok(()),
+ Action::Remove if previous.removes() => return Ok(()),
+ Action::Remove => {}
+ }
+ }
+ let remove = matches!(action, Action::Remove);
+ sqlx::query(
+ "INSERT INTO session_retirements(session_id,remove_session) VALUES (?,?)
+ ON CONFLICT(session_id) DO UPDATE SET remove_session=excluded.remove_session, completed=0",
+ )
+ .bind(session)
+ .bind(remove)
+ .execute(&mut *connection)
+ .await?;
+ if !remove {
+ sqlx::query("UPDATE session_control SET archived=1 WHERE id=?")
+ .bind(session)
+ .execute(&mut *connection)
+ .await?;
+ }
+ // Accepted queue identities and payload deletion share the lifecycle commit.
+ sqlx::query(
+ "INSERT INTO message_cancellations(session_id,message_id,cancellation_id)
+ SELECT session_id,message_id,?1 FROM message_admissions WHERE session_id=?1",
+ )
+ .bind(session)
+ .execute(&mut *connection)
+ .await?;
+ let cancelled = sqlx::query("DELETE FROM message_admissions WHERE session_id=?")
+ .bind(session)
+ .execute(&mut *connection)
+ .await?
+ .rows_affected();
+ if cancelled > 0 {
+ crate::message_queue::bump(connection, session).await?;
+ }
+ super::super::advance_revision(connection, session).await
+}
diff --git a/crates/event-log/src/shell_runs.rs b/crates/event-log/src/shell_runs.rs
index 75cfaf5ea3..7c7d6e8d78 100644
--- a/crates/event-log/src/shell_runs.rs
+++ b/crates/event-log/src/shell_runs.rs
@@ -93,7 +93,7 @@ impl EventLog {
if inserted.rows_affected() != 1 {
return Err(StoreError::ShellConflict);
}
- crate::sessions::copy::retain(&mut tx, &record.session_id).await?;
+ crate::sessions::retain(&mut tx, &record.session_id).await?;
tx.commit().await.map_err(StoreError::CommitUnknown)?;
// Publish on the independent SQL owner even if the caller
// abandoned its response after admission.
diff --git a/crates/event-log/src/steering_delivery.rs b/crates/event-log/src/steering_delivery.rs
index ca89a371c0..ff06f61082 100644
--- a/crates/event-log/src/steering_delivery.rs
+++ b/crates/event-log/src/steering_delivery.rs
@@ -36,6 +36,7 @@ impl EventLog {
.map_err(|error| match error {
StoreError::CommitUnknown(error) => CommitError::OutcomeUnknown(error.to_string()),
StoreError::OperationUnknown => CommitError::OutcomeUnknown(error.to_string()),
+ StoreError::SessionRetired => CommitError::Retired,
other => CommitError::Rejected(other.to_string()),
})
}
diff --git a/crates/event-log/src/workspace.rs b/crates/event-log/src/workspace.rs
index 4ad475fac0..b51e10c954 100644
--- a/crates/event-log/src/workspace.rs
+++ b/crates/event-log/src/workspace.rs
@@ -34,6 +34,32 @@ pub struct WorkspaceSession {
}
impl EventLog {
+ /// Ownership, not quiescence: another retained Session keeps a managed
+ /// checkout alive regardless of how many past users shared that directory.
+ pub async fn workspace_has_other_session(
+ &self,
+ cwd: &str,
+ session: &str,
+ ) -> Result<bool, StoreError> {
+ self.validate_root()?;
+ crate::sessions::validate_id(session)?;
+ let (cwd, session) = (cwd.to_owned(), session.to_owned());
+ self.connection
+ .run(move |connection| {
+ Box::pin(async move {
+ Ok(sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM session_control
+ WHERE json_extract(configuration, '$.workspace.hostCwd')=? AND id<>?)",
+ )
+ .bind(cwd)
+ .bind(session)
+ .fetch_one(connection)
+ .await?)
+ })
+ })
+ .await
+ }
+
pub async fn workspace_fence(&self, cwd: &str) -> Result<WorkspaceFence, StoreError> {
self.validate_root()?;
let cwd = cwd.to_owned();
diff --git a/crates/event-log/tests/archive.rs b/crates/event-log/tests/archive.rs
index aa1b40f10b..25709b694a 100644
--- a/crates/event-log/tests/archive.rs
+++ b/crates/event-log/tests/archive.rs
@@ -38,6 +38,81 @@ mod fixtures;
mod lineage;
use fixtures::*;
+#[tokio::test]
+async fn retirement_fences_new_effects_without_rejecting_accepted_results_or_exact_replay() {
+ use maka_event_log::sessions::SessionRetirement;
+ use maka_runtime::event::CommitError;
+ let directory = tempfile::tempdir().unwrap();
+ let log = EventLog::open(&directory.path().join("retirement.sqlite"))
+ .await
+ .unwrap();
+ log.create_session("session", "create", &json!({}), 1)
+ .await
+ .unwrap();
+ open(&log, "run", false).await;
+ let accepted = request("run", "step", None);
+ let sequence = log.append(&accepted).await.unwrap();
+ let revision = log
+ .get_session::<serde_json::Value>("session")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ log.begin_session_removal("session", revision)
+ .await
+ .unwrap();
+ assert_eq!(log.append(&accepted).await.unwrap(), sequence);
+ let output = serde_json::from_value(json!({
+ "parts":[{"kind":"tool_call","call":{"id":"call","name":"Read","input":{"path":"file"},"provider_executed":false}}],
+ "finish_reason":"tool-calls","usage":{}
+ })).unwrap();
+ log.append(&event(
+ "run",
+ Fact::ModelCompleted {
+ step_id: "step".into(),
+ output,
+ },
+ ))
+ .await
+ .unwrap();
+ assert!(matches!(
+ log.append(&request("run", "next", None)).await,
+ Err(CommitError::Retired)
+ ));
+ assert!(matches!(
+ log.append(&event(
+ "run",
+ Fact::ToolDispatched {
+ operation_id: "step:call".into(),
+ call: ToolCallIdentity::provider("step".into(), "call".into()),
+ name: "Read".into(),
+ input: json!({"path":"file"}),
+ }
+ ))
+ .await,
+ Err(CommitError::Retired)
+ ));
+ log.append(&event(
+ "run",
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Cancelled {
+ source: "session_removal".into(),
+ },
+ },
+ ))
+ .await
+ .unwrap();
+ assert_eq!(
+ log.finish_session_retirement("session").await.unwrap(),
+ SessionRetirement::Removed
+ );
+ assert!(matches!(
+ log.append(&accepted).await,
+ Err(CommitError::Retired)
+ ));
+ log.close().await.unwrap();
+}
+
#[tokio::test]
async fn archive_atomic_retry_reopen_scope_and_source_integrity() {
let directory = tempfile::tempdir().unwrap();
@@ -696,6 +771,19 @@ async fn inherited_results_prune_and_compact_without_changing_siblings_or_frozen
.event_id,
checkpoint.event().id
);
+ // Nested pins still need the intermediate writer's inherited ownership and
+ // checkpoint evidence even after its live Session and materials are gone.
+ let revision = log
+ .get_session::<serde_json::Value>("branch")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ log.begin_session_removal("branch", revision).await.unwrap();
+ assert_eq!(
+ log.finish_session_retirement("branch").await.unwrap(),
+ maka_event_log::sessions::SessionRetirement::Removed
+ );
assert_eq!(
log.read_model_context("nested", None, 100, 65536)
.await
diff --git a/crates/event-log/tests/message_queue.rs b/crates/event-log/tests/message_queue.rs
index 4cbee377d6..568b0824f4 100644
--- a/crates/event-log/tests/message_queue.rs
+++ b/crates/event-log/tests/message_queue.rs
@@ -32,6 +32,193 @@ use serde_json::json;
mod support;
use support::{admission, append, command, invocation, opening};
+#[tokio::test]
+async fn removal_atomically_cancels_pending_work_and_keeps_accepted_settlement_across_restart() {
+ use maka_event_log::sessions::{SessionRemovalResult as Result, SessionRetirement as State};
+ for active in [false, true] {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("removal.sqlite");
+ let log = EventLog::open(&path).await.unwrap();
+ log.create_session("session", "create", &json!({}), 1)
+ .await
+ .unwrap();
+ let process = uuid::Uuid::new_v4();
+ log.admit_session_process("session", process).await.unwrap();
+ let owner = invocation("first");
+ if active {
+ append(&log, &owner, opening()).await;
+ }
+ let pending = admission(
+ &owner,
+ "pending",
+ if active {
+ Disposition::Followup
+ } else {
+ Disposition::TurnStarted
+ },
+ );
+ log.admit_message(pending.clone()).await.unwrap();
+ let revision = log
+ .get_session::<serde_json::Value>("session")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ assert!(matches!(
+ log.begin_session_removal("session", revision + 1)
+ .await
+ .unwrap(),
+ Result::RevisionConflict { .. }
+ ));
+ let inspect = rusqlite::Connection::open(&path).unwrap();
+ inspect
+ .execute_batch(
+ "CREATE TRIGGER reject_retirement BEFORE INSERT ON message_cancellations
+ BEGIN SELECT RAISE(ABORT, 'cancellation failure'); END;",
+ )
+ .unwrap();
+ assert!(
+ log.begin_session_removal("session", revision)
+ .await
+ .is_err()
+ );
+ assert_eq!(log.session_retirement("session").await.unwrap(), None);
+ assert_eq!(
+ log.pending_messages("session").await.unwrap(),
+ vec![pending.clone()]
+ );
+ inspect
+ .execute_batch("DROP TRIGGER reject_retirement")
+ .unwrap();
+ drop(inspect);
+ assert_eq!(
+ log.begin_session_removal("session", revision)
+ .await
+ .unwrap(),
+ Result::Accepted(State::Removing)
+ );
+ assert!(!log.session_retirement_ready("session").await.unwrap());
+ assert!(
+ log.admit_session_process("session", uuid::Uuid::new_v4())
+ .await
+ .is_err()
+ );
+ assert!(log.message_cancelled("session", "pending").await.unwrap());
+ assert!(
+ log.get_session::<serde_json::Value>("session")
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ log.list_sessions::<serde_json::Value>(None, None, 32)
+ .await
+ .unwrap()
+ .sessions
+ .is_empty()
+ );
+ assert!(
+ log.retiring_session::<serde_json::Value>("session")
+ .await
+ .unwrap()
+ .is_some()
+ );
+ assert!(log.pending_message_sessions(None).await.unwrap().is_empty());
+ assert!(log.admit_message(pending).await.is_err());
+ assert!(matches!(
+ log.retain_session("session").await,
+ Err(StoreError::SessionRetired)
+ ));
+ assert!(
+ log.update_session_metadata(
+ "session",
+ revision + 1,
+ |_: &mut serde_json::Value| Ok(())
+ )
+ .await
+ .is_err()
+ );
+ if active {
+ assert_eq!(
+ log.finish_session_retirement("session").await.unwrap(),
+ State::Removing
+ );
+ append(
+ &log,
+ &owner,
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Cancelled {
+ source: "session_removal".into(),
+ },
+ },
+ )
+ .await;
+ }
+ log.close().await.unwrap();
+ let log = EventLog::open(&path).await.unwrap();
+ assert!(
+ !log.session_retirement_ready("session").await.unwrap(),
+ "losing the native process handle does not prove cleanup"
+ );
+ assert_eq!(
+ log.finish_session_retirement("session").await.unwrap(),
+ State::Removing
+ );
+ log.clean_session_process(process).await.unwrap();
+ assert!(log.session_retirement_ready("session").await.unwrap());
+ assert_eq!(
+ log.pending_session_retirements(None).await.unwrap(),
+ ["session"]
+ );
+ assert_eq!(
+ log.begin_session_removal("session", revision)
+ .await
+ .unwrap(),
+ Result::Accepted(State::Removing)
+ );
+ assert_eq!(
+ log.finish_session_retirement("session").await.unwrap(),
+ State::Removed
+ );
+ assert_eq!(
+ log.finish_session_retirement("session").await.unwrap(),
+ State::Removed
+ );
+ assert_eq!(
+ log.begin_session_removal("session", revision)
+ .await
+ .unwrap(),
+ Result::Accepted(State::Removed)
+ );
+ assert!(
+ log.get_session::<serde_json::Value>("session")
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ log.create_session("session", "create", &json!({}), 2)
+ .await
+ .is_err()
+ );
+ assert!(
+ log.append(
+ &EventWrite::plain(RuntimeEvent::new(invocation("late"), opening())).unwrap()
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ log.pending_session_retirements(None)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(log.message_cancelled("session", "pending").await.unwrap());
+ log.close().await.unwrap();
+ }
+}
+
#[tokio::test]
async fn queue_edits_cancel_or_deliver_once_with_atomic_revision_and_original_ownership() {
let temp = tempfile::tempdir().unwrap();
diff --git a/crates/event-log/tests/session_copy.rs b/crates/event-log/tests/session_copy.rs
index 56c62fdec8..af1e298244 100644
--- a/crates/event-log/tests/session_copy.rs
+++ b/crates/event-log/tests/session_copy.rs
@@ -101,6 +101,322 @@ async fn copy(
*session
}
+#[tokio::test]
+async fn removal_does_not_treat_revision_history_as_management_authority() {
+ use maka_event_log::sessions::{PluginSession, RemovalAuthority, RemoveFamilyResult};
+ use maka_plugins::{composition::Scope, storage::Namespace};
+ let temp = tempfile::tempdir().unwrap();
+ let log = EventLog::open(&temp.path().join("authority.sqlite"))
+ .await
+ .unwrap();
+ let namespace = Namespace::new("owner", Scope::Profile).unwrap();
+ log.create_session("parent", "parent", &json!({}), 1)
+ .await
+ .unwrap();
+ log.create_plugin_session(
+ &PluginSession {
+ session_id: "managed".into(),
+ creator: namespace.clone(),
+ fingerprint: "managed".into(),
+ managed: true,
+ authority_session_id: None,
+ },
+ &json!({}),
+ 1,
+ )
+ .await
+ .unwrap();
+ turn(&log, "managed", "source-turn", false).await;
+ let source = log.get_session::<Value>("managed").await.unwrap().unwrap();
+ log.copy_plugin_session(
+ SessionCopy {
+ source_session_id: source.id,
+ target_session_id: "unmanaged-revision".into(),
+ expected_source_revision: source.revision,
+ purpose: maka_runtime::session::CopyPurpose::Revision {
+ turn_id: "source-turn".into(),
+ },
+ },
+ &json!({}),
+ 2,
+ PluginSession {
+ session_id: "unmanaged-revision".into(),
+ creator: namespace.clone(),
+ fingerprint: "revision".into(),
+ managed: false,
+ authority_session_id: Some("parent".into()),
+ },
+ )
+ .await
+ .unwrap();
+ log.retain_session("unmanaged-revision").await.unwrap();
+ let revision = log
+ .get_session::<Value>("unmanaged-revision")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ for authority in [
+ RemovalAuthority::Unmanaged,
+ RemovalAuthority::Granted {
+ namespace,
+ sessions: ["unmanaged-revision".into()].into_iter().collect(),
+ },
+ ] {
+ assert!(matches!(
+ log.remove_session_family("unmanaged-revision", revision, authority)
+ .await,
+ Err(StoreError::SessionConflict)
+ ));
+ assert!(log.session_retirement("managed").await.unwrap().is_none());
+ assert!(
+ log.session_removal_receipt("unmanaged-revision")
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+ let revision = log
+ .get_session::<Value>("parent")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ let RemoveFamilyResult::Accepted(plan) = log
+ .remove_session_family("parent", revision, RemovalAuthority::Unmanaged)
+ .await
+ .unwrap()
+ else {
+ panic!("unchanged revision");
+ };
+ assert_eq!(plan.archive, ["unmanaged-revision"]);
+ assert!(
+ !log.get_session::<Value>("managed")
+ .await
+ .unwrap()
+ .unwrap()
+ .archived
+ );
+ log.close().await.unwrap();
+}
+
+#[tokio::test]
+async fn family_removal_freezes_one_atomic_plan_and_does_not_rearchive_restored_dependents() {
+ use maka_event_log::sessions::{PluginSession, RemoveFamilyResult, SessionRetirement};
+ use maka_plugins::{composition::Scope, storage::Namespace};
+ use maka_runtime::session::CopyPurpose;
+ use sqlx::Connection;
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("family.sqlite");
+ let log = EventLog::open(&path).await.unwrap();
+ log.create_session("root", "root", &json!({}), 1)
+ .await
+ .unwrap();
+ turn(&log, "root", "root-turn", false).await;
+ for target in ["revision", "draft", "branch"] {
+ let source = log.get_session::<Value>("root").await.unwrap().unwrap();
+ copy(
+ &log,
+ SessionCopy {
+ source_session_id: source.id,
+ target_session_id: target.into(),
+ expected_source_revision: source.revision,
+ purpose: if target == "branch" {
+ CopyPurpose::EmptySideConversation
+ } else {
+ CopyPurpose::Revision {
+ turn_id: "root-turn".into(),
+ }
+ },
+ },
+ )
+ .await;
+ if target == "revision" {
+ log.retain_session(target).await.unwrap();
+ }
+ }
+ let child = |id: &str, parent: &str| PluginSession {
+ session_id: id.into(),
+ creator: Namespace::new("any-package", Scope::Profile).unwrap(),
+ fingerprint: id.into(),
+ managed: false,
+ authority_session_id: Some(parent.into()),
+ };
+ log.create_plugin_session(&child("child", "revision"), &json!({}), 2)
+ .await
+ .unwrap();
+ turn(&log, "child", "child-turn", false).await;
+ let source = log.get_session::<Value>("child").await.unwrap().unwrap();
+ copy(
+ &log,
+ SessionCopy {
+ source_session_id: source.id,
+ target_session_id: "child-revision".into(),
+ expected_source_revision: source.revision,
+ purpose: CopyPurpose::Revision {
+ turn_id: "child-turn".into(),
+ },
+ },
+ )
+ .await;
+ log.create_plugin_session(&child("grandchild", "child-revision"), &json!({}), 3)
+ .await
+ .unwrap();
+ log.create_plugin_session(&child("already-archived", "root"), &json!({}), 4)
+ .await
+ .unwrap();
+ log.set_session_archived::<Value>("already-archived", true, 5)
+ .await
+ .unwrap();
+ let preview = log.preview_session_removal("revision").await.unwrap();
+ assert_eq!(preview.remove, ["revision", "root"]);
+ assert_eq!(
+ preview.archive,
+ ["already-archived", "child", "child-revision", "grandchild"]
+ );
+ assert_eq!(preview.archived_subtask_count, 2);
+ // Preview does not reserve an old dependency set. Admission recomputes it.
+ log.create_plugin_session(&child("late", "root"), &json!({}), 6)
+ .await
+ .unwrap();
+ let revision = log
+ .get_session::<Value>("revision")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ assert!(matches!(
+ log.remove_session_family(
+ "revision",
+ revision + 1,
+ maka_event_log::sessions::RemovalAuthority::Unmanaged
+ )
+ .await
+ .unwrap(),
+ RemoveFamilyResult::RevisionConflict { .. }
+ ));
+ let mut faults = sqlx::SqliteConnection::connect_with(
+ &sqlx::sqlite::SqliteConnectOptions::new().filename(&path),
+ )
+ .await
+ .unwrap();
+ sqlx::query(
+ "CREATE TRIGGER refuse_archive BEFORE INSERT ON session_retirements
+ WHEN NEW.session_id='child' BEGIN SELECT RAISE(ABORT,'archive failure'); END",
+ )
+ .execute(&mut faults)
+ .await
+ .unwrap();
+ assert!(
+ log.remove_session_family(
+ "revision",
+ revision,
+ maka_event_log::sessions::RemovalAuthority::Unmanaged
+ )
+ .await
+ .is_err()
+ );
+ assert!(log.session_retirement("root").await.unwrap().is_none());
+ assert!(
+ !log.get_session::<Value>("child")
+ .await
+ .unwrap()
+ .unwrap()
+ .archived
+ );
+ sqlx::query("DROP TRIGGER refuse_archive")
+ .execute(&mut faults)
+ .await
+ .unwrap();
+ faults.close().await.unwrap();
+ let RemoveFamilyResult::Accepted(plan) = log
+ .remove_session_family(
+ "revision",
+ revision,
+ maka_event_log::sessions::RemovalAuthority::Unmanaged,
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("unchanged revision");
+ };
+ assert_eq!(plan.archived_subtask_count, 3);
+ assert!(plan.archive.contains(&"late".into()));
+ assert!(log.get_session::<Value>("root").await.unwrap().is_none());
+ assert!(log.get_session::<Value>("draft").await.unwrap().is_some());
+ assert!(log.get_session::<Value>("branch").await.unwrap().is_some());
+ assert!(
+ log.get_session::<Value>("child")
+ .await
+ .unwrap()
+ .unwrap()
+ .archived
+ );
+ assert!(log.retain_session("child").await.is_err());
+ assert!(matches!(
+ log.set_session_archived::<Value>("child", false, 7).await,
+ Err(StoreError::SessionBusy)
+ ));
+ log.close().await.unwrap();
+ let log = EventLog::open(&path).await.unwrap();
+ for session in &plan.remove {
+ assert_eq!(
+ log.finish_session_retirement(session).await.unwrap(),
+ SessionRetirement::Removed
+ );
+ }
+ for session in &plan.archive {
+ assert_eq!(
+ log.finish_session_retirement(session).await.unwrap(),
+ SessionRetirement::Archived
+ );
+ }
+ let receipt = log
+ .session_copy_receipt("child-revision")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(copy(&log, receipt.request).await.id, "child-revision");
+ let archived = log.get_session::<Value>("child").await.unwrap().unwrap();
+ let branch = copy(
+ &log,
+ SessionCopy {
+ source_session_id: archived.id,
+ target_session_id: "from-archived".into(),
+ expected_source_revision: archived.revision,
+ purpose: CopyPurpose::EmptySideConversation,
+ },
+ )
+ .await;
+ assert_eq!(branch.id, "from-archived");
+ assert!(
+ log.retain_session("child").await.is_err(),
+ "copying history grants no execution"
+ );
+ log.set_session_archived::<Value>("child", false, 8)
+ .await
+ .unwrap();
+ turn(&log, "child", "restored-turn", false).await;
+ assert_eq!(
+ log.remove_session_family(
+ "revision",
+ revision,
+ maka_event_log::sessions::RemovalAuthority::Unmanaged
+ )
+ .await
+ .unwrap(),
+ RemoveFamilyResult::Accepted(plan)
+ );
+ assert!(
+ !log.get_session::<Value>("child")
+ .await
+ .unwrap()
+ .unwrap()
+ .archived
+ );
+ log.close().await.unwrap();
+}
+
#[tokio::test]
async fn copies_own_history_and_files_without_replaying_execution_across_retries_and_reopen() {
let temp = tempfile::tempdir().unwrap();
@@ -236,20 +552,19 @@ async fn copies_own_history_and_files_without_replaying_execution_across_retries
.await,
Err(StoreError::SessionConflict)
));
- // Remove source catalog state, not retained canonical facts. History reads
- // and exact receipts must not rely on a live source Session.
- let inspect = rusqlite::Connection::open(&path).unwrap();
- inspect
- .execute_batch(
- "PRAGMA foreign_keys=ON;
- BEGIN;
- DELETE FROM artifact_catalog WHERE session_id='source';
- DELETE FROM session_read_state WHERE session_id='source';
- DELETE FROM session_control WHERE id='source';
- COMMIT;",
- )
- .unwrap();
- drop(inspect);
+ // Real removal releases source resources without removing another Session's
+ // retained evidence. Receipt recovery cannot depend on source catalog state.
+ let revision = log
+ .get_session::<Value>("source")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ log.begin_session_removal("source", revision).await.unwrap();
+ assert_eq!(
+ log.finish_session_retirement("source").await.unwrap(),
+ maka_event_log::sessions::SessionRetirement::Removed
+ );
log.close().await.unwrap();
let log = EventLog::open(&path).await.unwrap();
assert_eq!(
diff --git a/crates/fs-tools/src/worktree.rs b/crates/fs-tools/src/worktree.rs
index 4eaa256554..bc55167427 100644
--- a/crates/fs-tools/src/worktree.rs
+++ b/crates/fs-tools/src/worktree.rs
@@ -22,6 +22,7 @@
mod checkout;
mod ownership;
mod patch;
+mod removal;
use crate::workspace::{git, invalid};
use serde::{Deserialize, Serialize};
@@ -132,6 +133,7 @@ impl Worktrees {
self.validate(binding)?;
interrupted(cancel)?;
let _owner = ownership::lock(&self.root, binding)?;
+ removal::require_live(binding)?;
if binding.directory.try_exists()? {
return self.inspect(binding);
}
@@ -142,6 +144,7 @@ impl Worktrees {
pub fn inspect(&self, binding: &Binding) -> io::Result<()> {
self.validate(binding)?;
ownership::verify(&self.root.join(&binding.id), binding)?;
+ removal::require_live(binding)?;
ownership::verify(&binding.admin(), binding)?;
let repo = git::discover(&binding.directory)?;
if repo
diff --git a/crates/fs-tools/src/worktree/ownership.rs b/crates/fs-tools/src/worktree/ownership.rs
index ff987f6401..a663dd2475 100644
--- a/crates/fs-tools/src/worktree/ownership.rs
+++ b/crates/fs-tools/src/worktree/ownership.rs
@@ -26,7 +26,7 @@ use std::{
path::Path,
};
-const OWNER: &str = "maka-owner.json";
+pub(super) const OWNER: &str = "maka-owner.json";
pub(super) struct AllocationLock(File);
impl Drop for AllocationLock {
diff --git a/crates/fs-tools/src/worktree/removal.rs b/crates/fs-tools/src/worktree/removal.rs
new file mode 100644
index 0000000000..5abe5f9a34
--- /dev/null
+++ b/crates/fs-tools/src/worktree/removal.rs
@@ -0,0 +1,132 @@
+/*
+ * 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::{Binding, Worktrees, ownership};
+use crate::workspace::invalid;
+use std::{fs, io, path::Path};
+
+const RETIRED: &str = "retired";
+
+impl Worktrees {
+ /// Permanently retire an allocation after all users and writers have drained.
+ /// Retry after interruption. Keep user branches and commits; the tiny owned
+ /// allocation tombstone prevents a stale binding from recreating the checkout.
+ pub fn remove(&self, binding: &Binding) -> io::Result<()> {
+ self.validate(binding)?;
+ let _owner = ownership::lock(&self.root, binding)?;
+ let allocation = binding.directory.parent().expect("validated layout");
+ let admin = binding.admin();
+ let retired = is_retired(binding)?;
+ if directory_exists(&admin)? {
+ // The owner is removed last. An empty directory is the only valid
+ // interruption point after unlinking it and before removing admin.
+ if !retired || fs::read_dir(&admin)?.next().is_some() {
+ ownership::verify(&admin, binding)?;
+ }
+ }
+ directory_exists(&binding.directory)?;
+ directory_exists(&allocation.join("checkout"))?;
+ if !retired {
+ ownership::write_new(&allocation.join(RETIRED), b"retired\n")?;
+ ownership::sync(allocation)?;
+ }
+ let repo = gix::open::Options::isolated()
+ .strict_config(true)
+ .open(&binding.common_dir)
+ .map_err(io::Error::other)?
+ .to_thread_local();
+ let base = gix::hash::ObjectId::from_hex(binding.base_commit.as_bytes())
+ .map_err(io::Error::other)?;
+ for name in [binding.base_ref(), binding.branch()] {
+ if let Some(reference) = repo.try_find_reference(&name).map_err(io::Error::other)? {
+ // Do not remove a branch the user advanced, or a replaced ref.
+ // delete() compares the observed target under the Git ref lock.
+ if reference.target() == gix::refs::TargetRef::Object(&base) {
+ reference.delete().map_err(io::Error::other)?;
+ }
+ }
+ }
+ remove_directory(&binding.directory)?;
+ remove_directory(&allocation.join("checkout"))?;
+ remove_file(&allocation.join("checkout-ready"))?;
+ if directory_exists(&admin)? {
+ for entry in fs::read_dir(&admin)? {
+ let entry = entry?;
+ if entry.file_name() == ownership::OWNER {
+ continue;
+ }
+ if entry.file_type()?.is_dir() {
+ fs::remove_dir_all(entry.path())?;
+ } else {
+ fs::remove_file(entry.path())?;
+ }
+ }
+ ownership::sync(&admin)?;
+ remove_file(&admin.join(ownership::OWNER))?;
+ fs::remove_dir(&admin)?;
+ ownership::sync(admin.parent().expect("worktree admin parent"))?;
+ }
+ ownership::sync(allocation)
+ }
+}
+
+pub(super) fn require_live(binding: &Binding) -> io::Result<()> {
+ if is_retired(binding)? {
+ Err(invalid("worktree allocation is retired"))
+ } else {
+ Ok(())
+ }
+}
+
+fn is_retired(binding: &Binding) -> io::Result<bool> {
+ let path = binding
+ .directory
+ .parent()
+ .expect("validated layout")
+ .join(RETIRED);
+ match fs::symlink_metadata(&path) {
+ Ok(meta) if meta.is_file() && fs::read(&path)? == b"retired\n" => Ok(true),
+ Ok(_) => Err(invalid("invalid worktree retirement marker")),
+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
+ Err(error) => Err(error),
+ }
+}
+
+fn directory_exists(path: &Path) -> io::Result<bool> {
+ match fs::symlink_metadata(path) {
+ Ok(meta) if meta.is_dir() => Ok(true),
+ Ok(_) => Err(invalid("owned worktree directory was replaced")),
+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
+ Err(error) => Err(error),
+ }
+}
+
+fn remove_directory(path: &Path) -> io::Result<()> {
+ if directory_exists(path)? {
+ fs::remove_dir_all(path)?;
+ }
+ Ok(())
+}
+
+fn remove_file(path: &Path) -> io::Result<()> {
+ match fs::remove_file(path) {
+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+ other => other,
+ }
+}
diff --git a/crates/fs-tools/tests/worktree.rs b/crates/fs-tools/tests/worktree.rs
index ecdc7d8388..c5cee4fcd2 100644
--- a/crates/fs-tools/tests/worktree.rs
+++ b/crates/fs-tools/tests/worktree.rs
@@ -205,6 +205,18 @@ fn linked_worktree_is_git_compatible_and_reopening_preserves_child_changes() {
git(&source, &["status", "--porcelain"]).is_empty(),
"export is reversible against its base"
);
+ let child_commit = git(&source, &["rev-parse", "child-owned"]);
+ manager.remove(&binding).unwrap();
+ Worktrees::open(&root).unwrap().remove(&binding).unwrap();
+ assert!(!binding.directory().exists());
+ assert!(manager.ensure(&binding, &cancel).is_err());
+ assert_eq!(git(&source, &["rev-parse", "child-owned"]), child_commit);
+ assert!(
+ !git(&source, &["worktree", "list", "--porcelain"])
+ .contains(binding.directory().to_str().unwrap())
+ );
+ assert!(git(&source, &["for-each-ref", "refs/maka/", "refs/heads/maka/"]).is_empty());
+ assert!(git(&source, &["status", "--porcelain"]).is_empty());
}
}
@@ -249,6 +261,8 @@ fn worktree_recovery_rejects_dirty_sources_foreign_owners_and_missing_published_
let bytes = fs::read(&owner).unwrap();
fs::write(&owner, "{}").unwrap();
assert!(manager.ensure(&binding, &cancel).is_err());
+ assert!(manager.remove(&binding).is_err());
+ assert!(binding.directory().exists());
fs::write(&owner, bytes).unwrap();
fs::rename(binding.directory(), allocation.join("user-recovered")).unwrap();
assert!(
@@ -256,4 +270,50 @@ fn worktree_recovery_rejects_dirty_sources_foreign_owners_and_missing_published_
"never reset a published but missing directory"
);
assert!(!binding.directory().exists());
+ manager.remove(&binding).unwrap();
+ assert_eq!(
+ fs::read_to_string(allocation.join("user-recovered/source.txt")).unwrap(),
+ "ready bytes preserved",
+ "cleanup only removes its known checkout paths"
+ );
+}
+
+#[test]
+fn interrupted_removal_preserves_advanced_branches_and_cannot_resurrect() {
+ let temp = tempfile::tempdir().unwrap();
+ let source = temp.path().join("repository");
+ repository(&source, "sha1");
+ let root = temp.path().join("host");
+ let manager = Worktrees::open(&root).unwrap();
+ let cancel = Arc::new(AtomicBool::new(false));
+ let id = "3".repeat(64);
+ let binding = manager.plan(&source, &id, cancel.clone()).unwrap();
+ manager.ensure(&binding, &cancel).unwrap();
+ fs::write(binding.directory().join("source.txt"), "committed\n").unwrap();
+ git(binding.directory(), &["commit", "-am", "keep this commit"]);
+ let branch = format!("refs/heads/maka/{id}");
+ let commit = git(&source, &["rev-parse", &branch]);
+ let allocation = binding.directory().parent().unwrap();
+ let admin = source.join(".git/worktrees").join(format!("maka-{id}"));
+ let owner = admin.join("maka-owner.json");
+ let proof = fs::read(&owner).unwrap();
+ fs::write(&owner, "{}").unwrap();
+ assert!(manager.remove(&binding).is_err());
+ assert!(!allocation.join("retired").exists());
+ assert!(binding.directory().exists());
+ fs::write(&owner, proof).unwrap();
+ // Crash after fencing and partially removing the checkout/admin payload.
+ fs::write(allocation.join("retired"), "retired\n").unwrap();
+ fs::remove_file(binding.directory().join("source.txt")).unwrap();
+ fs::remove_file(admin.join("index")).unwrap();
+ assert!(manager.ensure(&binding, &cancel).is_err());
+ manager.remove(&binding).unwrap();
+ assert_eq!(git(&source, &["rev-parse", &branch]), commit);
+ // Crash in the owner-unlink/rmdir gap leaves an empty admin directory.
+ fs::create_dir(&admin).unwrap();
+ Worktrees::open(&root).unwrap().remove(&binding).unwrap();
+ assert!(!admin.exists());
+ assert!(manager.ensure(&binding, &cancel).is_err());
+ assert_eq!(git(&source, &["rev-parse", &branch]), commit);
+ assert!(git(&source, &["status", "--porcelain"]).is_empty());
}
diff --git a/crates/js-runtime/src/plugin/sdk.js b/crates/js-runtime/src/plugin/sdk.js
index 4c537b4066..1246a6f5fe 100644
--- a/crates/js-runtime/src/plugin/sdk.js
+++ b/crates/js-runtime/src/plugin/sdk.js
@@ -208,6 +208,9 @@
},
resume: (input) => call('resume', input),
configure: (input) => call('configure', input),
+ removeSession: (input) => call('removeSession', input),
+ removalReceipt: (sessionId) => call('removalReceipt', { sessionId }),
+ previewRemoval: (sessionId) => call('previewRemoval', { sessionId }),
input: (invocation) => call('input', invocation),
readMessage: (input) => call('readMessage', input),
enqueue: (input) => call('enqueue', input),
diff --git a/crates/plugins/src/execution.rs b/crates/plugins/src/execution.rs
index b1e90f27ac..b0ad5d48c5 100644
--- a/crates/plugins/src/execution.rs
+++ b/crates/plugins/src/execution.rs
@@ -29,8 +29,10 @@ pub use message::{
Enqueue, Excerpt, MessageObservation, MessageReceipt, MessageResult, MessageState,
SessionMessage,
};
+mod removal;
mod root;
pub use interaction::{OfferInteraction, Prompt};
+pub use removal::{RemovalReceipt, RemoveSession, RemovedSession};
pub use root::{CreateRoot, RootApproval, RootTemplate, Settings as RootSettings};
/// Persisted constraints, not a bearer capability. Only an explicit Host grant
@@ -416,6 +418,23 @@ pub enum RevisionDisposition {
/// An acquired execution capability retains its captured permission ceiling.
pub trait Commands: Send + Sync + std::any::Any {
+ /// Remove an authorized revision family; every directly removed member must
+ /// be covered. Accepted work settles independently of the caller's lifetime.
+ fn remove_session(
+ &self,
+ request: RemoveSession,
+ ) -> futures_util::future::BoxFuture<'_, Result<RemovedSession, CommandError>>;
+ /// Read only an accepted removal. No catalog record or active execution is
+ /// required; current plugin identity and access are still checked.
+ fn removal_receipt(
+ &self,
+ session_id: String,
+ ) -> futures_util::future::BoxFuture<'_, Result<Option<RemovalReceipt>, CommandError>>;
+ /// Advisory count; removal recomputes and authorizes the plan at commit.
+ fn preview_removal(
+ &self,
+ session_id: String,
+ ) -> futures_util::future::BoxFuture<'_, Result<u64, CommandError>>;
/// Copy an immutable attachment between two Host-issued capabilities. Both
/// endpoints are reauthorized; a source Session ID alone grants nothing.
fn copy_attachment(
diff --git a/crates/plugins/src/execution/removal.rs b/crates/plugins/src/execution/removal.rs
new file mode 100644
index 0000000000..674098c4c4
--- /dev/null
+++ b/crates/plugins/src/execution/removal.rs
@@ -0,0 +1,62 @@
+/*
+ * 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 serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct RemoveSession {
+ pub session_id: String,
+ pub expected_revision: u64,
+}
+
+impl RemoveSession {
+ pub fn validate(&self) -> Result<(), crate::Error> {
+ crate::name(&self.session_id)?;
+ if self.expected_revision == 0 || self.expected_revision >= 1 << 53 {
+ return Err(crate::Error::Invalid("invalid Session revision".into()));
+ }
+ Ok(())
+ }
+}
+
+/// The accepted plan is durable; filesystem cleanup may still be pending.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct RemovalReceipt {
+ pub session_id: String,
+ pub archived_subtask_count: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(
+ tag = "kind",
+ rename_all = "snake_case",
+ rename_all_fields = "camelCase",
+ deny_unknown_fields
+)]
+pub enum RemovedSession {
+ Removed {
+ receipt: RemovalReceipt,
+ },
+ RevisionConflict {
+ expected_revision: u64,
+ actual_revision: u64,
+ },
+}
diff --git a/crates/protocol/src/authority.rs b/crates/protocol/src/authority.rs
index 4f70af7a4c..55e98ad69a 100644
--- a/crates/protocol/src/authority.rs
+++ b/crates/protocol/src/authority.rs
@@ -120,6 +120,7 @@ impl Operation {
| Self::SessionRecapGenerate
| Self::SessionRemove
| Self::SessionRemovePreview
+ | Self::SessionRemoveQuery
| Self::SessionRevisionAbandon
| Self::SessionRevisionCreate
| Self::SessionTranscriptPage
diff --git a/crates/protocol/src/operation.rs b/crates/protocol/src/operation.rs
index cbf700d2ca..6ca6a7283c 100644
--- a/crates/protocol/src/operation.rs
+++ b/crates/protocol/src/operation.rs
@@ -219,6 +219,7 @@ operations! {
SessionRecapGenerate => ("session.recap.generate", Command, Ready),
SessionRemove => ("session.remove", Command, Ready),
SessionRemovePreview => ("session.remove.preview", Query, Ready),
+ SessionRemoveQuery => ("session.remove.query", Query, Ready),
SessionRevisionAbandon => ("session.revision.abandon", Command, Ready),
SessionRevisionCreate => ("session.revision.create", Command, Ready),
SessionSharedQuery => ("session.shared.query", Query, Ready),
diff --git a/crates/protocol/src/session.rs b/crates/protocol/src/session.rs
index eedbf3052a..6636143617 100644
--- a/crates/protocol/src/session.rs
+++ b/crates/protocol/src/session.rs
@@ -132,6 +132,25 @@ pub struct SessionRemovePreviewInput {
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct SessionRemoveQueryInput {
+ pub session_id: String,
+}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(
+ tag = "kind",
+ rename_all = "snake_case",
+ rename_all_fields = "camelCase",
+ deny_unknown_fields
+)]
+pub enum SessionRemoveQueryResult {
+ Missing,
+ Removed {
+ session_id: String,
+ archived_subtask_count: u64,
+ },
+}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SessionRemovePreviewResult {
pub archivable_subtask_count: u64,
}
@@ -190,6 +209,8 @@ decoder!(
decoder!(decode_session_lifecycle_set_input, SessionLifecycleSetInput);
decoder!(decode_session_remove_input, SessionRemoveInput);
decoder!(decode_session_remove_result, SessionRemoveResult);
+decoder!(decode_session_remove_query_input, SessionRemoveQueryInput);
+decoder!(decode_session_remove_query_result, SessionRemoveQueryResult);
decoder!(
decode_session_remove_preview_input,
SessionRemovePreviewInput
diff --git a/crates/runtime-host/src/execution.rs b/crates/runtime-host/src/execution.rs
index 34af02224d..1074d0ce4d 100644
--- a/crates/runtime-host/src/execution.rs
+++ b/crates/runtime-host/src/execution.rs
@@ -32,9 +32,11 @@ mod plugins;
pub(crate) use plugins::ResourceTarget;
pub(crate) mod permissions;
mod prepare;
+mod processes;
mod provider;
mod read;
mod recovery;
+mod removal;
mod resume;
mod shell;
pub(crate) mod snapshot;
@@ -78,9 +80,10 @@ pub(crate) struct Executions {
interactions: Arc<crate::server::interactions::Interactions>,
active: Mutex<HashMap<String, ActiveRun>>,
submissions: message::Submissions,
- plugin_processes: Arc<Mutex<HashMap<String, usize>>>,
+ plugin_processes: processes::Registry,
workers: TaskTracker,
handoff_wake: tokio::sync::Notify,
+ removal_wake: tokio::sync::Notify,
shutdown: CancellationToken,
}
@@ -140,9 +143,10 @@ impl Executions {
interactions,
writes: Arc::new(maka_fs_tools::WriteCoordinator::default()),
active: Mutex::new(HashMap::new()),
- plugin_processes: Arc::default(),
+ plugin_processes: Default::default(),
workers,
handoff_wake: tokio::sync::Notify::new(),
+ removal_wake: tokio::sync::Notify::new(),
shutdown,
})
}
@@ -293,8 +297,10 @@ impl Executions {
fn requires_drain(error: &RunError) -> bool {
matches!(
error,
- RunError::Commit(_)
- | RunError::Store(StoreError::CommitUnknown(_) | StoreError::OperationUnknown)
+ RunError::Commit(
+ maka_runtime::event::CommitError::Rejected(_)
+ | maka_runtime::event::CommitError::OutcomeUnknown(_)
+ ) | RunError::Store(StoreError::CommitUnknown(_) | StoreError::OperationUnknown)
| RunError::Tool(ToolError::Persistence(_) | ToolError::CleanupUnconfirmed(_))
)
}
@@ -307,6 +313,7 @@ fn execution_error(error: RunError) -> OperationError {
Code::OutcomeUnknown
}
RunError::Busy => Code::SessionBusy,
+ RunError::Commit(maka_runtime::event::CommitError::Retired) => Code::NotFound,
RunError::ReconciliationRequired(_) => Code::OperationUnavailable,
RunError::InvalidInput(_) => Code::OperationUnavailable,
_ => Code::InternalFailure,
diff --git a/crates/runtime-host/src/execution/control.rs b/crates/runtime-host/src/execution/control.rs
index fa4d877140..891c8c01dc 100644
--- a/crates/runtime-host/src/execution/control.rs
+++ b/crates/runtime-host/src/execution/control.rs
@@ -22,6 +22,62 @@ use maka_protocol::OperationErrorCode as Code;
use maka_runtime::event::Invocation;
impl Executions {
+ /// The durable fence survives a lost requester. Never hold global admission
+ /// while waiting for another Session's resources to release native handles.
+ pub(crate) async fn drain_retiring_session(&self, session: &str) -> Result<bool> {
+ let admission = self.lock_admission().await;
+ if self
+ .log
+ .session_retirement(session)
+ .await
+ .map_err(internal)?
+ .is_none()
+ {
+ return Err(failure(
+ Code::OperationConflict,
+ "Session has no removal intent",
+ ));
+ }
+ let runs: Vec<_> = self
+ .active
+ .lock()
+ .unwrap()
+ .values()
+ .filter(|run| run.invocation.session_id == session)
+ .cloned()
+ .collect();
+ let mut completed = self.plugin_processes.stop(session);
+ for run in &runs {
+ run.cancellation.cancel();
+ completed.push(run.completed.clone());
+ }
+ for run in &runs {
+ self.interactions.stop_run(&run.invocation).await?;
+ }
+ drop(admission);
+ let drain = async {
+ self.shells.stop_session(session).await.map_err(|error| {
+ self.begin_drain();
+ internal(error)
+ })?;
+ for completed in completed {
+ completed.cancelled().await;
+ }
+ Ok::<(), maka_protocol::OperationError>(())
+ };
+ match tokio::time::timeout(std::time::Duration::from_secs(30), drain).await {
+ Err(_) => return Ok(false),
+ Ok(result) => result?,
+ }
+ if self.shutdown.is_cancelled() {
+ return Err(failure(
+ Code::HostDraining,
+ "Resource cleanup requires Host recovery",
+ ));
+ }
+ Ok(true)
+ }
+
pub(crate) fn active_session_owner(&self, session: &str) -> Option<Invocation> {
self.active
.lock()
diff --git a/crates/runtime-host/src/execution/plugins.rs b/crates/runtime-host/src/execution/plugins.rs
index 6cc1f6e15f..6df4106a4d 100644
--- a/crates/runtime-host/src/execution/plugins.rs
+++ b/crates/runtime-host/src/execution/plugins.rs
@@ -30,6 +30,7 @@ mod interactions;
mod llm;
mod messages;
mod network;
+mod removal;
mod resume;
mod root;
mod submit;
@@ -95,15 +96,6 @@ pub(crate) struct ProcessAdmission {
}
impl Executions {
- pub(crate) async fn retain_plugin_process_session(
- &self,
- session: &str,
- ) -> Result<(), StoreError> {
- self.log.retain_session(session).await?;
- self.publish_session_change(session).await;
- Ok(())
- }
-
pub(crate) async fn admit_plugin_process(
&self,
scope: &maka_plugins::call::Scope,
@@ -346,6 +338,28 @@ impl BoundCommands {
}
async fn authorize(&self, host: &Executions, session: &str) -> Result<(), Error> {
+ let current = self.authorize_session_control(host, session).await?;
+ if host
+ .log
+ .session_retirement(session)
+ .await
+ .map_err(storage)?
+ .is_some()
+ {
+ return Err(Error::Revoked);
+ }
+ if current.archived {
+ return Err(Error::Denied);
+ }
+ Ok(())
+ }
+
+ /// Lifecycle control may inspect archived Sessions, but grants no execution.
+ async fn authorize_session_control(
+ &self,
+ host: &Executions,
+ session: &str,
+ ) -> Result<maka_event_log::sessions::SessionRecord<SessionConfiguration>, Error> {
self.authorize_origin(host).await?;
if host
.log
@@ -369,8 +383,7 @@ impl BoundCommands {
.await
.map_err(storage)?
.ok_or(Error::NotFound)?;
- if current.archived
- || current.configuration.boundary_revision != grant.boundary_revision
+ if current.configuration.boundary_revision != grant.boundary_revision
|| current.configuration.sandbox_mode != grant.sandbox_mode
|| current.configuration.approval_policy != grant.approval_policy
|| current.configuration.workspace.host_cwd != grant.cwd
@@ -378,7 +391,7 @@ impl BoundCommands {
{
return Err(Error::Denied);
}
- Ok(())
+ Ok(current)
}
async fn receipt(&self, host: &Executions, operation: &str) -> Result<Receipt, Error> {
@@ -394,6 +407,21 @@ impl BoundCommands {
}
impl Commands for BoundCommands {
+ fn remove_session(
+ &self,
+ request: maka_plugins::execution::RemoveSession,
+ ) -> BoxFuture<'_, Result<maka_plugins::execution::RemovedSession, Error>> {
+ Box::pin(self.remove(request))
+ }
+ fn removal_receipt(
+ &self,
+ session_id: String,
+ ) -> BoxFuture<'_, Result<Option<maka_plugins::execution::RemovalReceipt>, Error>> {
+ Box::pin(self.read_removal_receipt(session_id))
+ }
+ fn preview_removal(&self, session_id: String) -> BoxFuture<'_, Result<u64, Error>> {
+ Box::pin(self.preview_session_removal(session_id))
+ }
fn copy_attachment(
&self,
source: Arc<dyn Commands>,
@@ -864,6 +892,7 @@ fn storage(error: StoreError) -> Error {
StoreError::EventConflict | StoreError::SessionConflict => Error::Conflict,
StoreError::SessionBusy => Error::Busy,
StoreError::SessionNotFound => Error::NotFound,
+ StoreError::SessionRetired => Error::Revoked,
StoreError::CommitUnknown(_) | StoreError::OperationUnknown => {
Error::OutcomeUnknown(error.to_string())
}
diff --git a/crates/runtime-host/src/execution/plugins/children.rs b/crates/runtime-host/src/execution/plugins/children.rs
index 2ebe0dd2d1..e205d70c00 100644
--- a/crates/runtime-host/src/execution/plugins/children.rs
+++ b/crates/runtime-host/src/execution/plugins/children.rs
@@ -132,6 +132,7 @@ impl BoundCommands {
let grants = self.grants.clone();
let submission_stop = self.submission_stop.clone();
let worker = host.clone();
+ let creator = self.namespace.clone();
let (send, receive) = tokio::sync::oneshot::channel();
host.workers.spawn(async move {
let result = async {
@@ -225,6 +226,9 @@ impl BoundCommands {
child.boundary_revision = 0;
child.collaboration_mode = CollaborationMode::Agent;
child.orchestration_mode = BehaviorId::default();
+ worker
+ .validate_workspace(&child)
+ .map_err(|error| Error::Invalid(error.message))?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| Error::Host(e.to_string()))?
@@ -233,7 +237,17 @@ impl BoundCommands {
.map_err(|_| Error::Host("system clock overflow".into()))?;
worker
.log
- .create_session(&id, &fingerprint, &child, now)
+ .create_plugin_session(
+ &maka_event_log::sessions::PluginSession {
+ session_id: id.clone(),
+ creator,
+ fingerprint: fingerprint.clone(),
+ managed: false,
+ authority_session_id: Some(request.parent_session_id.clone()),
+ },
+ &child,
+ now,
+ )
.await
.map_err(storage)?
}
diff --git a/crates/runtime-host/src/execution/plugins/removal.rs b/crates/runtime-host/src/execution/plugins/removal.rs
new file mode 100644
index 0000000000..d2217e09df
--- /dev/null
+++ b/crates/runtime-host/src/execution/plugins/removal.rs
@@ -0,0 +1,158 @@
+/*
+ * 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::{BoundCommands, Error, Executions, protocol, storage};
+use maka_event_log::sessions::{RemovalAuthority, RemovalPlan, RemoveFamilyResult};
+use maka_plugins::execution::{RemovalReceipt, RemoveSession, RemovedSession};
+
+impl BoundCommands {
+ pub(super) async fn read_removal_receipt(
+ &self,
+ session: String,
+ ) -> Result<Option<RemovalReceipt>, Error> {
+ let host = self.executions()?;
+ let _lease = self.context.admit().map_err(|_| Error::Revoked)?;
+ self.authorize_removal_receipt(&host, &session).await?;
+ Ok(host
+ .log
+ .session_removal_receipt(&session)
+ .await
+ .map_err(storage)?
+ .map(|plan| receipt(session, plan)))
+ }
+
+ async fn authorize_removal_receipt(
+ &self,
+ host: &Executions,
+ session: &str,
+ ) -> Result<(), Error> {
+ self.authorize_origin(host).await?;
+ if self.submission_stop.is_cancelled() {
+ return Err(Error::Revoked);
+ }
+ if host
+ .log
+ .session_manager(session)
+ .await
+ .map_err(storage)?
+ .is_some_and(|manager| manager != self.namespace)
+ {
+ return Err(Error::Denied);
+ }
+ if !self.grants.lock().unwrap().contains_key(session)
+ && host
+ .log
+ .session_creator(session)
+ .await
+ .map_err(storage)?
+ .as_ref()
+ != Some(&self.namespace)
+ {
+ return Err(Error::Denied);
+ }
+ Ok(())
+ }
+
+ async fn authorize_removal_plan(
+ &self,
+ host: &Executions,
+ session: &str,
+ ) -> Result<RemovalPlan, Error> {
+ self.authorize_session_control(host, session).await?;
+ let plan = host
+ .log
+ .preview_session_removal(session)
+ .await
+ .map_err(storage)?;
+ for target in &plan.remove {
+ self.authorize_session_control(host, target).await?;
+ }
+ if self.submission_stop.is_cancelled() {
+ return Err(Error::Revoked);
+ }
+ Ok(plan)
+ }
+
+ pub(super) async fn preview_session_removal(&self, session: String) -> Result<u64, Error> {
+ let host = self.executions()?;
+ let _lease = self.context.admit().map_err(|_| Error::Revoked)?;
+ let _gate = host.interactions.own_admission().await;
+ Ok(self
+ .authorize_removal_plan(&host, &session)
+ .await?
+ .archived_subtask_count)
+ }
+
+ pub(super) async fn remove(&self, input: RemoveSession) -> Result<RemovedSession, Error> {
+ input
+ .validate()
+ .map_err(|error| Error::Invalid(error.to_string()))?;
+ let host = self.executions()?;
+ let _lease = self.context.admit().map_err(|_| Error::Revoked)?;
+ let gate = host.interactions.own_admission().await;
+ self.authorize_removal_receipt(&host, &input.session_id)
+ .await?;
+ if let Some(plan) = host
+ .log
+ .session_removal_receipt(&input.session_id)
+ .await
+ .map_err(storage)?
+ {
+ return Ok(RemovedSession::Removed {
+ receipt: receipt(input.session_id, plan),
+ });
+ }
+ let plan = self
+ .authorize_removal_plan(&host, &input.session_id)
+ .await?;
+ let authority = RemovalAuthority::Granted {
+ namespace: self.namespace.clone(),
+ sessions: plan.remove.into_iter().collect(),
+ };
+ Ok(
+ match host
+ .remove_family(
+ input.session_id.clone(),
+ input.expected_revision,
+ authority,
+ gate,
+ )
+ .await
+ .map_err(protocol)?
+ {
+ RemoveFamilyResult::Accepted(plan) => RemovedSession::Removed {
+ receipt: receipt(input.session_id, plan),
+ },
+ RemoveFamilyResult::RevisionConflict { expected, actual } => {
+ RemovedSession::RevisionConflict {
+ expected_revision: expected,
+ actual_revision: actual,
+ }
+ }
+ },
+ )
+ }
+}
+
+fn receipt(session_id: String, plan: RemovalPlan) -> RemovalReceipt {
+ RemovalReceipt {
+ session_id,
+ archived_subtask_count: plan.archived_subtask_count,
+ }
+}
diff --git a/crates/runtime-host/src/execution/plugins/root.rs b/crates/runtime-host/src/execution/plugins/root.rs
index ee4b22458a..d37f9413f3 100644
--- a/crates/runtime-host/src/execution/plugins/root.rs
+++ b/crates/runtime-host/src/execution/plugins/root.rs
@@ -148,8 +148,7 @@ impl BoundCommands {
return Err(Error::Denied);
}
let current = &record.configuration;
- if record.archived
- || current.workspace != approval.workspace
+ if current.workspace != approval.workspace
|| current.workspace_origin != approval.workspace_origin
|| rank(current.sandbox_mode) > rank(approval.sandbox_mode)
|| !current
@@ -422,6 +421,7 @@ impl BoundCommands {
}
let expected =
configuration(&worker, &id, &request, &approval, existing.is_none()).await?;
+ worker.validate_workspace(&expected).map_err(|error| Error::Invalid(error.message))?;
let record = match existing {
Some(record) => record,
None => {
diff --git a/crates/runtime-host/src/execution/plugins/workspace.rs b/crates/runtime-host/src/execution/plugins/workspace.rs
index 6b8ce3c587..13ba82c2dc 100644
--- a/crates/runtime-host/src/execution/plugins/workspace.rs
+++ b/crates/runtime-host/src/execution/plugins/workspace.rs
@@ -155,7 +155,7 @@ async fn quiescent(
}
let session = &member.session_id;
if host.has_session_work(session).await.map_err(storage)?
- || host.plugin_processes.lock().unwrap().contains_key(session)
+ || host.plugin_processes.has(session)
|| host
.log
.has_unsettled_shells(session)
diff --git a/crates/runtime-host/src/execution/processes.rs b/crates/runtime-host/src/execution/processes.rs
new file mode 100644
index 0000000000..374e947603
--- /dev/null
+++ b/crates/runtime-host/src/execution/processes.rs
@@ -0,0 +1,130 @@
+/*
+ * 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 std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
+use tokio_util::sync::CancellationToken;
+use uuid::Uuid;
+
+#[derive(Default, Clone)]
+pub(super) struct Registry(Arc<Mutex<HashMap<String, HashMap<Uuid, Control>>>>);
+
+struct Control {
+ stop: CancellationToken,
+ completed: CancellationToken,
+}
+
+impl Registry {
+ pub(super) fn has(&self, session: &str) -> bool {
+ self.0.lock().unwrap().contains_key(session)
+ }
+
+ /// The caller fences admission before requesting stop. Completion means
+ /// the resource owner has released native handles, not merely cancelled them.
+ pub(super) fn stop(&self, session: &str) -> Vec<CancellationToken> {
+ self.0
+ .lock()
+ .unwrap()
+ .get(session)
+ .into_iter()
+ .flat_map(|entries| entries.values())
+ .map(|entry| {
+ entry.stop.cancel();
+ entry.completed.clone()
+ })
+ .collect()
+ }
+}
+
+impl super::Executions {
+ pub(crate) fn own_plugin_process(
+ &self,
+ session: &str,
+ stop: CancellationToken,
+ ) -> ProcessActivity {
+ let id = Uuid::new_v4();
+ let completed = CancellationToken::new();
+ self.plugin_processes
+ .0
+ .lock()
+ .unwrap()
+ .entry(session.into())
+ .or_default()
+ .insert(
+ id,
+ Control {
+ stop,
+ completed: completed.clone(),
+ },
+ );
+ ProcessActivity {
+ log: self.log.clone(),
+ registry: self.plugin_processes.clone(),
+ session: session.into(),
+ id,
+ completed,
+ shutdown: self.shutdown.clone(),
+ cleanup_confirmed: true,
+ }
+ }
+}
+
+/// Instance-lifetime processes outlive Turns but retain Session resource ownership.
+pub(crate) struct ProcessActivity {
+ log: Arc<maka_event_log::EventLog>,
+ registry: Registry,
+ session: String,
+ id: Uuid,
+ completed: CancellationToken,
+ shutdown: CancellationToken,
+ cleanup_confirmed: bool,
+}
+
+impl ProcessActivity {
+ pub(crate) async fn start(&mut self) -> Result<(), maka_event_log::StoreError> {
+ self.cleanup_confirmed = false;
+ self.log.admit_session_process(&self.session, self.id).await
+ }
+ pub(crate) async fn settle(mut self, clean: bool) -> Result<(), maka_event_log::StoreError> {
+ if clean {
+ self.log.clean_session_process(self.id).await?;
+ }
+ self.cleanup_confirmed = clean;
+ Ok(())
+ }
+}
+
+impl Drop for ProcessActivity {
+ fn drop(&mut self) {
+ // A dropped worker is not evidence of cleanup. Before start, however,
+ // publication failure cannot have created an OS resource.
+ if !self.cleanup_confirmed {
+ self.shutdown.cancel();
+ }
+ let mut registry = self.registry.0.lock().unwrap();
+ let entries = registry.get_mut(&self.session).expect("registered process");
+ entries.remove(&self.id);
+ if entries.is_empty() {
+ registry.remove(&self.session);
+ }
+ self.completed.cancel();
+ }
+}
diff --git a/crates/runtime-host/src/execution/removal.rs b/crates/runtime-host/src/execution/removal.rs
new file mode 100644
index 0000000000..941d45f787
--- /dev/null
+++ b/crates/runtime-host/src/execution/removal.rs
@@ -0,0 +1,233 @@
+/*
+ * 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::{Executions, Result, internal};
+use crate::session::SessionConfiguration;
+use maka_event_log::sessions::SessionRetirement;
+use std::{sync::Arc, time::Duration};
+
+impl Executions {
+ /// The accepted worker owns commit, notifications and recovery scheduling,
+ /// even if the Remote or plugin stops waiting for its receipt.
+ pub(crate) async fn remove_family(
+ self: &Arc<Self>,
+ session: String,
+ expected: u64,
+ authority: maka_event_log::sessions::RemovalAuthority,
+ admission: tokio::sync::OwnedMutexGuard<()>,
+ ) -> Result<maka_event_log::sessions::RemoveFamilyResult> {
+ let worker = self.clone();
+ let (send, receive) = tokio::sync::oneshot::channel();
+ self.workers.spawn(async move {
+ let result = if worker.accepting() {
+ worker
+ .log
+ .remove_session_family(&session, expected, authority)
+ .await
+ .map_err(|error| {
+ if matches!(
+ error,
+ maka_event_log::StoreError::CommitUnknown(_)
+ | maka_event_log::StoreError::OperationUnknown
+ ) {
+ worker.begin_drain();
+ }
+ if matches!(error, maka_event_log::StoreError::PrefixTooLarge) {
+ super::failure(
+ maka_protocol::OperationErrorCode::OperationConflict,
+ "Session removal exceeds the family size limit",
+ )
+ } else {
+ use maka_event_log::StoreError;
+ use maka_protocol::OperationErrorCode as Code;
+ let code = match error {
+ StoreError::SessionConflict | StoreError::SessionRetired => {
+ Code::OperationConflict
+ }
+ StoreError::SessionNotFound => Code::NotFound,
+ StoreError::SessionBusy => Code::SessionBusy,
+ StoreError::CommitUnknown(_) | StoreError::OperationUnknown => {
+ Code::CommitOutcomeUnknown
+ }
+ _ => Code::PersistenceFailed,
+ };
+ super::failure(code, &error.to_string())
+ }
+ })
+ } else {
+ Err(super::failure(
+ maka_protocol::OperationErrorCode::HostDraining,
+ "Host is draining",
+ ))
+ };
+ if let Ok(maka_event_log::sessions::RemoveFamilyResult::Accepted(plan)) = &result {
+ for session in plan.remove.iter().chain(&plan.archive) {
+ // A receipt retry must not retire a dependent that the user
+ // restored after the original removal finished.
+ match worker.log.session_retirement(session).await {
+ Ok(Some(_)) => worker
+ .capabilities
+ .registry
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .release_session(session),
+ Ok(None) => {}
+ Err(_) => worker.begin_drain(),
+ }
+ }
+ }
+ drop(admission);
+ if let Ok(maka_event_log::sessions::RemoveFamilyResult::Accepted(plan)) = &result {
+ worker.request_removal_recovery();
+ for session in plan.remove.iter().chain(&plan.archive) {
+ worker.publish_session_change(session).await;
+ }
+ }
+ let _ = send.send(result);
+ });
+ receive.await.map_err(|_| {
+ super::failure(
+ maka_protocol::OperationErrorCode::CommitOutcomeUnknown,
+ "Session removal owner disappeared",
+ )
+ })?
+ }
+
+ pub(crate) fn request_removal_recovery(&self) {
+ self.removal_wake.notify_one();
+ }
+
+ pub(crate) fn start_removal_recovery(self: &Arc<Self>) {
+ let host = self.clone();
+ self.workers.spawn(async move {
+ let mut pending = false;
+ let mut delay = Duration::from_millis(250);
+ loop {
+ tokio::select! {
+ biased;
+ _ = host.shutdown.cancelled() => break,
+ _ = host.removal_wake.notified() => { delay = Duration::from_millis(250); }
+ _ = tokio::time::sleep(delay), if pending => {
+ delay = (delay * 2).min(Duration::from_secs(30));
+ }
+ }
+ match host.recover_removals().await {
+ Ok(remaining) => pending = remaining,
+ Err(error) => {
+ host.begin_drain();
+ eprintln!("Session removal recovery failed: {}", error.message);
+ break;
+ }
+ }
+ }
+ });
+ self.request_removal_recovery();
+ }
+
+ async fn recover_removals(&self) -> Result<bool> {
+ let mut after = None;
+ let mut pending = false;
+ loop {
+ let page = self
+ .log
+ .pending_session_retirements(after.as_deref())
+ .await
+ .map_err(internal)?;
+ if page.is_empty() {
+ return Ok(pending);
+ }
+ for session in page {
+ after = Some(session.clone());
+ if !self.accepting() {
+ return Ok(true);
+ }
+ if !self.drain_retiring_session(&session).await? {
+ pending = true;
+ continue;
+ }
+ self.capabilities
+ .registry
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .release_session(&session);
+ pending |= !self.clean_removed_session(&session).await?;
+ }
+ }
+ }
+
+ async fn clean_removed_session(&self, session: &str) -> Result<bool> {
+ let admission = self.lock_admission().await;
+ if !self
+ .log
+ .session_retirement_ready(session)
+ .await
+ .map_err(internal)?
+ {
+ return Ok(false);
+ }
+ let Some(record) = self
+ .log
+ .retiring_session::<SessionConfiguration>(session)
+ .await
+ .map_err(internal)?
+ else {
+ return Ok(true);
+ };
+ let retirement = self
+ .log
+ .session_retirement(session)
+ .await
+ .map_err(internal)?;
+ if retirement == Some(SessionRetirement::Removing)
+ && let Some(binding) = record.configuration.worktree
+ {
+ let shared = self
+ .log
+ .workspace_has_other_session(&record.configuration.workspace.host_cwd, session)
+ .await
+ .map_err(internal)?;
+ if !shared {
+ // New owners need a live parent and a binding; path-only roots
+ // cannot adopt this allocation. The durable fence has retired
+ // the last parent, so filesystem I/O needs no global gate.
+ drop(admission);
+ let root = self.paths.state_root.join("subagent-worktrees");
+ let cleanup = tokio::task::spawn_blocking(move || {
+ maka_fs_tools::worktree::Worktrees::open(&root)?.remove(&binding)
+ })
+ .await
+ .map_err(internal)?;
+ if let Err(error) = cleanup {
+ eprintln!("Session {session} workspace cleanup pending: {error}");
+ return Ok(false);
+ }
+ }
+ }
+ let retired = !self
+ .log
+ .finish_session_retirement(session)
+ .await
+ .map_err(internal)?
+ .pending();
+ if retired {
+ self.publish_session_change(session).await;
+ }
+ Ok(retired)
+ }
+}
diff --git a/crates/runtime-host/src/execution/workspaces.rs b/crates/runtime-host/src/execution/workspaces.rs
index acaf503340..0474357f43 100644
--- a/crates/runtime-host/src/execution/workspaces.rs
+++ b/crates/runtime-host/src/execution/workspaces.rs
@@ -31,22 +31,31 @@ use std::{
use tokio_util::sync::CancellationToken;
impl Executions {
- pub(crate) fn own_plugin_process(&self, session: &str) -> ProcessActivity {
- *self
- .plugin_processes
- .lock()
- .unwrap()
- .entry(session.into())
- .or_default() += 1;
- ProcessActivity {
- registry: self.plugin_processes.clone(),
- session: session.into(),
+ /// Managed checkouts cannot acquire an untracked owner through a path-only
+ /// selection. Shared children inherit the binding and its lifecycle instead.
+ pub(crate) fn validate_workspace(&self, session: &SessionConfiguration) -> super::Result<()> {
+ let root = self.paths.state_root.join("subagent-worktrees");
+ let root = maka_fs_tools::workspace::project::host_path(&root).map_err(internal)?;
+ let cwd = std::path::Path::new(&session.workspace.host_cwd);
+ if session
+ .worktree
+ .as_ref()
+ .is_some_and(|binding| binding.directory() != cwd)
+ || (session.worktree.is_none() && cwd.starts_with(root))
+ {
+ return Err(failure(
+ Code::OperationConflict,
+ "Managed workspaces require their owning Session binding",
+ ));
}
+ Ok(())
}
+
pub(super) async fn prepare_worktree(
&self,
session: &SessionConfiguration,
) -> super::Result<()> {
+ self.validate_workspace(session)?;
let Some(binding) = session.worktree.clone() else {
return Ok(());
};
@@ -72,22 +81,6 @@ impl Executions {
}
}
-/// Instance-lifetime plugin processes outlive Turns but still write their Session workspace.
-pub(crate) struct ProcessActivity {
- registry: Arc<std::sync::Mutex<std::collections::HashMap<String, usize>>>,
- session: String,
-}
-impl Drop for ProcessActivity {
- fn drop(&mut self) {
- let mut registry = self.registry.lock().unwrap();
- let count = registry.get_mut(&self.session).expect("registered process");
- *count -= 1;
- if *count == 0 {
- registry.remove(&self.session);
- }
- }
-}
-
/// Cancellation also propagates when the preparing future itself is dropped.
struct Interrupt(Arc<AtomicBool>);
impl Drop for Interrupt {
diff --git a/crates/runtime-host/src/plugins/javascript/bridge.rs b/crates/runtime-host/src/plugins/javascript/bridge.rs
index b089a7bfdc..83eff2fd50 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge.rs
@@ -596,6 +596,18 @@ impl State {
let (commands, input) = self.execution(input)?;
encode(commands.configure(input).await?)
}
+ Request::RemoveSession(input) => {
+ let (commands, input) = self.execution(input)?;
+ encode(commands.remove_session(input).await?)
+ }
+ Request::RemovalReceipt(input) => {
+ let (commands, input) = self.execution(input)?;
+ encode(commands.removal_receipt(input.session_id).await?)
+ }
+ Request::PreviewRemoval(input) => {
+ let (commands, input) = self.execution(input)?;
+ encode(commands.preview_removal(input.session_id).await?)
+ }
Request::ReadMessage(input) => {
let (commands, input) = self.execution(input)?;
encode(commands.read_message(input).await?)
diff --git a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
index ec1049343a..10563a4ba4 100644
--- a/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
+++ b/crates/runtime-host/src/plugins/javascript/bridge/wire.rs
@@ -151,6 +151,12 @@ pub(super) enum Request {
ResumeExecution(Execution<maka_plugins::execution::Resume>),
#[serde(rename = "execution.configure")]
ConfigureExecution(Execution<maka_plugins::execution::Configure>),
+ #[serde(rename = "execution.removeSession")]
+ RemoveSession(Execution<maka_plugins::execution::RemoveSession>),
+ #[serde(rename = "execution.removalReceipt")]
+ RemovalReceipt(Execution<SessionQuery>),
+ #[serde(rename = "execution.previewRemoval")]
+ PreviewRemoval(Execution<SessionQuery>),
#[serde(rename = "execution.readMessage")]
ReadMessage(Execution<maka_plugins::execution::SessionMessage>),
#[serde(rename = "execution.enqueue")]
diff --git a/crates/runtime-host/src/plugins/process.rs b/crates/runtime-host/src/plugins/process.rs
index 2e6e70a78d..d916e2effa 100644
--- a/crates/runtime-host/src/plugins/process.rs
+++ b/crates/runtime-host/src/plugins/process.rs
@@ -124,13 +124,13 @@ impl Processes {
let activity = handle
.target
.session()
- .map(|id| host.own_plugin_process(id));
+ .map(|id| host.own_plugin_process(id, stop.clone()));
let session = handle.target.session().map(str::to_owned);
let execution =
self.0
.owner
.spawn_resource("protocol process", move |retiring| async move {
- let _activity = activity;
+ let mut activity = activity;
let mut ticket = ticket;
if let Some(ticket) = &mut ticket {
ticket.start();
@@ -141,10 +141,11 @@ impl Processes {
Lifetime::Instance => CancellationToken::new(),
};
let result = async {
- if let Some(session) = session {
- host.retain_plugin_process_session(&session)
- .await
- .map_err(|error| error.to_string())?;
+ if let Some(activity) = &mut activity {
+ activity.start().await.map_err(|error| error.to_string())?;
+ }
+ if let Some(session) = &session {
+ host.publish_session_change(session).await;
}
worker::run(
command,
@@ -162,6 +163,14 @@ impl Processes {
.await
}
.await;
+ let result = match activity {
+ Some(activity) => activity
+ .settle(result.is_ok())
+ .await
+ .map_err(|error| error.to_string())
+ .and(result),
+ None => result,
+ };
if result.is_err() {
host.begin_drain();
}
diff --git a/crates/runtime-host/src/server.rs b/crates/runtime-host/src/server.rs
index aa5803c6c4..c7fe22d938 100644
--- a/crates/runtime-host/src/server.rs
+++ b/crates/runtime-host/src/server.rs
@@ -371,6 +371,7 @@ impl Host {
}
startup_guard.disarm();
host.executions.start_handoff_recovery(host.epoch.clone());
+ host.executions.start_removal_recovery();
host.record_diagnostic(format_args!("Host ready: epoch {}", host.epoch));
Ok(host)
}
diff --git a/crates/runtime-host/src/server/authority.rs b/crates/runtime-host/src/server/authority.rs
index 2d2a4016da..d4223f5baa 100644
--- a/crates/runtime-host/src/server/authority.rs
+++ b/crates/runtime-host/src/server/authority.rs
@@ -244,6 +244,9 @@ fn path_free(request: &Request) -> bool {
| Operation::SessionTurnsQuery
| Operation::SessionTurnLandmarksQuery
| Operation::SessionLifecycleSet
+ | Operation::SessionRemove
+ | Operation::SessionRemovePreview
+ | Operation::SessionRemoveQuery
| Operation::SessionMetadataUpdate
| Operation::SessionReadMarkerSet
| Operation::SessionConfigurationUpdate
diff --git a/crates/runtime-host/src/server/operations.rs b/crates/runtime-host/src/server/operations.rs
index e83986f534..df741b3ce3 100644
--- a/crates/runtime-host/src/server/operations.rs
+++ b/crates/runtime-host/src/server/operations.rs
@@ -267,6 +267,9 @@ impl OperationRegistry for Operations {
Operation::SessionSourcesQuery => Some(maka_protocol::session::sources::ERRORS),
Operation::SessionCatalogQuery => Some(sessions::QUERY_ERRORS),
Operation::SessionLifecycleSet => Some(sessions::LIFECYCLE_ERRORS),
+ Operation::SessionRemove
+ | Operation::SessionRemovePreview
+ | Operation::SessionRemoveQuery => Some(sessions::removal::ERRORS),
Operation::SessionMetadataUpdate => Some(sessions::mutation::METADATA_ERRORS),
Operation::SessionReadMarkerSet => Some(sessions::mutation::READ_MARKER_ERRORS),
Operation::SessionConfigurationUpdate | Operation::SessionWorkspaceRelocate => {
diff --git a/crates/runtime-host/src/server/sessions.rs b/crates/runtime-host/src/server/sessions.rs
index 90129d1f97..16331df67c 100644
--- a/crates/runtime-host/src/server/sessions.rs
+++ b/crates/runtime-host/src/server/sessions.rs
@@ -22,6 +22,7 @@ pub(super) mod copy;
pub(super) mod create;
pub(super) use crate::session::model;
pub(super) mod mutation;
+pub(super) mod removal;
pub(super) mod workspace;
use crate::session::SessionConfiguration;
@@ -44,6 +45,9 @@ pub(super) enum Output {
Abandon(maka_protocol::session::copy::AbandonOutput),
CopyReceipt(maka_protocol::session::copy::QueryResult),
Sources(maka_protocol::session::sources::Output),
+ Removed(SessionRemoveResult),
+ RemovalPreview(SessionRemovePreviewResult),
+ RemovalReceipt(SessionRemoveQueryResult),
}
impl Output {
@@ -70,11 +74,23 @@ pub(super) fn supports(operation: Operation) -> bool {
| Operation::SessionReadMarkerSet
| Operation::SessionConfigurationUpdate
| Operation::SessionWorkspaceRelocate
+ | Operation::SessionRemove
+ | Operation::SessionRemovePreview
+ | Operation::SessionRemoveQuery
)
}
pub(super) fn decode_input(operation: Operation, value: &Value) -> maka_protocol::Result<Value> {
match operation {
+ Operation::SessionRemove => {
+ decode_session_remove_input(value)?;
+ }
+ Operation::SessionRemovePreview => {
+ decode_session_remove_preview_input(value)?;
+ }
+ Operation::SessionRemoveQuery => {
+ decode_session_remove_query_input(value)?;
+ }
Operation::SessionSourcesQuery => {
maka_protocol::session::sources::decode_input(value)?;
}
@@ -114,7 +130,13 @@ pub(super) fn decode_input(operation: Operation, value: &Value) -> maka_protocol
}
pub(super) fn decode_output(operation: Operation, value: &Value) -> maka_protocol::Result<Value> {
- if matches!(
+ if operation == Operation::SessionRemove {
+ decode_session_remove_result(value)?;
+ } else if operation == Operation::SessionRemovePreview {
+ decode_session_remove_preview_result(value)?;
+ } else if operation == Operation::SessionRemoveQuery {
+ decode_session_remove_query_result(value)?;
+ } else if matches!(
operation,
Operation::SessionBranchCreate | Operation::SessionRevisionCreate
) {
@@ -147,6 +169,23 @@ pub(super) async fn execute(
) -> Result<Output> {
let log = host.log.as_ref();
match operation {
+ Operation::SessionRemove => {
+ removal::remove(host, decode_session_remove_input(value).map_err(invalid)?)
+ .await
+ .map(Output::Removed)
+ }
+ Operation::SessionRemovePreview => removal::preview(
+ host,
+ decode_session_remove_preview_input(value).map_err(invalid)?,
+ )
+ .await
+ .map(Output::RemovalPreview),
+ Operation::SessionRemoveQuery => removal::query(
+ host,
+ decode_session_remove_query_input(value).map_err(invalid)?,
+ )
+ .await
+ .map(Output::RemovalReceipt),
Operation::SessionSourcesQuery => {
let input = maka_protocol::session::sources::decode_input(value).map_err(invalid)?;
let messages = log
@@ -359,7 +398,9 @@ fn failure(code: OperationErrorCode, message: &str) -> OperationError {
pub(super) fn stored(error: StoreError) -> OperationError {
let code = match &error {
- StoreError::SessionConflict => OperationErrorCode::OperationConflict,
+ StoreError::SessionConflict | StoreError::SessionRetired => {
+ OperationErrorCode::OperationConflict
+ }
StoreError::SessionNotFound => OperationErrorCode::NotFound,
StoreError::SessionBusy => OperationErrorCode::SessionBusy,
StoreError::CommitUnknown(_) | StoreError::OperationUnknown => {
diff --git a/crates/runtime-host/src/server/sessions/copy.rs b/crates/runtime-host/src/server/sessions/copy.rs
index 92716bf9ce..c9225f56a7 100644
--- a/crates/runtime-host/src/server/sessions/copy.rs
+++ b/crates/runtime-host/src/server/sessions/copy.rs
@@ -142,6 +142,7 @@ pub(super) async fn create(host: &Host, input: Input) -> Result<Output> {
}
async fn finish(host: &Host, input: Input, configuration: &SessionConfiguration) -> Result<Output> {
+ host.executions.validate_workspace(configuration)?;
let result = host
.log
.copy_session(
diff --git a/crates/runtime-host/src/server/sessions/create.rs b/crates/runtime-host/src/server/sessions/create.rs
index 71eff14d36..bde794ec41 100644
--- a/crates/runtime-host/src/server/sessions/create.rs
+++ b/crates/runtime-host/src/server/sessions/create.rs
@@ -93,6 +93,7 @@ pub(super) async fn create(
host.executions.executor_binding(&id, executor_id)?;
}
let config = resolve(&host.configuration, prepared, thinking, workspace).await?;
+ host.executions.validate_workspace(&config)?;
super::super::projects::record_usage(host, &config.workspace).await?;
let record = log
.create_session(
diff --git a/crates/runtime-host/src/server/sessions/removal.rs b/crates/runtime-host/src/server/sessions/removal.rs
new file mode 100644
index 0000000000..2ac2d420d0
--- /dev/null
+++ b/crates/runtime-host/src/server/sessions/removal.rs
@@ -0,0 +1,101 @@
+/*
+ * 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::{Result, stored};
+use crate::server::Host;
+use maka_event_log::sessions::RemoveFamilyResult;
+use maka_protocol::{OperationErrorCode as Code, session::*};
+
+pub(super) async fn remove(host: &Host, input: SessionRemoveInput) -> Result<SessionRemoveResult> {
+ let gate = host.interactions.own_admission().await;
+ crate::session::require_unmanaged(&host.log, &input.session_id, Code::OperationConflict)
+ .await?;
+ let result = host
+ .executions
+ .remove_family(
+ input.session_id.clone(),
+ input.expected_revision,
+ maka_event_log::sessions::RemovalAuthority::Unmanaged,
+ gate,
+ )
+ .await?;
+ Ok(match result {
+ RemoveFamilyResult::Accepted(plan) => SessionRemoveResult::Removed {
+ session_id: input.session_id,
+ archived_subtask_count: Some(plan.archived_subtask_count),
+ },
+ RemoveFamilyResult::RevisionConflict { expected, actual } => {
+ SessionRemoveResult::RevisionConflict {
+ expected_revision: expected,
+ actual_revision: actual,
+ }
+ }
+ })
+}
+
+pub(super) async fn preview(
+ host: &Host,
+ input: SessionRemovePreviewInput,
+) -> Result<SessionRemovePreviewResult> {
+ crate::session::require_unmanaged(&host.log, &input.session_id, Code::OperationConflict)
+ .await?;
+ let plan = host
+ .log
+ .preview_session_removal(&input.session_id)
+ .await
+ .map_err(stored)?;
+ Ok(SessionRemovePreviewResult {
+ archivable_subtask_count: plan.archived_subtask_count,
+ })
+}
+
+pub(super) async fn query(
+ host: &Host,
+ input: SessionRemoveQueryInput,
+) -> Result<SessionRemoveQueryResult> {
+ crate::session::require_unmanaged(&host.log, &input.session_id, Code::OperationConflict)
+ .await?;
+ Ok(
+ match host
+ .log
+ .session_removal_receipt(&input.session_id)
+ .await
+ .map_err(stored)?
+ {
+ Some(plan) => SessionRemoveQueryResult::Removed {
+ session_id: input.session_id,
+ archived_subtask_count: plan.archived_subtask_count,
+ },
+ None => SessionRemoveQueryResult::Missing,
+ },
+ )
+}
+
+pub(in crate::server) const ERRORS: &[Code] = &[
+ Code::HostNotReady,
+ Code::HostDraining,
+ Code::OperationUnavailable,
+ Code::InvalidRequest,
+ Code::NotFound,
+ Code::SessionBusy,
+ Code::OperationConflict,
+ Code::PersistenceFailed,
+ Code::CommitOutcomeUnknown,
+ Code::InternalFailure,
+];
diff --git a/crates/runtime-host/src/server/sessions/workspace.rs b/crates/runtime-host/src/server/sessions/workspace.rs
index eadfc38300..14cbaf05cb 100644
--- a/crates/runtime-host/src/server/sessions/workspace.rs
+++ b/crates/runtime-host/src/server/sessions/workspace.rs
@@ -88,6 +88,9 @@ pub(super) async fn relocate(host: &Host, value: &Value) -> Result<SessionUpdate
"Archived Session workspace cannot be relocated",
));
}
+ let mut destination = current.configuration.clone();
+ destination.workspace = workspace.clone();
+ host.executions.validate_workspace(&destination)?;
let committed = host
.log
.update_session_metadata(
diff --git a/crates/runtime-host/tests/fixtures/background-plugin.mjs b/crates/runtime-host/tests/fixtures/background-plugin.mjs
index aff3728086..4ad355ef7a 100644
--- a/crates/runtime-host/tests/fixtures/background-plugin.mjs
+++ b/crates/runtime-host/tests/fixtures/background-plugin.mjs
@@ -219,6 +219,47 @@ export default async function (ctx) {
if (error.code !== 'revoked') throw error;
}
const root = await commands.createRoot(request);
+ let deletion = await ctx.storage.read('removal-intent');
+ if (!deletion) {
+ const target = await commands.createRoot({ ...request, operationId: 'removal-target' });
+ const view = await commands.session(target.sessionId);
+ [deletion] = await ctx.storage.batch([
+ {
+ key: 'removal-intent',
+ expectedRevision: null,
+ data: {
+ kind: 'present',
+ value: { sessionId: target.sessionId, expectedRevision: view.revision },
+ },
+ },
+ ]);
+ if ((await commands.previewRemoval(target.sessionId)) !== 0)
+ throw new Error('independent root acquired unrelated dependents');
+ const stale = await commands.removeSession({
+ sessionId: target.sessionId,
+ expectedRevision: view.revision + 1,
+ });
+ if (stale.kind !== 'revision_conflict')
+ throw new Error('removal ignored its revision fence');
+ }
+ const removal = deletion.data.value;
+ const previousRemoval = await commands.removalReceipt(removal.sessionId);
+ if (!previousRemoval) {
+ const removed = await commands.removeSession(removal);
+ if (removed.kind !== 'removed') throw new Error('authorized removal did not commit');
+ }
+ const durableRemoval = await commands.removalReceipt(removal.sessionId);
+ if (
+ durableRemoval?.sessionId !== removal.sessionId ||
+ durableRemoval.archivedSubtaskCount !== 0
+ )
+ throw new Error('removal receipt did not survive retirement or restart');
+ const repeatedRemoval = await commands.removeSession(removal);
+ if (
+ repeatedRemoval.kind !== 'removed' ||
+ repeatedRemoval.receipt.sessionId !== removal.sessionId
+ )
+ throw new Error('removal retry required the removed catalog record');
const session = await commands.session(root.sessionId);
const configured = await commands.configure({
sessionId: root.sessionId,
diff --git a/crates/runtime-host/tests/integration/main.rs b/crates/runtime-host/tests/integration/main.rs
index 2aff24bbcf..345ce0d1f5 100644
--- a/crates/runtime-host/tests/integration/main.rs
+++ b/crates/runtime-host/tests/integration/main.rs
@@ -82,6 +82,7 @@ mod retirement;
mod runtime_policy;
mod scheduler_plugin;
mod session_history;
+mod session_removal;
mod skills_management;
mod skills_plugin;
mod system_prompt;
diff --git a/crates/runtime-host/tests/integration/session_removal.rs b/crates/runtime-host/tests/integration/session_removal.rs
new file mode 100644
index 0000000000..7bb3c9a7a1
--- /dev/null
+++ b/crates/runtime-host/tests/integration/session_removal.rs
@@ -0,0 +1,204 @@
+/*
+ * 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_event_log::sessions::SessionRetirement;
+use maka_fs_tools::worktree::Worktrees;
+use maka_protocol::session::{SandboxMode, WorkspaceProjection, WorkspaceTarget};
+use maka_runtime_host::{
+ server::{Host, local::LocalListener},
+ session::{PreparedSession, SessionConfiguration, SessionTarget},
+};
+use serde_json::json;
+use sqlx::Connection;
+use std::{
+ process::Command,
+ sync::{Arc, atomic::AtomicBool},
+ time::Duration,
+};
+use tokio_util::sync::CancellationToken;
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn removal_recovers_without_its_requester_and_releases_only_the_last_workspace_owner() {
+ let fixture = ClientFixture::new("maka-removal-");
+ let cwd =
+ maka_fs_tools::workspace::project::host_path(&fixture.workspace.canonicalize().unwrap())
+ .unwrap()
+ .to_owned();
+ for args in [
+ vec!["init", "--quiet"],
+ vec!["config", "user.name", "Maka tests"],
+ vec!["config", "user.email", "tests@maka.invalid"],
+ vec!["commit", "--quiet", "--allow-empty", "-m", "base"],
+ ] {
+ let output = Command::new("git")
+ .current_dir(&cwd)
+ .env("GIT_CONFIG_NOSYSTEM", "1")
+ .env(
+ "GIT_CONFIG_GLOBAL",
+ if cfg!(windows) { "NUL" } else { "/dev/null" },
+ )
+ .args(args)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ let root = fixture.owner().canonical_path().to_owned();
+ let worktrees = Worktrees::open(&root.join("subagent-worktrees")).unwrap();
+ let cancel = Arc::new(AtomicBool::new(false));
+ let binding = worktrees
+ .plan(std::path::Path::new(&cwd), &"a".repeat(64), cancel.clone())
+ .unwrap();
+ worktrees.ensure(&binding, &cancel).unwrap();
+ let configuration = PreparedSession::new(serde_json::from_value(json!({
+ "sessionId":"source", "workspace":{"kind":"host_path","path":cwd}, "executorId":"fixture"
+ })).unwrap()).unwrap().bind(
+ WorkspaceProjection { target: WorkspaceTarget::HostPath { path: cwd.clone() }, host_cwd: cwd.clone() },
+ SessionTarget::Executor { executor_id: "fixture".to_owned().try_into().unwrap(), settings: Default::default() },
+ SandboxMode::DangerFullAccess,
+ );
+ let log = fixture.log().await;
+ log.create_session("source", "source", &configuration, 1)
+ .await
+ .unwrap();
+ let mut shared = configuration.clone();
+ shared.workspace_origin = maka_runtime::execution::WorkspaceOrigin::Allocated;
+ shared.workspace.host_cwd = binding.directory().to_str().unwrap().into();
+ shared.workspace.target = WorkspaceTarget::HostPath {
+ path: shared.workspace.host_cwd.clone(),
+ };
+ shared.worktree = Some(binding.clone());
+ for session in ["first", "last"] {
+ log.create_session(session, session, &shared, 1)
+ .await
+ .unwrap();
+ }
+ log.close().await.unwrap();
+
+ for session in ["first", "last"] {
+ let log = fixture.log().await;
+ log.begin_session_removal(session, 1).await.unwrap();
+ log.close().await.unwrap();
+ // The accepting process disappeared before scheduling any cleanup.
+ let host = Host::open(fixture.owner()).await.unwrap();
+ #[cfg(unix)]
+ let endpoint = fixture.workspace.parent().unwrap().join("removal.sock");
+ #[cfg(windows)]
+ let endpoint =
+ std::path::PathBuf::from(format!(r"\\.\pipe\maka-removal-{}", uuid::Uuid::new_v4()));
+ let stop = CancellationToken::new();
+ let _cleanup = stop.clone().drop_guard();
+ let server = tokio::spawn(
+ LocalListener::bind(&endpoint)
+ .unwrap()
+ .serve(host.clone(), stop.clone()),
+ );
+ let mut peer = Peer::new(host.clone(), "removal").await;
+ let mut read = sqlx::SqliteConnection::connect_with(
+ &sqlx::sqlite::SqliteConnectOptions::new()
+ .filename(root.join(maka_event_log::root::ROOT_DATABASE))
+ .read_only(true),
+ )
+ .await
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while !sqlx::query_scalar::<_, bool>(
+ "SELECT completed FROM session_retirements WHERE session_id=?",
+ )
+ .bind(session)
+ .fetch_one(&mut read)
+ .await
+ .unwrap()
+ {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .unwrap();
+ read.close().await.unwrap();
+ if session == "first" {
+ worktrees.inspect(&binding).unwrap();
+ let selected = peer
+ .rpc(
+ "session.workspace.relocate",
+ json!({
+ "sessionId":"source", "expectedRevision":1,
+ "workspace":{"kind":"host_path","path":binding.directory()}
+ }),
+ )
+ .await;
+ assert_eq!(
+ selected["error"]["code"], "operation_conflict",
+ "{selected}"
+ );
+ } else {
+ assert!(!binding.directory().exists());
+ assert!(worktrees.ensure(&binding, &cancel).is_err());
+ }
+ let visible = peer
+ .rpc(
+ "session.catalog.query",
+ json!({"kind":"get","sessionId":"source"}),
+ )
+ .await;
+ assert_eq!(
+ visible["ok"], true,
+ "unrelated Session remains available: {visible}"
+ );
+ if session == "last" {
+ let missing = peer
+ .rpc("session.remove.query", json!({"sessionId":"source"}))
+ .await;
+ assert_eq!(missing["result"]["kind"], "missing", "{missing}");
+ let preview = peer
+ .rpc("session.remove.preview", json!({"sessionId":"source"}))
+ .await;
+ assert_eq!(preview["result"]["archivableSubtaskCount"], 0, "{preview}");
+ let input = json!({"sessionId":"source", "expectedRevision":1});
+ let removed = peer.rpc("session.remove", input.clone()).await;
+ assert_eq!(removed["result"]["kind"], "removed", "{removed}");
+ let replay = peer.rpc("session.remove", input).await;
+ assert_eq!(replay["result"], removed["result"], "{replay}");
+ let receipt = peer
+ .rpc("session.remove.query", json!({"sessionId":"source"}))
+ .await;
+ assert_eq!(receipt["result"], removed["result"], "{receipt}");
+ }
+ peer.close().await;
+ stop.cancel();
+ server.await.unwrap().unwrap();
+ drop(host);
+ let log = fixture.log().await;
+ assert_eq!(
+ log.session_retirement(session).await.unwrap(),
+ Some(SessionRetirement::Removed)
+ );
+ assert!(
+ log.get_session::<SessionConfiguration>(session)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ log.close().await.unwrap();
+ }
+}
diff --git a/crates/runtime/src/event.rs b/crates/runtime/src/event.rs
index 38135ade90..1cc82b76a5 100644
--- a/crates/runtime/src/event.rs
+++ b/crates/runtime/src/event.rs
@@ -326,6 +326,9 @@ impl LogPrefix {
#[derive(Debug, thiserror::Error)]
pub enum CommitError {
+ /// This Session has stopped accepting work. No effect was admitted.
+ #[error("session retired")]
+ Retired,
#[error("event rejected: {0}")]
Rejected(String),
#[error("event commit outcome unknown: {0}")]
diff --git a/crates/runtime/src/tools/journal.rs b/crates/runtime/src/tools/journal.rs
index c7643b8c9b..b5ac0a1edf 100644
--- a/crates/runtime/src/tools/journal.rs
+++ b/crates/runtime/src/tools/journal.rs
@@ -138,7 +138,12 @@ impl ToolJournal {
.map_err(|error| ToolError::Persistence(error.to_string()))?,
)
.await
- .map_err(|error| ToolError::Persistence(error.to_string()))?;
+ .map_err(|error| match error {
+ crate::event::CommitError::Retired => {
+ ToolError::Failed("session retired before effect".into())
+ }
+ other => ToolError::Persistence(other.to_string()),
+ })?;
let result = if cancellation.is_cancelled() {
Err(ToolError::Failed("cancelled before effect".into()))
diff --git a/docs/rust-parity.md b/docs/rust-parity.md
index 101f644170..521bdc6932 100644
--- a/docs/rust-parity.md
+++ b/docs/rust-parity.md
@@ -91,8 +91,8 @@ implementations; wire adapters may retain existing client vocabulary.
| External agents | Setup start/query/cancel; execution adapters, configuration, auth, conversation identity, adapter-specific attachments/interactions/resume/fork. | **Plugin + Host.** Implement concrete CLI/ACP adapters as Executor plugins over owned processes/HTTP. Generic Executor support is not a shipped adapter. Host owns authorization, cancellation and canonical external-event recording. |
| Usage / Pricing | Usage queries, revision-consistent screens/activity pages, pricing query/mutate and valuation. | **Plugin + Host.** Reports, price policy and rebuildable projections may be an Insights domain; Host records usage independently of plugin availability and provides consistent reads. Missing usage must not become zero. |
| Background health | BackgroundTaskHealth process and endpoint checks. | **Plugin + Host.** Health interpretation and Tool in a plugin; Host exposes authorized resource observations and bounded probes. A stored PID is not resource ownership. |
-| Session lineage | Public Rust/JS history copying and source reads, native branch/revision create/abandon, retention notices and receipt-based Client recovery exist. Desktop canonical-input editing remains. Regeneration is removed; edits use revision and resend. | **Host.** One transactional lineage and workspace authority; plugins may request changes through commands, not reproduce them in private storage. |
-| Session lifecycle | Removal/preview and shared Session queries. | **Host.** Coordinate references, running work, attachments, owned worktrees, grants and cleanup. Shared queries depend on real collaboration authorization. |
+| Session lineage | Public Rust/JS history copying and source reads, native branch/revision create/abandon, independent inherited pruning, Desktop canonical-input editing and complete durable drafts are implemented. Regeneration is removed; edits use revision and resend. | **Host.** One transactional lineage and workspace authority; plugins request changes through commands, not private lineage storage. |
+| Session lifecycle | Native and public plugin removal/preview/receipt APIs, atomic family retirement and queued cancellation, restart cleanup and shared-worktree ownership are implemented. Unreferenced canonical-material reclamation and shared Session queries remain. | **Host.** Preserve referenced history and accepted receipts; unknown process cleanup must not delete its workspace. Shared queries require real collaboration authorization. |
| Session transfer | Bundle export/import and unified external catalog/source/import for Codex, Claude Code and OpenCode. | **Plugin + Host.** Source parsing/discovery can be adapters; Host owns bounded canonical import, identities, artifacts, provenance and atomic publication. Native bundle format remains a Host contract. Never import source event bytes as trusted execution authority. |
| Runtime policy | Shell/external-agent consumers and ordinary named tool profiles. | **Split.** Shell launch policy and capability ceilings stay in Host. External-agent settings belong to their domain. Profiles contribute definitions; Host applies the intersection at admission and per-step capture. Storing settings alone is insufficient. |
| Access / collaboration | Credential rotation prepare/revoke; principal revoke; collaboration access, invitation, grant revoke, principal rename/revoke; Turn-request create/query/decide/acknowledge/withdraw. | **Host.** Reuse credential and durable admission authority. Plugins may provide workflows/UI but cannot decide grants, bypass revocation or own canonical accepted Turn requests. |
diff --git a/docs/rust-parity.zh-CN.md b/docs/rust-parity.zh-CN.md
index fa77862718..d12204a671 100644
--- a/docs/rust-parity.zh-CN.md
+++ b/docs/rust-parity.zh-CN.md
@@ -81,8 +81,8 @@ runtime 契约不能反向依赖插件实现,协议适配层可以保留现有
| 外部 agent | setup start/query/cancel;具体执行适配、配置、鉴权、对话身份,以及附件/交互/resume/fork。 | **插件 + Host。** CLI/ACP 适配作为 Executor 插件,使用受管理进程/HTTP。已有 Executor 框架不等于已有具体 adapter。Host 负责授权、取消和外部事件落盘。 |
| Usage/Pricing | Usage 查询、一致版本视图及活动分页,Pricing 查询/修改和估价。 | **插件 + Host。** 报表、价格策略和可重建投影可归 Insights 领域;Host 不依赖插件存活来记录用量,并提供一致快照。缺失用量不能视为零。 |
| 后台健康 | BackgroundTaskHealth 的进程和端点检查。 | **插件 + Host。** 插件解释健康状态并提供工具;Host 提供授权资源观察和有界探测。保存 PID 不等于拥有进程。 |
-| Session 谱系 | 公共 Rust/JS 历史复制及原始输入读取、原生分支/修订创建与放弃、保留通知及基于回执的 Client 恢复已有。Desktop 规范输入编辑仍待接入。已移除 regenerate,修改请求使用编辑重发。 | **Host。** 谱系及工作区只有一个事务权威;插件可以请求命令,不能在私有存储中重做。 |
-| Session 生命周期 | 删除/预览、shared 查询。 | **Host。** 协调引用、运行中工作、附件、托管 worktree、授权及清理。shared 查询依赖真实协作授权。 |
+| Session 谱系 | 已实现公共 Rust/JS 历史复制和原始输入读取、原生分支/修订创建与放弃、继承历史独立裁剪、Desktop 规范输入编辑及完整持久草稿。已移除 regenerate,修改请求使用编辑重发。 | **Host。** 谱系及工作区只有一个事务权威;插件请求命令,不在私有存储中重做谱系。 |
+| Session 生命周期 | 已实现原生与公共插件删除/预览/回执接口、原子家族退休及队列取消、重启清理和共享 worktree 所有权。无引用规范材料回收及 shared 查询仍待完成。 | **Host。** 保留被引用历史及已接受回执;进程清理不确定时不得删除工作目录。shared 查询需要真实协作授权。 |
| Session 迁入迁出 | bundle 导入/导出;Codex、Claude Code、OpenCode 的统一外部 catalog/source/import。 | **插件 + Host。** 来源解析/发现可以作为 adapter;Host 拥有有界规范导入、身份、附件、来源记录和原子发布。原生 bundle 格式仍是 Host 合同,不能把外部事件字节直接作为可信执行权威。 |
| Runtime policy | shell/external-agent 消费,普通 named tool profiles。 | **拆分。** shell 启动策略和能力上限留在 Host;外部 agent 设置由对应领域消费。Profile 提供定义,Host 在准入和每步捕获时取能力交集。只保存设置不算完成。 |
| 接入/协作 | credential rotation prepare/revoke、principal revoke;collaboration access、邀请、grant revoke、principal rename/revoke;Turn-request create/query/decide/acknowledge/withdraw。 | **Host。** 复用凭据和持久化准入权威。插件可以提供流程/UI,但不能决定授权、绕过撤销或拥有规范的已接受 Turn request。 |
diff --git a/docs/rust-runtime.md b/docs/rust-runtime.md
index ab3c48ab3e..5cb04d815e 100644
--- a/docs/rust-runtime.md
+++ b/docs/rust-runtime.md
@@ -327,6 +327,18 @@ remaining inherited tool results and compact its own context without changing it
siblings or earlier frozen reads. A subsequent copy adopts the parent's current projection;
archive verification always retains the original tool-call evidence.
+Session removal commits its revision-family plan, admission fence and queued-message
+cancellations atomically. Dependent Sessions are archived, not destroyed; restoring one
+after cleanup is not undone by an old removal retry. `session.remove.query` recovers the
+accepted receipt even after the catalog entry disappears. Public Rust/JS execution
+capabilities expose the same removal, preview and receipt semantics, requiring authority
+over every directly removed member; history access alone is insufficient.
+
+Host drains accepted executions and processes before reclaiming owned worktrees, and
+keeps a shared checkout until its last owner retires. Unproven process cleanup leaves
+the workspace intact without blocking unrelated Sessions. Canonical facts and inherited
+archive proofs remain stored; removal is not secure erasure of historical data.
+
## Conversation recall
`maka.recall` publishes lazy `Recall`, `RecallMore` and `RecallMaterial` through public history
diff --git a/docs/rust-runtime.zh-CN.md b/docs/rust-runtime.zh-CN.md
index 4dfbf6d674..24d412dbc1 100644
--- a/docs/rust-runtime.zh-CN.md
+++ b/docs/rust-runtime.zh-CN.md
@@ -249,6 +249,15 @@ Desktop 可预览并附加同一 Host 中另一会话的已提交文本快照。
上下文,不改变源会话、兄弟分支或先前的冻结读取。后续副本继承父会话当前的投影;
归档校验始终保留原始工具调用证据。
+会话删除原子提交修订家族计划、准入关闭和排队消息取消。依赖会话归档而非销毁;
+清理后恢复的依赖会话不会被旧删除重试再次归档。`session.remove.query` 在目录项消失后
+仍可恢复已接受回执。公共 Rust/JS 执行能力提供相同的删除、预览和回执语义,
+必须覆盖全部直接删除成员的权限;历史读取授权不等于删除授权。
+
+Host 等待已接受执行和进程清理后才回收托管 worktree,共享目录保留到最后一个所有者退出。
+不能确认进程清理时保留目录,不阻塞无关会话。规范事实与继承归档证明仍保存在日志中;
+删除会话不等于安全擦除历史数据。
+
## 会话回忆
`maka.recall` 通过公共历史能力发布动态加载的 `Recall`、`RecallMore` 和 `RecallMaterial`。
diff --git a/packages/plugin-sdk/src/execution.ts b/packages/plugin-sdk/src/execution.ts
index da8a611522..c07a540c04 100644
--- a/packages/plugin-sdk/src/execution.ts
+++ b/packages/plugin-sdk/src/execution.ts
@@ -177,7 +177,25 @@ export type Configured =
| { kind: 'committed'; session: SessionConfiguration }
| { kind: 'revision_conflict'; expectedRevision: number; actualRevision: number };
+/** Durable acceptance; resource cleanup may still be pending. */
+export interface RemovalReceipt {
+ sessionId: string;
+ archivedSubtaskCount: number;
+}
+
export interface Executions {
+ /** Every directly removed revision-family member must be authorized. */
+ removeSession(input: {
+ sessionId: string;
+ expectedRevision: number;
+ }): Promise<
+ | { kind: 'removed'; receipt: RemovalReceipt }
+ | { kind: 'revision_conflict'; expectedRevision: number; actualRevision: number }
+ >;
+ /** Recover acceptance without requiring the deleted catalog record. */
+ removalReceipt(sessionId: string): Promise<RemovalReceipt | null>;
+ /** Advisory dependent-family count, recomputed and authorized on removal. */
+ previewRemoval(sessionId: string): Promise<number>;
/** Host-local immutable copy; both capability endpoints require current authority. */
copyAttachment(
source: Executions,
diff --git a/packages/runtime-host/src/protocol/operations.ts b/packages/runtime-host/src/protocol/operations.ts
index 31b799e46f..f29c40f531 100644
--- a/packages/runtime-host/src/protocol/operations.ts
+++ b/packages/runtime-host/src/protocol/operations.ts
@@ -352,6 +352,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
'session.recap.generate',
'session.remove',
'session.remove.preview',
+ 'session.remove.query',
'session.revision.abandon',
'session.revision.create',
'session.transcript.page',
diff --git a/packages/runtime-host/src/protocol/session-retirement.ts b/packages/runtime-host/src/protocol/session-retirement.ts
index 4eb0183ca5..879f685c75 100644
--- a/packages/runtime-host/src/protocol/session-retirement.ts
+++ b/packages/runtime-host/src/protocol/session-retirement.ts
@@ -59,6 +59,18 @@ export interface SessionRemovePreviewInput {
readonly sessionId: string;
}
+export interface SessionRemoveQueryInput {
+ readonly sessionId: string;
+}
+
+export type SessionRemoveQueryResult =
+ | { readonly kind: 'missing' }
+ | {
+ readonly kind: 'removed';
+ readonly sessionId: string;
+ readonly archivedSubtaskCount: number;
+ };
+
export interface SessionRemovePreviewResult {
/**
* How many ordinary linked subagent subtasks a delete of this parent would
@@ -142,6 +154,42 @@ export const SESSION_RETIREMENT_OPERATION_SPECS = {
decodeInput: decodeSessionRemovePreviewInput,
decodeOutput: decodeSessionRemovePreviewResult,
}),
+ 'session.remove.query': defineOperation<
+ SessionRemoveQueryInput,
+ SessionRemoveQueryResult,
+ (typeof LIFECYCLE_ERRORS)[number]
+ >({
+ mode: 'query',
+ availability: 'ready',
+ errors: LIFECYCLE_ERRORS,
+ decodeInput: (value) => {
+ const input = requireExactRecord(value, 'Session removal receipt query', ['sessionId']);
+ return { sessionId: requireEntityId(input.sessionId, 'sessionId') };
+ },
+ decodeOutput: (value) => {
+ const result = requireRecord(value, 'Session removal receipt');
+ if (result.kind === 'missing') {
+ requireExactRecord(result, 'Missing Session removal receipt', ['kind']);
+ return { kind: 'missing' };
+ }
+ if (result.kind !== 'removed') throw invalidProtocolFrame('Invalid Session removal receipt');
+ const exact = requireExactRecord(result, 'Session removal receipt', [
+ 'kind',
+ 'sessionId',
+ 'archivedSubtaskCount',
+ ]);
+ return {
+ kind: 'removed',
+ sessionId: requireEntityId(exact.sessionId, 'sessionId'),
+ archivedSubtaskCount: requireCount(exact.archivedSubtaskCount, 'archivedSubtaskCount'),
+ };
+ },
+ assertOutputForInput: (input, output) => {
+ if (output.kind === 'removed' && output.sessionId !== input.sessionId) {
+ throw invalidProtocolFrame('Session removal receipt belongs to another Session');
+ }
+ },
+ }),
} as const;
export function decodeSessionLifecycleSetInput(value: unknown): SessionLifecycleSetInput {
diff --git a/packages/runtime-host/src/server/operation-dispatcher.ts b/packages/runtime-host/src/server/operation-dispatcher.ts
index 02818a6f80..d95286f08f 100644
--- a/packages/runtime-host/src/server/operation-dispatcher.ts
+++ b/packages/runtime-host/src/server/operation-dispatcher.ts
@@ -138,7 +138,10 @@ export type SessionRevisionOperationKey =
| 'session.branch.create'
| 'session.revision.create'
| 'session.revision.abandon';
-export type SessionRetirementOperationKey = keyof typeof SESSION_RETIREMENT_OPERATION_SPECS;
+export type SessionRetirementOperationKey = Exclude<
+ keyof typeof SESSION_RETIREMENT_OPERATION_SPECS,
+ 'session.remove.query'
+>;
export type SessionEffectOperationKey = keyof typeof SESSION_EFFECT_OPERATION_SPECS;
export type SessionTodoOperationKey = keyof typeof SESSION_TODO_OPERATION_SPECS;
export type SessionCatalogOperationKey =
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org