@lunora/observability 1.0.0-alpha.17 → 1.0.0-alpha.171

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 +1574 -1094
  3. package/dist/index.d.ts +1574 -1094
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.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-Dha-40Hv.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/NO_SENSITIVE_SCOPE-BAbpBlN5.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-ZFZnNvOy.mjs +2 -0
  16. package/dist/packem_shared/createMetrics-EODsLse6.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-CksedkkK.mjs +1 -0
  21. package/dist/packem_shared/readMetricHistory-BjPDSBkS.mjs +31 -0
  22. package/dist/packem_shared/request-log-DdeDQptI.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,20 @@ 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
+ /**
168
+ * The operator-only `internal` context of a `LunoraError`, when it is JSON-safe.
169
+ * Attached by the shard only on the detail header (see {@link describeInternal}),
170
+ * never by {@link describeError}, so it cannot leak into a log-event `error`.
171
+ */
172
+ internal?: Record<string, unknown>;
173
+ message: string;
174
+ name: string;
175
+ stack?: string;
176
+ }
163
177
  /**
164
178
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
165
179
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -173,6 +187,14 @@ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" |
173
187
  interface LogEvent {
174
188
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
175
189
  args: unknown[];
190
+ /**
191
+ * The first `Error` the call was handed, as an argument
192
+ * (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
193
+ * unredacted `message`, `stack`, and `code` when it carries one. Absent when
194
+ * the line logged no `Error`. An error tracker reads this rather than parsing
195
+ * the rendered `message`.
196
+ */
197
+ error?: ErrorDetail;
176
198
  /**
177
199
  * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
178
200
  * event** via `ctx.log.event(name, fields)` rather than as a human-readable
@@ -200,6 +222,12 @@ interface LogEvent {
200
222
  level: ContextLogLevel;
201
223
  /** Display string — the message, or the console-style args rendered and space-joined. */
202
224
  message: string;
225
+ /**
226
+ * Cloudflare Ray ID of the request this line was emitted under (see
227
+ * `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
228
+ * and for dispatches no HTTP request started (an alarm, a subscription re-run).
229
+ */
230
+ rayId?: string;
203
231
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
204
232
  shardKey?: string;
205
233
  /** Span id of the RPC this line was emitted under (trace correlation), or absent. */
@@ -320,10 +348,50 @@ interface SpanHandle {
320
348
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
349
  * reach around the API for it.
322
350
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
351
+ spanContext: () => SpanContextIds;
352
+ }
353
+ /**
354
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
355
+ *
356
+ * `sampled` is the propagated head decision (absent means "no verdict reached
357
+ * this tier", which every consumer reads as keep). It rides alongside the ids
358
+ * because everything that needs the ids to announce this span downstream — a
359
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
360
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
361
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
362
+ */
363
+ interface SpanContextIds {
364
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
365
+ sampled?: boolean;
366
+ /** This span's id (16-hex). */
367
+ spanId: string;
368
+ /** The trace this span belongs to (32-hex). */
369
+ traceId: string;
370
+ }
371
+ /**
372
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
373
+ * argument.
374
+ *
375
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
376
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
377
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
378
+ * so the id the adapter published is the id that reaches the collector rather
379
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
380
+ * reason: an adapter that tracks its own parent/child structure (OTel's
381
+ * `Context`) can express it without an ambient span stack.
382
+ *
383
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
384
+ * never mints its own ids.
385
+ *
386
+ * Both ids are required: an adapter that has published one has published the
387
+ * other, and `identity` is itself optional — omitting it, not passing a partial
388
+ * object, is how a caller says "no adapter involved".
389
+ */
390
+ interface SpanIdentity {
391
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
392
+ parentSpanId: string;
393
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
394
+ spanId: string;
327
395
  }
328
396
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
397
  interface SpanOptions {
@@ -402,6 +470,24 @@ interface SpanEvent {
402
470
  * the outermost span, which is why the fold prefers it as a trace's anchor.
403
471
  */
404
472
  dispatch?: boolean;
473
+ /**
474
+ * Cloudflare Ray ID of the request this span ran under (see
475
+ * `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
476
+ */
477
+ rayId?: string;
478
+ /**
479
+ * The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
480
+ * sink. Absent means no verdict reached this tier, which every consumer reads
481
+ * as keep.
482
+ *
483
+ * Carried because the OTLP encoders write it into the span's `flags` field,
484
+ * and a span exported with no `flags` reads as UNSAMPLED (0) at the collector
485
+ * — on EVERY span, including the ones it is meant to keep. It is genuinely
486
+ * per-span rather than derivable from "it was exported at all": a trace the
487
+ * tail bias rescued (head-sampled out, then errored) is exported with the bit
488
+ * CLEAR, and saying otherwise misreports the trace's verdict.
489
+ */
490
+ sampled?: boolean;
405
491
  /** Shard key for single-shard calls; absent for the unnamed root DO. */
406
492
  shardKey?: string;
407
493
  /** This span's own id (16-hex). */
@@ -413,35 +499,6 @@ interface SpanEvent {
413
499
  /** Acting userId, or absent when anonymous. */
414
500
  userId?: string;
415
501
  }
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
502
  /**
446
503
  * Minimal structural shape of one **host-native custom span** — the object a
447
504
  * `tracing.enterSpan(name, (span) => …)` callback receives (GA 2026-06-16). Only
@@ -465,8 +522,28 @@ interface HostSpanLike {
465
522
  * a span nobody will read.
466
523
  */
467
524
  readonly isTraced: boolean;
525
+ /**
526
+ * Record an OTel `exception` event on the span (CF 2026-09-25). Optional and
527
+ * feature-detected: older runtimes only have `setAttribute`.
528
+ */
529
+ recordException?: (exception: {
530
+ message: string;
531
+ name: string;
532
+ }) => unknown;
468
533
  /** Attach one primitive attribute to the CF span. */
469
- setAttribute: (key: string, value: boolean | number | string | undefined) => void;
534
+ setAttribute: (key: string, value: boolean | number | string | undefined) => unknown;
535
+ /** Attach several attributes in one call (CF 2026-09-25). Optional, like `recordException`. */
536
+ setAttributes?: (attributes: Record<string, boolean | number | string>) => unknown;
537
+ /**
538
+ * Set the span's OTel status (workers-types 5.20260929). Optional and
539
+ * feature-detected, like `recordException`: older runtimes lack it. The
540
+ * bridge only ever sets `"error"` — OTel instrumentation leaves a successful
541
+ * span `"unset"` rather than marking it `"ok"`.
542
+ */
543
+ setStatus?: (status: {
544
+ code: "error" | "ok" | "unset";
545
+ message?: string;
546
+ }) => unknown;
470
547
  }
471
548
  /**
472
549
  * Minimal structural shape of the `tracing` namespace exported by
@@ -475,6 +552,11 @@ interface HostSpanLike {
475
552
  */
476
553
  interface HostTracingLike {
477
554
  enterSpan: <T>(name: string, callback: (span: HostSpanLike) => T) => T;
555
+ /**
556
+ * The currently active span; outside any custom span, the invocation's root
557
+ * span (CF 2026-09-25). Optional and feature-detected: absent on older runtimes.
558
+ */
559
+ getActiveSpan?: () => HostSpanLike | undefined;
478
560
  }
479
561
  /**
480
562
  * Resolves CF's `tracing` namespace, or `undefined` when it is unavailable —
@@ -484,518 +566,1137 @@ interface HostTracingLike {
484
566
  * supplies the real resolver, tests a fake or `undefined`.
485
567
  */
486
568
  type HostTracingResolver = () => HostTracingLike | Promise<HostTracingLike | undefined> | undefined;
487
- /** What {@link createTracer} needs from the shard to build a span. */
488
- interface TracerDeps {
489
- /** The trace this ctx's spans belong to. */
490
- anchor: TraceAnchor;
491
- /**
492
- * Whether to record a span body's error message (and a `recordException`
493
- * stacktrace) verbatim rather than redacted. Mirrors the request log's
494
- * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
495
- * the span pipeline is the one sink third-party collectors (Datadog/Axiom
496
- * via `otlpSink`) receive, so it must not ship raw PII/internals by default
497
- * the way the request log and function-metrics sinks already don't.
498
- */
499
- captureRaw?: boolean;
500
- /** Function path the spans are attributed to. */
501
- functionPath: string;
502
- /**
503
- * **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
504
- * {@link TracerDeps.resolveHostTracing} yields a working
505
- * `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
506
- * **custom span**, so it nests inside CF's native binding/fetch/handler trace
507
- * tree on the hosted path. This only ADDS a CF-side span — the recorded
508
- * {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
509
- * source of truth plus the local studio waterfall. The `enterSpan` call itself
510
- * is now workerd-validated as available and side-effect-free inside a Durable
511
- * Object; CF's exported parent-linking under sampling remains unverified. See
512
- * {@link createTracer} for the double-export and Durable-Object async-context
513
- * caveats.
514
- */
515
- fuseHostSpans?: boolean;
516
- /** Hand a finished span to the buffer + sink. */
517
- record: (span: SpanEvent) => void;
518
- /**
519
- * Injected resolver for CF's `tracing` namespace (see
520
- * {@link HostTracingResolver}). Only consulted when
521
- * {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
522
- * calls it.
523
- */
524
- resolveHostTracing?: HostTracingResolver;
525
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
526
- shardKey: string | undefined;
527
- /** Read lazily — the acting user is resolved per span, not per ctx. */
528
- userId: () => string | undefined;
529
- }
530
- /** What {@link createMetrics} needs from the shard to build a measurement. */
531
- interface MetricsDeps {
532
- functionPath: string;
533
- record: (event: MetricEvent) => void;
534
- shardKey: string | undefined;
535
- }
536
- /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
537
- interface SpanCollection {
538
- attributes: Record<string, LogFields[string]>;
539
- events: SpanEventPoint[];
540
- links: SpanLink[];
541
- }
542
- /** A {@link SpanHandle} plus read access to what it has collected so far. */
543
- interface SpanCollector {
544
- collected: SpanCollection;
545
- handle: SpanHandle;
546
- }
547
569
  /**
548
- * Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
549
- * `ctx.trace` body, and the bag it writes into.
550
- *
551
- * Factored out because the same surface backs two things — every `ctx.trace`
552
- * span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
553
- * attributes become the canonical one-event-per-request summary. Sharing the
554
- * implementation is what makes those two feel like the same API instead of two
555
- * that happen to resemble each other.
556
- *
557
- * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
558
- * `exception.stacktrace` the same way {@link createTracer} gates a span's own
559
- * error message — a stack is file paths and internals by definition, the exact
560
- * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
- * escape hatch rather than shipping to a third-party collector by default.
570
+ * Copy an attribute bag onto a host span, best-effort: one native
571
+ * `setAttributes` call where the runtime has it, a `setAttribute` loop where it
572
+ * does not. Skipped for an untraced span; non-primitive values are dropped,
573
+ * since CF's setters take `string | number | boolean` only.
562
574
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
575
+ declare const setHostSpanAttributes: (span: HostSpanLike, attributes: Record<string, LogFields[string]>) => void;
567
576
  /**
568
- * Build the `ctx.trace` span factory for one dispatched function.
569
- *
570
- * **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
571
- * to that span; calling it is what makes a child. An earlier design kept an
572
- * ambient stack of "the currently open span" and parented to its top, which
573
- * reads nicer but is unfixably wrong under concurrency: in
574
- * `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
575
- * stack and is recorded as a *child* of `a` rather than its sibling — and
576
- * parallel fan-out is one of the main things people reach for a tracer to
577
- * measure. Distinguishing "called inside a's body" from "called concurrently
578
- * with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
579
- * `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
580
- * `nodejs_compat`). So the parent is threaded, exactly like the dependency
581
- * tracker and the subscription identity: correct in every case, and visible at
582
- * the call site.
583
- *
584
- * The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
585
- * cleared in the dispatch `finally`, and a subscription re-run builds its ctx
586
- * during* the writing mutation's flush — so reading that shared field at span
587
- * time would file the re-run's spans under the mutation's trace.
588
- *
589
- * **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
590
- * `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
591
- * a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
592
- * body runs inside a CF custom span so our span nests under CF's native
593
- * binding/fetch/handler trace tree on the hosted path, and the finished span's
594
- * key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
595
- * boundaries hold.
577
+ * Mirror a finished dispatch onto the host's invocation span — the one
578
+ * `tracing.getActiveSpan()` returns once every `ctx.trace` custom span has
579
+ * ended. Pure and fully best-effort: a missing `getActiveSpan`, an untraced span
580
+ * or a throwing setter is a silent no-op, never an error for the dispatch.
596
581
  *
597
- * **No double-export by default, and never a replacement.** The bridge only ADDS a
598
- * CF-side span; the recorded {@link SpanEvent} handed to `record` (our
599
- * `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
600
- * stays the source of truth. It is off unless explicitly enabled precisely
601
- * because, once on, a deployment that ALSO ships our `otlpSink` to a collector
602
- * AND lets CF export its trace tree emits the same logical span down two
603
- * pipelines — an intentional, documented trade the operator opts into, not a
604
- * default.
582
+ * `attributes` is the dispatch root span's already-redacted wide event, when it
583
+ * recorded one. `error` is set when the dispatch failed; its `serverFault` is the
584
+ * CALLER's verdict on whether that failure is the server's: the status of the
585
+ * response it actually sent (>= 500) for an RPC, always `true` for a trigger
586
+ * that threw. Only a server fault marks the span failed; a 4xx is an expected
587
+ * client outcome that OTel's server-span convention leaves `"unset"`. `message`
588
+ * must already be redacted.
605
589
  *
606
- * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
607
- * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
608
- * Object under `@cloudflare/vitest-pool-workers` (see
609
- * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
610
- * from `cloudflare:workers`, its callback executes and returns the body value
611
- * without throwing, `span.isTraced` is a real boolean, and — the key additive
612
- * guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
613
- * `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
614
- * harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
615
- * attached the run is unsampled (`isTraced === false`), so CF records nothing and
616
- * its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
617
- * inside a DO stays unverified upstream, and this remains capability-probed: an
618
- * absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
619
- * resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
620
- * misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
621
- * waterfall is unaffected.
590
+ * The status is written before the attributes so a throwing attribute setter
591
+ * cannot drop it.
622
592
  */
623
- declare const createTracer: (deps: TracerDeps) => ContextTracer;
624
- /** What {@link createTracedFetch} needs from the shard. */
625
- interface TracedFetchDeps {
626
- /** The trace the CLIENT spans belong to. */
627
- anchor: TraceAnchor;
628
- /** Function path the spans are attributed to. */
629
- functionPath: string;
630
- /**
631
- * Whether to inject `traceparent` into the outbound request — and, with a
632
- * predicate, to which destinations. Default `true`.
633
- */
634
- propagate?: ((url: URL) => boolean) | boolean;
635
- /** Hand a finished span to the buffer + sink. */
636
- record: (span: SpanEvent) => void;
637
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
638
- shardKey: string | undefined;
639
- /** Read lazily — the acting user is resolved per span. */
640
- userId: () => string | undefined;
593
+ declare const applyHostRootSpan: (tracing: HostTracingLike | undefined, root: {
594
+ attributes?: Record<string, LogFields[string]>;
595
+ error?: {
596
+ message: string;
597
+ serverFault: boolean;
598
+ };
599
+ }) => void;
600
+ /** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
601
+ declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
602
+ /**
603
+ * Triage status of an Issue. `open` is the implicit default (no state row); a
604
+ * developer moves it to `resolved` (fixed, but a *new* matching error re-opens
605
+ * it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
606
+ * and stays muted regardless of new occurrences).
607
+ */
608
+ type IssueStatus = "ignored" | "open" | "resolved";
609
+ /** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
610
+ type IssueSeverity = "critical" | "high" | "low" | "medium";
611
+ /** The persisted triage state for one Issue fingerprint. */
612
+ interface IssueState {
613
+ /** Free-form assignee (a userId or a name); absent when unassigned. */
614
+ assignee?: string;
615
+ /** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
616
+ hash: string;
617
+ /** Developer-tagged severity; absent when untriaged. */
618
+ severity?: IssueSeverity;
619
+ /** Current triage status. */
620
+ status: IssueStatus;
621
+ /** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
622
+ updatedAt: number;
623
+ /** Acting userId that last changed the state, when known. */
624
+ updatedBy?: string;
641
625
  }
642
- /** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
643
- type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
626
+ /** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
627
+ interface IssueStatePatch {
628
+ assignee?: null | string;
629
+ severity?: IssueSeverity | null;
630
+ status?: IssueStatus;
631
+ }
632
+ /** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
633
+ declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
634
+ /** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
635
+ declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
644
636
  /**
645
- * Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
646
- * becomes a **CLIENT span** and carries W3C trace context to the callee.
637
+ * Apply a triage patch to one Issue, upserting its state row. A `null` in the
638
+ * patch clears the field (unassign, untag severity); an omitted field is left
639
+ * unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
647
640
  *
648
- * Two gaps close here. First, an uninstrumented `fetch` makes the single most
649
- * common source of latency — waiting on somebody else's service — invisible: a
650
- * handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
651
- * without an outbound `traceparent` the callee starts a brand-new trace, so the
652
- * two halves of one logical request can never be stitched together, which is the
653
- * entire premise of distributed tracing.
654
- *
655
- * The span id is minted BEFORE the request is sent, precisely so the header
656
- * announces the id the span will actually be recorded under. Deriving it
657
- * afterwards (or reusing the parent's) would produce a `traceparent` naming a
658
- * span that never existed, and a callee parented to nothing.
659
- *
660
- * Kind is `client` rather than `internal` — that is what lets a collector draw
661
- * the edge to the downstream service in a service map.
662
- *
663
- * Failures are recorded and re-thrown untouched, and a non-2xx response is
664
- * recorded as an ERROR span (it is a failed call from the caller's point of
665
- * view) while still being returned normally — instrumentation, never flow
666
- * control.
667
- */
668
- declare const createTracedFetch: (deps: TracedFetchDeps, base: ContextFetch) => ContextFetch;
669
- /**
670
- * Build the `ctx.metrics` recorder for one dispatched function.
671
- *
672
- * Deliberately stateless: each call emits one measurement rather than
673
- * accumulating into a per-dispatch map. Pre-aggregating here would have to pick a
674
- * flush point and a merge rule per instrument kind (sum a counter, last-wins a
675
- * gauge, and a histogram cannot be merged at all without losing the
676
- * distribution) — so the runtime stays a transport and the collector, which is
677
- * built for exactly this, does the aggregation.
678
- */
679
- declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
680
- /**
681
- * Build the synthetic root span for a finished dispatch — the bar the studio's
682
- * waterfall hangs a request's `ctx.trace` spans under.
683
- *
684
- * Pure: the caller decides whether to record it (only when the dispatch actually
685
- * produced spans) and where to put it. It is never routed to `sink.onSpan`,
686
- * because the runtime already emits the dispatch to `onRpc` and a collector would
687
- * otherwise show it twice.
641
+ * Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
642
+ * field so a partial patch touches only what it names — except the explicit
643
+ * `null` sentinels for assignee/severity, which are threaded separately so a
644
+ * clear can win over `COALESCE`.
688
645
  */
689
- declare const dispatchRootSpan: (input: {
690
- anchor: TraceAnchor;
646
+ declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
647
+ /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
648
+ declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
649
+ /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
650
+ type RequestOutcome = "error" | "ok";
651
+ /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
652
+ interface RequestLogEntry {
653
+ /** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
654
+ cacheHit?: boolean;
655
+ /** 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?". */
656
+ deploymentId?: string;
657
+ /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
658
+ durationMs: number;
659
+ /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
660
+ errorMessage?: string;
661
+ /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
662
+ functionPath: string;
663
+ /** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
664
+ identity?: Record<string, unknown>;
665
+ /** `ok` for a returned result, `error` for a thrown handler. */
666
+ outcome: RequestOutcome;
667
+ /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
668
+ redactedArgs?: unknown;
669
+ /** Monotonic per-shard cursor — strictly increasing, never reused. */
670
+ seq: number;
671
+ /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
672
+ shardKey?: string;
673
+ /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
674
+ subscriptionsReRun: number;
675
+ /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
676
+ tablesRead: string[];
677
+ /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
678
+ tablesWritten: string[];
679
+ /** 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. */
680
+ traceId?: string;
681
+ /** Wall-clock millis when the dispatch completed. */
682
+ ts: number;
683
+ /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
684
+ userId?: string;
685
+ /** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
686
+ versionTag?: string;
687
+ }
688
+ /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
689
+ interface AppendRequestLogEntry {
690
+ cacheHit?: boolean;
691
+ deploymentId?: string;
692
+ durationMs: number;
693
+ errorMessage?: string;
694
+ functionPath: string;
695
+ identity?: Record<string, unknown>;
696
+ outcome: RequestOutcome;
691
697
  /**
692
- * Whether to record the failure message verbatim rather than redacted —
693
- * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
694
- * synthetic root span carries the SAME error message the request log and
695
- * function-metrics sinks already redact by default, so it must not be the
696
- * one durable copy that ships it raw to a third-party collector.
698
+ * Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
699
+ * Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
700
+ * keeps its `trace_id` join key and has no column for it.
697
701
  */
702
+ rayId?: string;
703
+ redactedArgs?: unknown;
704
+ shardKey?: string;
705
+ subscriptionsReRun?: number;
706
+ tablesRead?: string[];
707
+ tablesWritten?: string[];
708
+ traceId?: string;
709
+ ts: number;
710
+ userId?: string;
711
+ versionTag?: string;
712
+ }
713
+ /** Knobs the dispatch site threads into a request-log write. */
714
+ interface RequestLogWriteOptions {
715
+ /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
698
716
  captureRaw?: boolean;
717
+ /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
718
+ retention?: number;
719
+ }
720
+ /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
721
+ interface ReadRequestLogOptions {
722
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
723
+ functionPathPrefix?: string;
724
+ /** Upper bound on returned rows, clamped to [1, 10000]. */
725
+ limit?: number;
726
+ /** Keep only `ok` / `error` outcomes. */
727
+ outcome?: RequestOutcome;
728
+ /** Exact shard-key match. */
729
+ shardKey?: string;
699
730
  /**
700
- * What the handler attached to the dispatch through `ctx.span` — the **wide
701
- * event**. These are the attributes that would otherwise have been scattered
702
- * across a dozen `ctx.log` lines; carrying them on the one span that already
703
- * exists per request is the OTel-native way to get a wide event without
704
- * multiplying log records.
731
+ * Only entries strictly after this cursor. Setting it switches the read to
732
+ * ASCENDING order — see {@link readRequestLog} — because that is the only
733
+ * ordering under which advancing the cursor to the last returned `seq`
734
+ * actually pages forward without a hole.
705
735
  */
706
- collected?: SpanCollection;
707
- durationMs: number;
708
- failure: {
709
- thrown: unknown;
710
- } | undefined;
711
- functionPath: string;
712
- shardKey: string | undefined;
713
- startTs: number;
714
- userId: string | undefined;
715
- }) => SpanEvent;
716
- /** Running totals for `"summary"` mode; created by the caller, read once at the dispatch boundary. */
717
- interface DatabaseTally {
718
- calls: number;
719
- durationMs: number;
720
- errors: number;
721
- perOperation: Record<string, number>;
722
- spansEmitted: number;
723
- spansTruncated: boolean;
736
+ sinceSeq?: number;
737
+ /** Keep only entries whose read OR written table set contains this table. */
738
+ tableTouched?: string;
739
+ /** Exact acting-userId match. */
740
+ userId?: string;
741
+ }
742
+ /** 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}). */
743
+ interface RequestLogResult {
744
+ entries: RequestLogEntry[];
724
745
  }
725
746
  /**
726
- * How much detail `ctx.db` auto-instrumentation produces.
727
- *
728
- * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
729
- * extra spans, no extra log records, and a cost that does not grow with call count.
730
- *
731
- * `"spans"` — one span per database call. The full waterfall, at the price of a
732
- * span per call; right when diagnosing, noisy as a permanent default.
733
- *
734
- * `"off"` — no database telemetry at all.
747
+ * One grouped error **Issue**: many `error`-outcome request-log rows that share a
748
+ * fingerprint folded into a single triage row. The `hash` is the same stable key
749
+ * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
750
+ * object.
735
751
  */
736
- type DatabaseInstrumentation = "off" | "spans" | "summary";
737
- /** What {@link instrumentDatabase} needs to record what it observes. */
738
- interface DatabaseTelemetryDeps {
739
- /** The trace produced spans belong to (`"spans"` mode only). */
740
- anchor: TraceAnchor;
752
+ interface ErrorIssue {
753
+ /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
754
+ assignee?: string;
755
+ /** Number of `error` rows folded into this Issue within the scanned window. */
756
+ count: number;
757
+ /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
758
+ culprit: string;
759
+ /** Wall-clock millis of the oldest folded row. */
760
+ firstSeen: number;
741
761
  /**
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.
762
+ * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
763
+ * computed from the RAW (pre-redaction) message at write time and stored on
764
+ * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
765
+ * below can't change the grouping.
747
766
  */
748
- captureRaw?: boolean;
749
- /** Function path spans and attributes are attributed to. */
750
- functionPath: string;
751
- /** Detail level; see {@link DatabaseInstrumentation}. */
752
- mode: DatabaseInstrumentation;
753
- /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
754
- record: (span: SpanEvent) => void;
755
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
756
- shardKey: string | undefined;
767
+ hash: string;
768
+ /** Wall-clock millis of the newest folded row. */
769
+ lastSeen: number;
770
+ /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
771
+ sampleMessage: string;
772
+ /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
773
+ severity?: IssueSeverity;
757
774
  /**
758
- * Caller-supplied accumulator for `"summary"` mode. The instrumenter only ever
759
- * increments numbers on it; the shard reads it ONCE at the dispatch boundary
760
- * and formats it with {@link formatTally}.
761
- *
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.
775
+ * Wall-clock millis the persisted triage state was last changed; absent when
776
+ * the Issue has never been triaged. Compared against `lastSeen` to detect a
777
+ * regression (a new error after a resolve).
767
778
  */
768
- tally: DatabaseTally;
769
- /** Read lazily — the acting user is resolved per span. */
770
- userId: () => string | undefined;
779
+ stateUpdatedAt?: number;
780
+ /**
781
+ * Triage status folded in from the persisted state (`open` by default). A
782
+ * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
783
+ * auto-reopened to `open` here (a regression), so a fresh occurrence never
784
+ * hides behind a stale resolution; `ignored` stays sticky by design.
785
+ */
786
+ status: IssueStatus;
787
+ /** Human-readable title (first line of the sample message, capped). */
788
+ title: string;
789
+ }
790
+ /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
791
+ interface IssuesResult {
792
+ issues: ErrorIssue[];
793
+ }
794
+ /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
795
+ interface ReadIssuesOptions {
796
+ /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
797
+ functionPathPrefix?: string;
798
+ /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
799
+ limit?: number;
800
+ /** Exact shard-key match. */
801
+ shardKey?: string;
802
+ /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
803
+ status?: IssueStatus;
804
+ /** Exact acting-userId match. */
805
+ userId?: string;
771
806
  }
772
807
  /**
773
- * Wrap a `ctx.db` writer so its storage-touching methods are instrumented.
774
- *
775
- * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
776
- * path costs nothing — not even a proxy indirection.
808
+ * Mask credentials only, leaving PII alone: `maskCredentials` — credential key
809
+ * names, `name=value` pairs, auth schemes, JWTs, PEM keys, URL query / fragment
810
+ * / userinfo. For span, event, link and metric attributes: {@link redactArgs}'
811
+ * PII rules key on names like `id`, `url` and `date` and mask uuids, so they
812
+ * would erase the very `order.id` / `url` attributes a trace is read by, and
813
+ * `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
814
+ * thread, where every span, event and metric pays it. `captureRaw` as in
815
+ * {@link redactArgs}.
816
+ */
817
+ declare const redactCredentials: (value: unknown, captureRaw?: boolean) => unknown;
818
+ /**
819
+ * Redact the secrets / PII out of a value before it reaches the durable log, a
820
+ * Logpush event, a function-metrics row or a span's error message:
821
+ * `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
822
+ * `undefined` pass through unchanged.
823
+ *
824
+ * On a KEYED object (`args`, `identity`), a key that names a credential
825
+ * (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
826
+ * `DATABASE_URL`) has its value masked, numbers included; a key that measures
827
+ * credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
828
+ * `shared/credential-redaction.ts` for how keys are judged.
829
+ *
830
+ * On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
831
+ * fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
832
+ * with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
833
+ * masked; and so is a bare token in prose with no name attached, when its format
834
+ * has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
835
+ * `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
836
+ * `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
837
+ * string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
838
+ * been examined the remaining strings are replaced with a marker, so no arg can
839
+ * hold the Durable Object in regex work.
840
+ *
841
+ * Still NOT caught: a bare secret with no name attached and no vendor prefix (a
842
+ * random hex key, a password in a sentence). This is a credential-and-PII net,
843
+ * not proof that no secret can reach the log.
777
844
  *
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.
845
+ * `captureRaw` is the development escape hatch: in a dev environment the dispatch
846
+ * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
847
+ * see real arg/identity/error values; production always redacts. The dev
848
+ * decision is made at the call site from the deployment env, never inferred
849
+ * here — so a real deploy that omits the env var stays redacted.
784
850
  */
785
- declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
786
- /** A zero'd tally for one dispatch. */
787
- declare const createDatabaseTally: () => DatabaseTally;
851
+ declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
852
+ /** What a `v.sensitive` argument is replaced with before it reaches any log row, Logpush event or dev capture. */
853
+ declare const SENSITIVE_ARG_MASK = "«sensitive»";
788
854
  /**
789
- * Render the running tally as span attributes.
790
- *
791
- * 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.
855
+ * Replace the named arguments of one dispatch with {@link SENSITIVE_ARG_MASK},
856
+ * leaving every other argument as it was. Applied BEFORE {@link redactArgs}: the
857
+ * `captureRaw` development escape hatch skips redaction entirely, so masking
858
+ * inside `redactArgs` would leak a marked value in dev. Returns `args` itself when
859
+ * nothing is sensitive, and never mutates the caller's object.
794
860
  */
795
- declare const formatTally: (tally: DatabaseTally) => LogFields;
796
- /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
797
- declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
798
- /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
799
- declare const FUNCTION_METRICS_BUCKETS_TABLE = "__lunora_metrics_buckets";
800
- /** Reserved causal full-scan attribution table: per-(function, table) full-scan counts. */
801
- declare const FUNCTION_METRICS_SCANS_TABLE = "__lunora_metrics_scans";
802
- /** Reserved per-(table, index) hit-counter table backing the advisor dead-index lint. */
803
- declare const FUNCTION_METRICS_INDEX_TABLE = "__lunora_metrics_index";
804
- /**
805
- * Width of one history bucket, in milliseconds. 60s gives a minute-resolution
806
- * time series — fine-grained enough to chart bursts on the studio, coarse
807
- * enough that a single function emits at most one row per minute. Exported so
808
- * consumers (and tests) can align timestamps to the same grid.
809
- */
810
- declare const FUNCTION_METRICS_BUCKET_MS = 6e4;
861
+ declare const maskSensitiveArgs: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => Record<string, unknown>;
862
+ declare const sensitiveValues: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
811
863
  /**
812
- * Most recent buckets kept per function; older rows are trimmed after each
813
- * write so the time series can't grow unbounded. 1440 minute-buckets ≈ 24h of
814
- * history per function.
815
- */
816
- declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
817
- /**
818
- * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
819
- * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
820
- * same reason): the real bound is the app's own registered-function set plus
821
- * deploy churn (a rename/removal leaves its old path's row in place, still
822
- * counted against the cap, until an operator's own retention/cleanup
823
- * process — there is none built in today) — a few thousand registered
824
- * functions is already far beyond any real app. `shard-do.ts`'s dispatch
825
- * handler explicitly does NOT record per-function metrics for an
826
- * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
827
- * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
828
- * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
829
- * cap, deploy churn across the app's lifetime would still grow
830
- * `__lunora_metrics` (and its bucket/scan satellites) without bound,
831
- * eventually filling the shard's SQLite store shared with the app's real
832
- * data. At the cap, a brand-new path is refused — protecting the incumbent
833
- * leaderboard from a flood of one-off paths is the point, so admission is
834
- * refused rather than evicting an existing path to make room; already-tracked
835
- * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
836
- * `capped` is the read-side signal for this.
864
+ * The property names of the marked arguments, taken from every object under them. A
865
+ * marked key can be used as a log field or span-attribute name, so it is matched as a
866
+ * whole field name only (see {@link SecretSet}): a name such as `value` is ordinary
867
+ * prose and must not be masked wherever it appears in text.
837
868
  */
838
- declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
869
+ declare const sensitiveNames: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
839
870
  /**
840
- * Upper bound on rows the admin reads materialize into DO memory at once. Even
841
- * with the write-side `FUNCTION_METRICS_MAX_PATHS` cap in place, an existing
842
- * shard could already hold a bloated accumulator (rows written before the cap
843
- * landed), so the read path also clamps — a `SELECT *` with no LIMIT would
844
- * otherwise load every row via `.toArray()` and risk OOMing the ~128MB DO when
845
- * the studio Function Stats panel opens. Ordered reads keep the busiest/most
846
- * recent rows; the tail past this limit is simply not returned to the panel.
871
+ * The sensitive values of ONE invocation, handed by value to everything that
872
+ * records on its behalf (ctx.log, ctx.trace, ctx.span, ctx.fetch, ctx.metrics and
873
+ * the dispatch's root span). It is the only place the values live: a scope is
874
+ * built when the dispatch starts and {@link SensitiveScope.clear}ed when it
875
+ * settles, after which it scrubs nothing. Nothing reads it from shared state, so
876
+ * two concurrent dispatches on one shard each scrub only their own values.
847
877
  */
848
- declare const FUNCTION_METRICS_READ_LIMIT = 1e3;
849
- /** One coarse time-series sample for a function: call/error counts within `[bucketMs, bucketMs + FUNCTION_METRICS_BUCKET_MS)`. */
850
- interface FunctionMetricBucket {
851
- /** Epoch-ms floor of the bucket window. */
852
- bucketMs: number;
853
- /** Dispatches recorded in this window. */
854
- calls: number;
855
- /** Subset of `calls` that threw. */
856
- errors: number;
857
- }
858
- /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
859
- interface FunctionMetricBucketsResult {
860
- buckets: (FunctionMetricBucket & {
861
- path: string;
862
- })[];
878
+ interface SensitiveScope {
863
879
  /**
864
- * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
865
- * return, so `buckets` is a partial (newest) window rather than the app's
866
- * full retained history. Mirrors `readQueryInsights`'s `capped` and
867
- * `foldTraces`'s `total`: a silently truncated read looks identical to a
868
- * complete one to a caller that doesn't check for it — the Metrics chart's
869
- * window would appear to shrink as the app grows, with a wrong leftmost
870
- * bar, and nothing would say why.
880
+ * Admit more values into the invocation: a composed call runs inside the
881
+ * caller's invocation, so its own marked arguments are scrubbed from here on.
882
+ * `names` are that call's marked property names (see {@link sensitiveNames}).
883
+ * A no-op once the scope is cleared.
871
884
  */
872
- truncated: boolean;
873
- }
874
- /** One declared index a dispatch exercised (used to narrow a read). */
875
- interface IndexHit {
876
- /** The declared index name. */
877
- index: string;
878
- /** The table the index is declared on. */
879
- table: string;
880
- }
881
- /** One declared index's cumulative recorded read count (durable, non-decaying) — the advisor dead-index lint input. */
882
- interface FunctionMetricIndexHit {
883
- /** The declared index name. */
884
- index: string;
885
- /** Recorded reads that used this index to narrow. */
886
- reads: number;
887
- /** The table the index is declared on. */
888
- table: string;
889
- }
890
- /** Fields recorded for one completed dispatch. `errored` advances the failure counters. */
891
- interface RecordFunctionMetricInput {
885
+ add: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => void;
892
886
  /**
893
- * Whether the dispatch failed on an optimistic-concurrency (OCC) write
894
- * conflict — a compare-and-swap that lost to a concurrent commit. Advances
895
- * the durable `conflicts` counter behind the write-contention advisor. A
896
- * conflicted dispatch also `errored`, so conflicts are a subset of errors.
897
- * Omitted/false on the common path, keeping the hot path unchanged.
887
+ * Mark the dispatch settled. The values are forgotten once no `hold` is
888
+ * outstanding, so a record still open when the dispatch returns is scrubbed.
898
889
  */
899
- conflicted?: boolean;
900
- /** Wall-clock millis the handler took. */
901
- durationMs: number;
902
- /** Whether the dispatch threw. */
903
- errored: boolean;
904
- /** Most recent failure message, recorded only when `errored`. */
905
- errorMessage?: string;
890
+ clear: () => void;
891
+ /** Scrub a field bag; `undefined` passes through. */
892
+ fields: <T extends Record<string, unknown> | undefined>(bag: T) => T;
906
893
  /**
907
- * Distinct declared indexes this dispatch exercised (used to narrow a read),
908
- * collected from the `onIndexUse` signal. Each entry bumps the
909
- * per-`(table, index)` hit counter in `__lunora_metrics_index`, the durable
910
- * producer behind the advisor dead-index lint. Omitted/empty when the
911
- * dispatch used no declared index, keeping the hot path unchanged.
894
+ * Keep the values for a record opened under this scope and not yet written.
895
+ * Returns the release, which is idempotent. A record opened while the scope is
896
+ * live is scrubbed from the values as they stand then.
912
897
  */
913
- indexHits?: ReadonlyArray<IndexHit>;
914
- /** The `<file>:<function>` identifier. */
915
- path: string;
898
+ hold: () => () => void;
916
899
  /**
917
- * Distinct tables this dispatch full-scanned (read with no index / point
918
- * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
919
- * aggregate `scans` counter and the per-`(path, table)` attribution row.
920
- * Omitted/empty when the dispatch didn't full-scan anything (the common
921
- * indexed case), keeping the hot path to the same two upserts as before.
900
+ * Scrub a telemetry name (an event, span or metric name, or a plain log message). A name that is exactly
901
+ * a marked property name masks whole; any other name is scrubbed as free text.
922
902
  */
923
- scannedTables?: ReadonlyArray<string>;
924
- /** Epoch-ms the dispatch completed. */
925
- ts: number;
903
+ name: (name: string) => string;
904
+ /** Scrub a free-text string. */
905
+ text: (text: string) => string;
906
+ /** Scrub one structured value. */
907
+ value: <T>(value: T) => T;
926
908
  }
927
909
  /**
928
- * Create the four reserved metrics tables. Idempotent, so the read and write
929
- * paths can call it defensively. The accumulator table is keyed by `path` (one
930
- * row per function); the bucket table by `(path, bucketMs)` (one row per
931
- * function per window); the scans table by `(path, table)` (one row per
932
- * function per full-scanned table); the index table by `(table, index)` (one
933
- * row per declared index the app exercises).
910
+ * Build the scope for one invocation from the values and property names of its marked
911
+ * arguments (see {@link sensitiveValues} and {@link sensitiveNames}). The arrays are
912
+ * copied, so the caller keeps no handle on the values it passed in.
913
+ */
914
+ declare const createSensitiveScope: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => SensitiveScope;
915
+ /**
916
+ * The scope of an invocation with no marked arguments. Scrubs nothing, and admits
917
+ * nothing: it is shared by every such invocation, so `add` must not reach it.
918
+ */
919
+ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
920
+ /**
921
+ * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
922
+ * key, giving each shard a monotonic cursor the Logs tab pages through; the
923
+ * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
924
+ * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
925
+ * call it defensively.
934
926
  *
935
- * The accumulator's `scans` column is added via a guarded `ALTER TABLE` rather
936
- * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
937
- * causal-attribution feature gains the column on the next call without a
927
+ * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
928
+ * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
929
+ * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
930
+ * trace id, the correlation key to the span ring and to whatever collector
931
+ * `otlpSink` ships to.
932
+ *
933
+ * Both are also added via a guarded `ALTER TABLE`, mirroring
934
+ * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
935
+ * `__lunora_reqlog__` predates a column gains it on the next call without a
938
936
  * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
939
- * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
940
- * run once per handle (see {@link ensuredHandles}) — a handle already marked
941
- * ensured returns immediately.
937
+ * error from a re-run (or from the freshly-created schema above) is swallowed
938
+ * per column — the loop is what keeps one column's duplicate from skipping the
939
+ * next column's add.
942
940
  */
943
- declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
941
+ declare const ensureRequestLogTable: (sql: SqlExec) => void;
944
942
  /**
945
- * Persist one completed dispatch: a single upsert into the accumulator row and
946
- * one upsert into the current time bucket, then a bounded trim of old buckets
947
- * for that path. Creates the tables first so callers needn't. This is the hot
948
- * path — exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a
949
- * bounded `DELETE`, all keyed by primary key, so it stays cheap.
943
+ * Append one dispatch to the request log, then — once per
944
+ * {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
945
+ * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
946
+ * table first so callers needn't. Args/identity/error message are redacted here
947
+ * so a raw value never reaches the durable table — callers pass the unredacted
948
+ * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
949
+ * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
950
+ * dispatch site.
950
951
  *
951
- * When the dispatch full-scanned one or more tables (`scannedTables`), the
952
- * aggregate `scans` counter on the accumulator row advances by the distinct
953
- * table count and one extra `(path, table)` upsert fires per scanned table.
954
- * Indexed dispatches (the common case) skip all of that and pay nothing.
952
+ * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
953
+ * it's redacted below, and the resulting hash is persisted in
954
+ * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
955
+ * recomputing `fingerprintError` from the (redacted) `error_message` column, so
956
+ * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
957
+ * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
958
+ * existing Issue or change its identity.
955
959
  */
956
- declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
960
+ declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
957
961
  /**
958
- * Read the per-function full-scan attribution, grouped by function path. The
959
- * returned map keys are `path`; each value is the function's full-scanned
960
- * tables ordered by scan count (busiest scan first), so the causal "slow
961
- * BECAUSE it scanned X" read can lead with the dominant table. Creates the
962
- * table first so reads on a never-called shard return an empty map.
962
+ * Emit one structured request event to `console` so Cloudflare's Workers Logs /
963
+ * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
964
+ * NOT reimplement a transport: it produces a richer, lunora-attributed event and
965
+ * lets CF's existing trace-log pipe ship it. The event mirrors the durable
966
+ * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
967
+ * read/written, cache hit), with `args`, `identity`, AND `error` redacted
968
+ * exactly like the durable write so no raw PII/secret reaches the log pipeline.
969
+ *
970
+ * An `error` outcome goes to `console.error` (surfacing at error level in the
971
+ * trace so a SIEM can alert on it); everything else to `console.log`. The
972
+ * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
973
+ * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
974
+ * redaction, mirroring the durable write. Best-effort by contract — the caller
975
+ * wraps it so a serialization hiccup can never fail the served request.
963
976
  */
964
- declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
977
+ declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
965
978
  /**
966
- * Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
967
- * Each entry is a declared index and how many recorded reads used it to narrow
968
- * (a cumulative, non-decaying count); the lint reconciles this against the schema
969
- * to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
970
- * by table then index for stable output. Creates the table first so a read on a
971
- * never-exercised shard returns `[]`.
979
+ * The `ctx.log` event contract (shape + severity union) lives in
980
+ * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
981
+ * events and the `@lunora/runtime` sink that consumes them agree by construction.
982
+ * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
972
983
  */
973
- declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
984
+ type LogEventInput = LogEvent;
974
985
  /**
975
- * Fold a dispatch's distinct full-scanned tables into an in-memory attribution
976
- * list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
977
- * applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
978
- * SQL twin, so the one rule (one occurrence = +1 scan for that table, list
979
- * re-sorted busiest-first) lives in a single module — the in-memory copy exists
980
- * only for the warm-instance fallback when the durable read is unavailable.
981
- * Mutates and returns `into`.
986
+ * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
987
+ * and optional structured `fields`. The structured form — a message string plus
988
+ * a plain-object fields bag — is matched only for exactly `(string, object)`;
989
+ * every other shape is console-style and rendered whole (so existing
990
+ * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
991
+ * the per-call fields (per-call wins); the result is normalized to a fresh bag
992
+ * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
982
993
  */
983
- declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
994
+ declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
995
+ fields?: LogFields;
996
+ message: string;
997
+ };
984
998
  /**
985
- * Read the persisted per-function accumulators as {@link FunctionCallStat}s,
986
- * newest-called first. Creates the table first so reads on a never-called shard
987
- * return `[]` instead of throwing. The shape is a superset of the legacy
988
- * in-memory `getFunctionStats` rows — the additive `scans` total and
989
- * `scannedTables` causal attribution are folded in here so a single read backs
990
- * the Insights "missing index" / "full scan" signal.
999
+ * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1000
+ * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1001
+ * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1002
+ * raw Workers-trace firehose.
1003
+ *
1004
+ * Only the rendered `message` is emitted here, NOT the structured `args` array:
1005
+ * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1006
+ * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1007
+ * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1008
+ * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1009
+ * `message` already carries the developer's rendered values, exactly like a raw
1010
+ * `console.log` line.
1011
+ *
1012
+ * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1013
+ * surface at the right level in the trace); every other level to `console.log`.
1014
+ *
1015
+ * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1016
+ * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1017
+ * Unlike `args`, `fields` IS redacted before it rides this console line — a
1018
+ * developer can attach anything to a fields bag (`ctx.log.info("charged",
1019
+ * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1020
+ * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1021
+ * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1022
+ * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1023
+ * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1024
+ * there today — a conservative default, never a correctness gap. A field value
1025
+ * that can't be serialised (a circular object) would make `JSON.stringify`
1026
+ * throw and drop the whole line, so serialisation falls back to a fields-free
1027
+ * line rather than losing the event.
991
1028
  */
992
- declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
1029
+ declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
993
1030
  /**
994
- * Read the coarse time-series buckets for `path` (every path when omitted),
995
- * oldest-bucket first so a chart can plot them left-to-right. Creates the table
996
- * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
1031
+ * Read request-log entries, AND-combining the supplied filters (function-path
1032
+ * prefix, exact userId/shardKey/outcome, and a table-touched match against the
1033
+ * read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
1034
+ * is a bound parameter, so no filter can inject SQL. Creates the table first so
1035
+ * reads on a never-logged shard return `[]` instead of throwing. Mirrors
1036
+ * `readAuditLog`/`readCdcChanges`.
1037
+ *
1038
+ * **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
1039
+ * read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
1040
+ * With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
1041
+ * cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
1042
+ * n` answers "the newest n after the cursor", so a consumer that advances to the
1043
+ * largest returned `seq` skips everything between `sinceSeq` and that page
1044
+ * whenever more than `limit` rows accumulated between polls — the more traffic
1045
+ * the shard takes, the more it drops.
997
1046
  */
998
- declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
1047
+ declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1048
+ declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
1049
+ /**
1050
+ * Structural shape of the `ctx.trace` span factory (see the server
1051
+ * `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
1052
+ * dependency on `@lunora/server`; a cross-package assignability guard in
1053
+ * `@lunora/testing` fails the build if the two drift apart.
1054
+ *
1055
+ * The body's second argument is the enclosing span's {@link SpanHandle}, through
1056
+ * which it can attach attributes only known *after* it resolves (post-hoc). It is
1057
+ * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
1058
+ */
1059
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
1060
+ /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
1061
+ interface ContextMetrics {
1062
+ count: (name: string, value?: number, attributes?: LogFields) => void;
1063
+ gauge: (name: string, value: number, attributes?: LogFields) => void;
1064
+ record: (name: string, value: number, attributes?: LogFields) => void;
1065
+ }
1066
+ /** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
1067
+ interface TraceAnchor {
1068
+ /**
1069
+ * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
1070
+ * runtime alongside `traceparent`. Carried on the anchor so every span and
1071
+ * log line of the dispatch stamps the same value. Absent off the edge.
1072
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
1073
+ */
1074
+ rayId?: string;
1075
+ rootSpanId: string;
1076
+ /**
1077
+ * The W3C `sampled` verdict for this trace, inherited from the inbound
1078
+ * `traceparent` when there was one. Carried on the anchor rather than
1079
+ * re-derived per outbound call so every `ctx.fetch` of one dispatch
1080
+ * propagates the same answer.
1081
+ */
1082
+ sampled?: boolean;
1083
+ traceId: string;
1084
+ }
1085
+ /** What {@link createTracer} needs from the shard to build a span. */
1086
+ interface TracerDeps {
1087
+ /** The trace this ctx's spans belong to. */
1088
+ anchor: TraceAnchor;
1089
+ /**
1090
+ * Whether to record a span body's error message (and a `recordException`
1091
+ * stacktrace) verbatim rather than redacted. Mirrors the request log's
1092
+ * `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
1093
+ * the span pipeline is the one sink third-party collectors (Datadog/Axiom
1094
+ * via `otlpSink`) receive, so it must not ship raw PII/internals by default
1095
+ * the way the request log and function-metrics sinks already don't.
1096
+ */
1097
+ captureRaw?: boolean;
1098
+ /** Function path the spans are attributed to. */
1099
+ functionPath: string;
1100
+ /**
1101
+ * **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
1102
+ * {@link TracerDeps.resolveHostTracing} yields a working
1103
+ * `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
1104
+ * **custom span**, so it nests inside CF's native binding/fetch/handler trace
1105
+ * tree on the hosted path. This only ADDS a CF-side span — the recorded
1106
+ * {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
1107
+ * source of truth plus the local studio waterfall. The `enterSpan` call itself
1108
+ * is now workerd-validated as available and side-effect-free inside a Durable
1109
+ * Object; CF's exported parent-linking under sampling remains unverified. See
1110
+ * {@link createTracer} for the double-export and Durable-Object async-context
1111
+ * caveats.
1112
+ */
1113
+ fuseHostSpans?: boolean;
1114
+ /** Hand a finished span to the buffer + sink. */
1115
+ record: (span: SpanEvent) => void;
1116
+ /**
1117
+ * Injected resolver for CF's `tracing` namespace (see
1118
+ * {@link HostTracingResolver}). Only consulted when
1119
+ * {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
1120
+ * calls it.
1121
+ */
1122
+ resolveHostTracing?: HostTracingResolver;
1123
+ /**
1124
+ * The invocation's `v.sensitive` values (see {@link SensitiveScope}). Applied
1125
+ * to every span this tracer records, and to the body's own collector.
1126
+ */
1127
+ scope?: SensitiveScope;
1128
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1129
+ shardKey: string | undefined;
1130
+ /** Read lazily — the acting user is resolved per span, not per ctx. */
1131
+ userId: () => string | undefined;
1132
+ }
1133
+ /** What {@link createMetrics} needs from the shard to build a measurement. */
1134
+ interface MetricsDeps {
1135
+ functionPath: string;
1136
+ record: (event: MetricEvent) => void;
1137
+ /** The invocation's `v.sensitive` values, applied to each measurement's attributes. */
1138
+ scope?: SensitiveScope;
1139
+ shardKey: string | undefined;
1140
+ }
1141
+ /** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
1142
+ interface SpanCollection {
1143
+ attributes: Record<string, LogFields[string]>;
1144
+ events: SpanEventPoint[];
1145
+ links: SpanLink[];
1146
+ }
1147
+ /** A {@link SpanHandle} plus read access to what it has collected so far. */
1148
+ interface SpanCollector {
1149
+ collected: SpanCollection;
1150
+ handle: SpanHandle;
1151
+ }
1152
+ /**
1153
+ * Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
1154
+ * `ctx.trace` body, and the bag it writes into.
1155
+ *
1156
+ * Factored out because the same surface backs two things — every `ctx.trace`
1157
+ * span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
1158
+ * attributes become the canonical one-event-per-request summary. Sharing the
1159
+ * implementation is what makes those two feel like the same API instead of two
1160
+ * that happen to resemble each other.
1161
+ *
1162
+ * `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
1163
+ * `exception.stacktrace` the same way {@link createTracer} gates a span's own
1164
+ * error message — a stack is file paths and internals by definition, the exact
1165
+ * class `isInternalCode` redaction exists for, so it rides the same dev-only
1166
+ * escape hatch rather than shipping to a third-party collector by default.
1167
+ *
1168
+ * `scope` scrubs the invocation's `v.sensitive` values out of everything written
1169
+ * here, at write time, so the collector never holds the raw value. It is applied
1170
+ * whatever `captureRaw` says: the dev escape hatch exists for stacks and
1171
+ * internals, not for a marked argument.
1172
+ */
1173
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean, scope?: SensitiveScope) => SpanCollector;
1174
+ /**
1175
+ * Build the `ctx.trace` span factory for one dispatched function.
1176
+ *
1177
+ * **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
1178
+ * to that span; calling it is what makes a child. An earlier design kept an
1179
+ * ambient stack of "the currently open span" and parented to its top, which
1180
+ * reads nicer but is unfixably wrong under concurrency: in
1181
+ * `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
1182
+ * stack and is recorded as a *child* of `a` rather than its sibling — and
1183
+ * parallel fan-out is one of the main things people reach for a tracer to
1184
+ * measure. Distinguishing "called inside a's body" from "called concurrently
1185
+ * with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
1186
+ * `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
1187
+ * `nodejs_compat`). So the parent is threaded, exactly like the dependency
1188
+ * tracker and the subscription identity: correct in every case, and visible at
1189
+ * the call site.
1190
+ *
1191
+ * The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
1192
+ * cleared in the dispatch `finally`, and a subscription re-run builds its ctx
1193
+ * during* the writing mutation's flush — so reading that shared field at span
1194
+ * time would file the re-run's spans under the mutation's trace.
1195
+ *
1196
+ * **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
1197
+ * `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
1198
+ * a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
1199
+ * body runs inside a CF custom span so our span nests under CF's native
1200
+ * binding/fetch/handler trace tree on the hosted path, and the finished span's
1201
+ * key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
1202
+ * boundaries hold.
1203
+ *
1204
+ * **No double-export by default, and never a replacement.** The bridge only ADDS a
1205
+ * CF-side span; the recorded {@link SpanEvent} handed to `record` (our
1206
+ * `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
1207
+ * stays the source of truth. It is off unless explicitly enabled precisely
1208
+ * because, once on, a deployment that ALSO ships our `otlpSink` to a collector
1209
+ * AND lets CF export its trace tree emits the same logical span down two
1210
+ * pipelines — an intentional, documented trade the operator opts into, not a
1211
+ * default.
1212
+ *
1213
+ * **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
1214
+ * `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
1215
+ * Object under `@cloudflare/vitest-plugin` (see
1216
+ * `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
1217
+ * from `cloudflare:workers`, its callback executes and returns the body value
1218
+ * without throwing, `span.isTraced` is a real boolean, and — the key additive
1219
+ * guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
1220
+ * `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
1221
+ * harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
1222
+ * attached the run is unsampled (`isTraced === false`), so CF records nothing and
1223
+ * its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
1224
+ * inside a DO stays unverified upstream, and this remains capability-probed: an
1225
+ * absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
1226
+ * resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
1227
+ * misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
1228
+ * waterfall is unaffected.
1229
+ */
1230
+ declare const createTracer: (deps: TracerDeps) => ContextTracer;
1231
+ /** What {@link createTracedFetch} needs from the shard. */
1232
+ interface TracedFetchDeps {
1233
+ /** The trace the CLIENT spans belong to. */
1234
+ anchor: TraceAnchor;
1235
+ /**
1236
+ * Whether to record a failed fetch's error message verbatim rather than
1237
+ * redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
1238
+ * the same reason: a `fetch` TypeError embeds the request URL, so a key in a
1239
+ * query string would otherwise reach the collector in the clear on the very
1240
+ * span whose `url.full` is scrubbed by `redactUrl`.
1241
+ */
1242
+ captureRaw?: boolean;
1243
+ /** Function path the spans are attributed to. */
1244
+ functionPath: string;
1245
+ /**
1246
+ * Whether to inject `traceparent` into the outbound request — and, with a
1247
+ * predicate, to which destinations. Default `true`.
1248
+ */
1249
+ propagate?: ((url: URL) => boolean) | boolean;
1250
+ /** Hand a finished span to the buffer + sink. */
1251
+ record: (span: SpanEvent) => void;
1252
+ /** The invocation's `v.sensitive` values; a query string or path can carry one. */
1253
+ scope?: SensitiveScope;
1254
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1255
+ shardKey: string | undefined;
1256
+ /** Read lazily — the acting user is resolved per span. */
1257
+ userId: () => string | undefined;
1258
+ }
1259
+ /** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
1260
+ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
1261
+ /**
1262
+ * Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
1263
+ * becomes a **CLIENT span** and carries W3C trace context to the callee.
1264
+ *
1265
+ * Two gaps close here. First, an uninstrumented `fetch` makes the single most
1266
+ * common source of latency — waiting on somebody else's service — invisible: a
1267
+ * handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
1268
+ * without an outbound `traceparent` the callee starts a brand-new trace, so the
1269
+ * two halves of one logical request can never be stitched together, which is the
1270
+ * entire premise of distributed tracing.
1271
+ *
1272
+ * The span id is minted BEFORE the request is sent, precisely so the header
1273
+ * announces the id the span will actually be recorded under. Deriving it
1274
+ * afterwards (or reusing the parent's) would produce a `traceparent` naming a
1275
+ * span that never existed, and a callee parented to nothing.
1276
+ *
1277
+ * Kind is `client` rather than `internal` — that is what lets a collector draw
1278
+ * the edge to the downstream service in a service map.
1279
+ *
1280
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
1281
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
1282
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
1283
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
1284
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
1285
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
1286
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
1287
+ * the span whose bar you want it under and read the two side by side.
1288
+ *
1289
+ * Failures are recorded and re-thrown untouched, and a non-2xx response is
1290
+ * recorded as an ERROR span (it is a failed call from the caller's point of
1291
+ * view) while still being returned normally — instrumentation, never flow
1292
+ * control.
1293
+ */
1294
+ declare const createTracedFetch: (deps: TracedFetchDeps, base: ContextFetch) => ContextFetch;
1295
+ /**
1296
+ * Build the `ctx.metrics` recorder for one dispatched function.
1297
+ *
1298
+ * Deliberately stateless: each call emits one measurement rather than
1299
+ * accumulating into a per-dispatch map. Pre-aggregating here would have to pick a
1300
+ * flush point and a merge rule per instrument kind (sum a counter, last-wins a
1301
+ * gauge, and a histogram cannot be merged at all without losing the
1302
+ * distribution) — so the runtime stays a transport and the collector, which is
1303
+ * built for exactly this, does the aggregation.
1304
+ */
1305
+ declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
1306
+ /**
1307
+ * Build the synthetic root span for a finished dispatch — the bar the studio's
1308
+ * waterfall hangs a request's `ctx.trace` spans under.
1309
+ *
1310
+ * Pure: the caller decides whether to record it (only when the dispatch actually
1311
+ * produced spans) and where to put it. It is never routed to `sink.onSpan`,
1312
+ * because the runtime already emits the dispatch to `onRpc` and a collector would
1313
+ * otherwise show it twice.
1314
+ */
1315
+ declare const dispatchRootSpan: (input: {
1316
+ anchor: TraceAnchor;
1317
+ /**
1318
+ * Whether to record the failure message verbatim rather than redacted —
1319
+ * the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
1320
+ * synthetic root span carries the SAME error message the request log and
1321
+ * function-metrics sinks already redact by default, so it must not be the
1322
+ * one durable copy that ships it raw to a third-party collector.
1323
+ */
1324
+ captureRaw?: boolean;
1325
+ /**
1326
+ * What the handler attached to the dispatch through `ctx.span` — the **wide
1327
+ * event**. These are the attributes that would otherwise have been scattered
1328
+ * across a dozen `ctx.log` lines; carrying them on the one span that already
1329
+ * exists per request is the OTel-native way to get a wide event without
1330
+ * multiplying log records.
1331
+ */
1332
+ collected?: SpanCollection;
1333
+ durationMs: number;
1334
+ failure: {
1335
+ thrown: unknown;
1336
+ } | undefined;
1337
+ functionPath: string;
1338
+ /** The invocation's `v.sensitive` values; the failure message can quote one. */
1339
+ scope?: SensitiveScope;
1340
+ shardKey: string | undefined;
1341
+ startTs: number;
1342
+ userId: string | undefined;
1343
+ }) => SpanEvent;
1344
+ /** Running totals for `"summary"` mode; created by the caller, read once at the dispatch boundary. */
1345
+ interface DatabaseTally {
1346
+ calls: number;
1347
+ durationMs: number;
1348
+ errors: number;
1349
+ perOperation: Record<string, number>;
1350
+ spansEmitted: number;
1351
+ spansTruncated: boolean;
1352
+ }
1353
+ /**
1354
+ * Which instrumented surface a tally belongs to, and the key prefix
1355
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
1356
+ */
1357
+ type TallySurface = "db" | "sql";
1358
+ /**
1359
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
1360
+ *
1361
+ * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
1362
+ * extra spans, no extra log records, and a cost that does not grow with call count.
1363
+ *
1364
+ * `"spans"` — one span per database call. The full waterfall, at the price of a
1365
+ * span per call; right when diagnosing, noisy as a permanent default.
1366
+ *
1367
+ * `"off"` — no database telemetry at all.
1368
+ */
1369
+ type DatabaseInstrumentation = "off" | "spans" | "summary";
1370
+ /**
1371
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
1372
+ * instrumenter needs — declared here so this package takes no dependency on
1373
+ * hyperdrive.
1374
+ */
1375
+ interface SqlClientLike {
1376
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
1377
+ readonly dbSystem?: string;
1378
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
1379
+ }
1380
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
1381
+ interface DatabaseTelemetryDeps {
1382
+ /** The trace produced spans belong to (`"spans"` mode only). */
1383
+ anchor: TraceAnchor;
1384
+ /**
1385
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
1386
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
1387
+ * {@link failureMessage} for what each surface records without it.
1388
+ */
1389
+ captureRaw?: boolean;
1390
+ /** Function path spans and attributes are attributed to. */
1391
+ functionPath: string;
1392
+ /** Detail level; see {@link DatabaseInstrumentation}. */
1393
+ mode: DatabaseInstrumentation;
1394
+ /** Hand a finished span to the buffer + sink (`"spans"` mode only). */
1395
+ record: (span: SpanEvent) => void;
1396
+ /** The invocation's `v.sensitive` values; a driver's error message can quote one. */
1397
+ scope?: SensitiveScope;
1398
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1399
+ shardKey: string | undefined;
1400
+ /**
1401
+ * Caller-supplied accumulator for `"summary"` mode. The instrumenter only ever
1402
+ * increments numbers on it; the shard reads it ONCE at the dispatch boundary
1403
+ * and formats it with {@link formatTally}.
1404
+ *
1405
+ * Per-call cost stays at a few integer increments — no object allocation, no
1406
+ * lookup — which matters because this is on the path of every query. Nothing
1407
+ * is written through the dispatch's `SpanHandle` either, so the wide-event
1408
+ * collector is never materialized by instrumentation alone: a dispatch that
1409
+ * ran queries gets a root span carrying these counters, but no `lunora.dispatch`
1410
+ * log record unless the handler actually opened `ctx.span`.
1411
+ */
1412
+ tally: DatabaseTally;
1413
+ /**
1414
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
1415
+ * they instrument the client, and return that captured value: a span is
1416
+ * built after the call's await, and per-request shared state read by then
1417
+ * may already belong to a concurrent request.
1418
+ */
1419
+ userId: () => string | undefined;
1420
+ }
1421
+ /**
1422
+ * Wrap a `ctx.db` writer so its storage-touching methods are instrumented.
1423
+ *
1424
+ * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
1425
+ * path costs nothing — not even a proxy indirection.
1426
+ *
1427
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
1428
+ * optional members that a given backend may or may not implement, plus
1429
+ * properties (`system`) and builder factories (`query`) that must pass through
1430
+ * untouched. A proxy instruments exactly what it is asked to and is
1431
+ * transparently correct for everything else, including members added later —
1432
+ * an enumeration would silently stop covering them.
1433
+ */
1434
+ declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
1435
+ /**
1436
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
1437
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
1438
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
1439
+ * as `sql.*`), never `ctx.db`'s.
1440
+ *
1441
+ * Its span carries no statement text and no parameters — only the
1442
+ * leading-keyword operation, the system, and the returned row count. No
1443
+ * `db.collection.name` either: naming the table means parsing past
1444
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
1445
+ * safe. A failure records its TYPE (see {@link failureMessage}).
1446
+ *
1447
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
1448
+ * method to cover. Everything else on the client passes through untouched, and
1449
+ * `"off"` returns the client itself.
1450
+ */
1451
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
1452
+ /** A zero'd tally for one dispatch. */
1453
+ declare const createDatabaseTally: () => DatabaseTally;
1454
+ /**
1455
+ * Render the running tally as span attributes, under its surface's prefix
1456
+ * ({@link TallySurface}).
1457
+ *
1458
+ * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
1459
+ * It is a handful of keys, so the per-call cost is a small object assignment —
1460
+ * the property that makes `"summary"` mode scale to any call count.
1461
+ */
1462
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
1463
+ /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
1464
+ declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
1465
+ /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
1466
+ declare const FUNCTION_METRICS_BUCKETS_TABLE = "__lunora_metrics_buckets";
1467
+ /** Reserved causal full-scan attribution table: per-(function, table) full-scan counts. */
1468
+ declare const FUNCTION_METRICS_SCANS_TABLE = "__lunora_metrics_scans";
1469
+ /** Reserved per-(table, index) hit-counter table backing the advisor dead-index lint. */
1470
+ declare const FUNCTION_METRICS_INDEX_TABLE = "__lunora_metrics_index";
1471
+ /**
1472
+ * Width of one history bucket, in milliseconds. 60s gives a minute-resolution
1473
+ * time series — fine-grained enough to chart bursts on the studio, coarse
1474
+ * enough that a single function emits at most one row per minute. Exported so
1475
+ * consumers (and tests) can align timestamps to the same grid.
1476
+ */
1477
+ declare const FUNCTION_METRICS_BUCKET_MS = 6e4;
1478
+ /**
1479
+ * Most recent buckets kept per function; older rows are trimmed after each
1480
+ * write so the time series can't grow unbounded. 1440 minute-buckets ≈ 24h of
1481
+ * history per function.
1482
+ */
1483
+ declare const FUNCTION_METRICS_BUCKET_RETENTION = 1440;
1484
+ /**
1485
+ * Maximum distinct function `path`s tracked in the accumulator table. Mirrors
1486
+ * `query-metrics.ts`'s `QUERY_METRICS_MAX_STATEMENTS` cap (and exists for the
1487
+ * same reason): the real bound is the app's own registered-function set plus
1488
+ * deploy churn (a rename/removal leaves its old path's row in place, still
1489
+ * counted against the cap, until an operator's own retention/cleanup
1490
+ * process — there is none built in today) — a few thousand registered
1491
+ * functions is already far beyond any real app. `shard-do.ts`'s dispatch
1492
+ * handler explicitly does NOT record per-function metrics for an
1493
+ * unregistered/`FUNCTION_NOT_FOUND` dispatch (see the guard next to its
1494
+ * `FUNCTION_NOT_FOUND` check), so a caller cannot mint arbitrary `path`s here
1495
+ * the way a raw caller-supplied SQL shape can in `query-metrics.ts`. Without a
1496
+ * cap, deploy churn across the app's lifetime would still grow
1497
+ * `__lunora_metrics` (and its bucket/scan satellites) without bound,
1498
+ * eventually filling the shard's SQLite store shared with the app's real
1499
+ * data. At the cap, a brand-new path is refused — protecting the incumbent
1500
+ * leaderboard from a flood of one-off paths is the point, so admission is
1501
+ * refused rather than evicting an existing path to make room; already-tracked
1502
+ * paths keep accumulating past the cap. `readFunctionMetricsTotals`'s
1503
+ * `capped` is the read-side signal for this.
1504
+ */
1505
+ declare const FUNCTION_METRICS_MAX_PATHS = 5e3;
1506
+ /**
1507
+ * Upper bound on rows the admin reads materialize into DO memory at once. Even
1508
+ * with the write-side `FUNCTION_METRICS_MAX_PATHS` cap in place, an existing
1509
+ * shard could already hold a bloated accumulator (rows written before the cap
1510
+ * landed), so the read path also clamps — a `SELECT *` with no LIMIT would
1511
+ * otherwise load every row via `.toArray()` and risk OOMing the ~128MB DO when
1512
+ * the studio Function Stats panel opens. Ordered reads keep the busiest/most
1513
+ * recent rows; the tail past this limit is simply not returned to the panel.
1514
+ */
1515
+ declare const FUNCTION_METRICS_READ_LIMIT = 1e3;
1516
+ /** One coarse time-series sample for a function: call/error counts within `[bucketMs, bucketMs + FUNCTION_METRICS_BUCKET_MS)`. */
1517
+ interface FunctionMetricBucket {
1518
+ /** Epoch-ms floor of the bucket window. */
1519
+ bucketMs: number;
1520
+ /** Dispatches recorded in this window. */
1521
+ calls: number;
1522
+ /** Subset of `calls` that threw. */
1523
+ errors: number;
1524
+ }
1525
+ /** {@link readFunctionMetricBuckets} result: the time-series window plus whether the read limit cut it short. */
1526
+ interface FunctionMetricBucketsResult {
1527
+ buckets: (FunctionMetricBucket & {
1528
+ path: string;
1529
+ })[];
1530
+ /**
1531
+ * True when more rows existed than {@link FUNCTION_METRICS_READ_LIMIT} could
1532
+ * return, so `buckets` is a partial (newest) window rather than the app's
1533
+ * full retained history. Mirrors `readQueryInsights`'s `capped` and
1534
+ * `foldTraces`'s `total`: a silently truncated read looks identical to a
1535
+ * complete one to a caller that doesn't check for it — the Metrics chart's
1536
+ * window would appear to shrink as the app grows, with a wrong leftmost
1537
+ * bar, and nothing would say why.
1538
+ */
1539
+ truncated: boolean;
1540
+ }
1541
+ /** One declared index a dispatch exercised (used to narrow a read). */
1542
+ interface IndexHit {
1543
+ /** The declared index name. */
1544
+ index: string;
1545
+ /** The table the index is declared on. */
1546
+ table: string;
1547
+ }
1548
+ /** One declared index's cumulative recorded read count (durable, non-decaying) — the advisor dead-index lint input. */
1549
+ interface FunctionMetricIndexHit {
1550
+ /** The declared index name. */
1551
+ index: string;
1552
+ /** Recorded reads that used this index to narrow. */
1553
+ reads: number;
1554
+ /** The table the index is declared on. */
1555
+ table: string;
1556
+ }
1557
+ /**
1558
+ * Fields recorded for one completed dispatch, or for a coalesced delta of
1559
+ * several. `errored` advances the failure counters. The optional count-carrying
1560
+ * fields let a caller that batched N dispatches write their exact sum in one
1561
+ * upsert; omitted, every field defaults to the single-dispatch value.
1562
+ */
1563
+ interface RecordFunctionMetricInput {
1564
+ /** Dispatches this record stands for. Default `1`. */
1565
+ calls?: number;
1566
+ /**
1567
+ * Whether the dispatch failed on an optimistic-concurrency (OCC) write
1568
+ * conflict — a compare-and-swap that lost to a concurrent commit. Advances
1569
+ * the durable `conflicts` counter behind the write-contention advisor. A
1570
+ * conflicted dispatch also `errored`, so conflicts are a subset of errors.
1571
+ * Omitted/false on the common path, keeping the hot path unchanged.
1572
+ */
1573
+ conflicted?: boolean;
1574
+ /** Conflicts in a coalesced delta. Default `conflicted ? 1 : 0`. */
1575
+ conflicts?: number;
1576
+ /** Longest handler time in a coalesced delta. Default `durationMs`. */
1577
+ durationMaxMs?: number;
1578
+ /** Shortest handler time in a coalesced delta. Default `durationMs`. */
1579
+ durationMinMs?: number;
1580
+ /** Wall-clock millis the handler took. */
1581
+ durationMs: number;
1582
+ /** Summed handler time of a coalesced delta. Default `durationMs`. */
1583
+ durationTotalMs?: number;
1584
+ /** Whether the dispatch threw. */
1585
+ errored: boolean;
1586
+ /** Most recent failure message, recorded only when `errored`. */
1587
+ errorMessage?: string;
1588
+ /** Failed dispatches in a coalesced delta. Default `errored ? 1 : 0`. */
1589
+ errors?: number;
1590
+ /**
1591
+ * Per-`(table, index)` hit counts of a coalesced delta (one per dispatch that
1592
+ * used the index). When set, replaces {@link RecordFunctionMetricInput.indexHits}.
1593
+ */
1594
+ indexHitCounts?: ReadonlyArray<IndexHit & {
1595
+ count: number;
1596
+ }>;
1597
+ /**
1598
+ * Distinct declared indexes this dispatch exercised (used to narrow a read),
1599
+ * collected from the `onIndexUse` signal. Each entry bumps the
1600
+ * per-`(table, index)` hit counter in `__lunora_metrics_index`, the durable
1601
+ * producer behind the advisor dead-index lint. Omitted/empty when the
1602
+ * dispatch used no declared index, keeping the hot path unchanged.
1603
+ */
1604
+ indexHits?: ReadonlyArray<IndexHit>;
1605
+ /** Epoch-ms of the latest failure in a coalesced delta. Default `errored ? ts : null`. */
1606
+ lastErrorAt?: number | null;
1607
+ /** The `<file>:<function>` identifier. */
1608
+ path: string;
1609
+ /**
1610
+ * Per-table full-scan counts of a coalesced delta (one per dispatch that
1611
+ * scanned the table). When set, replaces {@link RecordFunctionMetricInput.scannedTables}.
1612
+ */
1613
+ scanCounts?: ReadonlyArray<{
1614
+ count: number;
1615
+ table: string;
1616
+ }>;
1617
+ /**
1618
+ * Distinct tables this dispatch full-scanned (read with no index / point
1619
+ * lookup), collected from the `SCAN_DEP` reads. Each entry bumps the
1620
+ * aggregate `scans` counter and the per-`(path, table)` attribution row.
1621
+ * Omitted/empty when the dispatch didn't full-scan anything (the common
1622
+ * indexed case), keeping the hot path to the same two upserts as before.
1623
+ */
1624
+ scannedTables?: ReadonlyArray<string>;
1625
+ /** Epoch-ms the dispatch completed. */
1626
+ ts: number;
1627
+ }
1628
+ /**
1629
+ * Create the four reserved metrics tables. Idempotent, so the read and write
1630
+ * paths can call it defensively. The accumulator table is keyed by `path` (one
1631
+ * row per function); the bucket table by `(path, bucketMs)` (one row per
1632
+ * function per window); the scans table by `(path, table)` (one row per
1633
+ * function per full-scanned table); the index table by `(table, index)` (one
1634
+ * row per declared index the app exercises).
1635
+ *
1636
+ * The accumulator's `scans` column is added via a guarded `ALTER TABLE` rather
1637
+ * than baked into the `CREATE` so a shard whose `__lunora_metrics` predates the
1638
+ * causal-attribution feature gains the column on the next call without a
1639
+ * migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
1640
+ * error from a re-run is swallowed. Both the `CREATE`s and the back-fill only
1641
+ * run once per handle (see {@link ensuredHandles}) — a handle already marked
1642
+ * ensured returns immediately.
1643
+ */
1644
+ declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
1645
+ /**
1646
+ * Persist one completed dispatch: a single upsert into the accumulator row and
1647
+ * one upsert into the current time bucket, then a bounded trim of old buckets
1648
+ * for that path. Creates the tables first so callers needn't. This is the hot
1649
+ * path — exactly two `INSERT … ON CONFLICT … DO UPDATE` statements plus a
1650
+ * bounded `DELETE`, all keyed by primary key, so it stays cheap.
1651
+ *
1652
+ * When the dispatch full-scanned one or more tables (`scannedTables`), the
1653
+ * aggregate `scans` counter on the accumulator row advances by the distinct
1654
+ * table count and one extra `(path, table)` upsert fires per scanned table.
1655
+ * Indexed dispatches (the common case) skip all of that and pay nothing.
1656
+ */
1657
+ declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
1658
+ /**
1659
+ * Read the per-function full-scan attribution, grouped by function path. The
1660
+ * returned map keys are `path`; each value is the function's full-scanned
1661
+ * tables ordered by scan count (busiest scan first), so the causal "slow
1662
+ * BECAUSE it scanned X" read can lead with the dominant table. Creates the
1663
+ * table first so reads on a never-called shard return an empty map.
1664
+ */
1665
+ declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
1666
+ /**
1667
+ * Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
1668
+ * Each entry is a declared index and how many recorded reads used it to narrow
1669
+ * (a cumulative, non-decaying count); the lint reconciles this against the schema
1670
+ * to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
1671
+ * by table then index for stable output. Creates the table first so a read on a
1672
+ * never-exercised shard returns `[]`.
1673
+ */
1674
+ declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
1675
+ /**
1676
+ * Fold a dispatch's distinct full-scanned tables into an in-memory attribution
1677
+ * list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
1678
+ * applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
1679
+ * SQL twin, so the one rule (one occurrence = +1 scan for that table, list
1680
+ * re-sorted busiest-first) lives in a single module — the in-memory copy exists
1681
+ * only for the warm-instance fallback when the durable read is unavailable.
1682
+ * Mutates and returns `into`.
1683
+ */
1684
+ declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
1685
+ /**
1686
+ * Read the persisted per-function accumulators as {@link FunctionCallStat}s,
1687
+ * newest-called first. Creates the table first so reads on a never-called shard
1688
+ * return `[]` instead of throwing. The shape is a superset of the legacy
1689
+ * in-memory `getFunctionStats` rows — the additive `scans` total and
1690
+ * `scannedTables` causal attribution are folded in here so a single read backs
1691
+ * the Insights "missing index" / "full scan" signal.
1692
+ */
1693
+ declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
1694
+ /**
1695
+ * Read the coarse time-series buckets for `path` (every path when omitted),
1696
+ * oldest-bucket first so a chart can plot them left-to-right. Creates the table
1697
+ * first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
1698
+ */
1699
+ declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
999
1700
  /**
1000
1701
  * Aggregate the persisted accumulators into the lifetime totals the metrics
1001
1702
  * health snapshot reports: total calls (`requests`), total `errors`. Returns
@@ -1091,86 +1792,39 @@ interface ExplainIssueDegraded extends ExplainIssueGrounding {
1091
1792
  /** Why the AI path degraded, for the client to surface. */
1092
1793
  reason: ExplainIssueDegradedReason;
1093
1794
  }
1094
- /** The arm returned when the model ran and produced text. */
1095
- interface ExplainIssueSuccess extends ExplainIssueGrounding {
1096
- /** The AI path ran and produced text. */
1097
- degraded: false;
1098
- /** The AI-generated plain-language explanation. */
1099
- explanation: string;
1100
- /** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
1101
- model: string;
1102
- }
1103
- type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1104
- /**
1105
- * Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
1106
- * `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
1107
- * optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
1108
- *
1109
- * Every caller-supplied field that reaches the prompt is capped here — capping
1110
- * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1111
- * prompt budget.
1112
- */
1113
- declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1114
- /**
1115
- * Run the full explain flow for one Issue: validate the payload, ground it in the
1116
- * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1117
- * a plain-language rewrite. Never throws for an AI-side failure; every such path
1118
- * returns the `degraded: true` arm carrying the grounded hint, so the caller
1119
- * always has something to render. Only a malformed payload throws (a 400).
1120
- *
1121
- * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1122
- * check lives here rather than at each call site.
1123
- */
1124
- declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1125
- defaultModel?: string;
1126
- }) => Promise<ExplainIssueResult>;
1127
- /** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
1128
- declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
1129
- /**
1130
- * Triage status of an Issue. `open` is the implicit default (no state row); a
1131
- * developer moves it to `resolved` (fixed, but a *new* matching error re-opens
1132
- * it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
1133
- * and stays muted regardless of new occurrences).
1134
- */
1135
- type IssueStatus = "ignored" | "open" | "resolved";
1136
- /** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
1137
- type IssueSeverity = "critical" | "high" | "low" | "medium";
1138
- /** The persisted triage state for one Issue fingerprint. */
1139
- interface IssueState {
1140
- /** Free-form assignee (a userId or a name); absent when unassigned. */
1141
- assignee?: string;
1142
- /** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
1143
- hash: string;
1144
- /** Developer-tagged severity; absent when untriaged. */
1145
- severity?: IssueSeverity;
1146
- /** Current triage status. */
1147
- status: IssueStatus;
1148
- /** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
1149
- updatedAt: number;
1150
- /** Acting userId that last changed the state, when known. */
1151
- updatedBy?: string;
1152
- }
1153
- /** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
1154
- interface IssueStatePatch {
1155
- assignee?: null | string;
1156
- severity?: IssueSeverity | null;
1157
- status?: IssueStatus;
1158
- }
1159
- /** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
1160
- declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
1161
- /** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
1162
- declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
1795
+ /** The arm returned when the model ran and produced text. */
1796
+ interface ExplainIssueSuccess extends ExplainIssueGrounding {
1797
+ /** The AI path ran and produced text. */
1798
+ degraded: false;
1799
+ /** The AI-generated plain-language explanation. */
1800
+ explanation: string;
1801
+ /** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
1802
+ model: string;
1803
+ }
1804
+ type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
1163
1805
  /**
1164
- * Apply a triage patch to one Issue, upserting its state row. A `null` in the
1165
- * patch clears the field (unassign, untag severity); an omitted field is left
1166
- * unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
1806
+ * Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
1807
+ * `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
1808
+ * optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
1167
1809
  *
1168
- * Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
1169
- * field so a partial patch touches only what it names — except the explicit
1170
- * `null` sentinels for assignee/severity, which are threaded separately so a
1171
- * clear can win over `COALESCE`.
1810
+ * Every caller-supplied field that reaches the prompt is capped here — capping
1811
+ * `sampleMessage` alone left `title`/`culprit` as an open door onto the same
1812
+ * prompt budget.
1172
1813
  */
1173
- declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
1814
+ declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
1815
+ /**
1816
+ * Run the full explain flow for one Issue: validate the payload, ground it in the
1817
+ * catalog, and — when `binding` is a usable Workers AI binding — ask the model for
1818
+ * a plain-language rewrite. Never throws for an AI-side failure; every such path
1819
+ * returns the `degraded: true` arm carrying the grounded hint, so the caller
1820
+ * always has something to render. Only a malformed payload throws (a 400).
1821
+ *
1822
+ * `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
1823
+ * check lives here rather than at each call site.
1824
+ */
1825
+ declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
1826
+ defaultModel?: string;
1827
+ }) => Promise<ExplainIssueResult>;
1174
1828
  /**
1175
1829
  * Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
1176
1830
  * (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
@@ -1196,6 +1850,8 @@ interface LogEntry {
1196
1850
  level: LogLevel;
1197
1851
  message: string;
1198
1852
  timestamp: number;
1853
+ /** 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. */
1854
+ traceId?: string;
1199
1855
  }
1200
1856
  /**
1201
1857
  * A bounded, in-memory ring buffer of recent {@link LogEntry} records.
@@ -1209,553 +1865,285 @@ interface LogEntry {
1209
1865
  * to R2 / a SIEM / a log service), or a **Tail Worker** for programmatic
1210
1866
  * capture. Lunora deliberately does not reimplement any of those — this buffer
1211
1867
  * stays a tiny dev/ops readout. Capacity is fixed at construction; once full,
1212
- * the oldest entry is evicted to make room (FIFO), so memory stays bounded
1213
- * regardless of traffic.
1214
- */
1215
- declare class LogBuffer {
1216
- /** Backing store, kept in insertion order (oldest first). */
1217
- private readonly buffer;
1218
- private readonly capacity;
1219
- constructor(capacity?: number);
1220
- /** Number of entries currently buffered. */
1221
- get size(): number;
1222
- /** Drop every buffered entry. */
1223
- clear(): void;
1224
- /**
1225
- * Snapshot of the buffered entries, **newest first** so the panel renders
1226
- * the most recent activity at the top without re-sorting. Returns a fresh
1227
- * array each call; the caller may mutate it freely.
1228
- */
1229
- entries(): LogEntry[];
1230
- /**
1231
- * Append an entry, evicting the oldest when at capacity so the buffer never
1232
- * grows past its bound.
1233
- */
1234
- push(entry: LogEntry): void;
1235
- }
1236
- /**
1237
- * One aggregated metric series: every measurement sharing a `(name, kind,
1238
- * attributes)` identity folded into a single running summary.
1239
- *
1240
- * All fields are maintained for every {@link MetricKind} — the fold is uniform
1241
- * and O(1), and letting the panel choose the meaningful projection per kind
1242
- * (counter → `sum`, gauge → `last`, histogram → `sum`/`count` for the mean, plus
1243
- * `min`/`max`) is cheaper and clearer than branching on kind at record time.
1244
- */
1245
- interface MetricSeries {
1246
- /** The series' dimensions, if any — the attributes that made it distinct. */
1247
- attributes?: LogFields;
1248
- /** Number of measurements folded into this series. */
1249
- count: number;
1250
- /** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
1251
- exemplarTraceId?: string;
1252
- /** Wall-clock millis of the first measurement folded in. */
1253
- firstTs: number;
1254
- /** Function path that recorded the series' most recent measurement. */
1255
- functionPath: string;
1256
- /** Instrument kind; decides which projection the panel shows. */
1257
- kind: MetricKind;
1258
- /** Most recent measured value — the current reading for a `gauge`. */
1259
- last: number;
1260
- /** Wall-clock millis of the most recent measurement. */
1261
- lastTs: number;
1262
- /** Largest measured value seen. */
1263
- max: number;
1264
- /** Smallest measured value seen. */
1265
- min: number;
1266
- /** Instrument name, e.g. `"orders.placed"`. */
1267
- name: string;
1268
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
1269
- shardKey?: string;
1270
- /** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
1271
- sum: number;
1272
- }
1273
- /**
1274
- * A bounded map of running metric aggregates, keyed by series identity. Eviction
1275
- * is least-recently-*updated*: a re-recorded series moves back to the tail (Map
1276
- * insertion order), so the capacity bound sheds cold, high-cardinality series and
1277
- * keeps the ones still receiving traffic — the opposite of a raw ring, which
1278
- * would evict a hot counter's own history.
1279
- */
1280
- declare class MetricBuffer {
1281
- private readonly capacity;
1282
- private readonly series;
1283
- constructor(capacity?: number);
1284
- /** Number of distinct series currently aggregated. */
1285
- get size(): number;
1286
- /** Drop every aggregated series. */
1287
- clear(): void;
1288
- /**
1289
- * Snapshot of the aggregated series, most-recently-updated first, each a fresh
1290
- * copy so a caller can't mutate the live aggregate. `series` is kept in
1291
- * update order (tail = newest), so one reverse yields newest-first.
1292
- */
1293
- entries(): MetricSeries[];
1294
- /** Fold one measurement into its series, creating or updating the aggregate. */
1295
- push(event: MetricEvent): void;
1296
- }
1297
- /** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
1298
- interface MetricHistoryPoint {
1299
- /** Epoch-ms floor of the bucket window. */
1300
- bucketMs: number;
1301
- /** Measurements folded into this bucket. */
1302
- count: number;
1303
- /** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
1304
- exemplarTraceId?: string;
1305
- /** Last measured value in the bucket — a gauge's reading at the window's end. */
1306
- last: number;
1307
- /** Largest value in the bucket. */
1308
- max: number;
1309
- /** Smallest value in the bucket. */
1310
- min: number;
1311
- /** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
1312
- sum: number;
1313
- }
1314
- /** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
1315
- interface MetricHistorySeries {
1316
- attributes?: LogFields;
1317
- functionPath: string;
1318
- kind: MetricKind;
1319
- name: string;
1320
- /** Buckets in ascending `bucketMs` order, ready to chart as a line. */
1321
- points: MetricHistoryPoint[];
1322
- shardKey?: string;
1323
- }
1324
- /** {@link readMetricHistory} result: every tracked series with its buckets. */
1325
- interface MetricHistoryResult {
1326
- /**
1327
- * True when the distinct-series cap has been reached — a **write-side**
1328
- * signal ("this shard can no longer admit a brand-new series", see
1329
- * `admitNewSeries`), not a read-side truncation flag. It is computed over
1330
- * the whole table regardless of `options.sinceMs`/the row-count read
1331
- * limit, so it can be `true` even when every series `readMetricHistory`
1332
- * actually returned fits comfortably: the caller should read it as "a
1333
- * flood of new series would currently be refused", the same thing
1334
- * `readQueryInsights`'s `capped` already signals for query-metrics.
1335
- */
1336
- capped: boolean;
1337
- series: MetricHistorySeries[];
1338
- }
1339
- /**
1340
- * Tunable caps for {@link recordMetricHistory}, threaded from the sink's
1341
- * `metricHistory` option. Each falls back to its module-constant default, so an
1342
- * omitted field keeps the historical behaviour.
1343
- */
1344
- 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}). */
1346
- maxSeries?: number;
1347
- /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
1348
- retentionBuckets?: number;
1349
- }
1350
- /**
1351
- * Fold one measurement into its `(series, minute)` bucket. Runs per
1352
- * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
1353
- * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
1354
- * already written is a single upsert (no reads), a bucket only in the DB costs one
1355
- * PK point-lookup + upsert, and only a genuinely new bucket also pays the
1356
- * distinct-series cap scan + retention trim. Still a durable SQLite write per
1357
- * measurement, so a hot loop recording thousands of points a second should
1358
- * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
1359
- * first so callers needn't.
1360
- *
1361
- * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
1362
- * the bucket so the studio can link a chart point back to a trace. Latest wins:
1363
- * a later sample carrying a trace replaces an earlier bucket's exemplar.
1364
- *
1365
- * `options` tunes the distinct-series cap and retention window from the sink's
1366
- * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
1367
- * module constant.
1368
- */
1369
- declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1370
- /**
1371
- * Read the durable history, grouped into one {@link MetricHistorySeries} per
1372
- * series with its buckets in ascending time order.
1373
- *
1374
- * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
1375
- * `series_key`-ordered: all active series write the same recent minutes, so this
1376
- * windows every series to a recent slice fairly, instead of handing the
1377
- * alphabetically-first series its full 1440-bucket history and starving the rest
1378
- * once the cap is hit. Each series' points are re-sorted ascending below, since a
1379
- * trend line reads oldest→newest.
1380
- *
1381
- * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
1382
- * the studio's time-window selector. `options.maxSeries`, mirroring the write
1383
- * side's tunable, is only used to compute `capped` — it does not affect which
1384
- * rows are read.
1385
- */
1386
- declare const readMetricHistory: (sql: SqlExec, options?: {
1387
- maxSeries?: number;
1388
- sinceMs?: number;
1389
- }) => MetricHistoryResult;
1390
- /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
1391
- interface QueryStatEntry {
1392
- /** Total number of times this statement was executed. */
1393
- execCount: number;
1394
- /** Normalised SQL text (literals stripped, truncated). */
1395
- normalizedSql: string;
1396
- /** Total rows read across all executions (SELECT result sizes). */
1397
- rowsRead: number;
1398
- /** Total rows written across all executions. */
1399
- rowsWritten: number;
1400
- /** Total wall-clock milliseconds across all executions. */
1401
- totalDurationMs: number;
1402
- }
1403
- /** One statement's activity within a chosen time range. */
1404
- interface QueryInsightEntry {
1405
- /** Mean milliseconds per execution across the range. */
1406
- avgDurationMs: number;
1407
- execCount: number;
1408
- normalizedSql: string;
1409
- /** Interpolated 50th percentile latency, in milliseconds. */
1410
- p50DurationMs: number;
1411
- /** Interpolated 95th percentile latency, in milliseconds. */
1412
- p95DurationMs: number;
1413
- rowsRead: number;
1414
- rowsWritten: number;
1415
- totalDurationMs: number;
1416
- }
1417
- /** One point on the throughput/latency charts. */
1418
- interface QueryInsightBucket {
1419
- /** Mean milliseconds per execution in this window, across all statements. */
1420
- avgDurationMs: number;
1421
- /** Bucket start, epoch millis. */
1422
- bucketMs: number;
1423
- execCount: number;
1424
- }
1425
- /** What `getQueryInsights` returns. */
1426
- interface QueryInsightsResult {
1427
- /** Time series across the whole range, all statements combined. */
1428
- buckets: QueryInsightBucket[];
1868
+ * the oldest entry is evicted to make room (FIFO), so memory stays bounded
1869
+ * regardless of traffic.
1870
+ */
1871
+ declare class LogBuffer {
1872
+ /** Backing store, kept in insertion order (oldest first). */
1873
+ private readonly buffer;
1874
+ private readonly capacity;
1875
+ /** How many entries the ring has evicted since it was last cleared. */
1876
+ private droppedCount;
1877
+ constructor(capacity?: number);
1429
1878
  /**
1430
- * True when the tracked-statement cap has been reached, so the caller can say
1431
- * "showing N of a capped set" rather than implying totality. Silent
1432
- * truncation reads as complete coverage when it is not.
1879
+ * Entries evicted for capacity since the last {@link LogBuffer.clear}.
1880
+ *
1881
+ * Without it a full ring is indistinguishable from a quiet instance that
1882
+ * happened to log exactly `capacity` lines: the reader sees 500 entries
1883
+ * either way and cannot tell whether 500 lines happened or 50,000 did. The
1884
+ * count is what turns "the newest 500" into an honest statement.
1433
1885
  */
1434
- capped: boolean;
1435
- entries: QueryInsightEntry[];
1436
- /** How many distinct statements the lifetime table is tracking. */
1437
- trackedStatements: number;
1886
+ get dropped(): number;
1887
+ /** Number of entries currently buffered. */
1888
+ get size(): number;
1889
+ /** Drop every buffered entry, including the eviction count. */
1890
+ clear(): void;
1891
+ /**
1892
+ * Snapshot of the buffered entries, **newest first** so the panel renders
1893
+ * the most recent activity at the top without re-sorting. Returns a fresh
1894
+ * array each call; the caller may mutate it freely.
1895
+ */
1896
+ entries(): LogEntry[];
1897
+ /**
1898
+ * Append an entry, evicting the oldest when at capacity so the buffer never
1899
+ * grows past its bound.
1900
+ */
1901
+ push(entry: LogEntry): void;
1438
1902
  }
1439
1903
  /**
1440
- * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
1441
- *
1442
- * Reads the bucket table (not the lifetime one) so the numbers answer "what is
1443
- * hot right now"; the statement TEXT is joined back from the lifetime table,
1444
- * which is the only place it is stored.
1445
- */
1446
- declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1447
- /**
1448
- * Record one statement's activity. Creates the table on first call. Silently
1449
- * skips recording when the normalised statement is empty (shouldn't happen
1450
- * in practice) or when the table is already at the
1451
- * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
1452
- * tracked. See `admitStatement` for how the cap check avoids an unconditional
1453
- * `COUNT(*)` on every execution.
1904
+ * One aggregated metric series: every measurement sharing a `(name, kind,
1905
+ * attributes)` identity folded into a single running summary.
1454
1906
  *
1455
- * `execCount` (default 1) lets a caller fold several executions of the SAME
1456
- * statement into one call — `shard-do.ts` does this per dispatch so a
1457
- * query-in-a-loop handler pays one upsert here instead of one per raw
1458
- * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
1459
- * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
1460
- * accumulate sums across separate calls — folding before calling is
1461
- * indistinguishable, from this table's point of view, from `execCount`
1462
- * separate calls with the same totals.
1463
- */
1464
- declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1465
- /**
1466
- * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
1467
- * (the leaderboard's default). Creates the table first so a read on a
1468
- * never-called shard returns `[]`.
1907
+ * All fields are maintained for every {@link MetricKind} — the fold is uniform
1908
+ * and O(1), and letting the panel choose the meaningful projection per kind
1909
+ * (counter → `sum`, gauge → `last`, histogram → `sum`/`count` for the mean, plus
1910
+ * `min`/`max`) is cheaper and clearer than branching on kind at record time.
1469
1911
  */
1470
- declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1471
- /** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
1472
- declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
1473
- /** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
1474
- type RequestOutcome = "error" | "ok";
1475
- /** One recorded `/rpc` dispatch, in monotonic `seq` order. */
1476
- interface RequestLogEntry {
1477
- /** 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
- cacheHit?: boolean;
1479
- /** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
1480
- durationMs: number;
1481
- /** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
1482
- errorMessage?: string;
1483
- /** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
1484
- functionPath: string;
1485
- /** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
1486
- identity?: Record<string, unknown>;
1487
- /** `ok` for a returned result, `error` for a thrown handler. */
1488
- outcome: RequestOutcome;
1489
- /** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
1490
- redactedArgs?: unknown;
1491
- /** Monotonic per-shard cursor — strictly increasing, never reused. */
1492
- seq: number;
1493
- /** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
1494
- shardKey?: string;
1495
- /** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
1496
- subscriptionsReRun: number;
1497
- /** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
1498
- tablesRead: string[];
1499
- /** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
1500
- tablesWritten: string[];
1501
- /** Wall-clock millis when the dispatch completed. */
1502
- ts: number;
1503
- /** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
1504
- userId?: string;
1505
- }
1506
- /** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
1507
- interface AppendRequestLogEntry {
1508
- cacheHit?: boolean;
1509
- durationMs: number;
1510
- errorMessage?: string;
1912
+ interface MetricSeries {
1913
+ /** The series' dimensions, if any — the attributes that made it distinct. */
1914
+ attributes?: LogFields;
1915
+ /** Number of measurements folded into this series. */
1916
+ count: number;
1917
+ /** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
1918
+ exemplarTraceId?: string;
1919
+ /** Wall-clock millis of the first measurement folded in. */
1920
+ firstTs: number;
1921
+ /** Function path that recorded the series' most recent measurement. */
1511
1922
  functionPath: string;
1512
- identity?: Record<string, unknown>;
1513
- outcome: RequestOutcome;
1514
- redactedArgs?: unknown;
1515
- shardKey?: string;
1516
- subscriptionsReRun?: number;
1517
- tablesRead?: string[];
1518
- tablesWritten?: string[];
1519
- ts: number;
1520
- userId?: string;
1521
- }
1522
- /** Knobs the dispatch site threads into a request-log write. */
1523
- interface RequestLogWriteOptions {
1524
- /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
1525
- captureRaw?: boolean;
1526
- /** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
1527
- retention?: number;
1528
- }
1529
- /** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
1530
- interface ReadRequestLogOptions {
1531
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1532
- functionPathPrefix?: string;
1533
- /** Upper bound on returned rows, clamped to [1, 10000]. */
1534
- limit?: number;
1535
- /** Keep only `ok` / `error` outcomes. */
1536
- outcome?: RequestOutcome;
1537
- /** Exact shard-key match. */
1923
+ /** Instrument kind; decides which projection the panel shows. */
1924
+ kind: MetricKind;
1925
+ /** Most recent measured value — the current reading for a `gauge`. */
1926
+ last: number;
1927
+ /** Wall-clock millis of the most recent measurement. */
1928
+ lastTs: number;
1929
+ /** Largest measured value seen. */
1930
+ max: number;
1931
+ /** Smallest measured value seen. */
1932
+ min: number;
1933
+ /** Instrument name, e.g. `"orders.placed"`. */
1934
+ name: string;
1935
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
1538
1936
  shardKey?: string;
1539
- /** Only entries strictly after this cursor (forward paging). */
1540
- sinceSeq?: number;
1541
- /** Keep only entries whose read OR written table set contains this table. */
1542
- tableTouched?: string;
1543
- /** Exact acting-userId match. */
1544
- userId?: string;
1545
- }
1546
- /** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first. */
1547
- interface RequestLogResult {
1548
- entries: RequestLogEntry[];
1937
+ /** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
1938
+ sum: number;
1549
1939
  }
1550
1940
  /**
1551
- * One grouped error **Issue**: many `error`-outcome request-log rows that share a
1552
- * fingerprint folded into a single triage row. The `hash` is the same stable key
1553
- * a cloud Incident groups on, so a local Issue and a cloud Incident are the same
1554
- * object.
1941
+ * A bounded map of running metric aggregates, keyed by series identity. Eviction
1942
+ * is least-recently-*updated*: a re-recorded series moves back to the tail (Map
1943
+ * insertion order), so the capacity bound sheds cold, high-cardinality series and
1944
+ * keeps the ones still receiving traffic — the opposite of a raw ring, which
1945
+ * would evict a hot counter's own history.
1555
1946
  */
1556
- interface ErrorIssue {
1557
- /** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
1558
- assignee?: string;
1559
- /** Number of `error` rows folded into this Issue within the scanned window. */
1560
- count: number;
1561
- /** The `<file>:<function>` (or `container:<name>`) the errors came from. */
1562
- culprit: string;
1563
- /** Wall-clock millis of the oldest folded row. */
1564
- firstSeen: number;
1565
- /**
1566
- * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
1567
- * computed from the RAW (pre-redaction) message at write time and stored on
1568
- * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
1569
- * below can't change the grouping.
1570
- */
1571
- hash: string;
1572
- /** Wall-clock millis of the newest folded row. */
1573
- lastSeen: number;
1574
- /** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
1575
- sampleMessage: string;
1576
- /** Developer-tagged severity from the persisted triage state; absent when untriaged. */
1577
- severity?: IssueSeverity;
1578
- /**
1579
- * Wall-clock millis the persisted triage state was last changed; absent when
1580
- * the Issue has never been triaged. Compared against `lastSeen` to detect a
1581
- * regression (a new error after a resolve).
1582
- */
1583
- stateUpdatedAt?: number;
1947
+ declare class MetricBuffer {
1948
+ private readonly capacity;
1949
+ private readonly series;
1950
+ constructor(capacity?: number);
1951
+ /** Number of distinct series currently aggregated. */
1952
+ get size(): number;
1953
+ /** Drop every aggregated series. */
1954
+ clear(): void;
1584
1955
  /**
1585
- * Triage status folded in from the persisted state (`open` by default). A
1586
- * `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
1587
- * auto-reopened to `open` here (a regression), so a fresh occurrence never
1588
- * hides behind a stale resolution; `ignored` stays sticky by design.
1956
+ * Snapshot of the aggregated series, most-recently-updated first, each a fresh
1957
+ * copy so a caller can't mutate the live aggregate. `series` is kept in
1958
+ * update order (tail = newest), so one reverse yields newest-first.
1589
1959
  */
1590
- status: IssueStatus;
1591
- /** Human-readable title (first line of the sample message, capped). */
1592
- title: string;
1960
+ entries(): MetricSeries[];
1961
+ /** Fold one measurement into its series, creating or updating the aggregate. */
1962
+ push(event: MetricEvent): void;
1593
1963
  }
1594
- /** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
1595
- interface IssuesResult {
1596
- issues: ErrorIssue[];
1964
+ /** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
1965
+ interface MetricHistoryPoint {
1966
+ /** Epoch-ms floor of the bucket window. */
1967
+ bucketMs: number;
1968
+ /** Measurements folded into this bucket. */
1969
+ count: number;
1970
+ /** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
1971
+ exemplarTraceId?: string;
1972
+ /** Last measured value in the bucket — a gauge's reading at the window's end. */
1973
+ last: number;
1974
+ /** Largest value in the bucket. */
1975
+ max: number;
1976
+ /** Smallest value in the bucket. */
1977
+ min: number;
1978
+ /** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
1979
+ sum: number;
1597
1980
  }
1598
- /** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
1599
- interface ReadIssuesOptions {
1600
- /** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
1601
- functionPathPrefix?: string;
1602
- /** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
1603
- limit?: number;
1604
- /** Exact shard-key match. */
1981
+ /** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
1982
+ interface MetricHistorySeries {
1983
+ attributes?: LogFields;
1984
+ functionPath: string;
1985
+ kind: MetricKind;
1986
+ name: string;
1987
+ /** Buckets in ascending `bucketMs` order, ready to chart as a line. */
1988
+ points: MetricHistoryPoint[];
1605
1989
  shardKey?: string;
1606
- /** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
1607
- status?: IssueStatus;
1608
- /** Exact acting-userId match. */
1609
- userId?: string;
1990
+ }
1991
+ /** {@link readMetricHistory} result: every tracked series with its buckets. */
1992
+ interface MetricHistoryResult {
1993
+ /**
1994
+ * True when the distinct-series cap has been reached — a **write-side**
1995
+ * signal ("this shard can no longer admit a brand-new series", see
1996
+ * `admitNewSeries`), not a read-side truncation flag. It is computed over
1997
+ * the whole table regardless of `options.sinceMs`/the row-count read
1998
+ * limit, so it can be `true` even when every series `readMetricHistory`
1999
+ * actually returned fits comfortably: the caller should read it as "a
2000
+ * flood of new series would currently be refused", the same thing
2001
+ * `readQueryInsights`'s `capped` already signals for query-metrics.
2002
+ */
2003
+ capped: boolean;
2004
+ series: MetricHistorySeries[];
1610
2005
  }
1611
2006
  /**
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).
1637
- *
1638
- * `captureRaw` is the development escape hatch: in a dev environment the dispatch
1639
- * site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
1640
- * see real arg/identity/error values; production always redacts. The dev
1641
- * decision is made at the call site from the deployment env, never inferred
1642
- * here — so a real deploy that omits the env var stays redacted.
2007
+ * Tunable caps for {@link recordMetricHistory}, threaded from the sink's
2008
+ * `metricHistory` option. Each falls back to its module-constant default, so an
2009
+ * omitted field keeps the historical behaviour.
1643
2010
  */
1644
- declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
2011
+ interface MetricHistoryOptions {
2012
+ /**
2013
+ * Distinct series tracked before a brand-new one is REFUSED admission
2014
+ * (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
2015
+ * already-tracked series keeps accumulating past the cap, and a flood of
2016
+ * one-off series cannot displace the app's real ones — see
2017
+ * {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
2018
+ * read-side signal that admission is being refused.
2019
+ */
2020
+ maxSeries?: number;
2021
+ /** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
2022
+ retentionBuckets?: number;
2023
+ }
1645
2024
  /**
1646
- * Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
1647
- * key, giving each shard a monotonic cursor the Logs tab pages through; the
1648
- * `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
1649
- * `NULL`/empty when none was recorded. Idempotent, so read and write paths can
1650
- * call it defensively.
2025
+ * Fold one measurement into its `(series, minute)` bucket. Runs per
2026
+ * `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
2027
+ * dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
2028
+ * already written is a single upsert (no reads), a bucket only in the DB costs one
2029
+ * PK point-lookup + upsert, and only a genuinely new bucket also pays the
2030
+ * distinct-series cap scan + retention trim. Still a durable SQLite write per
2031
+ * measurement, so a hot loop recording thousands of points a second should
2032
+ * pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
2033
+ * first so callers needn't.
1651
2034
  *
1652
- * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
1653
- * 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
1656
- * `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
1657
- * `__lunora_reqlog__` predates this column gains it on the next call without a
1658
- * 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.
1660
- */
1661
- declare const ensureRequestLogTable: (sql: SqlExec) => void;
1662
- /**
1663
- * Append one dispatch to the request log, then trim the log back to the most
1664
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
1665
- * table first so callers needn't. Args/identity/error message are redacted here
1666
- * so a raw value never reaches the durable table — callers pass the unredacted
1667
- * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
1668
- * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
1669
- * dispatch site.
2035
+ * `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
2036
+ * the bucket so the studio can link a chart point back to a trace. Latest wins:
2037
+ * a later sample carrying a trace replaces an earlier bucket's exemplar.
1670
2038
  *
1671
- * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
1672
- * it's redacted below, and the resulting hash is persisted in
1673
- * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
1674
- * recomputing `fingerprintError` from the (redacted) `error_message` column, so
1675
- * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
1676
- * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
1677
- * existing Issue or change its identity.
2039
+ * `options` tunes the distinct-series cap and retention window from the sink's
2040
+ * `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
2041
+ * module constant.
1678
2042
  */
1679
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
2043
+ declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
1680
2044
  /**
1681
- * Emit one structured request event to `console` so Cloudflare's Workers Logs /
1682
- * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
1683
- * NOT reimplement a transport: it produces a richer, lunora-attributed event and
1684
- * lets CF's existing trace-log pipe ship it. The event mirrors the durable
1685
- * `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
1686
- * read/written, cache hit), with `args`, `identity`, AND `error` redacted
1687
- * exactly like the durable write so no raw PII/secret reaches the log pipeline.
2045
+ * Read the durable history, grouped into one {@link MetricHistorySeries} per
2046
+ * series with its buckets in ascending time order.
1688
2047
  *
1689
- * An `error` outcome goes to `console.error` (surfacing at error level in the
1690
- * trace so a SIEM can alert on it); everything else to `console.log`. The
1691
- * `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
1692
- * events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
1693
- * redaction, mirroring the durable write. Best-effort by contract — the caller
1694
- * wraps it so a serialization hiccup can never fail the served request.
1695
- */
1696
- declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
1697
- /**
1698
- * The `ctx.log` event contract (shape + severity union) lives in
1699
- * `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
1700
- * events and the `@lunora/runtime` sink that consumes them agree by construction.
1701
- * `LogEventInput` is the DO's historical name for the shared `LogEvent`.
2048
+ * Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
2049
+ * `series_key`-ordered: all active series write the same recent minutes, so this
2050
+ * windows every series to a recent slice fairly, instead of handing the
2051
+ * alphabetically-first series its full 1440-bucket history and starving the rest
2052
+ * once the cap is hit. Each series' points are re-sorted ascending below, since a
2053
+ * trend line reads oldest→newest.
2054
+ *
2055
+ * `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
2056
+ * the studio's time-window selector. `options.maxSeries`, mirroring the write
2057
+ * side's tunable, is only used to compute `capped` — it does not affect which
2058
+ * rows are read.
1702
2059
  */
1703
- type LogEventInput = LogEvent;
2060
+ declare const readMetricHistory: (sql: SqlExec, options?: {
2061
+ maxSeries?: number;
2062
+ sinceMs?: number;
2063
+ }) => MetricHistoryResult;
2064
+ /** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
2065
+ interface QueryStatEntry {
2066
+ /** Total number of times this statement was executed. */
2067
+ execCount: number;
2068
+ /** Normalised SQL text (literals stripped, truncated). */
2069
+ normalizedSql: string;
2070
+ /** Total rows SCANNED across all executions (the billed number, not the result-set size). */
2071
+ rowsRead: number;
2072
+ /** Total rows WRITTEN across all executions. */
2073
+ rowsWritten: number;
2074
+ /** Total wall-clock milliseconds across all executions. */
2075
+ totalDurationMs: number;
2076
+ }
2077
+ /** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
2078
+ declare const latencyBucketIndex: (durationMs: number) => number;
2079
+ /** One statement's activity within a chosen time range. */
2080
+ interface QueryInsightEntry {
2081
+ /** Mean milliseconds per execution across the range. */
2082
+ avgDurationMs: number;
2083
+ execCount: number;
2084
+ normalizedSql: string;
2085
+ /** Interpolated 50th percentile latency, in milliseconds. */
2086
+ p50DurationMs: number;
2087
+ /** Interpolated 95th percentile latency, in milliseconds. */
2088
+ p95DurationMs: number;
2089
+ rowsRead: number;
2090
+ rowsWritten: number;
2091
+ totalDurationMs: number;
2092
+ }
2093
+ /** One point on the throughput/latency charts. */
2094
+ interface QueryInsightBucket {
2095
+ /** Mean milliseconds per execution in this window, across all statements. */
2096
+ avgDurationMs: number;
2097
+ /** Bucket start, epoch millis. */
2098
+ bucketMs: number;
2099
+ execCount: number;
2100
+ }
2101
+ /** What `getQueryInsights` returns. */
2102
+ interface QueryInsightsResult {
2103
+ /** Time series across the whole range, all statements combined. */
2104
+ buckets: QueryInsightBucket[];
2105
+ /**
2106
+ * True when the tracked-statement cap has been reached, so the caller can say
2107
+ * "showing N of a capped set" rather than implying totality. Silent
2108
+ * truncation reads as complete coverage when it is not.
2109
+ */
2110
+ capped: boolean;
2111
+ entries: QueryInsightEntry[];
2112
+ /** How many distinct statements the lifetime table is tracking. */
2113
+ trackedStatements: number;
2114
+ }
1704
2115
  /**
1705
- * Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
1706
- * and optional structured `fields`. The structured form — a message string plus
1707
- * a plain-object fields bag — is matched only for exactly `(string, object)`;
1708
- * every other shape is console-style and rendered whole (so existing
1709
- * `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
1710
- * the per-call fields (per-call wins); the result is normalized to a fresh bag
1711
- * of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
2116
+ * Per-statement activity within `rangeMs` of `now`, plus a combined time series.
2117
+ *
2118
+ * Reads the bucket table (not the lifetime one) so the numbers answer "what is
2119
+ * hot right now"; the statement TEXT is joined back from the lifetime table,
2120
+ * which is the only place it is stored.
1712
2121
  */
1713
- declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
1714
- fields?: LogFields;
1715
- message: string;
1716
- };
2122
+ declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
1717
2123
  /**
1718
- * Emit one application-log event from a `ctx.log.*` call to `console`, tagged
1719
- * `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
1720
- * it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
1721
- * raw Workers-trace firehose.
1722
- *
1723
- * Only the rendered `message` is emitted here, NOT the structured `args` array:
1724
- * the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
1725
- * un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
1726
- * would be a surprising PII/secret surface. The raw `args` stay on the in-process
1727
- * `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
1728
- * `message` already carries the developer's rendered values, exactly like a raw
1729
- * `console.log` line.
1730
- *
1731
- * `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
1732
- * surface at the right level in the trace); every other level to `console.log`.
2124
+ * Record one statement's activity. Creates the table on first call. Silently
2125
+ * skips recording when the normalised statement is empty (shouldn't happen
2126
+ * in practice) or when the table is already at the
2127
+ * {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
2128
+ * tracked. See `admitStatement` for how the cap check avoids an unconditional
2129
+ * `COUNT(*)` on every execution.
1733
2130
  *
1734
- * Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
1735
- * — they are intentional metadata a log pipeline filters on, unlike raw `args`.
1736
- * Unlike `args`, `fields` IS redacted before it rides this console line — a
1737
- * developer can attach anything to a fields bag (`ctx.log.info("charged",
1738
- * { email, cardLast4 })`), and this is the one line that's told to a SIEM as
1739
- * trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
1740
- * `options.captureRaw` (dev only) skips it, mirroring every other redaction
1741
- * point in this module; the sole current caller (`ShardDO.recordUserLog`)
1742
- * doesn't yet thread a dev flag through, so `fields` redacts unconditionally
1743
- * there today — a conservative default, never a correctness gap. A field value
1744
- * that can't be serialised (a circular object) would make `JSON.stringify`
1745
- * throw and drop the whole line, so serialisation falls back to a fields-free
1746
- * line rather than losing the event.
2131
+ * `execCount` (default 1) lets a caller fold several executions of the SAME
2132
+ * statement into one call — `shard-do.ts` does this per dispatch so a
2133
+ * query-in-a-loop handler pays one upsert here instead of one per raw
2134
+ * execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
2135
+ * `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
2136
+ * accumulate sums across separate calls — folding before calling is
2137
+ * indistinguishable, from this table's point of view, from `execCount`
2138
+ * separate calls with the same totals.
1747
2139
  */
1748
- declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
2140
+ declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
1749
2141
  /**
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`.
2142
+ * Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
2143
+ * (the leaderboard's default). Creates the table first so a read on a
2144
+ * never-called shard returns `[]`.
1756
2145
  */
1757
- declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
1758
- declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
2146
+ declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
1759
2147
  /**
1760
2148
  * Ordering/visual weight of a security finding — mirrors the studio's insight
1761
2149
  * severities so the Security Advisor and the Performance Advisor (Insights) share
@@ -1770,7 +2158,7 @@ type SecurityFindingLevel = "error" | "info" | "warning";
1770
2158
  *
1771
2159
  * `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
2160
  *
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.
2161
+ * `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
2162
  *
1775
2163
  * `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
2164
  *
@@ -1842,6 +2230,15 @@ interface TraceSpan {
1842
2230
  message: string;
1843
2231
  type: string;
1844
2232
  };
2233
+ /**
2234
+ * Timestamped occurrences inside the span — `span.addEvent(...)` and
2235
+ * `span.recordException(...)`. Carried through so a handled retry or a
2236
+ * swallowed exception is visible on the span it happened in, which is the
2237
+ * only place it is interpretable. Absent when the body recorded none.
2238
+ */
2239
+ events?: SpanEventPoint[];
2240
+ /** OTel `SpanKind`; absent means `"internal"`. */
2241
+ kind?: OtlpSpanKind;
1845
2242
  name: string;
1846
2243
  /** Start of this span relative to the trace's start, in ms. */
1847
2244
  offsetMs: number;
@@ -1860,12 +2257,25 @@ interface TraceSummary {
1860
2257
  rootName: string;
1861
2258
  shardKey?: string;
1862
2259
  /**
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.
2260
+ * Spans in **pre-order**, ready to render as waterfall rows: every span is
2261
+ * immediately followed by its own subtree, siblings in start order. So
2262
+ * indenting each row by its `depth` yields the real nesting — the row above
2263
+ * a `depth`-`n+1` row is genuinely its parent.
2264
+ *
2265
+ * This is a tree walk, not a sort, because no ordering on `(offsetMs,
2266
+ * depth)` can produce it. Given a parent, its child `a`, `a`'s child `a1`
2267
+ * and `a`'s sibling `b` all at offset 0, that comparator yields
2268
+ * `parent, a, b, a1` — which renders `a1` indented beneath `b`, under a
2269
+ * parent it does not belong to.
2270
+ *
2271
+ * **Why they tie is not millisecond resolution.** On the Workers runtime
2272
+ * `Date.now()` is pinned to the time of the last I/O — a Spectre mitigation,
2273
+ * not a bug — so it does not advance at all across pure computation. Every
2274
+ * duration in this package is `Date.now() - startTs`, which means a span
2275
+ * wrapping CPU-only work reports `0`, and a parent whose child performed no
2276
+ * I/O shares its exact start and end. See `docs/concepts/observability`
2277
+ * ("Span durations on Workers"); the practical consequence is that a `0 ms`
2278
+ * span means "no I/O happened here", not "this was fast".
1869
2279
  */
1870
2280
  spans: TraceSpan[];
1871
2281
  startTs: number;
@@ -1880,10 +2290,19 @@ interface TraceSummary {
1880
2290
  declare class SpanBuffer {
1881
2291
  private readonly buffer;
1882
2292
  private readonly capacity;
2293
+ /** How many spans the ring has evicted since it was last cleared. */
2294
+ private droppedCount;
1883
2295
  constructor(capacity?: number);
2296
+ /**
2297
+ * Spans evicted for capacity since the last {@link SpanBuffer.clear}. The
2298
+ * ring silently drops its oldest span once full, which makes a busy instance
2299
+ * look identical to one that recorded exactly `capacity` spans; this count
2300
+ * is the difference between the two.
2301
+ */
2302
+ get dropped(): number;
1884
2303
  /** Number of spans currently buffered. */
1885
2304
  get size(): number;
1886
- /** Drop every buffered span. */
2305
+ /** Drop every buffered span, including the eviction count. */
1887
2306
  clear(): void;
1888
2307
  /** Snapshot of the buffered spans in insertion order. Fresh array per call. */
1889
2308
  entries(): SpanEvent[];
@@ -1959,10 +2378,71 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
1959
2378
  * worker's trace and any container's beneath it), else freshly minted so a
1960
2379
  * dispatch with no inbound context — a subscription re-run, a server-initiated
1961
2380
  * call — still produces a coherent, self-contained local trace.
2381
+ *
2382
+ * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2383
+ * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2384
+ * anchor so every span and log line of the dispatch stamps it; absent or
2385
+ * malformed, the anchor simply has none. Informational only — see
2386
+ * {@link parseRayId}.
1962
2387
  */
1963
- declare const resolveTraceAnchor: (traceparent: string | undefined) => {
1964
- rootSpanId: string;
2388
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
1965
2389
  sampled: boolean;
1966
- traceId: string;
1967
2390
  };
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 };
2391
+ export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2392
+ /**
2393
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2394
+ *
2395
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2396
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2397
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2398
+ * inside `@lunora/do` only because that is where the Durable Object it
2399
+ * instruments happens to live.
2400
+ *
2401
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2402
+ * reverse, which is what makes this reusable by a second host rather than
2403
+ * merely relocated.
2404
+ *
2405
+ * This barrel is deliberately curated rather than `export *`. A star export
2406
+ * would promote every module internal to permanent public API — the exact
2407
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2408
+ * core. What is exported here is what a consumer actually needs.
2409
+ */
2410
+ type AuthMetrics,
2411
+ /**
2412
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2413
+ *
2414
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2415
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2416
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2417
+ * inside `@lunora/do` only because that is where the Durable Object it
2418
+ * instruments happens to live.
2419
+ *
2420
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2421
+ * reverse, which is what makes this reusable by a second host rather than
2422
+ * merely relocated.
2423
+ *
2424
+ * This barrel is deliberately curated rather than `export *`. A star export
2425
+ * would promote every module internal to permanent public API — the exact
2426
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2427
+ * core. What is exported here is what a consumer actually needs.
2428
+ */
2429
+ 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, NO_SENSITIVE_SCOPE, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
2430
+ /**
2431
+ * `@lunora/observability` — host-neutral telemetry storage and read models.
2432
+ *
2433
+ * Logs, traces, metrics, issue grouping and the security-audit view: the data
2434
+ * behind the Studio's observability pages. None of it is Cloudflare-specific —
2435
+ * it reads and writes through the SQL handle the engine hands it, and it lived
2436
+ * inside `@lunora/do` only because that is where the Durable Object it
2437
+ * instruments happens to live.
2438
+ *
2439
+ * The dependency runs `@lunora/do` → here → `@lunora/shard-engine`, never the
2440
+ * reverse, which is what makes this reusable by a second host rather than
2441
+ * merely relocated.
2442
+ *
2443
+ * This barrel is deliberately curated rather than `export *`. A star export
2444
+ * would promote every module internal to permanent public API — the exact
2445
+ * mistake `@lunora/do`'s own barrel documents having made once with the search
2446
+ * core. What is exported here is what a consumer actually needs.
2447
+ */
2448
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };