From 434b2ec7bbeae221b0cd0436591af100baac886e Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 11 Nov 2026 21:46:25 -0500 Subject: [PATCH] docs(architecture): reconcile publication transaction boundary, projection versioning, and cleanup separation in Issue 5 - Enforce BEGIN IMMEDIATE write-serialization boundary prior to response snapshot assembly. - Atomically commit final submission, COMPLETED status, and publication intent in Path A. - Version export projections in publication intent and validate reconstructed hashes. - Decouple Phase 1 read-only extraction from Phase 2 post-verification writable WAL checkpointing. - Mandate explicit closure of Phase 1 connection before opening Phase 2 cleanup. - Enforce dual advisory locking (per-attempt and destination) and atomic no-replace publication. - Decouple operational exit codes: separate EXPORT_IO_ERROR from CLEANUP_PENDING and conflicts. --- docs/architecture.md | 61 ++++++++++++++----- .../0006-ephemeral-sqlite-session-journal.md | 33 +++++----- .../0007-atomic-json-export-contract.md | 43 ++++++++++--- 3 files changed, 100 insertions(+), 37 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index e87f408..5190f42 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -148,22 +148,55 @@ During active assessment, `live-quiz` maintains state in a temporary SQLite data - **Grace-Period Expiration:** If the 2-hour grace period expires without resumption, the server process terminates cleanly to prevent zombie processes, retaining the journal with status `PAUSED` and emitting `outcome: SUSPENDED` on stdout. - Unexpected kills (`SIGKILL`, power failure) leave the journal intact for recovery. -### 5.3 Atomic Publication & Journal Deletion -Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`): -1. The server serializes the final attempt payload, preserving all submitted responses, acknowledged unsubmitted drafts (as `DRAFT`), and unattempted questions (as `UNANSWERED`). -2. Writes to a temporary file (`.attempt.json.tmp`) in the destination directory. -3. Validates the JSON structure and flushes/syncs to disk. -4. Atomically renames the file to the final destination (`attempt.json`). -5. Closes database handles and unlinks the temporary SQLite journal file set (`.sqlite3`, `-wal`, `-shm`). -6. Exits with code 0. +### 5.3 Ten-Step Atomic Publication Pipeline & Durability Contract +Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), publication executes through a strict 10-step durability pipeline protected by dual advisory locks (per-attempt and destination-level): +1. **Dual Advisory Concurrency Locks:** Acquire exclusive locks via `fcntl`/`flock` on: + - Per-attempt lock file (`~/.local/state/live-quiz/locks/attempt-.lock`), coordinating publication and recovery. + - Destination-level lock file (`~/.local/state/live-quiz/locks/dest-.lock`), coordinating publications across different attempts targeting the same path. + Locks are retained throughout publication and cleanup, and are never unlinked while held. +2. **Transaction-Bounded Payload Preparation & Canonical Serialization:** + - Execute `BEGIN IMMEDIATE` on the writable SQLite connection to establish the write-serialization boundary before snapshot extraction. + - **Path A (Final Submission → `COMPLETED`):** The final question submission mutation (`status = SUBMITTED`), the transition to `COMPLETED`, the complete response snapshot, and `publication_intent` are constructed and committed within this single transaction. The final response is never acknowledged as submitted without atomically committing assessment completion. + - **Path B (Timeout / Early Close):** The transaction lock is established before extracting the snapshot (capturing current drafts and unanswered questions) and committing `TIMED_OUT` or `CLOSED_EARLY` alongside `publication_intent`. + - Validate payload structurally against target `attempt.schema.json`. Serialize the canonical payload using RFC 8785 Canonical JSON (deterministic key ordering, UTF-8, normalized numbers) and calculate `expected_sha256`. +3. **Atomic Terminal Commitment & Publication Intent:** Within the open transaction, atomically commit: + - Terminal lifecycle state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`). + - Final response snapshot (incorporating the final submission in Path A). + - Immutable `publication_intent`: `target_schema_version`, `export_projection_version: "1"`, `destination_path`, `canonicalization_version: "1"`, `expected_sha256`. + - Execute `COMMIT;`. Filesystem publication then proceeds using the already-determined canonical bytes. +4. **Destination Conflict Pre-Check:** Under the destination lock, inspect `destination_path`. If an artifact exists with a different `attempt_id`, abort immediately with `CONFLICT_DIFFERENT_ATTEMPT` (exit 2) without writing or renaming. Overwriting another attempt's artifact is strictly prohibited. +5. **Attempt-Specific Temporary File Write & Fsync:** Write canonical bytes to `.attempt..tmp` in the destination directory, flush, and `fsync` the file descriptor. +6. **Atomic Rename / Link:** Atomically rename `.attempt..tmp` to `attempt.json` (on Linux, using `renameat2(..., RENAME_NOREPLACE)` or atomic link/rename guarantees no race overwrites another attempt's artifact). +7. **Destination Directory Fsync:** Open parent directory descriptor and `fsync` directory metadata, guaranteeing rename persistence across power failures. +8. **Verified WAL Checkpoint:** Through the open writable connection, execute passive/truncate WAL checkpoint (`PRAGMA wal_checkpoint(TRUNCATE);`) and verify completion (`busy == 0, log == 0`). +9. **Clean Close & Ordered Journal Cleanup:** Close all database handles cleanly. SQLite removes/truncates `-shm` and `-wal`. Then verify companion removal (unlinking `-wal` and `-shm` explicitly if still present), and unlink the primary `.sqlite3` database file **last**. +10. **Structured Process Outcome:** Emit single-line JSON outcome packet on stdout and exit 0 (`SUCCESS_FINALIZED`). -*Invariant:* The temporary journal file set is never deleted if export publication fails. Recovery (`live-quiz recover`) retries publication under the exact same `attempt_id`. +*Operational Decoupling:* +- If publication fails during steps 1–7 (e.g. disk full, permission denied, destination conflict, directory sync failure), the process exits with `EXPORT_IO_ERROR` (code 1) or conflict codes (2, 3) and the complete journal file set remains intact. +- If publication succeeds through step 7 but checkpoint or journal cleanup (steps 8–9) fails, the process exits with `CLEANUP_PENDING` (code 6), signaling that `attempt.json` is durable and verified, but journal removal requires retry. -### 5.4 Two Distinct Recovery Paths -Invoking `live-quiz recover --from-path ~/.local/state/live-quiz/sessions/.sqlite3` routes deterministically based on journal state: -1. **Nonterminal Recovery:** If the journal records an active or paused attempt (`RUNNING` or `PAUSED`), recovery restores the authoritative countdown clock, re-mounts acknowledged drafts, resumes the local HTTP server, and displays an in-browser resume control under the exact same `attempt_id`. -2. **Terminal Export Recovery:** If the journal already records a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`) but atomic export failed, recovery reconstructs and retries `attempt.json` publication *without reopening the assessment, restarting the timer, or permitting further modifications*. -In both paths, the temporary SQLite journal file set (`.sqlite3`, `-wal`, `-shm`) is unlinked only after durable export publication succeeds. +### 5.4 Two Distinct Recovery Paths & Idempotency Verification +Invoking `live-quiz recover --from-path ` acquires the shared advisory locks (per-attempt and destination lock) and routes deterministically: +1. **Nonterminal Recovery (`RUNNING` or `PAUSED`):** + - Applies in-place transactional migrations if the internal journal schema version differs from the current engine. + - Restores the authoritative countdown clock, re-mounts acknowledged drafts, resumes the local HTTP server, and displays an in-browser resume control under the exact same `attempt_id`. +2. **Terminal Export Recovery (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`):** + - **Phase 1: Read-Only Historical Extraction & Reconstruction:** + - Opens SQLite with a read-only connection (`mode=ro`), reading existing `-wal` and `-shm` frames without mutating user tables or schema on disk. + - Reads persisted `publication_intent`. Legacy journals lacking `publication_intent` are explicitly rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5) because their target schema and reference hash cannot be verified deterministically. + - Reconstructs canonical bytes using the versioned export projection (`export_projection_version`). Before publishing, recovery calculates the SHA-256 digest of the reconstructed bytes and verifies that it strictly matches `expected_sha256`. If a mismatch occurs, recovery halts closed (`CONFLICT_INTEGRITY_MISMATCH`, exit 3) and preserves the journal. + - **Idempotency Verification against Persisted Hash:** + - *Artifact does not exist:* Publishes reconstructed canonical bytes via steps 4–7. + - *Artifact exists with matching `attempt_id` and matching `expected_sha256`:* Previous publication succeeded; advances directly to Phase 2 cleanup. + - *Artifact exists with different `attempt_id`:* Halts immediately, preserves journal, emits `CONFLICT_DIFFERENT_ATTEMPT`, and exits code 2. + - *Artifact exists with matching `attempt_id` but differing SHA-256:* Halts immediately, preserves journal, emits `CONFLICT_INTEGRITY_MISMATCH`, and exits code 3. + - **Phase 2: Post-Verification Writable Cleanup Connection:** + - Opened only after Phase 1's read-only connection and read transaction are closed cleanly, ensuring no lingering reader locks prevent checkpointing. + - Opened only after `attempt.json` has been durably published, verified against `expected_sha256`, and destination directory `fsync` has completed. + - Connects in writable mode solely to execute `PRAGMA wal_checkpoint(TRUNCATE);` with verified completion (`busy == 0, log == 0`). Schema migrations or table mutations are strictly prohibited on this connection. + - Closes connection cleanly, unlinks companion files (`-wal`, `-shm`), unlinks `.sqlite3` **last**, emits `SUCCESS_FINALIZED`, and exits 0. If checkpointing fails, journal is kept intact and process exits with `CLEANUP_PENDING` (code 6). + - **Partial Cleanup Invariant:** Because cleanup unlinks companion files first and `.sqlite3` last, orphaned `-wal` or `-shm` files without `.sqlite3` represent an unexpected anomaly. Recovery halts safely and reports an integrity error rather than silently deleting orphaned files. --- diff --git a/docs/decisions/0006-ephemeral-sqlite-session-journal.md b/docs/decisions/0006-ephemeral-sqlite-session-journal.md index 309ad7b..c28df4c 100644 --- a/docs/decisions/0006-ephemeral-sqlite-session-journal.md +++ b/docs/decisions/0006-ephemeral-sqlite-session-journal.md @@ -38,21 +38,26 @@ stateDiagram-v2 end note ``` -4. **Durability Invariants & Engine Pragmas:** +4. **Durability Invariants, Journal Schema Versioning & Dual Advisory Locking:** - **Commit-Before-Ack:** The HTTP server commits transactions to SQLite *before* returning a successful `200 OK` acknowledgement to the client for any submission or autosaved draft. - - **Engine Configuration:** SQLite runs in Write-Ahead Logging mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;`). `synchronous=FULL` ensures SQLite performs the required WAL synchronization after each transaction commit, providing durability against process and system failures under the documented filesystem and storage assumptions. - - **Storage Location & Journal File Set:** Journals reside on persistent local storage (`~/.local/state/live-quiz/sessions/`), never in volatile tmpfs. In WAL mode, the journal consists of the primary database (`.sqlite3`) and its companion files (`.sqlite3-wal`, `.sqlite3-shm`). Because committed transactions may reside in the `-wal` file before checkpointing, recovery and lifecycle operations must manage and preserve the entire journal file set. - - **Crash Recovery Scope:** Recovery guarantees restoration of all *acknowledged* state. Unacknowledged in-flight client keystrokes that never completed an HTTP transaction are explicitly excluded. - - **Active-Time Recovery:** Active time is measured via a monotonic clock and checkpointed periodically (~1s interval). On recovery after an unexpected crash, the active countdown resumes from the last committed checkpoint. Process downtime while dead is excluded from the active-time budget and recorded separately as an interruption event. -5. **Journal Destruction Invariant & Draft Preservation:** - - Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), the server serializes `attempt.json`, preserving all submitted responses, acknowledged unsubmitted drafts (as `DRAFT`), and unattempted questions (as `UNANSWERED`). - - The temporary SQLite journal file set (`.sqlite3`, `-wal`, `-shm`) is unlinked **only after durable export publication succeeds** and all database connections are closed. If publication fails, the journal remains intact for retry via recovery. -6. **Explicit Recovery Command & Two Recovery Paths:** - - If a process is killed unexpectedly (`SIGKILL`) or grace period expires while paused, the journal set remains on disk. - - Running `live-quiz recover --from-path ` inspects journal state and executes one of two deterministic paths: - 1. **Nonterminal Recovery:** For `RUNNING` or `PAUSED` attempts, validates the journal set (leveraging companion `-wal`), restores the authoritative clock, reloads drafts, and resumes the server under the exact same `attempt_id`. - 2. **Terminal Export Recovery:** If the journal already records a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`) but publication failed, recovery retries `attempt.json` publication directly from the journal without reopening the assessment session, restarting the timer, or permitting further modifications. - - *Recovery Idempotency:* If recovery is invoked on a journal whose `attempt.json` was already successfully published, it verifies the export, cleans up the journal file set, and exits cleanly. + - **Engine Configuration:** SQLite runs in Write-Ahead Logging mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;`). `synchronous=FULL` ensures SQLite performs the required WAL synchronization after each transaction commit under documented filesystem/storage assumptions. + - **Independent Journal Schema Versioning:** SQLite journals declare an internal schema version (`schema_version`), evolved independently from external `attempt.json` schemas. Historical nonterminal journals are migrated directly to the current internal version via version-dispatched adapters (V1→Vcurrent). + - **Storage Location & Journal File Set:** Journals reside on persistent local storage (`~/.local/state/live-quiz/sessions/`), never in volatile tmpfs. The journal file set consists of `.sqlite3`, `.sqlite3-wal`, and `.sqlite3-shm`. + - **Dual Advisory Lock Scope:** All publication and recovery operations synchronize using exclusive advisory lock files in `~/.local/state/live-quiz/locks/` (per-attempt lock `attempt-.lock` and destination lock `dest-.lock`), which are never unlinked while held. + - **Crash Recovery Scope:** Recovery guarantees restoration of all *acknowledged* state. Active time resumes from the last committed ~1s checkpoint; downtime is excluded. +5. **Atomic Terminal Commitment & Safe Ordered Destruction:** + - **Atomic Terminal Transaction & Path Distinction:** The SQLite write boundary is established before final snapshot extraction via `BEGIN IMMEDIATE`: + - *Path A (Final Submission → `COMPLETED`):* The response mutation to `SUBMITTED`, transition to `COMPLETED`, complete response snapshot, and `publication_intent` (`target_schema_version`, `export_projection_version: "1"`, `canonicalization_version: "1"`, `destination_path`, `expected_sha256`) are committed in one single atomic transaction. The final response is never acknowledged without atomically committing completion. + - *Path B (Timeout / Early Close):* The transaction lock is established before extracting the snapshot (capturing current drafts and unanswered questions) and committing `TIMED_OUT` or `CLOSED_EARLY` alongside `publication_intent`. + - **Safe Ordered Deletion:** The journal is destroyed only after publication durability (including directory `fsync`) is established: through an open writable connection execute verified WAL checkpoint (`PRAGMA wal_checkpoint(TRUNCATE);`) → close all database connections cleanly → verify companion removal (unlinking `-wal` and `-shm` explicitly if present) → unlink primary `.sqlite3` **last**. + - If cleanup fails after durable export, `live-quiz` exits with `CLEANUP_PENDING` (code 6), preserving `.sqlite3` for cleanup retry. +6. **Recovery Paths & Hash-Verified Idempotency:** + - **Nonterminal Recovery:** In-place transactional migration to current internal schema; live assessment resumed. + - **Terminal Export Recovery:** Decouples Phase 1 read-only extraction from Phase 2 post-verification writable cleanup: + - *Phase 1 (Read-Only):* Uses read-only connection (`mode=ro`) to read existing WAL frames without mutating database tables or schema; reconstructs export using `export_projection_version` and verifies against persisted `expected_sha256`. Legacy journals lacking `publication_intent` are rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5). Phase 1 read-only connection is closed cleanly before Phase 2. + - *Idempotency Verification:* Compares existing destination artifacts against persisted `expected_sha256`. Matching hash triggers Phase 2 cleanup; mismatch triggers an integrity conflict (exit 3); different `attempt_id` triggers artifact conflict (exit 2). + - *Phase 2 (Writable Cleanup):* Opened only after Phase 1 connection is closed and durable publication is established; executes verified WAL checkpoint without schema or table modifications, closes connection, and unlinks companions then `.sqlite3` last. + - **Orphan Anomaly Rule:** Orphaned `-wal` or `-shm` files without `.sqlite3` represent an unexpected anomaly; recovery halts safely and reports an integrity error without deleting files. ## Alternatives Considered - **Permanent SQLite LMS Database:** Rejected. Burdening `live-quiz` with multi-workspace relational history, cross-project analytics, and long-term migrations creates severe scope creep. `live-quiz` is an assessment execution harness, not a full Learning Management System. diff --git a/docs/decisions/0007-atomic-json-export-contract.md b/docs/decisions/0007-atomic-json-export-contract.md index 2d5c37b..b0087d6 100644 --- a/docs/decisions/0007-atomic-json-export-contract.md +++ b/docs/decisions/0007-atomic-json-export-contract.md @@ -8,16 +8,27 @@ When `live-quiz` concludes, it must hand off the assessment evidence to caller w ## Decision Establish **`attempt.json` as a standardized, versioned JSON contract** published via an atomic file-replacement pattern: -1. **Atomic Publication Pipeline:** - - The final attempt data is serialized to JSON conforming to the versioned attempt schema contract (`attempt.schema.json`). - - Written to a temporary file (`.attempt.json.tmp`) within the target directory. - - Validated for structural correctness and flushed/fsynced to persistent storage. - - Atomically renamed to the final destination path (`attempt.json`). - - *Failure Guarantee:* If publication fails at any stage (e.g. disk full, permissions error), the temporary SQLite journal file set is retained intact, and the process exits with an error status. Recovery (`live-quiz recover`) retries publication under the exact same `attempt_id`. -2. **Reattempt vs. Recovery Semantics:** +1. **Ten-Step Atomic Publication Pipeline & Directory Durability:** + Publication follows a strict 10-step sequence protected by dual advisory locks (per-attempt lock `attempt-.lock` and destination lock `dest-.lock`): + - Acquire exclusive advisory locks (never unlinked while held). + - Establish write-serialization boundary via `BEGIN IMMEDIATE`: + - *Path A (Final Submission → `COMPLETED`):* The response mutation to `SUBMITTED`, transition to `COMPLETED`, complete response snapshot, and `publication_intent` (`target_schema_version`, `export_projection_version: "1"`, `canonicalization_version: "1"`, `destination_path`, `expected_sha256`) are committed together in one atomic transaction. + - *Path B (Timeout / Early Close):* The transaction is established before reading the final response snapshot and committing terminal status (`TIMED_OUT`/`CLOSED_EARLY`) and `publication_intent`. + - Validate structurally and serialize canonical payload conforming to RFC 8785 Canonical JSON, computing `expected_sha256` prior to `COMMIT;`. + - Destination conflict check: under destination lock, verify destination does not hold a different `attempt_id` (prohibiting overwriting another attempt's artifact). + - Write canonical bytes to attempt-specific temporary file `.attempt..tmp` in destination directory, flush, and `fsync` file descriptor. + - Atomically link/rename `.attempt..tmp` to `attempt.json` (using atomic no-replace semantics e.g. `renameat2(..., RENAME_NOREPLACE)`). + - `fsync` the parent directory descriptor to guarantee rename durability across power failure. + - Verified WAL checkpoint through open writable connection (`PRAGMA wal_checkpoint(TRUNCATE);`). + - Clean close & ordered journal cleanup: close handles cleanly → unlink `-wal` → unlink `-shm` → unlink primary `.sqlite3` **last**. + - Emit machine-readable outcome on stdout and exit 0 (`SUCCESS_FINALIZED`). +2. **Reattempt vs. Recovery Semantics & Idempotency Verification:** - **Reattempt (`live-quiz start`):** Launches a fresh execution against the *same* immutable assessment definition, generating a distinct new `attempt_id`. - - **Nonterminal Recovery (`live-quiz recover`):** Resumes an interrupted or paused attempt, restoring clock and drafts under the existing `attempt_id`. - - **Terminal Export Recovery (`live-quiz recover`):** Retries failed atomic publication directly from the terminal journal without reopening the assessment, restarting the timer, or permitting answer modifications. + - **Nonterminal Recovery (`live-quiz recover`):** In-place transactional migration; resumes interrupted or paused live assessment under the existing `attempt_id`. + - **Terminal Export Recovery (`live-quiz recover`):** + - *Phase 1 (Read-Only):* Opens SQLite with read-only connection (`mode=ro`), reading existing WAL frames without mutating tables or schema; reconstructs export using `export_projection_version` and validates reconstructed hash against persisted `expected_sha256` (failing closed with exit 3 on mismatch). Legacy journals lacking `publication_intent` are explicitly rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5). Phase 1 read-only connection is closed cleanly before Phase 2. + - *Idempotency Verification:* If target exists and matches `attempt_id` and `expected_sha256`, advances directly to Phase 2 cleanup. If different `attempt_id`, exits code 2; if hash mismatch, exits code 3. + - *Phase 2 (Writable Cleanup):* Opened only after Phase 1 connection is closed and publication durability is established; executes verified WAL checkpoint without schema modifications, closes handles, and unlinks companions then `.sqlite3` last. 3. **Contract Attributes & Canonical Objective Traceability:** Every exported attempt contains explicit provenance: - `schema_version` @@ -50,6 +61,20 @@ Establish **`attempt.json` as a standardized, versioned JSON contract** publishe - `DRAFT`: Evaluated as available evidence of learning without automatic penalty for draft status, disclosing draft provenance and reporting demonstrated vs. unestablished criteria. - `UNANSWERED`: Reports that no response evidence exists; must not infer misconceptions or conclude that the learner lacks underlying knowledge solely due to absence of recorded input. +5. **Structured Process Outcomes & Exit Codes:** + Operational failures are strictly decoupled from assessment lifecycle outcomes. Standard output emits a single-line JSON result packet (`{"outcome": "...", "attempt_id": "...", ...}`), while standard error carries human-readable logs: + + | Exit Code | Symbolic Name | Meaning | Journal Action | + | :---: | :--- | :--- | :--- | + | **`0`** | `SUCCESS_FINALIZED` | Export verified, directory synced, journal unlinked. | Deleted | + | **`0`** | `SUCCESS_SUSPENDED` | Pause grace period expired cleanly; resume available. | Preserved | + | **`1`** | `EXPORT_IO_ERROR` | Transient disk/write/sync failure during publication. | Preserved | + | **`2`** | `CONFLICT_DIFFERENT_ATTEMPT` | Destination occupied by a different `attempt_id`. | Preserved | + | **`3`** | `CONFLICT_INTEGRITY_MISMATCH` | Destination has matching ID but differing SHA-256 hash. | Preserved | + | **`4`** | `RECOVERY_CONCURRENCY_LOCKED` | Another process holds the advisory recovery lock. | Preserved | + | **`5`** | `UNSUPPORTED_SCHEMA_VERSION` | Journal or export schema version unsupported. | Preserved | + | **`6`** | `CLEANUP_PENDING` | Export durable and verified, but journal removal failed. | Preserved for retry | + ## Alternatives Considered - **Direct SQLite Database Querying by Evaluators / Future LMS:** Rejected. Exposing internal database tables couples external consumers to `live-quiz` schema migrations. - **Direct In-Place File Overwriting:** Rejected. If a process crash occurs during file write, the destination file is left partially written and corrupted.