Skip to content

Latest commit

 

History

History
344 lines (264 loc) · 17.1 KB

ENGINEERING.md

File metadata and controls

344 lines (264 loc) · 17.1 KB

EdgeTable — engineering notes

Internal companion to the README. Everything here is a decision that cost something to learn: the measurements behind the tuning, and the rules a change must not quietly break.

Measured extension behaviour lives in FINDINGS.md; the build plan and demo script in plan.md.

Layout

core/         edgetable-core -- the whole engine, no UI dependency
  db.rs         two connections, two models, the teardown order that avoids a segfault
  schema.rs     schema, GBNF grammar, labelling prompt, enrichment trigger
  rows.rs       list / insert / bulk insert / edit / the two clears
  enrich.rs     backfill workers (text on GEN, embeddings on EMB)
  search.rs     semantic and keyword, same return shape
  sync.rs       SQLite Cloud, plus the offline device-to-device payload path
  fields.rs     the data-driven column list behind the "+" menu
  paths.rs      where extensions and models are resolved from
  bin/selftest  the engine end to end, against real models
  bin/synccheck one sync from a throwaway database
src-tauri/    the desktop shell
  lib.rs        the Tauri commands -- thin wrappers, all behaviour lives in core
src/          the webview
  App.tsx       toolbar, sidebar, filters, the "+" field menu, backfill loop
  Grid.tsx      Glide Data Grid: pills, shimmer cells, inline edit
  api.ts        every invoke() call, typed, in one place
examples/     seed data, the runnable search example, the Phase 0 spike

Prerequisites and pinning

make install fills vendor/ from extensions.lock (extensions) and Hugging Face (models). Prebuilt releases rather than source checkouts: sqlite-ai carries llama.cpp/GGML, so building it means CMake and minutes, for a repo meant to be cloned and run. The release archives contain exactly ai.dylib, vector.dylib and cloudsync.dylib — the names paths.rs looks for.

The pin is not ceremony. Before extensions.lock existed the app resolved extensions from sibling working copies and had been running for weeks against builds two releases behind what was published (vector 1.0.0 against 1.1.0, cloudsync 1.1.0 against 1.1.2), with nobody the wiser.

Working on an extension? Point the app at your own build instead — the overrides win over vendor/, so a source checkout and a pinned release coexist: EDGETABLE_AI_EXT, EDGETABLE_VECTOR_EXT, EDGETABLE_SYNC_EXT, EDGETABLE_GEN_MODEL, EDGETABLE_EMBED_MODEL (extension paths take no suffix).

Build size

target/ is gitignored and never pushed — a push of this repository is 52 files and about 600 KB — but it is worth keeping in hand locally, because a default cargo build of the Tauri app produces 2.2 GB, most of it DWARF for dependencies nobody steps through (Tauri's tree is ~500 crates and rusqlite compiles SQLite itself). Left to accumulate across dev and release builds it reached 3.7 GB here.

Cargo.toml therefore sets debug = "line-tables-only" for our own code and debug = false for dependencies. Measured, same clean build each time:

dev profile target/ build
default 2.2 GB 46.2 s
line-tables-only, deps none 1.3 GB 43.6 s
no debug info at all 1.2 GB 43.0 s

The last row is why the middle one is the setting: dropping symbols entirely buys another 100 MB and costs every backtrace its file and line numbers. What line-tables-only gives up is variable inspection in a debugger, in dev builds — comment it out and rebuild for a session that needs it.

cargo clean recovers the lot; a full rebuild is about 45 s.

Tests

make test       # clippy + tsc + the UI suite. No models, no network.
make selftest   # the engine end to end. Real models, ~1 min.
make synccheck  # one sync from a throwaway database. Pull-only.
make spike      # the Phase 0 harness; the only thing that scores label accuracy.

make test needs a browser the first time: npx playwright install chromium. It is cached per machine, and it is a test-only dependency — running the app does not need it.

make with no target lists the user-facing commands. prereqs, check and device-b still work as aliases for install-without-npm, test and run-second.

The UI suite exists because the engine selftest covers Rust exhaustively and the UI not at all — which is precisely where every user-visible bug in this project came from. Playwright drives the real App, Grid, api.ts and glide, stubbing only the Tauri boundary (tests/fake-tauri.ts). Glide draws to a canvas, so assertions are on behaviour — what the UI asked the backend to do — not on DOM.

Regression-tested the hard way, each after shipping broken: a missing <div id="portal"> (editors could never open, silently), rowMarkers reverting to "number" (row delete dead), a toast in the layout flow (every click target moved 28 px), a sync that fetched rows and left the grid saying "No rows yet", seeding that never labelled an already-visible ✨ column, and an unbounded settle loop.

The fake must lie as little as possible. It JSON round-trips its results, because returning live arrays let React skip re-renders and hid a real bug; and it withholds labels from seeded rows, because seeding really does insert them unlabelled.

beforeEach waits 120 ms after the grid appears. There is no DOM signal for glide readiness — the canvas is present and fully sized while clicks are still dropped — and a click probe changed what the editor tests were testing.

The engine

One model per connection, and replacing it fails silently. llm_model_load() frees whatever that connection had, and the displaced model does not error — it returns ''. Hence two connections and a Role fixed at open time: GEN holds Qwen3-1.7B, EMB holds all-MiniLM. Reads go through EMB so a ~1 s generation never blocks a repaint.

Close connections oldest first. sqlite-ai registers a process-global llama log callback bound to one connection's context. Close the youngest while another is still using llama and the next log line runs through freed memory and segfaults. Engine::shutdown frees in open order; embed is opened last so it dies last.

cloudsync_init and vector_init are per-connection. Both are idempotent, so every connection runs both for every table. Skipping cloudsync_init makes writes fail with Unable to retrieve table name feedback in cloudsync_update, which reads like corruption and is not.

Quitting must free the models. NSApplication terminate: calls exit(), which runs atexit handlers without unwinding, so no Rust Drop fires, no model is freed, and GGML asserts its Metal resource sets are empty — aborting after the user clicked Quit. Freed from Tauri's RunEvent::Exit instead. A/B verified: exit 0 with the hook, SIGABRT without.

PRAGMA trusted_schema = ON is required, or SQLite refuses to run sqlite-ai's functions from inside a trigger.

Changing the prompt or the model

The category labels are on screen for the whole demo, and the grammar guarantees they are valid, not right. Qwen3-1.7B with the ordered precedence rules scores 92% against hand labels; Qwen3-0.6B scores 58% with every prompt tried, at no latency saving.

schema.rs holds the grammar and the prompt. After touching either, run make spike — it scores against hand labels in examples/spike.py and fails below 85%.

Sync

Manual only, and the app starts empty. A timer is wrong for a stage tool: beat 1 asks an audience to watch the network stay silent, and a timer makes a reset non-local — a fresh seed would push 24 new rows to the cloud 30 seconds later, every rehearsal. This deliberately overrides §4 of the plan.

Credentials

Resolution order is environment, then the device's settings table. That is dotenvy's own rule extended one step — a real environment variable beats .env — and it keeps a machine configured from a checkout authoritative while letting a script point elsewhere for one run.

Four decisions worth keeping:

  • The settings table must never be registered with cloudsync. It would change the schema hash and break sync against the server, and it would push an API key to the cloud. It is in LOCAL_ONLY_TABLES, which un-registers it on open — the same discipline fields already needed.
  • Validate before storing. save_credentials runs cloudsync_network_status() first and persists nothing if it fails. A bad key stored silently becomes a permanent Offline that a restart cannot clear, and looks exactly like a broken app.
  • Apply live. cloud_configured is an AtomicBool so saving attaches the credentials and flips the chip without a relaunch. A settings form that still needed a restart would have bought almost nothing.
  • Show which source is in force. The panel names it — "from the environment (.env)" or "saved on this device" — because the day an env var silently shadows what someone typed into the box is a day nobody can explain otherwise.

Entry point is the chip itself when it reads Local only, plus a ⚙ beside it. Deliberately not a dialog at startup: opening silently with no account is the first thing the demo claims, and a credentials prompt would step on it.

The key is stored in plain text in the database file. The correct home is the OS keychain; the reason it is not there is that a keychain prompt appearing mid-demo is a worse failure than a plaintext key on a demo laptop. "Forget" deletes the row.

A second device on one machine

EDGETABLE_DB overrides the database path, and that is all a second device needs: the site id lives in the database, not in the app, so two files are two devices. Verified — two instances side by side reported different site ids. Without the override a second window would open the same file as the first and there would be nothing to demonstrate.

The window title carries the file stem when the variable is set, because two identical windows are impossible to narrate.

The enrichment trigger is switched off while changes are applied

sqlite-sync writes an incoming row column by column and re-enters AFTER INSERT on each write. The trigger's NEW.summary IS NULL guard cannot stop it: on the write carrying body, the summary has not landed yet. So every arriving row was inferred locally, several times over, and the results overwritten by the values already on their way. Measured on a 24-row first sync, same moment, same call:

one press
trigger live 101.3 s
trigger dropped 4.6 s

Identical results either way. Rows that genuinely arrive unlabelled (from a device with no model) keep NULL AI columns, which is exactly what the backfill worker looks for, and the app runs a pass after every sync.

Note this contradicts the Phase 0 spike's own verdict line, which measured a single-statement payload_apply — where the guard does hold.

One press is patient about the pull, in proportion to the ask

cloudsync_network_sync() with no arguments is (wait_ms: 100, max_retries: 1) — one shot at the check endpoint. The service prepares the download asynchronously and answers "nothing ready yet" until it has, so one shot routinely comes back empty: three fresh devices needed 2, 3 and 2 presses before any row arrived. There is a 2-argument overload, and it is the one to call.

A check costs about 1.17 s when it comes back empty, so the budget follows what the press is for:

this device the press means checks
no rows "give me everything" — the snapshot must be built 8
unsent changes "send this" — the pull is incidental 1
up to date "any news?" — the only press patience helps 4

The middle row matters as much as the first: waiting out empty checks after an edit made the commonest action feel broken, for a pull nobody asked for. Patience is nearly free where it helps, because the loop returns the moment anything arrives.

Measured end to end: a first sync lands every row in 2.8–4.9 s on one press.

Nothing in sqlite-sync sets a network timeout, so a request falls back to the platform default; the service itself measured between 3 s and 71 s across one day.

A failed sync is retried once before reporting Offline. The upload is two hops — ask for a URL, then PUT to it — and the second failed twice in about ten pushes, each time succeeding immediately afterwards from an unchanged database.

Counting unsent work

cloudsync_changes is a shared log, not an outbox. It holds every change the database knows about, each tagged with the site that made it, and only site_id = cloudsync_siteid() is ours to send. Counting the rest made a device that had just pulled 188 rows report 188 rows waiting to go up, with no way to clear it. The query now uses the same pair of filters the extension uses to build the payload.

The count is rows, not entries: the log is column-granular and one deleted row can register 217 entries.

cloudsync_network_has_unsent_changes() makes a network call despite its name; the local count is used instead.

The two clears

Delete all rows is an ordinary DELETE: tombstones propagate.

Clear this device drops the sync metadata first, so the deletes leave nothing to push, re-enables sync, and rewinds the receive watermark. Verified in the selftest: one row delete queues 217 changes, clearing the device queues zero.

It is a bigger hammer than it looks. feedback is the only synced table, so cleaning it up is cleaning up the last one, and sqlite-sync treats that as leaving the network: it drops cloudsync_settings and resets the site id. The device rejoins as a stranger, pushing again from version 1 — which works, because version ranges are tracked per site. The selftest asserts the identity really does change, because nothing else documents it.

Never reset send_dbversion by hand. Re-claiming a version range the server already holds for your site earns a 409 already_exists, which surfaces as a permanent "Offline". cloudsync_network_reset_sync_version() resets all four watermarks, not just the receive pair its name suggests.

The server-side schema

Only the column name, its position, its type affinity and whether it is the primary key feed the schema hash — NOT NULL, DEFAULT, formatting and case do not. Get the column list and order right and it will match; a mismatch reads Cannot apply the received payload because the schema hash is unknown <hash>.

Keep the constraints anyway: CRDT merges arrive column by column, so a NOT NULL column with no DEFAULT has nothing to hold the row together mid-merge, and cloudsync_init refuses such a table locally.

fields is deliberately not synced — column visibility is per-device. A database created before that decision is un-registered on open, because a stale registration would still feed the hash.

Setup is one-time: adding an AI field reveals an existing column rather than running ALTER TABLE, so the hash never moves. If field-adding ever becomes a real ALTER, it turns into cloudsync_alter_apply() + cloudsync_network_migration_upload() and needs a schema-capable API key.

Because embedding is a synced column, a second device receives vectors with the rows and can search immediately. Verified live: a bare sqlite3 holding only cloudsync — no model, no sqlite-ai — pulled 26 rows with every AI value populated and every embedding intact at 1536 bytes.

"syncing" is not "synced". A push returns {"send":{"status":"syncing"…}} while the server settles it, and a peer syncing in that window receives nothing. Do not script two devices back to back on stage.

Semantic search

Vector search is top-k ranking, not matching: every row has a distance, so it always returns something. A k near the row count degenerates into re-sorting the table — which is what a default of 25 did to a 26-row demo. k is 8.

The cutoff slider filters hits already on screen, so it re-filters with no second call to the model. Distances are not calibrated across queries: a question the corpus cannot answer ("shipping and delivery times") scores 0.807 at best, while "someone is about to churn" scores 0.824 and returns good rows. Hence: exploration knob, off by default.

Embeddings are built for every row at startup, not when an AI field is revealed. They are an index, not an AI column; wiring them to the ✨ menu left a freshly seeded database with an empty index and search silently returning nothing.

UI rules

Nothing may shift under the cursor. Transient messages are bottom-left toasts overlaying the grid, never bars above it: as a bar, "Added 3 rows" pushed every row down 28 px and turned a click on row 1 into a click on the header. The same rule put the cutoff slider before the hit readout rather than after it.

Filters stay disabled until they can do something. Offered before their ✨ column has values, they silently empty the grid — every unenriched row holds NULL and matches nothing.

A new row takes the cursor with it. Rows are newest-first, so onRowAppended returns "top"; glide's default selects the last row, which parked the highlight on the oldest row at the bottom.

Unsent work outranks "Synced" in the chip. A chip reading "Synced · 12s ago" while rows sit undelivered is the most misleading thing the app could say.