Files
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

573 lines
21 KiB
Rust

//! 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;
}