@aztec/prover-client 0.0.1-commit.96dac018d → 0.0.1-commit.993d240

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 (78) 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 +2 -1
  5. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -1
  6. package/dest/light/lightweight_checkpoint_builder.js +19 -4
  7. package/dest/mocks/test_context.d.ts +3 -1
  8. package/dest/mocks/test_context.d.ts.map +1 -1
  9. package/dest/mocks/test_context.js +13 -7
  10. package/dest/orchestrator/block-building-helpers.d.ts +1 -1
  11. package/dest/orchestrator/checkpoint-proving-state.d.ts +8 -1
  12. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -1
  13. package/dest/orchestrator/checkpoint-proving-state.js +10 -1
  14. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +107 -0
  15. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  16. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.js +151 -0
  17. package/dest/orchestrator/epoch-proving-context.d.ts +51 -0
  18. package/dest/orchestrator/epoch-proving-context.d.ts.map +1 -0
  19. package/dest/orchestrator/epoch-proving-context.js +81 -0
  20. package/dest/orchestrator/epoch-proving-state.d.ts +1 -1
  21. package/dest/orchestrator/index.d.ts +4 -1
  22. package/dest/orchestrator/index.d.ts.map +1 -1
  23. package/dest/orchestrator/index.js +3 -0
  24. package/dest/orchestrator/orchestrator.d.ts +15 -25
  25. package/dest/orchestrator/orchestrator.d.ts.map +1 -1
  26. package/dest/orchestrator/orchestrator.js +33 -154
  27. package/dest/orchestrator/proving-scheduler.d.ts +72 -0
  28. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  29. package/dest/orchestrator/proving-scheduler.js +117 -0
  30. package/dest/orchestrator/top-tree-orchestrator.d.ts +83 -0
  31. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  32. package/dest/orchestrator/top-tree-orchestrator.js +182 -0
  33. package/dest/orchestrator/top-tree-proving-scheduler.d.ts +62 -0
  34. package/dest/orchestrator/top-tree-proving-scheduler.d.ts.map +1 -0
  35. package/dest/orchestrator/top-tree-proving-scheduler.js +73 -0
  36. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  37. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  38. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  39. package/dest/prover-client/prover-client.d.ts +62 -3
  40. package/dest/prover-client/prover-client.d.ts.map +1 -1
  41. package/dest/prover-client/prover-client.js +50 -2
  42. package/dest/proving_broker/broker_prover_facade.d.ts +1 -1
  43. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -1
  44. package/dest/proving_broker/broker_prover_facade.js +13 -19
  45. package/dest/proving_broker/config.d.ts +9 -73
  46. package/dest/proving_broker/config.d.ts.map +1 -1
  47. package/dest/proving_broker/config.js +3 -3
  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/proving_broker.d.ts +2 -2
  52. package/dest/proving_broker/proving_broker.d.ts.map +1 -1
  53. package/dest/proving_broker/proving_broker.js +32 -7
  54. package/dest/proving_broker/proving_broker_database/persisted.js +2 -2
  55. package/dest/proving_broker/rpc.d.ts +3 -1
  56. package/dest/proving_broker/rpc.d.ts.map +1 -1
  57. package/dest/proving_broker/rpc.js +80 -24
  58. package/dest/test/mock_prover.d.ts +3 -3
  59. package/package.json +18 -19
  60. package/src/config.ts +18 -2
  61. package/src/light/lightweight_checkpoint_builder.ts +25 -6
  62. package/src/mocks/test_context.ts +11 -8
  63. package/src/orchestrator/checkpoint-proving-state.ts +14 -1
  64. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +271 -0
  65. package/src/orchestrator/epoch-proving-context.ts +101 -0
  66. package/src/orchestrator/index.ts +8 -0
  67. package/src/orchestrator/orchestrator.ts +46 -210
  68. package/src/orchestrator/proving-scheduler.ts +156 -0
  69. package/src/orchestrator/top-tree-orchestrator.ts +314 -0
  70. package/src/orchestrator/top-tree-proving-scheduler.ts +154 -0
  71. package/src/orchestrator/top-tree-proving-state.ts +220 -0
  72. package/src/prover-client/prover-client.ts +127 -2
  73. package/src/proving_broker/broker_prover_facade.ts +17 -20
  74. package/src/proving_broker/config.ts +3 -2
  75. package/src/proving_broker/index.ts +1 -0
  76. package/src/proving_broker/proving_broker.ts +27 -5
  77. package/src/proving_broker/proving_broker_database/persisted.ts +2 -2
  78. package/src/proving_broker/rpc.ts +36 -24
@@ -3,14 +3,11 @@ import {
3
3
  L1_TO_L2_MSG_SUBTREE_HEIGHT,
4
4
  L1_TO_L2_MSG_SUBTREE_ROOT_SIBLING_PATH_LENGTH,
5
5
  NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH,
6
- NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
7
6
  NUM_BASE_PARITY_PER_ROOT_PARITY,
8
7
  } from '@aztec/constants';
9
8
  import { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
10
- import { padArrayEnd } from '@aztec/foundation/collection';
11
9
  import { Fr } from '@aztec/foundation/curves/bn254';
12
- import { AbortError } from '@aztec/foundation/error';
13
- import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
10
+ import type { LoggerBindings } from '@aztec/foundation/log';
14
11
  import { promiseWithResolvers } from '@aztec/foundation/promise';
15
12
  import { assertLength } from '@aztec/foundation/serialize';
16
13
  import { pushTestData } from '@aztec/foundation/testing';
@@ -25,6 +22,7 @@ import type {
25
22
  ReadonlyWorldStateAccess,
26
23
  ServerCircuitProver,
27
24
  } from '@aztec/stdlib/interfaces/server';
25
+ import { appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
28
26
  import type { Proof } from '@aztec/stdlib/proofs';
29
27
  import {
30
28
  type BaseRollupHints,
@@ -69,6 +67,7 @@ import type { BlockProvingState } from './block-proving-state.js';
69
67
  import type { CheckpointProvingState } from './checkpoint-proving-state.js';
70
68
  import { EpochProvingState, type ProvingResult, type TreeSnapshots } from './epoch-proving-state.js';
71
69
  import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
70
+ import { TopTreeProvingScheduler } from './top-tree-proving-scheduler.js';
72
71
  import { TxProvingState } from './tx-proving-state.js';
73
72
 
74
73
  /**
@@ -85,25 +84,24 @@ import { TxProvingState } from './tx-proving-state.js';
85
84
  /**
86
85
  * The orchestrator, managing the flow of recursive proving operations required to build the rollup proof tree.
87
86
  */
88
- export class ProvingOrchestrator implements EpochProver {
89
- private provingState: EpochProvingState | undefined = undefined;
90
- private pendingProvingJobs: AbortController[] = [];
87
+ export class ProvingOrchestrator extends TopTreeProvingScheduler implements EpochProver {
88
+ protected provingState: EpochProvingState | undefined = undefined;
91
89
 
92
- private provingPromise: Promise<ProvingResult> | undefined = undefined;
90
+ protected provingPromise: Promise<ProvingResult> | undefined = undefined;
93
91
  private metrics: ProvingOrchestratorMetrics;
94
- // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
92
+
95
93
  private dbs: Map<BlockNumber, MerkleTreeWriteOperations> = new Map();
96
- private logger: Logger;
97
94
 
98
95
  constructor(
99
96
  private dbProvider: ReadonlyWorldStateAccess & ForkMerkleTreeOperations,
100
- private prover: ServerCircuitProver,
97
+ prover: ServerCircuitProver,
101
98
  private readonly proverId: EthAddress,
102
99
  private readonly cancelJobsOnStop: boolean = false,
100
+ enqueueConcurrency: number,
103
101
  telemetryClient: TelemetryClient = getTelemetryClient(),
104
102
  bindings?: LoggerBindings,
105
103
  ) {
106
- this.logger = createLogger('prover-client:orchestrator', bindings);
104
+ super(prover, enqueueConcurrency, 'prover-client:orchestrator', bindings);
107
105
  this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'ProvingOrchestrator');
108
106
  }
109
107
 
@@ -119,9 +117,24 @@ export class ProvingOrchestrator implements EpochProver {
119
117
  return this.dbs.size;
120
118
  }
121
119
 
122
- public stop(): Promise<void> {
120
+ protected override cancelInternal(): void {
123
121
  this.cancel();
124
- return Promise.resolve();
122
+ }
123
+
124
+ protected override wrapCircuitCall<T>(
125
+ circuitName: string,
126
+ fn: (signal: AbortSignal) => Promise<T>,
127
+ ): (signal: AbortSignal) => Promise<T> {
128
+ return wrapCallbackInSpan(
129
+ this.tracer,
130
+ `ProvingOrchestrator.prover.${circuitName}`,
131
+ { [Attributes.PROTOCOL_CIRCUIT_NAME]: circuitName as CircuitName },
132
+ fn,
133
+ );
134
+ }
135
+
136
+ protected override onRootRollupComplete(state: EpochProvingState) {
137
+ state.resolve({ status: 'success' });
125
138
  }
126
139
 
127
140
  public startNewEpoch(
@@ -514,11 +527,7 @@ export class ProvingOrchestrator implements EpochProver {
514
527
  * If cancelJobsOnStop is false (default), jobs remain in the broker queue and can be reused on restart/reorg.
515
528
  */
516
529
  public cancel() {
517
- if (this.cancelJobsOnStop) {
518
- for (const controller of this.pendingProvingJobs) {
519
- controller.abort();
520
- }
521
- }
530
+ this.resetSchedulerState(this.cancelJobsOnStop);
522
531
 
523
532
  this.provingState?.cancel();
524
533
 
@@ -565,76 +574,7 @@ export class ProvingOrchestrator implements EpochProver {
565
574
  return epochProofResult;
566
575
  }
567
576
 
568
- /**
569
- * Enqueue a job to be scheduled
570
- * @param provingState - The proving state object being operated on
571
- * @param jobType - The type of job to be queued
572
- * @param job - The actual job, returns a promise notifying of the job's completion
573
- */
574
- private deferredProving<T>(
575
- provingState: EpochProvingState | CheckpointProvingState | BlockProvingState,
576
- request: (signal: AbortSignal) => Promise<T>,
577
- callback: (result: T) => void | Promise<void>,
578
- ) {
579
- if (!provingState.verifyState()) {
580
- this.logger.debug(`Not enqueuing job, state no longer valid`);
581
- return;
582
- }
583
-
584
- const controller = new AbortController();
585
- this.pendingProvingJobs.push(controller);
586
-
587
- // We use a 'safeJob'. We don't want promise rejections in the proving pool, we want to capture the error here
588
- // and reject the proving job whilst keeping the event loop free of rejections
589
- const safeJob = async () => {
590
- try {
591
- // there's a delay between enqueueing this job and it actually running
592
- if (controller.signal.aborted) {
593
- return;
594
- }
595
-
596
- const result = await request(controller.signal);
597
- if (!provingState.verifyState()) {
598
- this.logger.debug(`State no longer valid, discarding result`);
599
- return;
600
- }
601
-
602
- // we could have been cancelled whilst waiting for the result
603
- // and the prover ignored the signal. Drop the result in that case
604
- if (controller.signal.aborted) {
605
- return;
606
- }
607
-
608
- await callback(result);
609
- } catch (err) {
610
- if (err instanceof AbortError) {
611
- // operation was cancelled, probably because the block was cancelled
612
- // drop this result
613
- return;
614
- }
615
-
616
- this.logger.error(`Error thrown when proving job`, err);
617
- provingState!.reject(`${err}`);
618
- } finally {
619
- const index = this.pendingProvingJobs.indexOf(controller);
620
- if (index > -1) {
621
- this.pendingProvingJobs.splice(index, 1);
622
- }
623
- }
624
- };
625
-
626
- // let the callstack unwind before adding the job to the queue
627
- setImmediate(() => void safeJob());
628
- }
629
-
630
577
  private async updateL1ToL2MessageTree(l1ToL2Messages: Fr[], db: MerkleTreeWriteOperations) {
631
- const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(
632
- l1ToL2Messages,
633
- Fr.ZERO,
634
- NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
635
- 'Too many L1 to L2 messages',
636
- );
637
-
638
578
  const lastL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
639
579
  const lastL1ToL2MessageSubtreeRootSiblingPath = assertLength(
640
580
  await getSubtreeSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, L1_TO_L2_MSG_SUBTREE_HEIGHT, db),
@@ -642,7 +582,7 @@ export class ProvingOrchestrator implements EpochProver {
642
582
  );
643
583
 
644
584
  // Update the local trees to include the new l1 to l2 messages
645
- await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
585
+ await appendL1ToL2MessagesToTree(db, l1ToL2Messages);
646
586
 
647
587
  const newL1ToL2MessageTreeSnapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
648
588
  const newL1ToL2MessageSubtreeRootSiblingPath = assertLength(
@@ -749,7 +689,7 @@ export class ProvingOrchestrator implements EpochProver {
749
689
 
750
690
  // Enqueues the public chonk verifier circuit for a given transaction index, or reuses the one already enqueued.
751
691
  // Once completed, will enqueue the the public tx base rollup.
752
- private getOrEnqueueChonkVerifier(provingState: BlockProvingState, txIndex: number) {
692
+ protected getOrEnqueueChonkVerifier(provingState: BlockProvingState, txIndex: number) {
753
693
  if (!provingState.verifyState()) {
754
694
  this.logger.debug('Not running chonk verifier circuit, state invalid');
755
695
  return;
@@ -757,7 +697,6 @@ export class ProvingOrchestrator implements EpochProver {
757
697
 
758
698
  const txProvingState = provingState.getTxProvingState(txIndex);
759
699
  const txHash = txProvingState.processedTx.hash.toString();
760
- NESTED_RECURSIVE_ROLLUP_HONK_PROOF_LENGTH;
761
700
  const handleResult = (
762
701
  result: PublicInputsAndRecursiveProof<
763
702
  PublicChonkVerifierPublicInputs,
@@ -882,7 +821,11 @@ export class ProvingOrchestrator implements EpochProver {
882
821
  },
883
822
  ),
884
823
  async result => {
885
- this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`);
824
+ this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`, {
825
+ blockNumber: provingState.blockNumber,
826
+ checkpointIndex: provingState.parentCheckpoint.index,
827
+ ...result.inputs.toInspect(),
828
+ });
886
829
 
887
830
  const leafLocation = provingState.setBlockRootRollupProof(result);
888
831
  const checkpointProvingState = provingState.parentCheckpoint;
@@ -1001,6 +944,11 @@ export class ProvingOrchestrator implements EpochProver {
1001
944
  signal => this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber),
1002
945
  ),
1003
946
  async result => {
947
+ this.logger.debug(`Completed block merge rollup proof for checkpoint ${provingState.index}`, {
948
+ checkpointIndex: provingState.index,
949
+ mergeLocation: location,
950
+ ...result.inputs.toInspect(),
951
+ });
1004
952
  provingState.setBlockMergeRollupProof(location, result);
1005
953
  await this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
1006
954
  },
@@ -1053,7 +1001,10 @@ export class ProvingOrchestrator implements EpochProver {
1053
1001
  return;
1054
1002
  }
1055
1003
 
1056
- this.logger.debug(`Completed ${rollupType} proof for checkpoint ${provingState.index}.`);
1004
+ this.logger.debug(`Completed ${rollupType} proof for checkpoint ${provingState.index}`, {
1005
+ checkpointIndex: provingState.index,
1006
+ ...result.inputs.toInspect(),
1007
+ });
1057
1008
 
1058
1009
  const leafLocation = provingState.setCheckpointRootRollupProof(result);
1059
1010
  const epochProvingState = provingState.parentEpoch;
@@ -1067,99 +1018,6 @@ export class ProvingOrchestrator implements EpochProver {
1067
1018
  );
1068
1019
  }
1069
1020
 
1070
- private enqueueCheckpointMergeRollup(provingState: EpochProvingState, location: TreeNodeLocation) {
1071
- if (!provingState.verifyState()) {
1072
- this.logger.debug('Not running checkpoint merge rollup. State no longer valid.');
1073
- return;
1074
- }
1075
-
1076
- if (!provingState.tryStartProvingCheckpointMerge(location)) {
1077
- this.logger.debug('Checkpoint merge rollup already started.');
1078
- return;
1079
- }
1080
-
1081
- const inputs = provingState.getCheckpointMergeRollupInputs(location);
1082
-
1083
- this.deferredProving(
1084
- provingState,
1085
- wrapCallbackInSpan(
1086
- this.tracer,
1087
- 'ProvingOrchestrator.prover.getCheckpointMergeRollupProof',
1088
- {
1089
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-merge' satisfies CircuitName,
1090
- },
1091
- signal => this.prover.getCheckpointMergeRollupProof(inputs, signal, provingState.epochNumber),
1092
- ),
1093
- result => {
1094
- this.logger.debug('Completed proof for checkpoint merge rollup.');
1095
- provingState.setCheckpointMergeRollupProof(location, result);
1096
- this.checkAndEnqueueNextCheckpointMergeRollup(provingState, location);
1097
- },
1098
- );
1099
- }
1100
-
1101
- private enqueueEpochPadding(provingState: EpochProvingState) {
1102
- if (!provingState.verifyState()) {
1103
- this.logger.debug('Not running epoch padding. State no longer valid.');
1104
- return;
1105
- }
1106
-
1107
- if (!provingState.tryStartProvingPaddingCheckpoint()) {
1108
- this.logger.debug('Padding checkpoint already started.');
1109
- return;
1110
- }
1111
-
1112
- this.logger.debug('Padding epoch proof with a padding block root proof.');
1113
-
1114
- const inputs = provingState.getPaddingCheckpointInputs();
1115
-
1116
- this.deferredProving(
1117
- provingState,
1118
- wrapCallbackInSpan(
1119
- this.tracer,
1120
- 'ProvingOrchestrator.prover.getCheckpointPaddingRollupProof',
1121
- {
1122
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-checkpoint-padding' satisfies CircuitName,
1123
- },
1124
- signal => this.prover.getCheckpointPaddingRollupProof(inputs, signal, provingState.epochNumber),
1125
- ),
1126
- result => {
1127
- this.logger.debug('Completed proof for padding checkpoint.');
1128
- provingState.setCheckpointPaddingProof(result);
1129
- this.checkAndEnqueueRootRollup(provingState);
1130
- },
1131
- );
1132
- }
1133
-
1134
- // Executes the root rollup circuit
1135
- private enqueueRootRollup(provingState: EpochProvingState) {
1136
- if (!provingState.verifyState()) {
1137
- this.logger.debug('Not running root rollup, state no longer valid');
1138
- return;
1139
- }
1140
-
1141
- this.logger.debug(`Preparing root rollup`);
1142
-
1143
- const inputs = provingState.getRootRollupInputs();
1144
-
1145
- this.deferredProving(
1146
- provingState,
1147
- wrapCallbackInSpan(
1148
- this.tracer,
1149
- 'ProvingOrchestrator.prover.getRootRollupProof',
1150
- {
1151
- [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-root' satisfies CircuitName,
1152
- },
1153
- signal => this.prover.getRootRollupProof(inputs, signal, provingState.epochNumber),
1154
- ),
1155
- result => {
1156
- this.logger.verbose(`Orchestrator completed root rollup for epoch ${provingState.epochNumber}`);
1157
- provingState.setRootRollupProof(result);
1158
- provingState.resolve({ status: 'success' });
1159
- },
1160
- );
1161
- }
1162
-
1163
1021
  private checkAndEnqueueNextMergeRollup(provingState: BlockProvingState, currentLocation: TreeNodeLocation) {
1164
1022
  if (!provingState.isReadyForMergeRollup(currentLocation)) {
1165
1023
  return;
@@ -1198,7 +1056,7 @@ export class ProvingOrchestrator implements EpochProver {
1198
1056
  }
1199
1057
  }
1200
1058
 
1201
- private async checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1059
+ protected async checkAndEnqueueCheckpointRootRollup(provingState: CheckpointProvingState) {
1202
1060
  if (!provingState.isReadyForCheckpointRoot()) {
1203
1061
  return;
1204
1062
  }
@@ -1206,28 +1064,6 @@ export class ProvingOrchestrator implements EpochProver {
1206
1064
  await this.enqueueCheckpointRootRollup(provingState);
1207
1065
  }
1208
1066
 
1209
- private checkAndEnqueueNextCheckpointMergeRollup(provingState: EpochProvingState, currentLocation: TreeNodeLocation) {
1210
- if (!provingState.isReadyForCheckpointMerge(currentLocation)) {
1211
- return;
1212
- }
1213
-
1214
- const parentLocation = provingState.getParentLocation(currentLocation);
1215
- if (parentLocation.level === 0) {
1216
- this.checkAndEnqueueRootRollup(provingState);
1217
- } else {
1218
- this.enqueueCheckpointMergeRollup(provingState, parentLocation);
1219
- }
1220
- }
1221
-
1222
- private checkAndEnqueueRootRollup(provingState: EpochProvingState) {
1223
- if (!provingState.isReadyForRootRollup()) {
1224
- this.logger.debug('Not ready for root rollup');
1225
- return;
1226
- }
1227
-
1228
- this.enqueueRootRollup(provingState);
1229
- }
1230
-
1231
1067
  /**
1232
1068
  * Executes the VM circuit for a public function, will enqueue the corresponding kernel if the
1233
1069
  * previous kernel is ready
@@ -1261,7 +1097,7 @@ export class ProvingOrchestrator implements EpochProver {
1261
1097
  });
1262
1098
  }
1263
1099
 
1264
- private checkAndEnqueueBaseRollup(provingState: BlockProvingState, txIndex: number) {
1100
+ protected checkAndEnqueueBaseRollup(provingState: BlockProvingState, txIndex: number) {
1265
1101
  const txProvingState = provingState.getTxProvingState(txIndex);
1266
1102
  if (!txProvingState.ready()) {
1267
1103
  return;
@@ -0,0 +1,156 @@
1
+ import { AbortError } from '@aztec/foundation/error';
2
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
+ import { SerialQueue } from '@aztec/foundation/queue';
4
+ import { sleep } from '@aztec/foundation/sleep';
5
+
6
+ /**
7
+ * Minimal surface a deferred-proving state must expose. Both `EpochProvingState` /
8
+ * `CheckpointProvingState` / `BlockProvingState` (used by `ProvingOrchestrator`) and
9
+ * `TopTreeProvingState` (used by `TopTreeOrchestrator`) satisfy it.
10
+ */
11
+ export interface ProvingStateLike {
12
+ /** Returns false once the state has been cancelled or otherwise invalidated. */
13
+ verifyState(): boolean;
14
+ /** Surfaces a proving error to the state's owner. */
15
+ reject(reason: string): void;
16
+ }
17
+
18
+ /**
19
+ * Common scheduling infrastructure shared by every orchestrator that drives broker
20
+ * proving jobs:
21
+ *
22
+ * - One `SerialQueue` (`deferredJobQueue`) acting as the enqueue-throttle.
23
+ * - A list of `AbortController`s (`pendingProvingJobs`) so a `cancel()` can abort
24
+ * in-flight broker jobs when needed.
25
+ * - A `deferredProving<T>(state, request, callback, isCancelled?)` method that wraps
26
+ * a broker request in the standard "submit, drop result if state invalidated, push
27
+ * errors to state.reject" envelope.
28
+ *
29
+ * Subclasses own their own concrete proving state and define `cancelInternal()` for
30
+ * the rest of the cleanup work (closing world-state forks, marking sub-trees
31
+ * cancelled, etc.). `stop()` lives on the base class and follows the standard pattern
32
+ * of grabbing the old queue, calling `cancelInternal()` (which recreates the queue),
33
+ * and awaiting the old queue's drain.
34
+ */
35
+ export abstract class ProvingScheduler {
36
+ protected pendingProvingJobs: AbortController[] = [];
37
+ protected logger: Logger;
38
+ private deferredJobQueue: SerialQueue;
39
+
40
+ constructor(
41
+ private readonly enqueueConcurrency: number,
42
+ loggerName = 'prover-client:proving-scheduler',
43
+ bindings?: LoggerBindings,
44
+ ) {
45
+ this.logger = createLogger(loggerName, bindings);
46
+ this.deferredJobQueue = new SerialQueue();
47
+ this.deferredJobQueue.start(this.enqueueConcurrency);
48
+ }
49
+
50
+ /** Number of broker jobs currently in flight. */
51
+ public getNumPendingProvingJobs(): number {
52
+ return this.pendingProvingJobs.length;
53
+ }
54
+
55
+ /**
56
+ * Drains the deferred-job queue, recreates it (so the subclass can be reused), and
57
+ * optionally aborts every in-flight broker job. Aborting is the right choice on
58
+ * reorg-driven cancel (where the in-flight inputs are no longer valid) and the
59
+ * wrong choice on shutdown (where leaving jobs in the broker queue lets a restart
60
+ * pick them up).
61
+ */
62
+ protected resetSchedulerState(abortJobs: boolean): void {
63
+ void this.deferredJobQueue.cancel();
64
+ this.deferredJobQueue = new SerialQueue();
65
+ this.deferredJobQueue.start(this.enqueueConcurrency);
66
+ if (abortJobs) {
67
+ for (const controller of this.pendingProvingJobs) {
68
+ controller.abort();
69
+ }
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Subclass-defined cancellation. Implementations call `resetSchedulerState(...)`
75
+ * and then do their own cleanup (close world-state forks, propagate cancel into
76
+ * the proving state, etc.).
77
+ */
78
+ protected abstract cancelInternal(): void;
79
+
80
+ /**
81
+ * Standard stop: grab the old queue, cancel (which recreates the queue), then
82
+ * await the old queue's drain so any final job tear-down has unwound before we
83
+ * return.
84
+ */
85
+ public async stop(): Promise<void> {
86
+ const oldQueue = this.deferredJobQueue;
87
+ this.cancelInternal();
88
+ await oldQueue.cancel();
89
+ }
90
+
91
+ /**
92
+ * Submits a broker request. The returned-via-callback result is dropped if the
93
+ * state has become invalid (re-org, cancellation) by the time it lands. Errors
94
+ * are routed to `state.reject` unless they are abort-driven or the state is
95
+ * already invalid (in which case they're a stale echo of the cancel).
96
+ *
97
+ * @param state - Object exposing `verifyState()` and `reject()`.
98
+ * @param request - The broker call. Receives the controller's signal.
99
+ * @param callback - Runs on success, after `verifyState()` is checked.
100
+ * @param isCancelled - Optional extra cancellation predicate (e.g. a `cancelled`
101
+ * flag the subclass maintains independently of the state). Defaults to never.
102
+ */
103
+ protected deferredProving<S extends ProvingStateLike, T>(
104
+ state: S,
105
+ request: (signal: AbortSignal) => Promise<T>,
106
+ callback: (result: T) => void | Promise<void>,
107
+ isCancelled: () => boolean = () => false,
108
+ ): void {
109
+ if (!state.verifyState()) {
110
+ this.logger.debug(`Not enqueuing job, state no longer valid`);
111
+ return;
112
+ }
113
+
114
+ const controller = new AbortController();
115
+ this.pendingProvingJobs.push(controller);
116
+
117
+ // We use a 'safeJob'. We don't want promise rejections in the proving pool — we
118
+ // want to capture the error here and reject the proving state while keeping the
119
+ // event loop free of rejections.
120
+ const safeJob = async () => {
121
+ try {
122
+ if (controller.signal.aborted) {
123
+ return;
124
+ }
125
+ const result = await request(controller.signal);
126
+ if (controller.signal.aborted || !state.verifyState() || isCancelled()) {
127
+ this.logger.debug(`State no longer valid, discarding result`);
128
+ return;
129
+ }
130
+ await callback(result);
131
+ } catch (err) {
132
+ if (err instanceof AbortError || isCancelled()) {
133
+ return;
134
+ }
135
+ if (!state.verifyState()) {
136
+ this.logger.debug(`State no longer valid, discarding error from proving job`, err);
137
+ return;
138
+ }
139
+ this.logger.error(`Error thrown when proving job`, err);
140
+ state.reject(`${err}`);
141
+ } finally {
142
+ const idx = this.pendingProvingJobs.indexOf(controller);
143
+ if (idx > -1) {
144
+ this.pendingProvingJobs.splice(idx, 1);
145
+ }
146
+ }
147
+ };
148
+
149
+ void this.deferredJobQueue.put(async () => {
150
+ void safeJob();
151
+ // Yield to the macrotask queue so Node has a chance to interleave other work
152
+ // between enqueues.
153
+ await sleep(0);
154
+ });
155
+ }
156
+ }