Files
crank/apps/admin-api/src/service/resources/tests/publication_race.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

171 lines
7.1 KiB
Rust

//! Story 3.7 / AC03: детерминированный race «публикация vs Draft update».
//!
//! TL CODE-REVIEW (F4/race): существующие registry-тесты доказывают последовательный
//! mismatch и stale-replay, но не само чередование. Здесь используется уже принятый
//! BUILD-only шов `interleave::fire_after_resolve`: обновление того же Resource
//! исполняется ровно один раз **после** разрешения версии/байт и **до** commit
//! публикации. Ожидание: публикация отвергается как stale (HTTP 428 по существующему
//! mapping), строк публикации/owning-ссылки не появляется, CAS не сдвигается, а
//! обновлённый Draft остаётся сохранённым. Новый harness не создаётся.
use super::super::{DraftMetadata, NewDraft, PublishResource, UpdateDraft, interleave};
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use crank_core::resource::{ResourceError, ResourceStatus};
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery};
use serial_test::serial;
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const PUBLISHED_CANDIDATE: &[u8] = b"{\"publication_race\":\"v1-candidate\"}";
const LATER_EDIT: &[u8] = b"{\"publication_race\":\"v2-after-update\"}";
fn text_draft(bytes: &[u8]) -> NewDraft {
NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: "crank://story37/publication-race".to_owned(),
name: "publication_race".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 story37_at03_concurrent_draft_update_refuses_publication_without_writes() {
let harness = ResourceServiceHarness::spawn("story37_publication_race", LIMIT).await;
let service = harness.service.clone();
let workspace = WorkspaceId::new(WORKSPACE_ID);
let created = service
.create_draft(text_draft(PUBLISHED_CANDIDATE))
.await
.expect("the seed draft must be created");
let resource_id = created.resource_id;
let card = service
.card(&workspace, &resource_id)
.await
.expect("the seed card must be readable");
assert_eq!(card.version.version, 1);
let precondition = card.resource.updated_at.clone();
// Настоящее обновление того же Resource, исполняемое ровно один раз в окне
// «после разрешения версии/байт, до commit публикации».
let updating = service.clone();
let updated_id = resource_id.clone();
let updated_workspace = workspace.clone();
let update_precondition = precondition.clone();
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<(u32, String), 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: "edited during publication".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: Some(update_precondition),
immutable_fields: Vec::new(),
bytes: LATER_EDIT.to_vec(),
})
.await
.map(|card| (card.version.version, card.resource.updated_at))
.map_err(|error| error.to_string());
let _ = sender.send(outcome);
})
}));
let error = service
.publish(PublishResource {
workspace_id: workspace.clone(),
resource_id: resource_id.clone(),
expected_updated_at: Some(precondition.clone()),
})
.await
.expect_err("a publication interleaved with a Draft update must be refused");
assert_eq!(
error,
ResourceError::Stale,
"the interleaved update must surface as the accepted stale taxonomy (428 at HTTP)"
);
let concurrent = receiver
.await
.expect("the interleaved update must report its outcome");
let (updated_version, updated_at) =
concurrent.expect("the interleaved Draft update must really be accepted");
assert_eq!(
updated_version, 2,
"the concurrent update must have produced a new Draft version"
);
// Отказ публикации не сдвинул CAS: карточка осталась той, которую записал update.
let after = service
.card(&workspace, &resource_id)
.await
.expect("the card must be readable after the refused publication");
assert_eq!(
after.resource.updated_at, updated_at,
"the refused publication must not advance the card revision"
);
assert_eq!(
after.version.version, 2,
"the updated Draft must stay the current version"
);
assert_eq!(
after.resource.status,
ResourceStatus::Draft,
"the card must stay a Draft after the refused publication"
);
assert_eq!(
service
.read_content(&workspace, &resource_id)
.await
.expect("the updated Draft must stay readable"),
LATER_EDIT.to_vec(),
"the updated Draft bytes must survive the refused publication"
);
// Ни одной Published Version не появилось (ни для прежней, ни для новой версии).
for version in [1, 2] {
let resolution = harness
.registry
.resolve_resource_publication(WORKSPACE_ID, &resource_id, version)
.await
.expect_err("a refused publication must not create a Published Version");
assert_eq!(
resolution,
ResourceError::NotFound,
"no publication row/owning source must exist for version {version}"
);
}
// Владение: единственная активная owning-ссылка — новая Draft-версия; publication
// source не вставлен отказом.
let page = harness
.registry
.list_artifact_sources(ListArtifactSourcesQuery {
workspace_id: &workspace,
cursor: None,
limit: 100,
})
.await
.expect("artifact sources must be readable");
let active: Vec<_> = page
.items
.iter()
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
.collect();
assert_eq!(
active.len(),
1,
"only the current Draft keeps an active owning reference: {active:?}"
);
}