Review checklist
What to check in a lith app before a release, and on every change to the database, a stream or a handler. Each check names the mistake, what it does in production, and an rg command that finds it.
The lith projects made each of these mistakes, and most were found by reading code with a search. Run the commands from the project's root; each match is a place to look at. The checks match the review checklist in lith's skill, which coding agents use; the skill and this page say how the two stay together.
Writes
A write outside the writer
Every Exec must sit inside a command (an Apply(tx *writer.Tx) or a writer.Func), an Exclusive function, a migration, or a test. A store method that writes on its own is a second writer: it competes with the writer for SQLite's one write lock, and under load one of them fails with SQLITE_BUSY.
rg -n '\.(Exec|ExecContext)\(' --type go -g '!*_test.go'
A second connection that writes
A second connection to the database file that writes, for a factory reset or an import, takes the write lock beside the writer. A transaction on it that runs past the busy timeout fails the writer's batches with SQLITE_BUSY. Pragma toggles, ATTACH, DETACH and VACUUM belong in w.Exclusive, on the writer's own connection (Migrations, jobs and imports). Outside lith itself, look at every match:
rg -n 'sql\.Open\(' --type go
A deferred transaction that reads, then writes
A transaction begun without IMMEDIATE takes a read snapshot first and the write lock later. When another connection, Litestream's say, commits in between, the upgrade fails with SQLITE_BUSY_SNAPSHOT, and busy_timeout does not retry it.
rg -n 'BeginTx\([^)]*nil\)|\.Begin\(\)' --type go
On lith's write connection every transaction is IMMEDIATE; a match elsewhere needs a look.
One connection instead of a writer
A pool pinned to one connection serialises the writes but does not batch them: every write pays its own commit, and reads queue behind the writes. Outside lith:
rg -n 'SetMaxOpenConns\(1\)' --type go
A change made of several autocommits
A change that runs as several statements outside one transaction, an insert, then an audit row, then a publish, is not atomic: a crash between two leaves half of it. One command, one Apply, one savepoint.
SQL built at runtime in a command
A command that builds its SQL at runtime, such as an IN list with a mark per value, takes a place in the writer's statement cache for every text it makes, and pushes out the statements that repeat. Run it through tx.ExecUncached, tx.QueryUncached or tx.QueryRowUncached, or with a ctx from sqlite.Uncached, or pass the list as one JSON argument (Commands).
rg -n 'tx\.(Exec|Query|QueryRow)\((fmt\.Sprintf|"[^"]*" *\+|`[^`]*` *\+)' --type go
Network calls inside a command
Every command queued behind a command waits while it runs, so a command that waits for a mail server waits with the whole queue. Mail, HTTP calls and anything slow go in tx.AfterCommit or a job (Commands). Look at matches inside commands:
rg -n 'http\.(Get|Post)|smtp\.|\.Send\(' --type go
A writer called from a command
A command that calls Do on its own writer never returns: the writer is busy running it. One that calls Do or Send on another database's writer gets no atomicity, since the other database commits apart from the command, and with Do the batch waits for the other writer's, so two databases that do this to each other deadlock. A command writes its own database; a follow-up in another goes through a row the other side picks up, an outbox and a relay, not a call inside the command (Commands). Each match names the line where a command body starts (an Apply, a writer.Func, a function that takes a *writer.Tx) and the call:
rg -n -U -o -r '$1' '\*writer\.Tx[,)][^{\n]*\{[^\n]*?(?:\n(?:\t*[^}\t\n][^\n]*|\t+\}[^)\n][^\n]*|\t+\}|\t*))*?\n?[^\n]*?([\w.]+\.(?:Do|DoValue|Send))\(' --type go -g '!*_test.go'
The pattern is a heuristic: it ends a body at a line that starts with } or closes a func literal with }), so it misses a call after a nested literal closes, and it reads examples in comments.
An op id that is not scoped to who sent it
writer.Once and writer.OnceResult keep their keys in one table per database. A key that comes from the payload alone lets a client that learns another user's op id turn that user's command into a no-op, or receive its recorded result. Every key starts with who sent it, as the template's sid + ":" + op does (Commands). The first command lists every call to check, the second the plainest mistake:
rg -n 'writer\.Once(Result)?\(' --type go
rg -n 'Once(Result)?\([a-z]+\.(Op|ID|Key)\b' --type go
A publish after Do returns
An app that publishes a command's change to its own bus once w.Do returns publishes in the order the handlers wake up, not the order the commands committed, and publishes for a command that failed when the caller ignores Do's error or publishes beside it. Publish inside the command with tx.Publish, which keeps commit order and drops the value of a failed command, or use tx.AfterCommit for a side effect of that command (Commands). A publish tied to no commit, such as a signal for one tab, a tick or a notice after an Exclusive, is fine on the app's own bus. Look at the lines after each Do:
rg -n -A4 '\.Do\(' --type go -g '!*_test.go' | rg -i 'publish|broadcast|emit\('
The pattern is a heuristic: it also matches the path of a file and a correct tx.Publish in a writer.Func passed to Do, and misses a publish more than four lines after Do(.
Reads
- A render that opens its own transactions. A render reads through the transaction it is given:
sqlite.QuerierFrom(ctx), or a store whosedb.View(ctx, fn)joins the render's. One that opens transactions of its own, one for the list and one per open dialog, mixes snapshots and shows two moments at once. db.Woutside the writer and the migrations.db.Ropens the file read-only (mode=ro) and isquery_onlybesides, so a write through it fails loudly, even one whose text starts withPRAGMA query_only = 0; one throughdb.Wcompetes with the writer. A statement ondb.Rcan stillATTACHanother file and, after that pragma, write to it: no SQL text comes from outside.
SQL built at runtime in a read
A read whose SQL is built at runtime takes a place in a read connection's statement cache, or a render worker's, for every text it makes, and pushes out the statements that repeat. Run it with a ctx from sqlite.Uncached (Reads).
rg -n 'Query(Row)?Context\(ctx, (fmt\.Sprintf|"[^"]*" *\+|`[^`]*` *\+)' --type go
A view swapped on navigation
A navigation that unwatches one view and watches another, whose key carries the route, can be one view keyed by the tab that declares its route's topics with live.Depends (Views).
rg -n 'Unwatch\(' --type go
Events
A render that replays a stream
A view that reads a stream's events with events.Load, or the log with events.Since from its start, grows with the history and reads all of it at every change. Render from a projection; a feed reads Since from a position near the end (Event sourcing).
rg -n 'events\.(Load|Since)\(' --type go -g '!*_test.go'
A write to the event tables
lith_events, lith_event_state, lith_projections and lith_event_kinds belong to lith/events. A statement of the app's own that writes them skips the version check, the state row and the projectors, and an UPDATE changes history that projections were built from: events.Compact is the one place that rewrites an event, as a snapshot of the stream's state.
rg -n '(INSERT INTO|UPDATE|DELETE FROM) lith_(events|event_state|event_kinds|projections)' --type go
A projector that writes a table it does not name
A rebuild runs a projector's handlers over every event into copies of the tables it names in Tables. A handler that also writes another table writes it again for every event, so a projector with tables writes only those (Event sourcing).
Requests
A GET that writes
A GET handler writes nothing: no session row, no event, no counter per hit. Crawlers multiply every write a GET makes. Sessions start as a cookie, and a row appears with the first command that needs one.
A message in a status's body
An action that answers 4xx or 5xx with text for the person, a validation message, "too many requests", "the server is restarting", or err.Error(), tells nobody: Datastar's datastar-fetch event carries the status alone, so the page shows nothing, or a generic message of its own in place of the server's reason. What the person caused is an outcome in the tab's row, answered 204; what no command decided is a notice with hub.Notify; both carry the op id that ends the pending state. A bare status stays for machines: a body that does not parse, an id no page holds (Commands). The first command lists every http.Error outside the tests: look at those in actions that carry text. The second finds pages that read an error status. One use is right: the op tracking ends a waiting op on a 4xx other than 409 and 429, which comes without a notice, in the page's own words (Pages and Datastar). Anything else, an op that ends on a 409, a 429 or a 5xx, whose notice or deciding reconnect is on its way, or a message worded from the status, is where the stream should have told the page:
rg -n 'http\.Error\(' --type go -g '!*_test.go'
rg -n "\['error'|argsRaw\??\.status" -g '*.go' -g '*.templ' -g '*.js'
A document's own error page (a 404 for a board that does not exist) is fine: the person reads that page itself.
A pending state that does not show, or only spins
Every action is pending from the click until its op id comes back, and the page shows it: an indicator on what the person acted on, not only aria-busy for screen readers. It appears about 200 ms after the click, through a transition-delay or animation-delay on the aria-busy style, so an op acked within a tick shows nothing. Work that may run longer than a few seconds, an import, an export, a bulk change or a call to another service, reports progress instead of a spinner: its command records the acceptance, which acks the op at once, the job records how far it got in rows, and a view renders them, how far and of how much, until the job's outcome arrives.
rg -n 'aria-busy' -g '*.css'
A dialog that reports
A dialog asks; it never reports. An alert(), a confirm() that only says what happened, or a <dialog> opened with showModal() to say "Saved" or "Something went wrong" blocks the page for news the person cannot act on: a refusal goes inline where they acted, a notice in a toast, what happened elsewhere in a toast (Pages: which feedback to give). The search lists every dialog and the app's own wrappers, a notify() or showAlert() helper (a Go method of that name matches too): look at each for one that reports rather than asks.
rg -n '\b(alert|confirm)\(|showModal\(|<dialog|\b(show|open)(Alert|Modal|Dialog)\w*\(|(^|[^.\w])notify\(' -g '*.go' -g '*.templ' -g '*.js'
A toast that repeats the re-render
A toast that says "Card added" while the card appears where the person dropped it says it twice. The re-render is the confirmation; a toast is for what happened where the person cannot see it. The pattern is a heuristic: look at each match for a change the page already shows.
rg -n -i 'toast.{0,60}(saved|added|updated|created|deleted|moved)' -g '*.go' -g '*.templ' -g '*.js'
Client addresses read from headers
Client addresses come from edge.ClientIP, which trusts the proxy headers only from the local proxy, and takes the last X-Forwarded-For address before X-Real-IP. A handler that reads the headers itself lets any client choose its address, to dodge a rate limit or spend someone else's.
rg -n 'r\.Header\.Get\("X-(Real-IP|Forwarded-For)"\)' --type go
The proxy must set X-Forwarded-For: Caddy's reverse_proxy does by default, nginx with $proxy_add_x_forwarded_for. Caddy passes on an X-Real-IP the client sent unless the site block sets it, so a check that believes X-Real-IP first can be dodged. The template's Caddy block replaces both (The request edge).
A proxy on another host or a container bridge is believed only through edge.BehindProxies, around the server's handler. Check its list (the template's -trusted-proxies): every address in it can name any client, so it holds the app's own proxies and nothing that other machines or containers share.
An app that no proxy stands in front of, on its own public port or with a "proxied" flag turned off, wraps its handler in edge.NoProxies. Otherwise ClientIP still believes loopback, and any local process names any client. It replaces a hand-written filter that deletes the headers.
A limit keyed by the session alone
edge.Sessions accepts any well-formed session id and mints one for a request without a cookie, so a client that sends no cookie is a new session with every request. A limit by session alone is one it steps around; each needs a limit by the client's address (edge.ClientKey(r)) before it on the same route, as the template's /pace and /ack have.
rg -n '\.Allow\((edge\.SessionID|sid\b|v\.Session)' --type go
Static files inside the sessions
edge.Sessions sets its cookie on any answer to a request without one. On a static file, which goes out public and immutable, a shared cache keeps the Set-Cookie with it and hands that session to everyone who asks for the file after. Mount /static/ on the outer mux, outside Sessions, as the template does.
rg -n 'Handle\("GET /static/"' --type go
A secret beside reflected input, compressed
A compressed page that holds a secret of the user (a token, an address) beside text the request put there leaks the secret byte by byte to an attacker who can make the browser send requests and watch their sizes (BREACH). lith's session lives in the cookie and its CSRF check in headers, so the template's pages hold nothing to leak. A page that does send it with Cache-Control: no-transform, which edge.Compress leaves uncompressed (The request edge).
Routes without the CSRF check, or without authentication
Every route that changes data passes edge.CSRF, and the routes it exempts are listed with a reason. Every such route also checks that the session may do what it asks: the CSRF check says where a request comes from, and only the session says who sent it.
A fixed window where a promise needs a sliding one
A limit promised to people, such as five messages an hour, is edge.NewSliding(5, time.Hour). A fixed window lets up to twice as many through around the edge between two windows, and a bucket (edge.NewLimiter) gives tokens back as time passes.
rg -n 'edge\.NewWindow\(' --type go
Streams
A stream outside lith/live
A stream written outside lith/live lacks the tick, the dropping of stale frames and the window settings. Datastar's Go SDK given WithBrotli without WithBrotliLGWin keeps a 4 MiB window: 9.9 MiB of heap per open tab, measured.
rg -n 'datastar\.NewSSE|WithBrotli\(' --type go
A stream without a cap or a deadline
Every stream counts against a cap, every write to the network has a deadline, and shutdown cancels the streams. A slot or a lock held across a network write lets a few stalled clients stop every stream.
A stream that counts under no client
MaxStreams is one cap for everyone: one address that opens 200 idle streams, which cost it nothing, gives every other page a 503, and since the streams' budget shares its memory per stream, the streams that came first keep the compressed tiers while later pages get every frame uncompressed. A public stream sets Client: edge.ClientKey(r) in its live.Spec, and the hub then caps each address at Options.MaxStreamsPerClient (16) with a 429 (Streams).
rg -n 'live\.Spec\{' --type go
Tab state for a tab without a stream
An action that stores state for a tab checks first that the session has the tab's stream open (live.Hub.HasStream with the stream's ID, or the session the app noted when the stream opened). Otherwise every tab id a client makes up is a row until the sweep, and the sweep's DELETE runs in the writer's transaction.
A stream that does not come back after a deploy
A page's stream opens with retry: 'error' from an element whose id is the stream's Spec.Reconnect. 'auto', Datastar's default, leaves pages stale after a deploy; 'always' also reopens streams the server ended on purpose (Datastar notes).
rg -n "retry: '(always|auto)'|@(get|post)\('[^']*(stream|sse|live)" -g '*.templ' -g '*.go'
A refresh that morphs the stream or the signals
A stream with Spec.Refresh morphs a container that holds neither the stream's element nor the page's data-signals: a morphed stream element opens a second stream (lith skips such a refresh), and a plain data-signals overwrites the tab id and the pending ops. A page with typed input (Dirty) or another assets version gets a notice that asks for a reload, not a morph (Pages).
rg -n 'Refresh:' --type go
A server base context that ends with the signal
The server's BaseContext must not end with the signal. Request contexts would end before the hub stops, the streams would end without sse.Reconnect, and Chrome takes a stream cut that way for a clean end, so even retry: 'error' does not reopen it. Stop the hub first, and give the server context.WithoutCancel, or no base context at all.
rg -n 'BaseContext' --type go
Tab state in a map
A tab's state lives in SQLite, written by commands. A map of tabs in memory is empty after every deploy, and the pages that reconnect find nothing.
rg -n 'map\[string\]\*?[tT]ab' --type go
A view key that leaves out what Render filters by
Does every view key contain everything its Render filters by? Views with the same key are one view, rendered by the definition its first watcher gave. A list filtered by the person under a key of the route alone renders the first person's list for everyone who opens the route after them, titles they may not read included. In a database that people share, the key carries the person, the route and the filters (Views in a shared database, per person).
Commands and views that disagree on topics
Every view names its topics, and every command touches the topics it changes. A command that touches nothing leaves pages stale; a view that listens to a topic every commit touches renders on every commit, and so does a view on a level above many topics, such as board above every board:<id>. hub.Stats().RendersByKey shows the second. An id from outside the app goes into a topic through live.Topic, which escapes the : an id such as urn:uuid:… holds.
Schema
Random keys on large tables
Random keys scatter inserts over the B-tree: Anders Murphy measured inserts with UUIDv4 keys 14 to 16 times slower than with integer keys, at 10 million rows. Prefer INTEGER PRIMARY KEY; time-ordered ids will do. Random tokens go on small tables, and a bulk insert sorts its batch by key first.
rg -n 'uuid\.(New|NewString)|ulid\.Make' --type go
rg -n 'TEXT PRIMARY KEY' -g '*.sql'
A table that grows without a sweep
Every table that grows has a rule for what it keeps, and a sweep that enforces it. Look for the call that starts each sweep: a sweeper that main never starts deletes nothing (Migrations, jobs and imports).
Operations
- Backups. Litestream with a restore that is verified, or
VACUUM INTOcopies on a timer, copied off the machine. Acpof a WAL database is not a backup (Backups). - One owner for checkpoints. Litestream when it is attached, the writer otherwise.
- Migrations. Numbered files, applied by
user_version, one transaction each. Two branches never use one number for different files.
The skill and this page
lith's skill, in skills/lith, holds the same checklist for coding agents, as references/review.md, terse and with the projects' names. This page is written for people and is not generated from it. Instead, the docs' TestSkill fails when a command of the skill's checklist is missing here: a check added to the skill has to arrive on this page in the same change. A check added here belongs in the skill as well.