@secondlayer/shared 15.2.0 → 15.3.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 (84) hide show
  1. package/dist/src/archive/range-digest.d.ts +61 -9
  2. package/dist/src/archive/semantic-digest-builder.d.ts +61 -9
  3. package/dist/src/coverage/index.d.ts +64 -9
  4. package/dist/src/coverage/index.js.map +2 -2
  5. package/dist/src/db/index.d.ts +63 -10
  6. package/dist/src/db/index.js +19 -1
  7. package/dist/src/db/index.js.map +5 -4
  8. package/dist/src/db/queries/chain-reorgs.d.ts +61 -9
  9. package/dist/src/db/queries/chain-reorgs.js +17 -1
  10. package/dist/src/db/queries/chain-reorgs.js.map +5 -4
  11. package/dist/src/db/queries/contracts.d.ts +108 -28
  12. package/dist/src/db/queries/contracts.js +115 -15
  13. package/dist/src/db/queries/contracts.js.map +7 -5
  14. package/dist/src/db/queries/instance.d.ts +69 -10
  15. package/dist/src/db/queries/instance.js +147 -3
  16. package/dist/src/db/queries/instance.js.map +6 -4
  17. package/dist/src/db/queries/integrity.d.ts +77 -10
  18. package/dist/src/db/queries/integrity.js +236 -2
  19. package/dist/src/db/queries/integrity.js.map +7 -4
  20. package/dist/src/db/queries/subgraph-gaps.d.ts +69 -12
  21. package/dist/src/db/queries/subgraph-gaps.js +7 -3
  22. package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
  23. package/dist/src/db/queries/subgraph-operations.d.ts +61 -9
  24. package/dist/src/db/queries/subgraphs.d.ts +122 -42
  25. package/dist/src/db/queries/subgraphs.js +85 -27
  26. package/dist/src/db/queries/subgraphs.js.map +7 -6
  27. package/dist/src/db/queries/sync-scope.d.ts +61 -9
  28. package/dist/src/db/queries/webhook-replays.d.ts +73 -13
  29. package/dist/src/db/queries/webhook-replays.js +468 -19
  30. package/dist/src/db/queries/webhook-replays.js.map +9 -4
  31. package/dist/src/db/queries/webhooks.d.ts +96 -21
  32. package/dist/src/db/queries/webhooks.js +72 -17
  33. package/dist/src/db/queries/webhooks.js.map +6 -5
  34. package/dist/src/db/schema.d.ts +62 -10
  35. package/dist/src/db/schema.js +20 -1
  36. package/dist/src/db/schema.js.map +4 -3
  37. package/dist/src/db/transition.d.ts +46 -0
  38. package/dist/src/db/transition.js +38 -0
  39. package/dist/src/db/transition.js.map +10 -0
  40. package/dist/src/email/index.d.ts +16 -1
  41. package/dist/src/email/index.js +186 -130
  42. package/dist/src/email/index.js.map +5 -4
  43. package/dist/src/errors.d.ts +7 -1
  44. package/dist/src/errors.js +12 -1
  45. package/dist/src/errors.js.map +3 -3
  46. package/dist/src/index-http.d.ts +19 -10
  47. package/dist/src/index-http.js +5 -4
  48. package/dist/src/index-http.js.map +3 -3
  49. package/dist/src/index.d.ts +98 -19
  50. package/dist/src/index.js +41 -8
  51. package/dist/src/index.js.map +8 -7
  52. package/dist/src/insights/index.d.ts +62 -9
  53. package/dist/src/insights/index.js +55 -5
  54. package/dist/src/insights/index.js.map +7 -6
  55. package/dist/src/node/local-client.d.ts +61 -9
  56. package/dist/src/queue/listener.js +17 -1
  57. package/dist/src/queue/listener.js.map +5 -4
  58. package/dist/src/runtime/index.d.ts +0 -4
  59. package/dist/src/runtime/index.js +54 -4
  60. package/dist/src/runtime/index.js.map +6 -5
  61. package/dist/src/schemas/index.d.ts +36 -10
  62. package/dist/src/schemas/index.js +12 -8
  63. package/dist/src/schemas/index.js.map +4 -4
  64. package/dist/src/schemas/subgraphs.d.ts +22 -9
  65. package/dist/src/schemas/subgraphs.js +10 -6
  66. package/dist/src/schemas/subgraphs.js.map +3 -3
  67. package/dist/src/schemas/webhooks.d.ts +15 -2
  68. package/dist/src/schemas/webhooks.js +2 -2
  69. package/dist/src/schemas/webhooks.js.map +3 -3
  70. package/dist/src/subgraphs/spec.d.ts +5 -1
  71. package/dist/src/webhooks/health.d.ts +27 -0
  72. package/dist/src/webhooks/health.js +84 -0
  73. package/dist/src/webhooks/health.js.map +11 -0
  74. package/migrations/0184_status_checks.ts +92 -0
  75. package/migrations/0185_reorg_generation_settlement_seq.ts +89 -0
  76. package/migrations/0186_api_keys_one_active_tenant_per_name.ts +43 -0
  77. package/migrations/0187_accounts_email_lower_unique.ts +27 -0
  78. package/migrations/0188_webhook_reasons.ts +124 -0
  79. package/migrations/0189_subgraph_lifecycle.ts +83 -0
  80. package/migrations/0190_usage_ledger_debited_usd_micros.ts +59 -0
  81. package/migrations/0191_indexer_state_machines.ts +83 -0
  82. package/migrations/0192_hosted_stack_state.ts +37 -0
  83. package/migrations/0193_accounts_ghost_has_no_email.ts +34 -0
  84. package/package.json +9 -1
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/db/queries/integrity.ts"],
3
+ "sources": ["../src/db/queries/integrity.ts", "../src/env.ts", "../src/logger.ts", "../src/db/queries/instance.ts"],
4
4
  "sourcesContent": [
5
- "import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type ShortBlock = {\n\theight: number;\n\texpectedTxCount: number;\n\tactualTxCount: number;\n};\n\n/**\n * Canonical heights where `transactions` holds fewer (or more) rows than the\n * block was supposed to. `blocks.tx_count` is set by `persistBlock` from the\n * incoming block, so a mismatch means a later write silently moved or dropped\n * a tx after that block was persisted — a reorg replaying the wrong height, a\n * same-height tx_id collision, or a bug in the persist path itself. Ingest\n * used to report the *parsed* count, not the inserted count, so this kind of\n * short block was invisible; a skipped insert looked identical to success.\n *\n * Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this\n * column existed have no baseline to check against. Also scoped to a recent\n * window by default (like `findBrokenLinks`): every new block sets\n * `tx_count`, so the eligible range only grows, and a short block is an\n * active-repair concern, not something worth a full-table scan every cycle.\n */\nexport async function findShortBlocks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<ShortBlock[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\ttx_count: number;\n\t\tactual_count: string | number;\n\t}>`\n\t\tSELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count\n\t\t FROM blocks b\n\t\t LEFT JOIN transactions t ON t.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.tx_count IS NOT NULL\n\t\t ${windowClause}\n\t\t GROUP BY b.height, b.tx_count\n\t\tHAVING COUNT(t.tx_id) <> b.tx_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedTxCount: Number(r.tx_count),\n\t\tactualTxCount: Number(r.actual_count),\n\t}));\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n\t}));\n}\n"
5
+ "import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\nimport { stacksNetworkFromEnv } from \"./instance.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\n/**\n * The three honest answers to \"what is the chain tip\", so no reader derives its\n * own:\n *\n * seen highest block height the indexer has received (`index_progress`)\n * canonical highest block currently canonical in `blocks`\n * contiguous highest height with no gap below it (`index_progress`)\n *\n * `null` when nothing is recorded yet. The node's own tip is a different\n * question (it needs RPC) and is not answered here.\n */\nexport type ChainTipKind = \"seen\" | \"canonical\" | \"contiguous\";\n\nexport async function resolveChainTip(\n\tdb: Kysely<Database>,\n\tkind: ChainTipKind,\n\topts: { network?: string } = {},\n): Promise<number | null> {\n\tif (kind === \"canonical\") {\n\t\tconst row = await db\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.select(\"height\")\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.orderBy(\"height\", \"desc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? Number(row.height) : null;\n\t}\n\tconst column =\n\t\tkind === \"seen\" ? \"highest_seen_block\" : \"last_contiguous_block\";\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(column)\n\t\t.where(\"network\", \"=\", opts.network ?? stacksNetworkFromEnv())\n\t\t.executeTakeFirst();\n\treturn row ? Number(row[column]) : null;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type ShortBlock = {\n\theight: number;\n\texpectedTxCount: number;\n\tactualTxCount: number;\n};\n\n/**\n * Canonical heights where `transactions` holds fewer (or more) rows than the\n * block was supposed to. `blocks.tx_count` is set by `persistBlock` from the\n * incoming block, so a mismatch means a later write silently moved or dropped\n * a tx after that block was persisted — a reorg replaying the wrong height, a\n * same-height tx_id collision, or a bug in the persist path itself. Ingest\n * used to report the *parsed* count, not the inserted count, so this kind of\n * short block was invisible; a skipped insert looked identical to success.\n *\n * Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this\n * column existed have no baseline to check against. Also scoped to a recent\n * window by default (like `findBrokenLinks`): every new block sets\n * `tx_count`, so the eligible range only grows, and a short block is an\n * active-repair concern, not something worth a full-table scan every cycle.\n */\nexport async function findShortBlocks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<ShortBlock[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\ttx_count: number;\n\t\tactual_count: string | number;\n\t}>`\n\t\tSELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count\n\t\t FROM blocks b\n\t\t LEFT JOIN transactions t ON t.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.tx_count IS NOT NULL\n\t\t ${windowClause}\n\t\t GROUP BY b.height, b.tx_count\n\t\tHAVING COUNT(t.tx_id) <> b.tx_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedTxCount: Number(r.tx_count),\n\t\tactualTxCount: Number(r.actual_count),\n\t}));\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n\t}));\n}\n",
6
+ "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
7
+ "import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
8
+ "import type { Kysely } from \"kysely\";\nimport { logger } from \"../../logger.ts\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The network key `index_progress` is written under: `STACKS_NETWORK`, else\n * the deprecated `NETWORK` (logged once so a deployment that only sets it is\n * not silently re-keyed), else mainnet. Not validated; see\n * {@link instanceNetworkFromEnv} for the strict form.\n */\nexport function stacksNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tlogger.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? \"mainnet\");\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n\n/**\n * A stack with no local chain: it reads chain data from a hosted Index/Streams\n * API (`SUBGRAPH_INDEX_API_URL` set) and its own `index_progress` has no row\n * for this network (a hosted tenant). Derived, not configured: a self-hoster\n * running a local indexer has the row and keeps reading its own tables, even\n * with its processors pointed at its own api over HTTP.\n */\nexport async function hasNoLocalChain(\n\tdb: Kysely<Database>,\n\topts: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\thasProgressRow?: (network: string) => Promise<boolean>;\n\t} = {},\n): Promise<boolean> {\n\tconst env = opts.env ?? process.env;\n\tif (!env.SUBGRAPH_INDEX_API_URL) return false;\n\tconst network = stacksNetworkFromEnv(env);\n\tconst hasRow =\n\t\topts.hasProgressRow ?? ((n: string) => hasLocalProgressRow(db, n));\n\treturn !(await hasRow(network));\n}\n\nasync function hasLocalProgressRow(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(\"network\")\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst()\n\t\t.catch(() => undefined);\n\treturn row !== undefined;\n}\n"
6
9
  ],
7
- "mappings": ";AAAA;AASA,eAAsB,QAAQ,CAC7B,IACA,OACiB;AAAA,EACjB,MAAM,cAAc,QAAQ,YAAY,UAAU;AAAA,EAClD,QAAQ,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAelB;AAAA,IACF,QAAQ,EAAE;AAAA,EAEb,OAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,UAAU,OAAO,EAAE,SAAS;AAAA,IAC5B,QAAQ,OAAO,EAAE,OAAO;AAAA,IACxB,MAAM,OAAO,EAAE,IAAI;AAAA,EACpB,EAAE;AAAA;AAG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AO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,QAAQ,OAAO,EAAE,MAAM;AAAA,IACvB,iBAAiB,OAAO,EAAE,QAAQ;AAAA,IAClC,eAAe,OAAO,EAAE,YAAY;AAAA,EACrC,EAAE;AAAA;AAyBH,eAAsB,eAAe,CACpC,IAEA,OAAmD,CAAC,GAC5B;AAAA,EACxB,MAAM,aAAa,KAAK,WAAW,YAAY,MAAS,KAAK;AAAA,EAC7D,MAAM,cAAc,KAAK,QAAQ,YAAY,KAAK,UAAU;AAAA,EAC5D,MAAM,eACL,eAAe,OACZ,QACA,yCAAyC;AAAA,EAC7C,QAAQ,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,MAUlB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOF;AAAA,GACD,QAAQ,EAAE;AAAA,EACZ,OAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,QAAQ,OAAO,EAAE,MAAM;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,gBAAgB,EAAE;AAAA,IAClB,cAAc,EAAE;AAAA,EACjB,EAAE;AAAA;",
11
+ "debugId": "939BB1A42238203764756E2164756E21",
9
12
  "names": []
10
13
  }
@@ -40,6 +40,12 @@ interface SubgraphVerification {
40
40
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
41
41
  unproven: string[];
42
42
  }
43
+ /** Every state `subgraphs.status` can hold; mirrored by the
44
+ * `subgraphs_status_check` CHECK (migration 0189). */
45
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
46
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
47
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
48
+ type WebhookPauseReason = "user" | "circuit";
43
49
  interface BlocksTable {
44
50
  height: number;
45
51
  hash: string;
@@ -179,7 +185,7 @@ interface SubgraphsTable {
179
185
  id: Generated<string>;
180
186
  name: string;
181
187
  version: Generated<string>;
182
- status: Generated<string>;
188
+ status: Generated<SubgraphStatus>;
183
189
  definition: Record<string, unknown>;
184
190
  schema_hash: string;
185
191
  handler_path: string;
@@ -196,8 +202,10 @@ interface SubgraphsTable {
196
202
  handler_code: string | null;
197
203
  source_code: string | null;
198
204
  project_id: string | null;
199
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
200
- expires_at: Date | null;
205
+ /** Set while the account's metered reads are refused (spend cap, credits).
206
+ * Both columns are set or both null; `last_error` stays for real errors. */
207
+ billing_paused_at: Date | null;
208
+ billing_paused_code: string | null;
201
209
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
202
210
  sparse_probe_targets: unknown | null;
203
211
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -211,6 +219,9 @@ interface SubgraphsTable {
211
219
  created_at: Generated<Date>;
212
220
  updated_at: Generated<Date>;
213
221
  }
222
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
223
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
224
+ type AbiStatus = (typeof ABI_STATUSES)[number];
214
225
  interface ContractsTable {
215
226
  contract_id: string;
216
227
  deployer: string;
@@ -219,17 +230,23 @@ interface ContractsTable {
219
230
  abi: unknown | null;
220
231
  declared_traits: Generated<string[]>;
221
232
  inferred_standards: Generated<string[]>;
222
- abi_status: Generated<string>;
233
+ abi_status: Generated<AbiStatus>;
223
234
  abi_fetched_at: Date | null;
235
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
236
+ abi_attempts: Generated<number>;
237
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
238
+ abi_next_attempt_at: Date | null;
224
239
  created_at: Generated<Date>;
225
240
  }
241
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
242
+ type GapReason = "block_missing" | "processing_error";
226
243
  interface SubgraphGapsTable {
227
244
  id: Generated<string>;
228
245
  subgraph_id: string;
229
246
  subgraph_name: string;
230
247
  gap_start: number;
231
248
  gap_end: number;
232
- reason: string;
249
+ reason: GapReason;
233
250
  detected_at: Generated<Date>;
234
251
  resolved_at: Date | null;
235
252
  }
@@ -275,12 +292,13 @@ interface SubgraphOperationsTable {
275
292
  * (those checkpoint on subgraphs.last_processed_block). */
276
293
  cursor_block: string | number | bigint | null;
277
294
  }
295
+ type ApiKeyStatus = "active" | "revoked";
278
296
  interface ApiKeysTable {
279
297
  id: Generated<string>;
280
298
  key_hash: string;
281
299
  key_prefix: string;
282
300
  name: string | null;
283
- status: Generated<string>;
301
+ status: Generated<ApiKeyStatus>;
284
302
  rate_limit: Generated<number>;
285
303
  ip_address: string;
286
304
  account_id: string;
@@ -641,6 +659,10 @@ interface SbtcSettlementsTable {
641
659
  last_checked_at: Generated<Date>;
642
660
  /** Set once, when `settlement_confirmed` first flips true. */
643
661
  confirmed_at: Date | null;
662
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
663
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
664
+ * runtime. */
665
+ seq: Generated<number | string>;
644
666
  updated_at: Generated<Date>;
645
667
  }
646
668
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -760,7 +782,9 @@ interface PendingForkBlocksTable {
760
782
  payload: ColumnType<unknown, unknown, unknown>;
761
783
  received_at: Generated<Date>;
762
784
  }
763
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
785
+ /** Mirrored by the CHECK on `observer_journal.status`. */
786
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
787
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
764
788
  /**
765
789
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
766
790
  * processing columns are updated only after the current derived-state write
@@ -795,7 +819,7 @@ interface StageRegistryTable {
795
819
  enabled: Generated<boolean>;
796
820
  created_at: Generated<Date>;
797
821
  }
798
- /** One versioned sweep of a stage. */
822
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
799
823
  interface StageRunsTable {
800
824
  id: Generated<string>;
801
825
  stage_id: string;
@@ -929,6 +953,7 @@ interface Database {
929
953
  archive_fetches: ArchiveFetchesTable;
930
954
  usage_ledger: UsageLedgerTable;
931
955
  account_balance_alerts: AccountBalanceAlertsTable;
956
+ hosted_stack_state: HostedStackStateTable;
932
957
  webhook_incident_alerts: WebhookIncidentAlertsTable;
933
958
  cli_device_logins: CliDeviceLoginsTable;
934
959
  oauth_clients: OauthClientsTable;
@@ -1012,7 +1037,11 @@ interface UsageLedgerTable {
1012
1037
  * floor to observe past. */
1013
1038
  observed_quantity: string | number | null;
1014
1039
  usd_micros: string | number | bigint;
1040
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1015
1041
  debited: Generated<boolean>;
1042
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1043
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1044
+ debited_usd_micros: Generated<string | number | bigint>;
1016
1045
  source: string;
1017
1046
  /** API key behind a metered read; null for non-read units and older rows. */
1018
1047
  api_key_id: string | null;
@@ -1030,6 +1059,14 @@ interface AccountBalanceAlertsTable {
1030
1059
  sent_2d_at: Date | null;
1031
1060
  sent_stopped_at: Date | null;
1032
1061
  }
1062
+ /** The workload host's report of one account's hosted stack. Written only by
1063
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1064
+ interface HostedStackStateTable {
1065
+ account_id: string;
1066
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1067
+ stop_reason: "credits" | "cap" | "idle" | null;
1068
+ reported_at: Date;
1069
+ }
1033
1070
  /** Debounce state for the webhook-down email: one row per incident, open
1034
1071
  * while `resolved_at` is null. No preference columns by design. */
1035
1072
  interface WebhookIncidentAlertsTable {
@@ -1166,7 +1203,7 @@ interface SentinelAccountsTable {
1166
1203
  linked_at: Generated<Date>;
1167
1204
  via: "created" | "consent";
1168
1205
  }
1169
- type WebhookStatus = "active" | "paused" | "error";
1206
+ type WebhookStatus = "active" | "paused";
1170
1207
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1171
1208
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1172
1209
  * webhooks; the column stays as the discriminator. */
@@ -1192,6 +1229,8 @@ interface WebhooksTable {
1192
1229
  concurrency: Generated<number>;
1193
1230
  circuit_failures: Generated<number>;
1194
1231
  circuit_opened_at: Date | null;
1232
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1233
+ pause_reason: WebhookPauseReason | null;
1195
1234
  last_delivery_at: Date | null;
1196
1235
  last_success_at: Date | null;
1197
1236
  last_error: string | null;
@@ -1202,6 +1241,10 @@ interface WebhooksTable {
1202
1241
  updated_at: Generated<Date>;
1203
1242
  }
1204
1243
  type OutboxStatus = "pending" | "delivered" | "dead";
1244
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1245
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1246
+ * longer contains. */
1247
+ type DeadReason = "exhausted" | "orphaned";
1205
1248
  interface WebhookOutboxTable {
1206
1249
  id: Generated<string>;
1207
1250
  webhook_id: string;
@@ -1231,6 +1274,8 @@ interface WebhookOutboxTable {
1231
1274
  * into an orphaned fork. Null otherwise — delivery failures track their
1232
1275
  * history on `webhooks.last_error`, not per-row. */
1233
1276
  last_error: string | null;
1277
+ /** Set exactly while `status` is `dead`. */
1278
+ dead_reason: DeadReason | null;
1234
1279
  created_at: Generated<Date>;
1235
1280
  }
1236
1281
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1280,6 +1325,13 @@ interface TriggerEvaluatorStateTable {
1280
1325
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1281
1326
  * the evaluator fast-forwards it on first run. */
1282
1327
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1328
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1329
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1330
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1331
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1332
+ * transaction that emits a batch and advances the cursor, so a reorg that
1333
+ * lands mid-tick rolls the batch back. */
1334
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1283
1335
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1284
1336
  * chain-trigger evaluator (plan 060) — a separate clock from
1285
1337
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards
@@ -1414,7 +1466,7 @@ interface FeedbackTicketsTable {
1414
1466
  interface GapRange {
1415
1467
  start: number;
1416
1468
  end: number;
1417
- reason: string;
1469
+ reason: GapReason;
1418
1470
  }
1419
1471
  interface SubgraphGapRow {
1420
1472
  id: string;
@@ -1449,9 +1501,14 @@ declare function findSubgraphGaps(db: Kysely<Database>, subgraphName: string, op
1449
1501
  }>;
1450
1502
  /**
1451
1503
  * Mark gaps as resolved within a block range. Idempotent.
1452
- * Only resolves gaps fully contained within [fromBlock, toBlock].
1504
+ * Only resolves gaps fully contained within [fromBlock, toBlock]. With
1505
+ * `detectedBefore`, gaps recorded at or after it stay open: a walk passes its
1506
+ * own start time (from the database clock) so a block that failed during the
1507
+ * walk is not resolved by the walk that just recorded it.
1453
1508
  */
1454
- declare function resolveGaps(db: Kysely<Database>, subgraphName: string, fromBlock: number, toBlock: number): Promise<number>;
1509
+ declare function resolveGaps(db: Kysely<Database>, subgraphName: string, fromBlock: number, toBlock: number, opts?: {
1510
+ detectedBefore?: Date
1511
+ }): Promise<number>;
1455
1512
  /**
1456
1513
  * Total missing blocks across unresolved gaps for a subgraph.
1457
1514
  */
@@ -46,8 +46,12 @@ async function findSubgraphGaps(db, subgraphName, opts) {
46
46
  total: Number(countResult.count)
47
47
  };
48
48
  }
49
- async function resolveGaps(db, subgraphName, fromBlock, toBlock) {
50
- const result = await db.updateTable("subgraph_gaps").set({ resolved_at: new Date }).where("subgraph_name", "=", subgraphName).where("resolved_at", "is", null).where("gap_start", ">=", fromBlock).where("gap_end", "<=", toBlock).executeTakeFirst();
49
+ async function resolveGaps(db, subgraphName, fromBlock, toBlock, opts) {
50
+ let q = db.updateTable("subgraph_gaps").set({ resolved_at: new Date }).where("subgraph_name", "=", subgraphName).where("resolved_at", "is", null).where("gap_start", ">=", fromBlock).where("gap_end", "<=", toBlock);
51
+ if (opts?.detectedBefore) {
52
+ q = q.where("detected_at", "<", opts.detectedBefore);
53
+ }
54
+ const result = await q.executeTakeFirst();
51
55
  return Number(result.numUpdatedRows);
52
56
  }
53
57
  async function countSubgraphMissingBlocks(db, subgraphName) {
@@ -83,5 +87,5 @@ export {
83
87
  resolveGaps
84
88
  };
85
89
 
86
- //# debugId=3220DE92B2B7A0A764756E2164756E21
90
+ //# debugId=58476E98387FA37B64756E2164756E21
87
91
  //# sourceMappingURL=subgraph-gaps.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/queries/subgraph-gaps.ts"],
4
4
  "sourcesContent": [
5
- "import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport interface GapRange {\n\tstart: number;\n\tend: number;\n\treason: string;\n}\n\nexport interface SubgraphGapRow {\n\tid: string;\n\tsubgraphName: string;\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n\treason: string;\n\tdetectedAt: Date;\n\tresolvedAt: Date | null;\n}\n\nexport interface GapSummary {\n\tsubgraphName: string;\n\tgapCount: number;\n\ttotalMissingBlocks: number;\n}\n\n/**\n * Batch-insert gap ranges for a subgraph. Append-only — no merge on write.\n * Callers should coalesce contiguous skipped blocks into ranges before calling.\n */\nexport async function recordGapBatch(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tsubgraphName: string,\n\tgaps: GapRange[],\n): Promise<void> {\n\tif (gaps.length === 0) return;\n\n\tawait db\n\t\t.insertInto(\"subgraph_gaps\")\n\t\t.values(\n\t\t\tgaps.map((g) => ({\n\t\t\t\tsubgraph_id: subgraphId,\n\t\t\t\tsubgraph_name: subgraphName,\n\t\t\t\tgap_start: g.start,\n\t\t\t\tgap_end: g.end,\n\t\t\t\treason: g.reason,\n\t\t\t})),\n\t\t)\n\t\t.execute();\n}\n\n/**\n * List gaps for a subgraph with computed size.\n */\nexport async function findSubgraphGaps(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n\topts?: { limit?: number; offset?: number; unresolvedOnly?: boolean },\n): Promise<{ gaps: SubgraphGapRow[]; total: number }> {\n\tconst limit = opts?.limit ?? 50;\n\tconst offset = opts?.offset ?? 0;\n\tconst unresolvedOnly = opts?.unresolvedOnly ?? true;\n\n\tlet baseQuery = db\n\t\t.selectFrom(\"subgraph_gaps\")\n\t\t.where(\"subgraph_name\", \"=\", subgraphName);\n\n\tif (unresolvedOnly) {\n\t\tbaseQuery = baseQuery.where(\"resolved_at\", \"is\", null);\n\t}\n\n\tconst [rows, countResult] = await Promise.all([\n\t\tbaseQuery\n\t\t\t.select([\n\t\t\t\t\"id\",\n\t\t\t\t\"subgraph_name\",\n\t\t\t\t\"gap_start\",\n\t\t\t\t\"gap_end\",\n\t\t\t\tsql<number>`gap_end - gap_start + 1`.as(\"size\"),\n\t\t\t\t\"reason\",\n\t\t\t\t\"detected_at\",\n\t\t\t\t\"resolved_at\",\n\t\t\t])\n\t\t\t.orderBy(\"gap_start\", \"asc\")\n\t\t\t.limit(limit)\n\t\t\t.offset(offset)\n\t\t\t.execute(),\n\t\tbaseQuery\n\t\t\t.select(sql<number>`count(*)`.as(\"count\"))\n\t\t\t.executeTakeFirstOrThrow(),\n\t]);\n\n\treturn {\n\t\tgaps: rows.map((r) => ({\n\t\t\tid: r.id,\n\t\t\tsubgraphName: r.subgraph_name,\n\t\t\tgapStart: Number(r.gap_start),\n\t\t\tgapEnd: Number(r.gap_end),\n\t\t\tsize: Number(r.size),\n\t\t\treason: r.reason,\n\t\t\tdetectedAt: r.detected_at,\n\t\t\tresolvedAt: r.resolved_at,\n\t\t})),\n\t\ttotal: Number(countResult.count),\n\t};\n}\n\n/**\n * Mark gaps as resolved within a block range. Idempotent.\n * Only resolves gaps fully contained within [fromBlock, toBlock].\n */\nexport async function resolveGaps(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n\tfromBlock: number,\n\ttoBlock: number,\n): Promise<number> {\n\tconst result = await db\n\t\t.updateTable(\"subgraph_gaps\")\n\t\t.set({ resolved_at: new Date() })\n\t\t.where(\"subgraph_name\", \"=\", subgraphName)\n\t\t.where(\"resolved_at\", \"is\", null)\n\t\t.where(\"gap_start\", \">=\", fromBlock)\n\t\t.where(\"gap_end\", \"<=\", toBlock)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numUpdatedRows);\n}\n\n/**\n * Total missing blocks across unresolved gaps for a subgraph.\n */\nexport async function countSubgraphMissingBlocks(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(gap_end - gap_start + 1), 0) AS total\n FROM subgraph_gaps\n WHERE subgraph_name = ${subgraphName}\n AND resolved_at IS NULL\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\n/**\n * Aggregate gap counts + missing blocks grouped by subgraph_name.\n * Used by the /status endpoint for per-subgraph gap summary.\n */\nexport async function getGapSummaryBySubgraph(\n\tdb: Kysely<Database>,\n): Promise<GapSummary[]> {\n\tconst { rows } = await sql<{\n\t\tsubgraph_name: string;\n\t\tgap_count: string;\n\t\ttotal_missing: string;\n\t}>`\n SELECT\n subgraph_name,\n COUNT(*) AS gap_count,\n COALESCE(SUM(gap_end - gap_start + 1), 0) AS total_missing\n FROM subgraph_gaps\n WHERE resolved_at IS NULL\n GROUP BY subgraph_name\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tsubgraphName: r.subgraph_name,\n\t\tgapCount: Number(r.gap_count),\n\t\ttotalMissingBlocks: Number(r.total_missing),\n\t}));\n}\n"
5
+ "import { type Kysely, sql } from \"kysely\";\nimport type { Database, GapReason } from \"../types.ts\";\n\nexport interface GapRange {\n\tstart: number;\n\tend: number;\n\treason: GapReason;\n}\n\nexport interface SubgraphGapRow {\n\tid: string;\n\tsubgraphName: string;\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n\treason: string;\n\tdetectedAt: Date;\n\tresolvedAt: Date | null;\n}\n\nexport interface GapSummary {\n\tsubgraphName: string;\n\tgapCount: number;\n\ttotalMissingBlocks: number;\n}\n\n/**\n * Batch-insert gap ranges for a subgraph. Append-only — no merge on write.\n * Callers should coalesce contiguous skipped blocks into ranges before calling.\n */\nexport async function recordGapBatch(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tsubgraphName: string,\n\tgaps: GapRange[],\n): Promise<void> {\n\tif (gaps.length === 0) return;\n\n\tawait db\n\t\t.insertInto(\"subgraph_gaps\")\n\t\t.values(\n\t\t\tgaps.map((g) => ({\n\t\t\t\tsubgraph_id: subgraphId,\n\t\t\t\tsubgraph_name: subgraphName,\n\t\t\t\tgap_start: g.start,\n\t\t\t\tgap_end: g.end,\n\t\t\t\treason: g.reason,\n\t\t\t})),\n\t\t)\n\t\t.execute();\n}\n\n/**\n * List gaps for a subgraph with computed size.\n */\nexport async function findSubgraphGaps(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n\topts?: { limit?: number; offset?: number; unresolvedOnly?: boolean },\n): Promise<{ gaps: SubgraphGapRow[]; total: number }> {\n\tconst limit = opts?.limit ?? 50;\n\tconst offset = opts?.offset ?? 0;\n\tconst unresolvedOnly = opts?.unresolvedOnly ?? true;\n\n\tlet baseQuery = db\n\t\t.selectFrom(\"subgraph_gaps\")\n\t\t.where(\"subgraph_name\", \"=\", subgraphName);\n\n\tif (unresolvedOnly) {\n\t\tbaseQuery = baseQuery.where(\"resolved_at\", \"is\", null);\n\t}\n\n\tconst [rows, countResult] = await Promise.all([\n\t\tbaseQuery\n\t\t\t.select([\n\t\t\t\t\"id\",\n\t\t\t\t\"subgraph_name\",\n\t\t\t\t\"gap_start\",\n\t\t\t\t\"gap_end\",\n\t\t\t\tsql<number>`gap_end - gap_start + 1`.as(\"size\"),\n\t\t\t\t\"reason\",\n\t\t\t\t\"detected_at\",\n\t\t\t\t\"resolved_at\",\n\t\t\t])\n\t\t\t.orderBy(\"gap_start\", \"asc\")\n\t\t\t.limit(limit)\n\t\t\t.offset(offset)\n\t\t\t.execute(),\n\t\tbaseQuery\n\t\t\t.select(sql<number>`count(*)`.as(\"count\"))\n\t\t\t.executeTakeFirstOrThrow(),\n\t]);\n\n\treturn {\n\t\tgaps: rows.map((r) => ({\n\t\t\tid: r.id,\n\t\t\tsubgraphName: r.subgraph_name,\n\t\t\tgapStart: Number(r.gap_start),\n\t\t\tgapEnd: Number(r.gap_end),\n\t\t\tsize: Number(r.size),\n\t\t\treason: r.reason,\n\t\t\tdetectedAt: r.detected_at,\n\t\t\tresolvedAt: r.resolved_at,\n\t\t})),\n\t\ttotal: Number(countResult.count),\n\t};\n}\n\n/**\n * Mark gaps as resolved within a block range. Idempotent.\n * Only resolves gaps fully contained within [fromBlock, toBlock]. With\n * `detectedBefore`, gaps recorded at or after it stay open: a walk passes its\n * own start time (from the database clock) so a block that failed during the\n * walk is not resolved by the walk that just recorded it.\n */\nexport async function resolveGaps(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n\tfromBlock: number,\n\ttoBlock: number,\n\topts?: { detectedBefore?: Date },\n): Promise<number> {\n\tlet q = db\n\t\t.updateTable(\"subgraph_gaps\")\n\t\t.set({ resolved_at: new Date() })\n\t\t.where(\"subgraph_name\", \"=\", subgraphName)\n\t\t.where(\"resolved_at\", \"is\", null)\n\t\t.where(\"gap_start\", \">=\", fromBlock)\n\t\t.where(\"gap_end\", \"<=\", toBlock);\n\tif (opts?.detectedBefore) {\n\t\tq = q.where(\"detected_at\", \"<\", opts.detectedBefore);\n\t}\n\tconst result = await q.executeTakeFirst();\n\n\treturn Number(result.numUpdatedRows);\n}\n\n/**\n * Total missing blocks across unresolved gaps for a subgraph.\n */\nexport async function countSubgraphMissingBlocks(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(gap_end - gap_start + 1), 0) AS total\n FROM subgraph_gaps\n WHERE subgraph_name = ${subgraphName}\n AND resolved_at IS NULL\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\n/**\n * Aggregate gap counts + missing blocks grouped by subgraph_name.\n * Used by the /status endpoint for per-subgraph gap summary.\n */\nexport async function getGapSummaryBySubgraph(\n\tdb: Kysely<Database>,\n): Promise<GapSummary[]> {\n\tconst { rows } = await sql<{\n\t\tsubgraph_name: string;\n\t\tgap_count: string;\n\t\ttotal_missing: string;\n\t}>`\n SELECT\n subgraph_name,\n COUNT(*) AS gap_count,\n COALESCE(SUM(gap_end - gap_start + 1), 0) AS total_missing\n FROM subgraph_gaps\n WHERE resolved_at IS NULL\n GROUP BY subgraph_name\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tsubgraphName: r.subgraph_name,\n\t\tgapCount: Number(r.gap_count),\n\t\ttotalMissingBlocks: Number(r.total_missing),\n\t}));\n}\n"
6
6
  ],
7
- "mappings": ";AAAA;AA8BA,eAAsB,cAAc,CACnC,IACA,YACA,cACA,MACgB;AAAA,EAChB,IAAI,KAAK,WAAW;AAAA,IAAG;AAAA,EAEvB,MAAM,GACJ,WAAW,eAAe,EAC1B,OACA,KAAK,IAAI,CAAC,OAAO;AAAA,IAChB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,WAAW,EAAE;AAAA,IACb,SAAS,EAAE;AAAA,IACX,QAAQ,EAAE;AAAA,EACX,EAAE,CACH,EACC,QAAQ;AAAA;AAMX,eAAsB,gBAAgB,CACrC,IACA,cACA,MACqD;AAAA,EACrD,MAAM,QAAQ,MAAM,SAAS;AAAA,EAC7B,MAAM,SAAS,MAAM,UAAU;AAAA,EAC/B,MAA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AO,KAAK,IAAI,SAAS,CAAC;AAAA;AAOlC,eAAsB,uBAAuB,CAC5C,IACwB;AAAA,EACxB,QAAQ,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAYpB,QAAQ,EAAE;AAAA,EAEb,OAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,cAAc,EAAE;AAAA,IAChB,UAAU,OAAO,EAAE,SAAS;AAAA,IAC5B,oBAAoB,OAAO,EAAE,aAAa;AAAA,EAC3C,EAAE;AAAA;",
8
+ "debugId": "58476E98387FA37B64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -40,6 +40,12 @@ interface SubgraphVerification {
40
40
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
41
41
  unproven: string[];
42
42
  }
43
+ /** Every state `subgraphs.status` can hold; mirrored by the
44
+ * `subgraphs_status_check` CHECK (migration 0189). */
45
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
46
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
47
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
48
+ type WebhookPauseReason = "user" | "circuit";
43
49
  interface BlocksTable {
44
50
  height: number;
45
51
  hash: string;
@@ -179,7 +185,7 @@ interface SubgraphsTable {
179
185
  id: Generated<string>;
180
186
  name: string;
181
187
  version: Generated<string>;
182
- status: Generated<string>;
188
+ status: Generated<SubgraphStatus>;
183
189
  definition: Record<string, unknown>;
184
190
  schema_hash: string;
185
191
  handler_path: string;
@@ -196,8 +202,10 @@ interface SubgraphsTable {
196
202
  handler_code: string | null;
197
203
  source_code: string | null;
198
204
  project_id: string | null;
199
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
200
- expires_at: Date | null;
205
+ /** Set while the account's metered reads are refused (spend cap, credits).
206
+ * Both columns are set or both null; `last_error` stays for real errors. */
207
+ billing_paused_at: Date | null;
208
+ billing_paused_code: string | null;
201
209
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
202
210
  sparse_probe_targets: unknown | null;
203
211
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -211,6 +219,9 @@ interface SubgraphsTable {
211
219
  created_at: Generated<Date>;
212
220
  updated_at: Generated<Date>;
213
221
  }
222
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
223
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
224
+ type AbiStatus = (typeof ABI_STATUSES)[number];
214
225
  interface ContractsTable {
215
226
  contract_id: string;
216
227
  deployer: string;
@@ -219,17 +230,23 @@ interface ContractsTable {
219
230
  abi: unknown | null;
220
231
  declared_traits: Generated<string[]>;
221
232
  inferred_standards: Generated<string[]>;
222
- abi_status: Generated<string>;
233
+ abi_status: Generated<AbiStatus>;
223
234
  abi_fetched_at: Date | null;
235
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
236
+ abi_attempts: Generated<number>;
237
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
238
+ abi_next_attempt_at: Date | null;
224
239
  created_at: Generated<Date>;
225
240
  }
241
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
242
+ type GapReason = "block_missing" | "processing_error";
226
243
  interface SubgraphGapsTable {
227
244
  id: Generated<string>;
228
245
  subgraph_id: string;
229
246
  subgraph_name: string;
230
247
  gap_start: number;
231
248
  gap_end: number;
232
- reason: string;
249
+ reason: GapReason;
233
250
  detected_at: Generated<Date>;
234
251
  resolved_at: Date | null;
235
252
  }
@@ -275,12 +292,13 @@ interface SubgraphOperationsTable {
275
292
  * (those checkpoint on subgraphs.last_processed_block). */
276
293
  cursor_block: string | number | bigint | null;
277
294
  }
295
+ type ApiKeyStatus = "active" | "revoked";
278
296
  interface ApiKeysTable {
279
297
  id: Generated<string>;
280
298
  key_hash: string;
281
299
  key_prefix: string;
282
300
  name: string | null;
283
- status: Generated<string>;
301
+ status: Generated<ApiKeyStatus>;
284
302
  rate_limit: Generated<number>;
285
303
  ip_address: string;
286
304
  account_id: string;
@@ -641,6 +659,10 @@ interface SbtcSettlementsTable {
641
659
  last_checked_at: Generated<Date>;
642
660
  /** Set once, when `settlement_confirmed` first flips true. */
643
661
  confirmed_at: Date | null;
662
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
663
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
664
+ * runtime. */
665
+ seq: Generated<number | string>;
644
666
  updated_at: Generated<Date>;
645
667
  }
646
668
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -760,7 +782,9 @@ interface PendingForkBlocksTable {
760
782
  payload: ColumnType<unknown, unknown, unknown>;
761
783
  received_at: Generated<Date>;
762
784
  }
763
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
785
+ /** Mirrored by the CHECK on `observer_journal.status`. */
786
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
787
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
764
788
  /**
765
789
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
766
790
  * processing columns are updated only after the current derived-state write
@@ -795,7 +819,7 @@ interface StageRegistryTable {
795
819
  enabled: Generated<boolean>;
796
820
  created_at: Generated<Date>;
797
821
  }
798
- /** One versioned sweep of a stage. */
822
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
799
823
  interface StageRunsTable {
800
824
  id: Generated<string>;
801
825
  stage_id: string;
@@ -929,6 +953,7 @@ interface Database {
929
953
  archive_fetches: ArchiveFetchesTable;
930
954
  usage_ledger: UsageLedgerTable;
931
955
  account_balance_alerts: AccountBalanceAlertsTable;
956
+ hosted_stack_state: HostedStackStateTable;
932
957
  webhook_incident_alerts: WebhookIncidentAlertsTable;
933
958
  cli_device_logins: CliDeviceLoginsTable;
934
959
  oauth_clients: OauthClientsTable;
@@ -1012,7 +1037,11 @@ interface UsageLedgerTable {
1012
1037
  * floor to observe past. */
1013
1038
  observed_quantity: string | number | null;
1014
1039
  usd_micros: string | number | bigint;
1040
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1015
1041
  debited: Generated<boolean>;
1042
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1043
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1044
+ debited_usd_micros: Generated<string | number | bigint>;
1016
1045
  source: string;
1017
1046
  /** API key behind a metered read; null for non-read units and older rows. */
1018
1047
  api_key_id: string | null;
@@ -1030,6 +1059,14 @@ interface AccountBalanceAlertsTable {
1030
1059
  sent_2d_at: Date | null;
1031
1060
  sent_stopped_at: Date | null;
1032
1061
  }
1062
+ /** The workload host's report of one account's hosted stack. Written only by
1063
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1064
+ interface HostedStackStateTable {
1065
+ account_id: string;
1066
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1067
+ stop_reason: "credits" | "cap" | "idle" | null;
1068
+ reported_at: Date;
1069
+ }
1033
1070
  /** Debounce state for the webhook-down email: one row per incident, open
1034
1071
  * while `resolved_at` is null. No preference columns by design. */
1035
1072
  interface WebhookIncidentAlertsTable {
@@ -1167,7 +1204,7 @@ interface SentinelAccountsTable {
1167
1204
  via: "created" | "consent";
1168
1205
  }
1169
1206
  type SubgraphOperation = Selectable<SubgraphOperationsTable>;
1170
- type WebhookStatus = "active" | "paused" | "error";
1207
+ type WebhookStatus = "active" | "paused";
1171
1208
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1172
1209
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1173
1210
  * webhooks; the column stays as the discriminator. */
@@ -1193,6 +1230,8 @@ interface WebhooksTable {
1193
1230
  concurrency: Generated<number>;
1194
1231
  circuit_failures: Generated<number>;
1195
1232
  circuit_opened_at: Date | null;
1233
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1234
+ pause_reason: WebhookPauseReason | null;
1196
1235
  last_delivery_at: Date | null;
1197
1236
  last_success_at: Date | null;
1198
1237
  last_error: string | null;
@@ -1203,6 +1242,10 @@ interface WebhooksTable {
1203
1242
  updated_at: Generated<Date>;
1204
1243
  }
1205
1244
  type OutboxStatus = "pending" | "delivered" | "dead";
1245
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1246
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1247
+ * longer contains. */
1248
+ type DeadReason = "exhausted" | "orphaned";
1206
1249
  interface WebhookOutboxTable {
1207
1250
  id: Generated<string>;
1208
1251
  webhook_id: string;
@@ -1232,6 +1275,8 @@ interface WebhookOutboxTable {
1232
1275
  * into an orphaned fork. Null otherwise — delivery failures track their
1233
1276
  * history on `webhooks.last_error`, not per-row. */
1234
1277
  last_error: string | null;
1278
+ /** Set exactly while `status` is `dead`. */
1279
+ dead_reason: DeadReason | null;
1235
1280
  created_at: Generated<Date>;
1236
1281
  }
1237
1282
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1281,6 +1326,13 @@ interface TriggerEvaluatorStateTable {
1281
1326
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1282
1327
  * the evaluator fast-forwards it on first run. */
1283
1328
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1329
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1330
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1331
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1332
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1333
+ * transaction that emits a batch and advances the cursor, so a reorg that
1334
+ * lands mid-tick rolls the batch back. */
1335
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1284
1336
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1285
1337
  * chain-trigger evaluator (plan 060) — a separate clock from
1286
1338
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards