@lunora/cli 1.0.0-alpha.362 → 1.0.0-alpha.363

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,212 +1,185 @@
1
1
  ---
2
2
  name: lunora-performance-audit
3
- description: Diagnoses and fixes Lunora performance problems — full-table scans, missing
4
- indexes, OCC write conflicts, oversized subscriptions, and sharding/`.global()`
5
- scaling. Use when queries are slow, mutations conflict, `lunora insights`
6
- reports a hot-spot, or `@lunora/advisor` flags a table.
3
+ description: Diagnoses and fixes Lunora performance problems — full-table scans and missing indexes, expensive `ctx.db.related` traversals, OCC write conflicts (409 `CONFLICT`), live queries that re-run too often, hot shards, and choosing `.shardBy(key)` or `.global()` to scale. Starts from measured signal (`lunora insights`) and static signal (`lunora advisor`, `@lunora/advisor` lints such as `filter_without_index`, `unbounded_collect`, `unindexed_foreign_key`, `hot_shard`). Use when the user says a query or page is slow, mutations fail with conflicts under load, subscriptions are chatty, asks to "audit performance", "add the right index", or "should I shard this table", or when the Studio Advisors tab or `lunora advisor` flags something.
7
4
  ---
8
5
 
9
6
  # Lunora Performance Audit
10
7
 
11
- Systematically diagnose Lunora performance issues, route to the right fix, and
12
- apply it across sibling functions consistently.
8
+ Find the measured problem, route it to the matching fix below, and apply the
9
+ fix to every function that touches the same table.
13
10
 
14
- ## When to Use
11
+ If traffic is modest and nothing is measured as slow, prefer simpler code. Don't
12
+ introduce sharding, digest tables or document splits on speculation.
15
13
 
16
- - Queries feel slow or read far more rows than they return.
17
- - Mutations conflict (409 `CONFLICT`) under load (OCC).
18
- - Subscriptions fan out updates too broadly or re-run too often.
19
- - The Lunora Studio **Advisors** tab or `@lunora/advisor` flags a table.
20
-
21
- ## When Not to Use
22
-
23
- - Scale is small, traffic is modest, and there is no measured problem — prefer
24
- simpler code. Do not introduce sharding, digests, or splits on speculation.
25
-
26
- ## Core Workflow
14
+ ## Workflow
27
15
 
28
16
  1. **Scope** one concrete user flow with a clear entry and exit.
29
- 2. **Trace** every `ctx.db` read and write in that flow.
30
- 3. **Route** to the matching problem class below.
31
- 4. **Fix siblings** consistently — every function touching the same table should
32
- read it the same indexed way.
33
- 5. **Verify** behavior is unchanged and the advisor finding clears.
17
+ 2. **Gather signal** with `lunora insights` (runtime) and `lunora advisor`
18
+ (static).
19
+ 3. **Trace** every `ctx.db` read and write in that flow.
20
+ 4. **Route** to the problem class below and fix it.
21
+ 5. **Fix siblings** so every function reads the table the same indexed way. A
22
+ half-migrated access pattern is its own bug.
23
+ 6. **Verify:** behaviour unchanged, the advisor finding cleared, and the
24
+ `insights` row improved after the fix has served traffic.
34
25
 
35
- ## Signal Gathering
26
+ ## Signal
36
27
 
37
- ### Runtime signal: `lunora insights`
28
+ ### Runtime: `lunora insights`
38
29
 
39
- When the worker is running and has served traffic, start here — it reports the
40
- measured problem, not a suspected one:
30
+ Needs a running worker that has served traffic. It reports measured problems:
41
31
 
42
32
  ```bash
43
- lunora insights # against the local dev worker
44
- lunora insights --shard channel:demo # scope to one shard
45
- lunora insights --limit 25 --format json # machine-readable, more rows
46
- lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN
33
+ lunora insights # local dev worker (http://localhost:8787)
34
+ lunora insights --shard channel:demo # one shard instead of the root
35
+ lunora insights --limit 25 --format json
36
+ LUNORA_ADMIN_TOKEN=… lunora insights --prod --url https://app.example.com
47
37
  ```
48
38
 
49
- It ranks per-function **write-conflict hot-spots** (OCC contention — the
50
- sharding signal), **error rates**, and **latency outliers**. A function at the
51
- top of the write-conflict list is the direct input to the OCC section below; a
52
- latency outlier usually resolves to the read-amplification section.
39
+ It ranks per-function **write-conflict hot-spots** (go to Write conflicts),
40
+ **error rates**, and **latency outliers** (usually Read amplification). The
41
+ Studio Issues panel and `lunora logs` give error detail once you know where to
42
+ look.
53
43
 
54
- The Studio **Issues** panel and `lunora logs` cover the error side in more
55
- detail once `insights` tells you where to look.
44
+ ### Static: `lunora advisor` and `@lunora/advisor`
56
45
 
57
- ### Static signal: the advisors
46
+ No traffic needed. The Studio **Advisors** tab shows the same findings live in
47
+ dev.
48
+
49
+ ```bash
50
+ lunora advisor # score + write lunora.advisor.map.json
51
+ lunora advisor --entry messages#send # one procedure (file#exportName)
52
+ lunora advisor --baseline # CI: fail on regression vs the committed map
53
+ ```
58
54
 
59
- These need no traffic, so they also work on a cold codebase:
55
+ Lint ids are snake_case. The performance-relevant ones:
60
56
 
61
- - **Lunora Studio → Advisors tab** surfaces `@lunora/advisor` findings live in
62
- dev.
63
- - `@lunora/advisor` runs ~90 static lints over `defineSchema` + discovered query
64
- reads / insert writes (plus a few runtime lints). The performance/schema rules
65
- most relevant here:
66
- - `filter-without-index` — a query filters a table with no covering index.
67
- - `unindexed-foreign-key` — a relation/FK column has no index.
68
- - `duplicate-index` / `empty-index` — wasted or malformed indexes.
69
- - `index-references-unknown-field`, `relation-references-unknown-field`,
70
- `relation-references-unknown-table` — broken index/relation definitions.
71
- - `table-without-insert` — a table is read but never written (often a
72
- schema/typo signal).
57
+ | Lint | Meaning |
58
+ | --------------------------------- | ---------------------------------------------------------------------------- |
59
+ | `filter_without_index` | A query filters a table with no covering index. |
60
+ | `unbounded_collect` | `.collect()` with no index or filter loads every row (and re-sends it live). |
61
+ | `filter_on_primary_key` | Filtering on `_id` scans; use `ctx.db.get(id)`. |
62
+ | `unindexed_foreign_key` | An FK column has no index. |
63
+ | `unindexed_relation_target` | A `many` relation's target FK has no index, so `with:` reads scan. |
64
+ | `duplicate_index` / `empty_index` | Wasted or malformed index. |
65
+ | `index_utilization` (runtime) | A declared index nothing uses, or a hot table read with none. |
66
+ | `hot_shard` (runtime) | One shard takes a disproportionate share of a sharded function's load. |
67
+ | `fan_out_breadth` (runtime) | A shard set so wide a cross-shard read nears the subrequest limit. |
73
68
 
74
- ## Problem Class: Read Amplification (the common one)
69
+ ## Read amplification (the common one)
75
70
 
76
- **Symptom:** a query reads the whole table to return a few rows;
77
- `filter-without-index` fires.
71
+ **Symptom:** a query reads the whole table to return a few rows; a latency
72
+ outlier in `insights`, or `filter_without_index` / `unbounded_collect`.
78
73
 
79
- **Fix:** read through an index, not `.filter()`. Declare the index on the table
80
- and use `.withIndex()` with an equality/range on the leading columns.
74
+ **Fix:** declare an index and read through it with `.withIndex()`:
81
75
 
82
76
  ```ts
83
- // Bad — scans every row, then filters in memory.
77
+ // (auth / org membership check on `orgId` elided — see lunora-functions)
78
+ // Scans every row, then filters in memory.
84
79
  const mine = (await ctx.db.query("documents").collect()).filter((d) => d.orgId === orgId);
85
80
 
86
- // Good — declare the index…
81
+ // schema.ts
87
82
  documents: defineTable({ orgId: v.string(), createdAt: v.number() /* … */ }).index("by_org_created", ["orgId", "createdAt"]);
88
83
 
89
- // …and read through it.
84
+ // Reads only the org's range.
90
85
  const mine = await ctx.db
91
86
  .query("documents")
92
87
  .withIndex("by_org_created", (q) => q.eq("orgId", orgId))
93
88
  .collect();
94
89
  ```
95
90
 
96
- Index columns are ordered: put equality columns first, then the range/sort
97
- column. Fix every sibling query on the table the same way.
98
-
99
- ## Problem Class: Relation Traversal Cost
100
-
101
- **Symptom:** a query calling `ctx.db.related` is slow, or one page of it reads
102
- far more rows than it returns.
103
-
104
- A traversal is not one read. It is one batched `findMany` **per edge, per hop**,
105
- and the frontier grows multiplicatively — which is why every option is bounded,
106
- and why the bounds **refuse rather than clamp**:
107
-
108
- | Option | Default | Cap | What the cap is protecting |
109
- | ------------- | ------- | -------- | ---------------------------------------------------------------------------- |
110
- | `depth` | `1` | `4` | Past 4 hops a real schema is bounded by request time, not by `limit`. |
111
- | `limit` | `50` | `200` | Nodes returned in one page. |
112
- | cursor offset | `0` | `10 000` | The offset is re-walk work, not a skip: each hop reads `N + limit + 1` rows. |
113
-
114
- A caller asking for `depth: 9` gets a `BAD_REQUEST`, not a silent depth 4 — so a
115
- traversal that throws is a mis-sized request, not a bug to route around.
116
-
117
- **Fixes, in order of preference:**
118
-
119
- 1. **Narrow with `edges`.** Name only the `"<table>.<column>"` edges the feature
120
- needs. Following every declared foreign key is the usual reason a walk is
121
- wide — one unrelated `v.id(...)` column can double the frontier per hop.
122
- 2. **Narrow with `direction`.** `"in"` or `"out"` instead of the default
123
- `"both"` halves the edges expanded at each hop.
124
- 3. **Drop `depth` before raising `limit`.** Each hop multiplies; a page is
125
- linear.
126
- 4. **Index the foreign keys.** Every inward hop is a `WHERE fk IN (…)` read, so
127
- an unindexed FK makes each hop a scan. `@lunora/advisor` flags it as
128
- `unindexed-foreign-key`.
129
- 5. **Stop deep-paging.** An offset past 10 000 is refused outright. That is the
130
- signal the traversal is the wrong tool for the job — narrow the walk instead
131
- of paging through it.
132
-
133
- ## Problem Class: Write Conflicts (OCC)
134
-
135
- **Symptom:** mutations on hot rows fail under concurrency, or the function tops
136
- the write-conflict section of `lunora insights`. ShardDO uses optimistic
137
- concurrency control — concurrent writes to the same DO that touch overlapping
138
- state conflict. There is **no server-side retry loop**: the loser throws
139
- `ConflictError` (code `CONFLICT`, HTTP 409) and the caller decides, so a client
140
- that never handles it (`isConflictError` from `@lunora/client`) just surfaces
141
- 409s to the user.
142
-
143
- **Fixes, in order of preference:**
144
-
145
- 1. **Narrow the write.** Patch only the fields that changed; avoid read-modify-
146
- write over rows another mutation also touches.
147
- 2. **Partition with `.shardBy(key)`.** Move per-user / per-tenant / per-room
148
- state into its own DO so writes for different keys never contend. This is the
149
- primary horizontal-scale lever — most write contention is a single-DO
150
- hotspot.
151
- 3. **Avoid unbounded counters/aggregates in the hot path.** Accumulate in a
152
- sharded/append shape and fold lazily rather than serializing every writer
153
- through one row.
154
-
155
- ## Problem Class: Subscription Cost
91
+ Put equality columns first, then the range/sort column. For a large range,
92
+ paginate instead of `.collect()`.
156
93
 
157
- **Symptom:** a `useQuery` re-runs and re-pushes to many clients on unrelated
158
- writes.
94
+ ## Relation traversal cost
95
+
96
+ **Symptom:** a query using `ctx.db.related` is slow, or one page reads far more
97
+ rows than it returns.
98
+
99
+ A traversal is one batched `findMany` per edge, per hop, and the frontier grows
100
+ multiplicatively. The options are bounded, and an out-of-range value is rejected
101
+ with `BAD_REQUEST` instead of being clamped, so a throwing traversal means the
102
+ request is too big, not that there's a bug to route around.
159
103
 
160
- **Fixes:**
104
+ | Option | Default | Cap | Why |
105
+ | ------------- | ------- | -------- | ------------------------------------------------------------- |
106
+ | `depth` | `1` | `4` | Past 4 hops, request time is the limit, not `limit`. |
107
+ | `limit` | `50` | `200` | Nodes per page. |
108
+ | cursor offset | `0` | `10 000` | The offset is re-walked: each hop reads `N + limit + 1` rows. |
161
109
 
162
- - **Scope query args tightly** so a subscription only depends on the rows it
163
- renders — a query keyed by `orgId` should not re-run for another org's write.
164
- - **Read through indexes** (above) so the reactive dependency is the narrow
165
- index range, not the whole table.
166
- - ShardDO subscriptions are **hibernated WebSockets** — idle connections cost
167
- nothing; the lever is _how many rows each live query depends on_, not raw
168
- connection count.
110
+ Fixes, in order:
169
111
 
170
- ## Problem Class: Cross-Region Reads
112
+ 1. **Narrow `edges`** to the `"<table>.<column>"` edges the feature needs. One
113
+ unrelated `v.id(...)` column can double the frontier per hop.
114
+ 2. **Set `direction`** to `"in"` or `"out"` instead of the default `"both"`.
115
+ 3. **Lower `depth` before raising `limit`.** Hops multiply; a page is linear.
116
+ 4. **Index the foreign keys.** Every inward hop is a `WHERE fk IN (…)` read
117
+ (`unindexed_foreign_key`).
118
+ 5. **Stop deep-paging.** Needing an offset past 10 000 means the traversal is
119
+ the wrong tool; narrow the walk.
171
120
 
172
- **Symptom:** read-heavy, rarely-written data is slow for far-away users.
121
+ ## Write conflicts (OCC)
173
122
 
174
- **Fix:** chain `.global()` on the table to replicate it to D1 for low-latency
175
- cross-region reads (with read-your-writes via the Sessions API). Reserve it for
176
- read-mostly tables — `.global()` adds the D1 migration flow (see the
177
- `lunora-migration-helper` skill) and write-path cost.
123
+ **Symptom:** mutations on hot rows fail under concurrency, or a function tops
124
+ the write-conflict list in `insights`.
125
+
126
+ ShardDO uses optimistic concurrency. When a concurrent write commits first, the
127
+ mutation throws `ConflictError` (`code: "CONFLICT"`, HTTP 409). The runtime does
128
+ not retry it; a mutation body runs at most once per call, and the caller
129
+ decides what to do. On the client, check with `isConflictError(error)` from
130
+ `@lunora/client` (also exported via `lunorash/client`).
131
+
132
+ Not every 409 is contention. On the server, `ConflictError.kind` is `"occ"` for
133
+ real write contention, and `"unique"`, `"restrict"` or `"trigger"` for
134
+ constraint and guard failures. The client only sees `code: "CONFLICT"` (`kind`
135
+ is not part of the error envelope), so it cannot tell them apart. `insights` counts only `occ` as a write conflict, so fix a `unique`
136
+ 409 in the data or the insert logic, not by sharding.
137
+
138
+ Fixes, in order:
139
+
140
+ 1. **Narrow the write.** Patch only changed fields; avoid read-modify-write over
141
+ rows another mutation also writes.
142
+ 2. **Partition with `.shardBy(key)`.** Per-user / per-tenant / per-room state
143
+ in its own Durable Object never contends across keys. This is the main
144
+ horizontal-scale lever, since most contention is one hot DO.
145
+ 3. **Take counters and aggregates off the hot row.** Append and fold lazily
146
+ instead of serializing every writer through one row.
147
+
148
+ If `hot_shard` fires on an already-sharded table, the key is skewed: re-shard on
149
+ a higher-cardinality key or split the hot entity's state.
150
+
151
+ ## Subscription cost
152
+
153
+ **Symptom:** a `useQuery` re-runs and re-pushes to many clients on unrelated
154
+ writes.
178
155
 
179
- If the dataset outgrows D1, `.global({ backend: "hyperdrive" })` serves the same
180
- reactive `.global()` contract from Postgres/MySQL over Cloudflare Hyperdrive —
181
- see the `lunora-setup-hyperdrive-global` skill (and `lunora migrate
182
- d1-to-hyperdrive` to move an existing dataset).
156
+ - Scope query args tightly so a live query depends only on the rows it renders;
157
+ a query keyed by `orgId` shouldn't re-run on another org's write.
158
+ - Read through indexes so the dependency is the index range, not the table.
159
+ - Idle WebSockets are hibernated and cost nothing. The lever is how many rows
160
+ each live query depends on, not the connection count.
183
161
 
184
- ### `.shardBy(key)` vs `.global()` — choose one per table
162
+ ## Cross-region reads
185
163
 
186
- - `.shardBy(key)`: partitions a table across Durable Objects by key — scales
187
- _writes_ (e.g. messages per room). Reads are per-shard.
188
- - `.global()`: replicates a table to D1 — scales _cross-region reads_ with
189
- read-your-writes (e.g. a mostly-read catalog).
190
- - They are not combined on the same table; the default (neither) is a single
191
- root-scoped ShardDO.
164
+ **Symptom:** read-heavy, rarely-written data is slow for distant users.
192
165
 
193
- ## Guardrails
166
+ **Fix:** `.global()` replicates the table to D1 for low-latency reads from the
167
+ edge, with read-your-writes via D1 sessions. Use it only for read-mostly tables:
168
+ it adds write-path cost and its own DDL flow (`lunora-migration-helper`). If the
169
+ dataset outgrows D1, `.global({ backend: "hyperdrive" })` serves the same
170
+ reactive contract from Postgres/MySQL (`lunora-setup-hyperdrive-global`).
194
171
 
195
- - Prefer simpler code when scale is small or the signal is weak.
196
- - Do not recommend structural changes (digest tables, document splitting,
197
- sharding) without a measured signal or a known hot path.
198
- - When you change how one function reads/writes a table, change its siblings to
199
- match — half-migrated access patterns are their own bug.
172
+ `.shardBy(key)` scales writes (rows in one DO per key); `.global()` scales
173
+ cross-region reads. A table can't have both; the default is the single root
174
+ ShardDO. Switching an existing table's mode moves its rows, which is an
175
+ export/import, not a schema edit (see `lunora-migration-helper`).
200
176
 
201
177
  ## Checklist
202
178
 
203
- - [ ] Scoped one concrete flow; traced every `ctx.db` read/write.
204
- - [ ] Ran `lunora insights` (if the worker has traffic) for the measured signal.
205
- - [ ] Checked the Studio Advisors tab / `@lunora/advisor` findings.
206
- - [ ] Read amplification: replaced `.filter()` with an indexed `.withIndex()`.
207
- - [ ] Relation traversals: narrowed with `edges` / `direction` before `depth`;
208
- foreign keys indexed.
209
- - [ ] Write conflicts: narrowed writes and/or partitioned with `.shardBy(key)`.
210
- - [ ] Subscription cost: scoped query args so live queries depend on few rows.
211
- - [ ] Cross-region: applied `.global()` only to read-mostly tables.
212
- - [ ] Fixed sibling functions consistently; verified behavior unchanged.
179
+ - [ ] Scoped one flow; traced every `ctx.db` read/write.
180
+ - [ ] Checked `lunora insights` (if there's traffic) and `lunora advisor`.
181
+ - [ ] Scans replaced with `.withIndex()` reads; FKs indexed.
182
+ - [ ] Traversals narrowed with `edges` / `direction` before touching `depth`.
183
+ - [ ] Write conflicts confirmed as `occ`, then writes narrowed and/or `.shardBy(key)` applied.
184
+ - [ ] Live queries depend on few rows; `.global()` only on read-mostly tables.
185
+ - [ ] Siblings fixed consistently; behaviour unchanged; finding cleared.