docs(architecture): reconcile server-authoritative dual-clock timing and temporal edge cases in Issue 6

- Specify active assessment budget via CLOCK_MONOTONIC and pause grace keepalive via CLOCK_BOOTTIME.
- Mandate BOOTTIME-aware pause-grace watchdog evaluation upon system wake.
- Persist immutable attempt time_limit_ns at session initialization.
- Enforce commit-before-anchor advancement invariant for in-memory monotonic checkpoints.
- Establish strict serialized mutation admission rule under BEGIN IMMEDIATE write boundary.
- Require FastAPI autonomous watchdog for background timeout initiation.
- Document Suspend Gap Detection via clock delta comparison and session_intervals audit table.
- Reconcile ADR-0002 pause-grace deadline semantics with boot_id verification.
- Specify browser presentation-only countdown, visibility lifecycle resync, and formative threat model.
This commit is contained in:
kiskaadee committed 2026-11-11 22:40:44 -05:00
1 parent 434b2ec7bb
commit e71f7e5d46
4 files changed
+105 -11

No files matched your search

+46 -3
View File
@@ -143,12 +143,55 @@ The system explicitly separates:
### 5.2 Ephemeral SQLite Session Journal
During active assessment, `live-quiz` maintains state in a temporary SQLite database (`~/.local/state/live-quiz/sessions/<attempt-id>.sqlite3`):
- Server commits acknowledged draft updates, answer submissions, and timing events atomically to SQLite.
- **Active-Time Representation:** Accumulated active time is tracked and persisted as an integer nanosecond scalar (`accumulated_active_ns`) in the session state table, converted to seconds only for UI display and `attempt.json` export.
- **In-Memory Anchor Advancement Invariant:**
$$\Delta t = t_{\text{monotonic now}} - t_{\text{last committed}}$$
$$\text{accumulated\_active\_ns}' = \text{accumulated\_active\_ns} + \Delta t$$
The in-memory anchor `last_committed_checkpoint_ns` advances strictly **after** the SQLite transaction commits successfully. If commit fails, the anchor does not advance.
- **Checkpoint Triggers & Durability Guarantee:** Checkpoints target approximately 1 second while `RUNNING`, with synchronous immediate checkpoints on pause, autosave, submission, timeout, and early close (all sharing the serialized write boundary `BEGIN IMMEDIATE`). Recovery resumes from the last successfully committed active-time checkpoint; uncommitted elapsed time is not guaranteed to be preserved under sudden process crashes or machine load.
- **Durable Pause Checkpoint & In-Browser Resume:** Clicking **Pause** commits state, freezes active time, records `status = PAUSED` in SQLite, and displays an in-browser Resume control.
- **Configurable Pause Grace Period (Default: 2 Hours):** The server remains alive and accessible in the browser during a 2-hour window (`--pause-grace-period 2h`). If resumed within this window, the assessment continues instantly in the browser.
- **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.
- **Grace-Period Expiration & Boot Identity:** Pause grace is measured using Linux `CLOCK_BOOTTIME` (which advances across system sleep). Stored metadata includes `{ boot_id, pause_started_boottime_ns, pause_deadline_boottime_ns }`. If the 2-hour grace period expires without resumption on the same boot, the server process terminates cleanly to prevent zombie processes, retaining the journal with status `PAUSED` and emitting `outcome: SUSPENDED` on stdout. Across a machine reboot, the original in-browser server is dead, the persisted boottime deadline is never compared across different boot IDs, and the journal remains intact for manual CLI recovery.
- Unexpected kills (`SIGKILL`, power failure) leave the journal intact for recovery.
### 5.3 Ten-Step Atomic Publication Pipeline & Durability Contract
### 5.3 Dual-Clock Timing Architecture & Temporal Edge Cases
1. **Definition of Active Assessment Time:**
Active assessment time is accumulated while the assessment is `RUNNING`, the engine is operational, and the host system is awake. It does not accumulate while `PAUSED`, the host is suspended, or the engine is terminated:
| Situation | Assessment State | Active Budget | Pause Grace Window |
| :--- | :--- | :--- | :--- |
| Learner answering questions | `RUNNING` | Decreases | Not applicable (not paused) |
| Browser tab hidden / backgrounded | `RUNNING` | Decreases | Not applicable (not paused) |
| Host system suspended (laptop lid closed) | `RUNNING` | **Frozen** | Not applicable (not paused) |
| Learner explicitly pauses | `PAUSED` | **Frozen** | Elapses toward deadline |
| Host system suspended while paused | `PAUSED` | **Frozen** | Elapses toward deadline |
| Engine crashes or terminates | Last persisted checkpoint | **Frozen** | In-browser server exited (persisted boottime deadline continues elapsing on same boot only if last persisted state was PAUSED) |
2. **Dual-Clock System & Linux Platform Baseline:**
- **Active Assessment Budget (`CLOCK_MONOTONIC`):** Sampled via `time.monotonic_ns()`. Unaffected by discontinuous wall-clock shifts (manual time adjustments, NTP steps), though subject to gradual frequency adjustments (NTP slewing). Crucially, it halts during kernel suspend (ACPI S3/sleep), automatically freezing the assessment budget when a laptop lid closes without requiring OS D-Bus or `systemd-logind` hooks.
- **Operational Pause Grace Timer (`CLOCK_BOOTTIME`):** Sampled via `time.clock_gettime_ns(time.CLOCK_BOOTTIME)`. Advances during kernel suspend, ensuring that laptop sleep elapses the in-browser keepalive window.
- **BOOTTIME-Aware Pause-Grace Watchdog:** Because Python's `asyncio` event loop schedules delayed timers via `loop.time()` (which uses `CLOCK_MONOTONIC` and halts during suspend), an ordinary `asyncio.sleep()` cannot reliably fire a boottime deadline. The pause-grace watchdog re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (triggered when a suspend gap is detected or via a bounded periodic check), executing clean shutdown with `outcome: SUSPENDED` if the deadline has passed while asleep.
3. **Autonomous Watchdog, Immutable Time Limits & Serialized Admission:**
- **Immutable Attempt Time Limit (`time_limit_ns`):** The assessment duration budget is immutable for each attempt. It is persisted in SQLite session state at attempt initialization and traceable to the immutable questionnaire version. Recovery must never load altered CLI defaults or application configurations that silently mutate an existing attempt's time budget.
- An `asyncio` background watchdog in FastAPI monitors the remaining active budget. When the deadline is reached, it initiates the terminal transition to `TIMED_OUT` without waiting for client interaction.
- **Serialized Mutation Admission Rule:** Every mutation endpoint (`POST /api/response/autosave`, `POST /api/response/submit`) independently validates the deadline while holding the SQLite write-serialization boundary (`BEGIN IMMEDIATE`). Monotonic time is sampled *after* acquiring the write lock:
- $T_{\text{elapsed}} < T_{\text{limit}} \implies$ mutation accepted and checkpointed.
- $T_{\text{elapsed}} \ge T_{\text{limit}} \implies$ mutation rejected; endpoint commits `TIMED_OUT` and `publication_intent`.
- A delay in the background watchdog cannot allow late submissions to be accepted.
- **Overdue Recovery Guard:** If `live-quiz recover` inspects a journal where `accumulated_active_ns >= time_limit_ns`, the engine immediately terminalizes the attempt as `TIMED_OUT` and initiates atomic export before any interactive resume is permitted.
4. **System Suspend Gap Detection:**
- The engine periodically compares clock deltas:
$$T_{\text{suspended}} \approx \Delta T_{\text{BOOTTIME}} - \Delta T_{\text{MONOTONIC}}$$
- When a positive discrepancy exceeds a threshold (indicating the machine slept), the engine appends a `SUSPEND_GAP_DETECTED` event to the `session_intervals` audit table upon wake.
- `session_intervals` table uses `event_sequence INTEGER PRIMARY KEY AUTOINCREMENT` to guarantee strictly monotonic event ordering independently of wall-clock accuracy.
5. **Browser Presentation & Re-synchronization:**
- The browser UI is a presentation layer only. Countdown is calculated locally based on the latest server payload (`remaining_seconds`, `is_active`).
- When a tab is hidden, local visual updates halt to avoid burning CPU on throttled timers.
- The client listens to the Page Visibility API (`document.visibilityState === 'visible'`) and window reconnect events, issuing `GET /api/session` upon re-entry to resynchronize the countdown without continuous background polling.
6. **Threat Model & Trust Boundary:**
The timing architecture is **server-authoritative relative to the browser**, guarding against client clock tampering, background timer throttling, network latency games, and wall-clock skew. Host-level root or user tampering (e.g. modifying SQLite directly or patching the Python binary) is explicitly outside the threat model of a local, formative personal assessment tool.
### 5.4 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-<attempt-id>.lock`), coordinating publication and recovery.
@@ -176,7 +219,7 @@ Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), publi
- 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 & Idempotency Verification
### 5.5 Two Distinct Recovery Paths & Idempotency Verification
Invoking `live-quiz recover --from-path <journal.sqlite3>` 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.
@@ -15,7 +15,7 @@ Design `live-quiz` as a standard foreground UNIX process whose termination signa
2. **Structured Lifecycle Outcome:**
Upon process termination, `live-quiz` emits a machine-readable JSON outcome on stdout:
- **`FINALIZED`:** The assessment reached a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`). `attempt.json` was durably exported. Caller proceeds to evaluation.
- **`SUSPENDED`:** The assessment was paused and the 2-hour grace period expired (or process terminated). The SQLite journal is retained. Caller does **not** invoke evaluation.
- **`SUSPENDED`:** The assessment was paused and the server deliberately exits upon 2-hour grace period expiration. The pause grace period is measured using Linux `CLOCK_BOOTTIME` (advancing across system sleep) on the current host boot, distinct from the learner's active assessment budget (`CLOCK_MONOTONIC`). The SQLite journal is retained with status `PAUSED`. Caller does **not** invoke evaluation. Unexpected termination (`SIGKILL`, power failure) cannot guarantee a structured outcome packet; the caller must detect abnormal exit and offer manual recovery.
- **`ERROR`:** An operational error occurred. The SQLite journal is retained for recovery.
3. **Sequence Diagram:**
@@ -8,10 +8,31 @@
## Decision
Implement `live-quiz` using:
- **Backend & CLI:** Python 3.11+, FastAPI, Pydantic v2, and managed via `uv`.
- **Backend & CLI:** Python 3.11+, FastAPI, Pydantic v2, and managed via `uv` on Linux (the supported runtime platform).
- **Static Analysis:** Pyright (type checking) and Ruff (linting/formatting).
- **Frontend & TypeScript Tooling:** Single-page application built via the Rust-powered Vite Plus (`vp`), with all third-party libraries (CodeMirror, Mermaid.js, KaTeX) fully bundled into static assets (`dist/`). FastAPI mounts and serves `dist/` directly.
### Temporal Architecture & Lifecycle Coordination
1. **Platform Clocks & Linux Runtime Baseline:**
The backend relies on Linux kernel clock facilities exposed via Python's standard library:
- `time.monotonic_ns()` (`CLOCK_MONOTONIC`) for active assessment time. It is unaffected by discontinuous wall-clock steps (e.g. manual time changes, NTP steps), though subject to gradual frequency adjustments (NTP slewing). Crucially, it halts during kernel suspend (ACPI S3/sleep), automatically freezing the assessment budget when a laptop lid closes.
- `time.clock_gettime_ns(time.CLOCK_BOOTTIME)` (`CLOCK_BOOTTIME`) for the operational pause-grace keepalive timer. It advances during kernel suspend, ensuring that laptop sleep consumes the server keepalive window.
- Host boot identity is verified via `/proc/sys/kernel/random/boot_id` so that persisted boottime deadlines are never compared across system reboots.
- **BOOTTIME-Aware Pause-Grace Watchdog:** Because Python's `asyncio` loop timers wrap `CLOCK_MONOTONIC` and halt during system sleep, standard `asyncio.sleep()` cannot accurately expire a boottime grace period. The server re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (e.g. when a suspend gap is detected or via a bounded periodic watchdog), terminating cleanly with `outcome: SUSPENDED` if the deadline expired during sleep.
2. **FastAPI Autonomous Watchdog, Immutable Time Limits & Serialized Admission:**
- **Immutable Attempt Budget (`time_limit_ns`):** The effective duration budget is immutable for each attempt, persisted in SQLite session state at attempt initialization and validated against the frozen questionnaire version. Recovery must never load altered CLI defaults or application configurations that silently mutate an existing attempt's time budget.
- **Autonomous Watchdog:** An `asyncio` background task monitors remaining active budget. When elapsed active time reaches the budget, it triggers the terminal transition to `TIMED_OUT` without waiting for client interaction.
- **Serialized Mutation Admission Rule:** Every response mutation endpoint (`POST /api/response/autosave`, `POST /api/response/submit`) independently validates the deadline while holding the SQLite write-serialization boundary (`BEGIN IMMEDIATE`). Monotonic time is sampled *after* acquiring the lock:
- $T_{\text{elapsed}} < T_{\text{limit}} \implies$ mutation accepted and checkpointed.
- $T_{\text{elapsed}} \ge T_{\text{limit}} \implies$ mutation rejected; endpoint atomically commits `TIMED_OUT` and `publication_intent`.
- A delay or stall in the background watchdog cannot allow late submissions to be accepted.
3. **Vite Plus Frontend Client Timing Behavior:**
- **Presentation Only:** The browser treats server state as authoritative. Countdown is a local display projection based on the latest server payload (`remaining_seconds`, `is_active`).
- **Background Tab Throttling Mitigation:** When the browser tab is hidden or backgrounded, local visual updates halt to avoid burning CPU cycles against throttled timers.
- **Visibility Lifecycle Listener:** The client attaches a listener to the Page Visibility API (`document.visibilityState === 'visible'`) and window focus/reconnect events. Upon re-entering visibility, it immediately issues `GET /api/session` to resynchronize the displayed countdown without continuous polling.
4. **Threat Model & Trust Boundary:**
The timing architecture is **server-authoritative relative to the browser**, guarding against client clock tampering, background timer throttling, network latency games, and wall-clock skew. Host-level root or user tampering (e.g., modifying SQLite directly or patching the Python binary) is explicitly outside the threat model of a local, formative personal assessment tool.
## Alternatives Considered
- **Go Backend:** Rejected. While offering single-binary compilation, it introduces cognitive overhead and unfamiliar web/routing paradigms for the primary maintainer, diverting energy from core pedagogical features.
- **Node/TypeScript Backend:** Rejected. TypeScript is not the preferred backend language for this environment, and running Node on the server side adds unnecessary runtime dependencies.
@@ -12,11 +12,39 @@ Use a temporary, local SQLite database (`~/.local/state/live-quiz/sessions/<atte
- *Server Process:* Ephemeral (runs on demand, exits on finalization or pause grace-period expiration).
- *Assessment Instance:* Persistent concept identified by stable IDs and immutable questionnaire version hashes.
- *Assessment Attempt:* Persistent run representing a single pass against an immutable assessment version.
2. **Transactional State Journaling & Durable Checkpoints:**
2. **Transactional State Journaling, Monotonic Time & Durable Checkpoints:**
- Every acknowledged answer submission, draft update, and timing event is committed immediately to SQLite.
- Clicking **Pause** creates a durable checkpoint: pending drafts are saved, active time is frozen, and `status = PAUSED` is committed before browser acknowledgment.
- **Active-Time & Duration Limit Representation:** Accumulated active time is tracked and persisted as an integer nanosecond scalar (`accumulated_active_ns`) alongside the immutable assessment budget (`time_limit_ns`) in the session state table. Nanoseconds are converted to seconds only for UI display and `attempt.json` export. `time_limit_ns` is established at attempt initialization from the frozen questionnaire version; recovery must never allow changed CLI options or configuration defaults to alter an active attempt's time limit.
- **In-Memory Anchor Advancement Invariant:**
$$\Delta t = t_{\text{monotonic now}} - t_{\text{last committed}}$$
$$\text{accumulated\_active\_ns}' = \text{accumulated\_active\_ns} + \Delta t$$
The in-memory anchor `last_committed_checkpoint_ns` advances strictly **after** the SQLite transaction commits successfully. If commit fails, the anchor does not advance.
- **Checkpoint Triggers:**
- Periodic target: approximately 1 second while `RUNNING`.
- Synchronous immediate accounting on: pause, autosave, submission, timeout, and early close. All timing updates share the serialized SQLite write boundary (`BEGIN IMMEDIATE`).
- **Durable Pause Checkpoint & In-Browser Resume:** Clicking **Pause** commits pending drafts, freezes active time, records `status = PAUSED` in SQLite, and displays an in-browser Resume control.
- **Configurable Pause Grace Period (Default: 2 Hours):** The local server stays running during a 2-hour window (`--pause-grace-period 2h`). Resuming within this window is instant in the browser without CLI/agent interaction.
- If the 2-hour window expires without resumption, the server terminates cleanly to prevent zombie processes, retaining the journal with status `PAUSED`.
- **Boot Identity, Grace Deadline & Post-Wake Evaluation:** Pause grace is measured using Linux `CLOCK_BOOTTIME` (which advances during system sleep). When pausing, the journal persists:
```json
{
"boot_id": "...",
"pause_started_boottime_ns": 123456789,
"pause_deadline_boottime_ns": 123456789
}
```
Because `asyncio` delayed callbacks wrap `CLOCK_MONOTONIC` and halt during system sleep, the pause-grace watchdog re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (e.g. when a suspend gap is detected or via a bounded periodic check). If the deadline passed while asleep, it triggers clean shutdown with outcome `SUSPENDED`. Across a machine reboot, the original server process is dead, in-browser resume is unavailable, and the persisted boottime deadline is never compared against a differing boot ID; the journal remains intact for manual CLI recovery.
- If the 2-hour grace window expires without resumption, the server terminates cleanly with outcome `SUSPENDED`, retaining the journal with status `PAUSED`.
- **Audit Trail (`session_intervals`):** An append-only table records lifecycle intervals with a strictly monotonic sequence:
```sql
CREATE TABLE session_intervals (
event_sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL, -- 'STARTED', 'PAUSED', 'RESUMED', 'SUSPEND_GAP_DETECTED', 'CRASH_RECOVERED'
wall_timestamp_utc TEXT NOT NULL,
accumulated_active_ns INTEGER NOT NULL
);
```
`event_sequence` guarantees interval ordering independent of NTP wall-clock slewing or discontinuous steps.
- **Suspend Gap Detection:** By periodically comparing clock deltas ($T_{\text{suspended}} \approx \Delta T_{\text{BOOTTIME}} - \Delta T_{\text{MONOTONIC}}$), the engine detects when the host was asleep without requiring D-Bus or `systemd-logind` hooks, logging a `SUSPEND_GAP_DETECTED` event upon wake while active time remains frozen.
3. **Assessment State Machine:**
```mermaid
@@ -44,7 +72,9 @@ stateDiagram-v2
- **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 `<attempt-id>.sqlite3`, `<attempt-id>.sqlite3-wal`, and `<attempt-id>.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-<attempt-id>.lock` and destination lock `dest-<sha256_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.
- **Crash Recovery Scope & Timing Guarantees:** Recovery guarantees restoration of all *acknowledged* state. Active time resumes from the last successfully committed active-time checkpoint (`accumulated_active_ns`); uncommitted elapsed time is not guaranteed to be preserved under sudden termination, as the ~1-second interval is an operational target subject to system load. Process downtime while dead is excluded from the active budget and starts a fresh monotonic segment.
- **Overdue Recovery Guard:** If nonterminal recovery (`live-quiz recover`) inspects a journal where `accumulated_active_ns >= time_limit_ns`, the engine immediately terminalizes the attempt as `TIMED_OUT` and initiates atomic export before any interactive resume is permitted.
- **Clock Nuances & Platform Baseline:** Evaluated against Linux `CLOCK_MONOTONIC`. Immune to discontinuous wall-clock adjustments (manual time changes, NTP steps), though subject to NTP frequency slewing. Halts during system suspend.
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.
@@ -64,8 +94,8 @@ stateDiagram-v2
- **Flat-File JSON Appending:** Rejected. Subject to partial-write corruption during sudden process kills (`SIGKILL`) or power failures.
## Consequences
- **Positive:** Guarantees reliable recovery of all acknowledged submissions and drafts across process termination (`SIGKILL`, application crash) under documented WAL mode assumptions; prevents active-time budget leakage during crash downtime; allows in-browser pause without indefinite background processes; leaves zero state accumulation upon clean completion.
- **Negative / Trade-offs:** Requires an explicit recovery command (`live-quiz recover`) and managing temporary journal files (`.sqlite3`, `-wal`, `-shm`) in the XDG state directory; does not protect against unacknowledged client-side keystrokes that never completed an HTTP transaction.
- **Positive:** Guarantees reliable recovery of all acknowledged submissions and drafts across process termination (`SIGKILL`, application crash) under documented WAL mode assumptions; provides server-authoritative timing relative to the browser; prevents active-time budget leakage during crash downtime or host system suspension; allows in-browser pause without indefinite background processes; leaves zero state accumulation upon clean completion.
- **Negative / Trade-offs:** Requires an explicit recovery command (`live-quiz recover`) and managing temporary journal files (`.sqlite3`, `-wal`, `-shm`) in the XDG state directory; does not protect against unacknowledged client-side keystrokes that never completed an HTTP transaction; relies on Linux-specific clock interfaces (`CLOCK_BOOTTIME`). Host root/user manipulation is outside the formative assessment threat model.
## Related Decisions
- [ADR-0002: Harness-Agnostic Process Lifecycle](./0002-harness-agnostic-process-lifecycle.md)