@aztec/prover-node 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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 (75) hide show
  1. package/README.md +572 -0
  2. package/dest/actions/download-epoch-proving-job.js +1 -1
  3. package/dest/actions/rerun-epoch-proving-job.d.ts +14 -4
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +244 -24
  6. package/dest/actions/upload-epoch-proof-failure.d.ts +2 -2
  7. package/dest/actions/upload-epoch-proof-failure.d.ts.map +1 -1
  8. package/dest/bin/run-failed-epoch.js +6 -5
  9. package/dest/checkpoint-store.d.ts +95 -0
  10. package/dest/checkpoint-store.d.ts.map +1 -0
  11. package/dest/checkpoint-store.js +178 -0
  12. package/dest/config.d.ts +7 -8
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +24 -20
  15. package/dest/factory.d.ts +22 -13
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +41 -65
  18. package/dest/index.d.ts +2 -1
  19. package/dest/index.d.ts.map +1 -1
  20. package/dest/index.js +1 -0
  21. package/dest/job/checkpoint-prover.d.ts +165 -0
  22. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  23. package/dest/job/checkpoint-prover.js +405 -0
  24. package/dest/job/epoch-session.d.ts +160 -0
  25. package/dest/job/epoch-session.d.ts.map +1 -0
  26. package/dest/job/{epoch-proving-job.js → epoch-session.js} +301 -298
  27. package/dest/job/top-tree-job.d.ts +82 -0
  28. package/dest/job/top-tree-job.d.ts.map +1 -0
  29. package/dest/job/top-tree-job.js +152 -0
  30. package/dest/metrics.d.ts +40 -3
  31. package/dest/metrics.d.ts.map +1 -1
  32. package/dest/metrics.js +101 -4
  33. package/dest/monitors/epoch-monitor.d.ts +1 -1
  34. package/dest/monitors/epoch-monitor.d.ts.map +1 -1
  35. package/dest/monitors/epoch-monitor.js +11 -9
  36. package/dest/proof-publishing-service.d.ts +161 -0
  37. package/dest/proof-publishing-service.d.ts.map +1 -0
  38. package/dest/proof-publishing-service.js +335 -0
  39. package/dest/prover-node-publisher.d.ts +25 -15
  40. package/dest/prover-node-publisher.d.ts.map +1 -1
  41. package/dest/prover-node-publisher.js +202 -63
  42. package/dest/prover-node.d.ts +146 -69
  43. package/dest/prover-node.d.ts.map +1 -1
  44. package/dest/prover-node.js +545 -221
  45. package/dest/prover-publisher-factory.d.ts +6 -4
  46. package/dest/prover-publisher-factory.d.ts.map +1 -1
  47. package/dest/prover-publisher-factory.js +4 -3
  48. package/dest/session-manager.d.ts +158 -0
  49. package/dest/session-manager.d.ts.map +1 -0
  50. package/dest/session-manager.js +492 -0
  51. package/dest/test/index.d.ts +7 -6
  52. package/dest/test/index.d.ts.map +1 -1
  53. package/package.json +24 -22
  54. package/src/actions/download-epoch-proving-job.ts +1 -1
  55. package/src/actions/rerun-epoch-proving-job.ts +190 -31
  56. package/src/actions/upload-epoch-proof-failure.ts +1 -1
  57. package/src/bin/run-failed-epoch.ts +5 -3
  58. package/src/checkpoint-store.ts +212 -0
  59. package/src/config.ts +35 -32
  60. package/src/factory.ts +73 -111
  61. package/src/index.ts +1 -0
  62. package/src/job/checkpoint-prover.ts +538 -0
  63. package/src/job/epoch-session.ts +462 -0
  64. package/src/job/top-tree-job.ts +227 -0
  65. package/src/metrics.ts +123 -10
  66. package/src/monitors/epoch-monitor.ts +5 -6
  67. package/src/proof-publishing-service.ts +427 -0
  68. package/src/prover-node-publisher.ts +237 -79
  69. package/src/prover-node.ts +631 -248
  70. package/src/prover-publisher-factory.ts +8 -5
  71. package/src/session-manager.ts +592 -0
  72. package/src/test/index.ts +6 -6
  73. package/dest/job/epoch-proving-job.d.ts +0 -63
  74. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  75. package/src/job/epoch-proving-job.ts +0 -435
@@ -1,29 +1,31 @@
1
1
  import type { RollupContract } from '@aztec/ethereum/contracts';
2
2
  import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
3
3
  import type { PublisherManager } from '@aztec/ethereum/publisher-manager';
4
+ import type { EthAddress } from '@aztec/foundation/eth-address';
4
5
  import type { LoggerBindings } from '@aztec/foundation/log';
5
- import type { PublisherConfig, TxSenderConfig } from '@aztec/sequencer-client';
6
+ import type { ProverPublisherConfig, ProverTxSenderConfig } from '@aztec/sequencer-client';
6
7
  import type { TelemetryClient } from '@aztec/telemetry-client';
7
8
 
8
9
  import { ProverNodePublisher } from './prover-node-publisher.js';
9
10
 
10
11
  export class ProverPublisherFactory {
11
12
  constructor(
12
- private config: TxSenderConfig & PublisherConfig,
13
+ private config: ProverTxSenderConfig & ProverPublisherConfig,
13
14
  private deps: {
14
15
  rollupContract: RollupContract;
15
16
  publisherManager: PublisherManager<L1TxUtils>;
17
+ proofSubmissionTarget?: EthAddress;
16
18
  telemetry?: TelemetryClient;
17
19
  },
18
20
  private bindings?: LoggerBindings,
19
21
  ) {}
20
22
 
21
23
  public async start() {
22
- await this.deps.publisherManager.loadState();
24
+ await this.deps.publisherManager.start();
23
25
  }
24
26
 
25
- public stop() {
26
- this.deps.publisherManager.interrupt();
27
+ public async stop() {
28
+ await this.deps.publisherManager.stop();
27
29
  }
28
30
 
29
31
  /**
@@ -37,6 +39,7 @@ export class ProverPublisherFactory {
37
39
  {
38
40
  rollupContract: this.deps.rollupContract,
39
41
  l1TxUtils: l1Publisher,
42
+ proofSubmissionTarget: this.deps.proofSubmissionTarget,
40
43
  telemetry: this.deps.telemetry,
41
44
  },
42
45
  this.bindings,
@@ -0,0 +1,592 @@
1
+ import { BlockNumber, type EpochNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
5
+ import { SerialQueue } from '@aztec/foundation/queue';
6
+ import { RunningPromise } from '@aztec/foundation/running-promise';
7
+ import type { DateProvider } from '@aztec/foundation/timer';
8
+ import type { EpochProverFactory } from '@aztec/prover-client';
9
+ import type { L2BlockSource } from '@aztec/stdlib/block';
10
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
11
+ import {
12
+ type L1RollupConstants,
13
+ getEpochAtSlot,
14
+ getProofSubmissionDeadlineTimestamp,
15
+ getSlotRangeForEpoch,
16
+ } from '@aztec/stdlib/epoch-helpers';
17
+ import type { EpochProvingJobState } from '@aztec/stdlib/interfaces/server';
18
+
19
+ import type { CheckpointStore } from './checkpoint-store.js';
20
+ import { CheckpointProver } from './job/checkpoint-prover.js';
21
+ import type { EpochProvingJobData } from './job/epoch-proving-job-data.js';
22
+ import {
23
+ EpochSession,
24
+ type EpochSessionDeps,
25
+ type EpochSessionHooks,
26
+ type EpochSessionOptions,
27
+ type SessionSpec,
28
+ specKey,
29
+ } from './job/epoch-session.js';
30
+ import type { ProverNodeJobMetrics } from './metrics.js';
31
+ import type { ProofPublishingService } from './proof-publishing-service.js';
32
+
33
+ /** Trigger payload for `reconcile`. */
34
+ export type ReconcileTrigger =
35
+ | { kind: 'checkpoint'; epoch: EpochNumber }
36
+ | { kind: 'prune'; affectedEpochs: EpochNumber[] }
37
+ | { kind: 'tick' }
38
+ | { kind: 'start-proof'; spec: SessionSpec };
39
+
40
+ /** Config bag for session lifecycle decisions. */
41
+ export type SessionManagerConfig = {
42
+ /** Cap on the number of non-terminal sessions (full + partial). 0 disables. */
43
+ maxPendingJobs: number;
44
+ /** Interval at which the internal periodic tick fires `reconcile({ kind: 'tick' })`. */
45
+ tickIntervalMs: number;
46
+ /** Forwarded to every session: delay before top-tree proving, letting late reorgs settle. */
47
+ finalizationDelayMs: number | undefined;
48
+ };
49
+
50
+ export type SessionManagerDeps = {
51
+ checkpointStore: CheckpointStore;
52
+ l2BlockSource: Pick<
53
+ L2BlockSource,
54
+ 'isEpochComplete' | 'getCheckpoints' | 'getL1Constants' | 'getBlockNumber' | 'getBlockData'
55
+ >;
56
+ proverFactory: EpochProverFactory;
57
+ proverId: EthAddress;
58
+ publishingService: ProofPublishingService;
59
+ metrics: ProverNodeJobMetrics;
60
+ dateProvider: DateProvider;
61
+ config: SessionManagerConfig;
62
+ /**
63
+ * Fired once when a full session ends in its own genuine failure (`EpochSession.hasFailed()` — top-tree
64
+ * or submit failed with every prover healthy). The owner uploads a post-mortem here. Not fired for a
65
+ * `stopped` session (a prover under it failed — possibly a prune), which is recovered on re-add instead.
66
+ */
67
+ onSessionFailed?: (session: EpochSession) => Promise<void>;
68
+ bindings?: LoggerBindings;
69
+ };
70
+
71
+ /**
72
+ * Owns the lifecycle of every `EpochSession`. Each L2BlockStream event and periodic tick
73
+ * arrives via a dedicated entry point (`onCheckpointAdded`, `onPrune`, `onTick`, etc.) which
74
+ * schedules a `reconcile(trigger)` on a serial queue. Reconcile walks both session
75
+ * maps, cancels any session whose canonical content has shifted, re-creates it with
76
+ * the same spec but new content, and opens fresh full sessions for any epoch implicated
77
+ * by the trigger.
78
+ */
79
+ export class SessionManager {
80
+ private readonly log: Logger;
81
+ private readonly fullSessions: Map<EpochNumber, EpochSession> = new Map();
82
+ private readonly partialSessions: Map<string, EpochSession> = new Map();
83
+ /**
84
+ * Serialises every reconcile call. The trigger sources (L2BlockStream events, the
85
+ * periodic tick, JSON-RPC `startProof`) run independently, so without this queue two
86
+ * reconciles could interleave on the `await session.cancel(...)` step and orphan a
87
+ * freshly-constructed session.
88
+ */
89
+ private readonly reconcileQueue = new SerialQueue();
90
+ /** Cached L1 constants, populated on first read. */
91
+ private cachedL1Constants: L1RollupConstants | undefined;
92
+ /** Test-only hooks applied to every session this manager constructs. */
93
+ private sessionHooks: EpochSessionHooks | undefined;
94
+ /** Periodic tick that nudges reconcile to pick up newly-complete epochs. Started by `start()`. */
95
+ private epochTicker: RunningPromise | undefined;
96
+
97
+ constructor(private readonly deps: SessionManagerDeps) {
98
+ this.log = createLogger('prover-node:session-manager', deps.bindings);
99
+ this.reconcileQueue.start();
100
+ }
101
+
102
+ /**
103
+ * Starts the periodic tick. Separated from the constructor so tests can drive `onTick()`
104
+ * manually without the background ticker interleaving. Idempotent.
105
+ */
106
+ public start(): void {
107
+ if (this.epochTicker) {
108
+ return;
109
+ }
110
+ this.epochTicker = new RunningPromise(() => this.onTick(), this.log, this.deps.config.tickIntervalMs);
111
+ this.epochTicker.start();
112
+ }
113
+
114
+ /**
115
+ * Installs hooks applied to every session constructed from now on. Used by the e2e
116
+ * harness to interpose around top-tree proving (gate it, override it, observe it)
117
+ * without monkey-patching the orchestrator factory.
118
+ */
119
+ public setSessionHooks(hooks: EpochSessionHooks): void {
120
+ this.sessionHooks = hooks;
121
+ }
122
+
123
+ // ---------------- read-only views ----------------
124
+
125
+ /** Every live (non-terminal) session. */
126
+ public allSessions(): EpochSession[] {
127
+ return [...this.fullSessions.values(), ...this.partialSessions.values()];
128
+ }
129
+
130
+ /** Returns the full session for `epoch`, if any. */
131
+ public getFullSession(epoch: EpochNumber): EpochSession | undefined {
132
+ return this.fullSessions.get(epoch);
133
+ }
134
+
135
+ /** Returns the partial session for `spec`, if any. */
136
+ public getPartialSession(spec: SessionSpec): EpochSession | undefined {
137
+ return this.partialSessions.get(specKey(spec));
138
+ }
139
+
140
+ /** Observability summary used by the prover-node API. */
141
+ public getJobs(): { uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[] {
142
+ return this.allSessions().map(s => ({
143
+ uuid: s.getId(),
144
+ status: s.getState(),
145
+ epochNumber: s.getEpochNumber(),
146
+ }));
147
+ }
148
+
149
+ // ---------------- event entry points ----------------
150
+
151
+ /** Called by ProverNode after a chain-checkpointed event has been added to the store. */
152
+ public onCheckpointAdded(epoch: EpochNumber): Promise<void> {
153
+ return this.scheduleReconcile({ kind: 'checkpoint', epoch });
154
+ }
155
+
156
+ /** Called by ProverNode after a chain-pruned event has flipped store provers to pruned. */
157
+ public onPrune(affectedEpochs: EpochNumber[]): Promise<void> {
158
+ return this.scheduleReconcile({ kind: 'prune', affectedEpochs });
159
+ }
160
+
161
+ /**
162
+ * Called periodically by ProverNode's ticker. Picks up epochs that have become complete
163
+ * by time without a fresh checkpoint event (e.g. the epoch's last slots are empty), and
164
+ * advances to the next epoch once the previous one is proven on L1.
165
+ */
166
+ public onTick(): Promise<void> {
167
+ return this.scheduleReconcile({ kind: 'tick' });
168
+ }
169
+
170
+ // ---------------- public API ----------------
171
+
172
+ /**
173
+ * Schedules a proof attempt for the supplied epoch and returns the job id without waiting for
174
+ * the proof to complete — proving can far outlast an HTTP request, so callers poll `getJobs()`
175
+ * for the outcome. Every session — full or partial — begins at the epoch's first slot; the
176
+ * partial's spec stops at the last canonical slot, while the full's stops at the epoch's last
177
+ * slot. Dedupes against any existing session covering the same range, returning its id.
178
+ */
179
+ public async startProof(epoch: EpochNumber): Promise<string> {
180
+ const canonical = await this.deps.checkpointStore.listForEpoch(epoch);
181
+ if (canonical.length === 0) {
182
+ throw new EmptyEpochError(epoch);
183
+ }
184
+ // Don't re-prove an epoch the L1 proven chain already encompasses — it was already proven
185
+ // (possibly by another prover node), so a fresh proof would be wasted work.
186
+ if (await this.isProvenChainEncompassing(canonical)) {
187
+ throw new EpochAlreadyProvenError(epoch);
188
+ }
189
+ const l1Constants = await this.getL1Constants();
190
+ const [fromSlot] = getSlotRangeForEpoch(epoch, l1Constants);
191
+ const toSlot = canonical[canonical.length - 1].slotNumber;
192
+ const spec: SessionSpec = { kind: 'partial', epochNumber: epoch, fromSlot, toSlot };
193
+
194
+ // Reuse a session already covering this exact range rather than scheduling a duplicate.
195
+ const existingFull = this.getFullSession(epoch);
196
+ if (
197
+ existingFull &&
198
+ !existingFull.isTerminal() &&
199
+ existingFull.getSpec().fromSlot === fromSlot &&
200
+ existingFull.getSpec().toSlot === toSlot
201
+ ) {
202
+ return existingFull.getId();
203
+ }
204
+ const existingPartial = this.getPartialSession(spec);
205
+ if (existingPartial && !existingPartial.isTerminal()) {
206
+ return existingPartial.getId();
207
+ }
208
+
209
+ await this.scheduleReconcile({ kind: 'start-proof', spec });
210
+ const created = this.getPartialSession(spec);
211
+ if (!created) {
212
+ throw new Error(`Failed to schedule partial proof for epoch ${epoch}`);
213
+ }
214
+ return created.getId();
215
+ }
216
+
217
+ /** Stops the tick, drains the reconcile queue, and cancels every live session. */
218
+ public async stop(): Promise<void> {
219
+ await this.epochTicker?.stop();
220
+ await this.reconcileQueue.cancel();
221
+ const sessions = this.allSessions();
222
+ // A clean shutdown is just a restart, so preserve the in-flight broker jobs (abortJobs: false)
223
+ // for the restarted node to reuse rather than re-proving the epoch from scratch.
224
+ await Promise.allSettled(sessions.map(s => s.cancel('prover-node stopping', { abortJobs: false })));
225
+ }
226
+
227
+ // ---------------- reconcile ----------------
228
+
229
+ private scheduleReconcile(trigger: ReconcileTrigger): Promise<void> {
230
+ return this.reconcileQueue.put(() => this.reconcile(trigger));
231
+ }
232
+
233
+ private async reconcile(trigger: ReconcileTrigger): Promise<void> {
234
+ this.log.debug(`Reconciling`, { trigger });
235
+
236
+ this.recreateInvalidSessions();
237
+
238
+ const implicatedEpochs = await this.epochsForTrigger(trigger);
239
+ for (const epoch of implicatedEpochs) {
240
+ await this.openFullSessionIfReady(epoch);
241
+ }
242
+
243
+ if (trigger.kind === 'start-proof') {
244
+ this.openPartialSession(trigger.spec);
245
+ }
246
+ }
247
+
248
+ private recreateInvalidSessions(): void {
249
+ for (const [key, session] of Array.from(this.fullSessions.entries())) {
250
+ const canonical = this.checkpointsForSpec(session.getSpec());
251
+ const contentChanged = !this.checkpointsMatch(session.getCheckpoints(), canonical);
252
+
253
+ if (session.isTerminal()) {
254
+ // A full session that failed on its own account is retained as a "do not re-prove" marker while
255
+ // its content is unchanged — this is what stops the tick re-proving a deterministically-failing
256
+ // epoch. When the content changes (a re-add), it is replaced so the epoch retries over the new
257
+ // provers. Any other terminal full session is simply dropped.
258
+ if (session.hasFailed() && !contentChanged) {
259
+ continue;
260
+ }
261
+ this.fullSessions.delete(key);
262
+ if (contentChanged && this.canBuildOver(canonical)) {
263
+ const newSession = this.constructSession(session.getSpec(), canonical);
264
+ this.fullSessions.set(key, newSession);
265
+ void this.runSession(newSession);
266
+ }
267
+ continue;
268
+ }
269
+
270
+ if (contentChanged) {
271
+ this.fireAndForgetCancel(session, 'canonical content changed');
272
+ this.fullSessions.delete(key);
273
+ if (this.canBuildOver(canonical)) {
274
+ const newSession = this.constructSession(session.getSpec(), canonical);
275
+ this.fullSessions.set(key, newSession);
276
+ void this.runSession(newSession);
277
+ }
278
+ }
279
+ }
280
+ for (const [key, session] of Array.from(this.partialSessions.entries())) {
281
+ if (session.isTerminal()) {
282
+ this.partialSessions.delete(key);
283
+ continue;
284
+ }
285
+ const canonical = this.checkpointsForSpec(session.getSpec());
286
+ if (!this.checkpointsMatch(session.getCheckpoints(), canonical)) {
287
+ this.fireAndForgetCancel(session, 'canonical content changed');
288
+ this.partialSessions.delete(key);
289
+ if (this.canBuildOver(canonical)) {
290
+ const newSession = this.constructSession(session.getSpec(), canonical);
291
+ this.partialSessions.set(key, newSession);
292
+ void this.runSession(newSession);
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ /** A session may be built over a checkpoint set only when it is non-empty and contains no failed prover. */
299
+ private canBuildOver(canonical: readonly CheckpointProver[]): boolean {
300
+ return canonical.length > 0 && !this.hasFailedProver(canonical);
301
+ }
302
+
303
+ private async openFullSessionIfReady(epoch: EpochNumber): Promise<void> {
304
+ // A session present here already covers the epoch: either live, or a retained genuinely-failed
305
+ // session kept by `recreateInvalidSessions` as a "do not re-prove" marker. Either way, don't open
306
+ // another — the retained-failed one is replaced only when its canonical content changes.
307
+ if (this.fullSessions.has(epoch)) {
308
+ return;
309
+ }
310
+ if (this.atMaxSessionLimit()) {
311
+ this.log.debug(`Skipping full-session open for epoch ${epoch}: max pending jobs reached`);
312
+ return;
313
+ }
314
+ if (!(await this.deps.l2BlockSource.isEpochComplete(epoch))) {
315
+ return;
316
+ }
317
+ const l1Constants = await this.getL1Constants();
318
+ const archiverCps = await this.deps.l2BlockSource.getCheckpoints({ epoch });
319
+ if (archiverCps.length === 0) {
320
+ return;
321
+ }
322
+ const [fromSlot, toSlot] = getSlotRangeForEpoch(epoch, l1Constants);
323
+ const canonical = this.deps.checkpointStore.listInSlotRange(fromSlot, toSlot);
324
+ if (!this.archiverFullyCovered(archiverCps, canonical)) {
325
+ this.log.debug(`Skipping full-session open for epoch ${epoch}: archiver checkpoints not all in store`, {
326
+ archiverCount: archiverCps.length,
327
+ storeCount: canonical.length,
328
+ });
329
+ return;
330
+ }
331
+ if (this.hasFailedProver(canonical)) {
332
+ // A checkpoint prover in the set has failed (a sub-tree fault or a prune-induced fork fault), so a
333
+ // session over it would fail immediately. Don't re-create it every tick — it recovers when a
334
+ // prune/re-add replaces the failed prover with a fresh one, or fails for good at expiry.
335
+ this.log.debug(`Skipping full-session open for epoch ${epoch}: a checkpoint prover has failed`, { epoch });
336
+ return;
337
+ }
338
+ const spec: SessionSpec = { kind: 'full', epochNumber: epoch, fromSlot, toSlot };
339
+ const session = this.constructSession(spec, canonical);
340
+ this.fullSessions.set(epoch, session);
341
+ void this.runSession(session);
342
+ }
343
+
344
+ private openPartialSession(spec: SessionSpec): void {
345
+ const canonical = this.deps.checkpointStore.listInSlotRange(spec.fromSlot, spec.toSlot);
346
+ if (canonical.length === 0 || this.hasFailedProver(canonical)) {
347
+ return;
348
+ }
349
+ // Reuse a live partial session for this epoch whose checkpoint set already matches the
350
+ // canonical content — e.g. a repeated `startProof` with no new checkpoints mined since the
351
+ // last one. Reconstructing would re-prove identical content and burn a pending-job slot.
352
+ const existing = Array.from(this.partialSessions.values()).find(
353
+ s =>
354
+ s.getSpec().epochNumber === spec.epochNumber &&
355
+ !s.isTerminal() &&
356
+ this.checkpointsMatch(s.getCheckpoints(), canonical),
357
+ );
358
+ if (existing) {
359
+ return;
360
+ }
361
+ if (this.atMaxSessionLimit()) {
362
+ throw new Error(`Maximum pending proving jobs ${this.deps.config.maxPendingJobs} reached.`);
363
+ }
364
+ const session = this.constructSession(spec, canonical);
365
+ this.partialSessions.set(specKey(spec), session);
366
+ void this.runSession(session);
367
+ }
368
+
369
+ // ---------------- session construction ----------------
370
+
371
+ protected constructSession(spec: SessionSpec, checkpoints: readonly CheckpointProver[]): EpochSession {
372
+ return this.doConstructSession(spec, checkpoints, this.buildSessionDeps(spec.epochNumber), this.sessionHooks);
373
+ }
374
+
375
+ /** Extracted for test override. */
376
+ protected doConstructSession(
377
+ spec: SessionSpec,
378
+ checkpoints: readonly CheckpointProver[],
379
+ sessionDeps: EpochSessionDeps,
380
+ hooks?: EpochSessionHooks,
381
+ ): EpochSession {
382
+ return new EpochSession(spec, checkpoints, { ...sessionDeps, hooks });
383
+ }
384
+
385
+ private buildSessionDeps(epochNumber: EpochNumber): EpochSessionDeps {
386
+ const config: EpochSessionOptions = {
387
+ finalizationDelayMs: this.deps.config.finalizationDelayMs,
388
+ };
389
+ return {
390
+ proverFactory: this.deps.proverFactory,
391
+ proverId: this.deps.proverId,
392
+ publishingService: this.deps.publishingService,
393
+ metrics: this.deps.metrics,
394
+ dateProvider: this.deps.dateProvider,
395
+ deadline: this.computeDeadline(epochNumber),
396
+ config,
397
+ bindings: this.deps.bindings,
398
+ };
399
+ }
400
+
401
+ private computeDeadline(epochNumber: EpochNumber): Date | undefined {
402
+ if (!this.cachedL1Constants) {
403
+ return undefined;
404
+ }
405
+ const ts = getProofSubmissionDeadlineTimestamp(epochNumber, this.cachedL1Constants);
406
+ return new Date(Number(ts) * 1000);
407
+ }
408
+
409
+ private async runSession(session: EpochSession): Promise<void> {
410
+ // A reconcile may have cancelled this session before it starts (content-change
411
+ // recreation). Don't proceed — start() would build a TopTreeJob that should never run.
412
+ if (session.isTerminal()) {
413
+ this.log.debug(`Skipping start for ${session.getId()}: already terminal (${session.getState()})`);
414
+ return;
415
+ }
416
+ const state = await session.start();
417
+ this.log.info(`Session ${session.getId()} exited with state ${state}`);
418
+
419
+ // A full session that failed on its own account (top-tree/submit failed with every prover healthy)
420
+ // is a genuine, race-free failure: upload its post-mortem once. `recreateInvalidSessions` retains
421
+ // the terminal session so this fires exactly once (it is never re-run over the same content). A
422
+ // `stopped` session (a prover under it failed) is not uploaded — it may be a prune, and recovers on
423
+ // re-add.
424
+ if (session.getKind() === 'full' && session.hasFailed() && this.deps.onSessionFailed) {
425
+ try {
426
+ await this.deps.onSessionFailed(session);
427
+ } catch (err) {
428
+ this.log.error(`Error in onSessionFailed callback for epoch ${session.getEpochNumber()}`, err);
429
+ }
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Builds the EpochProvingJobData snapshot for a post-mortem failure upload from a set of
435
+ * checkpoint provers. Includes every checkpoint regardless of whether sub-tree proving
436
+ * completed — partial state is still useful for post-mortem analysis.
437
+ */
438
+ public static async buildProvingData(checkpoints: readonly CheckpointProver[]): Promise<EpochProvingJobData> {
439
+ if (checkpoints.length === 0) {
440
+ throw new Error('Cannot build proving data from an empty checkpoint set');
441
+ }
442
+ // Provers no longer cache their txs; re-fetch each checkpoint's txs from the tx pool (concurrently)
443
+ // for the snapshot. The pool retains them past the proving window (A-1274), so this is durable.
444
+ const perCheckpoint = await Promise.all(checkpoints.map(async c => ({ c, txs: await c.getTxsForUpload() })));
445
+ const txs = new Map();
446
+ const l1ToL2Messages: Record<number, Fr[]> = {};
447
+ for (const { c, txs: checkpointTxs } of perCheckpoint) {
448
+ for (const [hash, tx] of checkpointTxs) {
449
+ txs.set(hash, tx);
450
+ }
451
+ l1ToL2Messages[c.checkpoint.number] = c.l1ToL2Messages;
452
+ }
453
+ return {
454
+ epochNumber: checkpoints[0].epochNumber,
455
+ checkpoints: checkpoints.map(c => c.checkpoint),
456
+ txs,
457
+ l1ToL2Messages,
458
+ previousBlockHeader: checkpoints[0].previousBlockHeader,
459
+ attestations: [],
460
+ };
461
+ }
462
+
463
+ // ---------------- reconcile helpers ----------------
464
+
465
+ private atMaxSessionLimit(): boolean {
466
+ const { maxPendingJobs: max } = this.deps.config;
467
+ if (!max || max <= 0) {
468
+ return false;
469
+ }
470
+ const live = this.allSessions().filter(s => !s.isTerminal()).length;
471
+ return live >= max;
472
+ }
473
+
474
+ /**
475
+ * Maps a reconcile trigger to the epochs whose full session should be (re)opened.
476
+ *
477
+ * The periodic `tick` returns the next unproven epoch every time; it does not track prior attempts.
478
+ * `openFullSessionIfReady` is what keeps this from re-proving a doomed epoch: it refuses to build a
479
+ * session when any checkpoint prover in the set has failed, so a stuck epoch is cheaply skipped each
480
+ * tick rather than re-proved. `checkpoint` and `prune` fire when an epoch's canonical content changes
481
+ * (a checkpoint arrives, or a reorg prunes/replaces one) — which is what installs a fresh prover in
482
+ * place of a failed one, letting the next open succeed and recovering a pruned-then-re-added epoch.
483
+ */
484
+ private async epochsForTrigger(trigger: ReconcileTrigger): Promise<EpochNumber[]> {
485
+ switch (trigger.kind) {
486
+ case 'checkpoint':
487
+ return [trigger.epoch];
488
+ case 'prune':
489
+ return trigger.affectedEpochs;
490
+ case 'tick': {
491
+ const epoch = await this.nextUnprovenEpoch();
492
+ return epoch === undefined ? [] : [epoch];
493
+ }
494
+ case 'start-proof':
495
+ return [];
496
+ }
497
+ }
498
+
499
+ /**
500
+ * The next epoch to prove: the epoch containing the first block after the proven tip.
501
+ * Returns undefined when that block has not been mined yet (e.g. nothing new to prove).
502
+ * Subsequent ticks advance only once the chain's proven height moves forward, so epochs
503
+ * are proven in order rather than all at once.
504
+ */
505
+ private async nextUnprovenEpoch(): Promise<EpochNumber | undefined> {
506
+ const lastProven = (await this.deps.l2BlockSource.getBlockNumber({ tag: 'proven' })) ?? BlockNumber.ZERO;
507
+ const firstToProve = BlockNumber(lastProven + 1);
508
+ const header = (await this.deps.l2BlockSource.getBlockData({ number: firstToProve }))?.header;
509
+ if (!header) {
510
+ return undefined;
511
+ }
512
+ return getEpochAtSlot(header.getSlot(), await this.getL1Constants());
513
+ }
514
+
515
+ private checkpointsForSpec(spec: SessionSpec): CheckpointProver[] {
516
+ return this.deps.checkpointStore.listInSlotRange(spec.fromSlot, spec.toSlot);
517
+ }
518
+
519
+ /**
520
+ * True if any prover in the set has failed. The epoch cannot be proven over a failed prover (it can
521
+ * never produce its block proofs), so a session must not be built or rebuilt over it until a prune/re-add
522
+ * has replaced it with a fresh prover.
523
+ */
524
+ private hasFailedProver(checkpoints: readonly CheckpointProver[]): boolean {
525
+ return checkpoints.some(c => c.isFailed());
526
+ }
527
+
528
+ private fireAndForgetCancel(session: EpochSession, reason: string): void {
529
+ void session.cancel(reason).catch(err => this.log.warn(`Error cancelling session ${session.getId()}`, err));
530
+ }
531
+
532
+ private checkpointsMatch(a: readonly CheckpointProver[], b: readonly CheckpointProver[]): boolean {
533
+ if (a.length !== b.length) {
534
+ return false;
535
+ }
536
+ for (let i = 0; i < a.length; i++) {
537
+ if (a[i].id !== b[i].id || a[i].isCancelled()) {
538
+ return false;
539
+ }
540
+ }
541
+ return true;
542
+ }
543
+
544
+ private archiverFullyCovered(
545
+ archiverCps: readonly PublishedCheckpoint[],
546
+ storeCps: readonly CheckpointProver[],
547
+ ): boolean {
548
+ if (storeCps.length < archiverCps.length) {
549
+ return false;
550
+ }
551
+ // Compare by content-addressed id (number, slot, archive root) rather than checkpoint number:
552
+ // a reorg can keep the number while changing the checkpoint's post-state archive root.
553
+ const storeIds = new Set(storeCps.map(p => p.id));
554
+ return archiverCps.every(cp => storeIds.has(CheckpointProver.idFor(cp.checkpoint)));
555
+ }
556
+
557
+ /**
558
+ * Returns true if the L1 proven tip already covers every canonical checkpoint in the set — i.e.
559
+ * the epoch has already been fully proven, so there is no point starting a new proof for it.
560
+ * Conservatively returns false when nothing is proven yet.
561
+ */
562
+ private async isProvenChainEncompassing(canonical: readonly CheckpointProver[]): Promise<boolean> {
563
+ const provenBlock = await this.deps.l2BlockSource.getBlockNumber({ tag: 'proven' });
564
+ if (!provenBlock || provenBlock <= 0) {
565
+ return false;
566
+ }
567
+ const lastCheckpoint = canonical[canonical.length - 1].checkpoint;
568
+ const lastBlock = lastCheckpoint.blocks[lastCheckpoint.blocks.length - 1].number;
569
+ return provenBlock >= lastBlock;
570
+ }
571
+
572
+ private async getL1Constants(): Promise<L1RollupConstants> {
573
+ if (!this.cachedL1Constants) {
574
+ this.cachedL1Constants = await this.deps.l2BlockSource.getL1Constants();
575
+ }
576
+ return this.cachedL1Constants;
577
+ }
578
+ }
579
+
580
+ class EmptyEpochError extends Error {
581
+ constructor(epochNumber: EpochNumber) {
582
+ super(`No blocks found for epoch ${epochNumber}`);
583
+ this.name = 'EmptyEpochError';
584
+ }
585
+ }
586
+
587
+ class EpochAlreadyProvenError extends Error {
588
+ constructor(epochNumber: EpochNumber) {
589
+ super(`Epoch ${epochNumber} is already proven on L1`);
590
+ this.name = 'EpochAlreadyProvenError';
591
+ }
592
+ }
package/src/test/index.ts CHANGED
@@ -1,14 +1,14 @@
1
+ import type { EpochProverFactory } from '@aztec/prover-client';
1
2
  import type { EpochProverManager } from '@aztec/stdlib/interfaces/server';
2
3
 
3
- import type { EpochProvingJob } from '../job/epoch-proving-job.js';
4
- import type { ProverNodePublisher } from '../prover-node-publisher.js';
4
+ import type { ProofPublishingService } from '../proof-publishing-service.js';
5
5
  import { ProverNode } from '../prover-node.js';
6
+ import type { SessionManager } from '../session-manager.js';
6
7
 
7
8
  abstract class TestProverNodeClass extends ProverNode {
8
- declare public prover: EpochProverManager;
9
- declare public publisher: ProverNodePublisher;
10
-
11
- public abstract override tryUploadEpochFailure(job: EpochProvingJob): Promise<string | undefined>;
9
+ declare public prover: EpochProverManager & EpochProverFactory;
10
+ declare public publishingService: ProofPublishingService;
11
+ declare public sessionManager: SessionManager;
12
12
  }
13
13
 
14
14
  export type TestProverNode = TestProverNodeClass;