Files
crank/_bmad-output/implementation-artifacts/spec-2-4-artifact-claim-recovery.md
T

10 KiB

title, type, created, status, baseline_revision, baseline_commit, review_loop_iteration, context, legacy_aliases
title type created status baseline_revision baseline_commit review_loop_iteration context legacy_aliases
2.4 — Реализовать artifact claim/recovery coordinator feature 2026-08-27 done 8784964fb2 8784964fb2 0
_bmad-output/implementation-artifacts/epic-2-context.md
2.1b2b

Intent

Problem: Filesystem scanner уже находит и безопасно мутирует orphan candidates, но PostgreSQL не выдаёт fenced claims, не выполняет global reference recheck и не восстанавливает неоднозначные crash windows. Поэтому автоматический cleanup пока нельзя включить без риска удалить вновь привязанный blob либо навсегда потерять работу.

Approach: Добавить V12-compatible claim/recheck/finalize protocol и bounded Admin coordinator: startup recovery обрабатывает quarantine до final sweep, все filesystem вызовы идут через spawn_blocking, а после любой mutation cursor отбрасывается и начинается новый bounded cycle.

Boundaries & Constraints

Always: claim привязан к store-validated physical identity и непредсказуемому bounded token; global recheck учитывает active relations всех workspace; source attach блокируется при любом незавершённом claim; Deleted/AlreadyAbsent фиксируются как V12 unavailable; после возможной mutation claim не возвращается в idle; worker хранит не более одного cursor и только bounded low-cardinality counters.

Ask First: новая migration или lifecycle сверх V12 available|unavailable; раскрытие digest/path через Debug, logs, metrics, HTTP или UI; изменение 0700/same-UID threat model либо artifact layout.

Never: не удалять metadata/source rows; не считать detached relation active reference, но соблюдать grace для неё; не держать cursor после put/quarantine/delete; не выполнять blocking filesystem I/O на async executor; не добавлять upload/parser/routes/UI и не ослаблять inode/root revalidation.

I/O & Edge-Case Matrix

Scenario Input / State Expected Output / Behavior Error Handling
Claim Old final/quarantine candidate, no active relation Один fenced winner; missing blob row создаётся из store-minted capability Active/recent-detached/foreign token дают typed skip/conflict без mutation
Attach race Claim до/после concurrent source creation Общий blob lock и global recheck сохраняют referenced bytes Attach во время claim retryable; stale worker не finalize
Mutation Quarantine/delete либо ambiguous fsync Durable outcome меняет только token-owned DB state Retryable/uncertain сохраняет claim и запускает bounded recovery
Restart Expired claim, quarantine, already-absent, exhausted page Startup recovery завершается до final sweep; новый cycle продолжает работу Unsafe/integrity item классифицируется redacted и не блокирует следующие

Code Map

  • crates/crank-artifacts/src/{housekeeping.rs,model.rs} — добавить revalidated candidate→RegisteredArtifact capability и age check; сохранять redacted candidate/cursor и FD authority.
  • crates/crank-registry/src/model/artifact_source.rs, src/postgres/artifact_source.rs:18-308 — typed claim token/outcomes; reuse blob FOR UPDATE, global source query и V12 fields; ensure_blob не пропускает active claim.
  • crates/crank-registry/src/migrations/artifact_metadata_v12.sql:1-61 — read-only schema contract: unavailable означает confirmed physical absence; checksum/guard не менять.
  • apps/admin-api/src/main.rs:142-271,478-510, src/reconciliation.rs — composition и single-cursor scheduler; reuse immediate tick, MissedTickBehavior::Skip, redacted events.
  • crates/crank-registry/tests/integration/artifact_sources.rs, apps/admin-api/src/reconciliation/tests.rs — real PostgreSQL/filesystem race, restart, boundedness и FD evidence.

Tasks & Acceptance

Execution:

  • crates/crank-artifacts/src/{housekeeping.rs,model.rs,lib.rs} — mint non-forgeable registration from a revalidated candidate and expose grace eligibility without path access.
  • crates/crank-registry/src/{model/artifact_source.rs,error.rs,lib.rs}, src/postgres/artifact_source.rs — implement claim/replay/steal, global recheck, token-guarded finalize and claim-aware source revival using unchanged V12 schema.
  • apps/admin-api/src/{lib.rs,reconciliation.rs,main.rs}, Cargo.toml — run recovery-before-sweep with fixed safe defaults: immediate/15-minute ticks, 24-hour grace, 5-minute lease, 4096 traversal syscalls and 32 candidates/mutations per tick.
  • crates/crank-registry/tests/integration/**, apps/admin-api/src/reconciliation/tests.rs — cover the I/O matrix, cursor invalidation, one-cursor FD bound and crash/fault seams.

Acceptance Criteria:

  • Given concurrent claim/attach/lease-steal attempts, when one worker mutates, then active data is never removed, exactly one token controls DB transitions, and stale tokens cannot finalize.
  • Given rename/unlink/fsync/DB ambiguity or process exit, when a later tick starts, then recovery reaches deterministic unavailable or safe retry without releasing a possibly mutated claim or starving later entries.
  • Given any physical mutation, when coordinator continues, then old cursor is dropped, scanning restarts from None, open FDs remain bounded, and total work never exceeds per-tick limits.
  • Given full artifact, registry and Admin suites, when verification runs, then reports/logs contain no digest, source, workspace, token or path and all workspace gates pass.

Spec Change Log

Design Notes

V12 unavailable is the persistent absent state; republishing verified bytes may restore available only when no claim exists. A claimed row blocks source creation until finalize/recovery, closing the recheck→filesystem race without holding a PostgreSQL transaction across blocking I/O. The scanner bridge returns the existing RegisteredArtifact only after capability revalidation; it does not add a candidate digest/path accessor.

Verification

Commands:

  • cargo test -p crank-artifacts --test reconciliation -- --test-threads=1 — filesystem safety/fault matrix passes; default-parallel counter race remains deferred until all 2.1 stories finish.
  • cargo test -p crank-registry --test integration -- --test-threads=1 — claim, cross-workspace recheck, revival and restart matrix passes.
  • cargo test -p admin-api reconciliation -- --test-threads=1 — coordinator bounds, ordering, cursor/FD and recovery pass.
  • cargo fmt --all --check && cargo clippy --workspace --all-targets --all-features -- -D warnings — formatting/lints pass.
  • just migration-contract-check && just rust-boundaries && just rust-code-health && just verify — immutable V12 and workspace gates pass.

Suggested Review Order

Coordinator и production wiring

  • Единый bounded state machine гарантирует Recovery перед Sweep и сбрасывает stale cursor. reconciliation.rs:386

  • Startup запускает immediate tick и периодический 15-минутный цикл. reconciliation.rs:729

  • Admin composition открывает защищённое artifact storage после проверки master key. main.rs:234

Fencing и recovery authority

  • PostgreSQL claim/recheck/finalize сериализует attach races общим blob row lock. artifact_source.rs:31

  • Expired recovery использует CAS и запрещает resurrection прежнего token. artifact_source.rs:189

  • DB-clock helpers исключают worker clock skew из lease-решений. reconciliation.rs:1

  • Opaque 256-bit token и claim-типы закрывают observability leakage. artifact_source.rs:22

Filesystem capability и redaction

  • Candidate повторно валидируется до mint существующего RegisteredArtifact capability. recovery.rs:103

  • Фиксированные identity-free counters классифицируют unsafe, integrity и retryable outcomes. reconciliation.rs:59

Verification evidence

  • Production-backed coordinator test проверяет PostgreSQL, filesystem и cursor reset вместе. tests.rs:459

  • Anti-starvation test проводит Absent через prefix из 33 Unsafe claims. tests.rs:597

  • Row-lock expiry и concurrent recovery закреплены отдельным integration test. artifact_reconciliation.rs:16

  • Filesystem suite отвергает cursor с несовместимым namespace scope. reconciliation.rs:878