@lunora/observability 1.0.0-alpha.1 → 1.0.0-alpha.100

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.
Files changed (43) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +433 -82
  3. package/dist/index.d.ts +433 -82
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-CeplWoRm.mjs +22 -0
  6. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs +3 -0
  7. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs +56 -0
  8. package/dist/packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs +15 -0
  9. package/dist/packem_shared/LogBuffer-BmD4CfV0.mjs +1 -0
  10. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs +1 -0
  11. package/dist/packem_shared/MetricBuffer-DnOJJVHH.mjs +1 -0
  12. package/dist/packem_shared/REQUEST_LOG_TABLE-D3ax4pFP.mjs +1 -0
  13. package/dist/packem_shared/SpanBuffer-DnYOc8uk.mjs +1 -0
  14. package/dist/packem_shared/createDatabaseTally-BsElP16g.mjs +1 -0
  15. package/dist/packem_shared/createMetrics-DTJWo1fV.mjs +1 -0
  16. package/dist/packem_shared/findDanglingReferences-BNgg0jD_.mjs +1 -0
  17. package/dist/packem_shared/metric-buffer-Bx0XbypU.mjs +1 -0
  18. package/dist/packem_shared/prune-marker-B4An9Nuj.mjs +1 -0
  19. package/dist/packem_shared/readMetricHistory-TKfnwFNv.mjs +31 -0
  20. package/dist/packem_shared/readQueryInsights-8nYLTftS.mjs +32 -0
  21. package/dist/packem_shared/request-log-pOG0ApHK.mjs +24 -0
  22. package/dist/packem_shared/resolveTraceAnchor-Ft_Ewucb.mjs +1 -0
  23. package/dist/packem_shared/run-sql-0aPgJkIw.mjs +1 -0
  24. package/dist/packem_shared/trace-context-d_EfGPSZ.mjs +1 -0
  25. package/package.json +5 -5
  26. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-C2V-DiGu.mjs +0 -22
  27. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-xF11R4vX.mjs +0 -3
  28. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-B1U7xWMo.mjs +0 -56
  29. package/dist/packem_shared/ISSUE_SEVERITIES-Js6lGUG5.mjs +0 -15
  30. package/dist/packem_shared/LogBuffer-bIvCelI-.mjs +0 -1
  31. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-T-zuwRVR.mjs +0 -1
  32. package/dist/packem_shared/MetricBuffer-CYrLuEsz.mjs +0 -1
  33. package/dist/packem_shared/REQUEST_LOG_TABLE-Q_BYgAzY.mjs +0 -20
  34. package/dist/packem_shared/SpanBuffer-BR6Ff0M-.mjs +0 -1
  35. package/dist/packem_shared/createDatabaseTally-BTqRpC0j.mjs +0 -1
  36. package/dist/packem_shared/createMetrics-fpVig63l.mjs +0 -1
  37. package/dist/packem_shared/findDanglingReferences-D-x9LvY0.mjs +0 -1
  38. package/dist/packem_shared/log-fields-d5ouN1Pe.mjs +0 -1
  39. package/dist/packem_shared/metric-buffer-CdgXal7w.mjs +0 -1
  40. package/dist/packem_shared/readMetricHistory-DtnhufUq.mjs +0 -31
  41. package/dist/packem_shared/readQueryInsights-CwSKB0I1.mjs +0 -32
  42. package/dist/packem_shared/resolveTraceAnchor-IAN8riI0.mjs +0 -1
  43. package/dist/packem_shared/trace-context-DrdF960P.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -64,9 +64,9 @@ declare const ensureAuthMetricsTables: (sql: SqlExec) => void;
64
64
  * `failures` advances only when `outcome === "fail"`. `since_ms` is set once on
65
65
  * the first attempt and never moved (so it stays a true first-seen marker).
66
66
  *
67
- * Exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a bounded
68
- * `DELETE`, all keyed by primary key — cheap enough to fire off the auth
69
- * response path without blocking it.
67
+ * Exactly two `INSERT … ON CONFLICT … DO UPDATE` statements, all keyed by
68
+ * primary key, plus a bounded `DELETE` that runs once per bucket window —
69
+ * cheap enough to fire off the auth response path without blocking it.
70
70
  */
71
71
  declare const recordAuthEvent: (sql: SqlExec, input: RecordAuthEventInput) => void;
72
72
  /**
@@ -320,10 +320,50 @@ interface SpanHandle {
320
320
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
321
  * reach around the API for it.
322
322
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
323
+ spanContext: () => SpanContextIds;
324
+ }
325
+ /**
326
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
327
+ *
328
+ * `sampled` is the propagated head decision (absent means "no verdict reached
329
+ * this tier", which every consumer reads as keep). It rides alongside the ids
330
+ * because everything that needs the ids to announce this span downstream — a
331
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
332
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
333
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
334
+ */
335
+ interface SpanContextIds {
336
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
337
+ sampled?: boolean;
338
+ /** This span's id (16-hex). */
339
+ spanId: string;
340
+ /** The trace this span belongs to (32-hex). */
341
+ traceId: string;
342
+ }
343
+ /**
344
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
345
+ * argument.
346
+ *
347
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
348
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
349
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
350
+ * so the id the adapter published is the id that reaches the collector rather
351
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
352
+ * reason: an adapter that tracks its own parent/child structure (OTel's
353
+ * `Context`) can express it without an ambient span stack.
354
+ *
355
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
356
+ * never mints its own ids.
357
+ *
358
+ * Both ids are required: an adapter that has published one has published the
359
+ * other, and `identity` is itself optional — omitting it, not passing a partial
360
+ * object, is how a caller says "no adapter involved".
361
+ */
362
+ interface SpanIdentity {
363
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
364
+ parentSpanId: string;
365
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
366
+ spanId: string;
327
367
  }
328
368
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
369
  interface SpanOptions {
@@ -402,6 +442,19 @@ interface SpanEvent {
402
442
  * the outermost span, which is why the fold prefers it as a trace's anchor.
403
443
  */
404
444
  dispatch?: boolean;
445
+ /**
446
+ * The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
447
+ * sink. Absent means no verdict reached this tier, which every consumer reads
448
+ * as keep.
449
+ *
450
+ * Carried because the OTLP encoders write it into the span's `flags` field,
451
+ * and a span exported with no `flags` reads as UNSAMPLED (0) at the collector
452
+ * — on EVERY span, including the ones it is meant to keep. It is genuinely
453
+ * per-span rather than derivable from "it was exported at all": a trace the
454
+ * tail bias rescued (head-sampled out, then errored) is exported with the bit
455
+ * CLEAR, and saying otherwise misreports the trace's verdict.
456
+ */
457
+ sampled?: boolean;
405
458
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
406
459
  shardKey?: string;
407
460
  /** This span's own id (16-hex). */
@@ -423,7 +476,7 @@ interface SpanEvent {
423
476
  * which it can attach attributes only known *after* it resolves (post-hoc). It is
424
477
  * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
425
478
  */
426
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions) => Promise<T>;
479
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
427
480
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
428
481
  interface ContextMetrics {
429
482
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -488,6 +541,15 @@ type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | und
488
541
  interface TracerDeps {
489
542
  /** The trace this ctx's spans belong to. */
490
543
  anchor: TraceAnchor;
544
+ /**
545
+ * Whether to record a span body's error message (and a `recordException`
546
+ * stacktrace) verbatim rather than redacted. Mirrors the request log's
547
+ * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
548
+ * the span pipeline is the one sink third-party collectors (Datadog/Axiom
549
+ * via `otlpSink`) receive, so it must not ship raw PII/internals by default
550
+ * the way the request log and function-metrics sinks already don't.
551
+ */
552
+ captureRaw?: boolean;
491
553
  /** Function path the spans are attributed to. */
492
554
  functionPath: string;
493
555
  /**
@@ -544,11 +606,14 @@ interface SpanCollector {
544
606
  * attributes become the canonical one-event-per-request summary. Sharing the
545
607
  * implementation is what makes those two feel like the same API instead of two
546
608
  * that happen to resemble each other.
609
+ *
610
+ * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
611
+ * `exception.stacktrace` the same way {@link createTracer} gates a span's own
612
+ * error message — a stack is file paths and internals by definition, the exact
613
+ * class `isInternalCode` redaction exists for, so it rides the same dev-only
614
+ * escape hatch rather than shipping to a third-party collector by default.
547
615
  */
548
- declare const createSpanCollector: (ids: {
549
- spanId: string;
550
- traceId: string;
551
- }) => SpanCollector;
616
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean) => SpanCollector;
552
617
  /**
553
618
  * Build the `ctx.trace` span factory for one dispatched function.
554
619
  *
@@ -590,7 +655,7 @@ declare const createSpanCollector: (ids: {
590
655
  *
591
656
  * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
592
657
  * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
593
- * Object under `@cloudflare/vitest-pool-workers` (see
658
+ * Object under `@cloudflare/vitest-plugin` (see
594
659
  * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
595
660
  * from `cloudflare:workers`, its callback executes and returns the body value
596
661
  * without throwing, `span.isTraced` is a real boolean, and — the key additive
@@ -610,6 +675,14 @@ declare const createTracer: (deps: TracerDeps) => ContextTracer;
610
675
  interface TracedFetchDeps {
611
676
  /** The trace the CLIENT spans belong to. */
612
677
  anchor: TraceAnchor;
678
+ /**
679
+ * Whether to record a failed fetch's error message verbatim rather than
680
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
681
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
682
+ * query string would otherwise reach the collector in the clear on the very
683
+ * span whose `url.full` is scrubbed by `redactUrl`.
684
+ */
685
+ captureRaw?: boolean;
613
686
  /** Function path the spans are attributed to. */
614
687
  functionPath: string;
615
688
  /**
@@ -645,6 +718,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
645
718
  * Kind is `client` rather than `internal` — that is what lets a collector draw
646
719
  * the edge to the downstream service in a service map.
647
720
  *
721
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
722
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
723
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
724
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
725
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
726
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
727
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
728
+ * the span whose bar you want it under and read the two side by side.
729
+ *
648
730
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
649
731
  * recorded as an ERROR span (it is a failed call from the caller's point of
650
732
  * view) while still being returned normally — instrumentation, never flow
@@ -673,6 +755,14 @@ declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
673
755
  */
674
756
  declare const dispatchRootSpan: (input: {
675
757
  anchor: TraceAnchor;
758
+ /**
759
+ * Whether to record the failure message verbatim rather than redacted —
760
+ * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
761
+ * synthetic root span carries the SAME error message the request log and
762
+ * function-metrics sinks already redact by default, so it must not be the
763
+ * one durable copy that ships it raw to a third-party collector.
764
+ */
765
+ captureRaw?: boolean;
676
766
  /**
677
767
  * What the handler attached to the dispatch through `ctx.span` — the **wide
678
768
  * event**. These are the attributes that would otherwise have been scattered
@@ -715,6 +805,14 @@ type DatabaseInstrumentation = "off" | "spans" | "summary";
715
805
  interface DatabaseTelemetryDeps {
716
806
  /** The trace produced spans belong to (`"spans"` mode only). */
717
807
  anchor: TraceAnchor;
808
+ /**
809
+ * Whether to record a failed call's error message verbatim rather than
810
+ * redacted (`"spans"` mode only) — the same dev-only escape hatch as
811
+ * `TracerDeps.captureRaw`. A constraint-error message quotes the
812
+ * conflicting row, so this CLIENT span gets the same default-redacted
813
+ * posture as the request log and function-metrics sinks.
814
+ */
815
+ captureRaw?: boolean;
718
816
  /** Function path spans and attributes are attributed to. */
719
817
  functionPath: string;
720
818
  /** Detail level; see {@link DatabaseInstrumentation}. */
@@ -728,11 +826,12 @@ interface DatabaseTelemetryDeps {
728
826
  * increments numbers on it; the shard reads it ONCE at the dispatch boundary
729
827
  * and formats it with {@link formatTally}.
730
828
  *
731
- * Two properties fall out of that split. Per-call cost stays at a few integer
732
- * increments — no object allocation, no lookup — which matters because this is
733
- * on the path of every query. And because nothing is written through the
734
- * dispatch's `SpanHandle`, the wide-event collector is never materialized, so
735
- * a handler that instrumented nothing still doesn't trip the root-span gate.
829
+ * Per-call cost stays at a few integer increments — no object allocation, no
830
+ * lookup — which matters because this is on the path of every query. Nothing
831
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
832
+ * collector is never materialized by instrumentation alone: a dispatch that
833
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
834
+ * log record unless the handler actually opened `ctx.span`.
736
835
  */
737
836
  tally: DatabaseTally;
738
837
  /** Read lazily — the acting user is resolved per span. */
@@ -786,13 +885,23 @@ declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
786
885
  /**
787
886
  * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
788
887
  * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
789
- * same reason): the `path` is attacker-reachable — an unregistered/`FUNCTION_NOT_FOUND`
790
- * dispatch still records a row keyed by the caller-supplied `functionPath` — so
791
- * without a cap a flood of distinct random paths would grow `__lunora_metrics`
792
- * (and its bucket/scan satellites) without bound, eventually filling the shard's
793
- * SQLite store shared with the app's real data. A few thousand registered
794
- * functions is already far beyond any real app, so a new path past this cap is
795
- * dropped while already-tracked paths keep accumulating.
888
+ * same reason): the real bound is the app's own registered-function set plus
889
+ * deploy churn (a rename/removal leaves its old path's row in place, still
890
+ * counted against the cap, until an operator's own retention/cleanup
891
+ * process — there is none built in today) — a few thousand registered
892
+ * functions is already far beyond any real app. `shard-do.ts`'s dispatch
893
+ * handler explicitly does NOT record per-function metrics for an
894
+ * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
895
+ * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
896
+ * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
897
+ * cap, deploy churn across the app's lifetime would still grow
898
+ * `__lunora_metrics` (and its bucket/scan satellites) without bound,
899
+ * eventually filling the shard's SQLite store shared with the app's real
900
+ * data. At the cap, a brand-new path is refused — protecting the incumbent
901
+ * leaderboard from a flood of one-off paths is the point, so admission is
902
+ * refused rather than evicting an existing path to make room; already-tracked
903
+ * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
904
+ * `capped` is the read-side signal for this.
796
905
  */
797
906
  declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
798
907
  /**
@@ -814,6 +923,22 @@ interface FunctionMetricBucket {
814
923
  /** Subset of `calls` that threw. */
815
924
  errors: number;
816
925
  }
926
+ /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
927
+ interface FunctionMetricBucketsResult {
928
+ buckets: (FunctionMetricBucket & {
929
+ path: string;
930
+ })[];
931
+ /**
932
+ * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
933
+ * return, so `buckets` is a partial (newest) window rather than the app's
934
+ * full retained history. Mirrors `readQueryInsights`'s `capped` and
935
+ * `foldTraces`'s `total`: a silently truncated read looks identical to a
936
+ * complete one to a caller that doesn't check for it — the Metrics chart's
937
+ * window would appear to shrink as the app grows, with a wrong leftmost
938
+ * bar, and nothing would say why.
939
+ */
940
+ truncated: boolean;
941
+ }
817
942
  /** One declared index a dispatch exercised (used to narrow a read). */
818
943
  interface IndexHit {
819
944
  /** The declared index name. */
@@ -854,7 +979,7 @@ interface RecordFunctionMetricInput {
854
979
  * dispatch used no declared index, keeping the hot path unchanged.
855
980
  */
856
981
  indexHits?: ReadonlyArray<IndexHit>;
857
- /** The `&lt;file>:&lt;function>` identifier. */
982
+ /** The `<file>:<function>` identifier. */
858
983
  path: string;
859
984
  /**
860
985
  * Distinct tables this dispatch full-scanned (read with no index / point
@@ -879,7 +1004,9 @@ interface RecordFunctionMetricInput {
879
1004
  * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
880
1005
  * causal-attribution feature gains the column on the next call without a
881
1006
  * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
882
- * error from a re-run is swallowed.
1007
+ * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
1008
+ * run once per handle (see {@link ensuredHandles}) — a handle already marked
1009
+ * ensured returns immediately.
883
1010
  */
884
1011
  declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
885
1012
  /**
@@ -934,18 +1061,21 @@ declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
934
1061
  /**
935
1062
  * Read the coarse time-series buckets for `path` (every path when omitted),
936
1063
  * oldest-bucket first so a chart can plot them left-to-right. Creates the table
937
- * first so reads on a never-called shard return `[]`.
1064
+ * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
938
1065
  */
939
- declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => (FunctionMetricBucket & {
940
- path: string;
941
- })[];
1066
+ declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
942
1067
  /**
943
1068
  * Aggregate the persisted accumulators into the lifetime totals the metrics
944
- * health snapshot reports: total calls (`requests`), total `errors`, and the
945
- * earliest `last_called_at` seen — a best-effort "since" marker for durable
946
- * data. Returns zeroes on a never-called shard.
1069
+ * health snapshot reports: total calls (`requests`), total `errors`. Returns
1070
+ * zeroes on a never-called shard.
1071
+ *
1072
+ * `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
1073
+ * has been reached — the write-side signal that a brand-new function path is
1074
+ * currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
1075
+ * `capped` for query-metrics and `readMetricHistory`'s for metric-history.
947
1076
  */
948
1077
  declare const readFunctionMetricsTotals: (sql: SqlExec) => {
1078
+ capped: boolean;
949
1079
  errors: number;
950
1080
  requests: number;
951
1081
  };
@@ -978,7 +1108,7 @@ interface AiRunBinding {
978
1108
  }
979
1109
  /** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
980
1110
  interface ExplainIssueArgs {
981
- /** The Issue's culprit (`&lt;file>:&lt;function>` or `container:&lt;name>`), for grounding context. */
1111
+ /** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
982
1112
  culprit?: string;
983
1113
  /** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
984
1114
  model?: string;
@@ -1127,13 +1257,15 @@ type LogLevel = ContextLogLevel;
1127
1257
  */
1128
1258
  interface LogEntry {
1129
1259
  exitCode?: number;
1130
- /** Structured fields from a `ctx.log.&lt;level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1260
+ /** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
1131
1261
  fields?: Record<string, unknown>;
1132
1262
  functionPath?: string;
1133
1263
  instance?: string;
1134
1264
  level: LogLevel;
1135
1265
  message: string;
1136
1266
  timestamp: number;
1267
+ /** Trace the line was emitted under; absent outside a dispatch (container lifecycle, hibernation-path errors). What the Studio joins a log line to its waterfall on. */
1268
+ traceId?: string;
1137
1269
  }
1138
1270
  /**
1139
1271
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1154,10 +1286,21 @@ declare class LogBuffer {
1154
1286
  /** Backing store, kept in insertion order (oldest first). */
1155
1287
  private readonly buffer;
1156
1288
  private readonly capacity;
1289
+ /** How many entries the ring has evicted since it was last cleared. */
1290
+ private droppedCount;
1157
1291
  constructor(capacity?: number);
1292
+ /**
1293
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1294
+ *
1295
+ * Without it a full ring is indistinguishable from a quiet instance that
1296
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1297
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1298
+ * count is what turns "the newest 500" into an honest statement.
1299
+ */
1300
+ get dropped(): number;
1158
1301
  /** Number of entries currently buffered. */
1159
1302
  get size(): number;
1160
- /** Drop every buffered entry. */
1303
+ /** Drop every buffered entry, including the eviction count. */
1161
1304
  clear(): void;
1162
1305
  /**
1163
1306
  * Snapshot of the buffered entries, **newest first** so the panel renders
@@ -1261,6 +1404,17 @@ interface MetricHistorySeries {
1261
1404
  }
1262
1405
  /** {@link readMetricHistory} result: every tracked series with its buckets. */
1263
1406
  interface MetricHistoryResult {
1407
+ /**
1408
+ * True when the distinct-series cap has been reached — a **write-side**
1409
+ * signal ("this shard can no longer admit a brand-new series", see
1410
+ * `admitNewSeries`), not a read-side truncation flag. It is computed over
1411
+ * the whole table regardless of `options.sinceMs`/the row-count read
1412
+ * limit, so it can be `true` even when every series `readMetricHistory`
1413
+ * actually returned fits comfortably: the caller should read it as "a
1414
+ * flood of new series would currently be refused", the same thing
1415
+ * `readQueryInsights`'s `capped` already signals for query-metrics.
1416
+ */
1417
+ capped: boolean;
1264
1418
  series: MetricHistorySeries[];
1265
1419
  }
1266
1420
  /**
@@ -1269,7 +1423,14 @@ interface MetricHistoryResult {
1269
1423
  * omitted field keeps the historical behaviour.
1270
1424
  */
1271
1425
  interface MetricHistoryOptions {
1272
- /** Distinct series tracked before a brand-new one is dropped (default {@link METRIC_HISTORY_MAX_SERIES}). */
1426
+ /**
1427
+ * Distinct series tracked before a brand-new one is REFUSED admission
1428
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
1429
+ * already-tracked series keeps accumulating past the cap, and a flood of
1430
+ * one-off series cannot displace the app's real ones — see
1431
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
1432
+ * read-side signal that admission is being refused.
1433
+ */
1273
1434
  maxSeries?: number;
1274
1435
  /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1275
1436
  retentionBuckets?: number;
@@ -1306,9 +1467,12 @@ declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTr
1306
1467
  * trend line reads oldest→newest.
1307
1468
  *
1308
1469
  * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
1309
- * the studio's time-window selector.
1470
+ * the studio's time-window selector. `options.maxSeries`, mirroring the write
1471
+ * side's tunable, is only used to compute `capped` — it does not affect which
1472
+ * rows are read.
1310
1473
  */
1311
1474
  declare const readMetricHistory: (sql: SqlExec, options?: {
1475
+ maxSeries?: number;
1312
1476
  sinceMs?: number;
1313
1477
  }) => MetricHistoryResult;
1314
1478
  /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
@@ -1317,9 +1481,9 @@ interface QueryStatEntry {
1317
1481
  execCount: number;
1318
1482
  /** Normalised SQL text (literals stripped, truncated). */
1319
1483
  normalizedSql: string;
1320
- /** Total rows read across all executions (SELECT result sizes). */
1484
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
1321
1485
  rowsRead: number;
1322
- /** Total rows written across all executions. */
1486
+ /** Total rows WRITTEN across all executions. */
1323
1487
  rowsWritten: number;
1324
1488
  /** Total wall-clock milliseconds across all executions. */
1325
1489
  totalDurationMs: number;
@@ -1369,14 +1533,23 @@ interface QueryInsightsResult {
1369
1533
  */
1370
1534
  declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1371
1535
  /**
1372
- * Record one statement execution. Creates the table on first call. Silently
1536
+ * Record one statement's activity. Creates the table on first call. Silently
1373
1537
  * skips recording when the normalised statement is empty (shouldn't happen
1374
1538
  * in practice) or when the table is already at the
1375
1539
  * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
1376
- * tracked. The cap check is a single cheap `COUNT(*)` on the primary-key
1377
- * index, so the hot-path cost is minimal.
1540
+ * tracked. See `admitStatement` for how the cap check avoids an unconditional
1541
+ * `COUNT(*)` on every execution.
1542
+ *
1543
+ * `execCount` (default 1) lets a caller fold several executions of the SAME
1544
+ * statement into one call — `shard-do.ts` does this per dispatch so a
1545
+ * query-in-a-loop handler pays one upsert here instead of one per raw
1546
+ * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
1547
+ * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
1548
+ * accumulate sums across separate calls — folding before calling is
1549
+ * indistinguishable, from this table's point of view, from `execCount`
1550
+ * separate calls with the same totals.
1378
1551
  */
1379
- declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number) => void;
1552
+ declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1380
1553
  /**
1381
1554
  * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
1382
1555
  * (the leaderboard's default). Creates the table first so a read on a
@@ -1391,11 +1564,13 @@ type RequestOutcome = "error" | "ok";
1391
1564
  interface RequestLogEntry {
1392
1565
  /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
1393
1566
  cacheHit?: boolean;
1567
+ /** Worker deployment id from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared. Group on this to answer "did this start with a deploy?". */
1568
+ deploymentId?: string;
1394
1569
  /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1395
1570
  durationMs: number;
1396
- /** Error message when `outcome === "error"`; absent on success. */
1571
+ /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
1397
1572
  errorMessage?: string;
1398
- /** The `&lt;file>:&lt;function>` identifier dispatched, e.g. `messages:list`. */
1573
+ /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
1399
1574
  functionPath: string;
1400
1575
  /** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
1401
1576
  identity?: Record<string, unknown>;
@@ -1413,14 +1588,19 @@ interface RequestLogEntry {
1413
1588
  tablesRead: string[];
1414
1589
  /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1415
1590
  tablesWritten: string[];
1591
+ /** W3C trace id (32-hex) of the dispatch; `undefined` on a row appended before this column existed. See the module docstring on the retention asymmetry. */
1592
+ traceId?: string;
1416
1593
  /** Wall-clock millis when the dispatch completed. */
1417
1594
  ts: number;
1418
1595
  /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1419
1596
  userId?: string;
1597
+ /** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
1598
+ versionTag?: string;
1420
1599
  }
1421
1600
  /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1422
1601
  interface AppendRequestLogEntry {
1423
1602
  cacheHit?: boolean;
1603
+ deploymentId?: string;
1424
1604
  durationMs: number;
1425
1605
  errorMessage?: string;
1426
1606
  functionPath: string;
@@ -1431,8 +1611,10 @@ interface AppendRequestLogEntry {
1431
1611
  subscriptionsReRun?: number;
1432
1612
  tablesRead?: string[];
1433
1613
  tablesWritten?: string[];
1614
+ traceId?: string;
1434
1615
  ts: number;
1435
1616
  userId?: string;
1617
+ versionTag?: string;
1436
1618
  }
1437
1619
  /** Knobs the dispatch site threads into a request-log write. */
1438
1620
  interface RequestLogWriteOptions {
@@ -1443,7 +1625,7 @@ interface RequestLogWriteOptions {
1443
1625
  }
1444
1626
  /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
1445
1627
  interface ReadRequestLogOptions {
1446
- /** Functions whose path begins with this prefix (a `&lt;file>:` or `&lt;file>:&lt;fn>` correlation). */
1628
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1447
1629
  functionPathPrefix?: string;
1448
1630
  /** Upper bound on returned rows, clamped to [1, 10000]. */
1449
1631
  limit?: number;
@@ -1451,14 +1633,19 @@ interface ReadRequestLogOptions {
1451
1633
  outcome?: RequestOutcome;
1452
1634
  /** Exact shard-key match. */
1453
1635
  shardKey?: string;
1454
- /** Only entries strictly after this cursor (forward paging). */
1636
+ /**
1637
+ * Only entries strictly after this cursor. Setting it switches the read to
1638
+ * ASCENDING order — see {@link readRequestLog} — because that is the only
1639
+ * ordering under which advancing the cursor to the last returned `seq`
1640
+ * actually pages forward without a hole.
1641
+ */
1455
1642
  sinceSeq?: number;
1456
1643
  /** Keep only entries whose read OR written table set contains this table. */
1457
1644
  tableTouched?: string;
1458
1645
  /** Exact acting-userId match. */
1459
1646
  userId?: string;
1460
1647
  }
1461
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1648
+ /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first — or oldest first when the request paged forward with `sinceSeq` (see {@link readRequestLog}). */
1462
1649
  interface RequestLogResult {
1463
1650
  entries: RequestLogEntry[];
1464
1651
  }
@@ -1473,15 +1660,20 @@ interface ErrorIssue {
1473
1660
  assignee?: string;
1474
1661
  /** Number of `error` rows folded into this Issue within the scanned window. */
1475
1662
  count: number;
1476
- /** The `&lt;file>:&lt;function>` (or `container:&lt;name>`) the errors came from. */
1663
+ /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
1477
1664
  culprit: string;
1478
1665
  /** Wall-clock millis of the oldest folded row. */
1479
1666
  firstSeen: number;
1480
- /** Stable 16-char grouping hash over `functionPath :: bucket(message)`. */
1667
+ /**
1668
+ * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
1669
+ * computed from the RAW (pre-redaction) message at write time and stored on
1670
+ * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
1671
+ * below can't change the grouping.
1672
+ */
1481
1673
  hash: string;
1482
1674
  /** Wall-clock millis of the newest folded row. */
1483
1675
  lastSeen: number;
1484
- /** A representative raw error message — taken from the most recent folded row. */
1676
+ /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
1485
1677
  sampleMessage: string;
1486
1678
  /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
1487
1679
  severity?: IssueSeverity;
@@ -1507,7 +1699,7 @@ interface IssuesResult {
1507
1699
  }
1508
1700
  /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
1509
1701
  interface ReadIssuesOptions {
1510
- /** Functions whose path begins with this prefix (a `&lt;file>:` or `&lt;file>:&lt;fn>` correlation). */
1702
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1511
1703
  functionPathPrefix?: string;
1512
1704
  /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
1513
1705
  limit?: number;
@@ -1518,21 +1710,75 @@ interface ReadIssuesOptions {
1518
1710
  /** Exact acting-userId match. */
1519
1711
  userId?: string;
1520
1712
  }
1713
+ /**
1714
+ * Redact the secrets / PII out of a value before it reaches the durable log, a
1715
+ * Logpush event, a function-metrics row or a span's error message:
1716
+ * `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
1717
+ * `undefined` pass through unchanged.
1718
+ *
1719
+ * On a KEYED object (`args`, `identity`), a key that names a credential
1720
+ * (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
1721
+ * `DATABASE_URL`) has its value masked, numbers included; a key that measures
1722
+ * credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
1723
+ * `shared/credential-redaction.ts` for how keys are judged.
1724
+ *
1725
+ * On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
1726
+ * fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
1727
+ * with a credential name are masked; `Basic …` is masked; and `standardRules`'
1728
+ * value patterns (emails, long digit runs, `Bearer …`, JWTs) apply. Every string
1729
+ * is truncated to 4 KiB in what is stored, and once 16 KiB of one value has been
1730
+ * examined the remaining strings are replaced with a marker, so no arg can hold
1731
+ * the Durable Object in regex work.
1732
+ *
1733
+ * Still NOT caught: a bare credential in prose with no name attached
1734
+ * (`failed with sk_live_…`). This is a credential-and-PII net, not proof that no
1735
+ * secret can reach the log.
1736
+ *
1737
+ * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1738
+ * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
1739
+ * see real arg/identity/error values; production always redacts. The dev
1740
+ * decision is made at the call site from the deployment env, never inferred
1741
+ * here — so a real deploy that omits the env var stays redacted.
1742
+ */
1743
+ declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
1521
1744
  /**
1522
1745
  * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
1523
1746
  * key, giving each shard a monotonic cursor the Logs tab pages through; the
1524
1747
  * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
1525
1748
  * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
1526
1749
  * call it defensively.
1750
+ *
1751
+ * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1752
+ * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
1753
+ * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
1754
+ * trace id, the correlation key to the span ring and to whatever collector
1755
+ * `otlpSink` ships to.
1756
+ *
1757
+ * Both are also added via a guarded `ALTER TABLE`, mirroring
1758
+ * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1759
+ * `__lunora_reqlog__` predates a column gains it on the next call without a
1760
+ * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1761
+ * error from a re-run (or from the freshly-created schema above) is swallowed
1762
+ * per column — the loop is what keeps one column's duplicate from skipping the
1763
+ * next column's add.
1527
1764
  */
1528
1765
  declare const ensureRequestLogTable: (sql: SqlExec) => void;
1529
1766
  /**
1530
1767
  * Append one dispatch to the request log, then trim the log back to the most
1531
1768
  * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
1532
- * table first so callers needn't. Args/identity are redacted here so a raw value
1533
- * never reaches the durable table — callers pass the unredacted entry and rely on
1534
- * this, unless `captureRaw` (dev only) is set. `retention` is the operator's
1535
- * `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the dispatch site.
1769
+ * table first so callers needn't. Args/identity/error message are redacted here
1770
+ * so a raw value never reaches the durable table — callers pass the unredacted
1771
+ * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
1772
+ * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
1773
+ * dispatch site.
1774
+ *
1775
+ * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
1776
+ * it's redacted below, and the resulting hash is persisted in
1777
+ * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
1778
+ * recomputing `fingerprintError` from the (redacted) `error_message` column, so
1779
+ * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
1780
+ * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
1781
+ * existing Issue or change its identity.
1536
1782
  */
1537
1783
  declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1538
1784
  /**
@@ -1541,8 +1787,8 @@ declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry
1541
1787
  * NOT reimplement a transport: it produces a richer, lunora-attributed event and
1542
1788
  * lets CF's existing trace-log pipe ship it. The event mirrors the durable
1543
1789
  * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
1544
- * read/written, cache hit), with `args` AND `identity` redacted exactly like the
1545
- * durable write so no raw PII/secret reaches the log pipeline.
1790
+ * read/written, cache hit), with `args`, `identity`, AND `error` redacted
1791
+ * exactly like the durable write so no raw PII/secret reaches the log pipeline.
1546
1792
  *
1547
1793
  * An `error` outcome goes to `console.error` (surfacing at error level in the
1548
1794
  * trace so a SIEM can alert on it); everything else to `console.log`. The
@@ -1560,7 +1806,7 @@ declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: Requ
1560
1806
  */
1561
1807
  type LogEventInput = LogEvent;
1562
1808
  /**
1563
- * Split a `ctx.log.&lt;level>(...)` call's raw arguments into a display `message`
1809
+ * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
1564
1810
  * and optional structured `fields`. The structured form — a message string plus
1565
1811
  * a plain-object fields bag — is matched only for exactly `(string, object)`;
1566
1812
  * every other shape is console-style and rendered whole (so existing
@@ -1591,18 +1837,35 @@ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1591
1837
  *
1592
1838
  * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1593
1839
  * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1594
- * A field value that can't be serialised (a circular object) would make
1595
- * `JSON.stringify` throw and drop the whole line, so serialisation falls back to
1596
- * a fields-free line rather than losing the event.
1597
- */
1598
- declare const emitLogEvent: (input: LogEventInput) => void;
1599
- /**
1600
- * Read request-log entries newest-first, AND-combining the supplied filters
1601
- * (function-path prefix, exact userId/shardKey/outcome, and a table-touched
1602
- * match against the read OR written table sets), up to `limit` (clamped to
1603
- * [1, 10000]). Each value is a bound parameter, so no filter can inject SQL.
1604
- * Creates the table first so reads on a never-logged shard return `[]` instead
1605
- * of throwing. Mirrors `readAuditLog`/`readCdcChanges`.
1840
+ * Unlike `args`, `fields` IS redacted before it rides this console line — a
1841
+ * developer can attach anything to a fields bag (`ctx.log.info("charged",
1842
+ * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1843
+ * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1844
+ * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1845
+ * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1846
+ * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1847
+ * there today — a conservative default, never a correctness gap. A field value
1848
+ * that can't be serialised (a circular object) would make `JSON.stringify`
1849
+ * throw and drop the whole line, so serialisation falls back to a fields-free
1850
+ * line rather than losing the event.
1851
+ */
1852
+ declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1853
+ /**
1854
+ * Read request-log entries, AND-combining the supplied filters (function-path
1855
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1856
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1857
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1858
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1859
+ * `readAuditLog`/`readCdcChanges`.
1860
+ *
1861
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1862
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1863
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1864
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1865
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1866
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1867
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1868
+ * the shard takes, the more it drops.
1606
1869
  */
1607
1870
  declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1608
1871
  declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
@@ -1620,7 +1883,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1620
1883
  *
1621
1884
  * `admin-token-weak`: `LUNORA_ADMIN_TOKEN` is set but short enough to be brute-forceable. (An *unset* token disables admin introspection entirely, so this audit — itself admin-gated — only ever runs with a token present.)
1622
1885
  *
1623
- * `ws-gate-open`: admin HTTP RPCs require the bearer, but `LUNORA_WS_BEARER` is unset so the WebSocket upgrade gate defaults open — live admin subscriptions (Logs, Metrics, …) are reachable without a credential.
1886
+ * `ws-gate-open`: `LUNORA_WS_BEARER` is unset, so the WebSocket upgrade gate defaults open and anyone who can reach the worker can open a socket and run ordinary USER subscriptions (whatever `ctx.auth` / RLS then allows them to read). Admin subscriptions are NOT part of this: they require the socket's `admin` stamp, which the upgrade sets only from `LUNORA_ADMIN_TOKEN` or a minted admin sub-token, so an unset `LUNORA_WS_BEARER` never exposes Logs/Metrics/introspection. Which is why this is a posture finding about the app's own live-query surface, not an admin hole — set the var when subscribers are expected to present a shared credential.
1624
1887
  *
1625
1888
  * `dev-args-unredacted`: the worker reports a development environment, so the durable request log captures raw, un-redacted args and identity (PII). A production deploy mislabeled as dev would persist sensitive payloads.
1626
1889
  *
@@ -1692,6 +1955,15 @@ interface TraceSpan {
1692
1955
  message: string;
1693
1956
  type: string;
1694
1957
  };
1958
+ /**
1959
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
1960
+ * `span.recordException(...)`. Carried through so a handled retry or a
1961
+ * swallowed exception is visible on the span it happened in, which is the
1962
+ * only place it is interpretable. Absent when the body recorded none.
1963
+ */
1964
+ events?: SpanEventPoint[];
1965
+ /** OTel `SpanKind`; absent means `"internal"`. */
1966
+ kind?: OtlpSpanKind;
1695
1967
  name: string;
1696
1968
  /** Start of this span relative to the trace's start, in ms. */
1697
1969
  offsetMs: number;
@@ -1710,12 +1982,25 @@ interface TraceSummary {
1710
1982
  rootName: string;
1711
1983
  shardKey?: string;
1712
1984
  /**
1713
- * Spans ordered by `(offsetMs, depth)`, ready to render as waterfall rows.
1714
- * Start time alone is not enough to order them: spans are recorded on
1715
- * completion and `startTs` has millisecond resolution, so a parent and its
1716
- * child routinely tie. Breaking that tie by depth makes the sequence a valid
1717
- * pre-order traversal of the span tree, so indenting each row by its `depth`
1718
- * yields the nesting without a separate tree walk.
1985
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
1986
+ * immediately followed by its own subtree, siblings in start order. So
1987
+ * indenting each row by its `depth` yields the real nesting — the row above
1988
+ * a `depth`-`n+1` row is genuinely its parent.
1989
+ *
1990
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
1991
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
1992
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
1993
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
1994
+ * parent it does not belong to.
1995
+ *
1996
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
1997
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
1998
+ * not a bug — so it does not advance at all across pure computation. Every
1999
+ * duration in this package is `Date.now() - startTs`, which means a span
2000
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2001
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2002
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2003
+ * span means "no I/O happened here", not "this was fast".
1719
2004
  */
1720
2005
  spans: TraceSpan[];
1721
2006
  startTs: number;
@@ -1730,10 +2015,19 @@ interface TraceSummary {
1730
2015
  declare class SpanBuffer {
1731
2016
  private readonly buffer;
1732
2017
  private readonly capacity;
2018
+ /** How many spans the ring has evicted since it was last cleared. */
2019
+ private droppedCount;
1733
2020
  constructor(capacity?: number);
2021
+ /**
2022
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2023
+ * ring silently drops its oldest span once full, which makes a busy instance
2024
+ * look identical to one that recorded exactly `capacity` spans; this count
2025
+ * is the difference between the two.
2026
+ */
2027
+ get dropped(): number;
1734
2028
  /** Number of spans currently buffered. */
1735
2029
  get size(): number;
1736
- /** Drop every buffered span. */
2030
+ /** Drop every buffered span, including the eviction count. */
1737
2031
  clear(): void;
1738
2032
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1739
2033
  entries(): SpanEvent[];
@@ -1815,4 +2109,61 @@ declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1815
2109
  sampled: boolean;
1816
2110
  traceId: string;
1817
2111
  };
1818
- export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry, type AuthMetrics, type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DatabaseInstrumentation, type DatabaseTally, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FunctionMetricBucket, type FunctionMetricIndexHit, type HostTracingLike, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistorySeries, type MetricSeries, type MetricsDeps, type QueryStatEntry, REQUEST_LOG_TABLE, type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogResult, type RequestLogWriteOptions, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanHandle, type TraceAnchor, type TraceSpan, type TraceSummary, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, resolveTraceAnchor, upsertIssueState };
2112
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2113
+ /**
2114
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2115
+ *
2116
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2117
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2118
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2119
+ * inside `@lunora/do` only because that is where the Durable Object it
2120
+ * instruments happens to live.
2121
+ *
2122
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2123
+ * reverse, which is what makes this reusable by a second host rather than
2124
+ * merely relocated.
2125
+ *
2126
+ * This barrel is deliberately curated rather than `export *`. A star export
2127
+ * would promote every module internal to permanent public API — the exact
2128
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2129
+ * core. What is exported here is what a consumer actually needs.
2130
+ */
2131
+ type AuthMetrics,
2132
+ /**
2133
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2134
+ *
2135
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2136
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2137
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2138
+ * inside `@lunora/do` only because that is where the Durable Object it
2139
+ * instruments happens to live.
2140
+ *
2141
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2142
+ * reverse, which is what makes this reusable by a second host rather than
2143
+ * merely relocated.
2144
+ *
2145
+ * This barrel is deliberately curated rather than `export *`. A star export
2146
+ * would promote every module internal to permanent public API — the exact
2147
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2148
+ * core. What is exported here is what a consumer actually needs.
2149
+ */
2150
+ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DanglingReference, type DanglingReferenceResult, type DatabaseInstrumentation, type DatabaseTally, type DatabaseTelemetryDeps, type ErrorIssue, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FoldedTraces, type FunctionMetricBucket, type FunctionMetricBucketsResult, type FunctionMetricIndexHit, type HostSpanLike, type HostTracingLike, type HostTracingResolver, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricEvent, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistoryResult, type MetricHistorySeries, type MetricKind, type MetricSeries, type MetricsDeps, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
2151
+ /**
2152
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2153
+ *
2154
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2155
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2156
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2157
+ * inside `@lunora/do` only because that is where the Durable Object it
2158
+ * instruments happens to live.
2159
+ *
2160
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2161
+ * reverse, which is what makes this reusable by a second host rather than
2162
+ * merely relocated.
2163
+ *
2164
+ * This barrel is deliberately curated rather than `export *`. A star export
2165
+ * would promote every module internal to permanent public API — the exact
2166
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2167
+ * core. What is exported here is what a consumer actually needs.
2168
+ */
2169
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, upsertIssueState };