@secondlayer/subgraphs 4.3.4 → 4.4.0

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 (42) hide show
  1. package/dist/src/index.d.ts +63 -4
  2. package/dist/src/index.js +307 -28
  3. package/dist/src/index.js.map +14 -14
  4. package/dist/src/runtime/block-processor.d.ts +24 -2
  5. package/dist/src/runtime/block-processor.js +252 -21
  6. package/dist/src/runtime/block-processor.js.map +10 -10
  7. package/dist/src/runtime/catchup.d.ts +18 -1
  8. package/dist/src/runtime/catchup.js +253 -22
  9. package/dist/src/runtime/catchup.js.map +11 -11
  10. package/dist/src/runtime/context.js +20 -3
  11. package/dist/src/runtime/context.js.map +3 -3
  12. package/dist/src/runtime/processor.js +254 -23
  13. package/dist/src/runtime/processor.js.map +12 -12
  14. package/dist/src/runtime/reindex.d.ts +28 -1
  15. package/dist/src/runtime/reindex.js +254 -23
  16. package/dist/src/runtime/reindex.js.map +12 -12
  17. package/dist/src/runtime/reorg.d.ts +18 -1
  18. package/dist/src/runtime/reorg.js +253 -22
  19. package/dist/src/runtime/reorg.js.map +11 -11
  20. package/dist/src/runtime/replay.d.ts +10 -0
  21. package/dist/src/runtime/replay.js +184 -20
  22. package/dist/src/runtime/replay.js.map +9 -9
  23. package/dist/src/runtime/runner.d.ts +21 -1
  24. package/dist/src/runtime/runner.js +121 -5
  25. package/dist/src/runtime/runner.js.map +4 -4
  26. package/dist/src/runtime/source-matcher.d.ts +22 -2
  27. package/dist/src/runtime/source-matcher.js +61 -4
  28. package/dist/src/runtime/source-matcher.js.map +3 -3
  29. package/dist/src/schema/index.d.ts +18 -1
  30. package/dist/src/schema/index.js +73 -8
  31. package/dist/src/schema/index.js.map +5 -5
  32. package/dist/src/service.js +254 -23
  33. package/dist/src/service.js.map +12 -12
  34. package/dist/src/testing/index.d.ts +64 -2
  35. package/dist/src/testing/index.js +176 -7
  36. package/dist/src/testing/index.js.map +6 -6
  37. package/dist/src/triggers/index.d.ts +18 -1
  38. package/dist/src/types.d.ts +19 -2
  39. package/dist/src/validate.d.ts +19 -2
  40. package/dist/src/validate.js +44 -2
  41. package/dist/src/validate.js.map +3 -3
  42. package/package.json +3 -3
@@ -2,23 +2,23 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/validate.ts", "../src/runtime/context.ts", "../src/schema/generator.ts", "../src/schema/utils.ts", "../src/runtime/chain-read.ts", "../src/runtime/clarity.ts", "../src/runtime/source-matcher.ts", "../src/runtime/runner.ts", "../src/print-schema.ts", "../src/runtime/materialize.ts", "../src/runtime/print-validate.ts", "../src/runtime/violations.ts", "../src/runtime/block-processor.ts", "../src/runtime/block-source.ts", "../src/runtime/batch-loader.ts", "../src/runtime/observer-http-source.ts", "../src/runtime/reconstruct.ts", "../src/runtime/outbox-emit.ts", "../src/runtime/sandbox/flag.ts", "../src/runtime/sandbox/host.ts", "../src/runtime/sandbox/bundle.ts", "../src/runtime/webhook-state.ts", "../src/runtime/emitter-matcher.ts", "../src/runtime/stats.ts", "../src/runtime/catchup.ts", "../src/runtime/catchup-leader.ts", "../src/runtime/decoder-bound.ts", "../src/runtime/reindex.ts", "../src/runtime/reindex-notify.ts", "../src/define.ts", "../src/schema/prisma.ts", "../src/schema/drizzle.ts", "../src/schema/kysely.ts", "../src/schema/index-codegen.ts", "../src/schema/deployer.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod\";\nimport type {\n\tColumnType,\n\tMaterializeSpec,\n\tPrintEventPrints,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\n/**\n * A safe SQL identifier (table or column name). Mirrors the runtime guard in\n * runtime/context.ts (validateColumnName) so the schema validator can never\n * accept a name the runtime would reject — and closes the deploy-time DDL\n * injection path in schema/generator.ts, which interpolates these names raw.\n */\nexport const SqlIdentifierSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63) // Postgres truncates identifiers > 63 bytes; reject rather than collide.\n\t.regex(\n\t\t/^[a-z_][a-z0-9_]*$/i,\n\t\t\"Must be a valid SQL identifier: start with a letter or underscore, then letters/digits/underscores only\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\n/**\n * One declared print field: a bare column type, or a composite (optional,\n * nested tuple, list). Recursive — real print payloads nest, and a vocabulary\n * that could only say `\"jsonb\"` is what let a flat-field declaration pass\n * while every event decoded to null.\n */\nexport const PrintFieldSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tColumnTypeSchema,\n\t\tz.object({ type: PrintFieldSchema, optional: z.literal(true) }),\n\t\tz.object({ tuple: z.record(z.string(), PrintFieldSchema) }),\n\t\tz.object({ list: PrintFieldSchema }),\n\t]),\n);\n\n/**\n * A Clarity ABI type: a primitive name, or one of the composite shapes.\n * Recursive, so nested tuples/lists/optionals are checked all the way down.\n */\nconst AbiTypeSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tz.string(),\n\t\tz.object({ buff: z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-ascii\": z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-utf8\": z.object({ length: z.number() }) }),\n\t\tz.object({ optional: AbiTypeSchema }),\n\t\tz.object({\n\t\t\tlist: z.object({ type: AbiTypeSchema, length: z.number() }),\n\t\t}),\n\t\tz.object({\n\t\t\ttuple: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t}),\n\t\tz.object({\n\t\t\tresponse: z.object({ ok: AbiTypeSchema, error: AbiTypeSchema }),\n\t\t}),\n\t]),\n);\n\n/**\n * The canonical `AbiContract` shape, validated at deploy time.\n *\n * This used to be `z.record(z.string(), z.any())`, which accepted a raw\n * Hiro/Clarinet ABI (`read_only` access, `buffer` types, outputs wrapped as\n * `{ type: … }`) and let it through — the deploy succeeded and `event.input`\n * then mis-decoded at RUNTIME, per event, forever. Reject it here instead,\n * and name the fix: run it through `normalizeAbi` from\n * `@secondlayer/stacks/clarity`.\n */\nexport const AbiContractSchema: z.ZodType<unknown> = z.object({\n\tfunctions: z.array(\n\t\tz.object({\n\t\t\tname: z.string(),\n\t\t\taccess: z.enum([\"public\", \"read-only\", \"private\"], {\n\t\t\t\tmessage:\n\t\t\t\t\t\"ABI access must be public | read-only | private — a raw Hiro/Clarinet ABI uses `read_only`. Normalize it first: normalizeAbi() from @secondlayer/stacks/clarity.\",\n\t\t\t}),\n\t\t\targs: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t\t// Canonical shape is a bare AbiType; raw ABIs wrap it as `{ type: … }`.\n\t\t\toutputs: AbiTypeSchema,\n\t\t}),\n\t),\n\tmaps: z.array(z.unknown()).optional(),\n\tvariables: z.array(z.unknown()).optional(),\n\tfungible_tokens: z.array(z.unknown()).optional(),\n\tnon_fungible_tokens: z.array(z.unknown()).optional(),\n\timplemented_traits: z.array(z.unknown()).optional(),\n\tdefined_traits: z.array(z.unknown()).optional(),\n});\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(SqlIdentifierSchema, SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(SqlIdentifierSchema)).optional(),\n\tuniqueKeys: z.array(z.array(SqlIdentifierSchema)).optional(),\n\trelations: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: SqlIdentifierSchema,\n\t\t\t\treferences: SqlIdentifierSchema,\n\t\t\t\tfields: z.array(SqlIdentifierSchema).min(1),\n\t\t\t\treferencedColumns: z.array(SqlIdentifierSchema).min(1),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(SqlIdentifierSchema, SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n] as const;\n\n/** A contract id, or a set of them (max 20, matching the Index API cap). */\nconst contractIdField = z.union([\n\tz.string(),\n\tz.array(z.string()).min(1).max(20),\n]);\n\n/** Fields shared by the trait-scopable filters. */\nconst traitScope = { trait: z.string().optional() };\n/** Dynamic address set discovered from another source's events. */\nconst factoryScope = {\n\tfactory: z\n\t\t.object({ from: z.string().min(1), field: z.string().min(1) })\n\t\t.strict()\n\t\t.optional(),\n};\nconst amountRange = {\n\tminAmount: z.bigint().optional(),\n\tmaxAmount: z.bigint().optional(),\n};\n\nconst MaterializeColumnSchema = z.union([\n\tz.object({ from: z.string().min(1) }).strict(),\n\tz.object({ fromTx: z.enum([\"sender\", \"txId\"]) }).strict(),\n\tz.object({ fromBlock: z.enum([\"height\", \"hash\", \"timestamp\"]) }).strict(),\n]);\n\nconst MaterializeSpecSchema = z\n\t.object({\n\t\ttable: z.string().min(1),\n\t\tcolumns: z.record(z.string(), MaterializeColumnSchema),\n\t})\n\t.strict();\n\n/**\n * A REAL discriminated union — one member per source type, each `.strict()`\n * with only the fields that type actually supports.\n *\n * It used to be one flat object with every field optional, so\n * `{ type: \"contract_deploy\", assetIdentifier: \"SP…\", minAmount: 1n }`\n * validated clean at deploy and then matched nothing, forever. The runtime\n * union already knew better; only the validator didn't.\n */\nconst SubgraphFilterUnion = z.discriminatedUnion(\"type\", [\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_transfer\"),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...amountRange,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_mint\"),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_burn\"),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_lock\"),\n\t\t\tlockedAddress: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tabi: AbiContractSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_deploy\"),\n\t\t\tdeployer: z.string().optional(),\n\t\t\tcontractName: z.string().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"print_event\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\ttopic: z.string().optional(),\n\t\t\tprints: z\n\t\t\t\t.record(z.string(), z.record(z.string(), PrintFieldSchema))\n\t\t\t\t.optional(),\n\t\t\tmaterialize: MaterializeSpecSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n]);\n\n/**\n * `trait` and `contractId` compose rather than conflict: the matcher ANDs\n * them, so the pair means \"contracts conforming to this trait, narrowed to\n * these ids\". (The Index READ API refuses the combination because its query\n * planner picks one index path — that's an API constraint, not a semantic\n * one, and subgraph sources are not bound by it.)\n */\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> =\n\tSubgraphFilterUnion as unknown as z.ZodType<SubgraphFilter>;\n\n/** Pinned contractId: a non-empty string or a non-empty array of ids. */\nfunction hasPinnedContractId(\n\tcontractId: string | readonly string[] | undefined,\n): boolean {\n\tif (typeof contractId === \"string\") return contractId.length > 0;\n\tif (Array.isArray(contractId)) return contractId.length > 0;\n\treturn false;\n}\n\n/** Camel keys declared across a prints map, plus `topic` (native payload). */\nfunction printMaterializeFromKeys(\n\tprints: PrintEventPrints | undefined,\n): string[] {\n\tconst keys = new Set<string>([\"topic\"]);\n\tif (prints) {\n\t\tfor (const fields of Object.values(prints)) {\n\t\t\tfor (const k of Object.keys(fields)) keys.add(k);\n\t\t}\n\t}\n\treturn [...keys].sort();\n}\n\nfunction refineMaterialize(\n\tname: string,\n\tfilter: SubgraphFilter,\n\tschema: SubgraphSchema,\n\tctx: z.RefinementCtx,\n): void {\n\tif (!(\"materialize\" in filter) || filter.materialize === undefined) return;\n\tconst spec = filter.materialize as MaterializeSpec;\n\tconst table = schema[spec.table];\n\tif (!table) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"sources\", name, \"materialize\", \"table\"],\n\t\t\tmessage: `materialize table \"${spec.table}\" is not in schema`,\n\t\t});\n\t\treturn;\n\t}\n\tfor (const col of Object.keys(spec.columns)) {\n\t\tif (!(col in table.columns)) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"sources\", name, \"materialize\", \"columns\", col],\n\t\t\t\tmessage: `materialize column \"${col}\" is not on schema table \"${spec.table}\"`,\n\t\t\t});\n\t\t}\n\t}\n\tif (filter.type === \"print_event\") {\n\t\tconst known = printMaterializeFromKeys(filter.prints);\n\t\tconst knownSet = new Set(known);\n\t\tfor (const [col, mapping] of Object.entries(spec.columns)) {\n\t\t\tif (!(\"from\" in mapping)) continue;\n\t\t\tif (!knownSet.has(mapping.from)) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"materialize\", \"columns\", col, \"from\"],\n\t\t\t\t\tmessage: `materialize from \"${mapping.from}\" is not a known print field — known: ${known.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Deploy gates beyond the per-filter union: pinned print_event needs a\n * non-empty `prints` map, contract_call+functionName needs `abi`, and every\n * source needs a named handler, materialize, or `\"*\"`.\n */\nfunction refineDeployGates(\n\tdef: {\n\t\tsources: Record<string, SubgraphFilter>;\n\t\thandlers: Record<string, unknown>;\n\t\tschema: SubgraphSchema;\n\t},\n\tctx: z.RefinementCtx,\n): void {\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tif (filter.type === \"print_event\") {\n\t\t\t// Trait / unpinned (no contractId) may omit prints — no single schema.\n\t\t\tconst pinned = hasPinnedContractId(filter.contractId) && !filter.trait;\n\t\t\tif (pinned) {\n\t\t\t\tconst prints = filter.prints;\n\t\t\t\tif (\n\t\t\t\t\tprints === undefined ||\n\t\t\t\t\ttypeof prints !== \"object\" ||\n\t\t\t\t\tObject.keys(prints).length === 0\n\t\t\t\t) {\n\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tpath: [\"sources\", name, \"prints\"],\n\t\t\t\t\t\tmessage: `print_event source \"${name}\" has no prints map — field names would be untyped and empty tables would typecheck. Declare prints from index_print_schema / create --from-contract.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (filter.type === \"contract_call\" && filter.functionName !== undefined) {\n\t\t\tif (filter.abi === undefined) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"abi\"],\n\t\t\t\t\tmessage: `contract_call source \"${name}\" has functionName but no abi — pass a canonical ABI (normalizeAbi() from @secondlayer/stacks/clarity).`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\trefineMaterialize(name, filter, def.schema, ctx);\n\t}\n\n\tconst hasCatchAll = def.handlers[\"*\"] != null;\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tconst hasMaterialize =\n\t\t\t\"materialize\" in filter && filter.materialize !== undefined;\n\t\tconst hasHandler = def.handlers[name] != null;\n\t\tif (hasMaterialize && hasHandler) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has both materialize and a handler — use one or the other`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasHandler && !hasMaterialize && !hasCatchAll) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has no handler (and no \"*\") — events will be skipped and the table stay empty.`,\n\t\t\t});\n\t\t}\n\t}\n}\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z\n\t.object({\n\t\tname: SubgraphNameSchema,\n\t\tversion: z.string().optional(),\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\t// 'concurrent' = tip-first deploy: go live at tip immediately, fill\n\t\t// history via a background backfill. Only safe for order-tolerant\n\t\t// handlers (commutative or insert-only writes).\n\t\tbackfillMode: z.enum([\"blocking\", \"concurrent\"]).optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t})\n\t.superRefine((def, ctx) => {\n\t\trefineDeployGates(\n\t\t\tdef as {\n\t\t\t\tsources: Record<string, SubgraphFilter>;\n\t\t\t\thandlers: Record<string, unknown>;\n\t\t\t\tschema: SubgraphSchema;\n\t\t\t},\n\t\t\tctx,\n\t\t);\n\t}) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition, returning the parsed result or throwing on failure.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n\n/**\n * Per-source-type field vocabulary, DERIVED from\n * {@link SubgraphFilterSchema}. Agent-facing surfaces (the MCP filters\n * reference) used to hand-maintain a parallel copy of this list; deriving it\n * means adding a field to a filter can never leave the documentation behind.\n */\nexport function filterFieldsByType(): Array<{\n\ttype: string;\n\tfields: string[];\n}> {\n\t// Read the UNION directly (SubgraphFilterSchema wraps it in superRefine).\n\t// biome-ignore lint/suspicious/noExplicitAny: reading zod's internal option shapes\n\tconst options = (SubgraphFilterUnion as any)?._def?.options ?? [];\n\tconst out: Array<{ type: string; fields: string[] }> = [];\n\tfor (const option of options) {\n\t\t// `.superRefine()` wraps the union, so unwrap one level when present.\n\t\tconst shape = option?.shape ?? option?._def?.shape;\n\t\tif (!shape) continue;\n\t\tconst literal =\n\t\t\tshape.type?._def?.values?.[0] ?? shape.type?._def?.value ?? undefined;\n\t\tif (typeof literal !== \"string\") continue;\n\t\tout.push({\n\t\t\ttype: literal,\n\t\t\tfields: Object.keys(shape).filter((k) => k !== \"type\"),\n\t\t});\n\t}\n\treturn out;\n}\n",
5
+ "import { z } from \"zod\";\nimport type {\n\tColumnType,\n\tMaterializeSpec,\n\tPrintEventPrints,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\n/**\n * A safe SQL identifier (table or column name). Mirrors the runtime guard in\n * runtime/context.ts (validateColumnName) so the schema validator can never\n * accept a name the runtime would reject — and closes the deploy-time DDL\n * injection path in schema/generator.ts, which interpolates these names raw.\n */\nexport const SqlIdentifierSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63) // Postgres truncates identifiers > 63 bytes; reject rather than collide.\n\t.regex(\n\t\t/^[a-z_][a-z0-9_]*$/i,\n\t\t\"Must be a valid SQL identifier: start with a letter or underscore, then letters/digits/underscores only\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\n/**\n * One declared print field: a bare column type, or a composite (optional,\n * nested tuple, list). Recursive — real print payloads nest, and a vocabulary\n * that could only say `\"jsonb\"` is what let a flat-field declaration pass\n * while every event decoded to null.\n */\nexport const PrintFieldSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tColumnTypeSchema,\n\t\tz.object({ type: PrintFieldSchema, optional: z.literal(true) }),\n\t\tz.object({ tuple: z.record(z.string(), PrintFieldSchema) }),\n\t\tz.object({ list: PrintFieldSchema }),\n\t]),\n);\n\n/**\n * A Clarity ABI type: a primitive name, or one of the composite shapes.\n * Recursive, so nested tuples/lists/optionals are checked all the way down.\n */\nconst AbiTypeSchema: z.ZodType<unknown> = z.lazy(() =>\n\tz.union([\n\t\tz.string(),\n\t\tz.object({ buff: z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-ascii\": z.object({ length: z.number() }) }),\n\t\tz.object({ \"string-utf8\": z.object({ length: z.number() }) }),\n\t\tz.object({ optional: AbiTypeSchema }),\n\t\tz.object({\n\t\t\tlist: z.object({ type: AbiTypeSchema, length: z.number() }),\n\t\t}),\n\t\tz.object({\n\t\t\ttuple: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t}),\n\t\tz.object({\n\t\t\tresponse: z.object({ ok: AbiTypeSchema, error: AbiTypeSchema }),\n\t\t}),\n\t]),\n);\n\n/**\n * The canonical `AbiContract` shape, validated at deploy time.\n *\n * This used to be `z.record(z.string(), z.any())`, which accepted a raw\n * Hiro/Clarinet ABI (`read_only` access, `buffer` types, outputs wrapped as\n * `{ type: … }`) and let it through — the deploy succeeded and `event.input`\n * then mis-decoded at RUNTIME, per event, forever. Reject it here instead,\n * and name the fix: run it through `normalizeAbi` from\n * `@secondlayer/stacks/clarity`.\n */\nexport const AbiContractSchema: z.ZodType<unknown> = z.object({\n\tfunctions: z.array(\n\t\tz.object({\n\t\t\tname: z.string(),\n\t\t\taccess: z.enum([\"public\", \"read-only\", \"private\"], {\n\t\t\t\tmessage:\n\t\t\t\t\t\"ABI access must be public | read-only | private — a raw Hiro/Clarinet ABI uses `read_only`. Normalize it first: normalizeAbi() from @secondlayer/stacks/clarity.\",\n\t\t\t}),\n\t\t\targs: z.array(z.object({ name: z.string(), type: AbiTypeSchema })),\n\t\t\t// Canonical shape is a bare AbiType; raw ABIs wrap it as `{ type: … }`.\n\t\t\toutputs: AbiTypeSchema,\n\t\t}),\n\t),\n\tmaps: z.array(z.unknown()).optional(),\n\tvariables: z.array(z.unknown()).optional(),\n\tfungible_tokens: z.array(z.unknown()).optional(),\n\tnon_fungible_tokens: z.array(z.unknown()).optional(),\n\timplemented_traits: z.array(z.unknown()).optional(),\n\tdefined_traits: z.array(z.unknown()).optional(),\n});\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(SqlIdentifierSchema, SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(SqlIdentifierSchema)).optional(),\n\tuniqueKeys: z.array(z.array(SqlIdentifierSchema)).optional(),\n\trelations: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: SqlIdentifierSchema,\n\t\t\t\treferences: SqlIdentifierSchema,\n\t\t\t\tfields: z.array(SqlIdentifierSchema).min(1),\n\t\t\t\treferencedColumns: z.array(SqlIdentifierSchema).min(1),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(SqlIdentifierSchema, SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nexport const VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n] as const;\n\n/** A contract id, or a set of them (max 20, matching the Index API cap). */\nconst contractIdField = z.union([\n\tz.string(),\n\tz.array(z.string()).min(1).max(20),\n]);\n\n/** Fields shared by the trait-scopable filters. */\nconst traitScope = { trait: z.string().optional() };\n/** Dynamic address set discovered from another source's events. */\nconst factoryScope = {\n\tfactory: z\n\t\t.object({ from: z.string().min(1), field: z.string().min(1) })\n\t\t.strict()\n\t\t.optional(),\n};\nconst amountRange = {\n\tminAmount: z.bigint().optional(),\n\tmaxAmount: z.bigint().optional(),\n};\n\nconst MaterializeColumnSchema = z.union([\n\tz.object({ from: z.string().min(1) }).strict(),\n\tz.object({ fromTx: z.enum([\"sender\", \"txId\"]) }).strict(),\n\tz.object({ fromBlock: z.enum([\"height\", \"hash\", \"timestamp\"]) }).strict(),\n]);\n\nconst MaterializeSpecSchema = z\n\t.object({\n\t\ttable: z.string().min(1),\n\t\tcolumns: z.record(z.string(), MaterializeColumnSchema),\n\t})\n\t.strict();\n\n/**\n * A REAL discriminated union — one member per source type, each `.strict()`\n * with only the fields that type actually supports.\n *\n * It used to be one flat object with every field optional, so\n * `{ type: \"contract_deploy\", assetIdentifier: \"SP…\", minAmount: 1n }`\n * validated clean at deploy and then matched nothing, forever. The runtime\n * union already knew better; only the validator didn't.\n */\nconst SubgraphFilterUnion = z.discriminatedUnion(\"type\", [\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_transfer\"),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...amountRange,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_mint\"),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_burn\"),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"stx_lock\"),\n\t\t\tlockedAddress: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"ft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\tminAmount: z.bigint().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_transfer\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_mint\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\trecipient: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nft_burn\"),\n\t\t\tassetIdentifier: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tabi: AbiContractSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"contract_deploy\"),\n\t\t\tdeployer: z.string().optional(),\n\t\t\tcontractName: z.string().optional(),\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"print_event\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\ttopic: z.string().optional(),\n\t\t\tprints: z\n\t\t\t\t.record(z.string(), z.record(z.string(), PrintFieldSchema))\n\t\t\t\t.optional(),\n\t\t\tmaterialize: MaterializeSpecSchema.optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"nested_contract_call\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tfunctionName: z.string().optional(),\n\t\t\tcaller: z.string().optional(),\n\t\t\tsender: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"var_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tvarName: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_set\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_insert\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\ttype: z.literal(\"map_delete\"),\n\t\t\tcontractId: contractIdField.optional(),\n\t\t\tmap: z.string().optional(),\n\t\t\t...traitScope,\n\t\t\t...factoryScope,\n\t\t})\n\t\t.strict(),\n]);\n\n/**\n * `trait` and `contractId` compose rather than conflict: the matcher ANDs\n * them, so the pair means \"contracts conforming to this trait, narrowed to\n * these ids\". (The Index READ API refuses the combination because its query\n * planner picks one index path — that's an API constraint, not a semantic\n * one, and subgraph sources are not bound by it.)\n */\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> =\n\tSubgraphFilterUnion as unknown as z.ZodType<SubgraphFilter>;\n\n/** Pinned contractId: a non-empty string or a non-empty array of ids. */\nfunction hasPinnedContractId(\n\tcontractId: string | readonly string[] | undefined,\n): boolean {\n\tif (typeof contractId === \"string\") return contractId.length > 0;\n\tif (Array.isArray(contractId)) return contractId.length > 0;\n\treturn false;\n}\n\n/** Camel keys declared across a prints map, plus `topic` (native payload). */\nfunction printMaterializeFromKeys(\n\tprints: PrintEventPrints | undefined,\n): string[] {\n\tconst keys = new Set<string>([\"topic\"]);\n\tif (prints) {\n\t\tfor (const fields of Object.values(prints)) {\n\t\t\tfor (const k of Object.keys(fields)) keys.add(k);\n\t\t}\n\t}\n\treturn [...keys].sort();\n}\n\nfunction refineMaterialize(\n\tname: string,\n\tfilter: SubgraphFilter,\n\tschema: SubgraphSchema,\n\tctx: z.RefinementCtx,\n): void {\n\tif (!(\"materialize\" in filter) || filter.materialize === undefined) return;\n\tconst spec = filter.materialize as MaterializeSpec;\n\tconst table = schema[spec.table];\n\tif (!table) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"sources\", name, \"materialize\", \"table\"],\n\t\t\tmessage: `materialize table \"${spec.table}\" is not in schema`,\n\t\t});\n\t\treturn;\n\t}\n\tfor (const col of Object.keys(spec.columns)) {\n\t\tif (!(col in table.columns)) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"sources\", name, \"materialize\", \"columns\", col],\n\t\t\t\tmessage: `materialize column \"${col}\" is not on schema table \"${spec.table}\"`,\n\t\t\t});\n\t\t}\n\t}\n\tif (filter.type === \"print_event\") {\n\t\tconst known = printMaterializeFromKeys(filter.prints);\n\t\tconst knownSet = new Set(known);\n\t\tfor (const [col, mapping] of Object.entries(spec.columns)) {\n\t\t\tif (!(\"from\" in mapping)) continue;\n\t\t\tif (!knownSet.has(mapping.from)) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"materialize\", \"columns\", col, \"from\"],\n\t\t\t\t\tmessage: `materialize from \"${mapping.from}\" is not a known print field — known: ${known.join(\", \")}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Deploy gates beyond the per-filter union: pinned print_event needs a\n * non-empty `prints` map, contract_call+functionName needs `abi`, and every\n * source needs a named handler, materialize, or `\"*\"`.\n */\nfunction refineDeployGates(\n\tdef: {\n\t\tsources: Record<string, SubgraphFilter>;\n\t\thandlers: Record<string, unknown>;\n\t\tschema: SubgraphSchema;\n\t},\n\tctx: z.RefinementCtx,\n): void {\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tif (filter.type === \"print_event\") {\n\t\t\t// Trait / unpinned (no contractId) may omit prints — no single schema.\n\t\t\tconst pinned = hasPinnedContractId(filter.contractId) && !filter.trait;\n\t\t\tif (pinned) {\n\t\t\t\tconst prints = filter.prints;\n\t\t\t\tif (\n\t\t\t\t\tprints === undefined ||\n\t\t\t\t\ttypeof prints !== \"object\" ||\n\t\t\t\t\tObject.keys(prints).length === 0\n\t\t\t\t) {\n\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\t\tpath: [\"sources\", name, \"prints\"],\n\t\t\t\t\t\tmessage: `print_event source \"${name}\" has no prints map — field names would be untyped and empty tables would typecheck. Declare prints from index_print_schema / create --from-contract.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (filter.type === \"contract_call\" && filter.functionName !== undefined) {\n\t\t\tif (filter.abi === undefined) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\"sources\", name, \"abi\"],\n\t\t\t\t\tmessage: `contract_call source \"${name}\" has functionName but no abi — pass a canonical ABI (normalizeAbi() from @secondlayer/stacks/clarity).`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\trefineMaterialize(name, filter, def.schema, ctx);\n\t}\n\n\tconst hasCatchAll = def.handlers[\"*\"] != null;\n\tfor (const [name, filter] of Object.entries(def.sources)) {\n\t\tconst hasMaterialize =\n\t\t\t\"materialize\" in filter && filter.materialize !== undefined;\n\t\tconst hasHandler = def.handlers[name] != null;\n\t\tif (hasMaterialize && hasHandler) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has both materialize and a handler — use one or the other`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasHandler && !hasMaterialize && !hasCatchAll) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\"handlers\", name],\n\t\t\t\tmessage: `source \"${name}\" has no handler (and no \"*\") — events will be skipped and the table stay empty.`,\n\t\t\t});\n\t\t}\n\t}\n}\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z\n\t.object({\n\t\tname: SubgraphNameSchema,\n\t\tversion: z.string().optional(),\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\t// 'concurrent' = tip-first deploy: go live at tip immediately, fill\n\t\t// history via a background backfill. Only safe for order-tolerant\n\t\t// handlers (commutative or insert-only writes).\n\t\tbackfillMode: z.enum([\"blocking\", \"concurrent\"]).optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t})\n\t.superRefine((def, ctx) => {\n\t\trefineDeployGates(\n\t\t\tdef as {\n\t\t\t\tsources: Record<string, SubgraphFilter>;\n\t\t\t\thandlers: Record<string, unknown>;\n\t\t\t\tschema: SubgraphSchema;\n\t\t\t},\n\t\t\tctx,\n\t\t);\n\t}) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition, returning the parsed result or throwing on failure.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n\n/**\n * Per-source-type field vocabulary, DERIVED from\n * {@link SubgraphFilterSchema}. Agent-facing surfaces (the MCP filters\n * reference) used to hand-maintain a parallel copy of this list; deriving it\n * means adding a field to a filter can never leave the documentation behind.\n */\nexport function filterFieldsByType(): Array<{\n\ttype: string;\n\tfields: string[];\n}> {\n\t// Read the UNION directly (SubgraphFilterSchema wraps it in superRefine).\n\t// biome-ignore lint/suspicious/noExplicitAny: reading zod's internal option shapes\n\tconst options = (SubgraphFilterUnion as any)?._def?.options ?? [];\n\tconst out: Array<{ type: string; fields: string[] }> = [];\n\tfor (const option of options) {\n\t\t// `.superRefine()` wraps the union, so unwrap one level when present.\n\t\tconst shape = option?.shape ?? option?._def?.shape;\n\t\tif (!shape) continue;\n\t\tconst literal =\n\t\t\tshape.type?._def?.values?.[0] ?? shape.type?._def?.value ?? undefined;\n\t\tif (typeof literal !== \"string\") continue;\n\t\tout.push({\n\t\t\ttype: literal,\n\t\t\tfields: Object.keys(shape).filter((k) => k !== \"type\"),\n\t\t});\n\t}\n\treturn out;\n}\n",
6
6
  "import type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { formatUnits } from \"@secondlayer/stacks/utils\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { TYPE_MAP, emitJournalDDL } from \"../schema/generator.ts\";\nimport type { ComputedValue, SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\n/** Reorg journal entries older than this many blocks are prunable — far past\n * Stacks finality (observed reorg depth is single digits). */\nexport const JOURNAL_RETENTION_BLOCKS = 300;\n\n/** Schemas whose `_journal` table existence has been ensured this process.\n * Populated only after a successful flush (a rolled-back CREATE must retry). */\nconst journalEnsured = new Set<string>();\n\ninterface WriteOp {\n\tkind: \"insert\" | \"update\" | \"delete\" | \"increment\";\n\ttable: string;\n\tdata: Record<string, unknown>;\n\t/** For update: SET clause. For increment: column → signed delta. */\n\tset?: Record<string, unknown>;\n}\n\n/**\n * One step of a flush. Most writes are a plain SQL string executed in order.\n * An increment is a PAIR the executor branches on, because closing its\n * lost-update race needs a per-statement rowcount — see\n * {@link SubgraphContext.execStatements} and the rationale on the increment\n * batch in `buildStatements`.\n */\ntype FlushStatement =\n\t| string\n\t| {\n\t\t\tkind: \"increment\";\n\t\t\t/** `UPDATE … SET c = COALESCE(c,0) + δ WHERE <key>` */\n\t\t\tupdate: string;\n\t\t\t/** `INSERT … SELECT … WHERE NOT EXISTS (<key>)` */\n\t\t\tinsert: string;\n\t\t\t/** Key predicate, for the (unreachable-by-design) error message. */\n\t\t\tkeyPred: string;\n\t\t\ttable: string;\n\t };\n\nexport interface FlushWrite {\n\top: \"insert\" | \"update\" | \"delete\";\n\ttable: string;\n\t/** Full row data (for inserts) or where+set merged (for updates). Bigints stringified. */\n\trow: Record<string, unknown>;\n\t/** Stable identifier for dedup — `{blockHeight, txId, rowIndex}` */\n\tpk: { blockHeight: number; txId: string; rowIndex: number };\n}\n\nexport interface FlushManifest {\n\tcount: number;\n\twrites: FlushWrite[];\n}\n\nimport { type ChainReadClient, createChainReadClient } from \"./chain-read.ts\";\n\nexport interface BlockMeta {\n\theight: number;\n\thash: string;\n\ttimestamp: number;\n\tburnBlockHeight: number;\n\t/**\n\t * Nakamoto StacksBlockId — the identifier `?tip=` accepts, and the only way\n\t * to pin a read-only call to THIS block. Null on rows ingested before it\n\t * was persisted; `ctx.client.readOnly` refuses to run rather than silently\n\t * reading at the node's tip.\n\t */\n\tindexBlockHash?: string | null;\n}\n\nexport interface TxMeta {\n\ttxId: string;\n\tsender: string;\n\ttype: string;\n\tstatus: string;\n\tcontractId?: string | null;\n\tfunctionName?: string | null;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n\tif (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n\t\tthrow new Error(`Invalid column name: ${name}`);\n\t}\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n *\n * Row reads (findOne/findMany) are read-your-writes: they overlay the pending\n * ops queue on the DB state, so a handler observes every write queued earlier\n * in the same block. Without this, accumulator patterns (balance = f(existing))\n * silently lose all but the last same-block delta per row (fix-f040 B1).\n * Aggregate reads (count/sum/min/max) remain pre-flush DB state.\n */\nexport class SubgraphContext {\n\treadonly block: BlockMeta;\n\tprivate _tx: TxMeta;\n\tprivate readonly db: AnyDb;\n\tprivate readonly pgSchemaName: string;\n\tprivate readonly subgraphSchema: SubgraphSchema;\n\t/** Pending writes for this block. `protected` so the in-memory test\n\t * context (`@secondlayer/subgraphs/testing`) can materialize them through\n\t * the SAME overlay this class uses — never a second implementation. */\n\tprotected readonly ops: WriteOp[] = [];\n\t/**\n\t * Record pre-images of keyed mutations into the schema's `_journal` so a\n\t * reorg can restore prior row states (fix-f040 B2). Enabled on the live\n\t * path only — deep reindex/backfill heights are past finality, and the\n\t * journal would just be churn the pruner deletes.\n\t */\n\tprivate readonly journal: boolean;\n\n\t/** Memoized per block; see the `client` getter. */\n\tprotected _client?: ChainReadClient;\n\n\tconstructor(\n\t\tdb: AnyDb,\n\t\tpgSchemaName: string,\n\t\tsubgraphSchema: SubgraphSchema,\n\t\tblock: BlockMeta,\n\t\ttx: TxMeta,\n\t\tjournal = false,\n\t) {\n\t\tthis.db = db;\n\t\tthis.pgSchemaName = pgSchemaName;\n\t\tthis.subgraphSchema = subgraphSchema;\n\t\tthis.block = block;\n\t\tthis._tx = tx;\n\t\tthis.journal = journal;\n\t}\n\n\t/**\n\t * Chain reads pinned to THIS block. Lazily built so a handler that never\n\t * reads never touches the node config, and so the in-memory test context\n\t * can override it without a node.\n\t */\n\tget client(): ChainReadClient {\n\t\tthis._client ??= createChainReadClient({\n\t\t\tblockHeight: this.block.height,\n\t\t\tindexBlockHash: this.block.indexBlockHash,\n\t\t});\n\t\treturn this._client;\n\t}\n\n\tget tx(): TxMeta {\n\t\treturn this._tx;\n\t}\n\n\t/** Update the current transaction context (used by runner between events) */\n\tsetTx(tx: TxMeta): void {\n\t\tthis._tx = tx;\n\t}\n\n\t// --- Write operations (batched) ---\n\n\tinsert(table: string, row: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({\n\t\t\tkind: \"insert\",\n\t\t\ttable,\n\t\t\tdata: { ...row, _block_height: this.block.height, _tx_id: this._tx.txId },\n\t\t});\n\t}\n\n\tupdate(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"update\", table, data: where, set });\n\t}\n\n\tupsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return;\n\t\tconst keyColumns = Object.keys(key);\n\n\t\t// Check if there's a matching uniqueKeys constraint\n\t\tconst hasUniqueConstraint = tableDef.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\n\t\tconst meta = { _block_height: this.block.height, _tx_id: this._tx.txId };\n\n\t\tif (hasUniqueConstraint) {\n\t\t\t// Use ON CONFLICT for proper upsert\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: { ...key, ...row, ...meta, _upsert_keys: keyColumns },\n\t\t\t});\n\t\t} else {\n\t\t\t// Fallback: log warning, use findOne + conditional insert/update\n\t\t\tlogger.warn(\n\t\t\t\t\"upsert called without matching uniqueKeys constraint, using fallback\",\n\t\t\t\t{\n\t\t\t\t\ttable,\n\t\t\t\t\tkeys: keyColumns,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: {\n\t\t\t\t\t...key,\n\t\t\t\t\t...row,\n\t\t\t\t\t...meta,\n\t\t\t\t\t_upsert_fallback_keys: keyColumns,\n\t\t\t\t\t_upsert_fallback_set: row,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tdelete(table: string, where: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"delete\", table, data: where });\n\t}\n\n\t/**\n\t * Atomic counter update — the blessed accumulator primitive. Compiles to\n\t * `INSERT ... ON CONFLICT (key) DO UPDATE SET col = COALESCE(t.col,0) + delta`,\n\t * so deltas commute: same-block, replayed-in-order, and concurrent updates\n\t * all land correctly without read-modify-write. Missing row inserts the\n\t * delta as the initial value. Requires a uniqueKeys constraint matching\n\t * `key`; deltas may be negative.\n\t */\n\tincrement(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\tdeltas: Record<string, bigint | number>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tconst keyColumns = Object.keys(key);\n\t\tconst hasUniqueConstraint = tableDef?.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\t\tif (!hasUniqueConstraint) {\n\t\t\tthrow new Error(\n\t\t\t\t`increment(\"${table}\") requires a uniqueKeys constraint on [${keyColumns.join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t\tfor (const [col, v] of Object.entries(deltas)) {\n\t\t\tvalidateColumnName(col);\n\t\t\tif (keyColumns.includes(col)) {\n\t\t\t\tthrow new Error(`increment(\"${table}\"): \"${col}\" is a key column`);\n\t\t\t}\n\t\t\tif (typeof v !== \"bigint\" && typeof v !== \"number\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`increment(\"${table}\"): delta for \"${col}\" must be bigint or number`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis.ops.push({\n\t\t\tkind: \"increment\",\n\t\t\ttable,\n\t\t\tdata: {\n\t\t\t\t...key,\n\t\t\t\t_block_height: this.block.height,\n\t\t\t\t_tx_id: this._tx.txId,\n\t\t\t\t_upsert_keys: keyColumns,\n\t\t\t},\n\t\t\tset: { ...deltas },\n\t\t});\n\t}\n\n\t// --- Ops checkpoint (per-event atomicity) ---\n\n\t/** Current length of the pending-ops queue. Pair with {@link rollbackTo}. */\n\topsCheckpoint(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Discard ops queued after a checkpoint. The runner wraps each handler\n\t * invocation so a thrown handler contributes nothing — without this, a\n\t * transfer handler that debited then threw flushes a one-sided debit\n\t * (fix-f040 B6).\n\t */\n\trollbackTo(checkpoint: number): void {\n\t\tif (checkpoint < 0 || checkpoint > this.ops.length) return;\n\t\tthis.ops.length = checkpoint;\n\t}\n\n\t/** Partial update — sets only specified fields, preserves everything else */\n\tpatch(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.update(table, where, set);\n\t}\n\n\t/**\n\t * Find-then-merge-or-insert. Values can be functions: (existing) => newValue.\n\t * Async because it reads existing row first.\n\t */\n\tasync patchOrInsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, ComputedValue>,\n\t): Promise<void> {\n\t\tconst existing = await this.findOne(table, key);\n\t\tconst resolved: Record<string, unknown> = {};\n\t\tfor (const [k, v] of Object.entries(row)) {\n\t\t\tresolved[k] = typeof v === \"function\" ? v(existing) : v;\n\t\t}\n\t\tthis.upsert(table, key, resolved);\n\t}\n\n\t/** Format a bigint amount with decimal places */\n\tformatUnits(value: bigint, decimals: number): string {\n\t\treturn formatUnits(value, decimals);\n\t}\n\n\t// --- Read operations (immediate) ---\n\n\t/**\n\t * Committed rows matching `where`, BEFORE the pending-ops overlay. The one\n\t * seam a different backing store replaces (the in-memory test context);\n\t * everything above it — validation, overlay, op queueing, flush semantics\n\t * — stays here so the two can't diverge.\n\t */\n\tprotected async readRows(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tlimit?: number,\n\t): Promise<Record<string, unknown>[]> {\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst { clause } = buildWhereClause(where);\n\t\tconst query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}${\n\t\t\tlimit !== undefined ? ` LIMIT ${limit}` : \"\"\n\t\t}`;\n\t\tconst { rows } = await sql.raw(query).execute(this.db);\n\t\treturn (rows as Record<string, unknown>[]).map((r) =>\n\t\t\tthis.coerceRow(table, r),\n\t\t);\n\t}\n\n\tasync findOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown> | null> {\n\t\tthis.validateTable(table);\n\t\tconst row = (await this.readRows(table, where, 1))[0] ?? null;\n\t\treturn this.overlayOne(table, where, row);\n\t}\n\n\tasync findMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown>[]> {\n\t\tthis.validateTable(table);\n\t\treturn this.overlayMany(table, where, await this.readRows(table, where));\n\t}\n\n\t// --- Pending-ops overlay (read-your-writes) ---\n\n\t/**\n\t * Replay pending ops for `table` over a single DB-read result so reads\n\t * observe earlier same-block writes. Mirrors flush semantics: upserts\n\t * merge non-key/non-meta columns, increments add deltas, updates/deletes\n\t * apply by where-match. Overlaid rows synthesized from pending inserts\n\t * lack DB-generated columns (_id, _created_at).\n\t */\n\tprotected overlayOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRow: Record<string, unknown> | null,\n\t): Record<string, unknown> | null {\n\t\tif (this.ops.length === 0) return dbRow;\n\t\tlet row = dbRow;\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\trow = this.applyOpToRow(op, row, where);\n\t\t}\n\t\treturn row;\n\t}\n\n\tprotected overlayMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRows: Record<string, unknown>[],\n\t): Record<string, unknown>[] {\n\t\tif (this.ops.length === 0) return [...dbRows];\n\t\tlet result = [...dbRows];\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\tif (op.kind === \"update\") {\n\t\t\t\tfor (let i = 0; i < result.length; i++) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked by loop condition\n\t\t\t\t\tif (rowMatches(result[i]!, op.data))\n\t\t\t\t\t\tresult[i] = { ...result[i], ...(op.set ?? {}) };\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\tresult = result.filter((r) => !rowMatches(r, op.data));\n\t\t\t} else {\n\t\t\t\t// insert / increment — merge into the keyed row, or append if the\n\t\t\t\t// new row satisfies the filter.\n\t\t\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst idx = upsertKeys\n\t\t\t\t\t? result.findIndex((r) =>\n\t\t\t\t\t\t\tupsertKeys.every((k) => valEq(r[k], clean[k])),\n\t\t\t\t\t\t)\n\t\t\t\t\t: -1;\n\t\t\t\tif (idx >= 0) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked above\n\t\t\t\t\tconst existing = result[idx]!;\n\t\t\t\t\tresult[idx] = this.applyOpToRow(op, existing, where) ?? existing;\n\t\t\t\t} else {\n\t\t\t\t\tconst created = this.applyOpToRow(op, null, where);\n\t\t\t\t\tif (created) result.push(created);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Apply one pending op to a candidate row state (null = row absent). */\n\tprotected applyOpToRow(\n\t\top: WriteOp,\n\t\trow: Record<string, unknown> | null,\n\t\twhere: Record<string, unknown>,\n\t): Record<string, unknown> | null {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst clean = stripControlKeys(op.data);\n\n\t\tswitch (op.kind) {\n\t\t\tcase \"insert\": {\n\t\t\t\tif (row) {\n\t\t\t\t\t// Same entity? Compare on the upsert key — a plain insert (no\n\t\t\t\t\t// key) can never target an existing row.\n\t\t\t\t\tif (upsertKeys?.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\t// Mirror ON CONFLICT DO UPDATE: non-key, non-meta cols only.\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [k, v] of Object.entries(clean)) {\n\t\t\t\t\t\t\tif (!upsertKeys.includes(k) && !k.startsWith(\"_\")) merged[k] = v;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\treturn rowMatches(clean, where) ? { ...clean } : null;\n\t\t\t}\n\t\t\tcase \"increment\": {\n\t\t\t\tconst deltas = op.set ?? {};\n\t\t\t\tif (row) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: increment always carries _upsert_keys\n\t\t\t\t\tif (upsertKeys!.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\t\t\tmerged[col] = toBigIntOr0(merged[col]) + toBigIntOr0(d);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\tif (!rowMatches(clean, where)) return null;\n\t\t\t\tconst created: Record<string, unknown> = { ...clean };\n\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\tcreated[col] = toBigIntOr0(d);\n\t\t\t\t}\n\t\t\t\treturn created;\n\t\t\t}\n\t\t\tcase \"update\":\n\t\t\t\treturn row && rowMatches(row, op.data)\n\t\t\t\t\t? { ...row, ...(op.set ?? {}) }\n\t\t\t\t\t: row;\n\t\t\tcase \"delete\":\n\t\t\t\treturn row && rowMatches(row, op.data) ? null : row;\n\t\t}\n\t}\n\n\t// --- Aggregate reads ---\n\n\tasync count(table: string, where?: Record<string, unknown>): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(*)::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\tasync sum(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COALESCE(SUM(\"${column}\"), 0) AS total FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn BigInt(\n\t\t\t(rows as Record<string, unknown>[])[0]?.total?.toString() ?? \"0\",\n\t\t);\n\t}\n\n\tasync min(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MIN(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync max(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MAX(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync countDistinct(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(DISTINCT \"${column}\")::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\t/** Coerce string values from Postgres back to BigInt for uint/int columns */\n\tprivate coerceRow(\n\t\ttable: string,\n\t\trow: Record<string, unknown>,\n\t): Record<string, unknown> {\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return row;\n\t\tconst result = { ...row };\n\t\tfor (const [col, def] of Object.entries(tableDef.columns)) {\n\t\t\tif (\n\t\t\t\t(def.type === \"uint\" || def.type === \"int\") &&\n\t\t\t\ttypeof result[col] === \"string\"\n\t\t\t) {\n\t\t\t\tresult[col] = BigInt(result[col] as string);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t// --- Flush ---\n\n\t/** Number of pending write operations */\n\tget pendingOps(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Execute all batched writes in a single transaction.\n\t * Auto-populates _block_height, _tx_id, _created_at on inserts.\n\t *\n\t * Returns a {@link FlushManifest} describing every write so downstream\n\t * consumers (webhook emitter) can fan out outbox rows atomically\n\t * with the flush itself.\n\t */\n\tasync flush(): Promise<FlushManifest> {\n\t\tif (this.ops.length === 0) return { count: 0, writes: [] };\n\n\t\tawait this.ensureJournalTable();\n\n\t\tconst opsToFlush = [...this.ops];\n\t\tthis.ops.length = 0;\n\n\t\tconst statements = this.buildStatements(opsToFlush);\n\n\t\tif (\"isTransaction\" in this.db) {\n\t\t\tawait this.execStatements(this.db, statements);\n\t\t} else {\n\t\t\tawait (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n\t\t\t\tawait this.execStatements(tx, statements);\n\t\t\t});\n\t\t}\n\n\t\tconst writes: FlushWrite[] = opsToFlush.map((op, rowIndex) => {\n\t\t\tconst blockHeight =\n\t\t\t\t(op.data._block_height as number | undefined) ?? this.block.height;\n\t\t\tconst txId = (op.data._tx_id as string | undefined) ?? this._tx.txId;\n\t\t\tconst baseRow =\n\t\t\t\top.kind === \"update\" || op.kind === \"increment\"\n\t\t\t\t\t? { ...op.data, ...(op.set ?? {}) }\n\t\t\t\t\t: { ...op.data };\n\t\t\t// Strip upsert control keys — not part of the row shape\n\t\t\t(baseRow as Record<string, unknown>)._upsert_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_set = undefined;\n\t\t\treturn {\n\t\t\t\t// Increments surface as \"updated\" to subscribers — the row payload\n\t\t\t\t// carries the key + the applied delta, not the absolute value.\n\t\t\t\top: op.kind === \"increment\" ? \"update\" : op.kind,\n\t\t\t\ttable: op.table,\n\t\t\t\trow: jsonSafe(baseRow),\n\t\t\t\tpk: { blockHeight, txId, rowIndex },\n\t\t\t};\n\t\t});\n\n\t\treturn { count: opsToFlush.length, writes };\n\t}\n\n\t/**\n\t * Run a built statement list on an open transaction.\n\t *\n\t * Plain statements run in order. An increment runs UPDATE-first and then,\n\t * ONLY if that matched nothing, the guarded INSERT — and if the INSERT also\n\t * wrote nothing, the UPDATE again.\n\t *\n\t * That last step is the whole point. Under READ COMMITTED, two block\n\t * transactions flushing the same key while the row is absent both see\n\t * `UPDATE → 0 rows`; the first commits its INSERT, and the second's\n\t * `WHERE NOT EXISTS` then sees that committed row and inserts nothing. No\n\t * error, no constraint violation — the second delta was simply dropped.\n\t * Re-running the UPDATE takes a fresh snapshot that DOES see the winner's\n\t * row and applies the delta onto it.\n\t *\n\t * It cannot double-apply: the retry is reached only when the first UPDATE\n\t * matched no row AND the INSERT wrote no row, so the delta has not been\n\t * applied by either.\n\t */\n\tprivate async execStatements(\n\t\texecutor: AnyDb,\n\t\tstatements: FlushStatement[],\n\t): Promise<void> {\n\t\tconst affected = (r: { numAffectedRows?: bigint }): bigint =>\n\t\t\tr.numAffectedRows ?? 0n;\n\n\t\tfor (const stmt of statements) {\n\t\t\tif (typeof stmt === \"string\") {\n\t\t\t\tawait sql.raw(stmt).execute(executor);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst updated = await sql.raw(stmt.update).execute(executor);\n\t\t\tif (affected(updated) > 0n) continue;\n\n\t\t\tconst inserted = await sql.raw(stmt.insert).execute(executor);\n\t\t\tif (affected(inserted) > 0n) continue;\n\n\t\t\tconst retried = await sql.raw(stmt.update).execute(executor);\n\t\t\tif (affected(retried) === 0n) {\n\t\t\t\t// Neither wrote: the row a concurrent writer created was gone again\n\t\t\t\t// by the retry (a delete raced in). Fail loudly — silently dropping\n\t\t\t\t// the delta is the bug this whole path exists to prevent. The block\n\t\t\t\t// transaction rolls back and the walk re-processes it.\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`increment could not be applied to ${this.pgSchemaName}.${stmt.table} where ${stmt.keyPred}: row neither updated nor inserted`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Prepare a single insert row, returning its data, columns, upsert key for batching. */\n\tprivate prepareInsert(op: WriteOp): {\n\t\tdata: Record<string, unknown>;\n\t\tcols: string[];\n\t\tvals: string[];\n\t\tupsertKeys: string[] | undefined;\n\t\tbatchKey: string;\n\t} {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst data = { ...op.data };\n\t\t// biome-ignore lint/performance/noDelete: must remove key, not set undefined — Object.keys must not include these\n\t\tdelete data._upsert_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_set;\n\n\t\t// _block_height and _tx_id are captured at insert/upsert time (not flush time)\n\t\t// to ensure correct tx attribution when multiple txs are batched per block\n\t\tif (!data._block_height) data._block_height = this.block.height;\n\t\tif (!data._tx_id) data._tx_id = this._tx.txId;\n\t\tdata._created_at = \"NOW()\";\n\n\t\tconst cols = Object.keys(data);\n\t\tcols.forEach(validateColumnName);\n\t\tconst vals = cols.map((c) =>\n\t\t\tdata[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n\t\t);\n\n\t\t// Batch key: table + sorted columns + upsert key signature (spread to avoid mutating cols)\n\t\tconst batchKey = `${op.table}:${[...cols].sort().join(\",\")}:${upsertKeys ? [...upsertKeys].sort().join(\",\") : \"\"}`;\n\n\t\treturn { data, cols, vals, upsertKeys, batchKey };\n\t}\n\n\t/**\n\t * Lazily create `_journal` for schemas deployed before it existed. Cached\n\t * per process only once CONFIRMED present (to_regclass) — a CREATE issued\n\t * inside a block tx could roll back with it, so self-created tables are\n\t * re-verified on the next flush instead of trusted.\n\t */\n\tprivate async ensureJournalTable(): Promise<void> {\n\t\tif (!this.journal || journalEnsured.has(this.pgSchemaName)) return;\n\t\tconst { rows } = await sql\n\t\t\t.raw(`SELECT to_regclass('\"${this.pgSchemaName}\".\"_journal\"') AS r`)\n\t\t\t.execute(this.db);\n\t\tif ((rows as { r: unknown }[])[0]?.r) {\n\t\t\tjournalEnsured.add(this.pgSchemaName);\n\t\t\treturn;\n\t\t}\n\t\t// Schema names are generator-produced lowercase identifiers, so the\n\t\t// unquoted form emitJournalDDL emits is safe.\n\t\tfor (const stmt of emitJournalDDL(this.pgSchemaName)) {\n\t\t\tawait sql.raw(stmt).execute(this.db);\n\t\t}\n\t}\n\n\t/** SQL type of a user column (for casting journal key VALUES), if known. */\n\tprivate columnSqlType(table: string, col: string): string | undefined {\n\t\tconst def = this.subgraphSchema[table]?.columns?.[col];\n\t\treturn def ? TYPE_MAP[def.type] : undefined;\n\t}\n\n\t/**\n\t * Journal pre-images for a keyed batch: one `_journal` row per key with the\n\t * row's current state (`prev_row`), or NULL when the key doesn't exist yet\n\t * (the mutation will create it — a revert deletes it). Emitted BEFORE the\n\t * mutation statement, same transaction.\n\t */\n\tprivate journalCaptureSQL(\n\t\ttable: string,\n\t\tkeyCols: string[],\n\t\t/** One escaped-literal tuple per key, ordered like keyCols. */\n\t\tkeyLiteralRows: string[][],\n\t): string {\n\t\tconst cast = (col: string, expr: string) => {\n\t\t\tconst t = this.columnSqlType(table, col);\n\t\t\treturn t ? `CAST(${expr} AS ${t})` : expr;\n\t\t};\n\t\tconst keyObj = keyCols\n\t\t\t.map((k) => `'${k}', ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\", \");\n\t\tconst joinCond = keyCols\n\t\t\t.map((k) => `t.\"${k}\" = ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\" AND \");\n\t\tconst valuesList = keyLiteralRows\n\t\t\t.map((r) => `(${r.join(\", \")})`)\n\t\t\t.join(\", \");\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object(${keyObj}), to_jsonb(t.*) ` +\n\t\t\t`FROM (VALUES ${valuesList}) AS v(${keyCols.map((k) => `\"${k}\"`).join(\", \")}) ` +\n\t\t\t`LEFT JOIN \"${this.pgSchemaName}\".\"${table}\" t ON ${joinCond}`\n\t\t);\n\t}\n\n\t/** Journal pre-images of rows a where-clause mutation will touch, keyed by `_id`. */\n\tprivate journalCaptureByWhereSQL(table: string, clause: string): string {\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object('_id', t.\"_id\"), to_jsonb(t.*) ` +\n\t\t\t`FROM \"${this.pgSchemaName}\".\"${table}\" t WHERE ${clause}`\n\t\t);\n\t}\n\n\t/** Build SQL statements from write ops, batching compatible INSERTs. */\n\tprivate buildStatements(ops: WriteOp[]): FlushStatement[] {\n\t\tconst statements: FlushStatement[] = [];\n\n\t\t// Group consecutive inserts by batch key\n\t\ttype InsertBatch = {\n\t\t\ttable: string;\n\t\t\tcols: string[];\n\t\t\trows: string[][];\n\t\t\tupsertKeys: string[] | undefined;\n\t\t};\n\n\t\t// Consecutive increments on the same (table, key cols, delta cols)\n\t\t// coalesce: same-key deltas SUM (they commute), then compile to one\n\t\t// multi-row INSERT ... ON CONFLICT DO UPDATE SET c = COALESCE(c,0)+EXCLUDED.c.\n\t\ttype IncrementBatch = {\n\t\t\ttable: string;\n\t\t\tkeyCols: string[];\n\t\t\tdeltaCols: string[];\n\t\t\t/** key signature → { key values, summed deltas, insert-time meta } */\n\t\t\trows: Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\tkeys: Record<string, unknown>;\n\t\t\t\t\tdeltas: Record<string, bigint>;\n\t\t\t\t\tmeta: { blockHeight: unknown; txId: unknown };\n\t\t\t\t}\n\t\t\t>;\n\t\t};\n\n\t\tlet currentBatch: InsertBatch | null = null;\n\t\tlet currentBatchKey = \"\";\n\t\tlet incBatch: IncrementBatch | null = null;\n\t\tlet incBatchKey = \"\";\n\n\t\tconst flushIncrementBatch = () => {\n\t\t\tif (!incBatch) return;\n\t\t\tconst batch = incBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst cols = [\n\t\t\t\t...batch.keyCols,\n\t\t\t\t...batch.deltaCols,\n\t\t\t\t\"_block_height\",\n\t\t\t\t\"_tx_id\",\n\t\t\t\t\"_created_at\",\n\t\t\t];\n\t\t\tif (this.journal) {\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tbatch.keyCols,\n\t\t\t\t\t\tArray.from(batch.rows.values()).map((r) =>\n\t\t\t\t\t\t\tbatch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// NOT insert-on-conflict: Postgres validates the PROPOSED insert\n\t\t\t// tuple against CHECK constraints BEFORE conflict arbitration, so a\n\t\t\t// negative delta against an EXISTING row (every debit on a uint\n\t\t\t// balance) errors even though DO UPDATE would produce a legal value\n\t\t\t// (prod halts at sbtc 341445 / usdcx 5269728; empirically verified).\n\t\t\t// UPDATE-first lets the CHECK see the FINAL value; the guarded\n\t\t\t// INSERT covers missing rows — where a negative delta is a GENUINE\n\t\t\t// violation and must still fail loudly.\n\t\t\t//\n\t\t\t// The pair is emitted as ONE step rather than two statements because\n\t\t\t// the executor must branch on their rowcounts: an INSERT that wrote\n\t\t\t// nothing means a concurrent transaction created the row after our\n\t\t\t// UPDATE missed it, and the delta has to be re-applied instead of\n\t\t\t// silently dropped. See `execStatements`.\n\t\t\tfor (const r of batch.rows.values()) {\n\t\t\t\tconst keyPred = batch.keyCols\n\t\t\t\t\t.map((k) => `\"${k}\" = ${escapeLiteral(r.keys[k])}`)\n\t\t\t\t\t.join(\" AND \");\n\t\t\t\tconst updSet = batch.deltaCols\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(c) =>\n\t\t\t\t\t\t\t`\"${c}\" = COALESCE(\"${c}\", 0) + (${String(r.deltas[c] ?? 0n)})`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tconst insertVals = [\n\t\t\t\t\t...batch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t...batch.deltaCols.map((c) => String(r.deltas[c] ?? 0n)),\n\t\t\t\t\tescapeLiteral(r.meta.blockHeight),\n\t\t\t\t\tescapeLiteral(r.meta.txId),\n\t\t\t\t\t\"NOW()\",\n\t\t\t\t];\n\t\t\t\tstatements.push({\n\t\t\t\t\tkind: \"increment\",\n\t\t\t\t\ttable: batch.table,\n\t\t\t\t\tkeyPred,\n\t\t\t\t\tupdate: `UPDATE ${qualifiedTable} SET ${updSet} WHERE ${keyPred}`,\n\t\t\t\t\tinsert:\n\t\t\t\t\t\t`INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) ` +\n\t\t\t\t\t\t`SELECT ${insertVals.join(\", \")} ` +\n\t\t\t\t\t\t`WHERE NOT EXISTS (SELECT 1 FROM ${qualifiedTable} WHERE ${keyPred})`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tincBatch = null;\n\t\t\tincBatchKey = \"\";\n\t\t};\n\n\t\tconst flushInsertBatch = () => {\n\t\t\tif (!currentBatch) return;\n\t\t\tconst batch = currentBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst colList = batch.cols.map((c) => `\"${c}\"`).join(\", \");\n\n\t\t\t// Deduplicate by upsert key — last row wins (Postgres rejects duplicate keys in one INSERT)\n\t\t\tlet rows = batch.rows;\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tconst seen = new Map<string, number>();\n\t\t\t\tfor (let i = 0; i < rows.length; i++) {\n\t\t\t\t\tconst key = keyIndices.map((ki) => rows[i][ki]).join(\"\\0\");\n\t\t\t\t\tseen.set(key, i);\n\t\t\t\t}\n\t\t\t\tif (seen.size < rows.length) {\n\t\t\t\t\trows = Array.from(seen.values()).map((i) => rows[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst valuesList = rows.map((r) => `(${r.join(\", \")})`).join(\", \");\n\t\t\tlet stmt = `INSERT INTO ${qualifiedTable} (${colList}) VALUES ${valuesList}`;\n\n\t\t\t// Plain inserts are append-only (revert = delete by _block_height);\n\t\t\t// only keyed upserts can overwrite state worth journaling.\n\t\t\tif (this.journal && batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tuKeys,\n\t\t\t\t\t\trows.map((r) => keyIndices.map((ki) => r[ki])),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst batchKeys = batch.upsertKeys;\n\t\t\t\tconst updateCols = batch.cols.filter(\n\t\t\t\t\t(c) => !batchKeys.includes(c) && !c.startsWith(\"_\"),\n\t\t\t\t);\n\t\t\t\tif (updateCols.length > 0) {\n\t\t\t\t\tconst setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n\t\t\t\t} else {\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.push(stmt);\n\t\t\tcurrentBatch = null;\n\t\t\tcurrentBatchKey = \"\";\n\t\t};\n\n\t\tfor (const op of ops) {\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n\t\t\tif (op.kind === \"insert\") {\n\t\t\t\tflushIncrementBatch();\n\t\t\t\tconst { cols, vals, upsertKeys, batchKey } = this.prepareInsert(op);\n\n\t\t\t\tif (batchKey === currentBatchKey && currentBatch) {\n\t\t\t\t\t// Same table + columns + upsert key — append to batch\n\t\t\t\t\tcurrentBatch.rows.push(vals);\n\t\t\t\t} else {\n\t\t\t\t\t// Different batch — flush previous and start new\n\t\t\t\t\tflushInsertBatch();\n\t\t\t\t\tcurrentBatch = { table: op.table, cols, rows: [vals], upsertKeys };\n\t\t\t\t\tcurrentBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"increment\") {\n\t\t\t\tflushInsertBatch();\n\t\t\t\tconst keyCols = [...(op.data._upsert_keys as string[])].sort();\n\t\t\t\tconst deltaCols = Object.keys(op.set ?? {}).sort();\n\t\t\t\tconst batchKey = `inc:${op.table}:${keyCols.join(\",\")}:${deltaCols.join(\",\")}`;\n\t\t\t\tif (batchKey !== incBatchKey || !incBatch) {\n\t\t\t\t\tflushIncrementBatch();\n\t\t\t\t\tincBatch = { table: op.table, keyCols, deltaCols, rows: new Map() };\n\t\t\t\t\tincBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst keySig = keyCols.map((k) => escapeLiteral(clean[k])).join(\"\\0\");\n\t\t\t\tconst existing = incBatch.rows.get(keySig);\n\t\t\t\tif (existing) {\n\t\t\t\t\tfor (const c of deltaCols) {\n\t\t\t\t\t\texisting.deltas[c] =\n\t\t\t\t\t\t\t(existing.deltas[c] ?? 0n) + toBigIntOr0(op.set?.[c]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst deltas: Record<string, bigint> = {};\n\t\t\t\t\tfor (const c of deltaCols) deltas[c] = toBigIntOr0(op.set?.[c]);\n\t\t\t\t\tincBatch.rows.set(keySig, {\n\t\t\t\t\t\tkeys: clean,\n\t\t\t\t\t\tdeltas,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\tblockHeight: op.data._block_height ?? this.block.height,\n\t\t\t\t\t\t\ttxId: op.data._tx_id ?? this._tx.txId,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Non-insert — flush any pending batches first\n\t\t\t\tflushInsertBatch();\n\t\t\t\tflushIncrementBatch();\n\n\t\t\t\tif (op.kind === \"update\") {\n\t\t\t\t\tconst setEntries = Object.entries(op.set ?? {});\n\t\t\t\t\tfor (const [k] of setEntries) validateColumnName(k);\n\t\t\t\t\tconst setClauses = setEntries.map(\n\t\t\t\t\t\t([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n\t\t\t\t\t);\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t`UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n\t\t\t\t\t);\n\t\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Flush any remaining batches\n\t\tflushInsertBatch();\n\t\tflushIncrementBatch();\n\n\t\treturn statements;\n\t}\n\n\tprivate validateTable(table: string): void {\n\t\tif (!this.subgraphSchema[table]) {\n\t\t\tthrow new Error(\n\t\t\t\t`Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// --- Helpers ---\n\n/** Drop internal upsert control keys from an op's data. */\nfunction stripControlKeys(\n\tdata: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst {\n\t\t_upsert_keys: _a,\n\t\t_upsert_fallback_keys: _b,\n\t\t_upsert_fallback_set: _c,\n\t\t...clean\n\t} = data;\n\treturn clean;\n}\n\n/** Loose value equality across bigint/number/string representations. */\nfunction valEq(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (a == null || b == null) return false;\n\treturn String(a) === String(b);\n}\n\n/** Does `row` satisfy every column constraint in `where`? */\nfunction rowMatches(\n\trow: Record<string, unknown>,\n\twhere: Record<string, unknown>,\n): boolean {\n\treturn Object.entries(where).every(([k, v]) => valEq(row[k], v));\n}\n\nfunction toBigIntOr0(v: unknown): bigint {\n\tif (typeof v === \"bigint\") return v;\n\tif (v == null) return 0n;\n\ttry {\n\t\treturn BigInt(String(v));\n\t} catch {\n\t\treturn 0n;\n\t}\n}\n\n/** Coerce a row for JSON serialization — bigints become strings. */\nfunction jsonSafe(row: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(row)) {\n\t\tout[k] = typeof v === \"bigint\" ? v.toString() : v;\n\t}\n\treturn out;\n}\n\nfunction escapeLiteral(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\tif (typeof value === \"object\")\n\t\treturn `'${JSON.stringify(value, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v)).replace(/'/g, \"''\")}'::jsonb`;\n\t// String — escape single quotes\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n\tclause: string;\n\tvalues: unknown[];\n} {\n\tconst entries = Object.entries(where);\n\tif (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n\tfor (const [k] of entries) validateColumnName(k);\n\tconst parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n\treturn { clause: parts.join(\" AND \"), values: [] };\n}\n",
7
- "import { createHash } from \"node:crypto\";\nimport type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pgSchemaName, quotePgIdent } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n\ttext: \"TEXT\",\n\tuint: \"NUMERIC\",\n\tint: \"NUMERIC\",\n\tprincipal: \"TEXT\",\n\tboolean: \"BOOLEAN\",\n\ttimestamp: \"TIMESTAMPTZ\",\n\tjsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n\tstatements: string[];\n\thash: string;\n}\n\n// Postgres truncates identifiers over 63 bytes. schema/table/column names are\n// each individually capped at 63 (SqlIdentifierSchema / SubgraphNameSchema),\n// but concatenated (`idx_<schema>_<table>_<col>_id`, plus an optional\n// account-scoped schema prefix) they can exceed that — two different columns\n// could then truncate to the same name and silently collide on CREATE INDEX.\n// Route the sort-composite name through here: short names pass through\n// unchanged (human-readable, matches the single-column naming style); an\n// oversized name is truncated and given a content hash suffix so it can't\n// collide with a different oversized name that happens to share a prefix.\nconst MAX_IDENT_BYTES = 63;\nfunction safeIndexName(name: string): string {\n\tif (name.length <= MAX_IDENT_BYTES) return name;\n\tconst hash = createHash(\"sha256\").update(name).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_IDENT_BYTES - hash.length - 1)}_${hash}`;\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/** True if any column on the table uses full-text `search` (needs the pg_trgm\n * extension before its GIN index can be created). */\nexport function tableNeedsTrgm(tableDef: SubgraphTable): boolean {\n\treturn Object.values(tableDef.columns).some((col) => col.search);\n}\n\n/**\n * All per-table DDL for ONE table — create + meta/user/composite indexes + UNIQUE\n * constraints (NOT foreign keys; see {@link emitForeignKeyDDL}, emitted in a\n * second pass once every referenced table exists). Single-sourced so the full\n * generator and the deployer's additive-create path can't drift — a missing\n * UNIQUE or DEFAULT here would make a handler `upsert ON CONFLICT` fail at runtime.\n */\nexport function emitTableDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\tconst qualifiedName = `${quotePgIdent(schemaName)}.${quotePgIdent(tableName)}`;\n\tconst statements: string[] = [];\n\n\tconst columnDefs: string[] = [\n\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t];\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tconst sqlType = TYPE_MAP[col.type];\n\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\tlet colDef = `${quotePgIdent(colName)} ${sqlType}${nullable}`;\n\t\tif (col.default !== undefined) {\n\t\t\tcolDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n\t\t}\n\t\t// uint is unsigned by definition — fail loudly instead of silently\n\t\t// storing a negative (fix-f040 B4). Handlers run in chain order, so a\n\t\t// legitimate same-block receive-then-spend never trips this.\n\t\tif (col.type === \"uint\") {\n\t\t\tcolDef += ` CHECK (${quotePgIdent(colName)} >= 0)`;\n\t\t}\n\t\tcolumnDefs.push(colDef);\n\t}\n\tstatements.push(\n\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n\t);\n\n\t// Auto-indexes on meta columns.\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_block_height`)} ON ${qualifiedName} (_block_height)`,\n\t);\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_tx_id`)} ON ${qualifiedName} (_tx_id)`,\n\t);\n\n\t// Single-column indexes, plus a composite `(col, \"_id\")` sort index.\n\t// `/v1`'s `?_sort=<col>&_order=` keyset predicate compares `(col, \"_id\")`\n\t// and orders by `col, \"_id\"` — a composite index matches that exactly, so\n\t// deep pages on a low-cardinality column become an index-only scan instead\n\t// of a Filter/re-sort within each value group. The single-column index\n\t// stays too: it still serves plain equality filters (`?col=value`).\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.indexed) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_${colName}`)} ON ${qualifiedName} (${quotePgIdent(colName)})`,\n\t\t\t);\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(safeIndexName(`idx_${schemaName}_${tableName}_${colName}_id`))} ON ${qualifiedName} (${quotePgIdent(colName)}, ${quotePgIdent(\"_id\")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Trigram GIN indexes for search columns.\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.search) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_${colName}_trgm`)} ON ${qualifiedName} USING gin (${quotePgIdent(colName)} gin_trgm_ops)`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Composite indexes.\n\tif (tableDef.indexes) {\n\t\tfor (let i = 0; i < tableDef.indexes.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.indexes[i]!;\n\t\t\tconst idxName = quotePgIdent(\n\t\t\t\t`idx_${schemaName}_${tableName}_composite_${i}`,\n\t\t\t);\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.map(quotePgIdent).join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Unique constraints (required for upsert ON CONFLICT).\n\tif (tableDef.uniqueKeys) {\n\t\tfor (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.uniqueKeys[i]!;\n\t\t\tconst constraintName = quotePgIdent(\n\t\t\t\t`uq_${schemaName}_${tableName}_${cols.join(\"_\")}`,\n\t\t\t);\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.map(quotePgIdent).join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn statements;\n}\n\n/**\n * Per-schema revert journal. Before every keyed mutation (upsert / increment /\n * update / delete) the flush records the row's prior state; a reorg restores\n * those states instead of deleting whole rows by `_block_height` — which is\n * only correct for append-only tables, not accumulators (fix-f040 B2).\n * `prev_row IS NULL` marks a row first created by the journaled op.\n */\nexport function emitJournalDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._journal (\n _jid BIGSERIAL PRIMARY KEY,\n block_height BIGINT NOT NULL,\n table_name TEXT NOT NULL,\n row_key JSONB NOT NULL,\n prev_row JSONB,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_journal_height ON ${schemaName}._journal (block_height)`,\n\t];\n}\n\n/**\n * Storage for factory-discovered addresses.\n *\n * `block_height` is what makes the set reorg-scoped: the reorg handler\n * deletes rows at or above the fork alongside the data tables, so an address\n * revealed on an orphaned chain does not linger in the matcher forever\n * (the failure mode a set kept outside the rollback model would have).\n */\nexport function emitFactoryDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._factory_addresses (\n source_name TEXT NOT NULL,\n address TEXT NOT NULL,\n block_height BIGINT NOT NULL,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n PRIMARY KEY (source_name, address)\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_factory_height ON ${schemaName}._factory_addresses (block_height)`,\n\t];\n}\n\n/** Foreign-key DDL for one table's relations. Emit AFTER every referenced table\n * exists; references require the target columns to be a UNIQUE key. */\nexport function emitForeignKeyDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\treturn (tableDef.relations ?? []).map((rel) => {\n\t\tconst constraintName = quotePgIdent(\n\t\t\t`fk_${schemaName}_${tableName}_${rel.name}`,\n\t\t);\n\t\treturn (\n\t\t\t`ALTER TABLE ${quotePgIdent(schemaName)}.${quotePgIdent(tableName)} ADD CONSTRAINT ${constraintName} ` +\n\t\t\t`FOREIGN KEY (${rel.fields.map(quotePgIdent).join(\", \")}) ` +\n\t\t\t`REFERENCES ${quotePgIdent(schemaName)}.${quotePgIdent(rel.references)} (${rel.referencedColumns.map(quotePgIdent).join(\", \")})`\n\t\t);\n\t});\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(\n\tdef: SubgraphDefinition,\n\tschemaNameOverride?: string,\n): GeneratedSQL {\n\tconst schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n\tconst statements: string[] = [];\n\n\t// Check if any column uses search (trigram)\n\tconst needsTrgm = Object.values(def.schema).some((table) =>\n\t\tObject.values(table.columns).some((col) => col.search),\n\t);\n\n\tif (needsTrgm) {\n\t\tstatements.push(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\");\n\t}\n\n\t// Schema namespace\n\tstatements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n\t// One table per schema entry (single-sourced per-table DDL).\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitTableDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Revert journal (one per schema) — see emitJournalDDL.\n\tstatements.push(...emitJournalDDL(schemaName));\n\t// Only when a source actually uses a factory — no dead table otherwise.\n\tif (\n\t\tObject.values(def.sources ?? {}).some(\n\t\t\t(src) => (src as { factory?: unknown }).factory !== undefined,\n\t\t)\n\t) {\n\t\tstatements.push(...emitFactoryDDL(schemaName));\n\t}\n\n\t// Foreign keys are added in a second pass so every referenced table exists.\n\t// These mirror the ORM relations emitted by the codegen (no drift) and require\n\t// the referenced columns to be a UNIQUE key on the target table.\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitForeignKeyDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Hash based on schema structure only — version intentionally excluded\n\t// so server-managed version bumps don't look like schema changes\n\tconst hashInput = JSON.stringify(\n\t\t{\n\t\t\tname: def.name,\n\t\t\tschema: def.schema,\n\t\t\tsources: def.sources,\n\t\t},\n\t\t(_key, value) => (typeof value === \"bigint\" ? value.toString() : value),\n\t);\n\t// node crypto (not Bun.hash) so the published node-runtime `sl` CLI can\n\t// compute schema hashes too (e.g. `sl subgraphs spec`).\n\tconst hash = createHash(\"sha256\").update(hashInput).digest(\"hex\");\n\n\treturn { statements, hash };\n}\n",
7
+ "import { createHash } from \"node:crypto\";\nimport type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pgSchemaName, quotePgIdent } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n\ttext: \"TEXT\",\n\tuint: \"NUMERIC\",\n\tint: \"NUMERIC\",\n\tprincipal: \"TEXT\",\n\tboolean: \"BOOLEAN\",\n\ttimestamp: \"TIMESTAMPTZ\",\n\tjsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n\tstatements: string[];\n\thash: string;\n}\n\n// Postgres truncates identifiers over 63 bytes. schema/table/column names are\n// each individually capped at 63 (SqlIdentifierSchema / SubgraphNameSchema),\n// but concatenated (`idx_<schema>_<table>_<col>_id`, plus an optional\n// account-scoped schema prefix) they can exceed that — two different columns\n// could then truncate to the same name and silently collide on CREATE INDEX.\n// Route the sort-composite name through here: short names pass through\n// unchanged (human-readable, matches the single-column naming style); an\n// oversized name is truncated and given a content hash suffix so it can't\n// collide with a different oversized name that happens to share a prefix.\nconst MAX_IDENT_BYTES = 63;\nfunction safeIndexName(name: string): string {\n\tif (name.length <= MAX_IDENT_BYTES) return name;\n\tconst hash = createHash(\"sha256\").update(name).digest(\"hex\").slice(0, 8);\n\treturn `${name.slice(0, MAX_IDENT_BYTES - hash.length - 1)}_${hash}`;\n}\n\n/**\n * Plain equality index + `/v1` keyset composite `(col, _id)` for one\n * `indexed` column. Single source for {@link emitTableDDL} and additive\n * deploy — a missing composite on the add/flag-flip path made deep\n * `?_sort=` pages Filter/re-sort instead of an index-only scan.\n */\nexport function emitIndexedColumnIndexDDL(\n\tschemaName: string,\n\ttableName: string,\n\tcolName: string,\n\topts?: { concurrently?: boolean },\n): { create: string[]; drop: string[] } {\n\tconst concurrently = opts?.concurrently ? \" CONCURRENTLY\" : \"\";\n\tconst qualified = `${quotePgIdent(schemaName)}.${quotePgIdent(tableName)}`;\n\tconst plain = `idx_${schemaName}_${tableName}_${colName}`;\n\tconst composite = safeIndexName(\n\t\t`idx_${schemaName}_${tableName}_${colName}_id`,\n\t);\n\tconst col = quotePgIdent(colName);\n\tconst id = quotePgIdent(\"_id\");\n\treturn {\n\t\tcreate: [\n\t\t\t`CREATE INDEX${concurrently} IF NOT EXISTS ${quotePgIdent(plain)} ON ${qualified} (${col})`,\n\t\t\t`CREATE INDEX${concurrently} IF NOT EXISTS ${quotePgIdent(composite)} ON ${qualified} (${col}, ${id})`,\n\t\t],\n\t\tdrop: [\n\t\t\t`DROP INDEX${concurrently} IF EXISTS ${quotePgIdent(schemaName)}.${quotePgIdent(plain)}`,\n\t\t\t`DROP INDEX${concurrently} IF EXISTS ${quotePgIdent(schemaName)}.${quotePgIdent(composite)}`,\n\t\t],\n\t};\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/** True if any column on the table uses full-text `search` (needs the pg_trgm\n * extension before its GIN index can be created). */\nexport function tableNeedsTrgm(tableDef: SubgraphTable): boolean {\n\treturn Object.values(tableDef.columns).some((col) => col.search);\n}\n\n/**\n * All per-table DDL for ONE table — create + meta/user/composite indexes + UNIQUE\n * constraints (NOT foreign keys; see {@link emitForeignKeyDDL}, emitted in a\n * second pass once every referenced table exists). Single-sourced so the full\n * generator and the deployer's additive-create path can't drift — a missing\n * UNIQUE or DEFAULT here would make a handler `upsert ON CONFLICT` fail at runtime.\n */\nexport function emitTableDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\tconst qualifiedName = `${quotePgIdent(schemaName)}.${quotePgIdent(tableName)}`;\n\tconst statements: string[] = [];\n\n\tconst columnDefs: string[] = [\n\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t];\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tconst sqlType = TYPE_MAP[col.type];\n\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\tlet colDef = `${quotePgIdent(colName)} ${sqlType}${nullable}`;\n\t\tif (col.default !== undefined) {\n\t\t\tcolDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n\t\t}\n\t\t// uint is unsigned by definition — fail loudly instead of silently\n\t\t// storing a negative (fix-f040 B4). Handlers run in chain order, so a\n\t\t// legitimate same-block receive-then-spend never trips this.\n\t\tif (col.type === \"uint\") {\n\t\t\tcolDef += ` CHECK (${quotePgIdent(colName)} >= 0)`;\n\t\t}\n\t\tcolumnDefs.push(colDef);\n\t}\n\tstatements.push(\n\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n\t);\n\n\t// Auto-indexes on meta columns.\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_block_height`)} ON ${qualifiedName} (_block_height)`,\n\t);\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_tx_id`)} ON ${qualifiedName} (_tx_id)`,\n\t);\n\n\t// Single-column indexes, plus a composite `(col, \"_id\")` sort index.\n\t// `/v1`'s `?_sort=<col>&_order=` keyset predicate compares `(col, \"_id\")`\n\t// and orders by `col, \"_id\"` — a composite index matches that exactly, so\n\t// deep pages on a low-cardinality column become an index-only scan instead\n\t// of a Filter/re-sort within each value group. The single-column index\n\t// stays too: it still serves plain equality filters (`?col=value`).\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.indexed) {\n\t\t\tstatements.push(\n\t\t\t\t...emitIndexedColumnIndexDDL(schemaName, tableName, colName).create,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Trigram GIN indexes for search columns.\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.search) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_${colName}_trgm`)} ON ${qualifiedName} USING gin (${quotePgIdent(colName)} gin_trgm_ops)`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Composite indexes.\n\tif (tableDef.indexes) {\n\t\tfor (let i = 0; i < tableDef.indexes.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.indexes[i]!;\n\t\t\tconst idxName = quotePgIdent(\n\t\t\t\t`idx_${schemaName}_${tableName}_composite_${i}`,\n\t\t\t);\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.map(quotePgIdent).join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Unique constraints (required for upsert ON CONFLICT).\n\tif (tableDef.uniqueKeys) {\n\t\tfor (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.uniqueKeys[i]!;\n\t\t\tconst constraintName = quotePgIdent(\n\t\t\t\t`uq_${schemaName}_${tableName}_${cols.join(\"_\")}`,\n\t\t\t);\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.map(quotePgIdent).join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn statements;\n}\n\n/**\n * Per-schema revert journal. Before every keyed mutation (upsert / increment /\n * update / delete) the flush records the row's prior state; a reorg restores\n * those states instead of deleting whole rows by `_block_height` — which is\n * only correct for append-only tables, not accumulators (fix-f040 B2).\n * `prev_row IS NULL` marks a row first created by the journaled op.\n */\nexport function emitJournalDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._journal (\n _jid BIGSERIAL PRIMARY KEY,\n block_height BIGINT NOT NULL,\n table_name TEXT NOT NULL,\n row_key JSONB NOT NULL,\n prev_row JSONB,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_journal_height ON ${schemaName}._journal (block_height)`,\n\t];\n}\n\n/**\n * Storage for factory-discovered addresses.\n *\n * `block_height` is what makes the set reorg-scoped: the reorg handler\n * deletes rows at or above the fork alongside the data tables, so an address\n * revealed on an orphaned chain does not linger in the matcher forever\n * (the failure mode a set kept outside the rollback model would have).\n */\nexport function emitFactoryDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._factory_addresses (\n source_name TEXT NOT NULL,\n address TEXT NOT NULL,\n block_height BIGINT NOT NULL,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n PRIMARY KEY (source_name, address)\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_factory_height ON ${schemaName}._factory_addresses (block_height)`,\n\t];\n}\n\n/** Foreign-key DDL for one table's relations. Emit AFTER every referenced table\n * exists; references require the target columns to be a UNIQUE key. */\nexport function emitForeignKeyDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\treturn (tableDef.relations ?? []).map((rel) => {\n\t\tconst constraintName = quotePgIdent(\n\t\t\t`fk_${schemaName}_${tableName}_${rel.name}`,\n\t\t);\n\t\treturn (\n\t\t\t`ALTER TABLE ${quotePgIdent(schemaName)}.${quotePgIdent(tableName)} ADD CONSTRAINT ${constraintName} ` +\n\t\t\t`FOREIGN KEY (${rel.fields.map(quotePgIdent).join(\", \")}) ` +\n\t\t\t`REFERENCES ${quotePgIdent(schemaName)}.${quotePgIdent(rel.references)} (${rel.referencedColumns.map(quotePgIdent).join(\", \")})`\n\t\t);\n\t});\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(\n\tdef: SubgraphDefinition,\n\tschemaNameOverride?: string,\n): GeneratedSQL {\n\tconst schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n\tconst statements: string[] = [];\n\n\t// Check if any column uses search (trigram)\n\tconst needsTrgm = Object.values(def.schema).some((table) =>\n\t\tObject.values(table.columns).some((col) => col.search),\n\t);\n\n\tif (needsTrgm) {\n\t\tstatements.push(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\");\n\t}\n\n\t// Schema namespace\n\tstatements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n\t// One table per schema entry (single-sourced per-table DDL).\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitTableDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Revert journal (one per schema) — see emitJournalDDL.\n\tstatements.push(...emitJournalDDL(schemaName));\n\t// Only when a source actually uses a factory — no dead table otherwise.\n\tif (\n\t\tObject.values(def.sources ?? {}).some(\n\t\t\t(src) => (src as { factory?: unknown }).factory !== undefined,\n\t\t)\n\t) {\n\t\tstatements.push(...emitFactoryDDL(schemaName));\n\t}\n\n\t// Foreign keys are added in a second pass so every referenced table exists.\n\t// These mirror the ORM relations emitted by the codegen (no drift) and require\n\t// the referenced columns to be a UNIQUE key on the target table.\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitForeignKeyDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Hash based on schema structure only — version intentionally excluded\n\t// so server-managed version bumps don't look like schema changes\n\tconst hashInput = JSON.stringify(\n\t\t{\n\t\t\tname: def.name,\n\t\t\tschema: def.schema,\n\t\t\tsources: def.sources,\n\t\t},\n\t\t(_key, value) => (typeof value === \"bigint\" ? value.toString() : value),\n\t);\n\t// node crypto (not Bun.hash) so the published node-runtime `sl` CLI can\n\t// compute schema hashes too (e.g. `sl subgraphs spec`).\n\tconst hash = createHash(\"sha256\").update(hashInput).digest(\"hex\");\n\n\treturn { statements, hash };\n}\n",
8
8
  "// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n\n/**\n * Double-quotes a Postgres identifier unless it's already a safe bare\n * identifier, escaping any embedded double quotes. Defense-in-depth for the\n * DDL emitters: every name reaching them (schema/table/column names, and the\n * composite names generator.ts builds from them) is validated upstream\n * (`SqlIdentifierSchema` / `SubgraphNameSchema`), so this is a no-op for every\n * currently-valid name — output stays byte-identical. It only changes\n * anything if a hostile name (embedded quote, semicolon, whitespace, ...)\n * somehow reached this far, turning it into an inert quoted identifier\n * instead of raw SQL.\n */\nexport function quotePgIdent(name: string): string {\n\tif (/^[a-z_][a-z0-9_]*$/i.test(name)) return name;\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** `user_account` → `userAccount`. Column and variable names in every emitted\n * ORM surface go through this. */\nexport function snakeToCamel(name: string): string {\n\treturn name.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** `user_account` → `UserAccount`. Type/model names for one table must agree\n * across the Prisma, Drizzle, Kysely, and index-codegen emitters — a user can\n * import from more than one, so this lives here rather than per-generator. */\nexport function pascalCase(name: string): string {\n\tconst camel = snakeToCamel(name);\n\treturn camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n",
9
9
  "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Database } from \"@secondlayer/shared/db/schema\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { http, createPublicClient } from \"@secondlayer/stacks\";\nimport {\n\tContractResponseError,\n\ttype UnwrapResponse,\n\tbuildFunctionArgs,\n\tisResponseOutput,\n\treadContract,\n} from \"@secondlayer/stacks/actions\";\nimport type { ClarityValue } from \"@secondlayer/stacks/clarity\";\nimport type {\n\tAbiContract,\n\tAbiFunction,\n\tAbiType,\n\tExtractFunctionArgs,\n\tExtractFunctionOutput,\n\tExtractReadOnlyFunctions,\n\tToCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport {\n\tclarityValueToJSUntyped,\n\tdeserializeCV,\n\tnormalizeAbi,\n\tserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type { Kysely } from \"kysely\";\n\n/**\n * How long a read stays valid.\n *\n * - `per-block` (default): pinned to the block being processed, cached under\n * its `index_block_hash`. Sound for any read-only function — reindexing the\n * same block always returns the same value, and a reorg-replaced block has a\n * different id so it can't inherit the orphaned answer.\n * - `contract-constant`: the caller asserts the value cannot change for this\n * contract and these args (SIP-010 `get-decimals`/`get-symbol`), so it is\n * resolved ONCE instead of once per block. This is the mode that makes a\n * backfill affordable — under `per-block` every block is a distinct key and\n * therefore a distinct RPC. Declaring it on a value that does change pins the\n * first answer forever, so it is opt-in and never inferred.\n */\nexport type ChainReadCacheMode = \"per-block\" | \"contract-constant\";\n\nexport type ChainReadOptions = { cache?: ChainReadCacheMode };\n\n/**\n * The chain-read surface, fully typed by an ABI.\n *\n * Shaped like `getContract` from `@secondlayer/stacks` — the same ABI in, the\n * same camelCased read methods out — minus `call`/`buildCall`: a handler\n * indexes the chain, it never writes to it.\n *\n * Reached through {@link readContractAt} rather than off `ctx.client`\n * directly: an ABI-generic method living on the context interface makes every\n * structural comparison of a subgraph definition instantiate it, which exceeds\n * TS's depth budget. At a call site the ABI is already concrete and it costs\n * nothing.\n */\nexport interface ChainReadClient {\n\t/**\n\t * Read-only methods of a contract, evaluated against the exact block being\n\t * processed.\n\t *\n\t * Every call is pinned to the block's `index_block_hash`, so a handler is a\n\t * pure function of its block: reindexing a range produces byte-identical\n\t * rows. Reading at the node's tip instead would make the same reindex\n\t * return different values — that is the corruption this refuses to allow,\n\t * so a block whose id was never persisted throws rather than falling back.\n\t *\n\t * Results are memoized in Postgres, so a value is fetched once per block\n\t * rather than once per event (or once per contract with\n\t * `cache: \"contract-constant\"`).\n\t */\n\tcontract<const C extends AbiContract>(\n\t\tcontractId: string,\n\t\tabi: C,\n\t\toptions?: ChainReadOptions,\n\t): { read: ChainReadMethods<C> };\n}\n\n/**\n * True for a structural empty mapped type (`{}`) and for codegen's\n * `Record<string, never>`. `keyof Record<string, never>` is `string`, so the\n * first check alone is not enough. Local copy of the `getContract` helper —\n * importing `ContractInstance<C>[\"read\"]` would re-enter the codegen-brand\n * conditional this type exists to avoid.\n */\ntype IsEmptyArgs<A> = [keyof A & string] extends [never]\n\t? true\n\t: Record<string, never> extends A\n\t\t? true\n\t\t: false;\n\ntype ChainReadMethod<A, R> = IsEmptyArgs<A> extends true\n\t? (args?: A) => R\n\t: (args: A) => R;\n\n/**\n * The camelCased read methods of an ABI. Spelled out rather than reused from\n * `ContractInstance<C>[\"read\"]`: that type is a conditional over the codegen\n * brand, and evaluating it wherever a subgraph definition is structurally\n * compared pushes TS past its instantiation depth.\n */\nexport type ChainReadMethods<C extends AbiContract> = {\n\t[N in ExtractReadOnlyFunctions<C> as ToCamelCase<N>]: ChainReadMethod<\n\t\tExtractFunctionArgs<C, N>,\n\t\tPromise<UnwrapResponse<ExtractFunctionOutput<C, N>>>\n\t>;\n};\n\n/**\n * `ChainReadClient` with the ABI generic erased. Structurally cheap, so the\n * base `SubgraphContext` can carry it; `TypedSubgraphContext` uses the real\n * one and handlers get full inference.\n */\nexport interface ErasedChainReadClient {\n\t// `abi: unknown`, not `AbiContract`: naming the ABI type here drags its\n\t// (deeply recursive) definition into every structural comparison of a\n\t// subgraph definition. `readContractAt` constrains it properly.\n\tcontract(\n\t\tcontractId: string,\n\t\tabi: unknown,\n\t\toptions?: ChainReadOptions,\n\t): {\n\t\tread: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;\n\t};\n}\n\n/**\n * Typed read methods for one contract, from a handler.\n *\n * ```ts\n * const token = readContractAt(ctx, contractId, SIP010_ABI, {\n * cache: \"contract-constant\",\n * });\n * const decimals = await token.read.getDecimals(); // bigint\n * ```\n */\nexport function readContractAt<const C extends AbiContract>(\n\tctx: { client: ErasedChainReadClient },\n\tcontractId: string,\n\tabi: C,\n\toptions?: ChainReadOptions,\n): { read: ChainReadMethods<C> } {\n\treturn ctx.client.contract(contractId, abi, options) as unknown as {\n\t\tread: ChainReadMethods<C>;\n\t};\n}\n\nexport class ChainReadError extends Error {\n\toverride name = \"ChainReadError\";\n}\n\n/**\n * Node transport for handler reads. Deliberately its own client rather than a\n * shared singleton: `retryCount: 0` keeps a slow node from multiplying into the\n * block's retry budget (`processBlockWithRetry` already owns retries), and the\n * concurrency gate below bounds how much of a backfill can hit the node at once.\n */\nfunction nodeClient(rpcUrl: string) {\n\treturn createPublicClient({\n\t\ttransport: http(rpcUrl, { retryCount: 0, timeout: 10_000 }),\n\t});\n}\n\n/**\n * Cap concurrent node reads across all handlers in this process. A handler that\n * reads on every event turns a 100-block batch into thousands of in-flight\n * requests otherwise — enough to knock over the node the indexer depends on.\n */\nclass ConcurrencyGate {\n\tprivate active = 0;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(private readonly limit: number) {}\n\n\tasync run<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (this.active >= this.limit) {\n\t\t\tawait new Promise<void>((resolve) => this.queue.push(resolve));\n\t\t}\n\t\tthis.active++;\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tthis.active--;\n\t\t\tthis.queue.shift()?.();\n\t\t}\n\t}\n}\n\nconst DEFAULT_MAX_CONCURRENT_READS = 4;\n\nfunction maxConcurrentReads(): number {\n\tconst raw = process.env.SUBGRAPH_CHAIN_READ_CONCURRENCY;\n\tconst parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;\n\treturn Number.isFinite(parsed) && parsed > 0\n\t\t? parsed\n\t\t: DEFAULT_MAX_CONCURRENT_READS;\n}\n\nconst gate = new ConcurrencyGate(maxConcurrentReads());\n\n/** Stable key for an arg set — property order must not fork a cache entry. */\nfunction hashArgs(args: readonly ClarityValue[]): string {\n\tconst serialized = args.map((arg) => serializeCV(arg)).join(\",\");\n\treturn Bun.hash(serialized).toString(16);\n}\n\nfunction findFunction(abi: AbiContract, name: string): AbiFunction {\n\tconst fn = abi.functions.find((f) => f.name === name) as\n\t\t| AbiFunction\n\t\t| undefined;\n\tif (!fn) {\n\t\tthrow new ChainReadError(`No function \"${name}\" in the supplied ABI.`);\n\t}\n\tif (fn.access !== \"read-only\") {\n\t\tthrow new ChainReadError(\n\t\t\t`\"${name}\" is ${fn.access}, not read-only — a handler cannot call it.`,\n\t\t);\n\t}\n\treturn fn;\n}\n\nexport type ChainReadContext = {\n\tblockHeight: number;\n\tindexBlockHash: string | null | undefined;\n\trpcUrl?: string;\n\tdb?: Kysely<Database>;\n};\n\n/**\n * Build the `ctx.client` surface for one block. Generic lives on the METHOD,\n * not here, so a handler's ABI narrows per call without infecting\n * `SubgraphContext` with a type parameter.\n */\n/**\n * Build the `ctx.client` surface for one block. The ABI generic lives on\n * `contract()`, not here, so a handler's types narrow per contract without\n * `SubgraphContext` carrying a type parameter.\n */\nexport function createChainReadClient(ctx: ChainReadContext): ChainReadClient {\n\t// The ABI generic is erased inside the implementation on purpose:\n\t// re-resolving `ExtractFunctionArgs` against an unfixed type parameter is\n\t// what pushes TS past its instantiation depth on a real-sized ABI.\n\tconst readValue = async (\n\t\tcontractId: string,\n\t\tabi: AbiContract,\n\t\tfunctionName: string,\n\t\targs: Record<string, unknown>,\n\t\toptions: ChainReadOptions,\n\t): Promise<unknown> => {\n\t\tconst rpcUrl = ctx.rpcUrl ?? process.env.STACKS_NODE_RPC_URL;\n\t\tif (!rpcUrl) {\n\t\t\tthrow new ChainReadError(\n\t\t\t\t\"ctx.client needs a Stacks node: set STACKS_NODE_RPC_URL on the subgraph processor.\",\n\t\t\t);\n\t\t}\n\n\t\tconst constant = options.cache === \"contract-constant\";\n\t\tif (!constant && !ctx.indexBlockHash) {\n\t\t\tthrow new ChainReadError(\n\t\t\t\t`Block ${ctx.blockHeight} has no index_block_hash, so a read cannot be pinned to it. Reading at the node's tip would make this handler non-deterministic (the same reindex would produce different rows). Re-ingest the block, or pass cache: \"contract-constant\" if the value genuinely cannot change.`,\n\t\t\t);\n\t\t}\n\n\t\tconst fn = findFunction(abi, functionName);\n\t\tconst clarityArgs = buildFunctionArgs(fn, args);\n\t\tconst db = ctx.db ?? getSourceDb();\n\t\tconst argsHash = hashArgs(clarityArgs);\n\t\tconst pinnedTo = constant ? null : (ctx.indexBlockHash as string);\n\n\t\tconst cached = await db\n\t\t\t.selectFrom(\"chain_read_cache\")\n\t\t\t.select(\"result_hex\")\n\t\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t\t.where(\"function_name\", \"=\", fn.name)\n\t\t\t.where(\"args_hash\", \"=\", argsHash)\n\t\t\t.where((eb) =>\n\t\t\t\tpinnedTo === null\n\t\t\t\t\t? eb(\"index_block_hash\", \"is\", null)\n\t\t\t\t\t: eb(\"index_block_hash\", \"=\", pinnedTo),\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\n\t\tconst resultHex =\n\t\t\tcached?.result_hex ??\n\t\t\t(await gate.run(async () => {\n\t\t\t\t// A constant read still pins to this block where it can: \"cannot\n\t\t\t\t// change\" is a claim about future blocks, not a license to read\n\t\t\t\t// a tip that may be ahead of the one being processed.\n\t\t\t\tif (!ctx.indexBlockHash) {\n\t\t\t\t\t// The one path where an UNPINNED read happens. Reachable only\n\t\t\t\t\t// in constant mode on a block with no persisted id — which is\n\t\t\t\t\t// exactly what the pinning error tells you to do — so it is\n\t\t\t\t\t// allowed, but never silently.\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\"Chain read is not pinned to a block (no index_block_hash)\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontractId,\n\t\t\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\t\t\tblockHeight: ctx.blockHeight,\n\t\t\t\t\t\t\tnote: 'cache: \"contract-constant\" asserts this value cannot change; the node answered at its own tip',\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst value = await readContract(nodeClient(rpcUrl), {\n\t\t\t\t\tcontract: contractId,\n\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\targs: clarityArgs,\n\t\t\t\t\ttip: ctx.indexBlockHash ?? undefined,\n\t\t\t\t});\n\t\t\t\treturn serializeCV(value);\n\t\t\t}));\n\n\t\tif (!cached) {\n\t\t\tawait db\n\t\t\t\t.insertInto(\"chain_read_cache\")\n\t\t\t\t.values({\n\t\t\t\t\tcontract_id: contractId,\n\t\t\t\t\tfunction_name: fn.name,\n\t\t\t\t\targs_hash: argsHash,\n\t\t\t\t\tindex_block_hash: pinnedTo,\n\t\t\t\t\tblock_height: constant ? null : ctx.blockHeight,\n\t\t\t\t\tresult_hex: resultHex,\n\t\t\t\t})\n\t\t\t\t// Two handlers in the same batch can race to the same key; the\n\t\t\t\t// value is identical either way, so the loser keeps its own.\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst value = deserializeCV(resultHex);\n\t\tconst js = clarityValueToJSUntyped(fn.outputs as AbiType, value);\n\n\t\tif (isResponseOutput(fn.outputs as AbiType)) {\n\t\t\tconst response = js as { ok?: unknown; err?: unknown };\n\t\t\tif (\"ok\" in response) return response.ok;\n\t\t\tthrow new ContractResponseError(\n\t\t\t\t`${contractId}::${fn.name} returned an err response.`,\n\t\t\t\tresponse.err,\n\t\t\t);\n\t\t}\n\t\treturn js;\n\t};\n\n\treturn {\n\t\tcontract(contractId: string, rawAbi: AbiContract, options = {}) {\n\t\t\t// Accept a raw Hiro/Clarinet ABI as well as a normalized one — raw\n\t\t\t// ABIs wrap `outputs` as `{ type: … }`, which the JS bridge can't read.\n\t\t\tconst abi = normalizeAbi(rawAbi);\n\t\t\tconst camelToKebab = new Map<string, string>();\n\t\t\tfor (const fn of abi.functions) {\n\t\t\t\tcamelToKebab.set(toCamelCase(fn.name), fn.name);\n\t\t\t}\n\n\t\t\tconst read = new Proxy(\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tget(_target, prop: string) {\n\t\t\t\t\t\tconst fnName = camelToKebab.get(prop) ?? prop;\n\t\t\t\t\t\treturn (args: Record<string, unknown> = {}) =>\n\t\t\t\t\t\t\treadValue(contractId, abi, fnName, args, options);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn { read } as never;\n\t\t},\n\t};\n}\n",
10
10
  "import { cvToValue, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n\ttry {\n\t\tconst cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\tconst cv = deserializeCV(cleanHex);\n\t\treturn cvToValue(cv);\n\t} catch {\n\t\treturn hex;\n\t}\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n\tif (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n\t\treturn decodeClarityValue(data);\n\t}\n\n\tif (Array.isArray(data)) {\n\t\treturn data.map(decodeEventData);\n\t}\n\n\tif (typeof data === \"object\" && data !== null) {\n\t\tconst decoded: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tdecoded[key] = decodeEventData(value);\n\t\t}\n\t\treturn decoded;\n\t}\n\n\treturn data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n\treturn args.map(decodeClarityValue);\n}\n",
11
- "import type { SubgraphFilter } from \"../types.ts\";\n\nexport interface MatchedTx {\n\ttx: TxRecord;\n\tevents: EventRecord[];\n\t/** Source object key — used for handler dispatch */\n\tsourceName: string;\n}\n\nexport type TxRecord = {\n\ttx_id: string;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\t/** Position within the block — the runner sorts dispatch into chain order. */\n\ttx_index?: number;\n\tcontract_id?: string | null;\n\tfunction_name?: string | null;\n\tfunction_args?: unknown | null;\n\traw_result?: string | null;\n};\n\nexport type EventRecord = {\n\tid: string;\n\ttx_id: string;\n\ttype: string;\n\tevent_index: number;\n\tdata: unknown;\n};\n\n// ── Wildcard matching (shared with v1) ──────────────────────────────\n\nconst patternCache = new Map<string, RegExp>();\n\n/** Match a value against one pattern, or ANY pattern in a set. */\nfunction matchAny(value: string, pattern: string | readonly string[]): boolean {\n\treturn Array.isArray(pattern)\n\t\t? pattern.some((p) => matchPattern(value, p))\n\t\t: matchPattern(value, pattern as string);\n}\n\nfunction matchPattern(value: string, pattern: string): boolean {\n\tif (!pattern.includes(\"*\")) return value === pattern;\n\tlet re = patternCache.get(pattern);\n\tif (!re) {\n\t\tconst regex = pattern\n\t\t\t.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\t\t\t.replace(/\\*/g, \".*\");\n\t\tre = new RegExp(`^${regex}$`);\n\t\tpatternCache.set(pattern, re);\n\t}\n\treturn re.test(value);\n}\n\n// Trait → set of conforming contract IDs, resolved per block by the caller\n// (block-processor) from the contract registry. Kept as injected data so this\n// module stays pure/sync/DB-less.\nexport type TraitContracts = Map<string, ReadonlySet<string>>;\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n/**\n * True when a filter's optional `trait` admits this contract: no trait → always\n * allowed; trait set → the contract must be in the resolved conforming set.\n */\n/** Addresses discovered per source name (factory sets), resolved by the\n * caller as-of the block being processed. */\nexport type FactoryContracts = ReadonlyMap<string, ReadonlySet<string>>;\n\n/**\n * A factory-scoped source matches only contracts its factory has revealed.\n * Same shape as {@link traitAllows}: the set is injected, so this module\n * stays pure and sync.\n */\nfunction factoryAllows(\n\tfilter: { factory?: { from: string; field: string } },\n\tcontractId: string | undefined | null,\n\tfactoryContracts: FactoryContracts,\n): boolean {\n\tif (!filter.factory) return true;\n\tif (!contractId) return false;\n\treturn (factoryContracts.get(filter.factory.from) ?? EMPTY_SET).has(\n\t\tcontractId,\n\t);\n}\n\n/** Read a dotted path off a decoded payload (`\"data.pool\"`). */\nexport function readPath(payload: unknown, path: string): unknown {\n\tlet cur: unknown = payload;\n\tfor (const key of path.split(\".\")) {\n\t\tif (cur === null || typeof cur !== \"object\") return undefined;\n\t\tcur = (cur as Record<string, unknown>)[key];\n\t}\n\treturn cur;\n}\n\nfunction traitAllows(\n\tfilter: SubgraphFilter,\n\tcontractId: string | undefined | null,\n\ttraitContracts: TraitContracts,\n): boolean {\n\tconst trait = (filter as { trait?: string }).trait;\n\tif (!trait) return true;\n\tif (!contractId) return false;\n\treturn (traitContracts.get(trait) ?? EMPTY_SET).has(contractId);\n}\n\n/** Extract the contract id from an asset identifier (`<contract>::<token>`). */\nfunction assetContract(assetId: string | undefined): string | undefined {\n\treturn assetId?.split(\"::\")[0];\n}\n\n/**\n * Contract on a print payload. Legacy `smart_contract_event` rows use\n * `contract_identifier`; current `contract_event` rows use `contract_id`.\n * Matcher and runner must share this — a print that matches on `contract_id`\n * otherwise reaches the handler with `event.contractId === \"\"`.\n */\nexport function printContractId(\n\tdata: Record<string, unknown> | null | undefined,\n): string | undefined {\n\tif (!data) return undefined;\n\tconst id =\n\t\t(typeof data.contract_identifier === \"string\"\n\t\t\t? data.contract_identifier\n\t\t\t: undefined) ??\n\t\t(typeof data.contract_id === \"string\" ? data.contract_id : undefined);\n\treturn id || undefined;\n}\n\n// ── Per-filter-type matchers ────────────────────────────────────────\n\nfunction matchFilter(\n\tfilter: SubgraphFilter,\n\ttransactions: TxRecord[],\n\teventsByTx: Map<string, EventRecord[]>,\n\ttraitContracts: TraitContracts,\n\tfactoryContracts: FactoryContracts = new Map(),\n): { tx: TxRecord; events: EventRecord[] }[] {\n\tconst results: { tx: TxRecord; events: EventRecord[] }[] = [];\n\n\tswitch (filter.type) {\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\tcase \"stx_lock\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => e.type === eventType);\n\t\t\t\tif (matched.length === 0) continue;\n\n\t\t\t\t// Apply address filters\n\t\t\t\tconst filtered = matched.filter((e) => {\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"lockedAddress\" in filter && filter.lockedAddress) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!matchPattern(data.locked_address as string, filter.lockedAddress)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filters\n\t\t\t\t\tif (\"minAmount\" in filter && filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt(\n\t\t\t\t\t\t\t(data.amount ?? data.locked_amount ?? \"0\") as string,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t\"maxAmount\" in filter &&\n\t\t\t\t\t\t(filter as { maxAmount?: bigint }).maxAmount !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount > (filter as { maxAmount: bigint }).maxAmount)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: filtered });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\t// Asset identifier filter\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Trait scope — the asset's contract must conform.\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Address filters\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filter\n\t\t\t\t\tif (filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── NFT events ──\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract call ──\n\t\tcase \"contract_call\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"contract_call\") continue;\n\n\t\t\t\t// Contract filter\n\t\t\t\tif (filter.contractId) {\n\t\t\t\t\tif (!tx.contract_id || !matchAny(tx.contract_id, filter.contractId))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Factory scope: only contracts this source's factory revealed.\n\t\t\t\tif (!factoryAllows(filter, tx.contract_id, factoryContracts)) continue;\n\t\t\t\t// Function filter\n\t\t\t\tif (filter.functionName) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!tx.function_name ||\n\t\t\t\t\t\t!matchPattern(tx.function_name, filter.functionName)\n\t\t\t\t\t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Caller filter\n\t\t\t\tif (filter.caller) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.caller)) continue;\n\t\t\t\t}\n\t\t\t\t// Trait scope — the called contract must conform.\n\t\t\t\tif (!traitAllows(filter, tx.contract_id, traitContracts)) continue;\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"smart_contract\") continue;\n\n\t\t\t\tif (filter.deployer) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.deployer)) continue;\n\t\t\t\t}\n\t\t\t\tif (filter.contractName) {\n\t\t\t\t\tconst name = tx.contract_id?.split(\".\")[1] ?? \"\";\n\t\t\t\t\tif (!matchPattern(name, filter.contractName)) continue;\n\t\t\t\t}\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== \"smart_contract_event\" && e.type !== \"contract_event\")\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (data.topic !== \"print\") return false;\n\n\t\t\t\t\tconst contractId = printContractId(data);\n\t\t\t\t\tif (filter.contractId) {\n\t\t\t\t\t\tif (!contractId || !matchAny(contractId, filter.contractId))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!traitAllows(filter, contractId, traitContracts)) return false;\n\t\t\t\t\tif (!factoryAllows(filter, contractId, factoryContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Topic filter — check the decoded Clarity value's topic field\n\t\t\t\t\t// At this stage data.value is still raw hex; topic filtering happens\n\t\t\t\t\t// after decode in the runner. For now, skip topic filtering here.\n\t\t\t\t\t// The runner will filter by topic after decoding.\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn results;\n}\n\n/**\n * Match named filters against a block's transactions and events.\n * Returns matches with sourceName = the object key from sources.\n */\nexport function matchSources(\n\tsources: Record<string, SubgraphFilter>,\n\ttransactions: TxRecord[],\n\tevents: EventRecord[],\n\ttraitContracts: TraitContracts = new Map(),\n\tfactoryContracts: FactoryContracts = new Map(),\n): MatchedTx[] {\n\t// Index events by txId\n\tconst eventsByTx = new Map<string, EventRecord[]>();\n\tfor (const event of events) {\n\t\tconst list = eventsByTx.get(event.tx_id) ?? [];\n\t\tlist.push(event);\n\t\teventsByTx.set(event.tx_id, list);\n\t}\n\n\tconst seen = new Set<string>();\n\tconst results: MatchedTx[] = [];\n\n\tfor (const [sourceName, filter] of Object.entries(sources)) {\n\t\tconst matches = matchFilter(\n\t\t\tfilter,\n\t\t\ttransactions,\n\t\t\teventsByTx,\n\t\t\ttraitContracts,\n\t\t\tfactoryContracts,\n\t\t);\n\t\tfor (const match of matches) {\n\t\t\tconst dedupeKey = `${match.tx.tx_id}:${sourceName}`;\n\t\t\tif (!seen.has(dedupeKey)) {\n\t\t\t\tseen.add(dedupeKey);\n\t\t\t\tresults.push({ ...match, sourceName });\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results;\n}\n",
12
- "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport { camelizeKeys } from \"../print-schema.ts\";\nimport type {\n\tContractCallFilter,\n\tMaterializeSpec,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport { applyMaterializeInsert } from \"./materialize.ts\";\nimport { validatePrintPayload } from \"./print-validate.ts\";\nimport { type MatchedTx, printContractId } from \"./source-matcher.ts\";\nimport { recordPrintViolation } from \"./violations.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n\t/** Print events skipped because their decoded payload did not match the\n\t * source's declared `prints` schema. Never an error: skipping keeps the\n\t * block committable, which the checkpoint model requires. */\n\tskipped?: number;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * The string branch is legacy tolerance, not driver behaviour: rows written\n * before 2026-08-12 hold a jsonb *string* containing JSON because the writer\n * pre-serialized the array (see backfill-function-args.ts). Correct rows arrive\n * as arrays. Keep both paths until every environment has been backfilled.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(decoded) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tlet skipped = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n\t\t}\n\n\t\tconst filter = filterLookup.get(sourceName);\n\t\tconst materialize: MaterializeSpec | undefined =\n\t\t\tfilter && \"materialize\" in filter && filter.materialize !== undefined\n\t\t\t\t? filter.materialize\n\t\t\t\t: undefined;\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler && !materialize) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Declared `prints` is the developer's stated payload shape, so a\n\t\t\t// mismatch is a real defect (a contract upgrade, or a declaration\n\t\t\t// that never matched — the bns-names class, where every event\n\t\t\t// decoded to null for an entire deploy). Skip + log rather than\n\t\t\t// write nulls; never throw, which would wedge the block.\n\t\t\tif (event !== null && filter?.type === \"print_event\" && filter.prints) {\n\t\t\t\tconst printPayload = payload as {\n\t\t\t\t\ttopic?: string;\n\t\t\t\t\tdata?: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst verdict = validatePrintPayload(\n\t\t\t\t\tfilter.prints,\n\t\t\t\t\tprintPayload.topic ?? \"\",\n\t\t\t\t\tprintPayload.data ?? {},\n\t\t\t\t);\n\t\t\t\tif (!verdict.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Print payload does not match declared prints schema\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttopic: printPayload.topic,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t});\n\t\t\t\t\t// Persist for the authed violations GET — never throw.\n\t\t\t\t\tvoid recordPrintViolation({\n\t\t\t\t\t\tsubgraphName: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\tblockHeight: ctx.block.height,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t\tsamplePayload: {\n\t\t\t\t\t\t\ttopic: printPayload.topic ?? \"\",\n\t\t\t\t\t\t\tdata: printPayload.data ?? {},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (materialize) {\n\t\t\t\tconst result = applyMaterializeInsert(\n\t\t\t\t\tmaterialize,\n\t\t\t\t\tpayload,\n\t\t\t\t\tctx,\n\t\t\t\t\tsubgraph.schema,\n\t\t\t\t);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Materialize skipped: required field missing\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: result.reason,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tprocessed++;\n\t\t\t} else if (handler) {\n\t\t\t\tawait handler(payload, ctx);\n\t\t\t\tprocessed++;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n}\n",
11
+ "import type { SubgraphFilter } from \"../types.ts\";\n\nexport interface MatchedTx {\n\ttx: TxRecord;\n\tevents: EventRecord[];\n\t/** Source object key — used for handler dispatch */\n\tsourceName: string;\n}\n\nexport type TxRecord = {\n\ttx_id: string;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\t/** Position within the block — the runner sorts dispatch into chain order. */\n\ttx_index?: number;\n\tcontract_id?: string | null;\n\tfunction_name?: string | null;\n\tfunction_args?: unknown | null;\n\traw_result?: string | null;\n};\n\nexport type EventRecord = {\n\tid: string;\n\ttx_id: string;\n\ttype: string;\n\t/** Classic `event_index`, or `ordinal` when `clock === \"vm\"`. */\n\tevent_index: number;\n\tdata: unknown;\n\t/** Set on opt-in `vm_events` rows. Two clocks never sort or dedupe together. */\n\tclock?: \"vm\";\n};\n\n// ── Wildcard matching (shared with v1) ──────────────────────────────\n\nconst patternCache = new Map<string, RegExp>();\n\n/** Match a value against one pattern, or ANY pattern in a set. */\nfunction matchAny(value: string, pattern: string | readonly string[]): boolean {\n\treturn Array.isArray(pattern)\n\t\t? pattern.some((p) => matchPattern(value, p))\n\t\t: matchPattern(value, pattern as string);\n}\n\nfunction matchPattern(value: string, pattern: string): boolean {\n\tif (!pattern.includes(\"*\")) return value === pattern;\n\tlet re = patternCache.get(pattern);\n\tif (!re) {\n\t\tconst regex = pattern\n\t\t\t.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\t\t\t.replace(/\\*/g, \".*\");\n\t\tre = new RegExp(`^${regex}$`);\n\t\tpatternCache.set(pattern, re);\n\t}\n\treturn re.test(value);\n}\n\n// Trait → set of conforming contract IDs, resolved per block by the caller\n// (block-processor) from the contract registry. Kept as injected data so this\n// module stays pure/sync/DB-less.\nexport type TraitContracts = Map<string, ReadonlySet<string>>;\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n/**\n * True when a filter's optional `trait` admits this contract: no trait → always\n * allowed; trait set → the contract must be in the resolved conforming set.\n */\n/** Addresses discovered per source name (factory sets), resolved by the\n * caller as-of the block being processed. */\nexport type FactoryContracts = ReadonlyMap<string, ReadonlySet<string>>;\n\n/**\n * A factory-scoped source matches only contracts its factory has revealed.\n * Same shape as {@link traitAllows}: the set is injected, so this module\n * stays pure and sync.\n */\nfunction factoryAllows(\n\tfilter: { factory?: { from: string; field: string } },\n\tcontractId: string | undefined | null,\n\tfactoryContracts: FactoryContracts,\n): boolean {\n\tif (!filter.factory) return true;\n\tif (!contractId) return false;\n\treturn (factoryContracts.get(filter.factory.from) ?? EMPTY_SET).has(\n\t\tcontractId,\n\t);\n}\n\n/** Read a dotted path off a decoded payload (`\"data.pool\"`). */\nexport function readPath(payload: unknown, path: string): unknown {\n\tlet cur: unknown = payload;\n\tfor (const key of path.split(\".\")) {\n\t\tif (cur === null || typeof cur !== \"object\") return undefined;\n\t\tcur = (cur as Record<string, unknown>)[key];\n\t}\n\treturn cur;\n}\n\nfunction traitAllows(\n\tfilter: SubgraphFilter,\n\tcontractId: string | undefined | null,\n\ttraitContracts: TraitContracts,\n): boolean {\n\tconst trait = (filter as { trait?: string }).trait;\n\tif (!trait) return true;\n\tif (!contractId) return false;\n\treturn (traitContracts.get(trait) ?? EMPTY_SET).has(contractId);\n}\n\n/** Extract the contract id from an asset identifier (`<contract>::<token>`). */\nfunction assetContract(assetId: string | undefined): string | undefined {\n\treturn assetId?.split(\"::\")[0];\n}\n\n/**\n * Contract on a print payload. Legacy `smart_contract_event` rows use\n * `contract_identifier`; current `contract_event` rows use `contract_id`.\n * Matcher and runner must share this — a print that matches on `contract_id`\n * otherwise reaches the handler with `event.contractId === \"\"`.\n */\nexport function printContractId(\n\tdata: Record<string, unknown> | null | undefined,\n): string | undefined {\n\tif (!data) return undefined;\n\tconst id =\n\t\t(typeof data.contract_identifier === \"string\"\n\t\t\t? data.contract_identifier\n\t\t\t: undefined) ??\n\t\t(typeof data.contract_id === \"string\" ? data.contract_id : undefined);\n\treturn id || undefined;\n}\n\n// ── Per-filter-type matchers ────────────────────────────────────────\n\nfunction matchFilter(\n\tfilter: SubgraphFilter,\n\ttransactions: TxRecord[],\n\teventsByTx: Map<string, EventRecord[]>,\n\ttraitContracts: TraitContracts,\n\tfactoryContracts: FactoryContracts = new Map(),\n\tvmEventsByTx: Map<string, EventRecord[]> = new Map(),\n): { tx: TxRecord; events: EventRecord[] }[] {\n\tconst results: { tx: TxRecord; events: EventRecord[] }[] = [];\n\n\tswitch (filter.type) {\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\tcase \"stx_lock\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => e.type === eventType);\n\t\t\t\tif (matched.length === 0) continue;\n\n\t\t\t\t// Apply address filters\n\t\t\t\tconst filtered = matched.filter((e) => {\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"lockedAddress\" in filter && filter.lockedAddress) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!matchPattern(data.locked_address as string, filter.lockedAddress)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filters\n\t\t\t\t\tif (\"minAmount\" in filter && filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt(\n\t\t\t\t\t\t\t(data.amount ?? data.locked_amount ?? \"0\") as string,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t\"maxAmount\" in filter &&\n\t\t\t\t\t\t(filter as { maxAmount?: bigint }).maxAmount !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount > (filter as { maxAmount: bigint }).maxAmount)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: filtered });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\t// Asset identifier filter\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Trait scope — the asset's contract must conform.\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Address filters\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filter\n\t\t\t\t\tif (filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── NFT events ──\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract call ──\n\t\tcase \"contract_call\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"contract_call\") continue;\n\n\t\t\t\t// Contract filter\n\t\t\t\tif (filter.contractId) {\n\t\t\t\t\tif (!tx.contract_id || !matchAny(tx.contract_id, filter.contractId))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Factory scope: only contracts this source's factory revealed.\n\t\t\t\tif (!factoryAllows(filter, tx.contract_id, factoryContracts)) continue;\n\t\t\t\t// Function filter\n\t\t\t\tif (filter.functionName) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!tx.function_name ||\n\t\t\t\t\t\t!matchPattern(tx.function_name, filter.functionName)\n\t\t\t\t\t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Caller filter\n\t\t\t\tif (filter.caller) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.caller)) continue;\n\t\t\t\t}\n\t\t\t\t// Trait scope — the called contract must conform.\n\t\t\t\tif (!traitAllows(filter, tx.contract_id, traitContracts)) continue;\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"smart_contract\") continue;\n\n\t\t\t\tif (filter.deployer) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.deployer)) continue;\n\t\t\t\t}\n\t\t\t\tif (filter.contractName) {\n\t\t\t\t\tconst name = tx.contract_id?.split(\".\")[1] ?? \"\";\n\t\t\t\t\tif (!matchPattern(name, filter.contractName)) continue;\n\t\t\t\t}\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"nested_contract_call\":\n\t\tcase \"var_set\":\n\t\tcase \"map_set\":\n\t\tcase \"map_insert\":\n\t\tcase \"map_delete\": {\n\t\t\t// vm sources read the vm clock only. A classic tx-level source never\n\t\t\t// sees these rows, and a vm source never sees `events[]`.\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = vmEventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== filter.type) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tconst contractId = printContractId(data);\n\t\t\t\t\tif (\"contractId\" in filter && filter.contractId) {\n\t\t\t\t\t\tif (!contractId || !matchAny(contractId, filter.contractId))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!traitAllows(filter, contractId, traitContracts)) return false;\n\t\t\t\t\tif (!factoryAllows(filter, contractId, factoryContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (filter.type === \"nested_contract_call\") {\n\t\t\t\t\t\tif (filter.functionName) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.function_name !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.function_name, filter.functionName)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (filter.caller) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.caller !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.caller, filter.caller)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (filter.sender) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.sender !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.sender, filter.sender)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (filter.type === \"var_set\" && filter.varName) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof data.var_name !== \"string\" ||\n\t\t\t\t\t\t\t!matchPattern(data.var_name, filter.varName)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t(filter.type === \"map_set\" ||\n\t\t\t\t\t\t\tfilter.type === \"map_insert\" ||\n\t\t\t\t\t\t\tfilter.type === \"map_delete\") &&\n\t\t\t\t\t\tfilter.map\n\t\t\t\t\t) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof data.map_name !== \"string\" ||\n\t\t\t\t\t\t\t!matchPattern(data.map_name, filter.map)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (matched.length > 0) results.push({ tx, events: matched });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== \"smart_contract_event\" && e.type !== \"contract_event\")\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (data.topic !== \"print\") return false;\n\n\t\t\t\t\tconst contractId = printContractId(data);\n\t\t\t\t\tif (filter.contractId) {\n\t\t\t\t\t\tif (!contractId || !matchAny(contractId, filter.contractId))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!traitAllows(filter, contractId, traitContracts)) return false;\n\t\t\t\t\tif (!factoryAllows(filter, contractId, factoryContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Topic filter — check the decoded Clarity value's topic field\n\t\t\t\t\t// At this stage data.value is still raw hex; topic filtering happens\n\t\t\t\t\t// after decode in the runner. For now, skip topic filtering here.\n\t\t\t\t\t// The runner will filter by topic after decoding.\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn results;\n}\n\n/**\n * Match named filters against a block's transactions and events.\n * Returns matches with sourceName = the object key from sources.\n */\nexport function matchSources(\n\tsources: Record<string, SubgraphFilter>,\n\ttransactions: TxRecord[],\n\tevents: EventRecord[],\n\ttraitContracts: TraitContracts = new Map(),\n\tfactoryContracts: FactoryContracts = new Map(),\n\t/** Opt-in `vm_events` rows (second clock). Only vm-typed sources read them. */\n\tvmEvents: EventRecord[] = [],\n): MatchedTx[] {\n\t// Index events by txId — one map per clock.\n\tconst eventsByTx = new Map<string, EventRecord[]>();\n\tfor (const event of events) {\n\t\tconst list = eventsByTx.get(event.tx_id) ?? [];\n\t\tlist.push(event);\n\t\teventsByTx.set(event.tx_id, list);\n\t}\n\tconst vmEventsByTx = new Map<string, EventRecord[]>();\n\tfor (const event of vmEvents) {\n\t\tconst list = vmEventsByTx.get(event.tx_id) ?? [];\n\t\tlist.push(event);\n\t\tvmEventsByTx.set(event.tx_id, list);\n\t}\n\n\tconst seen = new Set<string>();\n\tconst results: MatchedTx[] = [];\n\n\tfor (const [sourceName, filter] of Object.entries(sources)) {\n\t\tconst matches = matchFilter(\n\t\t\tfilter,\n\t\t\ttransactions,\n\t\t\teventsByTx,\n\t\t\ttraitContracts,\n\t\t\tfactoryContracts,\n\t\t\tvmEventsByTx,\n\t\t);\n\t\tfor (const match of matches) {\n\t\t\tconst dedupeKey = `${match.tx.tx_id}:${sourceName}`;\n\t\t\tif (!seen.has(dedupeKey)) {\n\t\t\t\tseen.add(dedupeKey);\n\t\t\t\tresults.push({ ...match, sourceName });\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results;\n}\n",
12
+ "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport { camelizeKeys } from \"../print-schema.ts\";\nimport type {\n\tContractCallFilter,\n\tMaterializeSpec,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport { applyMaterializeInsert } from \"./materialize.ts\";\nimport { validatePrintPayload } from \"./print-validate.ts\";\nimport { type MatchedTx, printContractId } from \"./source-matcher.ts\";\nimport { recordPrintViolation } from \"./violations.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n\t/** Print events skipped because their decoded payload did not match the\n\t * source's declared `prints` schema. Never an error: skipping keeps the\n\t * block committable, which the checkpoint model requires. */\n\tskipped?: number;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * The string branch is legacy tolerance, not driver behaviour: rows written\n * before 2026-08-12 hold a jsonb *string* containing JSON because the writer\n * pre-serialized the array (see backfill-function-args.ts). Correct rows arrive\n * as arrays. Keep both paths until every environment has been backfilled.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Decode a hex Clarity value without mutating the original string field. */\nfunction decodeRawHex(hex: string): unknown {\n\tif (hex.startsWith(\"0x\") && hex.length > 2) {\n\t\treturn decodeClarityValue(hex);\n\t}\n\treturn hex;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(decoded) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── VM traces: preserve raw hex. Generic decodeEventData would turn\n\t\t// a long uint hex into bigint and leave a short boolean hex a string.\n\t\tcase \"nested_contract_call\": {\n\t\t\tconst data = (event.data ?? {}) as Record<string, unknown>;\n\t\t\tconst argsHex = Array.isArray(data.function_args)\n\t\t\t\t? data.function_args.filter((a): a is string => typeof a === \"string\")\n\t\t\t\t: [];\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(data) ?? \"\",\n\t\t\t\tsender: typeof data.sender === \"string\" ? data.sender : null,\n\t\t\t\tcaller: typeof data.caller === \"string\" ? data.caller : \"\",\n\t\t\t\tfunctionName:\n\t\t\t\t\ttypeof data.function_name === \"string\" ? data.function_name : \"\",\n\t\t\t\targs: decodeFunctionArgs(argsHex),\n\t\t\t\targuments: argsHex,\n\t\t\t\trawResult: typeof data.raw_result === \"string\" ? data.raw_result : \"\",\n\t\t\t\tresult: decodeRawResult(data.raw_result),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\t\tcase \"var_set\": {\n\t\t\tconst data = (event.data ?? {}) as Record<string, unknown>;\n\t\t\tconst rawValue = typeof data.raw_value === \"string\" ? data.raw_value : \"\";\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(data) ?? \"\",\n\t\t\t\tvarName: typeof data.var_name === \"string\" ? data.var_name : \"\",\n\t\t\t\trawValue,\n\t\t\t\tvalue: decodeRawHex(rawValue),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\t\tcase \"map_set\":\n\t\tcase \"map_insert\": {\n\t\t\tconst data = (event.data ?? {}) as Record<string, unknown>;\n\t\t\tconst rawKey = typeof data.raw_key === \"string\" ? data.raw_key : \"\";\n\t\t\tconst rawValue = typeof data.raw_value === \"string\" ? data.raw_value : \"\";\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(data) ?? \"\",\n\t\t\t\tmap: typeof data.map_name === \"string\" ? data.map_name : \"\",\n\t\t\t\trawKey,\n\t\t\t\tkey: decodeRawHex(rawKey),\n\t\t\t\trawValue,\n\t\t\t\tvalue: decodeRawHex(rawValue),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\t\tcase \"map_delete\": {\n\t\t\tconst data = (event.data ?? {}) as Record<string, unknown>;\n\t\t\tconst rawKey = typeof data.raw_key === \"string\" ? data.raw_key : \"\";\n\t\t\treturn {\n\t\t\t\tcontractId: printContractId(data) ?? \"\",\n\t\t\t\tmap: typeof data.map_name === \"string\" ? data.map_name : \"\",\n\t\t\t\trawKey,\n\t\t\t\tkey: decodeRawHex(rawKey),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tlet skipped = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\t// Within a tx the classic clock runs first, then the vm clock: the two\n\t// ordinals are not comparable, so they are never interleaved.\n\tconst clockRank = (e: DispatchUnit[\"event\"]) => (e?.clock === \"vm\" ? 1 : 0);\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\tclockRank(a.event) - clockRank(b.event) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n\t\t}\n\n\t\tconst filter = filterLookup.get(sourceName);\n\t\tconst materialize: MaterializeSpec | undefined =\n\t\t\tfilter && \"materialize\" in filter && filter.materialize !== undefined\n\t\t\t\t? filter.materialize\n\t\t\t\t: undefined;\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler && !materialize) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Declared `prints` is the developer's stated payload shape, so a\n\t\t\t// mismatch is a real defect (a contract upgrade, or a declaration\n\t\t\t// that never matched — the bns-names class, where every event\n\t\t\t// decoded to null for an entire deploy). Skip + log rather than\n\t\t\t// write nulls; never throw, which would wedge the block.\n\t\t\tif (event !== null && filter?.type === \"print_event\" && filter.prints) {\n\t\t\t\tconst printPayload = payload as {\n\t\t\t\t\ttopic?: string;\n\t\t\t\t\tdata?: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst verdict = validatePrintPayload(\n\t\t\t\t\tfilter.prints,\n\t\t\t\t\tprintPayload.topic ?? \"\",\n\t\t\t\t\tprintPayload.data ?? {},\n\t\t\t\t);\n\t\t\t\tif (!verdict.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Print payload does not match declared prints schema\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttopic: printPayload.topic,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t});\n\t\t\t\t\t// Persist for the authed violations GET — never throw.\n\t\t\t\t\tvoid recordPrintViolation({\n\t\t\t\t\t\tsubgraphName: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\tblockHeight: ctx.block.height,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t\tsamplePayload: {\n\t\t\t\t\t\t\ttopic: printPayload.topic ?? \"\",\n\t\t\t\t\t\t\tdata: printPayload.data ?? {},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (materialize) {\n\t\t\t\tconst result = applyMaterializeInsert(\n\t\t\t\t\tmaterialize,\n\t\t\t\t\tpayload,\n\t\t\t\t\tctx,\n\t\t\t\t\tsubgraph.schema,\n\t\t\t\t);\n\t\t\t\tif (!result.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Materialize skipped: required field missing\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: result.reason,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tprocessed++;\n\t\t\t} else if (handler) {\n\t\t\t\tawait handler(payload, ctx);\n\t\t\t\tprocessed++;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n}\n",
13
13
  "import {\n\ttype ClarityValue,\n\ttype TupleCV,\n\tdeserializeCV,\n} from \"@secondlayer/stacks/clarity\";\nimport type { ColumnType } from \"./types.ts\";\n\n/**\n * Empirical print-payload schema inference. Callers (the index print-schema\n * endpoint) extract topic + raw Clarity hex per row; this module deserializes\n * a bounded sample per topic, unifies the observed value shapes into a single\n * structural tree, and renders Clarity/TS/ColumnType views of each field.\n */\n\nexport interface PrintSample {\n\tblockHeight: number;\n\ttopic: string;\n\trawHex: string | null;\n}\n\nexport interface InferredPrintField {\n\t/** Original kebab-case tuple key (the `topic` discriminant is excluded) */\n\tname: string;\n\t/** What handlers see on `e.data` — exact runner camelization */\n\tcamel_name: string;\n\t/** Rendered Clarity type; buff/string lengths are the max observed */\n\tclarity_type: string;\n\t/** Decoded handler value type (uint→bigint, buffer→string, …) */\n\tts_type: string;\n\tcolumn_type: ColumnType;\n\t/** Present in 100% of this topic's decoded samples */\n\talways_present: boolean;\n\t/** Only when optional observed: share of present samples that were some */\n\toptional_some_rate?: number;\n}\n\nexport interface InferredTopicSchema {\n\ttopic: string;\n\tcount: number;\n\tfirst_height: number;\n\tlast_height: number;\n\tnon_tuple: boolean;\n\tfields: InferredPrintField[];\n}\n\n/**\n * Kebab-case → camelCase for print tuple keys. Canonical: the runner uses\n * this on `event.data`, and `camel_name` in inferred print schema is the\n * same function. Distinct from ABI `toCamelCase` (`transfer-STX` stays\n * `transfer-STX` here, becomes `transferSTX` there).\n */\nexport function camelizeDataKey(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** Recursively camelize object keys with the print-payload helper (not ABI\n * `toCamelCase` — that one strips `-STX` and prefixes leading digits). */\nexport function camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelizeDataKey(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Structural type tree. `null` inner = never observed (empty list, none-only\n * optional, one-sided response) and renders as \"?\".\n */\ntype Tree =\n\t| { kind: \"uint\" | \"int\" | \"bool\" | \"principal\" }\n\t| { kind: \"buffer\" | \"ascii\" | \"utf8\"; len: number }\n\t| { kind: \"optional\"; inner: Tree | null }\n\t| { kind: \"list\"; inner: Tree | null }\n\t| {\n\t\t\tkind: \"tuple\";\n\t\t\tcount: number;\n\t\t\tentries: Map<string, { tree: Tree; present: number }>;\n\t }\n\t| { kind: \"response\"; ok: Tree | null; err: Tree | null }\n\t| { kind: \"union\"; members: Tree[] };\n\nfunction cvToTree(cv: ClarityValue): Tree {\n\tswitch (cv.type) {\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn { kind: cv.type };\n\t\tcase \"true\":\n\t\tcase \"false\":\n\t\t\treturn { kind: \"bool\" };\n\t\tcase \"address\":\n\t\tcase \"contract\":\n\t\t\treturn { kind: \"principal\" };\n\t\tcase \"buffer\":\n\t\t\treturn { kind: \"buffer\", len: cv.value.length / 2 };\n\t\tcase \"ascii\":\n\t\t\treturn { kind: \"ascii\", len: cv.value.length };\n\t\tcase \"utf8\":\n\t\t\t// Clarity string-utf8 lengths are byte counts, not code points\n\t\t\treturn { kind: \"utf8\", len: new TextEncoder().encode(cv.value).length };\n\t\tcase \"none\":\n\t\t\treturn { kind: \"optional\", inner: null };\n\t\tcase \"some\":\n\t\t\treturn { kind: \"optional\", inner: cvToTree(cv.value) };\n\t\tcase \"ok\":\n\t\t\treturn { kind: \"response\", ok: cvToTree(cv.value), err: null };\n\t\tcase \"err\":\n\t\t\treturn { kind: \"response\", ok: null, err: cvToTree(cv.value) };\n\t\tcase \"list\": {\n\t\t\tlet inner: Tree | null = null;\n\t\t\tfor (const el of cv.value) {\n\t\t\t\tconst t = cvToTree(el);\n\t\t\t\tinner = inner ? unify(inner, t) : t;\n\t\t\t}\n\t\t\treturn { kind: \"list\", inner };\n\t\t}\n\t\tcase \"tuple\": {\n\t\t\tconst entries = new Map<string, { tree: Tree; present: number }>();\n\t\t\tfor (const [k, v] of Object.entries(cv.value)) {\n\t\t\t\tentries.set(k, { tree: cvToTree(v), present: 1 });\n\t\t\t}\n\t\t\treturn { kind: \"tuple\", count: 1, entries };\n\t\t}\n\t}\n}\n\nfunction unifyNullable(a: Tree | null, b: Tree | null): Tree | null {\n\tif (!a) return b;\n\tif (!b) return a;\n\treturn unify(a, b);\n}\n\n/**\n * Canonical union-member order. Unions hold at most one member per kind\n * (same-kind members always merge), so sorting by kind makes the union —\n * and everything rendered from it — independent of sample order.\n */\nconst UNION_KIND_ORDER: Record<string, number> = {\n\tuint: 0,\n\tint: 1,\n\tbool: 2,\n\tprincipal: 3,\n\tbuffer: 4,\n\tascii: 5,\n\tutf8: 6,\n\tlist: 7,\n\ttuple: 8,\n\tresponse: 9,\n};\n\nfunction makeUnion(members: Tree[]): Tree {\n\tconst sorted = [...members].sort(\n\t\t(a, b) =>\n\t\t\t(UNION_KIND_ORDER[a.kind] ?? 99) - (UNION_KIND_ORDER[b.kind] ?? 99),\n\t);\n\treturn { kind: \"union\", members: sorted };\n}\n\nfunction unify(a: Tree, b: Tree): Tree {\n\t// Optional hoists above unions/conflicts so unification is commutative and\n\t// associative: (optional T) ∪ U = (optional (T ∪ U)) regardless of which\n\t// sample order introduced the optional. Union members are never optional.\n\tif (a.kind === \"optional\" || b.kind === \"optional\") {\n\t\tconst ai = a.kind === \"optional\" ? a.inner : a;\n\t\tconst bi = b.kind === \"optional\" ? b.inner : b;\n\t\treturn { kind: \"optional\", inner: unifyNullable(ai, bi) };\n\t}\n\tif (a.kind === \"union\") return unionAdd(a.members, b);\n\tif (b.kind === \"union\") return unionAdd(b.members, a);\n\tif (a.kind !== b.kind) return makeUnion([a, b]);\n\tswitch (a.kind) {\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\tcase \"bool\":\n\t\tcase \"principal\":\n\t\t\treturn a;\n\t\tcase \"buffer\":\n\t\tcase \"ascii\":\n\t\tcase \"utf8\":\n\t\t\treturn { kind: a.kind, len: Math.max(a.len, (b as typeof a).len) };\n\t\tcase \"list\":\n\t\t\treturn {\n\t\t\t\tkind: \"list\",\n\t\t\t\tinner: unifyNullable(a.inner, (b as typeof a).inner),\n\t\t\t};\n\t\tcase \"response\": {\n\t\t\tconst rb = b as typeof a;\n\t\t\treturn {\n\t\t\t\tkind: \"response\",\n\t\t\t\tok: unifyNullable(a.ok, rb.ok),\n\t\t\t\terr: unifyNullable(a.err, rb.err),\n\t\t\t};\n\t\t}\n\t\tcase \"tuple\": {\n\t\t\tconst tb = b as typeof a;\n\t\t\tconst entries = new Map(\n\t\t\t\t[...a.entries].map(\n\t\t\t\t\t([k, e]) =>\n\t\t\t\t\t\t[k, { ...e }] as [string, { tree: Tree; present: number }],\n\t\t\t\t),\n\t\t\t);\n\t\t\tfor (const [k, e] of tb.entries) {\n\t\t\t\tconst existing = entries.get(k);\n\t\t\t\tentries.set(\n\t\t\t\t\tk,\n\t\t\t\t\texisting\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttree: unify(existing.tree, e.tree),\n\t\t\t\t\t\t\t\tpresent: existing.present + e.present,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: { ...e },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"tuple\", count: a.count + tb.count, entries };\n\t\t}\n\t}\n}\n\n/** Merge into an existing union: join a compatible member, else append. */\nfunction unionAdd(members: Tree[], t: Tree): Tree {\n\tif (t.kind === \"union\") {\n\t\tlet acc: Tree = { kind: \"union\", members };\n\t\tfor (const m of t.members) acc = unify(acc, m);\n\t\treturn acc;\n\t}\n\tconst next = [...members];\n\tfor (let i = 0; i < next.length; i++) {\n\t\tconst member = next[i];\n\t\tif (!member) continue;\n\t\tconst merged = unify(member, t);\n\t\tif (merged.kind !== \"union\") {\n\t\t\tnext[i] = merged;\n\t\t\treturn makeUnion(next);\n\t\t}\n\t}\n\tnext.push(t);\n\treturn makeUnion(next);\n}\n\nfunction wrapOptional(t: Tree): Tree {\n\treturn t.kind === \"optional\" ? t : { kind: \"optional\", inner: t };\n}\n\nfunction renderClarity(t: Tree | null): string {\n\tif (!t) return \"?\";\n\tswitch (t.kind) {\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\tcase \"bool\":\n\t\tcase \"principal\":\n\t\t\treturn t.kind;\n\t\tcase \"buffer\":\n\t\t\treturn `(buff ${t.len})`;\n\t\tcase \"ascii\":\n\t\t\treturn `(string-ascii ${t.len})`;\n\t\tcase \"utf8\":\n\t\t\treturn `(string-utf8 ${t.len})`;\n\t\tcase \"optional\":\n\t\t\treturn `(optional ${renderClarity(t.inner)})`;\n\t\tcase \"list\":\n\t\t\treturn `(list ${renderClarity(t.inner)})`;\n\t\tcase \"response\":\n\t\t\treturn `(response ${renderClarity(t.ok)} ${renderClarity(t.err)})`;\n\t\tcase \"tuple\": {\n\t\t\tconst parts = [...t.entries].map(([k, e]) => {\n\t\t\t\tconst tree = e.present < t.count ? wrapOptional(e.tree) : e.tree;\n\t\t\t\treturn `(${k} ${renderClarity(tree)})`;\n\t\t\t});\n\t\t\treturn `(tuple ${parts.join(\" \")})`;\n\t\t}\n\t\tcase \"union\":\n\t\t\treturn t.members.map(renderClarity).join(\" | \");\n\t}\n}\n\nfunction renderTs(t: Tree | null): string {\n\tif (!t) return \"unknown\";\n\tswitch (t.kind) {\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn \"bigint\";\n\t\tcase \"bool\":\n\t\t\treturn \"boolean\";\n\t\tcase \"principal\":\n\t\tcase \"buffer\":\n\t\tcase \"ascii\":\n\t\tcase \"utf8\":\n\t\t\treturn \"string\";\n\t\tcase \"optional\":\n\t\t\treturn t.inner ? `${renderTs(t.inner)} | null` : \"unknown | null\";\n\t\tcase \"list\": {\n\t\t\tconst inner = renderTs(t.inner);\n\t\t\treturn inner.includes(\" | \") ? `(${inner})[]` : `${inner}[]`;\n\t\t}\n\t\tcase \"response\": {\n\t\t\t// Runtime unwraps both sides → handler sees the union of inner types\n\t\t\tconst sides = [...new Set([renderTs(t.ok), renderTs(t.err)])];\n\t\t\treturn sides.join(\" | \");\n\t\t}\n\t\tcase \"tuple\": {\n\t\t\tconst parts = [...t.entries].map(([k, e]) => {\n\t\t\t\tconst opt = e.present < t.count ? \"?\" : \"\";\n\t\t\t\treturn `${camelizeDataKey(k)}${opt}: ${renderTs(e.tree)}`;\n\t\t\t});\n\t\t\treturn `{ ${parts.join(\"; \")} }`;\n\t\t}\n\t\tcase \"union\":\n\t\t\treturn [...new Set(t.members.map((m) => renderTs(m)))].join(\" | \");\n\t}\n}\n\nfunction toColumnType(t: Tree | null): ColumnType {\n\tif (!t) return \"jsonb\";\n\tswitch (t.kind) {\n\t\tcase \"uint\":\n\t\t\treturn \"uint\";\n\t\tcase \"int\":\n\t\t\treturn \"int\";\n\t\tcase \"bool\":\n\t\t\treturn \"boolean\";\n\t\tcase \"principal\":\n\t\t\treturn \"principal\";\n\t\tcase \"buffer\":\n\t\tcase \"ascii\":\n\t\tcase \"utf8\":\n\t\t\treturn \"text\";\n\t\tcase \"list\":\n\t\tcase \"tuple\":\n\t\t\treturn \"jsonb\";\n\t\t// Nullability is carried by always_present/optional_some_rate, not the column type\n\t\tcase \"optional\":\n\t\t\treturn toColumnType(t.inner);\n\t\tcase \"response\":\n\t\t\treturn t.ok ? toColumnType(t.ok) : \"jsonb\";\n\t\tcase \"union\":\n\t\t\treturn \"jsonb\";\n\t}\n}\n\n/** Per-topic deserialization budget: spread across the newest + oldest rows that have raw hex */\nconst MAX_DECODED_PER_TOPIC_NEWEST = 75;\nconst MAX_DECODED_PER_TOPIC_OLDEST = 25;\n\n/**\n * Infers per-topic field schemas from sampled print events. Counts and\n * height bounds cover ALL rows of a topic (cheap); only a bounded subset is\n * deserialized for typing. Rows with missing/undecodable hex still count but\n * contribute nothing to typing.\n */\nexport function inferPrintTopics(\n\tsamples: PrintSample[],\n): InferredTopicSchema[] {\n\tconst groups = new Map<string, PrintSample[]>();\n\tfor (const s of samples) {\n\t\tconst group = groups.get(s.topic);\n\t\tif (group) group.push(s);\n\t\telse groups.set(s.topic, [s]);\n\t}\n\n\tconst out: InferredTopicSchema[] = [];\n\tfor (const [topic, rows] of groups) {\n\t\tlet first = Number.POSITIVE_INFINITY;\n\t\tlet last = Number.NEGATIVE_INFINITY;\n\t\tfor (const r of rows) {\n\t\t\tif (r.blockHeight < first) first = r.blockHeight;\n\t\t\tif (r.blockHeight > last) last = r.blockHeight;\n\t\t}\n\n\t\t// Spend the decode budget only on rows that have raw hex, so null-hex\n\t\t// rows (still counted in totals/heights) don't starve typing.\n\t\tconst withHex = [...rows]\n\t\t\t.filter((r): r is PrintSample & { rawHex: string } => r.rawHex !== null)\n\t\t\t.sort((a, b) => b.blockHeight - a.blockHeight);\n\t\tconst budget = MAX_DECODED_PER_TOPIC_NEWEST + MAX_DECODED_PER_TOPIC_OLDEST;\n\t\tconst picked =\n\t\t\twithHex.length <= budget\n\t\t\t\t? withHex\n\t\t\t\t: [\n\t\t\t\t\t\t...withHex.slice(0, MAX_DECODED_PER_TOPIC_NEWEST),\n\t\t\t\t\t\t...withHex.slice(-MAX_DECODED_PER_TOPIC_OLDEST),\n\t\t\t\t\t];\n\n\t\tconst tuples: TupleCV[] = [];\n\t\tlet decoded = 0;\n\t\tfor (const p of picked) {\n\t\t\ttry {\n\t\t\t\tconst cv = deserializeCV(p.rawHex);\n\t\t\t\tdecoded++;\n\t\t\t\tif (cv.type === \"tuple\") tuples.push(cv);\n\t\t\t} catch {\n\t\t\t\t// undecodable hex contributes nothing to typing\n\t\t\t}\n\t\t}\n\n\t\t// Only claim non_tuple when something actually decoded to a non-tuple;\n\t\t// zero decoded samples is \"no evidence\", not a non-tuple payload.\n\t\tconst nonTuple = decoded > 0 && tuples.length === 0;\n\t\tconst fields: InferredPrintField[] = [];\n\t\tif (!nonTuple) {\n\t\t\tconst stats = new Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\ttree: Tree;\n\t\t\t\t\tpresent: number;\n\t\t\t\t\tnoneCount: number;\n\t\t\t\t\toptionalSeen: boolean;\n\t\t\t\t}\n\t\t\t>();\n\t\t\tfor (const t of tuples) {\n\t\t\t\tfor (const [key, value] of Object.entries(t.value)) {\n\t\t\t\t\t// `topic` is the discriminant, never payload data (runner strips it)\n\t\t\t\t\tif (key === \"topic\") continue;\n\t\t\t\t\tconst tree = cvToTree(value);\n\t\t\t\t\tconst existing = stats.get(key);\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\texisting.present++;\n\t\t\t\t\t\texisting.tree = unify(existing.tree, tree);\n\t\t\t\t\t\tif (value.type === \"none\") existing.noneCount++;\n\t\t\t\t\t\tif (value.type === \"none\" || value.type === \"some\") {\n\t\t\t\t\t\t\texisting.optionalSeen = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstats.set(key, {\n\t\t\t\t\t\t\ttree,\n\t\t\t\t\t\t\tpresent: 1,\n\t\t\t\t\t\t\tnoneCount: value.type === \"none\" ? 1 : 0,\n\t\t\t\t\t\t\toptionalSeen: value.type === \"none\" || value.type === \"some\",\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [name, st] of [...stats].sort(([a], [b]) =>\n\t\t\t\ta.localeCompare(b),\n\t\t\t)) {\n\t\t\t\tconst field: InferredPrintField = {\n\t\t\t\t\tname,\n\t\t\t\t\tcamel_name: camelizeDataKey(name),\n\t\t\t\t\tclarity_type: renderClarity(st.tree),\n\t\t\t\t\tts_type: renderTs(st.tree),\n\t\t\t\t\tcolumn_type: toColumnType(st.tree),\n\t\t\t\t\talways_present: st.present === tuples.length,\n\t\t\t\t};\n\t\t\t\tif (st.optionalSeen) {\n\t\t\t\t\tfield.optional_some_rate = (st.present - st.noneCount) / st.present;\n\t\t\t\t}\n\t\t\t\tfields.push(field);\n\t\t\t}\n\t\t}\n\n\t\tout.push({\n\t\t\ttopic,\n\t\t\tcount: rows.length,\n\t\t\tfirst_height: first,\n\t\t\tlast_height: last,\n\t\t\tnon_tuple: nonTuple,\n\t\t\tfields,\n\t\t});\n\t}\n\n\treturn out.sort((a, b) => b.count - a.count);\n}\n",
14
14
  "import type {\n\tMaterializeColumn,\n\tMaterializeSpec,\n\tSubgraphColumn,\n\tSubgraphSchema,\n} from \"../types.ts\";\nimport type { BlockMeta, TxMeta } from \"./context.ts\";\n\nexport type MaterializeBuildResult =\n\t| { ok: true; row: Record<string, unknown> }\n\t| { ok: false; reason: string };\n\nfunction resolveColumn(\n\tcol: MaterializeColumn,\n\tevent: Record<string, unknown>,\n\ttx: TxMeta,\n\tblock: BlockMeta,\n): { ok: true; value: unknown } | { ok: false; missing: string } {\n\tif (\"fromTx\" in col) {\n\t\treturn { ok: true, value: tx[col.fromTx] };\n\t}\n\tif (\"fromBlock\" in col) {\n\t\treturn { ok: true, value: block[col.fromBlock] };\n\t}\n\tconst data = event.data;\n\tconst dataObj =\n\t\tdata !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t? (data as Record<string, unknown>)\n\t\t\t: undefined;\n\tif (dataObj && Object.prototype.hasOwnProperty.call(dataObj, col.from)) {\n\t\treturn { ok: true, value: dataObj[col.from] };\n\t}\n\t// `topic` is a native print payload field, not always in `data`.\n\tif (col.from === \"topic\" && \"topic\" in event) {\n\t\treturn { ok: true, value: event.topic };\n\t}\n\t// Native FT/STX-style top-level fields (and any other payload keys).\n\tif (Object.prototype.hasOwnProperty.call(event, col.from)) {\n\t\treturn { ok: true, value: event[col.from] };\n\t}\n\treturn { ok: false, missing: col.from };\n}\n\n/**\n * Build an insert row from a static materialize spec. Missing optional\n * columns become null; missing required columns → skip (caller logs).\n */\nexport function buildMaterializeRow(\n\tspec: MaterializeSpec,\n\tevent: Record<string, unknown>,\n\tctx: { tx: TxMeta; block: BlockMeta },\n\ttableColumns: Record<string, SubgraphColumn>,\n): MaterializeBuildResult {\n\tconst row: Record<string, unknown> = {};\n\tfor (const [colName, mapping] of Object.entries(spec.columns)) {\n\t\tconst resolved = resolveColumn(mapping, event, ctx.tx, ctx.block);\n\t\tif (!resolved.ok) {\n\t\t\tconst colDef = tableColumns[colName];\n\t\t\tif (colDef?.nullable) {\n\t\t\t\trow[colName] = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: `required materialize field \"${resolved.missing}\" missing for column \"${colName}\"`,\n\t\t\t};\n\t\t}\n\t\trow[colName] = resolved.value ?? null;\n\t}\n\treturn { ok: true, row };\n}\n\n/** Apply materialize insert when the source has a spec; returns skip reason. */\nexport function applyMaterializeInsert(\n\tspec: MaterializeSpec,\n\tevent: Record<string, unknown>,\n\tctx: {\n\t\ttx: TxMeta;\n\t\tblock: BlockMeta;\n\t\tinsert: (table: string, row: Record<string, unknown>) => void;\n\t},\n\tschema: SubgraphSchema,\n): { ok: true } | { ok: false; reason: string } {\n\tconst table = schema[spec.table];\n\tif (!table) {\n\t\treturn { ok: false, reason: `materialize table \"${spec.table}\" missing` };\n\t}\n\tconst built = buildMaterializeRow(spec, event, ctx, table.columns);\n\tif (!built.ok) return built;\n\tctx.insert(spec.table, built.row);\n\treturn { ok: true };\n}\n",
15
15
  "import type { ColumnType, PrintField } from \"../types.ts\";\n\n/**\n * Runtime validation of a decoded print payload against a source's declared\n * `prints` schema.\n *\n * Declaring `prints` is the opt-in that makes strictness safe: the developer\n * has stated the shape, so a mismatch is a real defect (a contract upgrade,\n * or a hand-written declaration that never matched — the bns-names class of\n * bug, where a handler read flat `data.name` while BNS-V2 emitted a nested\n * tuple, and every event silently decoded to null for a whole deploy).\n *\n * Failure mode is SKIP + LOG, never throw: throwing would fail the block, and\n * a poisoned block that can never advance is incompatible with the\n * checkpoint model. One bad event is dropped and counted; the rest of the\n * block commits.\n */\n\nconst COLUMN_TYPES = new Set<string>([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nfunction isColumnType(field: PrintField): field is ColumnType {\n\treturn typeof field === \"string\" && COLUMN_TYPES.has(field);\n}\n\n/** Does a decoded value match one declared field? */\nfunction matchesField(field: PrintField, value: unknown): boolean {\n\tif (isColumnType(field)) {\n\t\tswitch (field) {\n\t\t\tcase \"uint\":\n\t\t\tcase \"int\":\n\t\t\t\treturn typeof value === \"bigint\" || typeof value === \"number\";\n\t\t\tcase \"boolean\":\n\t\t\t\treturn typeof value === \"boolean\";\n\t\t\tcase \"text\":\n\t\t\tcase \"principal\":\n\t\t\tcase \"timestamp\":\n\t\t\t\t// Buffers decode to strings; principals too. Accept any scalar the\n\t\t\t\t// decoder can render, but reject objects/arrays.\n\t\t\t\treturn (\n\t\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\t\ttypeof value === \"bigint\"\n\t\t\t\t);\n\t\t\tcase \"jsonb\":\n\t\t\t\t// Deliberately permissive: `jsonb` is the \"shape unknown\" escape.\n\t\t\t\treturn value !== undefined;\n\t\t}\n\t}\n\tif (typeof field !== \"object\" || field === null) return false;\n\tif (\"optional\" in field) {\n\t\treturn (\n\t\t\tvalue === undefined || value === null || matchesField(field.type, value)\n\t\t);\n\t}\n\tif (\"tuple\" in field) {\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn matchesTopic(field.tuple, value as Record<string, unknown>).ok;\n\t}\n\tif (\"list\" in field) {\n\t\treturn (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.every((item) => matchesField(field.list, item))\n\t\t);\n\t}\n\treturn false;\n}\n\nexport type PrintValidationResult =\n\t| { ok: true }\n\t| { ok: false; reason: string };\n\n/** Validate a decoded payload object against one topic's declared fields. */\nexport function matchesTopic(\n\tdeclared: Record<string, PrintField>,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tfor (const [name, field] of Object.entries(declared)) {\n\t\tconst present = name in data;\n\t\tconst optional =\n\t\t\ttypeof field === \"object\" && field !== null && \"optional\" in field;\n\t\tif (!present) {\n\t\t\tif (optional) continue;\n\t\t\treturn { ok: false, reason: `missing declared field \"${name}\"` };\n\t\t}\n\t\tif (!matchesField(field, data[name])) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: `field \"${name}\" does not match its declared type (got ${describe(data[name])})`,\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"array\";\n\treturn typeof value;\n}\n\n/**\n * Validate one decoded print event against a source's `prints` declaration.\n * Returns `{ ok: true }` when no declaration covers this topic (undeclared\n * topics are not the developer's stated contract, so they pass through).\n */\nexport function validatePrintPayload(\n\tprints: Record<string, Record<string, PrintField>> | undefined,\n\ttopic: string,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tif (!prints) return { ok: true };\n\tconst declared = prints[topic];\n\tif (!declared) return { ok: true };\n\treturn matchesTopic(declared, data);\n}\n",
16
16
  "import { getTargetDb } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { sql } from \"kysely\";\n\n/** Keep at most this many print-validate skips per subgraph. */\nexport const VIOLATIONS_CAP_PER_SUBGRAPH = 100;\n\nexport interface PrintViolationInput {\n\tsubgraphName: string;\n\tsourceName: string;\n\tblockHeight: number;\n\ttxId: string;\n\treason: string;\n\t/** Bounded decoded camel payload — never raw_value hex dumps. */\n\tsamplePayload: Record<string, unknown>;\n}\n\nfunction jsonSafe(value: unknown): unknown {\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (value === null || value === undefined) return value;\n\tif (Array.isArray(value)) return value.map(jsonSafe);\n\tif (typeof value === \"object\") {\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n\t\t\tout[k] = jsonSafe(v);\n\t\t}\n\t\treturn out;\n\t}\n\treturn value;\n}\n\ntype ViolationRecorder = (input: PrintViolationInput) => Promise<void>;\n\nasync function defaultRecordPrintViolation(\n\tinput: PrintViolationInput,\n): Promise<void> {\n\ttry {\n\t\tconst db = getTargetDb();\n\t\tconst sample = jsonSafe(input.samplePayload) as Record<string, unknown>;\n\t\tawait db\n\t\t\t.insertInto(\"subgraph_violations\")\n\t\t\t.values({\n\t\t\t\tsubgraph_name: input.subgraphName,\n\t\t\t\tsource_name: input.sourceName,\n\t\t\t\tblock_height: input.blockHeight,\n\t\t\t\ttx_id: input.txId,\n\t\t\t\treason: input.reason,\n\t\t\t\tsample_payload: sample,\n\t\t\t})\n\t\t\t.execute();\n\n\t\t// Delete oldest beyond the cap (same write path; no separate sweep).\n\t\tawait sql`\n\t\t\tDELETE FROM subgraph_violations\n\t\t\tWHERE id IN (\n\t\t\t\tSELECT id FROM subgraph_violations\n\t\t\t\tWHERE subgraph_name = ${input.subgraphName}\n\t\t\t\tORDER BY seen_at DESC\n\t\t\t\tOFFSET ${VIOLATIONS_CAP_PER_SUBGRAPH}\n\t\t\t)\n\t\t`.execute(db);\n\t} catch (err) {\n\t\tlogger.warn(\"Failed to record print violation\", {\n\t\t\tsubgraph: input.subgraphName,\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t}\n}\n\nlet recorder: ViolationRecorder = defaultRecordPrintViolation;\n\n/** Test seam — swap the persistence backend without mocking getTargetDb. */\nexport function setPrintViolationRecorder(fn: ViolationRecorder | null): void {\n\trecorder = fn ?? defaultRecordPrintViolation;\n}\n\n/**\n * Persist a print-validate skip on the control plane and trim to the cap.\n * Failures are logged, never thrown — a poisoned block must still commit.\n */\nexport async function recordPrintViolation(\n\tinput: PrintViolationInput,\n): Promise<void> {\n\tawait recorder(input);\n}\n",
17
- "import { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport { recordGapBatch } from \"@secondlayer/shared/db/queries/subgraph-gaps\";\nimport { advanceOperationCursor } from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\trecordLiveError,\n\trecordLiveProgress,\n\trecordSubgraphProcessed,\n\trewindLiveProgress,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport {\n\ttype BlockMeta,\n\tJOURNAL_RETENTION_BLOCKS,\n\tSubgraphContext,\n\ttype TxMeta,\n} from \"./context.ts\";\nimport { emitWebhookOutbox } from \"./outbox-emit.ts\";\nimport { buildEventPayload, runHandlers } from \"./runner.ts\";\nimport { sandboxEnabled } from \"./sandbox/flag.ts\";\nimport { evictSandboxWorker, runHandlersSandboxed } from \"./sandbox/host.ts\";\nimport {\n\ttype EventRecord,\n\ttype TxRecord,\n\tmatchSources,\n\treadPath,\n} from \"./source-matcher.ts\";\nimport { matcher } from \"./webhook-state.ts\";\n\n/**\n * The data-plane route for a subgraph: which schema its tables live in and the\n * managed target DB the writes/reads land on. Cached per subgraph to avoid a\n * per-block lookup; invalidated on redeploy via\n * {@link invalidateSubgraphRoute}.\n *\n * Also carries the f071 Stage A sandbox-dispatch inputs\n * (`sandboxWorkers`/`handlerCode`/`version`) — cheap to keep alongside the\n * route since `resolveRoute` already selects the full `subgraphs` row; kept\n * in lockstep with the same cache invalidation edge (redeploys change\n * `handler_code`/`version` together).\n */\ninterface SubgraphRoute {\n\tschemaName: string;\n\tdataDb: Kysely<Database>;\n\t/** `subgraphs.sandbox_workers` — combined with the global env gate by\n\t * `sandboxEnabled()`. Default false for every row; nothing in committed\n\t * code sets it true (f071 Stage A stays dark). */\n\tsandboxWorkers: boolean;\n\thandlerCode: string | null;\n\tversion: string;\n}\nconst routeCache = new Map<string, SubgraphRoute>();\n\nasync function resolveRoute(\n\tsubgraphName: string,\n\ttargetDb: Kysely<Database>,\n): Promise<SubgraphRoute> {\n\tconst cached = routeCache.get(subgraphName);\n\tif (cached) return cached;\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\tconst route: SubgraphRoute = {\n\t\tschemaName: row?.schema_name ?? pgSchemaName(subgraphName),\n\t\tdataDb: targetDb,\n\t\tsandboxWorkers: row?.sandbox_workers === true,\n\t\thandlerCode: row?.handler_code ?? null,\n\t\tversion: row?.version ?? \"\",\n\t};\n\trouteCache.set(subgraphName, route);\n\t// f071 Stage A observability: state which handler-execution path this\n\t// subgraph resolved to, once per route-cache resolution (process start,\n\t// or the next block after a redeploy invalidates the cache) — never per\n\t// block, so this can't spam logs. Doesn't change dispatch: reads the same\n\t// `sandboxEnabled` inputs the ternary at the call site below uses.\n\tlogger.info(\"subgraph handler dispatch path resolved\", {\n\t\tsubgraph: subgraphName,\n\t\tpath: sandboxEnabled({ sandbox_workers: route.sandboxWorkers })\n\t\t\t? \"sandbox\"\n\t\t\t: \"in-process\",\n\t});\n\treturn route;\n}\n\n/** Drop a subgraph's cached route — call on redeploy/delete (conn may\n * change). Also evicts any warm sandbox subprocess for this subgraph\n * (f071 Stage A `host.ts`) on the same edge: a redeploy can change\n * `handler_code`/`version` together, and a stale warm\n * subprocess must not survive past this invalidation any more than the\n * cached route does. A no-op today since nothing sets `sandbox_workers`,\n * but keeps the pool's documented invalidation contract honest for when it\n * is. */\nexport function invalidateSubgraphRoute(subgraphName: string): void {\n\trouteCache.delete(subgraphName);\n\tevictSandboxWorker(subgraphName);\n}\n\n/**\n * Resolve each distinct trait used by a subgraph's sources to its conforming\n * contract-id set, as of `blockHeight`, from the contract registry. Empty map\n * when no source is trait-scoped (the common case → no DB work).\n */\n/**\n * Resolve each factory-scoped source's address set for this block.\n *\n * Two parts, and the ORDER is the guarantee:\n * 1. addresses persisted by earlier blocks (`block_height <= blockHeight`,\n * so a reindex sees exactly what the live walk saw), then\n * 2. addresses revealed by THIS block's events — computed before matching,\n * so a contract discovered in block N receives its own block-N events.\n * Without this pass the first event from every discovered contract is\n * silently lost.\n */\n/**\n * Exported as a test seam. Both guarantees this function carries — a contract\n * discovered in block N receiving its OWN block-N events, and the persisted set\n * being height-stamped so a reorg can roll it back — were asserted only by\n * comment until now.\n */\nexport async function resolveFactoryContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\ttxs: TxRecord[],\n\tevts: EventRecord[],\n): Promise<{\n\tresolved: Map<string, ReadonlySet<string>>;\n\tdiscovered: Array<{ sourceName: string; address: string }>;\n}> {\n\t// Keyed by the DISCOVERING source (`factory.from`), not the consuming one:\n\t// several sources can share one factory, and this way the extraction runs\n\t// once per discovering source rather than once per consumer.\n\tconst factories = new Map<string, { from: string; field: string }>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst factory = (source as { factory?: { from: string; field: string } })\n\t\t\t.factory;\n\t\tif (factory) factories.set(factory.from, factory);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tconst discovered: Array<{ sourceName: string; address: string }> = [];\n\tif (factories.size === 0) return { resolved, discovered };\n\n\tfor (const [discoveringSource, factory] of factories) {\n\t\tconst known = new Set<string>();\n\t\t// 1. Everything revealed at or below this height.\n\t\ttry {\n\t\t\tconst rows = await sql<{ address: string }>`\n\t\t\t\tSELECT address FROM ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\tWHERE source_name = ${discoveringSource} AND block_height <= ${blockHeight}\n\t\t\t`.execute(db);\n\t\t\tfor (const row of rows.rows) known.add(row.address);\n\t\t} catch {\n\t\t\t// Table absent (first deploy before DDL, or a non-factory subgraph):\n\t\t\t// treat as an empty set rather than failing the block.\n\t\t}\n\n\t\t// 2. This block's own reveals — before matching, so same-block events\n\t\t// from a new contract are not dropped.\n\t\tconst discovering = subgraph.sources[factory.from];\n\t\tif (discovering) {\n\t\t\tconst matches = matchSources(\n\t\t\t\t{ [factory.from]: discovering },\n\t\t\t\ttxs,\n\t\t\t\tevts,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t);\n\t\t\tfor (const match of matches) {\n\t\t\t\tfor (const event of match.events ?? []) {\n\t\t\t\t\tconst payload = buildEventPayload(discovering, match.tx, event);\n\t\t\t\t\tconst value = readPath(payload, factory.field);\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\tvalue.length > 0 &&\n\t\t\t\t\t\t!known.has(value)\n\t\t\t\t\t) {\n\t\t\t\t\t\tknown.add(value);\n\t\t\t\t\t\tdiscovered.push({ sourceName: discoveringSource, address: value });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresolved.set(discoveringSource, known);\n\t}\n\treturn { resolved, discovered };\n}\n\n/** Persist this block's discoveries, stamped with the block that revealed\n * them so the reorg handler can roll them back. */\nasync function persistFactoryDiscoveries(\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\tdiscovered: Array<{ sourceName: string; address: string }>,\n): Promise<void> {\n\tif (discovered.length === 0) return;\n\tfor (const { sourceName, address } of discovered) {\n\t\tawait sql`\n\t\t\tINSERT INTO ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\t(source_name, address, block_height)\n\t\t\tVALUES (${sourceName}, ${address}, ${blockHeight})\n\t\t\tON CONFLICT (source_name, address) DO NOTHING\n\t\t`.execute(db);\n\t}\n}\n\nasync function resolveTraitContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tdb: Kysely<Database>,\n): Promise<Map<string, ReadonlySet<string>>> {\n\tconst traits = new Set<string>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst trait = (source as { trait?: string }).trait;\n\t\tif (trait) traits.add(trait);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tfor (const trait of traits) {\n\t\tconst ids = await resolveTraitContractIds(db, trait, blockHeight);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\nexport interface ProcessBlockTiming {\n\ttotalMs: number;\n\thandlerMs: number;\n\tflushMs: number;\n}\n\nexport interface ProcessBlockResult {\n\tblockHeight: number;\n\tmatched: number;\n\tprocessed: number;\n\terrors: number;\n\tskipped: boolean;\n\ttiming?: ProcessBlockTiming;\n}\n\n/**\n * Process a single block through a single subgraph's pipeline.\n *\n * Flow:\n * 1. Load block + txs + events from DB\n * 2. Run source matcher\n * 3. Run handlers with SubgraphContext\n * 4. Flush context (commit writes atomically)\n * 5. Update subgraph.last_processed_block\n */\nexport interface PreloadedBlockData {\n\tblock: import(\"@secondlayer/shared/db\").Block;\n\ttxs: import(\"@secondlayer/shared/db\").Transaction[];\n\tevents: import(\"@secondlayer/shared/db\").Event[];\n}\n\nexport interface ProcessBlockOptions {\n\t/** Skip updating last_processed_block in DB (reindex batches this externally). */\n\tskipProgressUpdate?: boolean;\n\t/** Pre-loaded block data — skips DB reads when provided (used by batch catch-up). */\n\tpreloaded?: PreloadedBlockData;\n\t/**\n\t * Crash-safe sequential processing. Two checkpoint scopes:\n\t * - `{ status }` (reindex): a written block commits\n\t * `subgraphs.last_processed_block = blockHeight` in the SAME transaction\n\t * as its writes; replays skip at/below the cursor. Only for strictly\n\t * ascending walks over the subgraph's own cursor.\n\t * - `{ operationId }` (backfill): same guarantee against the OPERATION's\n\t * own `cursor_block` — backfills legitimately revisit heights below the\n\t * live cursor, so they must never checkpoint (or read) the subgraph\n\t * cursor. The advance is a CONDITIONAL monotonic UPDATE: concurrent\n\t * writers serialize on it, and the loser's whole block tx rolls back\n\t * (surfaced as `skipped`, never an error/gap).\n\t * Either way: a crash can never leave committed deltas ahead of the\n\t * relevant checkpoint.\n\t */\n\tatomicProgress?: { status: string } | { operationId: string };\n\t/**\n\t * Reorg rewind (f069): set exclusively by `reorg.ts`'s fork-block\n\t * reprocess. Bypasses the live-path replay guard (a fork block's height\n\t * is, by construction, at or below the current cursor — the guard would\n\t * otherwise skip it) and writes the checkpoint via\n\t * `rewindLiveProgress` (unconditional — a rewind's whole point is\n\t * moving the cursor *backward*, which the live path's conditional\n\t * advance would refuse). Safe only because the reorg path holds a\n\t * transaction-scoped advisory lock across its whole\n\t * delete+reprocess+rewind sequence, so nothing else can interleave a\n\t * forward write. Never set this outside `reorg.ts`.\n\t */\n\treorgRewind?: true;\n\t/** The subgraph row's uuid. Required to record a gap row when a block\n\t * processes with handler errors — `subgraph_gaps.subgraph_id` is NOT NULL.\n\t * Absent on paths that pass `skipProgressUpdate` (they record gaps\n\t * themselves, see reindex.ts). */\n\tsubgraphId?: string;\n}\n\n/** Thrown inside the block tx when a racing writer already covered this\n * height — rolls the tx back; processBlock converts it to `skipped`. The\n * winner committed the block, so this is success-shaped, never a gap. */\nclass CursorRaceLostError extends Error {\n\tconstructor(operationId: string, height: number) {\n\t\tsuper(`op ${operationId} lost cursor race at block ${height}`);\n\t\tthis.name = \"CursorRaceLostError\";\n\t}\n}\n\n/** Live-path sibling of {@link CursorRaceLostError}: thrown when the live\n * path's conditional `recordLiveProgress` advance loses to a racing\n * writer that already committed a higher (or equal) `last_processed_block`\n * for this subgraph. Same success-shaped handling — the winner's commit\n * stands, so this becomes `result.skipped = true`, never an error/gap. */\nclass LiveCursorRaceLostError extends Error {\n\tconstructor(subgraphName: string, height: number) {\n\t\tsuper(`live cursor race lost for ${subgraphName} at block ${height}`);\n\t\tthis.name = \"LiveCursorRaceLostError\";\n\t}\n}\n\nfunction opCursorMode(\n\topts?: ProcessBlockOptions,\n): { operationId: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"operationId\" in ap ? ap : undefined;\n}\n\n/** True only for the reorg fork-block reprocess — see `reorgRewind` on\n * {@link ProcessBlockOptions}. */\nfunction isReorgRewind(opts?: ProcessBlockOptions): boolean {\n\treturn opts?.reorgRewind === true;\n}\n\nfunction statusMode(\n\topts?: ProcessBlockOptions,\n): { status: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"status\" in ap ? ap : undefined;\n}\n\n/** Default per-block retry schedule before a failure counts as persistent. */\nexport const BLOCK_RETRY_DELAYS_MS: number[] = [500, 2_000, 5_000];\n\n/**\n * Journal pre-images on the live path only. Deep reindex/backfill heights\n * (skipProgressUpdate) are past finality — a reorg can't reach them, so\n * journaling would be pure churn for the pruner.\n */\nfunction journalEnabled(opts?: ProcessBlockOptions): boolean {\n\treturn !opts?.skipProgressUpdate;\n}\n\n/**\n * processBlock with bounded retries. Throws the last error once the schedule\n * is exhausted — callers decide whether that halts the walk (strict paths) or\n * records a gap (backfill). Never advances any cursor on failure.\n */\nexport async function processBlockWithRetry(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n\tretryDelaysMs: number[] = BLOCK_RETRY_DELAYS_MS,\n): Promise<ProcessBlockResult> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {\n\t\ttry {\n\t\t\treturn await processBlock(subgraph, subgraphName, blockHeight, opts);\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t\tconst delay = retryDelaysMs[attempt];\n\t\t\tif (delay === undefined) break;\n\t\t\tlogger.warn(\"Block processing failed, retrying\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t\tretryInMs: delay,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport async function processBlock(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n): Promise<ProcessBlockResult> {\n\tconst targetDb = getTargetDb();\n\tconst blockStart = performance.now();\n\tconst result: ProcessBlockResult = {\n\t\tblockHeight,\n\t\tmatched: 0,\n\t\tprocessed: 0,\n\t\terrors: 0,\n\t\tskipped: false,\n\t};\n\n\t// 1. Load block from source DB (shared indexer) — use pre-loaded data if available\n\tlet block: PreloadedBlockData[\"block\"] | undefined;\n\tlet txs: PreloadedBlockData[\"txs\"];\n\tlet evts: PreloadedBlockData[\"events\"];\n\tif (opts?.preloaded) {\n\t\tblock = opts.preloaded.block;\n\t\ttxs = opts.preloaded.txs;\n\t\tevts = opts.preloaded.events;\n\t} else {\n\t\t// The block source returns canonical blocks only, so a missing entry\n\t\t// means the block is absent or non-canonical — skip either way.\n\t\tconst data = (\n\t\t\tawait resolveBlockSource(subgraph).loadBlockRange(\n\t\t\t\tblockHeight,\n\t\t\t\tblockHeight,\n\t\t\t)\n\t\t).get(blockHeight);\n\t\tif (!data) {\n\t\t\tlogger.debug(\"Block not found or non-canonical for subgraph processing\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tblock = data.block;\n\t\ttxs = data.txs;\n\t\tevts = data.events;\n\t}\n\n\t// 3. Match source. Trait-scoped sources ({ trait: \"sip-010\" }) resolve to the\n\t// set of conforming contracts AS OF this block (deploy_height ≤ blockHeight),\n\t// so a reindex backfills a token's full history even if it was classified\n\t// after deploy. Resolution is done here (DB access) so the matcher stays pure.\n\t// Route first: the factory set lives in this subgraph's pg schema, and it\n\t// must resolve BEFORE matching. `resolveRoute` is cached per subgraph.\n\tconst route = await resolveRoute(subgraphName, targetDb);\n\tconst schemaName = route.schemaName;\n\n\tconst traitContracts = await resolveTraitContracts(\n\t\tsubgraph,\n\t\tblockHeight,\n\t\ttargetDb,\n\t);\n\t// Factory sets resolve BEFORE matching so a contract revealed in this\n\t// block receives its own block-N events (see resolveFactoryContracts).\n\tconst { resolved: factoryContracts, discovered } =\n\t\tawait resolveFactoryContracts(\n\t\t\tsubgraph,\n\t\t\tblockHeight,\n\t\t\tschemaName,\n\t\t\ttargetDb,\n\t\t\ttxs,\n\t\t\tevts,\n\t\t);\n\tconst matched = matchSources(\n\t\tsubgraph.sources,\n\t\ttxs,\n\t\tevts,\n\t\ttraitContracts,\n\t\tfactoryContracts,\n\t);\n\tresult.matched = matched.length;\n\n\tif (matched.length === 0) {\n\t\tif (!opts?.skipProgressUpdate) {\n\t\t\tif (isReorgRewind(opts)) {\n\t\t\t\t// Fork block itself may match nothing for this subgraph — the\n\t\t\t\t// rewind still must land (unconditional, may move backward).\n\t\t\t\tawait rewindLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t\t} else {\n\t\t\t\t// Promote-but-never-unpark: unconditional \"active\" stamping let the\n\t\t\t\t// live walk overwrite \"reindexing\" set by a queued reindex op,\n\t\t\t\t// flapping the subgraph back into catch-up (and into collision with\n\t\t\t\t// the op's schema drop). Conditional advance (f069): a no-write\n\t\t\t\t// block can't race-lose in any way that matters (nothing was\n\t\t\t\t// written), so a `false` return here is a silent no-op — the\n\t\t\t\t// cursor simply stays at whatever a racing writer already set it\n\t\t\t\t// to.\n\t\t\t\tawait recordLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t// 4. Data plane (managed target DB) — resolved above, since factory-set\n\t// resolution needs the schema name.\n\tconst blockMeta: BlockMeta = {\n\t\theight: block.height,\n\t\thash: block.hash,\n\t\ttimestamp: block.timestamp,\n\t\tburnBlockHeight: block.burn_block_height,\n\t\tindexBlockHash: block.index_block_hash,\n\t};\n\tconst initialTx: TxMeta = {\n\t\ttxId: \"\",\n\t\tsender: \"\",\n\t\ttype: \"\",\n\t\tstatus: \"\",\n\t};\n\n\tlet handlerMs = 0;\n\tlet flushMs = 0;\n\n\t// Progress + health writes — always on the managed DB, identical in both\n\t// modes (the subgraphs control-plane table lives in target). Only ever\n\t// reached with real work to do on the live catch-up path and the reorg\n\t// rewind path (both leave `skipProgressUpdate` unset); reindex/backfill\n\t// always pass `skipProgressUpdate: true` and return above.\n\tconst applyProgress = async (\n\t\ttx: Transaction<Database>,\n\t\trr: { processed: number; errors: number },\n\t\tflushedWrites: boolean,\n\t) => {\n\t\tif (opts?.skipProgressUpdate) return;\n\t\tconst rewind = isReorgRewind(opts);\n\t\tif (rr.errors > 0 && rr.processed === 0) {\n\t\t\tif (rewind) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, \"error\", blockHeight);\n\t\t\t} else {\n\t\t\t\t// f069: conditional — see recordLiveError's docblock for why a lost\n\t\t\t\t// race here is always a silent no-op (an all-failed block never\n\t\t\t\t// flushes writes, so there's nothing to protect by throwing).\n\t\t\t\tawait recordLiveError(tx, subgraphName, blockHeight);\n\t\t\t}\n\t\t} else if (rewind) {\n\t\t\t// Unconditional, may move the cursor backward — see ProcessBlockOptions.\n\t\t\tawait rewindLiveProgress(tx, subgraphName, blockHeight);\n\t\t} else {\n\t\t\t// Promote-but-never-unpark (see matched-0 note). Conditional advance\n\t\t\t// (f069): a racing writer that already committed a higher cursor for\n\t\t\t// this height means OUR writes must not stand — abort the whole tx\n\t\t\t// so ctx.increment deltas already flushed above roll back with it.\n\t\t\tconst advanced = await recordLiveProgress(tx, subgraphName, blockHeight);\n\t\t\tif (!advanced && flushedWrites) {\n\t\t\t\tthrow new LiveCursorRaceLostError(subgraphName, blockHeight);\n\t\t\t}\n\t\t}\n\t\t// A handler that threw had its writes rolled back (runner.ts\n\t\t// ctx.rollbackTo) but the cursor still advances, so those events are\n\t\t// gone unless something records where. Gap rows are what `/gaps` and\n\t\t// backfill repair from — the reindex path has always written them\n\t\t// (reindex.ts), the live path never did.\n\t\tif (rr.errors > 0 && !rewind) {\n\t\t\tif (opts?.subgraphId) {\n\t\t\t\tawait recordGapBatch(tx, opts.subgraphId, subgraphName, [\n\t\t\t\t\t{ start: blockHeight, end: blockHeight, reason: \"processing_error\" },\n\t\t\t\t]);\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Block errors not recorded as a gap — no subgraphId\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\terrors: rr.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (rr.processed > 0 || rr.errors > 0) {\n\t\t\tconst lastError =\n\t\t\t\trr.errors > 0\n\t\t\t\t\t? `${rr.errors} error(s) at block ${blockHeight}`\n\t\t\t\t\t: undefined;\n\t\t\tawait recordSubgraphProcessed(\n\t\t\t\ttx,\n\t\t\t\tsubgraphName,\n\t\t\t\trr.processed,\n\t\t\t\trr.errors,\n\t\t\t\tlastError,\n\t\t\t);\n\t\t}\n\t};\n\n\t// Managed: a single atomic transaction on the target DB.\n\ttry {\n\t\tawait targetDb.transaction().execute(async (tx: Transaction<Database>) => {\n\t\t\t// Replay guard (sequential walks only): committed writes always carry\n\t\t\t// their checkpoint (below), so a block at/below the cursor has already\n\t\t\t// been applied — running it again would double-apply deltas.\n\t\t\tconst opMode = opCursorMode(opts);\n\t\t\tconst sm = statusMode(opts);\n\t\t\tconst rewind = isReorgRewind(opts);\n\t\t\tif (sm) {\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (opMode) {\n\t\t\t\t// Fast path only — the conditional advance below is the guarantee.\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t\t.where(\"id\", \"=\", opMode.operationId)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (\n\t\t\t\t\trow?.cursor_block != null &&\n\t\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t\t) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!rewind) {\n\t\t\t\t// f069: the same fast-path guard, now armed on the live path.\n\t\t\t\t// Fast path only — the conditional `recordLiveProgress` advance\n\t\t\t\t// below (via applyProgress) is the actual guarantee; this SELECT,\n\t\t\t\t// taken before handlers run, cannot see a same-height race that\n\t\t\t\t// commits between here and there. Never checked when `rewind` is\n\t\t\t\t// set: a reorg's fork block is, by construction, at or below the\n\t\t\t\t// current cursor, and must run anyway.\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\ttx,\n\t\t\t\tschemaName,\n\t\t\t\tsubgraph.schema,\n\t\t\t\tblockMeta,\n\t\t\t\tinitialTx,\n\t\t\t\tjournalEnabled(opts),\n\t\t\t);\n\n\t\t\t// f071 Stage A: dark, flag-gated dispatch. `sandboxEnabled` requires\n\t\t\t// BOTH the global env gate AND this subgraph's `sandbox_workers`\n\t\t\t// column — nothing in committed code sets that column, so this\n\t\t\t// branch is unreached in production today; `runHandlers` (below)\n\t\t\t// is what actually executes, byte-identical to before this plan.\n\t\t\t// When it IS reached: `runHandlersSandboxed` runs handlers in the\n\t\t\t// sandbox subprocess but replays their decided ops onto THIS same\n\t\t\t// `ctx`, bound to THIS same open transaction, before returning —\n\t\t\t// so the flush/manifest/outbox flow and the f069 guard placement\n\t\t\t// below are unaffected either way (see `host.ts`'s docblock).\n\t\t\tconst handlerStart = performance.now();\n\t\t\tconst runResult = sandboxEnabled({\n\t\t\t\tsandbox_workers: route.sandboxWorkers,\n\t\t\t})\n\t\t\t\t? await runHandlersSandboxed({\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tversion: route.version,\n\t\t\t\t\t\thandlerCode: route.handlerCode,\n\t\t\t\t\t\thostCtx: ctx,\n\t\t\t\t\t\tblock: blockMeta,\n\t\t\t\t\t\tmatched,\n\t\t\t\t\t})\n\t\t\t\t: await runHandlers(subgraph, matched, ctx);\n\t\t\thandlerMs = performance.now() - handlerStart;\n\n\t\t\tresult.processed = runResult.processed;\n\t\t\tresult.errors = runResult.errors;\n\n\t\t\tlet flushedWrites = false;\n\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\tconst flushStart = performance.now();\n\t\t\t\tconst manifest = await ctx.flush();\n\t\t\t\tflushedWrites = manifest.count > 0;\n\t\t\t\tif (manifest.count > 0) {\n\t\t\t\t\tawait emitWebhookOutbox(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\tmatcher,\n\t\t\t\t\t\tblock.height,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t}\n\n\t\t\t// Checkpoint travels with the writes it covers — a crash can never\n\t\t\t// leave committed deltas ahead of the checkpoint (fix-f040 B3).\n\t\t\tif (sm && flushedWrites) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, sm.status, blockHeight);\n\t\t\t} else if (opMode && flushedWrites) {\n\t\t\t\tconst advanced = await advanceOperationCursor(\n\t\t\t\t\ttx,\n\t\t\t\t\topMode.operationId,\n\t\t\t\t\tblockHeight,\n\t\t\t\t);\n\t\t\t\tif (!advanced) {\n\t\t\t\t\t// A racing writer (zombie/claimer) already covered this height —\n\t\t\t\t\t// abort OUR writes; the winner's commit stands.\n\t\t\t\t\tthrow new CursorRaceLostError(opMode.operationId, blockHeight);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait applyProgress(tx, runResult, flushedWrites);\n\t\t});\n\t} catch (err) {\n\t\tif (\n\t\t\terr instanceof CursorRaceLostError ||\n\t\t\terr instanceof LiveCursorRaceLostError\n\t\t) {\n\t\t\t// Success-shaped: the block IS committed (by the winner). Surfacing\n\t\t\t// this as an error would mint a false gap row and re-invite the\n\t\t\t// double-apply through gap repair.\n\t\t\tlogger.warn(\"cursor race lost — block already covered\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\terror: err.message,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tthrow err;\n\t}\n\n\t// Persist factory discoveries only after the block's writes commit, so a\n\t// failed block doesn't leave addresses claimed for a block that produced\n\t// nothing. Stamped with this height, so the reorg handler rolls them back\n\t// with everything else. Idempotent (ON CONFLICT DO NOTHING), so a\n\t// guard-skipped block replaying here is harmless.\n\tif (!result.skipped) {\n\t\tawait persistFactoryDiscoveries(\n\t\t\tschemaName,\n\t\t\troute.dataDb,\n\t\t\tblockHeight,\n\t\t\tdiscovered,\n\t\t);\n\t}\n\n\tconst totalMs = performance.now() - blockStart;\n\t// f069: a skipped block (guard fast-path, or a race-loss success-shaped\n\t// skip) never reaches here as a distinct branch — it falls through from\n\t// the transaction callback's early `return`. `blocks_processed` is now\n\t// load-bearing forensic evidence (f068's own re-derivation of it), so a\n\t// skip must not inflate it: only count blocks that actually ran handlers.\n\tif (!result.skipped) {\n\t\tresult.timing = {\n\t\t\ttotalMs: Math.round(totalMs),\n\t\t\thandlerMs: Math.round(handlerMs),\n\t\t\tflushMs: Math.round(flushMs),\n\t\t};\n\t}\n\n\t// 7. Row count warning — sample every 1000 blocks (uses pg_stat estimate, not COUNT(*))\n\tif (blockHeight % 1000 === 0) {\n\t\ttry {\n\t\t\tconst tables = Object.keys(subgraph.schema);\n\t\t\tfor (const table of tables) {\n\t\t\t\tconst { rows } = await sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(route.dataDb);\n\t\t\t\tconst count = Number((rows[0] as Record<string, unknown>)?.count ?? 0);\n\t\t\t\tif (count >= 10_000_000) {\n\t\t\t\t\tlogger.warn(\"Subgraph table exceeds 10M rows (estimate)\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tcount,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Expected: table may not exist yet (fresh subgraph, first few\n\t\t\t// blocks before DDL runs). Log at debug so real errors —\n\t\t\t// connection, permissions, query plan — aren't invisible.\n\t\t\tlogger.debug(\"Row count sample failed\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t}\n\n\t\t// Prune reorg-journal entries past finality (fix-f040 B2). Same cadence\n\t\t// as the row sample; retention is generous vs observed reorg depth.\n\t\tif (journalEnabled(opts)) {\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`DELETE FROM \"${schemaName}\".\"_journal\" WHERE \"block_height\" < ${blockHeight - JOURNAL_RETENTION_BLOCKS}`,\n\t\t\t\t)\n\t\t\t\t.execute(route.dataDb)\n\t\t\t\t.catch(() => {\n\t\t\t\t\t// Journal may not exist yet (pre-journal deploy, no writes since).\n\t\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n",
18
- "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Transaction } from \"@secondlayer/shared/db\";\nimport {\n\ttype IndexEventRow,\n\ttype IndexHttpClient,\n\ttype IndexTransactionRow,\n\tcreateInternalIndexHttpClient,\n} from \"@secondlayer/shared/index-http\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition, SubgraphFilter } from \"../types.ts\";\nimport { type BlockData, loadBlockRange } from \"./batch-loader.ts\";\nimport { ObserverHttpBlockSource } from \"./observer-http-source.ts\";\nimport {\n\treconstructBlock,\n\treconstructEvent,\n\treconstructTransaction,\n\treconstructTxFromEventRow,\n} from \"./reconstruct.ts\";\n\n/**\n * Where the subgraph runtime reads canonical chain data. Today it taps the\n * indexer Postgres directly (`PostgresBlockSource`); the re-point adds a\n * `PublicApiBlockSource` that consumes the Streams clock + Index data over\n * HTTP. `matchSources` / handlers / flush / outbox are unchanged — only the\n * loader + tip swap behind this seam.\n */\nexport interface BlockSource {\n\t/** Highest canonical block height available to process. */\n\tgetTip(): Promise<number>;\n\t/** Canonical block data for [fromHeight, toHeight], keyed by height. */\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>>;\n\t/** Sparse-scan probe: lowest height in (afterHeight, untilHeight] holding\n\t * an event this source's subgraph could match, or null when the rest of\n\t * the range is empty. Optional — only event-scoped sources support it. */\n\tnextDataHeight?(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null>;\n}\n\n/** A (decoded event type, optional contract scope) pair the sparse probe\n * checks. Contract scoping is what makes token-subgraph reindexes leap over\n * everything that isn't their token. */\nexport type SparseProbeTarget = { eventType: string; contractId?: string };\n\n/** Sparse scanning is sound only when EVERY source is an event-type filter —\n * a contract_call/contract_deploy source matches transactions, which the\n * event probe can't see. */\nexport function canSparseScan(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\treturn filters.every((f) => Boolean(EVENT_FILTER_TO_INDEX_TYPE[f.type]));\n}\n\n/** Probe targets for a subgraph's filters: decoded type + contract scope when\n * the filter pins one (assetIdentifier \"SP….contract::asset\" or contractId). */\nexport function sparseProbeTargets(\n\tsubgraph: SubgraphDefinition,\n): SparseProbeTarget[] {\n\tconst targets = new Map<string, SparseProbeTarget>();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst eventType = EVENT_FILTER_TO_INDEX_TYPE[f.type];\n\t\tif (!eventType) continue;\n\t\tconst scoped = f as { assetIdentifier?: string; contractId?: string };\n\t\tconst contractId =\n\t\t\tscoped.contractId ?? scoped.assetIdentifier?.split(\"::\")[0];\n\t\tconst key = `${eventType}|${contractId ?? \"\"}`;\n\t\ttargets.set(key, { eventType, ...(contractId ? { contractId } : {}) });\n\t}\n\treturn [...targets.values()];\n}\n\n/** Reads directly from the shared indexer Postgres (the original behavior). */\nexport class PostgresBlockSource implements BlockSource {\n\tasync getTip(): Promise<number> {\n\t\tconst progress = await getSourceDb()\n\t\t\t.selectFrom(\"index_progress\")\n\t\t\t.selectAll()\n\t\t\t.where(\"network\", \"=\", process.env.NETWORK ?? \"mainnet\")\n\t\t\t.executeTakeFirst();\n\t\treturn progress ? Number(progress.highest_seen_block) : 0;\n\t}\n\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\treturn loadBlockRange(getSourceDb(), fromHeight, toHeight);\n\t}\n}\n\n// Subgraph source filter types that map to a decoded Index event_type. The\n// `_event` suffix is the runtime's raw form; print is keyed `print_event`.\nconst EVENT_FILTER_TO_INDEX_TYPE: Record<string, string> = {\n\tstx_transfer: \"stx_transfer\",\n\tstx_mint: \"stx_mint\",\n\tstx_burn: \"stx_burn\",\n\tstx_lock: \"stx_lock\",\n\tft_transfer: \"ft_transfer\",\n\tft_mint: \"ft_mint\",\n\tft_burn: \"ft_burn\",\n\tnft_transfer: \"nft_transfer\",\n\tnft_mint: \"nft_mint\",\n\tnft_burn: \"nft_burn\",\n\tprint_event: \"print\",\n};\n\n// Tx-level source types — matched against /v1/index/transactions, not events.\nconst TX_SOURCE_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\nconst ALL_INDEX_EVENT_TYPES = [\n\t...new Set(Object.values(EVENT_FILTER_TO_INDEX_TYPE)),\n];\n\nfunction sourceFilters(subgraph: SubgraphDefinition): SubgraphFilter[] {\n\tconst sources = subgraph.sources;\n\treturn Array.isArray(sources)\n\t\t? (sources as SubgraphFilter[])\n\t\t: Object.values(sources as Record<string, SubgraphFilter>);\n}\n\n/**\n * True when any source matches transactions (contract_call / contract_deploy):\n * the handler receives the full tx, so the loader must fetch real transactions.\n * Event-only subgraphs skip walkTransactions and synthesize the tx from joined\n * event context instead (the ~37x reindex over-fetch; see indexing-speed plan).\n */\nexport function needsTransactionData(subgraph: SubgraphDefinition): boolean {\n\treturn sourceFilters(subgraph).some((f) => TX_SOURCE_TYPES.has(f.type));\n}\n\n/** Build the (few) event-bearing txs from joined event context, one per tx_id —\n * the event-only replacement for draining every transaction in the range. */\nfunction synthesizeTxsFromEvents(events: IndexEventRow[]): Transaction[] {\n\tconst byId = new Map<string, Transaction>();\n\tfor (const e of events) {\n\t\tif (!byId.has(e.tx_id)) byId.set(e.tx_id, reconstructTxFromEventRow(e));\n\t}\n\treturn [...byId.values()];\n}\n\n/**\n * The Index event_types the loader must fetch for a set of source filter types.\n * A contract_call/contract_deploy source matches a tx and hands its FULL event\n * set to the handler, so when one is present we fetch every event type (the\n * matched tx's events must be complete); otherwise just the referenced types.\n * Shared by the subgraph loader and the chain-trigger evaluator.\n */\nexport function indexEventTypesForFilterTypes(filterTypes: string[]): string[] {\n\tif (filterTypes.some((t) => TX_SOURCE_TYPES.has(t))) {\n\t\treturn ALL_INDEX_EVENT_TYPES;\n\t}\n\tconst types = new Set<string>();\n\tfor (const t of filterTypes) {\n\t\tconst indexType = EVENT_FILTER_TO_INDEX_TYPE[t];\n\t\tif (indexType) types.add(indexType);\n\t}\n\treturn [...types];\n}\n\n/** Index event_types a subgraph's sources require. Empty when sources are absent. */\nexport function referencedIndexEventTypes(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\tif (!subgraph.sources) return [];\n\treturn indexEventTypesForFilterTypes(\n\t\tsourceFilters(subgraph).map((f) => f.type),\n\t);\n}\n\n/**\n * streams-index eligibility: every source must be a known event-type or\n * contract_call/contract_deploy filter (no array-style sources, which leak the\n * unreconstructable `_eventId`). Trait scope IS allowed — trait resolution\n * reads the contract registry on the platform DB (`targetDb`), which the\n * processor always holds, so it's source-independent. Everything else stays on\n * the DB tap.\n */\nexport function isStreamsIndexEligible(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\tfor (const f of filters) {\n\t\tconst known =\n\t\t\tEVENT_FILTER_TO_INDEX_TYPE[f.type] || TX_SOURCE_TYPES.has(f.type);\n\t\tif (!known) return false;\n\t}\n\treturn true;\n}\n\n/** Streams clock + Index data plane, reconstructed into raw BlockData rows. */\nexport class PublicApiBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly http: IndexHttpClient,\n\t\tprivate readonly eventTypes: string[],\n\t\t/** When set, enables the sparse-scan probe (event-scoped subgraphs). */\n\t\tprivate readonly probeTargets?: SparseProbeTarget[],\n\t\t/** False for event-only subgraphs → skip walkTransactions, synthesize the\n\t\t * tx from joined event context. Defaults true (safe / unchanged). */\n\t\tprivate readonly needsTransactions = true,\n\t) {}\n\n\t/** Lowest height in (after, until] any probe target hits, or null. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.probeTargets?.length) return afterHeight + 1;\n\t\tconst hits = await Promise.all(\n\t\t\tthis.probeTargets.map((t) =>\n\t\t\t\tthis.http.firstEventHeight(\n\t\t\t\t\tt.eventType,\n\t\t\t\t\tafterHeight + 1,\n\t\t\t\t\tuntilHeight,\n\t\t\t\t\tt.contractId,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst found = hits.filter((h): h is number => h !== null);\n\t\treturn found.length ? Math.min(...found) : null;\n\t}\n\n\tgetTip(): Promise<number> {\n\t\t// Bound advancement to what the Index data plane can serve — never\n\t\t// process past it even if the Streams clock is ahead.\n\t\treturn this.http.getIndexTip();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\t// Event-only subgraphs join tx context onto events (withTx) and skip the\n\t\t// walkTransactions over-fetch entirely; tx-level sources fetch real txs.\n\t\tconst withTx = !this.needsTransactions;\n\t\tconst [blocks, txRows, eventLists] = await Promise.all([\n\t\t\tthis.http.walkBlocks(fromHeight, toHeight),\n\t\t\tthis.needsTransactions\n\t\t\t\t? this.http.walkTransactions(fromHeight, toHeight)\n\t\t\t\t: Promise.resolve<IndexTransactionRow[]>([]),\n\t\t\tPromise.all(\n\t\t\t\tthis.eventTypes.map((t) =>\n\t\t\t\t\tthis.http.walkEvents(t, fromHeight, toHeight, withTx),\n\t\t\t\t),\n\t\t\t),\n\t\t]);\n\n\t\tconst map = new Map<number, BlockData>();\n\t\t// Seed every canonical height (incl. empty blocks) so catch-up doesn't\n\t\t// file them as gaps.\n\t\tfor (const b of blocks) {\n\t\t\tmap.set(b.block_height, {\n\t\t\t\tblock: reconstructBlock(b),\n\t\t\t\ttxs: [],\n\t\t\t\tevents: [],\n\t\t\t});\n\t\t}\n\t\t// For event-only subgraphs, materialize only the event-bearing txs from\n\t\t// joined event context instead of every transaction in the range.\n\t\tconst txs = this.needsTransactions\n\t\t\t? txRows.map(reconstructTransaction)\n\t\t\t: synthesizeTxsFromEvents(eventLists.flat());\n\t\tfor (const t of txs) {\n\t\t\tmap.get(t.block_height)?.txs.push(t);\n\t\t}\n\t\tfor (const list of eventLists) {\n\t\t\tfor (const e of list) {\n\t\t\t\tmap.get(e.block_height)?.events.push(reconstructEvent(e));\n\t\t\t}\n\t\t}\n\t\t// Canonical ordering — multi-type event walks merge here.\n\t\tfor (const bd of map.values()) {\n\t\t\tbd.txs.sort((a, b) => a.tx_index - b.tx_index);\n\t\t\tbd.events.sort((a, b) => a.event_index - b.event_index);\n\t\t}\n\t\treturn map;\n\t}\n}\n\n/**\n * Wraps a primary source and falls back to a secondary, per call, when the\n * primary throws. Use it to make the HTTP (Streams+Index) plane a SOFT dependency:\n * if api is unavailable, the processor reads the Postgres tap and keeps advancing\n * instead of stalling. Safe to mix mid-stream — both taps read the same canonical\n * chain at the same heights and the cursor is forward-only. Stateless (no breaker)\n * so it's failover-safe across replicas; the primary is retried every call and\n * resumes transparently once healthy.\n */\nexport class FallbackBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly primary: BlockSource,\n\t\tprivate readonly fallback: BlockSource,\n\t) {}\n\n\tasync getTip(): Promise<number> {\n\t\ttry {\n\t\t\treturn await this.primary.getTip();\n\t\t} catch (err) {\n\t\t\tlogger.warn(\"block source primary getTip failed — using DB tap\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.getTip();\n\t\t}\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\ttry {\n\t\t\treturn await this.primary.loadBlockRange(fromHeight, toHeight);\n\t\t} catch (err) {\n\t\t\tlogger.warn(\"block source primary loadBlockRange failed — using DB tap\", {\n\t\t\t\tfrom: fromHeight,\n\t\t\t\tto: toHeight,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.loadBlockRange(fromHeight, toHeight);\n\t\t}\n\t}\n\n\t/** Probe via the primary only; a probe failure just means \"no skip\" —\n\t * the caller falls back to plain batch advancement. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.primary.nextDataHeight) return afterHeight + 1;\n\t\ttry {\n\t\t\treturn await this.primary.nextDataHeight(afterHeight, untilHeight);\n\t\t} catch {\n\t\t\treturn afterHeight + 1;\n\t\t}\n\t}\n}\n\nconst postgresBlockSource = new PostgresBlockSource();\n\n/**\n * HTTP (Streams+Index) chain source for a set of decoded event types, wrapped so\n * it falls back to the Postgres tap when api is down. Used by the chain-trigger\n * evaluator (which isn't subgraph-scoped, so it can't go through resolveBlockSource).\n */\nexport function buildChainBlockSource(eventTypes: string[]): BlockSource {\n\treturn new FallbackBlockSource(\n\t\tnew PublicApiBlockSource(buildHttpClient(), eventTypes),\n\t\tpostgresBlockSource,\n\t);\n}\n\nexport function buildHttpClient(): IndexHttpClient {\n\treturn createInternalIndexHttpClient();\n}\n\n/**\n * Resolve the block source for a subgraph. `SUBGRAPH_SOURCE=streams-index`\n * opts eligible subgraphs onto the public Streams clock + Index data;\n * `SUBGRAPH_SOURCE=observer-http` pages internal observer-events (experimental).\n * Default stays on the Postgres tap.\n */\nexport function resolveBlockSource(subgraph?: SubgraphDefinition): BlockSource {\n\tif (process.env.SUBGRAPH_SOURCE === \"observer-http\") {\n\t\tconst baseUrl = process.env.OBSERVER_HTTP_URL;\n\t\tif (!baseUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t\"SUBGRAPH_SOURCE=observer-http requires OBSERVER_HTTP_URL\",\n\t\t\t);\n\t\t}\n\t\treturn new ObserverHttpBlockSource({\n\t\t\tbaseUrl,\n\t\t\ttoken: process.env.OBSERVER_HTTP_EXPORT_TOKEN || null,\n\t\t});\n\t}\n\tif (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tsubgraph &&\n\t\tisStreamsIndexEligible(subgraph)\n\t) {\n\t\t// Soft-depend on api: fall back to the Postgres tap per-call if the HTTP\n\t\t// plane is down, so the processor keeps advancing instead of stalling.\n\t\treturn new FallbackBlockSource(\n\t\t\tnew PublicApiBlockSource(\n\t\t\t\tbuildHttpClient(),\n\t\t\t\treferencedIndexEventTypes(subgraph),\n\t\t\t\tcanSparseScan(subgraph) ? sparseProbeTargets(subgraph) : undefined,\n\t\t\t\tneedsTransactionData(subgraph),\n\t\t\t),\n\t\t\tpostgresBlockSource,\n\t\t);\n\t}\n\tif (process.env.SUBGRAPH_SOURCE === \"streams-index\" && subgraph) {\n\t\tlogger.debug(\"Subgraph not streams-index eligible, using DB tap\", {\n\t\t\tsubgraph: subgraph.name,\n\t\t});\n\t}\n\treturn postgresBlockSource;\n}\n",
19
- "import type {\n\tBlock,\n\tDatabase,\n\tEvent,\n\tTransaction,\n} from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\n\nexport interface BlockData {\n\tblock: Block;\n\ttxs: Transaction[];\n\tevents: Event[];\n}\n\n/**\n * Load a range of blocks with their transactions and events in 3 parallel queries.\n * Returns a Map keyed by block height. Non-canonical blocks are excluded.\n */\nexport async function loadBlockRange(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n\ttoHeight: number,\n): Promise<Map<number, BlockData>> {\n\tconst [blocks, txs, events] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.selectAll()\n\t\t\t.where(\"height\", \">=\", fromHeight)\n\t\t\t.where(\"height\", \"<=\", toHeight)\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"transactions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"events\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t]);\n\n\t// Index by block height (coerce to number — bigint columns may return as string or number)\n\tconst txsByHeight = new Map<number, Transaction[]>();\n\tfor (const tx of txs) {\n\t\tconst h = Number(tx.block_height);\n\t\tconst list = txsByHeight.get(h) ?? [];\n\t\tlist.push(tx);\n\t\ttxsByHeight.set(h, list);\n\t}\n\n\tconst eventsByHeight = new Map<number, Event[]>();\n\tfor (const evt of events) {\n\t\tconst h = Number(evt.block_height);\n\t\tconst list = eventsByHeight.get(h) ?? [];\n\t\tlist.push(evt);\n\t\teventsByHeight.set(h, list);\n\t}\n\n\tconst result = new Map<number, BlockData>();\n\tfor (const block of blocks) {\n\t\tconst h = Number(block.height);\n\t\tresult.set(h, {\n\t\t\tblock,\n\t\t\ttxs: txsByHeight.get(h) ?? [],\n\t\t\tevents: eventsByHeight.get(h) ?? [],\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Compute average events per block from a loaded batch.\n * Used for adaptive batch sizing.\n */\nexport function avgEventsPerBlock(batch: Map<number, BlockData>): number {\n\tif (batch.size === 0) return 0;\n\tlet totalEvents = 0;\n\tfor (const data of batch.values()) {\n\t\ttotalEvents += data.events.length;\n\t}\n\treturn totalEvents / batch.size;\n}\n",
20
- "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type { BlockData } from \"./batch-loader.ts\";\nimport type { BlockSource } from \"./block-source.ts\";\n\n/** Duplicated from indexer — do not import `@secondlayer/indexer` (cycle). */\nconst OBSERVER_HTTP_EXPORT_PATH = \"/internal/observer-events\";\n\nexport type ObserverHttpFetch = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport type ObserverHttpBlockSourceOpts = {\n\t/** e.g. http://127.0.0.1:3700 — trailing slash stripped */\n\tbaseUrl: string;\n\ttoken?: string | null;\n\tfetch?: ObserverHttpFetch;\n\t/** Unused on the wire; list filtering is server-side. */\n\tnetwork?: string;\n};\n\ntype ObserverEventsNext = {\n\tafter_height: number;\n\tafter_index_block_hash: string;\n};\n\ntype SbaObserverMessage = {\n\tpath: string;\n\tpayload: unknown;\n\tcontent_sha256: string;\n\tblock_height: number | null;\n\tindex_block_hash: string | null;\n\treceived_at?: string;\n};\n\ntype ObserverEventsResponse = {\n\tevents: SbaObserverMessage[];\n\tnext: ObserverEventsNext | null;\n};\n\ntype ObserverTipResponse = {\n\tblock_height: number;\n\tindex_block_hash: string | null;\n};\n\ntype ObserverTx = {\n\ttxid?: string;\n\ttx_index?: number;\n\ttx_type?: string;\n\tsender_address?: string;\n\tstatus?: string;\n\traw_result?: string | null;\n\traw_tx?: string;\n\tcontract_call?: { contract_id?: string; function_name?: string };\n\tsmart_contract?: { contract_id?: string };\n};\n\ntype ObserverEvent = {\n\ttxid?: string;\n\tevent_index?: number;\n\ttype?: string;\n\t[key: string]: unknown;\n};\n\ntype ObserverNewBlockPayload = {\n\tblock_height?: number;\n\tblock_hash?: string;\n\tparent_block_hash?: string;\n\tburn_block_height?: number;\n\tburn_block_hash?: string | null;\n\tindex_block_hash?: string | null;\n\ttimestamp?: number;\n\tblock_time?: number;\n\tburn_block_time?: number;\n\tburn_block_timestamp?: number;\n\ttransactions?: ObserverTx[];\n\tevents?: ObserverEvent[];\n};\n\nfunction stripTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction blockTimestamp(payload: ObserverNewBlockPayload): number {\n\tfor (const value of [\n\t\tpayload.timestamp,\n\t\tpayload.block_time,\n\t\tpayload.burn_block_time,\n\t\tpayload.burn_block_timestamp,\n\t]) {\n\t\tif (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction eventData(event: ObserverEvent): unknown {\n\tif (typeof event.type === \"string\" && event.type in event) {\n\t\treturn event[event.type] ?? {};\n\t}\n\treturn {};\n}\n\n/** Map a `/new_block` observer payload into subgraph `BlockData`. No Hiro. */\nexport function mapNewBlockPayloadToBlockData(payload: unknown): BlockData {\n\tconst p = payload as ObserverNewBlockPayload;\n\tif (\n\t\ttypeof p.block_height !== \"number\" ||\n\t\t!Number.isFinite(p.block_height) ||\n\t\ttypeof p.index_block_hash !== \"string\" ||\n\t\tp.index_block_hash.length === 0\n\t) {\n\t\tthrow new Error(\n\t\t\t\"observer /new_block payload missing block_height or index_block_hash\",\n\t\t);\n\t}\n\n\tconst height = p.block_height;\n\tconst block = {\n\t\theight,\n\t\thash: p.block_hash ?? \"\",\n\t\tparent_hash: p.parent_block_hash ?? \"\",\n\t\tburn_block_height: p.burn_block_height ?? 0,\n\t\tburn_block_hash: p.burn_block_hash ?? null,\n\t\tindex_block_hash: p.index_block_hash,\n\t\ttimestamp: blockTimestamp(p),\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n\n\tconst txs: Transaction[] = (p.transactions ?? []).map((tx) => {\n\t\tlet contractId: string | null = null;\n\t\tlet functionName: string | null = null;\n\t\tif (tx.tx_type === \"contract_call\" && tx.contract_call) {\n\t\t\tcontractId = tx.contract_call.contract_id ?? null;\n\t\t\tfunctionName = tx.contract_call.function_name ?? null;\n\t\t} else if (tx.tx_type === \"smart_contract\" && tx.smart_contract) {\n\t\t\tcontractId = tx.smart_contract.contract_id ?? null;\n\t\t}\n\t\treturn {\n\t\t\ttx_id: tx.txid ?? \"\",\n\t\t\tblock_height: height,\n\t\t\ttx_index: tx.tx_index ?? 0,\n\t\t\ttype: tx.tx_type ?? \"\",\n\t\t\tsender: tx.sender_address ?? \"\",\n\t\t\tstatus: tx.status ?? \"success\",\n\t\t\tcontract_id: contractId,\n\t\t\tfunction_name: functionName,\n\t\t\tfunction_args: [],\n\t\t\traw_result: tx.raw_result ?? null,\n\t\t\traw_tx: tx.raw_tx ?? \"\",\n\t\t\tcreated_at: new Date(0),\n\t\t} as Transaction;\n\t});\n\n\tconst events: Event[] = (p.events ?? []).map((event) => {\n\t\tconst txId = event.txid ?? \"\";\n\t\tconst eventIndex = event.event_index ?? 0;\n\t\treturn {\n\t\t\tid: `${txId}#${eventIndex}`,\n\t\t\ttx_id: txId,\n\t\t\tblock_height: height,\n\t\t\tevent_index: eventIndex,\n\t\t\ttype: event.type ?? \"\",\n\t\t\tdata: eventData(event),\n\t\t\tcreated_at: new Date(0),\n\t\t} as Event;\n\t});\n\n\treturn { block, txs, events };\n}\n\n/**\n * Experimental BlockSource: pages indexer `/internal/observer-events` and maps\n * raw `/new_block` bodies to `BlockData`. Not the production default.\n */\nexport class ObserverHttpBlockSource implements BlockSource {\n\tprivate readonly baseUrl: string;\n\tprivate readonly token: string | null;\n\tprivate readonly fetchFn: ObserverHttpFetch;\n\n\tconstructor(opts: ObserverHttpBlockSourceOpts) {\n\t\tthis.baseUrl = stripTrailingSlash(opts.baseUrl);\n\t\tthis.token = opts.token ?? null;\n\t\tthis.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n\t}\n\n\tprivate headers(): Record<string, string> {\n\t\tif (!this.token) return {};\n\t\treturn { Authorization: `Bearer ${this.token}` };\n\t}\n\n\tasync getTip(): Promise<number> {\n\t\tconst res = await this.fetchFn(\n\t\t\t`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}/tip`,\n\t\t\t{ headers: this.headers() },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t);\n\t\t}\n\t\tlet body: ObserverTipResponse;\n\t\ttry {\n\t\t\tbody = (await res.json()) as ObserverTipResponse;\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\ttypeof body.block_height !== \"number\" ||\n\t\t\t!Number.isFinite(body.block_height)\n\t\t) {\n\t\t\tthrow new Error(\"observer tip missing block_height\");\n\t\t}\n\t\treturn body.block_height;\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\tconst result = new Map<number, BlockData>();\n\t\tlet afterHeight: number | undefined =\n\t\t\tfromHeight > 0 ? fromHeight - 1 : undefined;\n\t\tlet afterIndexBlockHash: string | undefined;\n\n\t\tfor (;;) {\n\t\t\tconst url = new URL(`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}`);\n\t\t\turl.searchParams.set(\"path\", \"/new_block\");\n\t\t\turl.searchParams.set(\"limit\", \"100\");\n\t\t\tif (afterHeight != null) {\n\t\t\t\turl.searchParams.set(\"after_height\", String(afterHeight));\n\t\t\t}\n\t\t\tif (afterIndexBlockHash) {\n\t\t\t\turl.searchParams.set(\"after_index_block_hash\", afterIndexBlockHash);\n\t\t\t}\n\n\t\t\tconst res = await this.fetchFn(url.toString(), {\n\t\t\t\theaders: this.headers(),\n\t\t\t});\n\t\t\tif (!res.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet body: ObserverEventsResponse;\n\t\t\ttry {\n\t\t\t\tbody = (await res.json()) as ObserverEventsResponse;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet pastTo = false;\n\t\t\tfor (const message of body.events ?? []) {\n\t\t\t\tif (message.path === \"/new_burn_block\") continue;\n\t\t\t\tconst height = (message.payload as ObserverNewBlockPayload)\n\t\t\t\t\t?.block_height;\n\t\t\t\tif (typeof height === \"number\" && height > toHeight) {\n\t\t\t\t\tpastTo = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst data = mapNewBlockPayloadToBlockData(message.payload);\n\t\t\t\tconst h = data.block.height;\n\t\t\t\tif (h >= fromHeight && h <= toHeight) {\n\t\t\t\t\tresult.set(h, data);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (pastTo || body.next == null) break;\n\t\t\tafterHeight = body.next.after_height;\n\t\t\tafterIndexBlockHash = body.next.after_index_block_hash;\n\t\t}\n\n\t\treturn result;\n\t}\n}\n",
21
- "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\n\nexport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\n\n/**\n * Reconstruct the raw `blocks`/`events` row shapes the subgraph runtime expects\n * (the shapes `matchSources` + the handler runner read) from the decoded,\n * flattened rows the public Index API serves. This is what lets\n * `PublicApiBlockSource` feed the EXISTING pipeline byte-identically to the\n * Postgres tap.\n *\n * Two shape gaps the Index API can't avoid, handled here:\n * - Index event rows are flat (`event_type: \"ft_transfer\"`, columns\n * `sender`/`amount`/…); the runtime expects the node's nested `data` keyed by\n * a suffixed `type` (`ft_transfer_event`), with print under `contract_event`.\n * - nft/print Clarity values: the runtime decodes from the canonical hex\n * (`raw_value`), so we place the Index hex there. (The node's verbose\n * serde-tagged `value`, e.g. `{UInt:223}`, is not reproducible from hex and\n * is no longer read — see the nft tokenId normalization in runner.ts.)\n */\n\n/** ISO `block_time` (or null) → unix-seconds integer the runtime expects. */\nfunction isoToUnixSeconds(iso: string | null): number {\n\tif (!iso) return 0;\n\treturn Math.floor(new Date(iso).getTime() / 1000);\n}\n\nexport function reconstructBlock(b: IndexBlockRow): Block {\n\treturn {\n\t\theight: b.block_height,\n\t\thash: b.block_hash,\n\t\tparent_hash: b.parent_hash,\n\t\tburn_block_height: b.burn_block_height,\n\t\tburn_block_hash: b.burn_block_hash,\n\t\t// Present since the blocks endpoint started serving it; older API\n\t\t// deployments omit it, and a null propagates to a clean refusal in\n\t\t// `ctx.client.readOnly` rather than an unpinned tip read.\n\t\tindex_block_hash: b.index_block_hash ?? null,\n\t\ttimestamp: isoToUnixSeconds(b.block_time),\n\t\t// Index serves canonical rows only.\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n}\n\nexport function reconstructTransaction(t: IndexTransactionRow): Transaction {\n\treturn {\n\t\ttx_id: t.tx_id,\n\t\tblock_height: t.block_height,\n\t\ttx_index: t.tx_index,\n\t\ttype: t.tx_type,\n\t\tsender: t.sender,\n\t\tstatus: t.status,\n\t\tcontract_id:\n\t\t\tt.contract_call?.contract_id ?? t.smart_contract?.contract_id ?? null,\n\t\tfunction_name: t.contract_call?.function_name ?? null,\n\t\t// Raw hex ClarityValues — the runner decodes them via its own deserializeCV\n\t\t// path, identical to the DB tap.\n\t\tfunction_args: t.contract_call?.function_args_hex ?? [],\n\t\traw_result: t.contract_call?.result_hex ?? null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\n/**\n * Build a minimal canonical Transaction from an event row's joined tx context\n * (`tx_context=true` on /v1/index/events). For event-only subgraphs this lets\n * the loader materialize only the txs that actually carry a matched event,\n * instead of draining every transaction in the range (the ~37x reindex\n * over-fetch — see docs/sprints/indexing-speed/plan.md). `function_args` /\n * `raw_result` are empty: an event source never reads them (contract_call-only).\n */\nexport function reconstructTxFromEventRow(e: IndexEventRow): Transaction {\n\treturn {\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\ttx_index: e.tx_index ?? 0,\n\t\ttype: e.tx_type ?? \"\",\n\t\tsender: e.tx_sender ?? \"\",\n\t\tstatus: e.tx_status ?? \"success\",\n\t\tcontract_id: e.tx_contract_id ?? null,\n\t\tfunction_name: e.tx_function_name ?? null,\n\t\tfunction_args: [],\n\t\traw_result: null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\nexport function reconstructEvent(e: IndexEventRow): Event {\n\tconst base = {\n\t\t// Synthetic, deterministic id. The runtime only reads `id` for error logs\n\t\t// and the `*`-wildcard payload (which is streams-index-ineligible).\n\t\tid: `${e.tx_id}#${e.event_index}`,\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\tevent_index: e.event_index,\n\t\tcreated_at: new Date(0),\n\t};\n\n\tswitch (e.event_type) {\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\t// Canonical hex → runner decodes tokenId from raw_value.\n\t\t\t\t\traw_value: e.value,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t\t// Raw stx_transfer always carries memo (\"\" when empty); Index\n\t\t\t\t\t// returns null for empty — default to \"\" to match the DB tap.\n\t\t\t\t\t...(e.event_type === \"stx_transfer\" ? { memo: e.memo ?? \"\" } : {}),\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"stx_lock_event\",\n\t\t\t\tdata: {\n\t\t\t\t\tlocked_address: e.sender,\n\t\t\t\t\tlocked_amount: e.amount,\n\t\t\t\t\tunlock_height: e.payload.unlock_height,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"print\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"contract_event\",\n\t\t\t\tdata: {\n\t\t\t\t\ttopic: e.payload.topic,\n\t\t\t\t\t// Index serves `contract_id`. Matcher + runner also accept\n\t\t\t\t\t// legacy `contract_identifier`; emit the current field.\n\t\t\t\t\tcontract_id: e.contract_id,\n\t\t\t\t\tvalue: e.payload.value,\n\t\t\t\t\traw_value: e.payload.raw_value,\n\t\t\t\t},\n\t\t\t} as Event;\n\t}\n}\n",
17
+ "import { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport { recordGapBatch } from \"@secondlayer/shared/db/queries/subgraph-gaps\";\nimport { advanceOperationCursor } from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\trecordLiveError,\n\trecordLiveProgress,\n\trecordSubgraphProcessed,\n\trewindLiveProgress,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport {\n\ttype BlockMeta,\n\tJOURNAL_RETENTION_BLOCKS,\n\tSubgraphContext,\n\ttype TxMeta,\n} from \"./context.ts\";\nimport { emitWebhookOutbox } from \"./outbox-emit.ts\";\nimport { buildEventPayload, runHandlers } from \"./runner.ts\";\nimport { sandboxEnabled } from \"./sandbox/flag.ts\";\nimport { evictSandboxWorker, runHandlersSandboxed } from \"./sandbox/host.ts\";\nimport {\n\ttype EventRecord,\n\ttype TxRecord,\n\tmatchSources,\n\treadPath,\n} from \"./source-matcher.ts\";\nimport { matcher } from \"./webhook-state.ts\";\n\n/**\n * The data-plane route for a subgraph: which schema its tables live in and the\n * managed target DB the writes/reads land on. Cached per subgraph to avoid a\n * per-block lookup; invalidated on redeploy via\n * {@link invalidateSubgraphRoute}.\n *\n * Also carries the f071 Stage A sandbox-dispatch inputs\n * (`sandboxWorkers`/`handlerCode`/`version`) — cheap to keep alongside the\n * route since `resolveRoute` already selects the full `subgraphs` row; kept\n * in lockstep with the same cache invalidation edge (redeploys change\n * `handler_code`/`version` together).\n */\ninterface SubgraphRoute {\n\tschemaName: string;\n\tdataDb: Kysely<Database>;\n\t/** `subgraphs.sandbox_workers` — combined with the global env gate by\n\t * `sandboxEnabled()`. Default false for every row; nothing in committed\n\t * code sets it true (f071 Stage A stays dark). */\n\tsandboxWorkers: boolean;\n\thandlerCode: string | null;\n\tversion: string;\n}\nconst routeCache = new Map<string, SubgraphRoute>();\n\nasync function resolveRoute(\n\tsubgraphName: string,\n\ttargetDb: Kysely<Database>,\n): Promise<SubgraphRoute> {\n\tconst cached = routeCache.get(subgraphName);\n\tif (cached) return cached;\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\tconst route: SubgraphRoute = {\n\t\tschemaName: row?.schema_name ?? pgSchemaName(subgraphName),\n\t\tdataDb: targetDb,\n\t\tsandboxWorkers: row?.sandbox_workers === true,\n\t\thandlerCode: row?.handler_code ?? null,\n\t\tversion: row?.version ?? \"\",\n\t};\n\trouteCache.set(subgraphName, route);\n\t// f071 Stage A observability: state which handler-execution path this\n\t// subgraph resolved to, once per route-cache resolution (process start,\n\t// or the next block after a redeploy invalidates the cache) — never per\n\t// block, so this can't spam logs. Doesn't change dispatch: reads the same\n\t// `sandboxEnabled` inputs the ternary at the call site below uses.\n\tlogger.info(\"subgraph handler dispatch path resolved\", {\n\t\tsubgraph: subgraphName,\n\t\tpath: sandboxEnabled({ sandbox_workers: route.sandboxWorkers })\n\t\t\t? \"sandbox\"\n\t\t\t: \"in-process\",\n\t});\n\treturn route;\n}\n\n/** Drop a subgraph's cached route — call on redeploy/delete (conn may\n * change). Also evicts any warm sandbox subprocess for this subgraph\n * (f071 Stage A `host.ts`) on the same edge: a redeploy can change\n * `handler_code`/`version` together, and a stale warm\n * subprocess must not survive past this invalidation any more than the\n * cached route does. A no-op today since nothing sets `sandbox_workers`,\n * but keeps the pool's documented invalidation contract honest for when it\n * is. */\nexport function invalidateSubgraphRoute(subgraphName: string): void {\n\trouteCache.delete(subgraphName);\n\tevictSandboxWorker(subgraphName);\n}\n\n/**\n * Resolve each distinct trait used by a subgraph's sources to its conforming\n * contract-id set, as of `blockHeight`, from the contract registry. Empty map\n * when no source is trait-scoped (the common case → no DB work).\n */\n/**\n * Resolve each factory-scoped source's address set for this block.\n *\n * Two parts, and the ORDER is the guarantee:\n * 1. addresses persisted by earlier blocks (`block_height <= blockHeight`,\n * so a reindex sees exactly what the live walk saw), then\n * 2. addresses revealed by THIS block's events — computed before matching,\n * so a contract discovered in block N receives its own block-N events.\n * Without this pass the first event from every discovered contract is\n * silently lost.\n */\n/**\n * Exported as a test seam. Both guarantees this function carries — a contract\n * discovered in block N receiving its OWN block-N events, and the persisted set\n * being height-stamped so a reorg can roll it back — were asserted only by\n * comment until now.\n */\nexport async function resolveFactoryContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\ttxs: TxRecord[],\n\tevts: EventRecord[],\n\tvmEvts: EventRecord[] = [],\n): Promise<{\n\tresolved: Map<string, ReadonlySet<string>>;\n\tdiscovered: Array<{ sourceName: string; address: string }>;\n}> {\n\t// Keyed by the DISCOVERING source (`factory.from`), not the consuming one:\n\t// several sources can share one factory, and this way the extraction runs\n\t// once per discovering source rather than once per consumer.\n\tconst factories = new Map<string, { from: string; field: string }>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst factory = (source as { factory?: { from: string; field: string } })\n\t\t\t.factory;\n\t\tif (factory) factories.set(factory.from, factory);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tconst discovered: Array<{ sourceName: string; address: string }> = [];\n\tif (factories.size === 0) return { resolved, discovered };\n\n\tfor (const [discoveringSource, factory] of factories) {\n\t\tconst known = new Set<string>();\n\t\t// 1. Everything revealed at or below this height.\n\t\ttry {\n\t\t\tconst rows = await sql<{ address: string }>`\n\t\t\t\tSELECT address FROM ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\tWHERE source_name = ${discoveringSource} AND block_height <= ${blockHeight}\n\t\t\t`.execute(db);\n\t\t\tfor (const row of rows.rows) known.add(row.address);\n\t\t} catch {\n\t\t\t// Table absent (first deploy before DDL, or a non-factory subgraph):\n\t\t\t// treat as an empty set rather than failing the block.\n\t\t}\n\n\t\t// 2. This block's own reveals — before matching, so same-block events\n\t\t// from a new contract are not dropped.\n\t\tconst discovering = subgraph.sources[factory.from];\n\t\tif (discovering) {\n\t\t\tconst matches = matchSources(\n\t\t\t\t{ [factory.from]: discovering },\n\t\t\t\ttxs,\n\t\t\t\tevts,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t\tvmEvts,\n\t\t\t);\n\t\t\tfor (const match of matches) {\n\t\t\t\tfor (const event of match.events ?? []) {\n\t\t\t\t\tconst payload = buildEventPayload(discovering, match.tx, event);\n\t\t\t\t\tconst value = readPath(payload, factory.field);\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\tvalue.length > 0 &&\n\t\t\t\t\t\t!known.has(value)\n\t\t\t\t\t) {\n\t\t\t\t\t\tknown.add(value);\n\t\t\t\t\t\tdiscovered.push({ sourceName: discoveringSource, address: value });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresolved.set(discoveringSource, known);\n\t}\n\treturn { resolved, discovered };\n}\n\n/** Persist this block's discoveries, stamped with the block that revealed\n * them so the reorg handler can roll them back. */\nasync function persistFactoryDiscoveries(\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\tdiscovered: Array<{ sourceName: string; address: string }>,\n): Promise<void> {\n\tif (discovered.length === 0) return;\n\tfor (const { sourceName, address } of discovered) {\n\t\tawait sql`\n\t\t\tINSERT INTO ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\t(source_name, address, block_height)\n\t\t\tVALUES (${sourceName}, ${address}, ${blockHeight})\n\t\t\tON CONFLICT (source_name, address) DO NOTHING\n\t\t`.execute(db);\n\t}\n}\n\nasync function resolveTraitContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tdb: Kysely<Database>,\n): Promise<Map<string, ReadonlySet<string>>> {\n\tconst traits = new Set<string>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst trait = (source as { trait?: string }).trait;\n\t\tif (trait) traits.add(trait);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tfor (const trait of traits) {\n\t\tconst ids = await resolveTraitContractIds(db, trait, blockHeight);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\nexport interface ProcessBlockTiming {\n\ttotalMs: number;\n\thandlerMs: number;\n\tflushMs: number;\n}\n\nexport interface ProcessBlockResult {\n\tblockHeight: number;\n\tmatched: number;\n\tprocessed: number;\n\terrors: number;\n\tskipped: boolean;\n\ttiming?: ProcessBlockTiming;\n}\n\n/**\n * Process a single block through a single subgraph's pipeline.\n *\n * Flow:\n * 1. Load block + txs + events from DB\n * 2. Run source matcher\n * 3. Run handlers with SubgraphContext\n * 4. Flush context (commit writes atomically)\n * 5. Update subgraph.last_processed_block\n */\nexport interface PreloadedBlockData {\n\tblock: import(\"@secondlayer/shared/db\").Block;\n\ttxs: import(\"@secondlayer/shared/db\").Transaction[];\n\tevents: import(\"@secondlayer/shared/db\").Event[];\n\t/** Opt-in `vm_events` rows on the vm clock; see `BlockData.vmEvents`. */\n\tvmEvents?: import(\"./batch-loader.ts\").RuntimeEvent[];\n}\n\nexport interface ProcessBlockOptions {\n\t/** Skip updating last_processed_block in DB (reindex batches this externally). */\n\tskipProgressUpdate?: boolean;\n\t/** Pre-loaded block data — skips DB reads when provided (used by batch catch-up). */\n\tpreloaded?: PreloadedBlockData;\n\t/**\n\t * Crash-safe sequential processing. Two checkpoint scopes:\n\t * - `{ status }` (reindex): a written block commits\n\t * `subgraphs.last_processed_block = blockHeight` in the SAME transaction\n\t * as its writes; replays skip at/below the cursor. Only for strictly\n\t * ascending walks over the subgraph's own cursor.\n\t * - `{ operationId }` (backfill): same guarantee against the OPERATION's\n\t * own `cursor_block` — backfills legitimately revisit heights below the\n\t * live cursor, so they must never checkpoint (or read) the subgraph\n\t * cursor. The advance is a CONDITIONAL monotonic UPDATE: concurrent\n\t * writers serialize on it, and the loser's whole block tx rolls back\n\t * (surfaced as `skipped`, never an error/gap).\n\t * Either way: a crash can never leave committed deltas ahead of the\n\t * relevant checkpoint.\n\t */\n\tatomicProgress?: { status: string } | { operationId: string };\n\t/**\n\t * Reorg rewind (f069): set exclusively by `reorg.ts`'s fork-block\n\t * reprocess. Bypasses the live-path replay guard (a fork block's height\n\t * is, by construction, at or below the current cursor — the guard would\n\t * otherwise skip it) and writes the checkpoint via\n\t * `rewindLiveProgress` (unconditional — a rewind's whole point is\n\t * moving the cursor *backward*, which the live path's conditional\n\t * advance would refuse). Safe only because the reorg path holds a\n\t * transaction-scoped advisory lock across its whole\n\t * delete+reprocess+rewind sequence, so nothing else can interleave a\n\t * forward write. Never set this outside `reorg.ts`.\n\t */\n\treorgRewind?: true;\n\t/** The subgraph row's uuid. Required to record a gap row when a block\n\t * processes with handler errors — `subgraph_gaps.subgraph_id` is NOT NULL.\n\t * Absent on paths that pass `skipProgressUpdate` (they record gaps\n\t * themselves, see reindex.ts). */\n\tsubgraphId?: string;\n}\n\n/** Thrown inside the block tx when a racing writer already covered this\n * height — rolls the tx back; processBlock converts it to `skipped`. The\n * winner committed the block, so this is success-shaped, never a gap. */\nclass CursorRaceLostError extends Error {\n\tconstructor(operationId: string, height: number) {\n\t\tsuper(`op ${operationId} lost cursor race at block ${height}`);\n\t\tthis.name = \"CursorRaceLostError\";\n\t}\n}\n\n/** Live-path sibling of {@link CursorRaceLostError}: thrown when the live\n * path's conditional `recordLiveProgress` advance loses to a racing\n * writer that already committed a higher (or equal) `last_processed_block`\n * for this subgraph. Same success-shaped handling — the winner's commit\n * stands, so this becomes `result.skipped = true`, never an error/gap. */\nclass LiveCursorRaceLostError extends Error {\n\tconstructor(subgraphName: string, height: number) {\n\t\tsuper(`live cursor race lost for ${subgraphName} at block ${height}`);\n\t\tthis.name = \"LiveCursorRaceLostError\";\n\t}\n}\n\nfunction opCursorMode(\n\topts?: ProcessBlockOptions,\n): { operationId: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"operationId\" in ap ? ap : undefined;\n}\n\n/** True only for the reorg fork-block reprocess — see `reorgRewind` on\n * {@link ProcessBlockOptions}. */\nfunction isReorgRewind(opts?: ProcessBlockOptions): boolean {\n\treturn opts?.reorgRewind === true;\n}\n\nfunction statusMode(\n\topts?: ProcessBlockOptions,\n): { status: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"status\" in ap ? ap : undefined;\n}\n\n/** Default per-block retry schedule before a failure counts as persistent. */\nexport const BLOCK_RETRY_DELAYS_MS: number[] = [500, 2_000, 5_000];\n\n/**\n * Journal pre-images on the live path only. Deep reindex/backfill heights\n * (skipProgressUpdate) are past finality — a reorg can't reach them, so\n * journaling would be pure churn for the pruner.\n */\nfunction journalEnabled(opts?: ProcessBlockOptions): boolean {\n\treturn !opts?.skipProgressUpdate;\n}\n\n/**\n * processBlock with bounded retries. Throws the last error once the schedule\n * is exhausted — callers decide whether that halts the walk (strict paths) or\n * records a gap (backfill). Never advances any cursor on failure.\n */\nexport async function processBlockWithRetry(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n\tretryDelaysMs: number[] = BLOCK_RETRY_DELAYS_MS,\n): Promise<ProcessBlockResult> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {\n\t\ttry {\n\t\t\treturn await processBlock(subgraph, subgraphName, blockHeight, opts);\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t\tconst delay = retryDelaysMs[attempt];\n\t\t\tif (delay === undefined) break;\n\t\t\tlogger.warn(\"Block processing failed, retrying\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t\tretryInMs: delay,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport async function processBlock(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n): Promise<ProcessBlockResult> {\n\tconst targetDb = getTargetDb();\n\tconst blockStart = performance.now();\n\tconst result: ProcessBlockResult = {\n\t\tblockHeight,\n\t\tmatched: 0,\n\t\tprocessed: 0,\n\t\terrors: 0,\n\t\tskipped: false,\n\t};\n\n\t// 1. Load block from source DB (shared indexer) — use pre-loaded data if available\n\tlet block: PreloadedBlockData[\"block\"] | undefined;\n\tlet txs: PreloadedBlockData[\"txs\"];\n\tlet evts: PreloadedBlockData[\"events\"];\n\tlet vmEvts: NonNullable<PreloadedBlockData[\"vmEvents\"]>;\n\tif (opts?.preloaded) {\n\t\tblock = opts.preloaded.block;\n\t\ttxs = opts.preloaded.txs;\n\t\tevts = opts.preloaded.events;\n\t\tvmEvts = opts.preloaded.vmEvents ?? [];\n\t} else {\n\t\t// The block source returns canonical blocks only, so a missing entry\n\t\t// means the block is absent or non-canonical — skip either way.\n\t\tconst data = (\n\t\t\tawait resolveBlockSource(subgraph).loadBlockRange(\n\t\t\t\tblockHeight,\n\t\t\t\tblockHeight,\n\t\t\t)\n\t\t).get(blockHeight);\n\t\tif (!data) {\n\t\t\tlogger.debug(\"Block not found or non-canonical for subgraph processing\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tblock = data.block;\n\t\ttxs = data.txs;\n\t\tevts = data.events;\n\t\tvmEvts = data.vmEvents ?? [];\n\t}\n\n\t// 3. Match source. Trait-scoped sources ({ trait: \"sip-010\" }) resolve to the\n\t// set of conforming contracts AS OF this block (deploy_height ≤ blockHeight),\n\t// so a reindex backfills a token's full history even if it was classified\n\t// after deploy. Resolution is done here (DB access) so the matcher stays pure.\n\t// Route first: the factory set lives in this subgraph's pg schema, and it\n\t// must resolve BEFORE matching. `resolveRoute` is cached per subgraph.\n\tconst route = await resolveRoute(subgraphName, targetDb);\n\tconst schemaName = route.schemaName;\n\n\tconst traitContracts = await resolveTraitContracts(\n\t\tsubgraph,\n\t\tblockHeight,\n\t\ttargetDb,\n\t);\n\t// Factory sets resolve BEFORE matching so a contract revealed in this\n\t// block receives its own block-N events (see resolveFactoryContracts).\n\tconst { resolved: factoryContracts, discovered } =\n\t\tawait resolveFactoryContracts(\n\t\t\tsubgraph,\n\t\t\tblockHeight,\n\t\t\tschemaName,\n\t\t\ttargetDb,\n\t\t\ttxs,\n\t\t\tevts,\n\t\t\tvmEvts,\n\t\t);\n\tconst matched = matchSources(\n\t\tsubgraph.sources,\n\t\ttxs,\n\t\tevts,\n\t\ttraitContracts,\n\t\tfactoryContracts,\n\t\tvmEvts,\n\t);\n\tresult.matched = matched.length;\n\n\tif (matched.length === 0) {\n\t\tif (!opts?.skipProgressUpdate) {\n\t\t\tif (isReorgRewind(opts)) {\n\t\t\t\t// Fork block itself may match nothing for this subgraph — the\n\t\t\t\t// rewind still must land (unconditional, may move backward).\n\t\t\t\tawait rewindLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t\t} else {\n\t\t\t\t// Promote-but-never-unpark: unconditional \"active\" stamping let the\n\t\t\t\t// live walk overwrite \"reindexing\" set by a queued reindex op,\n\t\t\t\t// flapping the subgraph back into catch-up (and into collision with\n\t\t\t\t// the op's schema drop). Conditional advance (f069): a no-write\n\t\t\t\t// block can't race-lose in any way that matters (nothing was\n\t\t\t\t// written), so a `false` return here is a silent no-op — the\n\t\t\t\t// cursor simply stays at whatever a racing writer already set it\n\t\t\t\t// to.\n\t\t\t\tawait recordLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t// 4. Data plane (managed target DB) — resolved above, since factory-set\n\t// resolution needs the schema name.\n\tconst blockMeta: BlockMeta = {\n\t\theight: block.height,\n\t\thash: block.hash,\n\t\ttimestamp: block.timestamp,\n\t\tburnBlockHeight: block.burn_block_height,\n\t\tindexBlockHash: block.index_block_hash,\n\t};\n\tconst initialTx: TxMeta = {\n\t\ttxId: \"\",\n\t\tsender: \"\",\n\t\ttype: \"\",\n\t\tstatus: \"\",\n\t};\n\n\tlet handlerMs = 0;\n\tlet flushMs = 0;\n\n\t// Progress + health writes — always on the managed DB, identical in both\n\t// modes (the subgraphs control-plane table lives in target). Only ever\n\t// reached with real work to do on the live catch-up path and the reorg\n\t// rewind path (both leave `skipProgressUpdate` unset); reindex/backfill\n\t// always pass `skipProgressUpdate: true` and return above.\n\tconst applyProgress = async (\n\t\ttx: Transaction<Database>,\n\t\trr: { processed: number; errors: number },\n\t\tflushedWrites: boolean,\n\t) => {\n\t\tif (opts?.skipProgressUpdate) return;\n\t\tconst rewind = isReorgRewind(opts);\n\t\tif (rr.errors > 0 && rr.processed === 0) {\n\t\t\tif (rewind) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, \"error\", blockHeight);\n\t\t\t} else {\n\t\t\t\t// f069: conditional — see recordLiveError's docblock for why a lost\n\t\t\t\t// race here is always a silent no-op (an all-failed block never\n\t\t\t\t// flushes writes, so there's nothing to protect by throwing).\n\t\t\t\tawait recordLiveError(tx, subgraphName, blockHeight);\n\t\t\t}\n\t\t} else if (rewind) {\n\t\t\t// Unconditional, may move the cursor backward — see ProcessBlockOptions.\n\t\t\tawait rewindLiveProgress(tx, subgraphName, blockHeight);\n\t\t} else {\n\t\t\t// Promote-but-never-unpark (see matched-0 note). Conditional advance\n\t\t\t// (f069): a racing writer that already committed a higher cursor for\n\t\t\t// this height means OUR writes must not stand — abort the whole tx\n\t\t\t// so ctx.increment deltas already flushed above roll back with it.\n\t\t\tconst advanced = await recordLiveProgress(tx, subgraphName, blockHeight);\n\t\t\tif (!advanced && flushedWrites) {\n\t\t\t\tthrow new LiveCursorRaceLostError(subgraphName, blockHeight);\n\t\t\t}\n\t\t}\n\t\t// A handler that threw had its writes rolled back (runner.ts\n\t\t// ctx.rollbackTo) but the cursor still advances, so those events are\n\t\t// gone unless something records where. Gap rows are what `/gaps` and\n\t\t// backfill repair from — the reindex path has always written them\n\t\t// (reindex.ts), the live path never did.\n\t\tif (rr.errors > 0 && !rewind) {\n\t\t\tif (opts?.subgraphId) {\n\t\t\t\tawait recordGapBatch(tx, opts.subgraphId, subgraphName, [\n\t\t\t\t\t{ start: blockHeight, end: blockHeight, reason: \"processing_error\" },\n\t\t\t\t]);\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Block errors not recorded as a gap — no subgraphId\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\terrors: rr.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (rr.processed > 0 || rr.errors > 0) {\n\t\t\tconst lastError =\n\t\t\t\trr.errors > 0\n\t\t\t\t\t? `${rr.errors} error(s) at block ${blockHeight}`\n\t\t\t\t\t: undefined;\n\t\t\tawait recordSubgraphProcessed(\n\t\t\t\ttx,\n\t\t\t\tsubgraphName,\n\t\t\t\trr.processed,\n\t\t\t\trr.errors,\n\t\t\t\tlastError,\n\t\t\t);\n\t\t}\n\t};\n\n\t// Managed: a single atomic transaction on the target DB.\n\ttry {\n\t\tawait targetDb.transaction().execute(async (tx: Transaction<Database>) => {\n\t\t\t// Replay guard (sequential walks only): committed writes always carry\n\t\t\t// their checkpoint (below), so a block at/below the cursor has already\n\t\t\t// been applied — running it again would double-apply deltas.\n\t\t\tconst opMode = opCursorMode(opts);\n\t\t\tconst sm = statusMode(opts);\n\t\t\tconst rewind = isReorgRewind(opts);\n\t\t\tif (sm) {\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (opMode) {\n\t\t\t\t// Fast path only — the conditional advance below is the guarantee.\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t\t.where(\"id\", \"=\", opMode.operationId)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (\n\t\t\t\t\trow?.cursor_block != null &&\n\t\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t\t) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!rewind) {\n\t\t\t\t// f069: the same fast-path guard, now armed on the live path.\n\t\t\t\t// Fast path only — the conditional `recordLiveProgress` advance\n\t\t\t\t// below (via applyProgress) is the actual guarantee; this SELECT,\n\t\t\t\t// taken before handlers run, cannot see a same-height race that\n\t\t\t\t// commits between here and there. Never checked when `rewind` is\n\t\t\t\t// set: a reorg's fork block is, by construction, at or below the\n\t\t\t\t// current cursor, and must run anyway.\n\t\t\t\tconst row = await tx\n\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\ttx,\n\t\t\t\tschemaName,\n\t\t\t\tsubgraph.schema,\n\t\t\t\tblockMeta,\n\t\t\t\tinitialTx,\n\t\t\t\tjournalEnabled(opts),\n\t\t\t);\n\n\t\t\t// f071 Stage A: dark, flag-gated dispatch. `sandboxEnabled` requires\n\t\t\t// BOTH the global env gate AND this subgraph's `sandbox_workers`\n\t\t\t// column — nothing in committed code sets that column, so this\n\t\t\t// branch is unreached in production today; `runHandlers` (below)\n\t\t\t// is what actually executes, byte-identical to before this plan.\n\t\t\t// When it IS reached: `runHandlersSandboxed` runs handlers in the\n\t\t\t// sandbox subprocess but replays their decided ops onto THIS same\n\t\t\t// `ctx`, bound to THIS same open transaction, before returning —\n\t\t\t// so the flush/manifest/outbox flow and the f069 guard placement\n\t\t\t// below are unaffected either way (see `host.ts`'s docblock).\n\t\t\tconst handlerStart = performance.now();\n\t\t\tconst runResult = sandboxEnabled({\n\t\t\t\tsandbox_workers: route.sandboxWorkers,\n\t\t\t})\n\t\t\t\t? await runHandlersSandboxed({\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tversion: route.version,\n\t\t\t\t\t\thandlerCode: route.handlerCode,\n\t\t\t\t\t\thostCtx: ctx,\n\t\t\t\t\t\tblock: blockMeta,\n\t\t\t\t\t\tmatched,\n\t\t\t\t\t})\n\t\t\t\t: await runHandlers(subgraph, matched, ctx);\n\t\t\thandlerMs = performance.now() - handlerStart;\n\n\t\t\tresult.processed = runResult.processed;\n\t\t\tresult.errors = runResult.errors;\n\n\t\t\tlet flushedWrites = false;\n\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\tconst flushStart = performance.now();\n\t\t\t\tconst manifest = await ctx.flush();\n\t\t\t\tflushedWrites = manifest.count > 0;\n\t\t\t\tif (manifest.count > 0) {\n\t\t\t\t\tawait emitWebhookOutbox(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\tmatcher,\n\t\t\t\t\t\tblock.height,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t}\n\n\t\t\t// Checkpoint travels with the writes it covers — a crash can never\n\t\t\t// leave committed deltas ahead of the checkpoint (fix-f040 B3).\n\t\t\tif (sm && flushedWrites) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, sm.status, blockHeight);\n\t\t\t} else if (opMode && flushedWrites) {\n\t\t\t\tconst advanced = await advanceOperationCursor(\n\t\t\t\t\ttx,\n\t\t\t\t\topMode.operationId,\n\t\t\t\t\tblockHeight,\n\t\t\t\t);\n\t\t\t\tif (!advanced) {\n\t\t\t\t\t// A racing writer (zombie/claimer) already covered this height —\n\t\t\t\t\t// abort OUR writes; the winner's commit stands.\n\t\t\t\t\tthrow new CursorRaceLostError(opMode.operationId, blockHeight);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait applyProgress(tx, runResult, flushedWrites);\n\t\t});\n\t} catch (err) {\n\t\tif (\n\t\t\terr instanceof CursorRaceLostError ||\n\t\t\terr instanceof LiveCursorRaceLostError\n\t\t) {\n\t\t\t// Success-shaped: the block IS committed (by the winner). Surfacing\n\t\t\t// this as an error would mint a false gap row and re-invite the\n\t\t\t// double-apply through gap repair.\n\t\t\tlogger.warn(\"cursor race lost — block already covered\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\terror: err.message,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tthrow err;\n\t}\n\n\t// Persist factory discoveries only after the block's writes commit, so a\n\t// failed block doesn't leave addresses claimed for a block that produced\n\t// nothing. Stamped with this height, so the reorg handler rolls them back\n\t// with everything else. Idempotent (ON CONFLICT DO NOTHING), so a\n\t// guard-skipped block replaying here is harmless.\n\tif (!result.skipped) {\n\t\tawait persistFactoryDiscoveries(\n\t\t\tschemaName,\n\t\t\troute.dataDb,\n\t\t\tblockHeight,\n\t\t\tdiscovered,\n\t\t);\n\t}\n\n\tconst totalMs = performance.now() - blockStart;\n\t// f069: a skipped block (guard fast-path, or a race-loss success-shaped\n\t// skip) never reaches here as a distinct branch — it falls through from\n\t// the transaction callback's early `return`. `blocks_processed` is now\n\t// load-bearing forensic evidence (f068's own re-derivation of it), so a\n\t// skip must not inflate it: only count blocks that actually ran handlers.\n\tif (!result.skipped) {\n\t\tresult.timing = {\n\t\t\ttotalMs: Math.round(totalMs),\n\t\t\thandlerMs: Math.round(handlerMs),\n\t\t\tflushMs: Math.round(flushMs),\n\t\t};\n\t}\n\n\t// 7. Row count warning — sample every 1000 blocks (uses pg_stat estimate, not COUNT(*))\n\tif (blockHeight % 1000 === 0) {\n\t\ttry {\n\t\t\tconst tables = Object.keys(subgraph.schema);\n\t\t\tfor (const table of tables) {\n\t\t\t\tconst { rows } = await sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(route.dataDb);\n\t\t\t\tconst count = Number((rows[0] as Record<string, unknown>)?.count ?? 0);\n\t\t\t\tif (count >= 10_000_000) {\n\t\t\t\t\tlogger.warn(\"Subgraph table exceeds 10M rows (estimate)\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tcount,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Expected: table may not exist yet (fresh subgraph, first few\n\t\t\t// blocks before DDL runs). Log at debug so real errors —\n\t\t\t// connection, permissions, query plan — aren't invisible.\n\t\t\tlogger.debug(\"Row count sample failed\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t}\n\n\t\t// Prune reorg-journal entries past finality (fix-f040 B2). Same cadence\n\t\t// as the row sample; retention is generous vs observed reorg depth.\n\t\tif (journalEnabled(opts)) {\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`DELETE FROM \"${schemaName}\".\"_journal\" WHERE \"block_height\" < ${blockHeight - JOURNAL_RETENTION_BLOCKS}`,\n\t\t\t\t)\n\t\t\t\t.execute(route.dataDb)\n\t\t\t\t.catch(() => {\n\t\t\t\t\t// Journal may not exist yet (pre-journal deploy, no writes since).\n\t\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n",
18
+ "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Transaction } from \"@secondlayer/shared/db\";\nimport {\n\ttype IndexEventRow,\n\ttype IndexHttpClient,\n\ttype IndexTransactionRow,\n\tcreateInternalIndexHttpClient,\n} from \"@secondlayer/shared/index-http\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition, SubgraphFilter } from \"../types.ts\";\nimport { type BlockData, loadBlockRange } from \"./batch-loader.ts\";\nimport { ObserverHttpBlockSource } from \"./observer-http-source.ts\";\nimport {\n\treconstructBlock,\n\treconstructEvent,\n\treconstructTransaction,\n\treconstructTxFromEventRow,\n} from \"./reconstruct.ts\";\n\n/**\n * Where the subgraph runtime reads canonical chain data. Today it taps the\n * indexer Postgres directly (`PostgresBlockSource`); the re-point adds a\n * `PublicApiBlockSource` that consumes the Streams clock + Index data over\n * HTTP. `matchSources` / handlers / flush / outbox are unchanged — only the\n * loader + tip swap behind this seam.\n */\nexport interface BlockSource {\n\t/** Highest canonical block height available to process. */\n\tgetTip(): Promise<number>;\n\t/** Canonical block data for [fromHeight, toHeight], keyed by height. */\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>>;\n\t/** Sparse-scan probe: lowest height in (afterHeight, untilHeight] holding\n\t * an event this source's subgraph could match, or null when the rest of\n\t * the range is empty. Optional — only event-scoped sources support it. */\n\tnextDataHeight?(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null>;\n}\n\n/** A (decoded event type, optional contract scope) pair the sparse probe\n * checks. Contract scoping is what makes token-subgraph reindexes leap over\n * everything that isn't their token. */\nexport type SparseProbeTarget = { eventType: string; contractId?: string };\n\n/** Sparse scanning is sound only when EVERY source is an event-type filter —\n * a contract_call/contract_deploy source matches transactions, which the\n * event probe can't see. */\nexport function canSparseScan(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\treturn filters.every((f) => Boolean(EVENT_FILTER_TO_INDEX_TYPE[f.type]));\n}\n\n/** Probe targets for a subgraph's filters: decoded type + contract scope when\n * the filter pins one (assetIdentifier \"SP….contract::asset\" or contractId). */\nexport function sparseProbeTargets(\n\tsubgraph: SubgraphDefinition,\n): SparseProbeTarget[] {\n\tconst targets = new Map<string, SparseProbeTarget>();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst eventType = EVENT_FILTER_TO_INDEX_TYPE[f.type];\n\t\tif (!eventType) continue;\n\t\tconst scoped = f as { assetIdentifier?: string; contractId?: string };\n\t\tconst contractId =\n\t\t\tscoped.contractId ?? scoped.assetIdentifier?.split(\"::\")[0];\n\t\tconst key = `${eventType}|${contractId ?? \"\"}`;\n\t\ttargets.set(key, { eventType, ...(contractId ? { contractId } : {}) });\n\t}\n\treturn [...targets.values()];\n}\n\n/** Reads directly from the shared indexer Postgres (the original behavior). */\nexport class PostgresBlockSource implements BlockSource {\n\tasync getTip(): Promise<number> {\n\t\tconst progress = await getSourceDb()\n\t\t\t.selectFrom(\"index_progress\")\n\t\t\t.selectAll()\n\t\t\t.where(\"network\", \"=\", process.env.NETWORK ?? \"mainnet\")\n\t\t\t.executeTakeFirst();\n\t\treturn progress ? Number(progress.highest_seen_block) : 0;\n\t}\n\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\treturn loadBlockRange(getSourceDb(), fromHeight, toHeight);\n\t}\n}\n\n// Subgraph source filter types that map to a decoded Index event_type. The\n// `_event` suffix is the runtime's raw form; print is keyed `print_event`.\nconst EVENT_FILTER_TO_INDEX_TYPE: Record<string, string> = {\n\tstx_transfer: \"stx_transfer\",\n\tstx_mint: \"stx_mint\",\n\tstx_burn: \"stx_burn\",\n\tstx_lock: \"stx_lock\",\n\tft_transfer: \"ft_transfer\",\n\tft_mint: \"ft_mint\",\n\tft_burn: \"ft_burn\",\n\tnft_transfer: \"nft_transfer\",\n\tnft_mint: \"nft_mint\",\n\tnft_burn: \"nft_burn\",\n\tprint_event: \"print\",\n\tnested_contract_call: \"nested_contract_call\",\n\tvar_set: \"var_set\",\n\tmap_set: \"map_set\",\n\tmap_insert: \"map_insert\",\n\tmap_delete: \"map_delete\",\n};\n\n// Tx-level source types — matched against /v1/index/transactions, not events.\nconst TX_SOURCE_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\n// Second clock (ordinal). Never part of a tx's classic event set: a\n// contract_call/contract_deploy source fetches every CLASSIC type, and vm\n// types are fetched only when a vm source names them.\nexport const VM_INDEX_EVENT_TYPES: ReadonlySet<string> = new Set([\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n]);\nconst CLASSIC_INDEX_EVENT_TYPES = [\n\t...new Set(Object.values(EVENT_FILTER_TO_INDEX_TYPE)),\n].filter((t) => !VM_INDEX_EVENT_TYPES.has(t));\n\nfunction sourceFilters(subgraph: SubgraphDefinition): SubgraphFilter[] {\n\tconst sources = subgraph.sources;\n\treturn Array.isArray(sources)\n\t\t? (sources as SubgraphFilter[])\n\t\t: Object.values(sources as Record<string, SubgraphFilter>);\n}\n\n/**\n * True when any source matches transactions (contract_call / contract_deploy):\n * the handler receives the full tx, so the loader must fetch real transactions.\n * Event-only subgraphs skip walkTransactions and synthesize the tx from joined\n * event context instead (the ~37x reindex over-fetch; see indexing-speed plan).\n */\nexport function needsTransactionData(subgraph: SubgraphDefinition): boolean {\n\treturn sourceFilters(subgraph).some((f) => TX_SOURCE_TYPES.has(f.type));\n}\n\n/** Build the (few) event-bearing txs from joined event context, one per tx_id —\n * the event-only replacement for draining every transaction in the range. */\nfunction synthesizeTxsFromEvents(events: IndexEventRow[]): Transaction[] {\n\tconst byId = new Map<string, Transaction>();\n\tfor (const e of events) {\n\t\tif (!byId.has(e.tx_id)) byId.set(e.tx_id, reconstructTxFromEventRow(e));\n\t}\n\treturn [...byId.values()];\n}\n\n/**\n * The Index event_types the loader must fetch for a set of source filter types.\n * A contract_call/contract_deploy source matches a tx and hands its FULL event\n * set to the handler, so when one is present we fetch every classic event type\n * (the matched tx's events must be complete); otherwise just the referenced\n * types. VM types ride a second clock and are fetched only when referenced.\n * Shared by the subgraph loader and the chain-trigger evaluator.\n */\nexport function indexEventTypesForFilterTypes(filterTypes: string[]): string[] {\n\tconst types = new Set<string>();\n\tif (filterTypes.some((t) => TX_SOURCE_TYPES.has(t))) {\n\t\tfor (const t of CLASSIC_INDEX_EVENT_TYPES) types.add(t);\n\t}\n\tfor (const t of filterTypes) {\n\t\tconst indexType = EVENT_FILTER_TO_INDEX_TYPE[t];\n\t\tif (indexType) types.add(indexType);\n\t}\n\treturn [...types];\n}\n\n/** Index event_types a subgraph's sources require. Empty when sources are absent. */\nexport function referencedIndexEventTypes(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\tif (!subgraph.sources) return [];\n\treturn indexEventTypesForFilterTypes(\n\t\tsourceFilters(subgraph).map((f) => f.type),\n\t);\n}\n\n/**\n * streams-index eligibility: every source must be a known event-type or\n * contract_call/contract_deploy filter (no array-style sources, which leak the\n * unreconstructable `_eventId`). Trait scope IS allowed — trait resolution\n * reads the contract registry on the platform DB (`targetDb`), which the\n * processor always holds, so it's source-independent. Everything else stays on\n * the DB tap.\n */\nexport function isStreamsIndexEligible(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\tfor (const f of filters) {\n\t\tconst known =\n\t\t\tEVENT_FILTER_TO_INDEX_TYPE[f.type] || TX_SOURCE_TYPES.has(f.type);\n\t\tif (!known) return false;\n\t}\n\treturn true;\n}\n\n/** Streams clock + Index data plane, reconstructed into raw BlockData rows. */\nexport class PublicApiBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly http: IndexHttpClient,\n\t\tprivate readonly eventTypes: string[],\n\t\t/** When set, enables the sparse-scan probe (event-scoped subgraphs). */\n\t\tprivate readonly probeTargets?: SparseProbeTarget[],\n\t\t/** False for event-only subgraphs → skip walkTransactions, synthesize the\n\t\t * tx from joined event context. Defaults true (safe / unchanged). */\n\t\tprivate readonly needsTransactions = true,\n\t) {}\n\n\t/** Lowest height in (after, until] any probe target hits, or null. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.probeTargets?.length) return afterHeight + 1;\n\t\tconst hits = await Promise.all(\n\t\t\tthis.probeTargets.map((t) =>\n\t\t\t\tthis.http.firstEventHeight(\n\t\t\t\t\tt.eventType,\n\t\t\t\t\tafterHeight + 1,\n\t\t\t\t\tuntilHeight,\n\t\t\t\t\tt.contractId,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst found = hits.filter((h): h is number => h !== null);\n\t\treturn found.length ? Math.min(...found) : null;\n\t}\n\n\tgetTip(): Promise<number> {\n\t\t// VM rows land with ingest. Decoded Index tip can lag; use the source\n\t\t// field when this loader fetches any vm type.\n\t\tif (this.eventTypes.some((t) => VM_INDEX_EVENT_TYPES.has(t))) {\n\t\t\treturn this.http.getIndexSourceTip();\n\t\t}\n\t\treturn this.http.getIndexTip();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\t// Event-only subgraphs join tx context onto events (withTx) and skip the\n\t\t// walkTransactions over-fetch entirely; tx-level sources fetch real txs.\n\t\tconst withTx = !this.needsTransactions;\n\t\tconst [blocks, txRows, eventLists] = await Promise.all([\n\t\t\tthis.http.walkBlocks(fromHeight, toHeight),\n\t\t\tthis.needsTransactions\n\t\t\t\t? this.http.walkTransactions(fromHeight, toHeight)\n\t\t\t\t: Promise.resolve<IndexTransactionRow[]>([]),\n\t\t\tPromise.all(\n\t\t\t\tthis.eventTypes.map((t) =>\n\t\t\t\t\tthis.http.walkEvents(t, fromHeight, toHeight, withTx),\n\t\t\t\t),\n\t\t\t),\n\t\t]);\n\n\t\tconst map = new Map<number, BlockData>();\n\t\t// Seed every canonical height (incl. empty blocks) so catch-up doesn't\n\t\t// file them as gaps.\n\t\tfor (const b of blocks) {\n\t\t\tmap.set(b.block_height, {\n\t\t\t\tblock: reconstructBlock(b),\n\t\t\t\ttxs: [],\n\t\t\t\tevents: [],\n\t\t\t});\n\t\t}\n\t\t// For event-only subgraphs, materialize only the event-bearing txs from\n\t\t// joined event context instead of every transaction in the range.\n\t\tconst txs = this.needsTransactions\n\t\t\t? txRows.map(reconstructTransaction)\n\t\t\t: synthesizeTxsFromEvents(eventLists.flat());\n\t\tfor (const t of txs) {\n\t\t\tmap.get(t.block_height)?.txs.push(t);\n\t\t}\n\t\tfor (const list of eventLists) {\n\t\t\tfor (const e of list) {\n\t\t\t\tconst bd = map.get(e.block_height);\n\t\t\t\tif (!bd) continue;\n\t\t\t\t// vm rows ride their own clock: never merged into `events`, whose\n\t\t\t\t// order is classic event_index.\n\t\t\t\tif (VM_INDEX_EVENT_TYPES.has(e.event_type)) {\n\t\t\t\t\tbd.vmEvents ??= [];\n\t\t\t\t\tbd.vmEvents.push(reconstructEvent(e));\n\t\t\t\t} else {\n\t\t\t\t\tbd.events.push(reconstructEvent(e));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Canonical ordering — multi-type event walks merge here, per clock.\n\t\tfor (const bd of map.values()) {\n\t\t\tbd.txs.sort((a, b) => a.tx_index - b.tx_index);\n\t\t\tbd.events.sort((a, b) => a.event_index - b.event_index);\n\t\t\tbd.vmEvents?.sort((a, b) => a.event_index - b.event_index);\n\t\t}\n\t\treturn map;\n\t}\n}\n\n/**\n * Wraps a primary source and falls back to a secondary, per call, when the\n * primary throws. Use it to make the HTTP (Streams+Index) plane a SOFT dependency:\n * if api is unavailable, the processor reads the Postgres tap and keeps advancing\n * instead of stalling. Safe to mix mid-stream — both taps read the same canonical\n * chain at the same heights and the cursor is forward-only. Stateless (no breaker)\n * so it's failover-safe across replicas; the primary is retried every call and\n * resumes transparently once healthy.\n */\nexport class FallbackBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly primary: BlockSource,\n\t\tprivate readonly fallback: BlockSource,\n\t) {}\n\n\tasync getTip(): Promise<number> {\n\t\ttry {\n\t\t\treturn await this.primary.getTip();\n\t\t} catch (err) {\n\t\t\tlogger.warn(\"block source primary getTip failed — using DB tap\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.getTip();\n\t\t}\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\ttry {\n\t\t\treturn await this.primary.loadBlockRange(fromHeight, toHeight);\n\t\t} catch (err) {\n\t\t\tlogger.warn(\"block source primary loadBlockRange failed — using DB tap\", {\n\t\t\t\tfrom: fromHeight,\n\t\t\t\tto: toHeight,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.loadBlockRange(fromHeight, toHeight);\n\t\t}\n\t}\n\n\t/** Probe via the primary only; a probe failure just means \"no skip\" —\n\t * the caller falls back to plain batch advancement. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.primary.nextDataHeight) return afterHeight + 1;\n\t\ttry {\n\t\t\treturn await this.primary.nextDataHeight(afterHeight, untilHeight);\n\t\t} catch {\n\t\t\treturn afterHeight + 1;\n\t\t}\n\t}\n}\n\nconst postgresBlockSource = new PostgresBlockSource();\n\n/**\n * HTTP (Streams+Index) chain source for a set of decoded event types, wrapped so\n * it falls back to the Postgres tap when api is down. Used by the chain-trigger\n * evaluator (which isn't subgraph-scoped, so it can't go through resolveBlockSource).\n */\nexport function buildChainBlockSource(eventTypes: string[]): BlockSource {\n\treturn new FallbackBlockSource(\n\t\tnew PublicApiBlockSource(buildHttpClient(), eventTypes),\n\t\tpostgresBlockSource,\n\t);\n}\n\nexport function buildHttpClient(): IndexHttpClient {\n\treturn createInternalIndexHttpClient();\n}\n\n/**\n * Resolve the block source for a subgraph. `SUBGRAPH_SOURCE=streams-index`\n * opts eligible subgraphs onto the public Streams clock + Index data;\n * `SUBGRAPH_SOURCE=observer-http` pages internal observer-events (experimental).\n * Default stays on the Postgres tap.\n */\nexport function resolveBlockSource(subgraph?: SubgraphDefinition): BlockSource {\n\tif (process.env.SUBGRAPH_SOURCE === \"observer-http\") {\n\t\tconst baseUrl = process.env.OBSERVER_HTTP_URL;\n\t\tif (!baseUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t\"SUBGRAPH_SOURCE=observer-http requires OBSERVER_HTTP_URL\",\n\t\t\t);\n\t\t}\n\t\treturn new ObserverHttpBlockSource({\n\t\t\tbaseUrl,\n\t\t\ttoken: process.env.OBSERVER_HTTP_EXPORT_TOKEN || null,\n\t\t});\n\t}\n\tif (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tsubgraph &&\n\t\tisStreamsIndexEligible(subgraph)\n\t) {\n\t\t// Soft-depend on api: fall back to the Postgres tap per-call if the HTTP\n\t\t// plane is down, so the processor keeps advancing instead of stalling.\n\t\treturn new FallbackBlockSource(\n\t\t\tnew PublicApiBlockSource(\n\t\t\t\tbuildHttpClient(),\n\t\t\t\treferencedIndexEventTypes(subgraph),\n\t\t\t\tcanSparseScan(subgraph) ? sparseProbeTargets(subgraph) : undefined,\n\t\t\t\tneedsTransactionData(subgraph),\n\t\t\t),\n\t\t\tpostgresBlockSource,\n\t\t);\n\t}\n\tif (process.env.SUBGRAPH_SOURCE === \"streams-index\" && subgraph) {\n\t\tlogger.debug(\"Subgraph not streams-index eligible, using DB tap\", {\n\t\t\tsubgraph: subgraph.name,\n\t\t});\n\t}\n\treturn postgresBlockSource;\n}\n",
19
+ "import type {\n\tBlock,\n\tDatabase,\n\tEvent,\n\tTransaction,\n} from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\n\n/** A runtime event row. `clock: \"vm\"` marks an opt-in `vm_events` row whose\n * `event_index` is `ordinal` — a second ordinal that never sorts or\n * dedupes against classic `events.event_index`. */\nexport type RuntimeEvent = Event & { clock?: \"vm\" };\n\nexport interface BlockData {\n\tblock: Block;\n\ttxs: Transaction[];\n\t/** Classic `events` rows (Streams 1.0 clock). */\n\tevents: Event[];\n\t/** Opt-in `vm_events` rows on their own clock. Absent/empty on `\"*\"`\n\t * nodes and on archives collected without `storage`/`contract_calls`. */\n\tvmEvents?: RuntimeEvent[];\n}\n\n/** Stable synthetic id for a vm row. Distinct from the classic `tx#index`\n * so a print at event_index N and a map_set at ordinal N never share\n * an identity. */\nexport function vmEventId(txId: string, vmEventIndex: number): string {\n\treturn `${txId}#vm:${vmEventIndex}`;\n}\n\n/**\n * Load a range of blocks with their transactions and events in 4 parallel queries.\n * Returns a Map keyed by block height. Non-canonical blocks are excluded.\n */\nexport async function loadBlockRange(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n\ttoHeight: number,\n): Promise<Map<number, BlockData>> {\n\tconst [blocks, txs, events, vmRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.selectAll()\n\t\t\t.where(\"height\", \">=\", fromHeight)\n\t\t\t.where(\"height\", \"<=\", toHeight)\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"transactions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"events\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"vm_events\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.orderBy(\"ordinal\", \"asc\")\n\t\t\t.execute(),\n\t]);\n\n\t// Index by block height (coerce to number — bigint columns may return as string or number)\n\tconst txsByHeight = new Map<number, Transaction[]>();\n\tfor (const tx of txs) {\n\t\tconst h = Number(tx.block_height);\n\t\tconst list = txsByHeight.get(h) ?? [];\n\t\tlist.push(tx);\n\t\ttxsByHeight.set(h, list);\n\t}\n\n\tconst eventsByHeight = new Map<number, Event[]>();\n\tfor (const evt of events) {\n\t\tconst h = Number(evt.block_height);\n\t\tconst list = eventsByHeight.get(h) ?? [];\n\t\tlist.push(evt);\n\t\teventsByHeight.set(h, list);\n\t}\n\n\tconst vmByHeight = new Map<number, RuntimeEvent[]>();\n\tfor (const row of vmRows) {\n\t\tconst h = Number(row.block_height);\n\t\tconst list = vmByHeight.get(h) ?? [];\n\t\tlist.push({\n\t\t\tid: vmEventId(row.tx_id, Number(row.ordinal)),\n\t\t\ttx_id: row.tx_id,\n\t\t\tblock_height: h,\n\t\t\tevent_index: Number(row.ordinal),\n\t\t\ttype: row.type,\n\t\t\tdata: row.data,\n\t\t\tcreated_at: row.created_at,\n\t\t\tclock: \"vm\",\n\t\t} as RuntimeEvent);\n\t\tvmByHeight.set(h, list);\n\t}\n\n\tconst result = new Map<number, BlockData>();\n\tfor (const block of blocks) {\n\t\tconst h = Number(block.height);\n\t\tresult.set(h, {\n\t\t\tblock,\n\t\t\ttxs: txsByHeight.get(h) ?? [],\n\t\t\tevents: eventsByHeight.get(h) ?? [],\n\t\t\tvmEvents: vmByHeight.get(h) ?? [],\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Compute average events per block from a loaded batch.\n * Used for adaptive batch sizing.\n */\nexport function avgEventsPerBlock(batch: Map<number, BlockData>): number {\n\tif (batch.size === 0) return 0;\n\tlet totalEvents = 0;\n\tfor (const data of batch.values()) {\n\t\ttotalEvents += data.events.length;\n\t}\n\treturn totalEvents / batch.size;\n}\n",
20
+ "import {\n\tVM_NODE_TO_STORED_TYPE,\n\ttype VmNodeEventType,\n} from \"@secondlayer/shared\";\nimport type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport {\n\ttype BlockData,\n\ttype RuntimeEvent,\n\tvmEventId,\n} from \"./batch-loader.ts\";\nimport type { BlockSource } from \"./block-source.ts\";\n\n/** Duplicated from indexer — do not import `@secondlayer/indexer` (cycle). */\nconst OBSERVER_HTTP_EXPORT_PATH = \"/internal/observer-events\";\n\nexport type ObserverHttpFetch = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport type ObserverHttpBlockSourceOpts = {\n\t/** e.g. http://127.0.0.1:3700 — trailing slash stripped */\n\tbaseUrl: string;\n\ttoken?: string | null;\n\tfetch?: ObserverHttpFetch;\n\t/** Unused on the wire; list filtering is server-side. */\n\tnetwork?: string;\n};\n\ntype ObserverEventsNext = {\n\tafter_height: number;\n\tafter_index_block_hash: string;\n};\n\ntype SbaObserverMessage = {\n\tpath: string;\n\tpayload: unknown;\n\tcontent_sha256: string;\n\tblock_height: number | null;\n\tindex_block_hash: string | null;\n\treceived_at?: string;\n};\n\ntype ObserverEventsResponse = {\n\tevents: SbaObserverMessage[];\n\tnext: ObserverEventsNext | null;\n};\n\ntype ObserverTipResponse = {\n\tblock_height: number;\n\tindex_block_hash: string | null;\n};\n\ntype ObserverTx = {\n\ttxid?: string;\n\ttx_index?: number;\n\ttx_type?: string;\n\tsender_address?: string;\n\tstatus?: string;\n\traw_result?: string | null;\n\traw_tx?: string;\n\tcontract_call?: { contract_id?: string; function_name?: string };\n\tsmart_contract?: { contract_id?: string };\n};\n\ntype ObserverEvent = {\n\ttxid?: string;\n\tevent_index?: number;\n\ttype?: string;\n\t[key: string]: unknown;\n};\n\ntype ObserverNewBlockPayload = {\n\tblock_height?: number;\n\tblock_hash?: string;\n\tparent_block_hash?: string;\n\tburn_block_height?: number;\n\tburn_block_hash?: string | null;\n\tindex_block_hash?: string | null;\n\ttimestamp?: number;\n\tblock_time?: number;\n\tburn_block_time?: number;\n\tburn_block_timestamp?: number;\n\ttransactions?: ObserverTx[];\n\tevents?: ObserverEvent[];\n\t/** Opt-in traces; omitted on `\"*\"` bodies. */\n\tvm_events?: ObserverVmTrace[];\n};\n\ntype ObserverVmTrace = {\n\ttxid?: string;\n\tcommitted?: boolean;\n\ttype?: string;\n\t[key: string]: unknown;\n};\n\nfunction stripTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction blockTimestamp(payload: ObserverNewBlockPayload): number {\n\tfor (const value of [\n\t\tpayload.timestamp,\n\t\tpayload.block_time,\n\t\tpayload.burn_block_time,\n\t\tpayload.burn_block_timestamp,\n\t]) {\n\t\tif (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction eventData(event: ObserverEvent): unknown {\n\tif (typeof event.type === \"string\" && event.type in event) {\n\t\treturn event[event.type] ?? {};\n\t}\n\treturn {};\n}\n\n/** Map a `/new_block` observer payload into subgraph `BlockData`. No Hiro. */\nexport function mapNewBlockPayloadToBlockData(payload: unknown): BlockData {\n\tconst p = payload as ObserverNewBlockPayload;\n\tif (\n\t\ttypeof p.block_height !== \"number\" ||\n\t\t!Number.isFinite(p.block_height) ||\n\t\ttypeof p.index_block_hash !== \"string\" ||\n\t\tp.index_block_hash.length === 0\n\t) {\n\t\tthrow new Error(\n\t\t\t\"observer /new_block payload missing block_height or index_block_hash\",\n\t\t);\n\t}\n\n\tconst height = p.block_height;\n\tconst block = {\n\t\theight,\n\t\thash: p.block_hash ?? \"\",\n\t\tparent_hash: p.parent_block_hash ?? \"\",\n\t\tburn_block_height: p.burn_block_height ?? 0,\n\t\tburn_block_hash: p.burn_block_hash ?? null,\n\t\tindex_block_hash: p.index_block_hash,\n\t\ttimestamp: blockTimestamp(p),\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n\n\tconst txs: Transaction[] = (p.transactions ?? []).map((tx) => {\n\t\tlet contractId: string | null = null;\n\t\tlet functionName: string | null = null;\n\t\tif (tx.tx_type === \"contract_call\" && tx.contract_call) {\n\t\t\tcontractId = tx.contract_call.contract_id ?? null;\n\t\t\tfunctionName = tx.contract_call.function_name ?? null;\n\t\t} else if (tx.tx_type === \"smart_contract\" && tx.smart_contract) {\n\t\t\tcontractId = tx.smart_contract.contract_id ?? null;\n\t\t}\n\t\treturn {\n\t\t\ttx_id: tx.txid ?? \"\",\n\t\t\tblock_height: height,\n\t\t\ttx_index: tx.tx_index ?? 0,\n\t\t\ttype: tx.tx_type ?? \"\",\n\t\t\tsender: tx.sender_address ?? \"\",\n\t\t\tstatus: tx.status ?? \"success\",\n\t\t\tcontract_id: contractId,\n\t\t\tfunction_name: functionName,\n\t\t\tfunction_args: [],\n\t\t\traw_result: tx.raw_result ?? null,\n\t\t\traw_tx: tx.raw_tx ?? \"\",\n\t\t\tcreated_at: new Date(0),\n\t\t} as Transaction;\n\t});\n\n\tconst events: Event[] = (p.events ?? []).map((event) => {\n\t\tconst txId = event.txid ?? \"\";\n\t\tconst eventIndex = event.event_index ?? 0;\n\t\treturn {\n\t\t\tid: `${txId}#${eventIndex}`,\n\t\t\ttx_id: txId,\n\t\t\tblock_height: height,\n\t\t\tevent_index: eventIndex,\n\t\t\ttype: event.type ?? \"\",\n\t\t\tdata: eventData(event),\n\t\t\tcreated_at: new Date(0),\n\t\t} as Event;\n\t});\n\n\t// Opt-in `vm_events` (present only when the observer subscribed to\n\t// `storage` / `contract_calls`). Node type → stored name; own clock.\n\tconst vmEvents: RuntimeEvent[] = [];\n\tfor (const [i, trace] of (p.vm_events ?? []).entries()) {\n\t\tconst nodeType = trace.type;\n\t\tif (typeof nodeType !== \"string\" || !(nodeType in VM_NODE_TO_STORED_TYPE))\n\t\t\tcontinue;\n\t\tconst stored = VM_NODE_TO_STORED_TYPE[nodeType as VmNodeEventType];\n\t\tconst body = trace[nodeType];\n\t\tif (!body || typeof body !== \"object\") continue;\n\t\tconst txId = trace.txid ?? \"\";\n\t\tconst vmIndex = i;\n\t\tvmEvents.push({\n\t\t\tid: vmEventId(txId, vmIndex),\n\t\t\ttx_id: txId,\n\t\t\tblock_height: height,\n\t\t\tevent_index: vmIndex,\n\t\t\ttype: stored,\n\t\t\tdata: body,\n\t\t\tcreated_at: new Date(0),\n\t\t\tclock: \"vm\",\n\t\t} as RuntimeEvent);\n\t}\n\n\treturn { block, txs, events, vmEvents };\n}\n\n/**\n * Experimental BlockSource: pages indexer `/internal/observer-events` and maps\n * raw `/new_block` bodies to `BlockData`. Not the production default.\n */\nexport class ObserverHttpBlockSource implements BlockSource {\n\tprivate readonly baseUrl: string;\n\tprivate readonly token: string | null;\n\tprivate readonly fetchFn: ObserverHttpFetch;\n\n\tconstructor(opts: ObserverHttpBlockSourceOpts) {\n\t\tthis.baseUrl = stripTrailingSlash(opts.baseUrl);\n\t\tthis.token = opts.token ?? null;\n\t\tthis.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n\t}\n\n\tprivate headers(): Record<string, string> {\n\t\tif (!this.token) return {};\n\t\treturn { Authorization: `Bearer ${this.token}` };\n\t}\n\n\tasync getTip(): Promise<number> {\n\t\tconst res = await this.fetchFn(\n\t\t\t`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}/tip`,\n\t\t\t{ headers: this.headers() },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t);\n\t\t}\n\t\tlet body: ObserverTipResponse;\n\t\ttry {\n\t\t\tbody = (await res.json()) as ObserverTipResponse;\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\ttypeof body.block_height !== \"number\" ||\n\t\t\t!Number.isFinite(body.block_height)\n\t\t) {\n\t\t\tthrow new Error(\"observer tip missing block_height\");\n\t\t}\n\t\treturn body.block_height;\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\tconst result = new Map<number, BlockData>();\n\t\tlet afterHeight: number | undefined =\n\t\t\tfromHeight > 0 ? fromHeight - 1 : undefined;\n\t\tlet afterIndexBlockHash: string | undefined;\n\n\t\tfor (;;) {\n\t\t\tconst url = new URL(`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}`);\n\t\t\turl.searchParams.set(\"path\", \"/new_block\");\n\t\t\turl.searchParams.set(\"limit\", \"100\");\n\t\t\tif (afterHeight != null) {\n\t\t\t\turl.searchParams.set(\"after_height\", String(afterHeight));\n\t\t\t}\n\t\t\tif (afterIndexBlockHash) {\n\t\t\t\turl.searchParams.set(\"after_index_block_hash\", afterIndexBlockHash);\n\t\t\t}\n\n\t\t\tconst res = await this.fetchFn(url.toString(), {\n\t\t\t\theaders: this.headers(),\n\t\t\t});\n\t\t\tif (!res.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet body: ObserverEventsResponse;\n\t\t\ttry {\n\t\t\t\tbody = (await res.json()) as ObserverEventsResponse;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet pastTo = false;\n\t\t\tfor (const message of body.events ?? []) {\n\t\t\t\tif (message.path === \"/new_burn_block\") continue;\n\t\t\t\tconst height = (message.payload as ObserverNewBlockPayload)\n\t\t\t\t\t?.block_height;\n\t\t\t\tif (typeof height === \"number\" && height > toHeight) {\n\t\t\t\t\tpastTo = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst data = mapNewBlockPayloadToBlockData(message.payload);\n\t\t\t\tconst h = data.block.height;\n\t\t\t\tif (h >= fromHeight && h <= toHeight) {\n\t\t\t\t\tresult.set(h, data);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (pastTo || body.next == null) break;\n\t\t\tafterHeight = body.next.after_height;\n\t\t\tafterIndexBlockHash = body.next.after_index_block_hash;\n\t\t}\n\n\t\treturn result;\n\t}\n}\n",
21
+ "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\nimport { vmEventId } from \"./batch-loader.ts\";\n\nexport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\n\n/**\n * Reconstruct the raw `blocks`/`events` row shapes the subgraph runtime expects\n * (the shapes `matchSources` + the handler runner read) from the decoded,\n * flattened rows the public Index API serves. This is what lets\n * `PublicApiBlockSource` feed the EXISTING pipeline byte-identically to the\n * Postgres tap.\n *\n * Two shape gaps the Index API can't avoid, handled here:\n * - Index event rows are flat (`event_type: \"ft_transfer\"`, columns\n * `sender`/`amount`/…); the runtime expects the node's nested `data` keyed by\n * a suffixed `type` (`ft_transfer_event`), with print under `contract_event`.\n * - nft/print Clarity values: the runtime decodes from the canonical hex\n * (`raw_value`), so we place the Index hex there. (The node's verbose\n * serde-tagged `value`, e.g. `{UInt:223}`, is not reproducible from hex and\n * is no longer read — see the nft tokenId normalization in runner.ts.)\n */\n\n/** ISO `block_time` (or null) → unix-seconds integer the runtime expects. */\nfunction isoToUnixSeconds(iso: string | null): number {\n\tif (!iso) return 0;\n\treturn Math.floor(new Date(iso).getTime() / 1000);\n}\n\nexport function reconstructBlock(b: IndexBlockRow): Block {\n\treturn {\n\t\theight: b.block_height,\n\t\thash: b.block_hash,\n\t\tparent_hash: b.parent_hash,\n\t\tburn_block_height: b.burn_block_height,\n\t\tburn_block_hash: b.burn_block_hash,\n\t\t// Present since the blocks endpoint started serving it; older API\n\t\t// deployments omit it, and a null propagates to a clean refusal in\n\t\t// `ctx.client.readOnly` rather than an unpinned tip read.\n\t\tindex_block_hash: b.index_block_hash ?? null,\n\t\ttimestamp: isoToUnixSeconds(b.block_time),\n\t\t// Index serves canonical rows only.\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n}\n\nexport function reconstructTransaction(t: IndexTransactionRow): Transaction {\n\treturn {\n\t\ttx_id: t.tx_id,\n\t\tblock_height: t.block_height,\n\t\ttx_index: t.tx_index,\n\t\ttype: t.tx_type,\n\t\tsender: t.sender,\n\t\tstatus: t.status,\n\t\tcontract_id:\n\t\t\tt.contract_call?.contract_id ?? t.smart_contract?.contract_id ?? null,\n\t\tfunction_name: t.contract_call?.function_name ?? null,\n\t\t// Raw hex ClarityValues — the runner decodes them via its own deserializeCV\n\t\t// path, identical to the DB tap.\n\t\tfunction_args: t.contract_call?.function_args_hex ?? [],\n\t\traw_result: t.contract_call?.result_hex ?? null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\n/**\n * Build a minimal canonical Transaction from an event row's joined tx context\n * (`tx_context=true` on /v1/index/events). For event-only subgraphs this lets\n * the loader materialize only the txs that actually carry a matched event,\n * instead of draining every transaction in the range (the ~37x reindex\n * over-fetch — see docs/sprints/indexing-speed/plan.md). `function_args` /\n * `raw_result` are empty: an event source never reads them (contract_call-only).\n */\nexport function reconstructTxFromEventRow(e: IndexEventRow): Transaction {\n\treturn {\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\ttx_index: e.tx_index ?? 0,\n\t\ttype: e.tx_type ?? \"\",\n\t\tsender: e.tx_sender ?? \"\",\n\t\tstatus: e.tx_status ?? \"success\",\n\t\tcontract_id: e.tx_contract_id ?? null,\n\t\tfunction_name: e.tx_function_name ?? null,\n\t\tfunction_args: [],\n\t\traw_result: null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\nexport function reconstructEvent(e: IndexEventRow): Event {\n\tconst base = {\n\t\t// Synthetic, deterministic id. The runtime only reads `id` for error logs\n\t\t// and the `*`-wildcard payload (which is streams-index-ineligible).\n\t\tid: `${e.tx_id}#${e.event_index}`,\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\tevent_index: e.event_index,\n\t\tcreated_at: new Date(0),\n\t};\n\n\tswitch (e.event_type) {\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\t// Canonical hex → runner decodes tokenId from raw_value.\n\t\t\t\t\traw_value: e.value,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t\t// Raw stx_transfer always carries memo (\"\" when empty); Index\n\t\t\t\t\t// returns null for empty — default to \"\" to match the DB tap.\n\t\t\t\t\t...(e.event_type === \"stx_transfer\" ? { memo: e.memo ?? \"\" } : {}),\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"stx_lock_event\",\n\t\t\t\tdata: {\n\t\t\t\t\tlocked_address: e.sender,\n\t\t\t\t\tlocked_amount: e.amount,\n\t\t\t\t\tunlock_height: e.payload.unlock_height,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"print\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"contract_event\",\n\t\t\t\tdata: {\n\t\t\t\t\ttopic: e.payload.topic,\n\t\t\t\t\t// Index serves `contract_id`. Matcher + runner also accept\n\t\t\t\t\t// legacy `contract_identifier`; emit the current field.\n\t\t\t\t\tcontract_id: e.contract_id,\n\t\t\t\t\tvalue: e.payload.value,\n\t\t\t\t\traw_value: e.payload.raw_value,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"nested_contract_call\":\n\t\tcase \"var_set\":\n\t\tcase \"map_set\":\n\t\tcase \"map_insert\":\n\t\tcase \"map_delete\":\n\t\t\t// Second clock: `event_index` here is ordinal. Distinct id +\n\t\t\t// `clock` so it never dedupes or sorts against a classic row.\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tid: vmEventId(e.tx_id, e.event_index),\n\t\t\t\tclock: \"vm\",\n\t\t\t\ttype: e.event_type,\n\t\t\t\tdata: {\n\t\t\t\t\tcontract_identifier: e.contract_id,\n\t\t\t\t\t...(\"payload\" in e && e.payload && typeof e.payload === \"object\"\n\t\t\t\t\t\t? (e.payload as Record<string, unknown>)\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tsender: \"sender\" in e ? e.sender : undefined,\n\t\t\t\t\tcaller: \"caller\" in e ? e.caller : undefined,\n\t\t\t\t\tfunction_name: \"function_name\" in e ? e.function_name : undefined,\n\t\t\t\t\tfunction_args: \"function_args\" in e ? e.function_args : undefined,\n\t\t\t\t\traw_result: \"raw_result\" in e ? e.raw_result : undefined,\n\t\t\t\t\tmap_name: \"map\" in e ? e.map : undefined,\n\t\t\t\t\tvar_name: \"var_name\" in e ? e.var_name : undefined,\n\t\t\t\t\traw_key: \"raw_key\" in e ? e.raw_key : undefined,\n\t\t\t\t\traw_value: \"raw_value\" in e ? e.raw_value : undefined,\n\t\t\t\t},\n\t\t\t} as Event;\n\t}\n}\n",
22
22
  "import { createHash } from \"node:crypto\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { Transaction } from \"kysely\";\nimport type { FlushManifest } from \"./context.ts\";\nimport type { WebhookMatcher } from \"./emitter-matcher.ts\";\n\n/**\n * Emit webhook outbox rows for every flushed write that matches an\n * active webhook. Inserted inside the caller's transaction — the\n * outbox write commits (or rolls back) atomically with the subgraph row\n * writes. Zero outbox inserts if no subs match or the kill-switch is set.\n *\n * Set `SECONDLAYER_EMIT_OUTBOX=false` to bypass entirely — useful during\n * backfills or when a receiver is known-down and operators want to drain\n * tenant writes without producing dead outbox.\n */\n\nlet loggedKillSwitch = false;\n\n/** Flush op → event-type verb. A subscriber tracking a mutable row sees the\n * full lifecycle (created → updated → deleted), not just the initial insert. */\nconst OP_VERB = {\n\tinsert: \"created\",\n\tupdate: \"updated\",\n\tdelete: \"deleted\",\n} as const;\n\nexport function isEmitOutboxEnabled(): boolean {\n\treturn process.env.SECONDLAYER_EMIT_OUTBOX !== \"false\";\n}\n\nfunction dedupKey(\n\tsubgraphName: string,\n\ttableName: string,\n\tblockHeight: number,\n\ttxId: string,\n\trowIndex: number,\n\trow: Record<string, unknown>,\n): string {\n\t// Hash of row content + position → stable across replays of the same\n\t// block (unique constraint on (webhook_id, dedup_key) catches\n\t// duplicate emits if the block is reprocessed).\n\tconst canonical = `${subgraphName}:${tableName}:${blockHeight}:${txId}:${rowIndex}:${stableStringify(row)}`;\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 32);\n}\n\nfunction stableStringify(obj: Record<string, unknown>): string {\n\tconst keys = Object.keys(obj).sort();\n\treturn JSON.stringify(\n\t\tkeys.reduce<Record<string, unknown>>((acc, k) => {\n\t\t\tacc[k] = obj[k];\n\t\t\treturn acc;\n\t\t}, {}),\n\t);\n}\n\nexport async function emitWebhookOutbox(\n\ttx: Transaction<Database>,\n\tsubgraphName: string,\n\tmanifest: FlushManifest,\n\tmatcher: WebhookMatcher,\n\tblockHeight: number,\n): Promise<number> {\n\tif (!isEmitOutboxEnabled()) {\n\t\tif (!loggedKillSwitch) {\n\t\t\tlogger.warn(\"SECONDLAYER_EMIT_OUTBOX=false — outbox emission bypassed\");\n\t\t\tloggedKillSwitch = true;\n\t\t}\n\t\treturn 0;\n\t}\n\tloggedKillSwitch = false;\n\n\tif (manifest.count === 0 || matcher.size() === 0) return 0;\n\n\ttype OutboxInsert = {\n\t\twebhook_id: string;\n\t\tsubgraph_name: string;\n\t\ttable_name: string;\n\t\tblock_height: number;\n\t\ttx_id: string | null;\n\t\trow_pk: Record<string, unknown>;\n\t\tevent_type: string;\n\t\tpayload: Record<string, unknown>;\n\t\tdedup_key: string;\n\t};\n\n\tconst rows: OutboxInsert[] = [];\n\tfor (const write of manifest.writes) {\n\t\tconst subs = matcher.match(subgraphName, write.table, write.row);\n\t\tif (subs.length === 0) continue;\n\n\t\tconst eventType = `${subgraphName}.${write.table}.${OP_VERB[write.op]}`;\n\t\tfor (const s of subs) {\n\t\t\trows.push({\n\t\t\t\twebhook_id: s.id,\n\t\t\t\tsubgraph_name: subgraphName,\n\t\t\t\ttable_name: write.table,\n\t\t\t\tblock_height: blockHeight,\n\t\t\t\t// Nullish-only — an empty-string txId is still a value (block-level\n\t\t\t\t// write with no specific tx), not \"no tx\".\n\t\t\t\ttx_id: write.pk.txId ?? null,\n\t\t\t\trow_pk: write.pk,\n\t\t\t\tevent_type: eventType,\n\t\t\t\tpayload: write.row,\n\t\t\t\tdedup_key: dedupKey(\n\t\t\t\t\tsubgraphName,\n\t\t\t\t\twrite.table,\n\t\t\t\t\twrite.pk.blockHeight,\n\t\t\t\t\twrite.pk.txId,\n\t\t\t\t\twrite.pk.rowIndex,\n\t\t\t\t\twrite.row,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\t}\n\n\tif (rows.length === 0) return 0;\n\n\t// Bulk INSERT with ON CONFLICT DO NOTHING on (webhook_id, dedup_key)\n\t// so a replayed block is a no-op instead of an error.\n\tawait tx\n\t\t.insertInto(\"webhook_outbox\")\n\t\t.values(rows)\n\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t.execute();\n\n\treturn rows.length;\n}\n",
23
23
  "import type { Subgraph } from \"@secondlayer/shared/db\";\n\n/**\n * f071 Stage A — dark, flag-gated rollout of the sandboxed (per-tenant OS\n * subprocess — ported from the disproven Bun Worker substrate, spike doc\n * §10) handler-execution path. Two switches, both required:\n *\n * - `SUBGRAPH_SANDBOX_WORKERS === \"1\"` (env, read at call time — mirrors\n * the `SUBGRAPH_CONCURRENCY`/`SUBGRAPH_SOURCE` idiom in\n * `service.ts`/`webhook-plane.ts`) — the global CAPABILITY switch.\n * Off by default; an operator must deliberately enable the sandbox\n * machinery fleet-wide before any subgraph can use it.\n * - `subgraphs.sandbox_workers` (per-row, migration 0109) — the per-tenant\n * ROLLOUT switch. Off by default for every row (including new ones).\n *\n * Semantics: capability AND rollout, not OR. The global flag alone must\n * never route real traffic through the sandbox path — it only makes the path\n * reachable, so a specific subgraph's `sandbox_workers` column is what\n * actually decides whether ITS blocks run in-process (both flags' default\n * state) or through the sandbox. This lets a future cutover stage cut\n * subgraphs over one at a time without a global switch flip affecting the\n * rest of the fleet, while the dark-build/shadow-run stages can still keep\n * the whole capability off fleet-wide with a single env var.\n *\n * As of Stage A, no code path ever sets `sandbox_workers = true` — the\n * column only exists so a future cutover stage has somewhere to flip.\n * `sandboxEnabled` with today's data (column false everywhere) always\n * returns false regardless of the env flag, so the existing in-process path\n * is exercised unconditionally until an operator both (a) sets the env flag\n * and (b) flips a specific subgraph's column — neither of which this plan\n * does.\n */\nexport function sandboxWorkersGloballyEnabled(): boolean {\n\treturn process.env.SUBGRAPH_SANDBOX_WORKERS === \"1\";\n}\n\nexport function sandboxEnabled(\n\tsubgraph: Pick<Subgraph, \"sandbox_workers\">,\n): boolean {\n\treturn sandboxWorkersGloballyEnabled() && subgraph.sandbox_workers === true;\n}\n",
24
24
  "import { tmpdir } from \"node:os\";\nimport { fileURLToPath } from \"node:url\";\n// f071 Stage A — the host-side membrane + warm per-subgraph SUBPROCESS pool,\n// per the target architecture (`docs/internal/security/subgraph-processor-sandbox-spike.md`\n// §3.3, substrate updated by the Stage A addendum): one warm subprocess per\n// active subgraph, keyed by name, spawned lazily on the first sandboxed\n// block, reused across blocks, re-`init`ed only on a `sg.version` change\n// (mirroring `processor.ts`'s `knownVersions`/`definitionCache` contract),\n// and evicted via `invalidateSubgraphRoute` (redeploy/delete) — the same\n// invalidation edge the route cache uses.\n//\n// SUBSTRATE: this module used to spawn a Bun `Worker` (a thread inside this\n// process). Stage 2a's own isolation test (`isolation.test.ts`, kept as a\n// regression lock) proved that substrate does NOT isolate untrusted code —\n// `Bun.spawnSync` and bare `process.env` from inside a Worker reach the\n// HOST's real environ regardless of the Worker's `env: {}`, because a Worker\n// is a thread, not a process. `spawnSandboxProcess` below spawns a REAL OS\n// process instead: a child spawned with an explicit, from-scratch env\n// allowlist has that scrub at the OS level — its own `process.env`,\n// `Bun.env`, AND anything IT spawns inherit the scrub, not the host's.\n// `subprocess-isolation.test.ts` proves this empirically. `spawnSandboxWorker`\n// (still exported below) is retained ONLY so `isolation.test.ts` keeps\n// exercising the actual disproven Worker substrate — the pool below no\n// longer calls it.\n//\n// TRUST SPLIT (spike doc §3.1, unchanged by the substrate swap): this module\n// runs in the HOST process — it holds the open Postgres transaction (via the\n// `SubgraphContext` the caller passes in) and lives in the same process as\n// route resolution and the master key. The sandboxed subprocess it spawns\n// gets a from-scratch env allowlist (PATH only — never `process.env`\n// spread) and a resolver-locked-down bundle (`bundle.ts`) — it never sees a\n// DB handle, a connection string, or a host env var.\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { BlockMeta, SubgraphContext } from \"../context.ts\";\nimport type { RunResult } from \"../runner.ts\";\nimport type { MatchedTx } from \"../source-matcher.ts\";\nimport { bundleHandlerCode } from \"./bundle.ts\";\nimport type {\n\tBufferedOp,\n\tHostToWorkerMessage,\n\tWorkerToHostMessage,\n} from \"./protocol.ts\";\n\n/** Per-block deadline for the subprocess's `blockDone` (spike doc §3.3 \"crash\n * recovery\"): on expiry the subprocess is killed + evicted and the error\n * propagates into the block transaction, which rolls back and becomes a\n * transient failure in `processBlockWithRetry`'s existing schedule — retry\n * behavior itself is deliberately unchanged. */\nconst BLOCK_TIMEOUT_MS = Number.parseInt(\n\tprocess.env.SUBGRAPH_SANDBOX_BLOCK_TIMEOUT_MS ?? \"60000\",\n);\n\nconst SUBPROCESS_ENTRY_PATH = fileURLToPath(\n\tnew URL(\"./subprocess-entry.ts\", import.meta.url),\n);\n\n/**\n * Thin wrapper over `Bun.spawn`'s IPC surface so the rest of this module\n * (`ensureSandboxProcess`/`runBlockThroughProcess`) can treat the transport\n * the same shape `Worker` offered (`postMessage`-like `send`, a settable\n * message sink, `terminate`-like `kill`) without leaking Bun's\n * callback-at-spawn-time IPC API (`ipc` is fixed when `Bun.spawn` is called;\n * there is no `addEventListener` to attach/detach per run) into call sites.\n */\ninterface SandboxProcess {\n\tsend(msg: HostToWorkerMessage): void;\n\tkill(): void;\n\t/** Resolves once, whenever the child actually exits (crash, kill, or a\n\t * clean `process.exit`). Never rejects. */\n\treadonly exited: Promise<number>;\n\tsetOnMessage(handler: ((msg: WorkerToHostMessage) => void) | null): void;\n}\n\n/**\n * Exported so the containment test (`subprocess-isolation.test.ts`) drives\n * the EXACT production spawn (same entry path, same from-scratch env\n * allowlist), not a lookalike — mirrors why `spawnSandboxWorker` used to be\n * exported for `isolation.test.ts`.\n */\nexport function spawnSandboxProcess(): SandboxProcess {\n\tlet onMessage: ((msg: WorkerToHostMessage) => void) | null = null;\n\tconst proc = Bun.spawn({\n\t\t// `--no-env-file` is NOT optional. LOAD-BEARING FINDING from building\n\t\t// this: Bun auto-loads `.env`/`.env.local` for ANY `bun <file>`\n\t\t// invocation based on the CHILD's own cwd — independent of, and\n\t\t// applied AFTER, whatever `env` object is passed to `Bun.spawn`. The\n\t\t// first version of this function passed only `env: { PATH }` (no\n\t\t// flag) and the subprocess-isolation containment test caught it\n\t\t// immediately: the REAL repo `.env.local`'s `SECONDLAYER_SECRETS_KEY`\n\t\t// showed up in the child's `process.env` anyway, because the child's\n\t\t// cwd defaulted to the host's cwd (inside this repo, where\n\t\t// `.env.local` lives) and Bun loaded it on the child's own startup,\n\t\t// completely bypassing the explicit allowlist. `--no-env-file` plus a\n\t\t// `cwd` outside the repo (below) are both required, as defense in\n\t\t// depth against either mechanism alone changing behavior in a future\n\t\t// Bun version.\n\t\tcmd: [process.execPath, \"--no-env-file\", SUBPROCESS_ENTRY_PATH],\n\t\t// Explicit, from-scratch allowlist — NEVER spread process.env. PATH is\n\t\t// the only entry: the security boundary here is that this is the CHILD\n\t\t// PROCESS's own OS-level environ (unlike a Bun Worker's `env: {}`, which\n\t\t// only scrubbed the in-process thread's view — spike doc §10 / the\n\t\t// Stage A addendum), so shipping PATH does not leak\n\t\t// SECONDLAYER_SECRETS_KEY or any other host secret; it only lets the\n\t\t// child's own shell lookups (e.g. a hostile handler's\n\t\t// `Bun.spawnSync([\"/bin/sh\", ...])`) resolve a shell binary at all —\n\t\t// what that shell then sees for `$SECONDLAYER_SECRETS_KEY` is this\n\t\t// process's own (absent) environ, not the host's.\n\t\tenv: { PATH: process.env.PATH ?? \"\" },\n\t\t// Run from the OS tmp dir, not this repo's checkout — belt-and-braces\n\t\t// alongside --no-env-file (see above) so the child never has a\n\t\t// `.env.local` in its own cwd to find in the first place, and never\n\t\t// has an implicit relative-path view into the trusted repo tree.\n\t\tcwd: tmpdir(),\n\t\t// No extra inherited fds: stdin unused, stdout unused (all real\n\t\t// messaging is over the IPC channel Bun opens separately), stderr\n\t\t// piped for diagnostics only (never parsed for control flow).\n\t\tstdio: [\"ignore\", \"ignore\", \"pipe\"],\n\t\tserialization: \"advanced\",\n\t\tipc(message) {\n\t\t\tonMessage?.(message as WorkerToHostMessage);\n\t\t},\n\t});\n\t// Diagnostics only — never load-bearing for isolation (the child's own\n\t// environ never held a host secret, so nothing sensitive can appear\n\t// here). Streamed chunk-by-chunk rather than buffered until the process\n\t// exits: these subprocesses are warm and reused across many blocks, so\n\t// waiting for stream-close (`new Response(stream).text()`) would delay a\n\t// hostile/buggy handler's stderr until eventual pool shutdown — too late\n\t// to be useful for live debugging.\n\tvoid (async () => {\n\t\tconst reader = proc.stderr.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tconst text = decoder.decode(value, { stream: true });\n\t\t\t\tif (text.trim()) {\n\t\t\t\t\tlogger.warn(\"Sandbox subprocess stderr\", { stderr: text.trim() });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Stream read failure is itself just a diagnostics-path no-op.\n\t\t}\n\t})();\n\treturn {\n\t\tsend: (msg) => proc.send(msg),\n\t\tkill: () => proc.kill(),\n\t\texited: proc.exited,\n\t\tsetOnMessage: (handler) => {\n\t\t\tonMessage = handler;\n\t\t},\n\t};\n}\n\n/**\n * Retained ONLY so `isolation.test.ts` keeps spawning a REAL Bun `Worker` —\n * that test is a deliberate CI regression lock proving the Worker substrate\n * does NOT isolate untrusted code (spike doc §10); it must keep exercising\n * the actual broken substrate, not a lookalike, or the lock stops meaning\n * anything. The production pool below no longer calls this —\n * `spawnSandboxProcess` is the substrate Stage A ships.\n */\nexport function spawnSandboxWorker(): Worker {\n\treturn new Worker(new URL(\"./worker-entry.ts\", import.meta.url), {\n\t\tenv: {},\n\t});\n}\n\ninterface PoolEntry {\n\tproc: SandboxProcess;\n\tversion: string;\n\t/** Serializes runs through this subprocess — a subprocess can only\n\t * process one block at a time (its read-request/blockDone correlation is\n\t * per-run). The wider system already serializes per-subgraph block\n\t * processing; this is local insurance, not new scheduling. */\n\tchain: Promise<unknown>;\n}\n\nconst pool = new Map<string, PoolEntry>();\n\nexport interface SandboxRunParams {\n\tsubgraphName: string;\n\t/** `subgraphs.version` — subprocess re-`init`s when it changes. */\n\tversion: string;\n\t/** `subgraphs.handler_code` — bundled host-side on (re)init. */\n\thandlerCode: string | null;\n\t/** The SAME live ctx the in-process path would run handlers against —\n\t * bound to the open block transaction. Reads are answered through it;\n\t * the subprocess's decided ops are replayed onto it; the caller's\n\t * existing `flush()` + outbox flow then runs unchanged. */\n\thostCtx: SubgraphContext;\n\tblock: BlockMeta;\n\tmatched: MatchedTx[];\n}\n\nclass SandboxWorkerCrash extends Error {\n\tconstructor(subgraphName: string, cause: string) {\n\t\tsuper(`sandbox subprocess for \"${subgraphName}\" failed: ${cause}`);\n\t\tthis.name = \"SandboxWorkerCrash\";\n\t}\n}\n\nasync function initSandboxProcess(\n\tproc: SandboxProcess,\n\tsubgraphName: string,\n\tversion: string,\n\thandlerCode: string,\n): Promise<void> {\n\tconst bundledCode = await bundleHandlerCode(handlerCode);\n\tlet settled = false;\n\tconst ready = new Promise<void>((resolve, reject) => {\n\t\tproc.setOnMessage((msg) => {\n\t\t\tif (msg.type === \"ready\" && msg.version === version) {\n\t\t\t\tsettled = true;\n\t\t\t\tproc.setOnMessage(null);\n\t\t\t\tresolve();\n\t\t\t} else if (msg.type === \"error\") {\n\t\t\t\tsettled = true;\n\t\t\t\tproc.setOnMessage(null);\n\t\t\t\treject(new SandboxWorkerCrash(subgraphName, msg.message));\n\t\t\t}\n\t\t});\n\t\tconst init: HostToWorkerMessage = { type: \"init\", bundledCode, version };\n\t\tproc.send(init);\n\t});\n\t// A subprocess that dies before responding (bad bundle, bun crash, OOM at\n\t// import time) must fail init loudly rather than hang forever — mirrors\n\t// the old Worker path's `onerror` handler, re-homed onto `exited` since a\n\t// subprocess has no generic \"error\" event. Guarded by `settled` so this\n\t// never fires (or throws) once `ready` has already resolved/rejected via\n\t// a real message — including long after, when the subprocess eventually\n\t// exits during normal pool shutdown.\n\tconst crashed = proc.exited.then((code) => {\n\t\tif (settled) return;\n\t\tthrow new SandboxWorkerCrash(\n\t\t\tsubgraphName,\n\t\t\t`subprocess exited (code ${code}) during init`,\n\t\t);\n\t});\n\tawait Promise.race([ready, crashed]);\n}\n\n/** Get (or lazily spawn) the warm subprocess for a subgraph, re-`init`ing on\n * a version change — the subprocess-pool mirror of `loadSubgraphDefinition`'s\n * hot-reload contract. */\nasync function ensureSandboxProcess(\n\tsubgraphName: string,\n\tversion: string,\n\thandlerCode: string | null,\n): Promise<PoolEntry> {\n\tif (handlerCode == null) {\n\t\t// A subgraph can only be opted into the sandbox if its handler source\n\t\t// is in the control plane (`handler_code`). Rows predating that column\n\t\t// (disk-only `handler_path`) must not be silently run in-process when\n\t\t// the operator asked for the sandbox — fail the block loudly instead.\n\t\tthrow new SandboxWorkerCrash(\n\t\t\tsubgraphName,\n\t\t\t\"subgraph has no handler_code; cannot bundle for the sandbox path\",\n\t\t);\n\t}\n\tconst existing = pool.get(subgraphName);\n\tif (existing && existing.version === version) return existing;\n\n\tif (existing) {\n\t\t// Version bump — re-init the existing warm subprocess in place\n\t\t// (cheaper than a respawn; spike doc §3.3 \"hot-reload\").\n\t\ttry {\n\t\t\tawait initSandboxProcess(\n\t\t\t\texisting.proc,\n\t\t\t\tsubgraphName,\n\t\t\t\tversion,\n\t\t\t\thandlerCode,\n\t\t\t);\n\t\t\texisting.version = version;\n\t\t\tlogger.info(\"Sandbox subprocess handler reloaded\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tversion,\n\t\t\t});\n\t\t\treturn existing;\n\t\t} catch (err) {\n\t\t\t// Unhealthy subprocess — replace it below.\n\t\t\texisting.proc.kill();\n\t\t\tpool.delete(subgraphName);\n\t\t\tlogger.warn(\"Sandbox subprocess re-init failed; respawning\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t}\n\t}\n\n\tconst proc = spawnSandboxProcess();\n\ttry {\n\t\tawait initSandboxProcess(proc, subgraphName, version, handlerCode);\n\t} catch (err) {\n\t\tproc.kill();\n\t\tthrow err;\n\t}\n\tconst entry: PoolEntry = { proc, version, chain: Promise.resolve() };\n\tpool.set(subgraphName, entry);\n\treturn entry;\n}\n\n/** Terminate + drop a subgraph's warm subprocess. Wired into\n * `invalidateSubgraphRoute` (`block-processor.ts`), so redeploys and\n * deletions evict the subprocess on the same edge that drops the route\n * cache. Name kept from the Worker-era API — the eviction semantics are\n * identical, only the transport underneath changed. */\nexport function evictSandboxWorker(subgraphName: string): void {\n\tconst entry = pool.get(subgraphName);\n\tif (!entry) return;\n\tentry.proc.kill();\n\tpool.delete(subgraphName);\n}\n\n/** Terminate the whole pool (graceful shutdown / test teardown). */\nexport function shutdownSandboxPool(): void {\n\tfor (const name of [...pool.keys()]) evictSandboxWorker(name);\n}\n\n/**\n * Run one block's matched events through the subgraph's sandbox subprocess,\n * in place of the in-process `runHandlers(subgraph, matched, ctx)` call —\n * same inputs, same `{processed, errors}` result shape, same ctx left\n * holding the pending ops for the caller's unchanged `flush()` + outbox\n * flow.\n *\n * Membrane, per spike doc §3.2 (substrate updated by the Stage A addendum):\n * - the subprocess runs the REAL dispatch loop (`runHandlers`, imported by\n * `subprocess-entry.ts`) over a `WorkerCtx`; writes buffer subprocess-side;\n * - `readRequest`s are answered here through `hostCtx`'s real\n * `findOne`/`findMany`/aggregates. PRECISION NOTE (unchanged from Stage\n * 2a): this is equivalent to a raw base-DB read because `hostCtx`'s ops\n * array is empty for the entire duration of the subprocess run — ops are\n * only replayed onto it AFTER `blockDone` — and\n * `overlayOne`/`overlayMany` short-circuit to the DB row unchanged when\n * there are no pending ops. Reusing the real ctx read path (rather than\n * hand-rolling raw SQL here) keeps SQL construction and `coerceRow`'s\n * uint/int→BigInt coercion single-sourced with the in-process path; the\n * subprocess overlays its own pending ops on the returned row,\n * reconstructing exactly the in-process composition (raw read → coerce →\n * overlay).\n * - on `blockDone` the subprocess's `(method, args, tx)` ops are replayed\n * onto `hostCtx` by calling the real ctx methods (with `setTx` restoring\n * each op's original tx attribution) — the single source of truth for op\n * construction. The transaction never crosses the boundary.\n */\nexport async function runHandlersSandboxed(\n\tparams: SandboxRunParams,\n): Promise<RunResult> {\n\tconst { subgraphName, version, handlerCode, hostCtx, block, matched } =\n\t\tparams;\n\tconst entry = await ensureSandboxProcess(subgraphName, version, handlerCode);\n\n\t// Serialize per-subprocess: chain this run behind any in-flight one.\n\tconst run = entry.chain.then(() =>\n\t\trunBlockThroughProcess(entry, subgraphName, hostCtx, block, matched),\n\t);\n\t// The chain must survive a rejected run (the next block retries fresh).\n\tentry.chain = run.catch(() => undefined);\n\treturn run;\n}\n\nasync function runBlockThroughProcess(\n\tentry: PoolEntry,\n\tsubgraphName: string,\n\thostCtx: SubgraphContext,\n\tblock: BlockMeta,\n\tmatched: MatchedTx[],\n): Promise<RunResult> {\n\tconst { proc } = entry;\n\n\tlet timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n\tlet settled = false;\n\n\ttry {\n\t\tconst done = new Promise<{ ops: BufferedOp[]; result: RunResult }>(\n\t\t\t(resolve, reject) => {\n\t\t\t\tproc.setOnMessage((msg) => {\n\t\t\t\t\tif (msg.type === \"readRequest\") {\n\t\t\t\t\t\tanswerRead(hostCtx, msg)\n\t\t\t\t\t\t\t.then((reply) => {\n\t\t\t\t\t\t\t\tproc.send({ type: \"readResponse\", id: msg.id, reply });\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch((err) => {\n\t\t\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew SandboxWorkerCrash(\n\t\t\t\t\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t\t\t\t\t`host read failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (msg.type === \"blockDone\") {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tops: msg.ops,\n\t\t\t\t\t\t\tresult: { processed: msg.processed, errors: msg.errors },\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (msg.type === \"error\") {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\treject(new SandboxWorkerCrash(subgraphName, msg.message));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tproc.send({ type: \"runBlock\", block, matched });\n\t\t\t},\n\t\t);\n\n\t\t// A subprocess that dies mid-block (OOM, signal, uncaught exit) must\n\t\t// fail the block loudly, same as a timeout — guarded by `settled` so\n\t\t// this never fires after `done` already won the race, including long\n\t\t// after (when the subprocess eventually exits at pool shutdown).\n\t\tconst crashed = proc.exited.then((code) => {\n\t\t\tif (settled) return undefined as never;\n\t\t\tthrow new SandboxWorkerCrash(\n\t\t\t\tsubgraphName,\n\t\t\t\t`subprocess exited unexpectedly (code ${code}) mid-block`,\n\t\t\t);\n\t\t});\n\n\t\tconst deadline = new Promise<never>((_, reject) => {\n\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\tsettled = true;\n\t\t\t\treject(\n\t\t\t\t\tnew SandboxWorkerCrash(\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t`block ${block.height} exceeded ${BLOCK_TIMEOUT_MS}ms deadline`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}, BLOCK_TIMEOUT_MS);\n\t\t});\n\n\t\tconst { ops, result } = await Promise.race([done, crashed, deadline]);\n\n\t\t// End-of-block: replay the subprocess's decided ops through the REAL\n\t\t// ctx — real insert/upsert/increment/update/delete building the real\n\t\t// WriteOps (and eventually the real SQL at the caller's flush). setTx\n\t\t// restores each op's original tx attribution (context.ts captures\n\t\t// _tx_id at queue time, so replay must too).\n\t\tfor (const op of ops) {\n\t\t\thostCtx.setTx(op.tx);\n\t\t\treplayOp(hostCtx, op);\n\t\t}\n\t\treturn result;\n\t} catch (err) {\n\t\t// Timeout, subprocess crash, or host-read failure: the subprocess's\n\t\t// state is suspect (it may still be running the old block) —\n\t\t// terminate + evict so the retry gets a fresh spawn. The thrown error\n\t\t// rolls back the caller's block transaction; processBlockWithRetry\n\t\t// retries as usual. A hung/crashed sandbox NEVER silently skips a\n\t\t// block's events — it fails the block (f040 B5 halt/retry semantics).\n\t\tevictSandboxWorker(subgraphName);\n\t\tlogger.warn(\"Sandbox subprocess run failed; subprocess evicted\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblockHeight: block.height,\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\tthrow err;\n\t} finally {\n\t\tif (timeoutHandle !== undefined) clearTimeout(timeoutHandle);\n\t\tproc.setOnMessage(null);\n\t}\n}\n\nfunction replayOp(hostCtx: SubgraphContext, op: BufferedOp): void {\n\tswitch (op.method) {\n\t\tcase \"insert\":\n\t\t\thostCtx.insert(op.table, op.args[0] as Record<string, unknown>);\n\t\t\treturn;\n\t\tcase \"upsert\":\n\t\t\thostCtx.upsert(\n\t\t\t\top.table,\n\t\t\t\top.args[0] as Record<string, unknown>,\n\t\t\t\top.args[1] as Record<string, unknown>,\n\t\t\t);\n\t\t\treturn;\n\t\tcase \"increment\":\n\t\t\thostCtx.increment(\n\t\t\t\top.table,\n\t\t\t\top.args[0] as Record<string, unknown>,\n\t\t\t\top.args[1] as Record<string, bigint | number>,\n\t\t\t);\n\t\t\treturn;\n\t\tcase \"update\":\n\t\t\thostCtx.update(\n\t\t\t\top.table,\n\t\t\t\top.args[0] as Record<string, unknown>,\n\t\t\t\top.args[1] as Record<string, unknown>,\n\t\t\t);\n\t\t\treturn;\n\t\tcase \"delete\":\n\t\t\thostCtx.delete(op.table, op.args[0] as Record<string, unknown>);\n\t\t\treturn;\n\t}\n}\n\nasync function answerRead(\n\thostCtx: SubgraphContext,\n\tmsg: Extract<WorkerToHostMessage, { type: \"readRequest\" }>,\n): Promise<Extract<HostToWorkerMessage, { type: \"readResponse\" }>[\"reply\"]> {\n\tconst { method, table, where, column } = msg;\n\tswitch (method) {\n\t\tcase \"findOne\":\n\t\t\treturn { kind: \"row\", row: await hostCtx.findOne(table, where) };\n\t\tcase \"findMany\":\n\t\t\treturn { kind: \"rows\", rows: await hostCtx.findMany(table, where) };\n\t\tcase \"count\":\n\t\t\treturn { kind: \"count\", count: await hostCtx.count(table, where) };\n\t\tcase \"countDistinct\": {\n\t\t\tif (!column) throw new Error(\"countDistinct read missing column\");\n\t\t\treturn {\n\t\t\t\tkind: \"count\",\n\t\t\t\tcount: await hostCtx.countDistinct(table, column, where),\n\t\t\t};\n\t\t}\n\t\tcase \"sum\": {\n\t\t\tif (!column) throw new Error(\"sum read missing column\");\n\t\t\tconst v = await hostCtx.sum(table, column, where);\n\t\t\treturn { kind: \"amount\", amount: v.toString() };\n\t\t}\n\t\tcase \"min\": {\n\t\t\tif (!column) throw new Error(\"min read missing column\");\n\t\t\tconst v = await hostCtx.min(table, column, where);\n\t\t\treturn { kind: \"amount\", amount: v == null ? null : v.toString() };\n\t\t}\n\t\tcase \"max\": {\n\t\t\tif (!column) throw new Error(\"max read missing column\");\n\t\t\tconst v = await hostCtx.max(table, column, where);\n\t\t\treturn { kind: \"amount\", amount: v == null ? null : v.toString() };\n\t\t}\n\t}\n}\n",
@@ -28,17 +28,17 @@
28
28
  "import type { Database } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport type { ProcessBlockTiming } from \"./block-processor.ts\";\n\ninterface StatsEntry {\n\tsubgraphName: string;\n\tbucketStart: Date;\n\tblocksProcessed: number;\n\ttotalTimeMs: number;\n\thandlerTimeMs: number;\n\tflushTimeMs: number;\n\tmaxBlockTimeMs: number;\n\tmaxHandlerTimeMs: number;\n\ttotalOps: number;\n\tisCatchup: boolean;\n}\n\nconst FLUSH_INTERVAL_BLOCKS = 100;\nconst FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Accumulates per-block timing stats and flushes to DB periodically.\n * One instance per subgraph during catchup/reindex/live processing.\n */\nexport class StatsAccumulator {\n\tprivate current: StatsEntry;\n\tprivate lastFlush = Date.now();\n\n\tconstructor(\n\t\tprivate subgraphName: string,\n\t\tprivate isCatchup: boolean,\n\t) {\n\t\tthis.current = this.newEntry();\n\t}\n\n\trecord(timing: ProcessBlockTiming, opsCount: number): void {\n\t\tthis.current.blocksProcessed++;\n\t\tthis.current.totalTimeMs += timing.totalMs;\n\t\tthis.current.handlerTimeMs += timing.handlerMs;\n\t\tthis.current.flushTimeMs += timing.flushMs;\n\t\tthis.current.maxBlockTimeMs = Math.max(\n\t\t\tthis.current.maxBlockTimeMs,\n\t\t\ttiming.totalMs,\n\t\t);\n\t\tthis.current.maxHandlerTimeMs = Math.max(\n\t\t\tthis.current.maxHandlerTimeMs,\n\t\t\ttiming.handlerMs,\n\t\t);\n\t\tthis.current.totalOps += opsCount;\n\t}\n\n\tshouldFlush(): boolean {\n\t\treturn (\n\t\t\tthis.current.blocksProcessed >= FLUSH_INTERVAL_BLOCKS ||\n\t\t\tDate.now() - this.lastFlush >= FLUSH_INTERVAL_MS\n\t\t);\n\t}\n\n\tasync flush(db: Kysely<Database>): Promise<void> {\n\t\tif (this.current.blocksProcessed === 0) return;\n\n\t\tconst entry = this.current;\n\t\tthis.current = this.newEntry();\n\t\tthis.lastFlush = Date.now();\n\n\t\tconst avgOpsPerBlock =\n\t\t\tentry.blocksProcessed > 0 ? entry.totalOps / entry.blocksProcessed : 0;\n\n\t\tawait db\n\t\t\t.insertInto(\"subgraph_processing_stats\")\n\t\t\t.values({\n\t\t\t\tsubgraph_name: entry.subgraphName,\n\t\t\t\tbucket_start: entry.bucketStart,\n\t\t\t\tbucket_end: new Date(),\n\t\t\t\tblocks_processed: entry.blocksProcessed,\n\t\t\t\ttotal_time_ms: Math.round(entry.totalTimeMs),\n\t\t\t\thandler_time_ms: Math.round(entry.handlerTimeMs),\n\t\t\t\tflush_time_ms: Math.round(entry.flushTimeMs),\n\t\t\t\tmax_block_time_ms: Math.round(entry.maxBlockTimeMs),\n\t\t\t\tmax_handler_time_ms: Math.round(entry.maxHandlerTimeMs),\n\t\t\t\tavg_ops_per_block: Number.parseFloat(avgOpsPerBlock.toFixed(2)),\n\t\t\t\tis_catchup: entry.isCatchup,\n\t\t\t})\n\t\t\t.execute();\n\t}\n\n\tprivate newEntry(): StatsEntry {\n\t\treturn {\n\t\t\tsubgraphName: this.subgraphName,\n\t\t\tbucketStart: new Date(),\n\t\t\tblocksProcessed: 0,\n\t\t\ttotalTimeMs: 0,\n\t\t\thandlerTimeMs: 0,\n\t\t\tflushTimeMs: 0,\n\t\t\tmaxBlockTimeMs: 0,\n\t\t\tmaxHandlerTimeMs: 0,\n\t\t\ttotalOps: 0,\n\t\t\tisCatchup: this.isCatchup,\n\t\t};\n\t}\n}\n",
29
29
  "import { getTargetDb, sql } from \"@secondlayer/shared/db\";\nimport { getSubgraph } from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { type BlockData, avgEventsPerBlock } from \"./batch-loader.ts\";\nimport {\n\ttype ProcessBlockResult,\n\tprocessBlockWithRetry,\n} from \"./block-processor.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport { isCatchUpLeader } from \"./catchup-leader.ts\";\nimport {\n\tboundSourceTip,\n\tdecoderNamesForSubgraph,\n\tusesDecodedIndexPlane,\n} from \"./decoder-bound.ts\";\nimport { StatsAccumulator } from \"./stats.ts\";\n\nconst LOG_INTERVAL = 1000;\nconst STANDARD_CATCHUP_BATCH_CONFIG = {\n\tdefaultBatchSize: 500,\n\tminBatchSize: 100,\n\tmaxBatchSize: 1000,\n\tprefetch: true,\n};\n\nconst catchingUp = new Set<string>();\n\n/**\n * f057 guard: `recordLiveProgress` (subgraphs.ts) writes `last_processed_block`\n * unconditionally — no monotonic guard — because the reorg rewind MUST be able\n * to move the cursor backward. That means a catch-up walk's forward writes and\n * a reorg's backward rewind must never interleave for the same subgraph, or\n * whichever commits last wins regardless of correctness. `catchingUp` (above)\n * only excludes concurrent catch-ups; it does nothing against a reorg.\n *\n * Catch-up and the reorg handler can only ever race within the SAME process:\n * catch-up only ever runs on the catch-up leader (processor.ts `runCatchUp`),\n * and the reorg NOTIFY listener runs on every process including that leader —\n * so for THAT pair an in-process guard is sufficient.\n *\n * The reindex/backfill walk is the exception, and it is why the advisory lock\n * below exists. `startSubgraphOperationRunner` (processor.ts) is NOT\n * leader-gated — it runs on every processor instance — so a reindex or\n * backfill for subgraph S can be walking on instance B while the catch-up\n * leader walks the same S on instance A. They share no JS state, so the\n * in-process mutex serializes nothing between them. Backfill makes this\n * routine rather than exotic: it runs at status 'active', the exact status\n * `runCatchUp` selects on, and it never changes that status, so catch-up has\n * no reason to stand down.\n *\n * Acquisition order — every lock around a subgraph write, outermost first.\n * A fourth lock MUST slot into this order or it can deadlock:\n *\n * 1. `withSubgraphBlockLock` — in-process mutex, per subgraph name\n * 2. `subgraph-reorg:<name>` — advisory xact lock (reorg.ts, reorg only)\n * 3. `subgraph-block:<name>` — advisory xact lock (below, walks only)\n *\n * No path holds (2) and (3) at once: the reorg handler reprocesses the fork\n * block through `processBlock` directly, never through a walk, so it never\n * reaches (3); and neither walk ever takes (2). The order is therefore only\n * ever exercised as 1→2 (reorg) or 1→3 (walks), and no cycle exists.\n *\n * Two pieces, used together by catchUpSubgraph (below) and handleSubgraphReorg\n * (reorg.ts):\n *\n * - `withSubgraphBlockLock` is a per-subgraph mutex held for the duration of\n * ONE block's write — catch-up acquires it around each individual block it\n * commits (not around the whole walk), and the reorg handler acquires it\n * around its entire delete+reprocess+rewind sequence for a subgraph. So a\n * reorg only ever waits out a single in-flight block commit, never an\n * entire remaining catch-up walk — and since the lock is per-subgraph name,\n * a slow catch-up on one subgraph never stalls reorg handling for another\n * (handleSubgraphReorg processes subgraphs sequentially).\n * - `reorgEpoch` is a monotonic per-subgraph counter, bumped by\n * handleSubgraphReorg BEFORE it acquires the lock (so the bump is visible\n * immediately, independent of how long the lock wait takes, and is never\n * \"cleared\" — there's no race in un-setting a flag too early). catchUpSubgraph\n * snapshots the epoch once at the start of its walk and, after acquiring the\n * lock for each block, checks it again: a changed epoch means a reorg\n * touched this subgraph's cursor at some point during the walk, so the\n * walk's local progress state can no longer be trusted — it aborts the\n * whole tick without writing anything further. The next catch-up tick\n * re-reads `last_processed_block` fresh from the DB (line ~108) and resumes\n * correctly from the post-reorg cursor.\n */\nconst subgraphBlockLockHeld = new Set<string>();\nconst subgraphBlockLockWaiters = new Map<string, Array<() => void>>();\nconst reorgEpoch = new Map<string, number>();\n\nasync function acquireSubgraphBlockLock(name: string): Promise<() => void> {\n\tif (!subgraphBlockLockHeld.has(name)) {\n\t\tsubgraphBlockLockHeld.add(name);\n\t\treturn () => releaseSubgraphBlockLock(name);\n\t}\n\treturn new Promise<() => void>((resolve) => {\n\t\tconst waiters = subgraphBlockLockWaiters.get(name) ?? [];\n\t\twaiters.push(() => resolve(() => releaseSubgraphBlockLock(name)));\n\t\tsubgraphBlockLockWaiters.set(name, waiters);\n\t});\n}\n\nfunction releaseSubgraphBlockLock(name: string): void {\n\tconst waiters = subgraphBlockLockWaiters.get(name);\n\tif (waiters && waiters.length > 0) {\n\t\tconst next = waiters.shift() as () => void;\n\t\tif (waiters.length === 0) subgraphBlockLockWaiters.delete(name);\n\t\tnext(); // hand the lock straight to the next waiter (FIFO), stays held\n\t\treturn;\n\t}\n\tsubgraphBlockLockHeld.delete(name);\n}\n\n/** Run `fn` (a single block's write, or a reorg's whole rewind) holding the\n * per-subgraph block lock. Exported for reorg.ts. */\nexport async function withSubgraphBlockLock<T>(\n\tname: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst release = await acquireSubgraphBlockLock(name);\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Cross-process half of the block lock: a transaction-scoped Postgres advisory\n * lock keyed `subgraph-block:<name>`, held for the duration of `fn`.\n *\n * Held, not merely acquired: each block's own write transaction is opened\n * INSIDE `processBlock` (block-processor.ts — `targetDb.transaction()`), and\n * that boundary\n * is load-bearing for the f069 replay guard, so the lock cannot be taken on\n * the writing connection. Instead this wraps the write in a separate\n * lock-holding transaction on the target DB, exactly as the reorg lock does\n * (reorg.ts): `pg_advisory_xact_lock` releases only when THIS transaction\n * commits, regardless of which other connections `fn` awaits meanwhile.\n * Transaction-scoped rather than session-scoped so a crashed walk can never\n * strand the lock.\n *\n * The lock lives on the target DB — same as the reorg lock — because it\n * coordinates control-plane walkers, not data-plane rows.\n *\n * Connection budget: this holds one pooled target-DB connection while `fn`\n * takes another for the write, so an in-flight block costs 2 of\n * `DATABASE_POOL_MAX` (default 20). Concurrent block writes are bounded by\n * catch-up fan-out (5 subgraphs) plus operation concurrency (1) = 6 blocks =\n * 12 connections. Raising either concurrency knob must be checked against the\n * pool, or the wrapping transactions can starve the writes they wrap.\n */\nexport async function withSubgraphBlockAdvisoryLock<T>(\n\tname: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\treturn getTargetDb()\n\t\t.transaction()\n\t\t.execute(async (lockTx) => {\n\t\t\tawait sql`SELECT pg_advisory_xact_lock(hashtext(${`subgraph-block:${name}`}))`.execute(\n\t\t\t\tlockTx,\n\t\t\t);\n\t\t\treturn fn();\n\t\t});\n}\n\n/**\n * One block's write, holding BOTH halves of the block lock in the documented\n * order: the in-process mutex, then the cross-process advisory lock. Every\n * walk that writes a subgraph's schema — live catch-up, reindex, backfill —\n * must go through this, or it serializes against nothing.\n */\nexport async function withSubgraphBlockWriteLock<T>(\n\tname: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\treturn withSubgraphBlockLock(name, () =>\n\t\twithSubgraphBlockAdvisoryLock(name, fn),\n\t);\n}\n\n/** Bump a subgraph's reorg epoch. Call BEFORE acquiring the block lock so the\n * bump is visible to any concurrent catch-up immediately. Exported for\n * reorg.ts. */\nexport function bumpReorgEpoch(name: string): void {\n\treorgEpoch.set(name, (reorgEpoch.get(name) ?? 0) + 1);\n}\n\nfunction getReorgEpoch(name: string): number {\n\treturn reorgEpoch.get(name) ?? 0;\n}\n\n/** Thrown inside the lock to unwind a catch-up walk when a reorg's epoch bump\n * is observed mid-walk — distinct from a real processing failure so the\n * caller aborts silently instead of marking the subgraph \"error\". */\nclass ReorgEpochChangedError extends Error {\n\tconstructor(name: string) {\n\t\tsuper(`reorg epoch changed for ${name} mid catch-up`);\n\t\tthis.name = \"ReorgEpochChangedError\";\n\t}\n}\n\ntype CatchupBatchConfig = {\n\tdefaultBatchSize: number;\n\tminBatchSize: number;\n\tmaxBatchSize: number;\n\tprefetch: boolean;\n};\n\ntype CatchupBatchEnv = {\n\tSUBGRAPH_CATCHUP_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_MIN_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_MAX_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_PREFETCH?: string;\n};\n\nfunction parsePositiveInt(value: string | undefined): number | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst parsed = Number.parseInt(value, 10);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction parseBoolean(value: string | undefined): boolean | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst normalized = value.trim().toLowerCase();\n\tif (normalized === \"true\") return true;\n\tif (normalized === \"false\") return false;\n\treturn undefined;\n}\n\nexport function resolveCatchupBatchConfig(\n\tenv: CatchupBatchEnv = process.env as CatchupBatchEnv,\n): CatchupBatchConfig {\n\tconst base = STANDARD_CATCHUP_BATCH_CONFIG;\n\tconst minBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_MIN_BATCH_SIZE) ?? base.minBatchSize;\n\tconst maxBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_MAX_BATCH_SIZE) ?? base.maxBatchSize;\n\tconst defaultBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_BATCH_SIZE) ?? base.defaultBatchSize;\n\n\treturn {\n\t\tminBatchSize,\n\t\tmaxBatchSize,\n\t\tdefaultBatchSize: Math.min(\n\t\t\tMath.max(defaultBatchSize, minBatchSize),\n\t\t\tmaxBatchSize,\n\t\t),\n\t\tprefetch: parseBoolean(env.SUBGRAPH_CATCHUP_PREFETCH) ?? base.prefetch,\n\t};\n}\n\n/**\n * Adjust batch size based on event density.\n * Sparse blocks (early chain) → larger batches. Dense blocks → smaller batches.\n */\nfunction adjustBatchSize(\n\tcurrent: number,\n\tavgEvents: number,\n\tconfig: CatchupBatchConfig,\n): number {\n\tif (avgEvents > 50)\n\t\treturn Math.max(Math.round(current * 0.5), config.minBatchSize);\n\tif (avgEvents < 10)\n\t\treturn Math.min(Math.round(current * 1.5), config.maxBatchSize);\n\treturn current;\n}\n\n/**\n * Catch a subgraph up from its last_processed_block to the chain tip.\n * Uses batch loading (3 queries per batch instead of 3 per block) and\n * plan-aware pipeline prefetching.\n */\nexport async function catchUpSubgraph(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n): Promise<number> {\n\tif (catchingUp.has(subgraphName)) return 0;\n\tcatchingUp.add(subgraphName);\n\n\ttry {\n\t\tconst source = resolveBlockSource(subgraph);\n\t\tconst targetDb = getTargetDb();\n\n\t\t// Re-read from DB to avoid stale lastProcessedBlock\n\t\tconst subgraphRow = await getSubgraph(targetDb, subgraphName);\n\t\tif (!subgraphRow) return 0;\n\t\tconst lastProcessedBlock = Number(subgraphRow.last_processed_block);\n\n\t\t// Chain tip comes from the block source. On the decoded Index plane\n\t\t// (streams-index) bound it by the decoders this subgraph reads —\n\t\t// Index tip tracks ft_transfer, so a print subgraph that walked to it\n\t\t// would skip heights print has not committed. Postgres tap reads raw\n\t\t// events at ingest and must not wait on decode.\n\t\tconst rawTip = await source.getTip();\n\t\tif (rawTip <= 0) return 0;\n\t\tlet chainTip = rawTip;\n\t\tif (usesDecodedIndexPlane(subgraph)) {\n\t\t\tconst bound = await boundSourceTip(\n\t\t\t\trawTip,\n\t\t\t\tdecoderNamesForSubgraph(subgraph),\n\t\t\t);\n\t\t\tif (!bound.ok) {\n\t\t\t\tlogger.warn(\"Subgraph catch-up stalled: missing decoder checkpoint\", {\n\t\t\t\t\tevent: \"subgraph_catchup_decoder_stall\",\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tmissing: bound.missing,\n\t\t\t\t});\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (bound.floor !== null && bound.floor < rawTip) {\n\t\t\t\tlogger.debug(\"Subgraph catch-up tip bounded by decoder progress\", {\n\t\t\t\t\tevent: \"subgraph_catchup_decoder_floor\",\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\trawTip,\n\t\t\t\t\tfloor: bound.floor,\n\t\t\t\t\ttip: bound.tip,\n\t\t\t\t});\n\t\t\t}\n\t\t\tchainTip = bound.tip;\n\t\t}\n\t\tif (chainTip <= 0 || lastProcessedBlock >= chainTip) return 0;\n\n\t\tconst subgraphStart = Number(subgraphRow.start_block) || 1;\n\t\tconst startBlock = Math.max(lastProcessedBlock + 1, subgraphStart);\n\t\tconst totalBlocks = chainTip - lastProcessedBlock;\n\n\t\tlogger.info(\"Subgraph catch-up starting\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tfrom: startBlock,\n\t\t\tto: chainTip,\n\t\t\tblocks: totalBlocks,\n\t\t});\n\n\t\tconst stats = new StatsAccumulator(subgraphName, true);\n\t\tlet processed = 0;\n\t\tconst batchConfig = resolveCatchupBatchConfig();\n\t\tlet batchSize = batchConfig.defaultBatchSize;\n\t\tlet currentHeight = startBlock;\n\t\t// f057: snapshot the epoch once — see the guard comment above\n\t\t// `subgraphBlockLockHeld` for the invariant this protects.\n\t\tconst walkEpoch = getReorgEpoch(subgraphName);\n\n\t\t// Pipeline: start loading first batch and track the prefetched range.\n\t\t// batchEnd must match what was actually loaded — not recalculated from a\n\t\t// potentially resized batchSize (adaptive sizing can change it between iterations).\n\t\tlet prefetchedBatchEnd = Math.min(currentHeight + batchSize - 1, chainTip);\n\t\tlet nextBatchPromise = batchConfig.prefetch\n\t\t\t? source.loadBlockRange(currentHeight, prefetchedBatchEnd)\n\t\t\t: undefined;\n\n\t\twhile (currentHeight <= chainTip) {\n\t\t\t// f069: per-iteration leadership check. `isCatchUpLeader()` reads this\n\t\t\t// process's own in-memory lease state (catchup-leader.ts) — no DB\n\t\t\t// query, so it's cheap enough to check every batch. Pre-f069, only\n\t\t\t// `runCatchUp`'s entry gate (processor.ts) checked leadership, so a\n\t\t\t// process that lost its advisory-lock connection mid-walk (driver\n\t\t\t// auto-reconnect silently drops the session lock — leader.ts:84-99)\n\t\t\t// kept committing blocks indefinitely while a new leader walked the\n\t\t\t// same range: the two writers' overlapping commits, combined with\n\t\t\t// `recordLiveProgress` regressing the cursor on every laggard write,\n\t\t\t// is the mechanism the f068 investigation traced to the July burst.\n\t\t\t// The conditional cursor advance (block-processor.ts) now makes an\n\t\t\t// overlap safe even if this check somehow missed a beat, but ending\n\t\t\t// the laggard's walk promptly is still the right behavior — it stops\n\t\t\t// wasted work and the log noise of every write losing its race.\n\t\t\tif (!isCatchUpLeader()) {\n\t\t\t\tlogger.info(\"Lost catch-up leadership, stopping catch-up\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tprocessed,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Check if subgraph status changed (e.g. reindex started) — bail if so\n\t\t\tconst currentRow = await getSubgraph(targetDb, subgraphName);\n\t\t\tif (!currentRow || currentRow.status !== \"active\") {\n\t\t\t\tlogger.info(\"Subgraph status changed, stopping catch-up\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tstatus: currentRow?.status ?? \"deleted\",\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet batchEnd: number;\n\t\t\tlet batch: Map<number, BlockData>;\n\t\t\tif (nextBatchPromise) {\n\t\t\t\tbatch = await nextBatchPromise;\n\t\t\t\tbatchEnd = prefetchedBatchEnd;\n\n\t\t\t\t// Start prefetching next batch while we process this one.\n\t\t\t\tconst nextStart = batchEnd + 1;\n\t\t\t\tif (nextStart <= chainTip) {\n\t\t\t\t\tprefetchedBatchEnd = Math.min(nextStart + batchSize - 1, chainTip);\n\t\t\t\t\tnextBatchPromise = source.loadBlockRange(\n\t\t\t\t\t\tnextStart,\n\t\t\t\t\t\tprefetchedBatchEnd,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tnextBatchPromise = undefined;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Low-memory mode: load only the current batch, process it, then size\n\t\t\t\t// and load the next batch after this iteration completes.\n\t\t\t\tbatchEnd = Math.min(currentHeight + batchSize - 1, chainTip);\n\t\t\t\tbatch = await source.loadBlockRange(currentHeight, batchEnd);\n\t\t\t}\n\n\t\t\t// Process each block from pre-loaded data\n\t\t\tlet stopCatchup = false;\n\n\t\t\tfor (let height = currentHeight; height <= batchEnd; height++) {\n\t\t\t\tlet blockData = batch.get(height);\n\t\t\t\tif (!blockData) {\n\t\t\t\t\t// Refetch once — distinguishes a transient source hiccup from a\n\t\t\t\t\t// genuinely absent block.\n\t\t\t\t\tblockData = (await source.loadBlockRange(height, height)).get(height);\n\t\t\t\t}\n\t\t\t\tif (!blockData) {\n\t\t\t\t\t// Near the tip this is usually a reorg race (the height briefly\n\t\t\t\t\t// has no canonical block). Stop the tick with the cursor BEFORE\n\t\t\t\t\t// this height — the next catch-up re-attempts it. Skipping it\n\t\t\t\t\t// instead would silently drop its events (fix-f040 B5).\n\t\t\t\t\tlogger.warn(\"Block missing during catch-up, deferring to next tick\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tblockHeight: height,\n\t\t\t\t\t});\n\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst preloaded = blockData;\n\n\t\t\t\tlet result: ProcessBlockResult;\n\t\t\t\ttry {\n\t\t\t\t\t// Hold both halves of the per-subgraph block lock for this one\n\t\t\t\t\t// block's write — the in-process mutex (excludes a same-process\n\t\t\t\t\t// reorg) and the advisory lock (excludes a reindex/backfill walk\n\t\t\t\t\t// on another instance) — and bail without writing if a reorg's\n\t\t\t\t\t// epoch bump landed mid-walk. See the guard comment near\n\t\t\t\t\t// subgraphBlockLockHeld.\n\t\t\t\t\tresult = await withSubgraphBlockWriteLock(subgraphName, async () => {\n\t\t\t\t\t\tif (getReorgEpoch(subgraphName) !== walkEpoch) {\n\t\t\t\t\t\t\tthrow new ReorgEpochChangedError(subgraphName);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn processBlockWithRetry(subgraph, subgraphName, height, {\n\t\t\t\t\t\t\tpreloaded,\n\t\t\t\t\t\t\tsubgraphId: subgraphRow.id,\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof ReorgEpochChangedError) {\n\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\"Reorg detected mid catch-up, aborting walk without writing further progress\",\n\t\t\t\t\t\t\t{ subgraph: subgraphName, blockHeight: height },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// Persistent failure: halt with the cursor before this block.\n\t\t\t\t\t// Advancing past it would bake the missing events into every\n\t\t\t\t\t// downstream row (fix-f040 B5).\n\t\t\t\t\tconst errorMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tlogger.error(\"Block processing failed persistently during catch-up\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tblockHeight: height,\n\t\t\t\t\t\terror: errorMsg,\n\t\t\t\t\t});\n\t\t\t\t\tconst { updateSubgraphStatus, recordSubgraphProcessed } =\n\t\t\t\t\t\tawait import(\"@secondlayer/shared/db/queries/subgraphs\");\n\t\t\t\t\tawait recordSubgraphProcessed(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\t`catch-up halted at block ${height}: ${errorMsg}`,\n\t\t\t\t\t).catch(() => {});\n\t\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\").catch(\n\t\t\t\t\t\t() => {},\n\t\t\t\t\t);\n\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprocessed++;\n\n\t\t\t\tif (result.timing) {\n\t\t\t\t\tstats.record(result.timing, result.processed);\n\t\t\t\t\tif (stats.shouldFlush()) {\n\t\t\t\t\t\tawait stats.flush(targetDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (processed % LOG_INTERVAL === 0) {\n\t\t\t\t\tlogger.info(\"Subgraph catch-up progress\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tprocessed,\n\t\t\t\t\t\ttotal: totalBlocks,\n\t\t\t\t\t\tcurrentBlock: height,\n\t\t\t\t\t\tpct: Math.round((processed / totalBlocks) * 100),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// A missing block or persistent failure stops the walk with the\n\t\t\t// cursor before the problem height — never record-and-skip.\n\t\t\tif (stopCatchup) break;\n\n\t\t\t// Adaptive batch sizing based on event density\n\t\t\tconst avg = avgEventsPerBlock(batch);\n\t\t\tbatchSize = adjustBatchSize(batchSize, avg, batchConfig);\n\n\t\t\tcurrentHeight = batchEnd + 1;\n\t\t}\n\n\t\t// Flush remaining stats\n\t\tawait stats.flush(targetDb);\n\n\t\tlogger.info(\"Subgraph catch-up complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tprocessed,\n\t\t});\n\n\t\treturn processed;\n\t} finally {\n\t\tcatchingUp.delete(subgraphName);\n\t}\n}\n",
30
30
  "import {\n\ttype LeaderBackend,\n\tSUBGRAPH_CATCHUP_LOCK_KEY,\n\tcreatePostgresLeaderBackend,\n\twithLeaderLock,\n} from \"@secondlayer/shared/leader\";\nimport { targetListenerUrl } from \"@secondlayer/shared/queue/listener\";\n\n/**\n * Leader-gating for the subgraph catch-up driver.\n *\n * Catch-up runs on every NOTIFY/poll guarded only by an in-process Set, so 2+\n * processors would otherwise double-process every block. That is NOT safe by\n * default: handler writes go through `ctx.increment` (additive), which is\n * replay-sensitive, not idempotent — two processors committing the same\n * block's deltas corrupts an accumulator table exactly the way the f068\n * investigation found in production\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`).\n * Electing a single catch-up leader is still the right design (it avoids the\n * wasted CPU/DB of redundant walks), but the actual overlap-safety net is the\n * live path's conditional cursor advance (`block-processor.ts`,\n * `recordLiveProgress` in `packages/shared/src/db/queries/subgraphs.ts`;\n * f069) plus the per-iteration leadership check in `catchup.ts`'s walk loop —\n * a walker that loses its lease now stops promptly, and even if it didn't,\n * its writes could no longer win a same-height race against a newer leader's\n * commit. The in-process Set stays as the within-process guard; this lock is\n * the cross-process guard; the conditional advance is the correctness\n * guarantee that holds even if both of those are ever bypassed.\n *\n * The lock lives on the target DB — the `subgraphs` table and per-subgraph\n * cursors are control-plane state homed there by the source/target split.\n */\n\nlet catchUpLeader = false;\n\n/** True only on the process currently holding the catch-up leader lock. */\nexport function isCatchUpLeader(): boolean {\n\treturn catchUpLeader;\n}\n\nexport type StartCatchUpLeaderOptions = {\n\tpollMs?: number;\n\theartbeatMs?: number;\n\t/** Injectable for tests; defaults to the real Postgres backend on target. */\n\tcreateBackend?: () => LeaderBackend;\n\t/** Run once when leadership is acquired — e.g. an immediate catch-up so the\n\t * new leader doesn't wait a poll interval to start. */\n\tonAcquire?: () => void | Promise<void>;\n};\n\n/**\n * Acquire and hold the catch-up leader lock. Returns a stop function that ends\n * election and releases the lock. While held, `isCatchUpLeader()` is true so the\n * NOTIFY/poll/startup catch-up paths actually run work.\n */\nexport function startCatchUpLeader(\n\topts: StartCatchUpLeaderOptions = {},\n): () => Promise<void> {\n\treturn withLeaderLock(\n\t\tSUBGRAPH_CATCHUP_LOCK_KEY,\n\t\tasync () => {\n\t\t\tcatchUpLeader = true;\n\t\t\tawait opts.onAcquire?.();\n\t\t\treturn () => {\n\t\t\t\tcatchUpLeader = false;\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tpollMs: opts.pollMs,\n\t\t\theartbeatMs: opts.heartbeatMs,\n\t\t\tcreateBackend:\n\t\t\t\topts.createBackend ??\n\t\t\t\t(() => createPostgresLeaderBackend(targetListenerUrl())),\n\t\t},\n\t);\n}\n",
31
- "import { decodeStreamsCursor, isEmptyRangeCursor } from \"@secondlayer/shared\";\nimport { type Database, getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport {\n\tisStreamsIndexEligible,\n\treferencedIndexEventTypes,\n} from \"./block-source.ts\";\n\n/**\n * Decoder-progress bound for consumers that read decoded Index rows.\n *\n * Each decoded event type is produced by an independent decoder\n * (`decode.<event_type>.v1` — ADR-0008/0010). Index `getTip` tracks\n * `decode.ft_transfer.v1` (or ingestion, on the Postgres tap). A forward-only\n * cursor that processes a height before the decoder feeding a referenced type\n * has committed it misses the match and never revisits.\n *\n * Bound the tip by the MIN committed height over ONLY the decoders the\n * consumer actually reads. A stalled unreferenced decoder (idle pox4) must\n * never gate progress. A referenced decoder with no usable checkpoint stalls\n * the consumer rather than falling through to the raw tip.\n */\n\n/** ADR checkpoint name. Subgraphs does not depend on `@secondlayer/indexer`. */\nexport function decoderNameForEventType(indexEventType: string): string {\n\treturn `decode.${indexEventType}.v1`;\n}\n\nexport function decoderNamesForIndexEventTypes(eventTypes: string[]): string[] {\n\treturn eventTypes.map(decoderNameForEventType);\n}\n\nexport function decoderNamesForSubgraph(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\treturn decoderNamesForIndexEventTypes(referencedIndexEventTypes(subgraph));\n}\n\n/**\n * True when catch-up/reindex will load decoded Index rows (the race).\n * Postgres tap reads raw `events` at ingest and must not wait on decode.\n * Mirrors `resolveBlockSource`'s streams-index branch.\n */\nexport function usesDecodedIndexPlane(subgraph: SubgraphDefinition): boolean {\n\treturn (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tisStreamsIndexEligible(subgraph)\n\t);\n}\n\n/**\n * Highest height at which this cursor has fully committed. Mid-block\n * (`H:n`, n not the empty-range sentinel) means the rest of H is still\n * in flight — floor is H-1. Sentinel `H:2147483647` means H is done.\n */\nexport function committedHeight(\n\tcursor: string | null | undefined,\n): number | null {\n\tif (!cursor) return null;\n\ttry {\n\t\tconst decoded = decodeStreamsCursor(cursor);\n\t\tif (isEmptyRangeCursor(decoded)) return decoded.block_height;\n\t\treturn Math.max(0, decoded.block_height - 1);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport type DecoderBound =\n\t| { kind: \"unbounded\" }\n\t| { kind: \"stall\"; missing: string[] }\n\t| { kind: \"height\"; height: number };\n\n/**\n * Data-availability floor for `decoderNames`. Reads SOURCE-plane\n * `decoder_checkpoints` (same rationale as trait resolution: the consumer\n * handle is often the TARGET, where those rows are empty).\n */\nexport async function decoderBoundTip(\n\tdecoderNames: string[],\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<DecoderBound> {\n\tif (decoderNames.length === 0) return { kind: \"unbounded\" };\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst rows = await sourceDb\n\t\t.selectFrom(\"decoder_checkpoints\")\n\t\t.select([\"decoder_name\", \"last_cursor\"])\n\t\t.where(\"decoder_name\", \"in\", decoderNames)\n\t\t.execute();\n\tconst byName = new Map(rows.map((r) => [r.decoder_name, r.last_cursor]));\n\tconst missing: string[] = [];\n\tconst heights: number[] = [];\n\tfor (const name of decoderNames) {\n\t\tconst height = committedHeight(byName.get(name));\n\t\tif (height === null) missing.push(name);\n\t\telse heights.push(height);\n\t}\n\tif (missing.length > 0) return { kind: \"stall\", missing };\n\treturn { kind: \"height\", height: Math.min(...heights) };\n}\n\nexport type BoundSourceTip =\n\t| { ok: true; tip: number; floor: number | null }\n\t| { ok: false; missing: string[] };\n\n/** Combine a raw block-source tip with the decoder floor. */\nexport async function boundSourceTip(\n\trawTip: number,\n\tdecoderNames: string[],\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<BoundSourceTip> {\n\tconst bound = await decoderBoundTip(decoderNames, opts);\n\tif (bound.kind === \"stall\") return { ok: false, missing: bound.missing };\n\tif (bound.kind === \"unbounded\") {\n\t\treturn { ok: true, tip: rawTip, floor: null };\n\t}\n\treturn {\n\t\tok: true,\n\t\ttip: Math.min(rawTip, bound.height),\n\t\tfloor: bound.height,\n\t};\n}\n",
32
- "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { getRawClient, getTargetDb } from \"@secondlayer/shared/db\";\nimport {\n\ttype GapRange,\n\trecordGapBatch,\n\tresolveGaps,\n} from \"@secondlayer/shared/db/queries/subgraph-gaps\";\nimport {\n\tadvanceOperationCursor,\n\tupdateOperationProcessedEvents,\n} from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\trecordSubgraphProcessed,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { generateSubgraphSQL } from \"../schema/generator.ts\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { avgEventsPerBlock } from \"./batch-loader.ts\";\nimport {\n\ttype ProcessBlockResult,\n\tprocessBlockWithRetry,\n} from \"./block-processor.ts\";\nimport {\n\ttype BlockSource,\n\tcanSparseScan,\n\tresolveBlockSource,\n} from \"./block-source.ts\";\nimport { withSubgraphBlockWriteLock } from \"./catchup.ts\";\nimport {\n\tboundSourceTip,\n\tdecoderNamesForSubgraph,\n\tusesDecodedIndexPlane,\n} from \"./decoder-bound.ts\";\nimport { notifyReindexComplete } from \"./reindex-notify.ts\";\nimport { StatsAccumulator } from \"./stats.ts\";\n\nconst LOG_INTERVAL = 1000;\nconst HEALTH_FLUSH_INTERVAL = 1000;\nconst PROGRESS_FLUSH_INTERVAL_MS = 5_000;\n/** Consecutive fully-empty batches before the walk halts as source-degraded. */\nconst EMPTY_BATCH_HALT_THRESHOLD = 3;\nconst STANDARD_REINDEX_BATCH_CONFIG = {\n\tdefaultBatchSize: 500,\n\tminBatchSize: 100,\n\tmaxBatchSize: 1000,\n};\n\ntype ReindexBatchConfig = {\n\tdefaultBatchSize: number;\n\tminBatchSize: number;\n\tmaxBatchSize: number;\n};\ntype ReindexBatchEnv = {\n\tSUBGRAPH_REINDEX_BATCH_SIZE?: string;\n\tSUBGRAPH_REINDEX_MIN_BATCH_SIZE?: string;\n\tSUBGRAPH_REINDEX_MAX_BATCH_SIZE?: string;\n};\n\ntype ReindexResumeRow = {\n\tlast_processed_block: number | string;\n\treindex_from_block: number | string | null;\n\treindex_to_block: number | string | null;\n};\n\nexport function initialReindexProgressBlock(fromBlock: number): number {\n\treturn Math.max(0, fromBlock - 1);\n}\n\nexport function resolveReindexResumeBlock(\n\trow: ReindexResumeRow,\n): number | null {\n\tif (row.reindex_from_block == null || row.reindex_to_block == null) {\n\t\treturn null;\n\t}\n\n\tconst lastProcessedBlock = Number(row.last_processed_block);\n\tconst reindexFromBlock = Number(row.reindex_from_block);\n\n\treturn Math.max(lastProcessedBlock + 1, reindexFromBlock);\n}\n\nfunction parsePositiveInt(value: string | undefined): number | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst parsed = Number.parseInt(value, 10);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nexport function resolveReindexBatchConfig(\n\tenv: ReindexBatchEnv = process.env as ReindexBatchEnv,\n): ReindexBatchConfig {\n\tconst base = STANDARD_REINDEX_BATCH_CONFIG;\n\tconst minBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_MIN_BATCH_SIZE) ?? base.minBatchSize;\n\tconst maxBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_MAX_BATCH_SIZE) ?? base.maxBatchSize;\n\tconst defaultBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_BATCH_SIZE) ?? base.defaultBatchSize;\n\n\treturn {\n\t\tminBatchSize,\n\t\tmaxBatchSize,\n\t\tdefaultBatchSize: Math.min(\n\t\t\tMath.max(defaultBatchSize, minBatchSize),\n\t\t\tmaxBatchSize,\n\t\t),\n\t};\n}\n\n/**\n * Coalesce individual block heights + reasons into contiguous gap ranges.\n */\nfunction coalesceFailedBlocks(\n\tblocks: { height: number; reason: string }[],\n): GapRange[] {\n\tif (blocks.length === 0) return [];\n\tblocks.sort((a, b) => a.height - b.height);\n\n\tconst ranges: GapRange[] = [];\n\tlet start = blocks[0].height;\n\tlet end = blocks[0].height;\n\tlet reason = blocks[0].reason;\n\n\tfor (let i = 1; i < blocks.length; i++) {\n\t\tconst b = blocks[i];\n\t\tif (b.height === end + 1 && b.reason === reason) {\n\t\t\tend = b.height;\n\t\t} else {\n\t\t\tranges.push({ start, end, reason });\n\t\t\tstart = b.height;\n\t\t\tend = b.height;\n\t\t\treason = b.reason;\n\t\t}\n\t}\n\tranges.push({ start, end, reason });\n\treturn ranges;\n}\n\nexport interface ReindexOptions {\n\t/**\n\t * Floor on the walk's first block — NOT a caller-supplied range. When set\n\t * (e.g. an op row carrying a `from_block`), it raises the walk start and\n\t * can never lower it. There is deliberately no `toBlock` counterpart:\n\t * a reindex always runs to chain tip. See {@link resolveBlockRange}.\n\t */\n\tstartBlockFloor?: number;\n\tschemaName?: string;\n\t/** Op row to receive processed_events on each progress flush. */\n\toperationId?: string;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Shared block range processor used by both reindex and backfill.\n * Processes blocks in batches with prefetch pipeline.\n * Supports cancellation via AbortSignal — breaks cleanly at batch boundaries.\n */\nasync function processBlockRange(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t\tstatus: string;\n\t\tisCatchup: boolean;\n\t\tapiKeyId: string | null;\n\t\tsubgraphId?: string;\n\t\t/** When set, the progress flush writes processed_events onto the op row\n\t\t * — the honest numerator for event-based progress/ETA. */\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{\n\tblocksProcessed: number;\n\ttotalEventsProcessed: number;\n\ttotalErrors: number;\n\taborted: boolean;\n}> {\n\tconst source = resolveBlockSource(def);\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\tconst { fromBlock, toBlock, status } = opts;\n\tconst totalBlocks = toBlock - fromBlock + 1;\n\n\tconst stats = new StatsAccumulator(subgraphName, opts.isCatchup);\n\tlet blocksProcessed = 0;\n\tlet blocksSkippedByCursor = 0;\n\tlet totalEventsProcessed = 0;\n\tlet totalErrors = 0;\n\tlet pendingEventsProcessed = 0;\n\tlet pendingErrors = 0;\n\tlet pendingLastError: string | undefined;\n\tlet lastHealthFlushBlock = 0;\n\tlet lastHealthFlushAt = Date.now();\n\tlet lastProgressFlushAt = Date.now();\n\tconst batchConfig = resolveReindexBatchConfig();\n\tlet batchSize = batchConfig.defaultBatchSize;\n\tlet currentHeight = fromBlock;\n\tlet aborted = false;\n\tlet consecutiveEmptyBatches = 0;\n\t// Sparse scan: when a whole batch matches nothing, ask the source for the\n\t// next height that could match and leap there — token-scoped genesis\n\t// reindexes skip the (often vast) majority of chain history.\n\tconst sparse = Boolean(source.nextDataHeight && canSparseScan(def));\n\n\tconst flushHealth = async () => {\n\t\tif (pendingEventsProcessed === 0 && pendingErrors === 0) return;\n\t\tawait recordSubgraphProcessed(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\tpendingEventsProcessed,\n\t\t\tpendingErrors,\n\t\t\tpendingLastError,\n\t\t);\n\t\tpendingEventsProcessed = 0;\n\t\tpendingErrors = 0;\n\t\tpendingLastError = undefined;\n\t\tlastHealthFlushBlock = blocksProcessed;\n\t\tlastHealthFlushAt = Date.now();\n\t};\n\n\t/**\n\t * Stop the walk at an unprocessable block: surface the error, mark the\n\t * subgraph errored, and throw. Deliberately does NOT touch\n\t * last_processed_block — the cursor stays before the failed block so a\n\t * restart re-attempts it instead of silently skipping its events.\n\t */\n\tconst haltRange = async (\n\t\terrorMsg: string,\n\t\theight: number,\n\t): Promise<never> => {\n\t\tpendingErrors++;\n\t\tpendingLastError = errorMsg;\n\t\tawait flushHealth().catch(() => {});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\").catch(() => {});\n\t\tthrow new Error(`${subgraphName}: halted at block ${height}: ${errorMsg}`);\n\t};\n\n\t// Pipeline: start loading first batch and track the prefetched range.\n\t// batchEnd must match what was actually loaded — not recalculated from a\n\t// potentially resized batchSize (adaptive sizing can change it between iterations).\n\tlet nextBatchEnd = Math.min(currentHeight + batchSize - 1, toBlock);\n\tlet nextBatchPromise = source.loadBlockRange(currentHeight, nextBatchEnd);\n\n\twhile (currentHeight <= toBlock) {\n\t\t// Check for abort at batch boundary\n\t\tif (opts.signal?.aborted) {\n\t\t\taborted = true;\n\t\t\tlogger.info(\"Block processing aborted\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tcurrentBlock: currentHeight,\n\t\t\t\treason: String(opts.signal.reason ?? \"unknown\"),\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst batch = await nextBatchPromise;\n\t\tconst batchEnd = nextBatchEnd;\n\n\t\t// Source-health guard (fix-f040 B7): the source seeds every canonical\n\t\t// height in range (including empty blocks), so consecutive fully-empty\n\t\t// batches mean the SOURCE is degraded — not that thousands of blocks\n\t\t// are absent. The old behavior filed every height as a block_missing\n\t\t// gap and kept walking; one degraded source minted thousands of false\n\t\t// gap rows in minutes.\n\t\tif (batch.size === 0 && batchEnd >= currentHeight) {\n\t\t\tconsecutiveEmptyBatches++;\n\t\t\tif (consecutiveEmptyBatches >= EMPTY_BATCH_HALT_THRESHOLD) {\n\t\t\t\tawait haltRange(\n\t\t\t\t\t`block source returned ${consecutiveEmptyBatches} consecutive empty batches (ending ${currentHeight}..${batchEnd}) — source degraded`,\n\t\t\t\t\tcurrentHeight,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tconsecutiveEmptyBatches = 0;\n\t\t}\n\n\t\t// Prefetch next batch (uses current batchSize, which may have been adapted)\n\t\tconst nextStart = batchEnd + 1;\n\t\tif (nextStart <= toBlock) {\n\t\t\tnextBatchEnd = Math.min(nextStart + batchSize - 1, toBlock);\n\t\t\tnextBatchPromise = source.loadBlockRange(nextStart, nextBatchEnd);\n\t\t}\n\n\t\tconst batchFailedBlocks: { height: number; reason: string }[] = [];\n\t\tlet batchMatched = 0;\n\t\t// Reindex is a strictly ascending walk over the subgraph's own cursor, so\n\t\t// written blocks checkpoint atomically and replays skip (fix-f040 B3).\n\t\t// Backfill revisits heights below the live cursor — must stay batched.\n\t\t// Reindex checkpoints on the subgraph cursor; backfill (status 'active')\n\t\t// revisits heights BELOW the live cursor, so it checkpoints on its own\n\t\t// op row instead — and must NEVER write the live cursor (an unconditional\n\t\t// historical SET would regress it and make catch-up re-walk + double-apply).\n\t\tconst opCursor =\n\t\t\tstatus === \"active\" && opts.operationId\n\t\t\t\t? { operationId: opts.operationId }\n\t\t\t\t: undefined;\n\t\tconst atomicProgress = status === \"reindexing\" ? { status } : opCursor;\n\n\t\tfor (let height = currentHeight; height <= batchEnd; height++) {\n\t\t\tlet blockData = batch.get(height);\n\t\t\tif (!blockData) {\n\t\t\t\t// Could be a transient source hiccup — refetch the single height\n\t\t\t\t// before concluding the block is genuinely absent.\n\t\t\t\tblockData = (await source.loadBlockRange(height, height)).get(height);\n\t\t\t}\n\t\t\tif (!blockData) {\n\t\t\t\tif (status === \"reindexing\") {\n\t\t\t\t\t// Strict: a missing source block means every downstream value is\n\t\t\t\t\t// wrong, not approximately right. Halt; do not advance past it.\n\t\t\t\t\tconst errorMsg = `block ${height} missing from source — halting reindex (cursor stays at ${height - 1})`;\n\t\t\t\t\tawait haltRange(errorMsg, height);\n\t\t\t\t}\n\t\t\t\t// Backfill: the range IS the gap-repair pass; record what's still\n\t\t\t\t// missing and keep going.\n\t\t\t\tbatchFailedBlocks.push({ height, reason: \"block_missing\" });\n\t\t\t\tblocksProcessed++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet result: ProcessBlockResult;\n\t\t\ttry {\n\t\t\t\t// Same per-subgraph block lock the live catch-up walk takes, at the\n\t\t\t\t// same granularity (one block's write), so the two walks actually\n\t\t\t\t// contend instead of interleaving writes to the same rows. The\n\t\t\t\t// advisory half is the load-bearing one here: this walk runs under\n\t\t\t\t// the operation runner, which is not leader-gated, so it is\n\t\t\t\t// routinely in a DIFFERENT process from the catch-up leader.\n\t\t\t\t// Backfill runs at status 'active' and never changes it, so catch-up\n\t\t\t\t// never stands down on its own. See catchup.ts for the acquisition\n\t\t\t\t// order these two locks share with the reorg lock.\n\t\t\t\t//\n\t\t\t\t// Locked only when the block can write. This walk always passes\n\t\t\t\t// `skipProgressUpdate`, so a block that matches nothing writes\n\t\t\t\t// NOTHING — not even a cursor — and `matchSources`/factory discovery\n\t\t\t\t// draw exclusively from the txs and events below, so an empty block\n\t\t\t\t// cannot match. That is a property of the preloaded data, not a\n\t\t\t\t// second copy of the matcher's rules. It matters because a\n\t\t\t\t// genesis-era range is overwhelmingly empty blocks, and locking each\n\t\t\t\t// one costs a round trip that buys no serialization. (Catch-up\n\t\t\t\t// cannot take this shortcut: its no-match path still writes the\n\t\t\t\t// cursor, which is exactly what the lock protects there.)\n\t\t\t\tconst mayWrite =\n\t\t\t\t\tblockData.txs.length > 0 || blockData.events.length > 0;\n\t\t\t\tconst runBlock = () =>\n\t\t\t\t\tprocessBlockWithRetry(def, subgraphName, height, {\n\t\t\t\t\t\tskipProgressUpdate: true,\n\t\t\t\t\t\tatomicProgress,\n\t\t\t\t\t\tpreloaded: blockData,\n\t\t\t\t\t});\n\t\t\t\tresult = mayWrite\n\t\t\t\t\t? await withSubgraphBlockWriteLock(subgraphName, runBlock)\n\t\t\t\t\t: await runBlock();\n\t\t\t} catch (err) {\n\t\t\t\tconst errorMsg = getErrorMessage(err);\n\t\t\t\tlogger.error(\"Block processing failed persistently\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight: height,\n\t\t\t\t\terror: errorMsg,\n\t\t\t\t});\n\t\t\t\tif (status === \"reindexing\") {\n\t\t\t\t\t// Strict: skipping a block of events silently corrupts every\n\t\t\t\t\t// accumulator downstream. Halt with the cursor still BEFORE the\n\t\t\t\t\t// failed block so a restart re-attempts it (fix-f040 B5).\n\t\t\t\t\tawait haltRange(\n\t\t\t\t\t\t`block ${height} failed persistently: ${errorMsg}`,\n\t\t\t\t\t\theight,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Backfill: record and continue — the gap row keeps it repairable.\n\t\t\t\tbatchFailedBlocks.push({ height, reason: \"processing_error\" });\n\t\t\t\tblocksProcessed++;\n\t\t\t\ttotalErrors++;\n\t\t\t\tpendingErrors++;\n\t\t\t\tpendingLastError = errorMsg;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tblocksProcessed++;\n\t\t\tif (result.skipped) blocksSkippedByCursor++;\n\t\t\tbatchMatched += result.matched;\n\t\t\ttotalEventsProcessed += result.processed;\n\t\t\ttotalErrors += result.errors;\n\t\t\tpendingEventsProcessed += result.processed;\n\t\t\tpendingErrors += result.errors;\n\t\t\tif (result.errors > 0) {\n\t\t\t\tpendingLastError = `${result.errors} error(s) while processing block ${height}`;\n\t\t\t}\n\n\t\t\tif (result.timing) {\n\t\t\t\tstats.record(result.timing, result.processed);\n\t\t\t\tif (stats.shouldFlush()) {\n\t\t\t\t\tawait stats.flush(targetDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst now = Date.now();\n\t\t\tconst shouldFlushProgress =\n\t\t\t\tblocksProcessed % 100 === 0 ||\n\t\t\t\tnow - lastProgressFlushAt >= PROGRESS_FLUSH_INTERVAL_MS;\n\t\t\tif (shouldFlushProgress) {\n\t\t\t\tif (opCursor) {\n\t\t\t\t\t// Covers write-less stretches; conditional → can't regress the\n\t\t\t\t\t// in-tx advances written by processed blocks.\n\t\t\t\t\tawait advanceOperationCursor(targetDb, opCursor.operationId, height);\n\t\t\t\t} else {\n\t\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, status, height);\n\t\t\t\t}\n\t\t\t\tif (opts.operationId) {\n\t\t\t\t\tawait updateOperationProcessedEvents(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\topts.operationId,\n\t\t\t\t\t\ttotalEventsProcessed,\n\t\t\t\t\t).catch(() => {});\n\t\t\t\t}\n\t\t\t\tlastProgressFlushAt = now;\n\t\t\t}\n\n\t\t\tif (blocksProcessed % LOG_INTERVAL === 0) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`${status === \"reindexing\" ? \"Reindex\" : \"Backfill\"} progress`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tprocessed: blocksProcessed,\n\t\t\t\t\t\ttotal: totalBlocks,\n\t\t\t\t\t\tcurrentBlock: height,\n\t\t\t\t\t\tpct: Math.round((blocksProcessed / totalBlocks) * 100),\n\t\t\t\t\t\t...(blocksSkippedByCursor > 0\n\t\t\t\t\t\t\t? { skippedByCursor: blocksSkippedByCursor }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (status === \"reindexing\" && blocksProcessed > 0) {\n\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, status, batchEnd);\n\t\t}\n\n\t\tconst shouldFlushHealth =\n\t\t\tblocksProcessed - lastHealthFlushBlock >= HEALTH_FLUSH_INTERVAL ||\n\t\t\tDate.now() - lastHealthFlushAt >= PROGRESS_FLUSH_INTERVAL_MS;\n\t\tif (shouldFlushHealth) {\n\t\t\tawait flushHealth();\n\t\t}\n\n\t\t// Record any gaps from this batch\n\t\tif (batchFailedBlocks.length > 0 && opts.subgraphId) {\n\t\t\tconst gaps = coalesceFailedBlocks(batchFailedBlocks);\n\t\t\tawait recordGapBatch(targetDb, opts.subgraphId, subgraphName, gaps).catch(\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\tlogger.warn(\"Failed to record subgraph gaps\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Sparse skip: nothing in this batch could match → probe for the next\n\t\t// height that can, and jump the cursor there. The in-flight prefetch is\n\t\t// discarded (one wasted fetch buys skipping arbitrarily many).\n\t\tif (\n\t\t\tsparse &&\n\t\t\tbatchMatched === 0 &&\n\t\t\tbatchEnd < toBlock &&\n\t\t\tsource.nextDataHeight\n\t\t) {\n\t\t\tconst next = await source.nextDataHeight(batchEnd, toBlock);\n\t\t\tconst jumpTo = next === null ? toBlock + 1 : Math.max(next, batchEnd + 1);\n\t\t\tif (jumpTo > batchEnd + 1) {\n\t\t\t\tconst skipped = Math.min(jumpTo, toBlock + 1) - (batchEnd + 1);\n\t\t\t\tblocksProcessed += skipped;\n\t\t\t\tif (opCursor) {\n\t\t\t\t\tawait advanceOperationCursor(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\topCursor.operationId,\n\t\t\t\t\t\tjumpTo - 1,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tawait updateSubgraphStatus(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tjumpTo - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlogger.info(\"Sparse skip\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tfrom: batchEnd + 1,\n\t\t\t\t\tto: jumpTo - 1,\n\t\t\t\t\tskipped,\n\t\t\t\t});\n\t\t\t\tcurrentHeight = jumpTo;\n\t\t\t\tif (currentHeight <= toBlock) {\n\t\t\t\t\tnextBatchEnd = Math.min(currentHeight + batchSize - 1, toBlock);\n\t\t\t\t\tnextBatchPromise = source.loadBlockRange(currentHeight, nextBatchEnd);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Adaptive batch sizing\n\t\tconst avg = avgEventsPerBlock(batch);\n\t\tif (avg > 50)\n\t\t\tbatchSize = Math.max(\n\t\t\t\tMath.round(batchSize * 0.5),\n\t\t\t\tbatchConfig.minBatchSize,\n\t\t\t);\n\t\telse if (avg < 10)\n\t\t\tbatchSize = Math.min(\n\t\t\t\tMath.round(batchSize * 1.5),\n\t\t\t\tbatchConfig.maxBatchSize,\n\t\t\t);\n\n\t\tcurrentHeight = batchEnd + 1;\n\t}\n\n\tawait stats.flush(targetDb);\n\tawait flushHealth();\n\treturn { blocksProcessed, totalEventsProcessed, totalErrors, aborted };\n}\n\n/**\n * Resolve the reindex walk range. Always the whole subgraph:\n * `[def.startBlock, chain tip]`. Chain tip reads from `index_progress` —\n * lives in the source DB.\n *\n * Reindex drops the schema unconditionally, so the walk range is also the\n * ONLY data that survives. A narrower walk therefore does not \"reindex a\n * range\" — it silently destroys every row outside it while leaving the\n * subgraph reporting `active` at chain tip (f079: a single-block\n * `--from-block N --to-block N` emptied sbtc-flows, and the first recovery\n * attempt rebuilt only 21% of its history). Ranged, additive work is\n * `backfillSubgraph`'s job.\n *\n * `startBlockFloor` is a plan-policy floor, not a range: it can only raise\n * the start block, never lower it, and never bounds the end.\n */\nexport async function resolveBlockRange(\n\tsource: BlockSource,\n\tdef: SubgraphDefinition,\n\topts?: ReindexOptions,\n): Promise<{ fromBlock: number; toBlock: number }> {\n\tconst definitionStart = def.startBlock ?? 1;\n\tconst fromBlock =\n\t\topts?.startBlockFloor != null\n\t\t\t? Math.max(definitionStart, opts.startBlockFloor)\n\t\t\t: definitionStart;\n\tconst rawTip = await source.getTip();\n\tif (!usesDecodedIndexPlane(def)) {\n\t\treturn { fromBlock, toBlock: rawTip };\n\t}\n\tconst bound = await boundSourceTip(rawTip, decoderNamesForSubgraph(def));\n\tif (!bound.ok) {\n\t\tlogger.warn(\"Reindex stalled: missing decoder checkpoint\", {\n\t\t\tevent: \"subgraph_reindex_decoder_stall\",\n\t\t\tsubgraph: def.name,\n\t\t\tmissing: bound.missing,\n\t\t});\n\t\tthrow new Error(\n\t\t\t`Reindex stalled: missing decoder checkpoint (${bound.missing.join(\", \")})`,\n\t\t);\n\t}\n\tif (bound.floor !== null && bound.floor < rawTip) {\n\t\tlogger.debug(\"Reindex tip bounded by decoder progress\", {\n\t\t\tevent: \"subgraph_reindex_decoder_floor\",\n\t\t\tsubgraph: def.name,\n\t\t\trawTip,\n\t\t\tfloor: bound.floor,\n\t\t\ttip: bound.tip,\n\t\t});\n\t}\n\treturn { fromBlock, toBlock: bound.tip };\n}\n\n/**\n * Clear reindex metadata columns after completion or cancellation.\n */\nasync function clearReindexMetadata(\n\tdb: ReturnType<typeof getTargetDb>,\n\tsubgraphName: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({ reindex_from_block: null, reindex_to_block: null })\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.execute();\n}\n\n/**\n * Reindex a subgraph by dropping its tables, recreating them, and reprocessing\n * all historical blocks through the handler pipeline.\n *\n * Always whole-subgraph: `[start_block, chain tip]`. There is no ranged\n * reindex — the drop cannot be scoped to a range without re-running delta\n * handlers (`ctx.increment` / `ctx.update` / `ctx.patchOrInsert`) over rows\n * that were never removed, which is the exact double-count hazard `backfill`\n * already refuses. Use `backfillSubgraph` for ranged, additive work.\n *\n * Supports cancellation via AbortSignal — on shutdown abort, status stays\n * \"reindexing\" for auto-resume; on user cancel, status resets to \"active\".\n */\nexport async function reindexSubgraph(\n\tdef: SubgraphDefinition,\n\topts?: ReindexOptions,\n): Promise<{ processed: number }> {\n\t// Chain tip reads hit the block source; subgraph rows + tenant schemas live in target\n\tconst source = resolveBlockSource(def);\n\tconst targetDb = getTargetDb();\n\tconst client = getRawClient(\"target\");\n\tconst subgraphName = def.name;\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(subgraphName);\n\n\tawait updateSubgraphStatus(targetDb, subgraphName, \"reindexing\");\n\tlogger.info(\"Reindex starting\", { subgraph: subgraphName });\n\n\ttry {\n\t\t// Resolve block range BEFORE schema drop so we can persist metadata\n\t\tconst { fromBlock, toBlock } = await resolveBlockRange(source, def, opts);\n\n\t\tif (fromBlock > toBlock) {\n\t\t\tlogger.info(\"No blocks to reindex\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tfromBlock,\n\t\t\t\ttoBlock,\n\t\t\t});\n\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", 0);\n\t\t\treturn { processed: 0 };\n\t\t}\n\n\t\t// Drop and recreate schema + tables (tenant-side DDL)\n\t\tawait client.unsafe(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`);\n\t\tconst { statements } = generateSubgraphSQL(def, schemaName);\n\t\tfor (const stmt of statements) {\n\t\t\tawait client.unsafe(stmt);\n\t\t}\n\t\t// The schema drop just invalidated everything the cursor claims was\n\t\t// applied. Reset it BELOW the walk's start or the atomicProgress replay\n\t\t// guard treats a stale cursor (prior halted/cancelled run) as \"already\n\t\t// applied\" and silently skips the entire prefix — empty tables, then a\n\t\t// CHECK violation at the first real delta (the sbtc-balances halt at\n\t\t// block 1913668: 1.9M credit blocks skipped against a 1913667 cursor).\n\t\tawait updateSubgraphStatus(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\t\"reindexing\",\n\t\t\tMath.max(0, fromBlock - 1),\n\t\t);\n\t\tlogger.info(\"Schema recreated for reindex\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tcursorResetTo: Math.max(0, fromBlock - 1),\n\t\t});\n\n\t\t// Store reindex range after DDL is ready. A crash before this point falls\n\t\t// back to a fresh reindex, which safely drops/recreates the schema again.\n\t\tawait targetDb\n\t\t\t.updateTable(\"subgraphs\")\n\t\t\t.set({\n\t\t\t\tlast_processed_block: initialReindexProgressBlock(fromBlock),\n\t\t\t\treindex_from_block: fromBlock,\n\t\t\t\treindex_to_block: toBlock,\n\t\t\t\ttotal_processed: 0,\n\t\t\t\ttotal_errors: 0,\n\t\t\t\tlast_error: null,\n\t\t\t\tlast_error_at: null,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t})\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.execute();\n\n\t\tlogger.info(\"Reindexing blocks\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\ttotalBlocks: toBlock - fromBlock + 1,\n\t\t});\n\n\t\tconst subgraphRow = await targetDb\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select([\"id\"])\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.executeTakeFirst();\n\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\tstatus: \"reindexing\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: subgraphRow?.id,\n\t\t\toperationId: opts?.operationId,\n\t\t\tsignal: opts?.signal,\n\t\t});\n\n\t\t// Handle abort\n\t\tif (result.aborted) {\n\t\t\tconst reason = String(opts?.signal?.reason ?? \"unknown\");\n\t\t\tif (reason === \"user-cancelled\") {\n\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\");\n\t\t\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\t\t\tlogger.info(\"Reindex cancelled by user\", { subgraph: subgraphName });\n\t\t\t} else {\n\t\t\t\t// shutdown — leave status as \"reindexing\" for auto-resume\n\t\t\t\tlogger.info(\"Reindex interrupted by shutdown, will resume\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\tlogger.info(\"Reindex complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\t// Fire-and-forget — never delay or fail the reindex on a notify hiccup.\n\t\tvoid notifyReindexComplete(targetDb, subgraphName, {\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Reindex failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\");\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resume a previously interrupted reindex. Skips schema drop (already done)\n * and continues from last_processed_block + 1.\n */\nexport async function resumeReindex(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tschemaName: string;\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{ processed: number }> {\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.select([\n\t\t\t\"id\",\n\t\t\t\"last_processed_block\",\n\t\t\t\"reindex_from_block\",\n\t\t\t\"reindex_to_block\",\n\t\t])\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\n\tif (!row) throw new Error(`Subgraph \"${subgraphName}\" not found`);\n\n\tconst fromBlock = resolveReindexResumeBlock(row);\n\tconst toBlock = Number(row.reindex_to_block);\n\n\t// Legacy: no reindex metadata — fall back to full reindex\n\tif (fromBlock == null) {\n\t\tlogger.info(\"No reindex metadata, starting fresh reindex\", {\n\t\t\tsubgraph: subgraphName,\n\t\t});\n\t\treturn reindexSubgraph(def, {\n\t\t\tschemaName: opts.schemaName,\n\t\t\tsignal: opts.signal,\n\t\t});\n\t}\n\n\tif (fromBlock > toBlock) {\n\t\tlogger.info(\"Resume: no remaining blocks\", { subgraph: subgraphName });\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\treturn { processed: 0 };\n\t}\n\n\tlogger.info(\"Resuming reindex\", {\n\t\tsubgraph: subgraphName,\n\t\tfromBlock,\n\t\ttoBlock,\n\t\tremaining: toBlock - fromBlock + 1,\n\t});\n\n\ttry {\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\tstatus: \"reindexing\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: row.id,\n\t\t\toperationId: opts.operationId,\n\t\t\tsignal: opts.signal,\n\t\t});\n\n\t\tif (result.aborted) {\n\t\t\tconst reason = String(opts.signal?.reason ?? \"unknown\");\n\t\t\tif (reason === \"user-cancelled\") {\n\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\");\n\t\t\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\t\t\tlogger.info(\"Resume cancelled by user\", { subgraph: subgraphName });\n\t\t\t} else {\n\t\t\t\tlogger.info(\"Resume interrupted by shutdown, will resume again\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\tlogger.info(\"Resumed reindex complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Resumed reindex failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\");\n\t\tthrow err;\n\t}\n}\n\n/**\n * Backfill a subgraph by re-processing a block range WITHOUT dropping the schema.\n * Uses upserts so existing data is updated, not duplicated. Safe to run while\n * the subgraph is actively syncing.\n */\nexport async function backfillSubgraph(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t\tschemaName?: string;\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{ processed: number }> {\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\n\tlogger.info(\"Backfill starting\", {\n\t\tsubgraph: subgraphName,\n\t\tfrom: opts.fromBlock,\n\t\tto: opts.toBlock,\n\t});\n\n\ttry {\n\t\tconst subgraphRow = await targetDb\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select([\"id\"])\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.executeTakeFirst();\n\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock: opts.fromBlock,\n\t\t\ttoBlock: opts.toBlock,\n\t\t\tstatus: \"active\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: subgraphRow?.id,\n\t\t\toperationId: opts.operationId,\n\t\t\tsignal: opts.signal,\n\t\t});\n\n\t\tif (result.aborted) {\n\t\t\tlogger.info(\"Backfill aborted\", { subgraph: subgraphName });\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\t// Resolve any gaps within the backfilled range\n\t\tconst resolved = await resolveGaps(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\topts.fromBlock,\n\t\t\topts.toBlock,\n\t\t).catch(() => 0);\n\t\tif (resolved > 0) {\n\t\t\tlogger.info(\"Resolved subgraph gaps via backfill\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tresolved,\n\t\t\t});\n\t\t}\n\n\t\tlogger.info(\"Backfill complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Backfill failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tthrow err;\n\t}\n}\n",
31
+ "import { decodeStreamsCursor, isEmptyRangeCursor } from \"@secondlayer/shared\";\nimport { type Database, getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport {\n\tVM_INDEX_EVENT_TYPES,\n\tisStreamsIndexEligible,\n\treferencedIndexEventTypes,\n} from \"./block-source.ts\";\n\n/**\n * Decoder-progress bound for consumers that read decoded Index rows.\n *\n * Each decoded event type is produced by an independent decoder\n * (`decode.<event_type>.v1` — ADR-0008/0010). Index `getTip` tracks\n * `decode.ft_transfer.v1` (or ingestion, on the Postgres tap). A forward-only\n * cursor that processes a height before the decoder feeding a referenced type\n * has committed it misses the match and never revisits.\n *\n * Bound the tip by the MIN committed height over ONLY the decoders the\n * consumer actually reads. A stalled unreferenced decoder (idle pox4) must\n * never gate progress. A referenced decoder with no usable checkpoint stalls\n * the consumer rather than falling through to the raw tip.\n */\n\n/** ADR checkpoint name. Subgraphs does not depend on `@secondlayer/indexer`. */\nexport function decoderNameForEventType(indexEventType: string): string {\n\treturn `decode.${indexEventType}.v1`;\n}\n\nexport function decoderNamesForIndexEventTypes(eventTypes: string[]): string[] {\n\treturn eventTypes\n\t\t.filter((t) => !VM_INDEX_EVENT_TYPES.has(t))\n\t\t.map(decoderNameForEventType);\n}\n\nexport function decoderNamesForSubgraph(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\treturn decoderNamesForIndexEventTypes(referencedIndexEventTypes(subgraph));\n}\n\n/**\n * True when catch-up/reindex will load decoded Index rows (the race).\n * Postgres tap reads raw `events` at ingest and must not wait on decode.\n * Mirrors `resolveBlockSource`'s streams-index branch.\n */\nexport function usesDecodedIndexPlane(subgraph: SubgraphDefinition): boolean {\n\treturn (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tisStreamsIndexEligible(subgraph)\n\t);\n}\n\n/**\n * Highest height at which this cursor has fully committed. Mid-block\n * (`H:n`, n not the empty-range sentinel) means the rest of H is still\n * in flight — floor is H-1. Sentinel `H:2147483647` means H is done.\n */\nexport function committedHeight(\n\tcursor: string | null | undefined,\n): number | null {\n\tif (!cursor) return null;\n\ttry {\n\t\tconst decoded = decodeStreamsCursor(cursor);\n\t\tif (isEmptyRangeCursor(decoded)) return decoded.block_height;\n\t\treturn Math.max(0, decoded.block_height - 1);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport type DecoderBound =\n\t| { kind: \"unbounded\" }\n\t| { kind: \"stall\"; missing: string[] }\n\t| { kind: \"height\"; height: number };\n\n/**\n * Data-availability floor for `decoderNames`. Reads SOURCE-plane\n * `decoder_checkpoints` (same rationale as trait resolution: the consumer\n * handle is often the TARGET, where those rows are empty).\n */\nexport async function decoderBoundTip(\n\tdecoderNames: string[],\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<DecoderBound> {\n\tif (decoderNames.length === 0) return { kind: \"unbounded\" };\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst rows = await sourceDb\n\t\t.selectFrom(\"decoder_checkpoints\")\n\t\t.select([\"decoder_name\", \"last_cursor\"])\n\t\t.where(\"decoder_name\", \"in\", decoderNames)\n\t\t.execute();\n\tconst byName = new Map(rows.map((r) => [r.decoder_name, r.last_cursor]));\n\tconst missing: string[] = [];\n\tconst heights: number[] = [];\n\tfor (const name of decoderNames) {\n\t\tconst height = committedHeight(byName.get(name));\n\t\tif (height === null) missing.push(name);\n\t\telse heights.push(height);\n\t}\n\tif (missing.length > 0) return { kind: \"stall\", missing };\n\treturn { kind: \"height\", height: Math.min(...heights) };\n}\n\nexport type BoundSourceTip =\n\t| { ok: true; tip: number; floor: number | null }\n\t| { ok: false; missing: string[] };\n\n/** Combine a raw block-source tip with the decoder floor. */\nexport async function boundSourceTip(\n\trawTip: number,\n\tdecoderNames: string[],\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<BoundSourceTip> {\n\tconst bound = await decoderBoundTip(decoderNames, opts);\n\tif (bound.kind === \"stall\") return { ok: false, missing: bound.missing };\n\tif (bound.kind === \"unbounded\") {\n\t\treturn { ok: true, tip: rawTip, floor: null };\n\t}\n\treturn {\n\t\tok: true,\n\t\ttip: Math.min(rawTip, bound.height),\n\t\tfloor: bound.height,\n\t};\n}\n",
32
+ "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { getRawClient, getTargetDb } from \"@secondlayer/shared/db\";\nimport {\n\ttype GapRange,\n\trecordGapBatch,\n\tresolveGaps,\n} from \"@secondlayer/shared/db/queries/subgraph-gaps\";\nimport {\n\tadvanceOperationCursor,\n\tupdateOperationProcessedEvents,\n} from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\trecordSubgraphProcessed,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { generateSubgraphSQL } from \"../schema/generator.ts\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { avgEventsPerBlock } from \"./batch-loader.ts\";\nimport {\n\ttype ProcessBlockResult,\n\tprocessBlockWithRetry,\n} from \"./block-processor.ts\";\nimport {\n\ttype BlockSource,\n\tcanSparseScan,\n\tresolveBlockSource,\n} from \"./block-source.ts\";\nimport { withSubgraphBlockWriteLock } from \"./catchup.ts\";\nimport {\n\tboundSourceTip,\n\tdecoderNamesForSubgraph,\n\tusesDecodedIndexPlane,\n} from \"./decoder-bound.ts\";\nimport { notifyReindexComplete } from \"./reindex-notify.ts\";\nimport { StatsAccumulator } from \"./stats.ts\";\n\nconst LOG_INTERVAL = 1000;\nconst HEALTH_FLUSH_INTERVAL = 1000;\nconst PROGRESS_FLUSH_INTERVAL_MS = 5_000;\n/** Consecutive fully-empty batches before the walk halts as source-degraded. */\nconst EMPTY_BATCH_HALT_THRESHOLD = 3;\nconst STANDARD_REINDEX_BATCH_CONFIG = {\n\tdefaultBatchSize: 500,\n\tminBatchSize: 100,\n\tmaxBatchSize: 1000,\n};\n\ntype ReindexBatchConfig = {\n\tdefaultBatchSize: number;\n\tminBatchSize: number;\n\tmaxBatchSize: number;\n};\ntype ReindexBatchEnv = {\n\tSUBGRAPH_REINDEX_BATCH_SIZE?: string;\n\tSUBGRAPH_REINDEX_MIN_BATCH_SIZE?: string;\n\tSUBGRAPH_REINDEX_MAX_BATCH_SIZE?: string;\n};\n\ntype ReindexResumeRow = {\n\tlast_processed_block: number | string;\n\treindex_from_block: number | string | null;\n\treindex_to_block: number | string | null;\n};\n\nexport function initialReindexProgressBlock(fromBlock: number): number {\n\treturn Math.max(0, fromBlock - 1);\n}\n\nexport function resolveReindexResumeBlock(\n\trow: ReindexResumeRow,\n): number | null {\n\tif (row.reindex_from_block == null || row.reindex_to_block == null) {\n\t\treturn null;\n\t}\n\n\tconst lastProcessedBlock = Number(row.last_processed_block);\n\tconst reindexFromBlock = Number(row.reindex_from_block);\n\n\treturn Math.max(lastProcessedBlock + 1, reindexFromBlock);\n}\n\nfunction parsePositiveInt(value: string | undefined): number | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst parsed = Number.parseInt(value, 10);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nexport function resolveReindexBatchConfig(\n\tenv: ReindexBatchEnv = process.env as ReindexBatchEnv,\n): ReindexBatchConfig {\n\tconst base = STANDARD_REINDEX_BATCH_CONFIG;\n\tconst minBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_MIN_BATCH_SIZE) ?? base.minBatchSize;\n\tconst maxBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_MAX_BATCH_SIZE) ?? base.maxBatchSize;\n\tconst defaultBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_REINDEX_BATCH_SIZE) ?? base.defaultBatchSize;\n\n\treturn {\n\t\tminBatchSize,\n\t\tmaxBatchSize,\n\t\tdefaultBatchSize: Math.min(\n\t\t\tMath.max(defaultBatchSize, minBatchSize),\n\t\t\tmaxBatchSize,\n\t\t),\n\t};\n}\n\n/**\n * Coalesce individual block heights + reasons into contiguous gap ranges.\n */\nfunction coalesceFailedBlocks(\n\tblocks: { height: number; reason: string }[],\n): GapRange[] {\n\tif (blocks.length === 0) return [];\n\tblocks.sort((a, b) => a.height - b.height);\n\n\tconst ranges: GapRange[] = [];\n\tlet start = blocks[0].height;\n\tlet end = blocks[0].height;\n\tlet reason = blocks[0].reason;\n\n\tfor (let i = 1; i < blocks.length; i++) {\n\t\tconst b = blocks[i];\n\t\tif (b.height === end + 1 && b.reason === reason) {\n\t\t\tend = b.height;\n\t\t} else {\n\t\t\tranges.push({ start, end, reason });\n\t\t\tstart = b.height;\n\t\t\tend = b.height;\n\t\t\treason = b.reason;\n\t\t}\n\t}\n\tranges.push({ start, end, reason });\n\treturn ranges;\n}\n\nexport interface ReindexOptions {\n\t/**\n\t * Floor on the walk's first block — NOT a caller-supplied range. When set\n\t * (e.g. an op row carrying a `from_block`), it raises the walk start and\n\t * can never lower it. There is deliberately no `toBlock` counterpart:\n\t * a reindex always runs to chain tip. See {@link resolveBlockRange}.\n\t */\n\tstartBlockFloor?: number;\n\tschemaName?: string;\n\t/** Op row to receive processed_events on each progress flush. */\n\toperationId?: string;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Shared block range processor used by both reindex and backfill.\n * Processes blocks in batches with prefetch pipeline.\n * Supports cancellation via AbortSignal — breaks cleanly at batch boundaries.\n */\nasync function processBlockRange(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t\tstatus: string;\n\t\tisCatchup: boolean;\n\t\tapiKeyId: string | null;\n\t\tsubgraphId?: string;\n\t\t/** When set, the progress flush writes processed_events onto the op row\n\t\t * — the honest numerator for event-based progress/ETA. */\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{\n\tblocksProcessed: number;\n\ttotalEventsProcessed: number;\n\ttotalErrors: number;\n\taborted: boolean;\n}> {\n\tconst source = resolveBlockSource(def);\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\tconst { fromBlock, toBlock, status } = opts;\n\tconst totalBlocks = toBlock - fromBlock + 1;\n\n\tconst stats = new StatsAccumulator(subgraphName, opts.isCatchup);\n\tlet blocksProcessed = 0;\n\tlet blocksSkippedByCursor = 0;\n\tlet totalEventsProcessed = 0;\n\tlet totalErrors = 0;\n\tlet pendingEventsProcessed = 0;\n\tlet pendingErrors = 0;\n\tlet pendingLastError: string | undefined;\n\tlet lastHealthFlushBlock = 0;\n\tlet lastHealthFlushAt = Date.now();\n\tlet lastProgressFlushAt = Date.now();\n\tconst batchConfig = resolveReindexBatchConfig();\n\tlet batchSize = batchConfig.defaultBatchSize;\n\tlet currentHeight = fromBlock;\n\tlet aborted = false;\n\tlet consecutiveEmptyBatches = 0;\n\t// Sparse scan: when a whole batch matches nothing, ask the source for the\n\t// next height that could match and leap there — token-scoped genesis\n\t// reindexes skip the (often vast) majority of chain history.\n\tconst sparse = Boolean(source.nextDataHeight && canSparseScan(def));\n\n\tconst flushHealth = async () => {\n\t\tif (pendingEventsProcessed === 0 && pendingErrors === 0) return;\n\t\tawait recordSubgraphProcessed(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\tpendingEventsProcessed,\n\t\t\tpendingErrors,\n\t\t\tpendingLastError,\n\t\t);\n\t\tpendingEventsProcessed = 0;\n\t\tpendingErrors = 0;\n\t\tpendingLastError = undefined;\n\t\tlastHealthFlushBlock = blocksProcessed;\n\t\tlastHealthFlushAt = Date.now();\n\t};\n\n\t/**\n\t * Stop the walk at an unprocessable block: surface the error, mark the\n\t * subgraph errored, and throw. Deliberately does NOT touch\n\t * last_processed_block — the cursor stays before the failed block so a\n\t * restart re-attempts it instead of silently skipping its events.\n\t */\n\tconst haltRange = async (\n\t\terrorMsg: string,\n\t\theight: number,\n\t): Promise<never> => {\n\t\tpendingErrors++;\n\t\tpendingLastError = errorMsg;\n\t\tawait flushHealth().catch(() => {});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\").catch(() => {});\n\t\tthrow new Error(`${subgraphName}: halted at block ${height}: ${errorMsg}`);\n\t};\n\n\t// Pipeline: start loading first batch and track the prefetched range.\n\t// batchEnd must match what was actually loaded — not recalculated from a\n\t// potentially resized batchSize (adaptive sizing can change it between iterations).\n\tlet nextBatchEnd = Math.min(currentHeight + batchSize - 1, toBlock);\n\tlet nextBatchPromise = source.loadBlockRange(currentHeight, nextBatchEnd);\n\n\twhile (currentHeight <= toBlock) {\n\t\t// Check for abort at batch boundary\n\t\tif (opts.signal?.aborted) {\n\t\t\taborted = true;\n\t\t\tlogger.info(\"Block processing aborted\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tcurrentBlock: currentHeight,\n\t\t\t\treason: String(opts.signal.reason ?? \"unknown\"),\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst batch = await nextBatchPromise;\n\t\tconst batchEnd = nextBatchEnd;\n\n\t\t// Source-health guard (fix-f040 B7): the source seeds every canonical\n\t\t// height in range (including empty blocks), so consecutive fully-empty\n\t\t// batches mean the SOURCE is degraded — not that thousands of blocks\n\t\t// are absent. The old behavior filed every height as a block_missing\n\t\t// gap and kept walking; one degraded source minted thousands of false\n\t\t// gap rows in minutes.\n\t\tif (batch.size === 0 && batchEnd >= currentHeight) {\n\t\t\tconsecutiveEmptyBatches++;\n\t\t\tif (consecutiveEmptyBatches >= EMPTY_BATCH_HALT_THRESHOLD) {\n\t\t\t\tawait haltRange(\n\t\t\t\t\t`block source returned ${consecutiveEmptyBatches} consecutive empty batches (ending ${currentHeight}..${batchEnd}) — source degraded`,\n\t\t\t\t\tcurrentHeight,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tconsecutiveEmptyBatches = 0;\n\t\t}\n\n\t\t// Prefetch next batch (uses current batchSize, which may have been adapted)\n\t\tconst nextStart = batchEnd + 1;\n\t\tif (nextStart <= toBlock) {\n\t\t\tnextBatchEnd = Math.min(nextStart + batchSize - 1, toBlock);\n\t\t\tnextBatchPromise = source.loadBlockRange(nextStart, nextBatchEnd);\n\t\t}\n\n\t\tconst batchFailedBlocks: { height: number; reason: string }[] = [];\n\t\tlet batchMatched = 0;\n\t\t// Reindex is a strictly ascending walk over the subgraph's own cursor, so\n\t\t// written blocks checkpoint atomically and replays skip (fix-f040 B3).\n\t\t// Backfill revisits heights below the live cursor — must stay batched.\n\t\t// Reindex checkpoints on the subgraph cursor; backfill (status 'active')\n\t\t// revisits heights BELOW the live cursor, so it checkpoints on its own\n\t\t// op row instead — and must NEVER write the live cursor (an unconditional\n\t\t// historical SET would regress it and make catch-up re-walk + double-apply).\n\t\tconst opCursor =\n\t\t\tstatus === \"active\" && opts.operationId\n\t\t\t\t? { operationId: opts.operationId }\n\t\t\t\t: undefined;\n\t\tconst atomicProgress = status === \"reindexing\" ? { status } : opCursor;\n\n\t\tfor (let height = currentHeight; height <= batchEnd; height++) {\n\t\t\tlet blockData = batch.get(height);\n\t\t\tif (!blockData) {\n\t\t\t\t// Could be a transient source hiccup — refetch the single height\n\t\t\t\t// before concluding the block is genuinely absent.\n\t\t\t\tblockData = (await source.loadBlockRange(height, height)).get(height);\n\t\t\t}\n\t\t\tif (!blockData) {\n\t\t\t\tif (status === \"reindexing\") {\n\t\t\t\t\t// Strict: a missing source block means every downstream value is\n\t\t\t\t\t// wrong, not approximately right. Halt; do not advance past it.\n\t\t\t\t\tconst errorMsg = `block ${height} missing from source — halting reindex (cursor stays at ${height - 1})`;\n\t\t\t\t\tawait haltRange(errorMsg, height);\n\t\t\t\t}\n\t\t\t\t// Backfill: the range IS the gap-repair pass; record what's still\n\t\t\t\t// missing and keep going.\n\t\t\t\tbatchFailedBlocks.push({ height, reason: \"block_missing\" });\n\t\t\t\tblocksProcessed++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet result: ProcessBlockResult;\n\t\t\ttry {\n\t\t\t\t// Same per-subgraph block lock the live catch-up walk takes, at the\n\t\t\t\t// same granularity (one block's write), so the two walks actually\n\t\t\t\t// contend instead of interleaving writes to the same rows. The\n\t\t\t\t// advisory half is the load-bearing one here: this walk runs under\n\t\t\t\t// the operation runner, which is not leader-gated, so it is\n\t\t\t\t// routinely in a DIFFERENT process from the catch-up leader.\n\t\t\t\t// Backfill runs at status 'active' and never changes it, so catch-up\n\t\t\t\t// never stands down on its own. See catchup.ts for the acquisition\n\t\t\t\t// order these two locks share with the reorg lock.\n\t\t\t\t//\n\t\t\t\t// Locked only when the block can write. This walk always passes\n\t\t\t\t// `skipProgressUpdate`, so a block that matches nothing writes\n\t\t\t\t// NOTHING — not even a cursor — and `matchSources`/factory discovery\n\t\t\t\t// draw exclusively from the txs and events below, so an empty block\n\t\t\t\t// cannot match. That is a property of the preloaded data, not a\n\t\t\t\t// second copy of the matcher's rules. It matters because a\n\t\t\t\t// genesis-era range is overwhelmingly empty blocks, and locking each\n\t\t\t\t// one costs a round trip that buys no serialization. (Catch-up\n\t\t\t\t// cannot take this shortcut: its no-match path still writes the\n\t\t\t\t// cursor, which is exactly what the lock protects there.)\n\t\t\t\tconst mayWrite =\n\t\t\t\t\tblockData.txs.length > 0 ||\n\t\t\t\t\tblockData.events.length > 0 ||\n\t\t\t\t\t(blockData.vmEvents?.length ?? 0) > 0;\n\t\t\t\tconst runBlock = () =>\n\t\t\t\t\tprocessBlockWithRetry(def, subgraphName, height, {\n\t\t\t\t\t\tskipProgressUpdate: true,\n\t\t\t\t\t\tatomicProgress,\n\t\t\t\t\t\tpreloaded: blockData,\n\t\t\t\t\t});\n\t\t\t\tresult = mayWrite\n\t\t\t\t\t? await withSubgraphBlockWriteLock(subgraphName, runBlock)\n\t\t\t\t\t: await runBlock();\n\t\t\t} catch (err) {\n\t\t\t\tconst errorMsg = getErrorMessage(err);\n\t\t\t\tlogger.error(\"Block processing failed persistently\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight: height,\n\t\t\t\t\terror: errorMsg,\n\t\t\t\t});\n\t\t\t\tif (status === \"reindexing\") {\n\t\t\t\t\t// Strict: skipping a block of events silently corrupts every\n\t\t\t\t\t// accumulator downstream. Halt with the cursor still BEFORE the\n\t\t\t\t\t// failed block so a restart re-attempts it (fix-f040 B5).\n\t\t\t\t\tawait haltRange(\n\t\t\t\t\t\t`block ${height} failed persistently: ${errorMsg}`,\n\t\t\t\t\t\theight,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Backfill: record and continue — the gap row keeps it repairable.\n\t\t\t\tbatchFailedBlocks.push({ height, reason: \"processing_error\" });\n\t\t\t\tblocksProcessed++;\n\t\t\t\ttotalErrors++;\n\t\t\t\tpendingErrors++;\n\t\t\t\tpendingLastError = errorMsg;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tblocksProcessed++;\n\t\t\tif (result.skipped) blocksSkippedByCursor++;\n\t\t\tbatchMatched += result.matched;\n\t\t\ttotalEventsProcessed += result.processed;\n\t\t\ttotalErrors += result.errors;\n\t\t\tpendingEventsProcessed += result.processed;\n\t\t\tpendingErrors += result.errors;\n\t\t\tif (result.errors > 0) {\n\t\t\t\tpendingLastError = `${result.errors} error(s) while processing block ${height}`;\n\t\t\t}\n\n\t\t\tif (result.timing) {\n\t\t\t\tstats.record(result.timing, result.processed);\n\t\t\t\tif (stats.shouldFlush()) {\n\t\t\t\t\tawait stats.flush(targetDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst now = Date.now();\n\t\t\tconst shouldFlushProgress =\n\t\t\t\tblocksProcessed % 100 === 0 ||\n\t\t\t\tnow - lastProgressFlushAt >= PROGRESS_FLUSH_INTERVAL_MS;\n\t\t\tif (shouldFlushProgress) {\n\t\t\t\tif (opCursor) {\n\t\t\t\t\t// Covers write-less stretches; conditional → can't regress the\n\t\t\t\t\t// in-tx advances written by processed blocks.\n\t\t\t\t\tawait advanceOperationCursor(targetDb, opCursor.operationId, height);\n\t\t\t\t} else {\n\t\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, status, height);\n\t\t\t\t}\n\t\t\t\tif (opts.operationId) {\n\t\t\t\t\tawait updateOperationProcessedEvents(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\topts.operationId,\n\t\t\t\t\t\ttotalEventsProcessed,\n\t\t\t\t\t).catch(() => {});\n\t\t\t\t}\n\t\t\t\tlastProgressFlushAt = now;\n\t\t\t}\n\n\t\t\tif (blocksProcessed % LOG_INTERVAL === 0) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`${status === \"reindexing\" ? \"Reindex\" : \"Backfill\"} progress`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tprocessed: blocksProcessed,\n\t\t\t\t\t\ttotal: totalBlocks,\n\t\t\t\t\t\tcurrentBlock: height,\n\t\t\t\t\t\tpct: Math.round((blocksProcessed / totalBlocks) * 100),\n\t\t\t\t\t\t...(blocksSkippedByCursor > 0\n\t\t\t\t\t\t\t? { skippedByCursor: blocksSkippedByCursor }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (status === \"reindexing\" && blocksProcessed > 0) {\n\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, status, batchEnd);\n\t\t}\n\n\t\tconst shouldFlushHealth =\n\t\t\tblocksProcessed - lastHealthFlushBlock >= HEALTH_FLUSH_INTERVAL ||\n\t\t\tDate.now() - lastHealthFlushAt >= PROGRESS_FLUSH_INTERVAL_MS;\n\t\tif (shouldFlushHealth) {\n\t\t\tawait flushHealth();\n\t\t}\n\n\t\t// Record any gaps from this batch\n\t\tif (batchFailedBlocks.length > 0 && opts.subgraphId) {\n\t\t\tconst gaps = coalesceFailedBlocks(batchFailedBlocks);\n\t\t\tawait recordGapBatch(targetDb, opts.subgraphId, subgraphName, gaps).catch(\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\tlogger.warn(\"Failed to record subgraph gaps\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\t// Sparse skip: nothing in this batch could match → probe for the next\n\t\t// height that can, and jump the cursor there. The in-flight prefetch is\n\t\t// discarded (one wasted fetch buys skipping arbitrarily many).\n\t\tif (\n\t\t\tsparse &&\n\t\t\tbatchMatched === 0 &&\n\t\t\tbatchEnd < toBlock &&\n\t\t\tsource.nextDataHeight\n\t\t) {\n\t\t\tconst next = await source.nextDataHeight(batchEnd, toBlock);\n\t\t\tconst jumpTo = next === null ? toBlock + 1 : Math.max(next, batchEnd + 1);\n\t\t\tif (jumpTo > batchEnd + 1) {\n\t\t\t\tconst skipped = Math.min(jumpTo, toBlock + 1) - (batchEnd + 1);\n\t\t\t\tblocksProcessed += skipped;\n\t\t\t\tif (opCursor) {\n\t\t\t\t\tawait advanceOperationCursor(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\topCursor.operationId,\n\t\t\t\t\t\tjumpTo - 1,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tawait updateSubgraphStatus(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tjumpTo - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlogger.info(\"Sparse skip\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tfrom: batchEnd + 1,\n\t\t\t\t\tto: jumpTo - 1,\n\t\t\t\t\tskipped,\n\t\t\t\t});\n\t\t\t\tcurrentHeight = jumpTo;\n\t\t\t\tif (currentHeight <= toBlock) {\n\t\t\t\t\tnextBatchEnd = Math.min(currentHeight + batchSize - 1, toBlock);\n\t\t\t\t\tnextBatchPromise = source.loadBlockRange(currentHeight, nextBatchEnd);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Adaptive batch sizing\n\t\tconst avg = avgEventsPerBlock(batch);\n\t\tif (avg > 50)\n\t\t\tbatchSize = Math.max(\n\t\t\t\tMath.round(batchSize * 0.5),\n\t\t\t\tbatchConfig.minBatchSize,\n\t\t\t);\n\t\telse if (avg < 10)\n\t\t\tbatchSize = Math.min(\n\t\t\t\tMath.round(batchSize * 1.5),\n\t\t\t\tbatchConfig.maxBatchSize,\n\t\t\t);\n\n\t\tcurrentHeight = batchEnd + 1;\n\t}\n\n\tawait stats.flush(targetDb);\n\tawait flushHealth();\n\treturn { blocksProcessed, totalEventsProcessed, totalErrors, aborted };\n}\n\n/**\n * Resolve the reindex walk range. Always the whole subgraph:\n * `[def.startBlock, chain tip]`. Chain tip reads from `index_progress` —\n * lives in the source DB.\n *\n * Reindex drops the schema unconditionally, so the walk range is also the\n * ONLY data that survives. A narrower walk therefore does not \"reindex a\n * range\" — it silently destroys every row outside it while leaving the\n * subgraph reporting `active` at chain tip (f079: a single-block\n * `--from-block N --to-block N` emptied sbtc-flows, and the first recovery\n * attempt rebuilt only 21% of its history). Ranged, additive work is\n * `backfillSubgraph`'s job.\n *\n * `startBlockFloor` is a plan-policy floor, not a range: it can only raise\n * the start block, never lower it, and never bounds the end.\n */\nexport async function resolveBlockRange(\n\tsource: BlockSource,\n\tdef: SubgraphDefinition,\n\topts?: ReindexOptions,\n): Promise<{ fromBlock: number; toBlock: number }> {\n\tconst definitionStart = def.startBlock ?? 1;\n\tconst fromBlock =\n\t\topts?.startBlockFloor != null\n\t\t\t? Math.max(definitionStart, opts.startBlockFloor)\n\t\t\t: definitionStart;\n\tconst rawTip = await source.getTip();\n\tif (!usesDecodedIndexPlane(def)) {\n\t\treturn { fromBlock, toBlock: rawTip };\n\t}\n\tconst bound = await boundSourceTip(rawTip, decoderNamesForSubgraph(def));\n\tif (!bound.ok) {\n\t\tlogger.warn(\"Reindex stalled: missing decoder checkpoint\", {\n\t\t\tevent: \"subgraph_reindex_decoder_stall\",\n\t\t\tsubgraph: def.name,\n\t\t\tmissing: bound.missing,\n\t\t});\n\t\tthrow new Error(\n\t\t\t`Reindex stalled: missing decoder checkpoint (${bound.missing.join(\", \")})`,\n\t\t);\n\t}\n\tif (bound.floor !== null && bound.floor < rawTip) {\n\t\tlogger.debug(\"Reindex tip bounded by decoder progress\", {\n\t\t\tevent: \"subgraph_reindex_decoder_floor\",\n\t\t\tsubgraph: def.name,\n\t\t\trawTip,\n\t\t\tfloor: bound.floor,\n\t\t\ttip: bound.tip,\n\t\t});\n\t}\n\treturn { fromBlock, toBlock: bound.tip };\n}\n\n/**\n * Clear reindex metadata columns after completion or cancellation.\n */\nasync function clearReindexMetadata(\n\tdb: ReturnType<typeof getTargetDb>,\n\tsubgraphName: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({ reindex_from_block: null, reindex_to_block: null })\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.execute();\n}\n\n/**\n * Reindex a subgraph by dropping its tables, recreating them, and reprocessing\n * all historical blocks through the handler pipeline.\n *\n * Always whole-subgraph: `[start_block, chain tip]`. There is no ranged\n * reindex — the drop cannot be scoped to a range without re-running delta\n * handlers (`ctx.increment` / `ctx.update` / `ctx.patchOrInsert`) over rows\n * that were never removed, which is the exact double-count hazard `backfill`\n * already refuses. Use `backfillSubgraph` for ranged, additive work.\n *\n * Supports cancellation via AbortSignal — on shutdown abort, status stays\n * \"reindexing\" for auto-resume; on user cancel, status resets to \"active\".\n */\nexport async function reindexSubgraph(\n\tdef: SubgraphDefinition,\n\topts?: ReindexOptions,\n): Promise<{ processed: number }> {\n\t// Chain tip reads hit the block source; subgraph rows + tenant schemas live in target\n\tconst source = resolveBlockSource(def);\n\tconst targetDb = getTargetDb();\n\tconst client = getRawClient(\"target\");\n\tconst subgraphName = def.name;\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(subgraphName);\n\n\tawait updateSubgraphStatus(targetDb, subgraphName, \"reindexing\");\n\tlogger.info(\"Reindex starting\", { subgraph: subgraphName });\n\n\ttry {\n\t\t// Resolve block range BEFORE schema drop so we can persist metadata\n\t\tconst { fromBlock, toBlock } = await resolveBlockRange(source, def, opts);\n\n\t\tif (fromBlock > toBlock) {\n\t\t\tlogger.info(\"No blocks to reindex\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tfromBlock,\n\t\t\t\ttoBlock,\n\t\t\t});\n\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", 0);\n\t\t\treturn { processed: 0 };\n\t\t}\n\n\t\t// Drop and recreate schema + tables (tenant-side DDL)\n\t\tawait client.unsafe(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`);\n\t\tconst { statements } = generateSubgraphSQL(def, schemaName);\n\t\tfor (const stmt of statements) {\n\t\t\tawait client.unsafe(stmt);\n\t\t}\n\t\t// The schema drop just invalidated everything the cursor claims was\n\t\t// applied. Reset it BELOW the walk's start or the atomicProgress replay\n\t\t// guard treats a stale cursor (prior halted/cancelled run) as \"already\n\t\t// applied\" and silently skips the entire prefix — empty tables, then a\n\t\t// CHECK violation at the first real delta (the sbtc-balances halt at\n\t\t// block 1913668: 1.9M credit blocks skipped against a 1913667 cursor).\n\t\tawait updateSubgraphStatus(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\t\"reindexing\",\n\t\t\tMath.max(0, fromBlock - 1),\n\t\t);\n\t\tlogger.info(\"Schema recreated for reindex\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tcursorResetTo: Math.max(0, fromBlock - 1),\n\t\t});\n\n\t\t// Store reindex range after DDL is ready. A crash before this point falls\n\t\t// back to a fresh reindex, which safely drops/recreates the schema again.\n\t\tawait targetDb\n\t\t\t.updateTable(\"subgraphs\")\n\t\t\t.set({\n\t\t\t\tlast_processed_block: initialReindexProgressBlock(fromBlock),\n\t\t\t\treindex_from_block: fromBlock,\n\t\t\t\treindex_to_block: toBlock,\n\t\t\t\ttotal_processed: 0,\n\t\t\t\ttotal_errors: 0,\n\t\t\t\tlast_error: null,\n\t\t\t\tlast_error_at: null,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t})\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.execute();\n\n\t\tlogger.info(\"Reindexing blocks\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\ttotalBlocks: toBlock - fromBlock + 1,\n\t\t});\n\n\t\tconst subgraphRow = await targetDb\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select([\"id\"])\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.executeTakeFirst();\n\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\tstatus: \"reindexing\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: subgraphRow?.id,\n\t\t\toperationId: opts?.operationId,\n\t\t\tsignal: opts?.signal,\n\t\t});\n\n\t\t// Handle abort\n\t\tif (result.aborted) {\n\t\t\tconst reason = String(opts?.signal?.reason ?? \"unknown\");\n\t\t\tif (reason === \"user-cancelled\") {\n\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\");\n\t\t\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\t\t\tlogger.info(\"Reindex cancelled by user\", { subgraph: subgraphName });\n\t\t\t} else {\n\t\t\t\t// shutdown — leave status as \"reindexing\" for auto-resume\n\t\t\t\tlogger.info(\"Reindex interrupted by shutdown, will resume\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\tlogger.info(\"Reindex complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\t// Fire-and-forget — never delay or fail the reindex on a notify hiccup.\n\t\tvoid notifyReindexComplete(targetDb, subgraphName, {\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Reindex failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\");\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resume a previously interrupted reindex. Skips schema drop (already done)\n * and continues from last_processed_block + 1.\n */\nexport async function resumeReindex(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tschemaName: string;\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{ processed: number }> {\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.select([\n\t\t\t\"id\",\n\t\t\t\"last_processed_block\",\n\t\t\t\"reindex_from_block\",\n\t\t\t\"reindex_to_block\",\n\t\t])\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\n\tif (!row) throw new Error(`Subgraph \"${subgraphName}\" not found`);\n\n\tconst fromBlock = resolveReindexResumeBlock(row);\n\tconst toBlock = Number(row.reindex_to_block);\n\n\t// Legacy: no reindex metadata — fall back to full reindex\n\tif (fromBlock == null) {\n\t\tlogger.info(\"No reindex metadata, starting fresh reindex\", {\n\t\t\tsubgraph: subgraphName,\n\t\t});\n\t\treturn reindexSubgraph(def, {\n\t\t\tschemaName: opts.schemaName,\n\t\t\tsignal: opts.signal,\n\t\t});\n\t}\n\n\tif (fromBlock > toBlock) {\n\t\tlogger.info(\"Resume: no remaining blocks\", { subgraph: subgraphName });\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\treturn { processed: 0 };\n\t}\n\n\tlogger.info(\"Resuming reindex\", {\n\t\tsubgraph: subgraphName,\n\t\tfromBlock,\n\t\ttoBlock,\n\t\tremaining: toBlock - fromBlock + 1,\n\t});\n\n\ttry {\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock,\n\t\t\ttoBlock,\n\t\t\tstatus: \"reindexing\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: row.id,\n\t\t\toperationId: opts.operationId,\n\t\t\tsignal: opts.signal,\n\t\t});\n\n\t\tif (result.aborted) {\n\t\t\tconst reason = String(opts.signal?.reason ?? \"unknown\");\n\t\t\tif (reason === \"user-cancelled\") {\n\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\");\n\t\t\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\t\t\tlogger.info(\"Resume cancelled by user\", { subgraph: subgraphName });\n\t\t\t} else {\n\t\t\t\tlogger.info(\"Resume interrupted by shutdown, will resume again\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"active\", toBlock);\n\t\tawait clearReindexMetadata(targetDb, subgraphName);\n\t\tlogger.info(\"Resumed reindex complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Resumed reindex failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\");\n\t\tthrow err;\n\t}\n}\n\n/**\n * Backfill a subgraph by re-processing a block range WITHOUT dropping the schema.\n * Uses upserts so existing data is updated, not duplicated. Safe to run while\n * the subgraph is actively syncing.\n */\nexport async function backfillSubgraph(\n\tdef: SubgraphDefinition,\n\topts: {\n\t\tfromBlock: number;\n\t\ttoBlock: number;\n\t\tschemaName?: string;\n\t\toperationId?: string;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<{ processed: number }> {\n\tconst targetDb = getTargetDb();\n\tconst subgraphName = def.name;\n\n\tlogger.info(\"Backfill starting\", {\n\t\tsubgraph: subgraphName,\n\t\tfrom: opts.fromBlock,\n\t\tto: opts.toBlock,\n\t});\n\n\ttry {\n\t\tconst subgraphRow = await targetDb\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select([\"id\"])\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.executeTakeFirst();\n\n\t\tconst result = await processBlockRange(def, {\n\t\t\tfromBlock: opts.fromBlock,\n\t\t\ttoBlock: opts.toBlock,\n\t\t\tstatus: \"active\",\n\t\t\tisCatchup: false,\n\t\t\tapiKeyId: null,\n\t\t\tsubgraphId: subgraphRow?.id,\n\t\t\toperationId: opts.operationId,\n\t\t\tsignal: opts.signal,\n\t\t});\n\n\t\tif (result.aborted) {\n\t\t\tlogger.info(\"Backfill aborted\", { subgraph: subgraphName });\n\t\t\treturn { processed: result.blocksProcessed };\n\t\t}\n\n\t\t// Resolve any gaps within the backfilled range\n\t\tconst resolved = await resolveGaps(\n\t\t\ttargetDb,\n\t\t\tsubgraphName,\n\t\t\topts.fromBlock,\n\t\t\topts.toBlock,\n\t\t).catch(() => 0);\n\t\tif (resolved > 0) {\n\t\t\tlogger.info(\"Resolved subgraph gaps via backfill\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tresolved,\n\t\t\t});\n\t\t}\n\n\t\tlogger.info(\"Backfill complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tblocks: result.blocksProcessed,\n\t\t\tevents: result.totalEventsProcessed,\n\t\t\terrors: result.totalErrors,\n\t\t});\n\t\treturn { processed: result.blocksProcessed };\n\t} catch (err) {\n\t\tlogger.error(\"Backfill failed\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t\tthrow err;\n\t}\n}\n",
33
33
  "import { getErrorMessage } from \"@secondlayer/shared\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { Kysely } from \"kysely\";\n\n/**\n * Email an account when their subgraph's reindex/backfill finishes — the\n * counterpart to the CLI/dashboard ETA (they still had to leave a terminal or\n * tab open to see either). Fire-and-forget: a failed send only logs a\n * warning, never fails or retries against the reindex itself.\n *\n * Mirrors the Resend pattern in\n * `packages/worker/src/jobs/spend-cap-alert.ts` (`sendCapAlert`) — same env\n * vars, same \"log and skip\" behavior when unconfigured.\n */\nexport async function notifyReindexComplete(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n\tstats: { blocks: number; events: number; errors: number },\n): Promise<void> {\n\ttry {\n\t\tconst subgraph = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select([\"account_id\"])\n\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t.executeTakeFirst();\n\t\tif (!subgraph) return;\n\n\t\tconst account = await db\n\t\t\t.selectFrom(\"accounts\")\n\t\t\t.select([\"email\", \"notify_reindex_complete\"])\n\t\t\t.where(\"id\", \"=\", subgraph.account_id)\n\t\t\t.executeTakeFirst();\n\t\tif (!account?.email || !account.notify_reindex_complete) return;\n\n\t\tconst resendKey = process.env.RESEND_API_KEY;\n\t\tif (!resendKey) {\n\t\t\tlogger.warn(\"RESEND_API_KEY unset — skipping reindex-complete email\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst from =\n\t\t\tprocess.env.EMAIL_FROM ?? \"Secondlayer <noreply@secondlayer.tools>\";\n\t\tconst body =\n\t\t\tstats.errors > 0\n\t\t\t\t? `Your subgraph \"${subgraphName}\" finished reindexing — ${stats.blocks.toLocaleString()} blocks, ${stats.events.toLocaleString()} events, ${stats.errors.toLocaleString()} errors. Check the dashboard for details.`\n\t\t\t\t: `Your subgraph \"${subgraphName}\" finished reindexing — ${stats.blocks.toLocaleString()} blocks, ${stats.events.toLocaleString()} events processed, no errors. It's live now.`;\n\n\t\tconst res = await fetch(\"https://api.resend.com/emails\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${resendKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tfrom,\n\t\t\t\tto: [account.email],\n\t\t\t\tsubject: `Reindex complete: ${subgraphName}`,\n\t\t\t\ttext: body,\n\t\t\t}),\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tconst text = await res.text().catch(() => \"\");\n\t\t\tlogger.warn(\"reindex-complete email failed\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tstatus: res.status,\n\t\t\t\tbody: text.slice(0, 200),\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\t// Never let a notification failure affect the reindex result.\n\t\tlogger.warn(\"reindex-complete email threw\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\terror: getErrorMessage(err),\n\t\t});\n\t}\n}\n",
34
34
  "import type { AnyEvent, EventForFilter } from \"./events.ts\";\nimport type { TypedSubgraphContext } from \"./infer.ts\";\nimport type {\n\tMaterializeSpec,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphSchema,\n} from \"./types.ts\";\n\ntype HandlerFn<F extends SubgraphFilter, S extends SubgraphSchema> = (\n\tevent: EventForFilter<F>,\n\tctx: TypedSubgraphContext<S>,\n) => void | Promise<void>;\n\ntype SourceHasMaterialize<F> = F extends { materialize: MaterializeSpec }\n\t? true\n\t: false;\n\n/**\n * Handlers keyed by source name. Each handler's `event` is typed from the\n * matching source's filter `type` (e.g. a `print_event` source → `event.topic`\n * is a `string`), and `ctx` is typed against the subgraph `schema` (table\n * names + row columns checked). Sources with `materialize` may omit a\n * handler; every other source key is required. Optional `\"*\"` catch-all\n * receives any event (validate also accepts `*` alone).\n */\nexport type TypedHandlers<\n\tSources extends Record<string, SubgraphFilter>,\n\tS extends SubgraphSchema,\n> = {\n\t[K in keyof Sources as SourceHasMaterialize<Sources[K]> extends true\n\t\t? never\n\t\t: K]-?: HandlerFn<Sources[K], S>;\n} & {\n\t[K in keyof Sources as SourceHasMaterialize<Sources[K]> extends true\n\t\t? K\n\t\t: never]?: HandlerFn<Sources[K], S>;\n} & {\n\t\"*\"?: (event: AnyEvent, ctx: TypedSubgraphContext<S>) => void | Promise<void>;\n};\n\n/** Subgraph definition with `sources`/`schema` literals preserved for typed\n * handlers and downstream query-client inference (`getSubgraph`). */\nexport type TypedSubgraphDefinition<\n\tSources extends Record<string, SubgraphFilter>,\n\tS extends SubgraphSchema,\n> = Omit<SubgraphDefinition, \"sources\" | \"schema\" | \"handlers\"> & {\n\tsources: Sources;\n\tschema: S;\n\thandlers: TypedHandlers<Sources, S>;\n};\n\n/**\n * Identity function that preserves `sources` and `schema` literal types so\n * handlers are typed per source and the schema drives query-client inference.\n *\n * @example\n * ```ts\n * export default defineSubgraph({\n * name: \"my-subgraph\",\n * sources: { transfer: { type: \"ft_transfer\", assetIdentifier: \"SP...::token\" } },\n * schema: { transfers: { columns: { amount: { type: \"uint\" } } } },\n * handlers: {\n * transfer: (event, ctx) => {\n * // event: FtTransferPayload → event.amount is bigint, no cast\n * ctx.insert(\"transfers\", { amount: event.amount });\n * },\n * },\n * });\n * ```\n */\nexport function defineSubgraph<\n\tconst Sources extends Record<string, SubgraphFilter>,\n\tconst S extends SubgraphSchema,\n>(\n\tdef: TypedSubgraphDefinition<Sources, S>,\n): TypedSubgraphDefinition<Sources, S> {\n\treturn def;\n}\n\n/**\n * Identity helper that preserves a schema literal's exact types so it can be\n * HOISTED out of the `defineSubgraph()` call and reused:\n *\n * ```ts\n * export const schema = defineSchema({\n * balances: {\n * columns: { holder: { type: \"principal\" }, amount: { type: \"uint\" } },\n * uniqueKeys: [[\"holder\"]],\n * },\n * });\n *\n * // An extracted helper keeps the full typed surface — table names and row\n * // columns are still checked:\n * function credit(ctx: TypedSubgraphContext<typeof schema>, holder: string) {\n * ctx.increment(\"balances\", { holder }, { amount: 1n });\n * }\n *\n * export default defineSubgraph({ name: \"balances\", schema, sources, handlers });\n * ```\n *\n * `as const` alone does not work here (it produces `readonly` arrays that a\n * mutable `uniqueKeys` rejected) and a bare literal widens `type` to `string`.\n * That gap is why the shipped starter typed its helper `ctx: any` — and in\n * doing so modelled a non-commutative read-modify-write the docs warn against.\n */\nexport function defineSchema<const S extends SubgraphSchema>(schema: S): S {\n\treturn schema;\n}\n\n/**\n * The typed handler context for a subgraph definition — for annotating\n * helpers extracted out of a handler:\n *\n * ```ts\n * const def = defineSubgraph({ … });\n * function credit(ctx: InferContext<typeof def>) { … }\n * ```\n *\n * Prefer `TypedSubgraphContext<typeof schema>` when the schema is hoisted;\n * this is the form for when only the definition is in scope.\n */\nexport type InferContext<D> = D extends {\n\tschema: infer S extends SubgraphSchema;\n}\n\t? TypedSubgraphContext<S>\n\t: never;\n",
35
35
  "import type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pascalCase, pgSchemaName, snakeToCamel } from \"./utils.ts\";\n\n/**\n * Generate a `schema.prisma` from a subgraph definition. Pairs with the BYO data\n * plane: once a subgraph's decoded rows land in the user's own Postgres, this\n * emits the Prisma models so they get a fully-typed ORM (joins, relations,\n * transactions) over their own data — the \"Prisma wrapper for Stacks\" without us\n * shipping an ORM. Output mirrors the DDL in `generator.ts` so `prisma db pull`\n * against a deployed schema produces a matching model (no drift).\n */\n\n/** Clarity/subgraph column type → Prisma field type + optional `@db` native type. */\nconst PRISMA_TYPE: Record<ColumnType, { type: string; db?: string }> = {\n\t// uint128/int128 exceed JS/Prisma BigInt-safe range — Decimal is lossless.\n\tuint: { type: \"Decimal\", db: \"@db.Numeric\" },\n\tint: { type: \"Decimal\", db: \"@db.Numeric\" },\n\ttext: { type: \"String\" },\n\tprincipal: { type: \"String\" },\n\tboolean: { type: \"Boolean\" },\n\ttimestamp: { type: \"DateTime\", db: \"@db.Timestamptz\" },\n\tjsonb: { type: \"Json\" },\n};\n\n/** System columns every subgraph table gets (kept in sync with generator.ts). */\nconst SYSTEM_FIELDS: Array<{ field: string; col: string; line: string }> = [\n\t{ field: \"id\", col: \"_id\", line: \"BigInt @id @default(autoincrement())\" },\n\t{ field: \"blockHeight\", col: \"_block_height\", line: \"BigInt\" },\n\t{ field: \"txId\", col: \"_tx_id\", line: \"String\" },\n\t{\n\t\tfield: \"createdAt\",\n\t\tcol: \"_created_at\",\n\t\tline: \"DateTime @default(now()) @db.Timestamptz\",\n\t},\n];\n\nfunction quotePrismaDefault(value: string | number | boolean): string {\n\tif (typeof value === \"string\")\n\t\treturn `@default(\"${value.replace(/\"/g, '\\\\\"')}\")`;\n\treturn `@default(${value})`;\n}\n\n/** A back-relation field another table's relation induces on this one. */\ninterface BackRelation {\n\tfield: string;\n\tmodel: string;\n\trelationName: string;\n}\n\nfunction renderTable(\n\ttableName: string,\n\ttable: SubgraphTable,\n\tbackRelations: BackRelation[],\n): string {\n\tconst lines: string[] = [];\n\n\tfor (const sys of SYSTEM_FIELDS) {\n\t\tlines.push(` ${sys.field} ${sys.line} @map(\"${sys.col}\")`);\n\t}\n\n\tfor (const [colName, col] of Object.entries(table.columns)) {\n\t\tconst field = snakeToCamel(colName);\n\t\tconst mapped = PRISMA_TYPE[col.type];\n\t\tconst optional = col.nullable ? \"?\" : \"\";\n\t\tconst attrs: string[] = [];\n\t\tif (field !== colName) attrs.push(`@map(\"${colName}\")`);\n\t\tif (col.default !== undefined) attrs.push(quotePrismaDefault(col.default));\n\t\tif (mapped.db) attrs.push(mapped.db);\n\t\tlines.push(\n\t\t\t` ${field} ${mapped.type}${optional}${attrs.length ? ` ${attrs.join(\" \")}` : \"\"}`,\n\t\t);\n\t}\n\n\t// Forward relations (this table owns the FK).\n\tfor (const rel of table.relations ?? []) {\n\t\tconst optional = rel.fields.some((f) => table.columns[f]?.nullable)\n\t\t\t? \"?\"\n\t\t\t: \"\";\n\t\tconst relName = `${pascalCase(tableName)}_${rel.name}`;\n\t\tconst fields = rel.fields.map(snakeToCamel).join(\", \");\n\t\tconst refs = rel.referencedColumns.map(snakeToCamel).join(\", \");\n\t\tlines.push(\n\t\t\t` ${rel.name} ${pascalCase(rel.references)}${optional} @relation(\"${relName}\", fields: [${fields}], references: [${refs}])`,\n\t\t);\n\t}\n\n\t// Back relations (another table points here) — Prisma needs both sides.\n\tfor (const back of backRelations) {\n\t\tlines.push(\n\t\t\t` ${back.field} ${back.model}[] @relation(\"${back.relationName}\")`,\n\t\t);\n\t}\n\n\t// Block attributes: per-column @@index, composite @@index, @@unique.\n\tconst block: string[] = [];\n\tfor (const [colName, col] of Object.entries(table.columns)) {\n\t\tif (col.indexed) block.push(` @@index([${snakeToCamel(colName)}])`);\n\t}\n\tfor (const cols of table.indexes ?? []) {\n\t\tblock.push(` @@index([${cols.map(snakeToCamel).join(\", \")}])`);\n\t}\n\tfor (const cols of table.uniqueKeys ?? []) {\n\t\tblock.push(` @@unique([${cols.map(snakeToCamel).join(\", \")}])`);\n\t}\n\tblock.push(` @@map(\"${tableName}\")`);\n\n\treturn `model ${pascalCase(tableName)} {\\n${lines.join(\"\\n\")}\\n\\n${block.join(\"\\n\")}\\n}`;\n}\n\n/** Compute the back-relation field each table receives from others' relations. */\nfunction computeBackRelations(\n\tschema: Record<string, SubgraphTable>,\n): Map<string, BackRelation[]> {\n\tconst map = new Map<string, BackRelation[]>();\n\tfor (const [owningTable, table] of Object.entries(schema)) {\n\t\tfor (const rel of table.relations ?? []) {\n\t\t\tconst list = map.get(rel.references) ?? [];\n\t\t\tlist.push({\n\t\t\t\tfield: `${snakeToCamel(owningTable)}${pascalCase(rel.name)}`,\n\t\t\t\tmodel: pascalCase(owningTable),\n\t\t\t\trelationName: `${pascalCase(owningTable)}_${rel.name}`,\n\t\t\t});\n\t\t\tmap.set(rel.references, list);\n\t\t}\n\t}\n\treturn map;\n}\n\nexport interface PrismaGenOptions {\n\t/** Postgres schema the tables live in (account-scoped). */\n\tschemaName?: string;\n\t/** env var the datasource url reads from. */\n\tdatasourceEnv?: string;\n\t/**\n\t * Emit only the `model` blocks (no datasource/generator). Lets users compose\n\t * these models with their own schema via Prisma's `prismaSchemaFolder`.\n\t */\n\tmodelsOnly?: boolean;\n}\n\nexport function generatePrismaSchema(\n\tdef: SubgraphDefinition,\n\topts: PrismaGenOptions = {},\n): string {\n\tconst schemaName = opts.schemaName ?? pgSchemaName(def.name);\n\tconst env = opts.datasourceEnv ?? \"DATABASE_URL\";\n\n\tconst header = [\n\t\t`// Generated by \\`sl codegen subgraph --target prisma\\` from subgraph \"${def.name}\". Do not edit by hand.`,\n\t\t\"\",\n\t\t\"datasource db {\",\n\t\t' provider = \"postgresql\"',\n\t\t` url = env(\"${env}\")`,\n\t\t` schemas = [\"${schemaName}\"]`,\n\t\t\"}\",\n\t\t\"\",\n\t\t\"generator client {\",\n\t\t' provider = \"prisma-client-js\"',\n\t\t' previewFeatures = [\"multiSchema\"]',\n\t\t\"}\",\n\t].join(\"\\n\");\n\n\t// Fold @@schema into each model block (it must live inside the block).\n\tconst backRelations = computeBackRelations(def.schema);\n\tconst modelBlocks = Object.entries(def.schema).map(([tableName, table]) => {\n\t\tconst body = renderTable(\n\t\t\ttableName,\n\t\t\ttable,\n\t\t\tbackRelations.get(tableName) ?? [],\n\t\t);\n\t\treturn body.replace(/\\n}$/, `\\n @@schema(\"${schemaName}\")\\n}`);\n\t});\n\n\tif (opts.modelsOnly) return `${modelBlocks.join(\"\\n\\n\")}\\n`;\n\treturn `${header}\\n\\n${modelBlocks.join(\"\\n\\n\")}\\n`;\n}\n",
36
36
  "import type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pascalCase, pgSchemaName, snakeToCamel } from \"./utils.ts\";\n\n/**\n * Generate a Drizzle schema from a subgraph definition — the Drizzle arm of the\n * \"Prisma wrapper for Stacks\" story. Emits `pgSchema().table()` defs, `relations()`\n * (so the relational query API `db.query.x.findMany({ with: {…} })` works), and\n * `$inferSelect` row types. Like the Prisma generator, output mirrors the deployed\n * DDL — these tables are processor-written and owned by the BYO deploy, so treat\n * them read-only and never `drizzle-kit push`.\n */\n\n/** Subgraph column type → Drizzle pg-core builder. */\nconst DRIZZLE_BUILDER: Record<ColumnType, (col: string) => string> = {\n\t// numeric() returns string in Drizzle — lossless for Clarity uint128/int128.\n\tuint: (c) => `numeric(\"${c}\")`,\n\tint: (c) => `numeric(\"${c}\")`,\n\ttext: (c) => `text(\"${c}\")`,\n\tprincipal: (c) => `text(\"${c}\")`,\n\tboolean: (c) => `boolean(\"${c}\")`,\n\ttimestamp: (c) => `timestamp(\"${c}\", { withTimezone: true })`,\n\tjsonb: (c) => `jsonb(\"${c}\")`,\n};\n\nconst BUILDERS_USED: Record<ColumnType, string> = {\n\tuint: \"numeric\",\n\tint: \"numeric\",\n\ttext: \"text\",\n\tprincipal: \"text\",\n\tboolean: \"boolean\",\n\ttimestamp: \"timestamp\",\n\tjsonb: \"jsonb\",\n};\n\nfunction literalDefault(value: string | number | boolean): string {\n\treturn typeof value === \"string\"\n\t\t? `\"${value.replace(/\"/g, '\\\\\"')}\"`\n\t\t: `${value}`;\n}\n\nfunction renderTable(\n\tvarName: string,\n\ttableName: string,\n\ttable: SubgraphTable,\n): string {\n\tconst cols: string[] = [\n\t\t` id: bigserial(\"_id\", { mode: \"bigint\" }).primaryKey(),`,\n\t\t` blockHeight: bigint(\"_block_height\", { mode: \"bigint\" }).notNull(),`,\n\t\t` txId: text(\"_tx_id\").notNull(),`,\n\t\t` createdAt: timestamp(\"_created_at\", { withTimezone: true }).notNull().defaultNow(),`,\n\t];\n\tfor (const [colName, col] of Object.entries(table.columns)) {\n\t\tlet line = ` ${snakeToCamel(colName)}: ${DRIZZLE_BUILDER[col.type](colName)}`;\n\t\tif (!col.nullable) line += \".notNull()\";\n\t\tif (col.default !== undefined)\n\t\t\tline += `.default(${literalDefault(col.default)})`;\n\t\tcols.push(`${line},`);\n\t}\n\n\t// Third-arg table extras: indexes + unique constraints.\n\tconst extras: string[] = [];\n\tfor (const [colName, col] of Object.entries(table.columns)) {\n\t\tif (col.indexed) {\n\t\t\tconst f = snakeToCamel(colName);\n\t\t\textras.push(\n\t\t\t\t` ${f}Idx: index(\"idx_${tableName}_${colName}\").on(t.${f})`,\n\t\t\t);\n\t\t}\n\t}\n\ttable.indexes?.forEach((idxCols, i) => {\n\t\tconst on = idxCols.map((c) => `t.${snakeToCamel(c)}`).join(\", \");\n\t\textras.push(` idx${i}: index(\"idx_${tableName}_${i}\").on(${on})`);\n\t});\n\ttable.uniqueKeys?.forEach((uqCols, i) => {\n\t\tconst on = uqCols.map((c) => `t.${snakeToCamel(c)}`).join(\", \");\n\t\textras.push(` uq${i}: uniqueIndex(\"uq_${tableName}_${i}\").on(${on})`);\n\t});\n\n\tconst extrasBlock = extras.length\n\t\t? `, (t) => ({\\n${extras.join(\",\\n\")},\\n })`\n\t\t: \"\";\n\treturn `export const ${varName} = sg.table(\"${tableName}\", {\\n${cols.join(\"\\n\")}\\n}${extrasBlock});`;\n}\n\nfunction renderRelations(schema: Record<string, SubgraphTable>): string[] {\n\t// Back-relations: target table → list of owning tables referencing it.\n\tconst back = new Map<string, Array<{ field: string; from: string }>>();\n\tfor (const [owning, table] of Object.entries(schema)) {\n\t\tfor (const rel of table.relations ?? []) {\n\t\t\tconst list = back.get(rel.references) ?? [];\n\t\t\tlist.push({\n\t\t\t\tfield: `${snakeToCamel(owning)}${pascalCase(rel.name)}`,\n\t\t\t\tfrom: snakeToCamel(owning),\n\t\t\t});\n\t\t\tback.set(rel.references, list);\n\t\t}\n\t}\n\n\tconst out: string[] = [];\n\tfor (const [tableName, table] of Object.entries(schema)) {\n\t\tconst v = snakeToCamel(tableName);\n\t\tconst ones = (table.relations ?? []).map((rel) => {\n\t\t\tconst localFields = rel.fields\n\t\t\t\t.map((f) => `${v}.${snakeToCamel(f)}`)\n\t\t\t\t.join(\", \");\n\t\t\tconst refFields = rel.referencedColumns\n\t\t\t\t.map((c) => `${snakeToCamel(rel.references)}.${snakeToCamel(c)}`)\n\t\t\t\t.join(\", \");\n\t\t\treturn ` ${rel.name}: one(${snakeToCamel(rel.references)}, { fields: [${localFields}], references: [${refFields}] }),`;\n\t\t});\n\t\tconst manys = (back.get(tableName) ?? []).map(\n\t\t\t(b) => ` ${b.field}: many(${b.from}),`,\n\t\t);\n\t\tif (ones.length === 0 && manys.length === 0) continue;\n\t\tconst helpers = [ones.length ? \"one\" : \"\", manys.length ? \"many\" : \"\"]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\", \");\n\t\tout.push(\n\t\t\t`export const ${v}Relations = relations(${v}, ({ ${helpers} }) => ({\\n${[...ones, ...manys].join(\"\\n\")}\\n}));`,\n\t\t);\n\t}\n\treturn out;\n}\n\nexport interface DrizzleGenOptions {\n\tschemaName?: string;\n}\n\nexport function generateDrizzleSchema(\n\tdef: SubgraphDefinition,\n\topts: DrizzleGenOptions = {},\n): string {\n\tconst schemaName = opts.schemaName ?? pgSchemaName(def.name);\n\n\t// Only import the column builders actually used (+ always-used system ones).\n\tconst used = new Set<string>([\"bigserial\", \"bigint\", \"text\", \"timestamp\"]);\n\tlet needsIndex = false;\n\tlet needsUnique = false;\n\tfor (const table of Object.values(def.schema)) {\n\t\tfor (const col of Object.values(table.columns))\n\t\t\tused.add(BUILDERS_USED[col.type]);\n\t\tif (\n\t\t\tObject.values(table.columns).some((c) => c.indexed) ||\n\t\t\ttable.indexes?.length\n\t\t)\n\t\t\tneedsIndex = true;\n\t\tif (table.uniqueKeys?.length) needsUnique = true;\n\t}\n\tif (needsIndex) used.add(\"index\");\n\tif (needsUnique) used.add(\"uniqueIndex\");\n\tused.add(\"pgSchema\");\n\n\tconst hasRelations = Object.values(def.schema).some(\n\t\t(t) => t.relations?.length,\n\t);\n\tconst imports = [\n\t\t`import { ${[...used].sort().join(\", \")} } from \"drizzle-orm/pg-core\";`,\n\t\t...(hasRelations ? [`import { relations } from \"drizzle-orm\";`] : []),\n\t].join(\"\\n\");\n\n\tconst tables = Object.entries(def.schema).map(([name, table]) =>\n\t\trenderTable(snakeToCamel(name), name, table),\n\t);\n\tconst relationDecls = renderRelations(def.schema);\n\tconst typeExports = Object.keys(def.schema).map(\n\t\t(name) =>\n\t\t\t`export type ${pascalCase(name)} = typeof ${snakeToCamel(name)}.$inferSelect;`,\n\t);\n\n\treturn [\n\t\t`// Generated by \\`sl codegen subgraph --target drizzle\\` from subgraph \"${def.name}\". Do not edit by hand.`,\n\t\timports,\n\t\t\"\",\n\t\t`export const sg = pgSchema(\"${schemaName}\");`,\n\t\t\"\",\n\t\ttables.join(\"\\n\\n\"),\n\t\t...(relationDecls.length ? [\"\", relationDecls.join(\"\\n\\n\")] : []),\n\t\t\"\",\n\t\ttypeExports.join(\"\\n\"),\n\t\t\"\",\n\t].join(\"\\n\");\n}\n",
37
37
  "import type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pascalCase, pgSchemaName } from \"./utils.ts\";\n\n/**\n * Generate Kysely table interfaces from a subgraph definition — the Kysely arm of\n * the \"Prisma wrapper for Stacks\" story (alongside prisma.ts/drizzle.ts). Emits a\n * per-table interface plus a `DB` registry keyed by schema-qualified table name,\n * so `new Kysely<DB>()` gives fully-typed query building over BYO decoded rows.\n * Output mirrors the deployed DDL in generator.ts — tables are processor-written,\n * so treat them read-only. Column keys stay as the real DB names (Kysely maps to\n * physical columns, unlike the camel-cased Prisma/Drizzle models).\n */\n\n/** Subgraph column type → Kysely TS type. numeric/bigint serialize as string (lossless for Clarity uint128/int128). */\nconst KYSELY_TYPE: Record<ColumnType, string> = {\n\tuint: \"string\",\n\tint: \"string\",\n\ttext: \"string\",\n\tprincipal: \"string\",\n\tboolean: \"boolean\",\n\ttimestamp: \"Date\",\n\tjsonb: \"unknown\",\n};\n\n/** System columns every subgraph table gets (kept in sync with generator.ts). */\nconst SYSTEM_FIELDS: Array<{ col: string; type: string }> = [\n\t{ col: \"_id\", type: \"Generated<string>\" },\n\t{ col: \"_block_height\", type: \"string\" },\n\t{ col: \"_tx_id\", type: \"string\" },\n\t{ col: \"_created_at\", type: \"Generated<Date>\" },\n];\n\nfunction renderTable(tableName: string, table: SubgraphTable): string {\n\tconst lines = SYSTEM_FIELDS.map((f) => ` ${f.col}: ${f.type};`);\n\tfor (const [colName, col] of Object.entries(table.columns)) {\n\t\tlet type = KYSELY_TYPE[col.type];\n\t\tif (col.nullable) type = `${type} | null`;\n\t\t// A DB-side default makes the column optional on insert — Generated<> models that.\n\t\tif (col.default !== undefined) type = `Generated<${type}>`;\n\t\tlines.push(` ${colName}: ${type};`);\n\t}\n\treturn `export interface ${pascalCase(tableName)} {\\n${lines.join(\"\\n\")}\\n}`;\n}\n\nexport interface KyselyGenOptions {\n\t/** Postgres schema the tables live in (account-scoped). */\n\tschemaName?: string;\n}\n\nexport function generateKyselySchema(\n\tdef: SubgraphDefinition,\n\topts: KyselyGenOptions = {},\n): string {\n\tconst schemaName = opts.schemaName ?? pgSchemaName(def.name);\n\n\tconst interfaces = Object.entries(def.schema).map(([name, table]) =>\n\t\trenderTable(name, table),\n\t);\n\n\t// DB registry — schema-qualified keys so `db.selectFrom(\"schema.table\")` resolves.\n\tconst dbEntries = Object.keys(def.schema).map(\n\t\t(name) => ` \"${schemaName}.${name}\": ${pascalCase(name)};`,\n\t);\n\tconst dbRegistry = `export interface DB {\\n${dbEntries.join(\"\\n\")}\\n}`;\n\n\t// Selectable row aliases for ergonomic typed reads.\n\tconst rowExports = Object.keys(def.schema).map(\n\t\t(name) =>\n\t\t\t`export type ${pascalCase(name)}Row = Selectable<${pascalCase(name)}>;`,\n\t);\n\n\treturn [\n\t\t`// Generated by \\`sl codegen subgraph --target kysely\\` from subgraph \"${def.name}\". Do not edit by hand.`,\n\t\t`import type { Generated, Selectable } from \"kysely\";`,\n\t\t\"\",\n\t\tinterfaces.join(\"\\n\\n\"),\n\t\t\"\",\n\t\tdbRegistry,\n\t\t\"\",\n\t\trowExports.join(\"\\n\"),\n\t\t\"\",\n\t].join(\"\\n\");\n}\n",
38
38
  "import {\n\ttype IndexColumn,\n\ttype IndexColumnType,\n\ttype IndexPrimaryKey,\n\tSOURCE_READ_PKS,\n\tSOURCE_READ_TYPES,\n} from \"@secondlayer/shared/db\";\nimport { pascalCase, snakeToCamel } from \"./utils.ts\";\n\n/**\n * Emit a portable, typed schema for the public Index read domain (blocks,\n * decoded events, transactions, stacking, sBTC, BNS, …) from the single-sourced\n * `SOURCE_READ_TYPES` registry. This is the Index arm of the \"typed Stacks data in\n * your own stack\" story: a BYO-database consumer mirrors Index rows and gets a\n * fully-typed ORM / JSON-Schema that can't drift from the API (the registry is\n * drift-tested against the producer's read contract).\n *\n * Prisma uses the `SOURCE_READ_PKS` registry for model identity. Tables whose only\n * physical PK is a synthetic id excluded from the read contract (chain_reorgs) have\n * no read-set key and are omitted from Prisma output (other targets still emit them).\n */\n\nexport type IndexCodegenTarget =\n\t| \"prisma\"\n\t| \"kysely\"\n\t| \"drizzle\"\n\t| \"json-schema\";\n\nexport interface IndexCodegenOptions {\n\t/** Restrict output to these Index tables (default: all). */\n\ttables?: string[];\n\t/** Postgres schema to qualify table names with (default: bare names). */\n\tschemaName?: string;\n\t/** Prisma only: datasource url env var (default DATABASE_URL). */\n\tdatasourceEnv?: string;\n}\n\ntype IndexTables = typeof SOURCE_READ_TYPES;\n\n/** Resolve the requested tables (validated) → ordered [table, columns] entries. */\nfunction selectTables(\n\topts: IndexCodegenOptions,\n): Array<[string, Record<string, IndexColumn>]> {\n\tconst all = SOURCE_READ_TYPES as Record<string, Record<string, IndexColumn>>;\n\tconst names = opts.tables ?? Object.keys(all);\n\treturn names.map((name) => {\n\t\tconst cols = all[name];\n\t\tif (!cols) {\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown Index table \"${name}\". Known: ${Object.keys(all).sort().join(\", \")}`,\n\t\t\t);\n\t\t}\n\t\treturn [name, cols];\n\t});\n}\n\nconst KYSELY_TYPE: Record<IndexColumnType, string> = {\n\ttext: \"string\",\n\tint: \"number\",\n\tboolean: \"boolean\",\n\ttimestamp: \"Date\",\n\tjsonb: \"unknown\",\n};\n\nfunction generateKysely(\n\tentries: Array<[string, Record<string, IndexColumn>]>,\n\tschemaName?: string,\n): string {\n\tconst interfaces = entries.map(([table, cols]) => {\n\t\tconst lines = Object.entries(cols).map(([col, def]) => {\n\t\t\tconst type = def.nullable\n\t\t\t\t? `${KYSELY_TYPE[def.type]} | null`\n\t\t\t\t: KYSELY_TYPE[def.type];\n\t\t\treturn ` ${col}: ${type};`;\n\t\t});\n\t\treturn `export interface ${pascalCase(table)} {\\n${lines.join(\"\\n\")}\\n}`;\n\t});\n\tconst dbEntries = entries.map(([table]) => {\n\t\tconst key = schemaName ? `${schemaName}.${table}` : table;\n\t\treturn ` \"${key}\": ${pascalCase(table)};`;\n\t});\n\tconst rows = entries.map(\n\t\t([table]) =>\n\t\t\t`export type ${pascalCase(table)}Row = Selectable<${pascalCase(table)}>;`,\n\t);\n\treturn [\n\t\t\"// Generated by `sl codegen index --target kysely`. Do not edit by hand.\",\n\t\t`import type { Selectable } from \"kysely\";`,\n\t\t\"\",\n\t\tinterfaces.join(\"\\n\\n\"),\n\t\t\"\",\n\t\t`export interface IndexDB {\\n${dbEntries.join(\"\\n\")}\\n}`,\n\t\t\"\",\n\t\trows.join(\"\\n\"),\n\t\t\"\",\n\t].join(\"\\n\");\n}\n\nconst DRIZZLE_BUILDER: Record<IndexColumnType, (col: string) => string> = {\n\ttext: (c) => `text(\"${c}\")`,\n\tint: (c) => `integer(\"${c}\")`,\n\tboolean: (c) => `boolean(\"${c}\")`,\n\ttimestamp: (c) => `timestamp(\"${c}\", { withTimezone: true })`,\n\tjsonb: (c) => `jsonb(\"${c}\")`,\n};\n\nconst DRIZZLE_BUILDER_NAME: Record<IndexColumnType, string> = {\n\ttext: \"text\",\n\tint: \"integer\",\n\tboolean: \"boolean\",\n\ttimestamp: \"timestamp\",\n\tjsonb: \"jsonb\",\n};\n\nfunction generateDrizzle(\n\tentries: Array<[string, Record<string, IndexColumn>]>,\n\tschemaName?: string,\n): string {\n\tconst used = new Set<string>();\n\tfor (const [, cols] of entries)\n\t\tfor (const def of Object.values(cols))\n\t\t\tused.add(DRIZZLE_BUILDER_NAME[def.type]);\n\tif (schemaName) used.add(\"pgSchema\");\n\telse used.add(\"pgTable\");\n\n\tconst tableFn = schemaName ? \"sg.table\" : \"pgTable\";\n\tconst tables = entries.map(([table, cols]) => {\n\t\tconst lines = Object.entries(cols).map(([col, def]) => {\n\t\t\tlet line = ` ${snakeToCamel(col)}: ${DRIZZLE_BUILDER[def.type](col)}`;\n\t\t\tif (!def.nullable) line += \".notNull()\";\n\t\t\treturn `${line},`;\n\t\t});\n\t\treturn `export const ${snakeToCamel(table)} = ${tableFn}(\"${table}\", {\\n${lines.join(\"\\n\")}\\n});`;\n\t});\n\tconst rows = entries.map(\n\t\t([table]) =>\n\t\t\t`export type ${pascalCase(table)} = typeof ${snakeToCamel(table)}.$inferSelect;`,\n\t);\n\treturn [\n\t\t\"// Generated by `sl codegen index --target drizzle`. Do not edit by hand.\",\n\t\t`import { ${[...used].sort().join(\", \")} } from \"drizzle-orm/pg-core\";`,\n\t\t\"\",\n\t\t...(schemaName ? [`export const sg = pgSchema(\"${schemaName}\");`, \"\"] : []),\n\t\ttables.join(\"\\n\\n\"),\n\t\t\"\",\n\t\trows.join(\"\\n\"),\n\t\t\"\",\n\t].join(\"\\n\");\n}\n\nconst JSON_SCHEMA_TYPE: Record<IndexColumnType, Record<string, unknown>> = {\n\ttext: { type: \"string\" },\n\tint: { type: \"integer\" },\n\tboolean: { type: \"boolean\" },\n\ttimestamp: { type: \"string\", format: \"date-time\" },\n\tjsonb: {},\n};\n\nfunction generateJsonSchema(\n\tentries: Array<[string, Record<string, IndexColumn>]>,\n): string {\n\tconst defs: Record<string, unknown> = {};\n\tfor (const [table, cols] of entries) {\n\t\tconst properties: Record<string, unknown> = {};\n\t\tconst required: string[] = [];\n\t\tfor (const [col, def] of Object.entries(cols)) {\n\t\t\tconst base = JSON_SCHEMA_TYPE[def.type];\n\t\t\tif (def.nullable && \"type\" in base) {\n\t\t\t\tproperties[col] = { ...base, type: [base.type, \"null\"] };\n\t\t\t} else {\n\t\t\t\tproperties[col] = { ...base };\n\t\t\t\tif (!def.nullable) required.push(col);\n\t\t\t}\n\t\t}\n\t\tdefs[pascalCase(table)] = {\n\t\t\ttype: \"object\",\n\t\t\tproperties,\n\t\t\trequired,\n\t\t\tadditionalProperties: false,\n\t\t};\n\t}\n\treturn `${JSON.stringify(\n\t\t{\n\t\t\t$schema: \"https://json-schema.org/draft/2020-12/schema\",\n\t\t\ttitle: \"Secondlayer Index domain\",\n\t\t\t$defs: defs,\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n`;\n}\n\nconst PRISMA_TYPE: Record<IndexColumnType, { type: string; db?: string }> = {\n\ttext: { type: \"String\" },\n\tint: { type: \"Int\" },\n\tboolean: { type: \"Boolean\" },\n\ttimestamp: { type: \"DateTime\", db: \"@db.Timestamptz\" },\n\tjsonb: { type: \"Json\" },\n};\n\nfunction generatePrisma(\n\tentries: Array<[string, Record<string, IndexColumn>]>,\n\tschemaName: string | undefined,\n\tdatasourceEnv: string,\n): string {\n\tconst pks = SOURCE_READ_PKS as Record<string, IndexPrimaryKey>;\n\tconst skipped: string[] = [];\n\n\tconst models: string[] = [];\n\tfor (const [table, cols] of entries) {\n\t\tconst pk = pks[table];\n\t\tif (!pk) {\n\t\t\tskipped.push(table);\n\t\t\tcontinue;\n\t\t}\n\t\tconst single = pk.length === 1 ? pk[0] : null;\n\t\tconst lines = Object.entries(cols).map(([col, def]) => {\n\t\t\tconst field = snakeToCamel(col);\n\t\t\tconst mapped = PRISMA_TYPE[def.type];\n\t\t\tconst attrs: string[] = [];\n\t\t\tif (single === col) attrs.push(\"@id\");\n\t\t\tif (field !== col) attrs.push(`@map(\"${col}\")`);\n\t\t\tif (mapped.db) attrs.push(mapped.db);\n\t\t\tconst optional = def.nullable ? \"?\" : \"\";\n\t\t\treturn ` ${field} ${mapped.type}${optional}${attrs.length ? ` ${attrs.join(\" \")}` : \"\"}`;\n\t\t});\n\t\tconst block: string[] = [];\n\t\tif (!single) {\n\t\t\tblock.push(` @@id([${pk.map(snakeToCamel).join(\", \")}])`);\n\t\t}\n\t\tblock.push(` @@map(\"${table}\")`);\n\t\tif (schemaName) block.push(` @@schema(\"${schemaName}\")`);\n\t\tmodels.push(\n\t\t\t`model ${pascalCase(table)} {\\n${lines.join(\"\\n\")}\\n\\n${block.join(\"\\n\")}\\n}`,\n\t\t);\n\t}\n\n\tconst header = [\n\t\t\"// Generated by `sl codegen index --target prisma`. Do not edit by hand.\",\n\t\t...(skipped.length\n\t\t\t? [\n\t\t\t\t\t`// Omitted (no read-set primary key, query via another target): ${skipped.join(\", \")}`,\n\t\t\t\t]\n\t\t\t: []),\n\t\t\"\",\n\t\t\"datasource db {\",\n\t\t' provider = \"postgresql\"',\n\t\t` url = env(\"${datasourceEnv}\")`,\n\t\t...(schemaName ? [` schemas = [\"${schemaName}\"]`] : []),\n\t\t\"}\",\n\t\t\"\",\n\t\t\"generator client {\",\n\t\t' provider = \"prisma-client-js\"',\n\t\t...(schemaName ? [' previewFeatures = [\"multiSchema\"]'] : []),\n\t\t\"}\",\n\t].join(\"\\n\");\n\n\treturn `${header}\\n\\n${models.join(\"\\n\\n\")}\\n`;\n}\n\nexport function generateIndexSchema(\n\ttarget: IndexCodegenTarget,\n\topts: IndexCodegenOptions = {},\n): string {\n\tconst entries = selectTables(opts);\n\tswitch (target) {\n\t\tcase \"prisma\":\n\t\t\treturn generatePrisma(\n\t\t\t\tentries,\n\t\t\t\topts.schemaName,\n\t\t\t\topts.datasourceEnv ?? \"DATABASE_URL\",\n\t\t\t);\n\t\tcase \"kysely\":\n\t\t\treturn generateKysely(entries, opts.schemaName);\n\t\tcase \"drizzle\":\n\t\t\treturn generateDrizzle(entries, opts.schemaName);\n\t\tcase \"json-schema\":\n\t\t\treturn generateJsonSchema(entries);\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported Index codegen target \"${target}\".`);\n\t}\n}\n\n/** Index tables available to codegen, for help text and validation. */\nexport const INDEX_CODEGEN_TABLES: readonly string[] = Object.keys(\n\tSOURCE_READ_TYPES,\n) as Array<keyof IndexTables>;\n",
39
- "import type { Database } from \"@secondlayer/shared/db\";\nimport { type Kysely, sql } from \"kysely\";\nimport type {\n\tSubgraphDefinition,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { validateSubgraphDefinition } from \"../validate.ts\";\nimport {\n\tTYPE_MAP,\n\temitForeignKeyDDL,\n\temitTableDDL,\n\tgenerateSubgraphSQL,\n\ttableNeedsTrgm,\n} from \"./generator.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\ntype AnyDb = Kysely<Database>;\n\n/** Deep-clone an object, converting BigInts to strings for JSON serialization. */\nfunction toJsonSafe(obj: unknown): unknown {\n\treturn JSON.parse(\n\t\tJSON.stringify(obj, (_key, value) =>\n\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t),\n\t);\n}\n\nexport interface TableDiff {\n\t/** Tables added to the schema */\n\taddedTables: string[];\n\t/** Tables removed from the schema */\n\tremovedTables: string[];\n\t/** Per-table column diffs (only for tables present in both) */\n\ttables: Record<string, ColumnDiff>;\n\t/** Per-table uniqueKeys / composite-index diffs (tables present in both) */\n\tconstraints: Record<string, ConstraintDiff>;\n}\n\nexport interface ColumnDiff {\n\tadded: string[];\n\tremoved: string[];\n\t/** Data-shape changes (type/nullable/default) — breaking. */\n\tchanged: string[];\n\t/** Only the `indexed`/`search` flags differ — index DDL, never a rebuild. */\n\tindexChanged: string[];\n}\n\nexport interface ConstraintDiff {\n\t/** New uniqueKeys entries → `ALTER TABLE … ADD CONSTRAINT` (additive). */\n\taddedUniqueKeys: string[][];\n\t/** Removed uniqueKeys entries — breaking: handler upserts may target them. */\n\tremovedUniqueKeys: string[][];\n\t/** New composite `indexes` entries → CREATE INDEX (additive). */\n\taddedIndexes: string[][];\n\t/** Removed composite `indexes` entries → DROP INDEX (additive). */\n\tremovedIndexes: string[][];\n}\n\n/** Column identity minus the index flags: what actually shapes stored data. */\nfunction columnDataShape(col: unknown): string {\n\tconst { indexed, search, ...rest } = (col ?? {}) as Record<string, unknown>;\n\treturn JSON.stringify(rest, Object.keys(rest).sort());\n}\n\n/** Diff two `string[][]` lists (uniqueKeys / indexes) by column-list value. */\nfunction diffKeyLists(\n\texisting: readonly (readonly string[])[] | undefined,\n\tincoming: readonly (readonly string[])[] | undefined,\n): { added: string[][]; removed: string[][] } {\n\tconst key = (cols: readonly string[]) => JSON.stringify(cols);\n\tconst existingSet = new Set((existing ?? []).map(key));\n\tconst incomingSet = new Set((incoming ?? []).map(key));\n\treturn {\n\t\tadded: (incoming ?? [])\n\t\t\t.filter((cols) => !existingSet.has(key(cols)))\n\t\t\t.map((cols) => [...cols]),\n\t\tremoved: (existing ?? [])\n\t\t\t.filter((cols) => !incomingSet.has(key(cols)))\n\t\t\t.map((cols) => [...cols]),\n\t};\n}\n\n/**\n * Compare two multi-table subgraph schemas and return differences.\n *\n * Index-only changes (`indexed`/`search` flags, composite `indexes`) are\n * reported separately from data-shape changes: an index never requires a\n * rebuild, so it must never land in `changed`/breaking — flipping\n * `indexed: true` on a populated column used to cost a full reindex.\n */\nexport function diffSchema(\n\texisting: SubgraphSchema,\n\tincoming: SubgraphSchema,\n): TableDiff {\n\tconst existingTables = new Set(Object.keys(existing));\n\tconst incomingTables = new Set(Object.keys(incoming));\n\n\tconst addedTables = [...incomingTables].filter((t) => !existingTables.has(t));\n\tconst removedTables = [...existingTables].filter(\n\t\t(t) => !incomingTables.has(t),\n\t);\n\n\tconst tables: Record<string, ColumnDiff> = {};\n\tconst constraints: Record<string, ConstraintDiff> = {};\n\tfor (const tableName of incomingTables) {\n\t\tif (!existingTables.has(tableName)) continue;\n\t\tconst existingTable = existing[tableName];\n\t\tconst incomingTable = incoming[tableName];\n\t\tconst existingCols = existingTable?.columns;\n\t\tconst incomingCols = incomingTable?.columns;\n\n\t\tconst existingKeys = new Set(Object.keys(existingCols));\n\t\tconst incomingKeys = new Set(Object.keys(incomingCols));\n\t\tconst common = [...incomingKeys].filter((k) => existingKeys.has(k));\n\n\t\tconst sortedStringify = (o: unknown) =>\n\t\t\tJSON.stringify(o, Object.keys(o as object).sort());\n\n\t\ttables[tableName] = {\n\t\t\tadded: [...incomingKeys].filter((k) => !existingKeys.has(k)),\n\t\t\tremoved: [...existingKeys].filter((k) => !incomingKeys.has(k)),\n\t\t\tchanged: common.filter(\n\t\t\t\t(k) =>\n\t\t\t\t\tcolumnDataShape(existingCols[k]) !== columnDataShape(incomingCols[k]),\n\t\t\t),\n\t\t\tindexChanged: common.filter(\n\t\t\t\t(k) =>\n\t\t\t\t\tcolumnDataShape(existingCols[k]) ===\n\t\t\t\t\t\tcolumnDataShape(incomingCols[k]) &&\n\t\t\t\t\tsortedStringify(existingCols[k]) !== sortedStringify(incomingCols[k]),\n\t\t\t),\n\t\t};\n\n\t\tconst uq = diffKeyLists(\n\t\t\texistingTable?.uniqueKeys,\n\t\t\tincomingTable?.uniqueKeys,\n\t\t);\n\t\tconst ix = diffKeyLists(existingTable?.indexes, incomingTable?.indexes);\n\t\tconstraints[tableName] = {\n\t\t\taddedUniqueKeys: uq.added,\n\t\t\tremovedUniqueKeys: uq.removed,\n\t\t\taddedIndexes: ix.added,\n\t\t\tremovedIndexes: ix.removed,\n\t\t};\n\t}\n\n\treturn { addedTables, removedTables, tables, constraints };\n}\n\n/**\n * Returns true if the diff contains any breaking changes\n * (removed tables, removed columns, changed column types, or removed\n * uniqueKeys — handler upserts `ON CONFLICT` against those).\n * Index-flag and composite-index changes are never breaking.\n */\nexport function hasBreakingChanges(diff: TableDiff): {\n\tbreaking: boolean;\n\treasons: string[];\n} {\n\tconst reasons: string[] = [];\n\tif (diff.removedTables.length > 0) {\n\t\treasons.push(`removed tables: [${diff.removedTables.join(\", \")}]`);\n\t}\n\tfor (const [table, colDiff] of Object.entries(diff.tables)) {\n\t\tif (colDiff.removed.length > 0) {\n\t\t\treasons.push(`${table}: removed columns [${colDiff.removed.join(\", \")}]`);\n\t\t}\n\t\tif (colDiff.changed.length > 0) {\n\t\t\treasons.push(`${table}: changed columns [${colDiff.changed.join(\", \")}]`);\n\t\t}\n\t}\n\tfor (const [table, conDiff] of Object.entries(diff.constraints ?? {})) {\n\t\tif (conDiff.removedUniqueKeys.length > 0) {\n\t\t\treasons.push(\n\t\t\t\t`${table}: removed uniqueKeys [${conDiff.removedUniqueKeys\n\t\t\t\t\t.map((cols) => `(${cols.join(\", \")})`)\n\t\t\t\t\t.join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t}\n\treturn { breaking: reasons.length > 0, reasons };\n}\n\n/** Increment the patch segment of a semver string. \"1.0.2\" → \"1.0.3\" */\nfunction bumpPatch(version: string): string {\n\tconst parts = version.split(\".\");\n\tif (parts.length !== 3) return \"1.0.1\";\n\tconst patch = Number.parseInt(parts[2] ?? \"0\", 10);\n\treturn `${parts[0]}.${parts[1]}.${Number.isNaN(patch) ? 1 : patch + 1}`;\n}\n\nexport interface DeployDiff {\n\taddedTables: string[];\n\tremovedTables: string[];\n\taddedColumns: Record<string, string[]>;\n\tbreakingChanges: string[];\n\t/** Columns whose only change was the `indexed`/`search` flag (index DDL applied in place). */\n\tindexChanges?: Record<string, string[]>;\n\t/** uniqueKeys added in place via ALTER TABLE … ADD CONSTRAINT. */\n\taddedUniqueKeys?: Record<string, string[][]>;\n}\n\n/**\n * Map a raw `TableDiff` (+ breaking reasons) into the wire `DeployDiff`. `null`\n * diff (e.g. same-hash force reindex, where no schema diff exists) → empty\n * added/removed/columns with reasons preserved. Single source for both the\n * non-refuse \"reindexed\" result and the refuse-path error payload.\n */\nfunction toDeployDiff(diff: TableDiff | null, reasons: string[]): DeployDiff {\n\treturn {\n\t\taddedTables: diff?.addedTables ?? [],\n\t\tremovedTables: diff?.removedTables ?? [],\n\t\taddedColumns: diff\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.entries(diff.tables)\n\t\t\t\t\t\t.filter(([, c]) => c.added.length > 0)\n\t\t\t\t\t\t.map(([t, c]) => [t, c.added]),\n\t\t\t\t)\n\t\t\t: {},\n\t\tbreakingChanges: reasons,\n\t};\n}\n\nexport interface DeployPlan {\n\tschemaName: string;\n\t/** `DROP SCHEMA … CASCADE` a destructive rebuild would run first. */\n\tdropStatement: string;\n\t/** DDL the deploy will run. */\n\tstatements: string[];\n}\n\n/**\n * Render the DDL a deploy would run, without executing.\n * Powers `--dry-run`: the user reviews exactly what a deploy does first.\n */\nexport function renderDeployPlan(\n\tdef: SubgraphDefinition,\n\tschemaName?: string,\n): DeployPlan {\n\tvalidateSubgraphDefinition(def);\n\tconst { statements } = generateSubgraphSQL(def, schemaName);\n\tconst schema = schemaName ?? pgSchemaName(def.name);\n\tconst dropStatement = `DROP SCHEMA IF EXISTS \"${schema}\" CASCADE;`;\n\treturn { schemaName: schema, dropStatement, statements };\n}\n\n/**\n * Deploy a subgraph schema to the database.\n * - New subgraph → CREATE SCHEMA + tables + register\n * - Same hash → no-op (handler path updated)\n * - Additive change → ALTER TABLE ADD COLUMN / CREATE TABLE for new tables\n * - Breaking change → auto-reindex (drop + recreate)\n */\nexport async function deploySchema(\n\tdb: AnyDb,\n\tdef: SubgraphDefinition,\n\thandlerPath: string,\n\topts?: {\n\t\tforceReindex?: boolean;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tversion?: string;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t},\n): Promise<{\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tdiff?: DeployDiff;\n\t/** Non-fatal caveats the caller should surface (e.g. handler grafts at tip). */\n\twarnings?: string[];\n}> {\n\tvalidateSubgraphDefinition(def);\n\n\tconst { statements, hash } = generateSubgraphSQL(def, opts?.schemaName);\n\tconst { getSubgraph, registerSubgraph } = await import(\n\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t);\n\n\tconst ddlDb = db;\n\n\tconst existing = await getSubgraph(db, def.name, opts?.accountId);\n\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(def.name);\n\n\t// Server owns versioning: use explicit flag, bump patch from existing, or start at 1.0.0\n\tconst newVersion =\n\t\topts?.version ?? (existing ? bumpPatch(existing.version) : \"1.0.0\");\n\n\tconst regData = {\n\t\tname: def.name,\n\t\tversion: newVersion,\n\t\tdefinition: toJsonSafe({\n\t\t\tname: def.name,\n\t\t\tversion: def.version,\n\t\t\tdescription: def.description,\n\t\t\tstartBlock: def.startBlock,\n\t\t\tsources: def.sources,\n\t\t\tschema: def.schema,\n\t\t}) as Record<string, unknown>,\n\t\tschemaHash: hash,\n\t\thandlerPath,\n\t\tapiKeyId: opts?.apiKeyId,\n\t\taccountId: opts?.accountId,\n\t\thandlerCode: opts?.handlerCode,\n\t\tsourceCode: opts?.sourceCode,\n\t\tschemaName,\n\t\tstartBlock: def.startBlock,\n\t};\n\n\tif (existing) {\n\t\t// Guard against zombie rows: registry entry exists but PG schema was dropped\n\t\t// (e.g. partial delete or manual cleanup). Treat as a new subgraph.\n\t\tconst schemaExists = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS (\n\t\t\t\tSELECT 1 FROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${schemaName}\n\t\t\t) AS \"exists\"\n\t\t`\n\t\t\t.execute(ddlDb)\n\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\n\t\tif (!schemaExists) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.schema_hash === hash && !opts?.forceReindex) {\n\t\t\t// Update handler path and code in case file moved or handler changed.\n\t\t\tconst handlerChanged =\n\t\t\t\topts?.handlerCode != null && opts.handlerCode !== existing.handler_code;\n\t\t\tconst { updateSubgraphHandlerPath } = await import(\n\t\t\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t\t\t);\n\t\t\tawait updateSubgraphHandlerPath(db, def.name, handlerPath, {\n\t\t\t\thandlerCode: opts?.handlerCode,\n\t\t\t\tsourceCode: opts?.sourceCode,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\taction: handlerChanged ? \"handler_updated\" : \"unchanged\",\n\t\t\t\tsubgraphId: existing.id,\n\t\t\t\tversion: existing.version,\n\t\t\t\t// A handler-only change takes effect from the CURRENT tip: rows\n\t\t\t\t// already indexed keep the old handler's output. Silent until now —\n\t\t\t\t// say it, and name the fix.\n\t\t\t\t...(handlerChanged\n\t\t\t\t\t? {\n\t\t\t\t\t\t\twarnings: [\n\t\t\t\t\t\t\t\t\"handler changed but schema did not: new logic applies from the current tip only. \" +\n\t\t\t\t\t\t\t\t\t\"Rows already indexed were computed by the previous handler. \" +\n\t\t\t\t\t\t\t\t\t\"To recompute history, redeploy with --reindex (or backfill a range).\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\n\t\tif (existing.schema_hash === hash && opts?.forceReindex) {\n\t\t\t// Same schema but force reindex requested — drop and recreate.\n\t\t\tawait sql\n\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t.execute(ddlDb);\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.definition.schema) {\n\t\t\tconst diff = diffSchema(\n\t\t\t\texisting.definition.schema as SubgraphSchema,\n\t\t\t\tdef.schema,\n\t\t\t);\n\t\t\tconst { breaking, reasons } = hasBreakingChanges(diff);\n\n\t\t\tif (breaking || opts?.forceReindex) {\n\t\t\t\t// Breaking change or forced: drop schema, recreate, register\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\t\tconst deployDiff = toDeployDiff(diff, reasons);\n\t\t\t\treturn {\n\t\t\t\t\taction: \"reindexed\",\n\t\t\t\t\tsubgraphId: sg.id,\n\t\t\t\t\tversion: newVersion,\n\t\t\t\t\tdiff: deployDiff,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Create new tables using the SAME per-table emitter as the full\n\t\t\t// generator, so an additively-created table gets its UNIQUE constraints,\n\t\t\t// composite indexes, column defaults, and FKs — not just the bare columns.\n\t\t\t// (A missing UNIQUE here previously made a handler upsert ON CONFLICT fail\n\t\t\t// at runtime on additively-added tables.)\n\t\t\tconst addedDefs = diff.addedTables\n\t\t\t\t.map((tableName) => ({ tableName, tableDef: def.schema[tableName] }))\n\t\t\t\t.filter(\n\t\t\t\t\t(t): t is { tableName: string; tableDef: SubgraphTable } =>\n\t\t\t\t\t\tt.tableDef !== undefined,\n\t\t\t\t);\n\n\t\t\t// pg_trgm must exist before any search-column GIN index on the new tables.\n\t\t\tif (addedDefs.some(({ tableDef }) => tableNeedsTrgm(tableDef))) {\n\t\t\t\tawait sql.raw(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\").execute(ddlDb);\n\t\t\t}\n\t\t\tfor (const { tableName, tableDef } of addedDefs) {\n\t\t\t\tfor (const stmt of emitTableDDL(schemaName, tableName, tableDef)) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// FKs in a second pass so every referenced (new or pre-existing) table\n\t\t\t// exists first.\n\t\t\tfor (const { tableName, tableDef } of addedDefs) {\n\t\t\t\tfor (const stmt of emitForeignKeyDDL(schemaName, tableName, tableDef)) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add columns to existing tables\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.added.length === 0) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tfor (const colName of colDiff.added) {\n\t\t\t\t\tconst col = tableDef.columns[colName];\n\t\t\t\t\tif (!col) continue;\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tconst nullable = col.nullable\n\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t: ` NOT NULL DEFAULT ${getDefault(col.type)}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD COLUMN ${colName} ${sqlType}${nullable}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Index-flag flips on EXISTING (populated) columns: pure index DDL,\n\t\t\t// applied in place. CONCURRENTLY because the table has data and this\n\t\t\t// runs outside a transaction (autocommit per statement) — a plain\n\t\t\t// CREATE INDEX would take a write lock for the whole build.\n\t\t\tconst existingSchema = existing.definition.schema as SubgraphSchema;\n\t\t\tconst flagFlips: Record<string, string[]> = {};\n\t\t\tconst needsTrgmForFlips = Object.entries(diff.tables).some(\n\t\t\t\t([tableName, colDiff]) =>\n\t\t\t\t\tcolDiff.indexChanged.some(\n\t\t\t\t\t\t(colName) =>\n\t\t\t\t\t\t\tdef.schema[tableName]?.columns[colName]?.search &&\n\t\t\t\t\t\t\t!existingSchema[tableName]?.columns[colName]?.search,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (needsTrgmForFlips) {\n\t\t\t\tawait sql.raw(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\").execute(ddlDb);\n\t\t\t}\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.indexChanged.length === 0) continue;\n\t\t\t\tflagFlips[tableName] = colDiff.indexChanged;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tfor (const colName of colDiff.indexChanged) {\n\t\t\t\t\tconst was = existingSchema[tableName]?.columns[colName];\n\t\t\t\t\tconst now = def.schema[tableName]?.columns[colName];\n\t\t\t\t\tif (!now) continue;\n\t\t\t\t\tconst plainIdx = `idx_${schemaName}_${tableName}_${colName}`;\n\t\t\t\t\tconst trgmIdx = `idx_${schemaName}_${tableName}_${colName}_trgm`;\n\t\t\t\t\tif (now.indexed && !was?.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${plainIdx} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t} else if (!now.indexed && was?.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`DROP INDEX CONCURRENTLY IF EXISTS ${schemaName}.${plainIdx}`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\tif (now.search && !was?.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${trgmIdx} ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t} else if (!now.search && was?.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(`DROP INDEX CONCURRENTLY IF EXISTS ${schemaName}.${trgmIdx}`)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// uniqueKeys additions: ADD CONSTRAINT in place (idempotent via\n\t\t\t// pg_constraint check — Postgres has no ADD CONSTRAINT IF NOT EXISTS).\n\t\t\t// Removals never reach here: hasBreakingChanges classifies them\n\t\t\t// breaking, which lands in the reindex branch above.\n\t\t\tconst addedUq: Record<string, string[][]> = {};\n\t\t\tfor (const [tableName, conDiff] of Object.entries(diff.constraints)) {\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tfor (const cols of conDiff.addedUniqueKeys) {\n\t\t\t\t\tconst constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n\t\t\t\t\tconst exists = await sql<{ exists: boolean }>`\n\t\t\t\t\t\tSELECT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM pg_constraint\n\t\t\t\t\t\t\tWHERE conname = ${constraintName}\n\t\t\t\t\t\t) AS \"exists\"\n\t\t\t\t\t`\n\t\t\t\t\t\t.execute(ddlDb)\n\t\t\t\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\taddedUq[tableName] = [...(addedUq[tableName] ?? []), cols];\n\t\t\t\t}\n\t\t\t\t// Composite indexes: additive both ways. Names are positional in the\n\t\t\t\t// incoming schema; a reordered (unchanged-value) entry keeps its old\n\t\t\t\t// positionally-derived name, which is harmless.\n\t\t\t\tfor (const cols of conDiff.addedIndexes) {\n\t\t\t\t\tconst i = (def.schema[tableName]?.indexes ?? []).findIndex(\n\t\t\t\t\t\t(entry) => JSON.stringify(entry) === JSON.stringify(cols),\n\t\t\t\t\t);\n\t\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t}\n\t\t\t\tfor (const cols of conDiff.removedIndexes) {\n\t\t\t\t\tconst i = (existingSchema[tableName]?.indexes ?? []).findIndex(\n\t\t\t\t\t\t(entry) => JSON.stringify(entry) === JSON.stringify(cols),\n\t\t\t\t\t);\n\t\t\t\t\tif (i < 0) continue;\n\t\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(`DROP INDEX CONCURRENTLY IF EXISTS ${schemaName}.${idxName}`)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\tconst addedCols: Record<string, string[]> = {};\n\t\t\tfor (const [t, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif ((colDiff as ColumnDiff).added.length > 0)\n\t\t\t\t\taddedCols[t] = (colDiff as ColumnDiff).added;\n\t\t\t}\n\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\tremovedTables: [],\n\t\t\t\taddedColumns: addedCols,\n\t\t\t\tbreakingChanges: [],\n\t\t\t\t...(Object.keys(flagFlips).length > 0\n\t\t\t\t\t? { indexChanges: flagFlips }\n\t\t\t\t\t: {}),\n\t\t\t\t...(Object.keys(addedUq).length > 0\n\t\t\t\t\t? { addedUniqueKeys: addedUq }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\treturn {\n\t\t\t\taction: \"updated\",\n\t\t\t\tsubgraphId: sg.id,\n\t\t\t\tversion: newVersion,\n\t\t\t\tdiff: deployDiff,\n\t\t\t};\n\t\t}\n\t}\n\n\t// New subgraph — execute all DDL\n\tfor (const stmt of statements) {\n\t\tawait sql.raw(stmt).execute(ddlDb);\n\t}\n\n\tconst sg = await registerSubgraph(db, regData);\n\treturn { action: \"created\", subgraphId: sg.id, version: newVersion };\n}\n\nfunction getDefault(type: string): string {\n\tswitch (type) {\n\t\tcase \"text\":\n\t\tcase \"principal\":\n\t\t\treturn \"''\";\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn \"0\";\n\t\tcase \"boolean\":\n\t\t\treturn \"false\";\n\t\tcase \"timestamp\":\n\t\t\treturn \"NOW()\";\n\t\tcase \"jsonb\":\n\t\t\treturn \"'{}'\";\n\t\tdefault:\n\t\t\treturn \"''\";\n\t}\n}\n"
39
+ "import type { Database } from \"@secondlayer/shared/db\";\nimport { type Kysely, sql } from \"kysely\";\nimport type {\n\tSubgraphDefinition,\n\tSubgraphSchema,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { validateSubgraphDefinition } from \"../validate.ts\";\nimport {\n\tTYPE_MAP,\n\temitForeignKeyDDL,\n\temitIndexedColumnIndexDDL,\n\temitTableDDL,\n\tgenerateSubgraphSQL,\n\ttableNeedsTrgm,\n} from \"./generator.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\ntype AnyDb = Kysely<Database>;\n\n/** Deep-clone an object, converting BigInts to strings for JSON serialization. */\nfunction toJsonSafe(obj: unknown): unknown {\n\treturn JSON.parse(\n\t\tJSON.stringify(obj, (_key, value) =>\n\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t),\n\t);\n}\n\nexport interface TableDiff {\n\t/** Tables added to the schema */\n\taddedTables: string[];\n\t/** Tables removed from the schema */\n\tremovedTables: string[];\n\t/** Per-table column diffs (only for tables present in both) */\n\ttables: Record<string, ColumnDiff>;\n\t/** Per-table uniqueKeys / composite-index diffs (tables present in both) */\n\tconstraints: Record<string, ConstraintDiff>;\n}\n\nexport interface ColumnDiff {\n\tadded: string[];\n\tremoved: string[];\n\t/** Data-shape changes (type/nullable/default) — breaking. */\n\tchanged: string[];\n\t/** Only the `indexed`/`search` flags differ — index DDL, never a rebuild. */\n\tindexChanged: string[];\n}\n\nexport interface ConstraintDiff {\n\t/** New uniqueKeys entries → `ALTER TABLE … ADD CONSTRAINT` (additive). */\n\taddedUniqueKeys: string[][];\n\t/** Removed uniqueKeys entries — breaking: handler upserts may target them. */\n\tremovedUniqueKeys: string[][];\n\t/** New composite `indexes` entries → CREATE INDEX (additive). */\n\taddedIndexes: string[][];\n\t/** Removed composite `indexes` entries → DROP INDEX (additive). */\n\tremovedIndexes: string[][];\n}\n\n/** Column identity minus the index flags: what actually shapes stored data. */\nfunction columnDataShape(col: unknown): string {\n\tconst { indexed, search, ...rest } = (col ?? {}) as Record<string, unknown>;\n\treturn JSON.stringify(rest, Object.keys(rest).sort());\n}\n\n/** Diff two `string[][]` lists (uniqueKeys / indexes) by column-list value. */\nfunction diffKeyLists(\n\texisting: readonly (readonly string[])[] | undefined,\n\tincoming: readonly (readonly string[])[] | undefined,\n): { added: string[][]; removed: string[][] } {\n\tconst key = (cols: readonly string[]) => JSON.stringify(cols);\n\tconst existingSet = new Set((existing ?? []).map(key));\n\tconst incomingSet = new Set((incoming ?? []).map(key));\n\treturn {\n\t\tadded: (incoming ?? [])\n\t\t\t.filter((cols) => !existingSet.has(key(cols)))\n\t\t\t.map((cols) => [...cols]),\n\t\tremoved: (existing ?? [])\n\t\t\t.filter((cols) => !incomingSet.has(key(cols)))\n\t\t\t.map((cols) => [...cols]),\n\t};\n}\n\n/**\n * Compare two multi-table subgraph schemas and return differences.\n *\n * Index-only changes (`indexed`/`search` flags, composite `indexes`) are\n * reported separately from data-shape changes: an index never requires a\n * rebuild, so it must never land in `changed`/breaking — flipping\n * `indexed: true` on a populated column used to cost a full reindex.\n */\nexport function diffSchema(\n\texisting: SubgraphSchema,\n\tincoming: SubgraphSchema,\n): TableDiff {\n\tconst existingTables = new Set(Object.keys(existing));\n\tconst incomingTables = new Set(Object.keys(incoming));\n\n\tconst addedTables = [...incomingTables].filter((t) => !existingTables.has(t));\n\tconst removedTables = [...existingTables].filter(\n\t\t(t) => !incomingTables.has(t),\n\t);\n\n\tconst tables: Record<string, ColumnDiff> = {};\n\tconst constraints: Record<string, ConstraintDiff> = {};\n\tfor (const tableName of incomingTables) {\n\t\tif (!existingTables.has(tableName)) continue;\n\t\tconst existingTable = existing[tableName];\n\t\tconst incomingTable = incoming[tableName];\n\t\tconst existingCols = existingTable?.columns;\n\t\tconst incomingCols = incomingTable?.columns;\n\n\t\tconst existingKeys = new Set(Object.keys(existingCols));\n\t\tconst incomingKeys = new Set(Object.keys(incomingCols));\n\t\tconst common = [...incomingKeys].filter((k) => existingKeys.has(k));\n\n\t\tconst sortedStringify = (o: unknown) =>\n\t\t\tJSON.stringify(o, Object.keys(o as object).sort());\n\n\t\ttables[tableName] = {\n\t\t\tadded: [...incomingKeys].filter((k) => !existingKeys.has(k)),\n\t\t\tremoved: [...existingKeys].filter((k) => !incomingKeys.has(k)),\n\t\t\tchanged: common.filter(\n\t\t\t\t(k) =>\n\t\t\t\t\tcolumnDataShape(existingCols[k]) !== columnDataShape(incomingCols[k]),\n\t\t\t),\n\t\t\tindexChanged: common.filter(\n\t\t\t\t(k) =>\n\t\t\t\t\tcolumnDataShape(existingCols[k]) ===\n\t\t\t\t\t\tcolumnDataShape(incomingCols[k]) &&\n\t\t\t\t\tsortedStringify(existingCols[k]) !== sortedStringify(incomingCols[k]),\n\t\t\t),\n\t\t};\n\n\t\tconst uq = diffKeyLists(\n\t\t\texistingTable?.uniqueKeys,\n\t\t\tincomingTable?.uniqueKeys,\n\t\t);\n\t\tconst ix = diffKeyLists(existingTable?.indexes, incomingTable?.indexes);\n\t\tconstraints[tableName] = {\n\t\t\taddedUniqueKeys: uq.added,\n\t\t\tremovedUniqueKeys: uq.removed,\n\t\t\taddedIndexes: ix.added,\n\t\t\tremovedIndexes: ix.removed,\n\t\t};\n\t}\n\n\treturn { addedTables, removedTables, tables, constraints };\n}\n\n/**\n * Returns true if the diff contains any breaking changes\n * (removed tables, removed columns, changed column types, or removed\n * uniqueKeys — handler upserts `ON CONFLICT` against those).\n * Index-flag and composite-index changes are never breaking.\n */\nexport function hasBreakingChanges(diff: TableDiff): {\n\tbreaking: boolean;\n\treasons: string[];\n} {\n\tconst reasons: string[] = [];\n\tif (diff.removedTables.length > 0) {\n\t\treasons.push(`removed tables: [${diff.removedTables.join(\", \")}]`);\n\t}\n\tfor (const [table, colDiff] of Object.entries(diff.tables)) {\n\t\tif (colDiff.removed.length > 0) {\n\t\t\treasons.push(`${table}: removed columns [${colDiff.removed.join(\", \")}]`);\n\t\t}\n\t\tif (colDiff.changed.length > 0) {\n\t\t\treasons.push(`${table}: changed columns [${colDiff.changed.join(\", \")}]`);\n\t\t}\n\t}\n\tfor (const [table, conDiff] of Object.entries(diff.constraints ?? {})) {\n\t\tif (conDiff.removedUniqueKeys.length > 0) {\n\t\t\treasons.push(\n\t\t\t\t`${table}: removed uniqueKeys [${conDiff.removedUniqueKeys\n\t\t\t\t\t.map((cols) => `(${cols.join(\", \")})`)\n\t\t\t\t\t.join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t}\n\treturn { breaking: reasons.length > 0, reasons };\n}\n\n/** Increment the patch segment of a semver string. \"1.0.2\" → \"1.0.3\" */\nfunction bumpPatch(version: string): string {\n\tconst parts = version.split(\".\");\n\tif (parts.length !== 3) return \"1.0.1\";\n\tconst patch = Number.parseInt(parts[2] ?? \"0\", 10);\n\treturn `${parts[0]}.${parts[1]}.${Number.isNaN(patch) ? 1 : patch + 1}`;\n}\n\nexport interface DeployDiff {\n\taddedTables: string[];\n\tremovedTables: string[];\n\taddedColumns: Record<string, string[]>;\n\tbreakingChanges: string[];\n\t/** Columns whose only change was the `indexed`/`search` flag (index DDL applied in place). */\n\tindexChanges?: Record<string, string[]>;\n\t/** uniqueKeys added in place via ALTER TABLE … ADD CONSTRAINT. */\n\taddedUniqueKeys?: Record<string, string[][]>;\n}\n\n/**\n * Map a raw `TableDiff` (+ breaking reasons) into the wire `DeployDiff`. `null`\n * diff (e.g. same-hash force reindex, where no schema diff exists) → empty\n * added/removed/columns with reasons preserved. Single source for both the\n * non-refuse \"reindexed\" result and the refuse-path error payload.\n */\nfunction toDeployDiff(diff: TableDiff | null, reasons: string[]): DeployDiff {\n\treturn {\n\t\taddedTables: diff?.addedTables ?? [],\n\t\tremovedTables: diff?.removedTables ?? [],\n\t\taddedColumns: diff\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.entries(diff.tables)\n\t\t\t\t\t\t.filter(([, c]) => c.added.length > 0)\n\t\t\t\t\t\t.map(([t, c]) => [t, c.added]),\n\t\t\t\t)\n\t\t\t: {},\n\t\tbreakingChanges: reasons,\n\t};\n}\n\nexport interface DeployPlan {\n\tschemaName: string;\n\t/** `DROP SCHEMA … CASCADE` a destructive rebuild would run first. */\n\tdropStatement: string;\n\t/** DDL the deploy will run. */\n\tstatements: string[];\n}\n\n/**\n * Render the DDL a deploy would run, without executing.\n * Powers `--dry-run`: the user reviews exactly what a deploy does first.\n */\nexport function renderDeployPlan(\n\tdef: SubgraphDefinition,\n\tschemaName?: string,\n): DeployPlan {\n\tvalidateSubgraphDefinition(def);\n\tconst { statements } = generateSubgraphSQL(def, schemaName);\n\tconst schema = schemaName ?? pgSchemaName(def.name);\n\tconst dropStatement = `DROP SCHEMA IF EXISTS \"${schema}\" CASCADE;`;\n\treturn { schemaName: schema, dropStatement, statements };\n}\n\n/**\n * Deploy a subgraph schema to the database.\n * - New subgraph → CREATE SCHEMA + tables + register\n * - Same hash → no-op (handler path updated)\n * - Additive change → ALTER TABLE ADD COLUMN / CREATE TABLE for new tables\n * - Breaking change → auto-reindex (drop + recreate)\n */\nexport async function deploySchema(\n\tdb: AnyDb,\n\tdef: SubgraphDefinition,\n\thandlerPath: string,\n\topts?: {\n\t\tforceReindex?: boolean;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tversion?: string;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t},\n): Promise<{\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tdiff?: DeployDiff;\n\t/** Non-fatal caveats the caller should surface (e.g. handler grafts at tip). */\n\twarnings?: string[];\n}> {\n\tvalidateSubgraphDefinition(def);\n\n\tconst { statements, hash } = generateSubgraphSQL(def, opts?.schemaName);\n\tconst { getSubgraph, registerSubgraph } = await import(\n\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t);\n\n\tconst ddlDb = db;\n\n\tconst existing = await getSubgraph(db, def.name, opts?.accountId);\n\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(def.name);\n\n\t// Server owns versioning: use explicit flag, bump patch from existing, or start at 1.0.0\n\tconst newVersion =\n\t\topts?.version ?? (existing ? bumpPatch(existing.version) : \"1.0.0\");\n\n\tconst regData = {\n\t\tname: def.name,\n\t\tversion: newVersion,\n\t\tdefinition: toJsonSafe({\n\t\t\tname: def.name,\n\t\t\tversion: def.version,\n\t\t\tdescription: def.description,\n\t\t\tstartBlock: def.startBlock,\n\t\t\tsources: def.sources,\n\t\t\tschema: def.schema,\n\t\t}) as Record<string, unknown>,\n\t\tschemaHash: hash,\n\t\thandlerPath,\n\t\tapiKeyId: opts?.apiKeyId,\n\t\taccountId: opts?.accountId,\n\t\thandlerCode: opts?.handlerCode,\n\t\tsourceCode: opts?.sourceCode,\n\t\tschemaName,\n\t\tstartBlock: def.startBlock,\n\t};\n\n\tif (existing) {\n\t\t// Guard against zombie rows: registry entry exists but PG schema was dropped\n\t\t// (e.g. partial delete or manual cleanup). Treat as a new subgraph.\n\t\tconst schemaExists = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS (\n\t\t\t\tSELECT 1 FROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${schemaName}\n\t\t\t) AS \"exists\"\n\t\t`\n\t\t\t.execute(ddlDb)\n\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\n\t\tif (!schemaExists) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.schema_hash === hash && !opts?.forceReindex) {\n\t\t\t// Update handler path and code in case file moved or handler changed.\n\t\t\tconst handlerChanged =\n\t\t\t\topts?.handlerCode != null && opts.handlerCode !== existing.handler_code;\n\t\t\tconst { updateSubgraphHandlerPath } = await import(\n\t\t\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t\t\t);\n\t\t\tawait updateSubgraphHandlerPath(db, def.name, handlerPath, {\n\t\t\t\thandlerCode: opts?.handlerCode,\n\t\t\t\tsourceCode: opts?.sourceCode,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\taction: handlerChanged ? \"handler_updated\" : \"unchanged\",\n\t\t\t\tsubgraphId: existing.id,\n\t\t\t\tversion: existing.version,\n\t\t\t\t// A handler-only change takes effect from the CURRENT tip: rows\n\t\t\t\t// already indexed keep the old handler's output. Silent until now —\n\t\t\t\t// say it, and name the fix.\n\t\t\t\t...(handlerChanged\n\t\t\t\t\t? {\n\t\t\t\t\t\t\twarnings: [\n\t\t\t\t\t\t\t\t\"handler changed but schema did not: new logic applies from the current tip only. \" +\n\t\t\t\t\t\t\t\t\t\"Rows already indexed were computed by the previous handler. \" +\n\t\t\t\t\t\t\t\t\t\"To recompute history, redeploy with --reindex (or backfill a range).\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\n\t\tif (existing.schema_hash === hash && opts?.forceReindex) {\n\t\t\t// Same schema but force reindex requested — drop and recreate.\n\t\t\tawait sql\n\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t.execute(ddlDb);\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.definition.schema) {\n\t\t\tconst diff = diffSchema(\n\t\t\t\texisting.definition.schema as SubgraphSchema,\n\t\t\t\tdef.schema,\n\t\t\t);\n\t\t\tconst { breaking, reasons } = hasBreakingChanges(diff);\n\n\t\t\tif (breaking || opts?.forceReindex) {\n\t\t\t\t// Breaking change or forced: drop schema, recreate, register\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\t\tconst deployDiff = toDeployDiff(diff, reasons);\n\t\t\t\treturn {\n\t\t\t\t\taction: \"reindexed\",\n\t\t\t\t\tsubgraphId: sg.id,\n\t\t\t\t\tversion: newVersion,\n\t\t\t\t\tdiff: deployDiff,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Create new tables using the SAME per-table emitter as the full\n\t\t\t// generator, so an additively-created table gets its UNIQUE constraints,\n\t\t\t// composite indexes, column defaults, and FKs — not just the bare columns.\n\t\t\t// (A missing UNIQUE here previously made a handler upsert ON CONFLICT fail\n\t\t\t// at runtime on additively-added tables.)\n\t\t\tconst addedDefs = diff.addedTables\n\t\t\t\t.map((tableName) => ({ tableName, tableDef: def.schema[tableName] }))\n\t\t\t\t.filter(\n\t\t\t\t\t(t): t is { tableName: string; tableDef: SubgraphTable } =>\n\t\t\t\t\t\tt.tableDef !== undefined,\n\t\t\t\t);\n\n\t\t\t// pg_trgm must exist before any search-column GIN index on the new tables.\n\t\t\tif (addedDefs.some(({ tableDef }) => tableNeedsTrgm(tableDef))) {\n\t\t\t\tawait sql.raw(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\").execute(ddlDb);\n\t\t\t}\n\t\t\tfor (const { tableName, tableDef } of addedDefs) {\n\t\t\t\tfor (const stmt of emitTableDDL(schemaName, tableName, tableDef)) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// FKs in a second pass so every referenced (new or pre-existing) table\n\t\t\t// exists first.\n\t\t\tfor (const { tableName, tableDef } of addedDefs) {\n\t\t\t\tfor (const stmt of emitForeignKeyDDL(schemaName, tableName, tableDef)) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add columns to existing tables\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.added.length === 0) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tfor (const colName of colDiff.added) {\n\t\t\t\t\tconst col = tableDef.columns[colName];\n\t\t\t\t\tif (!col) continue;\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tconst nullable = col.nullable\n\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t: ` NOT NULL DEFAULT ${getDefault(col.type)}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD COLUMN ${colName} ${sqlType}${nullable}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tfor (const stmt of emitIndexedColumnIndexDDL(\n\t\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\t\ttableName,\n\t\t\t\t\t\t\tcolName,\n\t\t\t\t\t\t).create) {\n\t\t\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Index-flag flips on EXISTING (populated) columns: pure index DDL,\n\t\t\t// applied in place. CONCURRENTLY because the table has data and this\n\t\t\t// runs outside a transaction (autocommit per statement) — a plain\n\t\t\t// CREATE INDEX would take a write lock for the whole build.\n\t\t\tconst existingSchema = existing.definition.schema as SubgraphSchema;\n\t\t\tconst flagFlips: Record<string, string[]> = {};\n\t\t\tconst needsTrgmForFlips = Object.entries(diff.tables).some(\n\t\t\t\t([tableName, colDiff]) =>\n\t\t\t\t\tcolDiff.indexChanged.some(\n\t\t\t\t\t\t(colName) =>\n\t\t\t\t\t\t\tdef.schema[tableName]?.columns[colName]?.search &&\n\t\t\t\t\t\t\t!existingSchema[tableName]?.columns[colName]?.search,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (needsTrgmForFlips) {\n\t\t\t\tawait sql.raw(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\").execute(ddlDb);\n\t\t\t}\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.indexChanged.length === 0) continue;\n\t\t\t\tflagFlips[tableName] = colDiff.indexChanged;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tfor (const colName of colDiff.indexChanged) {\n\t\t\t\t\tconst was = existingSchema[tableName]?.columns[colName];\n\t\t\t\t\tconst now = def.schema[tableName]?.columns[colName];\n\t\t\t\t\tif (!now) continue;\n\t\t\t\t\tconst trgmIdx = `idx_${schemaName}_${tableName}_${colName}_trgm`;\n\t\t\t\t\tconst indexedIdx = emitIndexedColumnIndexDDL(\n\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tcolName,\n\t\t\t\t\t\t{ concurrently: true },\n\t\t\t\t\t);\n\t\t\t\t\tif (now.indexed && !was?.indexed) {\n\t\t\t\t\t\tfor (const stmt of indexedIdx.create) {\n\t\t\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!now.indexed && was?.indexed) {\n\t\t\t\t\t\tfor (const stmt of indexedIdx.drop) {\n\t\t\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (now.search && !was?.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${trgmIdx} ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t} else if (!now.search && was?.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(`DROP INDEX CONCURRENTLY IF EXISTS ${schemaName}.${trgmIdx}`)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// uniqueKeys additions: ADD CONSTRAINT in place (idempotent via\n\t\t\t// pg_constraint check — Postgres has no ADD CONSTRAINT IF NOT EXISTS).\n\t\t\t// Removals never reach here: hasBreakingChanges classifies them\n\t\t\t// breaking, which lands in the reindex branch above.\n\t\t\tconst addedUq: Record<string, string[][]> = {};\n\t\t\tfor (const [tableName, conDiff] of Object.entries(diff.constraints)) {\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tfor (const cols of conDiff.addedUniqueKeys) {\n\t\t\t\t\tconst constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n\t\t\t\t\tconst exists = await sql<{ exists: boolean }>`\n\t\t\t\t\t\tSELECT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM pg_constraint\n\t\t\t\t\t\t\tWHERE conname = ${constraintName}\n\t\t\t\t\t\t) AS \"exists\"\n\t\t\t\t\t`\n\t\t\t\t\t\t.execute(ddlDb)\n\t\t\t\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\taddedUq[tableName] = [...(addedUq[tableName] ?? []), cols];\n\t\t\t\t}\n\t\t\t\t// Composite indexes: additive both ways. Names are positional in the\n\t\t\t\t// incoming schema; a reordered (unchanged-value) entry keeps its old\n\t\t\t\t// positionally-derived name, which is harmless.\n\t\t\t\tfor (const cols of conDiff.addedIndexes) {\n\t\t\t\t\tconst i = (def.schema[tableName]?.indexes ?? []).findIndex(\n\t\t\t\t\t\t(entry) => JSON.stringify(entry) === JSON.stringify(cols),\n\t\t\t\t\t);\n\t\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t}\n\t\t\t\tfor (const cols of conDiff.removedIndexes) {\n\t\t\t\t\tconst i = (existingSchema[tableName]?.indexes ?? []).findIndex(\n\t\t\t\t\t\t(entry) => JSON.stringify(entry) === JSON.stringify(cols),\n\t\t\t\t\t);\n\t\t\t\t\tif (i < 0) continue;\n\t\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(`DROP INDEX CONCURRENTLY IF EXISTS ${schemaName}.${idxName}`)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\tconst addedCols: Record<string, string[]> = {};\n\t\t\tfor (const [t, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif ((colDiff as ColumnDiff).added.length > 0)\n\t\t\t\t\taddedCols[t] = (colDiff as ColumnDiff).added;\n\t\t\t}\n\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\tremovedTables: [],\n\t\t\t\taddedColumns: addedCols,\n\t\t\t\tbreakingChanges: [],\n\t\t\t\t...(Object.keys(flagFlips).length > 0\n\t\t\t\t\t? { indexChanges: flagFlips }\n\t\t\t\t\t: {}),\n\t\t\t\t...(Object.keys(addedUq).length > 0\n\t\t\t\t\t? { addedUniqueKeys: addedUq }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\treturn {\n\t\t\t\taction: \"updated\",\n\t\t\t\tsubgraphId: sg.id,\n\t\t\t\tversion: newVersion,\n\t\t\t\tdiff: deployDiff,\n\t\t\t};\n\t\t}\n\t}\n\n\t// New subgraph — execute all DDL\n\tfor (const stmt of statements) {\n\t\tawait sql.raw(stmt).execute(ddlDb);\n\t}\n\n\tconst sg = await registerSubgraph(db, regData);\n\treturn { action: \"created\", subgraphId: sg.id, version: newVersion };\n}\n\nfunction getDefault(type: string): string {\n\tswitch (type) {\n\t\tcase \"text\":\n\t\tcase \"principal\":\n\t\t\treturn \"''\";\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn \"0\";\n\t\tcase \"boolean\":\n\t\t\treturn \"false\";\n\t\tcase \"timestamp\":\n\t\t\treturn \"NOW()\";\n\t\tcase \"jsonb\":\n\t\t\treturn \"'{}'\";\n\t\tdefault:\n\t\t\treturn \"''\";\n\t}\n}\n"
40
40
  ],
41
- "mappings": ";;;;AAAA;AAYO,IAAM,qBAAwC,EACnD,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EAAE,EACN,MACA,qBACA,mFACD;AAQM,IAAM,sBAAyC,EACpD,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EAAE,EACN,MACA,uBACA,yGACD;AAEM,IAAM,mBAA0C,EAAE,KAAK;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAQM,IAAM,mBAAuC,EAAE,KAAK,MAC1D,EAAE,MAAM;AA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