The job store is to keep its database in the directory that holds the ntfy subscriptions' state files, so the directory moves to a section of its own: [state] dir, or UBERBRINGER_STATE_DIR, in place of [ntfy] state_dir. For now only the subscriptions use it. It still has no default and is still required with a subscription, and the checks at start name state.dir in their errors. install.sh writes [state] dir into new configs, and the Docker image sets UBERBRINGER_STATE_DIR. ntfy.state_dir has never been in a release, so its CHANGELOG entry changes in place and there is no fallback: a config that still sets it fails to load with an unknown key until the line moves to [state]. The image itself was not built, since the workstation has no Docker. Part of stage 1b of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 KiB
Plan: persistent job store and image previews
Status: in progress; stage 1a's measurements are done (Investigation findings), and so is stage 1b's [state] dir. The store itself is not 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
synchronoussetting 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 useCGO_ENABLED=0. The store's files live in the unit'sStateDirectory, 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_deleteevent 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:
- The store. SQLite through
modernc.org/sqlite(v1.63.0 today) anddatabase/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
sqlite3CLI from readingjobs.dbwhile the daemon runs. - Not GORM, though it writes the same bytes and fsyncs as plain SQL (measured). Its pure-Go dialector,
github.com/glebarez/sqlitev1.11.0, has had no release since 2024-03-14 and asks for maintainers (issue #152). A plaingo getof it pulls in SQLite 3.41.2, and it cannot share a binary withmodernc.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.
- 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
- Hardware for the measurements. The owner has no ARM boards and no Pi-class host, so stage 1a ran its probe on leil-test-1, an x86_64 VM on leil-rig with a virtual disk (Investigation findings, MEASURED ON LEIL-TEST-1). That measured Linux, device writes and flushes, and the unit's sandbox, but not an SD card or ARM. No build of the store runs on ARM hardware: modernc's own CI names no ARMv6 target, and there are old SIGSEGV reports for linux/arm. So the armv6, armv7 and arm64 tarballs ship the store untested on hardware, and the CHANGELOG says so.
- SQLite's locking mode.
locking_mode=EXCLUSIVEand one connection. There is no-shmfile 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, thesqlite3CLI or a later read-onlyuberbringercommand 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:
- Config key and directory. A top-level
[state] dir(UBERBRINGER_STATE_DIR) holdsjobs.dband thentfy-<name>.jsonfiles and replacesntfy.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.
- No release has shipped
For stage 1c:
- 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
202can 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.
- 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
- 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).
- 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, whoseerrorsays 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 notunknown, which/healthzalready uses for a printer that gives no status. Trade-off: a new status value reaches clients that switch onstatus, so it is listed under Breaking. - What is stored. The job as validated, a
receipt.Jobin 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
sendingis 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.
- Rendered bytes are never needed to resume, since a job that reached
- Retention. Statuses as today, the last
queue.history(1000) finished jobs. The content of finished jobs within a byte budget, a new keyqueue.content_bytes, default 64 MiB and at most 1 GiB, newest kept. The content of unfinished jobs is always kept, and so is that ofuncertainjobs 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.size100 × 4 MiB, about 400 MiB, and withauto_vacuum=NONEthe file never shrinks below its high-water mark. With several printers the bound is per lane: about 1.2 GiB for three (docs/plans/printers.md decision 4). - An age limit, for privacy, would be another key (phase 5).
- A count alone cannot bound it:
- 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
Submitwhose 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 = 0cannot defeat the check. - A digest gets a reference of its own, a TypeID with the prefix
digest, in place of the fixeddigest, 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.
- A
- A store write that fails after start (disk full, an I/O error, corruption found mid-run) stops the daemon.
- The queue stops and
Runreturns 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 reachedsendingstays queued and prints once after the restart. - The request whose insert failed gets
500internal_error; later ones getshutting_down. ntfy messages wait: the subscriber retries anySubmiterror 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.
- The queue stops and
- A job's status from its deliveries. A job has one delivery per printer, and its API
statusderives from theirs (Architecture, DELIVERIES AND SEVERAL PRINTERS). Each job has one delivery until the printers plan lands, but the schema and theStoreinterface 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. queuedwhile every one waits, none taken and none finished;printingwhile any is unfinished, once one has been taken or has finished;- once every one has finished:
uncertainif any is, since it means a receipt may have printed; otherwisefailedif any is; otherwisedone. - So
failedanduncertainstay final, as today: a failed oruncertaindelivery beside one that still waits or prints leaves the jobprinting, and one cancelled delivery beside done ones readsdone. - Trade-off: a client that reads only
statuslearns that one printer failed only once the others have finished; thedeliveriesarray shows each printer at once.
- Cancelled deliveries are passed over unless every delivery is cancelled; then the job is
For stage 1d:
- The libc pin. modernc requires the exact
modernc.org/libcits 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 withmodernc.org/sqlite. Stage 1d records it in CLAUDE.md's dependency rule and in design.md, and adds a gate check, since a routinego get -uwould otherwise move libc and break the driver silently. The other new indirect modules aremodernc.org/mathutil,modernc.org/memory,github.com/dustin/go-humanize,github.com/ncruces/go-strftimeandgithub.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. - 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 noVOLUME; docs/docker.md asks for a named volume, or a bind mount owned by10001:10001. This is Breaking: a container started with--read-onlyand 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. AVOLUMEwould let such containers start, but anonymous volumes pile up, and a new container would silently start with an empty one. - 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_timeoutplus 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 40at the defaults. Trade-off: a shorter timeout kills a write, which leaves its jobuncertain, never doubled. UMask=0077in 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=0build 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:
- 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) andlimit(1-100, default 50) in the query. Abeforethat names a job no longer kept answersinvalid_query, so paging never skips jobs silently.- Job status gains
ref, so a client can find the job an ntfy message became. /healthz'squeuegainsuncertain: the jobs founduncertainat the latest start, those with a delivery thatLoadturned fromsending. From remote-printers stage 4 it also counts the jobs a remote send has leftuncertainsince that start. A clean restart sets it back to 0, so it does not stay up for about 1,000 jobs.
For phase 2b:
- 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 reachedsendingand answers200with the status. A job with nothing left to cancel, every delivery having reachedsending, finished or been cancelled, answers200with its status if any delivery is cancelled, so a repeated request answers as the first did, and409with a new code,job_started, if none is; an unknown ID answersjob_not_found. Trade-off: more API, and the first route that changes a job already queued. - 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_priority4 or 5 receives nomessage_deletetoday. ntfy applies thepriority=filter to deletes and clears too (queryFilter.Passin its server/types.go), and a delete carries no priority, so it counts as 3. So the subscriber stops sendingpriority=and leaves out lower priorities itself, asdeliveralready 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 belowmin_priority. - A
message_deleteolder thanmax_backlogstill 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:
- 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/pngon the preview routes; text stays the default.- Images: a
base64image is drawn from its data, and aurlimage 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 answers422with 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 <file>.
- Images: a
For phase 4:
- 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
410with a new code,job_content_expired. As a PNG it loads its images as decision 19 says.
For phase 5, later:
- Epson's process-ID acknowledgement (
GS ( Hfn 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 mostuncertainjobs into confirmed prints, but it holds the printer connection until the receipt is done, so/healthzneeds another way to read status mid-job, and whether its answer gets through the printer's network board is unverified. - 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. - 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
partialoutcome is today's write error. OnceSendreports how many bytesWritetook (docs/plans/printers.md stage 3'sSendError, or phase 5's confirmed send), the owner may choose that such a job becomesuncertainand is never resent. Trade-off: fewer doubled fragments, against more jobs a person must check. With several printers, docs/plans/printers.md decision 22 fails such a delivery over to the next printer of an anycast list after the retries on the first printer (Architecture, DELIVERIES AND SEVERAL PRINTERS). That 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, on a Pi or on an SD card. Stage 1a then ran a probe on leil-test-1, a Linux VM (MEASURED ON LEIL-TEST-1). Versions are the latest on 2026-11-30, from proxy.golang.org; stage 1a used modernc.org/sqlite v1.64.0, released on 2026-12-01.
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
sendingdurably before the first byte goes out. A job found insendingafter a restart is in doubt and is never resent; a job stillqueuednever 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
sendingmark must be synced before the first byte, whatever the store. Most other writes may be lazy: losing one makes a job read asuncertain, or loses a job never sent, but never prints one twice. The exception isfailed: rolled back toqueued, 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
-walfile: 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. synchronousin 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_limitis set. - Sync levels can be mixed.
synchronousbelongs to the connection, is not persisted, and cannot change inside a transaction. The worker can runPRAGMA synchronous=FULL, commit thesendingmark, 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
sendingdurably 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. On leil-test-1's virtual disk, a FULL commit took 5.0 ms (median), or 2.9 ms with fdatasync, and a NORMAL one about 0.6 ms. An SD card's flush time is unmeasured. - fsyncs per job, with
doneand 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 with the schema. Every run here kept a job's status in one table. The schema under RECORDS, which splits it into
jobsanddeliveries, appended 11.46 frames (46.1 KiB) per text job on leil-test-1.
- 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
doneand the pruning into one commit; prune in batches; optionally compress bodies; optionally checkpoint while the queue is idle. - Operations.
- The database,
-waland-shmbelong together. Never delete the WAL or copy the.dbalone;VACUUM INTOmakes a backup. locking_mode=EXCLUSIVE, set before the first access, means no-shmand no mmap. A second process then getsSQLITE_BUSYat once, provided the daemon writes once at open.temp_store=MEMORYavoids temporary files.auto_vacuum=NONEreuses 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
-waland-shmthe database file's mode. secure_delete=FASTscrubs b-tree pages at no extra IO, but not free overflow pages, where image bodies end up.ONcosts extra writes.- WAL does not work over a network filesystem, and Docker Desktop bind mounts pass through a VM file share.
- The database,
MEASURED ON LEIL-TEST-1 (stage 1a, 2026-12-01)
- The host. leil-test-1, the test node of leil-rig: an AlmaLinux 9.8 VM (kernel 5.14, x86_64, 16 cores) under KVM on pve-1. The store's directory was on xfs on a virtual QEMU SCSI disk, with
write_cache"write back" and FUA on; what pve-1's storage does with a flush is unknown. So the times are a VM's, not an SD card's, and nothing ran on ARM (decision 2). The node was idle: load average 0.1 on 16 cores, no build running. - The probe.
jobprobe, built withCGO_ENABLED=0and Go 1.27.4 onmodernc.org/sqlitev1.64.0 (SQLite 3.54.1, libc v1.80.1, the same pin as v1.63.0). It sets the pragmas and creates the schema under RECORDS. It stores 1000 finished jobs, then runs 200 text jobs of 1,500 bytes, one delivery each: the insert at NORMAL, thesendingmark at FULL, thendoneand the pruning of the oldest job in one commit at NORMAL. Device counters come from/sys/dev/block, read after asyncfs, less an idle baseline taken over a minute first. - The sandbox allows the store. Both runs ran as transient units with the unit's sandbox:
DynamicUser,ProtectSystem=strict,PrivateDevices,MemoryDenyWriteExecute,SystemCallFilter=@system-servicewithSystemCallErrorNumber=EPERM, andSystemCallArchitectures=native. SELinux was enforcing, and both runs finished without an error.@system-servicetakes in@sync(fsync,fdatasync,syncfs),@file-system(fcntl,ftruncate,openat,unlink) and@basic-io(pread64,pwrite64). The database and the WAL were 0600, and there was no-shmfile.
| Per job | fsync | fdatasync |
|---|---|---|
| Device writes, less the baseline | 53.8 KiB in 2.37 requests | 53.4 KiB in 2.38 requests |
| Device flushes | 1.04 | 1.04 |
write_bytes in /proc/self/io |
52.6 KiB | 52.6 KiB |
| WAL frames | 11.46 (46.1 KiB) | 11.46 (46.1 KiB) |
FULL commit (sending): median, p99, max |
4.98, 8.36, 9.87 ms | 2.89, 6.15, 6.76 ms |
| NORMAL commit: median, p99, max | 0.55, 1.06, 15.12 ms | 0.61, 1.09, 24.01 ms |
- Checkpoints. Two automatic checkpoints ran in 200 jobs, about one every 87 jobs, and both ran inside an insert's commit. The slowest inserts, those that ran a checkpoint or restarted the log and synced its header, took 10-24 ms. The other NORMAL commits took about 1 ms or less. The final PASSIVE checkpoint, of 291 frames, took 6-7 ms and wrote 109.5 KiB to the device with 2 flushes. The database levelled off at 2.12 MiB and the WAL file at 3.93 MiB, within
journal_size_limit. - The baseline. The node's own services wrote about 2 MiB a minute, in about 250 write requests and 85 flushes. Over a run of about 1.5 s that is about 0.3 KiB and 0.01 flushes per job. The baseline takes out steady writes, not a burst.
- Against the estimates above:
- Flushes: 1.04 per job, as predicted: one for the
sendingmark and about 0.04 for checkpoints and restarts of the log. - WAL frames: 11.46 per text job, against 14.35 in the SQLite track's runs with one table.
- Device writes: 53.8 KiB per job, against the 75-80 KiB estimated for ext4. The device wrote about 8 KiB per job beyond the WAL frames: the xfs log of each sync and the job's share of the checkpoints. At 500 jobs a day that is about 26 MiB a day.
fdatasyncleft the writes and flushes the same and cut the synced commit's median by about 40%.
- Flushes: 1.04 per job, as predicted: one for the
- None of this argues against decision 1: the writes and flushes are at or below the findings' figures. An SD card's flush time and wear, ext4, and ARM remain unmeasured.
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.
Saverewrites 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.gocallingreflect.Value.MethodByNamewith 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 getof 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 namesqlite, so a binary with both panics at start. - GORM's own SQLite driver,
gorm.io/driver/sqlitev1.6.0, needs cgo. sqlcv1.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_listoverrun 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 andsynchronousswitched between FULL and NORMAL between commits. The race detector does not run on 32-bit ARM, and nothing has run the store on ARM hardware (decision 2).
- It syncs with fsync, not fdatasync, unless
- 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/sysis 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.
NoSynccannot 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 -hshows 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
SyncWritesdoes nothing: themsyncof 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. On that measure SQLite writes about 3-5× the journal's bytes, where the logical bytes differ about 30×. On xfs on leil-test-1, SQLite's device writes came to 53.8 KiB per job, below its estimate (MEASURED ON LEIL-TEST-1); ext4 and the other columns are unmeasured.
- 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 ( Hfn 48, the process ID response. The host sends1D 28 48 06 00 30 30 d1 d2 d3 d4after the data. For print data, the printer answers37 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. The TM-m50II's command list includes it too (docs/plans/printers.md, Investigation findings), still unverified over port 9100.
- Limits:
- If the host misses responses, the printer sends only the latest ID.
- Pending IDs are dropped when the buffers are cleared (
DLE DC4fn 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) andGS ( Hfn 49 report the printer's state.GS r 1answers 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: the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the
ESC @that starts each job turns it off, as Epson's guides confirm (docs/plans/printers.md, Investigation findings). Until the first job after a power-on, the printer may send unrequested 4-byte status frames, whichprinter.Client.Status, reading one byte per request, could take as "status unsupported". Whether the frames reach a port 9100 client is unverified.
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. The schema under RECORDS appended 46.1 KiB (11.46 frames) on leil-test-1.
- 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 ( Hfn 48). It is unverified on this printer. - Stage 1a measured on Linux what no track could: device writes and flushes, and whether
SystemCallFilter=@system-serviceallows what the store calls. Not measured by anything: an SD card, ARM hardware, ext4, 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).
- ESC/POS reference Ver. 10.01,
- Versions and go.mod files: proxy.golang.org.
Overview
WHAT SHIPS WHEN
- Stages 1a-1d: measurements on leil-rig, the
[state] dirkey, the state machine without a database, then the SQLite store. Every job is stored when it is accepted. The worker renders, connects, commits a syncedsendingmark, then writes. After a restart, queued jobs print in order, and a job caught mid-send showsuncertainand is never resent. - The API:
GET /api/v1/jobslists the history, job status showsref, and/healthzcounts the jobs founduncertainat 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 reachedsending, and an ntfymessage_deletecancels the waiting jobs of its notification and drops its held digest rows. A delivery that has reachedsendinggoes on. - Stages 3a-3c, the image preview: the preview routes answer
Accept: image/pngwith a picture of the paper, drawn from the bytes the job renders to. They need nothing from phases 1 and 2. - Previews of stored jobs:
GET /api/v1/jobs/{id}/previewas text, JSON or PNG. - 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.dirthe queue stays in memory and behaves as today, waiting jobs failing at shutdown included. - Existing statuses keep their meaning;
uncertain,cancelled(phase 2b) and thesent_atfield are new. - Job status gains the
deliveriesarray with docs/plans/printers.md stage 1b, for every job, whatever the number of printers (its decision 8). - 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] dirandqueue.content_bytesas unknown keys and ignoresjobs.db. The CHANGELOG and docs/configuration.md say so.
INVARIANTS
- Nothing reaches the printer unless the whole receipt rendered.
- No byte of the job goes to the printer before its delivery's
sendingmark is committed to the store, and synced when the store is durable. - A delivery that a client could have read as failed,
uncertainor 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 asendingmark, which docs/plans/printers.md decision 22 settles. - A status a client reads is never ahead of the store: memory changes only after the store's commit returns.
- Print contents never reach logs or Sentry, and the store's errors never quote them.
- printqueue never imports a database, so server and tools/genopenapi never compile one.
- A cancelled delivery never reaches the printer: its cancel and its
sendingmark 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
donerolled back tosendingreadsuncertain, and a lost insert loses a job never sent. Neither prints twice.failedis synced, because afailedrolled back toqueuedwould 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.cancelledis synced for the same reason: rolled back toqueued, 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
sendingcommit fails, the connection closes with no byte written. - A crash between the
sendingcommit and the write leaves anuncertainjob 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
sendingmark with its number;sent_atkeeps the first. - Shutdown with a durable store:
- Waiting jobs stay
queued. - A job that has not reached
sendingis abandoned and staysqueued: 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
sendingcommit and the end of its write finishes. So the stop takes at mostprinter.write_timeout(30 s by default) and two commits. - A job waiting between retries after an attempt reached
sendingfails, as today, and itssent_atshows that bytes went out.
- Waiting jobs stay
- 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_timeoutplus about 10 s (decision 15). A SIGKILL mid-write leaves the jobuncertain.
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.dbandjobs.db-walaside together, start it again (systemctl reset-failed uberbringerfirst 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 ifsent_atis 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 turneduncertain(Loadsays which) with itsjob_id,printer,sourceandref, never its content, and from phase 2/healthzcounts their jobs. A delivery founduncertainat an earlier start is not logged again. A remote attempt whose outcome stays unknown turnsuncertainduring 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 <id>is appended at send time, after the final cut, with a fresh 4-byte ID for each attempt from a counter in the store. Stored and previewed bytes never hold it, which matters becauseescpos.Interpretrefuses anyGS (other thanGS ( k. - The connection stays open while the daemon reads frames, classified by the first byte under the mask 0x93, and polls
DLE EOTevery 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_atto the status. A time-out givesuncertain, neverfailed, and never a resend. - After a restart, a job in
sendingor awaiting its ID is stilluncertain. 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
/healthztime out (3 s) during long prints. While a job holds the connection,/healthzreports 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:
// 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, "<topic>/<sequence ID>"; 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,
Addand 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, soStatusandPendingnever wait for a commit. From phase 2b, a delivery lock orders every change of a delivery's state after its insert: thesendingmark inbeforeWrite, the worker'sFinishand 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 inbeforeWrite, 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
jobschannel, whose capacity isSize, so it can hold a restored backlog.Pendingreads its length and the capacity check runs against it. If more jobs were stored thanqueue.sizenow allows (after the key was lowered), all of them load, andSubmitanswersqueue_fulluntil the backlog falls below the size. Submittakes no context, here or in the server'sJobsandntfySubmitter.Addruns on a background context: an insert that has begun finishes or fails, whatever the client does meanwhile.Metagains a flag, set by ntfy subscriptions only, that marks itsRefas unique at its source, andSequence, a card's ntfy notification (RECORDS), which phase 2b's cancel matches. A uniqueSubmitcommits with a sync (decision 5). If the queue already holds that source and reference (decision 10),Submitstores 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.ClientcallsbeforeWriteafter the dial, before it computes the write deadline and writes, so a slow sync does not use upwrite_timeout. The queue passes a function that callsStore.Sendingfor the delivery and sets itssent_aton 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 whenIdleis called, so an automatic checkpoint seldom lands on asendingcommit.- Restore before start: serve.go opens the store, which takes its lock, and the queue loads it before
group.Gostarts 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 thentfy-<name>.jsonfiles. Loadreturns no content, so a backlog of up toqueue.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 strictDecodeJob(after a downgrade or a field change) then fails with an error, logged byjob_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 reachedsendingstay queued; with the memory store, shutdown is as today.- With SQLite's single connection, a
Submitwaits for its insert and may wait behind the worker's synced commit or a checkpoint. On leil-test-1's virtual disk, a synced commit took at most about 10 ms, and an insert that ran a checkpoint 10-24 ms. On an SD card that wait is unmeasured. - The
Stateconstants stay in queue.go, the one file printqueue's schema test parses;StoredStateis a separate type in store.go.
RECORDS (SQLite, decision 1)
-- 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, <topic>/<sequence ID>; 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, indeliveries. Until the printers plan lands, every job has exactly one delivery, for the printerdefault. A multicast or broadcast job later gets one row per printer; an anycast job has one, whoseprinterthesendingmark sets to the printer used (DELIVERIES AND SEVERAL PRINTERS). - The
jobsrow 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.
deliveriesis a b-tree of its own, so an insert can change one page more than with one table. On leil-test-1 this schema appended 11.46 WAL frames per text job, against 14.35 in the SQLite track's runs with one table (Investigation findings). - Statuses are looked up in memory, so neither table needs an index on
id,stateorjob_seq, and updates go by a delivery'sseq. Each index left out is a b-tree fewer per insert. Pruning deletes a job's row and its deliveries' rows by theirseqs, which the queue passes toFinish. Loadreadsdeliveriesinseqorder and attaches each row to its job byjob_seqin memory.sequencelets an ntfymessage_deletefind a waiting job after a restart too (phase 2b). It holds the topic and the sequence ID as<topic>/<sequence ID>, since ntfy's sequence IDs are per topic (DELETE /<topic>/<sequence_id>) 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.
Loadreads each content's length, not the content. refsis pruned to the newest 512 per source byid, apart fromjobs, 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 aseq, so that is harmless;refsholds job IDs, and a later counter, such as the acknowledgement's, keeps its own. - A delivery's
doneand the pruning of the oldest jobs share one commit. - One connection: the store takes a
*sql.Connat Open and holds it for its life, with the pool at one open and one idle connection and no lifetime limits, sincesynchronous,locking_modeand 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.dirmay hold spaces,#or?. - Pragmas at open:
journal_mode=WAL,locking_mode=EXCLUSIVE(decision 3),synchronous=NORMAL,temp_store=MEMORY,journal_size_limitof 4 MiB,secure_delete=FAST, andauto_vacuum=NONEbefore the tables exist.wal_autocheckpointstays 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,cancelledcommit 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 auser_versionnewer than the binary knows, naming both; run each schema step in one synced transaction that also setsuser_version; write once, so a second instance fails at once. IdlerunsPRAGMA wal_checkpoint(PASSIVE).sqlite.Fdatasync(true)on Linux. The unit's syscall filter allowsfdatasync, and on leil-test-1 it cut a synced commit's median from 5.0 to 2.9 ms with the same device writes and flushes (stage 1a).- 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.historyfinished ones, as today. A job is finished once every delivery is; acancelleddelivery counts as finished (phase 2b). - Content: every unfinished job's, every
uncertainjob's while its status is kept, and finished jobs' newest first up toqueue.content_bytes(decision 9). Dropping content keeps the status; a preview of that job answers410. - 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 aCancel. A job goes with all its deliveries.
API
- Stage 1c:
statusgainsuncertain, in theStateenum'sjsonschematag, printqueue's schema test, docs/api.md, swagger.json and the CHANGELOG under Breaking. Status gainssent_at(name assumed), set once an attempt was about to write to the printer. A store failure inSubmitis an unexpected error:500internal_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/jobswithstatus,source,beforeandlimitin the query. It answers{"jobs": [...], "next": "job_..."}, newest first by sequence number. Bad values answerinvalid_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 onParamand a generator change. Job status gainsref./healthz'squeuegainsuncertain; the status code still depends on the printer alone. - Phase 2b (decision 17):
DELETE /api/v1/jobs/{id}, for full tokens, answers200with the status, or409with the new codejob_startedwhen no delivery is left to cancel and none is cancelled.statusgainscancelled, a new enum value, so the CHANGELOG lists it under Breaking, as it doesuncertain.DELETE /api/v1/printstill answers405, api.md's example formethod_not_allowed. - Phase 3c (decision 19):
Accept: image/pngonPOST /api/v1/previewandPOST /api/v1/preview/{module}. Text stays the answer to*/*. A picture over the height cap answers422preview_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 byAccept, as the POST preview answers, with the new code410job_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 intoserver/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 addsqueue.content_bytes, default 67108864 (64 MiB), 0 to 1 GiB, anint64so 32-bit ARM can hold it. Each gets its default, validation,configs/config.example.tomlentry and docs/configuration.md.ntfy.state_dirgoes, and its[Unreleased]CHANGELOG entry is edited rather than listed as Breaking. - Files:
<dir>/jobs.dband<dir>/jobs.db-wal(no-shmin exclusive mode), and<dir>/ntfy-<name>.json. - The unit already has
StateDirectory=uberbringerwith mode 0700. AddUMask=0077(decision 15), and reword the comment that namesntfy.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/uberbringerreplacesUBERBRINGER_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 by10001:10001, not a Docker Desktop bind mount, since WAL needs a local filesystem, and for a stop timeout aboveprinter.write_timeoutplus 10 s (--stop-timeout 40at the defaults). - Windows is for development only. modernc builds there and its WAL works (spike); it syncs with FlushFileBuffers.
state.dirhas no default, sogo runand 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'scheckand 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
uncertainbyjob_id,printer,sourceandref. - 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
Storeinterface 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 printerdefault. -
docs/plans/printers.md decision 18 stores the route:
route_by,route_ruleandroute_modeonjobs, andcandidatesandsent_toondeliveries, in stage 1d's first schema or in a step touser_version2. So a restored anycast delivery keeps its list, and a failover after asendingmark keeps the record that the first printer got bytes, which TELLING WHICH RECEIPTS PRINTED relies on. -
A job's API
statusderives 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. queuedwhile every one waits, none taken and none finished;printingwhile any is unfinished, once one has been taken or has finished;- once every one has finished:
uncertainif any is, since it means a receipt may have printed; otherwisefailedif any is; otherwisedone.
So
failedanduncertainstay final, as today: a failed oruncertaindelivery beside one that still waits or prints leaves the jobprinting, and one cancelled delivery beside done ones readsdone. With one delivery, the job's status is the delivery's. - Cancelled deliveries (phase 2b) are passed over unless every delivery is cancelled; then the job is
-
From docs/plans/printers.md stage 1b, every status gains a
deliveriesarray, one entry per delivery with itsprinter,status,attempts,started_at,sent_at,finished_atanderror, and the job's own fields sum or pick from them (its decision 8). Until then the status looks as this plan describes, its fields those of the one delivery. -
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
sendingmark is written, just as a dial failure writes nothing today. After asendingmark, the existing retry rule on that printer runs, then failover to the next (docs/plans/printers.md decision 22). 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 stored list (printers decision 18). -
One store per instance. Each delivery names its printer, so one store serves every printer: one queue with a lane and a worker per printer, each loading its own unfinished deliveries (docs/plans/printers.md decision 4).
-
Job IDs stay global, so
GET /api/v1/jobs/{id}needs no printer. -
The stored job is printer-neutral (design.md, "Blocks are laid out when the job renders") and rendered bytes are not stored, so a queued delivery can move to another printer. A queued delivery whose printer was removed from the config fails at restore (docs/plans/printers.md decision 5).
-
Acknowledgement IDs are counted per printer.
-
cancelledcomes with phase 2b, as a delivery's state; thedeliveries.statecolumn 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-<name>.jsonfiles. Until one instance drives several printers, each instance gets its own directory.
THE PREVIEW IMAGE (phase 3)
escpos.Interpretkeeps 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.Profilegains the geometry drawing needs, so that layout keeps coming from the profile: the glyph heights of Fonts A and B; the vertical motion unit, whichESC 3and the feed ofGS Vcount 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 whereprinter.cut_feedmoved 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-80mmandgeneric-58mmare 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 implementsimage.PalettedImagewith one bit per dot, whichimage/pngwrites as 1-bit rows; animage.Palettedtakes 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.PreviewImagerenders the job with its images loaded as decision 19 says, reads the bytes back withInterpretand draws them. Imports: receipt → paper → escpos.
Phases
Stage 1a: Measurements on leil-rig
Done on 2026-12-01. The numbers are under Investigation findings, MEASURED ON LEIL-TEST-1.
Goal. Measure on Linux what the workstation cannot: device writes and flushes per job, the time of a synced commit and of a checkpoint, and whether the unit's sandbox allows the calls the store makes. The owner has no ARM boards, so nothing runs on ARM hardware (decision 2).
Work. Nothing in the repository changes but this plan. The session writes a probe under the scratch directory and cross-compiles it. On the owner's word, it runs the probe itself on leil-test-1, leil-rig's test node, under the rig's lease (leil-rig's CLAUDE.md, The lease), 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/sqlitewith its pinned libc, one connection, and the pragmas and schema under RECORDS (jobs,deliveries,contentandrefs), 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-fdatasyncfor modernc'sFdatasync(true). - Setup, not measured:
-historyfinished 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
sendingmark at FULL, thendoneon 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 timedPRAGMA wal_checkpoint(PASSIVE). - Output, as text:
- per job, the device's sectors written and flush requests, from
/sys/dev/block/<major>:<minor>/statfor 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/iomisses; /proc/self/iowrite_bytesper 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;
- the WAL frames per job, read from the frame headers after each commit.
- per job, the device's sectors written and flush requests, from
-devicenames the block device where the probe cannot find it, as on btrfs; behind LVM or dm-crypt it follows the device down to the disk, where the kernel counts flushes.- Built with
CGO_ENABLED=0for linux/amd64.
On leil-test-1, otherwise idle, since the device counters include every process's writes:
- Install the binary as
/usr/local/bin/jobprobe:DynamicUsercannot reach a home directory, andPrivateTmphides/tmp. - 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 /usr/local/bin/jobprobe -dir /var/lib/jobprobe. A call the filter refuses fails the run with EPERM, so this testsfdatasync, the file locks,pwriteandftruncatefor real. - As a cross-check,
systemd-analyze syscall-filterlistsfsync,fdatasync,fcntl,pwrite64andftruncatein the groups@system-servicetakes in (@sync,@file-system,@basic-io). lsblkandsystemd-detect-virtrecord the disk.- Remove the binary and
/var/lib/private/jobprobe, and release the lease.
Tests. A 20-job run on the workstation (Windows, without device counters) shows that the probe works. Nothing heavier runs there.
Done when.
- The probe has run on leil-test-1, and its numbers are in Investigation findings.
- If a call fails with EPERM, or the numbers differ much from the findings, the owner has looked at decision 1 again.
Stage 1b: [state] dir
Done on 2026-12-01.
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_dirgoes.- 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 namestate.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_DIRin place ofUBERBRINGER_NTFY_STATE_DIR. - packaging/uberbringer.service: the comment names
state.dir.
Docs
- configs/config.example.toml:
[state] diradded;[ntfy] state_dirremoved. - The install note on
/var/lib/uberbringerin docs/install.md, the ntfy paragraph of docs/docker.md, thentfy.state_direntry in docs/configuration.md (it becomesstate.dir), and in docs/ntfy.md the example config and the State paragraph's<state_dir>/ntfy-<name>.json. - design.md: the ntfy State paragraph, which names
ntfy.state_dir. - CHANGELOG: the
[Unreleased]entry that addsntfy.state_dir, edited.
Tests.
- Config table tests:
state.diraccepted; a subscription withoutstate.dirrefused, the error namingstate.dir;ntfy.state_dirrefused 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_dirorUBERBRINGER_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 secondQueueon the same store stands for a restart. - queue.go:
- The submit and status locks and the waiting list (Architecture, THE STORE INTERFACE).
Submitchecks capacity, commitsAdd, then makes the job visible to the worker, so a failedAddleaves nothing queued. - Each job gets one delivery, for the printer
default. The worker works on that delivery:SendingandFinishname it by itsseq. A job's status derives from its deliveries by decision 12's rule, written for any number of them. Restore, called beforeRun: records back into memory, queued jobs onto the waiting list in sequence order, and one WARN line per delivery thatLoadturneduncertain.- The worker reads a job's content from the store when it takes it; one that no longer decodes fails.
beforeWritecallsSendingand setssent_at.failedand unique inserts commit with a sync. Every state change commits, then changes memory. A store error stops the worker, andRunreturns 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 byContentBytes, uncertain content kept; the store is told what to drop in the sameFinish. - The duplicate check for unique jobs, against the kept references.
StateUncertainandStatus.SentAt, with the enum tag.Idlewhen the waiting list empties.
- The submit and status locks and the waiting list (Architecture, THE STORE INTERFACE).
SendergainsbeforeWrite;Metagains the unique flag andSequence, the ntfy notification a card came from, whichAddstores and phase 2b's cancel matches.
internal/pkg/printer
Send(ctx, data, beforeWrite)calls it afterconnect, before the write deadline andWrite. 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 callsDigest, and drops it onceDigestsucceeds. 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.Digestcarries the reference. - message.go:
Notification()(name assumed) returns<topic>/<sequence>, the key of the notification a message or a delete belongs to, since sequence IDs are per topic; it is empty whenSequence()is.
internal/pkg/config
queue.content_bytes: default 64 MiB, 0 to 1 GiB, anint64.
internal/app/uberbringer
- serve.go: the memory store;
queue.content_bytesinto the options;Restorebeforegroup.Go. - ntfy.go: cards and digests are submitted as unique, with the message ID or the digest's reference. A card's
Meta.Sequenceism.Notification(); a digest's is empty.
internal/app/uberbringer/server
- Nothing beyond the regenerated enum and field: a store error from
Submitalready takes the unexpected-error path, andErrClosedafter the stop already answersshutting_down.
Docs
- docs/api.md: job status (
uncertain,sent_at, and whatfailedwithsent_atmeans). - 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
uncertainstatus; under Added,sent_atandqueue.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
Sizeloads whole;SubmitanswersErrQueueFulluntil it falls belowSize. - A fake Sender that returns after
beforeWritewithout writing, standing for a crash between the mark and the write: after a restart the job isuncertain, logged at WARN with its IDs only, and never sent again; a second restart logs no WARN for it. Sending,failedand unique inserts are synced; every other commit is not.- A dial failure writes no
Sendingrecord and sets nosent_at. A job whose first attempt reachedsendingand whose second failed to dial keepssent_at. - Store failures: when
Addfails,Submitreturns the error, nothing is queued and the queue stops. WhenSendingfails, the Sender writes nothing, the queue stops, the status never readsfailed, and after a restart the job is queued and prints once. WhenFinishfails, memory keeps its last state and the queue stops. - With the wrapper blocking a commit,
StatusandPendingstill 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
sendingfails withsent_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
uncertaincontent is never dropped; dropped content givesErrContentGone. - 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:
uncertainin the enum.
internal/pkg/printer
- Against a fake listener:
beforeWriteruns 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
Digestis 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 withoutsequence_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/sqliteat its latest stable release, with the exactmodernc.org/libcits go.mod pins, and the indirect modules decision 13 names. Run govulncheck.
tools
- A small program,
tools/libcpin(name assumed), that fails whengo list -m modernc.org/libcdiffers from the libc thatmodernc.org/sqliterequires ingo mod graph. It runs asgo 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 thejobs,deliveries,contentandrefstables.- The
Storemethods on the held connection.Addinserts the job, its deliveries and its content in one transaction.SendingandFinishupdate a delivery's row by itsseqand never touch thejobsrow.Finishand its pruning, of jobs, deliveries and contents byseq, share one transaction.Loadattaches each delivery to its job byjob_seq.Idlecheckpoints. - Errors carry the operation and the job's or delivery's sequence number only.
internal/app/uberbringer
- serve.go: when
state.diris set, check the directory once (moved from ntfy.go), whether or not there are subscriptions, then open the jobstore; otherwise the memory store. Open andRestorebefore the subscribers are made and beforegroup.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=0builds of linux/arm (GOARM=6) and linux/arm64, andgo 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.dirnow 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), themake checksteps, and "CI and releases", which says test.yml builds no binaries.
- docs/configuration.md:
- docs/api.md: job status (what survives a restart) and the
job_not_foundrow. - CHANGELOG: under Added, jobs survive a restart, and the armv6, armv7 and arm64 builds ship the store untested on hardware (decision 2); 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_atincluded, 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,failedand unique inserts commit at FULL, every other commit at NORMAL. The hook also readstotal_changes(), so a test sees thatSending, and aFinishthat prunes nothing, change one row, the delivery's. - A second
Openof 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).
Finishdrops jobs, their deliveries and content in the same transaction.Loadturns every delivery insendingintouncertainin one commit, leaves the other deliveries of the same job alone, returns the deliveries it turned, and returns content lengths without content. A secondLoadturns and returns none.refskeeps the newest 512 per source and outlives the pruning of their statuses.- A damaged page in the middle of the file fails
Openwith an error naming the file, and so does a damaged header. Auser_versionnewer 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):
runtwice on onet.TempDir()against a fake printer listener. Before the secondrun, the test adds a job whose delivery is insendingthrough jobstore, standing for a crash mid-send. Queued jobs print after the restart, ahead of new ones; the seeded job readsuncertain, and the listener never receives it. - With
state.dirset 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 that the ARM builds ship the store untested on hardware (decision 2).
- Paper, with the owner's OK, one short receipt at a time, waiting for his report after each:
- A receipt prints through the store and reads
done, and still readsdoneafter a restart. - 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. - A receipt is killed while its write waits (
systemctl kill -s KILL uberbringeron a host,taskkill /Fon 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 readsuncertainand is not sent again; once the cover is closed, what the printer had buffered prints, and only once.
- A receipt prints through the store and reads
- 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; abeforeno longer kept is an error the server maps toinvalid_query. The count of jobs with a delivery thatLoadturneduncertainat the latest start.Status.Ref.
internal/app/uberbringer/server
- The route
GET /api/v1/jobsin the table, for full tokens; its handler and response type;JobsgainsList, andfakeJobswith 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_queryrow, 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, abeforeno longer kept, the bounds oflimit, and bad values givinginvalid_query. - A token limited to modules gets
403token_scope. - schema_test: the new enums held to validation.
/healthzcounts theuncertainjobs 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.
curlon/api/v1/jobslists 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, withcancelledin theStateenum'sjsonschematag: a new value clients may meet, so the CHANGELOG lists it under Breaking, as it doesuncertain.- Only a delivery that has not reached
sendingcan 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 reachedsending, or has finished, goes on. Cancel(id)(name assumed) cancels the job's deliveries that have not reachedsendingand 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, andErrStarted(name assumed) if none is.CancelSequence(source, sequence)(name assumed) cancels those deliveries of each job from that source whoseMeta.Sequence(stage 1c), its notification, equalssequence, and returns the jobs' IDs. It matches in memory, so a job restored after a restart is found too. An emptysequencematches 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
sendingmark can never both pass their checks (invariant 7):beforeWrite: for a cancelled delivery it returnserrCancelled(name assumed), and the printer closes the connection with nothing written; otherwise it commitsSendingand changes memory.- The worker's
Finishtakes the lock too, which also orders the pruning it carries. For a delivery that has not reachedsending(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
sendingor finished. It commits the otherscancelledin one synced commit (Architecture, JOB STATES), which drops what the cancel pushes out of retention asFinishdoes; 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 noOnFailure, since the cancel's commit is its final state:errCancelledfromSendis never retried, and an error after its context ended ("rendering: context canceled", "giving up after n attempts") finds the deliverycancelledunder the lock. - A store error stops the queue (decision 11).
- If docs/plans/printers.md stage 3 has shipped, a delivery with any
sendingmark is not cancellable, even while it waits on the next printer of an anycast list, and a move takes the delivery lock (its decision 26). - 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:
StoredStategainscancelled, andStoregainsCancel(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'sstateandfinished_atand drops the given jobs, deliveries and contents. Thesequencecolumn is in the schema and written from stage 1d (RECORDS), so there is no schema step.
internal/pkg/ntfy
- subscriber.go:
deliverhandles amessage_deletebefore 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 aMessageerror is. It then drops the held rows of the event's notification and updates the held count inStatus.dealtthen 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_clearstays skipped (decision 18).messagelets amessage_deletepast themax_backlogcheck (decision 18).- The query no longer holds
priority=, on either transport, since both build it with one function (docs/plans/ntfy.md decision 8);delivergoes on leaving out messages belowMinPriority, andLastMessageAtcounts only those at or above it.MinPriority's doc comment says the subscriber filters (decision 18). printedis keyed byNotification()too, so an update in one topic is not taken for one in another.
- The
Handlerinterface gainsDelete; the fake handler in fake_test.go implements it. - ratelimit.go:
DigestRowgainsSequence, saved with the held set, andheldgainsdrop(topic, sequence), which removes the rows of that topic and sequence and lowersCountby as many; an empty sequence drops nothing. A held set left empty is reset, so no digest prints. Messages pastMaxDigestRowsare 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 untilDigestsucceeds (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:
ntfySubmittergainsCancelSequence. The newntfyPrinter.DeletecallsCancelSequence("ntfy:"+name, m.Notification())and logs each cancelled job at INFO withsubscription,refandjob_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, answering200with the status,409job_startedor404job_not_found;JobsgainsCancel, andfakeJobswith it; its case in TestRoutesConform. - errors.go:
409job_started, for a job whose every delivery has reachedsendingor finished, none of them cancelled. - Unchanged: the
ntfymodule route (POST /api/v1/print/ntfy) still answers204tomessage_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_startedrow in the error table, and the Job status section (cancelled). - docs/ntfy.md: how a subscription behaves: a
message_deletecancels the waiting receipts of its notification and drops its held digest rows, also undermin_priorityand pastmax_backlog; amessage_cleardoes neither;min_priorityis 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). - CHANGELOG: under Breaking, the
cancelledstatus; under Added,DELETE /api/v1/jobs/{id}and cancelling by ntfy deletes; under Changed, that a subscription withmin_priorityreads 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 readscancelledafter 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, notfailed, also once its worker has stopped. No retry follows,OnFailureis not called and no "job failed" line is logged. - The cancel against the
sendingmark, ordered by the wrapper blocking one commit and then the other, never by timing: when the cancel commits first,beforeWritefails and the fake Sender writes nothing; when the mark commits first,CancelreturnsErrStartedand the job prints. - The cancel against the worker's own
Finishof a delivery that has not reachedsending(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 oruncertaingivesErrStarted. - A record with two deliveries, put into the memory store by hand, one in
sendingand one queued: the cancel cancels the queued one, the other goes on, and the status follows decision 12. A second cancel returns the status, notErrStarted. - The
cancelledcommit is synced. When it fails, memory keepsqueued, the queue stops, and after a restart the job prints once. - A cancel that pushes the oldest finished job past
Historydrops it in the same commit. CancelSequencecancels 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 whoserefhappens 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
CancelSequenceand still readscancelledafter another restart. - schema_test:
cancelledin the enum.
internal/pkg/jobstore
- Through the test hook:
Cancelcommits 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'ssequence, survive a close and a reopen.
internal/pkg/ntfy, on the virtual clock
- A
message_deletecallsDeletewith the event. ADeleteerror is retried as aMessageerror 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
MinPriority4, the connection asks for nopriority=, a delete still callsDelete, and a message of priority 3 is still left out and not counted inLastMessageAt. - A delete older than
max_backlogin a replay still callsDelete. - An update in one topic of a sequence printed in another is not marked as an update.
- A
message_clearcalls nothing and drops nothing, and is recorded as dealt with as today.
internal/app/uberbringer
Deletecancels throughCancelSequencewith 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}answers200withcancelled, and200again on a repeat;200while the job renders or dials;409job_startedfor a job in its write, between retries after reachingsending, done, failed oruncertain; andjob_not_foundfor an unknown ID. A token limited to modules gets403token_scope.DELETE /api/v1/printstill answers405.
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 = 10andprinter.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.- With the printer switched off, a receipt is sent and then cancelled through
DELETE /api/v1/jobs/{id}. The job readscancelled, notfailed, and with the printer on again, nothing prints. - 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.
- With the printer switched off, a receipt is sent and then cancelled through
- 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'sWandH. - 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 testruns its seed corpus only; no-fuzzruns 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:base64images from their data,urlimages fetched through safehttp under one 30-s deadline for the whole preview, a crossed box for each image that failed or is still loading. It draws with the profile the text preview uses: the named printer's, or the default printer's.
internal/app/uberbringer/server
PreviewergainsPreviewImage. handlers_preview.go answersimage/pngwhen asked; text stays the default. The cap's error answers422preview_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 <file>.
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/pnggives200image/pngwith a PNG signature;*/*still gives text; a module preview as PNG; a job over the cap gives422preview_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,ErrNotFoundorErrContentGone.
internal/app/uberbringer/server
- The route
GET /api/v1/jobs/{id}/previewin the table, for full tokens. It renders with the profile of its first delivery's printer. It decodes the stored job strictly and answers through the same negotiation as the POST preview.JobsgainsContent, andfakeJobswith it. - errors.go:
410job_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
uncertainjob, with the memory store and the jobstore. - Pruned content gives
410job_content_expired; an unknown ID givesjob_not_found; a token limited to modules gets403. - 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, the phase 5 list moves to design.md's Deferred section, and this plan is deleted, its findings with it.
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:
- Does the TM-T88IV, through its board, answer
37 22 ID 00on port 9100 for a receipt ending inGS ( H 48 "0001"after the cut? Check that it printed and cut once, and how long after the cut the answer came. - Does the answer come after the knife? A long feed before the cut shows it.
- Does an answer sent after the host closed the connection reach the next one?
- Which board is fitted, UB-E02 or UB-E03? The board's status sheet says.
- 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
Writereturns.Statusreads through the frame reader and skips frames it did not ask for. /healthzwhile a job holds the connection.- Config:
printer.confirm(auto,process_idoroff) andprinter.confirm_timeout, in each printer's table (docs/plans/printers.md decision 3). Status gainsconfirmed_at. The store keeps the ID counter.
- Does the TM-T88IV, through its board, answer
-
The partial-write choice (decision 23), once the confirmed send reports the bytes written.
-
ntfy state in the store (decision 22).
-
An
Idempotency-Keyheader onPOST /api/v1/print. -
A reprint route for
uncertainjobs,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.