Files
crank/crates/crank-registry/tests/integration/agent_resource_bindings/archive_race.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

346 lines
13 KiB
Rust

//! 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<sqlx::postgres::PgRow>) -> Vec<AgentResourceBinding> {
rows.iter()
.map(|row| AgentResourceBinding {
resource_id: ResourceId::new(
row.try_get::<String, _>("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::postgres::PgRow> = 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;
}