@camstack/system 1.2.133 → 1.2.134

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.
@@ -0,0 +1,41 @@
1
+ import { Database } from 'better-sqlite3';
2
+ /**
3
+ * Delay before the one-shot `ANALYZE`, in ms.
4
+ *
5
+ * Boot is itself the busiest window this runner has (`ensureTable` ×9, the
6
+ * retired-key purge, the vector registry), and adding a 14 s statement to it
7
+ * would turn a slow boot into one an operator reads as a hang. Long enough that
8
+ * the cluster is serving before the engine goes quiet.
9
+ */
10
+ export declare const ANALYZE_DELAY_MS = 120000;
11
+ /** Env var that disables the one-shot analysis. `off` is the only value read. */
12
+ export declare const ANALYZE_ENV_VAR = "CAMSTACK_SQLITE_ANALYZE";
13
+ /** What {@link runAnalyzeIfMissing} did, for the caller to log. */
14
+ export type AnalyzeOutcome = {
15
+ readonly kind: 'already-present';
16
+ } | {
17
+ readonly kind: 'analyzed';
18
+ readonly tookMs: number;
19
+ readonly indexesAnalyzed: number;
20
+ } | {
21
+ readonly kind: 'failed';
22
+ readonly tookMs: number;
23
+ readonly error: string;
24
+ };
25
+ /**
26
+ * True when the database has no `sqlite_stat1` at all.
27
+ *
28
+ * Deliberately "none", not "old": a stale row still tells the planner the
29
+ * relative selectivity of two indexes, which is the entire question being
30
+ * asked. Re-analysis on a staleness heuristic would put a 14 s statement on a
31
+ * timer, and this runner cannot afford one.
32
+ */
33
+ export declare function hasIndexStatistics(db: Database): boolean;
34
+ /**
35
+ * `ANALYZE` the database, but only if it has never been analysed.
36
+ *
37
+ * Synchronous and long — see the module doc. Never throws: a database that
38
+ * refuses to be analysed is a missing optimisation, not a reason to take the
39
+ * settings engine down, and the outcome says so rather than going quiet.
40
+ */
41
+ export declare function runAnalyzeIfMissing(db: Database, now?: () => number): AnalyzeOutcome;
@@ -35,6 +35,23 @@ import { IScopedLogger } from '@camstack/types';
35
35
  * statement that really does take seconds. Both are needed; neither is
36
36
  * sufficient.
37
37
  *
38
+ * ## Why the SQL shape, and why the plan
39
+ *
40
+ * `(op, collection)` names a TABLE, not a call site. On 2026-08-25 the busiest
41
+ * line of a 90 s operator stall was `query pipeline-analytics:tracks — 1005
42
+ * calls, max 1615 ms` and eleven different reads in one addon are spelled
43
+ * exactly that way; the aggregate accused all of them and cleared none. So the
44
+ * shape of the prepared statement (`statement-shape.ts`) is part of the
45
+ * aggregate KEY, and the report prints it.
46
+ *
47
+ * A shape says WHICH query. It does not say why it is slow — "1.6 s for 501
48
+ * rows" is a full scan and "1.6 s for 501 rows" is also a cold disk, and those
49
+ * are the same line. `EXPLAIN QUERY PLAN` is the only thing that separates
50
+ * them, and it is attached to the slow-call WARN because that is where the
51
+ * question is asked. It is asked ONCE PER SHAPE PER WINDOW: a scan that fires
52
+ * the WARN fires it repeatedly, and a plan re-printed forty times is how the
53
+ * one line that mattered stops being read.
54
+ *
38
55
  * ## Cost
39
56
  *
40
57
  * Two `Date.now()` calls and one `Map` lookup per statement. At the measured
@@ -64,17 +81,37 @@ export interface SqliteOpSample {
64
81
  readonly deviceId?: number;
65
82
  /** See {@link SqliteOpLabel.owner}. */
66
83
  readonly owner?: string;
84
+ /** See {@link SqliteOpLabel.sql}. */
85
+ readonly sql?: string;
86
+ /** See {@link SqliteOpLabel.params}. */
87
+ readonly params?: readonly unknown[];
67
88
  }
68
- /** One `(op, collection, owner)` triple's totals over a report window. */
89
+ /** One `(op, collection, owner, shape)` tuple's totals over a report window. */
69
90
  export interface SqliteOpStat {
70
91
  readonly op: string;
71
92
  readonly collection: string;
72
93
  readonly owner?: string;
94
+ /** `statement-shape.ts` fingerprint; absent for a fixed-shape statement the
95
+ * engine did not hand to the profiler. */
96
+ readonly shape?: string;
73
97
  readonly calls: number;
74
98
  readonly totalMs: number;
75
99
  readonly maxMs: number;
76
100
  readonly rows: number;
77
101
  }
102
+ /**
103
+ * Runs `EXPLAIN QUERY PLAN` for a statement on the connection that executed it.
104
+ *
105
+ * Injected rather than reached for: the profiler must not own a database
106
+ * handle, and the plan is only trustworthy from the SAME connection — a second
107
+ * handle can differ in `sqlite_stat1` visibility and in temp-schema state, and
108
+ * a plan taken from a connection that is not the one that stalled describes a
109
+ * query nobody ran.
110
+ *
111
+ * Returns one string per plan row (SQLite's `detail` column). Must not throw —
112
+ * an unexplainable statement yields `[]`.
113
+ */
114
+ export type SqlExplainer = (sql: string, params: readonly unknown[]) => readonly string[];
78
115
  /**
79
116
  * Duration at which one statement is worth a WARN on its own, in ms.
80
117
  *
@@ -104,6 +141,8 @@ export interface SqliteOpProfilerOptions {
104
141
  readonly reportIntervalMs?: number;
105
142
  readonly reportFloorMs?: number;
106
143
  readonly topN?: number;
144
+ /** Absent ⇒ slow-call WARNs carry no plan. See {@link SqlExplainer}. */
145
+ readonly explain?: SqlExplainer;
107
146
  }
108
147
  /** Identity of a measured call, without the numbers `measure` supplies itself. */
109
148
  export interface SqliteOpLabel {
@@ -117,6 +156,27 @@ export interface SqliteOpLabel {
117
156
  * exactly where the 67 660-call storm of 2026-08-25 stopped.
118
157
  */
119
158
  readonly owner?: string;
159
+ /**
160
+ * The statement the engine prepared, verbatim.
161
+ *
162
+ * Supplied only by the ops that BUILD their SQL from a filter — those are the
163
+ * ones whose cost varies by call site. A fixed-shape statement (`get`, `set`)
164
+ * is already fully described by `(op, collection)`.
165
+ *
166
+ * Used for two things and nothing else: the shape that becomes part of the
167
+ * aggregate key, and the `EXPLAIN QUERY PLAN` on a slow call. Never logged
168
+ * raw — see `statement-shape.ts` for what is dropped.
169
+ */
170
+ readonly sql?: string;
171
+ /**
172
+ * The values bound to {@link sql}.
173
+ *
174
+ * Needed because `EXPLAIN QUERY PLAN` on a statement with unbound parameters
175
+ * is not the plan that ran: SQLite's planner reads bound values for `LIKE`
176
+ * prefixes and for index-selection on `IN`. Never logged, in whole or in
177
+ * part — they carry device ids, keys and user data.
178
+ */
179
+ readonly params?: readonly unknown[];
120
180
  }
121
181
  export declare class SqliteOpProfiler {
122
182
  private readonly logger;
@@ -125,7 +185,11 @@ export declare class SqliteOpProfiler {
125
185
  private readonly reportIntervalMs;
126
186
  private readonly reportFloorMs;
127
187
  private readonly topN;
188
+ private readonly explain;
128
189
  private readonly stats;
190
+ /** Shapes already explained in this window — see the class doc on why the
191
+ * plan is printed once and not on every WARN. Cleared by `drain`. */
192
+ private readonly explainedShapes;
129
193
  private windowStartedAt;
130
194
  private timer;
131
195
  constructor(options: SqliteOpProfilerOptions);
@@ -139,6 +203,15 @@ export declare class SqliteOpProfiler {
139
203
  */
140
204
  measure<T>(label: SqliteOpLabel, run: () => T): T;
141
205
  record(sample: SqliteOpSample): void;
206
+ /**
207
+ * `EXPLAIN QUERY PLAN` for a statement that just held the loop, or nothing.
208
+ *
209
+ * Nothing when: no explainer was injected, the op carries no SQL, or this
210
+ * shape has already been explained in this window. The explainer is
211
+ * contracted not to throw and is guarded anyway — a profiler that can turn a
212
+ * slow query into a crash is worse than one that cannot explain it.
213
+ */
214
+ private planFor;
142
215
  /** Totals for the window, busiest first, and reset. */
143
216
  drain(): readonly SqliteOpStat[];
144
217
  /** Emit one aggregate line for the window, unless the engine was idle. */
@@ -221,6 +221,24 @@ export declare class SqliteSettingsBackend implements ISettingsBackend {
221
221
  * Returns null if the backend has not been initialized yet.
222
222
  */
223
223
  getDatabase(): Database.Database | null;
224
+ /**
225
+ * `EXPLAIN QUERY PLAN` for a statement, as one string per plan row.
226
+ *
227
+ * Answers the question the timing alone cannot: "1.6 s for 501 rows" is a
228
+ * full scan and is also a cold disk, and only the plan tells them apart. It
229
+ * runs on the SAME connection as the statement, because that is the only
230
+ * connection whose `sqlite_stat1` visibility and temp schema match.
231
+ *
232
+ * `EXPLAIN QUERY PLAN` prepares and plans; it does not execute the statement,
233
+ * so it costs no page reads of its own. It is still called only from the
234
+ * slow-call path, once per shape per window.
235
+ *
236
+ * Never throws. A plan that cannot be taken (a statement the engine will no
237
+ * longer prepare, a closed handle mid-shutdown) is a missing ANSWER, not a
238
+ * failure worth turning a slow query into a crash — the profiler falls back
239
+ * to the line it would have printed anyway.
240
+ */
241
+ private explainQueryPlan;
224
242
  /**
225
243
  * Run one synchronous statement under the profiler.
226
244
  *
@@ -265,6 +283,16 @@ export declare class SqliteSettingsBackend implements ISettingsBackend {
265
283
  * storage report turns it off without a rebuild.
266
284
  */
267
285
  private scheduleMapGrowthCheck;
286
+ /**
287
+ * One-shot `ANALYZE`, long after boot, only if the database has none.
288
+ *
289
+ * `analyze-stats.ts` has the measurement that justifies it: without
290
+ * `sqlite_stat1` the planner walked 150 133 media rows to return six, and one
291
+ * `ANALYZE` took that same query from 727 ms to 3.2 ms. It is scheduled
292
+ * rather than run inline because it is a 14 s synchronous statement on the
293
+ * one thread the cluster reads configuration through.
294
+ */
295
+ private scheduleIndexAnalysis;
268
296
  private scheduleStorageReport;
269
297
  private logStorageReport;
270
298
  private readPragmaNumber;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A stable, low-cardinality name for the SHAPE of a SQL statement.
3
+ *
4
+ * ## Why the profiler needs this
5
+ *
6
+ * `SqliteOpProfiler` aggregated on `(op, collection)`, and that pair is not an
7
+ * identity — it is a table. On 2026-08-25 the busiest line of a 90 s operator
8
+ * stall read `query pipeline-analytics:tracks — 1005 calls, 2694 ms,
9
+ * max 1615 ms, 17981 rows`, and there was no way to tell from it WHICH of the
10
+ * eleven distinct reads that addon issues against that one table had spent the
11
+ * second and a half. Every one of them was equally accused; the aggregate could
12
+ * not clear a single one.
13
+ *
14
+ * The shape is the missing half. It is derived from the statement the engine
15
+ * actually prepared, so it cannot drift from the code the way a hand-passed
16
+ * label would, and it collapses to exactly one string per call site — which is
17
+ * what makes it safe as part of an aggregate key.
18
+ *
19
+ * ## What is thrown away, and why
20
+ *
21
+ * - **The projection.** `queryDeclared` always selects every column, so the
22
+ * `SELECT` list is the table's schema restated — pure noise, and the single
23
+ * longest part of the statement.
24
+ * - **The table name.** It is already the `collection` field of the report.
25
+ * - **The width of an `IN` list.** `IN (?, ?, … ×500)` and `IN (?)` are the
26
+ * same call site; keeping the literal placeholders would make every page of
27
+ * a chunked read its own aggregate row. The COUNT is kept (`IN (?×500)`)
28
+ * because it is the difference between "reads one row" and "reads five
29
+ * hundred", which is the whole question being asked.
30
+ *
31
+ * Bound values are never included. They are not needed to name a call site, and
32
+ * a statement's parameters routinely carry device ids, keys and user data — a
33
+ * profiler line is not a place to put them.
34
+ */
35
+ /**
36
+ * Longest fingerprint kept, in characters.
37
+ *
38
+ * A shape is a log field printed five to a line; past this it stops being
39
+ * readable and starts pushing the numbers off the end. Every real statement in
40
+ * this engine fits well inside it — the cap exists for the pathological
41
+ * `whereIn` with forty distinct fields, not for the normal case.
42
+ */
43
+ export declare const SQL_SHAPE_MAX_LENGTH = 220;
44
+ /** Appended when a shape is cut at {@link SQL_SHAPE_MAX_LENGTH}. */
45
+ export declare const SQL_SHAPE_ELLIPSIS = "\u2026";
46
+ /**
47
+ * How many distinct raw statements the memo holds before it is dropped.
48
+ *
49
+ * The engine prepares its SQL fresh on every call, so without a memo this runs
50
+ * a handful of regexes per statement at a few hundred statements a second.
51
+ * With one, it runs them once per call site. The bound exists because the raw
52
+ * key is unbounded in principle (an `IN` list of a new width mints a new
53
+ * entry): at the cap the memo is cleared rather than grown, which costs one
54
+ * re-derivation per shape and cannot leak.
55
+ */
56
+ export declare const SQL_SHAPE_MEMO_MAX_ENTRIES = 512;
57
+ /**
58
+ * Name the shape of `sql`, whose table is `collection`.
59
+ *
60
+ * Memoised on the raw statement — see {@link SQL_SHAPE_MEMO_MAX_ENTRIES}.
61
+ */
62
+ export declare function sqlShape(sql: string, collection: string): string;
63
+ /** Test seam: forget every memoised shape. */
64
+ export declare function resetSqlShapeMemo(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/system",
3
- "version": "1.2.133",
3
+ "version": "1.2.134",
4
4
  "description": "Core addon for CamStack — builtins, pipeline, process management, auth, logging, events",
5
5
  "keywords": [
6
6
  "camstack",