[skip ci] wip: preserve Hermes crank development checkpoint

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

No files matched your search

@@ -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(&current.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");
}