@aztec/prover-client 0.0.0-test.0

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 (154) hide show
  1. package/README.md +1 -0
  2. package/dest/bin/get-proof-inputs.d.ts +2 -0
  3. package/dest/bin/get-proof-inputs.d.ts.map +1 -0
  4. package/dest/bin/get-proof-inputs.js +51 -0
  5. package/dest/block_builder/index.d.ts +6 -0
  6. package/dest/block_builder/index.d.ts.map +1 -0
  7. package/dest/block_builder/index.js +1 -0
  8. package/dest/block_builder/light.d.ts +33 -0
  9. package/dest/block_builder/light.d.ts.map +1 -0
  10. package/dest/block_builder/light.js +82 -0
  11. package/dest/config.d.ts +17 -0
  12. package/dest/config.d.ts.map +1 -0
  13. package/dest/config.js +39 -0
  14. package/dest/index.d.ts +4 -0
  15. package/dest/index.d.ts.map +1 -0
  16. package/dest/index.js +2 -0
  17. package/dest/mocks/fixtures.d.ts +20 -0
  18. package/dest/mocks/fixtures.d.ts.map +1 -0
  19. package/dest/mocks/fixtures.js +77 -0
  20. package/dest/mocks/test_context.d.ts +55 -0
  21. package/dest/mocks/test_context.d.ts.map +1 -0
  22. package/dest/mocks/test_context.js +193 -0
  23. package/dest/orchestrator/block-building-helpers.d.ts +55 -0
  24. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -0
  25. package/dest/orchestrator/block-building-helpers.js +285 -0
  26. package/dest/orchestrator/block-proving-state.d.ts +76 -0
  27. package/dest/orchestrator/block-proving-state.d.ts.map +1 -0
  28. package/dest/orchestrator/block-proving-state.js +269 -0
  29. package/dest/orchestrator/epoch-proving-state.d.ts +60 -0
  30. package/dest/orchestrator/epoch-proving-state.d.ts.map +1 -0
  31. package/dest/orchestrator/epoch-proving-state.js +163 -0
  32. package/dest/orchestrator/index.d.ts +2 -0
  33. package/dest/orchestrator/index.d.ts.map +1 -0
  34. package/dest/orchestrator/index.js +1 -0
  35. package/dest/orchestrator/orchestrator.d.ts +110 -0
  36. package/dest/orchestrator/orchestrator.d.ts.map +1 -0
  37. package/dest/orchestrator/orchestrator.js +690 -0
  38. package/dest/orchestrator/orchestrator_metrics.d.ts +8 -0
  39. package/dest/orchestrator/orchestrator_metrics.d.ts.map +1 -0
  40. package/dest/orchestrator/orchestrator_metrics.js +17 -0
  41. package/dest/orchestrator/tx-proving-state.d.ts +34 -0
  42. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -0
  43. package/dest/orchestrator/tx-proving-state.js +94 -0
  44. package/dest/prover-client/factory.d.ts +6 -0
  45. package/dest/prover-client/factory.d.ts.map +1 -0
  46. package/dest/prover-client/factory.js +5 -0
  47. package/dest/prover-client/index.d.ts +3 -0
  48. package/dest/prover-client/index.d.ts.map +1 -0
  49. package/dest/prover-client/index.js +2 -0
  50. package/dest/prover-client/prover-client.d.ts +42 -0
  51. package/dest/prover-client/prover-client.d.ts.map +1 -0
  52. package/dest/prover-client/prover-client.js +110 -0
  53. package/dest/prover-client/server-epoch-prover.d.ts +28 -0
  54. package/dest/prover-client/server-epoch-prover.d.ts.map +1 -0
  55. package/dest/prover-client/server-epoch-prover.js +40 -0
  56. package/dest/proving_broker/broker_prover_facade.d.ts +46 -0
  57. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -0
  58. package/dest/proving_broker/broker_prover_facade.js +344 -0
  59. package/dest/proving_broker/config.d.ts +83 -0
  60. package/dest/proving_broker/config.d.ts.map +1 -0
  61. package/dest/proving_broker/config.js +104 -0
  62. package/dest/proving_broker/factory.d.ts +5 -0
  63. package/dest/proving_broker/factory.d.ts.map +1 -0
  64. package/dest/proving_broker/factory.js +9 -0
  65. package/dest/proving_broker/fixtures.d.ts +5 -0
  66. package/dest/proving_broker/fixtures.d.ts.map +1 -0
  67. package/dest/proving_broker/fixtures.js +12 -0
  68. package/dest/proving_broker/index.d.ts +10 -0
  69. package/dest/proving_broker/index.d.ts.map +1 -0
  70. package/dest/proving_broker/index.js +9 -0
  71. package/dest/proving_broker/proof_store/factory.d.ts +6 -0
  72. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -0
  73. package/dest/proving_broker/proof_store/factory.js +36 -0
  74. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts +14 -0
  75. package/dest/proving_broker/proof_store/gcs_proof_store.d.ts.map +1 -0
  76. package/dest/proving_broker/proof_store/gcs_proof_store.js +51 -0
  77. package/dest/proving_broker/proof_store/index.d.ts +4 -0
  78. package/dest/proving_broker/proof_store/index.d.ts.map +1 -0
  79. package/dest/proving_broker/proof_store/index.js +3 -0
  80. package/dest/proving_broker/proof_store/inline_proof_store.d.ts +15 -0
  81. package/dest/proving_broker/proof_store/inline_proof_store.d.ts.map +1 -0
  82. package/dest/proving_broker/proof_store/inline_proof_store.js +41 -0
  83. package/dest/proving_broker/proof_store/proof_store.d.ts +36 -0
  84. package/dest/proving_broker/proof_store/proof_store.d.ts.map +1 -0
  85. package/dest/proving_broker/proof_store/proof_store.js +3 -0
  86. package/dest/proving_broker/proving_agent.d.ts +46 -0
  87. package/dest/proving_broker/proving_agent.d.ts.map +1 -0
  88. package/dest/proving_broker/proving_agent.js +134 -0
  89. package/dest/proving_broker/proving_agent_instrumentation.d.ts +8 -0
  90. package/dest/proving_broker/proving_agent_instrumentation.d.ts.map +1 -0
  91. package/dest/proving_broker/proving_agent_instrumentation.js +16 -0
  92. package/dest/proving_broker/proving_broker.d.ts +64 -0
  93. package/dest/proving_broker/proving_broker.d.ts.map +1 -0
  94. package/dest/proving_broker/proving_broker.js +570 -0
  95. package/dest/proving_broker/proving_broker_database/memory.d.ts +16 -0
  96. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -0
  97. package/dest/proving_broker/proving_broker_database/memory.js +54 -0
  98. package/dest/proving_broker/proving_broker_database/persisted.d.ts +25 -0
  99. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -0
  100. package/dest/proving_broker/proving_broker_database/persisted.js +182 -0
  101. package/dest/proving_broker/proving_broker_database.d.ts +39 -0
  102. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -0
  103. package/dest/proving_broker/proving_broker_database.js +3 -0
  104. package/dest/proving_broker/proving_broker_instrumentation.d.ts +29 -0
  105. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -0
  106. package/dest/proving_broker/proving_broker_instrumentation.js +110 -0
  107. package/dest/proving_broker/proving_job_controller.d.ts +33 -0
  108. package/dest/proving_broker/proving_job_controller.d.ts.map +1 -0
  109. package/dest/proving_broker/proving_job_controller.js +166 -0
  110. package/dest/proving_broker/rpc.d.ts +27 -0
  111. package/dest/proving_broker/rpc.d.ts.map +1 -0
  112. package/dest/proving_broker/rpc.js +66 -0
  113. package/dest/test/mock_prover.d.ts +35 -0
  114. package/dest/test/mock_prover.d.ts.map +1 -0
  115. package/dest/test/mock_prover.js +82 -0
  116. package/package.json +112 -0
  117. package/src/bin/get-proof-inputs.ts +59 -0
  118. package/src/block_builder/index.ts +6 -0
  119. package/src/block_builder/light.ts +101 -0
  120. package/src/config.ts +55 -0
  121. package/src/index.ts +4 -0
  122. package/src/mocks/fixtures.ts +117 -0
  123. package/src/mocks/test_context.ts +257 -0
  124. package/src/orchestrator/block-building-helpers.ts +553 -0
  125. package/src/orchestrator/block-proving-state.ts +379 -0
  126. package/src/orchestrator/epoch-proving-state.ts +252 -0
  127. package/src/orchestrator/index.ts +1 -0
  128. package/src/orchestrator/orchestrator.ts +971 -0
  129. package/src/orchestrator/orchestrator_metrics.ts +22 -0
  130. package/src/orchestrator/tx-proving-state.ts +139 -0
  131. package/src/prover-client/factory.ts +14 -0
  132. package/src/prover-client/index.ts +2 -0
  133. package/src/prover-client/prover-client.ts +162 -0
  134. package/src/prover-client/server-epoch-prover.ts +51 -0
  135. package/src/proving_broker/broker_prover_facade.ts +585 -0
  136. package/src/proving_broker/config.ts +138 -0
  137. package/src/proving_broker/factory.ts +18 -0
  138. package/src/proving_broker/fixtures.ts +15 -0
  139. package/src/proving_broker/index.ts +9 -0
  140. package/src/proving_broker/proof_store/factory.ts +42 -0
  141. package/src/proving_broker/proof_store/gcs_proof_store.ts +72 -0
  142. package/src/proving_broker/proof_store/index.ts +3 -0
  143. package/src/proving_broker/proof_store/inline_proof_store.ts +63 -0
  144. package/src/proving_broker/proof_store/proof_store.ts +54 -0
  145. package/src/proving_broker/proving_agent.ts +181 -0
  146. package/src/proving_broker/proving_agent_instrumentation.ts +21 -0
  147. package/src/proving_broker/proving_broker.ts +687 -0
  148. package/src/proving_broker/proving_broker_database/memory.ts +63 -0
  149. package/src/proving_broker/proving_broker_database/persisted.ts +218 -0
  150. package/src/proving_broker/proving_broker_database.ts +44 -0
  151. package/src/proving_broker/proving_broker_instrumentation.ts +145 -0
  152. package/src/proving_broker/proving_job_controller.ts +194 -0
  153. package/src/proving_broker/rpc.ts +95 -0
  154. package/src/test/mock_prover.ts +253 -0
@@ -0,0 +1,570 @@
1
+ function _ts_decorate(decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ }
7
+ import { createLogger } from '@aztec/foundation/log';
8
+ import { RunningPromise, promiseWithResolvers } from '@aztec/foundation/promise';
9
+ import { PriorityMemoryQueue } from '@aztec/foundation/queue';
10
+ import { Timer } from '@aztec/foundation/timer';
11
+ import { ProvingRequestType } from '@aztec/stdlib/proofs';
12
+ import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
13
+ import assert from 'assert';
14
+ import { defaultProverBrokerConfig } from './config.js';
15
+ import { ProvingBrokerInstrumentation } from './proving_broker_instrumentation.js';
16
+ /**
17
+ * A broker that manages proof requests and distributes them to workers based on their priority.
18
+ * It takes a backend that is responsible for storing and retrieving proof requests and results.
19
+ */ export class ProvingBroker {
20
+ database;
21
+ logger;
22
+ queues;
23
+ // holds a copy of the database in memory in order to quickly fulfill requests
24
+ // this is fine because this broker is the only one that can modify the database
25
+ jobsCache;
26
+ // as above, but for results
27
+ resultsCache;
28
+ // tracks when each job was enqueued
29
+ enqueuedAt;
30
+ // keeps track of which jobs are currently being processed
31
+ // in the event of a crash this information is lost, but that's ok
32
+ // the next time the broker starts it will recreate jobsCache and still
33
+ // accept results from the workers
34
+ inProgress;
35
+ // keep track of which proving job has been retried
36
+ retries;
37
+ // a map of promises that will be resolved when a job is settled
38
+ promises;
39
+ cleanupPromise;
40
+ msTimeSource;
41
+ jobTimeoutMs;
42
+ maxRetries;
43
+ instrumentation;
44
+ tracer;
45
+ completedJobNotifications;
46
+ /**
47
+ * The broker keeps track of the highest epoch its seen.
48
+ * This information is used for garbage collection: once it reaches the next epoch, it can start pruning the database of old state.
49
+ * It is important that this value is initialised to zero. This ensures that we don't delete any old jobs until the current
50
+ * process instance receives a job request informing it of the actual current highest epoch
51
+ * Example:
52
+ * proving epoch 11 - the broker will wipe all jobs for epochs 9 and lower
53
+ * finished proving epoch 11 and got first job for epoch 12 -> the broker will wipe all settled jobs for epochs 10 and lower
54
+ * reorged back to end of epoch 10 -> epoch 11 is skipped and epoch 12 starts -> the broker will wipe all settled jobs for epochs 10 and lower
55
+ */ epochHeight;
56
+ maxEpochsToKeepResultsFor;
57
+ started;
58
+ constructor(database, { proverBrokerJobTimeoutMs, proverBrokerPollIntervalMs, proverBrokerJobMaxRetries, proverBrokerMaxEpochsToKeepResultsFor } = defaultProverBrokerConfig, client = getTelemetryClient(), logger = createLogger('prover-client:proving-broker')){
59
+ this.database = database;
60
+ this.logger = logger;
61
+ this.queues = {
62
+ [ProvingRequestType.PUBLIC_VM]: new PriorityMemoryQueue(provingJobComparator),
63
+ [ProvingRequestType.TUBE_PROOF]: new PriorityMemoryQueue(provingJobComparator),
64
+ [ProvingRequestType.PRIVATE_BASE_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
65
+ [ProvingRequestType.PUBLIC_BASE_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
66
+ [ProvingRequestType.MERGE_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
67
+ [ProvingRequestType.ROOT_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
68
+ [ProvingRequestType.BLOCK_MERGE_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
69
+ [ProvingRequestType.BLOCK_ROOT_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
70
+ [ProvingRequestType.SINGLE_TX_BLOCK_ROOT_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
71
+ [ProvingRequestType.EMPTY_BLOCK_ROOT_ROLLUP]: new PriorityMemoryQueue(provingJobComparator),
72
+ [ProvingRequestType.BASE_PARITY]: new PriorityMemoryQueue(provingJobComparator),
73
+ [ProvingRequestType.ROOT_PARITY]: new PriorityMemoryQueue(provingJobComparator)
74
+ };
75
+ this.jobsCache = new Map();
76
+ this.resultsCache = new Map();
77
+ this.enqueuedAt = new Map();
78
+ this.inProgress = new Map();
79
+ this.retries = new Map();
80
+ this.promises = new Map();
81
+ this.msTimeSource = ()=>Date.now();
82
+ this.completedJobNotifications = [];
83
+ this.epochHeight = 0;
84
+ this.maxEpochsToKeepResultsFor = 1;
85
+ this.started = false;
86
+ this.measureQueueDepth = (type)=>{
87
+ return this.queues[type].length();
88
+ };
89
+ this.countActiveJobs = (type)=>{
90
+ let count = 0;
91
+ for (const { id } of this.inProgress.values()){
92
+ const job = this.jobsCache.get(id);
93
+ if (job?.type === type) {
94
+ count++;
95
+ }
96
+ }
97
+ return count;
98
+ };
99
+ this.tracer = client.getTracer('ProvingBroker');
100
+ this.instrumentation = new ProvingBrokerInstrumentation(client);
101
+ this.cleanupPromise = new RunningPromise(this.cleanupPass.bind(this), this.logger, proverBrokerPollIntervalMs);
102
+ this.jobTimeoutMs = proverBrokerJobTimeoutMs;
103
+ this.maxRetries = proverBrokerJobMaxRetries;
104
+ this.maxEpochsToKeepResultsFor = proverBrokerMaxEpochsToKeepResultsFor;
105
+ }
106
+ measureQueueDepth;
107
+ countActiveJobs;
108
+ async start() {
109
+ if (this.started) {
110
+ this.logger.info('Proving Broker already started');
111
+ return Promise.resolve();
112
+ }
113
+ this.logger.info('Proving Broker started');
114
+ for await (const [item, result] of this.database.allProvingJobs()){
115
+ this.logger.info(`Restoring proving job id=${item.id} settled=${!!result}`, {
116
+ provingJobId: item.id,
117
+ status: result ? result.status : 'pending'
118
+ });
119
+ this.jobsCache.set(item.id, item);
120
+ this.promises.set(item.id, promiseWithResolvers());
121
+ if (result) {
122
+ this.promises.get(item.id).resolve(result);
123
+ this.resultsCache.set(item.id, result);
124
+ } else {
125
+ this.enqueueJobInternal(item);
126
+ }
127
+ }
128
+ this.cleanupPromise.start();
129
+ this.instrumentation.monitorQueueDepth(this.measureQueueDepth);
130
+ this.instrumentation.monitorActiveJobs(this.countActiveJobs);
131
+ this.started = true;
132
+ }
133
+ async stop() {
134
+ if (!this.started) {
135
+ this.logger.warn('ProvingBroker not started');
136
+ return Promise.resolve();
137
+ }
138
+ await this.cleanupPromise.stop();
139
+ }
140
+ enqueueProvingJob(job) {
141
+ return this.#enqueueProvingJob(job);
142
+ }
143
+ cancelProvingJob(id) {
144
+ return this.#cancelProvingJob(id);
145
+ }
146
+ getProvingJobStatus(id) {
147
+ return Promise.resolve(this.#getProvingJobStatus(id));
148
+ }
149
+ getCompletedJobs(ids) {
150
+ return this.#getCompletedJobs(ids);
151
+ }
152
+ getProvingJob(filter) {
153
+ return Promise.resolve(this.#getProvingJob(filter));
154
+ }
155
+ reportProvingJobSuccess(id, value, filter) {
156
+ return this.#reportProvingJobSuccess(id, value, filter);
157
+ }
158
+ reportProvingJobError(id, err, retry = false, filter) {
159
+ return this.#reportProvingJobError(id, err, retry, filter);
160
+ }
161
+ reportProvingJobProgress(id, startedAt, filter) {
162
+ return Promise.resolve(this.#reportProvingJobProgress(id, startedAt, filter));
163
+ }
164
+ async #enqueueProvingJob(job) {
165
+ // We return the job status at the start of this call
166
+ const jobStatus = this.#getProvingJobStatus(job.id);
167
+ if (this.jobsCache.has(job.id)) {
168
+ const existing = this.jobsCache.get(job.id);
169
+ assert.deepStrictEqual(job, existing, 'Duplicate proving job ID');
170
+ this.logger.warn(`Cached proving job id=${job.id} epochNumber=${job.epochNumber}. Not enqueuing again`, {
171
+ provingJobId: job.id
172
+ });
173
+ this.instrumentation.incCachedJobs(job.type);
174
+ return jobStatus;
175
+ }
176
+ if (this.isJobStale(job)) {
177
+ this.logger.warn(`Tried enqueueing stale proving job id=${job.id} epochNumber=${job.epochNumber}`, {
178
+ provingJobId: job.id
179
+ });
180
+ throw new Error(`Epoch too old: job epoch ${job.epochNumber}, current epoch: ${this.epochHeight}`);
181
+ }
182
+ this.logger.info(`New proving job id=${job.id} epochNumber=${job.epochNumber}`, {
183
+ provingJobId: job.id
184
+ });
185
+ try {
186
+ // do this first so it acts as a "lock". If this job is enqueued again while we're saving it the if at the top will catch it.
187
+ this.jobsCache.set(job.id, job);
188
+ await this.database.addProvingJob(job);
189
+ this.enqueueJobInternal(job);
190
+ this.instrumentation.incTotalJobs(job.type);
191
+ } catch (err) {
192
+ this.logger.error(`Failed to save proving job id=${job.id}: ${err}`, err, {
193
+ provingJobId: job.id
194
+ });
195
+ this.jobsCache.delete(job.id);
196
+ throw err;
197
+ }
198
+ return jobStatus;
199
+ }
200
+ async #cancelProvingJob(id) {
201
+ if (!this.jobsCache.has(id)) {
202
+ this.logger.warn(`Can't cancel a job that doesn't exist id=${id}`, {
203
+ provingJobId: id
204
+ });
205
+ return;
206
+ }
207
+ // notify listeners of the cancellation
208
+ if (!this.resultsCache.has(id)) {
209
+ this.logger.info(`Cancelling job id=${id}`, {
210
+ provingJobId: id
211
+ });
212
+ await this.#reportProvingJobError(id, 'Aborted', false);
213
+ }
214
+ }
215
+ cleanUpProvingJobState(ids) {
216
+ for (const id of ids){
217
+ this.jobsCache.delete(id);
218
+ this.promises.delete(id);
219
+ this.resultsCache.delete(id);
220
+ this.inProgress.delete(id);
221
+ this.retries.delete(id);
222
+ }
223
+ }
224
+ #getProvingJobStatus(id) {
225
+ const result = this.resultsCache.get(id);
226
+ if (result) {
227
+ return result;
228
+ } else {
229
+ // no result yet, check if we know the item
230
+ const item = this.jobsCache.get(id);
231
+ if (!item) {
232
+ return {
233
+ status: 'not-found'
234
+ };
235
+ }
236
+ return {
237
+ status: this.inProgress.has(id) ? 'in-progress' : 'in-queue'
238
+ };
239
+ }
240
+ }
241
+ #getCompletedJobs(ids) {
242
+ const completedJobs = ids.filter((id)=>this.resultsCache.has(id));
243
+ const notifications = this.completedJobNotifications;
244
+ this.completedJobNotifications = [];
245
+ return Promise.resolve(notifications.concat(completedJobs));
246
+ }
247
+ // eslint-disable-next-line require-await
248
+ #getProvingJob(filter = {
249
+ allowList: []
250
+ }) {
251
+ const allowedProofs = Array.isArray(filter.allowList) && filter.allowList.length > 0 ? [
252
+ ...filter.allowList
253
+ ] : Object.values(ProvingRequestType).filter((x)=>typeof x === 'number');
254
+ allowedProofs.sort(proofTypeComparator);
255
+ for (const proofType of allowedProofs){
256
+ const queue = this.queues[proofType];
257
+ let enqueuedJob;
258
+ // exhaust the queue and make sure we're not sending a job that's already in progress
259
+ // or has already been completed
260
+ // this can happen if the broker crashes and restarts
261
+ // it's possible agents will report progress or results for jobs that are in the queue (after the restart)
262
+ while(enqueuedJob = queue.getImmediate()){
263
+ const job = this.jobsCache.get(enqueuedJob.id);
264
+ if (job && !this.inProgress.has(enqueuedJob.id) && !this.resultsCache.has(enqueuedJob.id)) {
265
+ const time = this.msTimeSource();
266
+ this.inProgress.set(job.id, {
267
+ id: job.id,
268
+ startedAt: time,
269
+ lastUpdatedAt: time
270
+ });
271
+ const enqueuedAt = this.enqueuedAt.get(job.id);
272
+ if (enqueuedAt) {
273
+ this.instrumentation.recordJobWait(job.type, enqueuedAt);
274
+ }
275
+ return {
276
+ job,
277
+ time
278
+ };
279
+ }
280
+ }
281
+ }
282
+ return undefined;
283
+ }
284
+ async #reportProvingJobError(id, err, retry = false, filter) {
285
+ const info = this.inProgress.get(id);
286
+ const item = this.jobsCache.get(id);
287
+ const retries = this.retries.get(id) ?? 0;
288
+ if (!item) {
289
+ this.logger.warn(`Can't set error on unknown proving job id=${id} err=${err}`, {
290
+ provingJoId: id
291
+ });
292
+ return;
293
+ }
294
+ if (!info) {
295
+ this.logger.warn(`Proving job id=${id} type=${ProvingRequestType[item.type]} not in the in-progress set`, {
296
+ provingJobId: id
297
+ });
298
+ } else {
299
+ this.inProgress.delete(id);
300
+ }
301
+ if (this.resultsCache.has(id)) {
302
+ this.logger.warn(`Proving job id=${id} is already settled, ignoring err=${err}`, {
303
+ provingJobId: id
304
+ });
305
+ return this.#getProvingJob(filter);
306
+ }
307
+ if (retry && retries + 1 < this.maxRetries && !this.isJobStale(item)) {
308
+ this.logger.info(`Retrying proving job id=${id} type=${ProvingRequestType[item.type]} retry=${retries + 1} err=${err}`, {
309
+ provingJobId: id
310
+ });
311
+ // assign another job to this agent
312
+ // do this first, before we put the failed job back in the queue
313
+ const maybeAnotherJob = this.#getProvingJob(filter);
314
+ this.retries.set(id, retries + 1);
315
+ this.enqueueJobInternal(item);
316
+ this.instrumentation.incRetriedJobs(item.type);
317
+ return maybeAnotherJob;
318
+ }
319
+ this.logger.info(`Marking proving job as failed id=${id} type=${ProvingRequestType[item.type]} totalAttempts=${retries + 1} err=${err}`, {
320
+ provingJobId: id
321
+ });
322
+ // save the result to the cache and notify clients of the job status
323
+ // this should work even if our database breaks because the result is cached in memory
324
+ const result = {
325
+ status: 'rejected',
326
+ reason: String(err)
327
+ };
328
+ this.resultsCache.set(id, result);
329
+ this.promises.get(id).resolve(result);
330
+ this.completedJobNotifications.push(id);
331
+ this.instrumentation.incRejectedJobs(item.type);
332
+ if (info) {
333
+ const duration = this.msTimeSource() - info.startedAt;
334
+ this.instrumentation.recordJobDuration(item.type, duration);
335
+ }
336
+ try {
337
+ await this.database.setProvingJobError(id, err);
338
+ } catch (saveErr) {
339
+ this.logger.error(`Failed to save proving job error status id=${id} jobErr=${err}`, saveErr, {
340
+ provingJobId: id
341
+ });
342
+ throw saveErr;
343
+ }
344
+ return this.#getProvingJob(filter);
345
+ }
346
+ #reportProvingJobProgress(id, startedAt, filter) {
347
+ const job = this.jobsCache.get(id);
348
+ if (!job) {
349
+ this.logger.warn(`Proving job id=${id} does not exist`, {
350
+ provingJobId: id
351
+ });
352
+ return this.#getProvingJob(filter);
353
+ }
354
+ if (this.resultsCache.has(id)) {
355
+ this.logger.warn(`Proving job id=${id} has already been completed`, {
356
+ provingJobId: id
357
+ });
358
+ return this.#getProvingJob(filter);
359
+ }
360
+ const metadata = this.inProgress.get(id);
361
+ const now = this.msTimeSource();
362
+ if (!metadata) {
363
+ this.logger.warn(`Proving job id=${id} type=${ProvingRequestType[job.type]} not found in the in-progress cache, adding it`, {
364
+ provingJobId: id
365
+ });
366
+ // the queue will still contain the item at this point!
367
+ // we need to be careful when popping off the queue to make sure we're not sending
368
+ // a job that's already in progress
369
+ this.inProgress.set(id, {
370
+ id,
371
+ startedAt,
372
+ lastUpdatedAt: this.msTimeSource()
373
+ });
374
+ return undefined;
375
+ } else if (startedAt <= metadata.startedAt) {
376
+ if (startedAt < metadata.startedAt) {
377
+ this.logger.info(`Proving job id=${id} type=${ProvingRequestType[job.type]} startedAt=${startedAt} older agent has taken job`, {
378
+ provingJobId: id
379
+ });
380
+ } else {
381
+ this.logger.debug(`Proving job id=${id} type=${ProvingRequestType[job.type]} heartbeat`, {
382
+ provingJobId: id
383
+ });
384
+ }
385
+ metadata.startedAt = startedAt;
386
+ metadata.lastUpdatedAt = now;
387
+ return undefined;
388
+ }
389
+ this.logger.warn(`Proving job id=${id} type=${ProvingRequestType[job.type]} already being worked on by another agent. Sending new one`, {
390
+ provingJobId: id
391
+ });
392
+ return this.#getProvingJob(filter);
393
+ }
394
+ async #reportProvingJobSuccess(id, value, filter) {
395
+ const info = this.inProgress.get(id);
396
+ const item = this.jobsCache.get(id);
397
+ const retries = this.retries.get(id) ?? 0;
398
+ if (!item) {
399
+ this.logger.warn(`Proving job id=${id} not found`, {
400
+ provingJobId: id
401
+ });
402
+ return;
403
+ }
404
+ if (!info) {
405
+ this.logger.warn(`Proving job id=${id} type=${ProvingRequestType[item.type]} not in the in-progress set`, {
406
+ provingJobId: id
407
+ });
408
+ } else {
409
+ this.inProgress.delete(id);
410
+ }
411
+ if (this.resultsCache.has(id)) {
412
+ this.logger.warn(`Proving job id=${id} already settled, ignoring result`, {
413
+ provingJobId: id
414
+ });
415
+ return;
416
+ }
417
+ this.logger.info(`Proving job complete id=${id} type=${ProvingRequestType[item.type]} totalAttempts=${retries + 1}`, {
418
+ provingJobId: id
419
+ });
420
+ // save result to our local cache and notify clients
421
+ // if save to database fails, that's ok because we have the result in memory
422
+ // if the broker crashes and needs the result again, we're covered because we can just recompute it
423
+ const result = {
424
+ status: 'fulfilled',
425
+ value
426
+ };
427
+ this.resultsCache.set(id, result);
428
+ this.promises.get(id).resolve(result);
429
+ this.completedJobNotifications.push(id);
430
+ this.instrumentation.incResolvedJobs(item.type);
431
+ if (info) {
432
+ const duration = this.msTimeSource() - info.startedAt;
433
+ this.instrumentation.recordJobDuration(item.type, duration);
434
+ }
435
+ try {
436
+ await this.database.setProvingJobResult(id, value);
437
+ } catch (saveErr) {
438
+ this.logger.error(`Failed to save proving job result id=${id}`, saveErr, {
439
+ provingJobId: id
440
+ });
441
+ throw saveErr;
442
+ }
443
+ return this.#getProvingJob(filter);
444
+ }
445
+ async cleanupPass() {
446
+ this.cleanupStaleJobs();
447
+ this.reEnqueueExpiredJobs();
448
+ const oldestEpochToKeep = this.oldestEpochToKeep();
449
+ if (oldestEpochToKeep > 0) {
450
+ await this.database.deleteAllProvingJobsOlderThanEpoch(oldestEpochToKeep);
451
+ this.logger.trace(`Deleted all epochs older than ${oldestEpochToKeep}`);
452
+ }
453
+ }
454
+ cleanupStaleJobs() {
455
+ const jobIds = Array.from(this.jobsCache.keys());
456
+ const jobsToClean = [];
457
+ for (const id of jobIds){
458
+ const job = this.jobsCache.get(id);
459
+ if (this.isJobStale(job)) {
460
+ jobsToClean.push(id);
461
+ }
462
+ }
463
+ if (jobsToClean.length > 0) {
464
+ this.cleanUpProvingJobState(jobsToClean);
465
+ this.logger.info(`Cleaned up jobs=${jobsToClean.length}`);
466
+ }
467
+ }
468
+ reEnqueueExpiredJobs() {
469
+ const inProgressEntries = Array.from(this.inProgress.entries());
470
+ for (const [id, metadata] of inProgressEntries){
471
+ const item = this.jobsCache.get(id);
472
+ if (!item) {
473
+ this.logger.warn(`Proving job id=${id} not found. Removing it from the queue.`, {
474
+ provingJobId: id
475
+ });
476
+ this.inProgress.delete(id);
477
+ continue;
478
+ }
479
+ const now = this.msTimeSource();
480
+ const msSinceLastUpdate = now - metadata.lastUpdatedAt;
481
+ if (msSinceLastUpdate >= this.jobTimeoutMs) {
482
+ this.logger.warn(`Proving job id=${id} timed out. Adding it back to the queue.`, {
483
+ provingJobId: id
484
+ });
485
+ this.inProgress.delete(id);
486
+ this.enqueueJobInternal(item);
487
+ this.instrumentation.incTimedOutJobs(item.type);
488
+ }
489
+ }
490
+ }
491
+ enqueueJobInternal(job) {
492
+ if (!this.promises.has(job.id)) {
493
+ this.promises.set(job.id, promiseWithResolvers());
494
+ }
495
+ this.queues[job.type].put({
496
+ epochNumber: job.epochNumber,
497
+ id: job.id
498
+ });
499
+ this.enqueuedAt.set(job.id, new Timer());
500
+ this.epochHeight = Math.max(this.epochHeight, job.epochNumber);
501
+ }
502
+ isJobStale(job) {
503
+ return job.epochNumber < this.oldestEpochToKeep();
504
+ }
505
+ oldestEpochToKeep() {
506
+ return this.epochHeight - this.maxEpochsToKeepResultsFor;
507
+ }
508
+ }
509
+ _ts_decorate([
510
+ trackSpan('ProvingBroker.cleanupPass')
511
+ ], ProvingBroker.prototype, "cleanupPass", null);
512
+ /**
513
+ * Compares two proving jobs and selects which one's more important
514
+ * @param a - A proving job
515
+ * @param b - Another proving job
516
+ * @returns A number indicating the relative priority of the two proving jobs
517
+ */ function provingJobComparator(a, b) {
518
+ if (a.epochNumber < b.epochNumber) {
519
+ return -1;
520
+ } else if (a.epochNumber > b.epochNumber) {
521
+ return 1;
522
+ } else {
523
+ return 0;
524
+ }
525
+ }
526
+ /**
527
+ * Compares two proofs and selects which one's more important.
528
+ * If some proofs does not exist in the priority array then it's considered the least important.
529
+ *
530
+ * @param a - A proof type
531
+ * @param b - Another proof type
532
+ * @returns A number indicating the relative priority of the two proof types
533
+ */ function proofTypeComparator(a, b) {
534
+ const indexOfA = PROOF_TYPES_IN_PRIORITY_ORDER.indexOf(a);
535
+ const indexOfB = PROOF_TYPES_IN_PRIORITY_ORDER.indexOf(b);
536
+ if (indexOfA === indexOfB) {
537
+ return 0;
538
+ } else if (indexOfA === -1) {
539
+ // a is some new proof that didn't get added to the array
540
+ // b is more important because we know about it
541
+ return 1;
542
+ } else if (indexOfB === -1) {
543
+ // the opposite of the previous if branch
544
+ return -1;
545
+ } else if (indexOfA < indexOfB) {
546
+ return -1;
547
+ } else {
548
+ return 1;
549
+ }
550
+ }
551
+ /**
552
+ * Relative priority of each proof type. Proofs higher up on the list are more important and should be prioritized
553
+ * over proofs lower on the list.
554
+ *
555
+ * The aim is that this will speed up block proving as the closer we get to a block's root proof the more likely it
556
+ * is to get picked up by agents
557
+ */ const PROOF_TYPES_IN_PRIORITY_ORDER = [
558
+ ProvingRequestType.BLOCK_ROOT_ROLLUP,
559
+ ProvingRequestType.SINGLE_TX_BLOCK_ROOT_ROLLUP,
560
+ ProvingRequestType.BLOCK_MERGE_ROLLUP,
561
+ ProvingRequestType.ROOT_ROLLUP,
562
+ ProvingRequestType.MERGE_ROLLUP,
563
+ ProvingRequestType.PUBLIC_BASE_ROLLUP,
564
+ ProvingRequestType.PRIVATE_BASE_ROLLUP,
565
+ ProvingRequestType.PUBLIC_VM,
566
+ ProvingRequestType.TUBE_PROOF,
567
+ ProvingRequestType.ROOT_PARITY,
568
+ ProvingRequestType.BASE_PARITY,
569
+ ProvingRequestType.EMPTY_BLOCK_ROOT_ROLLUP
570
+ ];
@@ -0,0 +1,16 @@
1
+ import { type ProofUri, type ProvingJob, type ProvingJobId, type ProvingJobSettledResult } from '@aztec/stdlib/interfaces/server';
2
+ import type { ProvingBrokerDatabase } from '../proving_broker_database.js';
3
+ export declare class InMemoryBrokerDatabase implements ProvingBrokerDatabase {
4
+ private jobs;
5
+ private results;
6
+ getProvingJob(id: ProvingJobId): ProvingJob | undefined;
7
+ getProvingJobResult(id: ProvingJobId): ProvingJobSettledResult | undefined;
8
+ addProvingJob(job: ProvingJob): Promise<void>;
9
+ setProvingJobResult(id: ProvingJobId, value: ProofUri): Promise<void>;
10
+ setProvingJobError(id: ProvingJobId, reason: string): Promise<void>;
11
+ deleteProvingJobs(ids: ProvingJobId[]): Promise<void>;
12
+ deleteAllProvingJobsOlderThanEpoch(epochNumber: number): Promise<void>;
13
+ allProvingJobs(): AsyncIterableIterator<[ProvingJob, ProvingJobSettledResult | undefined]>;
14
+ close(): Promise<void>;
15
+ }
16
+ //# sourceMappingURL=memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../../src/proving_broker/proving_broker_database/memory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAE7B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAE3E,qBAAa,sBAAuB,YAAW,qBAAqB;IAClE,OAAO,CAAC,IAAI,CAAuC;IACnD,OAAO,CAAC,OAAO,CAAoD;IAEnE,aAAa,CAAC,EAAE,EAAE,YAAY,GAAG,UAAU,GAAG,SAAS;IAIvD,mBAAmB,CAAC,EAAE,EAAE,YAAY,GAAG,uBAAuB,GAAG,SAAS;IAI1E,aAAa,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAK7C,mBAAmB,CAAC,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,kBAAkB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKnE,iBAAiB,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQrD,kCAAkC,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ/D,cAAc,IAAI,qBAAqB,CAAC,CAAC,UAAU,EAAE,uBAAuB,GAAG,SAAS,CAAC,CAAC;IAMjG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAGvB"}
@@ -0,0 +1,54 @@
1
+ import { getEpochFromProvingJobId } from '@aztec/stdlib/interfaces/server';
2
+ export class InMemoryBrokerDatabase {
3
+ jobs = new Map();
4
+ results = new Map();
5
+ getProvingJob(id) {
6
+ return this.jobs.get(id);
7
+ }
8
+ getProvingJobResult(id) {
9
+ return this.results.get(id);
10
+ }
11
+ addProvingJob(job) {
12
+ this.jobs.set(job.id, job);
13
+ return Promise.resolve();
14
+ }
15
+ setProvingJobResult(id, value) {
16
+ this.results.set(id, {
17
+ status: 'fulfilled',
18
+ value
19
+ });
20
+ return Promise.resolve();
21
+ }
22
+ setProvingJobError(id, reason) {
23
+ this.results.set(id, {
24
+ status: 'rejected',
25
+ reason
26
+ });
27
+ return Promise.resolve();
28
+ }
29
+ deleteProvingJobs(ids) {
30
+ for (const id of ids){
31
+ this.jobs.delete(id);
32
+ this.results.delete(id);
33
+ }
34
+ return Promise.resolve();
35
+ }
36
+ deleteAllProvingJobsOlderThanEpoch(epochNumber) {
37
+ const toDelete = [
38
+ ...Array.from(this.jobs.keys()).filter((x)=>getEpochFromProvingJobId(x) < epochNumber),
39
+ ...Array.from(this.results.keys()).filter((x)=>getEpochFromProvingJobId(x) < epochNumber)
40
+ ];
41
+ return this.deleteProvingJobs(toDelete);
42
+ }
43
+ async *allProvingJobs() {
44
+ for await (const item of this.jobs.values()){
45
+ yield [
46
+ item,
47
+ this.results.get(item.id)
48
+ ];
49
+ }
50
+ }
51
+ close() {
52
+ return Promise.resolve();
53
+ }
54
+ }
@@ -0,0 +1,25 @@
1
+ import { type Logger } from '@aztec/foundation/log';
2
+ import { type ProofUri, ProvingJob, type ProvingJobId, ProvingJobSettledResult } from '@aztec/stdlib/interfaces/server';
3
+ import { type TelemetryClient } from '@aztec/telemetry-client';
4
+ import type { ProverBrokerConfig } from '../config.js';
5
+ import type { ProvingBrokerDatabase } from '../proving_broker_database.js';
6
+ export declare class KVBrokerDatabase implements ProvingBrokerDatabase {
7
+ private epochs;
8
+ private config;
9
+ private logger;
10
+ private metrics;
11
+ private batchQueue;
12
+ private constructor();
13
+ commitWrites(items: Array<ProvingJob | [ProvingJobId, ProvingJobSettledResult]>, epochNumber: number): Promise<void>;
14
+ private estimateSize;
15
+ static new(config: ProverBrokerConfig, client?: TelemetryClient, logger?: Logger): Promise<KVBrokerDatabase>;
16
+ private start;
17
+ close(): Promise<void>;
18
+ deleteAllProvingJobsOlderThanEpoch(epochNumber: number): Promise<void>;
19
+ addProvingJob(job: ProvingJob): Promise<void>;
20
+ allProvingJobs(): AsyncIterableIterator<[ProvingJob, ProvingJobSettledResult | undefined]>;
21
+ setProvingJobError(id: ProvingJobId, reason: string): Promise<void>;
22
+ setProvingJobResult(id: ProvingJobId, value: ProofUri): Promise<void>;
23
+ private getEpochDatabase;
24
+ }
25
+ //# sourceMappingURL=persisted.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persisted.d.ts","sourceRoot":"","sources":["../../../src/proving_broker/proving_broker_database/persisted.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,MAAM,EAAgB,MAAM,uBAAuB,CAAC;AAIlE,OAAO,EACL,KAAK,QAAQ,EACb,UAAU,EACV,KAAK,YAAY,EACjB,uBAAuB,EAExB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAA2B,KAAK,eAAe,EAAsB,MAAM,yBAAyB,CAAC;AAK5G,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAwD3E,qBAAa,gBAAiB,YAAW,qBAAqB;IAM1D,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,MAAM;IAEd,OAAO,CAAC,MAAM;IARhB,OAAO,CAAC,OAAO,CAAc;IAE7B,OAAO,CAAC,UAAU,CAA2E;IAE7F,OAAO;IAuBM,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,UAAU,GAAG,CAAC,YAAY,EAAE,uBAAuB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM;YAQnG,YAAY;WASN,GAAG,CACrB,MAAM,EAAE,kBAAkB,EAC1B,MAAM,GAAE,eAAsC,EAC9C,MAAM,SAAwD;IAgChE,OAAO,CAAC,KAAK;IAIP,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtB,kCAAkC,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAa5E,aAAa,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAItC,cAAc,IAAI,qBAAqB,CAAC,CAAC,UAAU,EAAE,uBAAuB,GAAG,SAAS,CAAC,CAAC;IAOjG,kBAAkB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAInE,mBAAmB,CAAC,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;YAIvD,gBAAgB;CAoB/B"}