1use crate::error::{ContractRuntimeError, Result};
15use crate::types::CircuitId;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub struct CostVector {
21 pub read_time_ps: u64,
22 pub compute_time_ps: u64,
23 pub block_usage: u64,
24 pub bytes_written: u64,
25 pub bytes_churned: u64,
26}
27
28impl CostVector {
29 pub const ZERO: Self = Self {
30 read_time_ps: 0,
31 compute_time_ps: 0,
32 block_usage: 0,
33 bytes_written: 0,
34 bytes_churned: 0,
35 };
36
37 pub const UNBOUNDED: Self = Self {
39 read_time_ps: u64::MAX,
40 compute_time_ps: u64::MAX,
41 block_usage: u64::MAX,
42 bytes_written: u64::MAX,
43 bytes_churned: u64::MAX,
44 };
45
46 fn dimensions(self) -> [(&'static str, u64); 5] {
47 [
48 ("read time (ps)", self.read_time_ps),
49 ("compute time (ps)", self.compute_time_ps),
50 ("block usage (bytes)", self.block_usage),
51 ("bytes written", self.bytes_written),
52 ("bytes churned", self.bytes_churned),
53 ]
54 }
55
56 #[must_use]
57 pub fn saturating_add(self, other: Self) -> Self {
58 Self {
59 read_time_ps: self.read_time_ps.saturating_add(other.read_time_ps),
60 compute_time_ps: self.compute_time_ps.saturating_add(other.compute_time_ps),
61 block_usage: self.block_usage.saturating_add(other.block_usage),
62 bytes_written: self.bytes_written.saturating_add(other.bytes_written),
63 bytes_churned: self.bytes_churned.saturating_add(other.bytes_churned),
64 }
65 }
66
67 #[must_use]
68 pub fn saturating_sub(self, other: Self) -> Self {
69 Self {
70 read_time_ps: self.read_time_ps.saturating_sub(other.read_time_ps),
71 compute_time_ps: self.compute_time_ps.saturating_sub(other.compute_time_ps),
72 block_usage: self.block_usage.saturating_sub(other.block_usage),
73 bytes_written: self.bytes_written.saturating_sub(other.bytes_written),
74 bytes_churned: self.bytes_churned.saturating_sub(other.bytes_churned),
75 }
76 }
77
78 #[must_use]
80 pub fn fits_within(self, capacity: Self) -> bool {
81 self.first_excess(capacity).is_none()
82 }
83
84 #[must_use]
87 pub fn first_excess(self, capacity: Self) -> Option<(&'static str, u64, u64)> {
88 self.dimensions()
89 .into_iter()
90 .zip(capacity.dimensions())
91 .find(|((_, used), (_, cap))| used > cap)
92 .map(|((name, used), (_, cap))| (name, used, cap))
93 }
94
95 fn dominant_share(self, capacity: Self) -> Share {
97 self.dimensions()
98 .into_iter()
99 .zip(capacity.dimensions())
100 .map(|((_, used), (_, cap))| Share::new(u128::from(used), u128::from(cap)))
101 .fold(Share::ZERO, Share::max)
102 }
103}
104
105#[derive(Debug, Clone, Copy)]
108struct Share {
109 used: u128,
110 capacity: u128,
111}
112
113impl Share {
114 const ZERO: Self = Self {
115 used: 0,
116 capacity: 1,
117 };
118
119 fn new(used: u128, capacity: u128) -> Self {
120 if used == 0 {
121 Self::ZERO
122 } else {
123 Self { used, capacity }
124 }
125 }
126
127 fn max(self, other: Self) -> Self {
128 if self.cmp(&other).is_lt() {
129 other
130 } else {
131 self
132 }
133 }
134}
135
136impl PartialEq for Share {
137 fn eq(&self, other: &Self) -> bool {
138 self.cmp(other).is_eq()
139 }
140}
141
142impl Eq for Share {}
143
144impl PartialOrd for Share {
145 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
146 Some(self.cmp(other))
147 }
148}
149
150impl Ord for Share {
151 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
152 (self.used * other.capacity).cmp(&(other.used * self.capacity))
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct CircuitWeight {
163 pub id: CircuitId,
164 pub vk_bytes: usize,
165 pub deploy_cost: CostVector,
167 pub maintenance_cost: CostVector,
169}
170
171#[derive(Debug, Clone, Copy)]
173pub struct PackBudget {
174 pub max_tx_bytes: usize,
178 pub deploy_overhead: usize,
183 pub maintenance_overhead: usize,
186 pub max_cost: CostVector,
188 pub deploy_overhead_cost: CostVector,
190 pub maintenance_overhead_cost: CostVector,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct DeployPlan {
201 pub deploy_batch: Vec<CircuitId>,
202 pub maintenance_batches: Vec<Vec<CircuitId>>,
203}
204
205impl DeployPlan {
206 #[must_use]
208 pub fn total_circuits(&self) -> usize {
209 self.deploy_batch.len() + self.maintenance_batches.iter().map(Vec::len).sum::<usize>()
210 }
211
212 #[must_use]
214 pub fn total_transactions(&self) -> usize {
215 1 + self.maintenance_batches.len()
216 }
217
218 #[must_use]
221 pub fn is_single_shot(&self) -> bool {
222 self.maintenance_batches.is_empty()
223 }
224}
225
226#[derive(Clone, Copy)]
228struct Load {
229 bytes: usize,
230 cost: CostVector,
231}
232
233impl Load {
234 fn plus(self, bytes: usize, cost: CostVector) -> Self {
235 Self {
236 bytes: self.bytes.saturating_add(bytes),
237 cost: self.cost.saturating_add(cost),
238 }
239 }
240
241 fn fits(self, budget: &PackBudget) -> bool {
242 self.bytes <= budget.max_tx_bytes && self.cost.fits_within(budget.max_cost)
243 }
244}
245
246pub fn plan_incremental_deploy(
259 circuits: &[CircuitWeight],
260 budget: &PackBudget,
261) -> Result<DeployPlan> {
262 let maint_cap = budget
267 .max_tx_bytes
268 .checked_sub(budget.maintenance_overhead)
269 .filter(|c| *c > 0)
270 .ok_or_else(|| ContractRuntimeError::Provider {
271 provider: "plan_incremental_deploy",
272 message: format!(
273 "max_tx_bytes ({}) is not larger than the maintenance-tx overhead ({}); \
274 raise --max-tx-bytes",
275 budget.max_tx_bytes, budget.maintenance_overhead,
276 ),
277 })?;
278 let maintenance_empty = Load {
279 bytes: budget.maintenance_overhead,
280 cost: budget.maintenance_overhead_cost,
281 };
282 check_feasible(circuits, budget, maint_cap)?;
283
284 let weight = |w: &CircuitWeight| {
286 Share::new(w.vk_bytes as u128, maint_cap as u128)
287 .max(w.maintenance_cost.dominant_share(budget.max_cost))
288 };
289 let mut sorted: Vec<&CircuitWeight> = circuits.iter().collect();
290 sorted.sort_by(|a, b| {
291 weight(b)
292 .cmp(&weight(a))
293 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
294 });
295
296 let mut deploy_batch: Vec<CircuitId> = Vec::new();
298 let mut deploy_load = Load {
299 bytes: budget.deploy_overhead,
300 cost: budget.deploy_overhead_cost,
301 };
302 let mut remaining: Vec<&CircuitWeight> = Vec::new();
303 for w in sorted {
304 let with = deploy_load.plus(w.vk_bytes, w.deploy_cost);
305 if with.fits(budget) {
306 deploy_load = with;
307 deploy_batch.push(w.id.clone());
308 } else {
309 remaining.push(w);
310 }
311 }
312
313 let mut bins: Vec<(Load, Vec<CircuitId>)> = Vec::new();
315 for w in remaining {
316 match bins
317 .iter_mut()
318 .find(|(load, _)| load.plus(w.vk_bytes, w.maintenance_cost).fits(budget))
319 {
320 Some((load, ids)) => {
321 *load = load.plus(w.vk_bytes, w.maintenance_cost);
322 ids.push(w.id.clone());
323 }
324 None => bins.push((
325 maintenance_empty.plus(w.vk_bytes, w.maintenance_cost),
326 vec![w.id.clone()],
327 )),
328 }
329 }
330
331 Ok(DeployPlan {
332 deploy_batch,
333 maintenance_batches: bins.into_iter().map(|(_, ids)| ids).collect(),
334 })
335}
336
337fn check_feasible(circuits: &[CircuitWeight], budget: &PackBudget, maint_cap: usize) -> Result<()> {
341 for (kind, overhead) in [
342 ("deploy", budget.deploy_overhead_cost),
343 ("maintenance", budget.maintenance_overhead_cost),
344 ] {
345 if let Some((dimension, used, cap)) = overhead.first_excess(budget.max_cost) {
346 return Err(ContractRuntimeError::Provider {
347 provider: "plan_incremental_deploy",
348 message: format!(
349 "an empty {kind} transaction already needs {used} {dimension}, over the \
350 per-transaction limit of {cap}"
351 ),
352 });
353 }
354 }
355
356 for w in circuits {
358 if w.vk_bytes > maint_cap {
359 return Err(ContractRuntimeError::Provider {
360 provider: "plan_incremental_deploy",
361 message: format!(
362 "circuit '{}' has a {}-byte verifier key, larger than the per-transaction \
363 capacity of {maint_cap} bytes at max_tx_bytes={}; this circuit cannot be \
364 deployed at this budget — raise --max-tx-bytes",
365 w.id.as_str(),
366 w.vk_bytes,
367 budget.max_tx_bytes,
368 ),
369 });
370 }
371 let alone = budget
372 .maintenance_overhead_cost
373 .saturating_add(w.maintenance_cost);
374 if let Some((dimension, used, cap)) = alone.first_excess(budget.max_cost) {
375 return Err(ContractRuntimeError::Provider {
376 provider: "plan_incremental_deploy",
377 message: format!(
378 "circuit '{}' alone needs {used} {dimension} in a maintenance transaction, \
379 over the per-transaction limit of {cap}; this circuit cannot be deployed",
380 w.id.as_str(),
381 ),
382 });
383 }
384 }
385
386 Ok(())
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 fn w(id: &str, vk_bytes: usize) -> CircuitWeight {
394 CircuitWeight {
395 id: CircuitId::new(id),
396 vk_bytes,
397 deploy_cost: CostVector::ZERO,
398 maintenance_cost: CostVector::ZERO,
399 }
400 }
401
402 fn budget(max: usize, deploy_oh: usize, maint_oh: usize) -> PackBudget {
403 PackBudget {
404 max_tx_bytes: max,
405 deploy_overhead: deploy_oh,
406 maintenance_overhead: maint_oh,
407 max_cost: CostVector::UNBOUNDED,
408 deploy_overhead_cost: CostVector::ZERO,
409 maintenance_overhead_cost: CostVector::ZERO,
410 }
411 }
412
413 fn assert_within_budget(plan: &DeployPlan, circuits: &[CircuitWeight], b: &PackBudget) {
415 let size = |id: &CircuitId| circuits.iter().find(|c| &c.id == id).unwrap().vk_bytes;
416 let deploy_sum: usize = plan.deploy_batch.iter().map(&size).sum();
417 assert!(
418 deploy_sum + b.deploy_overhead <= b.max_tx_bytes,
419 "deploy batch {deploy_sum}+{} over {}",
420 b.deploy_overhead,
421 b.max_tx_bytes
422 );
423 for batch in &plan.maintenance_batches {
424 let s: usize = batch.iter().map(&size).sum();
425 assert!(
426 s + b.maintenance_overhead <= b.max_tx_bytes,
427 "maintenance batch {s}+{} over {}",
428 b.maintenance_overhead,
429 b.max_tx_bytes
430 );
431 }
432 }
433
434 #[test]
435 fn everything_fits_in_one_deploy_when_budget_is_large() {
436 let circuits = vec![w("a", 1000), w("b", 1000), w("c", 1000)];
437 let b = budget(1_000_000, 5000, 2000);
438 let plan = plan_incremental_deploy(&circuits, &b).unwrap();
439 assert!(plan.is_single_shot());
440 assert_eq!(plan.deploy_batch.len(), 3);
441 assert_eq!(plan.total_transactions(), 1);
442 assert_eq!(plan.total_circuits(), 3);
443 }
444
445 #[test]
446 fn splits_across_deploy_and_maintenance_when_over_budget() {
447 let circuits = vec![w("a", 1000), w("b", 1000), w("c", 1000), w("d", 1000)];
451 let b = budget(2000, 800, 100);
452 let plan = plan_incremental_deploy(&circuits, &b).unwrap();
453 assert_eq!(plan.deploy_batch.len(), 1);
454 assert_eq!(plan.maintenance_batches.len(), 3);
455 assert_eq!(plan.total_circuits(), 4);
456 assert_within_budget(&plan, &circuits, &b);
457 }
458
459 #[test]
460 fn packs_multiple_small_circuits_per_maintenance_batch() {
461 let circuits: Vec<_> = (0..10).map(|i| w(&format!("c{i:02}"), 100)).collect();
465 let b = budget(1000, 950, 100);
466 let plan = plan_incremental_deploy(&circuits, &b).unwrap();
467 assert_eq!(plan.deploy_batch, [] as [CircuitId; 0]);
468 assert_eq!(plan.total_circuits(), 10);
469 assert_eq!(plan.maintenance_batches.len(), 2);
471 assert_within_budget(&plan, &circuits, &b);
472 }
473
474 #[test]
475 fn deploy_batch_packs_largest_first() {
476 let circuits = vec![w("small", 100), w("big", 1000), w("mid", 500)];
477 let b = budget(2000, 500, 100);
479 let plan = plan_incremental_deploy(&circuits, &b).unwrap();
480 assert!(plan.deploy_batch.contains(&CircuitId::new("big")));
481 assert!(plan.deploy_batch.contains(&CircuitId::new("mid")));
482 assert_within_budget(&plan, &circuits, &b);
483 }
484
485 #[test]
486 fn errors_when_a_single_vk_exceeds_capacity() {
487 let circuits = vec![w("huge", 5000)];
488 let b = budget(2000, 800, 100); let err = plan_incremental_deploy(&circuits, &b).unwrap_err();
490 assert!(format!("{err}").contains("huge"), "{err}");
491 assert!(format!("{err}").contains("raise --max-tx-bytes"), "{err}");
492 }
493
494 #[test]
495 fn errors_when_budget_below_maintenance_overhead() {
496 let circuits = vec![w("a", 10)];
497 let b = budget(100, 50, 100); let err = plan_incremental_deploy(&circuits, &b).unwrap_err();
499 assert!(
500 format!("{err}").contains("maintenance-tx overhead"),
501 "{err}"
502 );
503 }
504
505 #[test]
506 fn empty_contract_yields_lone_deploy() {
507 let plan = plan_incremental_deploy(&[], &budget(1000, 500, 100)).unwrap();
508 assert_eq!(plan.deploy_batch, [] as [CircuitId; 0]);
509 assert_eq!(plan.maintenance_batches, [] as [Vec<CircuitId>; 0]);
510 assert_eq!(plan.total_transactions(), 1);
511 assert!(plan.is_single_shot());
512 }
513
514 #[test]
515 fn plan_is_deterministic_for_equal_sizes() {
516 let circuits = vec![w("c", 100), w("a", 100), w("b", 100)];
517 let b = budget(1000, 950, 100);
518 let p1 = plan_incremental_deploy(&circuits, &b).unwrap();
519 let p2 = plan_incremental_deploy(&circuits, &b).unwrap();
520 assert_eq!(p1, p2);
521 }
522
523 fn writes(bytes_written: u64) -> CostVector {
524 CostVector {
525 bytes_written,
526 ..CostVector::ZERO
527 }
528 }
529
530 fn costed(id: &str, deploy_writes: u64, maintenance_writes: u64) -> CircuitWeight {
531 CircuitWeight {
532 id: CircuitId::new(id),
533 vk_bytes: 100,
534 deploy_cost: writes(deploy_writes),
535 maintenance_cost: writes(maintenance_writes),
536 }
537 }
538
539 fn cost_budget(max_writes: u64, deploy_writes: u64, maintenance_writes: u64) -> PackBudget {
540 PackBudget {
541 max_tx_bytes: 1_000_000,
542 deploy_overhead: 0,
543 maintenance_overhead: 0,
544 max_cost: CostVector {
545 bytes_written: max_writes,
546 ..CostVector::UNBOUNDED
547 },
548 deploy_overhead_cost: writes(deploy_writes),
549 maintenance_overhead_cost: writes(maintenance_writes),
550 }
551 }
552
553 #[test]
554 fn splits_by_cost_when_bytes_fit_one_transaction() {
555 let circuits: Vec<_> = (0..5)
558 .map(|i| costed(&format!("c{i}"), 3000, 3000))
559 .collect();
560 let plan = plan_incremental_deploy(&circuits, &cost_budget(7000, 1000, 500)).unwrap();
561 assert_eq!(plan.deploy_batch.len(), 2);
562 assert_eq!(
563 plan.maintenance_batches,
564 vec![
565 vec![CircuitId::new("c2"), CircuitId::new("c3")],
566 vec![CircuitId::new("c4")],
567 ]
568 );
569 }
570
571 #[test]
572 fn errors_when_a_lone_circuit_exceeds_the_cost_limit() {
573 let circuits = vec![costed("heavy", 9000, 9000)];
574 let err = plan_incremental_deploy(&circuits, &cost_budget(7000, 1000, 500)).unwrap_err();
575 let message = format!("{err}");
576 assert!(message.contains("heavy"), "{message}");
577 assert!(message.contains("bytes written"), "{message}");
578 }
579
580 #[test]
581 fn errors_when_an_empty_deploy_exceeds_the_cost_limit() {
582 let err = plan_incremental_deploy(&[], &cost_budget(7000, 8000, 500)).unwrap_err();
583 assert!(format!("{err}").contains("empty deploy"), "{err}");
584 }
585}