# Plan: persistent job store and image previews Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 1 records them. Each stage runs in its own session, briefed from its section: stage 1a follows decisions 1-3, stage 1b decision 4, stage 1c decisions 5-12, stage 1d decisions 13-15, phase 2 decision 16, phase 2b decisions 17 and 18, phase 3 decision 19 and phase 4 decision 20; phase 5 holds decisions 21-23. 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. Every check on the live printer needs the owner's OK. ## Decisions (owner, 2026-11-30) - **Jobs survive a restart.** Queued jobs, statuses and history are stored on disk. - **Storage:** the first choice is GORM on SQLite. Before anything is built, SQLite is investigated in WAL mode, through GORM or a lighter layer: its disk writes per job, what each `synchronous` setting and checkpoint costs and guarantees, and whether it can record a job as printed durably at the moment its bytes are sent. It is weighed against key-value stores such as bbolt and BadgerDB on the same terms. The choice goes into design.md once the owner makes it. - **Pure Go, files in `/var/lib/uberbringer`.** Release builds use `CGO_ENABLED=0`. The store's files live in the unit's `StateDirectory`, the only directory the daemon may write. - **A restart never prints a receipt twice.** The plan says how to tell which receipts printed before a crash. - **Previews:** a print preview as an image, a digital test print of a job showing text, boxes, barcodes, QR codes and images, without printing; and previews of submitted jobs, read back from the store by job ID. - **Several printers come in their own plan,** `docs/plans/printers.md`, planned next: named printers and groups, routed by Expr rules, in four delivery modes (unicast, multicast, broadcast and anycast). A job sent to several printers is one job with one delivery per printer, each tracked on its own. This plan's store allows that from the start, although each job has one delivery until that plan lands (Architecture, DELIVERIES AND SEVERAL PRINTERS). - **Waiting jobs can be cancelled** (phase 2b). An ntfy `message_delete` event cancels a job of its notification that is still waiting. The owner also asked a question, which is not a decision: **does a store that keeps data in memory and syncs it to disk later, such as BadgerDB, cut disk IO?** Hosts may be Raspberry-Pi-class with SD cards, which wear. "Does keeping data in memory cut IO?" under Investigation findings answers it. The owner accepted the details below on 2026-12-01. They are numbered, so the rest of the plan can refer to them. Decisions 7 and 21 follow docs/plans/remote-printers.md decisions 17 and 24. For stage 1a: 1. **The store.** 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 (decision 3) keeps even the `sqlite3` CLI from reading `jobs.db` while the daemon runs. - Not GORM, though it writes the same bytes and fsyncs as plain SQL (measured). 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. It adds about 10 MB to the daemon against 4 MB, 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), so once Expr is in the binary (docs/plans/templates.md, decision 1) that part of the gap goes. - Trade-off: 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. - The store comes in at its latest stable release. 2. **Hardware for the measurements.** The owner runs stage 1a's probe on one Pi-class host with an SD card, and on an ARMv6 board if he has one. modernc's own CI names no ARMv6 target, and there are old SIGSEGV reports for linux/arm. Without an ARMv6 run, the armv6 tarball ships the store untested on hardware, and the CHANGELOG says so. 3. **SQLite's locking mode.** `locking_mode=EXCLUSIVE` and one connection. There is no `-shm` file and no mmap, and a second daemon on the same directory fails at start. Trade-off: reads wait behind writes and their fsyncs, and no other process, the `sqlite3` CLI or a later read-only `uberbringer` command included, can read the database while the daemon runs. Statuses stay in memory, so only the worker and previews by ID read the database. For stage 1b: 4. **Config key and directory.** A top-level `[state] dir` (`UBERBRINGER_STATE_DIR`) holds `jobs.db` and the `ntfy-.json` files and replaces `ntfy.state_dir`. Empty keeps the queue in memory, as today, for Windows development and tests. - No release has shipped `ntfy.state_dir` (it is under `[Unreleased]` only), so there is no compatibility shim. Unknown keys in the file are errors, so a config with `[ntfy] state_dir`, which install.sh writes into every new config today, then stops the daemon at start until the line is changed. - Trade-off: one key ties ntfy state to the job store. Every host with a subscription also gets the durable store and its disk writes. For stage 1c: 5. **An accepted job need not survive a power cut.** Jobs from the HTTP routes commit their insert 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. A synced insert would cost 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. **No age limit for queued jobs.** The owner decided that queued jobs survive a restart. 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: 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 (phase 5). 7. **The job that was being sent at the crash ends `uncertain`,** as docs/plans/remote-printers.md decision 17 ends a remote send whose outcome stays unknown. It is a new terminal status, 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.** 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. - Print contents now rest on disk: 0600 files in the 0700 state directory, `secure_delete=FAST`, and deleted content can linger in free pages and the WAL until they are overwritten. 9. **Retention.** Statuses as today, the last `queue.history` (1000) finished jobs. The content of finished jobs within a byte budget, a new key `queue.content_bytes`, default 64 MiB and at most 1 GiB, newest kept. The content of unfinished jobs is always kept, and so is that of `uncertain` jobs until their status goes, since a reprint needs it. - A count alone cannot bound it: `webserver.body_limit` (4 MiB) × 1000 jobs is about 4 GB, too much for an SD card. - Trade-off: unfinished content alone can reach `queue.size` 100 × 4 MiB, about 400 MiB, and with `auto_vacuum=NONE` the file never shrinks below its high-water mark. - An age limit, for privacy, would be another key (phase 5). 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. So: - 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, as docs/plans/templates.md decision 22 has it. 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 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) stops the daemon. - 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. - The request whose insert failed gets `500` `internal_error`; later ones get `shutting_down`. ntfy messages wait: the subscriber retries any `Submit` error and offers the message again after the restart. - systemd restarts the daemon after 5 s, at most 3 times in 60 s (`StartLimitBurst=3`), then leaves the unit failed. - Trade-off: the API is down until someone acts. 12. **A job's status from its deliveries.** A job has one delivery per printer, and its API `status` derives from theirs (Architecture, DELIVERIES AND SEVERAL PRINTERS). Each job has one delivery until the printers plan lands, but the schema and the `Store` interface carry deliveries from stage 1c, so the rule is settled with them. A delivery counts as taken from when the worker picks it up until it finishes: while it renders, waits for the printer's slot, dials, waits between retries or sends. - Cancelled deliveries are passed over unless every delivery is cancelled; then the job is `cancelled`. The rest of the rule reads the other deliveries. - `queued` while every one waits, none taken and none finished; - `printing` while any is unfinished, once one has been taken or has finished; - once every one has finished: `uncertain` if any is, since it means a receipt may have printed; otherwise `failed` if any is; otherwise `done`. - So `failed` and `uncertain` stay final, as today: a failed or `uncertain` delivery beside one that still waits or prints leaves the job `printing`, and one cancelled delivery beside done ones reads `done`. - Trade-off: a client that reads only `status` learns that one printer failed only once the others have finished; the `deliveries` array shows each printer at once. For stage 1d: 13. **The libc pin.** modernc requires the exact `modernc.org/libc` its go.mod pins (v1.80.1 for v1.63.0; the latest libc is v1.82.14). The owner accepts this exception to "latest stable" for libc alone, which then moves only with `modernc.org/sqlite`. Stage 1d records it in CLAUDE.md's dependency rule and in design.md, and adds a gate check, since a routine `go get -u` would otherwise move libc and break the driver silently. The other new indirect modules are `modernc.org/mathutil`, `modernc.org/memory`, `github.com/dustin/go-humanize`, `github.com/ncruces/go-strftime` and `github.com/remyoudompheng/bigfft`; bigfft has no tagged release, so it comes in at a pseudo-version, as a few indirect modules in go.mod already do. 14. **The Docker image's state directory.** The image sets `UBERBRINGER_STATE_DIR=/var/lib/uberbringer`, so every container keeps a job store there, and it declares no `VOLUME`; docs/docker.md asks for a named volume, or a bind mount owned by `10001:10001`. This is **Breaking**: a container started with `--read-only` and no volume, or with a bind mount owned by root, stops at start where 0.2.0 ran, since today only containers with subscriptions touch the directory. A `VOLUME` would let such containers start, but anonymous volumes pile up, and a new container would silently start with an empty one. 15. **Operational defaults.** - A store that cannot be opened stops the daemon with an error naming the file, and docs/install.md and docs/docker.md give the steps to move it aside. A damaged ntfy state file, by contrast, means a fresh start with a warning. Starting with an empty store would silently forget the waiting jobs and which jobs were in doubt. - The stop timeout must exceed `printer.write_timeout` plus about 10 s (Architecture, JOB STATES). The unit keeps systemd's 90 s default, enough at the default 30-s write; docs/docker.md asks Docker users, whose default is 10 s, for `--stop-timeout 40` at the defaults. Trade-off: a shorter timeout kills a write, which leaves its job `uncertain`, never doubled. - `UMask=0077` in the unit, so the WAL and any later file are 0600 like the database; the state directory is 0700 already. - CI and the gate gain a `CGO_ENABLED=0` build of linux/arm (GOARM=6) and linux/arm64, and the libc check (decision 13). Trade-off: a longer CI run; today nothing compiles the arm targets before a release tag. For phase 2: 16. **A history listing.** `GET /api/v1/jobs`, newest first, for full tokens only. A listing shows every client's jobs, so tokens limited to modules do not get it. Trade-off: more API to keep. Its details: - `status`, `source`, `before` (a job ID; the page starts after it) and `limit` (1-100, default 50) in the query. A `before` that names a job no longer kept answers `invalid_query`, so paging never skips jobs silently. - Job status gains `ref`, so a client can find the job an ntfy message became. - `/healthz`'s `queue` gains `uncertain`: the jobs found `uncertain` at the latest start, those with a delivery that `Load` turned from `sending`. From remote-printers stage 4 it also counts the jobs a remote send has left `uncertain` since that start. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs. For phase 2b: 17. **Cancelling over HTTP.** `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. 18. **Which ntfy events 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. Cancelling on it would let any client of the topic that reads or dismisses the notification stop its receipt. Trade-off: a notification already read on a phone still prints while it waits. - 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. So 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. Trade-off: the server then sends every message of the topics, and the subscriber reads and drops those below `min_priority`. - 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 (decision 6). A delete the server no longer keeps is lost, and its job prints. For phase 3: 19. **The preview image.** PNG, one pixel per printer dot (512 wide on the TM-T88), black on white, the cut as a dashed line where the paper is cut, asked for with `Accept: image/png` on the preview routes; text stays the default. - Images: a `base64` image is drawn from its data, and a `url` image is fetched through safehttp, as printing does, so the picture shows the dithered image. All of one preview's fetches share one deadline, 30 s; an image that failed or is still loading then is drawn as a crossed box. Trade-off: a PNG preview holds its request while it fetches and contacts the image host. That reverses three statements, which phase 3c rewrites: design.md's "a preview never fetches anything" and "a slow or broken image URL holds no HTTP request", and api.md's "prints nothing and fetches no images". The text and JSON previews still fetch nothing. - Glyphs: box drawing and shading are drawn from the cell geometry, so lines run through the cell's centre to its edges and meet their neighbours, and shading is a dot pattern; box joins are what the owner checks on paper. Every other glyph comes from an embedded bitmap font, turned into Go tables by a generator. The font must cover the rest of cp437, cp850, cp858 and cp1252, come at 12×24 for Font A (9×17 for Font B, or the nearest size padded to it), and have a licence that allows embedding. Candidates: Terminus (OFL) and Spleen (BSD), both with a 12×24 size; their coverage of these code pages is unchecked. Trade-off: the font's licence ships in the repository. - Size: the line count does not bound the picture. An image, a QR code or a barcode counts as one line, yet one image may be 4,000 dots tall (`images.max_height`), text may be 8 times as tall, and a job holds up to 500 elements in up to 5 copies. A picture is capped at 100,000 dots, about 14 m of paper at 180 dpi and 6.4 MB at one bit per dot and 512 dots; a taller one answers `422` with a new code, `preview_too_long`. Trade-off: a receipt that prints can be too long to preview. - The printer encodes QR codes itself, so the preview's code can differ from the paper in pattern and, for data the printer packs more densely, in size. - The CLI gains `uberbringer preview --png `. For phase 4: 20. **Previews by ID: source and scope.** The stored job re-rendered (decision 8), for full tokens only, since the answer is print content and a token limited to modules could otherwise read other clients' receipts. A job whose content was pruned (decision 9) answers `410` with a new code, `job_content_expired`. As a PNG it loads its images as decision 19 says. For phase 5, later: 21. **Epson's process-ID acknowledgement** (`GS ( H` fn 48) on models that have it: not in phases 1-4; phase 5, if the owner says yes after a paper test. docs/plans/remote-printers.md decision 24 builds it at the agent with this phase 5 (its stage 6). 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 stays out of the store.** 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. That stays. docs/plans/remote-printers.md decision 17 builds on it: 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). Its 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 Four research tracks ran on 2026-11-30: SQLite, key-value stores, a build of each candidate and Epson's print acknowledgement, with a map of the repository; a review of the plan added a race-detector run. Runs were light and on the Windows workstation (NVMe SSD, NTFS), so latencies are not those of an SD card. Nothing ran against the printer or on a Pi; stage 1a measures there. Versions are the latest on 2026-11-30, from proxy.golang.org. THE ONE WRITE THAT MATTERS - A TCP write returns when the kernel has the bytes, not when they print. No store can record "printed" at the moment of sending. - What a store can do is record `sending` durably before the first byte goes out. A job found in `sending` after a restart is in doubt and is never resent; a job still `queued` never reached the printer. - A process crash (panic, OOM kill, kill -9) loses nothing already written, because the page cache survives. A power cut or a kernel crash loses writes not yet synced: Linux writes dirty data back about 30-35 s after it changed (a 30-s expiry, checked every 5 s). On a Pi, pulling the plug is the common crash. - So the `sending` mark must be synced before the first byte, whatever the store. Most other writes may be lazy: losing one makes a job read as `uncertain`, or loses a job never sent, but never prints one twice. The exception is `failed`: rolled back to `queued`, a job its client was told had failed would print after the restart (Architecture). The minimum is one fsync per job and one per failure, or two per job if an accepted job must survive a power cut (decision 5). - Every durability claim assumes the device honours a flush. SQLite's docs warn that "most consumer-grade mass storage devices lie about syncing". SD cards are suspect, and no source names specific cards. SQLITE IN WAL MODE - A commit appends one frame per changed page to the `-wal` file: a 24-byte header and the 4,096-byte page. The last frame carries the commit mark. Frames are checksummed in a chain, so recovery keeps the longest valid run of commits. - `synchronous` in WAL mode: | Setting | Syncs | Process crash | Power cut | |---|---|---|---| | FULL (modernc's compiled default; EXTRA acts the same in WAL mode) | the WAL after each commit | every commit survives | every commit survives, if the device flushes | | NORMAL | none per commit; the WAL before each checkpoint, the database after it | every commit survives | the database stays consistent; commits since the last sync may roll back | | OFF | none | every commit survives | the database may be corrupted | - **Checkpoints.** One runs (PASSIVE) on the commit that takes the WAL to 1000 pages, about 4 MB, and one when the last connection closes. It runs on the committing thread, so it can delay that commit. It costs 2 fsyncs, the WAL then the database, and a third for the WAL header when the log restarts. It copies only the latest version of each page. The WAL is reused from the start, not truncated, unless `journal_size_limit` is set. - **Sync levels can be mixed.** `synchronous` belongs to the connection, is not persisted, and cannot change inside a transaction. The worker can run `PRAGMA synchronous=FULL`, commit the `sending` mark, then return to NORMAL, all between transactions. The WAL is one append-only file, so that sync also makes every earlier NORMAL commit durable. - **So SQLite can record `sending` durably before the bytes go out, for one fsync per job**, plus about 0.04 per job in checkpoints. On the workstation's NVMe, a FULL commit took about 1.1 ms and a NORMAL one 0.02-0.05 ms. An SD card's flush time is unmeasured. - fsyncs per job, with `done` and the pruning in one commit: | Policy | fsyncs per job | |---|---| | FULL for `sending`, `failed` and inserts from ntfy (decision 5) | 1 + 0.04, plus 1 per failed job and per ntfy job | | FULL for every insert too (not decision 5) | 2 + 0.04, plus 1 per failed job | | FULL for every commit | 3 + 0.04, or 4 with the pruning as its own commit | | NORMAL for every commit | 0.04, with no guard against a second print after a power cut | - **Bytes per job.** The SQLite track measured with a full history of 1000 jobs, bodies in a table of their own, and pruning: - A text job (1.5 KB of JSON) appends 14.35 frames, about 57.7 KiB, to the WAL, and later writes 0.7 pages (2.8 KiB) into the database. A checkpoint comes about every 70 jobs, and the file levels off at 2.1 MiB. - An image job (50 KB of JSON) appends 28 frames (112.8 KiB), and the file levels off at 48 MiB. - Page 1 changes in almost every commit, because it holds the database size and the free-page count. - The spike, with a small table and no pruning, measured 2.67 frames for an insert of 1 KiB and 1 frame for an update: about 15 KB for an insert and one change. - Frame counts shift by about ±2 with the schema, so stage 1a measures the schema under RECORDS. Every run here kept a job's status in one table; RECORDS splits it into `jobs` and `deliveries`. - At 100 text jobs a day that is about 5.6 MiB of WAL; at 1000, about 56 MiB. - NORMAL saves flush barriers and ext4 journal commits, not bytes, since the kernel still writes the WAL within about 30-35 s. An fsync that changes a file's size or mtime also commits roughly 12-20 KiB of ext4 journal (an estimate, not measured). - The rollback journal (`journal_mode=DELETE`) is worse: 2.4× the bytes per insert, 23 file-control calls and about 4 ms per commit (spike). - Ways to cut IO: keep bodies out of the status row, since a row that changes size rewrites its overflow pages; merge `done` and the pruning into one commit; prune in batches; optionally compress bodies; optionally checkpoint while the queue is idle. - **Operations.** - The database, `-wal` and `-shm` belong together. Never delete the WAL or copy the `.db` alone; `VACUUM INTO` makes a backup. - `locking_mode=EXCLUSIVE`, set before the first access, means no `-shm` and no mmap. A second process then gets `SQLITE_BUSY` at once, provided the daemon writes once at open. - `temp_store=MEMORY` avoids temporary files. - `auto_vacuum=NONE` reuses freed pages, so the file levels off. A VACUUM rewrites the whole database through the WAL. - SQLite creates files 0644 less the umask, and gives `-wal` and `-shm` the database file's mode. - `secure_delete=FAST` scrubs b-tree pages at no extra IO, but not free overflow pages, where image bodies end up. `ON` costs extra writes. - WAL does not work over a network filesystem, and Docker Desktop bind mounts pass through a VM file share. PURE-GO SQLITE: DRIVERS AND LAYERS | | `modernc.org/sqlite` | `github.com/glebarez/sqlite` with GORM | `github.com/ncruces/go-sqlite3` | |---|---|---|---| | Latest | v1.63.0 (2026-11-22), SQLite 3.54.1 | v1.11.0 (2024-03-14), nothing tagged since; GORM v1.31.2 (2026-06-22) | v0.38.2 (2026-11-30), before 1.0; its GORM driver, gormlite, v0.34.0 | | How | SQLite's C transpiled to Go | a fork of GORM's SQLite driver, over a fork of modernc's driver | SQLite compiled to Wasm, translated to Go | | Added to the daemon (stripped, measured) | +4.0 MB (+26-27%) | +9.8-10.2 MB (+66-67%) | not measured | | Upkeep | active: 8 releases from August to November 2026 | issue #152 asks for maintainers; arm5 and arm9 panics open (#145, #108) | active; minor releases break its API | - The daemon is 15,278,240 bytes on linux/amd64, 14,876,832 on armv6 and 14,090,400 on arm64 (commit ee65e72, stripped). - GORM adds no disk IO over plain SQL: the same bytes and flushes per commit, and 0.01-0.02 ms more CPU. Its default transaction around a single statement adds no fsync. `Save` rewrites every column. AutoMigrate rebuilds an SQLite table to change a column, and the table it made in the spike has a separate primary-key index, so each insert changes two b-trees. - GORM's size comes from `schema.go` calling `reflect.Value.MethodByName` with a name that is not a constant. That stops the linker removing unused methods anywhere in the binary; about 6 MB of the cost is other packages' methods (Fiber's text symbols rose from 641 to 1,441). - A plain `go get` of glebarez's dialector resolves SQLite 3.41.2 (modernc v1.23.1). Moving its driver, `github.com/glebarez/go-sqlite`, to v1.23.0 gives SQLite 3.53.3. Forcing modernc v1.63.0 under it works, but upstream has not tested that pairing. glebarez and modernc both register the driver name `sqlite`, so a binary with both panics at start. - GORM's own SQLite driver, `gorm.io/driver/sqlite` v1.6.0, needs cgo. - `sqlc` v1.31.1 calls its SQLite engine Beta, and pinning it as a tool would pull wazero and pg_query_go into go.mod. - modernc notes: - It syncs with fsync, not fdatasync, unless `sqlite.Fdatasync(true)` (v1.62.0, Linux) is set. - Any `close()` of any descriptor of the database file anywhere in the process drops SQLite's POSIX locks. OFD locks are opt-in. - Its CPU cost is 1.3-2.0× that of C SQLite, which does not matter at this workload. - Downstream go.mod files must pin its exact libc (cznic issue #177). - Historical SIGSEGV reports exist for linux/arm (GitLab #132), and a 32-bit `va_list` overrun was fixed around v1.53. - v1.63.0 passed `go test -race` (with checkptr) on windows/amd64: 50 jobs with WAL, exclusive locking, one connection and `synchronous` switched between FULL and NORMAL between commits. The race detector does not run on 32-bit ARM, so armv6 and armv7 rest on stage 1a. - ncruces fixed WAL-mode corruption in two optional VFSes in v0.37.0. Its v0.38.2 go.mod has no wazero, so it should run under `MemoryDenyWriteExecute=true` (an inference). BBOLT (`go.etcd.io/bbolt` v1.5.0, 2026-06-03) - One file, pure Go, +0.25 MB to the daemon and no new dependency (`golang.org/x/sys` is already linked). Its CI cross-builds linux/386 and linux/arm and runs tests on Windows. - A commit rewrites every dirty page whole, from leaf to root, plus the free list and the meta page, with 2 fdatasyncs: the pages, then the meta page. - Measured with 1000 history jobs: 124.6 KiB and 6 fdatasyncs per job in 3 commits, or 100.5 KiB and 4 with commits merged; 2.1-2.7 ms per commit on NVMe. The spike, on a small file, measured 26 KB per insert and 21 KB per update, 2.4-5× SQLite's WAL bytes. - `NoSync` cannot be switched safely between commits. Unsynced pages and meta pages reach the disk in any order, so after a power cut the file can point at pages never written. - The file never shrinks without an offline `bbolt compact`. On 32-bit ARM its map is capped at 2 GB. - Its README lists possible corruption with ext4's `fast_commit` (kernel 5.10 and later; not on by default, as far as the track knows; `dumpe2fs -h` shows it) and with a power cut while an empty database initialises. BADGERDB (`github.com/dgraph-io/badger/v4` v4.9.6, 2026-08-05): not recommended by the research - It adds 8.4 MB to the daemon on amd64 (+55%) and 7.9 MB on armv6. - With default options, Open allocates 86 MiB of heap and maps a 2 GiB value log and a 128 MiB memtable file; the block cache can grow by 256 MiB more. Tuned options cut the heap to 11.5 MiB, but one combination of options panics inside Open. - Its CI never builds GOARCH=arm or 386. armv6 and armv7 builds succeed, but a 2 GiB mapping is very unlikely to fit a 32-bit process (unverified). - On Windows `SyncWrites` does nothing: the `msync` of its mmap helper (ristretto, `z/mmap_windows.go`) is an empty function. - Space comes back only through compaction. Values of 1 MB or more go to the value log, which then needs garbage collection. PEBBLE (`github.com/cockroachdb/pebble/v2` v2.1.7) is an LSM engine aimed at CockroachDB, with compactions and a heavy dependency tree. It is too much for about 1,100 records and was not measured. A HOME-GROWN JOURNAL - Append-only JSON lines (accepted about 1.7 KB, sending about 85 B, done about 95 B), with snapshots for compaction written through the temp-file, fsync and rename pattern the ntfy state already uses. - One fdatasync makes every earlier append durable, so 1 fsync per job, for `sending`, is enough. Each sync costs roughly 12-20 KiB of device writes on ext4 (an estimate). - Recovery loads the snapshot, replays the journal and cuts a torn last line. It needs no dependency and behaves the same on every platform. The cost is about a package of our own code with crash-recovery tests, and no ad-hoc queries. - A snapshot-only store, like the ntfy state, would rewrite 0.2-1.9 MB per change: fine for coalesced state, not for per-job writes. COMPARED (per job: accepted, sending, done with pruning; a 1.5 KB body; 1000 jobs of history) | | SQLite WAL, FULL for `sending` | bbolt | Journal | Badger, `SyncWrites` | |---|---|---|---|---| | Added to the daemon | +4.0 MB | +0.25 MB | 0 | +8.4 MB | | fsyncs per job | 1.04, plus failed and ntfy jobs | 4-6 | 1-3 | 3 on Linux; none on Windows | | Bytes per job, logical | 15-58 KiB of WAL, then checkpoints | 100-125 KiB | about 2 KB, then compaction | about 2.5 KB, then flushes and compaction | | Device writes per job (estimate) | about 75-80 KiB | about 150-245 KiB | about 16-26 KiB | about 12-16 KiB, before ext4's journal, flushes and compaction | | Device writes a day at 500 jobs (estimate) | about 38 MiB | about 75-120 MiB | about 8-13 MiB | about 6-8 MiB and more | | `sending` durable before the first byte | yes | yes, at 2 fsyncs per commit | yes | on Linux only | | 32-bit ARM | builds; ARMv6 not in upstream's tests | builds; CI cross-builds arm | no issue | not built by upstream's CI | | Queries | SQL | key order; TypeIDs sort by time | our own maps | key order | - The device estimates add, for each sync, a rewritten 4 KiB block and roughly 12-20 KiB of ext4 journal to the logical bytes; stage 1a measures them. On that measure SQLite writes about 3-5× the journal's bytes, where the logical bytes differ about 30×. - At 500 jobs a day, fsyncs a day: SQLite with decision 5's policy about 520, plus failures and ntfy jobs; the journal 500-1,500; SQLite with FULL for everything about 1,500 plus checkpoints; bbolt 2,000-3,000. For scale, saving every ntfy keepalive would have cost about 1,900 synced writes a day per subscription, which is why that cursor is saved at most every 10 minutes. DOES KEEPING DATA IN MEMORY CUT IO? Only by not syncing. Badger's saving with `SyncWrites=false` comes from leaving its memory-mapped log to kernel writeback, so that several commits landing in one 4 KiB page within the 30-35 s window reach the disk once. Every candidate can make the same trade: SQLite with `synchronous=NORMAL`, or a journal without fdatasync (bbolt's `NoSync` can corrupt its file). A process crash loses nothing in any of them; a power cut loses up to about 30-35 s of commits. If those include a `sending` mark, the restarted daemon sees the job as `queued` and prints it again. So the saving comes from the sync policy, not from the store, and the `sending` mark must be synced regardless. The cheapest correct policy, syncing `sending` and letting most other writes ride on it, is natural in SQLite's WAL and in a journal, works in Badger on Linux only, and cannot be done safely in bbolt. PRINT ACKNOWLEDGEMENT ON EPSON PRINTERS - design.md says ESC/POS gives no acknowledgement of what printed. Epson documents one: `GS ( H` fn 48, the process ID response. The host sends `1D 28 48 06 00 30 30 d1 d2 d3 d4` after the data. For print data, the printer answers `37 22 d1 d2 d3 d4 00` "when the printing is completed" (ESC/POS reference Ver. 10.01, p. 428-429). - The TM-T88IV Technical Reference Guide (Rev. C) lists the command, and so does the TM-T88V's (Rev. E). Epson's model pages list it for the TM-T88IV to TM-T88VII, seen only in search extracts, since the pages refuse direct fetches. TM-m50II support is unconfirmed. - Limits: - If the host misses responses, the printer sends only the latest ID. - Pending IDs are dropped when the buffers are cleared (`DLE DC4` fn 8, `DLE ENQ 2`) or the power goes off. - Epson does not say whether the cut counts as printing. - No response does not mean nothing printed: a job can stall at paper-out and finish later, or print in part. - Unverified: whether the response reaches the host over port 9100 through the printer's Ethernet board (UB-E02 or UB-E03), and what happens to a response sent after the host closed the connection. Only a paper test can tell. - No other mechanism on raw port 9100 reports a job's progress. `DLE EOT`, automatic status (`GS a`) and `GS ( H` fn 49 report the printer's state. `GS r 1` answers once the preceding lines have fed, without an ID. ePOS-Print on newer models reports a print result over HTTP, a different transport. - Even a perfect acknowledgement leaves a window between the printer finishing and the daemon recording it, so the store must be safe without one. - A side finding (an inference, unverified): the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the `ESC @` that starts each job turns it off. Until the first job after a power-on, the printer may send unrequested 4-byte status frames, which `printer.Client.Status`, reading one byte per request, could take as "status unsupported". WHERE THE REPORTS DISAGREE OR ARE UNSURE - WAL bytes per job: about 15 KB (spike: small table, no pruning), 20-40 KiB (the key-value track's estimate) and 57.7 KiB (SQLite track: full history with pruning). The setups differ; stage 1a measures the schema under RECORDS. - Badger's size: +5.6-6.0 MB on a small test program, +7.9-8.4 MB in the daemon. - modernc's size: +3.8 MB (v1.60.1, SQLite track) and +4.0 MB (v1.63.0, spike). - An acknowledgement on the TM-T88IV: design.md ("The queue lives in memory, on purpose") says ESC/POS gives none; Epson documents one (`GS ( H` fn 48). It is unverified on this printer. - Stage 1a measures what no track could: Linux, an SD card and ARM hardware, device writes and flushes, and whether `SystemCallFilter=@system-service` allows what the store calls. Not measured by any track: ncruces' size, Pebble, and fsync counts by strace (they come from SQLite's docs and bbolt's code). SOURCES - SQLite: sqlite.org/wal.html, /pragma.html, /fileformat2.html, /atomiccommit.html, /howtocorrupt.html. - modernc: pkg.go.dev/modernc.org/sqlite; its CHANGELOG, builder.json, fdatasync.go and ofd.go; gitlab.com/cznic/sqlite issues #132 and #177. - glebarez: github.com/glebarez/sqlite, its issues and commits; github.com/glebarez/go-sqlite. ncruces: github.com/ncruces/go-sqlite3, its releases, support matrix and VFS README. - GORM: gorm.io/docs/performance.html, /transactions.html, /migration.html. sqlc: docs.sqlc.dev. - bbolt: github.com/etcd-io/bbolt: README, CHANGELOG-1.5, db.go, tx.go, bolt_windows.go, internal/common/bolt_arm.go, the CI workflows. - Badger: github.com/dgraph-io/badger: options.go, db.go, memtable.go, value.go, skl/arena.go, docs/quickstart.md, docs/troubleshooting.md, the CI workflows, issue #2002; ristretto's z/file.go and z/mmap_windows.go. - Pebble: github.com/cockroachdb/pebble: README, options.go. - Linux writeback: docs.kernel.org/admin-guide/sysctl/vm.html, mm/page-writeback.c. - systemd: systemd.exec(5); the 90 s stop default is `DefaultTimeoutStopSec=` in systemd-system.conf(5), https://www.freedesktop.org/software/systemd/man/latest/systemd-system.conf.html. Docker's 10 s stop default: https://docs.docker.com/reference/cli/docker/container/stop/. - TypeID: github.com/jetify-com/typeid, README and spec. - Epson: - ESC/POS reference Ver. 10.01, `GS ( H`, mirrored in the TM-U210 manual: https://cellphone.manualsonline.com/manuals/mfg/epson/tmu210.html?p=428 (format and timing), ?p=429 (response, latest-only rule, clearing), ?p=430 (fn 49). - TM-T88IV TRG Rev. C: https://files.support.epson.com/pdf/pos/bulk/tm-t88iv_eng_trg_revc_02.pdf - TM-T88V TRG Rev. E: https://files.support.epson.com/pdf/pos/bulk/tmt88v_trg_reve.pdf - TM-m50II TRG Rev. G: https://files.support.epson.com/pdf/pos/bulk/tm-m50ii_trg_en_rev_g.pdf - UB-E02 TRG Rev. A: https://files.support.epson.com/pdf/pos/bulk/ube02_trg_reva.pdf - UB-E03 TRG, p. 50: https://www.manualslib.com/manual/1807854/Epson-Ub-E03.html?page=50 - TM-T20 quick reference: http://www.novopos.ch/client/EPSON/TM-T20/TM-T20_eng_qr.pdf - ePOS-Print API User's Manual Rev. K: https://files.support.epson.com/pdf/pos/bulk/tm-i_epos-print_um_en_revk.pdf - The command and model pages under https://download4.epson.biz/sec_pubs/pos/reference_en/escpos/, such as gs_lparen_ch_fn48.html and tmt88iv.html (search extracts only; they refuse direct fetches). - Versions and go.mod files: proxy.golang.org. ## Overview WHAT SHIPS WHEN 1. Stages 1a-1d: measurements on the owner's hardware, the `[state] dir` key, the state machine without a database, then the SQLite store. Every job is stored when it is accepted. The worker renders, connects, commits a synced `sending` mark, then writes. After a restart, queued jobs print in order, and a job caught mid-send shows `uncertain` and is never resent. 2. The API: `GET /api/v1/jobs` lists the history, job status shows `ref`, and `/healthz` counts the jobs found `uncertain` at the latest start. Phase 2b, cancelling, needs phase 1 but not phase 2: `DELETE /api/v1/jobs/{id}` cancels each delivery of a job that has not reached `sending`, and an ntfy `message_delete` cancels the waiting jobs of its notification and drops its held digest rows. A delivery that has reached `sending` goes on. 3. Stages 3a-3c, the image preview: the preview routes answer `Accept: image/png` with a picture of the paper, drawn from the bytes the job renders to. They need nothing from phases 1 and 2. 4. Previews of stored jobs: `GET /api/v1/jobs/{id}/preview` as text, JSON or PNG. 5. Later, on demand: Epson's acknowledgement, ntfy state in the store, an `Idempotency-Key`, a reprint route, an age limit, the partial-write choice. COMPATIBILITY - Without `state.dir` the queue stays in memory and behaves as today, waiting jobs failing at shutdown included. - Existing statuses keep their meaning; `uncertain`, `cancelled` (phase 2b) and the `sent_at` field are new. - Job status keeps its shape until there are several printers; only then does it gain the `deliveries` array (Architecture, DELIVERIES AND SEVERAL PRINTERS). - What prints does not change. TestRenderCompat and TestPaperReceipts keep passing. - The Docker image keeps a job store in `/var/lib/uberbringer`, so a container that cannot write there stops at start (decision 14, **Breaking**). - A downgrade: an older binary refuses `[state] dir` and `queue.content_bytes` as unknown keys and ignores `jobs.db`. The CHANGELOG and docs/configuration.md say so. INVARIANTS 1. Nothing reaches the printer unless the whole receipt rendered. 2. No byte goes to the printer before its delivery's `sending` mark is committed to the store, and synced when the store is durable. 3. A delivery that a client could have read as failed, `uncertain` or cancelled is never sent again without a new request. Nor, after a restart, is one that may have reached the printer. Within one run, before a delivery finishes, two paths resend one that may have reached the printer: the retries after a write error, as today, and an anycast failover after a `sending` mark, which the printers plan settles (decision 23). 4. A status a client reads is never ahead of the store: memory changes only after the store's commit returns. 5. Print contents never reach logs or Sentry, and the store's errors never quote them. 6. printqueue never imports a database, so server and tools/genopenapi never compile one. 7. A cancelled delivery never reaches the printer: its cancel and its `sending` mark exclude each other under one lock, and whichever commits first wins (phase 2b). ## Architecture JOB STATES A job has one or more deliveries, one per printer it goes to (DELIVERIES AND SEVERAL PRINTERS). The states below are a delivery's: each delivery runs through them on its own, with its own attempts, `sent_at` and error. Until the printers plan lands, each job has one delivery, for the printer `default`, and the job's API `status` is that delivery's, as the table shows; with several deliveries it derives from all of them (decision 12). | Stored state of a delivery | Written | Synced | API `status` | After a restart | |---|---|---|---|---| | `queued` | on `Submit`, with its job, before the `202` | for ntfy jobs only (decision 5) | `queued` | queued again, in submission order | | (taken: rendering, waiting for the printer's slot, dialling, or between retries that never reached `sending`) | not stored; the stored state stays `queued` | – | `printing` | still `queued`: nothing was sent | | `sending`, attempt n | after the connection opens, before the first byte; the first sets `sent_at` | **yes** | `printing` | `uncertain`, never resent | | `done` | after the write returned in full | no | `done` | history | | `failed` | a render error, every attempt failed, or a stored job that no longer decodes | **yes** | `failed` | history | | `uncertain` | at start, for each delivery found in `sending`; during a run, for a remote attempt whose outcome stays unknown (docs/plans/remote-printers.md, decision 17) | no | `uncertain` | history | | `cancelled` (phase 2b) | on a cancel, only for a delivery that has not reached `sending` | **yes** | `cancelled` | history | - A dial failure writes nothing, because the mark is written only once a connection is open. Retries while the printer is offline cost no disk writes, and such a job stays safe to retry. - A lost lazy write only weakens a status: a `done` rolled back to `sending` reads `uncertain`, and a lost insert loses a job never sent. Neither prints twice. `failed` is synced, because a `failed` rolled back to `queued` would print after the restart, after its client was told it failed and may have sent it again. Failures are rare, so the sync costs little. `cancelled` is synced for the same reason: rolled back to `queued`, a job would print after a client was told it was cancelled. - Memory changes only after the store's commit returns. A store write that fails stops the daemon (decision 11), and the job keeps the state the store last recorded. - If the `sending` commit fails, the connection closes with no byte written. - A crash between the `sending` commit and the write leaves an `uncertain` job that never printed. That is the safe direction. - Retries after a write error stay as today (decision 23; design.md accepts that a receipt that failed part-way can print part of itself twice). Each attempt commits its own `sending` mark with its number; `sent_at` keeps the first. - Shutdown with a durable store: - Waiting jobs stay `queued`. - A job that has not reached `sending` is abandoned and stays `queued`: one still rendering (its image fetches run one after another, up to the job's 2-minute bound), waiting for the printer's slot, dialling, or waiting between retries that never reached the printer. Rendering and connecting stop when the daemon stops; nothing was sent. - A job between its `sending` commit and the end of its write finishes. So the stop takes at most `printer.write_timeout` (30 s by default) and two commits. - A job waiting between retries after an attempt reached `sending` fails, as today, and its `sent_at` shows that bytes went out. - Shutdown with the memory store stays as today: the job in hand finishes on its detached context, rendering included, and waiting jobs fail, since the process forgets them anyway. - The stop timeout must therefore exceed `printer.write_timeout` plus about 10 s (decision 15). A SIGKILL mid-write leaves the job `uncertain`. STORE FAILURES (decision 11) - A store that cannot be opened stops the daemon with an error naming the file. The steps in docs/install.md and docs/docker.md: stop the daemon, move `jobs.db` and `jobs.db-wal` aside together, start it again (`systemctl reset-failed uberbringer` first if systemd stopped restarting it). The stored jobs are forgotten, and which of the last receipts printed must be checked against the paper by hand. - After Open, any failed store write stops the daemon, as decision 11 describes. Nothing is retried, since a write that failed once (a full disk, a damaged page) seldom succeeds a moment later. TELLING WHICH RECEIPTS PRINTED BEFORE A CRASH Each delivery's state tells what reached its printer: - `done`: written in full to the printer's connection. It printed unless the printer itself failed, as today. - `queued`: never reached the printer. - `failed`: reached the printer only if `sent_at` is set, and then part of it may have printed. The error does not tell: it is the last attempt's, so a first attempt that wrote part of the receipt and a second that failed to dial end with a dial error. - `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, decision 21) - The rendered bytes do not change. `GS ( H 48 ` 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. - After a restart, a job in `sending` or awaiting its ID is still `uncertain`. Turning acknowledgement off leaves the store exactly as safe. - For a printer behind an agent, it runs at the agent, which owns the connection (docs/plans/remote-printers.md, decision 24). - Holding the connection until the receipt prints would make `/healthz` time out (3 s) during long prints. While a job holds the connection, `/healthz` reports the status that connection last polled, with its age. THE STORE INTERFACE (printqueue) printqueue defines the interface and an in-memory implementation and imports no database. A new package, `internal/pkg/jobstore`, implements it on disk, and internal/app wires it in. The engine can change without touching the queue. A sketch; stage 1c settles the names: ```go // Record is one job as the store keeps it, with its deliveries. type Record struct { Seq uint64 // submission order, assigned under the submit lock ID JobID Source string Ref string Sequence string // the ntfy notification, "/"; empty for other jobs Unique bool // Ref is unique at its source: an ntfy message or digest CreatedAt time.Time Size int64 // bytes of stored content; 0 once pruned Deliveries []Delivery // one per printer; one, for "default", until there are several } // Delivery is a job on one printer. type Delivery struct { Seq uint64 // its own sequence number, assigned with the job's Printer string // the printer used, or the one to try first State StoredState // queued, sending, done, failed, uncertain or cancelled Attempts int Error string StartedAt time.Time SentAt time.Time // the first sending mark FinishedAt time.Time } // Loaded is what Load returns. type Loaded struct { Records []Record // in Seq order, with their deliveries, without content Refs []UniqueRef // the kept source and reference of each unique job, with its ID Uncertain []uint64 // the deliveries this Load turned from sending into uncertain } // Store keeps jobs across restarts. type Store interface { // Durable reports whether records outlive the process. Durable() bool // Load turns every delivery in sending into uncertain in one commit, // then returns the records, the kept references and the deliveries // it turned. Load(ctx context.Context) (Loaded, error) // Add stores a new job, its queued deliveries and its content. With // sync, the commit is durable when Add returns. Add(ctx context.Context, r Record, job []byte, sync bool) error // Sending records attempt n of a delivery on the printer it uses and // returns once that is durable. Sending(ctx context.Context, delivery uint64, printer string, attempt int, at time.Time) error // Finish records a delivery's final state and drops the given jobs, // deliveries and contents, in one commit; sync as for Add. Finish(ctx context.Context, d Delivery, dropJobs, dropDeliveries, dropContent []uint64, sync bool) error // Job returns a stored job's content, or ErrContentGone. Job(ctx context.Context, seq uint64) ([]byte, error) // Idle is called when the queue has nothing to do. Idle(ctx context.Context) error Close() error } ``` - The queue keeps every retained status in memory, as today (about 1,100 at the defaults), and loads them at start. A job's status derives from its deliveries (decision 12); with one delivery it is that delivery's. Status, the listing and the duplicate check read memory. The store is read at start, by the worker for the content of the job it takes, and by previews by ID. The queue decides retention and tells the store what to drop. - Locks: a submit lock covers the sequence number, the capacity check, `Add` and the append to the waiting list. The status lock guards the status map and the waiting list; it is innermost and never held across a store call, so `Status` and `Pending` never wait for a commit. From phase 2b, a delivery lock orders every change of a delivery's state after its insert: the `sending` mark in `beforeWrite`, the worker's `Finish` and the cancel. Each checks the delivery's state in memory, commits and changes memory without releasing it. The orders are the submit lock, then the store; and the printer's connection slot, then the delivery lock, then the store. The cancel never takes the slot, so it cannot deadlock with a send, but its synced commit can delay a send waiting in `beforeWrite`, and with it `/healthz`. The store never calls back into the queue. Every state change commits first, then changes memory. - The waiting list is a slice in sequence order, guarded by the status lock, with a channel that wakes the worker. It replaces today's `jobs` channel, whose capacity is `Size`, so it can hold a restored backlog. `Pending` reads its length and the capacity check runs against it. If more jobs were stored than `queue.size` now allows (after the key was lowered), all of them load, and `Submit` answers `queue_full` until the backlog falls below the size. - `Submit` takes no context, here or in the server's `Jobs` and `ntfySubmitter`. `Add` runs on a background context: an insert that has begun finishes or fails, whatever the client does meanwhile. - `Meta` gains a flag, set by ntfy subscriptions only, that marks its `Ref` as unique at its source, and `Sequence`, a card's ntfy notification (RECORDS), which phase 2b's cancel matches. A unique `Submit` commits with a sync (decision 5). If the queue already holds that source and reference (decision 10), `Submit` stores nothing and returns the earlier job's status, or a status with only its ID and source once that was pruned. - `Sender.Send(ctx, data, beforeWrite func() error)`: `printer.Client` calls `beforeWrite` after the dial, before it computes the write deadline and writes, so a slow sync does not use up `write_timeout`. The queue passes a function that calls `Store.Sending` for the delivery and sets its `sent_at` on the first attempt. The synced commit runs while the printer's connection slot is held, so a slow flush, or a checkpoint that commit triggers, also delays `/healthz` (3 s). The store checkpoints when `Idle` is called, so an automatic checkpoint seldom lands on a `sending` commit. - Restore before start: serve.go opens the store, which takes its lock, and the queue loads it before `group.Go` starts the worker, the server and the subscribers. So restored jobs go ahead of new ones, the sequence continues from the highest stored, restored statuses answer at once, and a second instance on the same directory fails before it reads the `ntfy-.json` files. - `Load` returns no content, so a backlog of up to `queue.size` × 4 MiB is not read into memory at start; the worker reads each job's content when it takes it. A stored job that no longer passes strict `DecodeJob` (after a downgrade or a field change) then fails with an error, logged by `job_id`, and is never dropped silently. Its content is never logged. - `Durable()` decides shutdown: with a durable store, waiting jobs and a job that has not reached `sending` stay queued; with the memory store, shutdown is as today. - With SQLite's single connection, a `Submit` waits for its insert and may wait behind the worker's synced commit or a checkpoint. On an SD card that wait is unmeasured until stage 1a. - The `State` constants stay in queue.go, the one file printqueue's schema test parses; `StoredState` is a separate type in store.go. RECORDS (SQLite, decision 1) ```sql -- PRAGMA user_version = 1 marks this schema; a later schema steps from it. CREATE TABLE jobs ( -- written once, at insert seq INTEGER PRIMARY KEY, -- submission order id TEXT NOT NULL, -- the job_ TypeID source TEXT NOT NULL, ref TEXT NOT NULL, sequence TEXT NOT NULL, -- the ntfy notification, /; empty for other jobs created_at INTEGER NOT NULL -- Unix nanoseconds ); CREATE TABLE deliveries ( -- one per printer a job goes to seq INTEGER PRIMARY KEY, -- assigned with the job's job_seq INTEGER NOT NULL, -- jobs.seq printer TEXT NOT NULL, -- the printer used, or the one to try first state TEXT NOT NULL, -- queued, sending, done, failed, uncertain, cancelled attempts INTEGER NOT NULL, error TEXT NOT NULL, started_at INTEGER, -- Unix nanoseconds sent_at INTEGER, -- the first sending mark finished_at INTEGER ); CREATE TABLE content ( seq INTEGER PRIMARY KEY, -- jobs.seq job BLOB NOT NULL -- the receipt.Job as JSON ); CREATE TABLE refs ( -- unique jobs, for the duplicate check source TEXT NOT NULL, ref TEXT NOT NULL, id TEXT NOT NULL, -- the job_ TypeID, which sorts by time PRIMARY KEY (source, ref) ) WITHOUT ROWID; ``` - A job's own fields live in `jobs`, and each delivery's, those of one printer, in `deliveries`. Until the printers plan lands, every job has exactly one delivery, for the printer `default`. A multicast or broadcast job later gets one row per printer; an anycast job has one, whose `printer` the `sending` mark sets to the printer used (DELIVERIES AND SEVERAL PRINTERS). - The `jobs` row is written once, with its deliveries and its content in the insert's commit, and is deleted at pruning. A status update rewrites only its delivery's row. - IO: the split costs one more small row per job at insert, in the same commit. `deliveries` is a b-tree of its own, so an insert can change one page more than with one table. The findings' numbers were measured with one table; stage 1a's probe measures this schema. - Statuses are looked up in memory, so neither table needs an index on `id`, `state` or `job_seq`, and updates go by a delivery's `seq`. Each index left out is a b-tree fewer per insert. Pruning deletes a job's row and its deliveries' rows by their `seq`s, which the queue passes to `Finish`. - `Load` reads `deliveries` in `seq` order and attaches each row to its job by `job_seq` in memory. - `sequence` lets an ntfy `message_delete` find a waiting job after a restart too (phase 2b). It holds the topic and the sequence ID as `/`, since ntfy's sequence IDs are per topic (`DELETE //`) and one subscription reads several topics; a topic name cannot hold `/`. It is written from stage 1d, so phase 2b needs no schema step and can cancel a job stored before it. - Content has its own table, so a status update never rewrites a body. `Load` reads each content's length, not the content. - `refs` is pruned to the newest 512 per source by `id`, apart from `jobs`, so pruning statuses never drops a reference. It is written only for unique jobs. - Times are Unix nanoseconds, so a status reads the same after a restart as before it. - A `seq`, a job's or a delivery's, can repeat after every row was pruned (`queue.history = 0`). Nothing outside the store's own rows refers to a `seq`, so that is harmless; `refs` holds job IDs, and a later counter, such as the acknowledgement's, keeps its own. - A delivery's `done` and the pruning of the oldest jobs share one commit. - One connection: the store takes a `*sql.Conn` at Open and holds it for its life, with the pool at one open and one idle connection and no lifetime limits, since `synchronous`, `locking_mode` and the lock belong to a connection. The pragmas are set by the connector (or the DSN's `_pragma`), so any new connection gets them too. An error on the held connection is a store failure (decision 11). - The DSN is built through the connector API, or escaped, since `state.dir` may hold spaces, `#` or `?`. - Pragmas at open: `journal_mode=WAL`, `locking_mode=EXCLUSIVE` (decision 3), `synchronous=NORMAL`, `temp_store=MEMORY`, `journal_size_limit` of 4 MiB, `secure_delete=FAST`, and `auto_vacuum=NONE` before the tables exist. `wal_autocheckpoint` stays at 1000. - A synced commit runs `PRAGMA synchronous=FULL`, commits, and restores NORMAL in a defer, so a failed statement never leaves the connection at FULL. `Sending`, `failed`, inserts of unique jobs and, from phase 2b, `cancelled` commit this way. - Open, in order: create the file 0600 if it is missing; set the pragmas; run `PRAGMA quick_check`, which only reads (the whole file, 2-48 MiB at the sizes in the findings), since SQLite otherwise finds a damaged page only when a statement reads it, mid-run; refuse a `user_version` newer than the binary knows, naming both; run each schema step in one synced transaction that also sets `user_version`; write once, so a second instance fails at once. - `Idle` runs `PRAGMA wal_checkpoint(PASSIVE)`. - `sqlite.Fdatasync(true)` on Linux, once stage 1a has shown that the unit's syscall filter allows `fdatasync`. - Nothing else in the process opens the file, since any close drops SQLite's locks. - A test hook, an unexported function the package's own tests set, runs inside each commit and reads `PRAGMA synchronous`, so tests see which commits ran at FULL. RETENTION - Statuses: every unfinished job and the last `queue.history` finished ones, as today. A job is finished once every delivery is; a `cancelled` delivery counts as finished (phase 2b). - Content: every unfinished job's, every `uncertain` job's while its status is kept, and finished jobs' newest first up to `queue.content_bytes` (decision 9). Dropping content keeps the status; a preview of that job answers `410`. - References of unique jobs: the newest 512 per source, whatever happens to their statuses (decision 10). - Pruning happens in the commit that finishes what pushes a job or content out: a delivery's `Finish`, or from phase 2b a `Cancel`. A job goes with all its deliveries. API - Stage 1c: `status` gains `uncertain`, in the `State` enum's `jsonschema` tag, printqueue's schema test, docs/api.md, swagger.json and the CHANGELOG under **Breaking**. Status gains `sent_at` (name assumed), set once an attempt was about to write to the printer. A store failure in `Submit` is an unexpected error: `500` `internal_error`, logged and reported once, the job not accepted, and the daemon stops (decision 11). - Stage 1d: a job kept in the store answers its status after a restart instead of `job_not_found`. - Phase 2 (decision 16): `GET /api/v1/jobs` with `status`, `source`, `before` and `limit` in the query. It answers `{"jobs": [...], "next": "job_..."}`, newest first by sequence number. Bad values answer `invalid_query`, whose api.md row ("On a module route") is reworded. The generator documents every query parameter as a string today, so an enum or integer parameter needs a field on `Param` and a generator change. Job status gains `ref`. `/healthz`'s `queue` gains `uncertain`; the status code still depends on the printer alone. - Phase 2b (decision 17): `DELETE /api/v1/jobs/{id}`, for full tokens, answers `200` with the status, or `409` with the new code `job_started` when no delivery is left to cancel and none is cancelled. `status` gains `cancelled`, a new enum value, so the CHANGELOG lists it under **Breaking**, as it does `uncertain`. `DELETE /api/v1/print` still answers `405`, api.md's example for `method_not_allowed`. - Phase 3c (decision 19): `Accept: image/png` on `POST /api/v1/preview` and `POST /api/v1/preview/{module}`. Text stays the answer to `*/*`. A picture over the height cap answers `422` `preview_too_long`. The generator needs a PNG body schema (`contentMediaType: image/png`). The compress middleware sits in front of these routes; phase 3c checks that it leaves PNG alone. - Phase 4 (decision 20): `GET /api/v1/jobs/{id}/preview`, as text, JSON or PNG by `Accept`, as the POST preview answers, with the new code `410` `job_content_expired`. - Every route is an entry in the table in `server/routes.go`, written there in OpenAPI form (`{id}`; api.md writes `:id`), with its case in TestRoutesConform. Every code goes into `server/errors.go`, the table in docs/api.md and the regenerated swagger.json. CONFIG, PACKAGING, INSTALL.SH, DOCKER, WINDOWS - Config (decision 4): `[state] dir`, with no default, required with an ntfy subscription, empty keeping the queue in memory. Stage 1c adds `queue.content_bytes`, default 67108864 (64 MiB), 0 to 1 GiB, an `int64` so 32-bit ARM can hold it. Each gets its default, validation, `configs/config.example.toml` entry and docs/configuration.md. `ntfy.state_dir` goes, and its `[Unreleased]` CHANGELOG entry is edited rather than listed as Breaking. - Files: `/jobs.db` and `/jobs.db-wal` (no `-shm` in exclusive mode), and `/ntfy-.json`. - The unit already has `StateDirectory=uberbringer` with mode 0700. Add `UMask=0077` (decision 15), and reword the comment that names `ntfy.state_dir`. - install.sh writes `[state] dir = "/var/lib/uberbringer"` into new configs. Re-runs keep the config, so an older config keeps the memory queue until the owner adds the line; docs/install.md says so. - Docker (decision 14): `UBERBRINGER_STATE_DIR=/var/lib/uberbringer` replaces `UBERBRINGER_NTFY_STATE_DIR`, and the comment says the directory holds the job store and the ntfy state. docs/docker.md asks for a named volume there, or a bind mount owned by `10001:10001`, not a Docker Desktop bind mount, since WAL needs a local filesystem, and for a stop timeout above `printer.write_timeout` plus 10 s (`--stop-timeout 40` at the defaults). - Windows is for development only. modernc builds there and its WAL works (spike); it syncs with FlushFileBuffers. `state.dir` has no default, so `go run` and the tests keep the memory queue unless a directory is set. - Builds: nothing in CI compiles the arm targets today. Stage 1d adds the arm builds and the libc check to `test.yml`, the Makefile's `check` and CLAUDE.md's gate (decision 15). LOGGING AND PRIVACY - Print contents now rest on disk: 0600 files in a 0700 directory, `secure_delete=FAST`, and retention by decision 9. docs/configuration.md says so. - No SQL is logged, and statements take parameters. Store errors name the operation and the job, never a value. If GORM is chosen, its logger is silenced. - At start, one INFO line gives the number of jobs resumed, and one WARN line names each delivery that start turned `uncertain` by `job_id`, `printer`, `source` and `ref`. - A store failure is an unexpected error: logged once at ERROR and reported to Sentry once, without content. - 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`. 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; - anycast: to one printer of an ordered list, as a priority list with failover: the first, on failure the second, then the third. - A job has one or more deliveries, one per printer it goes to, each tracked on its own. A multicast or broadcast job is one job with several deliveries; a unicast or anycast job has one. The state machine under JOB STATES applies to each delivery. The `Store` interface carries deliveries from stage 1c, and the database keeps them in a table of their own from stage 1d (RECORDS), so several deliveries per job need new rows, not new tables. Until the printers plan lands, every job has exactly one delivery, for the printer `default`. - The printers plan settles whether it needs new columns, and so a schema step. A delivery's row stores one `printer` and nothing of its route: no mode, group or anycast list, so a restored anycast delivery's list must be derived again from the rules and the config. And a failover after a `sending` mark would overwrite `printer`, so the row would no longer show that the first printer got bytes, which TELLING WHICH RECEIPTS PRINTED relies on; keeping that needs a column or a row per printer tried. - A job's API `status` derives from its deliveries (decision 12). A delivery counts as taken from when the worker picks it up until it finishes: while it renders, waits for the printer's slot, dials, waits between retries or sends (decision 12): - Cancelled deliveries (phase 2b) are passed over unless every delivery is cancelled; then the job is `cancelled`. The rest of the rule reads the other deliveries. - `queued` while every one waits, none taken and none finished; - `printing` while any is unfinished, once one has been taken or has finished; - once every one has finished: `uncertain` if any is, since it means a receipt may have printed; otherwise `failed` if any is; otherwise `done`. So `failed` and `uncertain` stay final, as today: a failed or `uncertain` delivery beside one that still waits or prints leaves the job `printing`, and one cancelled delivery beside done ones reads `done`. With one delivery, the job's status is the delivery's. - Once there are several printers, the status gains a `deliveries` array, one entry per delivery with its `printer`, `status`, `sent_at` and `error`. Until then the status looks as this plan describes, its fields those of the one delivery. What the job's own `sent_at`, `attempts` and `error` hold beside the array is for the printers plan. - Anycast: a delivery's printer is chosen when it is dispatched, and its row records the printer used. Before any byte was sent, a failure fails over to the next printer at once: the delivery moves to it and no `sending` mark is written, just as a dial failure writes nothing today. After a `sending` mark, the default is the existing retry rule on that printer, then failover to the next; the printers plan settles this. That failover can print a whole receipt on two printers (decision 23). A queued delivery restored after a restart starts again from the top of its list (assumed), which the rules and the config give again at restore, since the row stores no list. - One store per instance. Each delivery names its printer, so the printers plan can use one store, with one queue and worker per printer, each loading its own unfinished deliveries. - Job IDs stay global, so `GET /api/v1/jobs/{id}` needs no printer. - The stored job is printer-neutral (formatters invariant 1) and rendered bytes are not stored, so a queued delivery can move to another printer. A printer removed from the config while deliveries wait for it needs a rule; the printers plan settles it. - Acknowledgement IDs are counted per printer. - `cancelled` comes with phase 2b, as a delivery's state; the `deliveries.state` column takes it without a schema change. - Two instances must not share a state directory. Exclusive locking makes the second fail at start; today they would also share the `ntfy-.json` files. Until one instance drives several printers, each instance gets its own directory. THE PREVIEW IMAGE (phase 3) - `escpos.Interpret` keeps what drawing needs: line spacing (`ESC 2`, `ESC 3`) and feeds, the alignment of codes and images, the QR module size and correction level, the barcode height, module width and HRI position, and each raster image's bits. Today it drops all of these. The text and JSON previews do not change. - `escpos.Profile` gains the geometry drawing needs, so that layout keeps coming from the profile: the glyph heights of Fonts A and B; the vertical motion unit, which `ESC 3` and the feed of `GS V` count in; the default line spacing (`ESC 2`); and the distance from the print head to the cutter, so that the dashed cut line falls where the paper is cut, which is where `printer.cut_feed` moved it. The tm-t88 values come from the TM-T88IV's Technical Reference Guide. The other profiles get values for their resolution (`tm-t20`, `generic-80mm` and `generic-58mm` are 203 dpi), marked unverified until checked on paper. Rendering does not read these fields, so no printed byte changes. Formatters phase 5's "default line spacing per model" is the same field. - A new package, `internal/pkg/paper` (name assumed), draws those lines into a 1-bit image as wide as the profile's dots. The image is a type of its own that implements `image.PalettedImage` with one bit per dot, which `image/png` writes as 1-bit rows; an `image.Paletted` takes a byte per dot, about 30 MB for 60,000 rows. It draws: - glyphs in Font A and B, at sizes 1-8, bold, underlined (1 and 2) and inverted, for every code page (decision 19); - QR codes from an encoder, at the printer's module size; - EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128, with their digits; - raster images copied dot for dot; - cuts as dashed lines, and raw spans as a hatched band with a label, since a 1-bit picture has no grey; - nothing past the height cap (decision 19). - `receipt.Renderer.PreviewImage` renders the job with its images loaded as decision 19 says, reads the bytes back with `Interpret` and draws them. Imports: receipt → paper → escpos. ## Phases ### Stage 1a: Measurements on the owner's hardware **Goal.** Measure on a Pi-class host with an SD card what the workstation cannot: device writes and flushes per job, the time of a synced commit and of a checkpoint, whether ARMv6 runs the store, and whether the unit's sandbox allows the calls the store makes. **Work.** Nothing in the repository changes. The session writes a probe under the scratch directory, cross-compiles it, and gives the owner the binaries and the commands. The owner runs them, with his OK, never on the workstation. The probe, `jobprobe`, one Go module outside the repository: - The store decision 1 chose, at the version stage 1d will pin. For SQLite: `modernc.org/sqlite` with its pinned libc, one connection, and the pragmas and schema under RECORDS (`jobs`, `deliveries`, `content` and `refs`), created fresh in `-dir`. - Flags: `-dir`, `-jobs` (default 200), `-body` (bytes of JSON per job, default 1500), `-history` (default 1000), `-deliveries` (per job, default 1; 3 shows what a broadcast to three printers costs), and `-fdatasync` for modernc's `Fdatasync(true)`. - Setup, not measured: `-history` finished jobs, each with its deliveries, so pruning runs as it would in steady state. - Per job, as the daemon will: the job, its deliveries and its content inserted in one commit at NORMAL; for each delivery, the `sending` mark at FULL, then `done` on that delivery's row alone at NORMAL, the last of them in one commit with the pruning of the oldest job, its deliveries and its content. At the end, one timed `PRAGMA wal_checkpoint(PASSIVE)`. - Output, as text: - per job, the device's sectors written and flush requests, from `/sys/dev/block/:/stat` for the device of `-dir`, read before and after, less an idle baseline taken over a minute first; this counts ext4's journal, which `/proc/self/io` misses; - `/proc/self/io` `write_bytes` per job; - the time of each FULL and each NORMAL commit: median, 99th percentile and maximum (the slowest include the automatic checkpoints); - the time of the final checkpoint, and the sizes of the database and the WAL. - Built with `CGO_ENABLED=0` for linux/arm (GOARM=6 and 7) and linux/arm64. On the owner's host, otherwise idle, since the device counters include every process's writes: 1. Run it as a transient unit with the unit's sandbox, once with and once without `-fdatasync`: `systemd-run --wait --pipe -p DynamicUser=yes -p StateDirectory=jobprobe -p ProtectSystem=strict -p PrivateTmp=yes -p PrivateDevices=yes -p MemoryDenyWriteExecute=yes -p SystemCallFilter=@system-service -p SystemCallErrorNumber=EPERM -p SystemCallArchitectures=native ./jobprobe -dir /var/lib/jobprobe`. A call the filter refuses fails the run with EPERM, so this tests `fdatasync`, the file locks, `pwrite` and `ftruncate` for real. 2. As a cross-check, `systemd-analyze syscall-filter @system-service` lists `fsync`, `fdatasync`, `fcntl`, `pwrite64` and `ftruncate`. 3. The same on an ARMv6 board, if he has one (decision 2). **Tests.** A 20-job run on the workstation (Windows, without device counters) shows that the probe works. Nothing heavier runs there. **Done when.** - The owner has run the probe and reported its output, and the numbers are in Investigation findings. - If ARMv6 fails, or the numbers differ much from the findings, the owner has looked at decision 1 again. ### Stage 1b: `[state] dir` **Goal.** `[state] dir` replaces `ntfy.state_dir` (decision 4). Nothing else changes: the directory is still used only by ntfy subscriptions. **Work.** internal/pkg/config - `[state] dir`, with no default; required when a subscription is configured. `ntfy.state_dir` goes. - The tests that set `ntfy.state_dir`: config/subscriptions_test.go, config_test.go. internal/app/uberbringer - ntfy.go: the directory check (MkdirAll 0700 and a write probe) and the state files use `state.dir`; errors name `state.dir`. - ntfy_test.go: the tests that set `ntfy.state_dir`. Packaging - install.sh: `[state] dir = "/var/lib/uberbringer"` in new configs, in place of `[ntfy] state_dir`. - Dockerfile: `UBERBRINGER_STATE_DIR` in place of `UBERBRINGER_NTFY_STATE_DIR`. - packaging/uberbringer.service: the comment names `state.dir`. Docs - configs/config.example.toml: `[state] dir` added; `[ntfy] state_dir` removed. - The install note on `/var/lib/uberbringer` in docs/install.md, the ntfy paragraph of docs/docker.md, the `ntfy.state_dir` entry in docs/configuration.md (it becomes `state.dir`), and in docs/ntfy.md the example config and the State paragraph's `/ntfy-.json`. - design.md: the ntfy State paragraph, which names `ntfy.state_dir`. - CHANGELOG: the `[Unreleased]` entry that adds `ntfy.state_dir`, edited. **Tests.** - Config table tests: `state.dir` accepted; a subscription without `state.dir` refused, the error naming `state.dir`; `ntfy.state_dir` refused as an unknown key. - The ntfy wiring tests pass with `state.dir`, and the state files land in it. **Done when.** - No file outside this plan names `ntfy.state_dir` or `UBERBRINGER_NTFY_STATE_DIR`. - The full gate passes (CLAUDE.md lists it); the snapshot builds, since the Dockerfile and install.sh changed. ### Stage 1c: The state machine, without a database **Goal.** The queue runs on the `Store` interface, with the memory store only: jobs with deliveries, the state machine, `sent_at` and `uncertain`, restoring at start, the shutdown rules, store failures, the duplicate check and digest references, and retention by content bytes. No new dependency. With the memory store the daemon behaves as today, apart from what the API and the logs add, the duplicate check on ntfy jobs, and a digest kept apart from later held messages once it is made. **Work.** internal/pkg/printqueue - store.go: `Record`, `Delivery`, `StoredState`, `Store`, `Loaded`, `UniqueRef`, `ErrContentGone`, and the memory store. A test option makes the memory store report itself durable, so that a second `Queue` on the same store stands for a restart. - queue.go: - The submit and status locks and the waiting list (Architecture, THE STORE INTERFACE). `Submit` checks capacity, commits `Add`, then makes the job visible to the worker, so a failed `Add` leaves nothing queued. - Each job gets one delivery, for the printer `default`. The worker works on that delivery: `Sending` and `Finish` name it by its `seq`. A job's status derives from its deliveries by decision 12's rule, written for any number of them. - `Restore`, called before `Run`: records back into memory, queued jobs onto the waiting list in sequence order, and one WARN line per delivery that `Load` turned `uncertain`. - The worker reads a job's content from the store when it takes it; one that no longer decodes fails. - `beforeWrite` calls `Sending` and sets `sent_at`. `failed` and unique inserts commit with a sync. Every state change commits, then changes memory. A store error stops the worker, and `Run` returns it. - Shutdown by `Durable()` (Architecture, JOB STATES): with a durable store, rendering and connecting run on a context that ends with the daemon, and only the write runs detached. - Retention: statuses by `History`, content by `ContentBytes`, uncertain content kept; the store is told what to drop in the same `Finish`. - The duplicate check for unique jobs, against the kept references. - `StateUncertain` and `Status.SentAt`, with the enum tag. - `Idle` when the waiting list empties. - `Sender` gains `beforeWrite`; `Meta` gains the unique flag and `Sequence`, the ntfy notification a card came from, which `Add` stores and phase 2b's cancel matches. internal/pkg/printer - `Send(ctx, data, beforeWrite)` calls it after `connect`, before the write deadline and `Write`. An error closes the connection with nothing written. internal/pkg/ntfy - A digest gets its reference, a TypeID with the prefix `digest`, when it is made. The subscriber keeps the digest, its rows, count and reference, in the saved state apart from the held set, saves before it calls `Digest`, and drops it once `Digest` succeeds. While a digest waits, new messages are held for the next one, as they are held today while other messages are. A restart with a saved digest submits that digest again first, with the same rows and reference, so the queue's duplicate check (decision 10) finds it if it was queued before the crash. `Digest` carries the reference. - message.go: `Notification()` (name assumed) returns `/`, the key of the notification a message or a delete belongs to, since sequence IDs are per topic; it is empty when `Sequence()` is. internal/pkg/config - `queue.content_bytes`: default 64 MiB, 0 to 1 GiB, an `int64`. internal/app/uberbringer - serve.go: the memory store; `queue.content_bytes` into the options; `Restore` before `group.Go`. - ntfy.go: cards and digests are submitted as unique, with the message ID or the digest's reference. A card's `Meta.Sequence` is `m.Notification()`; a digest's is empty. internal/app/uberbringer/server - Nothing beyond the regenerated enum and field: a store error from `Submit` already takes the unexpected-error path, and `ErrClosed` after the stop already answers `shutting_down`. Docs - docs/api.md: job status (`uncertain`, `sent_at`, and what `failed` with `sent_at` means). - docs/swagger.json regenerated. - docs/configuration.md: `queue.content_bytes`. - configs/config.example.toml: `[queue] content_bytes`. - design.md: "Jobs remember their source" (a digest's reference), and the digest paragraph of the ntfy subscriptions. - CHANGELOG: under **Breaking**, the `uncertain` status; under Added, `sent_at` and `queue.content_bytes`; under Changed, a digest's reference in the logs. **Tests.** internal/pkg/printqueue, with the memory store and a wrapper that fails or blocks on demand and records which commits were synced: - Queued jobs resume after a restart, in sequence order, also when their IDs were minted out of order, and ahead of jobs submitted after it. - A backlog larger than `Size` loads whole; `Submit` answers `ErrQueueFull` until it falls below `Size`. - A fake Sender that returns after `beforeWrite` without writing, standing for a crash between the mark and the write: after a restart the job is `uncertain`, logged at WARN with its IDs only, and never sent again; a second restart logs no WARN for it. - `Sending`, `failed` and unique inserts are synced; every other commit is not. - A dial failure writes no `Sending` record and sets no `sent_at`. A job whose first attempt reached `sending` and whose second failed to dial keeps `sent_at`. - Store failures: when `Add` fails, `Submit` returns the error, nothing is queued and the queue stops. When `Sending` fails, the Sender writes nothing, the queue stops, the status never reads `failed`, and after a restart the job is queued and prints once. When `Finish` fails, memory keeps its last state and the queue stops. - With the wrapper blocking a commit, `Status` and `Pending` still answer. - Shutdown with a durable store: waiting jobs stay queued; a job still rendering (a renderer that blocks), waiting for the printer, or between dial failures stays queued; a job in its write finishes; a job between retries after reaching `sending` fails with `sent_at`. With the memory store, shutdown is as today: this extends TestShutdownFinishesCurrentJobAndFailsWaiting. - A unique job submitted twice gives one job, also after its status was pruned with `History: 0`; the same reference on a job that is not unique gives two. - A stored job that no longer decodes fails, logged by ID, without its content. - Retention by count and by content bytes; unfinished and `uncertain` content is never dropped; dropped content gives `ErrContentGone`. - A job's status from its deliveries, by decision 12's rule, as a table test over records with one, two and three deliveries in every mix of states. The queue makes one delivery per job, so records with several are put into the memory store by hand and restored; they come back whole. - TestMetaInStatusAndLogs still finds no content in the logs. - schema_test: `uncertain` in the enum. internal/pkg/printer - Against a fake listener: `beforeWrite` runs after the dial and before the first byte, and when it fails the listener receives nothing. internal/pkg/ntfy, on the virtual clock - The digest and its reference are in the saved state before `Digest` is called. A restart from that state, with the handler's success lost to the crash, submits the same digest with the same reference before any later one. Messages held after the digest was made, also while quiet hours delay its resubmission after the restart, go on the next digest under a new reference. A printed digest's successor gets a new one. - `Notification()` joins topic and sequence, falls back to the ID, and is empty for an event with neither. internal/pkg/config - `queue.content_bytes`: the default, 0, 1 GiB, and values outside the bounds refused. internal/app/uberbringer - ntfyPrinter submits cards and digests as unique, with their references. A card carries its notification in `Meta.Sequence`, also for a message without `sequence_id`; a digest carries none. **Done when.** - The full gate passes. ### Stage 1d: The SQLite store **Goal.** Jobs survive a restart on disk. A restart never prints a receipt twice. Each job costs one synced write, plus one per failure and per ntfy job. **Work.** go.mod - `modernc.org/sqlite` at its latest stable release, with the exact `modernc.org/libc` its go.mod pins, and the indirect modules decision 13 names. Run govulncheck. tools - A small program, `tools/libcpin` (name assumed), that fails when `go list -m modernc.org/libc` differs from the libc that `modernc.org/sqlite` requires in `go mod graph`. It runs as `go run ./tools/libcpin`, so it works from PowerShell and in CI alike. internal/pkg/jobstore (new) - `Open(dir)`: as RECORDS describes, in that order, creating the `jobs`, `deliveries`, `content` and `refs` tables. - The `Store` methods on the held connection. `Add` inserts the job, its deliveries and its content in one transaction. `Sending` and `Finish` update a delivery's row by its `seq` and never touch the `jobs` row. `Finish` and its pruning, of jobs, deliveries and contents by `seq`, share one transaction. `Load` attaches each delivery to its job by `job_seq`. `Idle` checkpoints. - Errors carry the operation and the job's or delivery's sequence number only. internal/app/uberbringer - serve.go: when `state.dir` is set, check the directory once (moved from ntfy.go), whether or not there are subscriptions, then open the jobstore; otherwise the memory store. Open and `Restore` before the subscribers are made and before `group.Go`. Close the store after the queue stops. Packaging - packaging/uberbringer.service: `UMask=0077`; the comment says the state directory holds the job store and the ntfy state. - Dockerfile: the comments (decision 14). - `.gitea/workflows/test.yml`: `CGO_ENABLED=0` builds of linux/arm (GOARM=6) and linux/arm64, and `go run ./tools/libcpin`; its header comment, which says branch pushes build no binaries. - 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 (decision 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. - docs/ntfy.md: the "Jobs" paragraph, which says a waiting job is lost at shutdown. - docs/configuration.md: the worker's log lines, under Logs. - docs/install.md and docs/docker.md: the steps for a store that will not open (STORE FAILURES). - docs/configuration.md: a downgrade note. - docs/development.md: the layout (`internal/pkg/jobstore`, `tools/libcpin`), the `make check` steps, and "CI and releases", which says test.yml builds no binaries. - docs/api.md: job status (what survives a restart) and the `job_not_found` row. - CHANGELOG: under Added, jobs survive a restart; under **Breaking**, that with a state directory waiting jobs print after a restart instead of failing, and the Docker image's store (decision 14); the downgrade note. - CLAUDE.md: the layout and the imports (jobstore → printqueue; internal/app → jobstore); the gate's new steps, and line 75's "It builds no binaries"; the libc exception beside the rule that dependencies are at their latest stable release. - docs/swagger.json regenerated, if anything changed. **Tests.** internal/pkg/jobstore. Each test calls `t.TempDir()` before `Open`, so on Windows the store is closed before its directory is removed. - Every field of a job and of its deliveries survives a close and a reopen, times to the nanosecond and `sent_at` included, also for a job with three deliveries, and in a directory whose name holds a space and `#` (and `?`, where the file system allows it). - Through the test hook: `Sending`, `failed` and unique inserts commit at FULL, every other commit at NORMAL. The hook also reads `total_changes()`, so a test sees that `Sending`, and a `Finish` that prunes nothing, change one row, the delivery's. - A second `Open` of the same directory fails at once. The test runs it in a child process, the test binary run again, so the lock is the file system's and not SQLite's table within one process. - The file is 0600 (Linux only). - `Finish` drops jobs, their deliveries and content in the same transaction. - `Load` turns every delivery in `sending` into `uncertain` in one commit, leaves the other deliveries of the same job alone, returns the deliveries it turned, and returns content lengths without content. A second `Load` turns and returns none. - `refs` keeps the newest 512 per source and outlives the pruning of their statuses. - A damaged page in the middle of the file fails `Open` with an error naming the file, and so does a damaged header. A `user_version` newer than the binary's is refused, naming both. - With `wal_autocheckpoint=0`, 30 jobs: WAL frames per job are logged and held to an upper bound with headroom, not to an exact number. internal/app/uberbringer - TestServeRestart (new): `run` twice on one `t.TempDir()` against a fake printer listener. Before the second `run`, the test adds a job whose delivery is in `sending` through jobstore, standing for a crash mid-send. Queued jobs print after the restart, ahead of new ones; the seeded job reads `uncertain`, and the listener never receives it. - With `state.dir` set and no subscription, the store opens, and a directory that cannot be written stops the start. - Without `state.dir`, TestServeEndToEnd passes unchanged. Crash tests use fault injection like the above, never kill loops or soaks on the workstation. **Done when.** - design.md records the owner's store choice, the sync policy and stage 1a's numbers, and armv6 ran on hardware, or the owner accepted it untested. If the owner agrees, the jobstore tests, cross-compiled with `go test -c` for GOARCH=arm GOARM=6, ran on his Pi. - Paper, with the owner's OK, one short receipt at a time, waiting for his report after each: 1. A receipt prints through the store and reads `done`, and still reads `done` after a restart. 2. With the printer switched off, a receipt is sent, and the daemon is stopped while the log still shows `send failed, retrying`. With the printer on again, the daemon starts, and the receipt prints once. 3. A receipt is killed while its write waits (`systemctl kill -s KILL uberbringer` on a host, `taskkill /F` on the workstation); one way to make the write wait is an open cover and a receipt larger than the printer's buffers, such as one with an image. After the restart it reads `uncertain` and is not sent again; once the cover is closed, what the printer had buffered prints, and only once. - The full gate passes, with the arm builds and the libc check; govulncheck is clean; the snapshot builds every target. - The Investigation findings section is deleted from this plan, now that design.md holds what it decided. ### Phase 2: The API for stored jobs **Goal.** Clients can see the history and the jobs in doubt (decision 16). **Work.** internal/pkg/printqueue - `List(filter, before, limit)` from memory, newest first by sequence number; a `before` no longer kept is an error the server maps to `invalid_query`. The count of jobs with a delivery that `Load` turned `uncertain` at the latest start. `Status.Ref`. internal/app/uberbringer/server - The route `GET /api/v1/jobs` in the table, for full tokens; its handler and response type; `Jobs` gains `List`, and `fakeJobs` with it; its case in TestRoutesConform. - `/healthz`: `queue.uncertain`. tools/genopenapi - Typed query parameters: an enum and an integer with bounds. Docs - docs/api.md: the route table, a "List jobs" section, the reworded `invalid_query` row, the Job status section (`ref`) and the health field. - design.md: "Jobs remember their source" says job status shows the reference too. - CHANGELOG. docs/swagger.json regenerated. **Tests.** - Filters by status and source, paging with `before`, a `before` no longer kept, the bounds of `limit`, and bad values giving `invalid_query`. - A token limited to modules gets `403` `token_scope`. - schema_test: the new enums held to validation. - `/healthz` counts the `uncertain` jobs found at start, a clean restart sets the count to 0, and the status code is unchanged. - No content in any log line. **Done when.** - `curl` on `/api/v1/jobs` lists the history, pages through it and filters it. - The full gate passes. ### Phase 2b: Cancelling waiting jobs **Goal.** A job's deliveries that have not reached `sending` can be cancelled: through `DELETE /api/v1/jobs/{id}` (decision 17), and through an ntfy `message_delete` for the notification it came from. A `message_clear` cancels nothing (decision 18). A cancelled delivery never reaches the printer, and a delivery that has reached `sending` goes on. **Work.** internal/pkg/printqueue - queue.go: - `StateCancelled`, with `cancelled` in the `State` enum's `jsonschema` tag: a new value clients may meet, so the CHANGELOG lists it under **Breaking**, as it does `uncertain`. - Only a delivery that has not reached `sending` can be cancelled: one waiting, rendering, waiting for the printer's slot, dialling, or between retries that never reached the printer. Cancelling a job cancels those of its deliveries; one that has reached `sending`, or has finished, goes on. - `Cancel(id)` (name assumed) cancels the job's deliveries that have not reached `sending` and returns its status. With none left to cancel it returns the status as it is if any delivery is cancelled, so a repeated cancel answers as the first did, and `ErrStarted` (name assumed) if none is. - `CancelSequence(source, sequence)` (name assumed) cancels those deliveries of each job from that source whose `Meta.Sequence` (stage 1c), its notification, equals `sequence`, and returns the jobs' IDs. It matches in memory, so a job restored after a restart is found too. An empty `sequence` matches nothing, so jobs without one, HTTP and module jobs and digests, are never cancelled by it. A job with nothing left to cancel is passed over without an error. - The delivery lock (name assumed; Architecture, THE STORE INTERFACE) orders the cancel against the worker. Each side checks the delivery's state in memory, commits and changes memory without releasing the lock, so a cancel and a `sending` mark can never both pass their checks (invariant 7): - `beforeWrite`: for a cancelled delivery it returns `errCancelled` (name assumed), and the printer closes the connection with nothing written; otherwise it commits `Sending` and changes memory. - The worker's `Finish` takes the lock too, which also orders the pruning it carries. For a delivery that has not reached `sending` (a render error, every dial failing, a job that no longer decodes, and with several printers an anycast list run out), it writes nothing when the delivery is cancelled. - The cancel leaves alone a delivery that has reached `sending` or finished. It commits the others `cancelled` in one synced commit (Architecture, JOB STATES), which drops what the cancel pushes out of retention as `Finish` does; then memory changes, they leave the waiting list, and their contexts end, so rendering, waiting for the printer's slot and dialling stop. - The worker of a cancelled delivery stops with no retry, no `Finish`, no "job failed" line and no `OnFailure`, since the cancel's commit is its final state: `errCancelled` from `Send` is never retried, and an error after its context ended ("rendering: context canceled", "giving up after n attempts") finds the delivery `cancelled` under the lock. - A store error stops the queue (decision 11). - A cancelled job counts as finished for retention. An ntfy job keeps its reference (decision 10), so a replay after a restart does not queue it again. - store.go: `StoredState` gains `cancelled`, and `Store` gains `Cancel(ctx, deliveries []uint64, at time.Time, dropJobs, dropDeliveries, dropContent []uint64) error`, one synced commit. The memory store implements it. internal/pkg/jobstore - `Cancel`: one synced transaction that sets each delivery's `state` and `finished_at` and drops the given jobs, deliveries and contents. The `sequence` column is in the schema and written from stage 1d (RECORDS), so there is no schema step. 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 as for any message, and the state is saved within a second. `message_clear` stays skipped (decision 18). - `message` lets a `message_delete` past the `max_backlog` check (decision 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 (decision 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. 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. - ntfy_test.go: the fake submitter gains `CancelSequence`. internal/app/uberbringer/server - The route `DELETE /api/v1/jobs/{id}` in the table, for full tokens; its handler, answering `200` with the status, `409` `job_started` or `404` `job_not_found`; `Jobs` gains `Cancel`, and `fakeJobs` with it; its case in TestRoutesConform. - errors.go: `409` `job_started`, for a job whose every delivery has reached `sending` or finished, none of them cancelled. - Unchanged: the `ntfy` module route (`POST /api/v1/print/ntfy`) still answers `204` to `message_delete`. Its jobs carry a request ID, so nothing ties them to the message. Docs - docs/api.md: the route table, a "Cancel a job" section, the `job_started` row in the error table, and the Job status section (`cancelled`). - docs/ntfy.md: how a subscription behaves: a `message_delete` cancels the waiting receipts of its notification and drops its held digest rows, also under `min_priority` and past `max_backlog`; a `message_clear` does neither; `min_priority` is applied by the subscriber, which reads every message of its topics. - design.md: the state machine's `cancelled`, its synced commit and the delivery lock; the ntfy subscriptions paragraph (deletes cancel, clears do not, and the subscriber filters priorities itself). - docs/plans/formatters.md: its phase 5 item "Queue.Cancel so message_delete can cancel a still-queued job" goes, since this phase builds it. - CHANGELOG: under **Breaking**, the `cancelled` status; under Added, `DELETE /api/v1/jobs/{id}` and cancelling by ntfy deletes; under Changed, that a subscription with `min_priority` reads every message and filters itself. - docs/swagger.json regenerated. **Tests.** internal/pkg/printqueue, with the memory store and the wrapper from stage 1c: - A waiting job cancels: it reads `cancelled`, leaves the waiting list and never reaches the Sender, and still reads `cancelled` after a restart. A second cancel returns the same status. - A job cancelled while rendering (a renderer that blocks), waiting for the printer, or between dial failures: the fake Sender writes nothing, and the job reads `cancelled`, not `failed`, also once its worker has stopped. No retry follows, `OnFailure` is not called and no "job failed" line is logged. - The cancel against the `sending` mark, ordered by the wrapper blocking one commit and then the other, never by timing: when the cancel commits first, `beforeWrite` fails and the fake Sender writes nothing; when the mark commits first, `Cancel` returns `ErrStarted` and the job prints. - The cancel against the worker's own `Finish` of a delivery that has not reached `sending` (a render error, the last dial failing), ordered the same way: whichever commits first is the final state, and memory agrees with the store. - A job in its write, between retries after reaching `sending`, or done, failed or `uncertain` gives `ErrStarted`. - A record with two deliveries, put into the memory store by hand, one in `sending` and one queued: the cancel cancels the queued one, the other goes on, and the status follows decision 12. A second cancel returns the status, not `ErrStarted`. - The `cancelled` commit is synced. When it fails, memory keeps `queued`, the queue stops, and after a restart the job prints once. - A cancel that pushes the oldest finished job past `History` drops it in the same commit. - `CancelSequence` cancels only that source's jobs with that notification: not another subscription's, nor one with the same sequence in another topic, nor an HTTP job whose `ref` happens to match. An empty sequence cancels nothing, with digests and HTTP jobs waiting. - A queued job with a sequence, restored after a restart on the durable memory store, is cancelled by `CancelSequence` and still reads `cancelled` after another restart. - schema_test: `cancelled` in the enum. internal/pkg/jobstore - Through the test hook: `Cancel` commits at FULL and, with nothing to prune, changes only the cancelled deliveries' rows (`total_changes()`); with drop lists, it drops those jobs, deliveries and contents in the same transaction. - A cancelled delivery's state and `finished_at`, and its job's `sequence`, survive a close and a reopen. internal/pkg/ntfy, on the virtual clock - A `message_delete` calls `Delete` with the event. A `Delete` error is retried as a `Message` error is, and the cursor moves only once it succeeds. - A delete drops the held rows of its topic and sequence and lowers the count, and the saved state shows it; a row of the same sequence in another topic stays; a held set that deletes empty prints no digest; messages past the rows stay counted; a digest already made and saved is left alone. - With `MinPriority` 4, the connection asks for no `priority=`, a delete still calls `Delete`, and a message of priority 3 is still left out and not counted in `LastMessageAt`. - A delete older than `max_backlog` in a replay still calls `Delete`. - An update in one topic of a sequence printed in another is not marked as an update. - A `message_clear` calls nothing and drops nothing, and is recorded as dealt with as today. internal/app/uberbringer - `Delete` cancels through `CancelSequence` with the subscription's source and the delete's notification; a delete for a notification with no waiting job does nothing. internal/app/uberbringer/server - `DELETE /api/v1/jobs/{id}` answers `200` with `cancelled`, and `200` again on a repeat; `200` while the job renders or dials; `409` `job_started` for a job in its write, between retries after reaching `sending`, done, failed or `uncertain`; and `job_not_found` for an unknown ID. A token limited to modules gets `403` `token_scope`. `DELETE /api/v1/print` still answers `405`. **Done when.** - Paper, with the owner's OK, one short receipt at a time, waiting for his report after each. With the printer off and the defaults, a job fails within about 30 s, and a failed job prints nothing either. So for both checks the config sets `printer.retries = 10` and `printer.retry_delay = "10s"`, which keep the job retrying up to its 2-minute bound; each cancel comes within a minute, and the defaults are restored afterwards. 1. With the printer switched off, a receipt is sent and then cancelled through `DELETE /api/v1/jobs/{id}`. The job reads `cancelled`, not `failed`, and with the printer on again, nothing prints. 2. With the printer switched off, a message is published to a subscribed ntfy topic and then deleted on the ntfy server. The job named by the "ntfy receipt queued" line reads `cancelled`, and with the printer on again, nothing prints. - The full gate passes. ### Phase 3a: Drawing text, images and cuts **Goal.** A picture of the paper from the bytes a job renders to, for everything but QR codes and barcodes, with no change to the server. **Work.** internal/pkg/escpos - interpret.go keeps the drawing data described under Architecture. The existing interpreter tests stay unchanged. - profile.go: the geometry fields (Architecture, THE PREVIEW IMAGE), with their sources. internal/pkg/paper (new; name assumed) - The 1-bit image type. - draw.go: lines into the image, as wide as the profile; text, rules, raster images, cuts and raw spans; the height cap, with an error the server maps to `preview_too_long`. - glyphs: box drawing and shading from the cell geometry; every other glyph from a bitmap font, as Go tables written by a generator (`tools/genglyphs`, name assumed) from the font's file, committed with its licence. The session first checks the candidates against decision 19's criteria; if none meets them, it stops and asks the owner. **Tests.** - Golden PNGs in testdata: `examples/blocks.json`; a glyph sheet per code page; every style and size; Font B; inverted text; box joins and shading; an image whose drawn dots equal its raster bits; a cut at the profile's cutter distance; a raw span; each block of docs/plans/blocks.md that has shipped, banners and spans drawn at a run's `W` and `H`. - A job over the cap fails with the cap's error before it draws past it. - FuzzDraw over `Interpret`'s output for fuzzed jobs: no panic, the width equals the profile's dots, and the height stays within the cap. `go test` runs its seed corpus only; no `-fuzz` runs on the workstation. - The text and JSON previews are unchanged: their goldens pass. TestRenderCompat passes: no printed byte changes. **Done when.** - The full gate passes. ### Phase 3b: QR codes and barcodes **Goal.** The picture shows QR codes and the six barcode symbologies the renderer emits. **Work.** internal/pkg/paper - qr.go: an encoder, either a pure-Go dependency at its latest stable release or our own code, chosen in this phase on the same terms as the store (size, upkeep, pure Go). A dependency comes in at its latest stable release, with govulncheck run after it. - barcode.go: EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128, with their digits. The tables are hand-written. **Tests.** - A QR code per correction level, whose module count is at most `escpos.QRModules`, and equal to it for data only byte mode holds, since an encoder that picks a denser mode gives a smaller code. - Each symbology, its bars checked against the standard's patterns for a known value, such as EAN-13 4006381333931. - A golden PNG of a receipt with a QR code and each barcode. **Done when.** - The full gate passes. ### Phase 3c: The image preview in the API and the CLI **Goal.** The preview routes and the CLI answer with the picture (decision 19). **Work.** internal/pkg/receipt - `Renderer.PreviewImage`: `base64` images from their data, `url` images fetched through safehttp under one 30-s deadline for the whole preview, a crossed box for each image that failed or is still loading. internal/app/uberbringer/server - `Previewer` gains `PreviewImage`. handlers_preview.go answers `image/png` when asked; text stays the default. The cap's error answers `422` `preview_too_long` (errors.go). Check that the compress middleware leaves PNG alone. tools/genopenapi - A PNG response body. internal/app/uberbringer - The CLI: `uberbringer preview --png `. Docs - docs/api.md: the preview section (the PNG, the fetch deadline, the cap) and the error row. The text and JSON previews still fetch no images; the PNG preview does. - design.md: why the picture is drawn from the bytes rather than the layout; the font, its licence, and why box drawing is drawn rather than taken from it; "The preview reads the bytes back" ("a preview never fetches anything") and "Images are fetched by the worker" ("a slow or broken image URL holds no HTTP request"), which a PNG preview no longer keeps to. - docs/cli.md, and the layout in docs/development.md (`internal/pkg/paper`, `tools/genglyphs`). - CLAUDE.md: the layout and the imports (receipt → paper → escpos). - CHANGELOG. docs/swagger.json regenerated. **Tests.** - Server: `Accept: image/png` gives `200` `image/png` with a PNG signature; `*/*` still gives text; a module preview as PNG; a job over the cap gives `422` `preview_too_long`; scopes unchanged. - An image URL that never answers is drawn as a crossed box once the deadline passes, through a fake fetcher, not a real wait. - The CLI writes a PNG file. **Done when.** - A tall PNG (a long receipt) opens and scrolls in a browser. - Paper, with the owner's OK, one receipt at a time, waiting for his report after each: `examples/blocks.json`, then one receipt with a QR code, a barcode and an image. Their PNGs match the paper: line breaks, box joins, code sizes, image edges and the cut. Photos of receipts already printed can stand in, if the owner has them. - The full gate passes. ### Phase 4: Previews of stored jobs **Goal.** `GET /api/v1/jobs/{id}/preview` shows a submitted job, as text, JSON or PNG (decision 20). **Work.** internal/pkg/printqueue - `Content(id)`: the stored job, `ErrNotFound` or `ErrContentGone`. internal/app/uberbringer/server - The route `GET /api/v1/jobs/{id}/preview` in the table, for full tokens. It decodes the stored job strictly and answers through the same negotiation as the POST preview. `Jobs` gains `Content`, and `fakeJobs` with it. - errors.go: `410` `job_content_expired`. Docs - docs/api.md: the route, a section and the error row. CHANGELOG. docs/swagger.json regenerated. **Tests.** - Previews of a queued, a done and an `uncertain` job, with the memory store and the jobstore. - Pruned content gives `410` `job_content_expired`; an unknown ID gives `job_not_found`; a token limited to modules gets `403`. - A stored job's text preview equals the POST preview of the same body. **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 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) **Goal.** Keep the core small. Each item is independent. **Work.** - Epson's acknowledgement (decision 21). First, each with the owner's OK and one short receipt at a time: 1. Does the TM-T88IV, through its board, answer `37 22 ID 00` on port 9100 for a receipt ending in `GS ( H 48 "0001"` after the cut? Check that it printed and cut once, and how long after the cut the answer came. 2. Does the answer come after the knife? A long feed before the cut shows it. 3. Does an answer sent after the host closed the connection reach the next one? 4. Which board is fitted, UB-E02 or UB-E03? The board's status sheet says. 5. Does the TM-m50II support it, once it arrives? Then, if it works: - escpos: `ProcessIDRequest(id)` and a frame reader for real-time status, automatic status, process IDs, clear responses and unknown blocks. - printer: a confirmed send with its four outcomes, using the count `Write` returns. `Status` reads through the frame reader and skips frames it did not ask for. - `/healthz` while a job holds the connection. - Config: `printer.confirm` (`auto`, `process_id` or `off`) and `printer.confirm_timeout`. Status gains `confirmed_at`. The store keeps the ID counter. - The partial-write choice (decision 23), once the confirmed send reports the bytes written. - ntfy state in the store (decision 22). - An `Idempotency-Key` header on `POST /api/v1/print`. - A reprint route for `uncertain` jobs, `POST /api/v1/jobs/{id}/reprint`, which queues a new job from the stored content. - An age limit for queued jobs or stored content (decisions 6 and 9). **Tests.** Each item ships with table tests in the style of the phases above. The acknowledgement also needs a fake printer that answers with process IDs, automatic status frames and stray real-time replies, and a test that a time-out gives `uncertain` and no resend. **Done when.** Each item is done when it has tests, docs and, where it changes what prints or how status is read, a paper check with the owner's OK.