@aztec/prover-node 0.0.1-commit.3fd054f6 → 0.0.1-commit.431c48d

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 (71) 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 +13 -3
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +146 -22
  6. package/dest/bin/run-failed-epoch.js +1 -3
  7. package/dest/checkpoint-store.d.ts +95 -0
  8. package/dest/checkpoint-store.d.ts.map +1 -0
  9. package/dest/checkpoint-store.js +178 -0
  10. package/dest/config.d.ts +3 -1
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +8 -1
  13. package/dest/factory.d.ts +1 -1
  14. package/dest/factory.d.ts.map +1 -1
  15. package/dest/factory.js +3 -7
  16. package/dest/index.d.ts +2 -1
  17. package/dest/index.d.ts.map +1 -1
  18. package/dest/index.js +1 -0
  19. package/dest/job/checkpoint-prover.d.ts +165 -0
  20. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  21. package/dest/job/checkpoint-prover.js +405 -0
  22. package/dest/job/epoch-session.d.ts +160 -0
  23. package/dest/job/epoch-session.d.ts.map +1 -0
  24. package/dest/job/epoch-session.js +744 -0
  25. package/dest/job/top-tree-job.d.ts +82 -0
  26. package/dest/job/top-tree-job.d.ts.map +1 -0
  27. package/dest/job/top-tree-job.js +152 -0
  28. package/dest/metrics.d.ts +35 -8
  29. package/dest/metrics.d.ts.map +1 -1
  30. package/dest/metrics.js +86 -14
  31. package/dest/monitors/epoch-monitor.js +6 -2
  32. package/dest/proof-publishing-service.d.ts +161 -0
  33. package/dest/proof-publishing-service.d.ts.map +1 -0
  34. package/dest/proof-publishing-service.js +335 -0
  35. package/dest/prover-node-publisher.d.ts +25 -15
  36. package/dest/prover-node-publisher.d.ts.map +1 -1
  37. package/dest/prover-node-publisher.js +201 -62
  38. package/dest/prover-node.d.ts +131 -66
  39. package/dest/prover-node.d.ts.map +1 -1
  40. package/dest/prover-node.js +536 -219
  41. package/dest/prover-publisher-factory.d.ts +3 -1
  42. package/dest/prover-publisher-factory.d.ts.map +1 -1
  43. package/dest/prover-publisher-factory.js +1 -0
  44. package/dest/session-manager.d.ts +158 -0
  45. package/dest/session-manager.d.ts.map +1 -0
  46. package/dest/session-manager.js +492 -0
  47. package/dest/test/index.d.ts +7 -6
  48. package/dest/test/index.d.ts.map +1 -1
  49. package/package.json +23 -23
  50. package/src/actions/download-epoch-proving-job.ts +1 -1
  51. package/src/actions/rerun-epoch-proving-job.ts +177 -32
  52. package/src/bin/run-failed-epoch.ts +1 -2
  53. package/src/checkpoint-store.ts +212 -0
  54. package/src/config.ts +12 -1
  55. package/src/factory.ts +2 -9
  56. package/src/index.ts +1 -0
  57. package/src/job/checkpoint-prover.ts +538 -0
  58. package/src/job/epoch-session.ts +462 -0
  59. package/src/job/top-tree-job.ts +227 -0
  60. package/src/metrics.ts +102 -23
  61. package/src/monitors/epoch-monitor.ts +2 -2
  62. package/src/proof-publishing-service.ts +427 -0
  63. package/src/prover-node-publisher.ts +236 -78
  64. package/src/prover-node.ts +617 -242
  65. package/src/prover-publisher-factory.ts +3 -0
  66. package/src/session-manager.ts +592 -0
  67. package/src/test/index.ts +6 -6
  68. package/dest/job/epoch-proving-job.d.ts +0 -63
  69. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  70. package/dest/job/epoch-proving-job.js +0 -762
  71. package/src/job/epoch-proving-job.ts +0 -465
@@ -0,0 +1,462 @@
1
+ import { BlockNumber, type CheckpointNumber, type EpochNumber, type SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
4
+ import { sleep } from '@aztec/foundation/sleep';
5
+ import { type DateProvider, Timer } from '@aztec/foundation/timer';
6
+ import type { EpochProverFactory } from '@aztec/prover-client';
7
+ import { TopTreeCancelledError } from '@aztec/prover-client/orchestrator';
8
+ import { type EpochProvingJobState, EpochProvingJobTerminalState } from '@aztec/stdlib/interfaces/server';
9
+ import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
10
+
11
+ import * as crypto from 'node:crypto';
12
+
13
+ import type { ProverNodeJobMetrics } from '../metrics.js';
14
+ import type { ProofPublishingService } from '../proof-publishing-service.js';
15
+ import { CheckpointProver } from './checkpoint-prover.js';
16
+ import { TopTreeJob, type TopTreeJobHooks, type TopTreeProof } from './top-tree-job.js';
17
+
18
+ export type { EpochProvingJobState };
19
+
20
+ /** Full vs partial — the only behavioural difference is at the L1 submission step. */
21
+ export type SessionKind = 'full' | 'partial';
22
+
23
+ /**
24
+ * Identifies what a session proves: a contiguous slot range within an epoch. The
25
+ * concrete prover set the session holds is the *implementation* of the spec — frozen
26
+ * at construction time, derived from the canonical content for `[fromSlot, toSlot]`.
27
+ *
28
+ * Reconciliation in `ProverNode` is uniform across kinds: whenever the canonical
29
+ * content for the slot range changes, the session is cancelled and replaced with a
30
+ * fresh session that **preserves the slot range** but adopts the new checkpoints.
31
+ *
32
+ * Kind affects only the publishing decision (see `EpochSession`).
33
+ */
34
+ export interface SessionSpec {
35
+ kind: SessionKind;
36
+ epochNumber: EpochNumber;
37
+ fromSlot: SlotNumber;
38
+ toSlot: SlotNumber;
39
+ }
40
+
41
+ /** Stable string key for use in maps. */
42
+ export function specKey(spec: SessionSpec): string {
43
+ return `${spec.kind}:${spec.epochNumber}:${spec.fromSlot}-${spec.toSlot}`;
44
+ }
45
+
46
+ /** Hooks tests use to interpose around the top-tree prove without monkey-patching. */
47
+ export type EpochSessionHooks = {
48
+ beforeTopTreeProve?: () => Promise<void> | void;
49
+ afterTopTreeProve?: () => Promise<void> | void;
50
+ topTreeProveOverride?: (defaultProve: () => Promise<TopTreeProof>) => Promise<TopTreeProof>;
51
+ };
52
+
53
+ export type EpochSessionOptions = {
54
+ /**
55
+ * If set, the session sleeps this many ms after `start()` (before the TopTreeJob is
56
+ * constructed). Lets late-arriving events (e.g. a prune) be processed before
57
+ * top-tree proving begins.
58
+ */
59
+ finalizationDelayMs?: number;
60
+ };
61
+
62
+ /** Dependencies an `EpochSession` needs at construction. */
63
+ export type EpochSessionDeps = {
64
+ proverFactory: EpochProverFactory;
65
+ proverId: EthAddress;
66
+ publishingService: Pick<ProofPublishingService, 'submit' | 'withdraw'>;
67
+ metrics: ProverNodeJobMetrics;
68
+ dateProvider: DateProvider;
69
+ /** Optional proving deadline. The session enters `timed-out` if exceeded. */
70
+ deadline: Date | undefined;
71
+ config: EpochSessionOptions;
72
+ bindings?: LoggerBindings;
73
+ hooks?: EpochSessionHooks;
74
+ };
75
+
76
+ /**
77
+ * One attempt at proving and publishing a contiguous slot range. The `SessionSpec` and
78
+ * the prover set are both frozen at construction time; the session does not adapt to
79
+ * reorgs or extensions of canonical content. Instead, `SessionManager` owns the
80
+ * reconciliation loop and replaces invalidated sessions wholesale (cancel + construct
81
+ * a fresh session with the new prover set).
82
+ *
83
+ * Each session does three things in sequence:
84
+ *
85
+ * 1. Run a `TopTreeJob` over its frozen prover subset to produce the epoch proof.
86
+ * 2. Hand the proof to the shared `ProofPublishingService` as a `PublishCandidate`.
87
+ * 3. Translate the service's outcome into a terminal session state.
88
+ *
89
+ * Everything to do with submission — predecessor gating, same-epoch dedup, deadline
90
+ * enforcement, and the L1 transaction itself — is the publishing service's concern.
91
+ * The session is just the producer of one candidate and the observer of its outcome.
92
+ *
93
+ * Lifecycle (happy path):
94
+ *
95
+ * initialized → awaiting-checkpoints → awaiting-root → publishing-proof → completed
96
+ *
97
+ * Terminal states map the publishing outcome: `published` → `completed`, `superseded` →
98
+ * `superseded`, `expired` → `timed-out`, `withdrawn` → `cancelled`. A fault ends the attempt in one
99
+ * of two terminal states depending on its cause: `stopped` if a checkpoint prover under it failed
100
+ * (possibly a prune — the reconciler will rebuild over a fresh prover on re-add), or `failed` if the
101
+ * session's own top-tree/submit work failed while every prover was healthy (a genuine, non-prune
102
+ * failure the reconciler retains and uploads — see `hasFailed()`).
103
+ * Additionally, the session-level deadline fires `cancel('deadline')` and transitions
104
+ * to `timed-out` for the pre-submit window (top-tree proving) — the publishing service
105
+ * handles the post-submit window via the candidate's `deadline`.
106
+ *
107
+ * `cancel()` is idempotent. It marks the session terminal, calls
108
+ * `publishingService.withdraw(uuid)` to drop any queued candidate (an in-flight publish
109
+ * runs to natural completion; the session has already settled), and tears down the
110
+ * top-tree job if proving is still in progress.
111
+ */
112
+ export class EpochSession implements Traceable {
113
+ public readonly tracer: Tracer;
114
+ private readonly uuid: string;
115
+ private readonly log: Logger;
116
+ private state: EpochProvingJobState = 'initialized';
117
+ private deadlineTimeoutHandler: NodeJS.Timeout | undefined;
118
+
119
+ private topTreeJob: TopTreeJob | undefined;
120
+ /** Cancelled top-tree jobs whose teardown is still in flight. Awaited at session stop. */
121
+ private readonly pendingTopTreeCleanups: TopTreeJob[] = [];
122
+
123
+ private readonly completionPromise: Promise<EpochProvingJobState>;
124
+ private resolveCompletion!: (state: EpochProvingJobState) => void;
125
+
126
+ /** Stable reference; never mutated after construction. */
127
+ private readonly checkpoints: readonly CheckpointProver[];
128
+
129
+ constructor(
130
+ private readonly spec: SessionSpec,
131
+ checkpoints: readonly CheckpointProver[],
132
+ private readonly deps: EpochSessionDeps,
133
+ ) {
134
+ if (checkpoints.length === 0) {
135
+ throw new Error(`Cannot construct EpochSession for ${specKey(spec)}: empty checkpoint set`);
136
+ }
137
+ this.checkpoints = [...checkpoints];
138
+ this.uuid = crypto.randomUUID();
139
+ this.log = createLogger('prover-node:epoch-session', {
140
+ ...deps.bindings,
141
+ instanceId: `session-${spec.kind}-${spec.epochNumber}-${spec.fromSlot}-${spec.toSlot}`,
142
+ });
143
+ this.tracer = deps.metrics.tracer;
144
+ this.completionPromise = new Promise(resolve => {
145
+ this.resolveCompletion = resolve;
146
+ });
147
+ this.scheduleDeadlineStop();
148
+ this.log.info(`Created EpochSession ${this.uuid}`, {
149
+ uuid: this.uuid,
150
+ ...spec,
151
+ checkpointCount: this.checkpoints.length,
152
+ checkpointIds: this.checkpoints.map(c => c.id),
153
+ });
154
+ }
155
+
156
+ public getId(): string {
157
+ return this.uuid;
158
+ }
159
+
160
+ public getSpec(): SessionSpec {
161
+ return this.spec;
162
+ }
163
+
164
+ public getState(): EpochProvingJobState {
165
+ return this.state;
166
+ }
167
+
168
+ public getEpochNumber(): EpochNumber {
169
+ return this.spec.epochNumber;
170
+ }
171
+
172
+ public getKind(): SessionKind {
173
+ return this.spec.kind;
174
+ }
175
+
176
+ public getDeadline(): Date | undefined {
177
+ return this.deps.deadline;
178
+ }
179
+
180
+ public getCheckpoints(): readonly CheckpointProver[] {
181
+ return this.checkpoints;
182
+ }
183
+
184
+ /** Resolves when the session reaches a terminal state. */
185
+ public whenDone(): Promise<EpochProvingJobState> {
186
+ return this.completionPromise;
187
+ }
188
+
189
+ /** True if the session is in a terminal state. */
190
+ public isTerminal(): boolean {
191
+ return EpochProvingJobTerminalState.includes(this.state);
192
+ }
193
+
194
+ /**
195
+ * True if the session ended in its own genuine failure — top-tree proving or L1 submission failed
196
+ * while every checkpoint prover succeeded. Because healthy provers rule out a prune-induced fault,
197
+ * this is a race-free "the epoch could not be proven" signal: the reconciler retains such a (full)
198
+ * session rather than re-proving it, and uploads a post-mortem. A `stopped` session (a checkpoint
199
+ * prover failed under it) is NOT a session failure in this sense.
200
+ */
201
+ public hasFailed(): boolean {
202
+ return this.state === 'failed';
203
+ }
204
+
205
+ /** First block this session proves. */
206
+ public getStartBlockNumber(): BlockNumber {
207
+ return BlockNumber(this.checkpoints[0].checkpoint.blocks[0].number);
208
+ }
209
+
210
+ /** Last block this session proves. */
211
+ public getEndBlockNumber(): BlockNumber {
212
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
213
+ return BlockNumber(lastCheckpoint.checkpoint.blocks[lastCheckpoint.checkpoint.blocks.length - 1].number);
214
+ }
215
+
216
+ /**
217
+ * Kicks off proving + submission. Fires and forgets — callers should await `whenDone()`.
218
+ * Returns a promise that resolves to the final state for callers that want to wait inline.
219
+ */
220
+ @trackSpan('EpochSession.start', function () {
221
+ return { [Attributes.EPOCH_NUMBER]: this.spec.epochNumber };
222
+ })
223
+ public async start(): Promise<EpochProvingJobState> {
224
+ try {
225
+ await this.run();
226
+ } catch (err) {
227
+ this.log.error(`Error in EpochSession ${this.uuid}`, err, {
228
+ uuid: this.uuid,
229
+ ...this.spec,
230
+ });
231
+ // Distinguish the two ways an attempt can fault:
232
+ // - a checkpoint prover in the set has failed OR was cancelled (a sub-tree fault, a prune-induced
233
+ // fork fault, or a control-plane cancel that reached this catch before the reconcile marked the
234
+ // session 'cancelled'): end in the non-declaring terminal 'stopped'. This is not the session's own
235
+ // failure and may be a prune, so the reconciler does not upload it; a re-add installs a fresh prover.
236
+ // - no prover failed or was cancelled, yet top-tree proving or L1 submission failed: this is the
237
+ // session's own, genuine failure — and, because every prover is healthy and un-cancelled, it is
238
+ // definitively NOT a prune. End in terminal 'failed' so the reconciler retains it (no pointless
239
+ // re-prove) and uploads a race-free post-mortem.
240
+ if (!this.isTerminal()) {
241
+ this.state = this.checkpoints.some(c => c.isFailed() || c.isCancelled()) ? 'stopped' : 'failed';
242
+ }
243
+ } finally {
244
+ clearTimeout(this.deadlineTimeoutHandler);
245
+ await this.teardownTopTreeIfNeeded();
246
+ this.resolveCompletion(this.state);
247
+ }
248
+ return this.state;
249
+ }
250
+
251
+ /**
252
+ * Cancels the session. Idempotent. Withdraws any submitted candidate from the
253
+ * publishing service so the in-flight publisher (if any) is interrupted.
254
+ */
255
+ public async cancel(reason = 'cancelled', { abortJobs = true }: { abortJobs?: boolean } = {}): Promise<void> {
256
+ if (this.isTerminal()) {
257
+ return;
258
+ }
259
+ this.log.info(`Cancelling EpochSession ${this.uuid}: ${reason}`, {
260
+ uuid: this.uuid,
261
+ ...this.spec,
262
+ previousState: this.state,
263
+ reason,
264
+ });
265
+ this.state = 'cancelled';
266
+ try {
267
+ this.deps.publishingService.withdraw(this.uuid);
268
+ } catch (err) {
269
+ this.log.error(`Error withdrawing candidate from publishing service`, err);
270
+ }
271
+ if (this.topTreeJob && !this.topTreeJob.isCancelled()) {
272
+ const job = this.topTreeJob;
273
+ this.topTreeJob = undefined;
274
+ // On a clean shutdown we leave the in-flight broker jobs alone so a restart can reuse them;
275
+ // other cancellations (reorg, supersede, deadline) abort them since their inputs are stale.
276
+ job.cancel(abortJobs);
277
+ this.pendingTopTreeCleanups.push(job);
278
+ }
279
+ await this.teardownTopTreeIfNeeded();
280
+ this.resolveCompletion(this.state);
281
+ }
282
+
283
+ private async run(): Promise<void> {
284
+ const timer = new Timer();
285
+
286
+ if (this.deps.config.finalizationDelayMs && this.deps.config.finalizationDelayMs > 0) {
287
+ this.log.warn(`Waiting ${this.deps.config.finalizationDelayMs}ms before starting top-tree proving`, {
288
+ uuid: this.uuid,
289
+ ...this.spec,
290
+ });
291
+ await sleep(this.deps.config.finalizationDelayMs);
292
+ if (this.isTerminal()) {
293
+ return;
294
+ }
295
+ }
296
+
297
+ // Stage 1 — top-tree proving.
298
+ const topTreeJob = new TopTreeJob(this.spec.epochNumber, this.checkpoints, {
299
+ proverFactory: this.deps.proverFactory,
300
+ metrics: this.deps.metrics,
301
+ log: this.log,
302
+ hooks: this.toTopTreeHooks(),
303
+ });
304
+ this.topTreeJob = topTreeJob;
305
+ const { fromCheckpoint, toCheckpoint, count } = topTreeJob.getRange();
306
+
307
+ this.state = 'awaiting-checkpoints';
308
+ let proof: TopTreeProof;
309
+ try {
310
+ proof = await topTreeJob.start();
311
+ } catch (err) {
312
+ if (err instanceof TopTreeCancelledError) {
313
+ // Session cancel kicked off the underlying teardown; nothing more to do here.
314
+ this.log.info(`Top-tree cancelled for EpochSession ${this.uuid}`, { uuid: this.uuid, ...this.spec });
315
+ return;
316
+ }
317
+ throw err;
318
+ }
319
+ this.topTreeJob = undefined;
320
+ this.log.info(`Top-tree proof ready for EpochSession ${this.uuid}`, {
321
+ uuid: this.uuid,
322
+ ...this.spec,
323
+ fromCheckpoint,
324
+ toCheckpoint,
325
+ durationMs: timer.ms(),
326
+ });
327
+
328
+ // Stage 2 — hand the proof to the publishing service and wait for its verdict.
329
+ await this.submitProof(proof, fromCheckpoint, toCheckpoint, count, timer);
330
+ }
331
+
332
+ private async submitProof(
333
+ proof: TopTreeProof,
334
+ fromCheckpoint: CheckpointNumber,
335
+ toCheckpoint: CheckpointNumber,
336
+ checkpointCount: number,
337
+ timer: Timer,
338
+ ): Promise<void> {
339
+ // Attestations come from the highest-numbered registered checkpoint — that's the one
340
+ // whose attestations the L1 contract checks for the proven range.
341
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
342
+ const attestations = lastCheckpoint.attestations.map(a => a.toViem());
343
+ const epochSizeBlocks = this.checkpoints.reduce((acc, c) => acc + c.checkpoint.blocks.length, 0);
344
+ const epochSizeTxs = this.checkpoints.reduce(
345
+ (acc, c) => acc + c.checkpoint.blocks.reduce((bAcc, block) => bAcc + block.body.txEffects.length, 0),
346
+ 0,
347
+ );
348
+
349
+ // Reflect the publish phase. Guard against a terminal state set concurrently by cancel() — the
350
+ // post-submit isTerminal() check below relies on cancel still winning.
351
+ if (!this.isTerminal()) {
352
+ this.state = 'publishing-proof';
353
+ }
354
+
355
+ const outcome = await this.deps.publishingService.submit({
356
+ id: this.uuid,
357
+ epoch: this.spec.epochNumber,
358
+ kind: this.spec.kind,
359
+ startBlock: this.getStartBlockNumber(),
360
+ endBlock: this.getEndBlockNumber(),
361
+ deadline: this.deps.deadline,
362
+ fromCheckpoint,
363
+ toCheckpoint,
364
+ publicInputs: proof.publicInputs,
365
+ proof: proof.proof,
366
+ batchedBlobInputs: proof.batchedBlobInputs,
367
+ attestations,
368
+ headers: this.checkpoints.map(c => c.checkpoint.header),
369
+ });
370
+
371
+ if (this.isTerminal()) {
372
+ // cancel() already set the terminal state — don't clobber it.
373
+ return;
374
+ }
375
+
376
+ switch (outcome) {
377
+ case 'published':
378
+ this.log.info(
379
+ `Submitted proof for epoch ${this.spec.epochNumber} (checkpoints ${fromCheckpoint}..${toCheckpoint})`,
380
+ { uuid: this.uuid, ...this.spec },
381
+ );
382
+ this.state = 'completed';
383
+ this.deps.metrics.recordProvingJob(timer.ms(), checkpointCount, epochSizeBlocks, epochSizeTxs);
384
+ return;
385
+ case 'superseded':
386
+ this.log.info(`EpochSession ${this.uuid} superseded by a longer candidate`, {
387
+ uuid: this.uuid,
388
+ ...this.spec,
389
+ });
390
+ this.state = 'superseded';
391
+ return;
392
+ case 'withdrawn':
393
+ // cancel() ran but the terminal-state check above missed it. Defensive: treat as cancelled.
394
+ this.state = 'cancelled';
395
+ return;
396
+ case 'expired':
397
+ this.log.warn(`EpochSession ${this.uuid} expired before publishing`, { uuid: this.uuid, ...this.spec });
398
+ this.state = 'timed-out';
399
+ return;
400
+ case 'failed':
401
+ throw new Error('Failed to submit epoch proof to L1');
402
+ }
403
+ }
404
+
405
+ private async teardownTopTreeIfNeeded(): Promise<void> {
406
+ if (this.topTreeJob) {
407
+ const job = this.topTreeJob;
408
+ this.topTreeJob = undefined;
409
+ job.cancel();
410
+ this.pendingTopTreeCleanups.push(job);
411
+ }
412
+ if (this.pendingTopTreeCleanups.length > 0) {
413
+ await Promise.allSettled(this.pendingTopTreeCleanups.map(j => j.whenDone()));
414
+ this.pendingTopTreeCleanups.length = 0;
415
+ }
416
+ }
417
+
418
+ private scheduleDeadlineStop(): void {
419
+ const deadline = this.deps.deadline;
420
+ if (!deadline) {
421
+ return;
422
+ }
423
+ const timeout = Math.max(deadline.getTime() - this.deps.dateProvider.now(), 0);
424
+ this.deadlineTimeoutHandler = setTimeout(() => {
425
+ void this.handleDeadline();
426
+ }, timeout);
427
+ }
428
+
429
+ /**
430
+ * Returns a promise that resolves once cancellation has propagated and the state has
431
+ * been flipped from 'cancelled' to 'timed-out'. Protected so unit tests can drive the
432
+ * deadline path without waiting on the real `setTimeout` to fire.
433
+ */
434
+ protected async handleDeadline(): Promise<void> {
435
+ if (this.isTerminal()) {
436
+ return;
437
+ }
438
+ this.log.warn(`EpochSession ${this.uuid} hit deadline`, { uuid: this.uuid, ...this.spec });
439
+ await this.cancel('deadline');
440
+ // After cancel, override state if it was the canonical timeout case so observers see 'timed-out'.
441
+ if (this.state === 'cancelled') {
442
+ this.state = 'timed-out';
443
+ }
444
+ }
445
+
446
+ private toTopTreeHooks(): TopTreeJobHooks {
447
+ const hooks = this.deps.hooks;
448
+ return {
449
+ // `beforeProve` fires once the sub-tree (checkpoint block) proofs are ready and the root prove is
450
+ // about to start — the boundary between `awaiting-checkpoints` and proving the top tree. Don't
451
+ // clobber a terminal state set concurrently by cancel().
452
+ beforeProve: async () => {
453
+ if (!this.isTerminal()) {
454
+ this.state = 'awaiting-root';
455
+ }
456
+ await hooks?.beforeTopTreeProve?.();
457
+ },
458
+ afterProve: hooks?.afterTopTreeProve,
459
+ proveOverride: hooks?.topTreeProveOverride,
460
+ };
461
+ }
462
+ }
@@ -0,0 +1,227 @@
1
+ import type { BatchedBlob } from '@aztec/blob-lib/types';
2
+ import type { CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
5
+ import { Timer } from '@aztec/foundation/timer';
6
+ import type { EpochProverFactory } from '@aztec/prover-client';
7
+ import { buildFinalBlobChallenges } from '@aztec/prover-client/helpers';
8
+ import {
9
+ type CheckpointTopTreeData,
10
+ TopTreeCancelledError,
11
+ type TopTreeOrchestrator,
12
+ } from '@aztec/prover-client/orchestrator';
13
+ import type { Proof } from '@aztec/stdlib/proofs';
14
+ import type { RootRollupPublicInputs } from '@aztec/stdlib/rollup';
15
+
16
+ import type { ProverNodeJobMetrics } from '../metrics.js';
17
+ import type { CheckpointProver } from './checkpoint-prover.js';
18
+
19
+ /** Result of a successful top-tree run. */
20
+ export type TopTreeProof = {
21
+ publicInputs: RootRollupPublicInputs;
22
+ proof: Proof;
23
+ batchedBlobInputs: BatchedBlob;
24
+ };
25
+
26
+ /**
27
+ * Hooks for tests to interpose around the underlying `topTree.prove(...)` call without
28
+ * monkey-patching the orchestrator.
29
+ */
30
+ export type TopTreeJobHooks = {
31
+ /** Called immediately before the top tree's `prove` runs. */
32
+ beforeProve?: () => Promise<void> | void;
33
+ /** Called after `prove` returns successfully (not on failure / cancellation). */
34
+ afterProve?: () => Promise<void> | void;
35
+ /**
36
+ * If set, called instead of running the underlying prove. Receives a thunk that
37
+ * runs the real call. Lets tests substitute a synthetic proof or delay/throw without
38
+ * re-implementing the rest of the finalize flow.
39
+ */
40
+ proveOverride?: (defaultProve: () => Promise<TopTreeProof>) => Promise<TopTreeProof>;
41
+ };
42
+
43
+ /**
44
+ * Self-contained top-tree job. Constructed from a snapshot of `CheckpointProver`s; runs
45
+ * `topTree.prove(...)` against their pending `blockProofs` promises and exposes the
46
+ * final epoch proof via `result`.
47
+ *
48
+ */
49
+ export class TopTreeJob {
50
+ /** Resolves with the final proof on success; rejects on cancellation or any prove error. */
51
+ readonly result: PromiseWithResolvers<TopTreeProof> = promiseWithResolvers();
52
+
53
+ /** Snapshot of checkpoint jobs the top tree is built from, in checkpoint-number order. */
54
+ readonly snapshot: readonly CheckpointProver[];
55
+
56
+ private readonly topTree: TopTreeOrchestrator;
57
+ private readonly fromCheckpoint: CheckpointNumber;
58
+ private readonly toCheckpoint: CheckpointNumber;
59
+ private cancelled = false;
60
+ /** Tracks the cancel-driven background teardown so `whenDone()` can await it. */
61
+ private cancelPromise?: Promise<void>;
62
+ private readonly executionTimer = new Timer();
63
+
64
+ constructor(
65
+ private readonly epochNumber: EpochNumber,
66
+ snapshot: readonly CheckpointProver[],
67
+ private readonly deps: {
68
+ proverFactory: EpochProverFactory;
69
+ metrics: ProverNodeJobMetrics;
70
+ log: Logger;
71
+ hooks?: TopTreeJobHooks;
72
+ },
73
+ ) {
74
+ if (snapshot.length === 0) {
75
+ throw new Error(`Cannot construct TopTreeJob for epoch ${epochNumber}: empty snapshot`);
76
+ }
77
+ for (let i = 1; i < snapshot.length; i++) {
78
+ const prev = snapshot[i - 1].checkpoint.number;
79
+ const curr = snapshot[i].checkpoint.number;
80
+ if (curr !== prev + 1) {
81
+ throw new Error(
82
+ `Cannot construct TopTreeJob for epoch ${epochNumber}: checkpoint numbers must be contiguous, got gap between ${prev} and ${curr}`,
83
+ );
84
+ }
85
+ }
86
+ this.snapshot = snapshot;
87
+ this.fromCheckpoint = snapshot[0].checkpoint.number;
88
+ this.toCheckpoint = snapshot[snapshot.length - 1].checkpoint.number;
89
+ this.topTree = deps.proverFactory.createTopTreeOrchestrator();
90
+ deps.log.info(
91
+ `Created TopTreeJob for epoch ${epochNumber} covering checkpoints ${this.fromCheckpoint}..${this.toCheckpoint}`,
92
+ {
93
+ epochNumber,
94
+ fromCheckpoint: this.fromCheckpoint,
95
+ toCheckpoint: this.toCheckpoint,
96
+ checkpointCount: snapshot.length,
97
+ },
98
+ );
99
+ // Mark the result's rejection branch as observed so a cancellation before any
100
+ // consumer awaits does not surface as unhandled.
101
+ this.result.promise.catch(() => {});
102
+ }
103
+
104
+ /** Range covered by this attempt — useful for logging and L1 submission. */
105
+ public getRange(): { fromCheckpoint: CheckpointNumber; toCheckpoint: CheckpointNumber; count: number } {
106
+ return { fromCheckpoint: this.fromCheckpoint, toCheckpoint: this.toCheckpoint, count: this.snapshot.length };
107
+ }
108
+
109
+ public isCancelled(): boolean {
110
+ return this.cancelled;
111
+ }
112
+
113
+ /** Wall-time since construction — used by the owning job for metrics. */
114
+ public elapsedMs(): number {
115
+ return this.executionTimer.ms();
116
+ }
117
+
118
+ /** Kicks off the prove. Returns the result promise (also available as `result.promise`). */
119
+ public start(): Promise<TopTreeProof> {
120
+ void this.run();
121
+ return this.result.promise;
122
+ }
123
+
124
+ /**
125
+ * Cancels the in-flight prove. Idempotent. Rejects the result promise with
126
+ * `TopTreeCancelledError`, then kicks off the underlying orchestrator's teardown
127
+ * in the background so callers don't block on it. The teardown promise is exposed
128
+ * via `whenDone()` — the parent collects the cancelled job and awaits all
129
+ * pending top-tree teardowns at the end of the epoch.
130
+ */
131
+ public cancel(abortJobs = true): void {
132
+ if (this.cancelled) {
133
+ return;
134
+ }
135
+ this.cancelled = true;
136
+ this.deps.log.info(
137
+ `Cancelling TopTreeJob for epoch ${this.epochNumber} (checkpoints ${this.fromCheckpoint}..${this.toCheckpoint})`,
138
+ {
139
+ epochNumber: this.epochNumber,
140
+ fromCheckpoint: this.fromCheckpoint,
141
+ toCheckpoint: this.toCheckpoint,
142
+ elapsedMs: this.executionTimer.ms(),
143
+ },
144
+ );
145
+ this.result.reject(new TopTreeCancelledError());
146
+ // Fire and forget: parent awaits the cancel-driven teardown via whenDone(); the
147
+ // chained .catch swallows rejections so the unawaited promise doesn't surface
148
+ // as an unhandled rejection.
149
+ this.cancelPromise = this.runCancel(abortJobs).catch(() => {});
150
+ }
151
+
152
+ /** Resolves once the cancel-driven teardown of the underlying orchestrator has unwound. */
153
+ public async whenDone(): Promise<void> {
154
+ if (this.cancelPromise) {
155
+ await this.cancelPromise;
156
+ }
157
+ }
158
+
159
+ private async runCancel(abortJobs: boolean): Promise<void> {
160
+ try {
161
+ this.topTree.cancel({ abortJobs });
162
+ } catch (err) {
163
+ this.deps.log.error('Error cancelling top tree', err);
164
+ }
165
+ try {
166
+ await this.topTree.stop();
167
+ } catch (err) {
168
+ this.deps.log.error('Error stopping top tree', err);
169
+ }
170
+ }
171
+
172
+ private async run() {
173
+ try {
174
+ const blobTimer = new Timer();
175
+ const blobFieldsPerCheckpoint = this.snapshot.map(j => j.checkpoint.toBlobFields());
176
+ const finalBlobBatchingChallenges = await buildFinalBlobChallenges(blobFieldsPerCheckpoint);
177
+ this.deps.metrics.recordBlobProcessing(blobTimer.ms());
178
+ this.deps.log.verbose(
179
+ `Built final blob batching challenges for epoch ${this.epochNumber} in ${blobTimer.ms()}ms`,
180
+ {
181
+ epochNumber: this.epochNumber,
182
+ checkpointCount: this.snapshot.length,
183
+ durationMs: blobTimer.ms(),
184
+ },
185
+ );
186
+
187
+ const checkpointData: CheckpointTopTreeData[] = this.snapshot.map(j => ({
188
+ blockProofs: j.whenBlockProofsReady(),
189
+ l2ToL1MsgsPerBlock: j.checkpoint.blocks.map(b => b.body.txEffects.map(tx => tx.l2ToL1Msgs)),
190
+ blobFields: j.checkpoint.toBlobFields(),
191
+ previousBlockHeader: j.previousBlockHeader,
192
+ previousArchiveSiblingPath: j.previousArchiveSiblingPath,
193
+ }));
194
+
195
+ const defaultProve = (): Promise<TopTreeProof> =>
196
+ this.topTree.prove(this.epochNumber, this.snapshot.length, finalBlobBatchingChallenges, checkpointData);
197
+
198
+ await this.deps.hooks?.beforeProve?.();
199
+ const proveTimer = new Timer();
200
+ this.deps.log.info(
201
+ `Starting top-tree prove for epoch ${this.epochNumber} (checkpoints ${this.fromCheckpoint}..${this.toCheckpoint})`,
202
+ {
203
+ epochNumber: this.epochNumber,
204
+ fromCheckpoint: this.fromCheckpoint,
205
+ toCheckpoint: this.toCheckpoint,
206
+ checkpointCount: this.snapshot.length,
207
+ },
208
+ );
209
+ const proof = await (this.deps.hooks?.proveOverride
210
+ ? this.deps.hooks.proveOverride(defaultProve)
211
+ : defaultProve());
212
+ await this.deps.hooks?.afterProve?.();
213
+ this.deps.log.info(`Top-tree prove succeeded for epoch ${this.epochNumber} in ${proveTimer.ms()}ms`, {
214
+ epochNumber: this.epochNumber,
215
+ fromCheckpoint: this.fromCheckpoint,
216
+ toCheckpoint: this.toCheckpoint,
217
+ durationMs: proveTimer.ms(),
218
+ totalElapsedMs: this.executionTimer.ms(),
219
+ });
220
+
221
+ this.result.resolve(proof);
222
+ } catch (err) {
223
+ // Cancel paths surface as TopTreeCancelledError; everything else propagates as-is.
224
+ this.result.reject(err);
225
+ }
226
+ }
227
+ }