Job exists; input URL accepted; no crawl started.
01 / Главный контракт
UI и logs показывают процесс, но после сбоя worker обязан восстановить job по persisted state/checkpoint, а не по истории терминала.
Если пользователь нажал «Продолжить», это решение должно быть записано до запуска full crawl. Если сервер перезагрузился в WAITING_FOR_OWNER, сервис обязан остаться ждать.
02 / Job state machine
Source topology is being researched and crawl_plan is being built.
Plan is persisted and valid enough to start first-batch crawl.
Crawler/classifier/order pipeline is working toward first up to 30 valid records.
First-batch preview frozen; job waits for explicit Continue.
Full crawl proceeds using approved plan/profile/version.
Final corpus, IDs, batch boundaries and manifests are checked.
Validated artifacts are being published to Work staging/production target.
Published URLs are opened and compared with expected state.
Live verification passed; final dataset URL recorded.
Job completed only part of intended source due explicit blocker/coverage limitation.
Cannot continue safely without corrective work.
Owner/system cancelled run; safe state preserved.
03 / Canonical job state fields
| Field | Purpose |
|---|---|
| job_id | Stable job identity. |
| source_id | Stable source/dataset identity. |
| source_url | Original user input. |
| job_status | Current state from state machine. |
| job_status_reason | Short human-readable reason for current state. |
| state_version | Monotonic version of canonical job state. |
| created_at | Creation timestamp. |
| updated_at | Last persisted state change. |
| active_run_id | Current/last execution attempt. |
| crawl_plan_id | Exact preflight plan snapshot in use. |
| crawl_plan_version | Version frozen for this run. |
| classifier_profile_id | Source-specific classifier profile. |
| classifier_profile_version | Profile version frozen for this run. |
| identity_version | Dedup/canonical/order ruleset version. |
| first_batch_gate_status | NOT_REACHED / WAITING / APPROVED / REJECTED. |
| first_batch_preview_ref | Pointer to staged preview artifact/state. |
| queue_checkpoint_ref | Pointer to persistent crawler queue/checkpoint. |
| candidate_cursor/state | Progress marker for classifier pipeline. |
| article_set_version | Current logical article set version. |
| counts | discovered/fetched/included/excluded/duplicates/failures/batches. |
| current_phase | Owner-readable phase. |
| current_activity | Current operation for UI. |
| next_exact_action | Single next executable action. |
| last_checkpoint_id | Latest completed checkpoint. |
| last_error | Normalized error summary if any. |
| final_dataset_url | Set only after live verification. |
| final_master_index_url | Set only after live verification. |
04 / Checkpoint types
| ID | Type | Meaning |
|---|---|---|
| CP-01 | PREFLIGHT_SAVED | crawl_plan persisted and validated. |
| CP-02 | FIRST_BATCH_PROGRESS | safe progress during first-batch crawl. |
| CP-03 | FIRST_BATCH_READY | first up to 30 valid records frozen for owner review. |
| CP-04 | OWNER_CONTINUE | explicit approval recorded. |
| CP-05 | FULL_CRAWL_PROGRESS | periodic durable queue/classifier progress. |
| CP-06 | CORPUS_FROZEN | full logical article set/order/IDs frozen before rendering. |
| CP-07 | VALIDATION_PASSED | dataset structure passed validation. |
| CP-08 | DEPLOY_STAGED | files copied to deploy staging target. |
| CP-09 | LIVE_VERIFIED | production URLs verified. |
| CP-10 | JOB_DONE | final outcome + URLs persisted. |
| Checkpoint field | Purpose |
|---|---|
| checkpoint_id | Stable checkpoint ID. |
| job_id | Owning job. |
| state_version | State version captured by checkpoint. |
| checkpoint_type | One of CP-01...CP-10. |
| created_at | Timestamp. |
| phase | Current phase. |
| status_before | Job status before checkpoint. |
| status_after | Job status after checkpoint. |
| queue_state_ref | Persistent queue snapshot/reference. |
| pipeline_state_ref | Classifier/order progress reference. |
| artifact_refs[] | Relevant staged/rendered/deployed artifacts. |
| counts | Progress counters. |
| versions | plan/profile/identity/template versions. |
| evidence_refs[] | Verification/log/test evidence. |
| resume_from | Exact recovery instruction. |
| checksum/state_hash | Optional integrity check for snapshot. |
05 / Atomicity rules
| ID | Rule |
|---|---|
| AR-01 | State update + checkpoint reference must be committed atomically where possible. |
| AR-02 | Do not mark status advanced before the corresponding durable state exists. |
| AR-03 | Do not mark checkpoint complete until verification for that checkpoint passed. |
| AR-04 | In-flight request may repeat after crash; downstream effects must be idempotent. |
| AR-05 | Artifact publication must not point MASTER INDEX to files that are not fully written. |
| AR-06 | DONE must never be written before live verification is complete. |
| AR-07 | Owner Continue must be persisted before workers resume full crawl. |
Например, VALIDATION_PASSED фиксируется только после того, как exact corpus/build version проверен. DONE — только после live URL verification.
06 / Recovery matrix
| Crash point | Resume behavior |
|---|---|
| Crash during preflight | Reload job + last plan-building checkpoint; resume only unfinished preflight surfaces. |
| Crash during first batch | Reload queue/profile/state; continue until first 30 or source exhausted. |
| Crash while waiting for owner | Remain WAITING_FOR_OWNER; never auto-continue. |
| Crash after owner approval | Approval remains durable; resume RUNNING_FULL. |
| Crash during full crawl | Resume pending queue and idempotent candidate/article pipeline. |
| Crash during validation | Restart validation from frozen corpus; do not recrawl unless validation finds source-data corruption. |
| Crash during deploy | Determine whether staging/production write is partial; re-run idempotent publish or rollback. |
| Crash after publish before live verify | Do not set DONE; resume at VERIFYING_LIVE. |
| Crash after live verify before final state write | Re-verify live or prove checkpoint CP-09, then write DONE safely. |
| Cancel case | Behavior |
|---|---|
| User cancel before first batch | Stop workers, checkpoint queue, status CANCELLED. |
| User cancel at WAITING_FOR_OWNER | Remain staged; allow later resume/new run by explicit action. |
| User cancel during full crawl | Stop at safe checkpoint; do not deploy partial corpus as completed dataset. |
| System shutdown | Graceful checkpoint if possible; otherwise rely on last durable state. |
| Emergency hard kill | Recovery must tolerate missing final in-flight update. |
07 / Consistency invariants
| ID | Invariant |
|---|---|
| I-01 | One job has exactly one canonical current state record. |
| I-02 | state_version never decreases. |
| I-03 | Job status transitions must be valid according to state machine. |
| I-04 | WAITING_FOR_OWNER cannot transition to RUNNING_FULL without persisted owner approval. |
| I-05 | Article IDs/order version used for rendering equals frozen corpus version. |
| I-06 | Validation applies to the exact artifact/corpus version later deployed. |
| I-07 | Production deploy references one immutable render/build version. |
| I-08 | final_dataset_url exists only for LIVE_VERIFIED/DONE or explicit PARTIAL publication policy. |
| I-09 | Logs may disappear; recovery still works. |
| I-10 | A replayed worker action must not create duplicate article records or duplicate deployment entries. |
08 / Требования к state storage
| Requirement | Contract |
|---|---|
| Durability | Survive process/server restart. |
| Transactional update | Support atomic status/checkpoint writes or safe equivalent. |
| Small footprint | MVP job metadata is compact; do not over-engineer event sourcing. |
| Queryable by UI | Fast read of current status/counters/current activity. |
| Versioned | State version and component versions must be explicit. |
| References not blobs | Large raw HTML/crawl artifacts should be referenced, not embedded in one state row. |
| No secrets | State store contains no passwords/tokens/cookies. |
| Backup compatible | Must fit existing Work backup/restore mechanism discovered in SP-03. |
SQLite/PostgreSQL/Redis/другая storage-модель выбирается по SP-03 runtime facts. Этот документ фиксирует свойства, а не заставляет инфраструктуру использовать конкретную БД.
09 / Logs vs state
| Layer | Role |
|---|---|
| Canonical job state | What is true now and where to resume. |
| Checkpoint records | Durable milestones and resume anchors. |
| Live logs | Human/AI-readable stream of what is happening right now. |
| Run summary | Compact terminal result of a run. |
| Debug artifacts | Optional files/evidence for diagnosis. |
10 / Structured state events
| Event | Payload |
|---|---|
| JOB_STATE_CHANGED | job_id, old_status, new_status, state_version, reason |
| CHECKPOINT_BEGIN | checkpoint_id, type, state_version |
| CHECKPOINT_COMMITTED | checkpoint_id, type, state_version, counts |
| CHECKPOINT_FAILED | checkpoint_id, error_code, detail |
| OWNER_GATE_WAIT | job_id, preview_ref, included_count |
| OWNER_GATE_APPROVED | job_id, approved_by, approved_at |
| OWNER_GATE_REJECTED | job_id, reason |
| RESUME_START | job_id, checkpoint_id, previous_run_id, new_run_id |
| RESUME_OK | job_id, restored_counts, pending_work |
| JOB_CANCELLED | job_id, checkpoint_id, reason |
| JOB_DONE | job_id, dataset_url, master_index_url, totals |
11 / Failure modes
| ID | Failure | Required behavior |
|---|---|---|
| F-08-01 | State DB unavailable | Stop mutation/work; do not continue stateless. |
| F-08-02 | Checkpoint partially written | Treat as invalid; fall back to previous complete checkpoint. |
| F-08-03 | Queue state newer than job state | Record consistency conflict; reconcile using monotonic versions. |
| F-08-04 | Job state newer than artifact state | Do not advance; regenerate/revalidate missing artifact. |
| F-08-05 | Owner approval lost | Forbidden by design; approval must be durable before worker resume. |
| F-08-06 | Duplicate resume workers | Use job lease/lock so only one active executor owns mutable run. |
| F-08-07 | Stale worker writes old state | Reject update when expected state_version/lease does not match. |
| F-08-08 | Deploy repeated after timeout | Publish operation must be idempotent or detect already matching build. |
| F-08-09 | DONE written but live URLs broken | Invariant violation; verifier must gate DONE. |
12 / Definition of Done
| ID | Criterion |
|---|---|
| A-08-01 | Forced process kill during crawl can recover from last checkpoint. |
| A-08-02 | Recovery does not require replaying console logs. |
| A-08-03 | WAITING_FOR_OWNER survives restart and never auto-continues. |
| A-08-04 | Persisted owner approval survives restart. |
| A-08-05 | At most one active mutable executor owns a job. |
| A-08-06 | Stale worker cannot overwrite newer job state. |
| A-08-07 | Repeated candidate/request actions remain idempotent. |
| A-08-08 | Validation restarts from frozen corpus without unnecessary recrawl. |
| A-08-09 | Deploy restart does not create duplicate dataset registrations. |
| A-08-10 | DONE is impossible before live verification checkpoint. |
| A-08-11 | State store contains component versions needed to reproduce/resume run. |
| A-08-12 | Long-term log history can be deleted without breaking resume. |
| A-08-13 | Job cancellation leaves recoverable, internally consistent state. |
| A-08-14 | State/checkpoint backup fits the existing Work backup mechanism. |
13 / Luna Medium bounded blocks
| Block | Scope | Expected result |
|---|---|---|
| LUNA-08-A | Job state schema | Fields, statuses, transition validator, unit tests. |
| LUNA-08-B | Checkpoint schema | Checkpoint types/payloads/state_version rules. |
| LUNA-08-C | Atomic state repository | Optimistic version or transaction-based writes. |
| LUNA-08-D | Job lease/lock | Single active executor + stale worker protection. |
| LUNA-08-E | Resume controller | Map status/checkpoint to exact next action. |
| LUNA-08-F | Owner gate persistence | WAITING/APPROVED/REJECTED transitions. |
| LUNA-08-G | Deploy/verification recovery | Resume-safe staged deploy and live verification. |
| LUNA-08-H | Chaos tests | Forced kill at each critical phase and verify recovery. |