| name | sqlite-schema |
|---|---|
| description | The --db SQLite sink — why it exists, the schema and its v1 → v23 migration chain, findings and their per-incident rows, survey sessions, retention tiers, MISSION §2 guardrails, and query recipes |
| type | reference |
Summary: -o FILE is the wire format — a stream other tools
consume. --db FILE is the retained artifact — durable entity state
and findings, upserted per entity rather than appended per tick, so a
month of operation costs megabytes instead of a terabyte.
Sources: src/db.h, src/db.c, src/db_schema.c,
tests/test_db.c, issues #42, #56, #154, #170 and #239.
Last updated: 2026-11-27 (owner request, the Probes tab's waterfall: schema v23, probe_history, directed probes counted per MAC, SSID and 10-minute bucket, observation tier, drained every 60 s; the v22 → v23 step and its two tests; the random-address purge keeps a device with a probe_history row), 2026-11-25 (#244: schema v22, the question_status table, one row each time a site question's answer changes, observation tier), 2026-11-25 (#245: schema v21 (built as v20, renumbered over #228's v20 on 2026-11-27), alert_incidents gains state, prelim_at, confirmed_at and withdraw_why, and a preliminary or withdrawn incident is a row there, never an alerts row; the v20 → v21 step and its two tests), 2026-11-26 (#228 step 5, owner ruling 2026-11-25: schema v20, twin_evidence_snapshots, the evidence vector behind an EVIL_TWIN pair's confidence for a future labelled-training pass, on the finding tier and deliberately not latched like the rest of this file; the v19 → v20 step and its two tests), 2026-11-24 (#250 review: alert_incidents and coverage_intervals name their offline readers, --handoff and --interference-report, and what of each they parse), 2026-11-23 (#246: schema v19, the quality columns of alert_incidents, complete, complete_why, latency_ms, corroboration and src_state, their order-free upsert; the v18 → v19 step and its two tests), 2026-11-23 (#242 item 2 review: v18 and slothweb's WEB_SDB_SCHEMA_MAX, still 17 in sloth-mesh, so the current slothweb refuses a v18 file whole; the deploy order; radio_ms and the overflowed channels), 2026-11-23 (#242 item 2: schema v18, coverage_intervals, one row per minute of what the monitor radios did, the coverage_interval record's figures, on the observation tier; the v17 → v18 step and its two tests); 2026-11-20 (#239, owner ruling of that day: schema v17, random_devices_daily, the count per UTC day and sources of the random addresses the retention step purges from devices after a week, the v16 → v17 step and its two tests; planner statistics: PRAGMA analysis_limit=400; PRAGMA optimize in the hourly maintenance, and what sqlite_stat1 holds, § Planner statistics); 2026-11-16 ([[victron]]: schema v16, victron_readings gains ac_voltage_v, ac_current_a and ac_apparent_va, the inverter record's AC output; the three-ALTER v15 → v16 step and its two tests); 2026-11-15 (#216, the cutover: which daemon writes which table; no schema change, DB_SCHEMA_VERSION stays 15 in both files); 2026-11-15 ([[victron]]: schema v15, victron_devices
in the entity tier and victron_readings in the observation tier, at
most one reading row a minute per device, the stamp-only v14 → v15 step
and its two tests; slothweb's Victron tab charts victron_readings).
2026-11-15 (#207 slice 1: schema v14, beacon_aps
gains operating_width — a BSS's occupied bandwidth, so a reader can
draw it instead of assuming 20 MHz — the v13 → v14 step and its two
tests; slothweb's /api/wifi/aps serves the field). 2026-11-05 ([[aprs]]: schema v13, aprs_stations in the entity tier and aprs_packets in the observation tier, one row per packet, the stamp-only v12 → v13 step and its two tests); 2026-11-05 (#26, [[adsb]]: schema v12, adsb_aircraft in the entity tier and adsb_sightings in the observation tier on the adsb_aircraft record's change-only rule, the stamp-only v11 → v12 step and its two tests; slothweb's GNSS and ADS-B "seen" history reads them and gnss_sightings). 2026-11-03 (#175: schema v11, alert_incidents, one row per incident beside the per-finding alerts row, written from the engine's lifecycle hook and each tick, bounded at 256 incidents a key, on the finding tier; the stamp-only v10 → v11 step and its two tests; slothweb's History and alert page read it). 2026-11-02 ([[gnss]]: schema v10, gnss_fixes and gnss_sightings in the observation tier on the records' banded change-only rule, the stamp-only v9 → v10 step and its two tests). 2026-11-02 ([[location]]: device_positions at rest samples on an RSSI band change or every gps.sample_s x 10, its row rate, and --location for a parked sensor). 2026-10-27 ([[location]]: schema v9, the alerts location stamp lat/lon/alt_m/acc_m/loc_src/loc_ts, the v8 → v9 step, device_positions and sensor_positions in the observation tier, the stamp's upsert rule and --db-compact-alerts carrying it). 2026-10-26 (idx_alerts_first_seen and idx_devices_first_seen, for slothweb's History strip; an index needs no bump, and the build cost is measured under "Indexes on time"). 2026-10-26 (#170 review: alerts.incident_first_seen, peak sev on the live row as on a compacted one, count / reopens as lower bounds, and --db-compact-alerts refusing an un-checkpointed SRC, writing nothing beside it, and handing DST to SRC's owner). 2026-10-26 (#170: schema v8, one alerts row per finding rather than per incident — the incident semantics below, the v7 → v8 step, and the opt-in --db-compact-alerts copy for the duplicates older builds wrote). 2026-10-23 (#163: the query recipes are slothweb's SQL box's, extracted at its build; three are refused there, the space recipe because dbstat gives away a withheld column's length). 2026-10-21 (#154: the v1 → v4 migration steps, so the chain now runs the full v1 → v7 and nothing below v5 is refused any more; also fixed a latent check_version() bug — reopening a file already at the current version could wrongly re-enter the migration chain once the floor reached v1, because "a schema_version row exists" and "the version to migrate from" shared one variable). 2026-10-21 (#155: schema v7, the devices classifier and DHCP option columns, the v6 → v7 step and the migration chain). 2026-10-20 (#106 round 2: schema v6, devices camera columns, the add-column-only v5 → v6 migration). Earlier: 2026-10-15 (#113: write path names poll_tick(); #134: sqlite3 >= 3.31.0 compile-time pin, SQLITE_OPEN_NOFOLLOW unconditional; #137).
Two files, one schema (since the cutover, #216,
ADR 0010). sloth-wifi (alias
sloth) writes /var/lib/sloth/sloth.db and sloth-rf writes
/var/lib/sloth-rf/sloth-rf.db. Both have this page's DDL, every
table, and the same DB_SCHEMA_VERSION, so a bump and its migration
apply to both files; what differs is which tables a daemon fills.
| Tables | sloth-wifi (sloth.db) |
sloth-rf (sloth-rf.db) |
|---|---|---|
devices, device_positions, beacon_aps, wifi_*, probe_clients, pnl_clients, arp, dhcp_leases, every flow, discovery and event table, twin_episodes, cleartext_creds |
written | empty (it has no capture) |
gnss_fixes, gnss_sightings |
empty since the cutover | written, with --gps |
adsb_aircraft, adsb_sightings |
empty since the cutover | written, with --adsb |
aprs_stations, aprs_packets |
empty since the cutover | written, with --aprs |
victron_devices, victron_readings |
empty since the cutover | written, with --victron |
sensor_positions |
written (with a fix) | written (with a fix): both daemons keep the sensor's own track |
sensors |
its radios and the receiver | the receiver and the decoders |
alerts, alert_incidents |
its findings | its findings (GNSS_*, ADSB_EMERGENCY, SENSOR_SOURCE_DOWN for its sources) |
sessions, meta |
written | written |
A sloth.db from before the cutover keeps the RF rows it has: nothing
is deleted or moved, and retention ages them out as it always did.
slothweb does not show them. It reads the RF tables from one file,
and with --rf-db (which the shipped unit always passes) that file is
sloth-rf.db, so the ADS-B, APRS, Victron and GNSS history pages start
empty at the cutover and show what sloth-rf has recorded since. The
older rows are read with sqlite3 -readonly on sloth.db until they
age out; no tool copies them across ([[deployment]] §11.4).
The writer's seam is db_set_rf_side() (src/db.h): sloth-rf
registers it and sloth-wifi does not, and unregistered the four
writers are not called, whatever the state holds (sloth-wifi has a
receiver's fix in its state and still writes no gnss_fixes row;
tests/test_rf_db.c). Where the sections below say a table is
"written only with --adsb" (or --aprs, --victron, --gps for the
gnss_* pair), the daemon is sloth-rf. slothweb reads the second
file with --rf-db ([[slothweb]] § Two daemons).
A production sensor writing -o produced 12.6 GB in 8 hours
(~38 GB/day), and after 12 hours the operator could not jq the file
interactively — a full-log query timed out. Roughly half that volume was
unchanged snapshot rows: the same entity re-serialised every poll
because it was still there.
Change-only emission (#44) cut the re-serialisation on the wire. The
sink attacks the other half of the problem: sloth's persisted
cardinality is bounded by construction. Every entity table in
include/sloth.h is a fixed array — MAX_DEVICES 256,
MAX_BEACON_APS 256, MAX_PNL_CLIENTS 128, MAX_WIFI_MERGED 512.
Upserting per entity with first_seen / last_seen instead of
appending per tick turns 38 GB/day into an estimated 15–30 MB (home),
~140 MB (busy office), ~350 MB (conference).
That pair of columns is also what makes the file queryable: "who was here between 2 and 4 AM" is a range scan, not a log grep.
-o and --data-socket are unchanged and are not deprecated. What
changed is positioning, in docs only: JSONL is the wire format and SIEM
contract; the SQLite file is the retained artifact.
- Not a query surface. The database is never served over the data
socket and gets no RPC. MISSION §4 forbids remote-control surfaces;
a local file is a sink, and that distinction only holds if there is no
way to reach it remotely. Operators query with the
sqlite3CLI. - Not a replacement for pcap. Per-alert pcap export ([[pcap-export]]) is still where packet-level evidence lives.
- Not on by default. No
--db, no database, no dependency cost at runtime.
WITH_SQLITE ?= 1 links the system libsqlite3, cloned from the
WITH_PCAP block. make WITH_SQLITE=0 builds without it; make embedded already excludes it, so the zero-dependency embedded target is
unchanged. CI builds both.
sqlite3 >= 3.31.0 is a compile-time requirement (#134). src/db.c
and research/query.c carry
#if SQLITE_VERSION_NUMBER < 3031000 #error …. The reason is
SQLITE_OPEN_NOFOLLOW: the -wal / -shm / -journal checks in
db_prepare_private() are advisory — a symlink can appear between the
lstat and SQLite's own open — and are acceptable only because SQLite
itself refuses to follow one. The flag used to sit behind an #ifdef
that compiled silently without it on older headers, which made the
side-file checks look stronger than they were on exactly the systems
where they were weakest. rq_open() (the read-only research corpus)
passes it too. 3.31.0 is from January 2020; every supported Debian,
Ubuntu, Fedora and Alpine ships newer.
SQLITE_DBCONFIG_DEFENSIVE is on (#137). db_open() sets it before
the first PRAGMA and reads it back; a library that does not honour it
fails the open (DEFENSIVE refused) rather than proceeding. The file
--db names may predate this run or have been written by something
else, and DEFENSIVE closes the schema-corruption paths
(writable_schema, direct shadow-table writes) that sloth never uses.
Only DEFENSIVE: TRUSTED_SCHEMA=0 is for the research corpus, whose
schema somebody else wrote — see [[research-corpus]].
poll_tick() (src/poll.c, #113)
├─ every snapshot refreshes sloth_state_t
└─ db_tick(state, now) ← DURABLE, the last phase: fully-refreshed state
├─ BEGIN IMMEDIATE
├─ ~29 prepared upserts
└─ COMMIT … then hourly: db_maintain()
It reads sloth_state_t directly and cannot hang off the jsonl
emitters. Every jsonl_emit_* opens with any_sink(), which is false
when neither -o nor --data-socket is active — so a --db-only run
would silently write an empty database. Routing through
jsonl_changed() would also make durable last_seen lag by up to the
300-second heartbeat, coupling durable state to a wire-format
optimisation.
- Private files (#87). SQLite would create the database
0644 & ~umaskand gives-wal/-shmthe main file's mode, so sloth creates the database file itself at 0600 first (by descriptor,O_NOFOLLOW) and opens it withSQLITE_OPEN_NOFOLLOW; the WAL and shared-memory files inherit 0600. An existing database,-wal,-shmor-journalthat is a symlink, belongs to another user, has more than one link or carries any group/other bit is refused —db_openfails and startup stops. sloth neverchmods it. A database written by an older build is typically0644; before upgrading,chmod 600 FILE FILE-wal FILE-shm(as the owning user) once. - WAL so a reader (your
sqlite3session) never blocks the writer. synchronous=NORMAL— fsync at checkpoint, not per commit. At 1 Hz on an SD card the difference is the card's lifetime; the exposure is the last few seconds of telemetry on a power cut, which a passive sensor can afford.BEGIN IMMEDIATEtakes the write lock up front, so a competing writer fails fast instead of surfacing at COMMIT with a batch staged.- Fail-open, always. Any error disables further writes and reports once. A database problem costs the operator persistence, never visibility.
These are what make the file trustworthy rather than merely present.
| Rule | Where | Why |
|---|---|---|
first_seen = MIN, last_seen = MAX |
every table | A re-observation never moves the start of an entity's history; an out-of-order tick cannot rewind its end. |
assocs.source prefers the smaller non-zero value |
assocs |
ASSOC_SRC_* is ordered strongest-first (EAPOL=1, ASSOC=2, REASSOC=3). A naive MAX preserves the weakest evidence and silently downgrades confirmed handshakes. 0 is UNKNOWN — absence of evidence — and must never win despite sorting below everything. |
| Flow counters = MAX | protocol flows | The in-memory rings reset counts on eviction; the durable row means "what has this pair done", not "since the last eviction". |
sensor_mask, proto_mask, eap_types_seen = OR |
merge / RDP / RADIUS | Coverage and offered-capability bits accumulate. A radio that heard an entity once still heard it. |
SMB dialect sticky to SMB1 |
smb_sessions |
Once a flow has spoken SMB1 that is the finding; a later SMB2 negotiation must not erase it. |
| Evidence flags latch | deauth, twins, karma | A burst that crossed the flood threshold was a flood; a twin caught mid-attack was caught mid-attack. |
sev = MAX, detail the latest at that peak |
alerts |
A row holds every incident of a key (#170), and a LOW reopen must not erase the CRIT before it. The compactor folds rows the same way. |
One row per finding; count sums incidents, reopens counts them |
alerts |
A write continues the key's newest row, so evict-and-refire, a quiet-period reopen and a restart all advance one row (#170). See Findings and incidents below. |
One row per incident: span widens, peak_sev/count/observations only rise, a close once recorded stays; sev the latest |
alert_incidents |
Written each tick from the hook's queue and then from the snapshot, and by a full queue's own flush between ticks. Every column but sev comes out the same whatever the order; sev is the last write's, and the snapshot, the newest view, is written last (#175). See Per-incident rows below. |
meta holds schema_version, currently 23. db_open() checks it
before applying the rest of the schema, so a mismatch produces the
clear version message rather than whatever SQL error the schema happens
to hit first. Since #154 the chain covers the full v1 → v23: any
file this build has ever written opens and migrates forward. Only a
file from a newer build (schema_version above 23) is refused.
(The table count above is measured — grep -oE "CREATE TABLE IF NOT EXISTS [a-zA-Z_0-9]+" src/db_schema.c | sort -u | wc -l — not carried
forward by hand; this page's "54" had drifted from the real count of
57 even before this change, which is the reason to measure rather than
increment.)
v5 (#90): karma_candidates.pnl_best. v6 (#106 round 2):
devices gains device_class, camera_vendor, camera_model,
setup_mode, cam_signals — see [[camera-detection]]. v7 (#155):
devices gains cam_score, cam_evidence (CAM_EV_* mask),
cam_vetoes (CAM_VETO_* mask), cam_conflict, dhcp_prl and
dhcp_vci (the client's DHCP options 55 / 60, display-only), and
device_class may now hold 3, not-camera. v8 (#170): alerts
gains reopens, incident_id, incident_count and
incident_first_seen, and its rows become one per finding — Findings and incidents below.
v9 (2026-10-27, [[location]]): alerts gains lat, lon,
alt_m, acc_m, loc_src and loc_ts, where the sensor was when the
row's current incident opened, and two new tables, device_positions
and sensor_positions. v10 (2026-11-02, [[gnss]]): two new tables,
gnss_fixes and gnss_sightings, the --gps receiver's own sky and
clock; no existing table or value changes. v11 (2026-11-03, #175):
one new table, alert_incidents, a row per incident beside the
per-finding alerts row (Per-incident rows below); alerts is
unchanged. v12 (2026-11-05, #26, [[adsb]]): two new tables,
adsb_aircraft and adsb_sightings, the --adsb decoder's aircraft;
no existing table or value changes. v13 (2026-11-05, [[aprs]]): two new
tables, aprs_stations and aprs_packets, the --aprs decoder's
stations and packets; no existing table or value changes. v14
(2026-11-15, #207 slice 1): beacon_aps gains operating_width
(sloth_ch_width_t: 0 unknown, else MHz, 8080 for 80+80
non-contiguous), upgrade-only on conflict like downgrade_flags and
akm_bits — a beacon that omits the operation IE it last carried does
not erase a wider width this file already recorded for the BSSID.
v15 (2026-11-15, [[victron]]): two new tables, victron_devices
and victron_readings, what --victron read from sloth-va's file; no
existing table or value changes.
The v14 → v15 migration. A stamp alone
(db_schema_migrate_v14_sql() is empty): both tables and their three
indexes ride the unconditional schema, and nothing is backfilled (no
earlier file recorded a Victron reading). Tested on a v14 file (a
current file with both tables dropped and the stamp set to 14, which is
a v14 file's exact shape, plus an alert row;
test_v14_file_migrates_additively: the alert row unchanged, both
tables and indexes present and empty) and on one whose stamp a trigger
refuses (test_v14_migration_failure_leaves_file_unchanged: it stays
v14 with neither table and the alert row as it was). slothweb's
WEB_SDB_SCHEMA_MAX moved to 15 with it.
v16 (2026-11-16, [[victron]]): victron_readings gains
ac_voltage_v, ac_current_a and ac_apparent_va, the AC output of
the Instant Readout inverter record; no existing column or value
changes.
The v15 → v16 migration. Three ALTER TABLE victron_readings ADD COLUMN, all nullable REAL (db_schema_migrate_v15_sql()), applied
only when the table exists (a file from before v15 gets the table whole
from the unconditional schema). A row written before the step has NULL
in all three, which is what it recorded. A migrated file holds the
three columns after off_reason, where the unconditional schema also
puts them. Tested on a v15 file (victron_readings rebuilt by hand at
its v15 shape, one reading; test_v15_file_migrates_additively: the
three columns present and NULL on that row, its own values unchanged)
and on one whose stamp a trigger refuses
(test_v15_migration_failure_leaves_file_unchanged: it stays v15 with
none of the three). slothweb's WEB_SDB_SCHEMA_MAX moved to 16 with
it; it reads the three as absent from a v15 file.
v17 (2026-11-20, #239): one new table, random_devices_daily,
the rollup the random-address purge counts into ([[retention]] § 2b);
no existing table or value changes.
The v16 → v17 migration. db_schema_migrate_v16_sql() is the
table's CREATE TABLE IF NOT EXISTS, the same DDL the unconditional
schema carries (RANDOM_DEVICES_DAILY_DDL in src/db_schema.c), so
the table and the stamp land in the step's one BEGIN IMMEDIATE
transaction. Nothing is backfilled: no earlier build purged a row.
Opening never purges; only the hourly maintenance does. Tested on a
v16 file (a current file with the table dropped, the stamp set to 16
and a device row; test_v16_file_migrates_additively: the table
present and empty, the device row unchanged) and on one whose stamp a
trigger refuses (test_v16_migration_failure_leaves_file_unchanged: it
stays v16 without the table, its device row as it was). sloth-mesh pins
the contract at 1.8.7, so its dashboard reads this table only after a
contract bump on its side.
v18 (2026-11-23, #242 item 2, [[coverage-assessment]] § 6): one
new table, coverage_intervals, with an index on last_seen; no
existing table or value changes.
Not additive for slothweb. sloth-mesh's WEB_SDB_SCHEMA_MAX
(src/web_slothdb.h) is still 17 when this is written, and slothweb
refuses a file newer than that whole ("written by a newer sloth
(schema v18 ...): not read; update slothweb"), not just the new table:
every sloth.db and --rf-db read on the dashboard goes blank (devices,
History, GNSS, ADS-B, Victron). Both daemons migrate their file to v18
when they open it. So the companion change, sloth-mesh's
WEB_SDB_SCHEMA_MAX moved to 18 with a contract re-pin (its
test_schema_max_is_sloths holds the two equal and goes red against
this contract until then, as does sloth's CI mesh-against-contract
job), has to land and be installed before this sloth is installed,
as at v13 to v17.
The v17 → v18 migration. db_schema_migrate_v17_sql() is the
table's and the index's CREATE ... IF NOT EXISTS, the same DDL the
unconditional schema carries (COVERAGE_INTERVALS_DDL in
src/db_schema.c), so both and the stamp land in the step's one
BEGIN IMMEDIATE transaction. Nothing is backfilled: no earlier build
measured an interval. Tested on a v17 file (a current file with the
table and index dropped, the stamp set to 17, a device row and a
random_devices_daily row; test_v17_file_migrates_additively: the
table and index present, the table empty, both rows unchanged) and on
one whose stamp a trigger refuses
(test_v17_migration_failure_leaves_file_unchanged: it stays v17
without the table or the index, both rows as they were).
v19 (2026-11-23, #246, [[coverage-assessment]] § 9): five nullable
columns on alert_incidents, the quality fields of each incident:
complete, complete_why, latency_ms, corroboration,
src_state (Per-incident rows below). No other table or value
changes. Not additive for slothweb either, for the reason v18 gives:
sloth-mesh's WEB_SDB_SCHEMA_MAX has to reach 19, with a contract
re-pin, and be installed before this sloth is. Its alert page reads
alert_incidents by named column, so the new columns break no query.
The v18 → v19 migration. db_schema_migrate_v18_sql() is five
ALTER TABLE alert_incidents ADD COLUMN, in the step's one BEGIN IMMEDIATE transaction with the stamp; the step runs only where
alert_incidents exists (a file older than v11 gets the table, columns
and all, from the unconditional schema). An existing row keeps NULL in
all five: nothing assessed it. Tested on a v18 file (a current file
with the five columns dropped, the stamp set to 18, one closed incident;
test_v18_file_migrates_additively: the five present, NULL on that
row, its eleven values as they were) and on one whose stamp a trigger
refuses (test_v18_migration_failure_leaves_file_unchanged: it stays
v18 without the columns). Every older-version fixture that starts from
a current file drops the five first (PRE_V19_INCIDENTS_SQL in
tests/test_db.c), since the ALTER would meet a duplicate column.
v20 (2026-11-26, #228 step 5, owner ruling 2026-11-25): one new
table, twin_evidence_snapshots, the twin_evidence_t vector (src/ alerts.h) behind an EVIL_TWIN candidate pair's confidence, for a
future supervised-training pass to read against labelled triage
verdicts. No existing table or value changes. Local only — never
exported to JSONL, never on the fleet-share allow-list.
The v19 → v20 migration. db_schema_migrate_v19_sql() is CREATE TABLE IF NOT EXISTS twin_evidence_snapshots and its index, the same
DDL the unconditional schema carries — a step with no ALTER, since
the table is new. Nothing is backfilled: no earlier build recorded a
row. Tested on a v19 file (a current file with the table and its index
dropped, alert_incidents at its v19 shape, the stamp set to 19; test_v19_file_migrates_additively: the
table and index present, the table empty) and on one whose stamp a
trigger refuses (test_v19_migration_failure_leaves_file_unchanged: it
stays v19 without the table or the index).
twin_evidence_snapshots (ssid, real_bssid, twin_bssid, confidence, diff_oui, same_oui, hashes_differ, late_arrival, attacker_oui, steered, self_steer, sibling, nbr_claim, carrier_ssid, mesh_vap, faint, inv_mismatch, inv_approved, inv_consulted, positive, context, hard, first_seen, last_seen), primary key (ssid, real_bssid, twin_bssid). One row per EVIL_TWIN candidate pair, written by
write_detector_evidence() from twins_snapshot()'s per-poll
s->twin_evidence_snaps[] (src/twins.c), same loop and same index as
twin_episodes. Every column but the identity and the two timestamps
is overwritten on conflict (excluded.*, no MAX) — the one
upsert in this file that is not latched, because a label store needs
the vector as most recently observed, not the loudest it ever reached
(twin_episode_t's own latching is exactly the shape #228 found unfit
for this; see include/sloth.h's comment on twin_evidence_snap_t).
On the finding tier (src/db.c TIER_FINDING), beside
karma_candidates and rogue_radius, for the reason those two are
there: the evidence should outlive nothing less than the finding it
justifies.
v21 (2026-11-25 as v20, renumbered 2026-11-27 over #228's v20; #245, [[alerts]] § Finding lifecycle): four
nullable columns on alert_incidents, state, prelim_at,
confirmed_at and withdraw_why (Per-incident rows below), and a
preliminary or withdrawn incident is now a row there (never an alerts
row). No other table or value changes. Not additive for slothweb, for
the reason v18 gives: sloth-mesh's WEB_SDB_SCHEMA_MAX has to reach 21,
with a contract re-pin, and be installed before this sloth is.
The v20 → v21 migration. db_schema_migrate_v20_sql() is four
ALTER TABLE alert_incidents ADD COLUMN, in the step's one BEGIN IMMEDIATE transaction with the stamp, run only where alert_incidents
exists. An existing row keeps NULL in all four: no earlier build gave
an incident a state. Tested on a v20 file (the pre-v19 table plus the
v18 → v19 ALTERs, the stamp set to 20, one closed incident;
test_v20_file_migrates_additively: the four present, NULL on that
row, its values as they were) and on one whose stamp a trigger refuses
(test_v20_migration_failure_leaves_file_unchanged: it stays v20
without the columns).
v22 (2026-11-25 as v21, renumbered 2026-11-27; #244, [[site-questions]]): a new table,
question_status, with indexes on last_seen and (qid, last_seen);
no other table or value changes. Not additive for slothweb, for the
reason v18 gives: sloth-mesh's WEB_SDB_SCHEMA_MAX has to reach 22,
with a contract re-pin, and be installed before this sloth is.
The v21 → v22 migration. db_schema_migrate_v21_sql() is the
table's own DDL (CREATE TABLE IF NOT EXISTS, the same text the
unconditional schema carries) in the step's one BEGIN IMMEDIATE
transaction with the stamp. Tested on a v21 file (a current file with
the table and its indexes dropped and the stamp set to 21, a device and
an incident row riding along; test_v21_file_migrates_additively: the
table empty with its 15 columns and two indexes, the rows as they were)
and on one whose stamp a trigger refuses
(test_v21_migration_failure_leaves_file_unchanged: it stays v21
without the table). Every older-version fixture that starts from a
current file drops it first (PRE_V22_SQL in tests/test_db.c).
question_status (last_seen, daemon, qid, priority, question, source, status, why, kinds, observable, partly, blind, n_alerts, found, ids). One row each time a site question's answer changes in the daemon
that holds the file, and one for every question after the file opens
(write_question_status(), beside write_coverage_intervals()): the
question_status record's fields ([[jsonl-schema]]), daemon wifi
or rf, last_seen the tick's time. observable, partly and
blind are NULL while the coverage is not assessed, never 0 for that.
Words, counts and incident ids beside the operator's own question text:
no address and no SSID. On the observation tier: an answer is derived
from the finding and coverage rows beside it and expires with them.
"When did Q1 become a finding" is
SELECT last_seen, found, ids FROM question_status WHERE qid='Q1' AND status='finding' ORDER BY last_seen.
v23 (2026-11-27, owner request: the Probes tab's waterfall): a new
table, probe_history, with indexes on last_seen and (ssid, bucket); no other table or value changes. Not additive for slothweb,
for the reason v18 gives: sloth-mesh's WEB_SDB_SCHEMA_MAX has to reach
23, with a contract re-pin, and be installed before this sloth is.
The v22 → v23 migration. db_schema_migrate_v22_sql() is the
table's own DDL (CREATE TABLE IF NOT EXISTS, the same text the
unconditional schema carries) in the step's one BEGIN IMMEDIATE
transaction with the stamp. Tested on a v22 file (a current file with
the table and its indexes dropped and the stamp set to 22, a device, a
pnl_ssids and a question_status row riding along;
test_v22_file_migrates_additively: the table empty with its 6 columns,
its 3-column key and two indexes, the rows as they were) and on one
whose stamp a trigger refuses
(test_v22_migration_failure_leaves_file_unchanged: it stays v22
without the table). Every older-version fixture that starts from a
current file drops it first (PRE_V23_SQL in tests/test_db.c).
probe_history (mac, ssid, bucket, count, first_seen, last_seen),
key (mac, ssid, bucket). Directed probe requests (a non-empty SSID
element; a wildcard probe names no network and is never a row) counted
per transmitter address, SSID and 10-minute bucket, sloth-wifi's alone
(sloth-rf has no capture and writes none). bucket is the bucket's
start in Unix seconds, UTC, a multiple of 600 (PROBE_HIST_BUCKET_S);
count the probes heard in it; first_seen / last_seen the first and
last of them, so bucket <= first_seen <= last_seen < bucket + 600.
mac is lowercase aa:bb:cc:dd:ee:ff as everywhere in the file (a
locally administered one is a randomised address: the second hex digit
is 2, 3, 6, 7, a, b, e or f); ssid is the element as pnl_ssids holds
it (C0 controls and DEL written ?, other octets kept, so not always
UTF-8). Where pnl_ssids says a device probed for a network between
two times, this is the shape in between.
How it is written (src/probe_hist.h, write_probe_history()): the
capture thread counts each probe probe_pnl_observe() takes into a
bounded table, and the tick drains it every DB_PROBE_HIST_FLUSH_S
(60 s) and at close, inside the tick's own transaction: one upsert per
key heard since the last drain that adds its count to the row. So a
key is at most ten upserts a bucket however often it probes, a row
for the bucket now open grows while it is open, and a killed process
loses at most the last minute. At most PROBE_HIST_BUCKET_KEYS (2048)
keys a bucket: a probe that would need a new key past that, or past
the table's two buckets' worth, is not counted and is noted in
sensor_health's evict_probe_hist ([[jsonl-schema]] 2.19.0). Probes
on a key already held are always counted, so a burst of randomised
addresses costs the rows of its newest addresses in that bucket, not
the counts of the devices already there, and the file grows by at
most 2048 rows a bucket (294 912 a day). Nothing is counted without
--db.
On the observation tier: each row is an observation between the
pnl_ssids inventory's first and last, which stays on the entity
tier; past the window it goes, and the size ceiling may take it. The
random-address purge treats a probe_history row as a tie to an SSID,
as it does a pnl_ssids one. "One SSID over time" reads
idx_probe_history_ssid; "the last N hours" reads
idx_probe_history_last_seen (a bucket's rows all have last_seen at
or after the bucket's start, so last_seen >= T finds every bucket
starting at or after T, and the one bucket before it that was still
heard after T); one device's rows read the key.
coverage_intervals (start, last_seen, dur_ms, radio_ms, ms_24, ms_5, ms_5dfs, ms_6, ms_unknown, f_beacon, f_probe, f_auth, f_assoc, f_deauth, f_action, f_ctrl, f_data, f_eapol, f_other, f_fcs_bad, cap_drop, cap_ifdrop, mon_drop, mon_ifdrop, chan_overflow, chans TEXT, sources TEXT). One row per closed 60 s interval, written by sloth-wifi
only (write_coverage_intervals(), from the ring of closed intervals
in src/cov_interval.c, so a --db-interval-secs longer than a minute
loses none of the last eight). start / last_seen are the interval's
two ends (wall clock), dur_ms its length on the monotonic clock,
radio_ms the monitor radios' time and ms_* that time by band
(5dfs: channels 52-64 and 100-144; unknown: a fixed radio that has
heard nothing). radio_ms is the sum of the ms_*, and includes the
time of channel entries beyond the 32 that chans does not list
(counted in chan_overflow). f_* are the frames received by class, summing to the
frames the monitor path recorded. The four drop columns are NULL when
the handle was not measured at both ends, never 0 for that. chans and
sources are the record's two arrays as JSON text, exactly as the
coverage_interval line writes them ([[jsonl-schema]]), so
json_each() reads them. Counts, channels and states only: no
address, no SSID. Not written in a --replay run. Observation tier.
Read by --interference-report ([[handoff]]), which parses chans
with sscanf() in the writer's key order (radio, ch, freq_mhz,
band, ms, frames; add_chans() in src/interference.c): an
entry in another shape is skipped, so a change to that order is a
change to that reader.
random_devices_daily (day TEXT, sources INTEGER, count, first_seen, last_seen, PRIMARY KEY (day, sources)). day is the UTC
date (YYYY-MM-DD) of a purged row's first_seen, sources its
DEV_SRC_* mask (in practice 16, probe only: anything with another
bit is kept, § 2b of [[retention]]). count is how many rows were
purged into it, first_seen / last_seen the earliest and latest
among them. An upsert adds to count and widens the two times; it is
never rewritten or aged out (no tier names it). Counts and times only:
no address and no SSID. On the sensor A copy of 2026-11-20 the first
pass counted 44,995 rows into 29 day rows.
victron_devices and victron_readings. Written only with
--victron, by write_victron(), from sloth's device table
(src/victron.c; at most 16 addresses). victron_devices (mac PK, first_seen, last_seen, serial, model, record, session, services, last_readout, last_gatt, readings, sessions, rssi) is upserted when the
row took a record since the last write and DB_VICTRON_MIN_S (60 s)
has passed, or at once when a discrete fact moved (serial, model,
record type, session outcome, service list): the earliest first_seen,
the latest last_seen, last_readout / last_gatt the latest each
(NULL never), serial / model / record / session / rssi the
newest non-empty, services the newest session's list (cleared by a
session that listed none), readings / sessions sloth's own counts
since it started (not a sum across runs). victron_readings (last_seen, mac, src, rssi, voltage_v, aux_voltage_v, mid_voltage_v, input_v, output_v, current_a, power_w, consumed_ah, soc_pct, ttg_min, temperature_c, alarm_reason, aux_input, device_state, charger_error, off_reason, ac_voltage_v, ac_current_a, ac_apparent_va) gets one row when the device took a record with values
and 60 s have passed since its last row: last_seen sloth's read time,
each value the latest sloth's table held (sticky: a value a record did
not carry is the last one that did; NULL never heard; alarm_reason
to off_reason are enumerations stored as integers; the three ac_*
are v16), src readout or gatt for the
path the newest values came from. The value columns are sloth's
allow-list by name (db_victron_col(); tests/test_db.c test_victron_columns_match_the_allow_list holds the two equal). No
column holds a PIN, a key or the device's own name. Rate: sloth-va
writes a readout every 30 s, so a device in range costs one row a
minute — three devices about 130k rows a month. victron_readings
sits in the observation tier, victron_devices in the entity tier.
Indexes: idx_victron_devices_last_seen,
idx_victron_readings_last_seen, idx_victron_readings_mac (mac, last_seen) for one device's history.
The v13 → v14 migration. ALTER TABLE beacon_aps ADD COLUMN operating_width INTEGER NOT NULL DEFAULT 0
(db_schema_migrate_v13_sql()); every other column and value is
untouched. Tested on a hand-built v13 beacon_aps fixture
(test_v13_file_migrates_additively) and on one whose stamp a trigger
refuses (test_v13_migration_failure_leaves_file_unchanged: it stays
v13 with no operating_width column). test_operating_width_never_regresses
pins the upsert's MAX() the same way
test_downgrade_flags_accumulate_on_the_ap pins the OR.
slothweb's WEB_SDB_SCHEMA_MAX (web/src/web_slothdb.h) moved
with it — test_schema_max_is_sloths holds the two equal, and a bump
here without that one left every sloth.db this build writes refused
by slothweb as "too new" (seen failing locally before the companion
change).
The v12 → v13 migration. A stamp alone
(db_schema_migrate_v12_sql() is empty): both tables and their three
indexes ride the unconditional schema, and nothing is backfilled (no
earlier file recorded a packet). Tested on a v12 file
(test_v12_file_migrates_additively) and on one whose stamp a trigger
refuses (test_v12_migration_failure_leaves_file_unchanged: it stays
v12 with neither table).
aprs_stations and aprs_packets. Written only with --aprs, by
write_aprs(), once per packet past the writer's own cursor on
src/aprs.c's packet ring (so once each, at any --db-interval-secs).
Each packet is one aprs_packets (last_seen, source, heard, dti, name, symbol, lat, lon, speed_kt, course, alt_m, level, status, comment) row
(last_seen Dire Wolf's utime; no key: one packet is often heard
twice in a second, direct and through a digipeater; absent figures
NULL) and one upsert of aprs_stations (call PK, first_seen, last_seen, visit_first, visits, packets, via, heard_direct, best_level, dti, symbol, lat, lon, pos_ts, comment, status, system): the earliest
first_seen, the latest last_seen, packets + 1, visits counted
each time sloth's own first_seen for the call moves (it expired after
3600 s unheard and came back), the newest non-empty via, dti, symbol,
position (with pos_ts), comment, status and system, heard_direct
once any packet was, the best level. An object's or item's position,
symbol and comment stay in its packet row, never on its sender's
station row. Every text column is what a transmitter sent.
aprs_packets sits in the observation tier, aprs_stations in the
entity tier. Indexes: idx_aprs_stations_last_seen,
idx_aprs_packets_last_seen, idx_aprs_packets_source (source, last_seen) for one station's packets.
The v11 → v12 migration. A stamp alone
(db_schema_migrate_v11_sql() is empty): both tables and their three
indexes ride the unconditional schema, and nothing is backfilled (no
earlier file recorded an aircraft). Tested on a v11 file
(test_v11_file_migrates_additively: alerts unchanged, both tables
and indexes present and empty) and on one whose stamp a trigger refuses
(test_v11_migration_failure_leaves_file_unchanged: it stays v11 with
neither table).
adsb_aircraft and adsb_sightings. Written only with --adsb,
by write_adsb(), on the adsb_aircraft JSONL record's change-only
rule (src/adsb.c adsb_row_sig(): identity, sloth's first_seen, the
held altitude band and position cell, squawk, emergency, callsign,
category) or the 300 s heartbeat, with the writer's own change memory,
so never once a second. Each write is one adsb_sightings (last_seen, hex, heard, flight, squawk, emergency, category, on_ground, alt_baro, alt_geom, alt_band, gs, track, baro_rate, lat, lon, rssi, messages, source_type) row, key (last_seen, hex) (heard is the decoder's
last message, baro_rate the geometric rate when there is no
barometric one, an absent figure NULL), and one upsert of the
inventory row adsb_aircraft (hex PK, non_icao, first_seen, last_seen, visit_first, visits, sightings, flight, squawk, category, source_type, emergency_seen, alt_min, alt_max, gs_max, rssi_max, messages, pos_seen): the earliest first_seen, the newest non-empty callsign,
squawk, category and source, the altitude, speed and RSSI extremes,
emergency_seen once any emergency other than none was reported,
and visits counted each time sloth's own first_seen for the address
moves (it expired after 60 s unheard and came back). hex is sloth's
spelling: six lower-case hex digits, ~-prefixed for a non-ICAO
address. adsb_sightings sits in the observation tier, adsb_aircraft
in the entity tier. Indexes: idx_adsb_aircraft_last_seen,
idx_adsb_sightings_last_seen, idx_adsb_sightings_hex (hex, last_seen) for one aircraft's track.
The v10 → v11 migration. A stamp alone
(db_schema_migrate_v10_sql() is empty): alert_incidents and its two
indexes ride the unconditional schema. Nothing is copied into it from
alerts: a v10 row's sev is the peak and its count the sum over
every incident it absorbed, figures no single incident had, so a
backfilled row would record what was never observed. The first v11
tick writes the incidents open then, and a key with no incident rows is
read from its alerts row as before. Tested on a v10 file
(test_v10_file_migrates_additively: alerts unchanged at 21 columns,
the table and indexes present, the table empty) and on one whose stamp
a trigger refuses (test_v10_migration_failure_leaves_file_unchanged:
it stays v10, with no alert_incidents).
The v9 → v10 migration. A stamp alone (db_schema_migrate_v9_sql()
is empty, as v2 → v3's was): both tables ride the unconditional
schema. Tested on a v9 file (test_v9_file_migrates_additively: the
rows and their stamps unchanged, alerts still 21 columns, the two
tables present) and on one whose stamp is refused by a trigger
(test_v9_migration_failure_leaves_file_unchanged: it stays v9 with
neither table).
gnss_fixes and gnss_sightings. Written only with --gps, by
write_gnss(), on the same banded change-only rule as the gnss_fix
and gnss_sat JSONL records (src/gps.c gps_gnss_fix_sig() /
gps_gnss_sat_sig()), with the writer's own change memory, so the row
rate is the record rate. gnss_fixes (last_seen PK, src, mode, status, nsat, usat, hdop, vdop, pdop, eph, epv, lat, lon, alt_m, speed_mps, track_deg, time_off_ms, jam, cn0_mean): one row when the fix's bands
move or every 300 s. gnss_sightings (last_seen, gnssid, prn, svid, el, az, cn0, used, health), key (last_seen, gnssid, prn) (PRN is the one
member gpsd always writes; gnssid is -1 from an NMEA-only gpsd; el
and az are NULL when gpsd sent none, and el may be negative — a
bird under the horizon gpsd still lists): one
row per satellite when its bands move (used, health, C/N0 to 6 dB,
elevation and azimuth to 15°) or every 300 s. Row rate: a steady
sky of a dozen satellites is ~290 fix rows and ~3,500 sightings a day;
a satellite crossing a band is one row. Both age with the observation
tier. slothweb reads both (allow-listed at version 10).
The v8 → v9 migration. Six ALTER TABLE alerts ADD COLUMN
statements, every column nullable with no default
(db_schema_migrate_v8_sql()), and the stamp, in one BEGIN IMMEDIATE
transaction. No v8 value changes; a v8 row reads as unstamped (all six
NULL), which it was. The two tables need no ALTER: they ride the
unconditional schema. Tested on a v8 file (test_v8_file_migrates_additively:
the four rows and their incident unchanged, the six columns NULL at
cids 15..20, then a v9 write stamping the current incident's row) and
on one whose last ALTER fails (test_v8_migration_failure_leaves_file_unchanged:
it stays v8, none of the five earlier columns present, every row as it
was).
The location stamp's upsert. The six columns move together under
one rule: within one incident (incident_id unchanged) a recorded
stamp is never overwritten — sloth stamps an incident once, as it
opens, so a later write carries the same one, and a restart re-writing
the incident with no fix must not erase it; a different incident on
the row brings its own stamp, NULL included, so the row always holds
its current incident's (test_alert_stamp_kept_within_incident).
--db-compact-alerts carries the newest row's stamp onto the folded
row, like the other per-incident columns.
device_positions and sensor_positions. Written only with
--gps and a fix no older than gps.max_fix_age_s (never from
--location). device_positions (mac, last_seen, lat, lon, acc_m, rssi),
key (mac, last_seen): where the sensor was when it heard the
device — not the device's position, sloth has no bearing — sampled when
the fix moved gps.min_move_m; at rest only when the device's RSSI
10 dB band changed (no sooner than gps.sample_s) or every
gps.sample_s x 10; rssi the device's last Wi-Fi signal, NULL
without one. sensor_positions (last_seen, lat, lon, alt_m, acc_m, loc_src, sats, hdop), key last_seen: the sensor's own track, on a
move or every gps.sample_s. Row rate: moving, one
device_positions row per heard device per gps.min_move_m
travelled; parked, one per device per 10 minutes plus band changes
(300 steady devices: ~43,000 rows a day), and one sensor_positions
row a minute. A sensor that does not move should run --location
instead of --gps, which writes neither table; see [[location]]. The sample's time
is named last_seen so the retention sweep, which ages every table by
that column, covers both; they are point samples, so they have no
first_seen (test_schema_tables_have_seen_columns names them as the
exception). Written INSERT OR IGNORE: a sample is one fact.
The v7 → v8 migration. Four ALTER TABLE alerts ADD COLUMN
statements with defaults (db_schema_migrate_v7_sql()) and the stamp,
in one BEGIN IMMEDIATE transaction. No v7 value changes — including
the duplicate rows an older build wrote, which stay exactly as they
were; folding them is --db-compact-alerts, on a copy, never the
migration. A v7 row reads reopens 0, incident_id NULL,
incident_count 0, incident_first_seen NULL (a reader takes
first_seen, which on a v7 row was the incident's start), and the
first v8 write for its key continues the
key's newest row as a reopen. Tested on a v7 file holding three rows for
one key (test_v7_file_migrates_additively) and on one whose last ALTER
fails, which stays v7 with none of the step's columns
(test_v7_migration_failure_leaves_file_unchanged).
The v6 → v7 migration. Six ALTER TABLE devices ADD COLUMN
statements with defaults (db_schema_migrate_v6_sql()) and the stamp,
in one BEGIN IMMEDIATE transaction; no v6 value changes (a v6 row's
device_class was 0..2 and stays so). Tested on a v6 file holding a
camera row (test_v6_file_migrates_additively) and on one whose last
ALTER fails, which stays v6 with none of the step's columns
(test_v6_migration_failure_leaves_file_unchanged).
The chain. src/db.c's g_steps[] lists one entry per step (from
1 through 10) and runs every one from the file's version up, each in its
own transaction with its own stamp, so a v1 file opened by this build
goes v1 → v2 → v3 → v4 → v5 → v6 → v7 → v8 → v9 → v10 → v11 in one db_open() call. A step
that fails leaves the file at the last version it fully reached — a v3
file whose next step fails is a v4 file, never half of v5
(test_v3_chain_stops_at_last_whole_step) — and db_open() refuses the
open (though the partial progress already committed stays on disk).
Each step also names the table(s) its ALTERs touch (tables[]); if
one of them was never created (a file that stopped very early), the
step skips its ALTER and only stamps, since the unconditional schema
below creates that table whole regardless of the stamped version. A
static check fails the build unless the steps run from
DB_MIGRATES_FROM to DB_SCHEMA_VERSION without a gap, so a bump
without its step does not compile.
#154 also fixed a latent bug in check_version(). It used one
variable both as "a schema_version row exists" and as "the version to
migrate from" (reusing the boolean 1 as a fake low version number when
no migration was needed). That was harmless while DB_MIGRATES_FROM was
5, because 1 < 5 ; once it dropped to 1, a file already sitting at the
current version satisfied found >= DB_MIGRATES_FROM on the strength of
the stale flag and got silently re-run through the whole chain,
failing on the first ALTER since every column already existed —
db_open() on an up-to-date file started returning 0. Fixed by tracking
the real migrate-from version (-1 when none applies) separately from
whether a row was found at all.
Upsert and not-camera. not-camera is a verdict against, not a
higher "for", so the devices upsert never lets it override the class
a row's MAC-keyed beacon bits imply (setup SSID 2, OUI 16): that history
keeps its class and the row is written cam_conflict 1, as the live
classifier would. For 0..2 the rule is the MAX it was. The other v7
columns are the latest tick's.
The v5 → v6 migration. The first migration db_open() performs, and
deliberately the only kind it will: five ALTER TABLE devices ADD COLUMN statements with defaults (db_schema_migrate_v5_sql()), plus the
version stamp, in one BEGIN IMMEDIATE transaction. No existing value
is rewritten, so a v5 forensic record reads the same afterwards; a
statement that fails rolls the whole step back and the file stays v5
(tests/test_db.c :: test_v5_migration_failure_leaves_file_unchanged).
Only a file newer than v11 is refused.
Migration path, by design (owner ruling 2026-10-21, replacing the
earlier "no migration path by design"). Every schema bump ships its
migration from the previous version in the same change, and the steps
chain, so db_open() brings a file of any supported age forward one
version at a time. A migration preserves forensic values: it adds
columns or tables with defaults, and where a change would alter what
stored data means it keeps the old column or table and adds the new one
beside it, never rewriting a recorded value in place. Each step is one
BEGIN IMMEDIATE transaction, tested on a file built at the previous
version, including the failure that leaves the file unchanged. Only a
file from a newer build is refused. src/db.c carries
a static check that the step list ends at DB_SCHEMA_VERSION, so the
next bump does not build until its step is written.
When to bump. Adding a whole new table is safe without a bump —
CREATE TABLE IF NOT EXISTS runs on every open, so an older file simply
gains it. An index is the same case: CREATE INDEX IF NOT EXISTS
runs on every open, adds an entry per row, and changes no stored value,
so idx_alerts_first_seen and idx_devices_first_seen (2026-10-26,
below) need no bump and no migration step
(tests/test_db.c :: test_current_file_gains_the_first_seen_indexes:
a current-version file without them gains both on its next open, keeps its stamp,
and every row of every table reads the same). Adding a column to an existing table is not: that
statement is a no-op on a table that already exists, and the column
never appears. v2 exists because probe_clients.presence (#53) was
added without a bump, so a v1 file failed at schema application with a
confusing SQL error instead of the clear version message — the v1 → v2
step (#154) adds the column. v3 is the one exception that proves the
rule above: assoc_reqs (#60 slice 5a) is a new table, so by this
same rule it needed no bump at all — METRICS.md row 60e records that
the bump was taken anyway, and the no-bump call was independently
confirmed three weeks later when #59's btm_requests (also new) rode
the then-current version with no bump of its own. The v2 → v3 step
(#154) therefore has no ALTER statement; it only advances the stamp,
and assoc_reqs gets created by the unconditional schema below exactly
as it would on any other version.
v4 is a deliberately batched bump. Four columns across three issues each wanted one, and each on its own was a poor trade — making every existing database refuse to open, for one field:
| Issue | Column | Table |
|---|---|---|
#60 |
phy_confirmed |
pnl_clients |
#62 |
downgrade_flags, akm_bits |
beacon_aps |
#65 |
nocert_sessions, nocert_no_hello, last_nocert_sta, last_nocert_ts |
rogue_radius |
Taken together it is one break instead of three, and it is the right
moment to take the next one too: if you are adding a column, look at
what else has been deferred first. The v3 → v4 step (#154) applies all
seven ALTERs across the three tables in one transaction: a v3 file on
which the last one fails keeps v3, none of the seven, including the two
that would have applied cleanly on their own
(test_v3_migration_failure_leaves_file_unchanged).
The consequence worth remembering when reading a slice note: #59's
btm_requests and anything else that adds only a table rides the
current version. There is also no automated guard here — a fresh file
gets every table regardless of version, so a missing bump only surfaces
when an existing older database is opened, which tests/test_db.c's
v1 → v4 migration tests now do.
v5 (#90, above) is the v4 → v5 step (#154): one ALTER TABLE karma_candidates ADD COLUMN pnl_best and the stamp. A v4 file on which
it fails (pnl_best already there) keeps v4 and its row unchanged
(test_v4_migration_failure_leaves_file_unchanged).
Keyed by natural identity, bounded by the fixed arrays in sloth.h.
| Table | Key | Notes |
|---|---|---|
devices |
mac |
synthesised profile + risk signals; camera identity since v6 (device_class, camera_vendor, camera_model, setup_mode, cam_signals — sticky only for the MAC-keyed beacon bits 2 and 16: those OR, the class they imply and setup_mode only rise, and the vendor stays while they stand; the IP-joined bits, the class they alone gave and camera_model are the latest tick's, so a reused lease does not write a camera onto another host's MAC for good — see [[camera-detection]]). An IP-only camera record (no MAC) is not written. Since v7 also cam_score, cam_evidence, cam_vetoes, cam_conflict, dhcp_prl, dhcp_vci (#155), the latest tick's; device_class 3 (not-camera) never overrides a MAC-keyed camera class |
pnl_clients / pnl_ssids |
mac / (mac, ssid) |
split so "which devices remember network X" is a join, not a scan of repeated JSON arrays — the deanonymisation question |
probe_clients |
mac |
unassociated 802.11 devices |
probe_history |
(mac, ssid, bucket) |
directed probes counted per 10-minute bucket (v23); an observation-tier table listed here beside the PNL it details, see the v23 section |
beacon_aps / beacon_ap_ssids |
bssid / (bssid, ssid) |
passive monitor inventory; the SSID child table is the KARMA signal and the multi-VAP topology record |
wifi_aps |
bssid |
nl80211 scan list — kept separate from beacon_aps because they are different observations with different trust: what we heard on the air versus what the kernel reports |
wifi_stas |
mac |
|
assocs |
(bssid, sta_mac) |
graded evidence; see the upsert rule above |
assoc_reqs |
(bssid, sta_mac) |
what the client asked for (#60) — the ask beside the grant. downgrade_flags OR-accumulates: a client recovering to strong parameters does not erase having been moved onto weak ones |
wifi_merged |
entity |
multi-radio coverage (#21) |
arp |
(ip, mac) |
|
dhcp_leases |
ip |
|
top_hosts |
ip |
byte counters keep the high-water mark, since state resets them on ring eviction |
mdns_services / nbns_names / ssdp_devices |
instance / (name, suffix) / usn |
|
ndp_ras / ndp_ra_prefixes |
src_ip / (src_ip, prefix) |
|
sensors |
(kind, iface) |
passive sensor registry (#28) |
random_devices_daily |
(day, sources) |
not an entity: the count of random addresses purged from devices (#239), never aged out |
Aggregates per endpoint pair, not per packet.
bgp_sessions, ssh_flows, rdp_flows, snmp_flows, mqtt_flows,
ldap_events, kerb_events, smb_sessions.
Keyed by episode, not by tick: an alert that persists for an hour is
one row whose count and last_seen advance, not 3600 rows. For
alerts the episode is the finding, below.
Two units, deliberately different:
- An incident (#98) is one continuous run of a dedup key in the
engine: it opens with
alert.create, carries oneincident_id, and closes with exactly onealert.resolve— afterALERT_RESOLVE_AFTER_S(300 s) with no rule re-asserting it, when the engine evicts it for room, or when its rule clears it. A key that fires again opens a new incident with a new id. Incidents are the JSONL lifecycle stream's unit ([[jsonl-schema]]), and that stream is where the gaps between them are recorded. - A finding is every incident of one key, for as long as its row is
retained. It is the
alertsrow's unit: a re-fire of the key — after an eviction, after a quiet period, or in a later process — advances the key's newest row rather than starting one.
So one row per key in steady state, and:
| Column | Meaning |
|---|---|
first_seen |
the finding's first sighting; never moved by a write |
last_seen |
MAX, as everywhere |
count |
evaluations, summed across incidents: a write of the incident already on the row adds what its count moved since the last write; a write of a different incident adds its whole count. A lower bound — see below |
reopens |
incidents after the first that this row absorbed. A lower bound — see below |
incident_id |
the latest of them — the join into the JSONL stream |
incident_count |
that incident's own count as last written, so count never double-counts the one still open |
incident_first_seen |
that incident's start (the engine's first_detected). first_seen..last_seen covers every incident and the quiet gaps between them, so "was it firing at t" reads this column: slothweb's History range reads (/api/history/alerts, the deauth episodes) overlap [COALESCE(incident_first_seen, first_seen), last_seen] |
sev |
the peak across the row's writes, as the compactor folds it. Latest-wins let a LOW reopen leave a CRIT finding reading LOW with the CRIT in no row of the file |
detail |
the latest write at that peak severity (a tie takes the new one, so a steady finding shows its current evidence) |
type, title, technique, match_ip, match_port |
the first write's |
How it holds: the engine keeps a key's first_seen across every reopen
in its side table (alert_side_t, #112 — before #170 only across an
eviction), and the writer looks up the key's newest row
(ST_ALERT_ROW, a seek on the primary key's prefix) and writes to that
first_seen whatever the engine says. The second is the guarantee: the
side table is 512 rows LRU and dies with the process, and the owner's
sensor had 7,598 keys. tests/test_db.c :: test_alert_evict_refire_churn_is_one_row evicts and re-fires one key
100 times under enough key pressure that the side table forgets it each
time, and gets one row with reopens 100;
test_alert_finding_outlives_a_restart does it across a close and
reopen; test_alert_reopen_keeps_peak_sev reopens a CRIT incident at
LOW.
count and reopens are lower bounds, sampled at writes. The
writer sees the engine's live alerts once per --db write (each tick,
or every --db-interval-secs). An incident that opens and closes
between two writes — resolved, evicted under pressure, or displaced —
is never on the row, so it adds nothing to either. They are exact when
every incident outlives a write interval, and fall further behind under
eviction churn and with a longer interval. The JSONL stream's
reopen_count on alert.* is the engine's own count from its side
table: it sees every incident, but restarts at 0 when the 512-row side
table forgets the key or the process restarts, while reopens
persists across both. Neither is derived from the other; for an exact
incident history, count alert.create records in the JSONL stream, or
(since v11) read alert_incidents, below, which the engine's hook
fills whatever the write interval.
Why not one row per (key, incident): the owner's v6 file held
867,748 rows for 7,598 keys. Its rate fell from about 130,000 rows a
day to about 2,500 on 2026-10-21, the eviction churn #112 addressed; of
the 12,317 rows written from 2026-10-22 to 10-26, 9,704 were a known key
back after a gap longer than the 300 s resolve period (most of them
five minutes to an hour) — the reopens a per-incident row would keep
producing forever. The gap the old per-episode row
showed is not lost when the sensor also writes the JSONL stream (-o):
it is there, as alert.resolve and the next alert.create. Since v11
a --db-only sensor keeps them too, in alert_incidents beside the
row, bounded per key (below), and the alerts row stays one per
finding. Retention still applies: a key whose row ages out of
the finding tier (12× --db-retain-days) and fires again starts a new
row.
The finding lifecycle (#245, v21). Every incident carries its
state ([[alerts]] § Finding lifecycle): preliminary, confirmed,
withdrawn or lapsed, NULL on rows an earlier
build wrote and on those a build before JSONL 2.21.0 wrote under
--no-preliminary, with prelim_at and confirmed_at on an incident
that began preliminary and withdraw_why beside withdrawn. A
preliminary incident is an alert_incidents row from its first record
(the hook sees it open) but not an alerts row: that table holds
findings, and first evidence is not one until it is confirmed; a
withdrawn incident never becomes one. The upsert keeps the columns
order-free: state is the latest write's except that withdrawn stays
(the incident is closed), and the two times and the why are set once.
lapsed is written by the tick's snapshot (the hook is not called for
it). The withdrawal rate per kind is COUNT(*) FILTER (WHERE state='withdrawn') over the rows with a prelim_at.
The alerts row's sev is the finding's peak and its count the sum
across incidents. That is right for the finding and wrong for "how bad
was it in this window": a key CRIT once and LOW since read CRIT in
every History range. alert_incidents keeps each incident's own
figures, and the alerts row is left exactly as above (a contract:
the alert list, the alert page's count and sev, and every recipe
read it).
| Column | Meaning |
|---|---|
key, incident_id |
the primary key: the alerts key, and the engine's id for the incident (the JSONL stream's incident_id). The id hashes the key, the wall second the incident opened and a per-process sequence number, so two runs' incidents of one key share a row only if both opened in the same second at the same sequence number (a clock set back across a restart) |
type |
the alert type |
first_seen |
the incident's own start, the engine's first_detected (the alerts row's incident_first_seen while it is the latest) |
last_seen |
its last evaluation, MAX |
sev |
its severity as last written |
peak_sev |
the highest it reached, including a rise and fall between two writes |
count |
its evaluations (the engine's count), MAX |
observations |
its evidence changes (the engine's observations, [[jsonl-schema]]), MAX |
closed_at, reason |
its alert.resolve: the wall time and the reason (expired, evicted, cleared or a rule's own). NULL while open, and NULL for an incident whose close the file never saw (a sensor stopped mid-incident) |
complete, complete_why |
v19 (#246, [[coverage-assessment]] § 9): full or partial, and beside partial its word (source_down, source_stale, suppressed, drops, hop). Once partial, the row stays partial with the word first written. NULL while not assessed (a --replay, an incident an earlier build wrote) |
latency_ms |
v19: the oldest cited frame to the incident's opening, ms; the first value written is kept. NULL when unknown, never 0 |
corroboration |
v19: the monitor radios that delivered a cited frame, the highest written. NULL with no cited frame held |
src_state |
v19: ok, stale or down, the rule's input at the last write that knew it; a NULL does not clear it |
No detail column: the finding's evidence is on the alerts row.
How it is written. Two ways, so nothing the engine does between two
writes is lost. Every --db write upserts each incident the engine's
snapshot holds, as the alerts row is written. And the engine calls a
lifecycle hook (alerts_set_incident_hook() in src/alerts.h, set by
db_open(), cleared by db_close()) as an incident opens, each time
its severity moves, and as it closes; the writer queues those per
incident and drains the queue at the start of its next write. That is
what reaches what a snapshot cannot: the close and its reason, a peak
reached and left between two writes, and an incident evicted inside one
alerts_update(), whose slot is reused before any snapshot shows it
closed. A queue that fills between writes (256 incidents: an eviction
storm under a long --db-interval-secs) is written there and then in
its own transaction, and db_close() writes what is left, so a sensor
stopped right after a close still records it. So unlike the alerts
row's count and reopens, which are sampled at writes, this table
has every incident the run had while the file was open.
Bounded per key. A key keeps its newest DB_INCIDENTS_PER_KEY
(256, src/db.h) incidents by start, the oldest deleted as the writer
records a new incident of the key: an evicted key re-fires as a new
incident every tick, which unbounded would be #170's growth one table
over. The table rides the finding tier's retention (12×
--db-retain-days) like alerts; the size guard never touches it. The
bound drops per-incident detail only: the alerts row still holds the
finding.
Who reads it. slothweb's History (/api/history/alerts) lists a key
whose incidents overlap the range with the highest peak_sev, the sum
of count and the number of incidents among those in the range, so a
range holding only a LOW incident reads LOW; a key with no incident rows
(an incident recorded before v11, or past the bound) is read from its
alerts row as before. The alert page (/api/alert) builds its runs
from the incidents and carries one incident's figures as db_incident
([[slothweb]]). sloth's own offline exports read it too, read-only
(src/site_db.c, [[handoff]]): --handoff lists the open incidents and
counts the closed ones by type and peak_sev; --interference-report
(and the packet's interference.md) reads the RF_DEGRADED,
RTS_FLOOD and GNSS_JAMMING rows' times, reason, count and
observations, parses the channel or transmitter out of key and the
figures out of the matching alerts.detail (by the rule's own format:
a change to rule_rf_degraded()'s, rule_rts_flood()'s or
rule_gnss_jamming()'s detail text is a change to this reader), and
reads beacon_aps (channel, has_qbss, qbss_chan_util) and
assocs over the episode.
Tests (tests/test_db.c): test_incident_rows_keep_each_incidents_figures
(the issue's case through the engine: one alerts row reading CRIT, two
incident rows, the first's peak CRIT and close expired, the second
LOW), test_incident_peak_between_ticks_is_kept,
test_incident_evicted_between_ticks_is_recorded (the hook's queue,
and its flush when full), test_incident_rows_bounded_per_key and
test_incident_close_is_flushed_on_db_close.
The migration never rewrites a recorded value, so the duplicates a pre-#170 build wrote stay in the file. Folding them is an explicit, offline copy the operator runs and then decides what to do with:
sloth --db-compact-alerts data/sloth.db data/sloth-compact.db- SRC is opened immutable (
file:SRC?mode=ro&immutable=1) and nothing is written to it or beside it — not even the-shmand empty-wala plain read-only open of a WAL-mode file creates and leaves. The test holds SRC byte-identical and its side files absent. - A non-empty
SRC-walorSRC-journalrefuses the command: it is what a sensor that was killed rather than stopped leaves, its last writes not yet in the main file. A copy of the main file would miss them, and the swap below would put the copy under that old-wal, which SQLite then replays onto pages it never belonged to — a corrupt file (malformed database schema … orphan index, reproduced on #170's review). Checkpoint first: start and stop the sensor cleanly, orsqlite3 SRC 'PRAGMA wal_checkpoint(TRUNCATE)'as the file's owner. - DST must not exist — nor
DST-wal,-shmor-journal, which SQLite would replay into the copy. It is created0600, filled withVACUUM INTO, migrated to this build's schema, compacted in one transaction andVACUUMed. A failure removes it. - One row per key: MIN
first_seen, MAXlast_seen, summedcount, peaksevwith thedetailof the most recent row at that peak,reopens= rows − 1 (plus anyreopensa v8 row carried), and the most recent row'stitle,type,technique,match_*, incident join and incident start (incident_first_seen, or a v7 row'sfirst_seen). Peak rather than latest severity because a folded row stands for many incidents and the worst of them is what an investigator asks for first — the live writer's rule too, so a compacted row and a live one mean the same thing. - Prints the counts and the time, and exits. Every other table is copied as it was.
- Run as root (reading a
0600file owned by theslothaccount usually means sudo), DST is handed to SRC's owner and group. The sensor opens--dbafter dropping to its--useraccount, anddb_open()refuses a file owned by anyone else, so a root-owned copy swapped in would stop it starting.sudo -u sloth sloth --db-compact-alerts …does the same without root writing anything.
On a copy of the owner's 254 MB snapshot (2026-10-26): 867,748 rows for
7,598 keys → 7,598 rows, file 245 MB → 13.7 MB, 17 s, source checksum
unchanged. A generated 900,000-row v7 table compacts in 3.5–7 s on the same host
(test_compact_alerts_900k_rows prints its timing). Swapping the
compacted file in is the owner's call, and the original is the backup:
- stop the sensor;
- confirm
SRC-walandSRC-shmare absent (or the-walempty) — the command refused a non-empty one, but a sensor started between the compaction and the swap writes a new one; - move SRC aside as the backup, then DST over
--db's path; - check the owner (
stat -c %U) is the sensor's--useraccount; - start the sensor.
test_compact_refuses_an_uncheckpointed_src holds the refusal, then
checkpoints, compacts, swaps and reopens.
alerts, cleartext_creds, eapol_events, deauth_events,
seqnum_correlations, twin_episodes, scan_entries /
scan_entry_ports.
Indexes on time. alerts and devices are indexed on both
last_seen (what is still here, retention) and, since 2026-10-26,
first_seen (what arrived when: slothweb's History strip counts rows
per first_seen cell, and without the index each count was a scan —
253 ms for 867,748 alert episodes on the owner's snapshot, past
slothweb's 250 ms budget). The one-time build runs in db_open() on the
first open of an older file, before capture starts, so it is that
start's delay. Measured on a desktop with the file on tmpfs: for
867,748 alerts (that snapshot, a WAL copy) about 0.65 s of CPU, and
0.93–1.85 s wall on the same host under load (load average 9–17, other
builds running). The 276 ms first quoted here was not reproduced: the
CPU time alone is over twice it. 1,000,000 generated alerts: 280 ms
idle, as first quoted. File 245.4 → 257.1 MB (+4.8 %) on the snapshot,
194.8 → 208.3 MB (+6.9 %) generated. The devices index on 32,000 rows:
6–7 ms idle, 20–60 ms loaded. So a ~1M-row file delays sloth's start
by roughly 1–2 s on a desktop, once; a Raspberry Pi on an SD card was
not measured and is likely several seconds. A reader in WAL mode (a
slothweb beside it) is not blocked by the build, and a reopen with the
indexes present costs microseconds.
An episode's first_seen never changes on its upsert, so after that
the index costs one entry per new episode, nothing per tick.
scan_entries is flagged-only (#41): an unflagged entry is one host
touching a couple of ports — ordinary traffic — and persisting it would
put the CDN false positives #41 removed back into the durable record.
karma_candidates (#30), rogue_radius (#31) and btm_requests (#59).
The first two closed a real hole: neither struct had a jsonl_emit_* at
all, so the alert survived while the reasoning behind it — SSID/PNL
overlap, Jaccard, IE uniformity, deauth chain, offered EAP methods,
identity leaks — was TUI-only and gone on exit. 96 rows maximum.
btm_requests records every 802.11v steer, forcing or not, keyed by
(bssid, sta_mac). Storing only the alerting subset would leave no
baseline: ordinary load balancing and a forced roam are the same frame,
separated by one bit and a rate. Counters upsert with MAX rather than
excluded, because the in-memory table is LRU-evicted and a pair that
ages out and returns restarts at 1 — taking the fresh value would erase
the steering that justified an alert still sitting in alerts.
sessions records one row per run — started, ended, and the
--site-label if given. It exists so a returning surveyor can ask what
is new since last time.
The data for that was already present: first_seen is MIN-ed across
every upsert, so an entity seen on a previous visit keeps its original
timestamp and only genuinely new ones fall inside the current window.
The session boundary is the only thing that was missing.
--report grows a New since last survey section listing new APs,
devices and probe clients. A session that never recorded an end (crash,
kill -9) falls back to its own start rather than reading as "no
previous visit", which would flood the next report with the whole site.
# what arrived between the last two visits, by hand
sqlite3 sloth.db "
SELECT mac, vendor, datetime(first_seen,'unixepoch') FROM devices
WHERE first_seen >= (SELECT COALESCE(ended,started) FROM sessions
ORDER BY started DESC LIMIT 1 OFFSET 1)
ORDER BY first_seen DESC;"--db-retain-days N (default 30) sets the window for observation
rows. Entities keep 3×, findings keep 12×.
| Tier | Window | Contents |
|---|---|---|
| observation | 1× | protocol flows, deauths, twins, EAPOL, scans, seqnum correlations, device_positions, sensor_positions, gnss_fixes, gnss_sightings, adsb_sightings, aprs_packets, victron_readings, coverage_intervals, question_status, probe_history |
| entity | 3× | devices, PNL, beacons, assocs, ARP, leases, discovery, sensors, adsb_aircraft, aprs_stations, victron_devices |
| finding | 12× | alerts, alert_incidents, cleartext_creds, karma_candidates, rogue_radius, btm_requests |
The ordering is what an investigator reaches for months later: what fired outlives who was here, which outlives the individual observations that established it. A single uniform window would drop all three together and lose the alert that made the file worth keeping.
Detector evidence sits in the finding tier deliberately. At 3× it would expire while the CRIT it justifies was still retained at 12× — recreating the #30/#31 hole through retention rather than through a missing emitter.
Everything does eventually age out. Findings keep twelve times longer, not forever.
--db-max-mb N (default 512, 0 = unlimited) is a pruning trigger, not
a cap. On breach the oldest observation rows go first — entity,
alert, credential and detector-evidence rows are never dropped by this
guard. A sensor that fills its disk should lose telemetry, not the
findings the disk was being kept for. If pruning every eligible row
still leaves the file over target, that is reported once and the file is
allowed to exceed it: discarding evidence to satisfy a number is the
worse failure. The guard is also bounded at 64 pruning rounds per pass
and measures only the main database file, not -wal/-shm.
Maintenance runs hourly, after the write, so a pruning stall never
delays the observation that triggered it — which also means it runs
only while sloth is running, and the first pass is an hour after the
first write. Age-out is last_seen < cutoff, so a row that keeps being
refreshed never expires.
Random addresses (#239). A locally administered address last heard
more than 7 days ago, heard for no longer than
retention.random_repeat_s (default 600 s) and grouped with no SSID
is purged from devices (with its probe_clients, pnl_clients,
pnl_ssids, device_positions and wifi_merged rows) and counted
into random_devices_daily, in bounded batches. The full test and the
batching are [[retention]] § 2b.
The hourly maintenance runs PRAGMA analysis_limit=400; PRAGMA optimize=0x10002; on sloth's connection, outside any transaction and
after the retention and ceiling passes (db_optimize() in
src/db.c); on a library older than 3.46, which ignores the 0x10000
"every table" bit, a file still without sqlite_stat1 afterwards gets
one ANALYZE under the same limit. A failure there costs the
statistics only: the sink keeps writing and the planner works without
them, as before. Without sqlite_stat1 SQLite picks between indexes on
fixed assumptions.
What sqlite_stat1 holds. One row per index: tbl and idx, the
table's and the index's names, and stat, integers (the row count, then
the average rows per distinct key prefix). No value from any row. With
analysis_limit set SQLite collects no sqlite_stat4 samples (those
would be index keys: MACs, SSIDs, IPs); measured on the sensor A copy
(Debian's library has ENABLE_STAT4): sqlite_stat4 absent, 65
sqlite_stat1 rows. tests/test_db.c :: test_maintenance_writes_planner_statistics holds both: every stat is
digits and spaces, and sqlite_stat4 is absent or empty. The
dashboard's SQL box refuses sqlite_stat3 and sqlite_stat4 regardless.
Cost, measured on a copy of the sensor A file (2026-11-20, 486 MiB,
87,224 devices, NVMe): the first run, with no statistics, 49 ms; a
run after it with nothing changed, under a millisecond. 65 rows, a few
pages written. Not measured on the SD-card host (the live sensor is not
touched for a measurement); the limit bounds the read per index to
about 400 rows whatever the table size. The issue's measurement: on
the same copy ANALYZE takes Hybrid's signal sort from 81 to 20 ms
and does not fix the dashboard's Monitor-scope timeouts
(sloth-mesh#13).
Retention is an investigative tradeoff, not a deletion guarantee, it covers nothing outside this file, and row deletion is not secure erasure. [[retention]] states exactly what is and is not covered — read that before citing sloth in a data-handling document.
auto_vacuumcaveat.PRAGMA auto_vacuum=INCREMENTALis requested at open, but SQLite only honours it on a newly created file — it cannot be changed on an existing database without a fullVACUUM. A database created before that pragma landed reuses freed pages instead of returning them: the file stops growing, but will not shrink.sqlite3 sloth.db VACUUM;once, offline, if you need the space back.
Enforced by tests/test_db.c, not by convention — a future column that
violates one turns the suite red.
- No column can hold secret material. No column named for a secret
may be TEXT or BLOB. Checked against the live schema via
pragma_table_info, so it covers tables added later. - No column is named for a secret, whatever its type — no
password,passwd,pmkid,anonce,snonce,mic. - The bytes are not there. A test seeds an EAPOL event carrying
recognisable material in
pmkid/anonce/snonce/mic, ticks, then scans the raw database file and asserts none of it appears — with a string we do persist as a positive control, so a pass means "absent" rather than "the scan is broken". A schema assertion cannot catch a leak through a future column, an index, or a stray bind.
The distinction the schema draws is identifier versus secret:
- Kept — usernames and identifiers that crossed the wire in the
clear:
cleartext_creds.username, RDP mstshash cookies, MQTT usernames, leaked EAP identities, SSH server banners. That is the exposure fact, which is the finding. - Kept as flags —
pw_observed,has_pmkid. 0/1, named to match the JSONL fields exactly. They record that an exposure was observed. - Never kept — the secrets themselves. PMKID / ANonce / SNonce / MIC
stay in the
--eapol-dirhashcat file the operator explicitly asked for. SNMP community strings are not persisted either, in any form: a v1/v2c community string is a shared secret, so it gets the same treatment as a PMKID. The distinct community count is kept, which is whatSNMP_COMMUNITY_BRUTEkeys on.
Note the SNMP case deviates from the wire format on purpose:
jsonl.cdoes emitlast_community. A stream the operator chose to write is not the same artifact as a database accumulating for months — the same distinction #42 drew for--eapol-dir.
These are also slothweb's SQL box recipes ([[slothweb]], M5): its build
extracts every quoted statement below as written, and stops on a
sqlite3 line written any other way. The box withholds
credential-bearing columns from the browser, so it refuses the two
recipes that read one (alerts.detail, cleartext_creds.username),
and dbstat too (a table's payload less its readable columns is the
withheld one's length), so the space recipe is refused as well; run
those three here.
# Which devices remember a given network? (the deanonymisation question)
sqlite3 sloth.db "SELECT mac, first_seen, last_seen FROM pnl_ssids
WHERE ssid='CorpWiFi' ORDER BY last_seen DESC;"
# Probes for a network ten minutes at a time, the last 24 hours, by device
sqlite3 sloth.db "SELECT datetime(bucket,'unixepoch'), mac, count
FROM probe_history WHERE ssid='CorpWiFi'
AND bucket >= strftime('%s','now') - 86400
ORDER BY bucket, mac;"
# Who was here between 02:00 and 04:00?
sqlite3 sloth.db "SELECT mac, vendor, hostname FROM devices
WHERE last_seen >= strftime('%s','2026-07-28 02:00:00')
AND first_seen <= strftime('%s','2026-07-28 04:00:00');"
# Findings by severity, most recent first
sqlite3 sloth.db "SELECT datetime(last_seen,'unixepoch'), title, sev, detail
FROM alerts ORDER BY sev DESC, last_seen DESC LIMIT 20;"
# Every AP that ever advertised more than one SSID (KARMA / multi-VAP)
sqlite3 sloth.db "SELECT bssid, COUNT(*) n FROM beacon_ap_ssids
GROUP BY bssid HAVING n > 1 ORDER BY n DESC;"
# A Pineapple candidate with the evidence behind it
sqlite3 sloth.db "SELECT bssid, score, ssid_count, pnl_overlap,
pnl_jaccard_ppm, ie_uniform, deauth_chain
FROM karma_candidates ORDER BY score DESC;"
# Cleartext credential exposures (usernames only, by design)
sqlite3 sloth.db "SELECT datetime(ts,'unixepoch'), src, dst, protocol,
username, pw_observed FROM cleartext_creds;"
# What is actually taking the space?
sqlite3 sloth.db "SELECT name, SUM(pgsize) b FROM dbstat
GROUP BY name ORDER BY b DESC LIMIT 10;"- [[jsonl-schema]] — the wire format, and the change-only emission this complements.
- [[log]] — doc-change record.
- [[alerts]] — what populates the
alertstable. - [[pcap-export]] — where packet-level evidence lives instead.
- [[retention]] — the tiers in full, and
alert_incidents' per-key bound. - [[slothweb]] — History and the alert page, the readers of
alert_incidents.