@lunora/observability 1.0.0-alpha.15 → 1.0.0-alpha.151

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 (44) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +495 -119
  3. package/dist/index.d.ts +495 -119
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.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-CHV71isV.mjs +56 -0
  8. package/dist/packem_shared/ISSUE_SEVERITIES-0SJ0glV4.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-BUw1hK3f.mjs +1 -0
  12. package/dist/packem_shared/REQUEST_LOG_TABLE-Dsev7GAt.mjs +1 -0
  13. package/dist/packem_shared/SpanBuffer-DnYOc8uk.mjs +1 -0
  14. package/dist/packem_shared/applyHostRootSpan-DToRfMn8.mjs +1 -0
  15. package/dist/packem_shared/createDatabaseTally-mUypNATC.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-D8wcdkye.mjs +1 -0
  17. package/dist/packem_shared/findDanglingReferences-BaOyIdxz.mjs +1 -0
  18. package/dist/packem_shared/latencyBucketIndex--kZoW0vc.mjs +32 -0
  19. package/dist/packem_shared/otlp-DR7601NL.mjs +1 -0
  20. package/dist/packem_shared/prune-marker-B4An9Nuj.mjs +1 -0
  21. package/dist/packem_shared/readMetricHistory-BjPDSBkS.mjs +31 -0
  22. package/dist/packem_shared/request-log-YtJxmSWX.mjs +24 -0
  23. package/dist/packem_shared/resolveTraceAnchor-DDAPZRBB.mjs +1 -0
  24. package/dist/packem_shared/run-sql-0aPgJkIw.mjs +1 -0
  25. package/package.json +6 -5
  26. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-DpVJl1bU.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-BXPeggfa.mjs +0 -56
  29. package/dist/packem_shared/ISSUE_SEVERITIES-E91cPcjt.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-DEHWxkC0.mjs +0 -1
  34. package/dist/packem_shared/SpanBuffer-BR6Ff0M-.mjs +0 -1
  35. package/dist/packem_shared/createDatabaseTally-_X8tMObq.mjs +0 -1
  36. package/dist/packem_shared/createMetrics-1k6z1bld.mjs +0 -1
  37. package/dist/packem_shared/findDanglingReferences-D-x9LvY0.mjs +0 -1
  38. package/dist/packem_shared/metric-buffer-CdgXal7w.mjs +0 -1
  39. package/dist/packem_shared/readMetricHistory-BdC01ptv.mjs +0 -31
  40. package/dist/packem_shared/readQueryInsights-BprtfEp-.mjs +0 -32
  41. package/dist/packem_shared/request-log-CHl9HlyL.mjs +0 -21
  42. package/dist/packem_shared/resolveTraceAnchor-IAN8riI0.mjs +0 -1
  43. package/dist/packem_shared/run-sql-BP8BI9zV.mjs +0 -1
  44. 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
  /**
@@ -160,6 +160,14 @@ interface EvaluationInput {
160
160
  /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
161
161
  score: number;
162
162
  }
163
+ /** The unredacted facts about a thrown value, for observability sinks only. */
164
+ interface ErrorDetail {
165
+ /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
+ code?: string;
167
+ message: string;
168
+ name: string;
169
+ stack?: string;
170
+ }
163
171
  /**
164
172
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
165
173
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -173,6 +181,14 @@ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" |
173
181
  interface LogEvent {
174
182
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
175
183
  args: unknown[];
184
+ /**
185
+ * The first `Error` the call was handed, as an argument
186
+ * (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
187
+ * unredacted `message`, `stack`, and `code` when it carries one. Absent when
188
+ * the line logged no `Error`. An error tracker reads this rather than parsing
189
+ * the rendered `message`.
190
+ */
191
+ error?: ErrorDetail;
176
192
  /**
177
193
  * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
178
194
  * event** via `ctx.log.event(name, fields)` rather than as a human-readable
@@ -200,6 +216,12 @@ interface LogEvent {
200
216
  level: ContextLogLevel;
201
217
  /** Display string — the message, or the console-style args rendered and space-joined. */
202
218
  message: string;
219
+ /**
220
+ * Cloudflare Ray ID of the request this line was emitted under (see
221
+ * `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
222
+ * and for dispatches no HTTP request started (an alarm, a subscription re-run).
223
+ */
224
+ rayId?: string;
203
225
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
204
226
  shardKey?: string;
205
227
  /** Span id of the RPC this line was emitted under (trace correlation), or absent. */
@@ -320,10 +342,50 @@ interface SpanHandle {
320
342
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
343
  * reach around the API for it.
322
344
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
345
+ spanContext: () => SpanContextIds;
346
+ }
347
+ /**
348
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
349
+ *
350
+ * `sampled` is the propagated head decision (absent means "no verdict reached
351
+ * this tier", which every consumer reads as keep). It rides alongside the ids
352
+ * because everything that needs the ids to announce this span downstream — a
353
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
354
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
355
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
356
+ */
357
+ interface SpanContextIds {
358
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
359
+ sampled?: boolean;
360
+ /** This span's id (16-hex). */
361
+ spanId: string;
362
+ /** The trace this span belongs to (32-hex). */
363
+ traceId: string;
364
+ }
365
+ /**
366
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
367
+ * argument.
368
+ *
369
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
370
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
371
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
372
+ * so the id the adapter published is the id that reaches the collector rather
373
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
374
+ * reason: an adapter that tracks its own parent/child structure (OTel's
375
+ * `Context`) can express it without an ambient span stack.
376
+ *
377
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
378
+ * never mints its own ids.
379
+ *
380
+ * Both ids are required: an adapter that has published one has published the
381
+ * other, and `identity` is itself optional — omitting it, not passing a partial
382
+ * object, is how a caller says "no adapter involved".
383
+ */
384
+ interface SpanIdentity {
385
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
386
+ parentSpanId: string;
387
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
388
+ spanId: string;
327
389
  }
328
390
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
391
  interface SpanOptions {
@@ -402,6 +464,24 @@ interface SpanEvent {
402
464
  * the outermost span, which is why the fold prefers it as a trace's anchor.
403
465
  */
404
466
  dispatch?: boolean;
467
+ /**
468
+ * Cloudflare Ray ID of the request this span ran under (see
469
+ * `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
470
+ */
471
+ rayId?: string;
472
+ /**
473
+ * The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
474
+ * sink. Absent means no verdict reached this tier, which every consumer reads
475
+ * as keep.
476
+ *
477
+ * Carried because the OTLP encoders write it into the span's `flags` field,
478
+ * and a span exported with no `flags` reads as UNSAMPLED (0) at the collector
479
+ * — on EVERY span, including the ones it is meant to keep. It is genuinely
480
+ * per-span rather than derivable from "it was exported at all": a trace the
481
+ * tail bias rescued (head-sampled out, then errored) is exported with the bit
482
+ * CLEAR, and saying otherwise misreports the trace's verdict.
483
+ */
484
+ sampled?: boolean;
405
485
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
406
486
  shardKey?: string;
407
487
  /** This span's own id (16-hex). */
@@ -413,35 +493,6 @@ interface SpanEvent {
413
493
  /** Acting userId, or absent when anonymous. */
414
494
  userId?: string;
415
495
  }
416
- /**
417
- * Structural shape of the `ctx.trace` span factory (see the server
418
- * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
419
- * dependency on `@lunora/server`; a cross-package assignability guard in
420
- * `@lunora/testing` fails the build if the two drift apart.
421
- *
422
- * The body's second argument is the enclosing span's {@link SpanHandle}, through
423
- * which it can attach attributes only known *after* it resolves (post-hoc). It is
424
- * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
425
- */
426
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions) => Promise<T>;
427
- /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
428
- interface ContextMetrics {
429
- count: (name: string, value?: number, attributes?: LogFields) => void;
430
- gauge: (name: string, value: number, attributes?: LogFields) => void;
431
- record: (name: string, value: number, attributes?: LogFields) => void;
432
- }
433
- /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
434
- interface TraceAnchor {
435
- rootSpanId: string;
436
- /**
437
- * The W3C `sampled` verdict for this trace, inherited from the inbound
438
- * `traceparent` when there was one. Carried on the anchor rather than
439
- * re-derived per outbound call so every `ctx.fetch` of one dispatch
440
- * propagates the same answer.
441
- */
442
- sampled?: boolean;
443
- traceId: string;
444
- }
445
496
  /**
446
497
  * Minimal structural shape of one **host-native custom span** — the object a
447
498
  * `tracing.enterSpan(name, (span) => …)` callback receives (GA 2026-06-16). Only
@@ -465,8 +516,28 @@ interface HostSpanLike {
465
516
  * a span nobody will read.
466
517
  */
467
518
  readonly isTraced: boolean;
519
+ /**
520
+ * Record an OTel `exception` event on the span (CF 2026-09-25). Optional and
521
+ * feature-detected: older runtimes only have `setAttribute`.
522
+ */
523
+ recordException?: (exception: {
524
+ message: string;
525
+ name: string;
526
+ }) => unknown;
468
527
  /** Attach one primitive attribute to the CF span. */
469
- setAttribute: (key: string, value: boolean | number | string | undefined) => void;
528
+ setAttribute: (key: string, value: boolean | number | string | undefined) => unknown;
529
+ /** Attach several attributes in one call (CF 2026-09-25). Optional, like `recordException`. */
530
+ setAttributes?: (attributes: Record<string, boolean | number | string>) => unknown;
531
+ /**
532
+ * Set the span's OTel status (workers-types 5.20260929). Optional and
533
+ * feature-detected, like `recordException`: older runtimes lack it. The
534
+ * bridge only ever sets `"error"` — OTel instrumentation leaves a successful
535
+ * span `"unset"` rather than marking it `"ok"`.
536
+ */
537
+ setStatus?: (status: {
538
+ code: "error" | "ok" | "unset";
539
+ message?: string;
540
+ }) => unknown;
470
541
  }
471
542
  /**
472
543
  * Minimal structural shape of the `tracing` namespace exported by
@@ -475,6 +546,11 @@ interface HostSpanLike {
475
546
  */
476
547
  interface HostTracingLike {
477
548
  enterSpan: <T>(name: string, callback: (span: HostSpanLike) => T) => T;
549
+ /**
550
+ * The currently active span; outside any custom span, the invocation's root
551
+ * span (CF 2026-09-25). Optional and feature-detected: absent on older runtimes.
552
+ */
553
+ getActiveSpan?: () => HostSpanLike | undefined;
478
554
  }
479
555
  /**
480
556
  * Resolves CF's `tracing` namespace, or `undefined` when it is unavailable —
@@ -484,6 +560,73 @@ interface HostTracingLike {
484
560
  * supplies the real resolver, tests a fake or `undefined`.
485
561
  */
486
562
  type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | undefined> | undefined;
563
+ /**
564
+ * Copy an attribute bag onto a host span, best-effort: one native
565
+ * `setAttributes` call where the runtime has it, a `setAttribute` loop where it
566
+ * does not. Skipped for an untraced span; non-primitive values are dropped,
567
+ * since CF's setters take `string | number | boolean` only.
568
+ */
569
+ declare const setHostSpanAttributes: (span: HostSpanLike, attributes: Record<string, LogFields[string]>) => void;
570
+ /**
571
+ * Mirror a finished dispatch onto the host's invocation span — the one
572
+ * `tracing.getActiveSpan()` returns once every `ctx.trace` custom span has
573
+ * ended. Pure and fully best-effort: a missing `getActiveSpan`, an untraced span
574
+ * or a throwing setter is a silent no-op, never an error for the dispatch.
575
+ *
576
+ * `attributes` is the dispatch root span's already-redacted wide event, when it
577
+ * recorded one. `error` is set when the dispatch failed; its `serverFault` is the
578
+ * CALLER's verdict on whether that failure is the server's: the status of the
579
+ * response it actually sent (>= 500) for an RPC, always `true` for a trigger
580
+ * that threw. Only a server fault marks the span failed; a 4xx is an expected
581
+ * client outcome that OTel's server-span convention leaves `"unset"`. `message`
582
+ * must already be redacted.
583
+ *
584
+ * The status is written before the attributes so a throwing attribute setter
585
+ * cannot drop it.
586
+ */
587
+ declare const applyHostRootSpan: (tracing: HostTracingLike | undefined, root: {
588
+ attributes?: Record<string, LogFields[string]>;
589
+ error?: {
590
+ message: string;
591
+ serverFault: boolean;
592
+ };
593
+ }) => void;
594
+ /**
595
+ * Structural shape of the `ctx.trace` span factory (see the server
596
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
597
+ * dependency on `@lunora/server`; a cross-package assignability guard in
598
+ * `@lunora/testing` fails the build if the two drift apart.
599
+ *
600
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
601
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
602
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
603
+ */
604
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
605
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
606
+ interface ContextMetrics {
607
+ count: (name: string, value?: number, attributes?: LogFields) => void;
608
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
609
+ record: (name: string, value: number, attributes?: LogFields) => void;
610
+ }
611
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
612
+ interface TraceAnchor {
613
+ /**
614
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
615
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
616
+ * log line of the dispatch stamps the same value. Absent off the edge.
617
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
618
+ */
619
+ rayId?: string;
620
+ rootSpanId: string;
621
+ /**
622
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
623
+ * `traceparent` when there was one. Carried on the anchor rather than
624
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
625
+ * propagates the same answer.
626
+ */
627
+ sampled?: boolean;
628
+ traceId: string;
629
+ }
487
630
  /** What {@link createTracer} needs from the shard to build a span. */
488
631
  interface TracerDeps {
489
632
  /** The trace this ctx's spans belong to. */
@@ -560,10 +703,7 @@ interface SpanCollector {
560
703
  * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
704
  * escape hatch rather than shipping to a third-party collector by default.
562
705
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
706
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean) => SpanCollector;
567
707
  /**
568
708
  * Build the `ctx.trace` span factory for one dispatched function.
569
709
  *
@@ -605,7 +745,7 @@ declare const createSpanCollector: (ids: {
605
745
  *
606
746
  * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
607
747
  * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
608
- * Object under `@cloudflare/vitest-pool-workers` (see
748
+ * Object under `@cloudflare/vitest-plugin` (see
609
749
  * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
610
750
  * from `cloudflare:workers`, its callback executes and returns the body value
611
751
  * without throwing, `span.isTraced` is a real boolean, and — the key additive
@@ -625,6 +765,14 @@ declare const createTracer: (deps: TracerDeps) => ContextTracer;
625
765
  interface TracedFetchDeps {
626
766
  /** The trace the CLIENT spans belong to. */
627
767
  anchor: TraceAnchor;
768
+ /**
769
+ * Whether to record a failed fetch's error message verbatim rather than
770
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
771
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
772
+ * query string would otherwise reach the collector in the clear on the very
773
+ * span whose `url.full` is scrubbed by `redactUrl`.
774
+ */
775
+ captureRaw?: boolean;
628
776
  /** Function path the spans are attributed to. */
629
777
  functionPath: string;
630
778
  /**
@@ -660,6 +808,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
660
808
  * Kind is `client` rather than `internal` — that is what lets a collector draw
661
809
  * the edge to the downstream service in a service map.
662
810
  *
811
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
812
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
813
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
814
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
815
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
816
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
817
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
818
+ * the span whose bar you want it under and read the two side by side.
819
+ *
663
820
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
664
821
  * recorded as an ERROR span (it is a failed call from the caller's point of
665
822
  * view) while still being returned normally — instrumentation, never flow
@@ -723,7 +880,12 @@ interface DatabaseTally {
723
880
  spansTruncated: boolean;
724
881
  }
725
882
  /**
726
- * How much detail `ctx.db` auto-instrumentation produces.
883
+ * Which instrumented surface a tally belongs to, and the key prefix
884
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
885
+ */
886
+ type TallySurface = "db" | "sql";
887
+ /**
888
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
727
889
  *
728
890
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
729
891
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -734,16 +896,24 @@ interface DatabaseTally {
734
896
  * `"off"` — no database telemetry at all.
735
897
  */
736
898
  type DatabaseInstrumentation = "off" | "spans" | "summary";
737
- /** What {@link instrumentDatabase} needs to record what it observes. */
899
+ /**
900
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
901
+ * instrumenter needs — declared here so this package takes no dependency on
902
+ * hyperdrive.
903
+ */
904
+ interface SqlClientLike {
905
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
906
+ readonly dbSystem?: string;
907
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
908
+ }
909
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
738
910
  interface DatabaseTelemetryDeps {
739
911
  /** The trace produced spans belong to (`"spans"` mode only). */
740
912
  anchor: TraceAnchor;
741
913
  /**
742
- * Whether to record a failed call's error message verbatim rather than
743
- * redacted (`"spans"` mode only) — the same dev-only escape hatch as
744
- * `TracerDeps.captureRaw`. A constraint-error message quotes the
745
- * conflicting row, so this CLIENT span gets the same default-redacted
746
- * posture as the request log and function-metrics sinks.
914
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
915
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
916
+ * {@link failureMessage} for what each surface records without it.
747
917
  */
748
918
  captureRaw?: boolean;
749
919
  /** Function path spans and attributes are attributed to. */
@@ -759,14 +929,20 @@ interface DatabaseTelemetryDeps {
759
929
  * increments numbers on it; the shard reads it ONCE at the dispatch boundary
760
930
  * and formats it with {@link formatTally}.
761
931
  *
762
- * Two properties fall out of that split. Per-call cost stays at a few integer
763
- * increments — no object allocation, no lookup — which matters because this is
764
- * on the path of every query. And because nothing is written through the
765
- * dispatch's `SpanHandle`, the wide-event collector is never materialized, so
766
- * a handler that instrumented nothing still doesn't trip the root-span gate.
932
+ * Per-call cost stays at a few integer increments — no object allocation, no
933
+ * lookup — which matters because this is on the path of every query. Nothing
934
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
935
+ * collector is never materialized by instrumentation alone: a dispatch that
936
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
937
+ * log record unless the handler actually opened `ctx.span`.
767
938
  */
768
939
  tally: DatabaseTally;
769
- /** Read lazily — the acting user is resolved per span. */
940
+ /**
941
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
942
+ * they instrument the client, and return that captured value: a span is
943
+ * built after the call's await, and per-request shared state read by then
944
+ * may already belong to a concurrent request.
945
+ */
770
946
  userId: () => string | undefined;
771
947
  }
772
948
  /**
@@ -775,24 +951,42 @@ interface DatabaseTelemetryDeps {
775
951
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
776
952
  * path costs nothing — not even a proxy indirection.
777
953
  *
778
- * Implemented as a `Proxy` rather than by enumerating and rebinding methods:
779
- * `DatabaseWriterLike` has optional members that a given backend may or may not
780
- * implement, plus properties (`system`) and builder factories (`query`) that
781
- * must pass through untouched. A proxy instruments exactly what it is asked to
782
- * and is transparently correct for everything else, including members added
783
- * later — an enumeration would silently stop covering them.
954
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
955
+ * optional members that a given backend may or may not implement, plus
956
+ * properties (`system`) and builder factories (`query`) that must pass through
957
+ * untouched. A proxy instruments exactly what it is asked to and is
958
+ * transparently correct for everything else, including members added later —
959
+ * an enumeration would silently stop covering them.
784
960
  */
785
961
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
962
+ /**
963
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
964
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
965
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
966
+ * as `sql.*`), never `ctx.db`'s.
967
+ *
968
+ * Its span carries no statement text and no parameters — only the
969
+ * leading-keyword operation, the system, and the returned row count. No
970
+ * `db.collection.name` either: naming the table means parsing past
971
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
972
+ * safe. A failure records its TYPE (see {@link failureMessage}).
973
+ *
974
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
975
+ * method to cover. Everything else on the client passes through untouched, and
976
+ * `"off"` returns the client itself.
977
+ */
978
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
786
979
  /** A zero'd tally for one dispatch. */
787
980
  declare const createDatabaseTally: () => DatabaseTally;
788
981
  /**
789
- * Render the running tally as span attributes.
982
+ * Render the running tally as span attributes, under its surface's prefix
983
+ * ({@link TallySurface}).
790
984
  *
791
985
  * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
792
- * Building this object on every call was pure waste on a hot path. It is a handful of keys, so the per-call cost is a small object
793
- * assignment — the property that makes `"summary"` mode scale to any call count.
986
+ * It is a handful of keys, so the per-call cost is a small object assignment —
987
+ * the property that makes `"summary"` mode scale to any call count.
794
988
  */
795
- declare const formatTally: (tally: DatabaseTally) => LogFields;
989
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
796
990
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
797
991
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
798
992
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -887,8 +1081,15 @@ interface FunctionMetricIndexHit {
887
1081
  /** The table the index is declared on. */
888
1082
  table: string;
889
1083
  }
890
- /** Fields recorded for one completed dispatch. `errored` advances the failure counters. */
1084
+ /**
1085
+ * Fields recorded for one completed dispatch, or for a coalesced delta of
1086
+ * several. `errored` advances the failure counters. The optional count-carrying
1087
+ * fields let a caller that batched N dispatches write their exact sum in one
1088
+ * upsert; omitted, every field defaults to the single-dispatch value.
1089
+ */
891
1090
  interface RecordFunctionMetricInput {
1091
+ /** Dispatches this record stands for. Default `1`. */
1092
+ calls?: number;
892
1093
  /**
893
1094
  * Whether the dispatch failed on an optimistic-concurrency (OCC) write
894
1095
  * conflict — a compare-and-swap that lost to a concurrent commit. Advances
@@ -897,12 +1098,29 @@ interface RecordFunctionMetricInput {
897
1098
  * Omitted/false on the common path, keeping the hot path unchanged.
898
1099
  */
899
1100
  conflicted?: boolean;
1101
+ /** Conflicts in a coalesced delta. Default `conflicted ? 1 : 0`. */
1102
+ conflicts?: number;
1103
+ /** Longest handler time in a coalesced delta. Default `durationMs`. */
1104
+ durationMaxMs?: number;
1105
+ /** Shortest handler time in a coalesced delta. Default `durationMs`. */
1106
+ durationMinMs?: number;
900
1107
  /** Wall-clock millis the handler took. */
901
1108
  durationMs: number;
1109
+ /** Summed handler time of a coalesced delta. Default `durationMs`. */
1110
+ durationTotalMs?: number;
902
1111
  /** Whether the dispatch threw. */
903
1112
  errored: boolean;
904
1113
  /** Most recent failure message, recorded only when `errored`. */
905
1114
  errorMessage?: string;
1115
+ /** Failed dispatches in a coalesced delta. Default `errored ? 1 : 0`. */
1116
+ errors?: number;
1117
+ /**
1118
+ * Per-`(table, index)` hit counts of a coalesced delta (one per dispatch that
1119
+ * used the index). When set, replaces {@link RecordFunctionMetricInput.indexHits}.
1120
+ */
1121
+ indexHitCounts?: ReadonlyArray<IndexHit & {
1122
+ count: number;
1123
+ }>;
906
1124
  /**
907
1125
  * Distinct declared indexes this dispatch exercised (used to narrow a read),
908
1126
  * collected from the `onIndexUse` signal. Each entry bumps the
@@ -911,8 +1129,18 @@ interface RecordFunctionMetricInput {
911
1129
  * dispatch used no declared index, keeping the hot path unchanged.
912
1130
  */
913
1131
  indexHits?: ReadonlyArray<IndexHit>;
1132
+ /** Epoch-ms of the latest failure in a coalesced delta. Default `errored ? ts : null`. */
1133
+ lastErrorAt?: number | null;
914
1134
  /** The `<file>:<function>` identifier. */
915
1135
  path: string;
1136
+ /**
1137
+ * Per-table full-scan counts of a coalesced delta (one per dispatch that
1138
+ * scanned the table). When set, replaces {@link RecordFunctionMetricInput.scannedTables}.
1139
+ */
1140
+ scanCounts?: ReadonlyArray<{
1141
+ count: number;
1142
+ table: string;
1143
+ }>;
916
1144
  /**
917
1145
  * Distinct tables this dispatch full-scanned (read with no index / point
918
1146
  * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
@@ -1196,6 +1424,8 @@ interface LogEntry {
1196
1424
  level: LogLevel;
1197
1425
  message: string;
1198
1426
  timestamp: number;
1427
+ /** 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. */
1428
+ traceId?: string;
1199
1429
  }
1200
1430
  /**
1201
1431
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1216,10 +1446,21 @@ declare class LogBuffer {
1216
1446
  /** Backing store, kept in insertion order (oldest first). */
1217
1447
  private readonly buffer;
1218
1448
  private readonly capacity;
1449
+ /** How many entries the ring has evicted since it was last cleared. */
1450
+ private droppedCount;
1219
1451
  constructor(capacity?: number);
1452
+ /**
1453
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1454
+ *
1455
+ * Without it a full ring is indistinguishable from a quiet instance that
1456
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1457
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1458
+ * count is what turns "the newest 500" into an honest statement.
1459
+ */
1460
+ get dropped(): number;
1220
1461
  /** Number of entries currently buffered. */
1221
1462
  get size(): number;
1222
- /** Drop every buffered entry. */
1463
+ /** Drop every buffered entry, including the eviction count. */
1223
1464
  clear(): void;
1224
1465
  /**
1225
1466
  * Snapshot of the buffered entries, **newest first** so the panel renders
@@ -1342,7 +1583,14 @@ interface MetricHistoryResult {
1342
1583
  * omitted field keeps the historical behaviour.
1343
1584
  */
1344
1585
  interface MetricHistoryOptions {
1345
- /** Distinct series tracked before the least-recently-updated one is evicted to admit a new one (default {@link METRIC_HISTORY_MAX_SERIES}). */
1586
+ /**
1587
+ * Distinct series tracked before a brand-new one is REFUSED admission
1588
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
1589
+ * already-tracked series keeps accumulating past the cap, and a flood of
1590
+ * one-off series cannot displace the app's real ones — see
1591
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
1592
+ * read-side signal that admission is being refused.
1593
+ */
1346
1594
  maxSeries?: number;
1347
1595
  /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1348
1596
  retentionBuckets?: number;
@@ -1393,13 +1641,15 @@ interface QueryStatEntry {
1393
1641
  execCount: number;
1394
1642
  /** Normalised SQL text (literals stripped, truncated). */
1395
1643
  normalizedSql: string;
1396
- /** Total rows read across all executions (SELECT result sizes). */
1644
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
1397
1645
  rowsRead: number;
1398
- /** Total rows written across all executions. */
1646
+ /** Total rows WRITTEN across all executions. */
1399
1647
  rowsWritten: number;
1400
1648
  /** Total wall-clock milliseconds across all executions. */
1401
1649
  totalDurationMs: number;
1402
1650
  }
1651
+ /** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
1652
+ declare const latencyBucketIndex: (durationMs: number) => number;
1403
1653
  /** One statement's activity within a chosen time range. */
1404
1654
  interface QueryInsightEntry {
1405
1655
  /** Mean milliseconds per execution across the range. */
@@ -1476,6 +1726,8 @@ type RequestOutcome = "error" | "ok";
1476
1726
  interface RequestLogEntry {
1477
1727
  /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
1478
1728
  cacheHit?: boolean;
1729
+ /** 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?". */
1730
+ deploymentId?: string;
1479
1731
  /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1480
1732
  durationMs: number;
1481
1733
  /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
@@ -1498,26 +1750,39 @@ interface RequestLogEntry {
1498
1750
  tablesRead: string[];
1499
1751
  /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1500
1752
  tablesWritten: string[];
1753
+ /** 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. */
1754
+ traceId?: string;
1501
1755
  /** Wall-clock millis when the dispatch completed. */
1502
1756
  ts: number;
1503
1757
  /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1504
1758
  userId?: string;
1759
+ /** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
1760
+ versionTag?: string;
1505
1761
  }
1506
1762
  /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1507
1763
  interface AppendRequestLogEntry {
1508
1764
  cacheHit?: boolean;
1765
+ deploymentId?: string;
1509
1766
  durationMs: number;
1510
1767
  errorMessage?: string;
1511
1768
  functionPath: string;
1512
1769
  identity?: Record<string, unknown>;
1513
1770
  outcome: RequestOutcome;
1771
+ /**
1772
+ * Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
1773
+ * Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
1774
+ * keeps its `trace_id` join key and has no column for it.
1775
+ */
1776
+ rayId?: string;
1514
1777
  redactedArgs?: unknown;
1515
1778
  shardKey?: string;
1516
1779
  subscriptionsReRun?: number;
1517
1780
  tablesRead?: string[];
1518
1781
  tablesWritten?: string[];
1782
+ traceId?: string;
1519
1783
  ts: number;
1520
1784
  userId?: string;
1785
+ versionTag?: string;
1521
1786
  }
1522
1787
  /** Knobs the dispatch site threads into a request-log write. */
1523
1788
  interface RequestLogWriteOptions {
@@ -1536,14 +1801,19 @@ interface ReadRequestLogOptions {
1536
1801
  outcome?: RequestOutcome;
1537
1802
  /** Exact shard-key match. */
1538
1803
  shardKey?: string;
1539
- /** Only entries strictly after this cursor (forward paging). */
1804
+ /**
1805
+ * Only entries strictly after this cursor. Setting it switches the read to
1806
+ * ASCENDING order — see {@link readRequestLog} — because that is the only
1807
+ * ordering under which advancing the cursor to the last returned `seq`
1808
+ * actually pages forward without a hole.
1809
+ */
1540
1810
  sinceSeq?: number;
1541
1811
  /** Keep only entries whose read OR written table set contains this table. */
1542
1812
  tableTouched?: string;
1543
1813
  /** Exact acting-userId match. */
1544
1814
  userId?: string;
1545
1815
  }
1546
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1816
+ /** 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}). */
1547
1817
  interface RequestLogResult {
1548
1818
  entries: RequestLogEntry[];
1549
1819
  }
@@ -1609,31 +1879,31 @@ interface ReadIssuesOptions {
1609
1879
  userId?: string;
1610
1880
  }
1611
1881
  /**
1612
- * Redact the secrets / PII out of a value before it reaches the durable log or a
1613
- * Logpush event, via `@visulima/redact`'s `standardRules`. Unlike a blunt
1614
- * type-tag stamp this masks sensitive values by PATTERN (not just by key name)
1615
- * while leaving benign values readable, so the studio's args/identity columns
1616
- * stay useful. `null` / `undefined` pass through unchanged.
1617
- *
1618
- * What `standardRules` actually catches differs by shape, verified against its
1619
- * real behavior rather than assumed from its name: on a KEYED object (`args`,
1620
- * `identity`) it also matches by key name, so `{ password: "hunter2" }` and
1621
- * `{ token: "…" }` ARE masked regardless of the value's shape. On a PLAIN
1622
- * STRING — which is what `errorMessage`/log `fields`-as-rendered-text are —
1623
- * only pattern-shaped matches apply: emails, long digit runs / structured
1624
- * numeric IDs (credit-card, phone, SSN, AWS-access-key-style), and an explicit
1625
- * `Bearer <token>` / `token=…`-shaped substring. A free-text `password=hunter2`
1626
- * or a bare provider API key embedded in prose (e.g. `sk-live-…`) is NOT
1627
- * caught on a plain string — there is no key to match against, and neither is
1628
- * a recognized value pattern. So this is a PII-pattern net for rendered text,
1629
- * not a general secrets scrubber; a handler that echoes a raw credential into
1630
- * an error message or a log string can still leak it through here. Works on a
1631
- * plain string too (`redact` traverses whatever value it's handed), which is
1632
- * how {@link appendRequestLogEntry} and {@link emitRequestLogEvent} reuse this
1633
- * for `errorMessage` — a validation error echoes the offending value, a
1634
- * constraint error quotes the conflicting row, so the error message is at
1635
- * least as PII-dense as args and gets the same treatment (with the free-text
1636
- * caveat above).
1882
+ * Redact the secrets / PII out of a value before it reaches the durable log, a
1883
+ * Logpush event, a function-metrics row or a span's error message:
1884
+ * `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
1885
+ * `undefined` pass through unchanged.
1886
+ *
1887
+ * On a KEYED object (`args`, `identity`), a key that names a credential
1888
+ * (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
1889
+ * `DATABASE_URL`) has its value masked, numbers included; a key that measures
1890
+ * credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
1891
+ * `shared/credential-redaction.ts` for how keys are judged.
1892
+ *
1893
+ * On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
1894
+ * fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
1895
+ * with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
1896
+ * masked; and so is a bare token in prose with no name attached, when its format
1897
+ * has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
1898
+ * `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
1899
+ * `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
1900
+ * string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
1901
+ * been examined the remaining strings are replaced with a marker, so no arg can
1902
+ * hold the Durable Object in regex work.
1903
+ *
1904
+ * Still NOT caught: a bare secret with no name attached and no vendor prefix (a
1905
+ * random hex key, a password in a sentence). This is a credential-and-PII net,
1906
+ * not proof that no secret can reach the log.
1637
1907
  *
1638
1908
  * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1639
1909
  * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
@@ -1651,12 +1921,17 @@ declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
1651
1921
  *
1652
1922
  * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1653
1923
  * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
1654
- * redacts it — see that function's docstring. It is added via a guarded
1655
- * `ALTER TABLE` rather than baked into the `CREATE`, mirroring
1924
+ * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
1925
+ * trace id, the correlation key to the span ring and to whatever collector
1926
+ * `otlpSink` ships to.
1927
+ *
1928
+ * Both are also added via a guarded `ALTER TABLE`, mirroring
1656
1929
  * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1657
- * `__lunora_reqlog__` predates this column gains it on the next call without a
1930
+ * `__lunora_reqlog__` predates a column gains it on the next call without a
1658
1931
  * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1659
- * error from a re-run (or the freshly-created schema above) is swallowed.
1932
+ * error from a re-run (or from the freshly-created schema above) is swallowed
1933
+ * per column — the loop is what keeps one column's duplicate from skipping the
1934
+ * next column's add.
1660
1935
  */
1661
1936
  declare const ensureRequestLogTable: (sql: SqlExec) => void;
1662
1937
  /**
@@ -1747,12 +2022,21 @@ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1747
2022
  */
1748
2023
  declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1749
2024
  /**
1750
- * Read request-log entries newest-first, AND-combining the supplied filters
1751
- * (function-path prefix, exact userId/shardKey/outcome, and a table-touched
1752
- * match against the read OR written table sets), up to `limit` (clamped to
1753
- * [1, 10000]). Each value is a bound parameter, so no filter can inject SQL.
1754
- * Creates the table first so reads on a never-logged shard return `[]` instead
1755
- * of throwing. Mirrors `readAuditLog`/`readCdcChanges`.
2025
+ * Read request-log entries, AND-combining the supplied filters (function-path
2026
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
2027
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
2028
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
2029
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
2030
+ * `readAuditLog`/`readCdcChanges`.
2031
+ *
2032
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
2033
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
2034
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
2035
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
2036
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
2037
+ * largest returned `seq` skips everything between `sinceSeq` and that page
2038
+ * whenever more than `limit` rows accumulated between polls — the more traffic
2039
+ * the shard takes, the more it drops.
1756
2040
  */
1757
2041
  declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1758
2042
  declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
@@ -1770,7 +2054,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1770
2054
  *
1771
2055
  * `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.)
1772
2056
  *
1773
- * `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.
2057
+ * `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.
1774
2058
  *
1775
2059
  * `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.
1776
2060
  *
@@ -1842,6 +2126,15 @@ interface TraceSpan {
1842
2126
  message: string;
1843
2127
  type: string;
1844
2128
  };
2129
+ /**
2130
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
2131
+ * `span.recordException(...)`. Carried through so a handled retry or a
2132
+ * swallowed exception is visible on the span it happened in, which is the
2133
+ * only place it is interpretable. Absent when the body recorded none.
2134
+ */
2135
+ events?: SpanEventPoint[];
2136
+ /** OTel `SpanKind`; absent means `"internal"`. */
2137
+ kind?: OtlpSpanKind;
1845
2138
  name: string;
1846
2139
  /** Start of this span relative to the trace's start, in ms. */
1847
2140
  offsetMs: number;
@@ -1860,12 +2153,25 @@ interface TraceSummary {
1860
2153
  rootName: string;
1861
2154
  shardKey?: string;
1862
2155
  /**
1863
- * Spans ordered by `(offsetMs, depth)`, ready to render as waterfall rows.
1864
- * Start time alone is not enough to order them: spans are recorded on
1865
- * completion and `startTs` has millisecond resolution, so a parent and its
1866
- * child routinely tie. Breaking that tie by depth makes the sequence a valid
1867
- * pre-order traversal of the span tree, so indenting each row by its `depth`
1868
- * yields the nesting without a separate tree walk.
2156
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2157
+ * immediately followed by its own subtree, siblings in start order. So
2158
+ * indenting each row by its `depth` yields the real nesting — the row above
2159
+ * a `depth`-`n+1` row is genuinely its parent.
2160
+ *
2161
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2162
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2163
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2164
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2165
+ * parent it does not belong to.
2166
+ *
2167
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2168
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2169
+ * not a bug — so it does not advance at all across pure computation. Every
2170
+ * duration in this package is `Date.now() - startTs`, which means a span
2171
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2172
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2173
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2174
+ * span means "no I/O happened here", not "this was fast".
1869
2175
  */
1870
2176
  spans: TraceSpan[];
1871
2177
  startTs: number;
@@ -1880,10 +2186,19 @@ interface TraceSummary {
1880
2186
  declare class SpanBuffer {
1881
2187
  private readonly buffer;
1882
2188
  private readonly capacity;
2189
+ /** How many spans the ring has evicted since it was last cleared. */
2190
+ private droppedCount;
1883
2191
  constructor(capacity?: number);
2192
+ /**
2193
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2194
+ * ring silently drops its oldest span once full, which makes a busy instance
2195
+ * look identical to one that recorded exactly `capacity` spans; this count
2196
+ * is the difference between the two.
2197
+ */
2198
+ get dropped(): number;
1884
2199
  /** Number of spans currently buffered. */
1885
2200
  get size(): number;
1886
- /** Drop every buffered span. */
2201
+ /** Drop every buffered span, including the eviction count. */
1887
2202
  clear(): void;
1888
2203
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1889
2204
  entries(): SpanEvent[];
@@ -1959,10 +2274,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1959
2274
  * worker's trace and any container's beneath it), else freshly minted so a
1960
2275
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1961
2276
  * call — still produces a coherent, self-contained local trace.
2277
+ *
2278
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2279
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2280
+ * anchor so every span and log line of the dispatch stamps it; absent or
2281
+ * malformed, the anchor simply has none. Informational only — see
2282
+ * {@link parseRayId}.
1962
2283
  */
1963
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1964
- rootSpanId: string;
2284
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1965
2285
  sampled: boolean;
1966
- traceId: string;
1967
2286
  };
1968
- 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 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, 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 };
2287
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2288
+ /**
2289
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2290
+ *
2291
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2292
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2293
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2294
+ * inside `@lunora/do` only because that is where the Durable Object it
2295
+ * instruments happens to live.
2296
+ *
2297
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2298
+ * reverse, which is what makes this reusable by a second host rather than
2299
+ * merely relocated.
2300
+ *
2301
+ * This barrel is deliberately curated rather than `export *`. A star export
2302
+ * would promote every module internal to permanent public API — the exact
2303
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2304
+ * core. What is exported here is what a consumer actually needs.
2305
+ */
2306
+ type AuthMetrics,
2307
+ /**
2308
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2309
+ *
2310
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2311
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2312
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2313
+ * inside `@lunora/do` only because that is where the Durable Object it
2314
+ * instruments happens to live.
2315
+ *
2316
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2317
+ * reverse, which is what makes this reusable by a second host rather than
2318
+ * merely relocated.
2319
+ *
2320
+ * This barrel is deliberately curated rather than `export *`. A star export
2321
+ * would promote every module internal to permanent public API — the exact
2322
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2323
+ * core. What is exported here is what a consumer actually needs.
2324
+ */
2325
+ 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,
2326
+ /**
2327
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2328
+ *
2329
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2330
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2331
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2332
+ * inside `@lunora/do` only because that is where the Durable Object it
2333
+ * instruments happens to live.
2334
+ *
2335
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2336
+ * reverse, which is what makes this reusable by a second host rather than
2337
+ * merely relocated.
2338
+ *
2339
+ * This barrel is deliberately curated rather than `export *`. A star export
2340
+ * would promote every module internal to permanent public API — the exact
2341
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2342
+ * core. What is exported here is what a consumer actually needs.
2343
+ */
2344
+ 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 SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };