@aztec/sequencer-client 0.0.1-commit.b9865e97 → 0.0.1-commit.be03c316

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/README.md +27 -27
  2. package/dest/client/sequencer-client.d.ts +16 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +17 -12
  5. package/dest/config.d.ts +6 -2
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +23 -14
  8. package/dest/global_variable_builder/fee_predictor.d.ts +1 -1
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -1
  10. package/dest/global_variable_builder/fee_predictor.js +11 -1
  11. package/dest/global_variable_builder/fee_provider.d.ts +1 -1
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -1
  13. package/dest/global_variable_builder/fee_provider.js +27 -5
  14. package/dest/global_variable_builder/global_builder.d.ts +3 -16
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +2 -25
  17. package/dest/index.d.ts +2 -2
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +1 -1
  20. package/dest/publisher/config.d.ts +5 -1
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +11 -1
  23. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  24. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  25. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  26. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +48 -8
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -1
  29. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +2 -2
  30. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -1
  31. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +4 -2
  32. package/dest/publisher/l1_tx_failed_store/index.d.ts +2 -2
  33. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -1
  34. package/dest/publisher/l1_tx_failed_store/index.js +1 -0
  35. package/dest/publisher/sequencer-publisher.d.ts +34 -6
  36. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  37. package/dest/publisher/sequencer-publisher.js +362 -61
  38. package/dest/publisher/write_json.d.ts +11 -0
  39. package/dest/publisher/write_json.d.ts.map +1 -0
  40. package/dest/publisher/write_json.js +57 -0
  41. package/dest/sequencer/automine/automine_factory.d.ts +5 -3
  42. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -1
  43. package/dest/sequencer/automine/automine_factory.js +2 -1
  44. package/dest/sequencer/automine/automine_sequencer.d.ts +43 -5
  45. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -1
  46. package/dest/sequencer/automine/automine_sequencer.js +199 -18
  47. package/dest/sequencer/automine/index.d.ts +3 -0
  48. package/dest/sequencer/automine/index.d.ts.map +1 -0
  49. package/dest/sequencer/automine/index.js +2 -0
  50. package/dest/sequencer/checkpoint_proposal_job.d.ts +24 -16
  51. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  52. package/dest/sequencer/checkpoint_proposal_job.js +98 -90
  53. package/dest/sequencer/events.d.ts +16 -5
  54. package/dest/sequencer/events.d.ts.map +1 -1
  55. package/dest/sequencer/index.d.ts +1 -3
  56. package/dest/sequencer/index.d.ts.map +1 -1
  57. package/dest/sequencer/index.js +0 -2
  58. package/dest/sequencer/requests_tracker.d.ts +22 -0
  59. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  60. package/dest/sequencer/requests_tracker.js +33 -0
  61. package/dest/sequencer/sequencer.d.ts +110 -36
  62. package/dest/sequencer/sequencer.d.ts.map +1 -1
  63. package/dest/sequencer/sequencer.js +329 -174
  64. package/dest/test/index.d.ts +3 -3
  65. package/dest/test/index.d.ts.map +1 -1
  66. package/dest/test/utils.d.ts +15 -1
  67. package/dest/test/utils.d.ts.map +1 -1
  68. package/dest/test/utils.js +18 -1
  69. package/package.json +30 -28
  70. package/src/client/sequencer-client.ts +20 -13
  71. package/src/config.ts +25 -12
  72. package/src/global_variable_builder/fee_predictor.ts +11 -1
  73. package/src/global_variable_builder/fee_provider.ts +27 -5
  74. package/src/global_variable_builder/global_builder.ts +2 -34
  75. package/src/index.ts +1 -10
  76. package/src/publisher/config.ts +22 -1
  77. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  78. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +114 -7
  79. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +4 -3
  80. package/src/publisher/l1_tx_failed_store/index.ts +1 -1
  81. package/src/publisher/sequencer-publisher.ts +383 -72
  82. package/src/publisher/write_json.ts +78 -0
  83. package/src/sequencer/automine/README.md +18 -4
  84. package/src/sequencer/automine/automine_factory.ts +8 -1
  85. package/src/sequencer/automine/automine_sequencer.ts +221 -20
  86. package/src/sequencer/automine/index.ts +6 -0
  87. package/src/sequencer/checkpoint_proposal_job.ts +119 -100
  88. package/src/sequencer/events.ts +16 -4
  89. package/src/sequencer/index.ts +0 -2
  90. package/src/sequencer/requests_tracker.ts +43 -0
  91. package/src/sequencer/sequencer.ts +360 -187
  92. package/src/test/index.ts +2 -2
  93. package/src/test/utils.ts +33 -0
  94. package/dest/sequencer/chain_state_overrides.d.ts +0 -61
  95. package/dest/sequencer/chain_state_overrides.d.ts.map +0 -1
  96. package/dest/sequencer/chain_state_overrides.js +0 -98
  97. package/dest/sequencer/timetable.d.ts +0 -98
  98. package/dest/sequencer/timetable.d.ts.map +0 -1
  99. package/dest/sequencer/timetable.js +0 -227
  100. package/src/sequencer/chain_state_overrides.ts +0 -162
  101. package/src/sequencer/timetable.ts +0 -288
@@ -18,9 +18,18 @@ import type {
18
18
  ProposedCheckpointSink,
19
19
  ValidateCheckpointResult,
20
20
  } from '@aztec/stdlib/block';
21
- import type { Checkpoint, ProposedCheckpointData } from '@aztec/stdlib/checkpoint';
21
+ import {
22
+ type Checkpoint,
23
+ type ProposedCheckpointData,
24
+ buildCheckpointSimulationOverridesPlan,
25
+ } from '@aztec/stdlib/checkpoint';
22
26
  import type { ChainConfig } from '@aztec/stdlib/config';
23
- import { getEpochAtSlot, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
27
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
28
+ import {
29
+ MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
30
+ MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
31
+ computeNetworkTxGasLimits,
32
+ } from '@aztec/stdlib/gas';
24
33
  import {
25
34
  type ResolvedSequencerConfig,
26
35
  type SequencerConfig,
@@ -30,7 +39,7 @@ import {
30
39
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
31
40
  import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
32
41
  import { pickFromSchema } from '@aztec/stdlib/schemas';
33
- import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
42
+ import { ProposerTimetable, buildProposerTimetable } from '@aztec/stdlib/timetable';
34
43
  import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
35
44
  import { FullNodeCheckpointsBuilder, NodeKeystoreAdapter, type ValidatorClient } from '@aztec/validator-client';
36
45
 
@@ -40,14 +49,13 @@ import { DefaultSequencerConfig } from '../config.js';
40
49
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
41
50
  import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
42
51
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
43
- import { buildCheckpointSimulationOverridesPlan } from './chain_state_overrides.js';
44
52
  import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
45
53
  import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
46
54
  import { CheckpointVoter } from './checkpoint_voter.js';
47
- import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
55
+ import { SequencerInterruptedError } from './errors.js';
48
56
  import type { SequencerEvents } from './events.js';
49
57
  import { SequencerMetrics } from './metrics.js';
50
- import { SequencerTimetable } from './timetable.js';
58
+ import { RequestsTracker } from './requests_tracker.js';
51
59
  import type { SequencerRollupConstants } from './types.js';
52
60
  import { SequencerState } from './utils.js';
53
61
 
@@ -72,22 +80,27 @@ type SequencerSlotContext = {
72
80
  * - Votes for proposals and slashes on L1
73
81
  */
74
82
  export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
75
- private runningPromise?: RunningPromise;
83
+ protected runningPromise?: RunningPromise;
76
84
  private state = SequencerState.STOPPED;
77
85
  private stateSlotNumber: SlotNumber | undefined;
78
- private stateEnteredAtMs = performance.now();
86
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */
87
+ private stateEnteredAtMs: number;
79
88
  private metrics: SequencerMetrics;
80
89
  private checkpointProposalJobMetrics: CheckpointProposalJobMetrics;
81
90
  private readonly stateLog: Logger;
82
91
 
83
- /** The last slot for which we attempted to perform our voting duties with degraded block production */
84
- private lastSlotForFallbackVote: SlotNumber | undefined;
92
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */
93
+ private lastSlotForFallbackAction: SlotNumber | undefined;
94
+
95
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
96
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */
97
+ private lastInvalidationAttempt: { slot: SlotNumber; checkpointNumber: CheckpointNumber } | undefined;
85
98
 
86
99
  /** The last slot for which we logged "no committee" warning, to avoid spam */
87
100
  private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
88
101
 
89
102
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
90
- private lastSlotForCheckpointProposalJob: SlotNumber | undefined;
103
+ protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
91
104
 
92
105
  /** Last successful checkpoint proposed */
93
106
  private lastCheckpointProposed: Checkpoint | undefined;
@@ -98,8 +111,19 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
98
111
  /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */
99
112
  protected lastCheckpointProposalJob: CheckpointProposalJob | undefined;
100
113
 
101
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
102
- protected timetable!: SequencerTimetable;
114
+ /**
115
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
116
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
117
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
118
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
119
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
120
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
121
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
122
+ */
123
+ protected readonly pendingRequests = new RequestsTracker();
124
+
125
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
126
+ protected timetable!: ProposerTimetable;
103
127
 
104
128
  /** Config for the sequencer */
105
129
  protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
@@ -125,6 +149,7 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
125
149
  ) {
126
150
  super();
127
151
  this.stateLog = log.createChild('state');
152
+ this.stateEnteredAtMs = this.dateProvider.now();
128
153
 
129
154
  // Add [FISHERMAN] prefix to logger if in fisherman mode
130
155
  if (config.fishermanMode) {
@@ -140,24 +165,119 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
140
165
  this.updateConfig(config);
141
166
  }
142
167
 
143
- /** Updates sequencer config by the defined values and updates the timetable */
168
+ /**
169
+ * Updates sequencer config by the defined values and rebuilds the timetable.
170
+ *
171
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
172
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
173
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
174
+ * never leaves the sequencer running with a rejected config and a stale timetable.
175
+ */
144
176
  public updateConfig(config: Partial<SequencerConfig>) {
145
177
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
178
+ const candidate = merge(this.config, filteredConfig);
179
+ let timetable: ProposerTimetable;
180
+ try {
181
+ timetable = this.buildTimetable(candidate);
182
+ } catch (err) {
183
+ this.log.warn(`Rejecting sequencer config update: ${(err as Error).message}`, {
184
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend'),
185
+ });
186
+ throw err;
187
+ }
188
+ this.config = candidate;
189
+ this.timetable = timetable;
146
190
  this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
147
- this.config = merge(this.config, filteredConfig);
148
- const p2pPropagationTime = this.config.attestationPropagationTime;
149
- this.timetable = new SequencerTimetable(
150
- {
151
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
152
- aztecSlotDuration: this.aztecSlotDuration,
153
- l1PublishingTime: this.l1PublishingTime,
154
- p2pPropagationTime,
155
- blockDurationMs: this.config.blockDurationMs,
156
- enforce: this.config.enforceTimeTable,
157
- },
158
- this.metrics,
159
- this.log,
160
- );
191
+ }
192
+
193
+ /**
194
+ * Builds the proposer timetable from the given config and L1 constants via the shared
195
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
196
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
197
+ * {@link ProposerTimetable}.
198
+ *
199
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
200
+ * minimums; callers must treat a throw as a rejected config and not commit it.
201
+ */
202
+ private buildTimetable(config: ResolvedSequencerConfig): ProposerTimetable {
203
+ const timetable = buildProposerTimetable(config, this.l1Constants);
204
+
205
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
206
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
207
+ aztecSlotDuration: timetable.aztecSlotDuration,
208
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
209
+ blockDuration: timetable.blockDuration,
210
+ minBlockDuration: timetable.minBlockDuration,
211
+ p2pPropagationTime: timetable.p2pPropagationTime,
212
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
213
+ maxNumberOfBlocks,
214
+ });
215
+
216
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
217
+
218
+ return timetable;
219
+ }
220
+
221
+ /**
222
+ * Checks this node's configured per-block allocation against the network admission limit. A node
223
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
224
+ * {@link computeNetworkTxGasLimits}).
225
+ *
226
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
227
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
228
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
229
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
230
+ *
231
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
232
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
233
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
234
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
235
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
236
+ * intentionally not modeled here for the same reason.
237
+ */
238
+ private assertConfigMeetsNetworkTxLimits(config: ResolvedSequencerConfig, maxBlocksPerCheckpoint: number) {
239
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
240
+ const l2Multiplier = config.perBlockAllocationMultiplier;
241
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
242
+
243
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
244
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
245
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
246
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
247
+ throw new Error(
248
+ `perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` +
249
+ `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
250
+ );
251
+ }
252
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
253
+ throw new Error(
254
+ `perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` +
255
+ `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
256
+ );
257
+ }
258
+
259
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
260
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
261
+ const networkLimit = computeNetworkTxGasLimits({
262
+ maxBlocksPerCheckpoint,
263
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit,
264
+ });
265
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
266
+ this.log.warn(
267
+ `Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` +
268
+ `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` +
269
+ `by this proposer's own blocks and left in the pool for other proposers.`,
270
+ { maxDABlockGas: config.maxDABlockGas, networkDaGas: networkLimit.daGas, maxBlocksPerCheckpoint },
271
+ );
272
+ }
273
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
274
+ this.log.warn(
275
+ `Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` +
276
+ `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` +
277
+ `by this proposer's own blocks and left in the pool for other proposers.`,
278
+ { maxL2BlockGas: config.maxL2BlockGas, networkL2Gas: networkLimit.l2Gas, maxBlocksPerCheckpoint },
279
+ );
280
+ }
161
281
  }
162
282
 
163
283
  /** Initializes the sequencer (precomputes tables). Takes about 3s. */
@@ -165,8 +285,22 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
165
285
  getKzg();
166
286
  }
167
287
 
168
- /** Starts the sequencer and moves to IDLE state. */
288
+ /**
289
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
290
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
291
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
292
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
293
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
294
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
295
+ */
169
296
  public start() {
297
+ if (this.state === SequencerState.STOPPING) {
298
+ throw new Error('Cannot start sequencer while it is stopping');
299
+ }
300
+ if (this.runningPromise?.isRunning()) {
301
+ this.log.warn('Attempted to start sequencer that is already running');
302
+ return;
303
+ }
170
304
  this.runningPromise = new RunningPromise(
171
305
  this.safeWork.bind(this),
172
306
  this.log,
@@ -182,34 +316,63 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
182
316
  return this.runningPromise?.trigger();
183
317
  }
184
318
 
185
- /** Stops the sequencer from building blocks and moves to STOPPED state. */
319
+ /**
320
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
321
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
322
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
323
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
324
+ * (e.g. around a test clock warp), use {@link pause} instead.
325
+ */
186
326
  public async stop(): Promise<void> {
327
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
328
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
329
+ return;
330
+ }
187
331
  this.log.info(`Stopping sequencer`);
188
332
  this.setState(SequencerState.STOPPING, undefined, { force: true });
189
333
  this.lastCheckpointProposalJob?.interrupt();
190
334
  await this.publisherFactory.stopAll();
335
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
336
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
337
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
338
+ // in-flight iteration.
191
339
  await this.runningPromise?.stop();
192
- await this.lastCheckpointProposalJob?.awaitPendingSubmission();
340
+ this.pendingRequests.interruptRequests();
341
+ await this.pendingRequests.awaitRequests();
193
342
  this.setState(SequencerState.STOPPED, undefined, { force: true });
194
343
  this.log.info('Stopped sequencer');
195
344
  }
196
345
 
346
+ /**
347
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
348
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
349
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
350
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
351
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
352
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
353
+ */
354
+ public async pause(): Promise<void> {
355
+ if (!this.runningPromise?.isRunning()) {
356
+ this.log.debug('Sequencer not running, ignoring pause');
357
+ return;
358
+ }
359
+ this.log.info('Pausing sequencer');
360
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
361
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
362
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
363
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
364
+ await this.runningPromise.stop();
365
+ await this.pendingRequests.awaitRequests();
366
+ this.log.info('Paused sequencer');
367
+ }
368
+
197
369
  /** Main sequencer loop with a try/catch */
198
370
  protected async safeWork() {
199
371
  try {
200
372
  await this.work();
201
373
  } catch (err) {
202
- if (
203
- err instanceof SequencerTooSlowError &&
204
- [SequencerState.INITIALIZING_CHECKPOINT, SequencerState.PROPOSER_CHECK].includes(err.proposedState)
205
- ) {
206
- // No need to alert if we just didn't get to start in time
207
- this.log.debug(err.message, { now: this.dateProvider.nowInSeconds() });
208
- } else {
209
- // Re-throw other errors
210
- this.emit('checkpoint-error', { error: err as Error });
211
- throw err;
212
- }
374
+ this.emit('checkpoint-error', { error: err as Error });
375
+ throw err;
213
376
  } finally {
214
377
  this.setState(SequencerState.IDLE, undefined);
215
378
  }
@@ -290,14 +453,8 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
290
453
  ts: bigint,
291
454
  nowSeconds: bigint,
292
455
  ): Promise<CheckpointProposalJob | undefined> {
293
- // Check we have not already processed this target slot (cheapest check)
294
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
295
- // running against actual time (eg when we use sandbox-style automining)
296
- if (
297
- this.lastSlotForCheckpointProposalJob &&
298
- this.lastSlotForCheckpointProposalJob >= targetSlot &&
299
- this.config.enforceTimeTable
300
- ) {
456
+ // Check we have not already processed this target slot (cheapest check).
457
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
301
458
  this.log.trace(`Target slot ${targetSlot} has already been processed`);
302
459
  return undefined;
303
460
  }
@@ -319,12 +476,11 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
319
476
  return undefined;
320
477
  }
321
478
 
322
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
323
- const syncedTo = await this.checkSync({ ts, slot });
324
- if (!syncedTo) {
325
- await this.tryVoteWhenSyncFails({ slot, targetSlot, ts });
326
- return undefined;
327
- }
479
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
480
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
481
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
482
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
483
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
328
484
 
329
485
  // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
330
486
  // Still perform governance/slashing voting (as proposer) once per slot.
@@ -332,8 +488,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
332
488
  const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
333
489
 
334
490
  if (isEscapeHatchOpen) {
335
- this.setState(SequencerState.PROPOSER_CHECK, slot);
336
- const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
337
491
  if (canPropose) {
338
492
  await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
339
493
  } else {
@@ -346,6 +500,50 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
346
500
  return undefined;
347
501
  }
348
502
 
503
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
504
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
505
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
506
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
507
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
508
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
509
+ if (!canPropose) {
510
+ try {
511
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
512
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
513
+ } catch (err) {
514
+ this.log.warn(`Failed to consider invalidating checkpoint`, { err, slot, targetSlot });
515
+ }
516
+ return undefined;
517
+ }
518
+
519
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
520
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
521
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
522
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
523
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
524
+ // still run when block building is abandoned.
525
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
526
+ const nowForStartGate = this.dateProvider.now() / 1000;
527
+ if (nowForStartGate > startDeadline) {
528
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
529
+ targetSlot,
530
+ nowForStartGate,
531
+ startDeadline,
532
+ });
533
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
534
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
535
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
536
+ this.lastSlotForCheckpointProposalJob = targetSlot;
537
+ return undefined;
538
+ }
539
+
540
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
541
+ // Now run the full sync check before building.
542
+ const syncedTo = await this.checkSync({ ts, slot });
543
+ if (!syncedTo) {
544
+ return undefined;
545
+ }
546
+
349
547
  // Next checkpoint follows from the last synced one
350
548
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
351
549
 
@@ -359,15 +557,8 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
359
557
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
360
558
  };
361
559
 
362
- // Check that we are a proposer for the target slot.
363
- this.setState(SequencerState.PROPOSER_CHECK, slot);
364
- const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
365
-
366
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
367
- if (!canPropose) {
368
- await this.considerInvalidatingCheckpoint(syncedTo, slot);
369
- return undefined;
370
- }
560
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
561
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
371
562
 
372
563
  // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
373
564
  // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
@@ -527,7 +718,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
527
718
 
528
719
  // Create and return the checkpoint proposal job
529
720
  return this.createCheckpointProposalJob(
530
- slot,
531
721
  targetSlot,
532
722
  targetEpoch,
533
723
  checkpointNumber,
@@ -542,7 +732,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
542
732
  }
543
733
 
544
734
  protected createCheckpointProposalJob(
545
- slot: SlotNumber,
546
735
  targetSlot: SlotNumber,
547
736
  targetEpoch: EpochNumber,
548
737
  checkpointNumber: CheckpointNumber,
@@ -555,7 +744,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
555
744
  proposedCheckpointData?: ProposedCheckpointData,
556
745
  ): CheckpointProposalJob {
557
746
  return new CheckpointProposalJob(
558
- slot,
559
747
  targetSlot,
560
748
  targetEpoch,
561
749
  checkpointNumber,
@@ -583,7 +771,8 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
583
771
  this.metrics,
584
772
  this.checkpointProposalJobMetrics.createRecorder(),
585
773
  this,
586
- (state, slot, timeReferenceSlot) => this.setState(state, slot, { timeReferenceSlot }),
774
+ this.pendingRequests,
775
+ this.setState.bind(this),
587
776
  this.tracer,
588
777
  this.log.getBindings(),
589
778
  proposedCheckpointData,
@@ -598,16 +787,17 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
598
787
  }
599
788
 
600
789
  /**
601
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
790
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
791
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
602
792
  * @param proposedState - The new state to transition to.
603
- * @param slotNumber - The logical slot associated with the new state.
793
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
794
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
604
795
  * @param force - Whether to force the transition even if the sequencer is stopped.
605
- * @param timeReferenceSlot - The slot to use for deadline checks when it differs from the logical slot.
606
796
  */
607
797
  protected setState(
608
798
  proposedState: SequencerState,
609
799
  slotNumber: SlotNumber | undefined,
610
- opts: { force?: boolean; timeReferenceSlot?: SlotNumber } = {},
800
+ opts: { force?: boolean } = {},
611
801
  ): void {
612
802
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
613
803
  this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
@@ -617,17 +807,14 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
617
807
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
618
808
  return;
619
809
  }
620
- let secondsIntoSlot = undefined;
621
- const timeReferenceSlot = opts.timeReferenceSlot ?? slotNumber;
622
- if (timeReferenceSlot !== undefined) {
623
- secondsIntoSlot = this.getSecondsIntoSlot(timeReferenceSlot);
624
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
625
- }
810
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
626
811
 
627
812
  const oldState = this.state;
628
813
  const oldStateSlotNumber = this.stateSlotNumber;
629
814
  const stateChanged = proposedState !== oldState;
630
- const transitionAtMs = performance.now();
815
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
816
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
817
+ const transitionAtMs = this.dateProvider.now();
631
818
  const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
632
819
 
633
820
  const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
@@ -637,18 +824,16 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
637
824
  oldState,
638
825
  newState: proposedState,
639
826
  slotNumber,
640
- timeReferenceSlot,
641
827
  stateSlotNumber: oldStateSlotNumber,
642
- secondsIntoSlot,
828
+ secondsIntoBuildFrame,
643
829
  ...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
644
830
  });
645
831
 
646
832
  this.emit('state-changed', {
647
833
  oldState,
648
834
  newState: proposedState,
649
- secondsIntoSlot,
650
- slot: slotNumber,
651
- timeReferenceSlot,
835
+ secondsIntoBuildFrame,
836
+ targetSlot: slotNumber,
652
837
  });
653
838
  if (stateChanged) {
654
839
  this.metrics.recordStateDuration(stateDurationMs, oldState);
@@ -681,9 +866,7 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
681
866
  number: syncSummary.latestBlockNumber,
682
867
  hash: syncSummary.latestBlockHash,
683
868
  })),
684
- this.l2BlockSource
685
- .getL2Tips()
686
- .then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed, proposedCheckpoint: t.proposedCheckpoint })),
869
+ this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
687
870
  this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
688
871
  this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
689
872
  this.l2BlockSource.getPendingChainValidationStatus(),
@@ -728,56 +911,28 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
728
911
  // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
729
912
  // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
730
913
  // once their build slot ends; this guard is the correctness barrier during the grace window before.
914
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
915
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
916
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
731
917
  if (
732
918
  blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
733
- (l2Tips.proposedCheckpoint.checkpoint.number !== blockData.checkpointNumber ||
734
- proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber)
919
+ proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
735
920
  ) {
736
921
  const logCtx = {
737
922
  blockCheckpointNumber: blockData.checkpointNumber,
738
923
  checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
739
- proposedCheckpointTipNumber: l2Tips.proposedCheckpoint.checkpoint.number,
740
- proposedCheckpointDataNumber: proposedCheckpointData?.checkpointNumber,
924
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
741
925
  blockNumber: blockData.header.getBlockNumber(),
742
926
  blockSlot: blockData.header.getSlot(),
743
927
  syncedL2Slot,
744
928
  ...args,
745
929
  };
746
930
 
747
- // Under pipelining the block proposal for a checkpoint leads its checkpoint proposal by up to one
748
- // slot, so a world-state tip sitting in an as-yet-unproposed checkpoint is the expected steady state
749
- // until that checkpoint is due. Only treat it as abnormal — and warn — once the checkpoint is overdue
750
- // by the same deadline the archiver uses to prune the orphan block (see pruneOrphanProposedBlocks).
751
- // Before then this is normal pipelining and we wait it out quietly.
752
- if (this.isProposedCheckpointOverdue(blockData.header.getSlot())) {
753
- this.log.warn(`Sequencer sync check failed: proposed block has no matching proposed checkpoint`, logCtx);
754
- } else {
755
- this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
756
- }
931
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
757
932
  return undefined;
758
933
  }
759
934
 
760
- const hasProposedCheckpoint = l2Tips.proposedCheckpoint.checkpoint.number > l2Tips.checkpointed.checkpoint.number;
761
-
762
- // The l2Tips and proposedCheckpointData reads above come from independent archiver snapshots
763
- // (a JS-side tips cache vs. a direct store read on `#proposedCheckpoints`). A concurrent archiver
764
- // write that mutates both can be observed split, leaving us with `hasProposedCheckpoint=true` but
765
- // no proposedCheckpointData (or one whose number doesn't match the tip). Refuse to proceed in that
766
- // window — the next checkSync tick will see a coherent snapshot.
767
- if (
768
- hasProposedCheckpoint &&
769
- (!proposedCheckpointData ||
770
- proposedCheckpointData.checkpointNumber !== l2Tips.proposedCheckpoint.checkpoint.number)
771
- ) {
772
- this.log.warn(`Sequencer sync check failed: inconsistent proposed-checkpoint state`, {
773
- proposedCheckpointTipNumber: l2Tips.proposedCheckpoint.checkpoint.number,
774
- checkpointedTipNumber: l2Tips.checkpointed.checkpoint.number,
775
- proposedCheckpointDataNumber: proposedCheckpointData?.checkpointNumber,
776
- syncedL2Slot,
777
- ...args,
778
- });
779
- return undefined;
780
- }
935
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
781
936
 
782
937
  // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
783
938
  // The checkpoint number to build is derived as blockData.checkpointNumber + 1
@@ -804,21 +959,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
804
959
  };
805
960
  }
806
961
 
807
- /**
808
- * Whether the enclosing checkpoint of a reexecuted block is overdue: past the deadline by which a
809
- * well-behaved proposer should have published it. Mirrors the archiver's orphan-prune deadline (the
810
- * start of the slot after the block's build slot, plus a grace period) so the sequencer only warns
811
- * about a missing proposed checkpoint once the archiver itself would prune the orphan block. The grace
812
- * is derived from the block build duration the same way the archiver defaults it at node wiring.
813
- */
814
- private isProposedCheckpointOverdue(blockSlot: SlotNumber): boolean {
815
- const expectedBySlot = SlotNumber(Number(blockSlot) - PROPOSER_PIPELINING_SLOT_OFFSET + 1);
816
- const graceSeconds =
817
- this.config.blockDurationMs !== undefined ? Math.ceil(this.config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
818
- const expectedByTime = getTimestampForSlot(expectedBySlot, this.l1Constants) + BigInt(graceSeconds);
819
- return BigInt(this.dateProvider.nowInSeconds()) >= expectedByTime;
820
- }
821
-
822
962
  /**
823
963
  * Checks if we are the proposer for the next slot.
824
964
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
@@ -869,36 +1009,29 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
869
1009
  }
870
1010
 
871
1011
  /**
872
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
873
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1012
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1013
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1014
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
874
1015
  */
875
- @trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
876
- protected async tryVoteWhenSyncFails(args: { slot: SlotNumber; targetSlot: SlotNumber; ts: bigint }): Promise<void> {
1016
+ @trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1017
+ protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
877
1018
  const { slot, targetSlot } = args;
878
1019
 
879
1020
  // Prevent duplicate attempts in the same slot
880
- if (this.lastSlotForFallbackVote === slot) {
881
- this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1021
+ if (this.lastSlotForFallbackAction === slot) {
1022
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
882
1023
  return;
883
1024
  }
884
1025
 
885
- // Check if we're past the max time for initializing a proposal
886
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
887
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
1026
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1027
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1028
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1029
+ const nowSeconds = this.dateProvider.now() / 1000;
1030
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
888
1031
 
889
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
890
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
891
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
892
- this.log.trace(`Not attempting to vote since there is still time for block building`, {
893
- secondsIntoSlot,
894
- maxAllowedTime,
895
- });
896
- return;
897
- }
898
-
899
- this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
900
- secondsIntoSlot,
901
- maxAllowedTime,
1032
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1033
+ nowSeconds,
1034
+ startDeadline,
902
1035
  });
903
1036
 
904
1037
  // Check if we're a proposer or proposal is open
@@ -909,7 +1042,7 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
909
1042
  }
910
1043
 
911
1044
  // Mark this slot as attempted
912
- this.lastSlotForFallbackVote = slot;
1045
+ this.lastSlotForFallbackAction = slot;
913
1046
 
914
1047
  // Get a publisher for voting
915
1048
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
@@ -934,19 +1067,41 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
934
1067
  const votesPromises = voter.enqueueVotes();
935
1068
  const votes = await Promise.all(votesPromises);
936
1069
 
937
- if (votes.every(p => !p)) {
938
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1070
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1071
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1072
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1073
+
1074
+ // Bail if nothing to do
1075
+ if (votes.every(p => !p) && !pruneEnqueued) {
1076
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
939
1077
  return;
940
1078
  }
941
1079
 
942
- this.log.info(`Voting in slot ${slot} despite sync failure`, { slot });
1080
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1081
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1082
+ slot,
1083
+ pruneEnqueued,
1084
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1085
+ slashingVoteEnqueued: !!slashingVoteEnqueued,
1086
+ });
1087
+
943
1088
  // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
944
1089
  // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
945
1090
  // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
946
- // work loop while waiting for the target slot to start.
947
- void publisher.sendRequestsAt(targetSlot).catch(err => {
948
- this.log.error(`Failed to publish votes despite sync failure for slot ${slot}`, err, { slot });
1091
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1092
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1093
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
949
1094
  });
1095
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1096
+ }
1097
+
1098
+ private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
1099
+ try {
1100
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1101
+ } catch (err) {
1102
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
1103
+ return false;
1104
+ }
950
1105
  }
951
1106
 
952
1107
  /**
@@ -962,13 +1117,13 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
962
1117
  const { slot, targetSlot, proposer } = args;
963
1118
 
964
1119
  // Prevent duplicate attempts in the same slot
965
- if (this.lastSlotForFallbackVote === slot) {
1120
+ if (this.lastSlotForFallbackAction === slot) {
966
1121
  this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
967
1122
  return;
968
1123
  }
969
1124
 
970
1125
  // Mark this slot as attempted
971
- this.lastSlotForFallbackVote = slot;
1126
+ this.lastSlotForFallbackAction = slot;
972
1127
 
973
1128
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
974
1129
 
@@ -1007,10 +1162,12 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1007
1162
  // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1008
1163
  // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1009
1164
  // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1010
- // waiting for the target slot to start, mirroring tryVoteWhenSyncFails.
1011
- void publisher.sendRequestsAt(targetSlot).catch(err => {
1165
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1166
+ // stop() can drain it.
1167
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1012
1168
  this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
1013
1169
  });
1170
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1014
1171
  }
1015
1172
 
1016
1173
  /**
@@ -1018,17 +1175,34 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1018
1175
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1019
1176
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1020
1177
  * and if they fail, any sequencer will try as well.
1178
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1179
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1021
1180
  */
1022
1181
  protected async considerInvalidatingCheckpoint(
1023
- syncedTo: SequencerSyncCheckResult,
1182
+ pendingChainValidationStatus: ValidateCheckpointResult,
1024
1183
  currentSlot: SlotNumber,
1025
1184
  ): Promise<void> {
1026
- const { pendingChainValidationStatus, syncedL2Slot } = syncedTo;
1027
1185
  if (pendingChainValidationStatus.valid) {
1028
1186
  return;
1029
1187
  }
1030
1188
 
1031
1189
  const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1190
+
1191
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1192
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1193
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1194
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1195
+ if (
1196
+ this.lastInvalidationAttempt?.slot === currentSlot &&
1197
+ this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
1198
+ ) {
1199
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1200
+ currentSlot,
1201
+ invalidCheckpointNumber,
1202
+ });
1203
+ return;
1204
+ }
1205
+
1032
1206
  const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1033
1207
  const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
1034
1208
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
@@ -1038,7 +1212,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1038
1212
 
1039
1213
  const logData = {
1040
1214
  invalidL1Timestamp: invalidCheckpointTimestamp,
1041
- syncedL2Slot,
1042
1215
  invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1043
1216
  secondsBeforeInvalidatingBlockAsCommitteeMember,
1044
1217
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
@@ -1091,6 +1264,10 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1091
1264
  return;
1092
1265
  }
1093
1266
 
1267
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1268
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1269
+ this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
1270
+
1094
1271
  this.log.info(
1095
1272
  invalidateAsCommitteeMember
1096
1273
  ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
@@ -1137,13 +1314,13 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1137
1314
  });
1138
1315
  }
1139
1316
 
1140
- private getSlotStartBuildTimestamp(slotNumber: SlotNumber): number {
1141
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
1142
- }
1143
-
1144
- private getSecondsIntoSlot(slotNumber: SlotNumber): number {
1145
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
1146
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1317
+ /**
1318
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1319
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1320
+ */
1321
+ private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
1322
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1323
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1147
1324
  }
1148
1325
 
1149
1326
  public get aztecSlotDuration() {
@@ -1174,10 +1351,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1174
1351
  public getConfig() {
1175
1352
  return this.config;
1176
1353
  }
1177
-
1178
- private get l1PublishingTime(): number {
1179
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1180
- }
1181
1354
  }
1182
1355
 
1183
1356
  type SequencerSyncCheckResult = {