//! 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, ApprovalEvidence, ExecutionAdmission, NoTasksFallback, RequestId, TaskAcceptRequest, TaskAccess, TaskEnvelope, TaskError, TaskFinishRequest, TaskId, TaskOwnerKind, TaskPins, TaskState, TaskStore, TaskSupportIds, ToolExecutionMode, TraceContext, current_unix_ms, }; use crank_registry::{AdmissionLimits, PostgresExecutionAdmission, PostgresTaskStore}; use serde_json::json; use sqlx::{PgPool, Row}; 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}"), 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()), }, 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(), } } 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 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; }