Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
fix(agent): preserve queued Host Wake task lease until dispatch
  • Loading branch information
Beaten0123 committed Nov 15, 2026
commit 482aec044edec101cad0eecd7459f86187adacbb
6 changes: 5 additions & 1 deletion crates/webcodex-store/src/agent_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ pub(crate) const MAX_AGENT_TASK_PROJECT_REF_CHARS: usize = 256;
pub const MAX_AGENT_TASK_LIST_LIMIT: usize = 100;
pub(crate) const DEFAULT_AGENT_TASK_ATTEMPT_LEASE_MS: i64 = 60_000;
pub(crate) const AGENT_TASK_ENDPOINT_DISPATCH_GRACE_MS: i64 = 5 * 60_000;
// A Task Wake queued behind an uncertain Host dispatch is not executing yet.
// Cover the 15-minute delivery safety window, 5-minute possible prior
// dispatch grace, and a final 60-second margin. This applies only while
// another post-dispatch Wake holds the Agent's single-flight slot.
pub(crate) const AGENT_TASK_ENDPOINT_QUEUED_WAKE_LEASE_MS: i64 = 21 * 60_000;
pub(crate) const AGENT_TASK_ENDPOINT_TAKEOVER_LEASE_MS: i64 = 30 * 60_000;

const OP_CREATE_AGENT_TASK: &str = "create_agent_task";
const OP_START_AGENT_TASK_ATTEMPT: &str = "start_agent_task_attempt";
const OP_COMPLETE_AGENT_TASK_ATTEMPT: &str = "complete_agent_task_attempt";
Expand Down
28 changes: 28 additions & 0 deletions crates/webcodex-store/src/agent_task/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,34 @@ impl Database {
));
}

// A new TaskAttempt's usual 60-second lease must not expire merely
// because an older uncertain Host Wake occupies the dispatch slot.
// Grant a one-shot bounded queue reservation in the same transaction
// as the new pending Wake. Exact replay cannot refresh this deadline.
let predecessor_blocks_dispatch: bool = transaction
.query_row(
"SELECT EXISTS(SELECT 1 FROM wc_agent_wakes
WHERE target_agent_id = ?1
AND state IN ('prepared', 'delivered', 'delivery_unknown'))",
params![assignee_agent_id],
|row| row.get(0),
)
.map_err(store_error)?;
if predecessor_blocks_dispatch {
transaction
.execute(
"UPDATE wc_agent_task_attempts
SET lease_expires_at_unix_ms = MAX(lease_expires_at_unix_ms, ?3)
WHERE attempt_id = ?1 AND task_id = ?2 AND state = 'active'",
params![
attempt_id,
task_id,
now.saturating_add(AGENT_TASK_ENDPOINT_QUEUED_WAKE_LEASE_MS),
],
)
.map_err(store_error)?;
}

let wake_id = allocate_identity(
&transaction,
AGENT_WAKE_ID_PREFIX,
Expand Down
139 changes: 139 additions & 0 deletions crates/webcodex-store/src/agent_task_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5445,3 +5445,142 @@ fn expired_uncertain_task_wake_fences_old_token_and_allows_new_host_takeover() {
AgentWakeState::Retired,
);
}

/// A stale uncertain Task dispatch cannot consume the next Attempt's 60s
/// lease while it owns the single-flight Host slot. Exact old consume is
/// revoked after its source Attempt expires and the safety window elapses.
#[test]
fn queued_task_attempt_survives_older_uncertain_task_wake_then_consumes_once() {
let temp = tempfile::tempdir().unwrap();
let db = Database::open(&temp.path().join("queued-behind-task-unknown.db")).unwrap();
let owner = principal('f');
let now = wall_now_ms();
let old = prepared_endpoint_takeover_fixture(&db, &owner, "old-task-slot", now);
db.mark_agent_wake_delivery_unknown_at(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
&old.wake_id,
&old.wake_attempt_id,
&old.wake_claim_fence,
now + 2,
)
.unwrap();

let task_id = create_assigned_task(&db, &owner, &old.assignee, "next-task-after-unknown");
let started = start(
&db,
&owner,
&task_id,
&old.assignee,
"next-task-queued",
now + 3,
);
let next = db
.start_agent_task_endpoint_continuation_at(
&owner,
&task_id,
&started.attempt.attempt_id,
&old.assignee,
&started.attempt_fence,
started.attempt.attempt_controller_generation,
now + 4,
)
.unwrap();
let queued_lease = attempt_lease_expires_at(&db, &started.attempt.attempt_id);
assert!(queued_lease > now + 20 * 60_000);
assert!(db
.claim_next_agent_wake(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
"mcp_app"
)
.unwrap()
.is_none());
assert_eq!(
db.agent_wake(&next.execution.wake_id)
.unwrap()
.unwrap()
.state,
AgentWakeState::Pending
);

// Existing execution is terminal before safety retirement, not
// silently promoted by this successor or a fabricated Host ACK.
db.conn_for_tests()
.execute(
"UPDATE wc_agent_task_attempts SET lease_expires_at_unix_ms = ?2
WHERE attempt_id = ?1 AND state = 'active'",
params![old.task_attempt_id, now - 1],
)
.unwrap();
db.conn_for_tests()
.execute(
"UPDATE wc_agent_wakes SET updated_at_unix_ms = ?2 WHERE wake_id = ?1",
params![
old.wake_id,
now - super::agent_wake::STALE_TASK_DELIVERY_UNKNOWN_MS - 1_000
],
)
.unwrap();
let claimed = db
.claim_next_agent_wake(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
"mcp_app",
)
.unwrap()
.expect("new valid Task Wake must take over after safe retirement");
assert_eq!(claimed.wake.wake_id, next.execution.wake_id);
assert_eq!(
db.agent_wake(&old.wake_id).unwrap().unwrap().state,
AgentWakeState::Retired
);
assert!(
db.consume_agent_wake(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
&old.wake_id,
&old.consume_token
)
.is_err(),
"late old uncertain Host turn cannot consume the revoked fence"
);
let dispatch_lease = attempt_lease_expires_at(&db, &started.attempt.attempt_id);
assert!(dispatch_lease < queued_lease);
assert!(dispatch_lease > wall_now_ms() + 4 * 60_000);
db.prepare_agent_wake_dispatch(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
&claimed.wake.wake_id,
&claimed.attempt.attempt_id,
&claimed.claim_fence,
&claimed.consume_token,
)
.unwrap();
db.consume_agent_wake(
&owner,
&old.assignee,
&old.endpoint_id,
old.endpoint_controller_generation,
&claimed.wake.wake_id,
&claimed.consume_token,
)
.unwrap();
assert_eq!(
db.agent_wake(&claimed.wake.wake_id).unwrap().unwrap().state,
AgentWakeState::Consumed
);
assert!(
attempt_lease_expires_at(&db, &started.attempt.attempt_id) > wall_now_ms() + 29 * 60_000
);
}
15 changes: 15 additions & 0 deletions crates/webcodex-store/src/agent_wake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2364,6 +2364,21 @@ fn bind_agent_task_wake_carrier(
attempt_controller_generation,
)?;
replace_agent_task_attempt_controller_in_transaction(transaction, principal, authority, now)?;
// This pending Wake has claimed the single-flight Host carrier. Drop
// its long queue-only reservation to the ordinary pre-consume dispatch
// window; only the exact new model-turn consume grants active-turn time.
transaction
.execute(
"UPDATE wc_agent_task_attempts
SET lease_expires_at_unix_ms = MIN(lease_expires_at_unix_ms, ?3)
WHERE attempt_id = ?1 AND task_id = ?2 AND state = 'active'",
params![
task_attempt_id,
task_id,
now.saturating_add(AGENT_TASK_ENDPOINT_DISPATCH_GRACE_MS),
],
)
.map_err(store_error)?;
let changed = transaction
.execute(
"UPDATE wc_agent_task_endpoint_executions
Expand Down
96 changes: 96 additions & 0 deletions crates/webcodex-store/src/agent_wake_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,63 @@ fn old_unknown_inbox_dispatch_cannot_starve_new_endpoint_agent_task_after_grace(
now_unix_ms(),
)
.unwrap();
// The old Host dispatch is outcome-unknown: no successor model turn may
// start, but the successor must survive its 60-second default lease.
let queued_lease: i64 = db
.conn_for_tests()
.query_row(
"SELECT lease_expires_at_unix_ms FROM wc_agent_task_attempts WHERE attempt_id = ?1",
[&started.attempt.attempt_id],
|row| row.get(0),
)
.unwrap();
assert!(
queued_lease >= now_unix_ms() + STALE_INBOX_DELIVERY_UNKNOWN_MS + 5 * 60_000,
"queued Task Wake must outlive the predecessor's Host uncertainty window"
);
assert!(
db.claim_next_agent_wake(
&fixture.owner,
&fixture.receiver_agent_id,
&endpoint.endpoint_id,
endpoint.controller_generation,
"mcp_app"
)
.unwrap()
.is_none(),
"the predecessor still owns exclusive Host dispatch"
);
assert_eq!(
db.agent_wake(&execution.execution.wake_id)
.unwrap()
.unwrap()
.state,
AgentWakeState::Pending
);
let replay = db
.start_agent_task_endpoint_continuation_at(
&fixture.owner,
&task,
&started.attempt.attempt_id,
&fixture.receiver_agent_id,
&started.attempt_fence,
1,
now_unix_ms() + 90_000,
)
.unwrap();
assert!(replay.replayed);
assert_eq!(
queued_lease,
db.conn_for_tests()
.query_row(
"SELECT lease_expires_at_unix_ms FROM wc_agent_task_attempts WHERE attempt_id = ?1",
[&started.attempt.attempt_id],
|row| row.get::<_, i64>(0)
)
.unwrap(),
"exact queue replay must never slide its one-shot deadline"
);

db.conn_for_tests()
.execute(
"UPDATE wc_agent_wakes SET updated_at_unix_ms = ?2 WHERE wake_id = ?1",
Expand All @@ -601,6 +658,22 @@ fn old_unknown_inbox_dispatch_cannot_starve_new_endpoint_agent_task_after_grace(
.expect("new executable Task Wake must outrank abandoned Inbox delivery");
assert_eq!(recovered.wake.wake_id, execution.execution.wake_id);
assert_eq!(recovered.wake.trigger_kind, "agent_task_attempt");
let dispatch_lease: i64 = db
.conn_for_tests()
.query_row(
"SELECT lease_expires_at_unix_ms FROM wc_agent_task_attempts WHERE attempt_id = ?1",
[&started.attempt.attempt_id],
|row| row.get(0),
)
.unwrap();
assert!(
dispatch_lease < queued_lease,
"claim must drop the long queue-only lease"
);
assert!(
dispatch_lease >= now_unix_ms() + 4 * 60_000,
"claim retains the ordinary bounded Host dispatch window"
);
assert_eq!(
db.agent_wake(&old.wake.wake_id).unwrap().unwrap().state,
AgentWakeState::Retired,
Expand Down Expand Up @@ -629,6 +702,29 @@ fn old_unknown_inbox_dispatch_cannot_starve_new_endpoint_agent_task_after_grace(
&recovered.consume_token,
)
.expect("new Task's Host continuation can consume its own exact Wake");
assert!(
db.conn_for_tests()
.query_row(
"SELECT lease_expires_at_unix_ms FROM wc_agent_task_attempts WHERE attempt_id = ?1",
[&started.attempt.attempt_id],
|row| row.get::<_, i64>(0),
)
.unwrap()
> now_unix_ms() + 29 * 60_000,
"only exact consume promotes the Attempt to the active model-turn lease"
);
assert!(
db.consume_agent_wake(
&fixture.owner,
&fixture.receiver_agent_id,
&endpoint.endpoint_id,
endpoint.controller_generation,
&old.wake.wake_id,
&old.consume_token
)
.is_err(),
"retired old Host token must never execute again"
);
}

#[test]
Expand Down
8 changes: 6 additions & 2 deletions docs/architecture/durable-agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -850,8 +850,10 @@ A4b intentionally separates a short pre-takeover lease from renewable bounded ac
```text
TaskAttempt start
-> short 60-second setup/pre-dispatch lease
Endpoint carrier claim / prepare
-> still short pre-dispatch semantics
Endpoint continuation created while older Wake is still post-dispatch
-> one bounded 21-minute queue-only reservation (no Host execution authority)
older Wake safely retires or is exactly consumed; new Wake claims Host carrier
-> long queue lease reduced to at most 5-minute pre-consume dispatch window
first durable Host dispatch outcome (dispatch_accepted | delivery_unknown)
-> bounded 5-minute Host scheduling grace
exact model turn bootstrap + first exact consume during that grace
Expand All @@ -868,6 +870,8 @@ abnormal/stalled model turn
-> a new Attempt requires an explicit authorized start
```

The 21-minute queue-only lease is created **once**, during the exact Endpoint-continuation start, only when an older `prepared`, `delivered`, or `delivery_unknown` Wake already owns the Agent's single Host dispatch slot. It covers the 15-minute conservative retirement window, a possible 5-minute predecessor scheduling grace, and 60 seconds for the successor; without a blocker the default 60-second lease is unchanged. Exact start replay cannot slide the reservation. Acquiring the successor Wake in a serializable Store transaction shortens any longer queue lease to at most `now + 5 minutes` before dispatch; this is not an actual model turn, does not extend the older Wake, and cannot promote to the 30-minute active-turn lease. Safety retirement and old-token revocation are unchanged. A blocked queue with no available Host or a predecessor that has not reached safe retirement is not claimed or redispatched; its bounded reservation eventually expires and requires a fresh authorized Attempt. This bounded mitigation is not a guarantee of real-time Host delivery.

Crossing the durable Host dispatch fence now creates a separate scheduling reservation only for an exact Task-origin Wake. The first `prepared -> dispatch_accepted | delivery_unknown` transition atomically rechecks the owned latest active/unexpired Attempt, exact assignee, exact Wake, and exact bound Endpoint/generation, then uses `max(existing_lease, now + 5 minutes)`. Delivery uncertainty gets the same reservation because the Host may already have accepted the message and exactly-once delivery forbids a blind resend. Same-generation process-local Host-binding loss or Server takeover that conservatively records an already-prepared Wake as `delivery_unknown` establishes that same one-shot grace before carrier capability is cleared; durable Endpoint replacement/expiry/detach fences the old generation instead and grants it no new grace. Dispatch replay, `delivery_unknown -> delivered` reconciliation, stale Endpoint generations, wrong Wakes, non-Task Wakes, polling, Endpoint heartbeat, and ClientWindow activity do not slide this reservation. A dispatch outcome arriving after the Attempt already expired or was superseded is still durable Wake evidence but never revives that Attempt.

The first successful exact consume of an `agent_task_attempt` Wake promotes only the same latest, active, unexpired, exact-assignee Attempt whose durable A4b Endpoint execution still matches that Wake and Endpoint generation. Promotion is atomic with Wake consumption and uses `max(existing_lease, now + 30 minutes)`. Consume replay does not slide the lease. An expired, terminal, superseded, or carrier-mismatched Attempt is never revived; its already-dispatched Wake can still be consumed/ACKed without lease promotion. `inbox_changed`, `attention_event`, and `agent_wait_events` consumption never changes a TaskAttempt lease.
Expand Down
Loading