21 KiB
title, type, created, status, baseline_revision, baseline_commit, review_loop_iteration, followup_review_recommended, context, warnings, deferred
| title | type | created | status | baseline_revision | baseline_commit | review_loop_iteration | followup_review_recommended | context | warnings | deferred | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2.1 — Безопасно сохранять загруженный OpenAPI source | feature | 2026-08-25 | superseded | 182bde8ac0 |
182bde8ac0 |
0 | false |
|
|
Историческая спецификация остановленной попытки. После timeout и проверки scope заменена Stories 2.1a–2.1d; не использовать как вход для нового запуска.
Intent
Problem: Текущий OpenAPI preview принимает неограниченную JSON-строку, сразу парсит её и не сохраняет исходные bytes. Поэтому preview и последующий import не имеют общего immutable source, а upload, целостность, isolation и recovery не защищены.
Approach: Добавить самостоятельный crank-artifacts с content-addressed immutable storage, PostgreSQL metadata и reconciliation; перевести Admin API/UI на bounded multipart upload, после сохранения читать source только с проверкой digest и лишь затем передавать parser’у.
Boundaries & Constraints
Always: принимать один UTF-8 файл .yaml/.yml/.json размером не более 256 KiB; определять путь только из opaque SHA-256 ref; выполнять temp write → file fsync → atomic no-clobber publish → directory fsync; разделять физическую дедупликацию и workspace-scoped metadata; не возвращать и не логировать raw source, реальные пути или cross-scope existence; проверять digest при каждом read; сохранять compatibility read только для absolute file:// под явно configured legacy root.
Block If: безопасная реализация требует platform contract за пределами Linux reference deployment либо существующая migration authority не позволяет добавить forward-only v12 без изменения уже применённых миграций.
Never: не менять и не откатывать sprint-status.yaml; не создавать Draft Operations в story 2.1; не использовать filename/document path для filesystem path; не принимать file:// при новом upload; не следовать symlink; не перечитывать mutable external source; не включать raw bytes/examples/descriptions в ошибки, logs, traces, metrics или browser telemetry; не переписывать legacy ref и не удалять legacy file до успешной verification.
I/O & Edge-Case Matrix
| Scenario | Input / State | Expected Output / Behavior | Error Handling |
|---|---|---|---|
| Valid upload | Один multipart file, supported name/MIME, UTF-8, 1..262144 bytes | Opaque artifact ref и bounded safe metadata; bytes durable; parser получает verified bytes | No error expected |
| Invalid upload | Empty, oversized, malformed multipart, unsupported extension/MIME/encoding | Ни metadata, ни Draft, ни final artifact | Stable localized 400/413 code + Request/Trace ID, без source/parser text |
| Duplicate/race | Одинаковые bytes в одном или разных workspace, конкурентные writers | Один immutable blob, независимые scoped metadata; чужой scope неразличим | Idempotent success без existence oracle |
| Integrity failure | Metadata есть, blob missing/corrupt | Parsing не запускается | Typed integrity error, без fallback |
| Recovery | Orphan старше grace period либо concurrent referenced blob | Удаляется только подтверждённый orphan; referenced blob сохраняется | Bounded sweep report |
| Hostile/legacy path | Traversal, symlink, absolute path; либо existing legacy file:// |
New refs rejected; legacy read только под configured root и с digest verification | Typed path/integrity error; source не меняется |
Code Map
Cargo.toml— workspace members/dependencies; зарегистрировать новыйcrank-artifacts.crates/crank-artifacts/src/lib.rs— новый pure filesystem boundary: opaque refs, bounded atomic writes, verified reads, legacy-root compatibility и orphan sweep; fault-injection/clock seams нужны recovery tests.crates/crank-artifacts/tests/— known-digest, concurrent dedupe, crash/disk-full, corruption, traversal/symlink, legacy и sweep tests.crates/crank-registry/src/migrations/authority.rs:18и новыйartifact_sources_v12.{rs,sql}/schema_guard_v12.rs— forward-only metadata schema и migration contract; прошлые migration sources read-only.crates/crank-registry/src/model.rs,src/postgres/artifact_source.rs,src/postgres/mod.rs,src/lib.rs— typed metadata/repository API с workspace-scoped lookup и safe sweep claim/delete.apps/admin-api/src/service.rs:52иsrc/storage.rs:9— подключить artifact store кAdminService; существующий samplefile://path не расширять на OpenAPI.apps/admin-api/src/routes/imports.rs:25,src/app.rs:51,src/dto.rs:527— заменить preview upload на bounded multipart contract и stable localized outcomes.apps/admin-api/src/service/imports.rs:32— upload → durable bytes → metadata commit → verified read → parser; сохранить artifact identity в import job и не создавать Operations.apps/admin-api/src/error.rs:39— переиспользовать 413/envelope, добавить bounded artifact error mapping без IO/path/parser details.apps/ui/js/api.js:412,apps/ui/js/openapi-import.js:342,apps/ui/index.html:395— отправлятьFormData, реализовать RU/EN idle/validating/uploading/error/success/cancel и monotonic request token/abort против stale response.apps/admin-api/tests/integration/openapi_source.rs,crates/crank-registry/tests/integration/,apps/ui/tests/e2e/operations.spec.js— outer-surface regression matrix; текущие JSON preview tests обновить без ослабления apply assertions.
Tasks & Acceptance
Execution:
crates/crank-artifacts/**,Cargo.toml,Cargo.lock— реализовать bounded content-addressed store и exhaustive negative/recovery tests — изолировать filesystem security/durability от Admin API.crates/crank-registry/src/{migrations,postgres,model.rs,lib.rs}— добавить v12 metadata (workspace, digest/ref, size, MIME, sensitivity, lifecycle, timestamps), scoped CRUD и sweep coordination — сделать ownership и recovery транзакционными.apps/admin-api/src/{app.rs,dto.rs,error.rs,routes/imports.rs,service.rs,service/imports.rs}— внедрить multipart upload, stable errors, metadata commit и verified source read до parsing — обеспечить единые bytes preview/import.apps/ui/{index.html,js/api.js,js/openapi-import.js}— заменить textarea transport на file upload и локализованные race-safe состояния — покрыть пользовательскую поверхность AC.apps/admin-api/tests/integration/openapi_source.rs,apps/admin-api/tests/integration/openapi_import.rs,crates/crank-registry/tests/integration/**,apps/ui/tests/e2e/operations.spec.js— проверить всю матрицу, restart durability, scope isolation и отсутствие source canary в diagnostics.docs/admin-api.md,docs/runtime-config.md,docs/openapi-import.md— зафиксировать multipart/bounds, opaque ref, lifecycle/sweeper и legacy-root compatibility contract.
Acceptance Criteria:
- Given authenticated Admin API, when
.yaml/.yml/.jsonзагружается multipart, then validation filename/MIME/size/UTF-8 происходит до parsing, invalid inputs дают stable RU/EN error и не создают artifact metadata, import job или Draft. - Given valid bytes, when upload завершается и сервис перезапускается, then SHA-256 ref, fsync/atomic persistence и workspace metadata сохраняются, а verified read возвращает byte-identical source.
- Given duplicate/concurrent uploads and two workspaces, when refs читаются/listed, then physical bytes deduplicated, scoped metadata independent, а foreign ref выглядит как обычный not-found без утечки свойств.
- Given crash windows, corruption, disk-full and orphan sweep, when recovery runs after grace period, then only confirmed unreferenced blobs удаляются, referenced/concurrently-committed blobs survive, and missing/corrupt bytes block parsing with typed integrity error.
- Given traversal, symlink, absolute/file URL inputs and legacy refs, when storage reads/writes/deletes, then operations remain under roots; new file URLs are rejected; verified legacy reads preserve original ref/file.
- Given source canary and UI file replacement/cancel/racing responses, when upload succeeds or fails, then raw canary is absent from telemetry/DOM diagnostics, RU/EN state is correct, and stale response cannot replace the newest file state.
Spec Change Log
Review Triage Log
Review Findings — 2026-08-28, aggregate Story 2.1 review
- [Review][Patch][high] Подготовить private artifact root в reference Docker deployment: новый named volume сейчас имеет mode
0755, аArtifactStore::openтребует ровно0700, поэтому чистая Community-установка не стартует [apps/admin-api/Dockerfile:17] - [Review][Patch][high] Сделать cleanup expired import jobs и dangling sources исчерпывающим и периодическим: одна пачка
128при startup/preview/apply оставляет backlog и не обслуживает тихий долгоживущий процесс [crates/crank-registry/src/postgres/import_job.rs:146] - [Review][Patch][high] Изолировать повреждённые
preview_payload.source: одна malformed row не должна откатывать всю cleanup-транзакцию и блокировать startup/новые imports [crates/crank-registry/src/postgres/import_job.rs:163] - [Review][Patch][high] Устранить race
Pending/concurrent apply: запрос, прочитавший старый Pending, должен получить canonical replay завершённой job, а неsource_unavailable[apps/admin-api/src/service/imports.rs:179] - [Review][Patch][high] Зафиксировать parser contract между preview и apply: rolling upgrade не должен молча применить иной набор операций или пропустить выбранные keys после повторного parse [apps/admin-api/src/service/imports.rs:203]
- [Review][Patch][high] Сделать отмену/закрытие UI во время mutating apply outcome-aware: browser abort не отменяет серверный commit и не должен терять job authority либо провоцировать duplicate renamed drafts [apps/ui/js/openapi-import.js:442]
- [Review][Patch][medium] Подключить production cleanup stale temp files с bounded continuation, чтобы crash leftovers не накапливались и ранние shards не создавали starvation [crates/crank-artifacts/src/housekeeping.rs:321]
- [Review][Patch][medium] Сделать аварийный detach source надёжным при cancellation/shutdown вместо fire-and-forget
Drop, результат которого теряется [apps/admin-api/src/service/imports.rs:420] - [Review][Patch][medium] Добавить bounded deadlines для startup/periodic reconciliation и parsing, чтобы зависший DB/FS/parser вызов не блокировал startup либо worker навсегда [apps/admin-api/src/reconciliation.rs:729]
- [Review][Patch][medium] Перенести
ArtifactStore::clone/FD duplication внутрьspawn_blocking, соблюдая контракт отсутствия filesystem syscalls на async executor [apps/admin-api/src/reconciliation.rs:248] - [Review][Patch][medium] Нормализовать MIME через parsed essence перед validation и persistence; корректные типы с parameters/case не должны расходиться между route и service [apps/admin-api/src/routes/imports.rs:71]
- [Review][Patch][medium] Учитывать quality weights/order в
Accept-Languageи передавать locale в create/apply API, включая reparse и diagnostics [apps/admin-api/src/routes/imports.rs:125] - [Review][Patch][medium] Сохранять unknown-operation skips в canonical
ImportJobApplyResult, чтобы idempotent replay был идентичен первому ответу [apps/admin-api/src/service/imports.rs:211] - [Review][Patch][medium] Добавить
operation_keyв created response и сопоставлять UI result с preview по стабильному key, а не по имени после rename [apps/admin-api/src/service/imports.rs:272] - [Review][Patch][medium] Отделить успешный server commit от ошибки
onImported()/refresh, чтобы UI не сообщал о неуспешном создании уже созданных drafts [apps/ui/js/openapi-import.js:719] - [Review][Patch][medium] Устранить противоречие
Specify later/обязательный Base URL и очищать server selection приpagehideсогласно UX contract [apps/ui/js/openapi-import.js:273] - [Review][Patch][medium] Расширить readiness проверкой доступности artifact subsystem, а не только PostgreSQL [apps/admin-api/src/service.rs:127]
- [Review][Patch][medium] Добавить индексы для expired jobs, JSON source lookup, expired claims и reconciliation/source lookup через новую forward-only migration [crates/crank-registry/src/migrations/artifact_metadata_v12.sql:60]
- [Review][Patch][medium] Исправить idempotency detach с
expected_updated_at: None: точный replay уже выполненного unconditional detach не должен конфликтовать [crates/crank-registry/src/postgres/artifact_source.rs:504] - [Review][Patch][medium] Изолировать process-global fault seams/counters, чтобы обычный default-parallel
crank-artifactstest run был стабильным, а CI не скрывал гонку--test-threads=1[crates/crank-artifacts/tests/reconciliation.rs:1] - [Review][Patch][medium] Убрать календарную зависимость из claim-revival regression test и использовать согласованный database clock [crates/crank-registry/tests/integration/artifact_reconciliation.rs:1]
- [Review][Patch][medium] Усилить fail-closed evidence validator:
accepted=trueдопустим только для automated/pass evidence, а не произвольного schema-valid кандидата [scripts/validate-capability-run.py:125] - [Review][Patch][medium] Добавить изолированный lifecycle regression для
no_methods, проверяющий отсутствие active source, а не наличие любого detached source после нескольких ошибок [apps/admin-api/tests/integration/openapi_source.rs:350] - [Review][Patch][medium] Проверять смену языка реальным
window.setLang()/crank:langchange, а не только вручную созданнымStorageEvent[apps/ui/tests/e2e/operations.spec.js:449] - [Review][Patch][medium] Добавить process-level startup test, который доказывает вызов immediate reconciliation и lifecycle cleanup из реальной composition root [apps/admin-api/src/main.rs:206]
Дополнительный независимый проход — 2026-08-29
- [Review][Patch][high] Сохранять authority mutating apply в
sessionStorageи восстанавливать ту же job после close/pagehide/reload, блокируя изменение inputs до canonical replay. - [Review][Patch][medium] Сделать V13 schema guard точным для всех пяти cleanup/reconciliation indexes, включая key order, predicate, uniqueness и validity/readiness.
- [Review][Patch][medium] Ограничить одновременно живущие blocking parser tasks глобальным semaphore и общим 30-секундным deadline.
- [Review][Patch][medium] Продолжать stale-temp scan за omitted entry и исчерпывать страницы в пределах bounded deadline без starvation.
- [Review][Patch][medium] Ограничить все три startup maintenance phase одним внешним 30-секундным deadline.
- [Review][Patch][medium] Считать HTTP 4xx, кроме 408, definitive apply outcome: очищать replay authority и разблокировать UI.
- [Review][Dismissed][medium] Не восстанавливать прежний публичный Rust-конструктор с owned
ArtifactStore: Community API ещё pre-release, аArc<ArtifactStore>исключает FD duplication и blocking syscall на async executor; breaking cleanup ранее явно принят владельцем продукта.
Design Notes
Physical blob identity is global SHA-256, but authorization is exclusively a PostgreSQL workspace metadata relation. Sweeper uses a two-phase candidate/recheck protocol after grace period; deletion never follows caller paths. Import jobs refer to the scoped source metadata id plus digest, so subsequent stories can reverify the same bytes without embedding source in preview JSON.
Verification
Commands:
cargo test -p crank-artifacts— all storage failure/race/path tests pass.cargo test -p crank-registry --test integration -- --test-threads=1— v12 metadata, isolation and migration tests pass.cargo test -p admin-api --test integration -- --test-threads=1— multipart and preview integration tests pass.cd apps/ui && npm run e2e -- operations.spec.js— RU/EN upload states and stale-response tests pass.just verify— full Rust/config/migration/lint/test gate passes.just verify-ui— production UI bundle builds.
Aggregate review verification — 2026-08-29
cargo check -p crank-artifacts -p crank-registry -p admin-api --all-targets— pass.cargo clippy -p crank-artifacts -p crank-registry -p admin-api --all-targets -- -D warnings— pass.cargo test -p crank-artifacts --all-targets— 57 tests pass при default parallelism.cargo test -p crank-registry --test integration -- --test-threads=1— 82 pass, 1 documented production-scale query-plan test ignored.cargo test -p admin-api --lib— 37 pass;config_startup— 6 pass; Admin integration — 66 pass.npm run build, OpenAPI Playwright E2E иpython3 -m unittest tests.unit.test_validate_capability_run— pass.docker buildx build --load -f apps/admin-api/Dockerfile -t crank/admin-api:story-2-1-review .— pass; fresh named volume provisioned as0700, relative storage root rejected with exit 64.cargo fmt --all -- --check,git diff --check, JS/shell syntax и все триdocker compose config— pass.
Verdict: все подтверждённые high/medium findings устранены; Story 2.1 и её части 2.1a–2.1d приняты. Один compatibility warning отклонён как осознанный pre-release API cleanup. Production-scale million-row query-plan evidence остаётся отдельным тяжёлым CI/release gate, а не блокером корректности Story.