diff --git a/.sisi/contract.json b/.sisi/contract.json new file mode 100644 index 0000000..710d494 --- /dev/null +++ b/.sisi/contract.json @@ -0,0 +1,123 @@ +{ + "id": "booksorter", + "goal": "Lookups ride out flaky sources, find data from every source before asking the owner, and the camera does not accept misreads", + "checks": [ + { + "id": "types", + "claim": "The whole project typechecks, including the new retry state on Book and the Google Books source", + "kind": "general", + "rung": 1, + "cmd": "npm run typecheck", + "expect": { + "exit": 0 + }, + "timeout_s": 20 + }, + { + "id": "unit-tests", + "claim": "Every unit test passes: backoff schedule, no give-up on temporary failures, Retry-After, restart resume, settle-with-a-number, Google Books source, widened similar tier, weekly re-check, misread hint, three-frame agreement", + "kind": "general", + "rung": 3, + "cmd": "npm test", + "expect": { + "exit": 0 + }, + "timeout_s": 25 + }, + { + "id": "build", + "claim": "The web bundle builds", + "kind": "general", + "rung": 3, + "cmd": "npm run build", + "expect": { + "exit": 0 + }, + "timeout_s": 10 + }, + { + "id": "jobs-state-machine", + "claim": "Under random sequences of enqueue, look-up-again, cancel, temporary failure, definitive answer, time passing and restart, the lookup queue never loses a pending book, never runs two lookups for one book at once, never writes to a removed book, and never marks a book Needs attention because of a temporary failure", + "kind": "general", + "rung": 2, + "cmd": "node --test src/server/jobs.property.test.ts", + "expect": { + "exit": 0 + }, + "timeout_s": 15 + }, + { + "id": "scanner-agreement", + "claim": "For random frame sequences, a camera read is accepted only after three consecutive agreeing valid ISBNs inside the time window, and a code with a wrong check digit is never accepted", + "kind": "general", + "rung": 2, + "cmd": "node --test src/web/readstate.property.test.ts", + "expect": { + "exit": 0 + }, + "timeout_s": 10 + }, + { + "id": "old-database-loads", + "claim": "A database file written before the looked_up_at column existed opens with every book intact, the same call numbers, and hand-entered numbers untouched; opening it twice changes nothing", + "kind": "general", + "rung": 2, + "cmd": "node --test src/server/db.migration.test.ts", + "expect": { + "exit": 0 + }, + "timeout_s": 10 + }, + { + "id": "live-lookups", + "claim": "Against the real catalogues, the three books with no official number get a number in the expected class (Durango Hikes GV199.42.C6, San Rafael Swell GV199.42.U8 or F832, Adventures of a Lifetime E160 or GV191), and the six books that resolved before get exactly the same number as before", + "kind": "general", + "rung": 3, + "tier": "deep", + "cmd": "node scripts/live-lookup-check.ts", + "expect": { + "exit": 0 + }, + "timeout_s": 1500 + } + ], + "invariants": [ + { + "id": "resolved-numbers-unchanged", + "claim": "Books that already resolved keep their numbers: 9781640976108 F721.F57 2023, 9781493029150 GB1198.3.C6 W25 2018, 9780826363770 F774.3.M86 2022, 9781937052898 GV854.5.C6 F68 2024, 9780874808131 GV199.42.C63 M58 2005, 9781426220951 GV199.5.S55 2020", + "baseline": "Numbers from the owner's server log of 2026-11-22, before any change in this session; enforced by the live-lookups check", + "cmd": "node scripts/live-lookup-check.ts --regressions-only", + "expect": { + "exit": 0 + }, + "tier": "deep", + "timeout_s": 1200, + "rung": 3, + "kind": "general" + }, + { + "id": "existing-tests-still-pass", + "claim": "The tests that passed before this session still pass", + "baseline": "305 passing at commit bb46d34; 368 passing at a08fbff; enforced by the unit-tests check", + "cmd": "npm test", + "expect": { + "exit": 0 + }, + "timeout_s": 25, + "rung": 3, + "kind": "general" + } + ], + "assumptions": [ + "A network error, timeout, 5xx or 429 is retried for as long as the book is pending; only definitive answers from every source lead to Needs attention.", + "Once a call number is in hand, a remaining step that still fails after six tries is dropped and the book settles with that number, marked approximate if a source could not be asked.", + "A number worked out from similar books, marked with ~, is better than an empty card. It needs at least two agreeing books.", + "Google Books (the key-less Atom feed) is acceptable as a source of title, author, publisher and category. It carries no LC number.", + "9781037052897 and 9781037042898 are camera misreads of 9781937052898; the owner confirmed he has only that book.", + "Camera reads need three agreeing frames (two in a capture burst); about 0.3 s slower on a clean barcode is acceptable.", + "Books with no number or an approximate one are looked up again only at server start, once the last lookup is a week old.", + "The card layout, the waiting text and real-camera behaviour are checked by the owner in a browser, not by an automated check (rung 6).", + "The contract file is committed to the repository with the rest of the project." + ], + "questions": [] +} \ No newline at end of file diff --git a/scripts/live-lookup-check.ts b/scripts/live-lookup-check.ts new file mode 100644 index 0000000..02baaec --- /dev/null +++ b/scripts/live-lookup-check.ts @@ -0,0 +1,69 @@ +// Live check of the real resolver against the real catalogues. Not a unit test (the name does not end in .test.ts), +// so `npm test` never runs it. Usage: node scripts/live-lookup-check.ts [--regressions-only] +// Exits 0 only when every book gets the expected call number. A temporary failure (Open Library drops connections +// often) is retried with backoff for up to a few minutes before the book counts as failed. +import { createResolver, TemporaryError } from '../src/server/resolve/resolver.ts'; +import { backoffMs } from '../src/server/jobs.ts'; +import { jobMemo } from '../src/server/sources/http.ts'; + +interface Case { isbn: string; label: string; check: (callNumber: string) => boolean; expect: string } + +const norm = (s: string) => s.replace(/\s+/g, ' ').trim(); +const exact = (want: string) => (got: string) => norm(got) === norm(want); +// A target is a class prefix: "GV199.42.U8" accepts GV199.42.U82 P76 2019 (the number is chosen from similar books, so only the class is pinned). +const prefix = (...wants: string[]) => (got: string) => wants.some((w) => norm(got).startsWith(w)); + +const REGRESSIONS: Case[] = [ + { isbn: '9781640976108', label: 'F721.F57 2023', expect: 'F721.F57 2023', check: exact('F721.F57 2023') }, + { isbn: '9781493029150', label: 'GB1198.3.C6 W25 2018', expect: 'GB1198.3.C6 W25 2018', check: exact('GB1198.3.C6 W25 2018') }, + { isbn: '9780826363770', label: 'F774.3.M86 2022', expect: 'F774.3.M86 2022', check: exact('F774.3.M86 2022') }, + { isbn: '9781937052898', label: 'GV854.5.C6 F68 2024', expect: 'GV854.5.C6 F68 2024', check: exact('GV854.5.C6 F68 2024') }, + { isbn: '9780874808131', label: 'GV199.42.C63 M58 2005', expect: 'GV199.42.C63 M58 2005', check: exact('GV199.42.C63 M58 2005') }, + { isbn: '9781426220951', label: 'GV199.5.S55 2020', expect: 'GV199.5.S55 2020', check: exact('GV199.5.S55 2020') }, +]; +const TARGETS: Case[] = [ + { isbn: '9780984221356', label: 'Durango Hikes', expect: 'GV199.42.C6...', check: prefix('GV199.42.C6') }, + { isbn: '9780692215005', label: 'San Rafael Swell', expect: 'GV199.42.U8... or F832...', check: prefix('GV199.42.U8', 'F832') }, + { isbn: '9798886472189', label: 'Adventures of a Lifetime', expect: 'E160... or GV191...', check: prefix('E160', 'GV191') }, +]; + +const MAX_WAIT_MS = 5 * 60_000; +const cases = process.argv.includes('--regressions-only') ? REGRESSIONS : [...REGRESSIONS, ...TARGETS]; + +const store = new Map(); +const resolver = createResolver({ fetch: globalThis.fetch, cache: { get: (k) => store.get(k) ?? null, set: (k, v) => { store.set(k, v); } } }); +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +async function lookup(isbn: string): Promise<{ callNumber: string | null; derivation: string; note: string }> { + const memo = new Map(); // what the sources already answered for real: a retry asks only for the rest + const started = Date.now(); + for (let attempt = 1; ; attempt++) { + let similar = ''; + try { + const res = await jobMemo.run(memo, () => resolver.resolve({ isbn13: isbn }, { onSimilar: (d) => { similar = d; } })); + const derivation = res.callNumber ? `${res.source}${res.source === 'similar' && similar ? ` (${similar})` : ''}${res.confidence ? `, ${res.confidence}` : ''}` : `none (${res.reason ?? 'no reason'})`; + return { callNumber: res.callNumber, derivation, note: attempt > 1 ? `after ${attempt} attempts` : '' }; + } catch (e) { + if (!(e instanceof TemporaryError)) throw e; + const wait = backoffMs(attempt, e.retryAfterMs); + if (Date.now() - started + wait > MAX_WAIT_MS) throw new Error(`still failing after ${attempt} attempts: ${e.message}`); + await sleep(wait); + } + } +} + +let failed = 0; +for (const c of cases) { + const t0 = Date.now(); + let got: string | null = null, derivation = '', ok = false, err = ''; + try { + const r = await lookup(c.isbn); + got = r.callNumber; derivation = r.derivation + (r.note ? `, ${r.note}` : ''); + ok = got !== null && c.check(got); + } catch (e) { err = e instanceof Error ? e.message : String(e); } + const secs = ((Date.now() - t0) / 1000).toFixed(1); + if (!ok) failed++; + console.log(`${ok ? 'ok ' : 'FAIL'} ${c.isbn} ${got ?? '(none)'} [${err || derivation}] ${secs}s${ok ? '' : ` expected ${c.expect}`}`); +} +console.log(failed === 0 ? `PASS (${cases.length} books)` : `FAIL (${failed} of ${cases.length} books)`); +process.exit(failed === 0 ? 0 : 1); diff --git a/src/server/db.migration.test.ts b/src/server/db.migration.test.ts new file mode 100644 index 0000000..aefdd86 --- /dev/null +++ b/src/server/db.migration.test.ts @@ -0,0 +1,140 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { openDb } from './db.ts'; + +// The books table as it was at bb46d34, before looked_up_at existed (base table, then the two additive columns). +const OLD_SCHEMA = ` + PRAGMA journal_mode = WAL; + CREATE TABLE books ( + id INTEGER PRIMARY KEY AUTOINCREMENT, isbn13 TEXT UNIQUE, lccn TEXT, title TEXT NOT NULL, subtitle TEXT, + authors TEXT NOT NULL DEFAULT '[]', publisher TEXT, year INTEGER, subjects TEXT NOT NULL DEFAULT '[]', + call_number TEXT, sort_key TEXT, confidence TEXT, source TEXT, dewey TEXT, status TEXT NOT NULL DEFAULT 'pending', + attention_reason TEXT, manual_override INTEGER NOT NULL DEFAULT 0, in_queue INTEGER NOT NULL DEFAULT 0, + printed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL + ); + CREATE TABLE source_cache (key TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); + ALTER TABLE books ADD COLUMN hierarchy_tail TEXT; + ALTER TABLE books ADD COLUMN edition TEXT; +`; + +type Row = Record; +const OLD_COLS = ['id', 'isbn13', 'lccn', 'title', 'subtitle', 'authors', 'publisher', 'year', 'subjects', 'call_number', + 'sort_key', 'confidence', 'source', 'dewey', 'status', 'attention_reason', 'manual_override', 'in_queue', 'printed_at', + 'created_at', 'updated_at', 'hierarchy_tail', 'edition']; + +const T = (n: number) => `2025-0${1 + (n % 9)}-1${n % 9}T10:00:00.000Z`; +const base = (i: number, over: Row): Row => ({ + isbn13: `97800000000${String(i).padStart(2, '0')}`, lccn: null, title: `Book ${i}`, subtitle: null, authors: '[]', + publisher: null, year: null, subjects: '[]', call_number: null, sort_key: null, confidence: null, source: null, + dewey: null, status: 'pending', attention_reason: null, manual_override: 0, in_queue: 1, printed_at: null, + created_at: T(i), updated_at: T(i + 1), hierarchy_tail: null, edition: null, ...over, +}); +const OLD_ROWS: Row[] = [ + base(1, { status: 'resolved', call_number: 'QA76.73.R87 K53 2018', sort_key: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: '005.1', authors: '["Klabnik, Steve"]', subjects: '["Rust"]', year: 2018, hierarchy_tail: '["Programming"]', edition: '2nd ed.' }), + base(2, { status: 'resolved', call_number: 'GV199.42.C6 X', confidence: 'approximate', source: 'similar', hierarchy_tail: '[]', edition: '' }), + base(3, { status: 'resolved', call_number: 'F721 .F57 2023', confidence: 'exact', source: 'manual', manual_override: 1, dewey: '796.5', printed_at: '2025-03-03T00:00:00.000Z', hierarchy_tail: '[]', edition: '' }), + base(4, { status: 'resolved', dewey: '910', call_number: 'HAND 1', confidence: 'exact', source: 'loc-isbn', manual_override: 1 }), + base(5, { status: 'needs_attention', attention_reason: 'No Library of Congress number found', dewey: '796' }), + base(6, { status: 'needs_attention', attention_reason: 'Lookup failed: Network error: fetch failed' }), + base(7, { status: 'needs_attention', attention_reason: 'Lookup failed: HTTP 503 from https://openlibrary.org/x' }), + base(8, { status: 'needs_attention', attention_reason: 'Lookup failed: Timed out after 20 s' }), + base(9, { status: 'needs_attention', attention_reason: 'Lookup failed: Network error: hand-typed', manual_override: 1, call_number: 'MINE 1' }), + base(10, { status: 'needs_attention', attention_reason: 'Lookup failed: Something odd the code never retried' }), + base(11, { status: 'pending' }), + base(12, { isbn13: null, lccn: '2001012345', title: 'Ünïcödé "quotes" \'single\' 日本語 \u{1F4DA}; DROP TABLE books;--', subtitle: 'sub\ttitle\nline2', authors: '["O\'Brien, Pat","Zoë"]', status: 'resolved', call_number: 'PS3565', confidence: 'exact', source: 'loc-lccn', in_queue: 0 }), + base(13, { isbn13: null, title: '', status: 'pending', in_queue: 0 }), +]; + +function writeOld(path: string): void { + const db = new DatabaseSync(path); + db.exec(OLD_SCHEMA); + const ins = db.prepare(`INSERT INTO books (${OLD_COLS.join(',')}) VALUES (${OLD_COLS.map(() => '?').join(',')})`); + OLD_ROWS.forEach((r, i) => ins.run(...OLD_COLS.map((c) => (c === 'id' ? i + 1 : (r[c] as any))))); + db.prepare("INSERT INTO settings (key, value) VALUES ('settings', ?)").run('{"offsetXmm":1.5,"offsetYmm":-2,"rotationDeg":0.25}'); + db.prepare("INSERT INTO source_cache (key, body) VALUES ('k', 'v')").run(); + db.close(); +} + +function dump(path: string, cols: string): Row[] { + const db = new DatabaseSync(path, { readOnly: true }); + try { return db.prepare(`SELECT ${cols} FROM books ORDER BY id`).all().map((r) => ({ ...r })); } finally { db.close(); } +} + +const TEMP_FAIL_IDS = [6, 7, 8]; + +function withOldDb(fn: (path: string) => void): void { + const dir = mkdtempSync(join(tmpdir(), 'bs-mig-')); + try { const p = join(dir, 'old.db'); writeOld(p); fn(p); } finally { rmSync(dir, { recursive: true, force: true }); } +} + +test('an old database opens with every row and every old column value identical', () => { + withOldDb((path) => { + const before = dump(path, OLD_COLS.join(',')); + assert.equal(before.length, OLD_ROWS.length); + const db = openDb(path); db.close(); + const after = dump(path, OLD_COLS.join(',')); + assert.equal(after.length, before.length); + assert.deepEqual(after, before); // not even updated_at moves: opening must not touch old values + }); +}); + +test('looked_up_at is backfilled from updated_at for books already looked up, and left empty for pending ones', () => { + withOldDb((path) => { + const db = openDb(path); db.close(); + const rows = dump(path, 'id, status, updated_at, looked_up_at'); + assert.equal(rows.length, OLD_ROWS.length); + for (const r of rows) { + if (r.status === 'pending') assert.equal(r.looked_up_at, null, `book ${r.id}`); + else assert.equal(r.looked_up_at, r.updated_at, `book ${r.id}`); + } + assert.ok(rows.some((r) => r.status !== 'pending') && rows.some((r) => r.status === 'pending')); + }); +}); + +test('opening twice changes nothing, and the settings and cache survive', () => { + withOldDb((path) => { + openDb(path).close(); + const once = dump(path, '*'); + const db2 = openDb(path); + assert.deepEqual(db2.getSettings(), { offsetXmm: 1.5, offsetYmm: -2, rotationDeg: 0.25 }); + assert.equal(db2.cache.get('k'), 'v'); + db2.close(); + assert.deepEqual(dump(path, '*'), once); + }); +}); + +test('the only change to old data is the documented re-queue of temporary failures; hand-entered rows are untouched', () => { + withOldDb((path) => { + const before = dump(path, OLD_COLS.join(',')); + const db = openDb(path); + assert.equal(db.requeueTemporaryFailures(), TEMP_FAIL_IDS.length); + db.close(); + const after = dump(path, OLD_COLS.join(',')); + assert.equal(after.length, before.length); + for (let i = 0; i < before.length; i++) { + const b = before[i]!, a = after[i]!; + if (TEMP_FAIL_IDS.includes(b.id as number)) { + assert.equal(a.status, 'pending'); assert.equal(a.attention_reason, null); + const { status: _s, attention_reason: _r, updated_at: _u, ...restA } = a; + const { status: _s2, attention_reason: _r2, updated_at: _u2, ...restB } = b; + assert.deepEqual(restA, restB, `book ${b.id}: only status, reason and updated_at may change`); + } else { + assert.deepEqual(a, b, `book ${b.id} must be untouched`); + } + } + // The hand-entered row whose reason looks temporary, and the genuine reasons, are still as they were. + assert.equal(after[8]!.status, 'needs_attention'); + assert.equal(after[4]!.attention_reason, 'No Library of Congress number found'); + assert.equal(after[9]!.status, 'needs_attention'); + // Idempotent: a second open and a second re-queue change nothing more. + const db2 = openDb(path); + assert.equal(db2.requeueTemporaryFailures(), 0); + db2.close(); + assert.deepEqual(dump(path, OLD_COLS.join(',')), after); + }); +}); diff --git a/src/server/jobs.property.test.ts b/src/server/jobs.property.test.ts new file mode 100644 index 0000000..5286af7 --- /dev/null +++ b/src/server/jobs.property.test.ts @@ -0,0 +1,248 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { openDb } from './db.ts'; +import type { Db } from './db.ts'; +import { backoffMs, createJobs } from './jobs.ts'; +import type { Jobs, ResolverLike } from './jobs.ts'; +import type { Book, Resolution, ResolveInput } from '../shared/types.ts'; + +// A randomised model test of the lookup queue. Replay one failure with JOBS_SEED=; JOBS_SEEDS sets how many run. +const ONLY = process.env.JOBS_SEED ? Number(process.env.JOBS_SEED) : null; +const SEEDS = Number(process.env.JOBS_SEEDS ?? 300); + +function prng(seed: number): () => number { + let a = seed >>> 0; + return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; +} + +class TemporaryError extends Error {} + +const T0 = Date.UTC(2026, 0, 1); +const DAY = 86_400_000; +const flush = async () => { await new Promise((r) => setImmediate(r)); await new Promise((r) => setImmediate(r)); }; + +interface FakeTimer { at: number; fn: () => void; live: boolean; unref(): void; ref(): void } +interface Call { gen: number; id: number; done: boolean; settle: (() => void) | null } + +async function scenario(seed: number): Promise { + const rnd = prng(seed); + const int = (n: number) => Math.floor(rnd() * n); + const trace: string[] = []; + const fail = (msg: string): never => { throw new Error(`${msg}\n seed ${seed} (replay: JOBS_SEED=${seed})\n last steps:\n ${trace.slice(-14).join('\n ')}`); }; + + // ---- fake clock and timers, installed globally for the length of the scenario + let clock = T0; + const timers: FakeTimer[] = []; + const realSet = globalThis.setTimeout, realClear = globalThis.clearTimeout; + (globalThis as any).setTimeout = (fn: () => void, ms: number) => { + const t: FakeTimer = { at: clock + Math.max(0, ms ?? 0), fn, live: true, unref() {}, ref() {} }; + timers.push(t); return t; + }; + (globalThis as any).clearTimeout = (t: FakeTimer | undefined) => { if (t) t.live = false; }; + const liveTimers = () => timers.filter((t) => t.live); + try { + const violations: string[] = []; + const flag = (m: string) => { violations.push(m); }; + // ---- the database, watched: what is written to a removed book, and the retry notes the queue leaves + const real = openDb(':memory:'); + const removed = new Set(); + const retryNote = new Map(); + const lastRetryAfter = new Map(); + const changes: Book[] = []; + let lastBackoff: { delay: number; n: number } | null = null; + const db: Db = { + ...real, + updateBook(id, patch) { if (removed.has(id)) flag(`(c) wrote ${JSON.stringify(patch)} to removed book ${id}`); return real.updateBook(id, patch); }, + insertPending(f) { return real.insertPending(f); }, + setRetry(id, r) { + if (r && removed.has(id)) flag(`(c) left a retry note for removed book ${id}`); + if (r && r.nextAt !== null) { + const wait = r.nextAt - clock; + if (!lastBackoff || wait !== lastBackoff.delay) flag(`(e) the timer wait ${wait} is not what the backoff returned (${lastBackoff?.delay})`); + const ra = lastRetryAfter.get(id) ?? 0; + if (wait < ra) flag(`(e) book ${id} waits ${wait} ms although the server said Retry-After ${ra} ms`); + const base = Math.min(300_000, 2_000 * 2 ** (r.attempt - 1)); + if (wait < Math.round(base * 0.75)) flag(`(e) wait ${wait} ms for attempt ${r.attempt} is below the floor ${Math.round(base * 0.75)}`); + if (wait > Math.max(Math.round(base * 1.25), ra)) flag(`(e) wait ${wait} ms for attempt ${r.attempt} is above the ceiling ${Math.max(Math.round(base * 1.25), ra)} (and Retry-After ${ra})`); + if (wait < 1500 || (ra === 0 && wait > 375_000)) flag(`(e) wait ${wait} ms outside 1.5 s .. 375 s`); + } + if (r) retryNote.set(id, { nextAt: r.nextAt }); else retryNote.delete(id); + real.setRetry(id, r); + }, + }; + + // ---- the fake resolver: each call gets an outcome from the seed; some calls are held until a step releases them + // Some seeds are a storm: the sources almost never answer, so single books fail many times in a row. + const tempP = [0.3, 0.5, 0.8, 0.93][int(4)]!; + const slowP = [0.1, 0.3, 0.5][int(3)]!; + type Mode = 'chaos' | 'answer'; + let mode: Mode = 'chaos'; + let gen = 0; + const calls: Call[] = []; + const idByIsbn = new Map(); + const definitive = new Map(); // how many definitive "no"/error outcomes each book was handed + const found = (isbn: string): Resolution => ({ + meta: { title: `Title ${isbn}`, authors: ['A'], subjects: [], year: 2000, publisher: 'P' }, + callNumber: 'QA76 .X', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: '005', reason: null, + }); + const resolverFor = (g: number): ResolverLike => ({ + async resolve(input: ResolveInput, opts) { + // A dead process (an instance from before a restart) asks no more questions and hears no more answers. + if (g !== gen) return new Promise(() => {}); + const isbn = input.isbn13!; + const id = idByIsbn.get(isbn)!; + const call: Call = { gen, id, done: false, settle: null }; + if (calls.some((c) => c.id === id && c.gen === gen && !c.done)) flag(`(a) two lookups in flight for book ${id}: ${JSON.stringify(calls.map((c) => [c.gen, c.id, c.done]))}`); + calls.push(call); + if (process.env.JOBS_DEBUG) console.log(clock - T0, 'CALL book', id, 'gen', gen); + const r = mode === 'answer' ? 2 : rnd(); + const slow = mode === 'chaos' && rnd() < slowP; + const outcome = (): Promise => { + if (r >= 2 || mode === 'answer') { opts?.onMeta?.(found(isbn).meta!); return Promise.resolve(found(isbn)); } + if (r < tempP) { + const ra = rnd() < 0.4 ? 1000 + int(600_000) : undefined; + if (ra === undefined) lastRetryAfter.delete(id); else lastRetryAfter.set(id, ra); + return Promise.reject(Object.assign(new TemporaryError('Network error: TEMPFAIL'), ra === undefined ? {} : { retryAfterMs: ra })); + } + if (r < tempP + (1 - tempP) * 0.6) { opts?.onMeta?.(found(isbn).meta!); return Promise.resolve(found(isbn)); } + if (r < tempP + (1 - tempP) * 0.9) { definitive.set(id, (definitive.get(id) ?? 0) + 1); return Promise.resolve({ ...found(isbn), callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' }); } + definitive.set(id, (definitive.get(id) ?? 0) + 1); + return Promise.reject(new Error('HTTP 404 from https://example.test/x')); + }; + if (!slow) { await Promise.resolve(); call.done = true; return outcome(); } + return new Promise((res, rej) => { + call.settle = () => { call.done = true; outcome().then(res, rej); }; + }); + }, + tail: async () => [], edition: async () => '', search: async () => [], + }); + + // ---- the queue under test; a restart is a new Jobs over the same database (the old one is dead: its calls never return) + const makeJobs = (): Jobs => { const g = gen; return createJobs({ + db, resolver: resolverFor(g), onChange: (b) => { changes.push(b); }, + now: () => clock, log: (l) => { if (process.env.JOBS_DEBUG) console.log(clock - T0, 'inst', g, l); }, + backoff: (n, ra) => { + const d = backoffMs(n, ra, rnd); + const base = Math.min(300_000, 2_000 * 2 ** (n - 1)); + if (n < 1) flag(`(e) backoff asked for attempt ${n}`); + if (d < Math.max(Math.round(base * 0.75), ra ?? 0)) flag(`(e) wait ${d} ms for attempt ${n} is below the floor (base ${base}, Retry-After ${ra})`); + if (d > Math.max(Math.round(base * 1.25), ra ?? 0)) flag(`(e) wait ${d} ms for attempt ${n} is above the ceiling (base ${base}, Retry-After ${ra})`); + if (d < 1500 || (ra === undefined && d > 375_000)) flag(`(e) wait ${d} ms outside 1.5 s .. 375 s`); + lastBackoff = { delay: d, n }; + return d; + }, + }); }; + let jobs = makeJobs(); + + // ---- time: fire due timers in order, letting everything settle after each + async function advance(ms: number): Promise { + const target = clock + ms; + for (;;) { + const due = liveTimers().filter((t) => t.at <= target).sort((a, b) => a.at - b.at)[0]; + if (!due) break; + clock = Math.max(clock, due.at); due.live = false; due.fn(); await flush(); check(); + } + clock = target; await flush(); + } + + // ---- the invariants + const liveCalls = () => calls.filter((c) => c.gen === gen && !c.done); + function check(): void { + if (violations.length) fail(violations[0]!); + for (const id of idByIsbn.values()) { + if (removed.has(id)) { + if (real.getBook(id)) fail(`(c) removed book ${id} exists again`); + continue; + } + const b = real.getBook(id); + if (!b) fail(`book ${id} vanished`); + if (b!.status === 'needs_attention' && (b!.attentionReason ?? '').includes('TEMPFAIL')) fail(`(d) book ${id} was handed to the person because of a temporary failure: ${b!.attentionReason}`); + if (b!.status === 'needs_attention' && !definitive.get(id)) fail(`(d) book ${id} needs attention but was never given a definitive no`); + if (b!.status === 'pending') { + const inFlight = liveCalls().some((c) => c.id === id); + const blocked = liveCalls().length > 0; // lookups run one at a time: it may be queued behind the held one + const note = retryNote.get(id); + const timer = note && note.nextAt !== null && note.nextAt >= clock && liveTimers().some((t) => t.at === note.nextAt); + if (!inFlight && !blocked && !timer) fail(`(b) pending book ${id} is lost: not in flight, nothing in flight to wait behind, and no timer due (retry note ${JSON.stringify(note)})`); + } + } + for (const c of changes) if (c.status === 'needs_attention' && (c.attentionReason ?? '').includes('TEMPFAIL')) fail(`(d) a needs_attention change carried a temporary failure: ${c.attentionReason}`); + } + + // ---- random steps + const nSteps = 20 + int(70); + let nextIsbn = 0; + const live = () => [...idByIsbn.values()].filter((id) => !removed.has(id)); + const addBook = () => { + const isbn = '978' + String(1_000_000_000 + seed * 1000 + nextIsbn++).padStart(10, '0'); + const kind = rnd(); + const r = kind < 0.7 + ? real.insertPending({ isbn13: isbn, title: isbn }) + : kind < 0.85 + ? real.insertPending({ isbn13: isbn, title: 'old', status: 'needs_attention', attentionReason: 'No Library of Congress number found', lookedUpAt: new Date(clock - 10 * DAY).toISOString() }) + : real.insertPending({ isbn13: isbn, title: 'old', status: 'resolved', callNumber: 'PS1 .A', sortKey: 'PS 1', confidence: 'approximate', source: 'similar', lookedUpAt: new Date(clock - 9 * DAY).toISOString() }); + idByIsbn.set(isbn, r.book.id); + if (kind >= 0.7) definitive.set(r.book.id, 1); + if (r.book.status === 'pending') jobs.enqueue(r.book.id); + return r.book.id; + }; + addBook(); await flush(); + for (let step = 0; step < nSteps; step++) { + const r = rnd(); + const ids = live(); + if (r < 0.2) trace.push(`add book ${addBook()}`); + else if (r < 0.32 && ids.length) { + const id = ids[int(ids.length)]!; + trace.push(`look up again ${id}`); + real.updateBook(id, { status: 'pending', attentionReason: null }); + jobs.enqueue(id, { fresh: true }); + } else if (r < 0.4 && ids.length) { + const id = ids[int(ids.length)]!; + trace.push(`remove ${id}`); + jobs.cancel(id); real.deleteBook(id); removed.add(id); retryNote.delete(id); + } else if (r < 0.62) { + const held = liveCalls().filter((c) => c.settle); + if (held.length) { const c = held[int(held.length)]!; trace.push(`release held call for book ${c.id}`); c.settle!(); c.settle = null; } + else trace.push('release (nothing held)'); + } else if (r < 0.9) { + const k = rnd(); + const ms = k < 0.4 ? int(5_000) : k < 0.8 ? int(120_000) : k < 0.95 ? int(900_000) : 8 * DAY; + trace.push(`advance ${ms} ms`); + await advance(ms); + } else { + trace.push('restart'); + for (const id of live()) jobs.cancel(id); + gen++; // the old process is gone: whatever it had in flight never answers + jobs = makeJobs(); + jobs.resume(); + } + if (process.env.JOBS_DEBUG) console.log('STEP', trace[trace.length - 1]); + await flush(); + check(); + } + + // ---- quiescence: a resolver that now answers must finish every pending book, with nothing left waiting + trace.push('--- resolver now answers; letting time pass'); + mode = 'answer'; + for (let i = 0; i < 500; i++) { + for (const c of liveCalls().filter((c) => c.settle)) { c.settle!(); c.settle = null; } + await flush(); check(); + const next = liveTimers().sort((a, b) => a.at - b.at)[0]; + if (!next && liveCalls().length === 0) break; + if (next) await advance(Math.max(0, next.at - clock)); + } + if (liveCalls().length) fail('(b) a lookup is still in flight at quiescence'); + for (const id of live()) { + const b = real.getBook(id)!; + if (b.status === 'pending') fail(`(b) book ${id} is still pending after the resolver answered and time passed`); + } + if (liveTimers().length) fail('(b) timers are still live at quiescence'); + } finally { + globalThis.setTimeout = realSet; globalThis.clearTimeout = realClear; + } +} + +test('lookup queue: random enqueue / look-up-again / remove / failures / answers / time / restart keep every invariant', async () => { + const seeds = ONLY !== null ? [ONLY] : Array.from({ length: SEEDS }, (_, i) => i + 1); + for (const s of seeds) await scenario(s); +}); diff --git a/src/server/jobs.ts b/src/server/jobs.ts index eea0f9c..c8e7288 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -170,7 +170,8 @@ export function createJobs(deps: { async function attempt(id: number): Promise { const book = db.getBook(id); if (!book || (book.status !== 'pending' && !rechecks.has(id))) { forget(id); return; } - const recheck = rechecks.has(id); + // A book that was made pending meanwhile ("Look up again") is a real lookup, not a recheck: it must end resolved or needs-attention. + const recheck = rechecks.has(id) && book.status !== 'pending'; const n = attempts.get(id) ?? 0; const input: ResolveInput = {}; if (book.isbn13) input.isbn13 = book.isbn13; diff --git a/src/web/readstate.property.test.ts b/src/web/readstate.property.test.ts new file mode 100644 index 0000000..6a36f4e --- /dev/null +++ b/src/web/readstate.property.test.ts @@ -0,0 +1,114 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { acceptRead, newReadState } from './readstate.ts'; + +// Replay a failure with READSTATE_SEED=. SEEDS controls how many seeds run. +const ONLY = process.env.READSTATE_SEED ? Number(process.env.READSTATE_SEED) : null; +const SEEDS = Number(process.env.READSTATE_SEEDS ?? 500); + +function prng(seed: number): () => number { + let a = seed >>> 0; + return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; +} + +const check13 = (d12: string) => { let s = 0; for (let i = 0; i < 12; i++) s += Number(d12[i]) * (i % 2 ? 3 : 1); return String((10 - (s % 10)) % 10); }; +const isIsbn = (c: string) => /^\d{13}$/.test(c) && /^97[89]/.test(c) && check13(c.slice(0, 12)) === c[12]; + +// Independent reference: the rules as documented (three consecutive valid-ISBN reads of one code, each within 1500 ms +// of the previous one; non-ISBN frames never reset the run; a code just announced is quiet for 5000 ms). +// A "run" is kept as a list of timestamps instead of a counter. +function reference() { + const announced = new Map(); + const rejected = new Map(); + let run: { isbn: string; times: number[] } | null = null; + return (code: string, t: number): { emit: string | null; reject: boolean } => { + if (!isIsbn(code)) { + const prev = rejected.get(code); + if (prev !== undefined && t - prev < 5000) return { emit: null, reject: false }; + rejected.set(code, t); + return { emit: null, reject: true }; + } + const prev = announced.get(code); + if (prev !== undefined && t - prev < 5000) { run = null; return { emit: null, reject: false }; } + const last = run && run.isbn === code ? run.times[run.times.length - 1]! : null; + if (run && run.isbn === code && last !== null && t - last <= 1500) run.times.push(t); + else run = { isbn: code, times: [t] }; + if (run.times.length >= 3) { run = null; announced.set(code, t); return { emit: code, reject: false }; } + return { emit: null, reject: false }; + }; +} + +let emits = 0; +function scenario(seed: number): void { + const rnd = prng(seed); + const pick = (xs: T[]): T => xs[Math.floor(rnd() * xs.length)]!; + const digits = (n: number) => Array.from({ length: n }, () => Math.floor(rnd() * 10)).join(''); + const valid: string[] = []; + const nearMiss: string[] = []; + const junk = ['', '0', '12345', '012345678905', '0123456789012', 'abcdefghijklm', '9781234', '97812345678901', '5901234123457', ' 9780306406157']; + for (let i = 0; i < 4; i++) { + const body = (rnd() < 0.5 ? '978' : '979') + digits(9); + const c = body + check13(body); + valid.push(c); + const wrong = (Number(c[12]) + 1 + Math.floor(rnd() * 9)) % 10; + nearMiss.push(body + wrong); + } + // A valid EAN-13 check digit but not a book prefix, and a book prefix with a wrong check digit. + const nb = '123' + digits(9); junk.push(nb + check13(nb)); + const gaps = [0, 1, 50, 120, 400, 1499, 1500, 1501, 2000, 4999, 5000, 5001, 9000]; + const ref = reference(); + let state = newReadState(); + let t = Math.floor(rnd() * 1e6); + const n = 30 + Math.floor(rnd() * 120); + const log: string[] = []; + for (let i = 0; i < n; i++) { + t += rnd() < 0.7 ? pick(gaps) : Math.floor(rnd() * 3000); + const r = rnd(); + // Mostly one code held in view, so runs of agreement actually happen. + const code = r < 0.55 ? pick(valid.slice(0, 2)) : r < 0.7 ? pick(valid) : r < 0.82 ? pick(nearMiss) : pick(junk); + const want = ref(code, t); + const got = acceptRead(state, code, t); + state = got.state; + log.push(`${t}:${code || '(empty)'}${got.emit ? ' EMIT' : ''}`); + const ctx = `seed ${seed} (replay: READSTATE_SEED=${seed}) step ${i}\n${log.slice(-8).join('\n')}`; + assert.equal(got.emit, want.emit, `emit differs from the reference. ${ctx}`); + assert.equal(got.reject, want.reject, `reject differs from the reference. ${ctx}`); + if (got.emit !== null) { + emits++; + assert.ok(isIsbn(got.emit), `emitted something that is not a valid ISBN. ${ctx}`); + assert.ok(!nearMiss.includes(got.emit) || valid.includes(got.emit), `a wrong check digit was accepted. ${ctx}`); + } + } +} + +test('random frame sequences: the accept logic matches an independent model of the three-frame rule', () => { + const seeds = ONLY !== null ? [ONLY] : Array.from({ length: SEEDS }, (_, i) => i + 1); + for (const s of seeds) scenario(s); + if (ONLY === null) assert.ok(emits > 500, `the generator should reach acceptance often (got ${emits})`); +}); + +test('a code with a wrong check digit is never accepted, however often or fast it is read', () => { + for (let seed = 1; seed <= 200; seed++) { + const rnd = prng(seed * 7919); + let state = newReadState(); + let t = 0; + const body = '978' + Array.from({ length: 9 }, () => Math.floor(rnd() * 10)).join(''); + const ok = check13(body); + const bad = body + String((Number(ok) + 1 + Math.floor(rnd() * 9)) % 10); + for (let i = 0; i < 60; i++) { + t += Math.floor(rnd() * 1200); + const r = acceptRead(state, bad, t); + state = r.state; + assert.equal(r.emit, null, `seed ${seed}: ${bad} accepted at step ${i}`); + } + } +}); + +test('three agreeing reads accept, two do not, a gap over 1.5 s restarts the count (pinned examples)', () => { + const code = '9781593278281'; + let s = newReadState(); + const feed = (t: number) => { const r = acceptRead(s, code, t); s = r.state; return r.emit; }; + assert.equal(feed(0), null); assert.equal(feed(300), null); assert.equal(feed(600), code); + s = newReadState(); + assert.equal(feed(0), null); assert.equal(feed(300), null); assert.equal(feed(2000), null); assert.equal(feed(2300), null); assert.equal(feed(2600), code); +});