[skip ci] wip: preserve Hermes crank development checkpoint

Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,345 @@
//! 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;
}
@@ -0,0 +1,572 @@
//! Story 3.8 / AT-3.8-04: real concurrency between the live read guard and the revoke
//! transition (owner decision A).
//!
//! Every scenario drives the *production* registry operations on separate multi-connection
//! registries over one test schema. The orchestration is a PostgreSQL barrier: each backend
//! carries its own `application_name`, `pg_blocking_pids` names the actual blocker, and a
//! test-only advisory-lock trigger parks the revoke transaction after it took its row lock.
//! Nothing here waits on timing alone, and no helper stubs the product.
//!
//! - revoke-first: a read that starts after the revoke took its lock waits, then is denied
//! (`Revoked`) without ever receiving a publication, so no artifact byte can be opened;
//! - read-first: the revoke waits for the in-flight guard and only then commits, so a read
//! linearized before the revoke may still finish;
//! - two first revokes on different connections produce exactly one audit event and keep the
//! first actor/correlation;
//! - dropping a guard releases the lock, and cancelling a waiting revoke leaves no tombstone.
use std::str::FromStr;
use std::time::Duration;
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::ResourceError;
use crank_registry::model::resource::RevokeResourceRequest;
use crank_registry::{PostgresPoolConfig, PostgresRegistry};
use sqlx::postgres::PgConnectOptions;
use sqlx::{PgPool, Row};
use time::OffsetDateTime;
use super::*;
/// Advisory gate key used by the test-only tombstone-insert trigger (test schema only).
pub(super) const REVOCATION_GATE_KEY: i64 = 3821;
/// A registry whose backends are identifiable in `pg_stat_activity` by `application_name`.
pub(super) async fn attributed_registry(
sandbox: &Sandbox,
application_name: &str,
) -> PostgresRegistry {
let base_url = crank_test_support::postgres_database_url().await;
let schema: String = sqlx::query_scalar("select current_schema()")
.fetch_one(&sandbox.pool)
.await
.expect("the test schema must be resolvable");
let url = format!(
"{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3D{application_name}"
);
let options = PgConnectOptions::from_str(&url).expect("attributed connect options must parse");
PostgresRegistry::connect_with_options_and_pool_config(
options,
PostgresPoolConfig {
max_connections: 6,
min_connections: 0,
acquire_timeout_ms: 10_000,
idle_timeout_ms: 600_000,
max_lifetime_ms: 1_800_000,
},
)
.await
.expect("the attributed test registry must connect")
}
/// Install a test-only gate: a BEFORE trigger on `table` parks the writing transaction on an
/// advisory lock, so the operation observably holds every lock it already took while the test
/// starts the competitor. The trigger lives only in this test's private schema.
pub(super) async fn install_advisory_gate(
sandbox: &Sandbox,
function: &str,
table: &str,
key: i64,
) {
let sql = format!(
"create function {function}() returns trigger language plpgsql as $$
begin
perform pg_advisory_xact_lock({key});
return new;
end $$;
create trigger {function}_gate
before insert or update on {table}
for each row execute function {function}();"
);
sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
.execute(&sandbox.pool)
.await
.expect("the test-only advisory gate trigger must install");
}
/// Install the gate inside the audited tombstone insert.
pub(super) async fn install_revocation_gate(sandbox: &Sandbox) {
install_advisory_gate(
sandbox,
"crank_test_gate_revocation_insert",
"resource_security_revocations",
REVOCATION_GATE_KEY,
)
.await;
}
/// Take the session-level advisory lock a gate function waits for.
pub(super) async fn take_gate(sandbox: &Sandbox, key: i64) -> PgPool {
let base_url = crank_test_support::postgres_database_url().await;
let schema: String = sqlx::query_scalar("select current_schema()")
.fetch_one(&sandbox.pool)
.await
.expect("the test schema must be resolvable");
let url =
format!("{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-gate");
let pool = PgPool::connect(&url)
.await
.expect("the gate pool must connect to the test schema");
sqlx::query("select pg_advisory_lock($1)")
.bind(key)
.execute(&pool)
.await
.expect("the gate advisory lock must be taken");
pool
}
pub(super) async fn release_gate(gate: PgPool, key: i64) {
sqlx::query("select pg_advisory_unlock($1)")
.bind(key)
.execute(&gate)
.await
.expect("the gate advisory lock must be releasable");
drop(gate);
}
/// Precise barrier: `waiter` is blocked by a backend whose `application_name` is `blocker`.
/// Returns false after the deadline so the caller turns a missing wait into a real assertion.
pub(super) async fn await_blocked_by(pool: &PgPool, waiter: &str, blocker: &str) -> bool {
let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
loop {
let waiters: Vec<i32> = sqlx::query_scalar(
"select pid from pg_stat_activity
where datname = current_database() and application_name = $1",
)
.bind(waiter)
.fetch_all(pool)
.await
.expect("pg_stat_activity must be observable");
for pid in waiters {
let blockers: Vec<i32> = sqlx::query_scalar("select unnest(pg_blocking_pids($1))")
.bind(pid)
.fetch_all(pool)
.await
.expect("pg_blocking_pids must be observable");
if blockers.is_empty() {
continue;
}
let names: Vec<String> = sqlx::query_scalar(
"select application_name from pg_stat_activity where pid = any($1)",
)
.bind(&blockers)
.fetch_all(pool)
.await
.expect("blocking backends must be observable");
if names.iter().any(|name| name == blocker) {
return true;
}
}
if tokio::time::Instant::now() >= deadline {
return false;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
pub(super) fn revoke_request(resource: &ResourceId, request_id: &str) -> RevokeResourceRequest {
RevokeResourceRequest {
workspace_id: WorkspaceId::new("ws_default"),
resource_id: resource.clone(),
actor_user_id: "user_default_owner".to_owned(),
request_id: request_id.to_owned(),
trace_id: format!("{request_id}-trace"),
revoked_at: OffsetDateTime::now_utc(),
}
}
/// Draft → Published v1 with a caller-chosen unique name (the fixture name is unique per
/// workspace, so a second Resource in the same schema needs its own).
async fn published_named_resource(
sandbox: &Sandbox,
workspace: &str,
resource_id: &str,
uri: &str,
name: &str,
bytes: &[u8],
) -> ResourceId {
let resource = ResourceId::new(resource_id);
sandbox
.registry
.create_resource_draft(
crank_registry::model::resource::CreateResourceDraftRequest {
workspace_id: WorkspaceId::new(workspace),
resource_id: resource.clone(),
uri: uri.to_owned(),
name: name.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
artifact: registered(sandbox, bytes),
created_at: OffsetDateTime::now_utc(),
},
)
.await
.expect("the named resource draft must be created");
publish_current_resource(sandbox, workspace, &resource, bytes).await;
resource
}
pub(super) async fn tombstone_rows(pool: &PgPool) -> i64 {
sqlx::query_scalar("select count(*) from resource_security_revocations")
.fetch_one(pool)
.await
.expect("tombstones must be queryable")
}
/// Revoke wins: the read that starts behind the revoke lock is denied before any publication
/// (and therefore before any artifact read), while the revoke itself is a normal 204 path.
#[tokio::test]
async fn story38_revoke_first_denies_a_waiting_read_without_a_publication() {
let sandbox = sandbox("revocation_race_revoke_first").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_race_revoke_first",
"crank://race/revoke-first",
b"revoke first v1",
)
.await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(
&revoke_resource,
"story38-race-revoke-first",
))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
"the revoke transaction must reach its tombstone insert and hold the Resource row lock"
);
// This read starts after the revoke took `resources FOR UPDATE`: it cannot pass the guard.
let reader = attributed_registry(&sandbox, "story38-reader").await;
let read_resource = resource.clone();
let read = tokio::spawn(async move {
reader
.begin_authorized_resource_read("ws_default", &read_resource, 1)
.await
.map(|guard| guard.publication().publication.uri.clone())
});
assert!(
await_blocked_by(&sandbox.pool, "story38-reader", "story38-revoker").await,
"the read must wait for the in-flight revoke instead of racing it"
);
assert!(
!read.is_finished(),
"a read behind the revoke must not complete while the revoke holds the row"
);
release_gate(gate, REVOCATION_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("revoke must finish once the gate is released")
.expect("revoke task must not panic")
.expect("revoke must commit");
let outcome = tokio::time::timeout(Duration::from_secs(15), read)
.await
.expect("the waiting read must finish after the revoke commits")
.expect("read task must not panic");
assert!(
matches!(outcome, Err(ResourceError::Revoked)),
"revoke-first must deny the read with the typed Revoked outcome, got {outcome:?}"
);
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
sandbox.cleanup().await;
}
/// Read wins: the revoke waits for the in-flight guard and commits afterwards; the read is
/// linearized before the revoke and only post-revoke reads see `Revoked`.
#[tokio::test]
async fn story38_read_first_serializes_a_revoke_after_the_in_flight_guard() {
let sandbox = sandbox("revocation_race_read_first").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_race_read_first",
"crank://race/read-first",
b"read first v1",
)
.await;
let reader = attributed_registry(&sandbox, "story38-reader").await;
let guard = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.expect("an unrevoked Resource must open the live guard");
assert_eq!(
guard.publication().publication.uri,
"crank://race/read-first"
);
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-race-read-first"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-reader").await,
"revoke must wait for the in-flight read guard, not bypass its shared lock"
);
assert!(
!revoke.is_finished(),
"revoke must not commit while the read guard still holds the row"
);
guard.commit().await.expect("the read must commit");
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("revoke must finish once the guard is released")
.expect("revoke task must not panic")
.expect("revoke must commit after the read");
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
let after = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.map(|_| ());
assert!(
matches!(after, Err(ResourceError::Revoked)),
"a read that starts after the committed revoke must be denied: {after:?}"
);
sandbox.cleanup().await;
}
/// Two first revokes on different connections: both succeed, exactly one event is written and
/// the first actor/correlation/time survive the second command.
#[tokio::test]
async fn story38_two_first_revokes_on_different_connections_write_one_event() {
let sandbox = sandbox("revocation_race_first_event").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_race_first_event",
"crank://race/first-event",
b"first event v1",
)
.await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let first = attributed_registry(&sandbox, "story38-revoker-a").await;
let first_resource = resource.clone();
let first_revoke = tokio::spawn(async move {
first
.revoke_resource(revoke_request(&first_resource, "story38-first-a"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker-a", "story38-gate").await,
"the first revoke must hold its row lock inside the audited insert"
);
let second = attributed_registry(&sandbox, "story38-revoker-b").await;
let second_resource = resource.clone();
let second_revoke = tokio::spawn(async move {
second
.revoke_resource(revoke_request(&second_resource, "story38-first-b"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker-b", "story38-revoker-a").await,
"the second first-revoke must wait for the row lock of the first"
);
release_gate(gate, REVOCATION_GATE_KEY).await;
for (name, handle) in [("a", first_revoke), ("b", second_revoke)] {
tokio::time::timeout(Duration::from_secs(15), handle)
.await
.unwrap_or_else(|_| panic!("revoke {name} must finish"))
.unwrap_or_else(|_| panic!("revoke {name} task must not panic"))
.unwrap_or_else(|error| panic!("revoke {name} must succeed: {error:?}"));
}
assert_eq!(tombstone_rows(&sandbox.pool).await, 1, "one audit event");
let row = sqlx::query(
"select actor_user_id, request_id, trace_id, revoked_at
from resource_security_revocations",
)
.fetch_one(&sandbox.pool)
.await
.expect("the single tombstone must be readable");
assert_eq!(
row.try_get::<String, _>("request_id").unwrap(),
"story38-first-a",
"the first correlation must be preserved"
);
assert_eq!(
row.try_get::<String, _>("actor_user_id").unwrap(),
"user_default_owner"
);
assert_eq!(
row.try_get::<String, _>("trace_id").unwrap(),
"story38-first-a-trace"
);
sandbox.cleanup().await;
}
/// A guard dropped without commit releases the row lock; a cancelled waiting revoke leaves no
/// audit event and no stuck lock.
#[tokio::test]
async fn story38_dropped_guard_and_cancelled_revoke_leave_no_stuck_lock() {
let sandbox = sandbox("revocation_race_cancel").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_race_cancel",
"crank://race/cancel",
b"cancel v1",
)
.await;
let reader = attributed_registry(&sandbox, "story38-reader").await;
let guard = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.expect("the guard must open before the revoke");
drop(guard);
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
tokio::time::timeout(
Duration::from_secs(15),
revoker.revoke_resource(revoke_request(&revoke_resource, "story38-after-drop")),
)
.await
.expect("a revoke after a dropped guard must not hang")
.expect("the revoke must succeed once the guard is dropped");
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
// Second Resource: a revoke cancelled while waiting must not write anything.
let other = published_named_resource(
&sandbox,
"ws_default",
"res_race_cancel_two",
"crank://race/cancel-two",
"cancel_two_doc",
b"cancel v2",
)
.await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let cancelled = attributed_registry(&sandbox, "story38-revoker-cancelled").await;
let cancelled_resource = other.clone();
let waiting = tokio::spawn(async move {
cancelled
.revoke_resource(revoke_request(&cancelled_resource, "story38-cancelled"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker-cancelled", "story38-gate").await,
"the cancelled revoke must be waiting inside its insert"
);
waiting.abort();
let _ = waiting.await;
release_gate(gate, REVOCATION_GATE_KEY).await;
tokio::time::timeout(
Duration::from_secs(15),
revoker.revoke_resource(revoke_request(&other, "story38-retry-after-cancel")),
)
.await
.expect("the retry must not hang behind the cancelled command")
.expect("the retry must succeed");
let rows: i64 = sqlx::query_scalar(
"select count(*) from resource_security_revocations where resource_id = $1",
)
.bind(other.as_str())
.fetch_one(&sandbox.pool)
.await
.expect("tombstones must be queryable");
assert_eq!(rows, 1, "a cancelled revoke must leave no event behind");
sandbox.cleanup().await;
}
/// A COMMIT that PostgreSQL itself refuses is a safe unavailable outcome: the read returns no
/// prepared content, no tombstone is written, and a fresh read still works.
#[tokio::test]
async fn story38_read_guard_commit_failure_is_a_safe_unavailable() {
let sandbox = sandbox("revocation_race_guard_commit").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_race_guard_commit",
"crank://race/guard-commit",
b"guard commit v1",
)
.await;
let base_url = crank_test_support::postgres_database_url().await;
let schema: String = sqlx::query_scalar("select current_schema()")
.fetch_one(&sandbox.pool)
.await
.expect("the test schema must be resolvable");
let url = format!(
"{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-guard-commit"
);
let options = PgConnectOptions::from_str(&url).expect("guard connect options must parse");
let registry = PostgresRegistry::connect_with_options_and_pool_config(
options,
PostgresPoolConfig {
max_connections: 1,
min_connections: 0,
acquire_timeout_ms: 10_000,
idle_timeout_ms: 600_000,
max_lifetime_ms: 1_800_000,
},
)
.await
.expect("the single-connection guard registry must connect");
let guard = registry
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.expect("the guard must open on an unrevoked Resource");
let pids: Vec<i32> = sqlx::query_scalar(
"select pid from pg_stat_activity
where datname = current_database() and application_name = 'story38-guard-commit'",
)
.fetch_all(&sandbox.pool)
.await
.expect("the guard backend must be observable");
assert_eq!(pids.len(), 1, "exactly one guard backend must exist");
let terminated: bool = sqlx::query_scalar("select pg_terminate_backend($1)")
.bind(pids[0])
.fetch_one(&sandbox.pool)
.await
.expect("the guard backend must be terminable");
assert!(terminated);
let outcome = guard.commit().await;
assert!(
matches!(outcome, Err(ResourceError::StorageUnavailable)),
"a refused COMMIT must be a safe unavailable outcome, got {outcome:?}"
);
assert_eq!(
tombstone_rows(&sandbox.pool).await,
0,
"a failed read commit must not be recorded as a revoke"
);
// Positive control on a fresh registry: nothing was revoked by the failed commit.
let reader = attributed_registry(&sandbox, "story38-reader").await;
let fresh = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.map(|_| ());
assert!(
fresh.is_ok(),
"an unrevoked Resource must still open a guard after the failed commit: {fresh:?}"
);
sandbox.cleanup().await;
}
@@ -0,0 +1,538 @@
//! Story 3.8 / AT-3.8-04: real mutation races against the revoke transition (owner decision A).
//!
//! The binding save, the Agent publication and the Resource publication each run on their own
//! multi-connection registry over one schema, against a real revoke on a different connection.
//! A test-only advisory gate parks one side after it took its production locks; the barrier names
//! the actual blocker (`pg_blocking_pids`) instead of guessing with sleeps.
//!
//! Every scenario asserts the final rows: no partial binding, no publication or catalog revision
//! after a refused mutation, and a successful mutation that legally precedes the revoke is kept.
use std::time::Duration;
use crank_core::WorkspaceId;
use crank_core::ids::ResourceId;
use crank_core::resource::ResourceError;
use crank_registry::model::resource::PublishResourceVersionRequest;
use crank_registry::{
AgentResourceBinding, PublishAgentRequest, RegistryError, SaveAgentCatalogConfigRequest,
};
use sqlx::Row;
use time::OffsetDateTime;
use super::revocation_race::{
REVOCATION_GATE_KEY, attributed_registry, await_blocked_by, install_advisory_gate,
install_revocation_gate, release_gate, revoke_request, take_gate, tombstone_rows,
};
use super::*;
const BINDING_GATE_KEY: i64 = 3822;
const AGENT_GATE_KEY: i64 = 3823;
const PUBLICATION_GATE_KEY: i64 = 3824;
fn binding(resource: &ResourceId) -> AgentResourceBinding {
AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 1,
}
}
async fn save_bindings(
registry: &crank_registry::PostgresRegistry,
workspace: &str,
agent: &crank_core::AgentId,
resource: &ResourceId,
) -> Result<(), RegistryError> {
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new(workspace),
agent_id: agent,
agent_version: 1,
bindings: &[],
tool_selection_policy: &Default::default(),
resource_bindings: &[binding(resource)],
expected_state: None,
})
.await
}
async fn publish_request(
sandbox: &Sandbox,
workspace: &str,
resource: &ResourceId,
bytes: &[u8],
) -> PublishResourceVersionRequest {
let current = sandbox
.registry
.get_resource_draft(workspace, resource)
.await
.expect("the draft must be readable before publishing");
PublishResourceVersionRequest {
workspace_id: WorkspaceId::new(workspace),
resource_id: resource.clone(),
expected_updated_at: current.resource.updated_at,
expected_version: current.version.version,
expected_digest: current.version.digest.clone(),
expected_size_bytes: current.version.size_bytes,
artifact: registered(sandbox, bytes),
published_at: OffsetDateTime::now_utc(),
}
}
async fn publication_rows(pool: &sqlx::PgPool, resource: &ResourceId) -> i64 {
sqlx::query_scalar("select count(*) from resource_publications where resource_id = $1")
.bind(resource.as_str())
.fetch_one(pool)
.await
.expect("publications must be queryable")
}
async fn catalog_revision(pool: &sqlx::PgPool, agent: &crank_core::AgentId) -> i64 {
sqlx::query_scalar("select catalog_revision from agents where id = $1")
.bind(agent.as_str())
.fetch_one(pool)
.await
.expect("the Agent must be readable")
}
async fn published_versions(pool: &sqlx::PgPool, agent: &crank_core::AgentId) -> i64 {
sqlx::query_scalar("select count(*) from published_agents where agent_id = $1")
.bind(agent.as_str())
.fetch_one(pool)
.await
.expect("published Agents must be queryable")
}
/// Revoke-first refuses a binding that starts behind the revoke lock: no rows, no revision bump.
#[tokio::test]
async fn story38_revoke_first_refuses_a_waiting_binding_without_partial_writes() {
let sandbox = sandbox("revocation_write_revoke_bind").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_revoke_bind",
"crank://race/revoke-bind",
b"revoke bind v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_revoke_bind", "rb").await;
let revision_before = catalog_revision(&sandbox.pool, &agent).await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-bind"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
"the revoke must hold the Resource row before the binding starts"
);
let binder = attributed_registry(&sandbox, "story38-binder").await;
let bind_agent = agent.clone();
let bind_resource = resource.clone();
let binding_write = tokio::spawn(async move {
save_bindings(&binder, "ws_default", &bind_agent, &bind_resource).await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-binder", "story38-revoker").await,
"the binding write must wait for the in-flight revoke"
);
release_gate(gate, REVOCATION_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must commit");
let outcome = tokio::time::timeout(Duration::from_secs(15), binding_write)
.await
.expect("the binding must finish")
.expect("the binding must not panic");
assert!(
matches!(outcome, Err(RegistryError::ResourceRevoked { .. })),
"a binding behind a committed revoke must be refused: {outcome:?}"
);
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 0);
assert_eq!(
catalog_revision(&sandbox.pool, &agent).await,
revision_before,
"a refused binding must not move catalog_revision"
);
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
sandbox.cleanup().await;
}
/// Binding-first commits legally; the later revoke still wins for every live read.
#[tokio::test]
async fn story38_binding_first_serializes_before_a_later_revoke() {
let sandbox = sandbox("revocation_write_bind_first").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_bind_first",
"crank://race/bind-first",
b"bind first v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_bind_first", "bf").await;
install_advisory_gate(
&sandbox,
"crank_test_gate_binding_insert",
"agent_resource_bindings",
BINDING_GATE_KEY,
)
.await;
let gate = take_gate(&sandbox, BINDING_GATE_KEY).await;
let binder = attributed_registry(&sandbox, "story38-binder").await;
let bind_agent = agent.clone();
let bind_resource = resource.clone();
let binding_write = tokio::spawn(async move {
save_bindings(&binder, "ws_default", &bind_agent, &bind_resource).await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-binder", "story38-gate").await,
"the binding transaction must park after taking its Resource locks"
);
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-bind-first"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-binder").await,
"the revoke must wait for the binding transaction that holds the Resource row"
);
release_gate(gate, BINDING_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), binding_write)
.await
.expect("the binding must finish")
.expect("the binding must not panic")
.expect("a binding that commits before the revoke must be accepted");
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must follow the committed binding");
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
let reader = attributed_registry(&sandbox, "story38-reader").await;
let denied = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.map(|_| ());
assert!(
matches!(denied, Err(ResourceError::Revoked)),
"after the revoke the existing binding must not grant live reads: {denied:?}"
);
sandbox.cleanup().await;
}
/// Revoke-first refuses an Agent publication whose bindings are already revoked.
#[tokio::test]
async fn story38_revoke_first_refuses_a_waiting_agent_publish() {
let sandbox = sandbox("revocation_write_revoke_agent").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_revoke_agent",
"crank://race/revoke-agent",
b"revoke agent v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_revoke_agent", "ra").await;
save_bindings(&sandbox.registry, "ws_default", &agent, &resource)
.await
.expect("the draft binding must save before the revoke");
let revision_before = catalog_revision(&sandbox.pool, &agent).await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-agent"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
"the revoke must hold the Resource row before the Agent publish starts"
);
let publisher = attributed_registry(&sandbox, "story38-agent-publish").await;
let publish_agent = agent.clone();
let published_at = OffsetDateTime::now_utc();
let publish = tokio::spawn(async move {
publisher
.publish_agent(PublishAgentRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &publish_agent,
version: 1,
published_at: &published_at,
published_by: None,
expected_state: None,
})
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-agent-publish", "story38-revoker").await,
"the Agent publication must wait for the in-flight revoke"
);
release_gate(gate, REVOCATION_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must commit");
let outcome = tokio::time::timeout(Duration::from_secs(15), publish)
.await
.expect("the Agent publish must finish")
.expect("the Agent publish must not panic");
assert!(
matches!(outcome, Err(RegistryError::ResourceRevoked { .. })),
"publishing an Agent bound to a revoked Resource must be refused: {outcome:?}"
);
assert_eq!(published_versions(&sandbox.pool, &agent).await, 0);
assert_eq!(
catalog_revision(&sandbox.pool, &agent).await,
revision_before,
"a refused Agent publication must not bump catalog_revision"
);
sandbox.cleanup().await;
}
/// Agent publish first: it holds the shared Resource lock, the revoke waits and follows; every
/// read after the revoke is denied, and no deadlock appears in the Agent → Resource order.
#[tokio::test]
async fn story38_agent_publish_first_serializes_before_a_later_revoke() {
let sandbox = sandbox("revocation_write_agent_first").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_agent_first",
"crank://race/agent-first",
b"agent first v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_agent_first", "af").await;
save_bindings(&sandbox.registry, "ws_default", &agent, &resource)
.await
.expect("the draft binding must save before publishing");
install_advisory_gate(
&sandbox,
"crank_test_gate_agent_update",
"agents",
AGENT_GATE_KEY,
)
.await;
let gate = take_gate(&sandbox, AGENT_GATE_KEY).await;
let publisher = attributed_registry(&sandbox, "story38-agent-publish").await;
let publish_agent = agent.clone();
let published_at = OffsetDateTime::now_utc();
let publish = tokio::spawn(async move {
publisher
.publish_agent(PublishAgentRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &publish_agent,
version: 1,
published_at: &published_at,
published_by: None,
expected_state: None,
})
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-agent-publish", "story38-gate").await,
"the Agent publish must park after taking the shared Resource lock"
);
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-agent-first"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-agent-publish").await,
"the revoke must wait for the Agent publication that holds the shared Resource lock"
);
release_gate(gate, AGENT_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), publish)
.await
.expect("the Agent publish must finish")
.expect("the Agent publish must not panic")
.expect("the Agent publication must commit before the revoke");
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must follow the Agent publication");
assert_eq!(published_versions(&sandbox.pool, &agent).await, 1);
assert_eq!(catalog_revision(&sandbox.pool, &agent).await, 1);
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
let reader = attributed_registry(&sandbox, "story38-reader").await;
let denied = reader
.begin_authorized_resource_read("ws_default", &resource, 1)
.await
.map(|_| ());
assert!(
matches!(denied, Err(ResourceError::Revoked)),
"the Agent snapshot published before the revoke must not stay readable: {denied:?}"
);
sandbox.cleanup().await;
}
/// Revoke-first refuses a waiting Resource publication and leaves no publication row.
#[tokio::test]
async fn story38_revoke_first_refuses_a_waiting_resource_publish() {
let sandbox = sandbox("revocation_write_revoke_publish").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_revoke_publish",
"crank://race/revoke-publish",
b"revoke publish v1",
)
.await;
draft_next_resource_version(&sandbox, "ws_default", &resource, b"revoke publish v2").await;
let request = publish_request(&sandbox, "ws_default", &resource, b"revoke publish v2").await;
install_revocation_gate(&sandbox).await;
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-publish"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
"the revoke must hold the Resource row before the publication starts"
);
let publisher = attributed_registry(&sandbox, "story38-resource-publish").await;
let publish = tokio::spawn(async move { publisher.publish_resource_version(request).await });
assert!(
await_blocked_by(&sandbox.pool, "story38-resource-publish", "story38-revoker").await,
"the Resource publication must wait for the in-flight revoke"
);
release_gate(gate, REVOCATION_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must commit");
let outcome = tokio::time::timeout(Duration::from_secs(15), publish)
.await
.expect("the publication must finish")
.expect("the publication must not panic");
assert!(
matches!(outcome, Err(ResourceError::Revoked)),
"a publication behind a committed revoke must be refused: {outcome:?}"
);
assert_eq!(
publication_rows(&sandbox.pool, &resource).await,
1,
"a refused publication must not add an immutable version"
);
sandbox.cleanup().await;
}
/// Resource publish first: the immutable version commits, the revoke follows and closes it.
#[tokio::test]
async fn story38_resource_publish_first_serializes_before_a_later_revoke() {
let sandbox = sandbox("revocation_write_publish_first").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_write_publish_first",
"crank://race/publish-first",
b"publish first v1",
)
.await;
draft_next_resource_version(&sandbox, "ws_default", &resource, b"publish first v2").await;
let request = publish_request(&sandbox, "ws_default", &resource, b"publish first v2").await;
install_advisory_gate(
&sandbox,
"crank_test_gate_resource_publication",
"resource_publications",
PUBLICATION_GATE_KEY,
)
.await;
let gate = take_gate(&sandbox, PUBLICATION_GATE_KEY).await;
let publisher = attributed_registry(&sandbox, "story38-resource-publish").await;
let publish = tokio::spawn(async move { publisher.publish_resource_version(request).await });
assert!(
await_blocked_by(&sandbox.pool, "story38-resource-publish", "story38-gate").await,
"the publication must park after locking the Resource row"
);
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
let revoke_resource = resource.clone();
let revoke = tokio::spawn(async move {
revoker
.revoke_resource(revoke_request(&revoke_resource, "story38-publish-first"))
.await
});
assert!(
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-resource-publish").await,
"the revoke must wait for the publication that holds the Resource row"
);
release_gate(gate, PUBLICATION_GATE_KEY).await;
tokio::time::timeout(Duration::from_secs(15), publish)
.await
.expect("the publication must finish")
.expect("the publication must not panic")
.expect("the publication must commit before the revoke");
tokio::time::timeout(Duration::from_secs(15), revoke)
.await
.expect("the revoke must finish")
.expect("the revoke must not panic")
.expect("the revoke must follow the committed publication");
assert_eq!(publication_rows(&sandbox.pool, &resource).await, 2);
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
let reader = attributed_registry(&sandbox, "story38-reader").await;
let denied = reader
.begin_authorized_resource_read("ws_default", &resource, 2)
.await
.map(|_| ());
assert!(
matches!(denied, Err(ResourceError::Revoked)),
"the version published before the revoke must not stay readable: {denied:?}"
);
// The immutable snapshot itself is untouched (only live access is closed).
let snapshot = sandbox
.registry
.resolve_resource_publication("ws_default", &resource, 2)
.await
.expect("the immutable publication must stay resolvable for the raw Admin path");
assert_eq!(snapshot.publication.version, 2);
let row = sqlx::query("select count(*) from resource_publications where resource_id = $1")
.bind(resource.as_str())
.fetch_one(&sandbox.pool)
.await
.expect("publications must be queryable");
assert_eq!(row.try_get::<i64, _>(0).unwrap(), 2);
sandbox.cleanup().await;
}
@@ -0,0 +1,702 @@
//! Story 3.7 / AC04 regression: fault-after-write rollback и concurrent
//! published-catalog old-or-new (TL review F3).
//!
//! Проверяется на реальном PostgreSQL:
//! - поздний сбой publication после уже выполненных в транзакции записей
//! откатывает status/bindings/pointer/revision и не оставляет partial rows;
//! - сбой editable fork после частичной работы не оставляет orphan version,
//! bindings или сдвига pointer/revision;
//! - bounded concurrent reader/republish видит целостный tuple
//! (agent_version/resources/catalog_revision/tools) старого ИЛИ нового snapshot,
//! никогда смешанный.
//!
//! Harness не создаётся: используются существующие sandbox/fixtures и test-only
//! триггеры в приватной тестовой схеме.
use std::time::Duration;
use crank_core::{AgentOperationBinding, OperationStatus, WorkspaceId};
use crank_registry::{
CreateVersionRequest, PublishAgentRequest, PublishRequest, RegistryError,
SaveAgentCatalogConfigRequest,
};
use super::*;
/// Поздний сбой publication: триггер срабатывает на финальном `update agents`,
/// когда `agent_versions.status` и `published_agents` в этой же транзакции уже
/// изменены. Так проверяется именно rollback после частичной работы, а не
/// precheck (stale expected_state отказывает до любых записей).
async fn install_publication_fault(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"create function crank_test_fail_publication_after_writes()
returns trigger language plpgsql as $$
begin
if new.latest_published_version is not null then
raise exception 'injected publication failure after earlier writes'
using errcode = '23514';
end if;
return new;
end;
$$;
create trigger crank_test_fail_publication_after_writes_guard
before update on agents
for each row execute function crank_test_fail_publication_after_writes();",
)
.execute(pool)
.await
.expect("the test-only publication fault trigger must install");
}
async fn remove_publication_fault(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"drop trigger crank_test_fail_publication_after_writes_guard on agents;
drop function crank_test_fail_publication_after_writes();",
)
.execute(pool)
.await
.expect("the test-only publication fault trigger must be removable");
}
/// Поздний сбой editable fork: версия, operation bindings и первая Resource
/// binding уже вставлены; падает вставка второй Resource binding
/// (`res_v18_fork_fault_b` этой fixture), поэтому проверяется откат уже
/// записанных строк, а не пустой транзакции.
async fn install_binding_write_fault(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"create function crank_test_fail_binding_write()
returns trigger language plpgsql as $$
begin
if new.resource_id = 'res_v18_fork_fault_b' then
raise exception 'injected binding write failure after fork writes'
using errcode = '23514';
end if;
return new;
end;
$$;
create trigger crank_test_fail_binding_write_guard
before insert on agent_resource_bindings
for each row execute function crank_test_fail_binding_write();",
)
.execute(pool)
.await
.expect("the test-only binding-write fault trigger must install");
}
async fn remove_binding_write_fault(pool: &sqlx::PgPool) {
sqlx::raw_sql(
"drop trigger crank_test_fail_binding_write_guard on agent_resource_bindings;
drop function crank_test_fail_binding_write();",
)
.execute(pool)
.await
.expect("the test-only binding-write fault trigger must be removable");
}
/// Второй опубликованный Resource того же workspace: имя draft-а уникально
/// внутри workspace, поэтому fixture задаёт своё.
async fn published_resource_named(
sandbox: &Sandbox,
resource_id: &str,
uri: &str,
name: &str,
bytes: &[u8],
) -> ResourceId {
let id = ResourceId::new(resource_id);
sandbox
.registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: WorkspaceId::new("ws_default"),
resource_id: id.clone(),
uri: uri.to_owned(),
name: name.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
artifact: registered(sandbox, bytes),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("named resource draft must be created");
publish_current_resource(sandbox, "ws_default", &id, bytes).await;
id
}
async fn version_count(pool: &sqlx::PgPool, agent_id: &str) -> i64 {
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
.bind(agent_id)
.fetch_one(pool)
.await
.expect("agent versions must be queryable")
}
async fn operation_binding_count(pool: &sqlx::PgPool, agent_id: &str, version: i32) -> i64 {
sqlx::query_scalar(
"select count(*) from agent_operation_bindings
where agent_id = $1 and agent_version = $2",
)
.bind(agent_id)
.bind(version)
.fetch_one(pool)
.await
.expect("operation bindings must be queryable")
}
async fn resource_rows(pool: &sqlx::PgPool, agent_id: &str, version: i32) -> i64 {
sqlx::query_scalar(
"select count(*) from agent_resource_bindings
where agent_id = $1 and agent_version = $2",
)
.bind(agent_id)
.bind(version)
.fetch_one(pool)
.await
.expect("resource bindings must be queryable")
}
async fn publish_agent_version(
sandbox: &Sandbox,
agent: &crank_core::AgentId,
version: u32,
) -> Result<(), RegistryError> {
sandbox
.registry
.publish_agent(PublishAgentRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: agent,
version,
published_at: &OffsetDateTime::now_utc(),
published_by: None,
expected_state: None,
})
.await
}
async fn catalog_of(sandbox: &Sandbox, slug: &str) -> crank_registry::PublishedAgentCatalog {
sandbox
.registry
.get_published_agent_catalog_by_slug("default", slug)
.await
.expect("published catalog must be readable")
}
#[tokio::test]
async fn story37_v18_publication_failure_after_writes_rolls_back_atomically() {
let sandbox = sandbox("v18_publish_fault").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_v18_publish_fault",
"crank://v18/publish-fault",
b"publish fault v1",
)
.await;
let agent =
create_draft_agent(&sandbox, "ws_default", "agent_v18_publish_fault", "v18-pf").await;
save_resource_bindings(
&sandbox,
"ws_default",
&agent,
&[AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 1,
}],
)
.await
.expect("draft binding must be saved");
let before = sandbox
.registry
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
.await
.expect("summary must be readable")
.expect("summary must exist");
install_publication_fault(&sandbox.pool).await;
let failed = publish_agent_version(&sandbox, &agent, 1)
.await
.expect_err("the injected late failure must abort the publication");
assert!(
matches!(failed, RegistryError::Storage(_)),
"a database failure after writes must surface as a storage error: {failed}"
);
remove_publication_fault(&sandbox.pool).await;
// Всё, что транзакция успела записать до сбоя, обязано откатиться.
let version = sandbox
.registry
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
.await
.expect("agent version must be readable")
.expect("agent version must exist");
assert_eq!(
version.status,
AgentStatus::Draft,
"a rolled-back publication must not leave the version published"
);
assert_eq!(
version.resource_bindings,
vec![AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 1
}],
"draft exact bindings must survive the rollback"
);
let after = sandbox
.registry
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
.await
.expect("summary must be readable")
.expect("summary must exist");
assert_eq!(after.status, AgentStatus::Draft);
assert_eq!(after.latest_published_version, None);
assert_eq!(
after.catalog_revision, before.catalog_revision,
"a rolled-back publication must not bump catalog_revision"
);
let pointer_rows: i64 =
sqlx::query_scalar("select count(*) from published_agents where agent_id = $1")
.bind(agent.as_str())
.fetch_one(&sandbox.pool)
.await
.expect("published pointer must be queryable");
assert_eq!(pointer_rows, 0, "a failed publish must not write a pointer");
assert_eq!(resource_rows(&sandbox.pool, agent.as_str(), 1).await, 1);
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
// Positive control: без fault та же публикация проходит и двигает pointer/revision.
publish_agent_version(&sandbox, &agent, 1)
.await
.expect("publication must succeed once the fault is removed");
let published = sandbox
.registry
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
.await
.expect("summary must be readable")
.expect("summary must exist");
assert_eq!(published.status, AgentStatus::Published);
assert_eq!(published.latest_published_version, Some(1));
assert_eq!(
published.catalog_revision,
before.catalog_revision + 1,
"publication must raise catalog_revision by exactly one"
);
let catalog = catalog_of(&sandbox, "v18-pf").await;
assert_eq!(catalog.agent_version, 1);
assert_eq!(
catalog.resources,
vec![AgentResourceBinding {
resource_id: resource,
resource_version: 1
}]
);
sandbox.cleanup().await;
}
#[tokio::test]
async fn story37_v18_editable_fork_failure_leaves_no_partial_version() {
let sandbox = sandbox("v18_fork_fault").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_v18_fork_fault",
"crank://v18/fork-fault",
b"fork fault v1",
)
.await;
let second = published_resource_named(
&sandbox,
"res_v18_fork_fault_b",
"crank://v18/fork-fault-b",
"binding_doc_b",
b"fork fault second v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_fork_fault", "v18-ff").await;
// Существующий опубликованный Tool binding: fork обязан успеть его записать.
let operation_binding = published_operation_binding(&sandbox).await;
let bindings = vec![operation_binding.clone()];
sandbox
.registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &agent,
agent_version: 1,
bindings: &bindings,
tool_selection_policy: &Default::default(),
resource_bindings: &[
AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: second.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("v1 config with a published Tool and two exact Resources must save");
publish_agent_version(&sandbox, &agent, 1)
.await
.expect("Agent v1 must publish");
draft_next_resource_version(&sandbox, "ws_default", &resource, b"fork fault v2").await;
assert_eq!(
publish_current_resource(&sandbox, "ws_default", &resource, b"fork fault v2").await,
2,
"exact Resource v2 must be available for the fork"
);
let before = sandbox
.registry
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
.await
.expect("summary must be readable")
.expect("summary must exist");
let catalog_before = catalog_of(&sandbox, "v18-ff").await;
install_binding_write_fault(&sandbox.pool).await;
let failed = sandbox
.registry
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &agent,
agent_version: 1,
bindings: &bindings,
tool_selection_policy: &Default::default(),
resource_bindings: &[
AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 2,
},
AgentResourceBinding {
resource_id: second.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect_err("the injected fork failure must abort the editable save");
assert!(
matches!(failed, RegistryError::Storage(_)),
"a database failure after fork writes must surface as a storage error: {failed}"
);
remove_binding_write_fault(&sandbox.pool).await;
// Partial work editable fork не должна пережить откат.
assert_eq!(
version_count(&sandbox.pool, agent.as_str()).await,
1,
"a failed fork must not leave an orphan Agent version"
);
assert_eq!(
operation_binding_count(&sandbox.pool, agent.as_str(), 2).await,
0,
"a failed fork must not leave partial operation bindings"
);
assert_eq!(
resource_rows(&sandbox.pool, agent.as_str(), 2).await,
0,
"a failed fork must not leave partial resource bindings"
);
// До сбоя транзакция успела записать Tool binding и первую Resource binding:
// обе обязаны исчезнуть вместе с версией 2, а snapshot v1 — остаться целым.
assert_eq!(
operation_binding_count(&sandbox.pool, agent.as_str(), 1).await,
1,
"the published v1 Tool binding must survive the rollback"
);
assert_eq!(
resource_rows(&sandbox.pool, agent.as_str(), 1).await,
2,
"the published v1 Resource bindings must survive the rollback"
);
let after = sandbox
.registry
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
.await
.expect("summary must be readable")
.expect("summary must exist");
assert_eq!(after.current_draft_version, 1);
assert_eq!(after.latest_published_version, Some(1));
assert_eq!(after.catalog_revision, before.catalog_revision);
assert_eq!(
after.updated_at, before.updated_at,
"a failed fork must not move the Agent updated_at"
);
assert_eq!(catalog_of(&sandbox, "v18-ff").await, catalog_before);
// Positive control: без fault тот же editable fork создаёт v2 и публикует новый snapshot.
let forked = sandbox
.registry
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &agent,
agent_version: 1,
bindings: &bindings,
tool_selection_policy: &Default::default(),
resource_bindings: &[
AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 2,
},
AgentResourceBinding {
resource_id: second.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("the editable fork must succeed once the fault is removed");
assert_eq!(forked, 2);
assert_eq!(
operation_binding_count(&sandbox.pool, agent.as_str(), 2).await,
1,
"the successful fork must persist the Tool binding that precedes the faulted Resource write"
);
assert_eq!(
resource_rows(&sandbox.pool, agent.as_str(), 2).await,
2,
"the successful fork must persist both exact Resource bindings"
);
publish_agent_version(&sandbox, &agent, 2)
.await
.expect("Agent v2 must publish");
let catalog = catalog_of(&sandbox, "v18-ff").await;
assert_eq!(catalog.agent_version, 2);
assert_eq!(
catalog.resources,
vec![
AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 2
},
AgentResourceBinding {
resource_id: second.clone(),
resource_version: 1
}
]
);
assert_eq!(
catalog.tools.len(),
1,
"the republished snapshot must keep its Tool binding"
);
let still_v1 = sandbox
.registry
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
.await
.expect("agent version must be readable")
.expect("agent version must exist");
assert_eq!(
still_v1.resource_bindings,
vec![
AgentResourceBinding {
resource_id: resource,
resource_version: 1
},
AgentResourceBinding {
resource_id: second,
resource_version: 1
}
]
);
sandbox.cleanup().await;
}
type CatalogTuple = (
u32,
String,
Vec<AgentResourceBinding>,
Vec<(String, String, u32)>,
);
fn catalog_tuple(catalog: &crank_registry::PublishedAgentCatalog) -> CatalogTuple {
(
catalog.agent_version,
catalog.catalog_revision.clone(),
catalog.resources.clone(),
catalog
.tools
.iter()
.map(|tool| {
(
tool.tool_name.clone(),
tool.operation.id.as_str().to_owned(),
tool.operation.version,
)
})
.collect(),
)
}
/// Публикует Operation v2 и возвращает binding, чтобы published catalog содержал
/// непустой `tools` рядом с resources.
async fn published_operation_binding(sandbox: &Sandbox) -> AgentOperationBinding {
let operation = test_operation("op_v18_concurrent", 1, OperationStatus::Draft);
sandbox
.registry
.create_operation(&WorkspaceId::new("ws_default"), &operation, None)
.await
.expect("operation draft must be created");
let operation_v2 = test_operation("op_v18_concurrent", 2, OperationStatus::Draft);
sandbox
.registry
.create_version(CreateVersionRequest {
workspace_id: &WorkspaceId::new("ws_default"),
snapshot: &operation_v2,
change_note: Some("v18 concurrent fixture"),
created_by: None,
})
.await
.expect("operation version must be created");
sandbox
.registry
.publish_operation(PublishRequest {
workspace_id: &WorkspaceId::new("ws_default"),
operation_id: &operation.id,
version: 2,
published_at: &OffsetDateTime::now_utc(),
published_by: None,
})
.await
.expect("operation v2 must publish");
AgentOperationBinding {
operation_id: operation.id,
operation_version: 2,
tool_name: "v18_concurrent_tool".to_owned(),
tool_title: "V18 concurrent tool".to_owned(),
tool_description_override: None,
enabled: true,
}
}
#[tokio::test]
async fn story37_v18_concurrent_catalog_read_sees_old_or_new_tuple_never_mixed() {
let sandbox = sandbox("v18_catalog_concurrent").await;
let resource = published_resource(
&sandbox,
"ws_default",
"res_v18_concurrent",
"crank://v18/concurrent",
b"concurrent v1",
)
.await;
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_concurrent", "v18-cc").await;
let operation_binding = published_operation_binding(&sandbox).await;
let bindings = vec![operation_binding.clone()];
sandbox
.registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &agent,
agent_version: 1,
bindings: &bindings,
tool_selection_policy: &Default::default(),
resource_bindings: &[AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 1,
}],
expected_state: None,
})
.await
.expect("v1 config with exact resource and tool must save");
publish_agent_version(&sandbox, &agent, 1)
.await
.expect("Agent v1 must publish");
draft_next_resource_version(&sandbox, "ws_default", &resource, b"concurrent v2").await;
assert_eq!(
publish_current_resource(&sandbox, "ws_default", &resource, b"concurrent v2").await,
2
);
let old_tuple = catalog_tuple(&catalog_of(&sandbox, "v18-cc").await);
assert_eq!(old_tuple.0, 1);
assert_eq!(
old_tuple.3.len(),
1,
"the old snapshot must carry the published tool"
);
// v2 меняет Tool binding, иначе смешанный tuple (старые version/resources +
// новый tools) был бы неотличим от старого snapshot.
let mut v2_bindings = bindings.clone();
v2_bindings[0].tool_name = "v18_concurrent_tool_v2".to_owned();
v2_bindings[0].tool_title = "V18 concurrent tool v2".to_owned();
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let reader_registry = sandbox.registry.clone();
let reader = tokio::spawn(async move {
let mut observed = Vec::with_capacity(256);
let mut started_tx = Some(started_tx);
for _ in 0..256 {
let catalog = reader_registry
.get_published_agent_catalog_by_slug("default", "v18-cc")
.await
.expect("concurrent catalog read must succeed");
observed.push(catalog_tuple(&catalog));
if let Some(started) = started_tx.take() {
let _ = started.send(());
}
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(1)).await;
}
observed
});
// Reader уже прочитал старый snapshot до начала fork/publish: окно наблюдения
// действительно перекрывает writer, а не идёт строго после него.
started_rx
.await
.expect("the reader must observe the catalog before the publication starts");
let forked = sandbox
.registry
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
workspace_id: &WorkspaceId::new("ws_default"),
agent_id: &agent,
agent_version: 1,
bindings: &v2_bindings,
tool_selection_policy: &Default::default(),
resource_bindings: &[AgentResourceBinding {
resource_id: resource.clone(),
resource_version: 2,
}],
expected_state: None,
})
.await
.expect("editable fork to v2 must succeed");
assert_eq!(forked, 2);
publish_agent_version(&sandbox, &agent, 2)
.await
.expect("Agent v2 must publish");
let observed = reader.await.expect("reader task must finish");
let new_tuple = catalog_tuple(&catalog_of(&sandbox, "v18-cc").await);
assert_eq!(new_tuple.0, 2);
assert_eq!(
new_tuple.3.len(),
1,
"the new snapshot must carry the edited tool"
);
assert_ne!(
new_tuple.3, old_tuple.3,
"tools must differ between snapshots, otherwise a mixed tuple is undetectable"
);
assert_ne!(
old_tuple, new_tuple,
"the fixture must actually produce two different catalog snapshots"
);
assert_eq!(
observed.first(),
Some(&old_tuple),
"the first read happened before the publication, so it must be the old tuple"
);
for (index, tuple) in observed.iter().enumerate() {
assert!(
*tuple == old_tuple || *tuple == new_tuple,
"concurrent read #{index} observed a mixed catalog tuple: {tuple:?}"
);
}
sandbox.cleanup().await;
}