@secondlayer/shared 15.5.0 → 15.6.1

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.
@@ -1502,11 +1502,13 @@ declare const subgraphMachine: Machine<SubgraphStatus>;
1502
1502
  /**
1503
1503
  * Move a subgraph from one of `from` to `to`, writing `set` in the same
1504
1504
  * statement. Returns the row, or `null` when it was not in a `from` state
1505
- * (something else, a halt or a redeploy, decided first): log and stop, never
1506
- * retry. Staying in the same state (`reindexing -> reindexing`) is a plain
1507
- * conditional write, not a transition.
1505
+ * (something else, a halt or a redeploy, decided first) or the id is gone
1506
+ * (deleted, or recreated under the same name with a new id): log and stop,
1507
+ * never retry. Addressed by id so work that belonged to an old row can't touch
1508
+ * a recreated one. Staying in the same state (`reindexing -> reindexing`) is
1509
+ * a plain conditional write, not a transition.
1508
1510
  */
1509
- declare function transitionSubgraph(db: Kysely2<Database>, name: string, from: readonly SubgraphStatus[], to: SubgraphStatus, set?: Record<string, unknown>): Promise<Subgraph | null>;
1511
+ declare function transitionSubgraph(db: Kysely2<Database>, subgraphId: string, from: readonly SubgraphStatus[], to: SubgraphStatus, set?: Record<string, unknown>): Promise<Subgraph | null>;
1510
1512
  /** Convert a subgraph name to its PostgreSQL schema name. */
1511
1513
  declare function pgSchemaName(subgraphName: string): string;
1512
1514
  /** OSS writes empty account_id — name is the local unique key. */
@@ -121,15 +121,14 @@ var subgraphMachine = defineMachine({
121
121
  error: ["reindexing", "active"]
122
122
  }
123
123
  });
124
- function transitionSubgraph(db, name, from, to, set) {
124
+ function transitionSubgraph(db, subgraphId, from, to, set) {
125
125
  for (const state of from) {
126
126
  if (state !== to)
127
127
  subgraphMachine.assert(state, to);
128
128
  }
129
129
  return casTransition(db, {
130
130
  table: "subgraphs",
131
- key: "name",
132
- id: name,
131
+ id: subgraphId,
133
132
  from,
134
133
  to,
135
134
  set
@@ -302,5 +301,5 @@ export {
302
301
  updateSubgraphHandlerPath
303
302
  };
304
303
 
305
- //# debugId=53B116467828D4A264756E2164756E21
304
+ //# debugId=D9FC72868ADBC9D264756E2164756E21
306
305
  //# sourceMappingURL=subgraphs.js.map
@@ -2,13 +2,13 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/queries/subgraphs.ts", "../src/mode.ts", "../src/schemas/subgraphs.ts", "../src/db/jsonb.ts", "../src/db/transition.ts"],
4
4
  "sourcesContent": [
5
- "import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport {\n\tSUBGRAPH_STATES,\n\ttype SubgraphStatus,\n\ttype SubgraphVerification,\n} from \"../../schemas/subgraphs.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * Subgraph lifecycle. `error` is sticky: a live walk never clears it, only a\n * redeploy (`error -> active`) or a reindex (`error -> reindexing`) does.\n * Every status write goes through {@link transitionSubgraph}; the live\n * progress writes below touch the cursor only and are gated on the status\n * they are valid for.\n */\nexport const subgraphMachine: Machine<SubgraphStatus> = defineMachine({\n\tstates: SUBGRAPH_STATES,\n\ttransitions: {\n\t\tactive: [\"reindexing\", \"error\"],\n\t\treindexing: [\"active\", \"error\"],\n\t\terror: [\"reindexing\", \"active\"],\n\t},\n});\n\n/**\n * Move a subgraph from one of `from` to `to`, writing `set` in the same\n * statement. Returns the row, or `null` when it was not in a `from` state\n * (something else, a halt or a redeploy, decided first): log and stop, never\n * retry. Staying in the same state (`reindexing -> reindexing`) is a plain\n * conditional write, not a transition.\n */\nexport function transitionSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\tfrom: readonly SubgraphStatus[],\n\tto: SubgraphStatus,\n\tset?: Record<string, unknown>,\n): Promise<Subgraph | null> {\n\tfor (const state of from) {\n\t\tif (state !== to) subgraphMachine.assert(state, to);\n\t}\n\treturn casTransition<SubgraphStatus, Subgraph>(db, {\n\t\ttable: \"subgraphs\",\n\t\tkey: \"name\",\n\t\tid: name,\n\t\tfrom,\n\t\tto,\n\t\tset,\n\t});\n}\n\n/** Convert a subgraph name to its PostgreSQL schema name. */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: data.pin ?? null,\n\t\tpin_preimage: data.pinPreimage ?? null,\n\t\tverification: data.verification\n\t\t\t? jsonb<SubgraphVerification>(data.verification)\n\t\t\t: null,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: values.pin,\n\t\tpin_preimage: values.pin_preimage,\n\t\tverification: values.verification,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\n/** The hash half of a cursor write. Absent when the caller has none; the\n * `subgraphs_clear_stale_block_hash` trigger (0197) then clears the stored hash\n * for a moved cursor instead of leaving one that names another block. */\nfunction cursorHash(blockHash: string | undefined) {\n\treturn blockHash === undefined\n\t\t? {}\n\t\t: { last_processed_block_hash: blockHash };\n}\n\n/**\n * Reindex progress: moves the cursor of a subgraph that is still\n * `reindexing`, and nothing else. Returns `false` when the subgraph left that\n * state (halted, cancelled, redeployed): the walk must not write on, and its\n * progress never revives a halt.\n */\nexport async function setReindexCursor(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"reindexing\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * moves an `active` subgraph to 'error' and records its height as processed;\n * the cursor half goes through the same conditional `<` guard as\n * {@link recordLiveProgress}. A reindexing or already-halted subgraph is left\n * alone. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only: reindex/backfill halts go through\n * {@link transitionSubgraph}. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tblockHeight: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\n/** Record a billing pause. Status, cursor, counters and `last_error` are\n * untouched: a paused subgraph is healthy, just waiting on its account. */\nexport async function markSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tcode: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: sql`COALESCE(billing_paused_at, now())`,\n\t\t\tbilling_paused_code: code,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\n/** Clear a billing pause once reads succeed again. */\nexport async function clearSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: null,\n\t\t\tbilling_paused_code: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"billing_paused_at\", \"is not\", null)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\thandlerPath: string,\n\topts?: {\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\t...(opts?.pin !== undefined ? { pin: opts.pin } : {}),\n\t\t\t...(opts?.pinPreimage !== undefined\n\t\t\t\t? { pin_preimage: opts.pinPreimage }\n\t\t\t\t: {}),\n\t\t\t...(opts?.verification !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tverification: opts.verification\n\t\t\t\t\t\t\t? jsonb<SubgraphVerification>(opts.verification)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// One transaction: DDL is transactional in Postgres, so a failed row delete\n\t// leaves the schema in place instead of a registered subgraph with no tables.\n\tconst remove = async (trx: Kysely<Database>) => {\n\t\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\t\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\t\ttrx,\n\t\t);\n\t\t// Remove from registry\n\t\tawait trx.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\t};\n\tif (db.isTransaction) await remove(db);\n\telse await db.transaction().execute(remove);\n\n\treturn subgraph;\n}\n\n/** Live-walk progress write: advances the cursor of an `active` subgraph and\n * never touches status. A `reindexing` or `error` subgraph is a no-op here:\n * the old promote-toward-active CASE let a live commit undo a halt and flap\n * a parked subgraph back into catch-up against its own reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Cursor only, `active` subgraphs only.\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n",
5
+ "import { type Kysely, sql } from \"kysely\";\nimport { isPlatformMode } from \"../../mode.ts\";\nimport {\n\tSUBGRAPH_STATES,\n\ttype SubgraphStatus,\n\ttype SubgraphVerification,\n} from \"../../schemas/subgraphs.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport { type Machine, casTransition, defineMachine } from \"../transition.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * Subgraph lifecycle. `error` is sticky: a live walk never clears it, only a\n * redeploy (`error -> active`) or a reindex (`error -> reindexing`) does.\n * Every status write goes through {@link transitionSubgraph}; the live\n * progress writes below touch the cursor only and are gated on the status\n * they are valid for.\n */\nexport const subgraphMachine: Machine<SubgraphStatus> = defineMachine({\n\tstates: SUBGRAPH_STATES,\n\ttransitions: {\n\t\tactive: [\"reindexing\", \"error\"],\n\t\treindexing: [\"active\", \"error\"],\n\t\terror: [\"reindexing\", \"active\"],\n\t},\n});\n\n/**\n * Move a subgraph from one of `from` to `to`, writing `set` in the same\n * statement. Returns the row, or `null` when it was not in a `from` state\n * (something else, a halt or a redeploy, decided first) or the id is gone\n * (deleted, or recreated under the same name with a new id): log and stop,\n * never retry. Addressed by id so work that belonged to an old row can't touch\n * a recreated one. Staying in the same state (`reindexing -> reindexing`) is\n * a plain conditional write, not a transition.\n */\nexport function transitionSubgraph(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tfrom: readonly SubgraphStatus[],\n\tto: SubgraphStatus,\n\tset?: Record<string, unknown>,\n): Promise<Subgraph | null> {\n\tfor (const state of from) {\n\t\tif (state !== to) subgraphMachine.assert(state, to);\n\t}\n\treturn casTransition<SubgraphStatus, Subgraph>(db, {\n\t\ttable: \"subgraphs\",\n\t\tid: subgraphId,\n\t\tfrom,\n\t\tto,\n\t\tset,\n\t});\n}\n\n/** Convert a subgraph name to its PostgreSQL schema name. */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/** OSS writes empty account_id — name is the local unique key. */\nexport function localSubgraphAccountId(accountId?: string): string {\n\tif (!isPlatformMode()) return \"\";\n\treturn accountId ?? \"\";\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<Subgraph> {\n\tconst accountId = localSubgraphAccountId(data.accountId);\n\tconst values = {\n\t\tname: data.name,\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\taccount_id: accountId,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: data.pin ?? null,\n\t\tpin_preimage: data.pinPreimage ?? null,\n\t\tverification: data.verification\n\t\t\t? jsonb<SubgraphVerification>(data.verification)\n\t\t\t: null,\n\t};\n\tconst updateSet = {\n\t\tversion: data.version,\n\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\tschema_hash: data.schemaHash,\n\t\thandler_path: data.handlerPath,\n\t\thandler_code: data.handlerCode ?? null,\n\t\tsource_code: data.sourceCode ?? null,\n\t\tschema_name: data.schemaName ?? null,\n\t\tstart_block: data.startBlock ?? 0,\n\t\tpin: values.pin,\n\t\tpin_preimage: values.pin_preimage,\n\t\tverification: values.verification,\n\t\tupdated_at: new Date(),\n\t};\n\n\t// OSS: name is unique. Upsert by name so leftover rows with a non-empty\n\t// account_id (pre-local-namespace deploys) don't insert a second row.\n\tif (!isPlatformMode()) {\n\t\tconst existing = await db\n\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", data.name)\n\t\t\t.executeTakeFirst();\n\t\tif (existing) {\n\t\t\treturn await db\n\t\t\t\t.updateTable(\"subgraphs\")\n\t\t\t\t.set({ ...updateSet, account_id: \"\" })\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirstOrThrow();\n\t\t}\n\t\treturn await db\n\t\t\t.insertInto(\"subgraphs\")\n\t\t\t.values(values)\n\t\t\t.returningAll()\n\t\t\t.executeTakeFirstOrThrow();\n\t}\n\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values(values)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet(updateSet),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (isPlatformMode() && accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\n/** The hash half of a cursor write. Absent when the caller has none; the\n * `subgraphs_clear_stale_block_hash` trigger (0197) then clears the stored hash\n * for a moved cursor instead of leaving one that names another block. */\nfunction cursorHash(blockHash: string | undefined) {\n\treturn blockHash === undefined\n\t\t? {}\n\t\t: { last_processed_block_hash: blockHash };\n}\n\n/**\n * Reindex progress: moves the cursor of a subgraph that is still\n * `reindexing`, and nothing else. Returns `false` when the subgraph left that\n * state (halted, cancelled, redeployed): the walk must not write on, and its\n * progress never revives a halt.\n */\nexport async function setReindexCursor(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"reindexing\")\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Live-walk ERROR write (f069): a block whose handlers ALL failed\n * (`processed === 0 && errors > 0`, `block-processor.ts`'s `applyProgress`)\n * moves an `active` subgraph to 'error' and records its height as processed;\n * the cursor half goes through the same conditional `<` guard as\n * {@link recordLiveProgress}. A reindexing or already-halted subgraph is left\n * alone. Marking a subgraph 'error' is not\n * itself replay-sensitive, but it shares the `last_processed_block` column\n * with the replay guard: an unconditional write here could regress the\n * cursor a racing (successful) writer already advanced past, which is\n * exactly the regress-then-re-walk loop this guard exists to close. In\n * practice `ctx.rollbackTo` (`runner.ts`) means an all-failed block never\n * flushes writes, so a lost race here is always a silent no-op, never a\n * case that needs `CursorRaceLostError`-style tx abort. Returns whether\n * the write applied. Live path only: reindex/backfill halts go through\n * {@link transitionSubgraph}. */\nexport async function recordLiveError(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tblockHeight: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus: \"error\",\n\t\t\tlast_processed_block: blockHeight,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", blockHeight)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\n/** Record a billing pause. Status, cursor, counters and `last_error` are\n * untouched: a paused subgraph is healthy, just waiting on its account. */\nexport async function markSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tcode: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: sql`COALESCE(billing_paused_at, now())`,\n\t\t\tbilling_paused_code: code,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\n/** Clear a billing pause once reads succeed again. */\nexport async function clearSubgraphBillingPaused(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tbilling_paused_at: null,\n\t\t\tbilling_paused_code: null,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"billing_paused_at\", \"is not\", null)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\thandlerPath: string,\n\topts?: {\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\tpin?: string | null;\n\t\tpinPreimage?: string | null;\n\t\tverification?: SubgraphVerification | null;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\t...(opts?.pin !== undefined ? { pin: opts.pin } : {}),\n\t\t\t...(opts?.pinPreimage !== undefined\n\t\t\t\t? { pin_preimage: opts.pinPreimage }\n\t\t\t\t: {}),\n\t\t\t...(opts?.verification !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tverification: opts.verification\n\t\t\t\t\t\t\t? jsonb<SubgraphVerification>(opts.verification)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// One transaction: DDL is transactional in Postgres, so a failed row delete\n\t// leaves the schema in place instead of a registered subgraph with no tables.\n\tconst remove = async (trx: Kysely<Database>) => {\n\t\t// Drop the subgraph's schema (CASCADE drops all tables within).\n\t\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\t\ttrx,\n\t\t);\n\t\t// Remove from registry\n\t\tawait trx.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\t};\n\tif (db.isTransaction) await remove(db);\n\telse await db.transaction().execute(remove);\n\n\treturn subgraph;\n}\n\n/** Live-walk progress write: advances the cursor of an `active` subgraph and\n * never touches status. A `reindexing` or `error` subgraph is a no-op here:\n * the old promote-toward-active CASE let a live commit undo a halt and flap\n * a parked subgraph back into catch-up against its own reindex op.\n *\n * `last_processed_block` is now written CONDITIONALLY — `WHERE\n * last_processed_block < lastProcessedBlock`, mirroring\n * `advanceOperationCursor`'s (`subgraph-operations.ts`) comparison shape —\n * and returns whether THIS call actually advanced it. This used to be\n * unconditional by design, on the premise that the only two writers able to\n * advance/rewind a given subgraph's cursor concurrently (the catch-up walk\n * and the reorg handler) serialize on an in-process per-subgraph lock +\n * reorg epoch guard (`packages/subgraphs/src/runtime/catchup.ts`,\n * `subgraphBlockLockHeld` / `reorgEpoch`; f057). That guard is in-process\n * only. The f068 investigation\n * (`docs/internal/audits/asset-holdings-unreproducible-balances-f068.md`)\n * found a cross-process sequence it does not cover: a catch-up leader that\n * loses its advisory-lock connection mid-walk keeps writing (leadership is\n * checked only at walk entry, not per-iteration) while a new leader takes\n * over and walks the same range — both commit increments for overlapping\n * heights, and every regressed cursor write from the laggard re-triggers a\n * full re-walk, growing per-height application without bound. The\n * conditional advance here (paired with the fast-path replay guard armed on\n * the live path in `block-processor.ts`) is now the cross-process\n * guarantee: a block at/below the current cursor can never re-advance it,\n * so a laggard's commits can no longer regress-then-retrigger.\n *\n * This conditionality is why the reorg rewind can no longer go through this\n * function — a rewind's whole point is to move the cursor *backward*, which\n * the `<` guard would silently refuse. Reorg mode calls\n * {@link rewindLiveProgress} instead, which keeps the old unconditional\n * semantics and is safe specifically because the reorg path takes a\n * transaction-scoped advisory lock (`reorg.ts`) other writers can't cross. */\nexport async function recordLiveProgress(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.where(\"last_processed_block\", \"<\", lastProcessedBlock)\n\t\t.executeTakeFirst();\n\treturn Number(result.numUpdatedRows ?? 0n) > 0;\n}\n\n/** Reorg-rewind progress write: the OLD unconditional `recordLiveProgress`\n * semantics, verbatim — moves `last_processed_block` to the fork height\n * regardless of its current value, because that is by definition a\n * backward move the conditional `<` guard in `recordLiveProgress` would\n * refuse. Cursor only, `active` subgraphs only.\n *\n * Callers: exclusively the subgraph-reorg path\n * (`packages/subgraphs/src/runtime/reorg.ts`, via `block-processor.ts`'s\n * `reorgRewind` mode), which is safe from the cross-process race this\n * function reintroduces because it holds a transaction-scoped Postgres\n * advisory lock (`pg_advisory_xact_lock`) for the whole\n * delete+reprocess+rewind sequence — no other writer can interleave a\n * forward write between the rewind and the fork block's reprocess. Do not\n * call this from the live catch-up path. */\nexport async function rewindLiveProgress(\n\tdb: Kysely<Database>,\n\tsubgraphId: string,\n\tlastProcessedBlock: number,\n\tblockHash?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tlast_processed_block: lastProcessedBlock,\n\t\t\t...cursorHash(blockHash),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"id\", \"=\", subgraphId)\n\t\t.where(\"status\", \"=\", \"active\")\n\t\t.execute();\n}\n",
6
6
  "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: the metered archive deployment. Magic-link auth, API keys,\n * accounts, credits, and metered `/v1` reads (Index + Streams + subgraphs)\n * against a single shared DB. No paid tier ladder — one metered `free`\n * tier plus first-party internal service credentials.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n\n/** The one shared testnet webhook stack (hosted). Off everywhere else. */\nexport function isTestnetWebhookStack(): boolean {\n\treturn process.env.TESTNET_WEBHOOK_STACK === \"true\";\n}\n\n/** Webhook rows are per-account: platform, or the shared testnet stack. */\nexport function isWebhookAccountScoped(): boolean {\n\treturn isPlatformMode() || isTestnetWebhookStack();\n}\n",
7
7
  "import { z } from \"zod\";\n\n// ── Deploy Subgraph Request ─────────────────────────────────────────────────\n\n/** The body for deploying a subgraph: sources, schema, and handler code. */\nexport interface DeploySubgraphRequest {\n\tname: string;\n\tdescription?: string;\n\tsources: Record<string, Record<string, unknown>>;\n\tschema: Record<string, unknown>;\n\thandlerCode: string;\n\t/** Override the definition's startBlock for this deploy only. */\n\tstartBlock?: number;\n\t/** Original TypeScript source, persisted so chat can read/diff/edit later. */\n\tsourceCode?: string;\n\t/** Validate the definition + print the DDL plan without deploying. */\n\tdryRun?: boolean;\n}\n\nexport const DeploySubgraphRequestSchema: z.ZodType<DeploySubgraphRequest> =\n\tz.object({\n\t\tname: z\n\t\t\t.string()\n\t\t\t.regex(/^[a-z0-9-]+$/, \"lowercase alphanumeric + hyphens only\")\n\t\t\t// `subgraph_<name>` must fit Postgres' 63-byte identifier limit.\n\t\t\t.max(54),\n\t\tdescription: z.string().optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), z.record(z.string(), z.unknown()))\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: z.record(z.string(), z.unknown()),\n\t\thandlerCode: z.string().max(1_048_576, \"handler code exceeds 1MB limit\"),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\tsourceCode: z\n\t\t\t.string()\n\t\t\t.max(1_048_576, \"source code exceeds 1MB limit\")\n\t\t\t.optional(),\n\t\tdryRun: z.boolean().optional(),\n\t});\n\n/**\n * How far a subgraph's rows can be checked without trusting the server,\n * derived from its sources and a scan of its handler. Never configured.\n *\n * - `state`: every input is a named state write, provable from block headers.\n * Handlers run in the deterministic realm. A deployed `state` subgraph is\n * verifiable: one with any reason is refused at deploy.\n * - `events`: an input (events, prints, tx results, `ctx.client`) needs\n * re-execution proofs, which are not served yet.\n * - `none`: a source can never be proven as written (trait scope, tip-first\n * backfill).\n */\nexport interface SubgraphVerification {\n\tlevel: \"state\" | \"events\" | \"none\";\n\t/** What stands between the subgraph and checkable rows, e.g.\n\t * `print_event source \"swaps\" needs event proofs` or\n\t * `subgraph.ts:41:12 Date: wall-clock time differs per run`. */\n\treasons: string[];\n\t/** What stays unproven even at this level, e.g. tx attribution of writes. */\n\tunproven: string[];\n}\n\n/** What a deploy did, the version, and where indexing starts. */\nexport interface DeploySubgraphResponse {\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tmessage: string;\n\t/** Effective indexing start height. */\n\tstart_block?: number;\n\toperationId?: string;\n\treindexStarted?: boolean;\n\t/** Bounded candidate-event denominator for the reindex just started, when the\n\t * op was classifiable as sparse/light. Absent for heavy ops (no upfront estimate\n\t * possible) — check `sl subgraphs status` after ~30s for a rate-based ETA instead. */\n\testimatedEvents?: number;\n\t/** Non-blocking deploy lints (e.g. handler reads a print field never observed on-chain). */\n\twarnings?: string[];\n\t/** sha256 identity of what was deployed; absent on unbundled deploys. */\n\tpin?: string;\n\tverification?: SubgraphVerification;\n\tdiff?: {\n\t\taddedTables: string[];\n\t\tremovedTables: string[];\n\t\taddedColumns: Record<string, string[]>;\n\t\tbreakingChanges: string[];\n\t};\n}\n\n// Subgraph API response types\n\n/** Every state `subgraphs.status` can hold; mirrored by the\n * `subgraphs_status_check` CHECK (migration 0189). */\nexport const SUBGRAPH_STATES = [\"active\", \"reindexing\", \"error\"] as const;\nexport type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];\n\n/** What an operator sees: `synced` and `catching_up` are both `active` rows. */\nexport type SubgraphSyncState =\n\t| \"synced\"\n\t| \"catching_up\"\n\t| \"reindexing\"\n\t| \"error\";\n\n/**\n * The one answer to \"is this subgraph caught up?\". `tip` is the chain tip the\n * subgraph is measured against (its reindex target while reindexing is the\n * caller's concern: a reindexing subgraph is `reindexing` whatever its cursor).\n */\nexport function syncState(\n\tsubgraph: {\n\t\tstatus: string;\n\t\tlastProcessedBlock: number | string;\n\t},\n\ttip: number,\n): SubgraphSyncState {\n\tif (subgraph.status === \"reindexing\") return \"reindexing\";\n\tif (subgraph.status === \"error\") return \"error\";\n\treturn Number(subgraph.lastProcessedBlock) < tip ? \"catching_up\" : \"synced\";\n}\n\n/** A subgraph's name, status, and indexing progress. */\nexport interface SubgraphSummary {\n\tname: string;\n\tversion: string;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\ttotalProcessed: number;\n\ttotalRows?: number;\n\ttotalErrors: number;\n\ttables: string[];\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tprogress: number;\n\tblocksRemaining?: number;\n\tsyncMode?: \"sync\" | \"reindex\";\n\tgapCount: number;\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n\t/** Most recent indexing error reason + when it occurred, if any. */\n\tlastError?: string | null;\n\tlastErrorAt?: string | null;\n\t/** Billing code (`spend_cap_reached`, `insufficient_credits`) while reads\n\t * are refused for the account; null otherwise. */\n\tbillingPausedCode?: string | null;\n\t/** Last row mutation timestamp; powers per-card freshness. */\n\tupdatedAt?: string | null;\n\tcreatedAt: string;\n}\n\nexport interface SubgraphGapRange {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n}\n\nexport interface SubgraphSyncInfo {\n\tstatus: SubgraphSyncState;\n\tmode?: \"sync\" | \"reindex\";\n\tstartBlock: number;\n\tlastProcessedBlock: number;\n\t/**\n\t * Backward-compatible denominator for progress displays. During reindexing,\n\t * this is the reindex target block rather than the live source chain tip.\n\t */\n\tchainTip: number;\n\tsourceChainTip?: number;\n\ttargetBlock?: number;\n\tblocksRemaining: number;\n\tprocessedBlocks?: number;\n\ttotalBlocks?: number;\n\tprogress: number;\n\t/** Present while the populating operation is queued: approximate claim\n\t * position + honest event denominator + naive start estimate. */\n\tqueue?: {\n\t\tposition: number | null;\n\t\testimatedEvents: number | null;\n\t\testimatedStartSeconds: number | null;\n\t};\n\t/** Event-based progress for sparse syncs (block pct is meaningless when\n\t * most heights are skipped). */\n\testimatedEvents?: number;\n\tprocessedEvents?: number;\n\tetaSeconds?: number | null;\n\tgaps: {\n\t\tcount: number;\n\t\ttotalMissingBlocks: number;\n\t\tranges: SubgraphGapRange[];\n\t};\n\t/** history_filling = expected gaps while a tip-first backfill op runs. */\n\tintegrity: \"complete\" | \"gaps_detected\" | \"history_filling\";\n}\n\n/** A subgraph's version, pin, status, tables, and sources. */\nexport interface SubgraphDetail {\n\tname: string;\n\tversion: string;\n\tschemaHash?: string;\n\t/** sha256 over schema, handler bundle, startBlock, network and runtime.\n\t * Null for subgraphs deployed before pins existed. */\n\tpin?: string | null;\n\t/** Null for subgraphs deployed before levels were derived. */\n\tverification?: SubgraphVerification | null;\n\tstatus: string;\n\tlastProcessedBlock: number;\n\tdescription?: string;\n\tsources?: Record<string, unknown>;\n\tdefinition?: Record<string, unknown>;\n\thealth: {\n\t\ttotalProcessed: number;\n\t\ttotalErrors: number;\n\t\terrorRate: number;\n\t\tlastError: string | null;\n\t\tlastErrorAt: string | null;\n\t\t/** Billing code while the account's reads are refused; null otherwise. */\n\t\tbillingPausedCode?: string | null;\n\t\t/** True after the processor matched work but user tables still have 0 rows. */\n\t\temptyMapping: boolean;\n\t};\n\tsync: SubgraphSyncInfo;\n\ttables: Record<\n\t\tstring,\n\t\t{\n\t\t\tendpoint: string;\n\t\t\tcolumns: Record<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\ttype: string;\n\t\t\t\t\tnullable?: boolean;\n\t\t\t\t\tindexed?: boolean;\n\t\t\t\t\tsearchable?: boolean;\n\t\t\t\t\tdefault?: string | number | boolean;\n\t\t\t\t}\n\t\t\t>;\n\t\t\trowCount: number;\n\t\t\texample: string;\n\t\t\tindexes?: readonly (readonly string[])[];\n\t\t\tuniqueKeys?: readonly (readonly string[])[];\n\t\t}\n\t>;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface SubgraphGapEntry {\n\tstart: number;\n\tend: number;\n\tsize: number;\n\treason: string;\n\tdetectedAt: string;\n\tresolvedAt: string | null;\n}\n\n/** Missing block ranges in a subgraph, with totals. */\nexport interface SubgraphGapsResponse {\n\tdata: SubgraphGapEntry[];\n\tmeta: {\n\t\ttotal: number;\n\t\ttotalMissingBlocks: number;\n\t\tlimit: number;\n\t\toffset: number;\n\t};\n}\n\n/** A queued reindex and the block range it covers. */\nexport interface ReindexResponse {\n\tmessage: string;\n\tfromBlock: number;\n\ttoBlock: number | string;\n\toperationId?: string;\n\tstatus?: \"queued\" | \"running\" | \"cancel_requested\";\n}\n\nexport interface SubgraphQueryParams {\n\tsort?: string;\n\torder?: string;\n\tlimit?: number;\n\toffset?: number;\n\tfields?: string;\n\tfilters?: Record<string, string>;\n}\n\n/**\n * Request shape for `GET /v1/subgraphs/:subgraphName/:tableName/aggregate`.\n * `filters` reuses the list/count where-surface; the rest name the columns to\n * aggregate. SUM/MIN/MAX columns must be numeric (uint/int, plus `_block_height`).\n */\nexport interface SubgraphAggregateParams {\n\tfilters?: Record<string, string>;\n\tcount?: boolean;\n\tcountDistinct?: string[];\n\tsum?: string[];\n\tmin?: string[];\n\tmax?: string[];\n}\n\n/**\n * Aggregate response. Keys are present only for requested aggregates.\n * `count`/`countDistinct` are JSON numbers (counts << 2^53); `sum`/`min`/`max`\n * are lossless strings (NUMERIC `::text`). `sum` of an empty set is `\"0\"`;\n * `min`/`max` are `null` when the filtered set is empty or all-null.\n */\nexport interface SubgraphAggregateResponse {\n\tcount?: number;\n\tcountDistinct?: Record<string, number>;\n\tsum?: Record<string, string>;\n\tmin?: Record<string, string | null>;\n\tmax?: Record<string, string | null>;\n}\n",
8
8
  "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
9
9
  "import { type Kysely, sql } from \"kysely\";\n\n/**\n * The one convention for state machines: states are a const array (mirrored by\n * a DB CHECK), transitions are a table next to the states, and every status\n * write goes through `casTransition`.\n */\n\nexport interface Machine<S extends string> {\n\treadonly states: readonly S[];\n\tcanTransition(from: S, to: S): boolean;\n\t/** Throws on an illegal move. */\n\tassert(from: S, to: S): void;\n}\n\n/** Pure transition table. `transitions` lists, per state, the states it may move to. */\nexport function defineMachine<const S extends string>(def: {\n\tstates: readonly S[];\n\ttransitions: { readonly [K in S]?: readonly S[] };\n}): Machine<S> {\n\tconst canTransition = (from: S, to: S) =>\n\t\tdef.transitions[from]?.includes(to) ?? false;\n\treturn {\n\t\tstates: def.states,\n\t\tcanTransition,\n\t\tassert(from, to) {\n\t\t\tif (!canTransition(from, to)) {\n\t\t\t\tthrow new Error(`illegal transition ${from} -> ${to}`);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface CasTransition<S extends string> {\n\ttable: string;\n\t/** Value of the row key. */\n\tid: string | number;\n\t/** Row key column, `id` unless the table is addressed by another unique column (`name`). */\n\tkey?: string;\n\t/** Status column, `status` unless the machine lives in another column. */\n\tcolumn?: string;\n\t/** The row moves only if it is currently in one of these states. */\n\tfrom: readonly S[];\n\tto: S;\n\t/** Extra columns written in the same statement. Wrap jsonb values with `jsonb()`. */\n\tset?: Record<string, unknown>;\n\t/** Stamp `updated_at = now()`. Pass `false` for tables without that column. */\n\tstampUpdatedAt?: boolean;\n\t/** Columns to return, `*` unless the row carries a large payload (`[\"sequence\"]`). */\n\treturning?: readonly string[];\n}\n\n/**\n * Compare-and-swap a status column: `UPDATE ... WHERE key = ? AND column = ANY(from)`.\n * Returns the updated row (or the `returning` columns), or `null` when the row was missing or not in a `from`\n * state (a lost race). The caller decides what `null` means; usually log and stop.\n * Works with `db` and inside a transaction (`trx`).\n */\nexport async function casTransition<\n\tS extends string,\n\t// biome-ignore lint/suspicious/noExplicitAny: dynamic table name, row shape is the caller's\n\tRow = Record<string, any>,\n>(\n\t// biome-ignore lint/suspicious/noExplicitAny: accepts Kysely<Database> and Transaction<Database>\n\tdb: Kysely<any>,\n\tt: CasTransition<S>,\n): Promise<Row | null> {\n\tconst column = sql.id(t.column ?? \"status\");\n\tconst assignments = [sql`${column} = ${t.to}`];\n\tif (t.stampUpdatedAt !== false) assignments.push(sql`updated_at = now()`);\n\tfor (const [key, value] of Object.entries(t.set ?? {})) {\n\t\tassignments.push(sql`${sql.id(key)} = ${value}`);\n\t}\n\n\tconst returning = t.returning\n\t\t? sql.join(t.returning.map((c) => sql.id(c)))\n\t\t: sql.raw(\"*\");\n\n\tconst { rows } = await sql<Row>`\n\t\tUPDATE ${sql.table(t.table)}\n\t\tSET ${sql.join(assignments)}\n\t\tWHERE ${sql.id(t.key ?? \"id\")} = ${t.id} AND ${column} = ANY(${sql.val([...t.from])})\n\t\tRETURNING ${returning}\n\t`.execute(db);\n\treturn rows[0] ?? null;\n}\n"
10
10
  ],
11
- "mappings": ";AAAA,gBAAsB;;;ACmBtB,IAAM,cAA+C;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACD;AAEA,SAAS,YAAY,GAAyB;AAAA,EAC7C,MAAM,MAAM,QAAQ,IAAI,eAAe,KAAK,EAAE,YAAY;AAAA,EAC1D,IAAI,OAAQ,YAAkC,SAAS,GAAG,GAAG;AAAA,IAC5D,OAAO;AAAA,EACR;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,WAAW,EACvB,IAAI;AAAA,IACJ,sBAAsB;AAAA,OACnB,WAAW,SAAS;AAAA,IACvB,YAAY,IAAI;AAAA,EACjB,CAAC,EACA,MAAM,MAAM,KAAK,UAAU,EAC3B,MAAM,UAAU,KAAK,QAAQ,EAC7B,QAAQ;AAAA;",
12
+ "debugId": "D9FC72868ADBC9D264756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -18,7 +18,10 @@ import { onChainPlane } from "../src/db/migration-role.ts";
18
18
  * supply shortfall: decoded mint−burn read 2,331.6 BTC vs on-chain 2,954.7).
19
19
  *
20
20
  * The logical key is `(block_height, tx_id, event_index)`:
21
- * - `event_index` is per-transaction, so `tx_id` is required to disambiguate.
21
+ * - Raw `event_index` has two eras: below ~block 7,440,500 (imported history)
22
+ * it restarts at 0 in each transaction, above that it counts across the
23
+ * whole block. Streams computes the block position itself. The key is
24
+ * unique under both, and `tx_id` is what disambiguates the per-tx era.
22
25
  * - `block_height` is included (not implied-redundant) on purpose: a reorg can
23
26
  * legitimately leave the same `(tx_id, event_index)` at two heights (orphan +
24
27
  * canonical). Keying on height permits those as distinct physical rows while
@@ -0,0 +1,69 @@
1
+ import { type Kysely, sql } from "kysely";
2
+ import { onControlPlane } from "../src/db/migration-role.ts";
3
+
4
+ /**
5
+ * Replaces `usage_ledger_unit_check` from 0196 so the ledger accepts the
6
+ * `subgraph.read` unit (hosted subgraph table reads, counted by the workload
7
+ * gateway). Same shape as 0196: every priced `MeterUnit` (retired `sentinel.*`
8
+ * included), `topup`, `grant`, `refund`; added `NOT VALID` so it binds every
9
+ * new write without blocking the deploy on historical rows. Skipped when the
10
+ * table is absent.
11
+ *
12
+ * Adding a unit means adding it to `prices.ts` AND to a new migration that
13
+ * replaces `usage_ledger_unit_check`; `meter-invariants.test.ts` fails when the
14
+ * two drift.
15
+ */
16
+
17
+ const PREVIOUS_METER_UNITS = [
18
+ "archive.partition",
19
+ "archive.partition.events",
20
+ "rows.delivered",
21
+ "memory.gb_hour",
22
+ "storage.gb_day",
23
+ "webhook.event",
24
+ "sentinel.run",
25
+ "sentinel.deep_audit",
26
+ "sentinel.check_run",
27
+ "sentinel.monitored_event",
28
+ ];
29
+ const METER_UNITS = [...PREVIOUS_METER_UNITS, "subgraph.read"];
30
+ const LEDGER_ONLY_UNITS = ["topup", "grant", "refund"];
31
+
32
+ function unitCheck(meterUnits: string[]): string {
33
+ const list = [...meterUnits, ...LEDGER_ONLY_UNITS]
34
+ .map((u) => `'${u}'`)
35
+ .join(", ");
36
+ return `unit IN (${list})`;
37
+ }
38
+
39
+ const NAME = "usage_ledger_unit_check";
40
+
41
+ async function tableExists(db: Kysely<unknown>, table: string) {
42
+ const { rows } = await sql<{ exists: boolean }>`
43
+ SELECT to_regclass(${`public.${table}`}) IS NOT NULL AS exists
44
+ `.execute(db);
45
+ return rows[0]?.exists === true;
46
+ }
47
+
48
+ async function replaceUnitCheck(db: Kysely<unknown>, meterUnits: string[]) {
49
+ await onControlPlane(async () => {
50
+ if (!(await tableExists(db, "usage_ledger"))) return;
51
+ await sql`ALTER TABLE usage_ledger DROP CONSTRAINT IF EXISTS ${sql.id(NAME)}`.execute(
52
+ db,
53
+ );
54
+ await sql`
55
+ ALTER TABLE usage_ledger
56
+ ADD CONSTRAINT ${sql.id(NAME)} CHECK (${sql.raw(unitCheck(meterUnits))}) NOT VALID
57
+ `.execute(db);
58
+ });
59
+ }
60
+
61
+ export async function up(db: Kysely<unknown>): Promise<void> {
62
+ await sql`SET lock_timeout = '30s'`.execute(db);
63
+ await replaceUnitCheck(db, METER_UNITS);
64
+ }
65
+
66
+ export async function down(db: Kysely<unknown>): Promise<void> {
67
+ await sql`SET lock_timeout = '30s'`.execute(db);
68
+ await replaceUnitCheck(db, PREVIOUS_METER_UNITS);
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secondlayer/shared",
3
- "version": "15.5.0",
3
+ "version": "15.6.1",
4
4
  "description": "Internal building blocks shared across Secondlayer packages.",
5
5
  "license": "MIT",
6
6
  "repository": {