@tangle-network/sdk-telemetry 0.7.7 → 0.7.9

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.
@@ -139,7 +139,7 @@ function partitionLifecycleWalls(sample, flow) {
139
139
  const present = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
140
140
  const finiteStages = (values) => Object.fromEntries(Object.entries(values ?? {}).filter(([, ms]) => Number.isFinite(ms)));
141
141
  const hops = sample.hops ?? {};
142
- const hop = (key) => Number.isFinite(hops[key]) ? hops[key] : null;
142
+ const hop = (key) => present(hops[key]);
143
143
  const handler = hop(flow.workerTotalHop);
144
144
  const preHandler = hop("preHandler");
145
145
  const hold = flow.settleHop ? hop(flow.settleHop) ?? 0 : 0;
@@ -160,11 +160,6 @@ function partitionLifecycleWalls(sample, flow) {
160
160
  const postReady = flow.postReadyOperations ?? /* @__PURE__ */ new Set();
161
161
  const rawLeaves = sample.spanLeaves ?? Object.fromEntries(operationLeafDurations(sample.spanOps ?? []));
162
162
  const spanLeaves = Object.fromEntries(Object.entries(rawLeaves).filter(([name, ms]) => name !== flow.totalOperation && !postReady.has(name) && Number.isFinite(ms)));
163
- /**
164
- * The Worker's own handler stages: its ledger minus the three nested walls,
165
- * the transport they imply and the middleware own-times, which are ranked
166
- * separately because they run OUTSIDE the handler's `total`.
167
- */
168
163
  const workerStages = Object.fromEntries(Object.entries(hops).filter(([name]) => Number.isFinite(hops[name]) && !SHAPE_HOPS.has(name) && name !== flow.settleHop && !name.startsWith("orch.") && !name.startsWith("mw.")));
169
164
  const orchTree = stageTree(finiteStages(sample.orchStages));
170
165
  const jobTree = stageTree(finiteStages(sample.jobPhases));
@@ -230,4 +225,4 @@ function partitionLifecycleWalls(sample, flow) {
230
225
  //#endregion
231
226
  export { leafOperations as a, partitionLifecycleWalls as c, STOP_ACCOUNTING_SPEC as i, spanTreeStages as l, DELETE_ACCOUNTING_SPEC as n, operationLeafDurations as o, RESUME_ACCOUNTING_SPEC as r, parentOperations as s, CREATE_ACCOUNTING_SPEC as t, stageTree as u };
232
227
 
233
- //# sourceMappingURL=lifecycle-wall-CZZAgPft.mjs.map
228
+ //# sourceMappingURL=lifecycle-wall-BeaxDTJ8.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle-wall-BeaxDTJ8.mjs","names":[],"sources":["../src/lifecycle-wall.ts"],"sourcesContent":["/**\n * The `ready` span carries the end-to-end create wall (caller start → the end\n * of createSidecar). These operations run AFTER `ready` is stamped, so they sit\n * OUTSIDE the ready window and must never be summed into the leaf total or the\n * residual goes negative.\n */\nconst CREATE_POST_READY_OPERATIONS = new Set([\n \"orchestrator.container_lookup\",\n \"orchestrator.snapshot_restore_check\",\n \"orchestrator.provision_finalize\",\n]);\n\n/**\n * Per-flow shape of the accounting window. `totalOperation` is the span whose\n * wall the named leaves must tile; `postReadyOperations` run AFTER it is\n * stamped (excluded from the leaf sum); `prepUmbrella` is the optional\n * create-style split of an entry umbrella minus its measured leaf children. Absent\n * `prepUmbrella` ⇒ `prepUnaccountedMs` is always 0 and the whole dark falls\n * into `unaccountedMs` (the shape every non-create flow uses).\n */\nexport type FlowAccountingSpec = {\n totalOperation: string;\n postReadyOperations?: ReadonlySet<string>;\n prepUmbrella?: { operation: string };\n};\n\nexport const CREATE_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.ready\",\n postReadyOperations: CREATE_POST_READY_OPERATIONS,\n prepUmbrella: {\n operation: \"orchestrator.provision_prep\",\n },\n};\n\nexport const RESUME_ACCOUNTING_SPEC: FlowAccountingSpec = {\n // `orchestrator.ready` runs from the request to the sidecar's ready stamp;\n // these run after that stamp.\n totalOperation: \"orchestrator.ready\",\n postReadyOperations: new Set([\n \"orchestrator.connection_build\",\n \"orchestrator.metering_restart\",\n \"orchestrator.resume_commit\",\n ]),\n};\n\nexport const STOP_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.stop_complete\",\n};\n\nexport const DELETE_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.delete_complete\",\n};\n\nexport interface LifecycleStageTiming {\n operation: string;\n durationMs?: number;\n parent?: string | null;\n}\ntype Values = Readonly<Record<string, number>>;\nexport interface LifecycleWallSample {\n wallMs: number;\n httpMs: number;\n hops?: Values;\n spanOps?: readonly LifecycleStageTiming[];\n spanLeaves?: Values;\n spanTotalMs?: number | null;\n orchStages?: Values | null;\n jobPhases?: Values | null;\n jobMs?: number | null;\n settleMs?: number | null;\n spanAccountedMs?: number;\n}\nexport interface LifecycleWallFlow extends Partial<FlowAccountingSpec> {\n workerTotalHop: string;\n addPreHandler: boolean;\n settleHop?: string;\n workerNamedHops?: readonly string[];\n}\n\n/**\n * A flat `{name: ms}` ledger read as the tree its names describe.\n *\n * Every producer in this repo emits nested stages FLAT, with the containment\n * in the name: `capture.<hostPhase>` and `capture.restic_<phase>` inside\n * `capture` (snapshot-helpers.ts), `materialize.parentRead|precreate|\n * branchComplete|host.*|child.*|residual` inside `materialize` (branch.ts),\n * `delete.<hostPhase>` inside `delete` and `restore_workspace.<phase>` inside\n * `restore_workspace` (snapshots.ts). Summing every entry as a sibling counts\n * the children inside their parent a second time and reports a wall the\n * orchestrator never spent.\n *\n * So a dotted name is NEVER top-level. It attaches to the longest prefix that\n * exists as a stage; when no prefix exists — the restore job's `host.<phase>`,\n * which the queue records inside `restore_workspace` without naming it\n * (snapshot-job-queue.ts:394) — it is still excluded from the top-level sum\n * and reported as a child of the ledger at large. Excluding it can only leave\n * MORE time unnamed, never fabricate a reconciliation.\n */\nexport function stageTree(stages: Readonly<Record<string, number>>) {\n const present = new Set(Object.keys(stages));\n const parentOf = (name: string) => {\n let cut = name.lastIndexOf(\".\");\n while (cut > 0) {\n const candidate = name.slice(0, cut);\n if (present.has(candidate)) return candidate;\n cut = candidate.lastIndexOf(\".\");\n }\n return name.includes(\".\") ? \"\" : null;\n };\n const nodes = Object.entries(stages).map(([name, ms]) => ({\n name,\n ms,\n parent: parentOf(name),\n }));\n const topLevel = nodes.filter((node) => node.parent === null);\n return {\n nodes,\n topLevel,\n /** Children whose declared parent is not in the ledger; never summed. */\n orphans: nodes.filter((node) => node.parent === \"\"),\n topLevelMs: topLevel.reduce((sum, node) => sum + node.ms, 0),\n };\n}\n\n/**\n * A response's span tree as `<stage>.<path>` rows and each parent's wall minus\n * its children as `<parent>.unattributed` (0 when children overlap), residuals\n * first so a capped header keeps them. Unparented spans nest in the total span.\n */\nexport function spanTreeStages(\n stage: string,\n stageMs: Readonly<Record<string, number>>,\n operations: readonly (LifecycleStageTiming & { status?: string })[] = [],\n spec?: Partial<FlowAccountingSpec>,\n): Record<string, number> {\n const total = spec?.totalOperation ?? \"\";\n const byName = new Map(operations.map((op) => [op.operation, op]));\n const path = (op: LifecycleStageTiming, depth = 0): string => {\n const outside =\n op.operation === total || spec?.postReadyOperations?.has(op.operation);\n const parent = byName.get(op.parent ?? (outside ? \"\" : total));\n const name = op.operation.slice(op.operation.lastIndexOf(\".\") + 1);\n return `${parent && depth < 8 ? path(parent, depth + 1) : stage}.${name}`;\n };\n const rows: Record<string, number> = { [stage]: stageMs[stage] ?? 0 };\n for (const { durationMs: ms, status, ...op } of operations)\n if (status === \"completed\" && typeof ms === \"number\" && ms >= 0)\n rows[path(op)] = (rows[path(op)] ?? 0) + ms;\n const residuals: Record<string, number> = {};\n for (const [parent, ms] of Object.entries(rows)) {\n const kids = Object.keys(rows).filter(\n (name) =>\n name.startsWith(`${parent}.`) &&\n !name.slice(parent.length + 1).includes(\".\"),\n );\n if (kids.length)\n residuals[`${parent}.unattributed`] = Math.max(\n 0,\n kids.reduce((rest, kid) => rest - (rows[kid] ?? 0), ms),\n );\n }\n delete rows[stage];\n return { ...residuals, ...rows };\n}\n\n/**\n * Hops that describe the SHAPE of the request rather than a slice of it: the\n * three nested walls, the transport the walls imply, and the retry counter.\n * They are the terms of the summary line, so ranking them again as sub-stages\n * would print the same milliseconds twice under a second name. `preHandler`\n * joins them because it is the umbrella over the `mw.*` own-times, which ARE\n * ranked.\n */\nconst SHAPE_HOPS = new Set([\n \"preHandler\",\n \"total\",\n \"serverWall\",\n \"orchestrator\",\n \"orchestratorServer\",\n \"transportMarkup\",\n \"orchestratorRetries\",\n]);\n\n/** Parent operations contain their descendants and are never counted as leaves. */\nexport function parentOperations(\n operations: readonly LifecycleStageTiming[],\n): ReadonlySet<string> {\n return new Set(\n operations.flatMap((op) =>\n typeof op.parent === \"string\" ? [op.parent] : [],\n ),\n );\n}\n\n/**\n * The measured leaves of one response's span tree, per the flow's own spec.\n *\n * Identical rule to the orchestrator's `computeFlowAccountingResiduals`: drop\n * the total span (it is the window), drop the spans stamped after it closes,\n * and drop any span another span names as its parent (a parent re-measures its\n * children). What is left sums to the window minus its named residual.\n */\nexport function leafOperations<T extends LifecycleStageTiming>(\n operations: readonly T[],\n excluded: ReadonlySet<string> = new Set(),\n parents = parentOperations(operations),\n) {\n return operations.filter(\n (op): op is T & { durationMs: number } =>\n !excluded.has(op.operation) &&\n !parents.has(op.operation) &&\n typeof op.durationMs === \"number\" &&\n Number.isFinite(op.durationMs),\n );\n}\n\nexport function operationLeafDurations(\n operations: readonly LifecycleStageTiming[],\n excluded: ReadonlySet<string> = new Set(),\n) {\n const leaves = new Map<string, number>();\n for (const op of leafOperations(operations, excluded))\n leaves.set(op.operation, (leaves.get(op.operation) ?? 0) + op.durationMs);\n return leaves;\n}\n\nconst difference = (a: number | null, b: number | null) =>\n a === null || b === null ? null : a - b;\nconst positiveDifference = (a: number | null, b: number | null) => {\n const value = difference(a, b);\n return value === null ? null : Math.max(0, value);\n};\n\n/**\n * Partition one input before aggregation: null is unavailable; a negative\n * residual is overlapping evidence, never an instruction to publish zero.\n * Callers retain their population grouping, medians and display labels.\n */\nexport function partitionLifecycleWalls(\n sample: LifecycleWallSample,\n flow: LifecycleWallFlow,\n) {\n const present = (value: number | null | undefined) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n const finiteStages = (values?: Values | null) =>\n Object.fromEntries(\n Object.entries(values ?? {}).filter(([, ms]) => Number.isFinite(ms)),\n );\n const hops = sample.hops ?? {};\n const hop = (key: string) => present(hops[key]);\n const handler = hop(flow.workerTotalHop);\n const preHandler = hop(\"preHandler\");\n const hold = flow.settleHop ? (hop(flow.settleHop) ?? 0) : 0;\n const workerWallMs =\n handler === null\n ? null\n : Math.max(0, handler - hold) +\n (flow.addPreHandler ? (preHandler ?? 0) : 0);\n const roundTripMs = hop(\"orchestrator\");\n const orchServerMs = hop(\"orchestratorServer\");\n const orchWall = roundTripMs ?? orchServerMs;\n const terms = {\n edge: positiveDifference(sample.httpMs, workerWallMs),\n worker: positiveDifference(workerWallMs, orchWall ?? 0),\n transport: positiveDifference(roundTripMs, orchServerMs),\n orch: orchServerMs ?? roundTripMs,\n job: present(sample.jobMs),\n settle: present(sample.settleMs),\n dark: 0,\n };\n terms.dark =\n sample.wallMs -\n Object.values(terms).reduce<number>((sum, ms) => sum + (ms ?? 0), 0);\n const postReady = flow.postReadyOperations ?? new Set();\n const rawLeaves =\n sample.spanLeaves ??\n Object.fromEntries(operationLeafDurations(sample.spanOps ?? []));\n const spanLeaves = Object.fromEntries(\n Object.entries(rawLeaves).filter(\n ([name, ms]) =>\n name !== flow.totalOperation &&\n !postReady.has(name) &&\n Number.isFinite(ms),\n ),\n );\n // Exclude nested walls, transport and middleware outside the handler's total.\n const workerStages = Object.fromEntries(\n Object.entries(hops).filter(\n ([name]) =>\n Number.isFinite(hops[name]) &&\n !SHAPE_HOPS.has(name) &&\n name !== flow.settleHop &&\n !name.startsWith(\"orch.\") &&\n !name.startsWith(\"mw.\"),\n ),\n );\n const orchTree = stageTree(finiteStages(sample.orchStages));\n const jobTree = stageTree(finiteStages(sample.jobPhases));\n const spanSum = Object.values(spanLeaves).reduce((sum, ms) => sum + ms, 0);\n const workerNamed =\n (flow.addPreHandler ? (preHandler ?? 0) : 0) +\n (flow.workerNamedHops\n ? flow.workerNamedHops.reduce((sum, key) => sum + (hop(key) ?? 0), 0)\n : stageTree(workerStages).topLevelMs);\n const workerUnattributedMs = difference(terms.worker, workerNamed);\n const orchNamed = orchTree.topLevel.length\n ? orchTree.topLevelMs\n : spanSum > 0\n ? spanSum\n : 0;\n const orchUnattributedMs = difference(terms.orch, orchNamed);\n const jobUnattributedMs = difference(terms.job, jobTree.topLevelMs);\n const unnamedMs =\n Math.max(0, workerUnattributedMs ?? terms.worker ?? 0) +\n Math.max(0, orchUnattributedMs ?? terms.orch ?? 0) +\n Math.max(0, jobUnattributedMs ?? terms.job ?? 0) +\n Math.max(0, terms.dark);\n const measuredTotal = (sample.spanOps ?? []).find(\n (op) => op.operation === flow.totalOperation,\n )?.durationMs;\n const spanTotalMs = present(sample.spanTotalMs ?? measuredTotal);\n const readySum = sample.spanAccountedMs ?? spanSum;\n const readyTerm = spanTotalMs ?? readySum;\n const orchTerm = roundTripMs ?? orchServerMs ?? readyTerm;\n let clampedMs = 0;\n const diff = (a: number | null, b: number | null) => {\n const delta = difference(a, b);\n if (delta === null) return null;\n clampedMs += Math.max(0, -delta);\n return Math.max(0, delta);\n };\n const transportMs = diff(roundTripMs, orchServerMs);\n const afterSpanMs = diff(orchServerMs, spanTotalMs);\n const pathSum = workerNamed + orchTerm;\n const outerMs =\n workerWallMs === null\n ? diff(\n sample.wallMs - readyTerm,\n workerNamed + (transportMs ?? 0) + (afterSpanMs ?? 0),\n )\n : diff(sample.wallMs, workerWallMs);\n const window = {\n transportMs,\n afterSpanMs,\n outerMs,\n workerUnattributedMs: positiveDifference(workerWallMs, pathSum),\n workerOwnMs: positiveDifference(workerWallMs, orchTerm),\n gaps: {\n overlapMs: positiveDifference(readySum, spanTotalMs) ?? 0,\n underTileMs: positiveDifference(spanTotalMs, readySum) ?? 0,\n workerOverlapMs: positiveDifference(pathSum, workerWallMs) ?? 0,\n unrowedMs:\n workerWallMs === null\n ? 0\n : Math.max(\n 0,\n orchTerm - readyTerm - (transportMs ?? 0) - (afterSpanMs ?? 0),\n ),\n clampedMs,\n },\n };\n return {\n wallMs: sample.wallMs,\n httpMs: sample.httpMs,\n workerWallMs,\n roundTripMs,\n orchServerMs,\n orchIncludesTransport: orchServerMs === null && roundTripMs !== null,\n workerIncludesTransport: roundTripMs === null && orchServerMs !== null,\n terms,\n workerUnattributedMs,\n orchUnattributedMs,\n jobUnattributedMs,\n unnamedMs,\n unnamedShare: sample.wallMs > 0 ? unnamedMs / sample.wallMs : 0,\n overcountMs: Math.max(0, -terms.dark),\n spanLeaves,\n workerStages,\n orchTree,\n jobTree,\n spanTotalMs,\n window,\n };\n}\n"],"mappings":"AA0BA,MAAa,yBAA6C;CACxD,gBAAgB;CAChB,qBAAqB,IAtBkB,IAAI;EAC3C;EACA;EACA;EACD,CAkBsB;CACrB,cAAc,EACZ,WAAW,+BACZ;CACF;AAED,MAAa,yBAA6C;CAGxD,gBAAgB;CAChB,qBAAqB,IAAI,IAAI;EAC3B;EACA;EACA;EACD,CAAC;CACH;AAED,MAAa,uBAA2C,EACtD,gBAAgB,8BACjB;AAED,MAAa,yBAA6C,EACxD,gBAAgB,gCACjB;;;;;;;;;;;;;;;;;;;;AA+CD,SAAgB,UAAU,QAA0C;CAClE,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,OAAO,CAAC;CAC5C,MAAM,YAAY,SAAiB;EACjC,IAAI,MAAM,KAAK,YAAY,IAAI;AAC/B,SAAO,MAAM,GAAG;GACd,MAAM,YAAY,KAAK,MAAM,GAAG,IAAI;AACpC,OAAI,QAAQ,IAAI,UAAU,CAAE,QAAO;AACnC,SAAM,UAAU,YAAY,IAAI;;AAElC,SAAO,KAAK,SAAS,IAAI,GAAG,KAAK;;CAEnC,MAAM,QAAQ,OAAO,QAAQ,OAAO,CAAC,KAAK,CAAC,MAAM,SAAS;EACxD;EACA;EACA,QAAQ,SAAS,KAAK;EACvB,EAAE;CACH,MAAM,WAAW,MAAM,QAAQ,SAAS,KAAK,WAAW,KAAK;AAC7D,QAAO;EACL;EACA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OAAO,SAAS,WAChB,eAAe,eAAe,MAAM,eAAe,GACpD,GACD,KAAK,OAAO,QAAQ,aAAa;EAKrC,sBAAsB,mBAAmB,cAAc,QAAQ;EAC/D,aAAa,mBAAmB,cAAc,SAAS;EACvD,MAAM;GACJ,WAAW,mBAAmB,UAAU,YAAY,IAAI;GACxD,aAAa,mBAAmB,aAAa,SAAS,IAAI;GAC1D,iBAAiB,mBAAmB,SAAS,aAAa,IAAI;GAC9D,WACE,iBAAiB,OACb,IACA,KAAK,IACH,GACA,WAAW,aAAa,eAAe,MAAM,eAAe,GAC7D;GACP;GACD;EACF;AACD,QAAO;EACL,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf;EACA;EACA;EACA,uBAAuB,iBAAiB,QAAQ,gBAAgB;EAChE,yBAAyB,gBAAgB,QAAQ,iBAAiB;EAClE;EACA;EACA;EACA;EACA;EACA,cAAc,OAAO,SAAS,IAAI,YAAY,OAAO,SAAS;EAC9D,aAAa,KAAK,IAAI,GAAG,CAAC,MAAM,KAAK;EACrC;EACA;EACA;EACA;EACA;EACA;EACD"}
@@ -13,11 +13,7 @@ interface CreateWallMeasurement {
13
13
  }
14
14
  /** The original other-Worker + post-create budget, including auth/middleware. */
15
15
  declare function createBookkeepingPostWall(phases: CreateWallPhases): number;
16
- /**
17
- * One cursor owned by the sequential request path. Parallel operations keep
18
- * their own spans and never transition this cursor from their callbacks.
19
- * Invalid clocks or missing caller hooks withhold a complete measurement.
20
- */
16
+ /** Sequential cursor; parallel spans stay separate. Invalid or incomplete walls stay unknown. */
21
17
  declare function createWallTiming(startedAt: number): {
22
18
  phase(name: CreateWallPhase, at: number): void;
23
19
  finish(receivedAt: number, respondedAt: number): CreateWallMeasurement | null;
@@ -1 +1 @@
1
- {"version":3,"file":"server-timing.d.mts","names":["ServerTimingEntry","name","dur","desc","parseServerTiming","header","parseServerTimingDurations","Record","PLATFORM_VERDICT_REUSE_REASONS","PlatformVerdictReuseRejection","HTTP_REQUEST_PHASE_NAMES","HttpRequestPhaseName","httpRequestPhaseFromTimingName","PLATFORM_VERDICT_SCOPE_CLASSES","PLATFORM_VERDICT_EVIDENCE_ORDERS","PlatformVerdictDependencyMismatch","scopeClass","evidenceOrder","createUpstreamHttpPhaseProjection","absorb","entries","HTTP_PHASE_COVERAGE_FIELDS","FAILURE_FACT_NAMES","FAILURE_FACT_CODES","FAILURE_FACT_KINDS"],"sources":["../src/create-wall.ts","../src/server-timing-parser.d.mts"],"mappings":";;;;cACa,kBAAA;AAAA,KAiBD,eAAA,WAA0B,kBAAA;AAAA,KAC1B,gBAAA,GAAmB,MAAA,CAAO,eAAA;AAAA,UACrB,qBAAA;EACf,MAAA,EAAQ,gBAAA;EACR,OAAA;EANQ;EAQR,uBAAA;AAAA;;iBAWc,yBAAA,CAA0B,MAAA,EAAQ,gBAAA;;AAhBlD;;;;iBA8BgB,gBAAA,CAAiB,SAAA;cAUjB,eAAA,EAAe,EAAA;6BAWP,WAAA,WAEjB,qBAAA;AAAA;;iBA6BS,oBAAA,CACd,MAAA,EAAQ,QAAA,CAAS,MAAA,oBAChB,qBAAA;;;UCvGcA,iBAAAA;EACfC,IAAAA;EACAC,GAAAA;EACAC,IAAAA;AAAAA;AAAAA,iBAGcC,iBAAAA,CACdC,MAAAA,8BACCL,iBAAAA;AAAAA,iBAEaM,0BAAAA,CACdD,MAAAA,8BACCE,MAAAA;AAAAA,cAEUC,8BAAAA;AAAAA,KA4BDC,6BAAAA,WACFD,8BAAAA;AAAAA,cAEGE,wBAAAA;AAAAA,KAkCDC,oBAAAA,WAA+BD,wBAAAA;AAAAA,cAI9BG,8BAAAA;AAAAA,cAQAC,gCAAAA;AAAAA,KAMDC,iCAAAA;EACVC,UAAAA,UAAoBH,8BAAAA;EACpBI,aAAAA,UAAuBH,gCAAAA;AAAAA;AAAAA,iBAGTI,iCAAAA,CAAAA;EACdC,MAAAA,CAAOd,MAAAA;EACPe,OAAAA;AAAAA;AAAAA,cAGWC,0BAAAA;AAAAA,cAQAC,kBAAAA;AAAAA,cACAC,kBAAAA;AAAAA,cACAC,kBAAAA"}
1
+ {"version":3,"file":"server-timing.d.mts","names":["ServerTimingEntry","name","dur","desc","parseServerTiming","header","parseServerTimingDurations","Record","PLATFORM_VERDICT_REUSE_REASONS","PlatformVerdictReuseRejection","HTTP_REQUEST_PHASE_NAMES","HttpRequestPhaseName","httpRequestPhaseFromTimingName","PLATFORM_VERDICT_SCOPE_CLASSES","PLATFORM_VERDICT_EVIDENCE_ORDERS","PlatformVerdictDependencyMismatch","scopeClass","evidenceOrder","createUpstreamHttpPhaseProjection","absorb","entries","HTTP_PHASE_COVERAGE_FIELDS","FAILURE_FACT_NAMES","FAILURE_FACT_CODES","FAILURE_FACT_KINDS"],"sources":["../src/create-wall.ts","../src/server-timing-parser.d.mts"],"mappings":";;;;cACa,kBAAA;AAAA,KAiBD,eAAA,WAA0B,kBAAA;AAAA,KAC1B,gBAAA,GAAmB,MAAA,CAAO,eAAA;AAAA,UACrB,qBAAA;EACf,MAAA,EAAQ,gBAAA;EACR,OAAA;EANQ;EAQR,uBAAA;AAAA;;iBAWc,yBAAA,CAA0B,MAAA,EAAQ,gBAAA;;iBAUlC,gBAAA,CAAiB,SAAA;cAUjB,eAAA,EAAe,EAAA;6BAWP,WAAA,WAEjB,qBAAA;AAAA;;iBA6BS,oBAAA,CACd,MAAA,EAAQ,QAAA,CAAS,MAAA,oBAChB,qBAAA;;;UCnGcA,iBAAAA;EACfC,IAAAA;EACAC,GAAAA;EACAC,IAAAA;AAAAA;AAAAA,iBAGcC,iBAAAA,CACdC,MAAAA,8BACCL,iBAAAA;AAAAA,iBAEaM,0BAAAA,CACdD,MAAAA,8BACCE,MAAAA;AAAAA,cAEUC,8BAAAA;AAAAA,KA4BDC,6BAAAA,WACFD,8BAAAA;AAAAA,cAEGE,wBAAAA;AAAAA,KAkCDC,oBAAAA,WAA+BD,wBAAAA;AAAAA,cAI9BG,8BAAAA;AAAAA,cAQAC,gCAAAA;AAAAA,KAMDC,iCAAAA;EACVC,UAAAA,UAAoBH,8BAAAA;EACpBI,aAAAA,UAAuBH,gCAAAA;AAAAA;AAAAA,iBAGTI,iCAAAA,CAAAA;EACdC,MAAAA,CAAOd,MAAAA;EACPe,OAAAA;AAAAA;AAAAA,cAGWC,0BAAAA;AAAAA,cAQAC,kBAAAA;AAAAA,cACAC,kBAAAA;AAAAA,cACAC,kBAAAA"}
@@ -1,4 +1,4 @@
1
- import { c as partitionLifecycleWalls } from "./lifecycle-wall-CZZAgPft.mjs";
1
+ import { c as partitionLifecycleWalls } from "./lifecycle-wall-BeaxDTJ8.mjs";
2
2
  //#region src/create-wall.ts
3
3
  /** Exclusive create-request wall phases; nested service spans are a separate view. */
4
4
  const CREATE_WALL_PHASES = [
@@ -22,11 +22,7 @@ const REQUIRED_PHASES = CREATE_WALL_PHASES.filter((phase) => phase !== "middlewa
22
22
  function createBookkeepingPostWall(phases) {
23
23
  return CREATE_WALL_PHASES.reduce((sum, phase) => sum + (phase === "preflight" || phase === "orchestrator" ? 0 : phases[phase]), 0);
24
24
  }
25
- /**
26
- * One cursor owned by the sequential request path. Parallel operations keep
27
- * their own spans and never transition this cursor from their callbacks.
28
- * Invalid clocks or missing caller hooks withhold a complete measurement.
29
- */
25
+ /** Sequential cursor; parallel spans stay separate. Invalid or incomplete walls stay unknown. */
30
26
  function createWallTiming(startedAt) {
31
27
  const phases = Object.fromEntries(CREATE_WALL_PHASES.map((phase) => [phase, 0]));
32
28
  const visited = new Set(["identity"]);
@@ -66,11 +62,11 @@ function createWallTiming(startedAt) {
66
62
  /** Read the already-parsed header. Historical/incomplete/overlapping rows stay unknown. */
67
63
  function readCreateWallTiming(stages) {
68
64
  const totalMs = stages["createWall.total"];
69
- if (!Number.isFinite(totalMs) || totalMs < 0 || totalMs !== stages.outerWall) return null;
65
+ if (totalMs === void 0 || !Number.isFinite(totalMs) || totalMs < 0 || totalMs !== stages.outerWall) return null;
70
66
  const phases = {};
71
67
  for (const phase of CREATE_WALL_PHASES) {
72
68
  const value = stages[`createWall.${phase}`];
73
- if (!Number.isFinite(value) || value < 0) return null;
69
+ if (value === void 0 || !Number.isFinite(value) || value < 0) return null;
74
70
  phases[phase] = value;
75
71
  }
76
72
  if (Object.values(phases).reduce((sum, ms) => sum + ms, 0) !== totalMs) return null;
@@ -1 +1 @@
1
- {"version":3,"file":"server-timing.mjs","names":[],"sources":["../src/create-wall.ts","../src/server-timing-parser.mjs"],"sourcesContent":["/** Exclusive create-request wall phases; nested service spans are a separate view. */\nexport const CREATE_WALL_PHASES = [\n \"middleware\",\n \"identity\",\n \"preflight\",\n \"tenantCoordination\",\n \"configuration\",\n \"leaseSelection\",\n \"credentialJournal\",\n \"quotaReservation\",\n \"orchestrator\",\n \"provisionResponse\",\n \"responseBody\",\n \"credentialAllocation\",\n \"postCreate\",\n \"response\",\n] as const;\n\nexport type CreateWallPhase = (typeof CREATE_WALL_PHASES)[number];\nexport type CreateWallPhases = Record<CreateWallPhase, number>;\nexport interface CreateWallMeasurement {\n phases: CreateWallPhases;\n totalMs: number;\n /** Includes middleware/auth, preserving the original bookkeeping + post budget. */\n bookkeepingPostCreateMs: number;\n}\n\nconst REQUIRED_PHASES = CREATE_WALL_PHASES.filter(\n (phase) =>\n phase !== \"middleware\" &&\n phase !== \"leaseSelection\" &&\n phase !== \"tenantCoordination\",\n);\n\n/** The original other-Worker + post-create budget, including auth/middleware. */\nexport function createBookkeepingPostWall(phases: CreateWallPhases): number {\n return CREATE_WALL_PHASES.reduce(\n (sum, phase) =>\n sum +\n (phase === \"preflight\" || phase === \"orchestrator\" ? 0 : phases[phase]),\n 0,\n );\n}\n\n/**\n * One cursor owned by the sequential request path. Parallel operations keep\n * their own spans and never transition this cursor from their callbacks.\n * Invalid clocks or missing caller hooks withhold a complete measurement.\n */\nexport function createWallTiming(startedAt: number) {\n const phases = Object.fromEntries(\n CREATE_WALL_PHASES.map((phase) => [phase, 0]),\n ) as CreateWallPhases;\n const visited = new Set<CreateWallPhase>([\"identity\"]);\n let current: CreateWallPhase = \"identity\";\n let cursor = startedAt;\n let valid = Number.isFinite(startedAt);\n let finished = false;\n return {\n phase(name: CreateWallPhase, at: number): void {\n if (finished || !Number.isFinite(at) || at < cursor) {\n valid = false;\n return;\n }\n phases[current] += at - cursor;\n cursor = at;\n current = name;\n visited.add(name);\n },\n finish(\n receivedAt: number,\n respondedAt: number,\n ): CreateWallMeasurement | null {\n if (\n finished ||\n !valid ||\n !Number.isFinite(receivedAt) ||\n !Number.isFinite(respondedAt) ||\n receivedAt > startedAt ||\n respondedAt < cursor ||\n REQUIRED_PHASES.some((phase) => !visited.has(phase))\n ) {\n finished = true;\n return null;\n }\n finished = true;\n phases[current] += respondedAt - cursor;\n phases.middleware = startedAt - receivedAt;\n const totalMs = respondedAt - receivedAt;\n if (Object.values(phases).reduce((sum, ms) => sum + ms, 0) !== totalMs)\n return null;\n return {\n phases: { ...phases },\n totalMs,\n bookkeepingPostCreateMs: createBookkeepingPostWall(phases),\n };\n },\n };\n}\n\n/** Read the already-parsed header. Historical/incomplete/overlapping rows stay unknown. */\nexport function readCreateWallTiming(\n stages: Readonly<Record<string, number>>,\n): CreateWallMeasurement | null {\n const totalMs = stages[\"createWall.total\"];\n if (!Number.isFinite(totalMs) || totalMs < 0 || totalMs !== stages.outerWall)\n return null;\n const phases = {} as CreateWallPhases;\n for (const phase of CREATE_WALL_PHASES) {\n const value = stages[`createWall.${phase}`];\n if (!Number.isFinite(value) || value < 0) return null;\n phases[phase] = value;\n }\n if (Object.values(phases).reduce((sum, ms) => sum + ms, 0) !== totalMs)\n return null;\n return {\n phases,\n totalMs,\n bookkeepingPostCreateMs: createBookkeepingPostWall(phases),\n };\n}\n","// HTTP quoted strings can contain both separators and escaped quotes.\nfunction splitHeader(value, separator) {\n const parts = [];\n let start = 0;\n let quoted = false;\n for (let i = 0; i < value.length; i++) {\n if (quoted && value[i] === \"\\\\\") i++;\n else if (value[i] === '\"') quoted = !quoted;\n else if (!quoted && value[i] === separator) {\n parts.push(value.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(value.slice(start));\n return parts;\n}\n\n/** Missing or malformed durations remain unmeasured, never zero. */\nexport function parseServerTiming(header) {\n if (!header) return [];\n const entries = [];\n for (const metric of splitHeader(header, \",\")) {\n const [rawName, ...params] = splitHeader(metric, \";\");\n const name = rawName.trim();\n if (!/^[!#$%&'*+.^_`|~\\w-]+$/.test(name)) continue;\n const entry = { name };\n const seen = new Set();\n for (const param of params) {\n const eq = param.indexOf(\"=\");\n const key = (eq < 0 ? param : param.slice(0, eq)).trim().toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n if (eq < 0) continue;\n let value = param.slice(eq + 1).trim();\n if (value.startsWith('\"')) {\n if (!/^\"(?:[^\"\\\\]|\\\\[\\s\\S])*\"$/.test(value)) continue;\n value = value.slice(1, -1).replace(/\\\\([\\s\\S])/g, \"$1\");\n }\n if (key === \"desc\") entry.desc = value;\n else if (\n key === \"dur\" &&\n /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(value)\n ) {\n const duration = Number(value);\n if (Number.isFinite(duration)) entry.dur = duration;\n }\n }\n entries.push(entry);\n }\n return entries;\n}\n\n/** A stage ledger retains only duration-bearing entries; later metrics win. */\nexport function parseServerTimingDurations(header) {\n return Object.fromEntries(\n parseServerTiming(header)\n .filter((entry) => entry.dur !== undefined)\n .map(({ name, dur }) => [name, dur]),\n );\n}\n\n/** Closed wire observations; these names carry no credential or authority values. */\nexport const PLATFORM_VERDICT_REUSE_REASONS = Object.freeze([\n \"entry_changed\",\n \"refusal_observed\",\n \"current_compliance\",\n \"negative_age\",\n \"retention_elapsed\",\n \"key_expired\",\n \"feed_missing\",\n \"feed_stale\",\n \"feed_generation\",\n \"dependencies_empty\",\n \"dependency_revision\",\n \"dependency_floor\",\n \"grant_missing\",\n \"grant_unreadable\",\n \"grant_shape\",\n \"grant_negative_age\",\n \"grant_retention_elapsed\",\n \"shared_refusal_observed\",\n \"shared_refusal_unreadable\",\n \"shared_read_unavailable\",\n \"grant_invalid\",\n \"grant_validation\",\n \"verification_inflight\",\n \"feed_contradiction\",\n \"current_required\",\n \"lkg_retention_elapsed\",\n]);\n\n/** Closed request-phase wire vocabulary, shared by producer and safe consumers. */\nexport const HTTP_REQUEST_PHASE_NAMES = Object.freeze([\n \"external.provision\",\n \"benchmarks.records.load\",\n \"benchmarks.records.build\",\n \"benchmarks.records.page\",\n \"benchmarks.records.json\",\n \"host.records.ready\",\n \"host.records.scan\",\n \"host.records.read\",\n \"host.records.metadata\",\n \"host.records.project\",\n \"host.records.retry\",\n \"admission.placement\",\n \"observability.refresh.wait\",\n \"fleet.sidecars\",\n \"native-export.snapshot.wait\",\n \"native-export.collect.wait\",\n \"scorecard.fleet.wait\",\n \"scorecard.capacity.wait\",\n \"scorecard.coverage.wait\",\n \"scorecard.compose\",\n \"scorecard.json\",\n \"proxy.model_refresh\",\n \"proxy.hub.lock_wait\",\n \"proxy.hub.refresh\",\n \"proxy.hub.state\",\n \"proxy.hub.proof\",\n \"proxy.hub.delivery\",\n \"proxy.runtime_token\",\n \"snapshot.delete.lock\",\n \"snapshot.delete.credentials\",\n \"snapshot.delete.list\",\n \"snapshot.delete.generation\",\n]);\n\nexport function httpRequestPhaseFromTimingName(name) {\n const prefix = name.startsWith(\"orch.phase.\") ? \"orch.phase.\" : \"phase.\";\n if (!name.startsWith(prefix)) return undefined;\n const phase = name.slice(prefix.length);\n return HTTP_REQUEST_PHASE_NAMES.includes(phase) ? phase : undefined;\n}\n\nexport const PLATFORM_VERDICT_SCOPE_CLASSES = Object.freeze([\n \"key\",\n \"identity\",\n \"owner_user\",\n \"owner_team\",\n \"lineage\",\n \"other\",\n]);\nexport const PLATFORM_VERDICT_EVIDENCE_ORDERS = Object.freeze([\n \"feed_before_observation\",\n \"feed_at_observation\",\n \"feed_after_observation\",\n \"unknown\",\n]);\n\n/** Closed failure facts: thrown values can carry credentials or URLs, so only these names leave. */\nexport const FAILURE_FACT_NAMES = Object.freeze([\n \"Error\",\n \"TypeError\",\n \"AbortError\",\n \"TimeoutError\",\n \"RangeError\",\n \"Other\",\n]);\nexport const FAILURE_FACT_CODES = Object.freeze([\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ECONNABORTED\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"ENETUNREACH\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"EADDRNOTAVAIL\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_BODY_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n \"UND_ERR_ABORTED\",\n]);\nexport const FAILURE_FACT_KINDS = Object.freeze([\n \"request-context\",\n \"connection-lost\",\n \"fetch-failed\",\n]);\n\n/** Bounded, closed-schema origin phase projection for the two Worker ledgers.\n * Duplicate observations remain separate; different origins/attempts cannot be summed.\n */\nexport const HTTP_PHASE_COVERAGE_FIELDS = Object.freeze([\n \"stored\",\n \"emitted\",\n \"omitted\",\n \"invalid\",\n \"collisions\",\n \"headerDropped\",\n]);\n\nexport function createUpstreamHttpPhaseProjection() {\n const entries = [];\n let bytes = 0;\n let dropped = 0;\n let rejectedInputs = 0;\n const fields = HTTP_PHASE_COVERAGE_FIELDS;\n const byteLength = (value) => new TextEncoder().encode(value).length;\n const keep = (entry) => {\n // Reserve a bounded forwarding-coverage entry inside this component's 4 KiB.\n const size = byteLength(entry) + 2;\n if (entries.length >= 31 || bytes + size > 3900) {\n dropped++;\n return;\n }\n entries.push(entry);\n bytes += size;\n };\n return {\n absorb(header) {\n if (header == null) return;\n if (\n typeof header !== \"string\" ||\n header.length > 4096 ||\n byteLength(header) > 4096\n ) {\n rejectedInputs++;\n return;\n }\n for (const entry of parseServerTiming(header)) {\n // Only direct origin names enter this fold; never prefix orch. twice.\n if (entry.name === \"phase.coverage\") {\n const counts = {};\n const parts = (entry.desc ?? \"\").split(\",\");\n if (parts.length !== fields.length) {\n dropped++;\n continue;\n }\n for (const part of parts) {\n const [key, value, ...extra] = part.split(\"=\");\n if (\n extra.length ||\n !fields.includes(key) ||\n Object.hasOwn(counts, key) ||\n !/^(?:0|[1-9]\\d*)$/.test(value ?? \"\") ||\n !Number.isSafeInteger(Number(value))\n )\n break;\n counts[key] = Number(value);\n }\n if (Object.keys(counts).length !== fields.length) {\n dropped++;\n continue;\n }\n keep(\n `orch.phase.coverage;desc=\"${fields.map((key) => `${key}=${counts[key]}`).join(\",\")}\"`,\n );\n } else if (entry.name.startsWith(\"phase.\")) {\n if (\n !httpRequestPhaseFromTimingName(entry.name) ||\n !Number.isFinite(entry.dur) ||\n entry.dur < 0 ||\n !/^outcome=(?:completed|error)$/.test(entry.desc ?? \"\")\n ) {\n dropped++;\n continue;\n }\n keep(\n `orch.${entry.name};dur=${Math.round(entry.dur)};desc=\"${entry.desc}\"`,\n );\n }\n }\n },\n entries() {\n return [\n ...entries,\n ...(dropped || rejectedInputs\n ? [\n `orch.phase.forwarding;desc=\"dropped=${dropped},rejectedInputs=${rejectedInputs}\"`,\n ]\n : []),\n ];\n },\n };\n}\n"],"mappings":";;;AACA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAWD,MAAM,kBAAkB,mBAAmB,QACxC,UACC,UAAU,gBACV,UAAU,oBACV,UAAU,qBACb;;AAGD,SAAgB,0BAA0B,QAAkC;AAC1E,QAAO,mBAAmB,QACvB,KAAK,UACJ,OACC,UAAU,eAAe,UAAU,iBAAiB,IAAI,OAAO,SAClE,EACD;;;;;;;AAQH,SAAgB,iBAAiB,WAAmB;CAClD,MAAM,SAAS,OAAO,YACpB,mBAAmB,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC,CAC9C;CACD,MAAM,UAAU,IAAI,IAAqB,CAAC,WAAW,CAAC;CACtD,IAAI,UAA2B;CAC/B,IAAI,SAAS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ACQ,MAAM,KAAK,WAAW,SAAS,EAAE;AAC1C,QACE,CAAC,+BAA+B,MAAM,KAAK,IAC3C,CAAC,OAAO,SAAS,MAAM,IAAI,IAC3B,MAAM,MAAM,KACZ,CAAC,gCAAgC,KAAK,MAAM,QAAQ,GAAG,EACvD;AACA;AACA;;AAEF,SACE,QAAQ,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,IAAI,CAAC,SAAS,MAAM,KAAK,GACrE;;;EAIP,UAAU;AACR,UAAO,CACL,GAAG,SACH,GAAI,WAAW,iBACX,CACE,uCAAuC,QAAQ,kBAAkB,eAAe,GACjF,GACD,EAAE,CACP;;EAEJ"}
1
+ {"version":3,"file":"server-timing.mjs","names":[],"sources":["../src/create-wall.ts","../src/server-timing-parser.mjs"],"sourcesContent":["/** Exclusive create-request wall phases; nested service spans are a separate view. */\nexport const CREATE_WALL_PHASES = [\n \"middleware\",\n \"identity\",\n \"preflight\",\n \"tenantCoordination\",\n \"configuration\",\n \"leaseSelection\",\n \"credentialJournal\",\n \"quotaReservation\",\n \"orchestrator\",\n \"provisionResponse\",\n \"responseBody\",\n \"credentialAllocation\",\n \"postCreate\",\n \"response\",\n] as const;\n\nexport type CreateWallPhase = (typeof CREATE_WALL_PHASES)[number];\nexport type CreateWallPhases = Record<CreateWallPhase, number>;\nexport interface CreateWallMeasurement {\n phases: CreateWallPhases;\n totalMs: number;\n /** Includes middleware/auth, preserving the original bookkeeping + post budget. */\n bookkeepingPostCreateMs: number;\n}\n\nconst REQUIRED_PHASES = CREATE_WALL_PHASES.filter(\n (phase) =>\n phase !== \"middleware\" &&\n phase !== \"leaseSelection\" &&\n phase !== \"tenantCoordination\",\n);\n\n/** The original other-Worker + post-create budget, including auth/middleware. */\nexport function createBookkeepingPostWall(phases: CreateWallPhases): number {\n return CREATE_WALL_PHASES.reduce(\n (sum, phase) =>\n sum +\n (phase === \"preflight\" || phase === \"orchestrator\" ? 0 : phases[phase]),\n 0,\n );\n}\n\n/** Sequential cursor; parallel spans stay separate. Invalid or incomplete walls stay unknown. */\nexport function createWallTiming(startedAt: number) {\n const phases = Object.fromEntries(\n CREATE_WALL_PHASES.map((phase) => [phase, 0]),\n ) as CreateWallPhases;\n const visited = new Set<CreateWallPhase>([\"identity\"]);\n let current: CreateWallPhase = \"identity\";\n let cursor = startedAt;\n let valid = Number.isFinite(startedAt);\n let finished = false;\n return {\n phase(name: CreateWallPhase, at: number): void {\n if (finished || !Number.isFinite(at) || at < cursor) {\n valid = false;\n return;\n }\n phases[current] += at - cursor;\n cursor = at;\n current = name;\n visited.add(name);\n },\n finish(\n receivedAt: number,\n respondedAt: number,\n ): CreateWallMeasurement | null {\n if (\n finished ||\n !valid ||\n !Number.isFinite(receivedAt) ||\n !Number.isFinite(respondedAt) ||\n receivedAt > startedAt ||\n respondedAt < cursor ||\n REQUIRED_PHASES.some((phase) => !visited.has(phase))\n ) {\n finished = true;\n return null;\n }\n finished = true;\n phases[current] += respondedAt - cursor;\n phases.middleware = startedAt - receivedAt;\n const totalMs = respondedAt - receivedAt;\n if (Object.values(phases).reduce((sum, ms) => sum + ms, 0) !== totalMs)\n return null;\n return {\n phases: { ...phases },\n totalMs,\n bookkeepingPostCreateMs: createBookkeepingPostWall(phases),\n };\n },\n };\n}\n\n/** Read the already-parsed header. Historical/incomplete/overlapping rows stay unknown. */\nexport function readCreateWallTiming(\n stages: Readonly<Record<string, number>>,\n): CreateWallMeasurement | null {\n const totalMs = stages[\"createWall.total\"];\n if (\n totalMs === undefined ||\n !Number.isFinite(totalMs) ||\n totalMs < 0 ||\n totalMs !== stages.outerWall\n )\n return null;\n const phases = {} as CreateWallPhases;\n for (const phase of CREATE_WALL_PHASES) {\n const value = stages[`createWall.${phase}`];\n if (value === undefined || !Number.isFinite(value) || value < 0)\n return null;\n phases[phase] = value;\n }\n if (Object.values(phases).reduce((sum, ms) => sum + ms, 0) !== totalMs)\n return null;\n return {\n phases,\n totalMs,\n bookkeepingPostCreateMs: createBookkeepingPostWall(phases),\n };\n}\n","// HTTP quoted strings can contain both separators and escaped quotes.\nfunction splitHeader(value, separator) {\n const parts = [];\n let start = 0;\n let quoted = false;\n for (let i = 0; i < value.length; i++) {\n if (quoted && value[i] === \"\\\\\") i++;\n else if (value[i] === '\"') quoted = !quoted;\n else if (!quoted && value[i] === separator) {\n parts.push(value.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(value.slice(start));\n return parts;\n}\n\n/** Missing or malformed durations remain unmeasured, never zero. */\nexport function parseServerTiming(header) {\n if (!header) return [];\n const entries = [];\n for (const metric of splitHeader(header, \",\")) {\n const [rawName, ...params] = splitHeader(metric, \";\");\n const name = rawName.trim();\n if (!/^[!#$%&'*+.^_`|~\\w-]+$/.test(name)) continue;\n const entry = { name };\n const seen = new Set();\n for (const param of params) {\n const eq = param.indexOf(\"=\");\n const key = (eq < 0 ? param : param.slice(0, eq)).trim().toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n if (eq < 0) continue;\n let value = param.slice(eq + 1).trim();\n if (value.startsWith('\"')) {\n if (!/^\"(?:[^\"\\\\]|\\\\[\\s\\S])*\"$/.test(value)) continue;\n value = value.slice(1, -1).replace(/\\\\([\\s\\S])/g, \"$1\");\n }\n if (key === \"desc\") entry.desc = value;\n else if (\n key === \"dur\" &&\n /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(value)\n ) {\n const duration = Number(value);\n if (Number.isFinite(duration)) entry.dur = duration;\n }\n }\n entries.push(entry);\n }\n return entries;\n}\n\n/** A stage ledger retains only duration-bearing entries; later metrics win. */\nexport function parseServerTimingDurations(header) {\n return Object.fromEntries(\n parseServerTiming(header)\n .filter((entry) => entry.dur !== undefined)\n .map(({ name, dur }) => [name, dur]),\n );\n}\n\n/** Closed wire observations; these names carry no credential or authority values. */\nexport const PLATFORM_VERDICT_REUSE_REASONS = Object.freeze([\n \"entry_changed\",\n \"refusal_observed\",\n \"current_compliance\",\n \"negative_age\",\n \"retention_elapsed\",\n \"key_expired\",\n \"feed_missing\",\n \"feed_stale\",\n \"feed_generation\",\n \"dependencies_empty\",\n \"dependency_revision\",\n \"dependency_floor\",\n \"grant_missing\",\n \"grant_unreadable\",\n \"grant_shape\",\n \"grant_negative_age\",\n \"grant_retention_elapsed\",\n \"shared_refusal_observed\",\n \"shared_refusal_unreadable\",\n \"shared_read_unavailable\",\n \"grant_invalid\",\n \"grant_validation\",\n \"verification_inflight\",\n \"feed_contradiction\",\n \"current_required\",\n \"lkg_retention_elapsed\",\n]);\n\n/** Closed request-phase wire vocabulary, shared by producer and safe consumers. */\nexport const HTTP_REQUEST_PHASE_NAMES = Object.freeze([\n \"external.provision\",\n \"benchmarks.records.load\",\n \"benchmarks.records.build\",\n \"benchmarks.records.page\",\n \"benchmarks.records.json\",\n \"host.records.ready\",\n \"host.records.scan\",\n \"host.records.read\",\n \"host.records.metadata\",\n \"host.records.project\",\n \"host.records.retry\",\n \"admission.placement\",\n \"observability.refresh.wait\",\n \"fleet.sidecars\",\n \"native-export.snapshot.wait\",\n \"native-export.collect.wait\",\n \"scorecard.fleet.wait\",\n \"scorecard.capacity.wait\",\n \"scorecard.coverage.wait\",\n \"scorecard.compose\",\n \"scorecard.json\",\n \"proxy.model_refresh\",\n \"proxy.hub.lock_wait\",\n \"proxy.hub.refresh\",\n \"proxy.hub.state\",\n \"proxy.hub.proof\",\n \"proxy.hub.delivery\",\n \"proxy.runtime_token\",\n \"snapshot.delete.lock\",\n \"snapshot.delete.credentials\",\n \"snapshot.delete.list\",\n \"snapshot.delete.generation\",\n]);\n\nexport function httpRequestPhaseFromTimingName(name) {\n const prefix = name.startsWith(\"orch.phase.\") ? \"orch.phase.\" : \"phase.\";\n if (!name.startsWith(prefix)) return undefined;\n const phase = name.slice(prefix.length);\n return HTTP_REQUEST_PHASE_NAMES.includes(phase) ? phase : undefined;\n}\n\nexport const PLATFORM_VERDICT_SCOPE_CLASSES = Object.freeze([\n \"key\",\n \"identity\",\n \"owner_user\",\n \"owner_team\",\n \"lineage\",\n \"other\",\n]);\nexport const PLATFORM_VERDICT_EVIDENCE_ORDERS = Object.freeze([\n \"feed_before_observation\",\n \"feed_at_observation\",\n \"feed_after_observation\",\n \"unknown\",\n]);\n\n/** Closed failure facts: thrown values can carry credentials or URLs, so only these names leave. */\nexport const FAILURE_FACT_NAMES = Object.freeze([\n \"Error\",\n \"TypeError\",\n \"AbortError\",\n \"TimeoutError\",\n \"RangeError\",\n \"Other\",\n]);\nexport const FAILURE_FACT_CODES = Object.freeze([\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ECONNABORTED\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"ENETUNREACH\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"EADDRNOTAVAIL\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_BODY_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n \"UND_ERR_ABORTED\",\n]);\nexport const FAILURE_FACT_KINDS = Object.freeze([\n \"request-context\",\n \"connection-lost\",\n \"fetch-failed\",\n]);\n\n/** Bounded, closed-schema origin phase projection for the two Worker ledgers.\n * Duplicate observations remain separate; different origins/attempts cannot be summed.\n */\nexport const HTTP_PHASE_COVERAGE_FIELDS = Object.freeze([\n \"stored\",\n \"emitted\",\n \"omitted\",\n \"invalid\",\n \"collisions\",\n \"headerDropped\",\n]);\n\nexport function createUpstreamHttpPhaseProjection() {\n const entries = [];\n let bytes = 0;\n let dropped = 0;\n let rejectedInputs = 0;\n const fields = HTTP_PHASE_COVERAGE_FIELDS;\n const byteLength = (value) => new TextEncoder().encode(value).length;\n const keep = (entry) => {\n // Reserve a bounded forwarding-coverage entry inside this component's 4 KiB.\n const size = byteLength(entry) + 2;\n if (entries.length >= 31 || bytes + size > 3900) {\n dropped++;\n return;\n }\n entries.push(entry);\n bytes += size;\n };\n return {\n absorb(header) {\n if (header == null) return;\n if (\n typeof header !== \"string\" ||\n header.length > 4096 ||\n byteLength(header) > 4096\n ) {\n rejectedInputs++;\n return;\n }\n for (const entry of parseServerTiming(header)) {\n // Only direct origin names enter this fold; never prefix orch. twice.\n if (entry.name === \"phase.coverage\") {\n const counts = {};\n const parts = (entry.desc ?? \"\").split(\",\");\n if (parts.length !== fields.length) {\n dropped++;\n continue;\n }\n for (const part of parts) {\n const [key, value, ...extra] = part.split(\"=\");\n if (\n extra.length ||\n !fields.includes(key) ||\n Object.hasOwn(counts, key) ||\n !/^(?:0|[1-9]\\d*)$/.test(value ?? \"\") ||\n !Number.isSafeInteger(Number(value))\n )\n break;\n counts[key] = Number(value);\n }\n if (Object.keys(counts).length !== fields.length) {\n dropped++;\n continue;\n }\n keep(\n `orch.phase.coverage;desc=\"${fields.map((key) => `${key}=${counts[key]}`).join(\",\")}\"`,\n );\n } else if (entry.name.startsWith(\"phase.\")) {\n if (\n !httpRequestPhaseFromTimingName(entry.name) ||\n !Number.isFinite(entry.dur) ||\n entry.dur < 0 ||\n !/^outcome=(?:completed|error)$/.test(entry.desc ?? \"\")\n ) {\n dropped++;\n continue;\n }\n keep(\n `orch.${entry.name};dur=${Math.round(entry.dur)};desc=\"${entry.desc}\"`,\n );\n }\n }\n },\n entries() {\n return [\n ...entries,\n ...(dropped || rejectedInputs\n ? [\n `orch.phase.forwarding;desc=\"dropped=${dropped},rejectedInputs=${rejectedInputs}\"`,\n ]\n : []),\n ];\n },\n };\n}\n"],"mappings":";;;AACA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAWD,MAAM,kBAAkB,mBAAmB,QACxC,UACC,UAAU,gBACV,UAAU,oBACV,UAAU,qBACb;;AAGD,SAAgB,0BAA0B,QAAkC;AAC1E,QAAO,mBAAmB,QACvB,KAAK,UACJ,OACC,UAAU,eAAe,UAAU,iBAAiB,IAAI,OAAO,SAClE,EACD;;;AAIH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c,OAAO,MAAM,CAAC,CAEpC;AACF,YAAO,OAAO,OAAO,MAAM;;AAE7B,QAAI,OAAO,KAAK,OAAO,CAAC,WAAW,OAAO,QAAQ;AAChD;AACA;;AAEF,SACE,6BAA6B,OAAO,KAAK,QAAQ,GAAG,IAAI,GAAG,OAAO,OAAO,CAAC,KAAK,IAAI,CAAC,GACrF;cACQ,MAAM,KAAK,WAAW,SAAS,EAAE;AAC1C,QACE,CAAC,+BAA+B,MAAM,KAAK,IAC3C,CAAC,OAAO,SAAS,MAAM,IAAI,IAC3B,MAAM,MAAM,KACZ,CAAC,gCAAgC,KAAK,MAAM,QAAQ,GAAG,EACvD;AACA;AACA;;AAEF,SACE,QAAQ,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,IAAI,CAAC,SAAS,MAAM,KAAK,GACrE;;;EAIP,UAAU;AACR,UAAO,CACL,GAAG,SACH,GAAI,WAAW,iBACX,CACE,uCAAuC,QAAQ,kBAAkB,eAAe,GACjF,GACD,EAAE,CACP;;EAEJ"}
@@ -1,4 +1,4 @@
1
- import { a as leafOperations, i as STOP_ACCOUNTING_SPEC, l as spanTreeStages, n as DELETE_ACCOUNTING_SPEC, o as operationLeafDurations, r as RESUME_ACCOUNTING_SPEC, s as parentOperations, t as CREATE_ACCOUNTING_SPEC, u as stageTree } from "./lifecycle-wall-CZZAgPft.mjs";
1
+ import { a as leafOperations, i as STOP_ACCOUNTING_SPEC, l as spanTreeStages, n as DELETE_ACCOUNTING_SPEC, o as operationLeafDurations, r as RESUME_ACCOUNTING_SPEC, s as parentOperations, t as CREATE_ACCOUNTING_SPEC, u as stageTree } from "./lifecycle-wall-BeaxDTJ8.mjs";
2
2
  //#region src/stage-span.ts
3
3
  /**
4
4
  * One span shape for every lifecycle-op stage across every hop.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-telemetry",
3
- "version": "0.7.7",
3
+ "version": "0.7.9",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,7 +31,7 @@
31
31
  "dist"
32
32
  ],
33
33
  "dependencies": {
34
- "@tangle-network/agent-core": "^1.0.0",
34
+ "@tangle-network/agent-core": "^1.0.3",
35
35
  "@tangle-network/agent-trace-contract": "^2.2.0"
36
36
  },
37
37
  "devDependencies": {
@@ -70,8 +70,8 @@
70
70
  }
71
71
  },
72
72
  "tangleRelease": {
73
- "sourceSha": "4ebbdbe755569ab872dd1b5b540bbd0688c00dea",
74
- "mergedAt": "2026-11-02T08:29:09-08:00"
73
+ "sourceSha": "c9c94777cfcfd997fa2b5913e42c8c622fcd0850",
74
+ "mergedAt": "2026-11-05T14:40:47-08:00"
75
75
  },
76
76
  "scripts": {
77
77
  "build": "tsdown",
@@ -1 +0,0 @@
1
- {"version":3,"file":"lifecycle-wall-CZZAgPft.mjs","names":[],"sources":["../src/lifecycle-wall.ts"],"sourcesContent":["/**\n * The `ready` span carries the end-to-end create wall (caller start → the end\n * of createSidecar). These operations run AFTER `ready` is stamped, so they sit\n * OUTSIDE the ready window and must never be summed into the leaf total or the\n * residual goes negative.\n */\nconst CREATE_POST_READY_OPERATIONS = new Set([\n \"orchestrator.container_lookup\",\n \"orchestrator.snapshot_restore_check\",\n \"orchestrator.provision_finalize\",\n]);\n\n/**\n * Per-flow shape of the accounting window. `totalOperation` is the span whose\n * wall the named leaves must tile; `postReadyOperations` run AFTER it is\n * stamped (excluded from the leaf sum); `prepUmbrella` is the optional\n * create-style split of an entry umbrella minus its measured leaf children. Absent\n * `prepUmbrella` ⇒ `prepUnaccountedMs` is always 0 and the whole dark falls\n * into `unaccountedMs` (the shape every non-create flow uses).\n */\nexport type FlowAccountingSpec = {\n totalOperation: string;\n postReadyOperations?: ReadonlySet<string>;\n prepUmbrella?: { operation: string };\n};\n\nexport const CREATE_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.ready\",\n postReadyOperations: CREATE_POST_READY_OPERATIONS,\n prepUmbrella: {\n operation: \"orchestrator.provision_prep\",\n },\n};\n\nexport const RESUME_ACCOUNTING_SPEC: FlowAccountingSpec = {\n // `orchestrator.ready` runs from the request to the sidecar's ready stamp;\n // these run after that stamp.\n totalOperation: \"orchestrator.ready\",\n postReadyOperations: new Set([\n \"orchestrator.connection_build\",\n \"orchestrator.metering_restart\",\n \"orchestrator.resume_commit\",\n ]),\n};\n\nexport const STOP_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.stop_complete\",\n};\n\nexport const DELETE_ACCOUNTING_SPEC: FlowAccountingSpec = {\n totalOperation: \"orchestrator.delete_complete\",\n};\n\nexport interface LifecycleStageTiming {\n operation: string;\n durationMs?: number;\n parent?: string | null;\n}\ntype Values = Readonly<Record<string, number>>;\nexport interface LifecycleWallSample {\n wallMs: number;\n httpMs: number;\n hops?: Values;\n spanOps?: readonly LifecycleStageTiming[];\n spanLeaves?: Values;\n spanTotalMs?: number | null;\n orchStages?: Values | null;\n jobPhases?: Values | null;\n jobMs?: number | null;\n settleMs?: number | null;\n spanAccountedMs?: number;\n}\nexport interface LifecycleWallFlow extends Partial<FlowAccountingSpec> {\n workerTotalHop: string;\n addPreHandler: boolean;\n settleHop?: string;\n workerNamedHops?: readonly string[];\n}\n\n/**\n * A flat `{name: ms}` ledger read as the tree its names describe.\n *\n * Every producer in this repo emits nested stages FLAT, with the containment\n * in the name: `capture.<hostPhase>` and `capture.restic_<phase>` inside\n * `capture` (snapshot-helpers.ts), `materialize.parentRead|precreate|\n * branchComplete|host.*|child.*|residual` inside `materialize` (branch.ts),\n * `delete.<hostPhase>` inside `delete` and `restore_workspace.<phase>` inside\n * `restore_workspace` (snapshots.ts). Summing every entry as a sibling counts\n * the children inside their parent a second time and reports a wall the\n * orchestrator never spent.\n *\n * So a dotted name is NEVER top-level. It attaches to the longest prefix that\n * exists as a stage; when no prefix exists — the restore job's `host.<phase>`,\n * which the queue records inside `restore_workspace` without naming it\n * (snapshot-job-queue.ts:394) — it is still excluded from the top-level sum\n * and reported as a child of the ledger at large. Excluding it can only leave\n * MORE time unnamed, never fabricate a reconciliation.\n */\nexport function stageTree(stages: Readonly<Record<string, number>>) {\n const present = new Set(Object.keys(stages));\n const parentOf = (name: string) => {\n let cut = name.lastIndexOf(\".\");\n while (cut > 0) {\n const candidate = name.slice(0, cut);\n if (present.has(candidate)) return candidate;\n cut = candidate.lastIndexOf(\".\");\n }\n return name.includes(\".\") ? \"\" : null;\n };\n const nodes = Object.entries(stages).map(([name, ms]) => ({\n name,\n ms,\n parent: parentOf(name),\n }));\n const topLevel = nodes.filter((node) => node.parent === null);\n return {\n nodes,\n topLevel,\n /** Children whose declared parent is not in the ledger; never summed. */\n orphans: nodes.filter((node) => node.parent === \"\"),\n topLevelMs: topLevel.reduce((sum, node) => sum + node.ms, 0),\n };\n}\n\n/**\n * A response's span tree as `<stage>.<path>` rows and each parent's wall minus\n * its children as `<parent>.unattributed` (0 when children overlap), residuals\n * first so a capped header keeps them. Unparented spans nest in the total span.\n */\nexport function spanTreeStages(\n stage: string,\n stageMs: Readonly<Record<string, number>>,\n operations: readonly (LifecycleStageTiming & { status?: string })[] = [],\n spec?: Partial<FlowAccountingSpec>,\n): Record<string, number> {\n const total = spec?.totalOperation ?? \"\";\n const byName = new Map(operations.map((op) => [op.operation, op]));\n const path = (op: LifecycleStageTiming, depth = 0): string => {\n const outside =\n op.operation === total || spec?.postReadyOperations?.has(op.operation);\n const parent = byName.get(op.parent ?? (outside ? \"\" : total));\n const name = op.operation.slice(op.operation.lastIndexOf(\".\") + 1);\n return `${parent && depth < 8 ? path(parent, depth + 1) : stage}.${name}`;\n };\n const rows: Record<string, number> = { [stage]: stageMs[stage] ?? 0 };\n for (const { durationMs: ms, status, ...op } of operations)\n if (status === \"completed\" && typeof ms === \"number\" && ms >= 0)\n rows[path(op)] = (rows[path(op)] ?? 0) + ms;\n const residuals: Record<string, number> = {};\n for (const [parent, ms] of Object.entries(rows)) {\n const kids = Object.keys(rows).filter(\n (name) =>\n name.startsWith(`${parent}.`) &&\n !name.slice(parent.length + 1).includes(\".\"),\n );\n if (kids.length)\n residuals[`${parent}.unattributed`] = Math.max(\n 0,\n kids.reduce((rest, kid) => rest - (rows[kid] ?? 0), ms),\n );\n }\n delete rows[stage];\n return { ...residuals, ...rows };\n}\n\n/**\n * Hops that describe the SHAPE of the request rather than a slice of it: the\n * three nested walls, the transport the walls imply, and the retry counter.\n * They are the terms of the summary line, so ranking them again as sub-stages\n * would print the same milliseconds twice under a second name. `preHandler`\n * joins them because it is the umbrella over the `mw.*` own-times, which ARE\n * ranked.\n */\nconst SHAPE_HOPS = new Set([\n \"preHandler\",\n \"total\",\n \"serverWall\",\n \"orchestrator\",\n \"orchestratorServer\",\n \"transportMarkup\",\n \"orchestratorRetries\",\n]);\n\n/** Parent operations contain their descendants and are never counted as leaves. */\nexport function parentOperations(\n operations: readonly LifecycleStageTiming[],\n): ReadonlySet<string> {\n return new Set(\n operations.flatMap((op) =>\n typeof op.parent === \"string\" ? [op.parent] : [],\n ),\n );\n}\n\n/**\n * The measured leaves of one response's span tree, per the flow's own spec.\n *\n * Identical rule to the orchestrator's `computeFlowAccountingResiduals`: drop\n * the total span (it is the window), drop the spans stamped after it closes,\n * and drop any span another span names as its parent (a parent re-measures its\n * children). What is left sums to the window minus its named residual.\n */\nexport function leafOperations<T extends LifecycleStageTiming>(\n operations: readonly T[],\n excluded: ReadonlySet<string> = new Set(),\n parents = parentOperations(operations),\n) {\n return operations.filter(\n (op): op is T & { durationMs: number } =>\n !excluded.has(op.operation) &&\n !parents.has(op.operation) &&\n typeof op.durationMs === \"number\" &&\n Number.isFinite(op.durationMs),\n );\n}\n\nexport function operationLeafDurations(\n operations: readonly LifecycleStageTiming[],\n excluded: ReadonlySet<string> = new Set(),\n) {\n const leaves = new Map<string, number>();\n for (const op of leafOperations(operations, excluded))\n leaves.set(op.operation, (leaves.get(op.operation) ?? 0) + op.durationMs);\n return leaves;\n}\n\nconst difference = (a: number | null, b: number | null) =>\n a === null || b === null ? null : a - b;\nconst positiveDifference = (a: number | null, b: number | null) => {\n const value = difference(a, b);\n return value === null ? null : Math.max(0, value);\n};\n\n/**\n * Partition one input before aggregation: null is unavailable; a negative\n * residual is overlapping evidence, never an instruction to publish zero.\n * Callers retain their population grouping, medians and display labels.\n */\nexport function partitionLifecycleWalls(\n sample: LifecycleWallSample,\n flow: LifecycleWallFlow,\n) {\n const present = (value: number | null | undefined) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n const finiteStages = (values?: Values | null) =>\n Object.fromEntries(\n Object.entries(values ?? {}).filter(([, ms]) => Number.isFinite(ms)),\n );\n const hops = sample.hops ?? {};\n const hop = (key: string) => (Number.isFinite(hops[key]) ? hops[key] : null);\n const handler = hop(flow.workerTotalHop);\n const preHandler = hop(\"preHandler\");\n const hold = flow.settleHop ? (hop(flow.settleHop) ?? 0) : 0;\n const workerWallMs =\n handler === null\n ? null\n : Math.max(0, handler - hold) +\n (flow.addPreHandler ? (preHandler ?? 0) : 0);\n const roundTripMs = hop(\"orchestrator\");\n const orchServerMs = hop(\"orchestratorServer\");\n const orchWall = roundTripMs ?? orchServerMs;\n const terms = {\n edge: positiveDifference(sample.httpMs, workerWallMs),\n worker: positiveDifference(workerWallMs, orchWall ?? 0),\n transport: positiveDifference(roundTripMs, orchServerMs),\n orch: orchServerMs ?? roundTripMs,\n job: present(sample.jobMs),\n settle: present(sample.settleMs),\n dark: 0,\n };\n terms.dark =\n sample.wallMs -\n Object.values(terms).reduce<number>((sum, ms) => sum + (ms ?? 0), 0);\n const postReady = flow.postReadyOperations ?? new Set();\n const rawLeaves =\n sample.spanLeaves ??\n Object.fromEntries(operationLeafDurations(sample.spanOps ?? []));\n const spanLeaves = Object.fromEntries(\n Object.entries(rawLeaves).filter(\n ([name, ms]) =>\n name !== flow.totalOperation &&\n !postReady.has(name) &&\n Number.isFinite(ms),\n ),\n );\n /**\n * The Worker's own handler stages: its ledger minus the three nested walls,\n * the transport they imply and the middleware own-times, which are ranked\n * separately because they run OUTSIDE the handler's `total`.\n */\n const workerStages = Object.fromEntries(\n Object.entries(hops).filter(\n ([name]) =>\n Number.isFinite(hops[name]) &&\n !SHAPE_HOPS.has(name) &&\n name !== flow.settleHop &&\n !name.startsWith(\"orch.\") &&\n !name.startsWith(\"mw.\"),\n ),\n );\n const orchTree = stageTree(finiteStages(sample.orchStages));\n const jobTree = stageTree(finiteStages(sample.jobPhases));\n const spanSum = Object.values(spanLeaves).reduce((sum, ms) => sum + ms, 0);\n const workerNamed =\n (flow.addPreHandler ? (preHandler ?? 0) : 0) +\n (flow.workerNamedHops\n ? flow.workerNamedHops.reduce((sum, key) => sum + (hop(key) ?? 0), 0)\n : stageTree(workerStages).topLevelMs);\n const workerUnattributedMs = difference(terms.worker, workerNamed);\n const orchNamed = orchTree.topLevel.length\n ? orchTree.topLevelMs\n : spanSum > 0\n ? spanSum\n : 0;\n const orchUnattributedMs = difference(terms.orch, orchNamed);\n const jobUnattributedMs = difference(terms.job, jobTree.topLevelMs);\n const unnamedMs =\n Math.max(0, workerUnattributedMs ?? terms.worker ?? 0) +\n Math.max(0, orchUnattributedMs ?? terms.orch ?? 0) +\n Math.max(0, jobUnattributedMs ?? terms.job ?? 0) +\n Math.max(0, terms.dark);\n const measuredTotal = (sample.spanOps ?? []).find(\n (op) => op.operation === flow.totalOperation,\n )?.durationMs;\n const spanTotalMs = present(sample.spanTotalMs ?? measuredTotal);\n const readySum = sample.spanAccountedMs ?? spanSum;\n const readyTerm = spanTotalMs ?? readySum;\n const orchTerm = roundTripMs ?? orchServerMs ?? readyTerm;\n let clampedMs = 0;\n const diff = (a: number | null, b: number | null) => {\n const delta = difference(a, b);\n if (delta === null) return null;\n clampedMs += Math.max(0, -delta);\n return Math.max(0, delta);\n };\n const transportMs = diff(roundTripMs, orchServerMs);\n const afterSpanMs = diff(orchServerMs, spanTotalMs);\n const pathSum = workerNamed + orchTerm;\n const outerMs =\n workerWallMs === null\n ? diff(\n sample.wallMs - readyTerm,\n workerNamed + (transportMs ?? 0) + (afterSpanMs ?? 0),\n )\n : diff(sample.wallMs, workerWallMs);\n const window = {\n transportMs,\n afterSpanMs,\n outerMs,\n workerUnattributedMs: positiveDifference(workerWallMs, pathSum),\n workerOwnMs: positiveDifference(workerWallMs, orchTerm),\n gaps: {\n overlapMs: positiveDifference(readySum, spanTotalMs) ?? 0,\n underTileMs: positiveDifference(spanTotalMs, readySum) ?? 0,\n workerOverlapMs: positiveDifference(pathSum, workerWallMs) ?? 0,\n unrowedMs:\n workerWallMs === null\n ? 0\n : Math.max(\n 0,\n orchTerm - readyTerm - (transportMs ?? 0) - (afterSpanMs ?? 0),\n ),\n clampedMs,\n },\n };\n return {\n wallMs: sample.wallMs,\n httpMs: sample.httpMs,\n workerWallMs,\n roundTripMs,\n orchServerMs,\n orchIncludesTransport: orchServerMs === null && roundTripMs !== null,\n workerIncludesTransport: roundTripMs === null && orchServerMs !== null,\n terms,\n workerUnattributedMs,\n orchUnattributedMs,\n jobUnattributedMs,\n unnamedMs,\n unnamedShare: sample.wallMs > 0 ? unnamedMs / sample.wallMs : 0,\n overcountMs: Math.max(0, -terms.dark),\n spanLeaves,\n workerStages,\n orchTree,\n jobTree,\n spanTotalMs,\n window,\n };\n}\n"],"mappings":"AA0BA,MAAa,yBAA6C;CACxD,gBAAgB;CAChB,qBAAqB,IAtBkB,IAAI;EAC3C;EACA;EACA;EACD,CAkBsB;CACrB,cAAc,EACZ,WAAW,+BACZ;CACF;AAED,MAAa,yBAA6C;CAGxD,gBAAgB;CAChB,qBAAqB,IAAI,IAAI;EAC3B;EACA;EACA;EACD,CAAC;CACH;AAED,MAAa,uBAA2C,EACtD,gBAAgB,8BACjB;AAED,MAAa,yBAA6C,EACxD,gBAAgB,gCACjB;;;;;;;;;;;;;;;;;;;;AA+CD,SAAgB,UAAU,QAA0C;CAClE,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,OAAO,CAAC;CAC5C,MAAM,YAAY,SAAiB;EACjC,IAAI,MAAM,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