Bring the job-store questions in line with the accepted plans

The owner has accepted the remote-printers, templates and ntfy plans
with every default since docs/plans/job-store.md was written. They
settle two of its questions and lean on the defaults of several more.

Questions 7 and 21 now say they are settled: remote-printers decision
17 ends an unknown remote send as uncertain, never sent again, and its
decision 24 builds Epson's acknowledgement only with phase 5, on the
owner's word. Both keep their numbers, since other plans cite them.

In the questions still open, no default changes. Question 1's GORM
comparison now counts Expr, which templates decision 1 links in.
Question 18 follows ntfy decisions 2 and 8: the cursor moves as during
any replay, and both transports drop priority= through one query
builder. Question 22 counts the larger state saves of ntfy decision 12.
Question 23 points to printers question 22 and to the byte count that
printers stage 3 adds. Questions 6, 10, 18 and 23 name the accepted
decisions that lean on them, and a rule's digest from templates
decision 18 gets the same reference and delete handling as a budget
digest.

The Status line and stages 1d and 4 named a Deferred item in design.md
that is now Planned next item 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 10:48:12 -06:00
1 parent b06f2d8d65
commit aaeeba8eb4
1 file changed
+18 -18
+18 -18
View File
@@ -1,6 +1,6 @@
# Plan: persistent job store and image previews
Status: **planning; nothing is built.** Each stage runs in its own session, briefed from its section, once the owner has answered the questions listed for it or accepted their assumed defaults: stage 1a needs questions 1-3, 1b needs 4, 1c needs 5-12, 1d needs 13-15, phase 2 needs 16, phase 2b needs 17 and 18, phase 3 needs 19 and phase 4 needs 20. Each answer goes into design.md at once and leaves this list. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. design.md's Deferred item still says this work is to be planned; once the owner accepts the plan, that item points here instead and design.md's Status line names this plan, as both do for formatters.
Status: **planning; nothing is built.** Each stage runs in its own session, briefed from its section, once the owner has answered the questions listed for it or accepted their assumed defaults: stage 1a needs questions 1-3, 1b needs 4, 1c needs 5, 6 and 8-12, 1d needs 13-15, phase 2 needs 16, phase 2b needs 17 and 18, phase 3 needs 19 and phase 4 needs 20. Questions 7 and 21 are settled by plans the owner has accepted since, and say so where they stand, so that the numbers other plans cite still hold. Each answer goes into design.md at once and leaves this list. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. design.md's Planned next item 1 says this plan is written and its questions await the owner; once the owner accepts the plan, that item records his answers.
## Decisions (owner, 2026-11-30)
@@ -42,7 +42,7 @@ Before stage 1a:
1. **The store.** Assumed: SQLite through `modernc.org/sqlite` (v1.63.0 today) and `database/sql`, with about 8 hand-written statements; not GORM.
- What SQLite buys here: crash recovery and torn writes are handled by SQLite rather than by our code; it is the owner's stated preference; and it leaves room for queries later. The design itself runs none: every status lives in memory, the store is read by sequence number only, and exclusive locking (question 3) keeps even the `sqlite3` CLI from reading `jobs.db` while the daemon runs.
- On the measures alone the home-grown journal wins: the fewest bytes and syncs, no dependency, the same behaviour on every platform. At the device the gap is smaller than the logical bytes suggest, because each sync also rewrites a 4 KiB block and roughly 12-20 KiB of ext4 journal: SQLite writes about 3-5× the journal's bytes, not about 30× (estimates, COMPARED). At 500 jobs a day the candidates write between about 8 and 120 MiB a day.
- GORM on SQLite, the first choice, writes the same bytes and fsyncs as plain SQL (measured). But it adds about 10 MB to the daemon against 4 MB (+67% against +26%), because one reflective call in GORM stops the linker dropping unused methods anywhere in the binary. Its pure-Go dialector, `github.com/glebarez/sqlite` v1.11.0, has had no release since 2024-03-14 and asks for maintainers (issue #152). A plain `go get` of it pulls in SQLite 3.41.2, and it cannot share a binary with `modernc.org/sqlite`. GORM's default logger prints SQL with its values, which would log print contents.
- GORM on SQLite, the first choice, writes the same bytes and fsyncs as plain SQL (measured). But it adds about 10 MB to the daemon against 4 MB (+67% against +26%), because one reflective call in GORM stops the linker dropping unused methods anywhere in the binary. Expr makes the same call (docs/plans/printers.md, Investigation findings, EXPR), and the owner has accepted linking it (docs/plans/templates.md, decision 1), so once Expr is in the binary GORM's extra cost over plain SQL falls to about its own code. Its pure-Go dialector, `github.com/glebarez/sqlite` v1.11.0, has had no release since 2024-03-14 and asks for maintainers (issue #152). A plain `go get` of it pulls in SQLite 3.41.2, and it cannot share a binary with `modernc.org/sqlite`. GORM's default logger prints SQL with its values, which would log print contents.
- bbolt v1.5.0 adds only 0.25 MB and no new dependency. It writes 2.4-5× SQLite's bytes and needs 2 fdatasyncs per commit, and mixing synced and unsynced commits can corrupt it, so it cannot leave the cheap writes unsynced.
- A home-grown append-only journal writes least (about 2 KB and 1 fsync per job) and adds no dependency. The cost is our own recovery and compaction code and its tests.
- BadgerDB v4.9.6 is not recommended by the research: it adds 8.4 MB, allocates 86 MiB of heap at Open by default, is never built for 32-bit ARM by its CI, and does not sync on Windows.
@@ -61,8 +61,8 @@ Before stage 1c:
5. **Must an accepted job survive a power cut?** Assumed: not for jobs from the HTTP routes. Their insert commits without a sync. It survives a crash of the daemon, and the next synced commit makes it durable too. A power cut within about 30-35 s of a `202` can lose a job that was never sent, as today, but never prints it twice. Yes costs a second fsync per job.
- Jobs from ntfy subscriptions do commit with a sync. The subscriber records a message as handled in its own state file, synced within a second, so a lost insert would lose the message for good. Their number is bounded by each subscription's paper budget, apart from messages at or above `bypass_priority`.
6. **An age limit for queued jobs.** The owner decided that queued jobs survive a restart. Assumed: they print in submission order however old, and waiting jobs stay queued at a clean stop as after a crash, since a stop and a start is a restart too. Trade-off: after a long outage, stale receipts print, such as a notification from hours before. An age limit would be a new key.
7. **The job that was being sent at the crash.** Assumed: a new terminal status `uncertain`, whose `error` says the receipt may have printed. It is never resent; a client or a person sends it again if the paper shows it missing. The name is not `unknown`, which `/healthz` already uses for a printer that gives no status. Trade-off: a new status value reaches clients that switch on `status`, so it is listed under **Breaking**. Reusing `failed` would hide that the receipt may have printed and invite a resend, which is a double print.
6. **An age limit for queued jobs.** The owner decided that queued jobs survive a restart. Assumed: they print in submission order however old, and waiting jobs stay queued at a clean stop as after a crash, since a stop and a start is a restart too. docs/plans/remote-printers.md decision 18 builds on this default: a remote printer's deliveries wait however long its agent is offline. Trade-off: after a long outage, stale receipts print, such as a notification from hours before. An age limit would be a new key.
7. **The job that was being sent at the crash. Settled** by docs/plans/remote-printers.md decision 17, which ends a remote send whose outcome stays unknown as `uncertain` and never sends it again; design.md's Planned next item 3 records it. A job found in `sending` at start takes the same new terminal status, `uncertain`, whose `error` says the receipt may have printed. It is never resent; a client or a person sends it again if the paper shows it missing. The name is not `unknown`, which `/healthz` already uses for a printer that gives no status. Trade-off: a new status value reaches clients that switch on `status`, so it is listed under **Breaking**.
8. **What is stored.** Assumed: the job as validated, a `receipt.Job` in JSON after any module built it. Not the rendered bytes, not the module payload, never the token.
- Rendered bytes are never needed to resume, since a job that reached `sending` is never resent. Storing them would cost up to 256,000 bytes per image, repeat the body for each copy, and need the raw spans and the render context to be read back.
- Trade-offs: a preview by ID re-renders the job under today's config, so it cannot show exactly what was sent; and a queued job resumed after a restart renders under the config of that moment and fetches its images again.
@@ -73,9 +73,9 @@ Before stage 1c:
- An age limit, for privacy, would be another key.
10. **ntfy replays after a crash.** A subscription saves its state within a second of queueing a message. Today a job lost in a crash is replaced by the replay. Once queued jobs resume, a crash in that second would print the message twice. Assumed:
- A `Submit` whose source and reference the queue already holds, from an ntfy subscription, returns the earlier job and queues nothing. Only ntfy jobs take part: on the HTTP routes the reference is a request ID, which a client may set, so a check on it could answer a new request with an old job.
- Webhook jobs with a delivery ID take part too (docs/plans/templates.md, decision 22). The ID is the sender's, read only after the delivery's signature passed.
- Webhook jobs with a delivery ID take part too, as docs/plans/templates.md decision 22 has it; that decision leans on this default. The ID is the sender's, read only after the delivery's signature passed.
- The queue keeps the last 512 (source, reference) pairs of each subscription and each hook with their job IDs, apart from the statuses, so `queue.history = 0` cannot defeat the check.
- A digest gets a reference of its own, a TypeID with the prefix `digest`, in place of the fixed `digest`, minted when the digest is made. The subscriber saves the digest with its reference before it submits it, so a restart submits the same digest under the same reference. The window also exists today, for a digest that printed in that second; stage 1c closes it. The saved digest is kept apart from messages held after it: were they added to a digest whose job was queued before the crash, the duplicate check would answer with that job, and they would never print.
- A digest gets a reference of its own, a TypeID with the prefix `digest`, in place of the fixed `digest`, minted when the digest is made. The subscriber saves the digest with its reference before it submits it, so a restart submits the same digest under the same reference. The window also exists today, for a digest that printed in that second; stage 1c closes it. The saved digest is kept apart from messages held after it: were they added to a digest whose job was queued before the crash, the duplicate check would answer with that job, and they would never print. A rule's digest (docs/plans/templates.md, decision 18) gets its reference and its save the same way; whichever of stage 1c and templates stage 3 lands second covers it.
- Trade-off: a digest can cost one more state save, two fsyncs.
11. **A store write that fails after start** (disk full, an I/O error, corruption found mid-run). Assumed: the daemon stops.
- The queue stops and `Run` returns the error, which stops the daemon; it is logged once at ERROR and reported to Sentry once. Memory changes only after the store has committed, so no client reads a status the store lacks, and a job keeps the state the store last recorded: one that had not reached `sending` stays queued and prints once after the restart.
@@ -111,8 +111,8 @@ Before phase 2b:
17. **Cancelling over HTTP.** Assumed: yes, `DELETE /api/v1/jobs/{id}`, for full tokens only, since a token limited to modules could otherwise cancel other clients' jobs. It cancels each delivery that has not reached `sending` and answers `200` with the status. A job with nothing left to cancel, every delivery having reached `sending`, finished or been cancelled, answers `200` with its status if any delivery is cancelled, so a repeated request answers as the first did, and `409` with a new code, `job_started`, if none is; an unknown ID answers `job_not_found`. Trade-off: more API, and the first route that changes a job already queued; without it, only an ntfy `message_delete` cancels.
18. **Which ntfy events cancel.** Each assumed:
- `message_clear`, which ntfy sends when a notification is dismissed or marked read, cancels nothing and drops no held message. The subscriber goes on skipping it as an event that prints nothing and recording it as dealt with: its ID joins the seen set, the cursor moves, and the state is saved within a second. Trade-off: a notification already read on a phone still prints while it waits. Cancelling on it would let any client of the topic that reads or dismisses the notification stop its receipt.
- A subscription with `min_priority` 4 or 5 receives no `message_delete` today. ntfy applies the `priority=` filter to deletes and clears too (`queryFilter.Pass` in its server/types.go), and a delete carries no priority, so it counts as 3. Assumed: the subscriber stops sending `priority=` and leaves out lower priorities itself, as `deliver` already does. Trade-off: the server then sends every message of the topics, and the subscriber reads and drops those below `min_priority`. The alternative keeps the server's filter, and such a subscription cannot cancel.
- `message_clear`, which ntfy sends when a notification is dismissed or marked read, cancels nothing and drops no held message. The subscriber goes on skipping it as an event that prints nothing and recording it as dealt with: its ID joins the seen set, the cursor moves as for any message (during a replay, not before the first keepalive: docs/plans/ntfy.md decision 2), and the state is saved within a second. Trade-off: a notification already read on a phone still prints while it waits. Cancelling on it would let any client of the topic that reads or dismisses the notification stop its receipt.
- A subscription with `min_priority` 4 or 5 receives no `message_delete` today. ntfy applies the `priority=` filter to deletes and clears too (`queryFilter.Pass` in its server/types.go), and a delete carries no priority, so it counts as 3. Assumed: the subscriber stops sending `priority=` and leaves out lower priorities itself, as `deliver` already does. The JSON stream and the WebSocket build their query with one function (docs/plans/ntfy.md decision 8), so both stop sending it, and that plan leans on this default. Trade-off: the server then sends every message of the topics, and the subscriber reads and drops those below `min_priority`. The alternative keeps the server's filter, and such a subscription cannot cancel.
- A `message_delete` older than `max_backlog` still cancels: that check leaves out stale receipts, and a delete prints nothing. So a delete made during a long outage cancels a job restored after it (question 6). A delete the server no longer keeps is lost, and its job prints.
Before phase 3:
@@ -130,9 +130,9 @@ Before phase 4:
Later:
21. **Epson's process-ID acknowledgement** (`GS ( H` fn 48) on models that have it. Assumed: not in phases 1-4; phase 5, if the owner says yes after a paper test. The state machine is safe without it. Trade-off: it would turn most `uncertain` jobs into confirmed prints, but it holds the printer connection until the receipt is done, so `/healthz` needs another way to read status mid-job, and whether its answer gets through the printer's network board is unverified.
22. **ntfy state in the store.** Assumed: no; the JSON files stay. They already write little (within a second of a change, and a keepalive-only cursor at most every 10 minutes), and the subscriber is built and tested on them. Trade-off: one file and one sync policy, against coupling ntfy to the store.
23. **A write error after part of a receipt went out.** Today such a send is retried, and design.md accepts that part of a receipt can then print twice, because retries let a job survive a printer that is briefly offline. Assumed: unchanged. Once `Send` reports how many bytes `Write` took (phase 5's confirmed send), the owner may choose that such a job becomes `uncertain` and is never resent. Trade-off: fewer doubled fragments, against more jobs a person must check. With several printers, the printers plan also decides when such a delivery fails over to the next printer of an anycast list (Architecture, DELIVERIES AND SEVERAL PRINTERS). The owner's default, failover after the retries on the first printer, is a second double-print path: the next printer gets the whole receipt, so a receipt the first printer took in full before the write error prints in full on both.
21. **Epson's process-ID acknowledgement** (`GS ( H` fn 48) on models that have it. **Settled** by docs/plans/remote-printers.md decision 24, which builds it at the agent only with this plan's phase 5, on the owner's word (its stage 6): not in phases 1-4; phase 5, if the owner says yes after a paper test. The state machine is safe without it. Trade-off: it would turn most `uncertain` jobs into confirmed prints, but it holds the printer connection until the receipt is done, so `/healthz` needs another way to read status mid-job, and whether its answer gets through the printer's network board is unverified.
22. **ntfy state in the store.** Assumed: no; the JSON files stay. They write within a second of a change, and a keepalive-only cursor at most every 10 minutes, and the subscriber is built and tested on them. On a WebSocket each save also writes every seen ID within `max_backlog`, up to some 700 KB on a busy topic with a 12-hour backlog (docs/plans/ntfy.md decision 12). Trade-off: one file and one sync policy, against coupling ntfy to the store, which could write only the IDs that changed.
23. **A write error after part of a receipt went out.** Today such a send is retried, and design.md accepts that part of a receipt can then print twice, because retries let a job survive a printer that is briefly offline. Assumed: unchanged. docs/plans/remote-printers.md decision 17 leans on this default: a remote `partial` outcome is today's write error. Once `Send` reports how many bytes `Write` took (docs/plans/printers.md stage 3's `SendError`, or phase 5's confirmed send), the owner may choose that such a job becomes `uncertain` and is never resent. Trade-off: fewer doubled fragments, against more jobs a person must check. With several printers, docs/plans/printers.md question 22 decides when such a delivery fails over to the next printer of an anycast list (Architecture, DELIVERIES AND SEVERAL PRINTERS). The owner's default, failover after the retries on the first printer, is a second double-print path: the next printer gets the whole receipt, so a receipt the first printer took in full before the write error prints in full on both.
## Investigation findings
@@ -363,7 +363,7 @@ Each delivery's state tells what reached its printer:
- `uncertain`: may have printed. At start the daemon logs one WARN line per delivery that start turned `uncertain` (`Load` says which) with its `job_id`, `printer`, `source` and `ref`, never its content, and from phase 2 `/healthz` counts their jobs. A delivery found `uncertain` at an earlier start is not logged again. A remote attempt whose outcome stays unknown turns `uncertain` during the run, with a WARN line of its own (docs/plans/remote-printers.md, decision 17). A person checks the paper; a reprint is always a new request.
- `cancelled` (phase 2b): never reached the printer.
ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, question 21)
ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, question 21, settled)
- The rendered bytes do not change. `GS ( H 48 <id>` is appended at send time, after the final cut, with a fresh 4-byte ID for each attempt from a counter in the store. Stored and previewed bytes never hold it, which matters because `escpos.Interpret` refuses any `GS (` other than `GS ( k`.
- The connection stays open while the daemon reads frames, classified by the first byte under the mask 0x93, and polls `DLE EOT` every few seconds. The polling also keeps the network board's idle time-out (300 s on the UB-E02 and UB-E03) away. It ends when the matching ID arrives, or after a time-out set by the job's printing time.
- The send then has one of four outcomes: not sent (safe to retry), partly written, written but unconfirmed, or confirmed. Only a confirmation adds `confirmed_at` to the status. A time-out gives `uncertain`, never `failed`, and never a resend.
@@ -533,7 +533,7 @@ LOGGING AND PRIVACY
- Tokens are never stored. Storing a token's subject, so that a client could preview only its own jobs, is left for later.
DELIVERIES AND SEVERAL PRINTERS
- Several printers come in their own plan, `docs/plans/printers.md`, planned next. Printers are named TOML tables, with groups, and Expr rules (`github.com/expr-lang/expr`) route each job. A job goes out in one of four modes:
- Several printers come in their own plan, `docs/plans/printers.md`. Printers are named TOML tables, with groups, and Expr rules (`github.com/expr-lang/expr`) route each job. A job goes out in one of four modes:
- unicast: to one printer;
- multicast: to each printer of a named set;
- broadcast: to every printer;
@@ -739,7 +739,7 @@ Packaging
- Makefile: the same two steps in `check`.
Docs
- design.md: replace "The queue lives in memory, on purpose" with the store the owner chose, the state machine, the sync policy and store failures, with stage 1a's numbers. Update the diagram ("printqueue (memory, 1 worker)") and "no database", the ntfy paragraph that says waiting jobs are lost, and the statement that ESC/POS has no acknowledgement. Record the libc exception (question 13). Shrink the Deferred item to the previews.
- design.md: replace "The queue lives in memory, on purpose" with the store the owner chose, the state machine, the sync policy and store failures, with stage 1a's numbers. Update the diagram ("printqueue (memory, 1 worker)") and "no database", the ntfy paragraph that says waiting jobs are lost, and the statement that ESC/POS has no acknowledgement. Record the libc exception (question 13). Planned next item 1 keeps only what is left to build.
- The docs:
- docs/configuration.md: `state.dir` now holds the job store too; a privacy note.
- docs/install.md and docs/docker.md: the state directory, a named volume or a bind mount owned by `10001:10001`, and the stop timeout.
@@ -840,12 +840,12 @@ internal/pkg/jobstore
internal/pkg/ntfy
- subscriber.go:
- `deliver` handles a `message_delete` before its check for printable messages, which skips every other event that prints nothing ("ntfy event skipped"). It calls the handler's new method, `Delete(ctx, m)` (name assumed), with the event; an error is retried as a `Message` error is. It then drops the held rows of the event's notification and updates the held count in `Status`. `dealt` then records the event as it records any other: its ID joins the seen set, the cursor moves, and the state is saved within a second. `message_clear` stays skipped (question 18).
- `deliver` handles a `message_delete` before its check for printable messages, which skips every other event that prints nothing ("ntfy event skipped"). It calls the handler's new method, `Delete(ctx, m)` (name assumed), with the event; an error is retried as a `Message` error is. It then drops the held rows of the event's notification and updates the held count in `Status`. `dealt` then records the event as it records any other: its ID joins the seen set, the cursor moves as for any message, and the state is saved within a second. `message_clear` stays skipped (question 18).
- `message` lets a `message_delete` past the `max_backlog` check (question 18).
- `connect` no longer sends `priority=`; `deliver` goes on leaving out messages below `MinPriority`, and `LastMessageAt` counts only those at or above it. `MinPriority`'s doc comment says the subscriber filters (question 18).
- The query no longer holds `priority=`, on either transport, since both build it with one function (docs/plans/ntfy.md decision 8); `deliver` goes on leaving out messages below `MinPriority`, and `LastMessageAt` counts only those at or above it. `MinPriority`'s doc comment says the subscriber filters (question 18).
- `printed` is keyed by `Notification()` too, so an update in one topic is not taken for one in another.
- The `Handler` interface gains `Delete`; the fake handler in fake_test.go implements it.
- ratelimit.go: `DigestRow` gains `Sequence`, saved with the held set, and `held` gains `drop(topic, sequence)`, which removes the rows of that topic and sequence and lowers `Count` by as many; an empty sequence drops nothing. A held set left empty is reset, so no digest prints. Messages past `MaxDigestRows` are only counted, without a row, so a delete cannot find them and they stay in the count (assumed). A digest already made, which the saved state keeps apart until `Digest` succeeds (stage 1c), is left alone: it may be queued already.
- ratelimit.go: `DigestRow` gains `Sequence`, saved with the held set, and `held` gains `drop(topic, sequence)`, which removes the rows of that topic and sequence and lowers `Count` by as many; an empty sequence drops nothing. A held set left empty is reset, so no digest prints. Messages past `MaxDigestRows` are only counted, without a row, so a delete cannot find them and they stay in the count (assumed). A digest already made, which the saved state keeps apart until `Digest` succeeds (stage 1c), is left alone: it may be queued already. The messages a rule holds for its own digest (docs/plans/templates.md, decision 18) are a second held set, which drops the same way; whichever of this phase and templates stage 3 lands second covers it.
internal/app/uberbringer
- ntfy.go: `ntfySubmitter` gains `CancelSequence`. The new `ntfyPrinter.Delete` calls `CancelSequence("ntfy:"+name, m.Notification())` and logs each cancelled job at INFO with `subscription`, `ref` and `job_id`. A digest already queued is not cancelled: its reference is the digest's, and it may hold other messages.
@@ -1004,7 +1004,7 @@ Docs
**Done when.**
- A job printed earlier previews by its ID as text and as PNG.
- The full gate passes.
- Once phases 1-4, 2b included, are all done: design.md's Deferred item goes, and this plan is trimmed to its phase 5 list, as formatters.md is.
- Once phases 1-4, 2b included, are all done: design.md's Planned next item 1 goes, and this plan is trimmed to its phase 5 list, as formatters.md is.
### Phase 5: Later, on demand (build only when the owner asks)