[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"
);
}