@lunora/observability 1.0.0-alpha.12 → 1.0.0-alpha.120

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 (45) hide show
  1. package/README.md +2 -4
  2. package/dist/index.d.mts +442 -118
  3. package/dist/index.d.ts +442 -118
  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-ChlIe0vF.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-DnOJJVHH.mjs +1 -0
  12. package/dist/packem_shared/REQUEST_LOG_TABLE-BLucY1KR.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-BGQNFq78.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-Byt8y5Kw.mjs +1 -0
  17. package/dist/packem_shared/findDanglingReferences-BaOyIdxz.mjs +1 -0
  18. package/dist/packem_shared/metric-buffer-Bx0XbypU.mjs +1 -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-TKfnwFNv.mjs +31 -0
  22. package/dist/packem_shared/readQueryInsights-DkQfxGfP.mjs +32 -0
  23. package/dist/packem_shared/request-log-BmtC_cDV.mjs +24 -0
  24. package/dist/packem_shared/resolveTraceAnchor-DDAPZRBB.mjs +1 -0
  25. package/dist/packem_shared/run-sql-0aPgJkIw.mjs +1 -0
  26. package/package.json +5 -5
  27. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-DpVJl1bU.mjs +0 -22
  28. package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-xF11R4vX.mjs +0 -3
  29. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BXPeggfa.mjs +0 -56
  30. package/dist/packem_shared/ISSUE_SEVERITIES-E91cPcjt.mjs +0 -15
  31. package/dist/packem_shared/LogBuffer-bIvCelI-.mjs +0 -1
  32. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-T-zuwRVR.mjs +0 -1
  33. package/dist/packem_shared/MetricBuffer-CYrLuEsz.mjs +0 -1
  34. package/dist/packem_shared/REQUEST_LOG_TABLE-DEHWxkC0.mjs +0 -1
  35. package/dist/packem_shared/SpanBuffer-BR6Ff0M-.mjs +0 -1
  36. package/dist/packem_shared/createDatabaseTally-_X8tMObq.mjs +0 -1
  37. package/dist/packem_shared/createMetrics-1k6z1bld.mjs +0 -1
  38. package/dist/packem_shared/findDanglingReferences-D-x9LvY0.mjs +0 -1
  39. package/dist/packem_shared/metric-buffer-CdgXal7w.mjs +0 -1
  40. package/dist/packem_shared/readMetricHistory-BdC01ptv.mjs +0 -31
  41. package/dist/packem_shared/readQueryInsights-BprtfEp-.mjs +0 -32
  42. package/dist/packem_shared/request-log-CHl9HlyL.mjs +0 -21
  43. package/dist/packem_shared/resolveTraceAnchor-IAN8riI0.mjs +0 -1
  44. package/dist/packem_shared/run-sql-BP8BI9zV.mjs +0 -1
  45. package/dist/packem_shared/trace-context-DrdF960P.mjs +0 -1
package/dist/index.d.mts 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
  /**
@@ -200,6 +200,12 @@ interface LogEvent {
200
200
  level: ContextLogLevel;
201
201
  /** Display string — the message, or the console-style args rendered and space-joined. */
202
202
  message: string;
203
+ /**
204
+ * Cloudflare Ray ID of the request this line was emitted under (see
205
+ * `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
206
+ * and for dispatches no HTTP request started (an alarm, a subscription re-run).
207
+ */
208
+ rayId?: string;
203
209
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
204
210
  shardKey?: string;
205
211
  /** Span id of the RPC this line was emitted under (trace correlation), or absent. */
@@ -320,10 +326,50 @@ interface SpanHandle {
320
326
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
327
  * reach around the API for it.
322
328
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
329
+ spanContext: () => SpanContextIds;
330
+ }
331
+ /**
332
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
333
+ *
334
+ * `sampled` is the propagated head decision (absent means "no verdict reached
335
+ * this tier", which every consumer reads as keep). It rides alongside the ids
336
+ * because everything that needs the ids to announce this span downstream — a
337
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
338
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
339
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
340
+ */
341
+ interface SpanContextIds {
342
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
343
+ sampled?: boolean;
344
+ /** This span's id (16-hex). */
345
+ spanId: string;
346
+ /** The trace this span belongs to (32-hex). */
347
+ traceId: string;
348
+ }
349
+ /**
350
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
351
+ * argument.
352
+ *
353
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
354
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
355
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
356
+ * so the id the adapter published is the id that reaches the collector rather
357
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
358
+ * reason: an adapter that tracks its own parent/child structure (OTel's
359
+ * `Context`) can express it without an ambient span stack.
360
+ *
361
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
362
+ * never mints its own ids.
363
+ *
364
+ * Both ids are required: an adapter that has published one has published the
365
+ * other, and `identity` is itself optional — omitting it, not passing a partial
366
+ * object, is how a caller says "no adapter involved".
367
+ */
368
+ interface SpanIdentity {
369
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
370
+ parentSpanId: string;
371
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
372
+ spanId: string;
327
373
  }
328
374
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
375
  interface SpanOptions {
@@ -402,6 +448,24 @@ interface SpanEvent {
402
448
  * the outermost span, which is why the fold prefers it as a trace's anchor.
403
449
  */
404
450
  dispatch?: boolean;
451
+ /**
452
+ * Cloudflare Ray ID of the request this span ran under (see
453
+ * `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
454
+ */
455
+ rayId?: string;
456
+ /**
457
+ * The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
458
+ * sink. Absent means no verdict reached this tier, which every consumer reads
459
+ * as keep.
460
+ *
461
+ * Carried because the OTLP encoders write it into the span's `flags` field,
462
+ * and a span exported with no `flags` reads as UNSAMPLED (0) at the collector
463
+ * — on EVERY span, including the ones it is meant to keep. It is genuinely
464
+ * per-span rather than derivable from "it was exported at all": a trace the
465
+ * tail bias rescued (head-sampled out, then errored) is exported with the bit
466
+ * CLEAR, and saying otherwise misreports the trace's verdict.
467
+ */
468
+ sampled?: boolean;
405
469
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
406
470
  shardKey?: string;
407
471
  /** This span's own id (16-hex). */
@@ -413,35 +477,6 @@ interface SpanEvent {
413
477
  /** Acting userId, or absent when anonymous. */
414
478
  userId?: string;
415
479
  }
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
480
  /**
446
481
  * Minimal structural shape of one **host-native custom span** — the object a
447
482
  * `tracing.enterSpan(name, (span) => …)` callback receives (GA 2026-06-16). Only
@@ -465,8 +500,28 @@ interface HostSpanLike {
465
500
  * a span nobody will read.
466
501
  */
467
502
  readonly isTraced: boolean;
503
+ /**
504
+ * Record an OTel `exception` event on the span (CF 2026-09-25). Optional and
505
+ * feature-detected: older runtimes only have `setAttribute`.
506
+ */
507
+ recordException?: (exception: {
508
+ message: string;
509
+ name: string;
510
+ }) => unknown;
468
511
  /** Attach one primitive attribute to the CF span. */
469
- setAttribute: (key: string, value: boolean | number | string | undefined) => void;
512
+ setAttribute: (key: string, value: boolean | number | string | undefined) => unknown;
513
+ /** Attach several attributes in one call (CF 2026-09-25). Optional, like `recordException`. */
514
+ setAttributes?: (attributes: Record<string, boolean | number | string>) => unknown;
515
+ /**
516
+ * Set the span's OTel status (workers-types 5.20260929). Optional and
517
+ * feature-detected, like `recordException`: older runtimes lack it. The
518
+ * bridge only ever sets `"error"` — OTel instrumentation leaves a successful
519
+ * span `"unset"` rather than marking it `"ok"`.
520
+ */
521
+ setStatus?: (status: {
522
+ code: "error" | "ok" | "unset";
523
+ message?: string;
524
+ }) => unknown;
470
525
  }
471
526
  /**
472
527
  * Minimal structural shape of the `tracing` namespace exported by
@@ -475,6 +530,11 @@ interface HostSpanLike {
475
530
  */
476
531
  interface HostTracingLike {
477
532
  enterSpan: <T>(name: string, callback: (span: HostSpanLike) => T) => T;
533
+ /**
534
+ * The currently active span; outside any custom span, the invocation's root
535
+ * span (CF 2026-09-25). Optional and feature-detected: absent on older runtimes.
536
+ */
537
+ getActiveSpan?: () => HostSpanLike | undefined;
478
538
  }
479
539
  /**
480
540
  * Resolves CF's `tracing` namespace, or `undefined` when it is unavailable —
@@ -484,6 +544,73 @@ interface HostTracingLike {
484
544
  * supplies the real resolver, tests a fake or `undefined`.
485
545
  */
486
546
  type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | undefined> | undefined;
547
+ /**
548
+ * Copy an attribute bag onto a host span, best-effort: one native
549
+ * `setAttributes` call where the runtime has it, a `setAttribute` loop where it
550
+ * does not. Skipped for an untraced span; non-primitive values are dropped,
551
+ * since CF's setters take `string | number | boolean` only.
552
+ */
553
+ declare const setHostSpanAttributes: (span: HostSpanLike, attributes: Record<string, LogFields[string]>) => void;
554
+ /**
555
+ * Mirror a finished dispatch onto the host's invocation span — the one
556
+ * `tracing.getActiveSpan()` returns once every `ctx.trace` custom span has
557
+ * ended. Pure and fully best-effort: a missing `getActiveSpan`, an untraced span
558
+ * or a throwing setter is a silent no-op, never an error for the dispatch.
559
+ *
560
+ * `attributes` is the dispatch root span's already-redacted wide event, when it
561
+ * recorded one. `error` is set when the dispatch failed; its `serverFault` is the
562
+ * CALLER's verdict on whether that failure is the server's: the status of the
563
+ * response it actually sent (>= 500) for an RPC, always `true` for a trigger
564
+ * that threw. Only a server fault marks the span failed; a 4xx is an expected
565
+ * client outcome that OTel's server-span convention leaves `"unset"`. `message`
566
+ * must already be redacted.
567
+ *
568
+ * The status is written before the attributes so a throwing attribute setter
569
+ * cannot drop it.
570
+ */
571
+ declare const applyHostRootSpan: (tracing: HostTracingLike | undefined, root: {
572
+ attributes?: Record<string, LogFields[string]>;
573
+ error?: {
574
+ message: string;
575
+ serverFault: boolean;
576
+ };
577
+ }) => void;
578
+ /**
579
+ * Structural shape of the `ctx.trace` span factory (see the server
580
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
581
+ * dependency on `@lunora/server`; a cross-package assignability guard in
582
+ * `@lunora/testing` fails the build if the two drift apart.
583
+ *
584
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
585
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
586
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
587
+ */
588
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
589
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
590
+ interface ContextMetrics {
591
+ count: (name: string, value?: number, attributes?: LogFields) => void;
592
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
593
+ record: (name: string, value: number, attributes?: LogFields) => void;
594
+ }
595
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
596
+ interface TraceAnchor {
597
+ /**
598
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
599
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
600
+ * log line of the dispatch stamps the same value. Absent off the edge.
601
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
602
+ */
603
+ rayId?: string;
604
+ rootSpanId: string;
605
+ /**
606
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
607
+ * `traceparent` when there was one. Carried on the anchor rather than
608
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
609
+ * propagates the same answer.
610
+ */
611
+ sampled?: boolean;
612
+ traceId: string;
613
+ }
487
614
  /** What {@link createTracer} needs from the shard to build a span. */
488
615
  interface TracerDeps {
489
616
  /** The trace this ctx's spans belong to. */
@@ -560,10 +687,7 @@ interface SpanCollector {
560
687
  * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
688
  * escape hatch rather than shipping to a third-party collector by default.
562
689
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
690
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean) => SpanCollector;
567
691
  /**
568
692
  * Build the `ctx.trace` span factory for one dispatched function.
569
693
  *
@@ -605,7 +729,7 @@ declare const createSpanCollector: (ids: {
605
729
  *
606
730
  * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
607
731
  * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
608
- * Object under `@cloudflare/vitest-pool-workers` (see
732
+ * Object under `@cloudflare/vitest-plugin` (see
609
733
  * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
610
734
  * from `cloudflare:workers`, its callback executes and returns the body value
611
735
  * without throwing, `span.isTraced` is a real boolean, and — the key additive
@@ -625,6 +749,14 @@ declare const createTracer: (deps: TracerDeps) => ContextTracer;
625
749
  interface TracedFetchDeps {
626
750
  /** The trace the CLIENT spans belong to. */
627
751
  anchor: TraceAnchor;
752
+ /**
753
+ * Whether to record a failed fetch's error message verbatim rather than
754
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
755
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
756
+ * query string would otherwise reach the collector in the clear on the very
757
+ * span whose `url.full` is scrubbed by `redactUrl`.
758
+ */
759
+ captureRaw?: boolean;
628
760
  /** Function path the spans are attributed to. */
629
761
  functionPath: string;
630
762
  /**
@@ -660,6 +792,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
660
792
  * Kind is `client` rather than `internal` — that is what lets a collector draw
661
793
  * the edge to the downstream service in a service map.
662
794
  *
795
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
796
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
797
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
798
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
799
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
800
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
801
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
802
+ * the span whose bar you want it under and read the two side by side.
803
+ *
663
804
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
664
805
  * recorded as an ERROR span (it is a failed call from the caller's point of
665
806
  * view) while still being returned normally — instrumentation, never flow
@@ -723,7 +864,12 @@ interface DatabaseTally {
723
864
  spansTruncated: boolean;
724
865
  }
725
866
  /**
726
- * How much detail `ctx.db` auto-instrumentation produces.
867
+ * Which instrumented surface a tally belongs to, and the key prefix
868
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
869
+ */
870
+ type TallySurface = "db" | "sql";
871
+ /**
872
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
727
873
  *
728
874
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
729
875
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -734,16 +880,24 @@ interface DatabaseTally {
734
880
  * `"off"` — no database telemetry at all.
735
881
  */
736
882
  type DatabaseInstrumentation = "off" | "spans" | "summary";
737
- /** What {@link instrumentDatabase} needs to record what it observes. */
883
+ /**
884
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
885
+ * instrumenter needs — declared here so this package takes no dependency on
886
+ * hyperdrive.
887
+ */
888
+ interface SqlClientLike {
889
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
890
+ readonly dbSystem?: string;
891
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
892
+ }
893
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
738
894
  interface DatabaseTelemetryDeps {
739
895
  /** The trace produced spans belong to (`"spans"` mode only). */
740
896
  anchor: TraceAnchor;
741
897
  /**
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.
898
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
899
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
900
+ * {@link failureMessage} for what each surface records without it.
747
901
  */
748
902
  captureRaw?: boolean;
749
903
  /** Function path spans and attributes are attributed to. */
@@ -759,14 +913,20 @@ interface DatabaseTelemetryDeps {
759
913
  * increments numbers on it; the shard reads it ONCE at the dispatch boundary
760
914
  * and formats it with {@link formatTally}.
761
915
  *
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.
916
+ * Per-call cost stays at a few integer increments — no object allocation, no
917
+ * lookup — which matters because this is on the path of every query. Nothing
918
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
919
+ * collector is never materialized by instrumentation alone: a dispatch that
920
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
921
+ * log record unless the handler actually opened `ctx.span`.
767
922
  */
768
923
  tally: DatabaseTally;
769
- /** Read lazily — the acting user is resolved per span. */
924
+ /**
925
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
926
+ * they instrument the client, and return that captured value: a span is
927
+ * built after the call's await, and per-request shared state read by then
928
+ * may already belong to a concurrent request.
929
+ */
770
930
  userId: () => string | undefined;
771
931
  }
772
932
  /**
@@ -775,24 +935,42 @@ interface DatabaseTelemetryDeps {
775
935
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
776
936
  * path costs nothing — not even a proxy indirection.
777
937
  *
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.
938
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
939
+ * optional members that a given backend may or may not implement, plus
940
+ * properties (`system`) and builder factories (`query`) that must pass through
941
+ * untouched. A proxy instruments exactly what it is asked to and is
942
+ * transparently correct for everything else, including members added later —
943
+ * an enumeration would silently stop covering them.
784
944
  */
785
945
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
946
+ /**
947
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
948
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
949
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
950
+ * as `sql.*`), never `ctx.db`'s.
951
+ *
952
+ * Its span carries no statement text and no parameters — only the
953
+ * leading-keyword operation, the system, and the returned row count. No
954
+ * `db.collection.name` either: naming the table means parsing past
955
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
956
+ * safe. A failure records its TYPE (see {@link failureMessage}).
957
+ *
958
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
959
+ * method to cover. Everything else on the client passes through untouched, and
960
+ * `"off"` returns the client itself.
961
+ */
962
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
786
963
  /** A zero'd tally for one dispatch. */
787
964
  declare const createDatabaseTally: () => DatabaseTally;
788
965
  /**
789
- * Render the running tally as span attributes.
966
+ * Render the running tally as span attributes, under its surface's prefix
967
+ * ({@link TallySurface}).
790
968
  *
791
969
  * 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.
970
+ * It is a handful of keys, so the per-call cost is a small object assignment —
971
+ * the property that makes `"summary"` mode scale to any call count.
794
972
  */
795
- declare const formatTally: (tally: DatabaseTally) => LogFields;
973
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
796
974
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
797
975
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
798
976
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -1196,6 +1374,8 @@ interface LogEntry {
1196
1374
  level: LogLevel;
1197
1375
  message: string;
1198
1376
  timestamp: number;
1377
+ /** 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. */
1378
+ traceId?: string;
1199
1379
  }
1200
1380
  /**
1201
1381
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1216,10 +1396,21 @@ declare class LogBuffer {
1216
1396
  /** Backing store, kept in insertion order (oldest first). */
1217
1397
  private readonly buffer;
1218
1398
  private readonly capacity;
1399
+ /** How many entries the ring has evicted since it was last cleared. */
1400
+ private droppedCount;
1219
1401
  constructor(capacity?: number);
1402
+ /**
1403
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1404
+ *
1405
+ * Without it a full ring is indistinguishable from a quiet instance that
1406
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1407
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1408
+ * count is what turns "the newest 500" into an honest statement.
1409
+ */
1410
+ get dropped(): number;
1220
1411
  /** Number of entries currently buffered. */
1221
1412
  get size(): number;
1222
- /** Drop every buffered entry. */
1413
+ /** Drop every buffered entry, including the eviction count. */
1223
1414
  clear(): void;
1224
1415
  /**
1225
1416
  * Snapshot of the buffered entries, **newest first** so the panel renders
@@ -1342,7 +1533,14 @@ interface MetricHistoryResult {
1342
1533
  * omitted field keeps the historical behaviour.
1343
1534
  */
1344
1535
  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}). */
1536
+ /**
1537
+ * Distinct series tracked before a brand-new one is REFUSED admission
1538
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
1539
+ * already-tracked series keeps accumulating past the cap, and a flood of
1540
+ * one-off series cannot displace the app's real ones — see
1541
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
1542
+ * read-side signal that admission is being refused.
1543
+ */
1346
1544
  maxSeries?: number;
1347
1545
  /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1348
1546
  retentionBuckets?: number;
@@ -1393,9 +1591,9 @@ interface QueryStatEntry {
1393
1591
  execCount: number;
1394
1592
  /** Normalised SQL text (literals stripped, truncated). */
1395
1593
  normalizedSql: string;
1396
- /** Total rows read across all executions (SELECT result sizes). */
1594
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
1397
1595
  rowsRead: number;
1398
- /** Total rows written across all executions. */
1596
+ /** Total rows WRITTEN across all executions. */
1399
1597
  rowsWritten: number;
1400
1598
  /** Total wall-clock milliseconds across all executions. */
1401
1599
  totalDurationMs: number;
@@ -1476,6 +1674,8 @@ type RequestOutcome = "error" | "ok";
1476
1674
  interface RequestLogEntry {
1477
1675
  /** 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
1676
  cacheHit?: boolean;
1677
+ /** 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?". */
1678
+ deploymentId?: string;
1479
1679
  /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1480
1680
  durationMs: number;
1481
1681
  /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
@@ -1498,26 +1698,39 @@ interface RequestLogEntry {
1498
1698
  tablesRead: string[];
1499
1699
  /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1500
1700
  tablesWritten: string[];
1701
+ /** 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. */
1702
+ traceId?: string;
1501
1703
  /** Wall-clock millis when the dispatch completed. */
1502
1704
  ts: number;
1503
1705
  /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1504
1706
  userId?: string;
1707
+ /** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
1708
+ versionTag?: string;
1505
1709
  }
1506
1710
  /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1507
1711
  interface AppendRequestLogEntry {
1508
1712
  cacheHit?: boolean;
1713
+ deploymentId?: string;
1509
1714
  durationMs: number;
1510
1715
  errorMessage?: string;
1511
1716
  functionPath: string;
1512
1717
  identity?: Record<string, unknown>;
1513
1718
  outcome: RequestOutcome;
1719
+ /**
1720
+ * Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
1721
+ * Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
1722
+ * keeps its `trace_id` join key and has no column for it.
1723
+ */
1724
+ rayId?: string;
1514
1725
  redactedArgs?: unknown;
1515
1726
  shardKey?: string;
1516
1727
  subscriptionsReRun?: number;
1517
1728
  tablesRead?: string[];
1518
1729
  tablesWritten?: string[];
1730
+ traceId?: string;
1519
1731
  ts: number;
1520
1732
  userId?: string;
1733
+ versionTag?: string;
1521
1734
  }
1522
1735
  /** Knobs the dispatch site threads into a request-log write. */
1523
1736
  interface RequestLogWriteOptions {
@@ -1536,14 +1749,19 @@ interface ReadRequestLogOptions {
1536
1749
  outcome?: RequestOutcome;
1537
1750
  /** Exact shard-key match. */
1538
1751
  shardKey?: string;
1539
- /** Only entries strictly after this cursor (forward paging). */
1752
+ /**
1753
+ * Only entries strictly after this cursor. Setting it switches the read to
1754
+ * ASCENDING order — see {@link readRequestLog} — because that is the only
1755
+ * ordering under which advancing the cursor to the last returned `seq`
1756
+ * actually pages forward without a hole.
1757
+ */
1540
1758
  sinceSeq?: number;
1541
1759
  /** Keep only entries whose read OR written table set contains this table. */
1542
1760
  tableTouched?: string;
1543
1761
  /** Exact acting-userId match. */
1544
1762
  userId?: string;
1545
1763
  }
1546
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1764
+ /** 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
1765
  interface RequestLogResult {
1548
1766
  entries: RequestLogEntry[];
1549
1767
  }
@@ -1609,31 +1827,31 @@ interface ReadIssuesOptions {
1609
1827
  userId?: string;
1610
1828
  }
1611
1829
  /**
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).
1830
+ * Redact the secrets / PII out of a value before it reaches the durable log, a
1831
+ * Logpush event, a function-metrics row or a span's error message:
1832
+ * `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
1833
+ * `undefined` pass through unchanged.
1834
+ *
1835
+ * On a KEYED object (`args`, `identity`), a key that names a credential
1836
+ * (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
1837
+ * `DATABASE_URL`) has its value masked, numbers included; a key that measures
1838
+ * credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
1839
+ * `shared/credential-redaction.ts` for how keys are judged.
1840
+ *
1841
+ * On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
1842
+ * fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
1843
+ * with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
1844
+ * masked; and so is a bare token in prose with no name attached, when its format
1845
+ * has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
1846
+ * `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
1847
+ * `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
1848
+ * string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
1849
+ * been examined the remaining strings are replaced with a marker, so no arg can
1850
+ * hold the Durable Object in regex work.
1851
+ *
1852
+ * Still NOT caught: a bare secret with no name attached and no vendor prefix (a
1853
+ * random hex key, a password in a sentence). This is a credential-and-PII net,
1854
+ * not proof that no secret can reach the log.
1637
1855
  *
1638
1856
  * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1639
1857
  * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
@@ -1651,12 +1869,17 @@ declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
1651
1869
  *
1652
1870
  * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1653
1871
  * 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
1872
+ * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
1873
+ * trace id, the correlation key to the span ring and to whatever collector
1874
+ * `otlpSink` ships to.
1875
+ *
1876
+ * Both are also added via a guarded `ALTER TABLE`, mirroring
1656
1877
  * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1657
- * `__lunora_reqlog__` predates this column gains it on the next call without a
1878
+ * `__lunora_reqlog__` predates a column gains it on the next call without a
1658
1879
  * 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.
1880
+ * error from a re-run (or from the freshly-created schema above) is swallowed
1881
+ * per column — the loop is what keeps one column's duplicate from skipping the
1882
+ * next column's add.
1660
1883
  */
1661
1884
  declare const ensureRequestLogTable: (sql: SqlExec) => void;
1662
1885
  /**
@@ -1747,12 +1970,21 @@ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1747
1970
  */
1748
1971
  declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
1749
1972
  /**
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`.
1973
+ * Read request-log entries, AND-combining the supplied filters (function-path
1974
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1975
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1976
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1977
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1978
+ * `readAuditLog`/`readCdcChanges`.
1979
+ *
1980
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1981
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1982
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1983
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1984
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1985
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1986
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1987
+ * the shard takes, the more it drops.
1756
1988
  */
1757
1989
  declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1758
1990
  declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
@@ -1770,7 +2002,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1770
2002
  *
1771
2003
  * `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
2004
  *
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.
2005
+ * `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
2006
  *
1775
2007
  * `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
2008
  *
@@ -1842,6 +2074,15 @@ interface TraceSpan {
1842
2074
  message: string;
1843
2075
  type: string;
1844
2076
  };
2077
+ /**
2078
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
2079
+ * `span.recordException(...)`. Carried through so a handled retry or a
2080
+ * swallowed exception is visible on the span it happened in, which is the
2081
+ * only place it is interpretable. Absent when the body recorded none.
2082
+ */
2083
+ events?: SpanEventPoint[];
2084
+ /** OTel `SpanKind`; absent means `"internal"`. */
2085
+ kind?: OtlpSpanKind;
1845
2086
  name: string;
1846
2087
  /** Start of this span relative to the trace's start, in ms. */
1847
2088
  offsetMs: number;
@@ -1860,12 +2101,25 @@ interface TraceSummary {
1860
2101
  rootName: string;
1861
2102
  shardKey?: string;
1862
2103
  /**
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.
2104
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2105
+ * immediately followed by its own subtree, siblings in start order. So
2106
+ * indenting each row by its `depth` yields the real nesting — the row above
2107
+ * a `depth`-`n+1` row is genuinely its parent.
2108
+ *
2109
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2110
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2111
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2112
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2113
+ * parent it does not belong to.
2114
+ *
2115
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2116
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2117
+ * not a bug — so it does not advance at all across pure computation. Every
2118
+ * duration in this package is `Date.now() - startTs`, which means a span
2119
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2120
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2121
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2122
+ * span means "no I/O happened here", not "this was fast".
1869
2123
  */
1870
2124
  spans: TraceSpan[];
1871
2125
  startTs: number;
@@ -1880,10 +2134,19 @@ interface TraceSummary {
1880
2134
  declare class SpanBuffer {
1881
2135
  private readonly buffer;
1882
2136
  private readonly capacity;
2137
+ /** How many spans the ring has evicted since it was last cleared. */
2138
+ private droppedCount;
1883
2139
  constructor(capacity?: number);
2140
+ /**
2141
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2142
+ * ring silently drops its oldest span once full, which makes a busy instance
2143
+ * look identical to one that recorded exactly `capacity` spans; this count
2144
+ * is the difference between the two.
2145
+ */
2146
+ get dropped(): number;
1884
2147
  /** Number of spans currently buffered. */
1885
2148
  get size(): number;
1886
- /** Drop every buffered span. */
2149
+ /** Drop every buffered span, including the eviction count. */
1887
2150
  clear(): void;
1888
2151
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1889
2152
  entries(): SpanEvent[];
@@ -1959,10 +2222,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1959
2222
  * worker's trace and any container's beneath it), else freshly minted so a
1960
2223
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1961
2224
  * call — still produces a coherent, self-contained local trace.
2225
+ *
2226
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2227
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2228
+ * anchor so every span and log line of the dispatch stamps it; absent or
2229
+ * malformed, the anchor simply has none. Informational only — see
2230
+ * {@link parseRayId}.
1962
2231
  */
1963
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1964
- rootSpanId: string;
2232
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1965
2233
  sampled: boolean;
1966
- traceId: string;
1967
2234
  };
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 };
2235
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2236
+ /**
2237
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2238
+ *
2239
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2240
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2241
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2242
+ * inside `@lunora/do` only because that is where the Durable Object it
2243
+ * instruments happens to live.
2244
+ *
2245
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2246
+ * reverse, which is what makes this reusable by a second host rather than
2247
+ * merely relocated.
2248
+ *
2249
+ * This barrel is deliberately curated rather than `export *`. A star export
2250
+ * would promote every module internal to permanent public API — the exact
2251
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2252
+ * core. What is exported here is what a consumer actually needs.
2253
+ */
2254
+ type AuthMetrics,
2255
+ /**
2256
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2257
+ *
2258
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2259
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2260
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2261
+ * inside `@lunora/do` only because that is where the Durable Object it
2262
+ * instruments happens to live.
2263
+ *
2264
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2265
+ * reverse, which is what makes this reusable by a second host rather than
2266
+ * merely relocated.
2267
+ *
2268
+ * This barrel is deliberately curated rather than `export *`. A star export
2269
+ * would promote every module internal to permanent public API — the exact
2270
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2271
+ * core. What is exported here is what a consumer actually needs.
2272
+ */
2273
+ 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,
2274
+ /**
2275
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2276
+ *
2277
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2278
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2279
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2280
+ * inside `@lunora/do` only because that is where the Durable Object it
2281
+ * instruments happens to live.
2282
+ *
2283
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2284
+ * reverse, which is what makes this reusable by a second host rather than
2285
+ * merely relocated.
2286
+ *
2287
+ * This barrel is deliberately curated rather than `export *`. A star export
2288
+ * would promote every module internal to permanent public API — the exact
2289
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2290
+ * core. What is exported here is what a consumer actually needs.
2291
+ */
2292
+ 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, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };