@aztec/prover-client 0.0.1-commit.a072138 → 0.0.1-commit.a5db02d

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 (129) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +16 -2
  4. package/dest/light/lightweight_checkpoint_builder.d.ts +10 -5
  5. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  6. package/dest/light/lightweight_checkpoint_builder.js +56 -23
  7. package/dest/mocks/test_context.d.ts +11 -11
  8. package/dest/mocks/test_context.d.ts.map +1 -1
  9. package/dest/mocks/test_context.js +30 -30
  10. package/dest/orchestrator/block-building-helpers.d.ts +4 -4
  11. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -1
  12. package/dest/orchestrator/block-building-helpers.js +2 -2
  13. package/dest/orchestrator/block-proving-state.d.ts +4 -1
  14. package/dest/orchestrator/block-proving-state.d.ts.map +1 -1
  15. package/dest/orchestrator/block-proving-state.js +7 -0
  16. package/dest/orchestrator/checkpoint-proving-state.d.ts +20 -36
  17. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  18. package/dest/orchestrator/checkpoint-proving-state.js +22 -120
  19. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +161 -0
  20. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  21. package/dest/orchestrator/{orchestrator.js → checkpoint-sub-tree-orchestrator.js} +285 -462
  22. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  23. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  24. package/dest/orchestrator/chonk-cache.js +80 -0
  25. package/dest/orchestrator/index.d.ts +4 -2
  26. package/dest/orchestrator/index.d.ts.map +1 -1
  27. package/dest/orchestrator/index.js +3 -1
  28. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  29. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  30. package/dest/orchestrator/proving-scheduler.js +120 -0
  31. package/dest/orchestrator/top-tree-orchestrator.d.ts +88 -0
  32. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  33. package/dest/orchestrator/top-tree-orchestrator.js +232 -0
  34. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  35. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  36. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  37. package/dest/orchestrator/tx-proving-state.d.ts +3 -3
  38. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -1
  39. package/dest/prover-client/prover-client.d.ts +64 -7
  40. package/dest/prover-client/prover-client.d.ts.map +1 -1
  41. package/dest/prover-client/prover-client.js +62 -13
  42. package/dest/proving_broker/broker_prover_facade.d.ts +3 -3
  43. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  44. package/dest/proving_broker/broker_prover_facade.js +18 -19
  45. package/dest/proving_broker/config.d.ts +11 -67
  46. package/dest/proving_broker/config.d.ts.map +1 -1
  47. package/dest/proving_broker/config.js +16 -5
  48. package/dest/proving_broker/index.d.ts +2 -1
  49. package/dest/proving_broker/index.d.ts.map +1 -1
  50. package/dest/proving_broker/index.js +1 -0
  51. package/dest/proving_broker/proof_store/factory.d.ts +2 -5
  52. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -1
  53. package/dest/proving_broker/proof_store/factory.js +7 -30
  54. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  55. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  56. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  57. package/dest/proving_broker/proof_store/index.d.ts +2 -2
  58. package/dest/proving_broker/proof_store/index.d.ts.map +1 -1
  59. package/dest/proving_broker/proof_store/index.js +1 -1
  60. package/dest/proving_broker/proving_broker.d.ts +8 -5
  61. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  62. package/dest/proving_broker/proving_broker.js +119 -19
  63. package/dest/proving_broker/proving_broker_database/memory.d.ts +3 -1
  64. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -1
  65. package/dest/proving_broker/proving_broker_database/memory.js +10 -0
  66. package/dest/proving_broker/proving_broker_database/persisted.d.ts +13 -2
  67. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -1
  68. package/dest/proving_broker/proving_broker_database/persisted.js +32 -5
  69. package/dest/proving_broker/proving_broker_database.d.ts +15 -1
  70. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -1
  71. package/dest/proving_broker/proving_broker_instrumentation.d.ts +3 -1
  72. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -1
  73. package/dest/proving_broker/proving_broker_instrumentation.js +7 -0
  74. package/dest/proving_broker/rpc.d.ts +6 -2
  75. package/dest/proving_broker/rpc.d.ts.map +1 -1
  76. package/dest/proving_broker/rpc.js +87 -23
  77. package/dest/test/epoch_settlement.d.ts +36 -0
  78. package/dest/test/epoch_settlement.d.ts.map +1 -0
  79. package/dest/test/epoch_settlement.js +52 -0
  80. package/dest/test/index.d.ts +2 -0
  81. package/dest/test/index.d.ts.map +1 -0
  82. package/dest/test/index.js +1 -0
  83. package/dest/test/mock_prover.d.ts +4 -4
  84. package/dest/test/mock_prover.js +2 -2
  85. package/package.json +20 -20
  86. package/src/config.ts +18 -2
  87. package/src/light/lightweight_checkpoint_builder.ts +58 -25
  88. package/src/mocks/test_context.ts +26 -43
  89. package/src/orchestrator/block-building-helpers.ts +2 -2
  90. package/src/orchestrator/block-proving-state.ts +9 -0
  91. package/src/orchestrator/checkpoint-proving-state.ts +21 -162
  92. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +1044 -0
  93. package/src/orchestrator/chonk-cache.ts +99 -0
  94. package/src/orchestrator/index.ts +8 -1
  95. package/src/orchestrator/proving-scheduler.ts +160 -0
  96. package/src/orchestrator/top-tree-orchestrator.ts +384 -0
  97. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  98. package/src/orchestrator/tx-proving-state.ts +3 -3
  99. package/src/prover-client/prover-client.ts +134 -25
  100. package/src/proving_broker/broker_prover_facade.ts +21 -22
  101. package/src/proving_broker/config.ts +16 -2
  102. package/src/proving_broker/index.ts +1 -0
  103. package/src/proving_broker/proof_store/factory.ts +10 -32
  104. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  105. package/src/proving_broker/proof_store/index.ts +1 -1
  106. package/src/proving_broker/proving_broker.ts +113 -17
  107. package/src/proving_broker/proving_broker_database/memory.ts +10 -0
  108. package/src/proving_broker/proving_broker_database/persisted.ts +42 -7
  109. package/src/proving_broker/proving_broker_database.ts +16 -0
  110. package/src/proving_broker/proving_broker_instrumentation.ts +9 -0
  111. package/src/proving_broker/rpc.ts +46 -20
  112. package/src/test/epoch_settlement.ts +82 -0
  113. package/src/test/index.ts +1 -0
  114. package/src/test/mock_prover.ts +2 -2
  115. package/dest/orchestrator/epoch-proving-state.d.ts +0 -75
  116. package/dest/orchestrator/epoch-proving-state.d.ts.map +0 -1
  117. package/dest/orchestrator/epoch-proving-state.js +0 -267
  118. package/dest/orchestrator/orchestrator.d.ts +0 -128
  119. package/dest/orchestrator/orchestrator.d.ts.map +0 -1
  120. package/dest/prover-client/server-epoch-prover.d.ts +0 -32
  121. package/dest/prover-client/server-epoch-prover.d.ts.map +0 -1
  122. package/dest/prover-client/server-epoch-prover.js +0 -40
  123. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts +0 -14
  124. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts.map +0 -1
  125. package/dest/proving_broker/proof_store/gcs_proof_store.js +0 -52
  126. package/src/orchestrator/epoch-proving-state.ts +0 -378
  127. package/src/orchestrator/orchestrator.ts +0 -1281
  128. package/src/prover-client/server-epoch-prover.ts +0 -69
  129. package/src/proving_broker/proof_store/gcs_proof_store.ts +0 -76
@@ -0,0 +1,78 @@
1
+ import { jsonParseWithSchema, jsonStringify } from '@aztec/foundation/json-rpc';
2
+ import type { FileStore } from '@aztec/stdlib/file-store';
3
+ import {
4
+ type ProofUri,
5
+ type ProvingJobId,
6
+ type ProvingJobInputs,
7
+ type ProvingJobInputsMap,
8
+ ProvingJobResult,
9
+ type ProvingJobResultsMap,
10
+ getProvingJobInputClassFor,
11
+ } from '@aztec/stdlib/interfaces/server';
12
+ import { ProvingRequestType } from '@aztec/stdlib/proofs';
13
+
14
+ import type { ProofStore } from './proof_store.js';
15
+
16
+ const INPUTS_PATH = 'inputs';
17
+ const OUTPUTS_PATH = 'outputs';
18
+
19
+ /**
20
+ * A proof store implementation backed by a generic FileStore.
21
+ * Supports any storage backend (GCS, S3, local filesystem) via the FileStore abstraction.
22
+ */
23
+ export class FileStoreProofStore implements ProofStore {
24
+ constructor(private readonly fileStore: FileStore) {}
25
+
26
+ async saveProofInput<T extends ProvingRequestType>(
27
+ id: ProvingJobId,
28
+ type: T,
29
+ inputs: ProvingJobInputsMap[T],
30
+ ): Promise<ProofUri> {
31
+ const path = `${INPUTS_PATH}/${ProvingRequestType[type]}/${id}`;
32
+ const uri = await this.fileStore.save(path, inputs.toBuffer());
33
+ return uri as ProofUri;
34
+ }
35
+
36
+ async saveProofOutput<T extends ProvingRequestType>(
37
+ id: ProvingJobId,
38
+ type: T,
39
+ result: ProvingJobResultsMap[T],
40
+ ): Promise<ProofUri> {
41
+ const jobResult = { type, result } as ProvingJobResult;
42
+ const json = jsonStringify(jobResult);
43
+ const path = `${OUTPUTS_PATH}/${ProvingRequestType[type]}/${id}.json`;
44
+ const uri = await this.fileStore.save(path, Buffer.from(json, 'utf-8'));
45
+ return uri as ProofUri;
46
+ }
47
+
48
+ async getProofInput(uri: ProofUri): Promise<ProvingJobInputs> {
49
+ try {
50
+ const buffer = await this.fileStore.read(uri);
51
+ const type = this.extractTypeFromUri(uri);
52
+ const inputs = getProvingJobInputClassFor(type).fromBuffer(buffer);
53
+ return { inputs, type } as ProvingJobInputs;
54
+ } catch (err) {
55
+ throw new Error(`Error getting proof input at ${uri}: ${err}`);
56
+ }
57
+ }
58
+
59
+ async getProofOutput(uri: ProofUri): Promise<ProvingJobResult> {
60
+ try {
61
+ const buffer = await this.fileStore.read(uri);
62
+ return jsonParseWithSchema(buffer.toString('utf-8'), ProvingJobResult);
63
+ } catch (err) {
64
+ throw new Error(`Error getting proof output at ${uri}: ${err}`);
65
+ }
66
+ }
67
+
68
+ private extractTypeFromUri(uri: string): ProvingRequestType {
69
+ const url = new URL(uri);
70
+ const pathParts = url.pathname.split('/').filter(Boolean);
71
+ const typeString = pathParts.at(-2);
72
+ const type = typeString ? ProvingRequestType[typeString as keyof typeof ProvingRequestType] : undefined;
73
+ if (type === undefined) {
74
+ throw new Error(`Unrecognized proof type ${typeString} in URI ${uri}`);
75
+ }
76
+ return type;
77
+ }
78
+ }
@@ -1,4 +1,4 @@
1
1
  export * from './proof_store.js';
2
2
  export * from './inline_proof_store.js';
3
3
  export * from './factory.js';
4
- export * from './gcs_proof_store.js';
4
+ export * from './file_store_proof_store.js';
@@ -7,6 +7,7 @@ import {
7
7
  type GetProvingJobResponse,
8
8
  type ProofUri,
9
9
  type ProvingJob,
10
+ type ProvingJobBrokerDebug,
10
11
  type ProvingJobConsumer,
11
12
  type ProvingJobFilter,
12
13
  type ProvingJobId,
@@ -36,7 +37,7 @@ type EnqueuedProvingJob = Pick<ProvingJob, 'id' | 'epochNumber'>;
36
37
  * A broker that manages proof requests and distributes them to workers based on their priority.
37
38
  * It takes a backend that is responsible for storing and retrieving proof requests and results.
38
39
  */
39
- export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Traceable {
40
+ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, ProvingJobBrokerDebug, Traceable {
40
41
  private queues: ProvingQueues = {
41
42
  [ProvingRequestType.PUBLIC_VM]: new PriorityMemoryQueue<EnqueuedProvingJob>(provingJobComparator),
42
43
  [ProvingRequestType.PUBLIC_CHONK_VERIFIER]: new PriorityMemoryQueue<EnqueuedProvingJob>(provingJobComparator),
@@ -114,6 +115,8 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
114
115
 
115
116
  private started = false;
116
117
 
118
+ private debugReplayEnabled: boolean;
119
+
117
120
  public constructor(
118
121
  private database: ProvingBrokerDatabase,
119
122
  {
@@ -121,6 +124,7 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
121
124
  proverBrokerPollIntervalMs,
122
125
  proverBrokerJobMaxRetries,
123
126
  proverBrokerMaxEpochsToKeepResultsFor,
127
+ proverBrokerDebugReplayEnabled,
124
128
  }: Required<
125
129
  Pick<
126
130
  ProverBrokerConfig,
@@ -128,6 +132,7 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
128
132
  | 'proverBrokerPollIntervalMs'
129
133
  | 'proverBrokerJobMaxRetries'
130
134
  | 'proverBrokerMaxEpochsToKeepResultsFor'
135
+ | 'proverBrokerDebugReplayEnabled'
131
136
  >
132
137
  > = defaultProverBrokerConfig,
133
138
  client: TelemetryClient = getTelemetryClient(),
@@ -139,6 +144,7 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
139
144
  this.jobTimeoutMs = proverBrokerJobTimeoutMs!;
140
145
  this.maxRetries = proverBrokerJobMaxRetries!;
141
146
  this.maxEpochsToKeepResultsFor = proverBrokerMaxEpochsToKeepResultsFor!;
147
+ this.debugReplayEnabled = proverBrokerDebugReplayEnabled ?? false;
142
148
  }
143
149
 
144
150
  private measureQueueDepth: MonitorCallback = (type: ProvingRequestType) => {
@@ -241,17 +247,65 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
241
247
  return Promise.resolve(this.#reportProvingJobProgress(id, startedAt, filter));
242
248
  }
243
249
 
250
+ public async replayProvingJob(
251
+ jobId: ProvingJobId,
252
+ type: ProvingRequestType,
253
+ epochNumber: EpochNumber,
254
+ inputsUri: ProofUri,
255
+ ): Promise<ProvingJobStatus> {
256
+ if (!this.debugReplayEnabled) {
257
+ throw new Error('Debug replay not enabled. Set PROVER_BROKER_DEBUG_REPLAY_ENABLED=true');
258
+ }
259
+
260
+ this.logger.info(`Replaying proving job`, { provingJobId: jobId, epochNumber, inputsUri });
261
+
262
+ // Clear existing state and enqueue
263
+ this.cleanUpProvingJobState([jobId]);
264
+
265
+ const job: ProvingJob = { id: jobId, type, epochNumber, inputsUri };
266
+ this.jobsCache.set(jobId, job);
267
+ await this.database.addProvingJob(job);
268
+ this.enqueueJobInternal(job);
269
+
270
+ return { status: 'in-queue' };
271
+ }
272
+
244
273
  async #enqueueProvingJob(job: ProvingJob): Promise<ProvingJobStatus> {
245
274
  // We return the job status at the start of this call
246
- const jobStatus = this.#getProvingJobStatus(job.id);
275
+ let jobStatus = this.#getProvingJobStatus(job.id);
247
276
  if (this.jobsCache.has(job.id)) {
248
277
  const existing = this.jobsCache.get(job.id);
249
278
  assert.deepStrictEqual(job, existing, 'Duplicate proving job ID');
250
- this.logger.warn(`Cached proving job id=${job.id} epochNumber=${job.epochNumber}. Not enqueuing again`, {
251
- provingJobId: job.id,
252
- });
253
- this.instrumentation.incCachedJobs(job.type);
254
- return jobStatus;
279
+
280
+ if (this.resultsCache.get(job.id)?.status === 'aborted') {
281
+ // The producer is re-requesting a job it previously cancelled: revive it rather than
282
+ // returning the cached abort, clearing the aborted state in memory and in the database so the
283
+ // revival survives a restart.
284
+ //
285
+ // Concurrency model: `jobsCache` is the enqueue lock. Every path that puts a job on the queue
286
+ // populates `jobsCache` *synchronously, before its first await* (see the "New proving job"
287
+ // block below), so a second concurrent enqueue of the same id observes the entry at the top
288
+ // of this method and takes a cached, no-op branch instead of enqueuing a duplicate. The revive
289
+ // must keep holding that lock: we tear down the settled state and re-set `jobsCache` in a
290
+ // single synchronous span (no await in between), and only then await the database. Because a
291
+ // concurrent re-request can only interleave at that await — by which point `jobsCache` is
292
+ // populated again and the aborted result is gone — it falls into the cached branch and no-ops,
293
+ // so the job is enqueued exactly once. (`cleanUpProvingJobState` also drops the promise, which
294
+ // was resolved with the abort, so `enqueueJobInternal` below mints a fresh one for the retry.)
295
+ this.logger.info(`Reviving aborted proving job id=${job.id} epochNumber=${job.epochNumber}`, {
296
+ provingJobId: job.id,
297
+ });
298
+ this.cleanUpProvingJobState([job.id]);
299
+ this.jobsCache.set(job.id, job);
300
+ await this.database.deleteProvingJobResult(job.id);
301
+ jobStatus = this.#getProvingJobStatus(job.id);
302
+ } else {
303
+ this.logger.warn(`Cached proving job id=${job.id} epochNumber=${job.epochNumber}. Not enqueuing again`, {
304
+ provingJobId: job.id,
305
+ });
306
+ this.instrumentation.incCachedJobs(job.type);
307
+ return jobStatus;
308
+ }
255
309
  }
256
310
 
257
311
  if (this.isJobStale(job)) {
@@ -277,27 +331,53 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
277
331
  }
278
332
 
279
333
  async #cancelProvingJob(id: ProvingJobId): Promise<void> {
280
- if (!this.jobsCache.has(id)) {
334
+ const job = this.jobsCache.get(id);
335
+ if (!job) {
281
336
  this.logger.warn(`Can't cancel a job that doesn't exist id=${id}`, { provingJobId: id });
282
337
  return;
283
338
  }
284
339
 
285
- // notify listeners of the cancellation
286
- if (!this.resultsCache.has(id)) {
287
- this.logger.info(`Cancelling job id=${id}`, { provingJobId: id });
288
- await this.#reportProvingJobError(id, 'Aborted', false);
340
+ // Leave jobs that have already settled (completed or failed) alone: those results are terminal.
341
+ if (this.resultsCache.has(id)) {
342
+ return;
343
+ }
344
+
345
+ this.logger.info(`Cancelling job id=${id}`, { provingJobId: id });
346
+ this.inProgress.delete(id);
347
+
348
+ // Record the cancellation as its own settled state and persist it, so it survives a restart and
349
+ // notifies the current waiter. Unlike a completion or failure this is not terminal: re-enqueuing
350
+ // the same job id revives it (see #enqueueProvingJob), so the abort never permanently blocks the
351
+ // proof.
352
+ const result: ProvingJobSettledResult = { status: 'aborted' };
353
+ this.resultsCache.set(id, result);
354
+ this.promises.get(id)?.resolve(result);
355
+ this.completedJobNotifications.push(id);
356
+ this.instrumentation.incAbortedJobs(job.type);
357
+
358
+ try {
359
+ await this.database.setProvingJobAborted(id);
360
+ } catch (saveErr) {
361
+ this.logger.error(`Failed to save proving job aborted status id=${id}`, saveErr, { provingJobId: id });
362
+ throw saveErr;
289
363
  }
290
364
  }
291
365
 
292
366
  private cleanUpProvingJobState(ids: ProvingJobId[]) {
367
+ const idsToClean = new Set(ids);
293
368
  for (const id of ids) {
294
369
  this.jobsCache.delete(id);
370
+ const deferred = this.promises.get(id);
371
+ if (deferred) {
372
+ deferred.resolve({ status: 'rejected', reason: 'Proving job cleaned up' });
373
+ }
295
374
  this.promises.delete(id);
296
375
  this.resultsCache.delete(id);
297
376
  this.inProgress.delete(id);
298
377
  this.retries.delete(id);
299
378
  this.enqueuedAt.delete(id);
300
379
  }
380
+ this.completedJobNotifications = this.completedJobNotifications.filter(id => !idsToClean.has(id));
301
381
  }
302
382
 
303
383
  #getProvingJobStatus(id: ProvingJobId): ProvingJobStatus {
@@ -560,21 +640,21 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
560
640
  }
561
641
 
562
642
  private async cleanupPass() {
563
- this.cleanupStaleJobs();
564
643
  this.reEnqueueExpiredJobs();
565
644
  const oldestEpochToKeep = this.oldestEpochToKeep();
566
645
  if (oldestEpochToKeep > 0) {
646
+ this.cleanupJobsOlderThanEpoch(EpochNumber(oldestEpochToKeep));
567
647
  await this.database.deleteAllProvingJobsOlderThanEpoch(EpochNumber(oldestEpochToKeep));
568
648
  this.logger.trace(`Deleted all epochs older than ${oldestEpochToKeep}`);
569
649
  }
570
650
  }
571
651
 
572
- private cleanupStaleJobs() {
652
+ private cleanupJobsOlderThanEpoch(epochNumber: EpochNumber) {
573
653
  const jobIds = Array.from(this.jobsCache.keys());
574
654
  const jobsToClean: ProvingJobId[] = [];
575
655
  for (const id of jobIds) {
576
656
  const job = this.jobsCache.get(id)!;
577
- if (this.isJobStale(job)) {
657
+ if (job.epochNumber < epochNumber) {
578
658
  jobsToClean.push(id);
579
659
  }
580
660
  }
@@ -598,10 +678,26 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Tr
598
678
  const now = this.msTimeSource();
599
679
  const msSinceLastUpdate = now - metadata.lastUpdatedAt;
600
680
  if (msSinceLastUpdate >= this.jobTimeoutMs) {
601
- this.logger.warn(`Proving job id=${id} timed out. Adding it back to the queue.`, { provingJobId: id });
602
681
  this.inProgress.delete(id);
603
- this.enqueueJobInternal(item);
604
682
  this.instrumentation.incTimedOutJobs(item.type);
683
+
684
+ const retries = this.retries.get(id) ?? 0;
685
+ if (retries + 1 < this.maxRetries && !this.isJobStale(item)) {
686
+ this.logger.warn(`Proving job id=${id} timed out. Re-enqueueing (retry ${retries + 1}/${this.maxRetries}).`, {
687
+ provingJobId: id,
688
+ });
689
+ this.retries.set(id, retries + 1);
690
+ this.enqueueJobInternal(item);
691
+ } else {
692
+ this.logger.error(`Proving job id=${id} timed out after ${retries + 1} attempts. Marking as failed.`, {
693
+ provingJobId: id,
694
+ });
695
+ const result: ProvingJobSettledResult = { status: 'rejected', reason: 'Timed out' };
696
+ this.resultsCache.set(id, result);
697
+ this.promises.get(id)?.resolve(result);
698
+ this.completedJobNotifications.push(id);
699
+ this.instrumentation.incRejectedJobs(item.type);
700
+ }
605
701
  }
606
702
  }
607
703
  }
@@ -36,6 +36,16 @@ export class InMemoryBrokerDatabase implements ProvingBrokerDatabase {
36
36
  return Promise.resolve();
37
37
  }
38
38
 
39
+ setProvingJobAborted(id: ProvingJobId): Promise<void> {
40
+ this.results.set(id, { status: 'aborted' });
41
+ return Promise.resolve();
42
+ }
43
+
44
+ deleteProvingJobResult(id: ProvingJobId): Promise<void> {
45
+ this.results.delete(id);
46
+ return Promise.resolve();
47
+ }
48
+
39
49
  deleteProvingJobs(ids: ProvingJobId[]): Promise<void> {
40
50
  for (const id of ids) {
41
51
  this.jobs.delete(id);
@@ -41,7 +41,11 @@ class SingleEpochDatabase {
41
41
  return this.store.estimateSize();
42
42
  }
43
43
 
44
- async batchWrite(jobs: ProvingJob[], results: Array<[ProvingJobId, ProvingJobSettledResult]>) {
44
+ async batchWrite(
45
+ jobs: ProvingJob[],
46
+ results: Array<[ProvingJobId, ProvingJobSettledResult]>,
47
+ deletedResults: ProvingJobId[] = [],
48
+ ) {
45
49
  await this.store.transactionAsync(async () => {
46
50
  for (const job of jobs) {
47
51
  await this.jobs.set(job.id, jsonStringify(job));
@@ -49,6 +53,11 @@ class SingleEpochDatabase {
49
53
  for (const [id, result] of results) {
50
54
  await this.jobResults.set(id, jsonStringify(result));
51
55
  }
56
+ // Deletes are applied after sets so that, if a set and a delete for the same id land in one
57
+ // batch (e.g. an abort immediately followed by a revive's result-delete), the delete wins.
58
+ for (const id of deletedResults) {
59
+ await this.jobResults.delete(id);
60
+ }
52
61
  });
53
62
  }
54
63
 
@@ -66,6 +75,11 @@ class SingleEpochDatabase {
66
75
  await this.jobResults.set(id, jsonStringify(result));
67
76
  }
68
77
 
78
+ async setProvingJobAborted(id: ProvingJobId): Promise<void> {
79
+ const result: ProvingJobSettledResult = { status: 'aborted' };
80
+ await this.jobResults.set(id, jsonStringify(result));
81
+ }
82
+
69
83
  async setProvingJobResult(id: ProvingJobId, value: ProofUri): Promise<void> {
70
84
  const result: ProvingJobSettledResult = { status: 'fulfilled', value };
71
85
  await this.jobResults.set(id, jsonStringify(result));
@@ -80,10 +94,19 @@ class SingleEpochDatabase {
80
94
  }
81
95
  }
82
96
 
97
+ /**
98
+ * An item queued for a batched write. A {@link ProvingJob} adds/updates a job; a `[id, result]`
99
+ * tuple sets a job's settled result; a `[id, undefined]` tuple deletes a job's result. Deletes ride
100
+ * the same queue as writes so they stay FIFO-ordered against them: a revive's result-delete must
101
+ * land after the abort that preceded it, otherwise a still-queued abort could flush later and
102
+ * resurrect the cancelled state on disk.
103
+ */
104
+ type BrokerWrite = ProvingJob | [ProvingJobId, ProvingJobSettledResult | undefined];
105
+
83
106
  export class KVBrokerDatabase implements ProvingBrokerDatabase {
84
107
  private metrics: LmdbMetrics;
85
108
 
86
- private batchQueue: BatchQueue<ProvingJob | [ProvingJobId, ProvingJobSettledResult], number>;
109
+ private batchQueue: BatchQueue<BrokerWrite, number>;
87
110
 
88
111
  public readonly tracer: Tracer;
89
112
 
@@ -112,12 +135,16 @@ export class KVBrokerDatabase implements ProvingBrokerDatabase {
112
135
  }
113
136
 
114
137
  // exposed for testing
115
- public async commitWrites(items: Array<ProvingJob | [ProvingJobId, ProvingJobSettledResult]>, epochNumber: number) {
138
+ public async commitWrites(items: Array<BrokerWrite>, epochNumber: number) {
116
139
  const jobsToAdd = items.filter((item): item is ProvingJob => 'id' in item);
117
- const resultsToAdd = items.filter((item): item is [ProvingJobId, ProvingJobSettledResult] => Array.isArray(item));
140
+ const resultOps = items.filter((item): item is [ProvingJobId, ProvingJobSettledResult | undefined] =>
141
+ Array.isArray(item),
142
+ );
143
+ const resultsToSet = resultOps.filter((op): op is [ProvingJobId, ProvingJobSettledResult] => op[1] !== undefined);
144
+ const resultsToDelete = resultOps.filter(op => op[1] === undefined).map(([id]) => id);
118
145
 
119
146
  const db = await this.getEpochDatabase(EpochNumber(epochNumber));
120
- await db.batchWrite(jobsToAdd, resultsToAdd);
147
+ await db.batchWrite(jobsToAdd, resultsToSet, resultsToDelete);
121
148
  }
122
149
 
123
150
  private async estimateSize() {
@@ -154,7 +181,7 @@ export class KVBrokerDatabase implements ProvingBrokerDatabase {
154
181
  const db = await openVersionedStoreAt(
155
182
  fullDirectory,
156
183
  SingleEpochDatabase.SCHEMA_VERSION,
157
- config.l1Contracts.rollupAddress,
184
+ config.rollupAddress,
158
185
  config.dataStoreMapSizeKb,
159
186
  );
160
187
  const epochDb = new SingleEpochDatabase(db);
@@ -207,6 +234,14 @@ export class KVBrokerDatabase implements ProvingBrokerDatabase {
207
234
  return this.batchQueue.put([id, { status: 'rejected', reason }], getEpochFromProvingJobId(id));
208
235
  }
209
236
 
237
+ setProvingJobAborted(id: ProvingJobId): Promise<void> {
238
+ return this.batchQueue.put([id, { status: 'aborted' }], getEpochFromProvingJobId(id));
239
+ }
240
+
241
+ deleteProvingJobResult(id: ProvingJobId): Promise<void> {
242
+ return this.batchQueue.put([id, undefined], getEpochFromProvingJobId(id));
243
+ }
244
+
210
245
  setProvingJobResult(id: ProvingJobId, value: ProofUri): Promise<void> {
211
246
  return this.batchQueue.put([id, { status: 'fulfilled', value }], getEpochFromProvingJobId(id));
212
247
  }
@@ -222,7 +257,7 @@ export class KVBrokerDatabase implements ProvingBrokerDatabase {
222
257
  const db = await openVersionedStoreAt(
223
258
  newEpochDirectory,
224
259
  SingleEpochDatabase.SCHEMA_VERSION,
225
- this.config.l1Contracts.rollupAddress,
260
+ this.config.rollupAddress,
226
261
  this.config.dataStoreMapSizeKb,
227
262
  );
228
263
  epochDb = new SingleEpochDatabase(db);
@@ -38,6 +38,22 @@ export interface ProvingBrokerDatabase {
38
38
  */
39
39
  setProvingJobError(id: ProvingJobId, err: string): Promise<void>;
40
40
 
41
+ /**
42
+ * Records that a proof request was cancelled. Unlike a result or error this is not terminal:
43
+ * re-enqueuing the same job id revives it, so the aborted state can survive a restart without
44
+ * permanently blocking the proof.
45
+ * @param id - The ID of the cancelled proof request
46
+ */
47
+ setProvingJobAborted(id: ProvingJobId): Promise<void>;
48
+
49
+ /**
50
+ * Clears any stored result for a proof request, returning it to the pending state while keeping
51
+ * the job itself. Used when reviving an aborted job so the revival is persisted and a restart
52
+ * cannot resurrect the stale aborted state.
53
+ * @param id - The ID of the proof request whose result should be cleared
54
+ */
55
+ deleteProvingJobResult(id: ProvingJobId): Promise<void>;
56
+
41
57
  /**
42
58
  * Closes the database
43
59
  */
@@ -18,6 +18,7 @@ export class ProvingBrokerInstrumentation {
18
18
  private activeJobs: ObservableGauge;
19
19
  private resolvedJobs: UpDownCounter;
20
20
  private rejectedJobs: UpDownCounter;
21
+ private abortedJobs: UpDownCounter;
21
22
  private timedOutJobs: UpDownCounter;
22
23
  private cachedJobs: UpDownCounter;
23
24
  private totalJobs: UpDownCounter;
@@ -39,6 +40,8 @@ export class ProvingBrokerInstrumentation {
39
40
 
40
41
  this.rejectedJobs = createUpDownCounterWithDefault(meter, Metrics.PROVING_QUEUE_REJECTED_JOBS, provingJobAttrs);
41
42
 
43
+ this.abortedJobs = createUpDownCounterWithDefault(meter, Metrics.PROVING_QUEUE_ABORTED_JOBS, provingJobAttrs);
44
+
42
45
  this.retriedJobs = createUpDownCounterWithDefault(meter, Metrics.PROVING_QUEUE_RETRIED_JOBS, provingJobAttrs);
43
46
 
44
47
  this.timedOutJobs = createUpDownCounterWithDefault(meter, Metrics.PROVING_QUEUE_TIMED_OUT_JOBS, provingJobAttrs);
@@ -72,6 +75,12 @@ export class ProvingBrokerInstrumentation {
72
75
  });
73
76
  }
74
77
 
78
+ incAbortedJobs(proofType: ProvingRequestType) {
79
+ this.abortedJobs.add(1, {
80
+ [Attributes.PROVING_JOB_TYPE]: ProvingRequestType[proofType],
81
+ });
82
+ }
83
+
75
84
  incRetriedJobs(proofType: ProvingRequestType) {
76
85
  this.retriedJobs.add(1, {
77
86
  [Attributes.PROVING_JOB_TYPE]: ProvingRequestType[proofType],
@@ -1,9 +1,11 @@
1
+ import { EpochNumberSchema } from '@aztec/foundation/branded-types';
1
2
  import { createSafeJsonRpcClient } from '@aztec/foundation/json-rpc/client';
2
3
  import {
3
4
  type GetProvingJobResponse,
4
5
  ProofUri,
5
6
  ProvingJob,
6
7
  type ProvingJobBroker,
8
+ type ProvingJobBrokerDebug,
7
9
  type ProvingJobConsumer,
8
10
  ProvingJobId,
9
11
  type ProvingJobProducer,
@@ -16,6 +18,15 @@ import { makeTracedFetch } from '@aztec/telemetry-client';
16
18
 
17
19
  import { z } from 'zod';
18
20
 
21
+ /** Indefinite backoff for broker communication: 1, 1, 1, 2, 4, 4, 4, ... seconds. */
22
+ export function* proverBrokerBackoff() {
23
+ const v = [1, 1, 1, 2, 4];
24
+ let i = 0;
25
+ while (true) {
26
+ yield v[Math.min(i++, v.length - 1)];
27
+ }
28
+ }
29
+
19
30
  const ProvingJobFilterSchema = z.object({
20
31
  allowList: z.array(z.nativeEnum(ProvingRequestType)),
21
32
  });
@@ -26,26 +37,29 @@ const GetProvingJobResponse = z.object({
26
37
  });
27
38
 
28
39
  export const ProvingJobProducerSchema: ApiSchemaFor<ProvingJobProducer> = {
29
- enqueueProvingJob: z.function().args(ProvingJob).returns(ProvingJobStatus),
30
- getProvingJobStatus: z.function().args(ProvingJobId).returns(ProvingJobStatus),
31
- cancelProvingJob: z.function().args(ProvingJobId).returns(z.void()),
32
- getCompletedJobs: z.function().args(z.array(ProvingJobId)).returns(z.array(ProvingJobId)),
40
+ enqueueProvingJob: z.function({ input: z.tuple([ProvingJob]), output: ProvingJobStatus }),
41
+ getProvingJobStatus: z.function({ input: z.tuple([ProvingJobId]), output: ProvingJobStatus }),
42
+ cancelProvingJob: z.function({ input: z.tuple([ProvingJobId]), output: z.void() }),
43
+ getCompletedJobs: z.function({ input: z.tuple([z.array(ProvingJobId)]), output: z.array(ProvingJobId) }),
33
44
  };
34
45
 
35
46
  export const ProvingJobConsumerSchema: ApiSchemaFor<ProvingJobConsumer> = {
36
- getProvingJob: z.function().args(optional(ProvingJobFilterSchema)).returns(GetProvingJobResponse.optional()),
37
- reportProvingJobError: z
38
- .function()
39
- .args(ProvingJobId, z.string(), optional(z.boolean()), optional(ProvingJobFilterSchema))
40
- .returns(GetProvingJobResponse.optional()),
41
- reportProvingJobProgress: z
42
- .function()
43
- .args(ProvingJobId, z.number(), optional(ProvingJobFilterSchema))
44
- .returns(GetProvingJobResponse.optional()),
45
- reportProvingJobSuccess: z
46
- .function()
47
- .args(ProvingJobId, ProofUri, optional(ProvingJobFilterSchema))
48
- .returns(GetProvingJobResponse.optional()),
47
+ getProvingJob: z.function({
48
+ input: z.tuple([optional(ProvingJobFilterSchema)]),
49
+ output: GetProvingJobResponse.optional(),
50
+ }),
51
+ reportProvingJobError: z.function({
52
+ input: z.tuple([ProvingJobId, z.string(), optional(z.boolean()), optional(ProvingJobFilterSchema)]),
53
+ output: GetProvingJobResponse.optional(),
54
+ }),
55
+ reportProvingJobProgress: z.function({
56
+ input: z.tuple([ProvingJobId, z.number(), optional(ProvingJobFilterSchema)]),
57
+ output: GetProvingJobResponse.optional(),
58
+ }),
59
+ reportProvingJobSuccess: z.function({
60
+ input: z.tuple([ProvingJobId, ProofUri, optional(ProvingJobFilterSchema)]),
61
+ output: GetProvingJobResponse.optional(),
62
+ }),
49
63
  };
50
64
 
51
65
  export const ProvingJobBrokerSchema: ApiSchemaFor<ProvingJobBroker> = {
@@ -53,10 +67,22 @@ export const ProvingJobBrokerSchema: ApiSchemaFor<ProvingJobBroker> = {
53
67
  ...ProvingJobProducerSchema,
54
68
  };
55
69
 
70
+ export const ProvingJobBrokerDebugSchema: ApiSchemaFor<ProvingJobBrokerDebug> = {
71
+ replayProvingJob: z.function({
72
+ input: z.tuple([ProvingJobId, z.nativeEnum(ProvingRequestType), EpochNumberSchema, ProofUri]),
73
+ output: ProvingJobStatus,
74
+ }),
75
+ };
76
+
77
+ export const ProvingJobBrokerSchemaWithDebug: ApiSchemaFor<ProvingJobBroker & ProvingJobBrokerDebug> = {
78
+ ...ProvingJobBrokerSchema,
79
+ ...ProvingJobBrokerDebugSchema,
80
+ };
81
+
56
82
  export function createProvingJobBrokerClient(
57
83
  url: string,
58
84
  versions: Partial<ComponentsVersions>,
59
- fetch = makeTracedFetch([1, 2, 3], false),
85
+ fetch = makeTracedFetch(proverBrokerBackoff, false),
60
86
  ): ProvingJobBroker {
61
87
  return createSafeJsonRpcClient(url, ProvingJobBrokerSchema, {
62
88
  namespaceMethods: 'proverBroker',
@@ -68,7 +94,7 @@ export function createProvingJobBrokerClient(
68
94
  export function createProvingJobProducerClient(
69
95
  url: string,
70
96
  versions: Partial<ComponentsVersions>,
71
- fetch = makeTracedFetch([1, 2, 3], false),
97
+ fetch = makeTracedFetch(proverBrokerBackoff, false),
72
98
  ): ProvingJobProducer {
73
99
  return createSafeJsonRpcClient(url, ProvingJobProducerSchema, {
74
100
  namespaceMethods: 'provingJobProducer',
@@ -80,7 +106,7 @@ export function createProvingJobProducerClient(
80
106
  export function createProvingJobConsumerClient(
81
107
  url: string,
82
108
  versions: Partial<ComponentsVersions>,
83
- fetch = makeTracedFetch([1, 2, 3], false),
109
+ fetch = makeTracedFetch(proverBrokerBackoff, false),
84
110
  ): ProvingJobConsumer {
85
111
  return createSafeJsonRpcClient(url, ProvingJobConsumerSchema, {
86
112
  namespaceMethods: 'provingJobConsumer',