//! Story 3.8 / AC04 regression: archive and a *new* Resource binding are serialized by the //! database, not decided by an unlocked check-then-write. //! //! The binding write must lock every candidate `resources` row before it inspects the lifecycle //! status, so: //! - an archive that already committed wins and the binding is refused (no partial writes); //! - a binding that already holds the rows commits first and the archive legally follows it. //! //! Both orders are orchestrated by real lock state (`pg_locks`, test container is per test binary //! and `--test-threads=1` keeps it exclusive), never by sleep timing, and both use the real //! registry calls (`save_agent_catalog_config` / `archive_resource`). use std::time::Duration; use crank_core::WorkspaceId; use crank_registry::model::resource::ArchiveResourceRequest; use crank_registry::{AgentResourceBinding, RegistryError, SaveAgentCatalogConfigRequest}; use sqlx::Row; use super::*; /// Advisory-lock key of the test-only insert gate below (test schema only, released with the txn). const BINDING_GATE_KEY: i64 = 3810; /// Bounded wait for a *waiting* lock of `locktype`: the orchestration follows observable PostgreSQL /// lock state instead of guessing with sleeps. Returns whether the wait was observed within the /// deadline, so a caller can turn a missing wait into a meaningful assertion failure. async fn await_lock_wait(pool: &sqlx::PgPool, locktype: &str) -> bool { let deadline = tokio::time::Instant::now() + Duration::from_secs(10); loop { let waiting: i64 = sqlx::query_scalar("select count(*) from pg_locks where locktype = $1 and not granted") .bind(locktype) .fetch_one(pool) .await .expect("pg_locks must be observable in the test database"); if waiting > 0 { return true; } if tokio::time::Instant::now() >= deadline { return false; } tokio::time::sleep(Duration::from_millis(10)).await; } } fn requested_binding(resource: &ResourceId) -> AgentResourceBinding { AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, } } fn stored_binding_rows(rows: Vec) -> Vec { rows.iter() .map(|row| AgentResourceBinding { resource_id: ResourceId::new( row.try_get::("resource_id") .expect("binding resource id must decode"), ), resource_version: 1, }) .collect() } /// Archive wins the race: it holds the Resource row lock (exactly like `archive_resource`) while the /// binding attempt starts, so the binding must observe `archived` and refuse without writing. #[tokio::test] async fn story38_archive_first_refuses_a_new_binding_without_partial_writes() { let sandbox = sandbox("archive_race_archive_first").await; let resource = published_resource( &sandbox, "ws_default", "res_race_archive_first", "crank://race/archive-first", b"archive first v1", ) .await; let agent = create_draft_agent( &sandbox, "ws_default", "agent_race_archive_first", "race-af", ) .await; let before = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("agent summary must be readable") .expect("agent summary must exist"); // The archiver locks and archives the row in one transaction, then commits only after the // binding attempt is observably waiting for that transaction. let concurrent = sandbox.database.concurrent_registry(8).await; let orchestration = concurrent.pool(); let mut archiver = orchestration .begin() .await .expect("archiver transaction must start"); let status: String = sqlx::query_scalar( "select status from resources where workspace_id = $1 and resource_id = $2 for update", ) .bind("ws_default") .bind(resource.as_str()) .fetch_one(&mut *archiver) .await .expect("the archive candidate must be lockable"); assert_eq!(status, "published"); sqlx::query( "update resources set status = 'archived', updated_at = now() where workspace_id = $1 and resource_id = $2", ) .bind("ws_default") .bind(resource.as_str()) .execute(&mut *archiver) .await .expect("the locked Resource row must accept the archive transition"); let writer = concurrent.clone(); let writer_binding = requested_binding(&resource); let writer_agent = agent.clone(); let binding = tokio::spawn(async move { writer .save_agent_catalog_config(SaveAgentCatalogConfigRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &writer_agent, agent_version: 1, bindings: &[], tool_selection_policy: &Default::default(), resource_bindings: std::slice::from_ref(&writer_binding), expected_state: None, }) .await }); // The binding write must wait for the archiver's transaction: it cannot pass the lifecycle // check before that transaction ends. let waited = await_lock_wait(orchestration, "transactionid").await; archiver .commit() .await .expect("the archive must commit after the binding is waiting"); let outcome = binding.await.expect("the binding task must finish"); assert!( waited, "the binding write must wait for the in-flight archive instead of racing it: {outcome:?}" ); assert!( matches!( outcome, Err(RegistryError::ResourceArchived { ref resource_id }) if resource_id == resource.as_str() ), "a binding that loses against a committed archive must be refused: {outcome:?}" ); assert_eq!( binding_rows(&sandbox, agent.as_str()).await, 0, "a refused binding must not leave partial rows" ); let after = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("agent summary must be readable") .expect("agent summary must exist"); assert_eq!( after.updated_at, before.updated_at, "a refused binding must not move the Agent updated_at" ); assert_eq!( after.catalog_revision, before.catalog_revision, "a refused binding must not bump catalog_revision" ); let archived: String = sqlx::query_scalar( "select status from resources where workspace_id = $1 and resource_id = $2", ) .bind("ws_default") .bind(resource.as_str()) .fetch_one(&sandbox.pool) .await .expect("the archived Resource must be readable"); assert_eq!(archived, "archived"); sandbox.cleanup().await; } /// Binding wins the race: the binding transaction holds the Resource row locks and is held inside /// its insert by a test-only gate, an archive that starts meanwhile must wait, and after the /// binding commits the archive legally follows it (both rows, no deadlock, no rolled-back archive). #[tokio::test] async fn story38_binding_first_serializes_before_a_later_archive() { let sandbox = sandbox("archive_race_binding_first").await; let resource = published_resource( &sandbox, "ws_default", "res_race_binding_first", "crank://race/binding-first", b"binding first v1", ) .await; let agent = create_draft_agent( &sandbox, "ws_default", "agent_race_binding_first", "race-bf", ) .await; // Test-only gate: the insert already runs after the Resource rows are locked, so holding this // advisory lock deterministically places the archive behind those row locks. sqlx::raw_sql( "create function crank_test_gate_binding_write() returns trigger language plpgsql as $$ begin perform pg_advisory_xact_lock(3810); return new; end; $$; create trigger crank_test_gate_binding_write_gate before insert on agent_resource_bindings for each row execute function crank_test_gate_binding_write();", ) .execute(&sandbox.pool) .await .expect("the test-only binding gate trigger must install"); let concurrent = sandbox.database.concurrent_registry(8).await; let orchestration = concurrent.pool(); let mut gate = orchestration .acquire() .await .expect("the gate connection must be acquired"); sqlx::query("select pg_advisory_lock($1)") .bind(BINDING_GATE_KEY) .execute(&mut *gate) .await .expect("the gate advisory lock must be taken"); let writer = concurrent.clone(); let writer_binding = requested_binding(&resource); let writer_agent = agent.clone(); let binding = tokio::spawn(async move { writer .save_agent_catalog_config(SaveAgentCatalogConfigRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &writer_agent, agent_version: 1, bindings: &[], tool_selection_policy: &Default::default(), resource_bindings: std::slice::from_ref(&writer_binding), expected_state: None, }) .await }); // The binding transaction is now past the Resource row locks and parked on the gate. assert!( await_lock_wait(orchestration, "advisory").await, "the binding transaction must reach its insert (and therefore already hold the Resource row locks)" ); let current = sandbox .registry .get_resource_draft("ws_default", &resource) .await .expect("the Resource draft must be readable before archive"); let archiver_registry = sandbox.registry.clone(); let archiver_resource = resource.clone(); let expected_updated_at = current.resource.updated_at; let archiver = tokio::spawn(async move { archiver_registry .archive_resource(ArchiveResourceRequest { workspace_id: WorkspaceId::new("ws_default"), resource_id: archiver_resource, expected_updated_at, archived_at: OffsetDateTime::now_utc(), }) .await }); // The archive cannot overtake the binding: it waits for the binding transaction. assert!( await_lock_wait(orchestration, "transactionid").await, "the archive must wait for the binding transaction that holds the Resource row locks" ); sqlx::query("select pg_advisory_unlock($1)") .bind(BINDING_GATE_KEY) .execute(&mut *gate) .await .expect("the gate advisory lock must be releasable"); drop(gate); binding .await .expect("the binding task must finish") .expect("a binding that commits before the archive must be accepted"); archiver .await .expect("the archive task must finish") .expect("the archive must follow the committed binding"); let rows: Vec = sqlx::query( "select resource_id from agent_resource_bindings where agent_id = $1 and agent_version = 1", ) .bind(agent.as_str()) .fetch_all(&sandbox.pool) .await .expect("binding rows must be queryable"); assert_eq!( stored_binding_rows(rows), vec![requested_binding(&resource)], "the binding that won the race must stay written" ); let archived: String = sqlx::query_scalar( "select status from resources where workspace_id = $1 and resource_id = $2", ) .bind("ws_default") .bind(resource.as_str()) .fetch_one(&sandbox.pool) .await .expect("the archived Resource must be readable"); assert_eq!( archived, "archived", "the archive must complete once the binding transaction ended" ); // The immutable published snapshot is untouched by the archive. let snapshot = sandbox .registry .resolve_resource_publication("ws_default", &resource, 1) .await .expect("the exact published version must stay readable after archive"); let published = registered(&sandbox, b"binding first v1"); assert_eq!( snapshot.publication.digest.as_str(), published.artifact_ref().digest_hex(), "archive must not rewrite the published digest" ); sandbox.cleanup().await; }