CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
887 lines
36 KiB
Rust
887 lines
36 KiB
Rust
//! 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.
|