Files
crank/crates/crank-registry/tests/integration/agent_resource_bindings/rollback.rs
T
Hermes DevOps 75fe5a123c [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.
2026-10-25 10:00:22 +00:00

703 lines
25 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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;
}