@aztec/prover-node 5.0.0-private.20260318 → 5.0.0-rc.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.
Files changed (71) hide show
  1. package/README.md +506 -0
  2. package/dest/actions/download-epoch-proving-job.js +1 -1
  3. package/dest/actions/rerun-epoch-proving-job.d.ts +4 -3
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +103 -21
  6. package/dest/bin/run-failed-epoch.js +1 -3
  7. package/dest/checkpoint-store.d.ts +83 -0
  8. package/dest/checkpoint-store.d.ts.map +1 -0
  9. package/dest/checkpoint-store.js +181 -0
  10. package/dest/config.d.ts +1 -1
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +1 -1
  13. package/dest/factory.d.ts +1 -1
  14. package/dest/factory.d.ts.map +1 -1
  15. package/dest/factory.js +22 -8
  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 +134 -0
  20. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  21. package/dest/job/checkpoint-prover.js +350 -0
  22. package/dest/job/epoch-session.d.ts +146 -0
  23. package/dest/job/epoch-session.d.ts.map +1 -0
  24. package/dest/job/epoch-session.js +709 -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 +29 -5
  29. package/dest/metrics.d.ts.map +1 -1
  30. package/dest/metrics.js +73 -9
  31. package/dest/monitors/epoch-monitor.js +6 -2
  32. package/dest/proof-publishing-service.d.ts +159 -0
  33. package/dest/proof-publishing-service.d.ts.map +1 -0
  34. package/dest/proof-publishing-service.js +334 -0
  35. package/dest/prover-node-publisher.d.ts +18 -11
  36. package/dest/prover-node-publisher.d.ts.map +1 -1
  37. package/dest/prover-node-publisher.js +195 -57
  38. package/dest/prover-node.d.ts +96 -68
  39. package/dest/prover-node.d.ts.map +1 -1
  40. package/dest/prover-node.js +382 -227
  41. package/dest/prover-publisher-factory.d.ts +2 -2
  42. package/dest/prover-publisher-factory.d.ts.map +1 -1
  43. package/dest/prover-publisher-factory.js +3 -3
  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 +452 -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 +114 -28
  52. package/src/bin/run-failed-epoch.ts +1 -2
  53. package/src/checkpoint-store.ts +213 -0
  54. package/src/config.ts +2 -1
  55. package/src/factory.ts +18 -10
  56. package/src/index.ts +1 -0
  57. package/src/job/checkpoint-prover.ts +465 -0
  58. package/src/job/epoch-session.ts +424 -0
  59. package/src/job/top-tree-job.ts +227 -0
  60. package/src/metrics.ts +88 -12
  61. package/src/monitors/epoch-monitor.ts +2 -2
  62. package/src/proof-publishing-service.ts +424 -0
  63. package/src/prover-node-publisher.ts +220 -67
  64. package/src/prover-node.ts +439 -249
  65. package/src/prover-publisher-factory.ts +3 -3
  66. package/src/session-manager.ts +552 -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,709 @@
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
369
+ }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
+ }
373
+ var _dec, _initProto;
374
+ import { BlockNumber } from '@aztec/foundation/branded-types';
375
+ import { createLogger } from '@aztec/foundation/log';
376
+ import { sleep } from '@aztec/foundation/sleep';
377
+ import { Timer } from '@aztec/foundation/timer';
378
+ import { TopTreeCancelledError } from '@aztec/prover-client/orchestrator';
379
+ import { EpochProvingJobTerminalState } from '@aztec/stdlib/interfaces/server';
380
+ import { Attributes, trackSpan } from '@aztec/telemetry-client';
381
+ import * as crypto from 'node:crypto';
382
+ import { TopTreeJob } from './top-tree-job.js';
383
+ /** Stable string key for use in maps. */ export function specKey(spec) {
384
+ return `${spec.kind}:${spec.epochNumber}:${spec.fromSlot}-${spec.toSlot}`;
385
+ }
386
+ _dec = trackSpan('EpochSession.start', function() {
387
+ return {
388
+ [Attributes.EPOCH_NUMBER]: this.spec.epochNumber
389
+ };
390
+ });
391
+ /**
392
+ * One attempt at proving and publishing a contiguous slot range. The `SessionSpec` and
393
+ * the prover set are both frozen at construction time; the session does not adapt to
394
+ * reorgs or extensions of canonical content. Instead, `SessionManager` owns the
395
+ * reconciliation loop and replaces invalidated sessions wholesale (cancel + construct
396
+ * a fresh session with the new prover set).
397
+ *
398
+ * Each session does three things in sequence:
399
+ *
400
+ * 1. Run a `TopTreeJob` over its frozen prover subset to produce the epoch proof.
401
+ * 2. Hand the proof to the shared `ProofPublishingService` as a `PublishCandidate`.
402
+ * 3. Translate the service's outcome into a terminal session state.
403
+ *
404
+ * Everything to do with submission — predecessor gating, same-epoch dedup, deadline
405
+ * enforcement, and the L1 transaction itself — is the publishing service's concern.
406
+ * The session is just the producer of one candidate and the observer of its outcome.
407
+ *
408
+ * Lifecycle (happy path):
409
+ *
410
+ * initialized → awaiting-checkpoints → completed
411
+ *
412
+ * Terminal states map the publishing outcome: `published` → `completed`, `superseded` →
413
+ * `superseded`, `failed` → `failed`, `expired` → `timed-out`, `withdrawn` → `cancelled`.
414
+ * Additionally, the session-level deadline fires `cancel('deadline')` and transitions
415
+ * to `timed-out` for the pre-submit window (top-tree proving) — the publishing service
416
+ * handles the post-submit window via the candidate's `deadline`.
417
+ *
418
+ * `cancel()` is idempotent. It marks the session terminal, calls
419
+ * `publishingService.withdraw(uuid)` to drop any queued candidate (an in-flight publish
420
+ * runs to natural completion; the session has already settled), and tears down the
421
+ * top-tree job if proving is still in progress.
422
+ */ export class EpochSession {
423
+ spec;
424
+ deps;
425
+ static{
426
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
427
+ [
428
+ _dec,
429
+ 2,
430
+ "start"
431
+ ]
432
+ ], []));
433
+ }
434
+ tracer;
435
+ uuid;
436
+ log;
437
+ state;
438
+ deadlineTimeoutHandler;
439
+ topTreeJob;
440
+ /** Cancelled top-tree jobs whose teardown is still in flight. Awaited at session stop. */ pendingTopTreeCleanups;
441
+ completionPromise;
442
+ resolveCompletion;
443
+ /** Stable reference; never mutated after construction. */ checkpoints;
444
+ constructor(spec, checkpoints, deps){
445
+ this.spec = spec;
446
+ this.deps = deps;
447
+ this.state = (_initProto(this), 'initialized');
448
+ this.pendingTopTreeCleanups = [];
449
+ if (checkpoints.length === 0) {
450
+ throw new Error(`Cannot construct EpochSession for ${specKey(spec)}: empty checkpoint set`);
451
+ }
452
+ this.checkpoints = [
453
+ ...checkpoints
454
+ ];
455
+ this.uuid = crypto.randomUUID();
456
+ this.log = createLogger('prover-node:epoch-session', {
457
+ ...deps.bindings,
458
+ instanceId: `session-${spec.kind}-${spec.epochNumber}-${spec.fromSlot}-${spec.toSlot}`
459
+ });
460
+ this.tracer = deps.metrics.tracer;
461
+ this.completionPromise = new Promise((resolve)=>{
462
+ this.resolveCompletion = resolve;
463
+ });
464
+ this.scheduleDeadlineStop();
465
+ this.log.info(`Created EpochSession ${this.uuid}`, {
466
+ uuid: this.uuid,
467
+ ...spec,
468
+ checkpointCount: this.checkpoints.length,
469
+ checkpointIds: this.checkpoints.map((c)=>c.id)
470
+ });
471
+ }
472
+ getId() {
473
+ return this.uuid;
474
+ }
475
+ getSpec() {
476
+ return this.spec;
477
+ }
478
+ getState() {
479
+ return this.state;
480
+ }
481
+ getEpochNumber() {
482
+ return this.spec.epochNumber;
483
+ }
484
+ getKind() {
485
+ return this.spec.kind;
486
+ }
487
+ getDeadline() {
488
+ return this.deps.deadline;
489
+ }
490
+ getCheckpoints() {
491
+ return this.checkpoints;
492
+ }
493
+ /** Resolves when the session reaches a terminal state. */ whenDone() {
494
+ return this.completionPromise;
495
+ }
496
+ /** True if the session is in a terminal state. */ isTerminal() {
497
+ return EpochProvingJobTerminalState.includes(this.state);
498
+ }
499
+ /** First block this session proves. */ getStartBlockNumber() {
500
+ return BlockNumber(this.checkpoints[0].checkpoint.blocks[0].number);
501
+ }
502
+ /** Last block this session proves. */ getEndBlockNumber() {
503
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
504
+ return BlockNumber(lastCheckpoint.checkpoint.blocks[lastCheckpoint.checkpoint.blocks.length - 1].number);
505
+ }
506
+ /**
507
+ * Kicks off proving + submission. Fires and forgets — callers should await `whenDone()`.
508
+ * Returns a promise that resolves to the final state for callers that want to wait inline.
509
+ */ async start() {
510
+ try {
511
+ await this.run();
512
+ } catch (err) {
513
+ this.log.error(`Error in EpochSession ${this.uuid}`, err, {
514
+ uuid: this.uuid,
515
+ ...this.spec
516
+ });
517
+ if (!this.isTerminal()) {
518
+ this.state = 'failed';
519
+ }
520
+ } finally{
521
+ clearTimeout(this.deadlineTimeoutHandler);
522
+ await this.teardownTopTreeIfNeeded();
523
+ this.resolveCompletion(this.state);
524
+ }
525
+ return this.state;
526
+ }
527
+ /**
528
+ * Cancels the session. Idempotent. Withdraws any submitted candidate from the
529
+ * publishing service so the in-flight publisher (if any) is interrupted.
530
+ */ async cancel(reason = 'cancelled') {
531
+ if (this.isTerminal()) {
532
+ return;
533
+ }
534
+ this.log.info(`Cancelling EpochSession ${this.uuid}: ${reason}`, {
535
+ uuid: this.uuid,
536
+ ...this.spec,
537
+ previousState: this.state,
538
+ reason
539
+ });
540
+ this.state = 'cancelled';
541
+ try {
542
+ this.deps.publishingService.withdraw(this.uuid);
543
+ } catch (err) {
544
+ this.log.error(`Error withdrawing candidate from publishing service`, err);
545
+ }
546
+ if (this.topTreeJob && !this.topTreeJob.isCancelled()) {
547
+ const job = this.topTreeJob;
548
+ this.topTreeJob = undefined;
549
+ job.cancel();
550
+ this.pendingTopTreeCleanups.push(job);
551
+ }
552
+ await this.teardownTopTreeIfNeeded();
553
+ this.resolveCompletion(this.state);
554
+ }
555
+ async run() {
556
+ const timer = new Timer();
557
+ if (this.deps.config.finalizationDelayMs && this.deps.config.finalizationDelayMs > 0) {
558
+ this.log.warn(`Waiting ${this.deps.config.finalizationDelayMs}ms before starting top-tree proving`, {
559
+ uuid: this.uuid,
560
+ ...this.spec
561
+ });
562
+ await sleep(this.deps.config.finalizationDelayMs);
563
+ if (this.isTerminal()) {
564
+ return;
565
+ }
566
+ }
567
+ // Stage 1 — top-tree proving.
568
+ const topTreeJob = new TopTreeJob(this.spec.epochNumber, this.checkpoints, {
569
+ proverFactory: this.deps.proverFactory,
570
+ metrics: this.deps.metrics,
571
+ log: this.log,
572
+ hooks: this.toTopTreeHooks()
573
+ });
574
+ this.topTreeJob = topTreeJob;
575
+ const { fromCheckpoint, toCheckpoint, count } = topTreeJob.getRange();
576
+ this.state = 'awaiting-checkpoints';
577
+ let proof;
578
+ try {
579
+ proof = await topTreeJob.start();
580
+ } catch (err) {
581
+ if (err instanceof TopTreeCancelledError) {
582
+ // Session cancel kicked off the underlying teardown; nothing more to do here.
583
+ this.log.info(`Top-tree cancelled for EpochSession ${this.uuid}`, {
584
+ uuid: this.uuid,
585
+ ...this.spec
586
+ });
587
+ return;
588
+ }
589
+ throw err;
590
+ }
591
+ this.topTreeJob = undefined;
592
+ this.log.info(`Top-tree proof ready for EpochSession ${this.uuid}`, {
593
+ uuid: this.uuid,
594
+ ...this.spec,
595
+ fromCheckpoint,
596
+ toCheckpoint,
597
+ durationMs: timer.ms()
598
+ });
599
+ // Stage 2 — hand the proof to the publishing service and wait for its verdict.
600
+ await this.submitProof(proof, fromCheckpoint, toCheckpoint, count, timer);
601
+ }
602
+ async submitProof(proof, fromCheckpoint, toCheckpoint, checkpointCount, timer) {
603
+ // Attestations come from the highest-numbered registered checkpoint — that's the one
604
+ // whose attestations the L1 contract checks for the proven range.
605
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
606
+ const attestations = lastCheckpoint.attestations.map((a)=>a.toViem());
607
+ const epochSizeBlocks = this.checkpoints.reduce((acc, c)=>acc + c.checkpoint.blocks.length, 0);
608
+ const epochSizeTxs = this.checkpoints.reduce((acc, c)=>acc + c.checkpoint.blocks.reduce((bAcc, block)=>bAcc + block.body.txEffects.length, 0), 0);
609
+ const outcome = await this.deps.publishingService.submit({
610
+ id: this.uuid,
611
+ epoch: this.spec.epochNumber,
612
+ kind: this.spec.kind,
613
+ startBlock: this.getStartBlockNumber(),
614
+ endBlock: this.getEndBlockNumber(),
615
+ deadline: this.deps.deadline,
616
+ fromCheckpoint,
617
+ toCheckpoint,
618
+ publicInputs: proof.publicInputs,
619
+ proof: proof.proof,
620
+ batchedBlobInputs: proof.batchedBlobInputs,
621
+ attestations
622
+ });
623
+ if (this.isTerminal()) {
624
+ // cancel() already set the terminal state — don't clobber it.
625
+ return;
626
+ }
627
+ switch(outcome){
628
+ case 'published':
629
+ this.log.info(`Submitted proof for epoch ${this.spec.epochNumber} (checkpoints ${fromCheckpoint}..${toCheckpoint})`, {
630
+ uuid: this.uuid,
631
+ ...this.spec
632
+ });
633
+ this.state = 'completed';
634
+ this.deps.metrics.recordProvingJob(timer.ms(), timer.ms(), checkpointCount, epochSizeBlocks, epochSizeTxs);
635
+ return;
636
+ case 'superseded':
637
+ this.log.info(`EpochSession ${this.uuid} superseded by a longer candidate`, {
638
+ uuid: this.uuid,
639
+ ...this.spec
640
+ });
641
+ this.state = 'superseded';
642
+ return;
643
+ case 'withdrawn':
644
+ // cancel() ran but the terminal-state check above missed it. Defensive: treat as cancelled.
645
+ this.state = 'cancelled';
646
+ return;
647
+ case 'expired':
648
+ this.log.warn(`EpochSession ${this.uuid} expired before publishing`, {
649
+ uuid: this.uuid,
650
+ ...this.spec
651
+ });
652
+ this.state = 'timed-out';
653
+ return;
654
+ case 'failed':
655
+ throw new Error('Failed to submit epoch proof to L1');
656
+ }
657
+ }
658
+ async teardownTopTreeIfNeeded() {
659
+ if (this.topTreeJob) {
660
+ const job = this.topTreeJob;
661
+ this.topTreeJob = undefined;
662
+ job.cancel();
663
+ this.pendingTopTreeCleanups.push(job);
664
+ }
665
+ if (this.pendingTopTreeCleanups.length > 0) {
666
+ await Promise.allSettled(this.pendingTopTreeCleanups.map((j)=>j.whenDone()));
667
+ this.pendingTopTreeCleanups.length = 0;
668
+ }
669
+ }
670
+ scheduleDeadlineStop() {
671
+ const deadline = this.deps.deadline;
672
+ if (!deadline) {
673
+ return;
674
+ }
675
+ const timeout = Math.max(deadline.getTime() - this.deps.dateProvider.now(), 0);
676
+ this.deadlineTimeoutHandler = setTimeout(()=>{
677
+ void this.handleDeadline();
678
+ }, timeout);
679
+ }
680
+ /**
681
+ * Returns a promise that resolves once cancellation has propagated and the state has
682
+ * been flipped from 'cancelled' to 'timed-out'. Protected so unit tests can drive the
683
+ * deadline path without waiting on the real `setTimeout` to fire.
684
+ */ async handleDeadline() {
685
+ if (this.isTerminal()) {
686
+ return;
687
+ }
688
+ this.log.warn(`EpochSession ${this.uuid} hit deadline`, {
689
+ uuid: this.uuid,
690
+ ...this.spec
691
+ });
692
+ await this.cancel('deadline');
693
+ // After cancel, override state if it was the canonical timeout case so observers see 'timed-out'.
694
+ if (this.state === 'cancelled') {
695
+ this.state = 'timed-out';
696
+ }
697
+ }
698
+ toTopTreeHooks() {
699
+ const hooks = this.deps.hooks;
700
+ if (!hooks?.beforeTopTreeProve && !hooks?.afterTopTreeProve && !hooks?.topTreeProveOverride) {
701
+ return undefined;
702
+ }
703
+ return {
704
+ beforeProve: hooks.beforeTopTreeProve,
705
+ afterProve: hooks.afterTopTreeProve,
706
+ proveOverride: hooks.topTreeProveOverride
707
+ };
708
+ }
709
+ }