chore(bmad): preserve planning and acceptance artifacts in Git
This commit is contained in:
1 parent
fed5b7dfb3
commit
ea3b71cb5e
93 files changed
+20696
No files matched your search
@@ -0,0 +1,126 @@
|
||||
---
|
||||
title: '2.4 — Реализовать artifact claim/recovery coordinator'
|
||||
type: 'feature'
|
||||
created: '2026-08-27'
|
||||
status: 'done'
|
||||
baseline_revision: '8784964fb2e6017dd5f0c7d6ce7360875ff8efef'
|
||||
baseline_commit: '8784964fb2e6017dd5f0c7d6ce7360875ff8efef'
|
||||
review_loop_iteration: 0
|
||||
context:
|
||||
- '_bmad-output/implementation-artifacts/epic-2-context.md'
|
||||
legacy_aliases:
|
||||
- '2.1b2b'
|
||||
---
|
||||
|
||||
<frozen-after-approval reason="human-owned intent — do not modify unless human renegotiates">
|
||||
|
||||
## 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 и не блокирует следующие |
|
||||
|
||||
</frozen-after-approval>
|
||||
|
||||
## 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:**
|
||||
- [x] `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.
|
||||
- [x] `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.
|
||||
- [x] `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.
|
||||
- [x] `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`](../../apps/admin-api/src/reconciliation.rs#L386)
|
||||
|
||||
- Startup запускает immediate tick и периодический 15-минутный цикл.
|
||||
[`reconciliation.rs:729`](../../apps/admin-api/src/reconciliation.rs#L729)
|
||||
|
||||
- Admin composition открывает защищённое artifact storage после проверки master key.
|
||||
[`main.rs:234`](../../apps/admin-api/src/main.rs#L234)
|
||||
|
||||
**Fencing и recovery authority**
|
||||
|
||||
- PostgreSQL claim/recheck/finalize сериализует attach races общим blob row lock.
|
||||
[`artifact_source.rs:31`](../../crates/crank-registry/src/postgres/artifact_source.rs#L31)
|
||||
|
||||
- Expired recovery использует CAS и запрещает resurrection прежнего token.
|
||||
[`artifact_source.rs:189`](../../crates/crank-registry/src/postgres/artifact_source.rs#L189)
|
||||
|
||||
- DB-clock helpers исключают worker clock skew из lease-решений.
|
||||
[`reconciliation.rs:1`](../../crates/crank-registry/src/postgres/artifact_source/reconciliation.rs#L1)
|
||||
|
||||
- Opaque 256-bit token и claim-типы закрывают observability leakage.
|
||||
[`artifact_source.rs:22`](../../crates/crank-registry/src/model/artifact_source.rs#L22)
|
||||
|
||||
**Filesystem capability и redaction**
|
||||
|
||||
- Candidate повторно валидируется до mint существующего `RegisteredArtifact` capability.
|
||||
[`recovery.rs:103`](../../crates/crank-artifacts/src/recovery.rs#L103)
|
||||
|
||||
- Фиксированные identity-free counters классифицируют unsafe, integrity и retryable outcomes.
|
||||
[`reconciliation.rs:59`](../../apps/admin-api/src/reconciliation.rs#L59)
|
||||
|
||||
**Verification evidence**
|
||||
|
||||
- Production-backed coordinator test проверяет PostgreSQL, filesystem и cursor reset вместе.
|
||||
[`tests.rs:459`](../../apps/admin-api/src/reconciliation/tests.rs#L459)
|
||||
|
||||
- Anti-starvation test проводит Absent через prefix из 33 Unsafe claims.
|
||||
[`tests.rs:597`](../../apps/admin-api/src/reconciliation/tests.rs#L597)
|
||||
|
||||
- Row-lock expiry и concurrent recovery закреплены отдельным integration test.
|
||||
[`artifact_reconciliation.rs:16`](../../crates/crank-registry/tests/integration/artifact_reconciliation.rs#L16)
|
||||
|
||||
- Filesystem suite отвергает cursor с несовместимым namespace scope.
|
||||
[`reconciliation.rs:878`](../../crates/crank-artifacts/tests/reconciliation.rs#L878)
|
||||
Reference in new issue
Block a user