[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:
1 parent
1b6db09bd1
commit
301dce301a
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,916 @@
|
||||
//! Story 3.7 / AC04 regression: typed exact Resource bindings Agent (V18).
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL, что integrity держится **схемой**, а не только
|
||||
//! JSON-ответом API:
|
||||
//! - workspace-равенство на обоих концах composite FK (Agent и Resource publication);
|
||||
//! - published Agent Version bindings иммутабельны (V9 guard function);
|
||||
//! - закреплённая exact v1 не меняется после публикации Resource v2;
|
||||
//! - failed save/publish откатываются без partial rows/pointer/revision;
|
||||
//! - published catalog reader отдаёт resources из того же снимка, что
|
||||
//! agent_version/catalog_revision/tools.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use super::common::*;
|
||||
|
||||
mod archive_race;
|
||||
mod revocation_race;
|
||||
mod revocation_write_race;
|
||||
mod rollback;
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, PublishResourceVersionRequest, UpdateResourceDraftRequest,
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry,
|
||||
PublishAgentRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-agent-resource-bindings-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
pool: sqlx::PgPool,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
database: TestDatabase,
|
||||
}
|
||||
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
Sandbox {
|
||||
registry,
|
||||
pool,
|
||||
store,
|
||||
_root: root,
|
||||
database,
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox {
|
||||
async fn cleanup(&self) {
|
||||
self.database.cleanup().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
async fn seed_workspace(sandbox: &Sandbox, workspace_id: &str, slug: &str) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
sandbox
|
||||
.registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: WorkspaceId::new(workspace_id),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("synthetic workspace must be created");
|
||||
}
|
||||
|
||||
/// Draft → Published Resource v1 через принятый Story 3.6/3.7 registry-контракт.
|
||||
async fn published_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
uri: &str,
|
||||
bytes: &[u8],
|
||||
) -> ResourceId {
|
||||
let id = ResourceId::new(resource_id);
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: id.clone(),
|
||||
uri: uri.to_owned(),
|
||||
name: "binding_doc".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("resource draft must be created");
|
||||
publish_current_resource(sandbox, workspace_id, &id, bytes).await;
|
||||
id
|
||||
}
|
||||
|
||||
async fn publish_current_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) -> u32 {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(workspace_id, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: resource_id.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(),
|
||||
})
|
||||
.await
|
||||
.expect("valid current draft must publish");
|
||||
publication.version
|
||||
}
|
||||
|
||||
async fn draft_next_resource_version(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(workspace_id, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(sandbox, bytes),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after publication must succeed");
|
||||
}
|
||||
|
||||
async fn create_draft_agent(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
agent_id: &str,
|
||||
slug: &str,
|
||||
) -> crank_core::AgentId {
|
||||
let id = crank_core::AgentId::new(agent_id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let agent = Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
description: "Story 3.7 typed binding fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id: id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: Default::default(),
|
||||
created_at: now,
|
||||
};
|
||||
sandbox
|
||||
.registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent must be created");
|
||||
id
|
||||
}
|
||||
|
||||
async fn save_resource_bindings(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
agent_id: &crank_core::AgentId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<(), crank_registry::RegistryError> {
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new(workspace_id),
|
||||
agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: bindings,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn binding_rows(sandbox: &Sandbox, agent_id: &str) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from agent_resource_bindings where agent_id = $1")
|
||||
.bind(agent_id)
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("binding rows must be queryable")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_typed_fk_enforces_workspace_on_both_ends() {
|
||||
let sandbox = sandbox("v18_fk_scope").await;
|
||||
seed_workspace(&sandbox, "ws_other", "other").await;
|
||||
let own = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_default",
|
||||
"crank://v18/default",
|
||||
b"default v1",
|
||||
)
|
||||
.await;
|
||||
let foreign = published_resource(
|
||||
&sandbox,
|
||||
"ws_other",
|
||||
"res_v18_foreign",
|
||||
"crank://v18/foreign",
|
||||
b"foreign v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_fk", "v18-fk").await;
|
||||
let other_agent =
|
||||
create_draft_agent(&sandbox, "ws_other", "agent_v18_other", "v18-other").await;
|
||||
let foreign_binding = AgentResourceBinding {
|
||||
resource_id: foreign.clone(),
|
||||
resource_version: 1,
|
||||
};
|
||||
|
||||
// Чужой Agent в binding.workspace_id отвергается composite FK на Agent-конце.
|
||||
let agent_scope = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 1)",
|
||||
)
|
||||
.bind(other_agent.as_str())
|
||||
.bind(own.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a foreign-workspace Agent must be rejected by the Agent-side FK");
|
||||
assert_eq!(
|
||||
database_error_code(&agent_scope),
|
||||
"23503",
|
||||
"Agent workspace mismatch must be a foreign-key violation: {agent_scope}"
|
||||
);
|
||||
|
||||
// Чужая Resource publication отвергается composite FK на Resource-конце.
|
||||
let resource_scope = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 1)",
|
||||
)
|
||||
.bind(agent.as_str())
|
||||
.bind(foreign_binding.resource_id.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a foreign-workspace Resource publication must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&resource_scope),
|
||||
"23503",
|
||||
"Resource workspace mismatch must be a foreign-key violation: {resource_scope}"
|
||||
);
|
||||
|
||||
// Positive control: та же вставка в своём workspace проходит и видна читателю.
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: own.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a same-workspace exact binding must be accepted");
|
||||
let record = 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!(
|
||||
record.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: own,
|
||||
resource_version: 1
|
||||
}]
|
||||
);
|
||||
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
fn database_error_code(error: &sqlx::Error) -> String {
|
||||
match error {
|
||||
sqlx::Error::Database(database) => database.code().unwrap_or_default().to_string(),
|
||||
other => panic!("expected a database error, got {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_published_agent_resource_bindings_are_immutable() {
|
||||
let sandbox = sandbox("v18_immutable").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_immutable",
|
||||
"crank://v18/immutable",
|
||||
b"immutable v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_immutable", "v18-imm").await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft binding must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("resource-only Agent must publish at registry level");
|
||||
|
||||
let update = sqlx::query(
|
||||
"update agent_resource_bindings set resource_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a published Agent binding must not be updated");
|
||||
assert_eq!(
|
||||
database_error_code(&update),
|
||||
"23514",
|
||||
"immutability guard must raise a check violation: {update}"
|
||||
);
|
||||
let delete = sqlx::query("delete from agent_resource_bindings where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a published Agent binding must not be deleted");
|
||||
assert_eq!(
|
||||
database_error_code(&delete),
|
||||
"23514",
|
||||
"immutability guard must reject deletes: {delete}"
|
||||
);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
1,
|
||||
"refused mutations must keep the published snapshot"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_published_binding_cannot_move_to_a_draft_agent_or_version() {
|
||||
let sandbox = sandbox("v18_immutable_move").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_move",
|
||||
"crank://v18/move",
|
||||
b"move v1",
|
||||
)
|
||||
.await;
|
||||
let published_agent =
|
||||
create_draft_agent(&sandbox, "ws_default", "agent_v18_move_pub", "v18-move-pub").await;
|
||||
let draft_agent = create_draft_agent(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"agent_v18_move_draft",
|
||||
"v18-move-draft",
|
||||
)
|
||||
.await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&published_agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft binding must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &published_agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("resource-only Agent must publish");
|
||||
|
||||
// Перенос Published snapshot -> Draft Agent другого id: оба composite FK остаются
|
||||
// валидными (тот же workspace), поэтому отказать обязан immutable guard по OLD-ключу.
|
||||
let to_draft_agent = sqlx::query(
|
||||
"update agent_resource_bindings set agent_id = $1
|
||||
where agent_id = $2 and agent_version = 1",
|
||||
)
|
||||
.bind(draft_agent.as_str())
|
||||
.bind(published_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("moving a published binding to a Draft Agent must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&to_draft_agent),
|
||||
"23514",
|
||||
"V18 guard must reject relocation away from the published source: {to_draft_agent}"
|
||||
);
|
||||
|
||||
// Draft-версия того же Agent создаётся штатным editable fork (v2 без bindings).
|
||||
let forked = sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &published_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Agent must fork a Draft version");
|
||||
assert_eq!(forked, 2, "editable fork must create Agent version 2");
|
||||
let to_draft_version = sqlx::query(
|
||||
"update agent_resource_bindings set agent_version = $1
|
||||
where agent_id = $2 and agent_version = 1",
|
||||
)
|
||||
.bind(i32::try_from(forked).expect("forked version must fit the DB integer domain"))
|
||||
.bind(published_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("moving a published binding to a Draft version must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&to_draft_version),
|
||||
"23514",
|
||||
"V18 guard must reject relocation to a Draft version: {to_draft_version}"
|
||||
);
|
||||
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"move v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"move v2").await,
|
||||
2
|
||||
);
|
||||
// NEW-конец тоже защищён: нельзя добавить binding в уже опубликованный snapshot.
|
||||
let insert_into_published = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 2)",
|
||||
)
|
||||
.bind(published_agent.as_str())
|
||||
.bind(resource.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("inserting a binding into a published Agent version must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&insert_into_published),
|
||||
"23514",
|
||||
"V18 guard must reject new rows for a published version: {insert_into_published}"
|
||||
);
|
||||
|
||||
// Positive control: Draft binding по-прежнему изменяем (обычный UPDATE).
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&draft_agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a Draft Agent binding must be accepted");
|
||||
let draft_move = sqlx::query(
|
||||
"update agent_resource_bindings set resource_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(draft_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect("a Draft binding must remain mutable");
|
||||
assert_eq!(draft_move.rows_affected(), 1);
|
||||
|
||||
// Отказы не тронули published snapshot и каталог.
|
||||
assert_eq!(binding_rows(&sandbox, published_agent.as_str()).await, 1);
|
||||
let pinned = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &published_agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
pinned.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1
|
||||
}],
|
||||
"refused relocations must keep the published exact v1"
|
||||
);
|
||||
let catalog = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-move-pub")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(catalog.agent_version, 1);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
}],
|
||||
"the published catalog must keep the original exact snapshot"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_exact_v1_survives_resource_v2_and_catalog_reader_is_coherent() {
|
||||
let sandbox = sandbox("v18_exact_v1").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_exact",
|
||||
"crank://v18/exact",
|
||||
b"exact v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_exact", "v18-exact").await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft exact v1 must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent must publish");
|
||||
let summary_before = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"exact v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"exact v2").await,
|
||||
2,
|
||||
"the edited Draft must publish as exact v2"
|
||||
);
|
||||
|
||||
let pinned = 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!(
|
||||
pinned.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1
|
||||
}],
|
||||
"Resource v2 must not replace the pinned exact v1"
|
||||
);
|
||||
let summary_after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(
|
||||
summary_after.catalog_revision, summary_before.catalog_revision,
|
||||
"a Resource publication must not bump the Agent catalog_revision"
|
||||
);
|
||||
|
||||
let catalog = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-exact")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(
|
||||
catalog.agent_version, 1,
|
||||
"catalog must keep the published Agent version"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.catalog_revision,
|
||||
format!(
|
||||
"agent-version-1-catalog-revision-{}",
|
||||
summary_after.catalog_revision
|
||||
),
|
||||
"resources and revision must come from the same published snapshot"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
}],
|
||||
"catalog reader must expose the exact pinned Resource Version"
|
||||
);
|
||||
|
||||
// Явный republish Agent фиксирует новый snapshot, старый остаётся exact v1.
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 2,
|
||||
}],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Agent must fork a new Draft with v2");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 2,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("republished Agent version 2 must publish");
|
||||
let catalog_v2 = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-exact")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(catalog_v2.agent_version, 2);
|
||||
assert_eq!(
|
||||
catalog_v2.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 2
|
||||
}],
|
||||
"an explicit republish must switch the catalog to the new exact snapshot"
|
||||
);
|
||||
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: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 1
|
||||
}],
|
||||
"the earlier published snapshot must stay exact v1"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_failed_write_and_publication_leave_no_partial_state() {
|
||||
let sandbox = sandbox("v18_rollback").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_rollback",
|
||||
"crank://v18/rollback",
|
||||
b"rollback v1",
|
||||
)
|
||||
.await;
|
||||
// Draft v2 существует, но не опубликован: exact version недоступна для binding.
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"rollback v2").await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_rollback", "v18-rb").await;
|
||||
|
||||
let failed_save = save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect_err("an unpublished Resource version must fail the write");
|
||||
assert!(
|
||||
matches!(failed_save, crank_registry::RegistryError::Storage(_)),
|
||||
"the FK refusal must surface as a storage error: {failed_save}"
|
||||
);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
0,
|
||||
"a failed save must not leave partial binding rows"
|
||||
);
|
||||
let versions: i64 =
|
||||
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("agent versions must be queryable");
|
||||
assert_eq!(versions, 1, "a failed save must not add a version row");
|
||||
let summary = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(
|
||||
summary.current_draft_version, 1,
|
||||
"a failed save must not move the Draft pointer"
|
||||
);
|
||||
|
||||
// Stale publication: отказ до записи, pointer/revision/rows не меняются.
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a published exact v1 must be accepted");
|
||||
let stale_state = crank_registry::AgentStateExpectation {
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
catalog_revision: summary.catalog_revision,
|
||||
updated_at: summary.updated_at,
|
||||
};
|
||||
let failed_publish = sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: Some(&stale_state),
|
||||
})
|
||||
.await
|
||||
.expect_err("a stale publication precondition must fail");
|
||||
assert!(
|
||||
matches!(
|
||||
failed_publish,
|
||||
crank_registry::RegistryError::AgentStaleRevision { .. }
|
||||
),
|
||||
"stale publication must keep the Agent taxonomy: {failed_publish}"
|
||||
);
|
||||
let published_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!(
|
||||
published_rows, 0,
|
||||
"a failed publish must not write a pointer"
|
||||
);
|
||||
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.catalog_revision, summary.catalog_revision);
|
||||
assert_eq!(after.latest_published_version, None);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
1,
|
||||
"a failed publish must not drop the draft binding"
|
||||
);
|
||||
|
||||
// Positive control: корректная публикация атомарно двигает pointer и revision.
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: Some(&crank_registry::AgentStateExpectation {
|
||||
status: after.status,
|
||||
current_draft_version: after.current_draft_version,
|
||||
latest_published_version: after.latest_published_version,
|
||||
catalog_revision: after.catalog_revision,
|
||||
updated_at: after.updated_at,
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.expect("a fresh precondition must publish");
|
||||
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.latest_published_version, Some(1));
|
||||
assert_eq!(
|
||||
published.catalog_revision,
|
||||
after.catalog_revision + 1,
|
||||
"publication must raise catalog_revision by exactly one"
|
||||
);
|
||||
assert_eq!(
|
||||
published.status,
|
||||
AgentStatus::Published,
|
||||
"publication must atomically switch the Agent pointer"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+538
@@ -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;
|
||||
}
|
||||
@@ -236,6 +236,7 @@ async fn published_agent_snapshot_remains_immutable_after_draft_edit() {
|
||||
agent_version: version.version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
@@ -307,6 +308,7 @@ async fn stale_agent_revision_rejects_mutation() {
|
||||
agent_version: version.version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#![allow(dead_code, unused_imports)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crank_core::{
|
||||
AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApiKeyHeaderAuthConfig, AuthConfig,
|
||||
@@ -295,6 +296,29 @@ impl TestDatabase {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Registry over a multi-connection pool in this test schema: concurrency regressions need
|
||||
/// sessions that can genuinely block on each other's row locks.
|
||||
pub(super) async fn concurrent_registry(&self, max_connections: u32) -> PostgresRegistry {
|
||||
let database_url = format!(
|
||||
"{}?options=-csearch_path%3D{}",
|
||||
self.database_url, self.schema
|
||||
);
|
||||
let options = sqlx::postgres::PgConnectOptions::from_str(&database_url)
|
||||
.expect("the test database url must parse into connect options");
|
||||
PostgresRegistry::connect_with_options_and_pool_config(
|
||||
options,
|
||||
crank_registry::PostgresPoolConfig {
|
||||
max_connections,
|
||||
min_connections: 0,
|
||||
acquire_timeout_ms: 10_000,
|
||||
idle_timeout_ms: 600_000,
|
||||
max_lifetime_ms: 1_800_000,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the concurrent test registry must connect")
|
||||
}
|
||||
|
||||
pub(super) async fn cleanup(&self) {
|
||||
self.admin_pool
|
||||
.execute(sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
|
||||
@@ -5,8 +5,13 @@ mod artifact_metadata;
|
||||
mod import_plan;
|
||||
mod legacy_adoption;
|
||||
mod preflight;
|
||||
mod resource_security_revocations;
|
||||
mod rollback;
|
||||
|
||||
mod schema_removal;
|
||||
|
||||
pub(crate) use schema_removal::*;
|
||||
|
||||
static EVENT_TRIGGER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
|
||||
fn legacy_preservation_row_expr(table: &str) -> &'static str {
|
||||
@@ -57,6 +62,14 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
(13, "artifact-cleanup-indexes-v13"),
|
||||
(14, "import-plan-v14"),
|
||||
(15, "onboarding-import-selection-v15"),
|
||||
(16, "resource-drafts-v16"),
|
||||
(17, "resource-publications-v17"),
|
||||
(18, "agent-resource-bindings-v18"),
|
||||
(19, "resource-security-revocations-v19"),
|
||||
(20, "resource-template-sources-v20"),
|
||||
(21, "prompts-v21"),
|
||||
(22, "prompt-publications-v22"),
|
||||
(23, "prompt-dependencies-v23"),
|
||||
];
|
||||
assert_eq!(rows.len(), expected.len());
|
||||
for (row, (version, name)) in rows.iter().zip(expected) {
|
||||
@@ -121,11 +134,105 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
.await
|
||||
.expect("V14 import plan relations must be readable");
|
||||
assert_eq!(import_plan_relations.len(), 2);
|
||||
let publication_relations = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name in ('resource_publications', 'resource_versions')
|
||||
order by table_name",
|
||||
)
|
||||
.fetch_all(first.pool())
|
||||
.await
|
||||
.expect("V17 publication relation must be readable");
|
||||
assert_eq!(
|
||||
publication_relations.len(),
|
||||
2,
|
||||
"V17 must add resource_publications beside resource_versions"
|
||||
);
|
||||
let binding_relations = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name = 'agent_resource_bindings'",
|
||||
)
|
||||
.fetch_all(first.pool())
|
||||
.await
|
||||
.expect("V18 binding relation must be readable");
|
||||
assert_eq!(
|
||||
binding_relations.len(),
|
||||
1,
|
||||
"V18 must add the typed agent_resource_bindings table"
|
||||
);
|
||||
let binding_fks: i64 = sqlx::query_scalar(
|
||||
"select count(*)::bigint
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'agent_resource_bindings' and c.contype = 'f'",
|
||||
)
|
||||
.fetch_one(first.pool())
|
||||
.await
|
||||
.expect("V18 binding constraints must be readable");
|
||||
assert_eq!(
|
||||
binding_fks, 3,
|
||||
"V18 must keep workspace equality on both ends plus the exact Agent version"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(first.pool()).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn v18_guard_rejects_missing_agent_resource_binding_trigger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v18_guard_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop trigger agent_resource_bindings_immutable_guard on agent_resource_bindings")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V18 trigger must be droppable for the drift fixture");
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(
|
||||
error.version(),
|
||||
Some(18),
|
||||
"a missing V18 immutability trigger must be attributed to V18: {error}"
|
||||
);
|
||||
assert_eq!(error.stage(), "v18.immutable_trigger");
|
||||
sqlx::raw_sql(
|
||||
"create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_binding_mutation();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the canonical trigger must be restorable");
|
||||
let function_drift = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(
|
||||
function_drift.code(),
|
||||
"partial_sequence",
|
||||
"V18 guard must pin the V18-local OLD+NEW function, not the V9 function"
|
||||
);
|
||||
assert_eq!(function_drift.stage(), "v18.immutable_trigger");
|
||||
sqlx::raw_sql(
|
||||
"drop trigger agent_resource_bindings_immutable_guard on agent_resource_bindings;
|
||||
create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_resource_binding_mutation();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V18-local guard must be restorable");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restoring the exact V18 contract must return the current verdict"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_connect_is_read_only_on_fresh_database() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_read_only_startup").await;
|
||||
@@ -247,7 +354,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -360,13 +467,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 2,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let trace_column: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
@@ -409,7 +516,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 3,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -469,7 +576,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 4,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -723,207 +830,6 @@ async fn v3_upgrade_ignores_oversized_legacy_request_ids_in_partial_index() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
async fn remove_v3_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_request_id_idx;
|
||||
alter table invocation_logs drop column if exists trace_id;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v4_schema(pool: &sqlx::PgPool) {
|
||||
remove_v5_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists operation_versions_immutable_guard on operation_versions;
|
||||
drop function if exists crank_guard_operation_version_immutable();
|
||||
drop trigger if exists published_operations_monotonic_guard on published_operations;
|
||||
drop function if exists crank_guard_published_operation_pointer();
|
||||
drop trigger if exists operations_latest_pointer_monotonic_guard on operations;
|
||||
drop function if exists crank_guard_operation_latest_pointer();
|
||||
alter table operation_versions
|
||||
drop constraint if exists operation_versions_snapshot_provenance_check,
|
||||
drop column if exists name,
|
||||
drop column if exists display_name,
|
||||
drop column if exists category,
|
||||
drop column if exists protocol,
|
||||
drop column if exists security_level,
|
||||
drop column if exists snapshot_provenance,
|
||||
drop column if exists snapshot_observed_at,
|
||||
drop column if exists published_at,
|
||||
drop column if exists published_by;
|
||||
delete from __crank_migrations where version = 4;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v5_schema(pool: &sqlx::PgPool) {
|
||||
remove_v6_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_operation_version_idx;
|
||||
alter table invocation_logs
|
||||
drop column if exists operation_version,
|
||||
drop column if exists execution_stage,
|
||||
drop column if exists execution_error_code,
|
||||
drop column if exists retryability,
|
||||
drop column if exists outcome_certainty;
|
||||
delete from __crank_migrations where version = 5;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v6_schema(pool: &sqlx::PgPool) {
|
||||
remove_v7_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists platform_api_keys_workspace_name_active_idx;
|
||||
create unique index if not exists platform_api_keys_workspace_name_idx on platform_api_keys(workspace_id, name);
|
||||
delete from __crank_migrations where version = 6;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v7_schema(pool: &sqlx::PgPool) {
|
||||
remove_v8_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"alter table secret_versions drop constraint if exists secret_versions_target_all_or_none_check,
|
||||
drop constraint if exists secret_versions_target_epoch_check,
|
||||
drop constraint if exists secret_versions_master_key_epoch_check,
|
||||
drop column if exists target_master_key_epoch, drop column if exists target_key_version,
|
||||
drop column if exists target_ciphertext, drop column if exists master_key_epoch;
|
||||
drop table if exists master_key_rotations;
|
||||
drop table if exists master_key_identities;
|
||||
delete from __crank_migrations where version = 7;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v8_schema(pool: &sqlx::PgPool) {
|
||||
remove_v9_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists admin_security_audit_events;
|
||||
drop table if exists admin_login_backoff;
|
||||
drop table if exists admin_bootstrap_contracts;
|
||||
alter table user_sessions
|
||||
drop constraint if exists user_sessions_csrf_hash_check,
|
||||
drop column if exists csrf_hash,
|
||||
drop column if exists revoked_at;
|
||||
delete from __crank_migrations where version = 8;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v9_schema(pool: &sqlx::PgPool) {
|
||||
remove_v10_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists published_agents_monotonic_guard on published_agents;
|
||||
drop function if exists crank_reject_published_agent_pointer_rewind();
|
||||
drop trigger if exists agent_operation_bindings_immutable_guard on agent_operation_bindings;
|
||||
drop function if exists crank_reject_published_agent_binding_mutation();
|
||||
drop trigger if exists agent_versions_immutable_guard on agent_versions;
|
||||
drop function if exists crank_reject_published_agent_version_mutation();
|
||||
alter table published_agents
|
||||
drop constraint if exists published_agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
alter table agents
|
||||
drop constraint if exists agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
delete from __crank_migrations where version = 9;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v10_schema(pool: &sqlx::PgPool) {
|
||||
remove_v11_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists approval_requests_pending_scope_fingerprint_idx;
|
||||
drop index if exists approval_requests_workspace_request_trace_idx;
|
||||
alter table approval_requests drop constraint if exists approval_requests_request_id_check;
|
||||
alter table approval_requests drop constraint if exists approval_requests_trace_id_check;
|
||||
alter table approval_requests drop column if exists request_id;
|
||||
alter table approval_requests drop column if exists trace_id;
|
||||
create unique index if not exists approval_requests_pending_fingerprint_idx
|
||||
on approval_requests(agent_id, operation_id, operation_version, request_fingerprint)
|
||||
where status = 'pending' and request_fingerprint is not null;
|
||||
delete from __crank_migrations where version = 10;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
remove_v12_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_selections;
|
||||
drop trigger if exists product_events_append_only_guard on product_events;
|
||||
drop function if exists crank_reject_product_event_mutation();
|
||||
drop table if exists product_event_daily_rollups;
|
||||
drop table if exists product_events;
|
||||
drop index if exists invocation_logs_workspace_agent_key_success_idx;
|
||||
alter table invocation_logs drop constraint if exists invocation_logs_platform_key_scope_fk;
|
||||
alter table invocation_logs drop column if exists platform_api_key_id;
|
||||
alter table platform_api_keys drop constraint if exists platform_api_keys_workspace_agent_id_unique;
|
||||
delete from __crank_migrations where version = 11;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
drop table if exists import_plans;
|
||||
drop function if exists crank_reject_import_plan_mutation();
|
||||
alter table import_jobs drop constraint if exists import_jobs_workspace_id_unique;
|
||||
delete from __crank_migrations where version = 14;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v15_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_import_selections;
|
||||
alter table operations drop constraint if exists operations_workspace_id_unique;
|
||||
alter table product_events drop constraint if exists product_events_name_check;
|
||||
alter table product_events add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
alter table product_event_daily_rollups drop constraint if exists product_event_daily_rollups_name_check;
|
||||
alter table product_event_daily_rollups add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
delete from __crank_migrations where version = 15;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
drop index if exists import_jobs_expires_at_idx;
|
||||
drop index if exists artifact_sources_openapi_dangling_idx;
|
||||
drop index if exists artifact_sources_blob_lifecycle_detached_idx;
|
||||
drop index if exists artifact_blobs_expired_claim_idx;
|
||||
delete from __crank_migrations where version = 13;
|
||||
drop table if exists artifact_sources;
|
||||
drop table if exists artifact_blobs;
|
||||
delete from __crank_migrations where version = 12;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
mod dependent_source_fks;
|
||||
mod exhaustive_v12;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -31,7 +32,7 @@ async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -130,8 +131,22 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
drop function unrelated_trigger_fn();",
|
||||
),
|
||||
(
|
||||
"alter table artifact_sources set unlogged;",
|
||||
"alter table artifact_sources set logged;",
|
||||
// V16 добавил `resource_versions_source_fkey`, а V17 —
|
||||
// `resource_publications_source_fkey`: обе logged-таблицы ссылаются на
|
||||
// `artifact_sources`, поэтому PostgreSQL больше не переводит её в unlogged
|
||||
// (`42P16`). Тот же класс дрейфа (persistence отношения, его проверяет
|
||||
// `schema_guard_v12`) снимает блокирующие ссылки на время дрейфа и
|
||||
// возвращает их при восстановлении.
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;
|
||||
alter table artifact_sources set unlogged;",
|
||||
"alter table artifact_sources set logged;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);
|
||||
alter table resource_publications add constraint resource_publications_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
(
|
||||
"alter table artifact_sources drop constraint artifact_sources_id_check;
|
||||
@@ -162,7 +177,7 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -215,7 +230,7 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -451,6 +466,33 @@ async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String,
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Определение constraint **указанного отношения** текущей схемы; `None`, если его нет.
|
||||
///
|
||||
/// Отношение обязательно параметром: без него одноимённый объект другой таблицы
|
||||
/// (или другой схемы) мог бы молча подменить результат, а «однозначность» —
|
||||
/// это проверяемое свойство (R-C), а не предположение вызывающего.
|
||||
async fn constraint_definition(pool: &sqlx::PgPool, relation: &str, name: &str) -> Option<String> {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
|
||||
)
|
||||
.bind(relation)
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("a constraint definition must be queryable");
|
||||
assert!(
|
||||
definitions.len() <= 1,
|
||||
"constraint `{name}` on `{relation}` must resolve to exactly one definition, \
|
||||
observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions.into_iter().next()
|
||||
}
|
||||
|
||||
async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
@@ -465,7 +507,7 @@ async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -656,6 +698,50 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_v12_drift(&pool, drift, &restore).await;
|
||||
} else if constraint == "artifact_sources_pkey" {
|
||||
// V16/V17 добавили `resource_versions_source_fkey` и
|
||||
// `resource_publications_source_fkey`, которые физически опираются на
|
||||
// pkey-индекс `artifact_sources_pkey`. Чтобы дрейф «constraint отсутствует»
|
||||
// был исполнимым, блокирующие ссылки снимаются на время дрейфа и
|
||||
// возвращаются при восстановлении — тот же приём, что для `artifact_blobs_pkey`.
|
||||
let draft_dependent =
|
||||
constraint_definition(&pool, "resource_versions", "resource_versions_source_fkey")
|
||||
.await;
|
||||
let publication_dependent = constraint_definition(
|
||||
&pool,
|
||||
"resource_publications",
|
||||
"resource_publications_source_fkey",
|
||||
)
|
||||
.await;
|
||||
let mut drift = String::new();
|
||||
if draft_dependent.is_some() {
|
||||
drift.push_str(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n",
|
||||
);
|
||||
}
|
||||
if publication_dependent.is_some() {
|
||||
drift.push_str(
|
||||
"alter table resource_publications drop constraint \
|
||||
resource_publications_source_fkey;\n",
|
||||
);
|
||||
}
|
||||
drift.push_str("alter table artifact_sources drop constraint artifact_sources_pkey;");
|
||||
let mut restore = format!(
|
||||
"alter table artifact_sources add constraint artifact_sources_pkey {definition};\n"
|
||||
);
|
||||
if let Some(definition_of_fk) = draft_dependent {
|
||||
restore.push_str(&format!(
|
||||
"alter table resource_versions add constraint resource_versions_source_fkey \
|
||||
{definition_of_fk};\n"
|
||||
));
|
||||
}
|
||||
if let Some(definition_of_fk) = publication_dependent {
|
||||
restore.push_str(&format!(
|
||||
"alter table resource_publications add constraint \
|
||||
resource_publications_source_fkey {definition_of_fk};"
|
||||
));
|
||||
}
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} drop constraint {constraint};");
|
||||
let restore = format!("alter table {table} add constraint {constraint} {definition};");
|
||||
@@ -740,3 +826,61 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4 (V16 guard): шесть однофакторных мутаций определения и проверка выбора
|
||||
// зависимого FK/created index по текущей схеме перенесены в подмодуль
|
||||
// `artifact_metadata/exhaustive_v12.rs` — там же живёт разрешённый helper
|
||||
// `dependent_source_fk_definition`, и health-правило ограничивает файл 1000 строками.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// V17 guard (Story 3.7): минимальные однофакторные мутации схемы публикаций.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn v17_guard_rejects_publication_schema_drift() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v17_guard_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
|
||||
for (drift, restore) in [
|
||||
(
|
||||
"alter table resource_publications add column raw_upload_filename text;",
|
||||
"alter table resource_publications drop column raw_upload_filename;",
|
||||
),
|
||||
(
|
||||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||||
check (true);",
|
||||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||||
),
|
||||
(
|
||||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||||
foreign key (workspace_id, artifact_source_id) \
|
||||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||||
foreign key (workspace_id, artifact_source_id) \
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
] {
|
||||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||||
assert_eq!(error.version(), Some(17), "drift: {drift}");
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
//! Test-support: определения FK, зависящих от `artifact_sources_pkey`.
|
||||
//!
|
||||
//! Вынесено из `exhaustive_v12.rs`, чтобы legacy-файл не превышал health-лимит
|
||||
//! 1000 строк после добавления V17-ссылки.
|
||||
|
||||
/// Определение V16-ссылки `resource_versions_source_fkey`, которая зависит от
|
||||
/// `artifact_sources_pkey`. Снимок V12 её не содержит (helper фильтрует две
|
||||
/// artifact-таблицы), поэтому дрейф pkey снимает и возвращает её отдельно.
|
||||
///
|
||||
/// R-C: имя разрешается вместе с **текущей схемой и конкретным отношением** —
|
||||
/// одноимённый FK другой схемы не должен попадать в результат; однозначность
|
||||
/// результата проверяется явно, а не предполагается вызывающим.
|
||||
pub(super) async fn dependent_source_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the V16 foreign key that depends on artifact_sources_pkey must be captured");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the dependent V16 foreign key must resolve to exactly one definition in the current \
|
||||
schema, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one dependent definition was asserted above")
|
||||
}
|
||||
|
||||
/// Определение V17-ссылки `resource_publications_source_fkey`, которая также зависит от
|
||||
/// `artifact_sources_pkey`.
|
||||
pub(super) async fn dependent_publication_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_publications'
|
||||
and c.conname = 'resource_publications_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the V17 foreign key that depends on artifact_sources_pkey must be captured");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the dependent V17 foreign key must resolve to exactly one definition in the current \
|
||||
schema, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one dependent definition was asserted above")
|
||||
}
|
||||
+548
-4
@@ -1,5 +1,18 @@
|
||||
//! Исчерпывающие проверки дрейфа схемы: V12 (типы/дефолты/nullability/определения
|
||||
//! constraints и индексов двух artifact-таблиц) и V16 (шесть однофакторных мутаций
|
||||
//! определения `resources`/`resource_versions` + выбор зависимого FK и created
|
||||
//! index по текущей схеме).
|
||||
//!
|
||||
//! Модуль держит проверки V16 по текущей схеме; определения зависимых
|
||||
//! FK-хелперов вынесены в `dependent_source_fks.rs`, чтобы оба файла оставались
|
||||
//! в пределах health-лимита 1000 строк.
|
||||
|
||||
use crank_registry::{MigrationAuthority, MigrationPreflight};
|
||||
|
||||
use super::dependent_source_fks::{
|
||||
dependent_publication_fk_definition, dependent_source_fk_definition,
|
||||
};
|
||||
|
||||
// V12 changed-type coverage. Every column gets a reachable `alter column ...
|
||||
// type` drift whose `information_schema.data_type` differs from the frozen
|
||||
// guard expectation, plus the exact expression that puts the original type
|
||||
@@ -276,7 +289,7 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"a rejected primary-key nullability change must leave the schema current"
|
||||
);
|
||||
|
||||
@@ -303,20 +316,52 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
|
||||
let pkey = definitions
|
||||
.get("artifact_sources_pkey")
|
||||
.expect("artifact_sources primary key definition must be captured");
|
||||
let fk = dependent_source_fk_definition(pool).await;
|
||||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||||
(
|
||||
format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources alter column {column} drop not null;"
|
||||
),
|
||||
format!(
|
||||
"alter table artifact_sources alter column {column} set not null;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};"
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
),
|
||||
)
|
||||
};
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
/// Определение одноимённого FK схемы-«тени» (`story36_guard_shadow`), если она создана.
|
||||
async fn shadow_source_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = 'story36_guard_shadow'
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the shadow constraint must be readable");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the shadow foreign key must resolve to exactly one definition, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one shadow definition was asserted above")
|
||||
}
|
||||
|
||||
pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
CONSTRAINT_DEFINITION_DRIFT.len(),
|
||||
@@ -345,6 +390,26 @@ pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else if *constraint == "artifact_sources_pkey" {
|
||||
let fk = dependent_source_fk_definition(pool).await;
|
||||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||||
let drift = format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {drift_definition};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {original};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
@@ -408,7 +473,7 @@ async fn assert_definition_only_drift(
|
||||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -424,3 +489,482 @@ async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4 (affected ATDD до исправления): V16 guard обязан сверять семантику
|
||||
// constraints и полную структуру created index, а не только имя и contype.
|
||||
// Источник: CORRECTION-PACKAGE P4 (TL F06, ARC «отдельный FK lookup»).
|
||||
// Блок перенесён из `artifact_metadata.rs` (health-правило ограничивает файл
|
||||
// 1000 строками) вместе с разрешённым helper-ом `dependent_source_fk_definition`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Полный снимок определений, которыми оперирует V16 guard, снятый из `pg_catalog`.
|
||||
///
|
||||
/// Снимок **независим** от `MigrationAuthority::preflight`: он отвечает на вопрос
|
||||
/// «каталог действительно восстановлен», а не «guard считает его правильным». Именно
|
||||
/// поэтому он нужен для возврата V16-мутаций: тот же guard принимает все шесть
|
||||
/// неправильных определений, и `Current { version: 18 }` не доказывает точное
|
||||
/// восстановление (TL review run105 F4).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct DefinitionSnapshot {
|
||||
/// Все constraints трёх отношений: `(имя, contype, pg_get_constraintdef)`.
|
||||
constraints: Vec<(String, String, String)>,
|
||||
/// Структура created index (колонки, предикат, определение); `None` — индекса нет.
|
||||
created_index: Option<String>,
|
||||
}
|
||||
|
||||
async fn catalog_definition_snapshot(pool: &sqlx::PgPool) -> DefinitionSnapshot {
|
||||
let constraints = sqlx::query_as::<_, (String, String, String)>(
|
||||
"select c.conname::text, c.contype::text, pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('resources', 'resource_versions', 'artifact_sources')
|
||||
order by c.conname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the definition snapshot must be readable");
|
||||
let created_index = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_indexdef(i.indexrelid) || ' [valid=' || i.indisvalid::text
|
||||
|| ', ready=' || i.indisready::text || ']'
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'resources_workspace_created_idx'",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.expect("the created index definition must be observable");
|
||||
DefinitionSnapshot {
|
||||
constraints,
|
||||
created_index,
|
||||
}
|
||||
}
|
||||
|
||||
/// One-factor V16 drift: имя и contype сохраняются, меняется только определение.
|
||||
/// Ожидание — specific preflight refusal (partial_sequence, version 16); точное
|
||||
/// восстановление исходного определения обязано вернуть `Current { version: 18 }`.
|
||||
#[tokio::test]
|
||||
async fn story36_v16_guard_rejects_constraint_and_created_index_definition_drift() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v16_definition_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"the baseline before the drift matrix must be the current V16 schema"
|
||||
);
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
let mut unrejected: Vec<&str> = Vec::new();
|
||||
|
||||
for (label, drift, restore) in [
|
||||
(
|
||||
"weakened-check",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len check (true);",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
(
|
||||
"wrong-fk-columns-and-target",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id) references workspaces(id) on delete cascade;",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade;",
|
||||
),
|
||||
(
|
||||
"not-valid-fk",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) not valid;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
(
|
||||
"fk-delete-action",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete restrict;",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade;",
|
||||
),
|
||||
(
|
||||
"created-index-predicate",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id) where status = 'draft';",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);",
|
||||
),
|
||||
(
|
||||
"created-index-extra-column",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id, kind);",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);",
|
||||
),
|
||||
// F5 (TL run109 CODE-REVIEW): CHECK, который остаётся синтаксически
|
||||
// «похожим» (содержит ожидаемый фрагмент), но ослаблен до всегда-истинного,
|
||||
// обязан быть отвергнут: сверка подстрок вместо семантики его пропускает.
|
||||
(
|
||||
"weakened-check-with-original-snippet",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024 or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
// F5: `NOT VALID` CHECK сохраняет выражение, поэтому дрейф наблюдается только
|
||||
// через `convalidated`; guard обязан читать признак валидации, а не только текст.
|
||||
(
|
||||
"not-valid-check",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024) not valid;",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
// F5: у FK сверяются точные target/columns/actions, а не только префикс
|
||||
// определения: `ON DELETE CASCADE` на source-FK — дрейф, а не вариант нормы.
|
||||
(
|
||||
"source-fk-delete-action",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
// F5: deferrability — часть определения FK и тоже обязана быть точной.
|
||||
(
|
||||
"source-fk-deferrable",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id)
|
||||
deferrable initially deferred;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
// R2 (TL run113 EH1/IA2): перечисляющий CHECK обязан отвергаться, если к нему
|
||||
// добавлен любой другой предикат. Множество строковых литералов при этом
|
||||
// остаётся ожидаемым, поэтому сверка «по набору значений» такой дрейф
|
||||
// пропускает, хотя ограничение ослаблено до всегда-истинного (колонка в
|
||||
// добавленном предикате объявлена `not null`). Обе таблицы и все четыре
|
||||
// перечисления V16 принадлежат одной границе F5.
|
||||
(
|
||||
"enum-check-with-or-predicate-resources-kind",
|
||||
"alter table resources drop constraint resources_kind_check;
|
||||
alter table resources add constraint resources_kind_check
|
||||
check (kind in ('text', 'json', 'binary') or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_kind_check;
|
||||
alter table resources add constraint resources_kind_check
|
||||
check (kind in ('text', 'json', 'binary'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-resources-status",
|
||||
"alter table resources drop constraint resources_status_check;
|
||||
alter table resources add constraint resources_status_check
|
||||
check (status in ('draft', 'published', 'archived') or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_status_check;
|
||||
alter table resources add constraint resources_status_check
|
||||
check (status in ('draft', 'published', 'archived'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-version-kind",
|
||||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||||
alter table resource_versions add constraint resource_versions_kind_check
|
||||
check (kind in ('text', 'json', 'binary') or workspace_id is not null);",
|
||||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||||
alter table resource_versions add constraint resource_versions_kind_check
|
||||
check (kind in ('text', 'json', 'binary'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-version-sensitivity",
|
||||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||||
check (sensitivity in ('public', 'internal', 'secret') or workspace_id is not null);",
|
||||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||||
),
|
||||
// R2 (TL run113 EH2): нормализация, удаляющая пробелы ВНУТРИ строкового
|
||||
// литерала, делает ослабленный regex неотличимым от канонического: класс
|
||||
// `[0-9a-f ]` допускает пробельные символы в 64-символьном digest.
|
||||
(
|
||||
"digest-literal-space-drift",
|
||||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||||
alter table resource_versions add constraint resource_versions_digest_check
|
||||
check (digest ~ '^[0-9a-f ]{64}$');",
|
||||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||||
alter table resource_versions add constraint resource_versions_digest_check
|
||||
check (digest ~ '^[0-9a-f]{64}$');",
|
||||
),
|
||||
// R2: смена регистра ВНУТРИ литерала — такое же ослабление (uppercase MIME
|
||||
// перестаёт приниматься), но после приведения к нижнему регистру строка
|
||||
// совпадает с канонической.
|
||||
(
|
||||
"mime-literal-case-drift",
|
||||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||||
check (octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[a-za-z0-9!#$&^_.+-]+/[a-za-z0-9!#$&^_.+-]+$');",
|
||||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||||
check (octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$');",
|
||||
),
|
||||
] {
|
||||
// Снимок каталога берётся независимо от guard-а: он нужен и чтобы подтвердить,
|
||||
// что мутация реально изменила определения, и чтобы доказать точное
|
||||
// восстановление после неё (F4).
|
||||
let before = catalog_definition_snapshot(&pool).await;
|
||||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||||
let drifted = catalog_definition_snapshot(&pool).await;
|
||||
let drift_observed = drifted != before;
|
||||
// Каждый вектор исполняется независимо: отказ фиксируется наблюдением, а не паникой,
|
||||
// поэтому следующие пять мутаций не пропускаются из-за первого расхождения (R-C).
|
||||
let refusal = match MigrationAuthority::preflight(&pool).await {
|
||||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16) => {
|
||||
format!(
|
||||
"refused code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
unrejected.push(label);
|
||||
format!(
|
||||
"unexpected refusal code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
)
|
||||
}
|
||||
Ok(state) => {
|
||||
unrejected.push(label);
|
||||
format!("accepted {state:?}")
|
||||
}
|
||||
};
|
||||
// Восстановление выполняется всегда — и при подтверждённом отказе, и при расхождении.
|
||||
sqlx::raw_sql(restore)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("restoring the exact definition must apply");
|
||||
let restored = MigrationAuthority::preflight(&pool).await;
|
||||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 23 }));
|
||||
// Точное восстановление доказывается сравнением снятого снимка с baseline, а не
|
||||
// мнением того же guard-а, который принимает неправильные определения (F4).
|
||||
let restored_exact = catalog_definition_snapshot(&pool).await == before;
|
||||
if !restored_current || !restored_exact || !drift_observed {
|
||||
unrejected.push(label);
|
||||
}
|
||||
observations.push(format!(
|
||||
"{label}: {refusal}; drift_observed={drift_observed}; \
|
||||
restored_current16={restored_current}; restored_exact={restored_exact}"
|
||||
));
|
||||
}
|
||||
assert!(
|
||||
unrejected.is_empty(),
|
||||
"every one-factor V16 definition drift must really change the captured catalog, be \
|
||||
refused with a specific preflight error and be restored to the exact captured baseline; \
|
||||
observations: {observations:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// R-C: зависимый V16 FK разрешается по **текущей схеме и своему отношению**, а не
|
||||
/// по одному имени. Одноимённый валидный FK другой схемы не должен ни подменять
|
||||
/// результат, ни маскировать настоящий дрейф, а восстановление обязано вернуть
|
||||
/// снятое ранее определение байт-в-байт (не «Current16 при слабом guard»).
|
||||
#[tokio::test]
|
||||
async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v16_schema_scope").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"baseline before inserting the shadow schema"
|
||||
);
|
||||
|
||||
// Снимок канонической ссылки текущей схемы (baseline восстановления).
|
||||
let canonical = dependent_source_fk_definition(&pool).await;
|
||||
assert!(
|
||||
canonical.contains("artifact_sources") && !canonical.contains("NOT VALID"),
|
||||
"the canonical dependent reference must be the validated V16 foreign key: {canonical}"
|
||||
);
|
||||
|
||||
// Схема-«тень»: то же имя FK, другое, но валидное определение; плюс одноимённый
|
||||
// created index, чтобы проверить и выбор индекса по текущей схеме.
|
||||
sqlx::raw_sql(
|
||||
"create schema story36_guard_shadow;
|
||||
create table story36_guard_shadow.artifact_sources (
|
||||
workspace_id text not null,
|
||||
source_id text not null,
|
||||
primary key (workspace_id, source_id)
|
||||
);
|
||||
create table story36_guard_shadow.resource_versions (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
artifact_source_id text not null
|
||||
);
|
||||
alter table story36_guard_shadow.resource_versions
|
||||
add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references story36_guard_shadow.artifact_sources(workspace_id, source_id)
|
||||
on delete restrict;
|
||||
create table story36_guard_shadow.resources (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
created_at timestamptz not null,
|
||||
kind text not null,
|
||||
status text not null,
|
||||
primary key (workspace_id, resource_id)
|
||||
);
|
||||
create index resources_workspace_created_idx
|
||||
on story36_guard_shadow.resources (workspace_id, created_at, resource_id)
|
||||
where status = 'draft';",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the shadow schema with same-named objects must be creatable");
|
||||
|
||||
let shadow = shadow_source_fk_definition(&pool).await;
|
||||
assert_ne!(
|
||||
shadow, canonical,
|
||||
"the shadow constraint must really differ from the canonical definition"
|
||||
);
|
||||
assert!(
|
||||
shadow.contains("story36_guard_shadow") && shadow.contains("ON DELETE RESTRICT"),
|
||||
"the shadow constraint must point at its own schema and carry its own action: {shadow}"
|
||||
);
|
||||
|
||||
// Helper обязан вернуть определение текущей схемы — даже при существующей тени.
|
||||
let resolved = dependent_source_fk_definition(&pool).await;
|
||||
assert_eq!(
|
||||
resolved, canonical,
|
||||
"the dependent FK must be resolved from the current schema, not from a same-named \
|
||||
constraint of another schema"
|
||||
);
|
||||
assert!(
|
||||
!resolved.contains("story36_guard_shadow"),
|
||||
"the shadow constraint must never leak into the helper result: {resolved}"
|
||||
);
|
||||
|
||||
// Тень не меняет вердикт guard-а по текущей схеме.
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"a same-named object in another schema must not change the verdict for the current schema"
|
||||
);
|
||||
|
||||
// Настоящий дрейф текущей схемы: ссылка перестаёт быть валидной (NOT VALID).
|
||||
sqlx::raw_sql(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) not valid;",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the one-factor NOT VALID drift must be applicable");
|
||||
|
||||
let drifted = dependent_source_fk_definition(&pool).await;
|
||||
assert!(
|
||||
drifted.contains("NOT VALID"),
|
||||
"the drift must be observable in the catalog: {drifted}"
|
||||
);
|
||||
let validation: bool = sqlx::query_scalar(
|
||||
"select c.convalidated
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("the drift must be observable through pg_constraint");
|
||||
assert!(
|
||||
!validation,
|
||||
"the drifted reference must be recorded as not validated"
|
||||
);
|
||||
|
||||
// Наблюдение вместо паники: следующий assertion не должен прерывать восстановление.
|
||||
let verdict = MigrationAuthority::preflight(&pool).await;
|
||||
let refused_with_specific_error = matches!(
|
||||
&verdict,
|
||||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16)
|
||||
);
|
||||
let observation = match &verdict {
|
||||
Err(error) => format!(
|
||||
"refused code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
),
|
||||
Ok(state) => format!("accepted {state:?}"),
|
||||
};
|
||||
|
||||
// Точное восстановление снятого определения — не по вердикту guard-а, а по снимку.
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {canonical};"
|
||||
)))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("restoring the captured definition must apply");
|
||||
assert_eq!(
|
||||
dependent_source_fk_definition(&pool).await,
|
||||
canonical,
|
||||
"restoration must return the byte-exact definition captured before the drift"
|
||||
);
|
||||
assert_eq!(
|
||||
shadow_source_fk_definition(&pool).await,
|
||||
shadow,
|
||||
"the shadow definition must stay byte-identical through drift and restoration"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"the exact restoration must return the current V16 schema"
|
||||
);
|
||||
|
||||
// Уборка: без схемы-тени текущая схема по-прежнему V16.
|
||||
sqlx::raw_sql("drop schema story36_guard_shadow cascade;")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
|
||||
assert!(
|
||||
refused_with_specific_error,
|
||||
"a real drift of the dependent source FK in the current schema must be refused with \
|
||||
partial_sequence/16 even while a same-named FK exists in another schema; observed \
|
||||
`{observation}` (source-id affected: R-C)"
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let tables = sqlx::query(
|
||||
"select table_name
|
||||
@@ -224,7 +224,7 @@ async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 13,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
|
||||
@@ -88,7 +88,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -101,7 +101,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
assert_eq!(operation_count, 1);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -230,7 +230,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -280,7 +280,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
assert!(supports_elicitation);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Story 3.8: V19 immutable Resource security revocations — migration evidence.
|
||||
//!
|
||||
//! Fresh install, upgrade from V18 without rewriting the prior ledger, schema
|
||||
//! drift detection, failed-DDL rollback and the fail-closed future-version gate
|
||||
//! (the path an old binary takes when it meets a database newer than itself).
|
||||
|
||||
use super::*;
|
||||
use crank_registry::MigrationApplyResult;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fresh_install_creates_the_empty_revocation_authority() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_fresh_install").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let rows: i64 = sqlx::query_scalar("select count(*) from resource_security_revocations")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("V19 table must be queryable after a fresh install");
|
||||
assert_eq!(
|
||||
rows, 0,
|
||||
"an empty authoritative table must preserve the previous (unrevoked) behaviour; \
|
||||
no data backfill or mass migration is allowed"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v18_upgrades_to_v19_without_rewriting_the_prior_ledger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_upgrade").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let before: Vec<(i64, String, String)> =
|
||||
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
remove_v19_schema(&pool).await;
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::apply(&pool).await.unwrap(),
|
||||
MigrationApplyResult::Applied { from: 18, to: 23 }
|
||||
);
|
||||
let after: Vec<(i64, String, String)> =
|
||||
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(before, after, "V16–V18 ledger rows must not be rewritten");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v19_guard_rejects_a_missing_revocation_trigger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_trigger_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"drop trigger resource_security_revocations_immutable_guard
|
||||
on resource_security_revocations",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V19 trigger must be droppable for the drift fixture");
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.version(), Some(19));
|
||||
assert_eq!(error.stage(), "v19.immutable_trigger");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_database_newer_than_the_binary_fails_closed_at_startup() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_future_version").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
// The same `version > CURRENT_VERSION` branch an old V23 binary takes when it
|
||||
// meets a V24 database; a synthetic V24 row exercises it without a second binary.
|
||||
sqlx::query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values (24, 'future-v24', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "future_version");
|
||||
assert_eq!(error.version(), Some(24));
|
||||
assert_eq!(error.recovery(), "install_matching_application");
|
||||
assert!(
|
||||
MigrationAuthority::require_current(&pool).await.is_err(),
|
||||
"startup must refuse a newer database instead of serving with unknown schema"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_v19_migration_rolls_back_schema_and_ledger() {
|
||||
let _event_trigger_guard = EVENT_TRIGGER_TEST_LOCK.lock().await;
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_rollback").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
remove_v19_schema(&pool).await;
|
||||
let schema: String = sqlx::query_scalar("select current_schema()")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let failure_trigger = format!(
|
||||
"create function reject_story38_v19() returns event_trigger language plpgsql as $$
|
||||
begin
|
||||
if current_schema() = '{schema}' and current_query() like '%resource_security_revocations%' then
|
||||
raise exception 'injected v19 ddl failure';
|
||||
end if;
|
||||
end $$;
|
||||
create event trigger reject_story38_v19 on ddl_command_start
|
||||
execute function reject_story38_v19();"
|
||||
);
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(failure_trigger))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::apply(&pool).await.unwrap_err();
|
||||
sqlx::raw_sql(
|
||||
"drop event trigger reject_story38_v19;
|
||||
drop function reject_story38_v19();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(error.code(), "apply_failed");
|
||||
assert_eq!(error.version(), Some(19));
|
||||
let present: bool = sqlx::query_scalar(
|
||||
"select to_regclass(format('%I.%I', current_schema(), 'resource_security_revocations')) is not null",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!present, "failed V19 DDL must roll the table back");
|
||||
let ledger_v19: i64 =
|
||||
sqlx::query_scalar("select count(*) from __crank_migrations where version = 19")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ledger_v19, 0);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -63,7 +63,7 @@ async fn failed_artifact_metadata_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Тестовые helpers, возвращающие приватную схему к состоянию до конкретной
|
||||
//! миграции (вынесены из `migrations.rs`, чтобы файл оставался в пределах
|
||||
//! rust-code-health); поведение не меняется.
|
||||
|
||||
pub(crate) async fn remove_v3_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_request_id_idx;
|
||||
alter table invocation_logs drop column if exists trace_id;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v4_schema(pool: &sqlx::PgPool) {
|
||||
remove_v5_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists operation_versions_immutable_guard on operation_versions;
|
||||
drop function if exists crank_guard_operation_version_immutable();
|
||||
drop trigger if exists published_operations_monotonic_guard on published_operations;
|
||||
drop function if exists crank_guard_published_operation_pointer();
|
||||
drop trigger if exists operations_latest_pointer_monotonic_guard on operations;
|
||||
drop function if exists crank_guard_operation_latest_pointer();
|
||||
alter table operation_versions
|
||||
drop constraint if exists operation_versions_snapshot_provenance_check,
|
||||
drop column if exists name,
|
||||
drop column if exists display_name,
|
||||
drop column if exists category,
|
||||
drop column if exists protocol,
|
||||
drop column if exists security_level,
|
||||
drop column if exists snapshot_provenance,
|
||||
drop column if exists snapshot_observed_at,
|
||||
drop column if exists published_at,
|
||||
drop column if exists published_by;
|
||||
delete from __crank_migrations where version = 4;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v5_schema(pool: &sqlx::PgPool) {
|
||||
remove_v6_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_operation_version_idx;
|
||||
alter table invocation_logs
|
||||
drop column if exists operation_version,
|
||||
drop column if exists execution_stage,
|
||||
drop column if exists execution_error_code,
|
||||
drop column if exists retryability,
|
||||
drop column if exists outcome_certainty;
|
||||
delete from __crank_migrations where version = 5;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v6_schema(pool: &sqlx::PgPool) {
|
||||
remove_v7_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists platform_api_keys_workspace_name_active_idx;
|
||||
create unique index if not exists platform_api_keys_workspace_name_idx on platform_api_keys(workspace_id, name);
|
||||
delete from __crank_migrations where version = 6;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v7_schema(pool: &sqlx::PgPool) {
|
||||
remove_v8_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"alter table secret_versions drop constraint if exists secret_versions_target_all_or_none_check,
|
||||
drop constraint if exists secret_versions_target_epoch_check,
|
||||
drop constraint if exists secret_versions_master_key_epoch_check,
|
||||
drop column if exists target_master_key_epoch, drop column if exists target_key_version,
|
||||
drop column if exists target_ciphertext, drop column if exists master_key_epoch;
|
||||
drop table if exists master_key_rotations;
|
||||
drop table if exists master_key_identities;
|
||||
delete from __crank_migrations where version = 7;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v8_schema(pool: &sqlx::PgPool) {
|
||||
remove_v9_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists admin_security_audit_events;
|
||||
drop table if exists admin_login_backoff;
|
||||
drop table if exists admin_bootstrap_contracts;
|
||||
alter table user_sessions
|
||||
drop constraint if exists user_sessions_csrf_hash_check,
|
||||
drop column if exists csrf_hash,
|
||||
drop column if exists revoked_at;
|
||||
delete from __crank_migrations where version = 8;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v9_schema(pool: &sqlx::PgPool) {
|
||||
remove_v10_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists published_agents_monotonic_guard on published_agents;
|
||||
drop function if exists crank_reject_published_agent_pointer_rewind();
|
||||
drop trigger if exists agent_operation_bindings_immutable_guard on agent_operation_bindings;
|
||||
drop function if exists crank_reject_published_agent_binding_mutation();
|
||||
drop trigger if exists agent_versions_immutable_guard on agent_versions;
|
||||
drop function if exists crank_reject_published_agent_version_mutation();
|
||||
alter table published_agents
|
||||
drop constraint if exists published_agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
alter table agents
|
||||
drop constraint if exists agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
delete from __crank_migrations where version = 9;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v10_schema(pool: &sqlx::PgPool) {
|
||||
remove_v11_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists approval_requests_pending_scope_fingerprint_idx;
|
||||
drop index if exists approval_requests_workspace_request_trace_idx;
|
||||
alter table approval_requests drop constraint if exists approval_requests_request_id_check;
|
||||
alter table approval_requests drop constraint if exists approval_requests_trace_id_check;
|
||||
alter table approval_requests drop column if exists request_id;
|
||||
alter table approval_requests drop column if exists trace_id;
|
||||
create unique index if not exists approval_requests_pending_fingerprint_idx
|
||||
on approval_requests(agent_id, operation_id, operation_version, request_fingerprint)
|
||||
where status = 'pending' and request_fingerprint is not null;
|
||||
delete from __crank_migrations where version = 10;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
remove_v12_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_selections;
|
||||
drop trigger if exists product_events_append_only_guard on product_events;
|
||||
drop function if exists crank_reject_product_event_mutation();
|
||||
drop table if exists product_event_daily_rollups;
|
||||
drop table if exists product_events;
|
||||
drop index if exists invocation_logs_workspace_agent_key_success_idx;
|
||||
alter table invocation_logs drop constraint if exists invocation_logs_platform_key_scope_fk;
|
||||
alter table invocation_logs drop column if exists platform_api_key_id;
|
||||
alter table platform_api_keys drop constraint if exists platform_api_keys_workspace_agent_id_unique;
|
||||
delete from __crank_migrations where version = 11;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
drop table if exists import_plans;
|
||||
drop function if exists crank_reject_import_plan_mutation();
|
||||
alter table import_jobs drop constraint if exists import_jobs_workspace_id_unique;
|
||||
delete from __crank_migrations where version = 14;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v15_schema(pool: &sqlx::PgPool) {
|
||||
remove_v16_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_import_selections;
|
||||
alter table operations drop constraint if exists operations_workspace_id_unique;
|
||||
alter table product_events drop constraint if exists product_events_name_check;
|
||||
alter table product_events add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
alter table product_event_daily_rollups drop constraint if exists product_event_daily_rollups_name_check;
|
||||
alter table product_event_daily_rollups add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
delete from __crank_migrations where version = 15;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v16_schema(pool: &sqlx::PgPool) {
|
||||
remove_v17_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_versions;
|
||||
drop index if exists resources_workspace_created_idx;
|
||||
drop table if exists resources;
|
||||
delete from __crank_migrations where version = 16;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v17_schema(pool: &sqlx::PgPool) {
|
||||
remove_v18_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_publications;
|
||||
drop index if exists resource_publications_workspace_uri_idx;
|
||||
delete from __crank_migrations where version = 17;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v18_schema(pool: &sqlx::PgPool) {
|
||||
remove_v19_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists agent_resource_bindings;
|
||||
drop function if exists crank_reject_published_agent_resource_binding_mutation();
|
||||
drop index if exists agent_resource_bindings_resource_idx;
|
||||
drop index if exists agents_workspace_id_idx;
|
||||
delete from __crank_migrations where version = 18;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v19_schema(pool: &sqlx::PgPool) {
|
||||
remove_v20_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_security_revocations;
|
||||
drop function if exists crank_reject_resource_security_revocation_mutation();
|
||||
delete from __crank_migrations where version = 19;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.16: снять V23 (version-keyed пины зависимостей Prompt) перед возвратом к < 23.
|
||||
pub(crate) async fn remove_v23_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists prompt_message_resource_refs;
|
||||
drop table if exists prompt_dependencies;
|
||||
delete from __crank_migrations where version = 23;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.13: снять V22 (Published Prompt Versions и typed Prompt bindings)
|
||||
/// перед возвратом к состоянию < 22.
|
||||
pub(crate) async fn remove_v22_schema(pool: &sqlx::PgPool) {
|
||||
remove_v23_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists agent_prompt_bindings;
|
||||
drop table if exists prompt_publications;
|
||||
drop trigger if exists prompt_arguments_immutable_guard on prompt_arguments;
|
||||
drop trigger if exists prompt_messages_immutable_guard on prompt_messages;
|
||||
alter table prompts drop constraint if exists prompts_latest_published_version_check;
|
||||
alter table prompts drop column if exists latest_published_version;
|
||||
drop function if exists crank_reject_published_prompt_version_mutation();
|
||||
drop function if exists crank_reject_prompt_publication_mutation();
|
||||
drop function if exists crank_reject_published_agent_prompt_binding_mutation();
|
||||
delete from __crank_migrations where version = 22;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.12: снять V21 (typed Prompt Drafts) перед возвратом к состоянию < 21.
|
||||
pub(crate) async fn remove_v21_schema(pool: &sqlx::PgPool) {
|
||||
remove_v22_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists prompt_messages;
|
||||
drop table if exists prompt_arguments;
|
||||
drop table if exists prompt_versions;
|
||||
drop table if exists prompts;
|
||||
delete from __crank_migrations where version = 21;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.10: обратная совместимость fixture-ов — снять V20 и вернуть V16/V17
|
||||
/// ограничения artifact-строк, чтобы схема соответствовала версии < 20.
|
||||
pub(crate) async fn remove_v20_schema(pool: &sqlx::PgPool) {
|
||||
remove_v21_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_template_sources;
|
||||
drop function if exists crank_guard_resource_template_source_immutable();
|
||||
alter table resource_versions drop constraint if exists resource_versions_source_kind_check;
|
||||
alter table resource_versions drop constraint if exists resource_versions_size_check;
|
||||
alter table resource_versions add constraint resource_versions_size_check check (size_bytes between 1 and 262144);
|
||||
alter table resource_versions drop constraint if exists resource_versions_source_id_check;
|
||||
alter table resource_versions add constraint resource_versions_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
|
||||
alter table resource_versions drop column if exists source_kind;
|
||||
alter table resource_versions alter column artifact_source_id set not null;
|
||||
alter table resource_publications drop constraint if exists resource_publications_source_kind_check;
|
||||
alter table resource_publications drop constraint if exists resource_publications_size_check;
|
||||
alter table resource_publications add constraint resource_publications_size_check check (size_bytes between 1 and 262144);
|
||||
alter table resource_publications drop constraint if exists resource_publications_source_id_check;
|
||||
alter table resource_publications add constraint resource_publications_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
|
||||
alter table resource_publications drop column if exists source_kind;
|
||||
alter table resource_publications alter column artifact_source_id set not null;
|
||||
delete from __crank_migrations where version = 20;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
drop index if exists import_jobs_expires_at_idx;
|
||||
drop index if exists artifact_sources_openapi_dangling_idx;
|
||||
drop index if exists artifact_sources_blob_lifecycle_detached_idx;
|
||||
drop index if exists artifact_blobs_expired_claim_idx;
|
||||
delete from __crank_migrations where version = 13;
|
||||
drop table if exists artifact_sources;
|
||||
drop table if exists artifact_blobs;
|
||||
delete from __crank_migrations where version = 12;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Story 3.16 / FR-18 на уровне реестра: version-keyed пины зависимостей Prompt.
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL и реальном artifact store, что контракт держится схемой и
|
||||
//! транзакциями, а не только JSON-ответом admin-api:
|
||||
//! - публикация Prompt сохраняет точную опубликованную версию Resource (resource_id, version,
|
||||
//! digest, kind, source_class, sensitivity) и объявленные точки вставки;
|
||||
//! - новая версия Resource не переписывает пины уже опубликованного Prompt;
|
||||
//! - guard-триггер запрещает менять строки пинов опубликованной версии напрямую через SQL;
|
||||
//! - dependency другого workspace неотличима от отсутствующей (`prompt_dependency_unresolved`);
|
||||
//! - dependency, на которую не ссылается ни одно сообщение, отклоняется до любого чтения
|
||||
//! (`prompt_dependency_unused`);
|
||||
//! - публикация хранит строгую (effective) sensitivity.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::{
|
||||
Workspace, WorkspaceId, WorkspaceStatus,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry, RegistryError,
|
||||
model::{
|
||||
CreatePromptDraftRequest, PublishPromptRequest,
|
||||
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-prompt-composition-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
}
|
||||
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database_url = crank_test_support::postgres_schema_url(&format!("story316_{name}")).await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("test schema must accept connections");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("registry must connect");
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
Sandbox {
|
||||
registry,
|
||||
store,
|
||||
_root: root,
|
||||
}
|
||||
}
|
||||
|
||||
/// Второй workspace того же реестра: dependency из него не адресуема.
|
||||
async fn create_foreign_workspace(registry: &PostgresRegistry) -> WorkspaceId {
|
||||
let workspace_id = WorkspaceId::new("ws_story316_foreign");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: "story316-foreign".to_owned(),
|
||||
display_name: "Story 3.16 foreign".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("foreign workspace must be created");
|
||||
workspace_id
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
/// Публикует static Resource в заданном workspace и возвращает точную опубликованную версию.
|
||||
async fn published_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
resource_id: &str,
|
||||
sensitivity: &str,
|
||||
bytes: &[u8],
|
||||
) -> (ResourceId, u32, String) {
|
||||
let id = ResourceId::new(resource_id);
|
||||
let registry = &sandbox.registry;
|
||||
if registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
// Новая опубликованная версия существующего Resource (Story 3.7 path).
|
||||
let current = registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.expect("current draft readable");
|
||||
registry
|
||||
.update_resource_draft(
|
||||
crank_registry::model::resource::UpdateResourceDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.clone(),
|
||||
description: "second version".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: sensitivity.to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(sandbox, bytes),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("second draft version must be creatable");
|
||||
} else {
|
||||
registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.clone(),
|
||||
uri: format!("crank://resources/{resource_id}"),
|
||||
name: resource_id.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: sensitivity.to_owned(),
|
||||
artifact: registered(sandbox, bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("resource draft must be created");
|
||||
}
|
||||
let current = registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
let publication = registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.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(),
|
||||
})
|
||||
.await
|
||||
.expect("published Resource version");
|
||||
(id, publication.version, publication.digest)
|
||||
}
|
||||
|
||||
fn composed_definition(
|
||||
dependencies: serde_json::Value,
|
||||
refs: serde_json::Value,
|
||||
) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "release-notes",
|
||||
"description": "Composed prompt",
|
||||
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
|
||||
"messages": [
|
||||
{"role": "system", "content": "Summarise only the attached document."},
|
||||
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": refs}
|
||||
],
|
||||
"dependencies": dependencies
|
||||
}))
|
||||
.expect("composed definition parses")
|
||||
}
|
||||
|
||||
async fn create_draft(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
prompt_id: &str,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
sensitivity,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt draft creates")
|
||||
}
|
||||
|
||||
async fn publish_draft(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
prompt_id: &str,
|
||||
expected_updated_at: time::OffsetDateTime,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
sandbox
|
||||
.registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
expected_updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt publishes")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_stores_version_keyed_pins_and_insertion_points() {
|
||||
let sandbox = sandbox("pins").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (resource, version, digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_pins",
|
||||
"internal",
|
||||
b"pinned body",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let created = create_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_pins",
|
||||
PromptSensitivity::Public,
|
||||
definition,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(created.dependencies.len(), 1);
|
||||
assert_eq!(created.dependencies[0].resource_id, resource.as_str());
|
||||
assert_eq!(created.dependencies[0].version, version);
|
||||
assert_eq!(created.dependencies[0].digest, digest);
|
||||
assert_eq!(created.dependencies[0].kind.as_str(), "text");
|
||||
assert_eq!(created.dependencies[0].source_class.as_str(), "static");
|
||||
assert_eq!(
|
||||
created.dependencies[0].sensitivity,
|
||||
PromptSensitivity::Internal
|
||||
);
|
||||
|
||||
let stored_version: i32 =
|
||||
sqlx::query_scalar("select resource_version from prompt_dependencies where prompt_id = $1")
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("pins are queryable");
|
||||
assert_eq!(stored_version, i32::try_from(version).unwrap());
|
||||
|
||||
let refs: i32 = sqlx::query_scalar(
|
||||
"select dependency_position from prompt_message_resource_refs where prompt_id = $1",
|
||||
)
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("insertion points are queryable");
|
||||
assert_eq!(refs, 0);
|
||||
|
||||
// AC3: публикация хранит строгую политику, локальное значение остаётся в prompts.
|
||||
let published = publish_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_pins",
|
||||
created.updated_at,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(published.prompt.status(), PromptStatus::Published);
|
||||
let publication_sensitivity: String = sqlx::query_scalar(
|
||||
"select sensitivity from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication is queryable");
|
||||
assert_eq!(publication_sensitivity, "internal");
|
||||
let local_sensitivity: String =
|
||||
sqlx::query_scalar("select sensitivity from prompts where prompt_id = $1")
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("local value is queryable");
|
||||
assert_eq!(
|
||||
local_sensitivity, "public",
|
||||
"the local value is not rewritten"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_pins_stay_immutable_after_a_new_resource_version() {
|
||||
let sandbox = sandbox("immutable").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (resource, version, digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_immutable",
|
||||
"internal",
|
||||
b"CHANGELOG v1",
|
||||
)
|
||||
.await;
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let created = create_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_immutable",
|
||||
PromptSensitivity::Internal,
|
||||
definition,
|
||||
)
|
||||
.await;
|
||||
publish_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_immutable",
|
||||
created.updated_at,
|
||||
)
|
||||
.await;
|
||||
|
||||
// Новая опубликованная версия того же Resource.
|
||||
let (_, second_version, second_digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_immutable",
|
||||
"internal",
|
||||
b"CHANGELOG v2",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(second_version, version + 1);
|
||||
assert_ne!(second_digest, digest);
|
||||
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.get_published_prompt_version(
|
||||
&workspace,
|
||||
&PromptId::new("prm_story316_immutable"),
|
||||
version,
|
||||
)
|
||||
.await
|
||||
.expect("published prompt version is readable");
|
||||
assert_eq!(
|
||||
publication.dependencies[0].version, version,
|
||||
"the publication keeps the exact pinned version"
|
||||
);
|
||||
assert_eq!(publication.dependencies[0].digest, digest);
|
||||
|
||||
// Guard опубликованной версии: прямая правка пина через SQL отклоняется.
|
||||
let update = sqlx::query(
|
||||
"update prompt_dependencies set resource_version = resource_version + 1 where prompt_id = $1",
|
||||
)
|
||||
.bind("prm_story316_immutable")
|
||||
.execute(sandbox.registry.pool())
|
||||
.await;
|
||||
assert!(
|
||||
update.is_err(),
|
||||
"a published pin must be immutable through SQL as well"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_cross_workspace_dependency_is_unresolved() {
|
||||
let sandbox = sandbox("foreign").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let foreign = create_foreign_workspace(&sandbox.registry).await;
|
||||
let (resource, version, _digest) = published_resource(
|
||||
&sandbox,
|
||||
&foreign,
|
||||
"res_story316_foreign",
|
||||
"internal",
|
||||
b"foreign body",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new("prm_story316_foreign"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a foreign dependency is not addressable");
|
||||
assert!(matches!(
|
||||
error,
|
||||
RegistryError::PromptDependencyUnresolved { position: 0, .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_unused_dependency_is_refused() {
|
||||
let sandbox = sandbox("unused").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (first, first_version, _) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_unused_a",
|
||||
"internal",
|
||||
b"first",
|
||||
)
|
||||
.await;
|
||||
let (second, second_version, _) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_unused_b",
|
||||
"internal",
|
||||
b"second",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([
|
||||
{"resource_id": first.as_str(), "version": first_version},
|
||||
{"resource_id": second.as_str(), "version": second_version}
|
||||
]),
|
||||
json!([0]),
|
||||
);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new("prm_story316_unused"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a dependency that no message references is refused");
|
||||
match error {
|
||||
RegistryError::PromptDependencyUnused {
|
||||
position,
|
||||
resource_id,
|
||||
version,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(position, 1);
|
||||
assert_eq!(resource_id, second.as_str());
|
||||
assert_eq!(version, second_version);
|
||||
}
|
||||
other => panic!("expected prompt_dependency_unused, got {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
use crank_core::{
|
||||
WorkspaceId,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
MigrationAuthority, PostgresRegistry,
|
||||
model::{CreatePromptDraftRequest, UpdatePromptDraftRequest},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WS: &str = "ws_default";
|
||||
|
||||
fn prompt(content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"name","schema":{"type":"string"},"required":true}],
|
||||
"messages":[{"role":"user","content":content}]
|
||||
}))
|
||||
.expect("valid typed definition")
|
||||
}
|
||||
|
||||
async fn registry_pool(label: &str) -> (PostgresRegistry, sqlx::PgPool) {
|
||||
let url = crank_test_support::postgres_schema_url(&format!("story312_{label}")).await;
|
||||
let pool = sqlx::PgPool::connect(&url)
|
||||
.await
|
||||
.expect("test postgres schema connects");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&url)
|
||||
.await
|
||||
.expect("registry connects");
|
||||
(registry, pool)
|
||||
}
|
||||
|
||||
async fn registry(label: &str) -> PostgresRegistry {
|
||||
registry_pool(label).await.0
|
||||
}
|
||||
|
||||
fn defaulted_prompt(default: serde_json::Value) -> serde_json::Value {
|
||||
json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"text","schema":{"type":"string"},"required":false,"default":default}],
|
||||
"messages":[{"role":"user","content":"{{text}}"}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn jsonb_text_bytes(pool: &sqlx::PgPool, text: &str) -> i32 {
|
||||
sqlx::query_scalar("select octet_length(to_jsonb($1::text)::text)")
|
||||
.bind(text)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("PostgreSQL reports the stored jsonb size")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_draft_persists_typed_definition_and_is_previewable() {
|
||||
let registry = registry("draft_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_roundtrip");
|
||||
let record = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
assert_eq!(record.prompt.status(), PromptStatus::Draft);
|
||||
assert_eq!(record.prompt.version(), 1);
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("typed draft reloads");
|
||||
assert_eq!(record, restored);
|
||||
let args = serde_json::Map::from_iter([("name".to_owned(), json!("Ada"))]);
|
||||
assert_eq!(
|
||||
restored.prompt.definition().preview(&args).unwrap()[0].content,
|
||||
"Hello Ada"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_multiline_defaults_roundtrip_through_real_postgres() {
|
||||
let (registry, pool) = registry_pool("multiline_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_multiline");
|
||||
let line_based = "\n".repeat(3_000);
|
||||
let tab_based = "\t".repeat(3_000);
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": "multiline",
|
||||
"description": "Defaults with short JSON escapes",
|
||||
"arguments": [
|
||||
{"name":"lines","schema":{"type":"string"},"required":false,"default":line_based},
|
||||
{"name":"tabs","schema":{"type":"string"},"required":false,"default":tab_based}
|
||||
],
|
||||
"messages": [{"role":"user","content":"{{lines}}|{{tabs}}"}]
|
||||
}))
|
||||
.expect("multiline defaults stay inside the storage guard");
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft with multiline defaults persists");
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("multiline draft reloads");
|
||||
assert_eq!(restored.prompt.definition(), &definition);
|
||||
let stored_sizes: Vec<i32> = sqlx::query_scalar(
|
||||
"select octet_length(default_value::text) from prompt_arguments where prompt_id=$1 order by position",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.expect("stored default sizes are readable");
|
||||
assert!(stored_sizes.iter().all(|size| *size <= 16_384));
|
||||
let rendered = restored
|
||||
.prompt
|
||||
.definition()
|
||||
.preview(&serde_json::Map::new())
|
||||
.expect("multiline defaults preview");
|
||||
assert_eq!(rendered[0].content, format!("{line_based}|{tab_based}"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_default_size_matches_the_real_postgres_jsonb_text() {
|
||||
let (_registry, pool) = registry_pool("jsonb_text_size").await;
|
||||
let cases = [
|
||||
("plain", 'a', 16_382, 16_383),
|
||||
("lf", '\n', 8_191, 8_192),
|
||||
("tab", '\t', 8_191, 8_192),
|
||||
("cr", '\r', 8_191, 8_192),
|
||||
("backspace", '\u{8}', 8_191, 8_192),
|
||||
("formfeed", '\u{c}', 8_191, 8_192),
|
||||
("quote", '"', 8_191, 8_192),
|
||||
("backslash", '\\', 8_191, 8_192),
|
||||
("unicode", 'я', 8_191, 8_192),
|
||||
("control_0x01", '\u{1}', 2_730, 2_731),
|
||||
];
|
||||
for (label, unit, at_count, over_count) in cases {
|
||||
let at_limit = unit.to_string().repeat(at_count);
|
||||
let over_limit = unit.to_string().repeat(over_count);
|
||||
let at_size = jsonb_text_bytes(&pool, &at_limit).await;
|
||||
let over_size = jsonb_text_bytes(&pool, &over_limit).await;
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!(at_limit))).is_ok(),
|
||||
at_size <= 16_384,
|
||||
"{label}: validator and PostgreSQL must agree at {at_size} bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!(over_limit))).is_ok(),
|
||||
over_size <= 16_384,
|
||||
"{label}: validator and PostgreSQL must agree at {over_size} bytes"
|
||||
);
|
||||
assert!(at_size <= 16_384 && over_size > 16_384);
|
||||
}
|
||||
// U+0000 is storage-incompatible in both columns this aggregate writes to.
|
||||
for (label, statement, value) in [
|
||||
("jsonb", "select ($1::jsonb)::text", "\"\\u0000\""),
|
||||
("text", "select $1::text", "a\u{0}b"),
|
||||
] {
|
||||
let stored: Result<String, _> = sqlx::query_scalar(statement)
|
||||
.bind(value)
|
||||
.fetch_one(&pool)
|
||||
.await;
|
||||
assert!(
|
||||
stored.is_err(),
|
||||
"PostgreSQL must reject U+0000 in {label}: {stored:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!("\u{0}"))),
|
||||
Err(crank_core::prompt::PromptError::InvalidDefinition),
|
||||
"a storage-incompatible NUL default must fail before SQL"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_draft_roundtrips_enum_defaults_and_ordered_messages() {
|
||||
let registry = registry("typed_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_typed");
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": "typed",
|
||||
"description": "Enum, defaults and several messages",
|
||||
"arguments": [
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","plain"]},"required":false,"default":"warm"},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":3},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":true}
|
||||
],
|
||||
"messages": [
|
||||
{"role":"system","content":"Tone {{tone}}."},
|
||||
{"role":"user","content":"Count {{count}}, enabled {{enabled}}."},
|
||||
{"role":"assistant","content":"Acknowledged."}
|
||||
]
|
||||
}))
|
||||
.expect("valid typed definition");
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Secret,
|
||||
definition: definition.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("typed draft reloads");
|
||||
assert_eq!(restored.prompt.definition(), &definition);
|
||||
assert_eq!(restored.prompt.sensitivity(), PromptSensitivity::Secret);
|
||||
assert_eq!(restored.prompt.definition().as_json(), definition.as_json());
|
||||
let args = serde_json::Map::from_iter([
|
||||
("enabled".to_owned(), json!(true)),
|
||||
("count".to_owned(), json!(7)),
|
||||
]);
|
||||
let rendered = restored
|
||||
.prompt
|
||||
.definition()
|
||||
.preview(&args)
|
||||
.expect("restored defaults and enum render");
|
||||
assert_eq!(rendered[0].content, "Tone warm.");
|
||||
assert_eq!(rendered[1].content, "Count 7, enabled true.");
|
||||
assert_eq!(rendered[2].content, "Acknowledged.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_list_serves_records_beyond_the_first_hundred() {
|
||||
let registry = registry("list_all").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let start = OffsetDateTime::now_utc();
|
||||
let mut ids = Vec::new();
|
||||
for index in 0..101 {
|
||||
let prompt_id = PromptId::new(format!("prm_story312_page_{index:03}"));
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: start + time::Duration::milliseconds(index),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
ids.push(prompt_id);
|
||||
}
|
||||
let listed = registry
|
||||
.list_prompt_drafts(&workspace_id)
|
||||
.await
|
||||
.expect("list reads every draft");
|
||||
let listed_ids: Vec<String> = listed
|
||||
.iter()
|
||||
.map(|record| record.prompt.prompt_id().to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
listed_ids.len(),
|
||||
101,
|
||||
"no Draft may be truncated from the list"
|
||||
);
|
||||
assert_eq!(listed_ids.first(), Some(&ids[0].to_string()));
|
||||
assert_eq!(listed_ids.last(), Some(&ids[100].to_string()));
|
||||
for id in &ids {
|
||||
assert!(
|
||||
listed_ids.contains(&id.to_string()),
|
||||
"draft {id} must stay listed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_update_uses_compare_and_swap_and_workspace_scope() {
|
||||
let registry = registry("draft_cas_scope").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_cas");
|
||||
let created = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Secret,
|
||||
definition: prompt("Old {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
let changed = registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("New {{name}}"),
|
||||
expected_updated_at: created.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("current revision updates");
|
||||
assert_eq!(changed.prompt.version(), 2);
|
||||
assert_eq!(changed.prompt.status(), PromptStatus::Draft);
|
||||
assert!(matches!(
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Stale {{name}}"),
|
||||
expected_updated_at: created.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await,
|
||||
Err(crank_registry::RegistryError::PromptStaleRevision { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
registry
|
||||
.get_prompt_draft(&WorkspaceId::new("ws_foreign"), &prompt_id)
|
||||
.await,
|
||||
Err(crank_registry::RegistryError::PromptNotFound { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,756 @@
|
||||
//! Story 3.13 / FR-17: immutable Published Prompt Versions и exact typed Prompt
|
||||
//! bindings Agent (V22).
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL, что контракт держится схемой и
|
||||
//! транзакциями, а не только JSON-ответом API:
|
||||
//! - publish фиксирует точную версию, последующая правка открывает новый Draft,
|
||||
//! exact v1 не меняется после edit/publish/archive;
|
||||
//! - concurrent publish с одинаковым `expected_updated_at` даёт ровно одну
|
||||
//! публикацию, проигравший получает stale;
|
||||
//! - guard-триггеры запрещают менять definition опубликованной версии и строку
|
||||
//! публикации напрямую через SQL;
|
||||
//! - binding адресует exact published версию, archived/unpublished отклоняются,
|
||||
//! published Agent bindings иммутабельны, повтор Agent publish не даёт двойной
|
||||
//! bump, scope другого workspace не раскрывается.
|
||||
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry,
|
||||
PublishAgentRequest, RegistryError,
|
||||
model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WS: &str = "ws_default";
|
||||
|
||||
fn prompt(content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"name","schema":{"type":"string"},"required":true}],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
}))
|
||||
.expect("valid typed definition")
|
||||
}
|
||||
|
||||
async fn registry_pool(label: &str) -> (PostgresRegistry, sqlx::PgPool) {
|
||||
let url = crank_test_support::postgres_schema_url(&format!("story313_{label}")).await;
|
||||
let pool = sqlx::PgPool::connect(&url)
|
||||
.await
|
||||
.expect("test postgres schema connects");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&url)
|
||||
.await
|
||||
.expect("registry connects");
|
||||
(registry, pool)
|
||||
}
|
||||
|
||||
async fn registry(label: &str) -> PostgresRegistry {
|
||||
registry_pool(label).await.0
|
||||
}
|
||||
|
||||
async fn create_prompt(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates")
|
||||
}
|
||||
|
||||
async fn publish(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
expected_updated_at: OffsetDateTime,
|
||||
) -> Result<crank_registry::model::PromptDraftRecord, RegistryError> {
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// NEW-side проверки guard-триггеров обязаны падать именно на защите
|
||||
/// опубликованной версии, а не на случайном ограничении схемы.
|
||||
fn assert_immutable_guard_rejected(
|
||||
result: Result<sqlx::postgres::PgQueryResult, sqlx::Error>,
|
||||
expected_message: &str,
|
||||
) {
|
||||
let error = match result {
|
||||
Ok(_) => panic!("raw SQL must be rejected by `{expected_message}`"),
|
||||
Err(error) => error,
|
||||
};
|
||||
let message = match &error {
|
||||
sqlx::Error::Database(database) => database.message().to_owned(),
|
||||
other => panic!("expected the `{expected_message}` guard rejection, got: {other}"),
|
||||
};
|
||||
assert!(
|
||||
message.contains(expected_message),
|
||||
"the guard must reject the write with `{expected_message}`, got: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn create_draft_agent(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &str,
|
||||
slug: &str,
|
||||
) -> AgentId {
|
||||
let id = AgentId::new(agent_id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
description: "Story 3.13 prompt binding fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: Default::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent is created");
|
||||
id
|
||||
}
|
||||
|
||||
async fn save_prompt_bindings(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
agent_version: u32,
|
||||
prompt_id: &PromptId,
|
||||
prompt_version: u32,
|
||||
) -> Result<u32, RegistryError> {
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_publish_pins_immutable_version_and_edit_opens_new_draft() {
|
||||
let registry = registry("publish_lifecycle").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_lifecycle");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("valid Draft publishes");
|
||||
assert_eq!(published.prompt.status(), PromptStatus::Published);
|
||||
assert_eq!(published.prompt.version(), 1);
|
||||
assert_eq!(published.latest_published_version, Some(1));
|
||||
assert_eq!(published.prompt.definition(), created.prompt.definition());
|
||||
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact published version reads");
|
||||
assert_eq!(exact.name, "welcome");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
|
||||
let edited_definition = prompt("Edited {{name}}");
|
||||
let edited = registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: edited_definition.clone(),
|
||||
expected_updated_at: published.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Prompt opens a new Draft");
|
||||
assert_eq!(edited.prompt.status(), PromptStatus::Draft);
|
||||
assert_eq!(edited.prompt.version(), 2);
|
||||
assert_eq!(edited.latest_published_version, Some(1));
|
||||
assert_eq!(edited.prompt.definition(), &edited_definition);
|
||||
|
||||
let preserved = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("the pinned publication survives a Draft edit");
|
||||
assert_eq!(&preserved.definition, created.prompt.definition());
|
||||
assert_eq!(preserved.name, "welcome");
|
||||
|
||||
// Вторая публикация: publish v2 создаёт отдельный immutable snapshot, при этом
|
||||
// exact v1 остаётся читаемой и latest_published_version поднимается до 2.
|
||||
let published_v2 = publish(®istry, &workspace_id, &prompt_id, edited.updated_at)
|
||||
.await
|
||||
.expect("the edited Draft publishes as v2");
|
||||
assert_eq!(published_v2.prompt.status(), PromptStatus::Published);
|
||||
assert_eq!(published_v2.prompt.version(), 2);
|
||||
assert_eq!(published_v2.latest_published_version, Some(2));
|
||||
assert_eq!(published_v2.prompt.definition(), &edited_definition);
|
||||
|
||||
let exact_v1_after_v2 = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact v1 stays readable after publishing v2");
|
||||
assert_eq!(&exact_v1_after_v2.definition, created.prompt.definition());
|
||||
assert_eq!(exact_v1_after_v2.version, 1);
|
||||
let exact_v2 = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||||
.await
|
||||
.expect("exact v2 is readable by its own number");
|
||||
assert_eq!(exact_v2.version, 2);
|
||||
assert_eq!(&exact_v2.definition, &edited_definition);
|
||||
|
||||
let archived = registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: published_v2.updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("archive is a lifecycle action");
|
||||
assert_eq!(archived.prompt.status(), PromptStatus::Archived);
|
||||
|
||||
let refused = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||||
assert!(matches!(refused, Err(RegistryError::PromptNotDraft { .. })));
|
||||
|
||||
let after_archive = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("archive is not a security revoke");
|
||||
assert_eq!(&after_archive.definition, created.prompt.definition());
|
||||
let v2_after_archive = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||||
.await
|
||||
.expect("the second publication survives archive");
|
||||
assert_eq!(&v2_after_archive.definition, &edited_definition);
|
||||
|
||||
// Повторная публикация той же версии не создаёт вторую строку публикации.
|
||||
let repeat = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||||
assert!(matches!(repeat, Err(RegistryError::PromptNotDraft { .. })));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_repeated_publish_of_the_same_version_conflicts_without_mutation() {
|
||||
let (registry, pool) = registry_pool("repeated_publish").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_repeat");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("first publish succeeds");
|
||||
let repeat = publish(®istry, &workspace_id, &prompt_id, published.updated_at).await;
|
||||
assert!(matches!(
|
||||
repeat,
|
||||
Err(RegistryError::PromptPublicationConflict { .. })
|
||||
));
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(rows, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_concurrent_publish_with_same_precondition_yields_one_publication() {
|
||||
let (registry, pool) = registry_pool("concurrent_publish").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_concurrent");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let (first, second) = tokio::join!(
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at),
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
);
|
||||
let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
|
||||
assert_eq!(successes, 1, "exactly one publish may win the CAS race");
|
||||
let loser = if first.is_err() { first } else { second };
|
||||
assert!(matches!(
|
||||
loser,
|
||||
Err(RegistryError::PromptStaleRevision { .. })
|
||||
));
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(rows, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_database_guard_protects_published_definition_and_publication() {
|
||||
let (registry, pool) = registry_pool("definition_guard").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_guard");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
|
||||
let mutated = sqlx::query(
|
||||
"update prompt_messages set content = 'tampered'
|
||||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(mutated.is_err(), "published messages must be immutable");
|
||||
let removed = sqlx::query(
|
||||
"delete from prompt_arguments where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(removed.is_err(), "published arguments must be immutable");
|
||||
let rewritten = sqlx::query(
|
||||
"update prompt_publications set name = 'tampered'
|
||||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(rewritten.is_err(), "publication rows must be immutable");
|
||||
|
||||
// NEW-сторона guard: в опубликованную версию нельзя добавить новую строку
|
||||
// definition напрямую через SQL.
|
||||
let inserted_argument = sqlx::query(
|
||||
"insert into prompt_arguments
|
||||
(workspace_id, prompt_id, version, argument_name, argument_type, required,
|
||||
default_value, enumeration, position)
|
||||
values ($1, $2, 1, 'injected', 'string', false, null, null, 3)",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted_argument, "published Prompt version is immutable");
|
||||
let inserted_message = sqlx::query(
|
||||
"insert into prompt_messages (workspace_id, prompt_id, version, position, role, content)
|
||||
values ($1, $2, 1, 2, 'assistant', 'injected')",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted_message, "published Prompt version is immutable");
|
||||
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact read still works");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_exact_read_and_publish_are_workspace_scoped() {
|
||||
let (registry, pool) = registry_pool("scope").await;
|
||||
let own = WorkspaceId::new(WS);
|
||||
let other = WorkspaceId::new("ws_story313_other");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: other.clone(),
|
||||
slug: "story313-other".to_owned(),
|
||||
display_name: "Story 3.13 other".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("second workspace is created");
|
||||
let prompt_id = PromptId::new("prm_story313_scope");
|
||||
let created = create_prompt(®istry, &own, &prompt_id).await;
|
||||
publish(®istry, &own, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
|
||||
let hidden = registry
|
||||
.get_published_prompt_version(&other, &prompt_id, 1)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
hidden,
|
||||
Err(RegistryError::PromptPublicationNotFound { .. })
|
||||
));
|
||||
let foreign_publish = publish(®istry, &other, &prompt_id, created.updated_at).await;
|
||||
assert!(matches!(
|
||||
foreign_publish,
|
||||
Err(RegistryError::PromptNotFound { .. })
|
||||
));
|
||||
let publications: i64 =
|
||||
sqlx::query_scalar("select count(*) from prompt_publications where prompt_id = $1")
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(publications, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_agent_binding_is_exact_typed_and_published_snapshot_is_stable() {
|
||||
let (registry, pool) = registry_pool("agent_binding").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_binding");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_story313", "agent313").await;
|
||||
|
||||
let saved = save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact published Prompt binding is accepted");
|
||||
assert_eq!(saved, 1);
|
||||
let version = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
version.prompt_bindings,
|
||||
vec![AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
// Draft edit после binding не меняет закреплённую версию.
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Changed {{name}}"),
|
||||
expected_updated_at: published.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after binding succeeds");
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("binding keeps the exact published definition");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
|
||||
// Agent publication атомарно включает binding и bump catalog_revision; повтор
|
||||
// уже опубликованной версии идемпотентен.
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("agent publishes with the exact Prompt snapshot");
|
||||
let summary = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(summary.latest_published_version, Some(1));
|
||||
assert_eq!(summary.catalog_revision, 1);
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("repeated publish is idempotent");
|
||||
let repeated = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(repeated.catalog_revision, 1, "no double catalog bump");
|
||||
|
||||
// После unpublish та же версия публикуется обычным путём: Agent снова
|
||||
// Published, revision растёт один раз, exact Prompt binding сохраняется.
|
||||
registry
|
||||
.unpublish_agent(&workspace_id, &agent_id, &OffsetDateTime::now_utc(), None)
|
||||
.await
|
||||
.expect("agent unpublishes");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("republishing the same version after unpublish succeeds");
|
||||
let republished = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(republished.catalog_revision, 3);
|
||||
let still_bound = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(still_bound.prompt_bindings.len(), 1);
|
||||
|
||||
// Published Agent bindings иммутабельны и через прямой SQL.
|
||||
let rewritten = sqlx::query(
|
||||
"update agent_prompt_bindings set prompt_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(rewritten.is_err(), "published Agent bindings are immutable");
|
||||
|
||||
// NEW-сторона guard: в опубликованную версию Agent нельзя добавить новую
|
||||
// привязку к другой опубликованной версии Prompt.
|
||||
let second_prompt_id = PromptId::new("prm_story313_binding_second");
|
||||
let second = create_prompt(®istry, &workspace_id, &second_prompt_id).await;
|
||||
publish(
|
||||
®istry,
|
||||
&workspace_id,
|
||||
&second_prompt_id,
|
||||
second.updated_at,
|
||||
)
|
||||
.await
|
||||
.expect("the second Prompt fixture publishes");
|
||||
let inserted = sqlx::query(
|
||||
"insert into agent_prompt_bindings
|
||||
(workspace_id, agent_id, agent_version, prompt_id, prompt_version)
|
||||
values ($1, $2, 1, $3, 1)",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(second_prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted, "published Agent Prompt bindings are immutable");
|
||||
|
||||
let removed =
|
||||
sqlx::query("delete from agent_prompt_bindings where agent_id = $1 and agent_version = 1")
|
||||
.bind(agent_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(removed, "published Agent Prompt bindings are immutable");
|
||||
|
||||
let still_bound = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
still_bound.prompt_bindings,
|
||||
vec![AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
"raw SQL must not change the published Agent snapshot"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_binding_to_unpublished_or_archived_prompt_is_refused() {
|
||||
let registry = registry("binding_refusals").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_refusals");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
|
||||
// Ещё не опубликованный Prompt: exact версии 1 нет в prompt_publications.
|
||||
let unpublished = save_prompt_bindings(
|
||||
®istry,
|
||||
&workspace_id,
|
||||
&create_draft_agent(®istry, &workspace_id, "agent_313_a", "agent313a").await,
|
||||
1,
|
||||
&prompt_id,
|
||||
1,
|
||||
)
|
||||
.await;
|
||||
assert!(unpublished.is_err(), "unpublished version cannot be bound");
|
||||
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_313_b", "agent313b").await;
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||||
.await
|
||||
.expect("published version binds");
|
||||
|
||||
registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: published.updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("archive succeeds");
|
||||
|
||||
let archived =
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1).await;
|
||||
assert!(
|
||||
matches!(archived, Err(RegistryError::PromptArchived { .. })),
|
||||
"archived Prompt must refuse new bindings: {archived:?}"
|
||||
);
|
||||
let version = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
version.prompt_bindings.len(),
|
||||
1,
|
||||
"a refused binding must not clear existing bindings"
|
||||
);
|
||||
}
|
||||
|
||||
/// Гонка «bind в Draft-версию Agent» ↔ «publish этой версии»: обе операции
|
||||
/// сериализуются на строке Agent, и опубликованный снимок не мутирует ни в одном
|
||||
/// из порядков — bind либо успевает до publish, либо уезжает в новую Draft.
|
||||
#[tokio::test]
|
||||
async fn story313_concurrent_bind_and_agent_publish_keep_the_publication_stable() {
|
||||
let (registry, pool) = registry_pool("bind_publish_race").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_race");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("the Prompt fixture publishes");
|
||||
let agent_id =
|
||||
create_draft_agent(®istry, &workspace_id, "agent_313_race", "agent313race").await;
|
||||
let binding = AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
};
|
||||
|
||||
let publish_at = OffsetDateTime::now_utc();
|
||||
let (bound, published) = tokio::join!(
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1),
|
||||
registry.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &publish_at,
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
);
|
||||
published.expect("Agent publish serializes against the concurrent binding save");
|
||||
|
||||
let summary = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(summary.latest_published_version, Some(1));
|
||||
|
||||
let published_v1 = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("version 1 exists");
|
||||
assert_eq!(published_v1.status, AgentStatus::Published);
|
||||
|
||||
match bound {
|
||||
// Bind ушёл первым: опубликованный снимок содержит эту привязку.
|
||||
Ok(1) => {
|
||||
assert_eq!(published_v1.prompt_bindings, vec![binding.clone()]);
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
}
|
||||
// Publish ушёл первым: bind форкнут в новую Draft, published v1 не изменился.
|
||||
Ok(2) => {
|
||||
assert!(
|
||||
published_v1.prompt_bindings.is_empty(),
|
||||
"publish won the race, so the published v1 must stay empty: {published_v1:?}"
|
||||
);
|
||||
let draft_v2 = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 2)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("the forked Draft version exists");
|
||||
assert_eq!(draft_v2.status, AgentStatus::Draft);
|
||||
assert_eq!(draft_v2.prompt_bindings, vec![binding.clone()]);
|
||||
}
|
||||
other => panic!("unexpected concurrent binding outcome: {other:?}"),
|
||||
}
|
||||
|
||||
// Повторное чтение: опубликованный снимок не изменился после гонки.
|
||||
let replayed = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("version 1 exists");
|
||||
assert_eq!(replayed.prompt_bindings, published_v1.prompt_bindings);
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from agent_prompt_bindings where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("binding rows are readable");
|
||||
assert_eq!(
|
||||
rows,
|
||||
published_v1.prompt_bindings.len() as i64,
|
||||
"the published Agent snapshot must not gain or lose binding rows"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
//! BUILD-ONLY: проверки реестра Story 3.6 (AT-3.6-01/03, таргет P).
|
||||
//!
|
||||
//! Статус файла на стадии Dev ATDD: **не зарегистрирован** в `tests/integration.rs`
|
||||
//! (`mod integration { mod resource_drafts; }` добавляет BUILD), поэтому он не компилируется и
|
||||
//! не исполняется: `PostgresRegistry::create_resource_draft`/`update_resource_draft`/
|
||||
//! `resolve_resource_version` и миграция V16 ещё не существуют. Нулевая коллекция этого файла
|
||||
//! не является PASS.
|
||||
//!
|
||||
//! Минимальный будущий интерфейс (SPEC v4 §5, D-15):
|
||||
//! - `crank_registry::postgres::resource::{create_resource_draft, update_resource_draft,
|
||||
//! get_resource_draft, list_resource_drafts, resolve_resource_version}`;
|
||||
//! - `crank_registry::model::resource::{CreateResourceDraftRequest, UpdateResourceDraftRequest,
|
||||
//! ResourceDraftRecord, ResolvedResourceVersion}`, где оба мутирующих запроса получают
|
||||
//! `artifact: RegisteredArtifact` — доказательство уже зарегистрированных durable bytes
|
||||
//! (`ArtifactStore::put_registered` в сервисе), а не сырые bytes и не digest строкой:
|
||||
//! реестр получает durable metadata/owning ref и **не** становится владельцем записи файла
|
||||
//! (D-15 шаг 3 `ensure_blob`, D-19 «put» — точка сервиса);
|
||||
//! - `resource_versions` не имеет `updated_at`; CAS-precondition берётся из `artifact_sources`
|
||||
//! через существующий `get_source_in_transaction` (D-15 шаг 2);
|
||||
//! - таблицы V16 — по наброску SPEC §5.
|
||||
//!
|
||||
//! Фиксированные имена тестов (SPEC §2) должны появиться при регистрации без переименования.
|
||||
//! Каждый тест получает собственные PG-схему и приватный artifact root, поэтому положительные
|
||||
//! seed-ы не смешиваются между тестами и digest в них всегда соответствует реально
|
||||
//! зарегистрированным bytes (независимый оракул — `sha256_hex`).
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, ResolvedResourceVersion, ResourceDraftRecord,
|
||||
UpdateResourceDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
|
||||
use serde_json::json;
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
|
||||
mod resource_publications;
|
||||
mod resource_template;
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-resource-drafts-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
}
|
||||
|
||||
/// Изолированный стенд: своя PG-схема V16, свой приватный store, свой workspace.
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database_url = crank_test_support::postgres_schema_url(&format!("story36_{name}")).await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("test schema must accept connections");
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("V16 must be applicable");
|
||||
let registry = PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("registry must connect");
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
create_workspace(®istry).await;
|
||||
Sandbox {
|
||||
registry,
|
||||
store,
|
||||
_root: root,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_workspace(registry: &PostgresRegistry) {
|
||||
// V1 baseline уже сеет `ws_default`, поэтому фикстура не создаёт его повторно:
|
||||
// тесту нужен именно доступный workspace, а не вторая его копия.
|
||||
let workspace_id = WorkspaceId::new(WORKSPACE_ID);
|
||||
if registry
|
||||
.get_workspace(&workspace_id)
|
||||
.await
|
||||
.expect("workspace lookup must succeed")
|
||||
.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id,
|
||||
slug: "story36-registry".to_owned(),
|
||||
display_name: "Story 3.6 Registry".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("synthetic workspace must be created");
|
||||
}
|
||||
|
||||
/// Регистрирует bytes в приватном store и создаёт Draft, передавая реестру именно
|
||||
/// `RegisteredArtifact` (durable metadata/owning ref), а не сырые bytes.
|
||||
async fn seeded_draft(sandbox: &Sandbox) -> ResourceId {
|
||||
let bytes = b"registry payload";
|
||||
let artifact = sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably");
|
||||
let request = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry"),
|
||||
uri: "crank://registry/draft".to_owned(),
|
||||
name: "registry_draft".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(request)
|
||||
.await
|
||||
.expect("draft must be created");
|
||||
ResourceId::new("res_story36_registry")
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at01_resource_and_version_roundtrip_through_postgres() {
|
||||
let sandbox = sandbox("at01_roundtrip").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
let record: ResourceDraftRecord = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
assert_eq!(record.resource.uri, "crank://registry/draft");
|
||||
assert_eq!(record.resource.kind, "text");
|
||||
assert_eq!(record.version.version, 1);
|
||||
assert_eq!(record.version.sensitivity, "internal");
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from resources")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from resource_versions")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_exact_digest_and_metadata_roundtrip() {
|
||||
let sandbox = sandbox("at03_digest").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
// Независимый оракул: digest считается тестом из тех же bytes, а не берётся у реестра.
|
||||
let digest = sha256_hex(b"registry payload");
|
||||
assert_eq!(
|
||||
resolved.snapshot.version.digest, digest,
|
||||
"digest must match independently computed SHA-256"
|
||||
);
|
||||
assert_eq!(resolved.snapshot.version.size_bytes, 16);
|
||||
assert_eq!(resolved.snapshot.version.mime_type, "text/plain");
|
||||
|
||||
// Повторная регистрация тех же bytes переиспользует blob, но создаёт новую version-строку.
|
||||
let updated = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: String::new(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
})
|
||||
.await
|
||||
.expect("update must succeed");
|
||||
assert_eq!(updated.version, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_corrupt_missing_and_mismatched_artifact_fail_closed() {
|
||||
let sandbox = sandbox("at03_integrity").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// рассинхронизация metadata/digest/size обязана давать фиксированную ошибку без bytes
|
||||
sqlx::query("update artifact_blobs set size_bytes = size_bytes + 1")
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("fixture mutation must apply");
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect_err("mismatched artifact metadata must fail closed");
|
||||
assert_eq!(error.code(), "resource_artifact_integrity");
|
||||
}
|
||||
|
||||
/// F7 (TL run109 CODE-REVIEW): полное наблюдаемое состояние отката duplicate-create.
|
||||
///
|
||||
/// Считаются **все четыре** отношения (`resources`, `resource_versions`,
|
||||
/// `artifact_sources`, `artifact_blobs`), фиксируются строки принятого Draft и
|
||||
/// owning-ссылки, а не только «сколько ресурсов стало». Допускаемые AD-10 orphan
|
||||
/// bytes лежат в файловом store вне БД, поэтому строк отказ добавлять не должен.
|
||||
async fn accepted_snapshot(pool: &sqlx::PgPool) -> Vec<String> {
|
||||
let mut snapshot = Vec::new();
|
||||
let counts = sqlx::query_as::<_, (i64, i64, i64, i64, i64)>(
|
||||
"select (select count(*) from resources),
|
||||
(select count(*) from resource_versions),
|
||||
(select count(*) from artifact_sources),
|
||||
(select count(*) from artifact_blobs),
|
||||
(select count(*) from artifact_sources where lifecycle = 'active')",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("the four V16 relations must stay countable");
|
||||
snapshot.push(format!("counts={counts:?}"));
|
||||
|
||||
let resources = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
),
|
||||
>(
|
||||
"select resource_id, uri, name, status, kind, description,
|
||||
current_draft_version::text,
|
||||
created_at::text || '|' || updated_at::text
|
||||
from resources order by resource_id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the accepted resource rows must be readable");
|
||||
for row in resources {
|
||||
snapshot.push(format!("resource={row:?}"));
|
||||
}
|
||||
|
||||
let versions = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
i32,
|
||||
String,
|
||||
String,
|
||||
i64,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
),
|
||||
>(
|
||||
"select resource_id, version, kind, mime_type, size_bytes, digest, sensitivity,
|
||||
artifact_source_id,
|
||||
created_at::text || '|' || coalesce(superseded_at::text, '<current>')
|
||||
from resource_versions order by resource_id, version",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the accepted version rows must be readable");
|
||||
for row in versions {
|
||||
snapshot.push(format!("version={row:?}"));
|
||||
}
|
||||
|
||||
let refs = sqlx::query_as::<_, (String, String, String, String, String, String, String)>(
|
||||
"select source_id, workspace_id, lifecycle, blob_digest, mime_type, sensitivity,
|
||||
created_at::text || '|' || coalesce(detached_at::text, '<attached>')
|
||||
from artifact_sources order by source_id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("owning references must be readable");
|
||||
for row in refs {
|
||||
snapshot.push(format!("ref={row:?}"));
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// R3/F7: принятая версия и её bytes обязаны читаться **теми же** данными сразу
|
||||
/// после каждого отказа, а не только после всей пары отказов: сравнивается полный
|
||||
/// resolved-снимок версии и фактически прочитанные bytes по его же ссылке.
|
||||
async fn assert_accepted_version_intact(
|
||||
sandbox: &Sandbox,
|
||||
resource_id: &ResourceId,
|
||||
before: &ResolvedResourceVersion,
|
||||
) {
|
||||
let after = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, resource_id, before.snapshot.version.version)
|
||||
.await
|
||||
.expect("the accepted version must resolve right after the refusal");
|
||||
assert_eq!(
|
||||
after.snapshot, before.snapshot,
|
||||
"the accepted Draft card metadata (identifiers, pointer, version, description, \
|
||||
timestamps, digest/size/MIME/sensitivity and source binding) must be unchanged right \
|
||||
after the refusal (F7)"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&after.artifact_ref)
|
||||
.expect("the previously accepted bytes must stay readable right after the refusal"),
|
||||
b"registry payload".to_vec(),
|
||||
"the previously accepted bytes must stay readable and exact right after the refusal (F7)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_rollback_leaves_no_accepted_resource_or_owning_ref() {
|
||||
let sandbox = sandbox("at03_rollback").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// «До»: полное состояние принятого Draft, включая все четыре отношения.
|
||||
let before = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
let resolved_before = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the accepted version must resolve before the duplicates");
|
||||
assert_eq!(
|
||||
resolved_before.snapshot.version.digest,
|
||||
sha256_hex(b"registry payload")
|
||||
);
|
||||
|
||||
// duplicate uri с **другими** bytes (put содержимого мог состояться, orphan bytes
|
||||
// допустимы, AD-10); принятых строк быть не должно.
|
||||
let duplicate_uri = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry_dup"),
|
||||
uri: "crank://registry/draft".to_owned(),
|
||||
name: "registry_other".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"other payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(duplicate_uri)
|
||||
.await
|
||||
.expect_err("duplicate uri must be rejected");
|
||||
assert_eq!(error.code(), "resource_uri_duplicate");
|
||||
// Наблюдение неизменности **сразу** после отказа по uri (TL run111): не только
|
||||
// после пары отказов, иначе «второй отказ откатился» маскировал бы первый.
|
||||
let after_uri = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after_uri, before,
|
||||
"a duplicate uri must leave all four relations and the accepted Draft exactly as they \
|
||||
were, observed right after that refusal (F7)"
|
||||
);
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
|
||||
// duplicate name: тот же единственный нарушенный фактор, но по другой колонке.
|
||||
let duplicate_name = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry_dup_name"),
|
||||
uri: "crank://registry/other".to_owned(),
|
||||
name: "registry_draft".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"third payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(duplicate_name)
|
||||
.await
|
||||
.expect_err("duplicate name must be rejected");
|
||||
assert_eq!(error.code(), "resource_name_duplicate");
|
||||
// Такое же отдельное наблюдение после отказа по name.
|
||||
let after_name = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after_name, before,
|
||||
"a duplicate name must leave all four relations and the accepted Draft exactly as they \
|
||||
were, observed right after that refusal (F7)"
|
||||
);
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
|
||||
// «После»: ни одно из четырёх отношений, ни текущий указатель/версия/metadata/
|
||||
// timestamps/owning-ссылка не изменились.
|
||||
let after = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after, before,
|
||||
"each duplicate create must leave all four relations and the accepted Draft exactly \
|
||||
as they were (F7)"
|
||||
);
|
||||
|
||||
// И старые bytes по-прежнему читаются теми же (не новыми) bytes.
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_supersedes_before_insert_and_switches_pointer() {
|
||||
let sandbox = sandbox("at03_supersede").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "second".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect("update must succeed");
|
||||
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from resource_versions where superseded_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1,
|
||||
"exactly one current draft version after update"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i32>(
|
||||
"select current_draft_version from resources where resource_id = $1",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable"),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_rollback_after_supersede_restores_previous_current_version() {
|
||||
let sandbox = sandbox("at03_update_rollback").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
// repository вызывается напрямую, ниже доменной валидации: отказ наступает уже ПОСЛЕ шага
|
||||
// пометки прежней версии (CHECK `resources_description_len` отвергает 1025 байт).
|
||||
let error = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "d".repeat(1025),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"third payload"),
|
||||
})
|
||||
.await
|
||||
.expect_err("DB CHECK must reject the oversized description");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
|
||||
// Откат обязан вернуть прежнюю версию в состояние «единственная текущая».
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from resource_versions where superseded_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("artifact_sources must be queryable"),
|
||||
1,
|
||||
"the previous owning reference must stay active"
|
||||
);
|
||||
}
|
||||
|
||||
/// Независимо посчитанный digest (оракул не берётся из реализации).
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let digest = sha256(bytes);
|
||||
let mut hex = String::with_capacity(64);
|
||||
for byte in digest {
|
||||
write!(&mut hex, "{byte:02x}").expect("hex formatting");
|
||||
}
|
||||
hex
|
||||
}
|
||||
|
||||
fn sha256(bytes: &[u8]) -> [u8; 32] {
|
||||
// Независимое вычисление: используется уже объявленная зависимость крейты (`sha2.workspace`),
|
||||
// новая зависимость не вводится.
|
||||
use sha2::{Digest as _, Sha256};
|
||||
Sha256::digest(bytes).into()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P5 (affected ATDD до исправления): полные итоги строк и прежние bytes после
|
||||
// отката позднего UPDATE, плюс положительный контроль следующего update.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn count(sandbox: &Sandbox, sql: &'static str) -> i64 {
|
||||
sqlx::query_scalar::<_, i64>(sql)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("row totals must be queryable")
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct RowTotals {
|
||||
resources: i64,
|
||||
versions: i64,
|
||||
owning_refs: i64,
|
||||
blobs: i64,
|
||||
}
|
||||
|
||||
impl RowTotals {
|
||||
async fn observe(sandbox: &Sandbox) -> Self {
|
||||
Self {
|
||||
resources: count(sandbox, "select count(*) from resources").await,
|
||||
versions: count(sandbox, "select count(*) from resource_versions").await,
|
||||
owning_refs: count(sandbox, "select count(*) from artifact_sources").await,
|
||||
blobs: count(sandbox, "select count(*) from artifact_blobs").await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Точное состояние текущей версии Draft и её owning-ссылки.
|
||||
///
|
||||
/// Наблюдается повторным чтением (не из закешированных значений) и сравнивается целиком:
|
||||
/// указатель, ссылка, digest/size/MIME/sensitivity, timestamps и metadata (R-D).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct DraftSnapshot {
|
||||
version: i32,
|
||||
digest: String,
|
||||
size_bytes: i64,
|
||||
mime_type: String,
|
||||
sensitivity: String,
|
||||
artifact_source_id: String,
|
||||
version_created_at: String,
|
||||
superseded_is_null: bool,
|
||||
current_draft_version: i32,
|
||||
resource_updated_at: String,
|
||||
description: String,
|
||||
status: String,
|
||||
source_lifecycle: String,
|
||||
source_digest: String,
|
||||
source_detached: bool,
|
||||
}
|
||||
|
||||
impl DraftSnapshot {
|
||||
async fn observe(sandbox: &Sandbox, resource_id: &ResourceId) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select v.version, v.digest, v.size_bytes, v.mime_type, v.sensitivity,
|
||||
v.artifact_source_id, v.created_at::text as version_created_at,
|
||||
(v.superseded_at is null) as superseded_is_null,
|
||||
r.current_draft_version, r.updated_at::text as resource_updated_at,
|
||||
r.description, r.status,
|
||||
s.lifecycle as source_lifecycle, s.blob_digest as source_digest,
|
||||
(s.detached_at is not null) as source_detached
|
||||
from resource_versions v
|
||||
join resources r
|
||||
on r.workspace_id = v.workspace_id and r.resource_id = v.resource_id
|
||||
join artifact_sources s
|
||||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||||
where v.workspace_id = $1
|
||||
and v.resource_id = $2
|
||||
and v.version = r.current_draft_version",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the current Draft version and its owning reference must be observable");
|
||||
Self {
|
||||
version: row.get("version"),
|
||||
digest: row.get("digest"),
|
||||
size_bytes: row.get("size_bytes"),
|
||||
mime_type: row.get("mime_type"),
|
||||
sensitivity: row.get("sensitivity"),
|
||||
artifact_source_id: row.get("artifact_source_id"),
|
||||
version_created_at: row.get("version_created_at"),
|
||||
superseded_is_null: row.get("superseded_is_null"),
|
||||
current_draft_version: row.get("current_draft_version"),
|
||||
resource_updated_at: row.get("resource_updated_at"),
|
||||
description: row.get("description"),
|
||||
status: row.get("status"),
|
||||
source_lifecycle: row.get("source_lifecycle"),
|
||||
source_digest: row.get("source_digest"),
|
||||
source_detached: row.get("source_detached"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Состояние конкретной owning-ссылки по её `source_id`.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct SourceState {
|
||||
lifecycle: String,
|
||||
digest: String,
|
||||
detached: bool,
|
||||
}
|
||||
|
||||
async fn source_state(sandbox: &Sandbox, source_id: &str) -> SourceState {
|
||||
let row = sqlx::query(
|
||||
"select lifecycle, blob_digest, (detached_at is not null) as detached
|
||||
from artifact_sources
|
||||
where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(source_id)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the owning reference must be observable by its source_id");
|
||||
SourceState {
|
||||
lifecycle: row.get("lifecycle"),
|
||||
digest: row.get("blob_digest"),
|
||||
detached: row.get("detached"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_rollback_preserves_totals_and_old_bytes() {
|
||||
let sandbox = sandbox("at03_rollback_totals").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
let before = RowTotals::observe(&sandbox).await;
|
||||
let before_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
let old_ref = resolved.artifact_ref.clone();
|
||||
let bytes_before_refusal = sandbox
|
||||
.store
|
||||
.read(&old_ref)
|
||||
.expect("old bytes must be readable before the rejected update");
|
||||
|
||||
// repository вызывается напрямую, ниже доменной валидации: отказ наступает уже ПОСЛЕ шага
|
||||
// пометки прежней версии (CHECK `resources_description_len` отвергает 1025 байт).
|
||||
let error = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "d".repeat(1025),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect_err("the late UPDATE must be refused by the DB CHECK");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
|
||||
// (1) Полные итоги ВСЕХ участвующих классов строк не изменились (не только «активных»).
|
||||
let after = RowTotals::observe(&sandbox).await;
|
||||
assert_eq!(
|
||||
after, before,
|
||||
"a rolled back update must not change resource/version/owning/blob row totals"
|
||||
);
|
||||
|
||||
// (2) Прежняя версия снова единственная текущая; её ссылка активна; указатель и timestamp не двигались.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the previous version must remain resolvable");
|
||||
assert_eq!(current.snapshot.version.version, 1);
|
||||
assert_eq!(
|
||||
current.snapshot.version.digest,
|
||||
resolved.snapshot.version.digest
|
||||
);
|
||||
assert_eq!(
|
||||
current.snapshot.resource.updated_at, resolved.snapshot.resource.updated_at,
|
||||
"the optimistic-precondition timestamp must not move on rollback"
|
||||
);
|
||||
// Повторное чтение ПОСЛЕ отказа через тот же exact ref: oracle не доверяет
|
||||
// закешированному до отказа Vec (R-D).
|
||||
let bytes_after_refusal = sandbox
|
||||
.store
|
||||
.read(&old_ref)
|
||||
.expect("the previous bytes must stay readable through the same artifact reference");
|
||||
assert_eq!(
|
||||
bytes_after_refusal, bytes_before_refusal,
|
||||
"a rejected update must not touch the content of the previous version"
|
||||
);
|
||||
assert_eq!(bytes_after_refusal, b"registry payload");
|
||||
assert_eq!(
|
||||
sha256_hex(&bytes_after_refusal),
|
||||
current.snapshot.version.digest,
|
||||
"the re-read bytes must still match the recorded digest of the previous version"
|
||||
);
|
||||
// Полное состояние (ссылка, указатель, timestamps, metadata) не изменилось.
|
||||
let after_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(
|
||||
after_snapshot, before_snapshot,
|
||||
"a rolled back update must not change the current version, its reference, timestamps or metadata"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resource_versions where superseded_at is null"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the previous owning reference must stay active and undetached"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resources where current_draft_version = 1"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the current pointer must still point at version 1"
|
||||
);
|
||||
|
||||
// (3) Положительный контроль: следующий корректный update отсоединяет старую ссылку и активирует новую.
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "second".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect("a fresh valid update after the rollback must succeed");
|
||||
|
||||
assert_eq!(RowTotals::observe(&sandbox).await.versions, 2);
|
||||
assert_eq!(RowTotals::observe(&sandbox).await.owning_refs, 2);
|
||||
// Точные роли ссылок: прежняя стала detached и сохранила свой digest, новая — active (R-D).
|
||||
let superseded_source = source_state(&sandbox, &before_snapshot.artifact_source_id).await;
|
||||
assert_eq!(
|
||||
superseded_source.lifecycle, "detached",
|
||||
"the superseded version's reference must be detached"
|
||||
);
|
||||
assert!(superseded_source.detached);
|
||||
assert_eq!(
|
||||
superseded_source.digest, before_snapshot.source_digest,
|
||||
"the detached reference must keep the exact digest of the previous version"
|
||||
);
|
||||
let new_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(new_snapshot.version, 2);
|
||||
assert_eq!(new_snapshot.current_draft_version, 2);
|
||||
assert_ne!(
|
||||
new_snapshot.artifact_source_id, before_snapshot.artifact_source_id,
|
||||
"an accepted update must switch the current version to a new owning reference"
|
||||
);
|
||||
assert_eq!(new_snapshot.source_lifecycle, "active");
|
||||
assert!(!new_snapshot.source_detached);
|
||||
assert_eq!(new_snapshot.digest, sha256_hex(b"second payload"));
|
||||
assert_eq!(new_snapshot.source_digest, new_snapshot.digest);
|
||||
assert_eq!(new_snapshot.description, "second");
|
||||
assert_eq!(new_snapshot.sensitivity, "public");
|
||||
assert!(new_snapshot.superseded_is_null);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resource_versions where superseded_at is null"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"exactly one live owning reference after a successful update"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'detached' and detached_at is not null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the superseded version's reference must be detached with a timestamp"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resources where current_draft_version = 2"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
// Остаток R-D (P5) вынесен в подмодуль: health-правило ограничивает файл 1000 строками,
|
||||
// а прежние фикстуры (`sandbox`/`seeded_draft`/`RowTotals`/`DraftSnapshot`) переиспользуются.
|
||||
#[path = "resource_drafts/p5_remnant.rs"]
|
||||
mod p5_remnant;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUILD obligations, которые этот файл НЕ подтверждает (не считать покрытием по именам тестов)
|
||||
// ---------------------------------------------------------------------------
|
||||
// - `MembershipRole`/workspace access здесь не проверяется: это уровень HTTP-сервиса (таргет A).
|
||||
// - `resource_versions.digest == artifact_sources.blob_digest` и прочие metadata-сверки чтения
|
||||
// проверяются только частично (см. `story36_at03_corrupt_missing_and_mismatched_artifact_fail_closed`);
|
||||
// полная матрица рассинхронизаций digest/size/MIME/sensitivity/lifecycle — обязательство BUILD.
|
||||
@@ -0,0 +1,598 @@
|
||||
//! Остаток пакета P5 (R-D) для таргета P: ранее разрешённый объём, который не был
|
||||
//! выполнен в run100/run102 и прямо возвращён TL run103:35 (Published-снимок после
|
||||
//! реального редактирования черновика, однофакторная integrity-матрица на durable
|
||||
//! seed-ах, целочисленные границы версии и детерминированного `source_id`).
|
||||
//!
|
||||
//! Модуль подключается из `tests/integration/resource_drafts.rs` и использует те же
|
||||
//! приватные фикстуры (`sandbox`, `seeded_draft`, `registered`): рабочая копия
|
||||
//! разбита на подмодуль, потому что health-правило ограничивает файл 1000 строками.
|
||||
//! Физическое чтение байт здесь идёт через `ArtifactStore::read` по точному
|
||||
//! `artifact_ref`, поэтому digest/bytes сверяются независимым оракулом.
|
||||
|
||||
use super::{
|
||||
DraftSnapshot, RowTotals, Sandbox, WORKSPACE_ID, count, registered, sandbox, seeded_draft,
|
||||
sha256_hex, source_state,
|
||||
};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, ResolvedResourceVersion, UpdateResourceDraftRequest,
|
||||
};
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const ORIGINAL_BYTES: &[u8] = b"registry payload";
|
||||
const EDITED_BYTES: &[u8] = b"registry payload v2";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (1): реальное редактирование черновика обязано сохранить ранее полученный
|
||||
// Published-снимок версии байт-в-байт (metadata/digest/version) и её bytes.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Metadata-снимок конкретной версии и её owning-ссылки (без времени замены:
|
||||
/// `superseded_at` — ожидаемый эффект редактирования, а не часть снимка).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct PublishedRow {
|
||||
version: i32,
|
||||
kind: String,
|
||||
mime_type: String,
|
||||
size_bytes: i64,
|
||||
digest: String,
|
||||
sensitivity: String,
|
||||
created_at: String,
|
||||
artifact_source_id: String,
|
||||
source_digest: String,
|
||||
source_mime_type: String,
|
||||
source_sensitivity: String,
|
||||
}
|
||||
|
||||
impl PublishedRow {
|
||||
async fn observe(sandbox: &Sandbox, resource_id: &ResourceId, version: i32) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select v.version, v.kind, v.mime_type, v.size_bytes, v.digest, v.sensitivity,
|
||||
v.created_at::text as created_at, v.artifact_source_id,
|
||||
s.blob_digest as source_digest, s.mime_type as source_mime_type,
|
||||
s.sensitivity as source_sensitivity
|
||||
from resource_versions v
|
||||
join artifact_sources s
|
||||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||||
where v.workspace_id = $1 and v.resource_id = $2 and v.version = $3",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the published version row and its owning reference must be observable");
|
||||
Self {
|
||||
version: row.get("version"),
|
||||
kind: row.get("kind"),
|
||||
mime_type: row.get("mime_type"),
|
||||
size_bytes: row.get("size_bytes"),
|
||||
digest: row.get("digest"),
|
||||
sensitivity: row.get("sensitivity"),
|
||||
created_at: row.get("created_at"),
|
||||
artifact_source_id: row.get("artifact_source_id"),
|
||||
source_digest: row.get("source_digest"),
|
||||
source_mime_type: row.get("source_mime_type"),
|
||||
source_sensitivity: row.get("source_sensitivity"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Стала ли версия заменённой (поле вне снимка, но часть контракта обновления).
|
||||
async fn superseded(sandbox: &Sandbox, resource_id: &ResourceId, version: i32) -> bool {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select superseded_at is not null from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the superseding state of the version must be observable")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at01_real_draft_edit_preserves_the_previously_resolved_published_snapshot() {
|
||||
let sandbox = sandbox("at01_published_snapshot").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Published-снимок берётся до редактирования — это и есть «ранее полученное»
|
||||
// представление опубликованной версии (модель версии без path/filename/source-id).
|
||||
let published: ResolvedResourceVersion = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version 1 must resolve before the edit");
|
||||
assert_eq!(published.snapshot.version.version, 1);
|
||||
assert_eq!(
|
||||
published.snapshot.version.digest,
|
||||
sha256_hex(ORIGINAL_BYTES)
|
||||
);
|
||||
let published_bytes = sandbox
|
||||
.store
|
||||
.read(&published.artifact_ref)
|
||||
.expect("the resolved artifact_ref must read the exact bytes");
|
||||
assert_eq!(published_bytes, ORIGINAL_BYTES);
|
||||
let published_row = PublishedRow::observe(&sandbox, &resource_id, 1).await;
|
||||
assert_eq!(
|
||||
published_row.digest,
|
||||
sha256_hex(ORIGINAL_BYTES),
|
||||
"the published row must carry the digest of the real bytes"
|
||||
);
|
||||
assert!(
|
||||
!PublishedRow::superseded(&sandbox, &resource_id, 1).await,
|
||||
"version 1 must be current before the edit"
|
||||
);
|
||||
|
||||
let edited = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication snapshot".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: published.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, EDITED_BYTES),
|
||||
})
|
||||
.await
|
||||
.expect("a valid edit of the draft must succeed");
|
||||
assert_eq!(edited.version, 2);
|
||||
assert_ne!(edited.digest, published.snapshot.version.digest);
|
||||
|
||||
// (1) Ранее полученный Published-снимок остаётся точным: строка версии 1 и её
|
||||
// owning-ссылка не изменились ни в одном поле (metadata/digest/version).
|
||||
let replayed_row = PublishedRow::observe(&sandbox, &resource_id, 1).await;
|
||||
assert_eq!(
|
||||
replayed_row, published_row,
|
||||
"a real draft edit must not change the previously published row (version, kind, MIME, \
|
||||
size, digest, sensitivity, created_at, superseding time)"
|
||||
);
|
||||
let source = source_state(&sandbox, &replayed_row.artifact_source_id).await;
|
||||
assert_eq!(
|
||||
source.digest, published_row.digest,
|
||||
"the published version keeps its own owning reference digest"
|
||||
);
|
||||
assert!(
|
||||
PublishedRow::superseded(&sandbox, &resource_id, 1).await,
|
||||
"the accepted edit must mark the previous version as superseded"
|
||||
);
|
||||
|
||||
// (2) Байты прежнего снимка читаются по его собственному `artifact_ref` точными bytes —
|
||||
// это тот же ref, который был получен ДО редактирования.
|
||||
let old_bytes = sandbox
|
||||
.store
|
||||
.read(&published.artifact_ref)
|
||||
.expect("the previously obtained artifact_ref must keep reading the exact bytes");
|
||||
assert_eq!(old_bytes, ORIGINAL_BYTES);
|
||||
assert_eq!(sha256_hex(&old_bytes), published.snapshot.version.digest);
|
||||
|
||||
// (3) Разрешённое через API чтение заменённой версии — отказ (ссылка отсоединена
|
||||
// штатным обновлением), а не выдача «почти того же» содержимого. Наблюдаемый код
|
||||
// записывается, чтобы контракт не подменялся конкретным текстом ошибки.
|
||||
let superseded = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await;
|
||||
let superseded_observation = match &superseded {
|
||||
Ok(value) => format!(
|
||||
"accepted version={} digest={}",
|
||||
value.snapshot.version.version, value.snapshot.version.digest
|
||||
),
|
||||
Err(error) => format!("refused code={}", error.code()),
|
||||
};
|
||||
|
||||
// (4) Текущая версия переключилась на новые bytes.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.resolve_current_resource_version(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("the current version must resolve");
|
||||
assert_eq!(current.snapshot.version.version, 2);
|
||||
assert_eq!(current.snapshot.version.digest, sha256_hex(EDITED_BYTES));
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(¤t.artifact_ref)
|
||||
.expect("the new version must read its own bytes"),
|
||||
EDITED_BYTES
|
||||
);
|
||||
assert_ne!(current.artifact_ref, published.artifact_ref);
|
||||
assert!(
|
||||
superseded.is_err(),
|
||||
"a superseded version must not stay served after the edit; observed \
|
||||
{superseded_observation}"
|
||||
);
|
||||
|
||||
let card = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("the card must stay readable");
|
||||
assert_eq!(card.resource.current_draft_version, 2);
|
||||
assert_eq!(card.resource.uri, "crank://registry/draft");
|
||||
assert_eq!(card.resource.name, "registry_draft");
|
||||
assert_eq!(card.resource.kind, "text");
|
||||
assert_eq!(card.version.version, 2);
|
||||
|
||||
// (4) Итоги строк: две версии, одна живая ссылка, одна отсоединённая.
|
||||
let totals = RowTotals::observe(&sandbox).await;
|
||||
assert_eq!(totals.versions, 2);
|
||||
assert_eq!(totals.owning_refs, 2);
|
||||
assert_eq!(totals.resources, 1);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null",
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'detached' and detached_at is not null",
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (2): однофакторная integrity-матрица на durable seed-ах.
|
||||
// Каждый вектор исполняется независимо, с точным отказом и точным восстановлением,
|
||||
// поэтому первое расхождение не скрывает остальные пять (TL run103:35).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
struct ArtifactIdentity {
|
||||
blob_digest: String,
|
||||
blob_size_bytes: i64,
|
||||
blob_artifact_ref: String,
|
||||
blob_lifecycle: String,
|
||||
version_digest: String,
|
||||
version_size_bytes: i64,
|
||||
version_mime_type: String,
|
||||
version_sensitivity: String,
|
||||
source_mime_type: String,
|
||||
source_sensitivity: String,
|
||||
source_lifecycle: String,
|
||||
source_detached_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl ArtifactIdentity {
|
||||
async fn observe(sandbox: &Sandbox) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select b.digest as blob_digest, b.size_bytes as blob_size_bytes,
|
||||
b.artifact_ref as blob_artifact_ref, b.storage_lifecycle as blob_lifecycle,
|
||||
v.digest as version_digest, v.size_bytes as version_size_bytes,
|
||||
v.mime_type as version_mime_type, v.sensitivity as version_sensitivity,
|
||||
s.mime_type as source_mime_type, s.sensitivity as source_sensitivity,
|
||||
s.lifecycle as source_lifecycle, s.detached_at as source_detached_at
|
||||
from artifact_blobs b
|
||||
join artifact_sources s on s.blob_digest = b.digest
|
||||
join resource_versions v
|
||||
on v.workspace_id = s.workspace_id and v.artifact_source_id = s.source_id
|
||||
where v.superseded_at is null
|
||||
order by s.source_id
|
||||
limit 1",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the durable artifact identity must be observable");
|
||||
Self {
|
||||
blob_digest: row.get("blob_digest"),
|
||||
blob_size_bytes: row.get("blob_size_bytes"),
|
||||
blob_artifact_ref: row.get("blob_artifact_ref"),
|
||||
blob_lifecycle: row.get("blob_lifecycle"),
|
||||
version_digest: row.get("version_digest"),
|
||||
version_size_bytes: row.get("version_size_bytes"),
|
||||
version_mime_type: row.get("version_mime_type"),
|
||||
version_sensitivity: row.get("version_sensitivity"),
|
||||
source_mime_type: row.get("source_mime_type"),
|
||||
source_sensitivity: row.get("source_sensitivity"),
|
||||
source_lifecycle: row.get("source_lifecycle"),
|
||||
source_detached_at: row.get("source_detached_at"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Восстановление ровно зафиксированного значения (не «похожего»): сравнение
|
||||
/// `before == after` требует байт-в-байт того же состояния.
|
||||
async fn restore(&self, sandbox: &Sandbox) {
|
||||
sqlx::query(
|
||||
"update artifact_blobs
|
||||
set digest = $1, size_bytes = $2, artifact_ref = $3, storage_lifecycle = $4",
|
||||
)
|
||||
.bind(&self.blob_digest)
|
||||
.bind(self.blob_size_bytes)
|
||||
.bind(&self.blob_artifact_ref)
|
||||
.bind(&self.blob_lifecycle)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the blob identity must be restorable");
|
||||
sqlx::query(
|
||||
"update resource_versions
|
||||
set digest = $1, size_bytes = $2, mime_type = $3, sensitivity = $4",
|
||||
)
|
||||
.bind(&self.version_digest)
|
||||
.bind(self.version_size_bytes)
|
||||
.bind(&self.version_mime_type)
|
||||
.bind(&self.version_sensitivity)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the version metadata must be restorable");
|
||||
sqlx::query(
|
||||
"update artifact_sources
|
||||
set mime_type = $1, sensitivity = $2, lifecycle = $3, detached_at = $4",
|
||||
)
|
||||
.bind(&self.source_mime_type)
|
||||
.bind(&self.source_sensitivity)
|
||||
.bind(&self.source_lifecycle)
|
||||
.bind(self.source_detached_at)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the owning reference identity must be restorable");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_integrity_mismatch_matrix_fails_closed_without_content() {
|
||||
let sandbox = sandbox("at03_integrity_matrix").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Позитивный контроля до матрицы: durable seed реально читается точными bytes.
|
||||
let baseline = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the durable seed must resolve before any mutation");
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&baseline.artifact_ref)
|
||||
.expect("the durable seed must read its bytes"),
|
||||
ORIGINAL_BYTES
|
||||
);
|
||||
let identity = ArtifactIdentity::observe(&sandbox).await;
|
||||
|
||||
// Однофакторные мутации: меняется ровно один элемент metadata, от которого зависит
|
||||
// сверка чтения (§6). Расхождение `artifact_blobs.artifact_ref` с digest недостижимо:
|
||||
// его связывает CHECK `artifact_blobs_ref_check (artifact_ref = 'sha256:' || digest)`,
|
||||
// поэтому вектор не выдумывается, а заменён проверкой самой связи через version-digest.
|
||||
let mutations: [(&str, &str); 8] = [
|
||||
(
|
||||
"blob-size",
|
||||
"update artifact_blobs set size_bytes = size_bytes + 1",
|
||||
),
|
||||
(
|
||||
"blob-storage-lifecycle",
|
||||
"update artifact_blobs set storage_lifecycle = 'unavailable'",
|
||||
),
|
||||
(
|
||||
"version-digest",
|
||||
"update resource_versions set digest = repeat('0', 64)",
|
||||
),
|
||||
(
|
||||
"version-size",
|
||||
"update resource_versions set size_bytes = size_bytes + 1",
|
||||
),
|
||||
(
|
||||
"version-mime-type",
|
||||
"update resource_versions set mime_type = 'text/html'",
|
||||
),
|
||||
(
|
||||
"version-sensitivity",
|
||||
"update resource_versions set sensitivity = 'public'",
|
||||
),
|
||||
(
|
||||
"source-mime-type",
|
||||
"update artifact_sources set mime_type = 'text/html'",
|
||||
),
|
||||
(
|
||||
"source-lifecycle",
|
||||
"update artifact_sources set lifecycle = 'detached', detached_at = updated_at",
|
||||
),
|
||||
];
|
||||
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
let mut unexpected: Vec<&str> = Vec::new();
|
||||
for (label, mutation) in mutations {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(mutation.to_owned()))
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("mutation `{label}` must apply: {error}"));
|
||||
assert_ne!(
|
||||
ArtifactIdentity::observe(&sandbox).await,
|
||||
identity,
|
||||
"mutation `{label}` must really change the observed identity"
|
||||
);
|
||||
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await;
|
||||
match resolved {
|
||||
Err(error) if error.code() == "resource_artifact_integrity" => {
|
||||
observations.push(format!("{label}: refused {code}", code = error.code()));
|
||||
}
|
||||
Err(error) => {
|
||||
unexpected.push(label);
|
||||
observations.push(format!(
|
||||
"{label}: unexpected refusal {code}",
|
||||
code = error.code()
|
||||
));
|
||||
}
|
||||
Ok(value) => {
|
||||
unexpected.push(label);
|
||||
observations.push(format!(
|
||||
"{label}: accepted with digest={} size={}",
|
||||
value.snapshot.version.digest, value.snapshot.version.size_bytes
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Точное восстановление и повторный положительный контроль — даже если выше
|
||||
// зафиксировано расхождение.
|
||||
identity.restore(&sandbox).await;
|
||||
assert_eq!(
|
||||
ArtifactIdentity::observe(&sandbox).await,
|
||||
identity,
|
||||
"mutation `{label}` must be restored byte-exactly"
|
||||
);
|
||||
let restored = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("restore after `{label}` must resolve: {error:?}"));
|
||||
assert_eq!(
|
||||
restored, baseline,
|
||||
"restoration after `{label}` must return the exact published snapshot"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&restored.artifact_ref)
|
||||
.expect("the restored artifact must read its bytes"),
|
||||
ORIGINAL_BYTES
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
unexpected.is_empty(),
|
||||
"every one-factor integrity mismatch must fail closed with `resource_artifact_integrity` \
|
||||
and return no content; observations: {observations:?}"
|
||||
);
|
||||
assert_eq!(observations.len(), 8);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (3): целочисленные границы версии и детерминированного `source_id`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_version_and_source_id_boundaries_are_exact() {
|
||||
let sandbox = sandbox("at03_boundaries").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Версия 0 не должна «случайно» совпасть с текущей версией.
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 0)
|
||||
.await
|
||||
.expect_err("version 0 must not resolve to the current version");
|
||||
assert_eq!(error.code(), "resource_not_found");
|
||||
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, i32::MAX as u32)
|
||||
.await
|
||||
.expect_err("an unused version must be not found");
|
||||
assert_eq!(error.code(), "resource_not_found");
|
||||
|
||||
// Значения вне диапазона `integer` не могут быть связаны с колонкой `version`.
|
||||
for version in [i32::MAX as u32 + 1, u32::MAX] {
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, version)
|
||||
.await
|
||||
.expect_err("a version outside the integer range cannot be bound");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
}
|
||||
|
||||
// Детерминированный `source_id` при максимально допустимом хвосте ResourceId (96).
|
||||
let tail_96 = "a".repeat(96);
|
||||
let boundary_id = ResourceId::new(format!("res_{tail_96}"));
|
||||
let boundary_bytes = b"boundary payload";
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: boundary_id.clone(),
|
||||
uri: "crank://registry/boundary".to_owned(),
|
||||
name: "registry_boundary".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, boundary_bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a ResourceId with the maximal 96-character tail must be accepted");
|
||||
|
||||
let source_id: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(boundary_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the deterministic owning reference must be observable");
|
||||
assert_eq!(
|
||||
source_id,
|
||||
format!("src_{tail_96}_v1"),
|
||||
"the owning reference is derived from the ResourceId tail and the version"
|
||||
);
|
||||
assert!(
|
||||
source_id.len() <= 128 && source_id.len() >= 5,
|
||||
"the derived source id must stay inside the stored grammar: {source_id}"
|
||||
);
|
||||
assert_eq!(
|
||||
source_id.len(),
|
||||
4 + 96 + 2 + 1,
|
||||
"a maximal tail still produces a storable source id"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &boundary_id, 1)
|
||||
.await
|
||||
.expect("the boundary draft must resolve")
|
||||
.snapshot
|
||||
.version
|
||||
.digest,
|
||||
sha256_hex(boundary_bytes)
|
||||
);
|
||||
|
||||
// Хвост на один символ длиннее отвергается целиком: ни строки Resource, ни версии,
|
||||
// ни owning-ссылки не появляется.
|
||||
let before = RowTotals::observe(&sandbox).await;
|
||||
let tail_97 = "b".repeat(97);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new(format!("res_{tail_97}")),
|
||||
uri: "crank://registry/boundary-over".to_owned(),
|
||||
name: "registry_boundary_over".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"over boundary payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a source id longer than the stored grammar must be refused");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
assert_eq!(
|
||||
RowTotals::observe(&sandbox).await,
|
||||
before,
|
||||
"a refused over-long identifier must leave no accepted Resource, version or owning ref"
|
||||
);
|
||||
|
||||
// Прежний черновик и его связь не тронуты.
|
||||
let snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(snapshot.version, 1);
|
||||
assert_eq!(snapshot.source_lifecycle, "active");
|
||||
assert_eq!(
|
||||
source_state(&sandbox, &snapshot.artifact_source_id)
|
||||
.await
|
||||
.lifecycle,
|
||||
"active"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Story 3.7 / AC03 registry-level: immutable publication ownership, CAS и отказ
|
||||
//! без partial writes.
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL:
|
||||
//! - публикация создаёт отдельную owning-ссылку на тот же immutable blob;
|
||||
//! - Draft edit после публикации не отсоединяет publication source и не меняет snapshot;
|
||||
//! - повторный/stale publish и отказ по несовпавшему snapshot не пишут строк и не
|
||||
//! сдвигают ревизию карточки.
|
||||
|
||||
use super::*;
|
||||
|
||||
use crank_core::resource::ResourceError;
|
||||
use crank_registry::model::resource::{PublishResourceVersionRequest, ResourcePublicationRecord};
|
||||
|
||||
async fn publish_current(sandbox: &Sandbox, resource_id: &ResourceId) -> ResourcePublicationRecord {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.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, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a valid current draft must publish")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_at03_publication_owns_blob_independently_of_draft_edit() {
|
||||
let sandbox = sandbox("at37_publication_owning").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let publication = publish_current(&sandbox, &resource_id).await;
|
||||
|
||||
assert_eq!(publication.version, 1);
|
||||
assert_eq!(publication.uri, "crank://registry/draft");
|
||||
assert_eq!(publication.kind, "text");
|
||||
assert_eq!(publication.mime_type, "text/plain");
|
||||
assert_eq!(publication.sensitivity, "internal");
|
||||
assert_eq!(publication.size_bytes, 16);
|
||||
assert_eq!(publication.digest, sha256_hex(b"registry payload"));
|
||||
|
||||
let status: String = sqlx::query_scalar("select status from resources where resource_id = $1")
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable");
|
||||
assert_eq!(
|
||||
status, "published",
|
||||
"publish must switch the card to published"
|
||||
);
|
||||
|
||||
let draft_source: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_versions where resource_id = $1 and superseded_at is null",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("draft source must be queryable");
|
||||
let publication_source: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_publications where resource_id = $1 and version = 1",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication source must be queryable");
|
||||
assert_ne!(
|
||||
draft_source, publication_source,
|
||||
"publication must own a dedicated source, not the mutable draft owning ref"
|
||||
);
|
||||
|
||||
// Draft edit: новая версия, новая draft-ссылка, карточка снова Draft.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"edited payload"),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after publication must succeed");
|
||||
|
||||
let status: String = sqlx::query_scalar("select status from resources where resource_id = $1")
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable");
|
||||
assert_eq!(
|
||||
status, "draft",
|
||||
"a Draft edit must return the card to draft"
|
||||
);
|
||||
|
||||
let publication_lifecycle: String = sqlx::query_scalar(
|
||||
"select lifecycle from artifact_sources where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(&publication_source)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication source must still exist");
|
||||
assert_eq!(
|
||||
publication_lifecycle, "active",
|
||||
"a Draft edit must not detach the publication owning source"
|
||||
);
|
||||
|
||||
// Snapshot остаётся exact и читается через publication owning source.
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("published version must stay resolvable after the edit");
|
||||
assert_eq!(resolved.publication, publication);
|
||||
let bytes = sandbox
|
||||
.store
|
||||
.read(&resolved.artifact_ref)
|
||||
.expect("published bytes must stay readable");
|
||||
assert_eq!(bytes, b"registry payload");
|
||||
}
|
||||
|
||||
async fn totals(sandbox: &Sandbox) -> (i64, i64, i64, i64, i64) {
|
||||
(
|
||||
count(sandbox, "select count(*) from resources").await,
|
||||
count(sandbox, "select count(*) from resource_versions").await,
|
||||
count(sandbox, "select count(*) from artifact_sources").await,
|
||||
count(sandbox, "select count(*) from artifact_blobs").await,
|
||||
count(sandbox, "select count(*) from resource_publications").await,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_at03_stale_repeat_and_refusal_never_write_rows() {
|
||||
let sandbox = sandbox("at37_publication_stale").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let card_before = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
|
||||
// Отказ по несовпавшему snapshot (TOCTOU) — stale и без записей, ещё до публикации.
|
||||
let initial = totals(&sandbox).await;
|
||||
let mismatched = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: card_before.version.version,
|
||||
expected_digest: sha256_hex(b"not the stored payload"),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a snapshot mismatch must be refused");
|
||||
assert!(matches!(mismatched, ResourceError::Stale));
|
||||
assert_eq!(
|
||||
totals(&sandbox).await,
|
||||
initial,
|
||||
"a refused snapshot must not write rows"
|
||||
);
|
||||
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: card_before.version.version,
|
||||
expected_digest: card_before.version.digest.clone(),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a valid current draft must publish");
|
||||
assert_eq!(publication.version, 1);
|
||||
let after_publish = totals(&sandbox).await;
|
||||
let published_card = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
assert!(
|
||||
published_card.resource.updated_at > card_before.resource.updated_at,
|
||||
"a successful publish must advance the CAS revision monotonically"
|
||||
);
|
||||
|
||||
// Повтор той же публикации с прежней карточкой: CAS уже сдвинут.
|
||||
let repeated = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: 1,
|
||||
expected_digest: card_before.version.digest.clone(),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("repeating the same publish must be stale");
|
||||
assert!(matches!(repeated, ResourceError::Stale));
|
||||
|
||||
// Повтор со свежей карточкой без правки Draft: версия уже опубликована (no duplicate).
|
||||
let duplicate = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: published_card.resource.updated_at,
|
||||
expected_version: published_card.version.version,
|
||||
expected_digest: published_card.version.digest.clone(),
|
||||
expected_size_bytes: published_card.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("re-publishing an unchanged published draft must be stale");
|
||||
assert!(matches!(duplicate, ResourceError::Stale));
|
||||
|
||||
assert_eq!(
|
||||
totals(&sandbox).await,
|
||||
after_publish,
|
||||
"stale/refused publications must not write rows"
|
||||
);
|
||||
let card_after = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
assert_eq!(
|
||||
card_after.resource.updated_at, published_card.resource.updated_at,
|
||||
"a refused publish must not advance the CAS revision"
|
||||
);
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("published version must stay readable");
|
||||
assert_eq!(resolved.publication, publication);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! BUILD-ONLY PG Story 3.10 (FR-16): version-keyed template definitions (V20).
|
||||
//!
|
||||
//! Проверяет то, что видно только на реальной схеме: definition-строки
|
||||
//! insert-only, публикация ссылается на ту же version-keyed строку, правка Draft
|
||||
//! не меняет опубликованное определение, CAS-гарды не создают дублей/сирот, а
|
||||
//! artifact-строки сохраняют прежние инварианты.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
ResourceTemplateDraftRecord, UpdateResourceTemplateDraftRequest,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crank_registry::PostgresRegistry;
|
||||
|
||||
const WORKSPACE: &str = WORKSPACE_ID;
|
||||
|
||||
fn sha256_hex(value: &str) -> String {
|
||||
format!("{:x}", Sha256::digest(value.as_bytes()))
|
||||
}
|
||||
|
||||
fn definition(operation_id: &str, uri_template: &str) -> String {
|
||||
json!({
|
||||
"operation_id": operation_id,
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "format": "uuid" }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
async fn create_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
definition_json: &str,
|
||||
) -> ResourceTemplateDraftRecord {
|
||||
registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_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(),
|
||||
definition_json: definition_json.to_owned(),
|
||||
definition_digest: sha256_hex(definition_json),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template draft must be created")
|
||||
}
|
||||
|
||||
async fn publish_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
record: &ResourceTemplateDraftRecord,
|
||||
) -> Result<(), crank_core::resource::ResourceError> {
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: record.snapshot.resource.updated_at,
|
||||
expected_version: record.snapshot.version.version,
|
||||
expected_digest: record.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_template_source_is_immutable_in_postgres() {
|
||||
let sandbox = sandbox("story310_template_immutable").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_immutable");
|
||||
let first = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/immutable",
|
||||
"story310_immutable",
|
||||
&first,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(created.snapshot.version.source_kind, "template");
|
||||
assert_eq!(created.snapshot.version.size_bytes, 0);
|
||||
assert_eq!(created.source.definition_json, first);
|
||||
|
||||
// Definition-строка insert-only: UPDATE отвергается trigger-ом БД.
|
||||
let tamper = sqlx::query(
|
||||
"update resource_template_sources set definition_json = $1
|
||||
where workspace_id = $2 and resource_id = $3 and version = 1",
|
||||
)
|
||||
.bind(definition("op_story310_other", "crank://orders/{order_id}"))
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await;
|
||||
assert!(
|
||||
tamper.is_err(),
|
||||
"a stored template definition must not be mutable"
|
||||
);
|
||||
|
||||
publish_template(registry, &resource_id, &created)
|
||||
.await
|
||||
.expect("the draft must publish");
|
||||
let (publication, source) = registry
|
||||
.resolve_resource_template_publication(WORKSPACE, &resource_id, 1)
|
||||
.await
|
||||
.expect("published template snapshot must resolve");
|
||||
assert_eq!(publication.source_kind, "template");
|
||||
assert_eq!(publication.size_bytes, 0);
|
||||
assert_eq!(source.definition_json, first);
|
||||
assert_eq!(source.definition_digest, sha256_hex(&first));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_draft_edit_does_not_mutate_published_source() {
|
||||
let sandbox = sandbox("story310_template_edit").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_edit");
|
||||
let first = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let second = definition("op_story310_second", "crank://orders/{order_id}");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/edit",
|
||||
"story310_edit",
|
||||
&first,
|
||||
)
|
||||
.await;
|
||||
publish_template(registry, &resource_id, &created)
|
||||
.await
|
||||
.expect("first publication must succeed");
|
||||
// Публикация сдвигает CAS-ревизию карточки: редактирование берёт её из свежего чтения.
|
||||
let published_draft = registry
|
||||
.get_resource_draft(WORKSPACE, &resource_id)
|
||||
.await
|
||||
.expect("published draft card must be readable");
|
||||
|
||||
let updated = registry
|
||||
.update_resource_template_draft(UpdateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "retargeted".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: published_draft.resource.updated_at,
|
||||
definition_json: second.clone(),
|
||||
definition_digest: sha256_hex(&second),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit must create the next version");
|
||||
assert_eq!(updated.snapshot.version.version, 2);
|
||||
assert_eq!(updated.source.definition_json, second);
|
||||
|
||||
// Published v1 остаётся прежним source-снимком.
|
||||
let (_, published_source) = registry
|
||||
.resolve_resource_template_publication(WORKSPACE, &resource_id, 1)
|
||||
.await
|
||||
.expect("published v1 must stay readable");
|
||||
assert_eq!(published_source.definition_json, first);
|
||||
|
||||
// Устаревший precondition публикации не создаёт новую версию и не пишет сирот.
|
||||
let stale = registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: created.snapshot.resource.updated_at,
|
||||
expected_version: created.snapshot.version.version,
|
||||
expected_digest: created.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(stale, Err(crank_core::resource::ResourceError::Stale));
|
||||
let publications: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("publication count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(publications, 1, "a stale publish must not add a row");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_concurrent_publish_uses_the_existing_guard() {
|
||||
let sandbox = sandbox("story310_template_concurrent").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_concurrent");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/concurrent",
|
||||
"story310_concurrent",
|
||||
&definition("op_story310_first", "crank://orders/{order_id}"),
|
||||
)
|
||||
.await;
|
||||
let request = || PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: created.snapshot.resource.updated_at,
|
||||
expected_version: created.snapshot.version.version,
|
||||
expected_digest: created.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
// Один и тот же precondition: row-lock + CAS пропускают ровно одну публикацию.
|
||||
let (first, second) = tokio::join!(
|
||||
registry.publish_resource_template_version(request()),
|
||||
registry.publish_resource_template_version(request()),
|
||||
);
|
||||
let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
|
||||
assert_eq!(successes, 1, "exactly one concurrent publish may win");
|
||||
let stale = [first, second]
|
||||
.into_iter()
|
||||
.filter_map(Result::err)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(stale, vec![crank_core::resource::ResourceError::Stale]);
|
||||
let publications: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("publication count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(publications, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_failed_template_create_leaves_no_orphan_and_static_rows_keep_checks() {
|
||||
let sandbox = sandbox("story310_template_orphan").await;
|
||||
let registry = &sandbox.registry;
|
||||
// Static Draft по-прежнему создаётся и остаётся artifact-строкой.
|
||||
let static_id = seeded_draft(&sandbox).await;
|
||||
let static_record = registry
|
||||
.get_resource_draft(WORKSPACE, &static_id)
|
||||
.await
|
||||
.expect("static draft must stay readable");
|
||||
assert_eq!(static_record.version.source_kind, "artifact");
|
||||
assert!(static_record.version.size_bytes > 0);
|
||||
|
||||
// Дубликат URI: транзакция create шаблона обязана откатиться целиком.
|
||||
let resource_id = ResourceId::new("res_story310_template_orphan");
|
||||
let definition_json = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let duplicate = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: static_record.resource.uri.clone(),
|
||||
name: "story310_orphan".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.clone(),
|
||||
definition_digest: sha256_hex(&definition_json),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
duplicate,
|
||||
Err(crank_core::resource::ResourceError::UriDuplicate)
|
||||
);
|
||||
let orphans: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_template_sources
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("template source count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(orphans, 0, "a rejected create must not leave a definition");
|
||||
let versions: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("version count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(versions, 0, "a rejected create must not leave a version");
|
||||
}
|
||||
Reference in new issue
Block a user