1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use std::sync::Arc;
use futures::StreamExt;
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use sp1_core_executor::{ExecutionRecord, Program, SP1CoreOpts, SplitOpts, SyscallCode};
use sp1_hypercube::air::ShardRange;
use sp1_prover_types::{await_scoped_vec, Artifact, ArtifactClient, ArtifactType, TaskStatus};
use tokio::{sync::mpsc, task::JoinSet};
use tracing::Instrument;
use crate::worker::{
controller::{create_core_proving_task, ProveShardGate},
MessageSender, ProofData, SpawnProveOutput, TaskContext, TaskError, TaskId, TraceData,
WorkerClient,
};
/// String used as key for add_ref to ensure precompile artifacts are not cleaned up before they
/// are fully split into multiple shards.
const CONTROLLER_PRECOMPILE_ARTIFACT_REF: &str = "_controller";
/// An artifact of precompile events, and the range of indices to index into.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrecompileArtifactSlice {
pub artifact: Artifact,
pub start_idx: usize,
pub end_idx: usize,
}
/// A lightweight container for the precompile events in a shard.
///
/// Rather than actually holding all of the events, the events are represented as `Artifact`s with
/// start and end indices.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeferredEvents(pub HashMap<SyscallCode, Vec<PrecompileArtifactSlice>>);
impl DeferredEvents {
/// Defer all events in an ExecutionRecord by uploading each precompile in chunks.
pub async fn defer_record<A: ArtifactClient>(
record: ExecutionRecord,
client: &A,
split_opts: SplitOpts,
) -> Result<DeferredEvents, TaskError> {
// Move all synchronous work (iteration, chunking) into spawn_blocking
// to avoid blocking the async runtime.
let chunk_data = tokio::task::spawn_blocking(move || {
let mut chunk_data = Vec::new();
for (code, events) in record.precompile_events.events.iter() {
let threshold = split_opts.syscall_threshold[*code];
for chunk in events.chunks(threshold) {
chunk_data.push((*code, chunk.to_vec()));
}
}
chunk_data
})
.await
.map_err(|e| TaskError::Fatal(e.into()))?;
// Create all artifacts in batch (this is cheap - just generates IDs)
let artifacts =
client.create_artifacts(chunk_data.len()).map_err(TaskError::Fatal)?.to_vec();
// Build futures with pre-created artifacts and run uploads in parallel
let futures = chunk_data
.into_iter()
.zip(artifacts)
.map(|((code, chunk), artifact)| {
let client = client.clone();
async move {
client.upload(&artifact, &chunk).await.unwrap();
(code, artifact, chunk.len())
}
})
.collect::<Vec<_>>();
let res =
await_scoped_vec(futures).await.map_err(|e| TaskError::Fatal(anyhow::anyhow!(e)))?;
let mut deferred: HashMap<SyscallCode, Vec<PrecompileArtifactSlice>> = HashMap::new();
for (code, artifact, count) in res {
deferred.entry(code).or_default().push(PrecompileArtifactSlice {
artifact,
start_idx: 0,
end_idx: count,
});
}
Ok(DeferredEvents(deferred))
}
/// Create an empty DeferredEvents.
pub fn empty() -> Self {
Self(HashMap::new())
}
/// Append the events from another DeferredEvents to self. Analogous to
/// `ExecutionRecord::append`.
pub async fn append(&mut self, other: DeferredEvents, client: &impl ArtifactClient) {
for (code, events) in other.0 {
// Add task references for artifacts so they are not cleaned up before they are fully
// split.
for PrecompileArtifactSlice { artifact, .. } in &events {
if let Err(e) = client.add_ref(artifact, CONTROLLER_PRECOMPILE_ARTIFACT_REF).await {
tracing::error!("Failed to add ref to artifact {:?}: {:?}", artifact, e);
}
}
self.0.entry(code).or_default().extend(events);
}
}
/// Split the DeferredEvents into multiple TraceData. Similar to `ExecutionRecord::split`.
pub async fn split(
&mut self,
last: bool,
opts: SplitOpts,
client: &impl ArtifactClient,
) -> Vec<TraceData> {
let mut shards = Vec::new();
let keys = self.0.keys().cloned().collect::<Vec<_>>();
for code in keys {
let threshold = opts.syscall_threshold[code];
// self.0[code] contains uploaded artifacts with start and end indices. start is
// initially 0. Create shards of precompiles from self.0[code] up to
// threshold, then update new [start, end) indices for future splits. If
// last is true, don't leave any remainder.
loop {
let mut count = 0;
// Loop through until we've found enough precompiles, and remove from self.0[code].
// `index` will be set such that artifacts [0, index) will be made into a shard.
let mut index = 0;
for (i, artifact_slice) in self.0[&code].iter().enumerate() {
let PrecompileArtifactSlice { start_idx, end_idx, .. } = artifact_slice;
count += end_idx - start_idx;
// Break if we've found enough or it's the last Artifact and `last` is true.
if count >= threshold || (last && i == self.0[&code].len() - 1) {
index = i + 1;
break;
}
}
// If not enough was found, break.
if index == 0 {
break;
}
// Otherwise remove the artifacts and handle remainder of last artifact if there is
// any.
let mut artifacts =
self.0.get_mut(&code).unwrap().drain(..index).collect::<Vec<_>>();
// Truncate the partial-last slice BEFORE adding refs so the key we register
// matches the (start, end) the consumer sees in its TraceData and uses to
// remove_ref.
if count > threshold {
let mut new_range = artifacts.last().cloned().unwrap();
new_range.start_idx = new_range.end_idx - (count - threshold);
artifacts.last_mut().unwrap().end_idx = new_range.start_idx;
self.0.get_mut(&code).unwrap().insert(0, new_range);
}
// For each artifact, add refs for the range needed in prove_shard, and then remove
// the controller ref if it's been fully split.
for (i, slice) in artifacts.iter().enumerate() {
let PrecompileArtifactSlice { artifact, start_idx, end_idx } = slice;
if let Err(e) =
client.add_ref(artifact, &format!("{}_{}", start_idx, end_idx)).await
{
tracing::error!("Failed to add ref to artifact {}: {:?}", artifact, e);
}
// If there's a remainder, don't remove the controller ref yet.
if i == artifacts.len() - 1 && count > threshold {
break;
}
if let Err(e) = client
.remove_ref(
artifact,
ArtifactType::UnspecifiedArtifactType,
CONTROLLER_PRECOMPILE_ARTIFACT_REF,
)
.await
{
tracing::error!("Failed to remove ref to artifact {}: {:?}", artifact, e);
}
}
shards.push(TraceData::Precompile(artifacts, code));
}
}
shards
}
}
pub struct DeferredMessage {
pub task_id: TaskId,
pub record: Artifact,
}
pub fn precompile_channel(
program: &Program,
opts: &SP1CoreOpts,
) -> (mpsc::UnboundedSender<DeferredMessage>, PrecompileHandler) {
let split_opts =
SplitOpts::new(opts, program.instructions.len(), program.enable_untrusted_programs);
let (deferred_marker_tx, deferred_marker_rx) = mpsc::unbounded_channel();
(deferred_marker_tx, PrecompileHandler { split_opts, deferred_marker_rx })
}
pub struct PrecompileHandler {
split_opts: SplitOpts,
deferred_marker_rx: mpsc::UnboundedReceiver<DeferredMessage>,
}
impl PrecompileHandler {
#[allow(clippy::too_many_arguments)]
pub(super) async fn emit_precompile_shards<A: ArtifactClient, W: WorkerClient>(
self,
elf_artifact: Artifact,
common_input_artifact: Artifact,
prove_shard_tx: MessageSender<W, ProofData>,
artifact_client: A,
worker_client: W,
gate: ProveShardGate<A, W>,
context: TaskContext,
) -> Result<(), TaskError> {
let precompile_range = ShardRange::precompile();
let mut join_set = JoinSet::new();
let task_data_map = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let PrecompileHandler { split_opts, mut deferred_marker_rx } = self;
// This subscriber monitors for deferred marker task completion
let (subscriber, mut event_stream) =
worker_client.subscriber(context.proof_id.clone()).await?.stream();
join_set.spawn({
let task_data_map = task_data_map.clone();
async move {
while let Some(deferred_message) = deferred_marker_rx.recv().await {
tracing::debug!(
"received deferred message with task id {:?}",
deferred_message.task_id
);
let DeferredMessage { task_id, record: deferred_events } = deferred_message;
task_data_map.lock().await.insert(task_id.clone(), deferred_events);
subscriber.subscribe(task_id.clone()).map_err(|e| {
TaskError::Fatal(anyhow::anyhow!(
"error subscribing to task {}: {}",
task_id,
e
))
})?;
}
Ok::<_, TaskError>(())
}
.instrument(tracing::debug_span!("deferred listener"))
});
join_set.spawn({
let worker_client = worker_client.clone();
let artifact_client = artifact_client.clone();
async move {
let mut deferred_accumulator = DeferredEvents::empty();
while let Some((task_id, status)) = event_stream.next().await {
tracing::debug!(
task_id = task_id.to_string(),
"received deferred marker task status: {:?}",
status
);
if status != TaskStatus::Succeeded {
return Err(TaskError::Fatal(anyhow::anyhow!(
"deferred marker task failed: {}",
task_id
)));
}
let deferred_events_artifact = task_data_map.lock().await.remove(&task_id);
if let Some(deferred_events_artifact) = deferred_events_artifact {
let deferred_events = artifact_client
.download::<DeferredEvents>(&deferred_events_artifact)
.await;
if deferred_events.is_err() {
tracing::error!(
"failed to download deferred events artifact: {:?}",
deferred_events_artifact
);
}
// TODO: figure out how to return this as an error while still
// being able to run pure execution without proving.
let deferred_events =
deferred_events.unwrap_or_else(|_| DeferredEvents::empty());
// Free the per-shard wrapper now that we've consumed it. The
// precompile chunks it pointed to are kept alive by the
// `_controller` refs that `append` is about to add. Without this
// the wrapper sits until the 4 h TTL — one zombie per shard.
let _ = artifact_client
.try_delete(
&deferred_events_artifact,
ArtifactType::UnspecifiedArtifactType,
)
.await;
deferred_accumulator.append(deferred_events, &artifact_client).await;
let new_shards =
deferred_accumulator.split(false, split_opts, &artifact_client).await;
for shard in new_shards {
let SpawnProveOutput { deferred_message, proof_data } =
create_core_proving_task(
elf_artifact.clone(),
common_input_artifact.clone(),
context.clone(),
precompile_range,
shard,
worker_client.clone(),
artifact_client.clone(),
&gate,
)
.await
.map_err(|e| TaskError::Fatal(e.into()))?;
if deferred_message.is_some() {
return Err(TaskError::Fatal(anyhow::anyhow!(
"deferred message is not none",
)));
}
prove_shard_tx.send(proof_data).await.map_err(|e| {
TaskError::Fatal(anyhow::anyhow!(
"error sending to proving tx: {}",
e
))
})?;
}
} else {
tracing::debug!(
"deferred events artifact not found for task id: {}",
task_id
);
}
}
let final_shards = deferred_accumulator
.split(true, split_opts, &artifact_client)
.instrument(tracing::debug_span!("split last"))
.await;
for shard in final_shards {
let SpawnProveOutput { deferred_message, proof_data } =
create_core_proving_task(
elf_artifact.clone(),
common_input_artifact.clone(),
context.clone(),
precompile_range,
shard,
worker_client.clone(),
artifact_client.clone(),
&gate,
)
.await
.map_err(|e| TaskError::Fatal(e.into()))?;
debug_assert!(deferred_message.is_none());
prove_shard_tx.send(proof_data).await.map_err(|e| {
TaskError::Fatal(anyhow::anyhow!("error sending to proving tx: {}", e))
})?;
}
tracing::debug!("deferred listener task finished");
Ok::<_, TaskError>(())
}
.instrument(tracing::debug_span!("deferred sender"))
});
while let Some(result) = join_set.join_next().await {
result.map_err(|e| {
TaskError::Fatal(anyhow::anyhow!("deferred listener task panicked: {}", e))
})??;
}
Ok::<(), TaskError>(())
}
}