Skip to main content

moonproof_contracts/incremental_deploy/
plan.rs

1//! Pure bin-packing for an incremental deploy.
2//!
3//! Given each circuit's measured share of a deploy / maintenance
4//! transaction — its bytes and its modelled cost — and the measured
5//! fixed overhead of each transaction kind, decide which circuits ship
6//! in the deploy and how the rest group into maintenance batches, so
7//! every transaction stays within the per-transaction limits.
8//!
9//! Kept free of IO and ledger types so it can be exhaustively unit
10//! tested with synthetic sizes; the orchestrator supplies the measured
11//! weights and overheads, and checks each planned batch against the
12//! ledger's own cost model before using it.
13
14use crate::error::{ContractRuntimeError, Result};
15use crate::types::CircuitId;
16
17/// A transaction's modelled cost, one entry per dimension of the
18/// ledger's `SyntheticCost`, durations in picoseconds.
19#[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    /// A capacity no cost reaches: packs by bytes alone.
38    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    /// `true` when no dimension exceeds `capacity`'s.
79    #[must_use]
80    pub fn fits_within(self, capacity: Self) -> bool {
81        self.first_excess(capacity).is_none()
82    }
83
84    /// The first dimension over `capacity`: its name, this value, and
85    /// the capacity.
86    #[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    /// The largest share of `capacity` any dimension takes.
96    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/// `used / capacity`, compared exactly by cross-multiplying; a share of
106/// no capacity is unbounded unless nothing is used.
107#[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        // Operands are at most `u64::MAX`, so the products fit in u128.
153        (self.used * other.capacity).cmp(&(other.used * self.capacity))
154    }
155}
156
157/// One circuit's contribution to a transaction: its verifier-key byte
158/// length, which is what the operations table (deploy) or the
159/// `VerifierKeyInsert` update (maintenance) actually carries, and the
160/// cost it adds to each kind of transaction.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct CircuitWeight {
163    pub id: CircuitId,
164    pub vk_bytes: usize,
165    /// The cost installing the key in the deploy adds.
166    pub deploy_cost: CostVector,
167    /// The cost installing the key in a maintenance transaction adds.
168    pub maintenance_cost: CostVector,
169}
170
171/// The budget the planner packs against.
172#[derive(Debug, Clone, Copy)]
173pub struct PackBudget {
174    /// Ceiling for any single transaction's projected size: the
175    /// smallest of the user's `--max-tx-bytes` and the ledger's and the
176    /// node's per-transaction byte limits.
177    pub max_tx_bytes: usize,
178    /// Measured fixed size of a deploy transaction carrying zero
179    /// circuits — the ledger state, maintenance authority, intent, and
180    /// serialization framing. The orchestrator obtains it by building an
181    /// empty-subset deploy tx.
182    pub deploy_overhead: usize,
183    /// Measured fixed size of a maintenance transaction carrying zero
184    /// verifier-key payload — the update framing, signature, and intent.
185    pub maintenance_overhead: usize,
186    /// The modelled cost any single transaction may reach.
187    pub max_cost: CostVector,
188    /// Measured cost of a deploy transaction carrying zero circuits.
189    pub deploy_overhead_cost: CostVector,
190    /// Measured cost of a maintenance transaction carrying zero updates.
191    pub maintenance_overhead_cost: CostVector,
192}
193
194/// The decided batches. The deploy transaction always happens (it
195/// creates the contract and its ledger state); `deploy_batch` is the
196/// circuits installed alongside it and may be empty. Each entry of
197/// `maintenance_batches` is one follow-up `VerifierKeyInsert`
198/// transaction.
199#[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    /// Total circuits across deploy + maintenance.
207    #[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    /// Total transactions: the deploy plus one per maintenance batch.
213    #[must_use]
214    pub fn total_transactions(&self) -> usize {
215        1 + self.maintenance_batches.len()
216    }
217
218    /// `true` when the whole contract fits in the deploy transaction —
219    /// no maintenance passes needed.
220    #[must_use]
221    pub fn is_single_shot(&self) -> bool {
222        self.maintenance_batches.is_empty()
223    }
224}
225
226/// A batch's running load: bytes and cost.
227#[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
246/// Pack circuits into a deploy batch + maintenance batches under the
247/// budget, the heaviest first (first-fit-decreasing on each circuit's
248/// dominant share of the per-transaction limits).
249///
250/// # Errors
251///
252/// - [`ContractRuntimeError::Provider`] if `max_tx_bytes` leaves no room
253///   for even an empty maintenance transaction
254///   (`max_tx_bytes <= maintenance_overhead`), if an empty deploy or
255///   maintenance transaction already exceeds the cost limit, or if some
256///   circuit's verifier key alone cannot fit any transaction at this
257///   budget.
258pub fn plan_incremental_deploy(
259    circuits: &[CircuitWeight],
260    budget: &PackBudget,
261) -> Result<DeployPlan> {
262    // Maintenance is the universal path — every circuit can be installed
263    // by a maintenance tx, so its capacity gates feasibility. The deploy
264    // batch is an optimization that piggybacks circuits onto the deploy
265    // when its (larger) overhead leaves room.
266    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    // First-fit-decreasing: heaviest first packs tightest.
285    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    // Phase 1 — fill the single deploy batch.
297    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    // Phase 2 — first-fit-decreasing the rest into maintenance bins.
314    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
337/// Refuse a budget no plan can meet: an empty transaction already over
338/// the cost limit, or a circuit too heavy for a maintenance transaction
339/// of its own.
340fn 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    // Reject any circuit too large for the universal (maintenance) path.
357    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    /// Helper: every batch's packed VK bytes stay within capacity.
414    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        // Each VK 1000 bytes. Deploy overhead 800, maintenance 100,
448        // budget 2000 → deploy_cap 1200 (1 circuit), maint_cap 1900 (1
449        // circuit per batch since 2 would be 2000 > 1900).
450        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        // 10 circuits of 100 bytes. Deploy overhead 950, maint 100,
462        // budget 1000 → deploy_cap 50 (none fit), maint_cap 900 (9 per
463        // batch). Expect deploy empty, 2 maintenance batches (9 + 1).
464        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        // 9 fit per maintenance batch (900 cap / 100) → 2 batches.
470        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        // Deploy cap = 1500: big(1000)+mid(500) fit, small spills.
478        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); // maint_cap 1900 < 5000
489        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); // max_tx_bytes <= maintenance_overhead
498        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        // Each circuit writes 3000 bytes in either transaction; 7000 may
556        // be written per transaction, 1000 already by the deploy.
557        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}