Files
crank/crates/crank-registry/tests/integration/tasks/mod.rs
T
bsodfather a3057de51e
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 20m46s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
feat(epic4): безопасные повторы и отмена durable Task (Story 4.4)
Durable per-outbound attempt до отправки запроса, bounded retry/read,
server-owned verified writes, честный cancel/unknown, deadline/fencing,
additive schema v29. Staged renames task.rs/tasks.rs разложены на модули.

Includes disclosed cosmetic parity exception: единственная правка вне
принятой дельты — удалена лишняя пустая строка в конце
scripts/ci-story-checks.sh (EOF blank line); story-код не менялся.
2026-10-30 12:21:57 +00:00

919 lines
33 KiB
Rust

//! ATDD Story 4.2 (FR-22/FR-23): durable Task acceptance on a real PostgreSQL schema.
//!
//! These oracles drive the real store: Task + dispatch intent + queue slot in one transaction, replay
//! and typed conflict before any capacity mutation, bounded shared capacity, the Task-linked intent
//! guard of the legacy admission paths, one-winner terminal CAS with an immutable result, bounded
//! retention, owner/authorization-scope isolation and fail-closed health.
use super::common;
use crank_core::{
AdmissionMode, AdmissionOutcome, AdmissionRequest, AdmissionScope, AgentId, ApprovalEvidence,
BeginAttempt, ExecutionAdmission, NoTasksFallback, PlatformApiKey, PlatformApiKeyId,
PlatformApiKeyKind, PlatformApiKeyScope, PlatformApiKeyStatus, RequestId, TaskAcceptRequest,
TaskAccess, TaskEnvelope, TaskError, TaskFinishRequest, TaskId, TaskOwnerKind, TaskPins,
TaskState, TaskStore, TaskSupportIds, ToolExecutionMode, TraceContext, WorkspaceId,
current_unix_ms,
};
use crank_registry::{
AdmissionLimits, CreatePlatformApiKeyRequest, PostgresExecutionAdmission, PostgresTaskStore,
};
use serde_json::json;
use sqlx::{PgPool, Row};
use time::{Duration as TimeDuration, OffsetDateTime};
const WORKSPACE: &str = "ws_default";
const AGENT: &str = "agent_a";
fn limits(queue: usize) -> AdmissionLimits {
AdmissionLimits {
global_limit: 4,
agent_limit: 4,
tool_limit: 4,
queue_limit: queue,
}
}
fn store_with(pool: PgPool, queue: usize) -> PostgresTaskStore {
PostgresTaskStore::new(pool, limits(queue), Default::default()).expect("valid store config")
}
fn unsampled_support() -> TaskSupportIds {
TaskSupportIds::new(
RequestId::generate(),
&TraceContext::parse("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00").unwrap(),
)
}
fn request(key: &str, fingerprint: &str, agent: &str, deadline_in_ms: i64) -> TaskAcceptRequest {
let deadline = current_unix_ms() + deadline_in_ms;
TaskAcceptRequest {
task_id: TaskId::generate(),
workspace_id: WORKSPACE.to_owned(),
owner_kind: TaskOwnerKind::Agent,
owner_id: agent.to_owned(),
authorization_scope: format!("credential:pk_{agent}"),
platform_api_key_id: Some(PlatformApiKeyId::new(format!("pk_{agent}"))),
operation_id: "op_report".to_owned(),
pins: TaskPins {
operation_version: 3,
policy_mode: ToolExecutionMode::Background,
execution_deadline_unix_ms: deadline,
retain_until_unix_ms: deadline + 3_600_000,
approval_reference: Some("appr_1".to_owned()),
retry: crank_core::TaskRetryPolicy::single_attempt(),
},
scoped_key: key.to_owned(),
input_fingerprint: fingerprint.to_owned(),
input: TaskEnvelope::try_redacted(&json!({"report": "q3", "api_key": "sk_live"})).unwrap(),
support: unsampled_support(),
executable_input_ciphertext: None,
executable_input_key_version: None,
executable_input_master_key_epoch: None,
}
}
fn access(agent: &str) -> TaskAccess {
TaskAccess {
workspace_id: WORKSPACE.to_owned(),
owner_kind: TaskOwnerKind::Agent,
owner_id: agent.to_owned(),
authorization_scope: format!("credential:pk_{agent}"),
}
}
fn key(seed: &str) -> String {
format!("{seed:0<64}").chars().take(64).collect()
}
fn digest(seed: &str) -> String {
format!("{seed:0<64}").chars().take(64).collect()
}
async fn row_counts(pool: &PgPool) -> (i64, i64) {
let row = sqlx::query(
"select
(select count(*)::bigint from tasks) as tasks,
(select count(*)::bigint from execution_admission_entries where task_id is not null)
as intents",
)
.fetch_one(pool)
.await
.unwrap();
(row.get("tasks"), row.get("intents"))
}
#[tokio::test]
async fn acceptance_commits_task_intent_and_slot_together() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let request = request(&key("k1"), &digest("f1"), AGENT, 30_000);
let task_id = request.task_id;
let support = request.support.clone();
// Another connection holds both controller rows: the acceptance cannot commit yet.
let mut blocker = registry.pool().begin().await.unwrap();
sqlx::query(
"insert into execution_admission_controllers (workspace_id) values ('*'), ($1)
on conflict (workspace_id) do nothing",
)
.bind(WORKSPACE)
.execute(&mut *blocker)
.await
.unwrap();
sqlx::query("update execution_admission_controllers set updated_at = updated_at")
.execute(&mut *blocker)
.await
.unwrap();
let pool = registry.pool().clone();
let acceptance = tokio::spawn(async move { store.accept(request).await });
tokio::time::sleep(std::time::Duration::from_millis(150)).await;
// No partial Task, no intent and no accepted response exist before COMMIT.
assert!(!acceptance.is_finished());
assert_eq!(row_counts(&pool).await, (0, 0));
blocker.commit().await.unwrap();
let acceptance = acceptance.await.unwrap().expect("acceptance commits");
assert_eq!(acceptance.state, TaskState::Queued);
assert!(!acceptance.replayed);
assert_eq!(acceptance.task_id, task_id);
assert_eq!(acceptance.support, support);
assert_eq!(row_counts(registry.pool()).await, (1, 1));
// A fresh connection and store read the committed pins/identities back.
let reader = store_with(database.concurrent_registry(2).await.pool().clone(), 8);
let record = reader.read(&access(AGENT), task_id).await.unwrap();
assert_eq!(record.state, TaskState::Queued);
assert_eq!(record.pins.operation_version, 3);
assert_eq!(record.pins.policy_mode, ToolExecutionMode::Background);
assert_eq!(record.pins.approval_reference.as_deref(), Some("appr_1"));
assert_eq!(record.support.request_id, support.request_id);
assert_eq!(record.support.trace_id, support.trace_id);
assert_eq!(record.support.traceparent, support.traceparent);
assert!(!record.support.trace_sampled);
// Secret-bearing input is classified before persistence.
assert_eq!(record.input.value()["api_key"], json!("[redacted]"));
assert_eq!(record.input.value()["report"], json!("q3"));
assert!(record.result.is_none());
database.cleanup().await;
}
#[tokio::test]
async fn replay_returns_the_same_task_and_one_slot() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let first = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.expect("first acceptance");
let before = store.read(&access(AGENT), first.task_id).await.unwrap();
let replay = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.expect("replay returns the accepted Task");
assert_eq!(replay.task_id, first.task_id);
assert!(replay.replayed);
assert_eq!(replay.support.request_id, first.support.request_id);
assert_eq!(row_counts(registry.pool()).await, (1, 1));
// Replay never rewrites the accepted row or its audit evidence.
let after = store.read(&access(AGENT), first.task_id).await.unwrap();
assert_eq!(after.version, before.version);
assert_eq!(after.updated_at_unix_ms, before.updated_at_unix_ms);
assert_eq!(after.created_at_unix_ms, before.created_at_unix_ms);
database.cleanup().await;
}
#[tokio::test]
async fn replay_stays_available_with_a_full_queue_and_past_execution_deadline() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 1);
// A short deadline: the Task is still retained after its execution deadline elapsed.
let first = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
.await
.expect("first acceptance");
sqlx::query(
"update tasks set execution_deadline = now() - interval '1 hour' where task_id = $1",
)
.bind(first.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
let replayed = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
.await
.expect("replay works with a full queue and an elapsed execution deadline");
assert_eq!(replayed.task_id, first.task_id);
assert!(replayed.replayed);
database.cleanup().await;
}
#[tokio::test]
async fn a_different_fingerprint_on_the_same_key_is_a_typed_conflict() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let first = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.expect("first acceptance");
let before = store.read(&access(AGENT), first.task_id).await.unwrap();
let conflict = store
.accept(request(&key("k1"), &digest("f2"), AGENT, 30_000))
.await
.expect_err("different input is a conflict");
assert_eq!(conflict, TaskError::FingerprintConflict);
assert_eq!(row_counts(registry.pool()).await, (1, 1));
let after = store.read(&access(AGENT), first.task_id).await.unwrap();
assert_eq!(after.version, before.version);
assert_eq!(after.updated_at_unix_ms, before.updated_at_unix_ms);
database.cleanup().await;
}
#[tokio::test]
async fn bounded_capacity_is_shared_and_overload_creates_nothing() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 1);
let admission =
PostgresExecutionAdmission::new(registry.pool().clone(), limits(1), Default::default())
.unwrap();
// A durable enqueue decision and a durable Task share the same bounded queue budget.
let waiting = admission
.admit(AdmissionRequest {
scope: AdmissionScope {
workspace_id: WORKSPACE.to_owned(),
agent_key: AGENT.to_owned(),
operation_id: "op_sync".to_owned(),
operation_version: 1,
},
mode: AdmissionMode::Background,
policy_mode: ToolExecutionMode::Background,
no_tasks_fallback: NoTasksFallback::Synchronous,
approval: ApprovalEvidence::NotRequired,
fingerprint: "fp_sync".to_owned(),
expires_at_unix_ms: current_unix_ms() + 30_000,
})
.await
.unwrap();
assert!(matches!(waiting, AdmissionOutcome::Enqueued(_)));
let overloaded = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.expect_err("queue is full");
assert!(matches!(overloaded, TaskError::Overloaded { .. }));
assert_eq!(row_counts(registry.pool()).await, (0, 0));
assert_eq!(
admission.snapshot().await.unwrap().waiting,
1,
"the durable refusal changed no capacity"
);
database.cleanup().await;
}
#[tokio::test]
async fn legacy_cleanup_and_cancel_never_remove_a_task_linked_intent() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let admission =
PostgresExecutionAdmission::new(registry.pool().clone(), limits(8), Default::default())
.unwrap();
let accepted = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
.await
.expect("acceptance");
// The linked reserved row looks expired; the legacy TTL cleanup must ignore it.
sqlx::query("update execution_admission_entries set expires_at = now() - interval '1 hour'")
.execute(registry.pool())
.await
.unwrap();
let ticket: i64 =
sqlx::query("select ticket_id from execution_admission_entries where task_id = $1")
.bind(accepted.task_id.as_uuid())
.fetch_one(registry.pool())
.await
.unwrap()
.get("ticket_id");
let owner_token: String =
sqlx::query("select owner_token from execution_admission_entries where ticket_id = $1")
.bind(ticket)
.fetch_one(registry.pool())
.await
.unwrap()
.get("owner_token");
// A legacy attempt runs the bounded expiry cleanup; a foreign/own legacy cancel is refused.
let _ = admission
.admit(AdmissionRequest {
scope: AdmissionScope {
workspace_id: WORKSPACE.to_owned(),
agent_key: "agent_b".to_owned(),
operation_id: "op_sync".to_owned(),
operation_version: 1,
},
mode: AdmissionMode::Synchronous,
policy_mode: ToolExecutionMode::Synchronous,
no_tasks_fallback: NoTasksFallback::Synchronous,
approval: ApprovalEvidence::NotRequired,
fingerprint: "fp_sync".to_owned(),
expires_at_unix_ms: current_unix_ms() + 50,
})
.await;
assert!(!admission.cancel(ticket as u64, &owner_token).await.unwrap());
assert_eq!(row_counts(registry.pool()).await, (1, 1));
assert_eq!(
store
.read(&access(AGENT), accepted.task_id)
.await
.unwrap()
.state,
TaskState::Queued
);
database.cleanup().await;
}
#[tokio::test]
async fn terminal_transition_has_one_winner_and_an_immutable_result() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let accepted = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.unwrap();
let queued = store.read(&access(AGENT), accepted.task_id).await.unwrap();
assert_eq!(queued.version, 1);
// Moving a queued Task straight to completed is not an allowed transition.
let skipped = TaskFinishRequest {
access: access(AGENT),
task_id: accepted.task_id,
expected_state: TaskState::Queued,
expected_version: queued.version,
target_state: TaskState::Completed,
result: Some(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
error: None,
};
assert_eq!(
store
.finish(skipped)
.await
.expect_err("transition rejected"),
TaskError::Invalid {
message: "task state transition is not allowed".to_owned()
}
);
let started = TaskFinishRequest {
access: access(AGENT),
task_id: accepted.task_id,
expected_state: TaskState::Queued,
expected_version: queued.version,
target_state: TaskState::Working,
result: None,
error: None,
};
assert_eq!(
store
.finish(started)
.await
.expect_err("working is not terminal"),
TaskError::Invalid {
message: "task finish target is not terminal".to_owned()
}
);
sqlx::query("update tasks set state = 'working' where task_id = $1")
.bind(accepted.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
let working = store.read(&access(AGENT), accepted.task_id).await.unwrap();
let mut finishers = Vec::new();
for marker in ["first", "second"] {
let store = store.clone();
let mut finish = TaskFinishRequest {
access: access(AGENT),
task_id: accepted.task_id,
expected_state: TaskState::Working,
expected_version: working.version,
target_state: TaskState::Completed,
result: Some(TaskEnvelope::try_redacted(&json!({"marker": marker})).unwrap()),
error: None,
};
finish.target_state = TaskState::Completed;
finishers.push(tokio::spawn(async move { store.finish(finish).await }));
}
let first = finishers.remove(0).await.unwrap();
let second = finishers.remove(0).await.unwrap();
let winners = [&first, &second]
.iter()
.filter(|result| result.is_ok())
.count();
assert_eq!(winners, 1, "exactly one concurrent CAS wins");
let loser = if first.is_err() { &first } else { &second };
assert_eq!(
loser.as_ref().err().unwrap(),
&TaskError::StateConflict,
"the loser observes a rejected transition, not a rewrite"
);
let terminal = store.read(&access(AGENT), accepted.task_id).await.unwrap();
assert_eq!(terminal.state, TaskState::Completed);
assert_eq!(terminal.version, working.version + 1);
let marker = terminal.result.as_ref().unwrap().value()["marker"]
.as_str()
.unwrap()
.to_owned();
assert!(marker == "first" || marker == "second");
// A repeated terminal write and a terminal->terminal move are rejected.
let repeated = TaskFinishRequest {
access: access(AGENT),
task_id: accepted.task_id,
expected_state: TaskState::Completed,
expected_version: terminal.version,
target_state: TaskState::Failed,
result: None,
error: Some(TaskEnvelope::try_redacted(&json!({"reason": "x"})).unwrap()),
};
assert!(repeated.validate().is_err());
// Terminal Task and its dispatch intent left together.
assert_eq!(row_counts(registry.pool()).await, (1, 0));
database.cleanup().await;
}
#[tokio::test]
async fn retention_is_bounded_and_never_deletes_live_work() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let queued = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.unwrap();
let expired_queued = store
.accept(request(&key("k2"), &digest("f2"), AGENT, 1))
.await
.unwrap();
sqlx::query(
"update tasks set execution_deadline = now() - interval '1 hour' where task_id = $1",
)
.bind(expired_queued.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
// A retained terminal Task whose retention has not expired yet and one that has.
let terminal = store
.accept(request(&key("k3"), &digest("f3"), AGENT, 30_000))
.await
.unwrap();
sqlx::query(
"update tasks set state = 'completed', result_envelope = '{\"ok\":true}'::jsonb,
retain_until = now() + interval '1 hour' where task_id = $1",
)
.bind(terminal.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
sqlx::query("delete from execution_admission_entries where task_id = $1")
.bind(terminal.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
let expired_terminal = store
.accept(request(&key("k4"), &digest("f4"), AGENT, 30_000))
.await
.unwrap();
sqlx::query(
"update tasks set state = 'cancelled', execution_deadline = now() - interval '2 hours',
retain_until = now() - interval '1 hour'
where task_id = $1",
)
.bind(expired_terminal.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
sqlx::query("delete from execution_admission_entries where task_id = $1")
.bind(expired_terminal.task_id.as_uuid())
.execute(registry.pool())
.await
.unwrap();
let report = store.purge_expired(64).await.unwrap();
assert_eq!(report.expired_queued, 1);
assert_eq!(report.expired_terminal, 1);
// Live queued work is never deleted or failed; the expired queued Task released its slot.
assert_eq!(
store
.read(&access(AGENT), queued.task_id)
.await
.unwrap()
.state,
TaskState::Queued
);
assert_eq!(
store
.read(&access(AGENT), terminal.task_id)
.await
.unwrap()
.state,
TaskState::Completed
);
assert!(matches!(
store
.read(&access(AGENT), expired_queued.task_id)
.await
.unwrap()
.state,
TaskState::Failed
));
assert!(
store
.read(&access(AGENT), expired_terminal.task_id)
.await
.is_err()
);
let remaining: i64 = sqlx::query("select count(*)::bigint as count from execution_admission_entries where task_id is not null")
.fetch_one(registry.pool())
.await
.unwrap()
.get("count");
assert_eq!(remaining, 1, "only the live queued Task keeps its intent");
database.cleanup().await;
}
#[tokio::test]
async fn foreign_scope_reads_are_not_found_and_never_leak_payload() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
let accepted = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.unwrap();
// Positive control: the owner reads its Task.
assert!(store.read(&access(AGENT), accepted.task_id).await.is_ok());
// Foreign owner, foreign authorization scope and foreign workspace are all not-found.
let mut foreign_owner = access(AGENT);
foreign_owner.owner_id = "agent_b".to_owned();
assert_eq!(
store
.read(&foreign_owner, accepted.task_id)
.await
.unwrap_err(),
TaskError::NotFound
);
let mut foreign_scope = access(AGENT);
foreign_scope.authorization_scope = "credential:pk_other".to_owned();
assert_eq!(
store
.read(&foreign_scope, accepted.task_id)
.await
.unwrap_err(),
TaskError::NotFound
);
let mut foreign_workspace = access(AGENT);
foreign_workspace.workspace_id = "ws_other".to_owned();
assert_eq!(
store
.read(&foreign_workspace, accepted.task_id)
.await
.unwrap_err(),
TaskError::NotFound
);
// The same caller key under a foreign owner creates its own Task, never a visible collision.
let other = store
.accept(request(&key("k1"), &digest("f1"), "agent_b", 30_000))
.await
.unwrap();
assert_ne!(other.task_id, accepted.task_id);
assert_eq!(row_counts(registry.pool()).await, (2, 2));
database.cleanup().await;
}
#[tokio::test]
async fn invalid_bounded_envelope_is_rejected_before_persistence() {
let database = common::TestDatabase::new().await;
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
let _migrated = database.registry().await;
let registry = database.concurrent_registry(4).await;
let store = store_with(registry.pool().clone(), 8);
assert!(
TaskEnvelope::try_redacted(&json!({"blob": "x".repeat(64 * 1024)})).is_err(),
"an oversized envelope is rejected before any accept"
);
let mut invalid = request(&key("k1"), &digest("f1"), AGENT, 30_000);
invalid.scoped_key = "short".to_owned();
assert!(matches!(invalid.validate(), Err(TaskError::Invalid { .. })));
assert_eq!(
store.accept(invalid).await.unwrap_err(),
TaskError::Invalid {
message: "task scoped key digest is invalid".to_owned()
}
);
assert_eq!(row_counts(registry.pool()).await, (0, 0));
database.cleanup().await;
}
#[tokio::test]
async fn task_worker_lease_and_fencing_contract() {
let database = common::TestDatabase::new().await;
let registry = database.registry().await;
let store = store_with(registry.pool().clone(), 8);
let created = store
.accept(request(&key("lease1"), &digest("f1"), AGENT, 30_000))
.await
.unwrap();
let leases = store.claim_batch("worker_1", 4, 10_000).await.unwrap();
assert_eq!(leases.len(), 1);
assert_eq!(leases[0].record.task_id, created.task_id);
assert_eq!(leases[0].record.state, TaskState::Working);
assert_eq!(leases[0].owner, "worker_1");
let lease = &leases[0];
let fenced_progress = store
.write_progress(
"worker_1",
lease.record.task_id,
lease.fence,
TaskEnvelope::try_redacted(&json!({"progress": 1})).unwrap(),
)
.await
.unwrap();
assert!(fenced_progress.progress.is_some());
// stale fence rejected
let bad = store
.renew_lease("worker_1", lease.record.task_id, lease.fence + 1, 10_000)
.await;
assert!(bad.is_err());
// checkpoint dispatch once
let checkpointed = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker_1".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-1".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await
.unwrap();
assert_eq!(checkpointed.attempt.attempt_id, "attempt-1");
assert_eq!(checkpointed.attempt.ordinal, 1);
assert!(checkpointed.task.dispatch_started_at_unix_ms.is_some());
assert_eq!(
checkpointed.task.current_attempt_id.as_deref(),
Some("attempt-1")
);
// second checkpoint rejected
let second = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker_1".to_owned(),
fence: lease.fence,
expected_version: checkpointed.task.version,
attempt_id: "attempt-2".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await;
assert!(second.is_err());
database.cleanup().await;
}
#[tokio::test]
async fn store_failure_fails_closed_without_records() {
let database = common::TestDatabase::new().await;
// No migration on this schema: the durable Task state does not exist yet.
let unmigrated = database.raw_pool().await;
let store = store_with(unmigrated, 8);
assert!(store.health().await.is_err());
let error = store
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
.await
.expect_err("acceptance fails closed");
assert!(matches!(error, TaskError::Unavailable { .. }));
database.cleanup().await;
}
/// Story 4.3 ATDD: the typed immutable Platform API key reference of an accepted Task is persisted,
/// read back through the lease, and only an active, unexpired, exactly bound key is authoritatively
/// revalidated. Revocation, expiry and a foreign workspace/agent binding all close; an administrator
/// Task stores no machine key identity at all, so a worker fails closed on it.
#[tokio::test]
async fn accepted_task_authority_reference_is_persisted_and_revalidated() {
let database = common::TestDatabase::new().await;
let registry = database.registry().await;
let store = store_with(registry.pool().clone(), 8);
let workspace = WorkspaceId::new(WORKSPACE);
let now = OffsetDateTime::now_utc();
// `ws_default` is seeded by the baseline migration; the keys only need that workspace row.
let agent = AgentId::new(AGENT);
let active_id = PlatformApiKeyId::new("pk_task_active");
for key in [
authority_key(
"pk_task_active",
&workspace,
AGENT,
PlatformApiKeyStatus::Active,
None,
),
authority_key(
"pk_task_revoked",
&workspace,
AGENT,
PlatformApiKeyStatus::Revoked,
None,
),
authority_key(
"pk_task_expired",
&workspace,
AGENT,
PlatformApiKeyStatus::Active,
Some(now - TimeDuration::hours(1)),
),
] {
let secret_hash = format!("secret-hash-{}", key.id.as_str());
registry
.create_platform_api_key(CreatePlatformApiKeyRequest {
secret_hash: &secret_hash,
api_key: &key,
})
.await
.unwrap();
}
// Acceptance persists only the immutable typed reference, never the bearer secret.
let mut accepted = request(&key("k_authority"), &digest("fa"), AGENT, 300_000);
accepted.platform_api_key_id = Some(active_id.clone());
let task_id = accepted.task_id;
store.accept(accepted).await.expect("acceptance commits");
let leases = store
.claim_batch("worker_authority", 8, 30_000)
.await
.expect("claim");
let lease = leases
.into_iter()
.find(|lease| lease.record.task_id == task_id)
.expect("accepted task is leased");
assert_eq!(lease.record.platform_api_key_id.as_ref(), Some(&active_id));
// Positive: the exact active key of this workspace/agent is revalidated authoritatively.
let revalidated = registry
.revalidate_platform_api_key(&workspace, &agent, &active_id)
.await
.expect("authoritative read")
.expect("active key is authoritative");
assert!(
revalidated
.api_key
.scopes
.contains(&PlatformApiKeyScope::Write)
);
// Negatives: revocation, expiry and a foreign workspace/agent binding all fail closed.
let foreign_agent = AgentId::new("agent_b");
let foreign_workspace = WorkspaceId::new("ws_elsewhere");
for (other_workspace, other_agent, other_key) in [
(&workspace, &agent, PlatformApiKeyId::new("pk_task_revoked")),
(&workspace, &agent, PlatformApiKeyId::new("pk_task_expired")),
(&workspace, &foreign_agent, active_id.clone()),
(&foreign_workspace, &agent, active_id.clone()),
] {
let found = registry
.revalidate_platform_api_key(other_workspace, other_agent, &other_key)
.await
.unwrap();
assert!(
found.is_none(),
"authority must fail closed for {}",
other_key.as_str()
);
}
// An administrator Task carries no machine key identity: the worker has nothing to revalidate.
let mut admin_request = request(&key("k_admin"), &digest("fb"), AGENT, 300_000);
admin_request.owner_kind = TaskOwnerKind::Admin;
admin_request.owner_id = "user_admin".to_owned();
admin_request.authorization_scope = "admin:user_admin".to_owned();
admin_request.platform_api_key_id = None;
let admin_task = admin_request.task_id;
store
.accept(admin_request)
.await
.expect("administrator acceptance commits");
let admin_record = store
.read(
&TaskAccess {
workspace_id: WORKSPACE.to_owned(),
owner_kind: TaskOwnerKind::Admin,
owner_id: "user_admin".to_owned(),
authorization_scope: "admin:user_admin".to_owned(),
},
admin_task,
)
.await
.expect("owner read");
assert_eq!(admin_record.platform_api_key_id, None);
database.cleanup().await;
}
fn authority_key(
id: &str,
workspace_id: &WorkspaceId,
agent: &str,
status: PlatformApiKeyStatus,
expires_at: Option<OffsetDateTime>,
) -> PlatformApiKey {
PlatformApiKey {
id: PlatformApiKeyId::new(id),
workspace_id: workspace_id.clone(),
agent_id: Some(AgentId::new(agent)),
key_kind: PlatformApiKeyKind::McpClient,
name: id.to_owned(),
prefix: "crk_live".to_owned(),
scopes: vec![PlatformApiKeyScope::Write],
status,
created_at: OffsetDateTime::now_utc(),
last_used_at: None,
expires_at,
allowed_origins: Vec::new(),
}
}
mod task_attempts;
mod task_worker;