Files
crank/apps/admin-api/src/service/resources/tests/snapshot_after_resolve.rs
T
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08:22 +00:00

176 lines
7.7 KiB
Rust

//! F6 (TL run109 CODE-REVIEW): сохранность pinned-версии, когда обновление того же
//! Resource приходит **после** разрешения версии.
//!
//! Источник: CODE-REVIEW run109 F6. Существующая проверка `snapshot.rs` исполняет
//! чередование **до** `resolve_current_resource_version`, поэтому оба повторных
//! разрешения увидели бы уже новую версию и регресс «два разрешения в одном
//! ответе» такой тест не поймал бы. Здесь шаг стоит после разрешения и до
//! физического чтения байт: он либо ничего не меняет в наблюдаемом ответе
//! (honest existing GREEN для корректного кода), либо доказывает, что metadata и
//! bytes взяты из разных разрешений.
//!
//! Тест намеренно не требует RED: production-ветка уже обслуживает ответ одним
//! pinned-разрешением, а новое наблюдение — это preservation-проверка.
use super::super::{DraftMetadata, NewDraft, UpdateDraft, interleave};
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use serial_test::serial;
use sha2::{Digest, Sha256};
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const FIRST: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":1}";
const SECOND: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":2,\"late\":true}";
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn text_draft(bytes: &[u8]) -> NewDraft {
NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: "crank://snapshot/after-resolve".to_owned(),
name: "snapshot_after_resolve".to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
#[tokio::test]
#[serial]
async fn story36_at04_preview_stays_pinned_when_the_update_lands_after_resolution() {
let harness = ResourceServiceHarness::spawn("snapshot_after_resolve", LIMIT).await;
let service = harness.service.clone();
let workspace = WorkspaceId::new(WORKSPACE_ID);
let created = service
.create_draft(text_draft(FIRST))
.await
.expect("the seed draft must be created");
let resource_id = created.resource_id;
let precondition = service
.card(&workspace, &resource_id)
.await
.expect("the seed card must be readable")
.resource
.updated_at
.clone();
// Настоящее обновление того же Resource и той же PG-схемы, исполняемое ровно
// один раз в окне «после разрешения версии, до физического чтения байт».
let updating = service.clone();
let updated_id = resource_id.clone();
let updated_workspace = workspace.clone();
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<u32, String>>();
interleave::install_after_resolve(Box::new(move || {
Box::pin(async move {
let outcome = updating
.update_draft(UpdateDraft {
workspace_id: updated_workspace,
resource_id: updated_id,
description: "updated after resolution".to_owned(),
// MIME тоже меняется в рамках того же kind, поэтому ответ обязан
// остаться на MIME разрешённой версии, а не поздней (F6).
mime_type: "text/markdown".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: Some(precondition),
immutable_fields: Vec::new(),
bytes: SECOND.to_vec(),
})
.await
.map(|card| card.version.version)
.map_err(|error| error.to_string());
let _ = sender.send(outcome);
})
}));
let preview = service
.preview(&workspace, &resource_id)
.await
.expect("preview must succeed");
let concurrent = receiver
.await
.expect("the after-resolution step must report its outcome");
// Положительный контроль: позднее обновление действительно принято, поэтому
// «версия 1 в ответе» — наблюдение, а не следствие неудавшегося шага.
assert_eq!(
concurrent,
Ok(2),
"the update that landed after the resolution must really be accepted"
);
let digest_first = sha256_hex(FIRST);
let digest_second = sha256_hex(SECOND);
let expected_text = std::str::from_utf8(FIRST)
.expect("the fixture content must be UTF-8")
.to_owned();
let observed = format!(
"version={} digest={} size={} mime={} text={:?}",
preview.version.version,
preview.version.digest,
preview.version.size_bytes,
preview.version.mime_type,
preview.preview.text
);
// Весь ответ относится к версии, разрешённой до позднего обновления.
assert_eq!(
preview.version.version, 1,
"the answer must stay pinned to the version resolved before the late update: {observed}"
);
assert_eq!(
preview.version.digest, digest_first,
"the digest must belong to the resolved version: {observed}"
);
assert_eq!(
preview.version.size_bytes,
i64::try_from(FIRST.len()).expect("fixture size must fit i64"),
"the size must belong to the resolved version: {observed}"
);
assert_eq!(
preview.preview.text.as_deref(),
Some(expected_text.as_str()),
"the preview text must be the bytes of the resolved version: {observed}"
);
// Явный MIME-оракул: поздняя правка меняет именно MIME, поэтому ответ обязан
// показывать MIME разрешённой версии (F6).
assert_eq!(
preview.version.mime_type, "text/plain",
"the MIME must belong to the resolved version, not to the late update: {observed}"
);
assert_ne!(
preview.version.digest, digest_second,
"the response must not mix in bytes of the later version: {observed}"
);
assert_eq!(
preview.resource.current_draft_version, 1,
"the card metadata of this answer must not be re-read after the late update: {observed}"
);
// И валидный последующий запрос уже отдаёт версию 2 целиком: обновление настоящее.
let after = service
.card(&workspace, &resource_id)
.await
.expect("the card must be readable after the late update");
assert_eq!(after.version.version, 2, "the late update must be durable");
assert_eq!(after.version.digest, digest_second);
assert_eq!(
after.version.mime_type, "text/markdown",
"the late update's own MIME must be durable as well"
);
assert_eq!(
service
.read_content(&workspace, &resource_id)
.await
.expect("content must be readable after the late update"),
SECOND.to_vec()
);
}