@aztec/prover-client 0.0.1-commit.9ef841308 → 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 (101) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +4 -0
  4. package/dest/light/lightweight_checkpoint_builder.d.ts +1 -1
  5. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  6. package/dest/light/lightweight_checkpoint_builder.js +15 -5
  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 +21 -26
  10. package/dest/orchestrator/block-building-helpers.d.ts +1 -1
  11. package/dest/orchestrator/checkpoint-proving-state.d.ts +20 -36
  12. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  13. package/dest/orchestrator/checkpoint-proving-state.js +22 -120
  14. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +161 -0
  15. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  16. package/dest/orchestrator/{orchestrator.js → checkpoint-sub-tree-orchestrator.js} +267 -451
  17. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  18. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  19. package/dest/orchestrator/chonk-cache.js +80 -0
  20. package/dest/orchestrator/index.d.ts +4 -2
  21. package/dest/orchestrator/index.d.ts.map +1 -1
  22. package/dest/orchestrator/index.js +3 -1
  23. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  24. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  25. package/dest/orchestrator/proving-scheduler.js +120 -0
  26. package/dest/orchestrator/top-tree-orchestrator.d.ts +88 -0
  27. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  28. package/dest/orchestrator/top-tree-orchestrator.js +232 -0
  29. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  30. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  31. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  32. package/dest/orchestrator/tx-proving-state.d.ts +3 -3
  33. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -1
  34. package/dest/prover-client/prover-client.d.ts +61 -4
  35. package/dest/prover-client/prover-client.d.ts.map +1 -1
  36. package/dest/prover-client/prover-client.js +54 -7
  37. package/dest/proving_broker/broker_prover_facade.d.ts +3 -3
  38. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  39. package/dest/proving_broker/broker_prover_facade.js +5 -0
  40. package/dest/proving_broker/config.d.ts +8 -72
  41. package/dest/proving_broker/config.d.ts.map +1 -1
  42. package/dest/proving_broker/config.js +2 -2
  43. package/dest/proving_broker/index.d.ts +2 -1
  44. package/dest/proving_broker/index.d.ts.map +1 -1
  45. package/dest/proving_broker/index.js +1 -0
  46. package/dest/proving_broker/proving_broker.d.ts +2 -2
  47. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  48. package/dest/proving_broker/proving_broker.js +92 -24
  49. package/dest/proving_broker/proving_broker_database/memory.d.ts +3 -1
  50. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -1
  51. package/dest/proving_broker/proving_broker_database/memory.js +10 -0
  52. package/dest/proving_broker/proving_broker_database/persisted.d.ts +13 -2
  53. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -1
  54. package/dest/proving_broker/proving_broker_database/persisted.js +32 -5
  55. package/dest/proving_broker/proving_broker_database.d.ts +15 -1
  56. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -1
  57. package/dest/proving_broker/rpc.d.ts +3 -1
  58. package/dest/proving_broker/rpc.d.ts.map +1 -1
  59. package/dest/proving_broker/rpc.js +80 -24
  60. package/dest/test/epoch_settlement.d.ts +36 -0
  61. package/dest/test/epoch_settlement.d.ts.map +1 -0
  62. package/dest/test/epoch_settlement.js +52 -0
  63. package/dest/test/index.d.ts +2 -0
  64. package/dest/test/index.d.ts.map +1 -0
  65. package/dest/test/index.js +1 -0
  66. package/dest/test/mock_prover.d.ts +1 -1
  67. package/dest/test/mock_prover.js +2 -2
  68. package/package.json +19 -18
  69. package/src/config.ts +5 -0
  70. package/src/light/lightweight_checkpoint_builder.ts +16 -6
  71. package/src/mocks/test_context.ts +21 -40
  72. package/src/orchestrator/checkpoint-proving-state.ts +21 -162
  73. package/src/orchestrator/{orchestrator.ts → checkpoint-sub-tree-orchestrator.ts} +415 -661
  74. package/src/orchestrator/chonk-cache.ts +99 -0
  75. package/src/orchestrator/index.ts +8 -1
  76. package/src/orchestrator/proving-scheduler.ts +160 -0
  77. package/src/orchestrator/top-tree-orchestrator.ts +384 -0
  78. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  79. package/src/orchestrator/tx-proving-state.ts +3 -3
  80. package/src/prover-client/prover-client.ts +128 -18
  81. package/src/proving_broker/broker_prover_facade.ts +4 -2
  82. package/src/proving_broker/config.ts +2 -1
  83. package/src/proving_broker/index.ts +1 -0
  84. package/src/proving_broker/proving_broker.ts +84 -22
  85. package/src/proving_broker/proving_broker_database/memory.ts +10 -0
  86. package/src/proving_broker/proving_broker_database/persisted.ts +42 -7
  87. package/src/proving_broker/proving_broker_database.ts +16 -0
  88. package/src/proving_broker/rpc.ts +36 -24
  89. package/src/test/epoch_settlement.ts +82 -0
  90. package/src/test/index.ts +1 -0
  91. package/src/test/mock_prover.ts +2 -2
  92. package/dest/orchestrator/epoch-proving-state.d.ts +0 -75
  93. package/dest/orchestrator/epoch-proving-state.d.ts.map +0 -1
  94. package/dest/orchestrator/epoch-proving-state.js +0 -269
  95. package/dest/orchestrator/orchestrator.d.ts +0 -130
  96. package/dest/orchestrator/orchestrator.d.ts.map +0 -1
  97. package/dest/prover-client/server-epoch-prover.d.ts +0 -32
  98. package/dest/prover-client/server-epoch-prover.d.ts.map +0 -1
  99. package/dest/prover-client/server-epoch-prover.js +0 -40
  100. package/src/orchestrator/epoch-proving-state.ts +0 -380
  101. package/src/prover-client/server-epoch-prover.ts +0 -69
@@ -0,0 +1,219 @@
1
+ import type { BatchedBlob, BatchedBlobAccumulator, FinalBlobBatchingChallenges } from '@aztec/blob-lib';
2
+ import type { NESTED_RECURSIVE_PROOF_LENGTH, NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH } from '@aztec/constants';
3
+ import { EpochNumber } from '@aztec/foundation/branded-types';
4
+ import { type TreeNodeLocation, UnbalancedTreeStore } from '@aztec/foundation/trees';
5
+ import type { PublicInputsAndRecursiveProof } from '@aztec/stdlib/interfaces/server';
6
+ import type { Proof } from '@aztec/stdlib/proofs';
7
+ import {
8
+ CheckpointMergeRollupPrivateInputs,
9
+ CheckpointPaddingRollupPrivateInputs,
10
+ CheckpointRollupPublicInputs,
11
+ RootRollupPrivateInputs,
12
+ type RootRollupPublicInputs,
13
+ } from '@aztec/stdlib/rollup';
14
+
15
+ import { toProofData } from './block-building-helpers.js';
16
+ import type { ProofState } from './block-proving-state.js';
17
+
18
+ enum TOP_TREE_LIFECYCLE {
19
+ CREATED,
20
+ RESOLVED,
21
+ REJECTED,
22
+ }
23
+
24
+ /**
25
+ * Lean top-tree-only state. Owns the merge tree of checkpoint root proofs, the
26
+ * single-checkpoint padding proof slot, the final root rollup proof, and the blob
27
+ * accumulator endpoints needed to finalise the epoch's batched blob proof.
28
+ *
29
+ * Constructed with `totalNumCheckpoints` and `finalBlobBatchingChallenges` upfront —
30
+ * by the time the top tree starts, all checkpoints are known and the challenges are
31
+ * derivable from their blob fields.
32
+ */
33
+ export class TopTreeProvingState {
34
+ private checkpointProofs: UnbalancedTreeStore<
35
+ ProofState<CheckpointRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
36
+ >;
37
+ private checkpointPaddingProof:
38
+ | ProofState<CheckpointRollupPublicInputs, typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH>
39
+ | undefined;
40
+ private rootRollupProof: ProofState<RootRollupPublicInputs, typeof NESTED_RECURSIVE_PROOF_LENGTH> | undefined;
41
+ private endBlobAccumulator: BatchedBlobAccumulator | undefined;
42
+ private finalBatchedBlob: BatchedBlob | undefined;
43
+ private lifecycle = TOP_TREE_LIFECYCLE.CREATED;
44
+ constructor(
45
+ public readonly epochNumber: EpochNumber,
46
+ public readonly totalNumCheckpoints: number,
47
+ public readonly finalBlobBatchingChallenges: FinalBlobBatchingChallenges,
48
+ public readonly startBlobAccumulator: BatchedBlobAccumulator,
49
+ private readonly completionCallback: () => void,
50
+ private readonly rejectionCallback: (reason: string) => void,
51
+ ) {
52
+ if (totalNumCheckpoints < 1) {
53
+ throw new Error(`TopTreeProvingState requires at least one checkpoint; got ${totalNumCheckpoints}.`);
54
+ }
55
+ this.checkpointProofs = new UnbalancedTreeStore(totalNumCheckpoints);
56
+ }
57
+
58
+ // --- checkpoint root rollup ---
59
+
60
+ public setCheckpointRootRollupProof(
61
+ checkpointIndex: number,
62
+ provingOutput: PublicInputsAndRecursiveProof<
63
+ CheckpointRollupPublicInputs,
64
+ typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
65
+ >,
66
+ ): TreeNodeLocation {
67
+ return this.checkpointProofs.setLeaf(checkpointIndex, { provingOutput });
68
+ }
69
+
70
+ // --- checkpoint merge rollup ---
71
+
72
+ public tryStartProvingCheckpointMerge(location: TreeNodeLocation) {
73
+ if (this.checkpointProofs.getNode(location)?.isProving) {
74
+ return false;
75
+ }
76
+ this.checkpointProofs.setNode(location, { isProving: true });
77
+ return true;
78
+ }
79
+
80
+ public setCheckpointMergeRollupProof(
81
+ location: TreeNodeLocation,
82
+ provingOutput: PublicInputsAndRecursiveProof<
83
+ CheckpointRollupPublicInputs,
84
+ typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
85
+ >,
86
+ ) {
87
+ this.checkpointProofs.setNode(location, { provingOutput });
88
+ }
89
+
90
+ public isReadyForCheckpointMerge(location: TreeNodeLocation) {
91
+ return !!this.checkpointProofs.getSibling(location)?.provingOutput;
92
+ }
93
+
94
+ public getParentLocation(location: TreeNodeLocation) {
95
+ return this.checkpointProofs.getParentLocation(location);
96
+ }
97
+
98
+ public getCheckpointMergeRollupInputs(mergeLocation: TreeNodeLocation) {
99
+ const [left, right] = this.checkpointProofs.getChildren(mergeLocation).map(c => c?.provingOutput);
100
+ if (!left || !right) {
101
+ throw new Error('At least one child is not ready for the checkpoint merge rollup.');
102
+ }
103
+ return new CheckpointMergeRollupPrivateInputs([toProofData(left), toProofData(right)]);
104
+ }
105
+
106
+ // --- padding (single-checkpoint case) ---
107
+
108
+ public tryStartProvingPaddingCheckpoint() {
109
+ if (this.checkpointPaddingProof?.isProving) {
110
+ return false;
111
+ }
112
+ this.checkpointPaddingProof = { isProving: true };
113
+ return true;
114
+ }
115
+
116
+ public setCheckpointPaddingProof(
117
+ provingOutput: PublicInputsAndRecursiveProof<
118
+ CheckpointRollupPublicInputs,
119
+ typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
120
+ >,
121
+ ) {
122
+ this.checkpointPaddingProof = { provingOutput };
123
+ }
124
+
125
+ public getPaddingCheckpointInputs() {
126
+ return new CheckpointPaddingRollupPrivateInputs();
127
+ }
128
+
129
+ // --- root rollup ---
130
+
131
+ public tryStartProvingRootRollup() {
132
+ if (this.rootRollupProof?.isProving) {
133
+ return false;
134
+ }
135
+ this.rootRollupProof = { isProving: true };
136
+ return true;
137
+ }
138
+
139
+ public setRootRollupProof(provingOutput: PublicInputsAndRecursiveProof<RootRollupPublicInputs>) {
140
+ this.rootRollupProof = { provingOutput };
141
+ }
142
+
143
+ public isReadyForRootRollup() {
144
+ const childProofs = this.#getChildProofsForRoot();
145
+ return childProofs.every(p => !!p);
146
+ }
147
+
148
+ public getRootRollupInputs() {
149
+ const [left, right] = this.#getChildProofsForRoot();
150
+ if (!left || !right) {
151
+ throw new Error('At least one child is not ready for the root rollup.');
152
+ }
153
+ return RootRollupPrivateInputs.from({
154
+ previousRollups: [toProofData(left), toProofData(right)],
155
+ });
156
+ }
157
+
158
+ // --- blob accumulator finalisation ---
159
+
160
+ /**
161
+ * Sets the end-of-epoch blob accumulator, computed by the top-tree orchestrator
162
+ * from the surviving checkpoints' blob fields. Required before `finalizeBatchedBlob`.
163
+ */
164
+ public setEndBlobAccumulator(accumulator: BatchedBlobAccumulator) {
165
+ this.endBlobAccumulator = accumulator;
166
+ }
167
+
168
+ public async finalizeBatchedBlob() {
169
+ if (!this.endBlobAccumulator) {
170
+ throw new Error('End blob accumulator not set; call setEndBlobAccumulator before finalize.');
171
+ }
172
+ this.finalBatchedBlob = await this.endBlobAccumulator.finalize(true /* verifyProof */);
173
+ }
174
+
175
+ public getEpochProofResult(): { proof: Proof; publicInputs: RootRollupPublicInputs; batchedBlobInputs: BatchedBlob } {
176
+ const provingOutput = this.rootRollupProof?.provingOutput;
177
+ if (!provingOutput || !this.finalBatchedBlob) {
178
+ throw new Error('Top-tree proof not ready; root rollup or batched blob missing.');
179
+ }
180
+ return {
181
+ proof: provingOutput.proof.binaryProof,
182
+ publicInputs: provingOutput.inputs,
183
+ batchedBlobInputs: this.finalBatchedBlob,
184
+ };
185
+ }
186
+
187
+ // --- lifecycle ---
188
+
189
+ public verifyState() {
190
+ return this.lifecycle === TOP_TREE_LIFECYCLE.CREATED;
191
+ }
192
+
193
+ public resolve() {
194
+ if (!this.verifyState()) {
195
+ return;
196
+ }
197
+ this.lifecycle = TOP_TREE_LIFECYCLE.RESOLVED;
198
+ this.completionCallback();
199
+ }
200
+
201
+ public reject(reason: string) {
202
+ if (!this.verifyState()) {
203
+ return;
204
+ }
205
+ this.lifecycle = TOP_TREE_LIFECYCLE.REJECTED;
206
+ this.rejectionCallback(reason);
207
+ }
208
+
209
+ public cancel() {
210
+ this.reject('Top-tree proving cancelled');
211
+ }
212
+
213
+ #getChildProofsForRoot() {
214
+ const rootLocation = { level: 0, index: 0 };
215
+ return this.totalNumCheckpoints === 1
216
+ ? [this.checkpointProofs.getNode(rootLocation)?.provingOutput, this.checkpointPaddingProof?.provingOutput]
217
+ : this.checkpointProofs.getChildren(rootLocation).map(c => c?.provingOutput);
218
+ }
219
+ }
@@ -1,4 +1,4 @@
1
- import { AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED, NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH } from '@aztec/constants';
1
+ import { AVM_V2_PROOF_LENGTH_IN_FIELDS, NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH } from '@aztec/constants';
2
2
  import type { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { getVkData } from '@aztec/noir-protocol-circuits-types/server/vks';
4
4
  import type { AvmCircuitInputs } from '@aztec/stdlib/avm';
@@ -32,7 +32,7 @@ export class TxProvingState {
32
32
  PublicChonkVerifierPublicInputs,
33
33
  typeof NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH
34
34
  >;
35
- private avmProof?: RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED>;
35
+ private avmProof?: RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS>;
36
36
 
37
37
  constructor(
38
38
  public readonly processedTx: ProcessedTx,
@@ -80,7 +80,7 @@ export class TxProvingState {
80
80
  this.publicChonkVerifier = publicChonkVerifierProofAndVk;
81
81
  }
82
82
 
83
- public setAvmProof(avmProof: RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED>) {
83
+ public setAvmProof(avmProof: RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS>) {
84
84
  this.avmProof = avmProof;
85
85
  }
86
86
 
@@ -1,11 +1,13 @@
1
1
  import { type ACVMConfig, type BBConfig, BBNativeRollupProver, TestCircuitProver } from '@aztec/bb-prover';
2
+ import type { EpochNumber } from '@aztec/foundation/branded-types';
2
3
  import { times } from '@aztec/foundation/collection';
4
+ import type { Fr } from '@aztec/foundation/curves/bn254';
3
5
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
6
  import { type Logger, createLogger } from '@aztec/foundation/log';
7
+ import { SerialQueue } from '@aztec/foundation/queue';
5
8
  import { NativeACVMSimulator } from '@aztec/simulator/server';
6
9
  import {
7
10
  type ActualProverConfig,
8
- type EpochProver,
9
11
  type EpochProverManager,
10
12
  type ForkMerkleTreeOperations,
11
13
  type ProvingJobBroker,
@@ -15,19 +17,68 @@ import {
15
17
  type ServerCircuitProver,
16
18
  tryStop,
17
19
  } from '@aztec/stdlib/interfaces/server';
20
+ import type { CheckpointConstantData } from '@aztec/stdlib/rollup';
21
+ import type { BlockHeader } from '@aztec/stdlib/tx';
18
22
  import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
19
23
 
20
24
  import type { ProverClientConfig } from '../config.js';
21
- import { ProvingOrchestrator } from '../orchestrator/orchestrator.js';
25
+ import { CheckpointSubTreeOrchestrator } from '../orchestrator/checkpoint-sub-tree-orchestrator.js';
26
+ import type { ChonkCache } from '../orchestrator/chonk-cache.js';
27
+ import { TopTreeOrchestrator } from '../orchestrator/top-tree-orchestrator.js';
22
28
  import { BrokerCircuitProverFacade } from '../proving_broker/broker_prover_facade.js';
23
29
  import { InlineProofStore, type ProofStore, createProofStore } from '../proving_broker/proof_store/index.js';
24
30
  import { ProvingAgent } from '../proving_broker/proving_agent.js';
25
- import { ServerEpochProver } from './server-epoch-prover.js';
31
+
32
+ /**
33
+ * The factory surface that `EpochProvingJob` (in `prover-node`) depends on. Implemented
34
+ * by `ProverClient`. Defined here rather than in stdlib because the return types
35
+ * (`CheckpointSubTreeOrchestrator`, `TopTreeOrchestrator`) are concrete classes from
36
+ * this package.
37
+ *
38
+ * A single `BrokerCircuitProverFacade` is owned by `ProverClient` and shared across
39
+ * every orchestrator (every sub-tree and every top-tree across every concurrent epoch
40
+ * job). The broker delivers each completed-job notification exactly once (drained on
41
+ * the first `getCompletedJobs` poll), so multiple facades polling the same broker
42
+ * race and lose notifications
43
+ *
44
+ * The facade's job map cleans up entries on resolve/reject, and the prover-node
45
+ * keeps `ProverClient` alive for its whole lifetime
46
+ */
47
+ export interface EpochProverFactory {
48
+ getProverId(): EthAddress;
49
+ /**
50
+ * Constructs and starts a `CheckpointSubTreeOrchestrator` for a single checkpoint
51
+ * against the supplied shared `chonkCache`. The cache is owned by the prover-node
52
+ * and survives across epochs / sessions.
53
+ */
54
+ createCheckpointSubTreeOrchestrator(
55
+ chonkCache: ChonkCache,
56
+ epochNumber: EpochNumber,
57
+ checkpointConstants: CheckpointConstantData,
58
+ l1ToL2Messages: Fr[],
59
+ totalNumBlocks: number,
60
+ headerOfLastBlockInPreviousCheckpoint: BlockHeader,
61
+ ): Promise<CheckpointSubTreeOrchestrator>;
62
+ createTopTreeOrchestrator(): TopTreeOrchestrator;
63
+ }
26
64
 
27
65
  /** Manages proving of epochs by orchestrating the proving of individual blocks relying on a pool of prover agents. */
28
- export class ProverClient implements EpochProverManager {
66
+ export class ProverClient implements EpochProverManager, EpochProverFactory {
29
67
  private running = false;
30
68
  private agents: ProvingAgent[] = [];
69
+ /**
70
+ * The single broker facade shared by every orchestrator created from this client.
71
+ * Constructed lazily on `start()` and torn down on `stop()` — see the comment on
72
+ * `EpochProverFactory` for why a single shared facade is required.
73
+ */
74
+ private facade: BrokerCircuitProverFacade | undefined;
75
+ /**
76
+ * Single deferred-proving-job queue shared across every orchestrator (sub-trees and
77
+ * top-trees, across every concurrent epoch session). Throttles the total rate of job
78
+ * submission to the broker once, rather than once per orchestrator. Started lazily
79
+ * alongside the facade and cancelled on `stop()`.
80
+ */
81
+ private deferredJobQueue: SerialQueue | undefined;
31
82
 
32
83
  private constructor(
33
84
  private config: ProverClientConfig,
@@ -40,25 +91,76 @@ export class ProverClient implements EpochProverManager {
40
91
  private log: Logger = createLogger('prover-client:tx-prover'),
41
92
  ) {}
42
93
 
43
- public createEpochProver(): EpochProver {
44
- const bindings = this.log.getBindings();
45
- const facade = new BrokerCircuitProverFacade(
46
- this.orchestratorClient,
47
- this.proofStore,
48
- this.failedProofStore,
49
- undefined,
50
- bindings,
51
- );
52
- const orchestrator = new ProvingOrchestrator(
94
+ /**
95
+ * Lazy-init the shared facade. The broker delivers each completed-job notification
96
+ * exactly once (drained on the first `getCompletedJobs` poll), so we cannot start
97
+ * a shared facade alongside the per-call facades that `createEpochProver` builds —
98
+ * they would race for notifications and one side would silently drop them. Starting
99
+ * the shared facade only on first use of one of the new factory methods keeps the
100
+ * legacy `createEpochProver` path race-free.
101
+ */
102
+ private getFacade(): BrokerCircuitProverFacade {
103
+ if (!this.running) {
104
+ throw new Error('ProverClient is not running; call start() before constructing orchestrators.');
105
+ }
106
+ if (!this.facade) {
107
+ this.facade = new BrokerCircuitProverFacade(
108
+ this.orchestratorClient,
109
+ this.proofStore,
110
+ this.failedProofStore,
111
+ undefined,
112
+ this.log.getBindings(),
113
+ );
114
+ this.facade.start();
115
+ }
116
+ return this.facade;
117
+ }
118
+
119
+ /** Lazy-init the shared deferred-job queue, started with the configured enqueue concurrency. */
120
+ private getDeferredJobQueue(): SerialQueue {
121
+ if (!this.running) {
122
+ throw new Error('ProverClient is not running; call start() before constructing orchestrators.');
123
+ }
124
+ if (!this.deferredJobQueue) {
125
+ this.deferredJobQueue = new SerialQueue();
126
+ this.deferredJobQueue.start(this.config.enqueueConcurrency);
127
+ }
128
+ return this.deferredJobQueue;
129
+ }
130
+
131
+ public createCheckpointSubTreeOrchestrator(
132
+ chonkCache: ChonkCache,
133
+ epochNumber: EpochNumber,
134
+ checkpointConstants: CheckpointConstantData,
135
+ l1ToL2Messages: Fr[],
136
+ totalNumBlocks: number,
137
+ headerOfLastBlockInPreviousCheckpoint: BlockHeader,
138
+ ): Promise<CheckpointSubTreeOrchestrator> {
139
+ return CheckpointSubTreeOrchestrator.start(
53
140
  this.worldState,
54
- facade,
141
+ this.getFacade(),
55
142
  this.config.proverId,
143
+ chonkCache,
144
+ epochNumber,
56
145
  this.config.cancelJobsOnStop,
57
- this.config.enqueueConcurrency,
146
+ this.getDeferredJobQueue(),
147
+ checkpointConstants,
148
+ l1ToL2Messages,
149
+ totalNumBlocks,
150
+ headerOfLastBlockInPreviousCheckpoint,
58
151
  this.telemetry,
59
- bindings,
152
+ this.log.getBindings(),
153
+ );
154
+ }
155
+
156
+ public createTopTreeOrchestrator(): TopTreeOrchestrator {
157
+ return new TopTreeOrchestrator(
158
+ this.getFacade(),
159
+ this.config.proverId,
160
+ this.getDeferredJobQueue(),
161
+ this.telemetry,
162
+ this.log.getBindings(),
60
163
  );
61
- return new ServerEpochProver(facade, orchestrator);
62
164
  }
63
165
 
64
166
  public getProverId(): EthAddress {
@@ -100,6 +202,14 @@ export class ProverClient implements EpochProverManager {
100
202
  }
101
203
  this.running = false;
102
204
  await this.stopAgents();
205
+ if (this.deferredJobQueue) {
206
+ await this.deferredJobQueue.cancel();
207
+ this.deferredJobQueue = undefined;
208
+ }
209
+ if (this.facade) {
210
+ await tryStop(this.facade, this.log);
211
+ this.facade = undefined;
212
+ }
103
213
  await tryStop(this.orchestratorClient);
104
214
  }
105
215
 
@@ -1,5 +1,5 @@
1
1
  import type {
2
- AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED,
2
+ AVM_V2_PROOF_LENGTH_IN_FIELDS,
3
3
  NESTED_RECURSIVE_PROOF_LENGTH,
4
4
  NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
5
5
  RECURSIVE_PROOF_LENGTH,
@@ -288,6 +288,8 @@ export class BrokerCircuitProverFacade implements ServerCircuitProver {
288
288
  }
289
289
  } else if (result.status === 'rejected') {
290
290
  return { success: false, reason: result.reason };
291
+ } else if (result.status === 'aborted') {
292
+ return { success: false, reason: 'Aborted' };
291
293
  } else {
292
294
  throw new Error(`Unexpected proving job status ${result.status}`);
293
295
  }
@@ -394,7 +396,7 @@ export class BrokerCircuitProverFacade implements ServerCircuitProver {
394
396
  inputs: AvmCircuitInputs,
395
397
  signal?: AbortSignal,
396
398
  epochNumber?: EpochNumber,
397
- ): Promise<RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS_PADDED>> {
399
+ ): Promise<RecursiveProof<typeof AVM_V2_PROOF_LENGTH_IN_FIELDS>> {
398
400
  return this.enqueueJob(
399
401
  this.generateId(ProvingRequestType.PUBLIC_VM, inputs, epochNumber),
400
402
  ProvingRequestType.PUBLIC_VM,
@@ -4,6 +4,7 @@ import {
4
4
  booleanConfigHelper,
5
5
  getDefaultConfig,
6
6
  numberConfigHelper,
7
+ optionalNumberConfigHelper,
7
8
  } from '@aztec/foundation/config';
8
9
  import { pickConfigMappings } from '@aztec/foundation/config';
9
10
  import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
@@ -73,7 +74,7 @@ export const proverBrokerConfigMappings: ConfigMappingsType<ProverBrokerConfig>
73
74
  },
74
75
  proverBrokerStoreMapSizeKb: {
75
76
  env: 'PROVER_BROKER_STORE_MAP_SIZE_KB',
76
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
77
+ ...optionalNumberConfigHelper(),
77
78
  description: "The size of the prover broker's database. Will override the dataStoreMapSizeKb if set.",
78
79
  },
79
80
  proverBrokerDebugReplayEnabled: {
@@ -7,3 +7,4 @@ export * from './proving_broker_database/persisted.js';
7
7
  export * from './proof_store/index.js';
8
8
  export * from './factory.js';
9
9
  export * from './config.js';
10
+ export { BrokerCircuitProverFacade } from './broker_prover_facade.js';
@@ -272,15 +272,40 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
272
272
 
273
273
  async #enqueueProvingJob(job: ProvingJob): Promise<ProvingJobStatus> {
274
274
  // We return the job status at the start of this call
275
- const jobStatus = this.#getProvingJobStatus(job.id);
275
+ let jobStatus = this.#getProvingJobStatus(job.id);
276
276
  if (this.jobsCache.has(job.id)) {
277
277
  const existing = this.jobsCache.get(job.id);
278
278
  assert.deepStrictEqual(job, existing, 'Duplicate proving job ID');
279
- this.logger.warn(`Cached proving job id=${job.id} epochNumber=${job.epochNumber}. Not enqueuing again`, {
280
- provingJobId: job.id,
281
- });
282
- this.instrumentation.incCachedJobs(job.type);
283
- 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
+ }
284
309
  }
285
310
 
286
311
  if (this.isJobStale(job)) {
@@ -306,27 +331,53 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
306
331
  }
307
332
 
308
333
  async #cancelProvingJob(id: ProvingJobId): Promise<void> {
309
- if (!this.jobsCache.has(id)) {
334
+ const job = this.jobsCache.get(id);
335
+ if (!job) {
310
336
  this.logger.warn(`Can't cancel a job that doesn't exist id=${id}`, { provingJobId: id });
311
337
  return;
312
338
  }
313
339
 
314
- // notify listeners of the cancellation
315
- if (!this.resultsCache.has(id)) {
316
- this.logger.info(`Cancelling job id=${id}`, { provingJobId: id });
317
- await this.#reportProvingJobError(id, 'Aborted', false, undefined, true);
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;
318
363
  }
319
364
  }
320
365
 
321
366
  private cleanUpProvingJobState(ids: ProvingJobId[]) {
367
+ const idsToClean = new Set(ids);
322
368
  for (const id of ids) {
323
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
+ }
324
374
  this.promises.delete(id);
325
375
  this.resultsCache.delete(id);
326
376
  this.inProgress.delete(id);
327
377
  this.retries.delete(id);
328
378
  this.enqueuedAt.delete(id);
329
379
  }
380
+ this.completedJobNotifications = this.completedJobNotifications.filter(id => !idsToClean.has(id));
330
381
  }
331
382
 
332
383
  #getProvingJobStatus(id: ProvingJobId): ProvingJobStatus {
@@ -395,7 +446,6 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
395
446
  err: string,
396
447
  retry = false,
397
448
  filter?: ProvingJobFilter,
398
- aborted = false,
399
449
  ): Promise<GetProvingJobResponse | undefined> {
400
450
  const info = this.inProgress.get(id);
401
451
  const item = this.jobsCache.get(id);
@@ -456,11 +506,7 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
456
506
  this.promises.get(id)!.resolve(result);
457
507
  this.completedJobNotifications.push(id);
458
508
 
459
- if (aborted) {
460
- this.instrumentation.incAbortedJobs(item.type);
461
- } else {
462
- this.instrumentation.incRejectedJobs(item.type);
463
- }
509
+ this.instrumentation.incRejectedJobs(item.type);
464
510
  if (info) {
465
511
  const duration = this.msTimeSource() - info.startedAt;
466
512
  this.instrumentation.recordJobDuration(item.type, duration);
@@ -594,21 +640,21 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
594
640
  }
595
641
 
596
642
  private async cleanupPass() {
597
- this.cleanupStaleJobs();
598
643
  this.reEnqueueExpiredJobs();
599
644
  const oldestEpochToKeep = this.oldestEpochToKeep();
600
645
  if (oldestEpochToKeep > 0) {
646
+ this.cleanupJobsOlderThanEpoch(EpochNumber(oldestEpochToKeep));
601
647
  await this.database.deleteAllProvingJobsOlderThanEpoch(EpochNumber(oldestEpochToKeep));
602
648
  this.logger.trace(`Deleted all epochs older than ${oldestEpochToKeep}`);
603
649
  }
604
650
  }
605
651
 
606
- private cleanupStaleJobs() {
652
+ private cleanupJobsOlderThanEpoch(epochNumber: EpochNumber) {
607
653
  const jobIds = Array.from(this.jobsCache.keys());
608
654
  const jobsToClean: ProvingJobId[] = [];
609
655
  for (const id of jobIds) {
610
656
  const job = this.jobsCache.get(id)!;
611
- if (this.isJobStale(job)) {
657
+ if (job.epochNumber < epochNumber) {
612
658
  jobsToClean.push(id);
613
659
  }
614
660
  }
@@ -632,10 +678,26 @@ export class ProvingBroker implements ProvingJobProducer, ProvingJobConsumer, Pr
632
678
  const now = this.msTimeSource();
633
679
  const msSinceLastUpdate = now - metadata.lastUpdatedAt;
634
680
  if (msSinceLastUpdate >= this.jobTimeoutMs) {
635
- this.logger.warn(`Proving job id=${id} timed out. Adding it back to the queue.`, { provingJobId: id });
636
681
  this.inProgress.delete(id);
637
- this.enqueueJobInternal(item);
638
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
+ }
639
701
  }
640
702
  }
641
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);