STATIYA_POLUCHATEL_1
SP-08 · JOB STATE & RESUME
P2 / CANONICAL JOB STATE · LOGS ARE NOT STATE

Job state, checkpoint и безопасное возобновление

Долгий обход ресурса не должен начинаться заново после рестарта. Прогресс хранится в каноническом job state, критические этапы фиксируются checkpoints, owner gate переживает перезапуск, а статус DONE невозможен до live verification.

13job states
10checkpoint types
1active executor per job
0resume from logs

01 / Главный контракт

STATE STORE = source of truth for execution.

UI и logs показывают процесс, но после сбоя worker обязан восстановить job по persisted state/checkpoint, а не по истории терминала.

Owner approval — durable event.

Если пользователь нажал «Продолжить», это решение должно быть записано до запуска full crawl. Если сервер перезагрузился в WAITING_FOR_OWNER, сервис обязан остаться ждать.

02 / Job state machine

CREATED

Job exists; input URL accepted; no crawl started.

PREFLIGHT

Source topology is being researched and crawl_plan is being built.

PREFLIGHT_READY

Plan is persisted and valid enough to start first-batch crawl.

RUNNING_FIRST_BATCH

Crawler/classifier/order pipeline is working toward first up to 30 valid records.

WAITING_FOR_OWNER

First-batch preview frozen; job waits for explicit Continue.

RUNNING_FULL

Full crawl proceeds using approved plan/profile/version.

VALIDATING

Final corpus, IDs, batch boundaries and manifests are checked.

DEPLOYING

Validated artifacts are being published to Work staging/production target.

VERIFYING_LIVE

Published URLs are opened and compared with expected state.

DONE

Live verification passed; final dataset URL recorded.

PARTIAL

Job completed only part of intended source due explicit blocker/coverage limitation.

FAILED

Cannot continue safely without corrective work.

CANCELLED

Owner/system cancelled run; safe state preserved.

03 / Canonical job state fields

FieldPurpose
job_idStable job identity.
source_idStable source/dataset identity.
source_urlOriginal user input.
job_statusCurrent state from state machine.
job_status_reasonShort human-readable reason for current state.
state_versionMonotonic version of canonical job state.
created_atCreation timestamp.
updated_atLast persisted state change.
active_run_idCurrent/last execution attempt.
crawl_plan_idExact preflight plan snapshot in use.
crawl_plan_versionVersion frozen for this run.
classifier_profile_idSource-specific classifier profile.
classifier_profile_versionProfile version frozen for this run.
identity_versionDedup/canonical/order ruleset version.
first_batch_gate_statusNOT_REACHED / WAITING / APPROVED / REJECTED.
first_batch_preview_refPointer to staged preview artifact/state.
queue_checkpoint_refPointer to persistent crawler queue/checkpoint.
candidate_cursor/stateProgress marker for classifier pipeline.
article_set_versionCurrent logical article set version.
countsdiscovered/fetched/included/excluded/duplicates/failures/batches.
current_phaseOwner-readable phase.
current_activityCurrent operation for UI.
next_exact_actionSingle next executable action.
last_checkpoint_idLatest completed checkpoint.
last_errorNormalized error summary if any.
final_dataset_urlSet only after live verification.
final_master_index_urlSet only after live verification.

04 / Checkpoint types

IDTypeMeaning
CP-01PREFLIGHT_SAVEDcrawl_plan persisted and validated.
CP-02FIRST_BATCH_PROGRESSsafe progress during first-batch crawl.
CP-03FIRST_BATCH_READYfirst up to 30 valid records frozen for owner review.
CP-04OWNER_CONTINUEexplicit approval recorded.
CP-05FULL_CRAWL_PROGRESSperiodic durable queue/classifier progress.
CP-06CORPUS_FROZENfull logical article set/order/IDs frozen before rendering.
CP-07VALIDATION_PASSEDdataset structure passed validation.
CP-08DEPLOY_STAGEDfiles copied to deploy staging target.
CP-09LIVE_VERIFIEDproduction URLs verified.
CP-10JOB_DONEfinal outcome + URLs persisted.
Checkpoint fieldPurpose
checkpoint_idStable checkpoint ID.
job_idOwning job.
state_versionState version captured by checkpoint.
checkpoint_typeOne of CP-01...CP-10.
created_atTimestamp.
phaseCurrent phase.
status_beforeJob status before checkpoint.
status_afterJob status after checkpoint.
queue_state_refPersistent queue snapshot/reference.
pipeline_state_refClassifier/order progress reference.
artifact_refs[]Relevant staged/rendered/deployed artifacts.
countsProgress counters.
versionsplan/profile/identity/template versions.
evidence_refs[]Verification/log/test evidence.
resume_fromExact recovery instruction.
checksum/state_hashOptional integrity check for snapshot.

05 / Atomicity rules

IDRule
AR-01State update + checkpoint reference must be committed atomically where possible.
AR-02Do not mark status advanced before the corresponding durable state exists.
AR-03Do not mark checkpoint complete until verification for that checkpoint passed.
AR-04In-flight request may repeat after crash; downstream effects must be idempotent.
AR-05Artifact publication must not point MASTER INDEX to files that are not fully written.
AR-06DONE must never be written before live verification is complete.
AR-07Owner Continue must be persisted before workers resume full crawl.
Нельзя объявлять этап завершённым раньше данных.

Например, VALIDATION_PASSED фиксируется только после того, как exact corpus/build version проверен. DONE — только после live URL verification.

06 / Recovery matrix

Crash pointResume behavior
Crash during preflightReload job + last plan-building checkpoint; resume only unfinished preflight surfaces.
Crash during first batchReload queue/profile/state; continue until first 30 or source exhausted.
Crash while waiting for ownerRemain WAITING_FOR_OWNER; never auto-continue.
Crash after owner approvalApproval remains durable; resume RUNNING_FULL.
Crash during full crawlResume pending queue and idempotent candidate/article pipeline.
Crash during validationRestart validation from frozen corpus; do not recrawl unless validation finds source-data corruption.
Crash during deployDetermine whether staging/production write is partial; re-run idempotent publish or rollback.
Crash after publish before live verifyDo not set DONE; resume at VERIFYING_LIVE.
Crash after live verify before final state writeRe-verify live or prove checkpoint CP-09, then write DONE safely.
Cancel caseBehavior
User cancel before first batchStop workers, checkpoint queue, status CANCELLED.
User cancel at WAITING_FOR_OWNERRemain staged; allow later resume/new run by explicit action.
User cancel during full crawlStop at safe checkpoint; do not deploy partial corpus as completed dataset.
System shutdownGraceful checkpoint if possible; otherwise rely on last durable state.
Emergency hard killRecovery must tolerate missing final in-flight update.

07 / Consistency invariants

IDInvariant
I-01One job has exactly one canonical current state record.
I-02state_version never decreases.
I-03Job status transitions must be valid according to state machine.
I-04WAITING_FOR_OWNER cannot transition to RUNNING_FULL without persisted owner approval.
I-05Article IDs/order version used for rendering equals frozen corpus version.
I-06Validation applies to the exact artifact/corpus version later deployed.
I-07Production deploy references one immutable render/build version.
I-08final_dataset_url exists only for LIVE_VERIFIED/DONE or explicit PARTIAL publication policy.
I-09Logs may disappear; recovery still works.
I-10A replayed worker action must not create duplicate article records or duplicate deployment entries.

08 / Требования к state storage

RequirementContract
DurabilitySurvive process/server restart.
Transactional updateSupport atomic status/checkpoint writes or safe equivalent.
Small footprintMVP job metadata is compact; do not over-engineer event sourcing.
Queryable by UIFast read of current status/counters/current activity.
VersionedState version and component versions must be explicit.
References not blobsLarge raw HTML/crawl artifacts should be referenced, not embedded in one state row.
No secretsState store contains no passwords/tokens/cookies.
Backup compatibleMust fit existing Work backup/restore mechanism discovered in SP-03.
Технологию пока не фиксируем.

SQLite/PostgreSQL/Redis/другая storage-модель выбирается по SP-03 runtime facts. Этот документ фиксирует свойства, а не заставляет инфраструктуру использовать конкретную БД.

09 / Logs vs state

LayerRole
Canonical job stateWhat is true now and where to resume.
Checkpoint recordsDurable milestones and resume anchors.
Live logsHuman/AI-readable stream of what is happening right now.
Run summaryCompact terminal result of a run.
Debug artifactsOptional files/evidence for diagnosis.

10 / Structured state events

EventPayload
JOB_STATE_CHANGEDjob_id, old_status, new_status, state_version, reason
CHECKPOINT_BEGINcheckpoint_id, type, state_version
CHECKPOINT_COMMITTEDcheckpoint_id, type, state_version, counts
CHECKPOINT_FAILEDcheckpoint_id, error_code, detail
OWNER_GATE_WAITjob_id, preview_ref, included_count
OWNER_GATE_APPROVEDjob_id, approved_by, approved_at
OWNER_GATE_REJECTEDjob_id, reason
RESUME_STARTjob_id, checkpoint_id, previous_run_id, new_run_id
RESUME_OKjob_id, restored_counts, pending_work
JOB_CANCELLEDjob_id, checkpoint_id, reason
JOB_DONEjob_id, dataset_url, master_index_url, totals

11 / Failure modes

IDFailureRequired behavior
F-08-01State DB unavailableStop mutation/work; do not continue stateless.
F-08-02Checkpoint partially writtenTreat as invalid; fall back to previous complete checkpoint.
F-08-03Queue state newer than job stateRecord consistency conflict; reconcile using monotonic versions.
F-08-04Job state newer than artifact stateDo not advance; regenerate/revalidate missing artifact.
F-08-05Owner approval lostForbidden by design; approval must be durable before worker resume.
F-08-06Duplicate resume workersUse job lease/lock so only one active executor owns mutable run.
F-08-07Stale worker writes old stateReject update when expected state_version/lease does not match.
F-08-08Deploy repeated after timeoutPublish operation must be idempotent or detect already matching build.
F-08-09DONE written but live URLs brokenInvariant violation; verifier must gate DONE.

12 / Definition of Done

IDCriterion
A-08-01Forced process kill during crawl can recover from last checkpoint.
A-08-02Recovery does not require replaying console logs.
A-08-03WAITING_FOR_OWNER survives restart and never auto-continues.
A-08-04Persisted owner approval survives restart.
A-08-05At most one active mutable executor owns a job.
A-08-06Stale worker cannot overwrite newer job state.
A-08-07Repeated candidate/request actions remain idempotent.
A-08-08Validation restarts from frozen corpus without unnecessary recrawl.
A-08-09Deploy restart does not create duplicate dataset registrations.
A-08-10DONE is impossible before live verification checkpoint.
A-08-11State store contains component versions needed to reproduce/resume run.
A-08-12Long-term log history can be deleted without breaking resume.
A-08-13Job cancellation leaves recoverable, internally consistent state.
A-08-14State/checkpoint backup fits the existing Work backup mechanism.

13 / Luna Medium bounded blocks

BlockScopeExpected result
LUNA-08-AJob state schemaFields, statuses, transition validator, unit tests.
LUNA-08-BCheckpoint schemaCheckpoint types/payloads/state_version rules.
LUNA-08-CAtomic state repositoryOptimistic version or transaction-based writes.
LUNA-08-DJob lease/lockSingle active executor + stale worker protection.
LUNA-08-EResume controllerMap status/checkpoint to exact next action.
LUNA-08-FOwner gate persistenceWAITING/APPROVED/REJECTED transitions.
LUNA-08-GDeploy/verification recoveryResume-safe staged deploy and live verification.
LUNA-08-HChaos testsForced kill at each critical phase and verify recovery.
CHAOS TEST EXAMPLE 1. start full crawl 2. wait until checkpoint N 3. kill worker process forcibly 4. restart service 5. verify: - same job_id - state_version not rolled back - owner approval preserved - pending queue restored - no duplicate candidate/article records - counters remain consistent 6. continue to next checkpoint

14 / Handoff

NEXT PLANNING ARTIFACT Statiya_poluchatel_1_09_OPERATOR_UI_LIVE_LOGS.html SP-09 reads canonical job state and live event stream. UI must never invent status from text logs. Inputs for UI: job_status current_phase current_activity counts first_batch_gate_status preview_ref last_error next_exact_action final_dataset_url live structured log events