@aztec/prover-node 0.0.1-commit.993d52e → 0.0.1-commit.9a89641

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 (76) 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 +1 -3
  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 +4 -2
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +10 -3
  15. package/dest/factory.d.ts +4 -1
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +28 -12
  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-session.js +744 -0
  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 +201 -62
  42. package/dest/prover-node.d.ts +134 -67
  43. package/dest/prover-node.d.ts.map +1 -1
  44. package/dest/prover-node.js +539 -218
  45. package/dest/prover-publisher-factory.d.ts +4 -2
  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 +1 -2
  58. package/src/checkpoint-store.ts +212 -0
  59. package/src/config.ts +14 -3
  60. package/src/factory.ts +26 -12
  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 +236 -78
  69. package/src/prover-node.ts +622 -243
  70. package/src/prover-publisher-factory.ts +6 -3
  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/dest/job/epoch-proving-job.js +0 -752
  76. package/src/job/epoch-proving-job.ts +0 -449
@@ -0,0 +1,744 @@
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 → awaiting-root → publishing-proof → completed
411
+ *
412
+ * Terminal states map the publishing outcome: `published` → `completed`, `superseded` →
413
+ * `superseded`, `expired` → `timed-out`, `withdrawn` → `cancelled`. A fault ends the attempt in one
414
+ * of two terminal states depending on its cause: `stopped` if a checkpoint prover under it failed
415
+ * (possibly a prune — the reconciler will rebuild over a fresh prover on re-add), or `failed` if the
416
+ * session's own top-tree/submit work failed while every prover was healthy (a genuine, non-prune
417
+ * failure the reconciler retains and uploads — see `hasFailed()`).
418
+ * Additionally, the session-level deadline fires `cancel('deadline')` and transitions
419
+ * to `timed-out` for the pre-submit window (top-tree proving) — the publishing service
420
+ * handles the post-submit window via the candidate's `deadline`.
421
+ *
422
+ * `cancel()` is idempotent. It marks the session terminal, calls
423
+ * `publishingService.withdraw(uuid)` to drop any queued candidate (an in-flight publish
424
+ * runs to natural completion; the session has already settled), and tears down the
425
+ * top-tree job if proving is still in progress.
426
+ */ export class EpochSession {
427
+ spec;
428
+ deps;
429
+ static{
430
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
431
+ [
432
+ _dec,
433
+ 2,
434
+ "start"
435
+ ]
436
+ ], []));
437
+ }
438
+ tracer;
439
+ uuid;
440
+ log;
441
+ state;
442
+ deadlineTimeoutHandler;
443
+ topTreeJob;
444
+ /** Cancelled top-tree jobs whose teardown is still in flight. Awaited at session stop. */ pendingTopTreeCleanups;
445
+ completionPromise;
446
+ resolveCompletion;
447
+ /** Stable reference; never mutated after construction. */ checkpoints;
448
+ constructor(spec, checkpoints, deps){
449
+ this.spec = spec;
450
+ this.deps = deps;
451
+ this.state = (_initProto(this), 'initialized');
452
+ this.pendingTopTreeCleanups = [];
453
+ if (checkpoints.length === 0) {
454
+ throw new Error(`Cannot construct EpochSession for ${specKey(spec)}: empty checkpoint set`);
455
+ }
456
+ this.checkpoints = [
457
+ ...checkpoints
458
+ ];
459
+ this.uuid = crypto.randomUUID();
460
+ this.log = createLogger('prover-node:epoch-session', {
461
+ ...deps.bindings,
462
+ instanceId: `session-${spec.kind}-${spec.epochNumber}-${spec.fromSlot}-${spec.toSlot}`
463
+ });
464
+ this.tracer = deps.metrics.tracer;
465
+ this.completionPromise = new Promise((resolve)=>{
466
+ this.resolveCompletion = resolve;
467
+ });
468
+ this.scheduleDeadlineStop();
469
+ this.log.info(`Created EpochSession ${this.uuid}`, {
470
+ uuid: this.uuid,
471
+ ...spec,
472
+ checkpointCount: this.checkpoints.length,
473
+ checkpointIds: this.checkpoints.map((c)=>c.id)
474
+ });
475
+ }
476
+ getId() {
477
+ return this.uuid;
478
+ }
479
+ getSpec() {
480
+ return this.spec;
481
+ }
482
+ getState() {
483
+ return this.state;
484
+ }
485
+ getEpochNumber() {
486
+ return this.spec.epochNumber;
487
+ }
488
+ getKind() {
489
+ return this.spec.kind;
490
+ }
491
+ getDeadline() {
492
+ return this.deps.deadline;
493
+ }
494
+ getCheckpoints() {
495
+ return this.checkpoints;
496
+ }
497
+ /** Resolves when the session reaches a terminal state. */ whenDone() {
498
+ return this.completionPromise;
499
+ }
500
+ /** True if the session is in a terminal state. */ isTerminal() {
501
+ return EpochProvingJobTerminalState.includes(this.state);
502
+ }
503
+ /**
504
+ * True if the session ended in its own genuine failure — top-tree proving or L1 submission failed
505
+ * while every checkpoint prover succeeded. Because healthy provers rule out a prune-induced fault,
506
+ * this is a race-free "the epoch could not be proven" signal: the reconciler retains such a (full)
507
+ * session rather than re-proving it, and uploads a post-mortem. A `stopped` session (a checkpoint
508
+ * prover failed under it) is NOT a session failure in this sense.
509
+ */ hasFailed() {
510
+ return this.state === 'failed';
511
+ }
512
+ /** First block this session proves. */ getStartBlockNumber() {
513
+ return BlockNumber(this.checkpoints[0].checkpoint.blocks[0].number);
514
+ }
515
+ /** Last block this session proves. */ getEndBlockNumber() {
516
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
517
+ return BlockNumber(lastCheckpoint.checkpoint.blocks[lastCheckpoint.checkpoint.blocks.length - 1].number);
518
+ }
519
+ /**
520
+ * Kicks off proving + submission. Fires and forgets — callers should await `whenDone()`.
521
+ * Returns a promise that resolves to the final state for callers that want to wait inline.
522
+ */ async start() {
523
+ try {
524
+ await this.run();
525
+ } catch (err) {
526
+ this.log.error(`Error in EpochSession ${this.uuid}`, err, {
527
+ uuid: this.uuid,
528
+ ...this.spec
529
+ });
530
+ // Distinguish the two ways an attempt can fault:
531
+ // - a checkpoint prover in the set has failed OR was cancelled (a sub-tree fault, a prune-induced
532
+ // fork fault, or a control-plane cancel that reached this catch before the reconcile marked the
533
+ // session 'cancelled'): end in the non-declaring terminal 'stopped'. This is not the session's own
534
+ // failure and may be a prune, so the reconciler does not upload it; a re-add installs a fresh prover.
535
+ // - no prover failed or was cancelled, yet top-tree proving or L1 submission failed: this is the
536
+ // session's own, genuine failure — and, because every prover is healthy and un-cancelled, it is
537
+ // definitively NOT a prune. End in terminal 'failed' so the reconciler retains it (no pointless
538
+ // re-prove) and uploads a race-free post-mortem.
539
+ if (!this.isTerminal()) {
540
+ this.state = this.checkpoints.some((c)=>c.isFailed() || c.isCancelled()) ? 'stopped' : 'failed';
541
+ }
542
+ } finally{
543
+ clearTimeout(this.deadlineTimeoutHandler);
544
+ await this.teardownTopTreeIfNeeded();
545
+ this.resolveCompletion(this.state);
546
+ }
547
+ return this.state;
548
+ }
549
+ /**
550
+ * Cancels the session. Idempotent. Withdraws any submitted candidate from the
551
+ * publishing service so the in-flight publisher (if any) is interrupted.
552
+ */ async cancel(reason = 'cancelled', { abortJobs = true } = {}) {
553
+ if (this.isTerminal()) {
554
+ return;
555
+ }
556
+ this.log.info(`Cancelling EpochSession ${this.uuid}: ${reason}`, {
557
+ uuid: this.uuid,
558
+ ...this.spec,
559
+ previousState: this.state,
560
+ reason
561
+ });
562
+ this.state = 'cancelled';
563
+ try {
564
+ this.deps.publishingService.withdraw(this.uuid);
565
+ } catch (err) {
566
+ this.log.error(`Error withdrawing candidate from publishing service`, err);
567
+ }
568
+ if (this.topTreeJob && !this.topTreeJob.isCancelled()) {
569
+ const job = this.topTreeJob;
570
+ this.topTreeJob = undefined;
571
+ // On a clean shutdown we leave the in-flight broker jobs alone so a restart can reuse them;
572
+ // other cancellations (reorg, supersede, deadline) abort them since their inputs are stale.
573
+ job.cancel(abortJobs);
574
+ this.pendingTopTreeCleanups.push(job);
575
+ }
576
+ await this.teardownTopTreeIfNeeded();
577
+ this.resolveCompletion(this.state);
578
+ }
579
+ async run() {
580
+ const timer = new Timer();
581
+ if (this.deps.config.finalizationDelayMs && this.deps.config.finalizationDelayMs > 0) {
582
+ this.log.warn(`Waiting ${this.deps.config.finalizationDelayMs}ms before starting top-tree proving`, {
583
+ uuid: this.uuid,
584
+ ...this.spec
585
+ });
586
+ await sleep(this.deps.config.finalizationDelayMs);
587
+ if (this.isTerminal()) {
588
+ return;
589
+ }
590
+ }
591
+ // Stage 1 — top-tree proving.
592
+ const topTreeJob = new TopTreeJob(this.spec.epochNumber, this.checkpoints, {
593
+ proverFactory: this.deps.proverFactory,
594
+ metrics: this.deps.metrics,
595
+ log: this.log,
596
+ hooks: this.toTopTreeHooks()
597
+ });
598
+ this.topTreeJob = topTreeJob;
599
+ const { fromCheckpoint, toCheckpoint, count } = topTreeJob.getRange();
600
+ this.state = 'awaiting-checkpoints';
601
+ let proof;
602
+ try {
603
+ proof = await topTreeJob.start();
604
+ } catch (err) {
605
+ if (err instanceof TopTreeCancelledError) {
606
+ // Session cancel kicked off the underlying teardown; nothing more to do here.
607
+ this.log.info(`Top-tree cancelled for EpochSession ${this.uuid}`, {
608
+ uuid: this.uuid,
609
+ ...this.spec
610
+ });
611
+ return;
612
+ }
613
+ throw err;
614
+ }
615
+ this.topTreeJob = undefined;
616
+ this.log.info(`Top-tree proof ready for EpochSession ${this.uuid}`, {
617
+ uuid: this.uuid,
618
+ ...this.spec,
619
+ fromCheckpoint,
620
+ toCheckpoint,
621
+ durationMs: timer.ms()
622
+ });
623
+ // Stage 2 — hand the proof to the publishing service and wait for its verdict.
624
+ await this.submitProof(proof, fromCheckpoint, toCheckpoint, count, timer);
625
+ }
626
+ async submitProof(proof, fromCheckpoint, toCheckpoint, checkpointCount, timer) {
627
+ // Attestations come from the highest-numbered registered checkpoint — that's the one
628
+ // whose attestations the L1 contract checks for the proven range.
629
+ const lastCheckpoint = this.checkpoints[this.checkpoints.length - 1];
630
+ const attestations = lastCheckpoint.attestations.map((a)=>a.toViem());
631
+ const epochSizeBlocks = this.checkpoints.reduce((acc, c)=>acc + c.checkpoint.blocks.length, 0);
632
+ const epochSizeTxs = this.checkpoints.reduce((acc, c)=>acc + c.checkpoint.blocks.reduce((bAcc, block)=>bAcc + block.body.txEffects.length, 0), 0);
633
+ // Reflect the publish phase. Guard against a terminal state set concurrently by cancel() — the
634
+ // post-submit isTerminal() check below relies on cancel still winning.
635
+ if (!this.isTerminal()) {
636
+ this.state = 'publishing-proof';
637
+ }
638
+ const outcome = await this.deps.publishingService.submit({
639
+ id: this.uuid,
640
+ epoch: this.spec.epochNumber,
641
+ kind: this.spec.kind,
642
+ startBlock: this.getStartBlockNumber(),
643
+ endBlock: this.getEndBlockNumber(),
644
+ deadline: this.deps.deadline,
645
+ fromCheckpoint,
646
+ toCheckpoint,
647
+ publicInputs: proof.publicInputs,
648
+ proof: proof.proof,
649
+ batchedBlobInputs: proof.batchedBlobInputs,
650
+ attestations,
651
+ headers: this.checkpoints.map((c)=>c.checkpoint.header)
652
+ });
653
+ if (this.isTerminal()) {
654
+ // cancel() already set the terminal state — don't clobber it.
655
+ return;
656
+ }
657
+ switch(outcome){
658
+ case 'published':
659
+ this.log.info(`Submitted proof for epoch ${this.spec.epochNumber} (checkpoints ${fromCheckpoint}..${toCheckpoint})`, {
660
+ uuid: this.uuid,
661
+ ...this.spec
662
+ });
663
+ this.state = 'completed';
664
+ this.deps.metrics.recordProvingJob(timer.ms(), checkpointCount, epochSizeBlocks, epochSizeTxs);
665
+ return;
666
+ case 'superseded':
667
+ this.log.info(`EpochSession ${this.uuid} superseded by a longer candidate`, {
668
+ uuid: this.uuid,
669
+ ...this.spec
670
+ });
671
+ this.state = 'superseded';
672
+ return;
673
+ case 'withdrawn':
674
+ // cancel() ran but the terminal-state check above missed it. Defensive: treat as cancelled.
675
+ this.state = 'cancelled';
676
+ return;
677
+ case 'expired':
678
+ this.log.warn(`EpochSession ${this.uuid} expired before publishing`, {
679
+ uuid: this.uuid,
680
+ ...this.spec
681
+ });
682
+ this.state = 'timed-out';
683
+ return;
684
+ case 'failed':
685
+ throw new Error('Failed to submit epoch proof to L1');
686
+ }
687
+ }
688
+ async teardownTopTreeIfNeeded() {
689
+ if (this.topTreeJob) {
690
+ const job = this.topTreeJob;
691
+ this.topTreeJob = undefined;
692
+ job.cancel();
693
+ this.pendingTopTreeCleanups.push(job);
694
+ }
695
+ if (this.pendingTopTreeCleanups.length > 0) {
696
+ await Promise.allSettled(this.pendingTopTreeCleanups.map((j)=>j.whenDone()));
697
+ this.pendingTopTreeCleanups.length = 0;
698
+ }
699
+ }
700
+ scheduleDeadlineStop() {
701
+ const deadline = this.deps.deadline;
702
+ if (!deadline) {
703
+ return;
704
+ }
705
+ const timeout = Math.max(deadline.getTime() - this.deps.dateProvider.now(), 0);
706
+ this.deadlineTimeoutHandler = setTimeout(()=>{
707
+ void this.handleDeadline();
708
+ }, timeout);
709
+ }
710
+ /**
711
+ * Returns a promise that resolves once cancellation has propagated and the state has
712
+ * been flipped from 'cancelled' to 'timed-out'. Protected so unit tests can drive the
713
+ * deadline path without waiting on the real `setTimeout` to fire.
714
+ */ async handleDeadline() {
715
+ if (this.isTerminal()) {
716
+ return;
717
+ }
718
+ this.log.warn(`EpochSession ${this.uuid} hit deadline`, {
719
+ uuid: this.uuid,
720
+ ...this.spec
721
+ });
722
+ await this.cancel('deadline');
723
+ // After cancel, override state if it was the canonical timeout case so observers see 'timed-out'.
724
+ if (this.state === 'cancelled') {
725
+ this.state = 'timed-out';
726
+ }
727
+ }
728
+ toTopTreeHooks() {
729
+ const hooks = this.deps.hooks;
730
+ return {
731
+ // `beforeProve` fires once the sub-tree (checkpoint block) proofs are ready and the root prove is
732
+ // about to start — the boundary between `awaiting-checkpoints` and proving the top tree. Don't
733
+ // clobber a terminal state set concurrently by cancel().
734
+ beforeProve: async ()=>{
735
+ if (!this.isTerminal()) {
736
+ this.state = 'awaiting-root';
737
+ }
738
+ await hooks?.beforeTopTreeProve?.();
739
+ },
740
+ afterProve: hooks?.afterTopTreeProve,
741
+ proveOverride: hooks?.topTreeProveOverride
742
+ };
743
+ }
744
+ }