@secondlayer/subgraphs 3.23.2 → 3.24.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.
@@ -450,6 +450,19 @@ interface ProcessBlockOptions {
450
450
  } | {
451
451
  operationId: string
452
452
  };
453
+ /**
454
+ * Reorg rewind (f069): set exclusively by `reorg.ts`'s fork-block
455
+ * reprocess. Bypasses the live-path replay guard (a fork block's height
456
+ * is, by construction, at or below the current cursor — the guard would
457
+ * otherwise skip it) and writes the checkpoint via
458
+ * `rewindLiveProgress` (unconditional — a rewind's whole point is
459
+ * moving the cursor *backward*, which the live path's conditional
460
+ * advance would refuse). Safe only because the reorg path holds a
461
+ * transaction-scoped advisory lock across its whole
462
+ * delete+reprocess+rewind sequence, so nothing else can interleave a
463
+ * forward write. Never set this outside `reorg.ts`.
464
+ */
465
+ reorgRewind?: true;
453
466
  }
454
467
  /** Default per-block retry schedule before a failure counts as persistent. */
455
468
  declare const BLOCK_RETRY_DELAYS_MS: number[];
@@ -11,6 +11,11 @@ import { createHash } from "node:crypto";
11
11
 
12
12
  // src/schema/utils.ts
13
13
  import { pgSchemaName } from "@secondlayer/shared/db/queries/subgraphs";
14
+ function quotePgIdent(name) {
15
+ if (/^[a-z_][a-z0-9_]*$/i.test(name))
16
+ return name;
17
+ return `"${name.replace(/"/g, '""')}"`;
18
+ }
14
19
 
15
20
  // src/schema/generator.ts
16
21
  var TYPE_MAP = {
@@ -35,7 +40,7 @@ function tableNeedsTrgm(tableDef) {
35
40
  return Object.values(tableDef.columns).some((col) => col.search);
36
41
  }
37
42
  function emitTableDDL(schemaName, tableName, tableDef) {
38
- const qualifiedName = `${schemaName}.${tableName}`;
43
+ const qualifiedName = `${quotePgIdent(schemaName)}.${quotePgIdent(tableName)}`;
39
44
  const statements = [];
40
45
  const columnDefs = [
41
46
  "_id BIGSERIAL PRIMARY KEY",
@@ -46,12 +51,12 @@ function emitTableDDL(schemaName, tableName, tableDef) {
46
51
  for (const [colName, col] of Object.entries(tableDef.columns)) {
47
52
  const sqlType = TYPE_MAP[col.type];
48
53
  const nullable = col.nullable ? "" : " NOT NULL";
49
- let colDef = `${colName} ${sqlType}${nullable}`;
54
+ let colDef = `${quotePgIdent(colName)} ${sqlType}${nullable}`;
50
55
  if (col.default !== undefined) {
51
56
  colDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;
52
57
  }
53
58
  if (col.type === "uint") {
54
- colDef += ` CHECK (${colName} >= 0)`;
59
+ colDef += ` CHECK (${quotePgIdent(colName)} >= 0)`;
55
60
  }
56
61
  columnDefs.push(colDef);
57
62
  }
@@ -59,30 +64,30 @@ function emitTableDDL(schemaName, tableName, tableDef) {
59
64
  ${columnDefs.join(`,
60
65
  `)}
61
66
  )`);
62
- statements.push(`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`);
63
- statements.push(`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`);
67
+ statements.push(`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_block_height`)} ON ${qualifiedName} (_block_height)`);
68
+ statements.push(`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_tx_id`)} ON ${qualifiedName} (_tx_id)`);
64
69
  for (const [colName, col] of Object.entries(tableDef.columns)) {
65
70
  if (col.indexed) {
66
- statements.push(`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`);
71
+ statements.push(`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_${colName}`)} ON ${qualifiedName} (${quotePgIdent(colName)})`);
67
72
  }
68
73
  }
69
74
  for (const [colName, col] of Object.entries(tableDef.columns)) {
70
75
  if (col.search) {
71
- statements.push(`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`);
76
+ statements.push(`CREATE INDEX IF NOT EXISTS ${quotePgIdent(`idx_${schemaName}_${tableName}_${colName}_trgm`)} ON ${qualifiedName} USING gin (${quotePgIdent(colName)} gin_trgm_ops)`);
72
77
  }
73
78
  }
74
79
  if (tableDef.indexes) {
75
80
  for (let i = 0;i < tableDef.indexes.length; i++) {
76
81
  const cols = tableDef.indexes[i];
77
- const idxName = `idx_${schemaName}_${tableName}_composite_${i}`;
78
- statements.push(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(", ")})`);
82
+ const idxName = quotePgIdent(`idx_${schemaName}_${tableName}_composite_${i}`);
83
+ statements.push(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.map(quotePgIdent).join(", ")})`);
79
84
  }
80
85
  }
81
86
  if (tableDef.uniqueKeys) {
82
87
  for (let i = 0;i < tableDef.uniqueKeys.length; i++) {
83
88
  const cols = tableDef.uniqueKeys[i];
84
- const constraintName = `uq_${schemaName}_${tableName}_${cols.join("_")}`;
85
- statements.push(`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(", ")})`);
89
+ const constraintName = quotePgIdent(`uq_${schemaName}_${tableName}_${cols.join("_")}`);
90
+ statements.push(`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.map(quotePgIdent).join(", ")})`);
86
91
  }
87
92
  }
88
93
  return statements;
@@ -114,8 +119,8 @@ function emitFactoryDDL(schemaName) {
114
119
  }
115
120
  function emitForeignKeyDDL(schemaName, tableName, tableDef) {
116
121
  return (tableDef.relations ?? []).map((rel) => {
117
- const constraintName = `fk_${schemaName}_${tableName}_${rel.name}`;
118
- return `ALTER TABLE ${schemaName}.${tableName} ADD CONSTRAINT ${constraintName} ` + `FOREIGN KEY (${rel.fields.join(", ")}) ` + `REFERENCES ${schemaName}.${rel.references} (${rel.referencedColumns.join(", ")})`;
122
+ const constraintName = quotePgIdent(`fk_${schemaName}_${tableName}_${rel.name}`);
123
+ return `ALTER TABLE ${quotePgIdent(schemaName)}.${quotePgIdent(tableName)} ADD CONSTRAINT ${constraintName} ` + `FOREIGN KEY (${rel.fields.map(quotePgIdent).join(", ")}) ` + `REFERENCES ${quotePgIdent(schemaName)}.${quotePgIdent(rel.references)} (${rel.referencedColumns.map(quotePgIdent).join(", ")})`;
119
124
  });
120
125
  }
121
126
  function generateSubgraphSQL(def, schemaNameOverride) {
@@ -1627,9 +1632,11 @@ import { resolveTraitContractIds } from "@secondlayer/shared/db/queries/contract
1627
1632
  import { advanceOperationCursor } from "@secondlayer/shared/db/queries/subgraph-operations";
1628
1633
  import {
1629
1634
  isByoSubgraph,
1635
+ recordLiveError,
1630
1636
  recordLiveProgress,
1631
1637
  recordSubgraphProcessed,
1632
1638
  resolveSubgraphDb,
1639
+ rewindLiveProgress,
1633
1640
  updateSubgraphStatus
1634
1641
  } from "@secondlayer/shared/db/queries/subgraphs";
1635
1642
  import { logger as logger6 } from "@secondlayer/shared/logger";
@@ -2337,10 +2344,20 @@ class CursorRaceLostError extends Error {
2337
2344
  this.name = "CursorRaceLostError";
2338
2345
  }
2339
2346
  }
2347
+
2348
+ class LiveCursorRaceLostError extends Error {
2349
+ constructor(subgraphName, height) {
2350
+ super(`live cursor race lost for ${subgraphName} at block ${height}`);
2351
+ this.name = "LiveCursorRaceLostError";
2352
+ }
2353
+ }
2340
2354
  function opCursorMode(opts) {
2341
2355
  const ap = opts?.atomicProgress;
2342
2356
  return ap && "operationId" in ap ? ap : undefined;
2343
2357
  }
2358
+ function isReorgRewind(opts) {
2359
+ return opts?.reorgRewind === true;
2360
+ }
2344
2361
  function statusMode(opts) {
2345
2362
  const ap = opts?.atomicProgress;
2346
2363
  return ap && "status" in ap ? ap : undefined;
@@ -2410,7 +2427,11 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2410
2427
  result.matched = matched.length;
2411
2428
  if (matched.length === 0) {
2412
2429
  if (!opts?.skipProgressUpdate) {
2413
- await recordLiveProgress(targetDb, subgraphName, blockHeight);
2430
+ if (isReorgRewind(opts)) {
2431
+ await rewindLiveProgress(targetDb, subgraphName, blockHeight);
2432
+ } else {
2433
+ await recordLiveProgress(targetDb, subgraphName, blockHeight);
2434
+ }
2414
2435
  }
2415
2436
  return result;
2416
2437
  }
@@ -2429,13 +2450,23 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2429
2450
  };
2430
2451
  let handlerMs = 0;
2431
2452
  let flushMs = 0;
2432
- const applyProgress = async (tx, rr) => {
2453
+ const applyProgress = async (tx, rr, flushedWrites) => {
2433
2454
  if (opts?.skipProgressUpdate)
2434
2455
  return;
2456
+ const rewind = isReorgRewind(opts);
2435
2457
  if (rr.errors > 0 && rr.processed === 0) {
2436
- await updateSubgraphStatus(tx, subgraphName, "error", blockHeight);
2458
+ if (rewind) {
2459
+ await updateSubgraphStatus(tx, subgraphName, "error", blockHeight);
2460
+ } else {
2461
+ await recordLiveError(tx, subgraphName, blockHeight);
2462
+ }
2463
+ } else if (rewind) {
2464
+ await rewindLiveProgress(tx, subgraphName, blockHeight);
2437
2465
  } else {
2438
- await recordLiveProgress(tx, subgraphName, blockHeight);
2466
+ const advanced = await recordLiveProgress(tx, subgraphName, blockHeight);
2467
+ if (!advanced && flushedWrites && !route.byo) {
2468
+ throw new LiveCursorRaceLostError(subgraphName, blockHeight);
2469
+ }
2439
2470
  }
2440
2471
  if (rr.processed > 0 || rr.errors > 0) {
2441
2472
  const lastError = rr.errors > 0 ? `${rr.errors} error(s) at block ${blockHeight}` : undefined;
@@ -2484,13 +2515,15 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2484
2515
  } else if (byoOm && manifest && manifest.count > 0) {
2485
2516
  await advanceOperationCursor(tx, byoOm.operationId, blockHeight);
2486
2517
  }
2487
- await applyProgress(tx, runResult);
2518
+ await applyProgress(tx, runResult, manifest ? manifest.count > 0 : false);
2488
2519
  });
2489
2520
  } else {
2490
2521
  try {
2491
2522
  await targetDb.transaction().execute(async (tx) => {
2492
2523
  const opMode = opCursorMode(opts);
2493
- if (statusMode(opts)) {
2524
+ const sm = statusMode(opts);
2525
+ const rewind = isReorgRewind(opts);
2526
+ if (sm) {
2494
2527
  const row = await tx.selectFrom("subgraphs").select("last_processed_block").where("name", "=", subgraphName).executeTakeFirst();
2495
2528
  if (row && Number(row.last_processed_block) >= blockHeight) {
2496
2529
  result.skipped = true;
@@ -2502,6 +2535,12 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2502
2535
  result.skipped = true;
2503
2536
  return;
2504
2537
  }
2538
+ } else if (!rewind) {
2539
+ const row = await tx.selectFrom("subgraphs").select("last_processed_block").where("name", "=", subgraphName).executeTakeFirst();
2540
+ if (row && Number(row.last_processed_block) >= blockHeight) {
2541
+ result.skipped = true;
2542
+ return;
2543
+ }
2505
2544
  }
2506
2545
  const ctx = new SubgraphContext(tx, schemaName, subgraph.schema, blockMeta, initialTx, false, journalEnabled(opts));
2507
2546
  const handlerStart = performance.now();
@@ -2519,7 +2558,6 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2519
2558
  }
2520
2559
  flushMs = performance.now() - flushStart;
2521
2560
  }
2522
- const sm = statusMode(opts);
2523
2561
  if (sm && flushedWrites) {
2524
2562
  await updateSubgraphStatus(tx, subgraphName, sm.status, blockHeight);
2525
2563
  } else if (opMode && flushedWrites) {
@@ -2528,10 +2566,10 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2528
2566
  throw new CursorRaceLostError(opMode.operationId, blockHeight);
2529
2567
  }
2530
2568
  }
2531
- await applyProgress(tx, runResult);
2569
+ await applyProgress(tx, runResult, flushedWrites);
2532
2570
  });
2533
2571
  } catch (err) {
2534
- if (err instanceof CursorRaceLostError) {
2572
+ if (err instanceof CursorRaceLostError || err instanceof LiveCursorRaceLostError) {
2535
2573
  logger6.warn("cursor race lost — block already covered", {
2536
2574
  subgraph: subgraphName,
2537
2575
  blockHeight,
@@ -2544,11 +2582,13 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
2544
2582
  }
2545
2583
  }
2546
2584
  const totalMs = performance.now() - blockStart;
2547
- result.timing = {
2548
- totalMs: Math.round(totalMs),
2549
- handlerMs: Math.round(handlerMs),
2550
- flushMs: Math.round(flushMs)
2551
- };
2585
+ if (!result.skipped) {
2586
+ result.timing = {
2587
+ totalMs: Math.round(totalMs),
2588
+ handlerMs: Math.round(handlerMs),
2589
+ flushMs: Math.round(flushMs)
2590
+ };
2591
+ }
2552
2592
  if (blockHeight % 1000 === 0) {
2553
2593
  try {
2554
2594
  const tables = Object.keys(subgraph.schema);
@@ -2583,5 +2623,5 @@ export {
2583
2623
  BLOCK_RETRY_DELAYS_MS
2584
2624
  };
2585
2625
 
2586
- //# debugId=ED4E61C22DF18FC964756E2164756E21
2626
+ //# debugId=339F2648E4EA97C964756E2164756E21
2587
2627
  //# sourceMappingURL=block-processor.js.map