Skip to main content

moonproof_contracts/
profile.rs

1//! Circuit ZK constraint, 5-dimensional block-budget, and DUST fee
2//! profiling for compiled Compact contracts.
3//!
4//! Every measurement in this module comes directly from the Midnight
5//! prover and ledger crates — zero invented formulas or heuristics:
6//!
7//! - Circuit `k`, `rows`, and ZKIR major version come from
8//!   [`moonproof_prover::VersionedIr`] (`parse_zkir_tagged` / `parse_zkir_json`).
9//! - Opcode histograms and public I/O counts come from the compiled
10//!   `.zkir` JSON when present alongside `.bzkir`.
11//! - Deploy transaction bytes and 5-dimensional `SyntheticCost`
12//!   (`read_time`, `compute_time`, `block_usage`, `bytes_written`,
13//!   `bytes_churned`) come from [`measure_tx`] (`Transaction::cost`).
14//! - Per-transaction block-budget caps and incremental split counts
15//!   come from [`TransactionBudget`] and [`plan_deploy`].
16//! - DUST fees in atomic Specks come from `Transaction::fees_with_margin`.
17
18use std::collections::{BTreeMap, BTreeSet, HashMap};
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21
22use moonproof_ledger::base_crypto::time::Timestamp;
23use moonproof_ledger::ledger::structure::{LedgerParameters, INITIAL_PARAMETERS};
24use moonproof_prover::{parse_zkir_json, parse_zkir_tagged, VersionedIr};
25use moonproof_runtime::{IrExecutable, NoWitnesses};
26use moonproof_runtime_ir::RuntimeValue;
27use rand::rngs::StdRng;
28use rand::SeedableRng;
29use serde::{Deserialize, Serialize};
30
31use crate::error::{ContractRuntimeError, Result};
32use crate::incremental_deploy::{
33    build_sizing_maintenance_tx, measure_tx, plan_deploy, PlannedCircuit, TransactionBudget,
34    DEFAULT_MAX_TX_BYTES,
35};
36use crate::providers::{
37    FacadeWalletProvider, FileSystemZkConfigProvider, HasWallet, HasZkConfig, ZkConfigProvider,
38};
39use crate::types::CircuitId;
40use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};
41
42/// Snapshot schema version emitted to `.moonproof-snapshot`.
43pub const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
44
45/// Utilization threshold in basis points (`85.00%`) at or above which
46/// a circuit is flagged as close to the next power-of-2 Halo2 `k` cliff.
47pub const NEAR_CLIFF_THRESHOLD_BPS: u32 = 8_500;
48
49/// Standard five-block fee margin matching the wallet balancer.
50pub const STANDARD_FEE_MARGIN_BLOCKS: usize = 5;
51
52/// Deterministic offline timestamp used for sizing transactions.
53const SIZING_TIMESTAMP_SECS: u64 = 1_700_000_000;
54
55/// Deterministic RNG seed so offline snapshots are byte-for-byte
56/// reproducible across runs.
57const SIZING_RNG_SEED: u64 = 0x5A0A_5A0A_0011_0001;
58
59/// Return the compiled ledger era tag (`"ledger9"` or `"ledger8"`).
60#[must_use]
61pub fn ledger_era_name() -> &'static str {
62    if moonproof_ledger::HAS_ZKIR_V3 {
63        "ledger9"
64    } else {
65        "ledger8"
66    }
67}
68
69/// Serialize `u128` as a decimal string so JSON consumers (including JS
70/// with 53-bit `Number` precision) never truncate Speck totals.
71mod u128_as_string {
72    use serde::{Deserialize, Deserializer, Serializer};
73
74    pub fn serialize<S: Serializer>(val: &u128, serializer: S) -> Result<S::Ok, S::Error> {
75        serializer.serialize_str(&val.to_string())
76    }
77
78    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u128, D::Error> {
79        let s = String::deserialize(deserializer)?;
80        s.parse::<u128>().map_err(serde::de::Error::custom)
81    }
82}
83
84// =====================================================================
85// Data model
86// =====================================================================
87
88/// Per-circuit ZK constraint and artifact profile.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct CircuitProfile {
91    pub name: String,
92    pub zkir_version: u8,
93    pub k: u8,
94    pub domain_size: u64,
95    pub rows: usize,
96    pub headroom_rows: u64,
97    /// `rows / 2^k` in basis points (`0..=10_000`).
98    pub utilization_bps: u32,
99    /// `true` when `utilization_bps >= NEAR_CLIFF_THRESHOLD_BPS`.
100    pub near_cliff: bool,
101    pub prover_key_bytes: u64,
102    pub verifier_key_bytes: u64,
103    pub bzkir_bytes: u64,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub public_inputs: Option<usize>,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub public_outputs: Option<usize>,
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub instruction_count: Option<usize>,
110    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
111    pub opcode_histogram: BTreeMap<String, usize>,
112}
113
114/// One measured cost dimension against its per-transaction node cap.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct CostDimension {
117    pub used: u64,
118    pub limit: u64,
119    /// Usage share in basis points (`10_000` = 100%; values above
120    /// `10_000` exceed the per-transaction cap).
121    pub pct_bps: u32,
122}
123
124impl CostDimension {
125    /// Compute a cost dimension's basis-point utilization against `limit`.
126    #[must_use]
127    pub fn new(used: u64, limit: u64) -> Self {
128        let pct_bps = if limit == 0 {
129            if used == 0 {
130                0
131            } else {
132                u32::MAX
133            }
134        } else {
135            let scaled = u128::from(used).saturating_mul(10_000) / u128::from(limit);
136            u32::try_from(scaled).unwrap_or(u32::MAX)
137        };
138        Self {
139            used,
140            limit,
141            pct_bps,
142        }
143    }
144
145    /// `true` when `used > limit`.
146    #[must_use]
147    pub fn exceeded(&self) -> bool {
148        self.used > self.limit
149    }
150}
151
152/// Deploy transaction budget, 5D `SyntheticCost`, incremental split
153/// plan, and exact ledger DUST fee profile.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155pub struct DeployProfile {
156    pub params_source: String,
157    pub single_shot_fits: bool,
158    pub total_transactions: usize,
159    pub maintenance_passes: usize,
160    pub tx_bytes: CostDimension,
161    pub read_time_ps: CostDimension,
162    pub compute_time_ps: CostDimension,
163    pub block_usage: CostDimension,
164    pub bytes_written: CostDimension,
165    pub bytes_churned: CostDimension,
166    pub bottleneck_dimension: String,
167    /// Exact ledger fee (`tx.fees_with_margin(&params, 0)`) in atomic
168    /// Specks. When `single_shot_fits` is `true`, this is the single
169    /// deploy transaction's fee; when incremental deploy is required,
170    /// this is the sum across the planned deploy + maintenance passes.
171    #[serde(with = "u128_as_string")]
172    pub estimated_dust_specks: u128,
173    /// Exact ledger fee (`tx.fees_with_margin(&params, 5)`) in atomic
174    /// Specks with the standard 5-block margin.
175    #[serde(with = "u128_as_string")]
176    pub estimated_dust_with_margin_specks: u128,
177    #[serde(default, skip_serializing_if = "Vec::is_empty")]
178    pub deploy_batch: Vec<String>,
179    #[serde(default, skip_serializing_if = "Vec::is_empty")]
180    pub maintenance_batches: Vec<Vec<String>>,
181}
182
183/// Complete profile for a single compiled contract.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185pub struct ContractProfile {
186    pub name: String,
187    pub circuits: BTreeMap<String, CircuitProfile>,
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub deploy: Option<DeployProfile>,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub deploy_note: Option<String>,
192}
193
194/// Deterministic `.moonproof-snapshot` file format.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub struct SnapshotFile {
197    pub schema_version: u32,
198    pub ledger_era: String,
199    pub params_source: String,
200    pub contracts: BTreeMap<String, ContractProfile>,
201}
202
203impl SnapshotFile {
204    /// Create an empty snapshot stamped with the current schema version
205    /// and ledger era.
206    #[must_use]
207    pub fn new(params_source: impl Into<String>) -> Self {
208        Self {
209            schema_version: SNAPSHOT_SCHEMA_VERSION,
210            ledger_era: ledger_era_name().to_owned(),
211            params_source: params_source.into(),
212            contracts: BTreeMap::new(),
213        }
214    }
215
216    /// Serialize deterministically as pretty-printed JSON with a
217    /// trailing newline.
218    ///
219    /// # Errors
220    ///
221    /// Propagates `serde_json` serialization failures.
222    pub fn to_pretty_json(&self) -> std::result::Result<String, serde_json::Error> {
223        let mut s = serde_json::to_string_pretty(self)?;
224        s.push('\n');
225        Ok(s)
226    }
227
228    /// Parse a previously written snapshot file.
229    ///
230    /// # Errors
231    ///
232    /// Propagates `serde_json` parse errors.
233    pub fn from_json(input: &str) -> std::result::Result<Self, serde_json::Error> {
234        serde_json::from_str(input)
235    }
236}
237
238/// Inputs shaping [`profile_contract_dir`].
239#[derive(Clone)]
240pub struct ProfileOptions {
241    /// Ledger parameters used for cost modelling and DUST fee pricing.
242    /// Defaults to `INITIAL_PARAMETERS` for deterministic offline CI.
243    pub params: LedgerParameters,
244    /// Human-readable provenance tag stored in the output (e.g.
245    /// `"initial-parameters"` or `"network:preprod@height:12345"`).
246    pub params_source: String,
247    /// Optional tighter per-transaction byte ceiling.
248    pub max_tx_bytes: usize,
249    /// Constructor arguments when the contract declares a non-empty
250    /// constructor. `None` runs zero-arg constructors automatically and
251    /// skips deploy profiling cleanly when constructor args are required.
252    pub constructor_args: Option<RuntimeValue>,
253    /// Network id stamped onto synthetic sizing transactions.
254    pub network_id: String,
255    /// Include per-opcode ZKIR instruction histograms from `.zkir` JSON.
256    pub include_opcodes: bool,
257}
258
259impl Default for ProfileOptions {
260    fn default() -> Self {
261        Self {
262            params: INITIAL_PARAMETERS.clone(),
263            params_source: "initial-parameters".to_owned(),
264            max_tx_bytes: DEFAULT_MAX_TX_BYTES,
265            constructor_args: None,
266            network_id: "local-test".to_owned(),
267            include_opcodes: false,
268        }
269    }
270}
271
272// =====================================================================
273// Offline provider bundle (wallet + filesystem zk-config only)
274// =====================================================================
275
276struct OfflineSizingProviders {
277    wallet: FacadeWalletProvider,
278    zk_config: FileSystemZkConfigProvider,
279}
280
281impl OfflineSizingProviders {
282    fn new(contract_dir: &Path) -> Self {
283        Self {
284            wallet: FacadeWalletProvider::zero_keys(),
285            zk_config: FileSystemZkConfigProvider::new(contract_dir.to_path_buf()),
286        }
287    }
288}
289
290impl HasWallet for OfflineSizingProviders {
291    type Wallet = FacadeWalletProvider;
292    fn wallet(&self) -> &Self::Wallet {
293        &self.wallet
294    }
295}
296
297impl HasZkConfig for OfflineSizingProviders {
298    type ZkConfig = FileSystemZkConfigProvider;
299    fn zk_config(&self) -> &Self::ZkConfig {
300        &self.zk_config
301    }
302}
303
304// =====================================================================
305// Circuit & contract profiling
306// =====================================================================
307
308#[derive(Deserialize)]
309struct ZkirJsonSummary {
310    #[serde(default)]
311    inputs: Vec<serde_json::Value>,
312    #[serde(default)]
313    outputs: Vec<serde_json::Value>,
314    #[serde(default)]
315    instructions: Vec<ZkirJsonInstruction>,
316}
317
318#[derive(Deserialize)]
319struct ZkirJsonInstruction {
320    op: String,
321}
322
323fn file_len_or_zero(path: &Path) -> u64 {
324    std::fs::metadata(path).map_or(0, |m| m.len())
325}
326
327fn load_versioned_ir(contract_dir: &Path, circuit_name: &str) -> Result<VersionedIr> {
328    let bzkir_path = contract_dir
329        .join("zkir")
330        .join(format!("{circuit_name}.bzkir"));
331    if bzkir_path.exists() {
332        let bytes = std::fs::read(&bzkir_path).map_err(|e| ContractRuntimeError::Provider {
333            provider: "profile_circuit",
334            message: format!("reading {}: {e}", bzkir_path.display()),
335        })?;
336        return parse_zkir_tagged(&bytes).map_err(|e| ContractRuntimeError::Provider {
337            provider: "profile_circuit",
338            message: format!("parsing {}: {e}", bzkir_path.display()),
339        });
340    }
341
342    let zkir_path = contract_dir
343        .join("zkir")
344        .join(format!("{circuit_name}.zkir"));
345    if zkir_path.exists() {
346        let json =
347            std::fs::read_to_string(&zkir_path).map_err(|e| ContractRuntimeError::Provider {
348                provider: "profile_circuit",
349                message: format!("reading {}: {e}", zkir_path.display()),
350            })?;
351        return parse_zkir_json(&json).map_err(|e| ContractRuntimeError::Provider {
352            provider: "profile_circuit",
353            message: format!("parsing {}: {e}", zkir_path.display()),
354        });
355    }
356
357    Err(ContractRuntimeError::Provider {
358        provider: "profile_circuit",
359        message: format!(
360            "neither zkir/{circuit_name}.bzkir nor zkir/{circuit_name}.zkir exists under {}",
361            contract_dir.display()
362        ),
363    })
364}
365
366/// Profile a single circuit inside a compiled contract output directory.
367///
368/// # Errors
369///
370/// Returns an error when the circuit's `.bzkir` / `.zkir` artifact is
371/// missing or fails to parse under the active ledger era's ZKIR loader.
372pub fn profile_circuit(
373    contract_dir: &Path,
374    circuit_name: &str,
375    include_opcodes: bool,
376) -> Result<CircuitProfile> {
377    let ir = load_versioned_ir(contract_dir, circuit_name)?;
378    let zkir_version = ir.major();
379    let (k, rows) = ir.k_and_rows();
380    let domain_size = 1u64.checked_shl(u32::from(k)).unwrap_or(u64::MAX);
381    let rows_u64 = u64::try_from(rows).unwrap_or(u64::MAX);
382    let headroom_rows = domain_size.saturating_sub(rows_u64);
383    let utilization_bps = if domain_size == 0 {
384        10_000
385    } else {
386        let bps = u128::from(rows_u64).saturating_mul(10_000) / u128::from(domain_size);
387        u32::try_from(bps).unwrap_or(10_000).min(10_000)
388    };
389    let near_cliff = utilization_bps >= NEAR_CLIFF_THRESHOLD_BPS;
390
391    let keys_dir = contract_dir.join("keys");
392    let prover_key_bytes = file_len_or_zero(&keys_dir.join(format!("{circuit_name}.prover")));
393    let verifier_key_bytes = file_len_or_zero(&keys_dir.join(format!("{circuit_name}.verifier")));
394    let bzkir_bytes = file_len_or_zero(
395        &contract_dir
396            .join("zkir")
397            .join(format!("{circuit_name}.bzkir")),
398    );
399
400    let (public_inputs, public_outputs, instruction_count, opcode_histogram) =
401        parse_zkir_json_stats(
402            &contract_dir
403                .join("zkir")
404                .join(format!("{circuit_name}.zkir")),
405            include_opcodes,
406        );
407
408    Ok(CircuitProfile {
409        name: circuit_name.to_owned(),
410        zkir_version,
411        k,
412        domain_size,
413        rows,
414        headroom_rows,
415        utilization_bps,
416        near_cliff,
417        prover_key_bytes,
418        verifier_key_bytes,
419        bzkir_bytes,
420        public_inputs,
421        public_outputs,
422        instruction_count,
423        opcode_histogram,
424    })
425}
426
427fn parse_zkir_json_stats(
428    zkir_path: &Path,
429    include_opcodes: bool,
430) -> (
431    Option<usize>,
432    Option<usize>,
433    Option<usize>,
434    BTreeMap<String, usize>,
435) {
436    let Ok(raw) = std::fs::read_to_string(zkir_path) else {
437        return (None, None, None, BTreeMap::new());
438    };
439    let Ok(parsed) = serde_json::from_str::<ZkirJsonSummary>(&raw) else {
440        return (None, None, None, BTreeMap::new());
441    };
442    let mut histogram = BTreeMap::new();
443    if include_opcodes {
444        for instr in &parsed.instructions {
445            *histogram.entry(instr.op.clone()).or_insert(0) += 1;
446        }
447    }
448    (
449        Some(parsed.inputs.len()),
450        Some(parsed.outputs.len()),
451        Some(parsed.instructions.len()),
452        histogram,
453    )
454}
455
456fn locate_runtime_ir(contract_dir: &Path) -> Option<PathBuf> {
457    let nested = contract_dir.join("compiler").join("contract.mpir");
458    if nested.exists() {
459        return Some(nested);
460    }
461    let flat = contract_dir.join("contract.mpir");
462    if flat.exists() {
463        return Some(flat);
464    }
465    None
466}
467
468fn discover_zkir_circuit_names(contract_dir: &Path) -> BTreeSet<String> {
469    let mut names = BTreeSet::new();
470    let zkir_dir = contract_dir.join("zkir");
471    let Ok(entries) = std::fs::read_dir(&zkir_dir) else {
472        return names;
473    };
474    for entry in entries.flatten() {
475        let path = entry.path();
476        let ext = path.extension().and_then(|e| e.to_str());
477        if matches!(ext, Some("bzkir" | "zkir")) {
478            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
479                names.insert(stem.to_owned());
480            }
481        }
482    }
483    names
484}
485
486/// Profile every circuit and (when `contract.mpir` and constructor
487/// arguments are available) the deploy transaction's 5D block-budget
488/// and DUST fee for a compiled contract output directory.
489///
490/// # Errors
491///
492/// Returns an error if `contract_dir` does not exist, a circuit ZKIR
493/// fails to parse, or deploy transaction construction / ledger cost
494/// evaluation fails.
495pub async fn profile_contract_dir(
496    name: &str,
497    contract_dir: &Path,
498    options: &ProfileOptions,
499) -> Result<ContractProfile> {
500    if !contract_dir.exists() {
501        return Err(ContractRuntimeError::Provider {
502            provider: "profile_contract_dir",
503            message: format!(
504                "contract output directory does not exist: {}",
505                contract_dir.display()
506            ),
507        });
508    }
509
510    let ir_path = locate_runtime_ir(contract_dir);
511    let executable = match &ir_path {
512        Some(path) => Some(
513            IrExecutable::from_path(path, Arc::new(NoWitnesses)).map_err(|e| {
514                ContractRuntimeError::Provider {
515                    provider: "profile_contract_dir",
516                    message: format!("loading {}: {e}", path.display()),
517                }
518            })?,
519        ),
520        None => None,
521    };
522
523    // Prefer the IR's provable circuit list when available; fall back to
524    // scanning `zkir/` so raw compactc output directories work too.
525    let mut circuit_names = BTreeSet::new();
526    if let Some(exec) = &executable {
527        for id in exec.provable_circuit_ids() {
528            circuit_names.insert(id.as_str().to_owned());
529        }
530    }
531    if circuit_names.is_empty() {
532        circuit_names = discover_zkir_circuit_names(contract_dir);
533    }
534
535    let circuit_list: Vec<String> = circuit_names.into_iter().collect();
536    let circuits = profile_circuits_parallel(contract_dir, &circuit_list, options.include_opcodes)?;
537
538    let (deploy, deploy_note) = match executable {
539        None => (
540            None,
541            Some(
542                "contract.mpir not found; run `moonproof build` to enable deploy budget & DUST profiling"
543                    .to_owned(),
544            ),
545        ),
546        Some(exec) => profile_deploy(contract_dir, exec, options).await?,
547    };
548
549    Ok(ContractProfile {
550        name: name.to_owned(),
551        circuits,
552        deploy,
553        deploy_note,
554    })
555}
556
557fn profile_circuits_parallel(
558    contract_dir: &Path,
559    circuit_names: &[String],
560    include_opcodes: bool,
561) -> Result<BTreeMap<String, CircuitProfile>> {
562    if circuit_names.len() <= 1 {
563        let mut out = BTreeMap::new();
564        for cname in circuit_names {
565            let prof = profile_circuit(contract_dir, cname, include_opcodes)?;
566            out.insert(cname.clone(), prof);
567        }
568        return Ok(out);
569    }
570
571    // `IrSource::model()` is pure CPU-bound Halo2 layout synthesis; fan
572    // out across OS threads bounded by available parallelism.
573    let worker_count = std::thread::available_parallelism()
574        .map_or(4, std::num::NonZeroUsize::get)
575        .min(circuit_names.len());
576    let next_idx = std::sync::atomic::AtomicUsize::new(0);
577    let results: Vec<Result<Vec<(String, CircuitProfile)>>> = std::thread::scope(|scope| {
578        let mut handles = Vec::with_capacity(worker_count);
579        for _ in 0..worker_count {
580            handles.push(scope.spawn(|| {
581                let mut local = Vec::new();
582                loop {
583                    let i = next_idx.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
584                    let Some(cname) = circuit_names.get(i) else {
585                        break;
586                    };
587                    let prof = profile_circuit(contract_dir, cname, include_opcodes)?;
588                    local.push((cname.clone(), prof));
589                }
590                Ok(local)
591            }));
592        }
593        handles
594            .into_iter()
595            .map(|h| {
596                h.join().unwrap_or_else(|_| {
597                    Err(ContractRuntimeError::Provider {
598                        provider: "profile_contract_dir",
599                        message: "circuit profiling worker thread panicked".to_owned(),
600                    })
601                })
602            })
603            .collect()
604    });
605
606    let mut out = BTreeMap::new();
607    for worker_res in results {
608        for (cname, prof) in worker_res? {
609            out.insert(cname, prof);
610        }
611    }
612    Ok(out)
613}
614
615async fn load_planned_verifier_keys(
616    base_exec: &IrExecutable<NoWitnesses>,
617    providers: &OfflineSizingProviders,
618) -> std::result::Result<
619    (
620        Vec<PlannedCircuit>,
621        HashMap<String, crate::types::VerifierKey>,
622    ),
623    String,
624> {
625    let circuit_ids = base_exec.provable_circuit_ids();
626    let mut planned = Vec::with_capacity(circuit_ids.len());
627    let mut vk_map = HashMap::with_capacity(circuit_ids.len());
628    for id in circuit_ids {
629        let vk = providers
630            .zk_config
631            .get_verifier_key(&id)
632            .await
633            .map_err(|e| {
634                format!(
635                    "missing verifier key for `{}` ({e}); skipping deploy budget profiling",
636                    id.as_str()
637                )
638            })?;
639        vk_map.insert(id.as_str().to_owned(), vk.clone());
640        planned.push(PlannedCircuit { id, vk });
641    }
642    Ok((planned, vk_map))
643}
644
645async fn profile_deploy(
646    contract_dir: &Path,
647    base_exec: IrExecutable<NoWitnesses>,
648    options: &ProfileOptions,
649) -> Result<(Option<DeployProfile>, Option<String>)> {
650    let ctor_args_decl = &base_exec.ir().constructor.arguments;
651    let constructor_args = match (&options.constructor_args, ctor_args_decl.is_empty()) {
652        (Some(val), _) => val.clone(),
653        (None, true) => RuntimeValue::Null,
654        (None, false) => {
655            let names: Vec<&str> = ctor_args_decl.iter().map(|a| a.name.as_str()).collect();
656            return Ok((
657                None,
658                Some(format!(
659                    "contract constructor requires argument(s) [{}]; configure \
660                     [contracts.<name>.constructor_args] in moonproof.toml to profile deploy budget & DUST",
661                    names.join(", ")
662                )),
663            ));
664        }
665    };
666
667    let providers = OfflineSizingProviders::new(contract_dir);
668    let (planned, vk_map) = match load_planned_verifier_keys(&base_exec, &providers).await {
669        Ok(loaded) => loaded,
670        Err(note) => return Ok((None, Some(note))),
671    };
672    let executable = base_exec.with_verifier_keys(vk_map);
673
674    let deploy_opts = DeployOptions {
675        constructor_args,
676        initial_private_state: RuntimeValue::Null,
677        signing_key: None,
678        additional_coin_enc_public_key_mappings: None,
679        current_time: Timestamp::from_secs(SIZING_TIMESTAMP_SECS),
680        network_id: options.network_id.clone(),
681        persistent_state: None,
682        fee_balancing: None,
683        register_circuits: None,
684    };
685
686    let budget = TransactionBudget::new(&options.params, options.max_tx_bytes);
687    let mut rng = StdRng::seed_from_u64(SIZING_RNG_SEED);
688
689    let single_tx =
690        build_sizing_deploy_tx(&mut rng, &executable, &providers, &deploy_opts, None).await?;
691    let single_measure = measure_tx(&single_tx, &options.params)?;
692    let single_shot_fits = budget.excess(&single_measure).is_none();
693
694    let (
695        total_transactions,
696        maintenance_passes,
697        deploy_batch,
698        maintenance_batches,
699        estimated_dust_specks,
700        estimated_dust_with_margin_specks,
701    ) = if single_shot_fits {
702        let fee0 = tx_fee(&single_tx, &options.params, 0)?;
703        let fee5 = tx_fee(&single_tx, &options.params, STANDARD_FEE_MARGIN_BLOCKS)?;
704        let batch = planned.iter().map(|c| c.id.as_str().to_owned()).collect();
705        (1, 0, batch, Vec::new(), fee0, fee5)
706    } else {
707        plan_and_price_incremental(
708            &mut rng,
709            &executable,
710            &providers,
711            &deploy_opts,
712            &planned,
713            &budget,
714            &options.params,
715        )
716        .await?
717    };
718
719    Ok((
720        Some(assemble_deploy_profile(
721            &options.params_source,
722            single_shot_fits,
723            total_transactions,
724            maintenance_passes,
725            &single_measure,
726            &budget,
727            estimated_dust_specks,
728            estimated_dust_with_margin_specks,
729            deploy_batch,
730            maintenance_batches,
731        )),
732        None,
733    ))
734}
735
736#[allow(clippy::type_complexity)]
737async fn plan_and_price_incremental<C: HasWallet + HasZkConfig + ?Sized>(
738    rng: &mut StdRng,
739    executable: &IrExecutable<NoWitnesses>,
740    providers: &C,
741    deploy_opts: &DeployOptions,
742    planned: &[PlannedCircuit],
743    budget: &TransactionBudget,
744    params: &LedgerParameters,
745) -> Result<(usize, usize, Vec<String>, Vec<Vec<String>>, u128, u128)> {
746    let plan = plan_deploy(
747        rng,
748        executable,
749        providers,
750        deploy_opts,
751        planned,
752        budget,
753        params,
754    )
755    .await?;
756    let (fee0, fee5) = sum_incremental_fees(
757        rng,
758        executable,
759        providers,
760        deploy_opts,
761        planned,
762        &plan,
763        params,
764    )
765    .await?;
766    let d_batch = plan
767        .deploy_batch
768        .iter()
769        .map(|id| id.as_str().to_owned())
770        .collect();
771    let m_batches = plan
772        .maintenance_batches
773        .iter()
774        .map(|b| b.iter().map(|id| id.as_str().to_owned()).collect())
775        .collect();
776    Ok((
777        plan.total_transactions(),
778        plan.maintenance_batches.len(),
779        d_batch,
780        m_batches,
781        fee0,
782        fee5,
783    ))
784}
785
786#[allow(clippy::too_many_arguments)]
787fn assemble_deploy_profile(
788    params_source: &str,
789    single_shot_fits: bool,
790    total_transactions: usize,
791    maintenance_passes: usize,
792    single_measure: &crate::incremental_deploy::TxMeasure,
793    budget: &TransactionBudget,
794    estimated_dust_specks: u128,
795    estimated_dust_with_margin_specks: u128,
796    deploy_batch: Vec<String>,
797    maintenance_batches: Vec<Vec<String>>,
798) -> DeployProfile {
799    let tx_bytes = CostDimension::new(
800        u64::try_from(single_measure.bytes).unwrap_or(u64::MAX),
801        u64::try_from(budget.max_bytes).unwrap_or(u64::MAX),
802    );
803    let read_time_ps = CostDimension::new(
804        single_measure.cost.read_time.into_picoseconds(),
805        budget.max_cost.read_time.into_picoseconds(),
806    );
807    let compute_time_ps = CostDimension::new(
808        single_measure.cost.compute_time.into_picoseconds(),
809        budget.max_cost.compute_time.into_picoseconds(),
810    );
811    let block_usage =
812        CostDimension::new(single_measure.cost.block_usage, budget.max_cost.block_usage);
813    let bytes_written = CostDimension::new(
814        single_measure.cost.bytes_written,
815        budget.max_cost.bytes_written,
816    );
817    let bytes_churned = CostDimension::new(
818        single_measure.cost.bytes_churned,
819        budget.max_cost.bytes_churned,
820    );
821
822    let bottleneck_dimension = [
823        ("tx_bytes", tx_bytes.pct_bps),
824        ("read_time", read_time_ps.pct_bps),
825        ("compute_time", compute_time_ps.pct_bps),
826        ("block_usage", block_usage.pct_bps),
827        ("bytes_written", bytes_written.pct_bps),
828        ("bytes_churned", bytes_churned.pct_bps),
829    ]
830    .into_iter()
831    .max_by_key(|(_, pct)| *pct)
832    .map_or("tx_bytes", |(name, _)| name)
833    .to_owned();
834
835    DeployProfile {
836        params_source: params_source.to_owned(),
837        single_shot_fits,
838        total_transactions,
839        maintenance_passes,
840        tx_bytes,
841        read_time_ps,
842        compute_time_ps,
843        block_usage,
844        bytes_written,
845        bytes_churned,
846        bottleneck_dimension,
847        estimated_dust_specks,
848        estimated_dust_with_margin_specks,
849        deploy_batch,
850        maintenance_batches,
851    }
852}
853
854async fn build_sizing_deploy_tx<C: HasWallet + HasZkConfig + ?Sized>(
855    rng: &mut StdRng,
856    executable: &IrExecutable<NoWitnesses>,
857    providers: &C,
858    base: &DeployOptions,
859    register_circuits: Option<Vec<CircuitId>>,
860) -> Result<crate::tx_phase::UnprovenTx> {
861    let sizing = DeployOptions {
862        constructor_args: base.constructor_args.clone(),
863        initial_private_state: base.initial_private_state.clone(),
864        signing_key: None,
865        additional_coin_enc_public_key_mappings: base
866            .additional_coin_enc_public_key_mappings
867            .clone(),
868        current_time: base.current_time,
869        network_id: base.network_id.clone(),
870        persistent_state: None,
871        fee_balancing: base.fee_balancing.clone(),
872        register_circuits,
873    };
874    let unproven = create_unproven_deploy_tx(rng, executable, providers, sizing).await?;
875    unproven
876        .private
877        .unproven_tx
878        .ok_or_else(|| ContractRuntimeError::Provider {
879            provider: "profile_deploy",
880            message: "sizing deploy transaction was not populated".to_owned(),
881        })
882}
883
884fn tx_fee(
885    tx: &crate::tx_phase::UnprovenTx,
886    params: &LedgerParameters,
887    margin_blocks: usize,
888) -> Result<u128> {
889    tx.as_inner()
890        .fees_with_margin(params, margin_blocks)
891        .map_err(|e| ContractRuntimeError::Provider {
892            provider: "profile_deploy",
893            message: format!("ledger fee calculation failed (margin={margin_blocks}): {e:?}"),
894        })
895}
896
897async fn sum_incremental_fees<C: HasWallet + HasZkConfig + ?Sized>(
898    rng: &mut StdRng,
899    executable: &IrExecutable<NoWitnesses>,
900    providers: &C,
901    deploy_opts: &DeployOptions,
902    planned: &[PlannedCircuit],
903    plan: &crate::incremental_deploy::DeployPlan,
904    params: &LedgerParameters,
905) -> Result<(u128, u128)> {
906    let deploy_tx = build_sizing_deploy_tx(
907        rng,
908        executable,
909        providers,
910        deploy_opts,
911        Some(plan.deploy_batch.clone()),
912    )
913    .await?;
914    let mut total_fee0 = tx_fee(&deploy_tx, params, 0)?;
915    let mut total_fee5 = tx_fee(&deploy_tx, params, STANDARD_FEE_MARGIN_BLOCKS)?;
916
917    for batch in &plan.maintenance_batches {
918        let circuits: Vec<PlannedCircuit> = batch
919            .iter()
920            .filter_map(|id| planned.iter().find(|c| &c.id == id).cloned())
921            .collect();
922        let maint_tx = build_sizing_maintenance_tx(
923            rng,
924            &circuits,
925            &deploy_opts.network_id,
926            deploy_opts.current_time,
927            deploy_opts.fee_balancing.as_ref(),
928        )?;
929        total_fee0 = total_fee0.saturating_add(tx_fee(&maint_tx, params, 0)?);
930        total_fee5 =
931            total_fee5.saturating_add(tx_fee(&maint_tx, params, STANDARD_FEE_MARGIN_BLOCKS)?);
932    }
933
934    Ok((total_fee0, total_fee5))
935}
936
937// =====================================================================
938// Snapshot diff & CI regression policy
939// =====================================================================
940
941/// Thresholds evaluated by [`diff_snapshots`] to gate CI builds.
942#[derive(Debug, Clone, Copy, PartialEq)]
943pub struct SnapshotPolicy {
944    /// Maximum allowed circuit row growth percentage (`0.0` = no growth
945    /// allowed; `None` disables the row-growth check).
946    pub max_row_growth_pct: Option<f64>,
947    /// Maximum allowed deploy DUST fee growth percentage (`None`
948    /// disables the DUST-growth check).
949    pub max_dust_growth_pct: Option<f64>,
950    /// Allow Halo2 `k` to increase on any circuit.
951    pub allow_k_increase: bool,
952    /// Allow deploy transaction count to increase (e.g. single-shot ->
953    /// incremental, or extra maintenance pass).
954    pub allow_pass_increase: bool,
955}
956
957impl Default for SnapshotPolicy {
958    fn default() -> Self {
959        Self {
960            max_row_growth_pct: Some(0.0),
961            max_dust_growth_pct: None,
962            allow_k_increase: false,
963            allow_pass_increase: false,
964        }
965    }
966}
967
968/// Per-circuit delta between baseline and current snapshots.
969#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
970pub struct CircuitDiff {
971    pub circuit: String,
972    pub status: String,
973    pub baseline_k: Option<u8>,
974    pub current_k: Option<u8>,
975    pub k_delta: i16,
976    pub baseline_rows: Option<usize>,
977    pub current_rows: Option<usize>,
978    pub rows_delta: i64,
979    pub rows_pct_change: Option<f64>,
980    pub vk_bytes_delta: i64,
981    pub pk_bytes_delta: i64,
982}
983
984/// Per-contract deploy delta between baseline and current snapshots.
985#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
986pub struct DeployDiff {
987    pub baseline_transactions: usize,
988    pub current_transactions: usize,
989    pub transactions_delta: i64,
990    pub tx_bytes_delta: i64,
991    pub bytes_written_delta: i64,
992    pub dust_delta_specks: i128,
993    pub dust_pct_change: Option<f64>,
994}
995
996/// Per-contract comparison summary.
997#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
998pub struct ContractDiff {
999    pub contract: String,
1000    pub circuits: Vec<CircuitDiff>,
1001    #[serde(default, skip_serializing_if = "Option::is_none")]
1002    pub deploy: Option<DeployDiff>,
1003}
1004
1005/// One policy violation discovered by [`diff_snapshots`].
1006#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1007pub struct Regression {
1008    pub contract: String,
1009    #[serde(default, skip_serializing_if = "Option::is_none")]
1010    pub circuit: Option<String>,
1011    pub message: String,
1012}
1013
1014/// Full structured diff + policy evaluation between two snapshots.
1015#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1016pub struct SnapshotDiff {
1017    pub contracts: Vec<ContractDiff>,
1018    pub regressions: Vec<Regression>,
1019}
1020
1021impl SnapshotDiff {
1022    /// `true` when zero policy regressions were recorded.
1023    #[must_use]
1024    pub fn passed(&self) -> bool {
1025        self.regressions.is_empty()
1026    }
1027}
1028
1029fn signed_delta_u64(before: u64, after: u64) -> i64 {
1030    i64::try_from(i128::from(after) - i128::from(before)).unwrap_or(i64::MAX)
1031}
1032
1033fn signed_delta_usize(before: usize, after: usize) -> i64 {
1034    let b = i128::try_from(before).unwrap_or(i128::MAX);
1035    let a = i128::try_from(after).unwrap_or(i128::MAX);
1036    i64::try_from(a - b).unwrap_or(i64::MAX)
1037}
1038
1039#[allow(clippy::cast_precision_loss)]
1040fn pct_change_u128(before: u128, after: u128) -> Option<f64> {
1041    if before == 0 {
1042        return None;
1043    }
1044    let delta = (after as f64) - (before as f64);
1045    Some((delta / (before as f64)) * 100.0)
1046}
1047
1048/// Compare `current` against `baseline` and evaluate every contract and
1049/// circuit against `policy`.
1050#[must_use]
1051pub fn diff_snapshots(
1052    baseline: &SnapshotFile,
1053    current: &SnapshotFile,
1054    policy: &SnapshotPolicy,
1055) -> SnapshotDiff {
1056    let mut all_contracts: BTreeSet<&str> = BTreeSet::new();
1057    for k in baseline.contracts.keys() {
1058        all_contracts.insert(k.as_str());
1059    }
1060    for k in current.contracts.keys() {
1061        all_contracts.insert(k.as_str());
1062    }
1063
1064    let mut contracts = Vec::new();
1065    let mut regressions = Vec::new();
1066
1067    for cname in all_contracts {
1068        let base_c = baseline.contracts.get(cname);
1069        let curr_c = current.contracts.get(cname);
1070        let circuit_diffs = diff_contract_circuits(cname, base_c, curr_c, policy, &mut regressions);
1071        let deploy_diff = diff_contract_deploy(cname, base_c, curr_c, policy, &mut regressions);
1072
1073        contracts.push(ContractDiff {
1074            contract: cname.to_owned(),
1075            circuits: circuit_diffs,
1076            deploy: deploy_diff,
1077        });
1078    }
1079
1080    SnapshotDiff {
1081        contracts,
1082        regressions,
1083    }
1084}
1085
1086fn diff_contract_circuits(
1087    cname: &str,
1088    base_c: Option<&ContractProfile>,
1089    curr_c: Option<&ContractProfile>,
1090    policy: &SnapshotPolicy,
1091    regressions: &mut Vec<Regression>,
1092) -> Vec<CircuitDiff> {
1093    let mut all_circuits: BTreeSet<&str> = BTreeSet::new();
1094    if let Some(c) = base_c {
1095        for k in c.circuits.keys() {
1096            all_circuits.insert(k.as_str());
1097        }
1098    }
1099    if let Some(c) = curr_c {
1100        for k in c.circuits.keys() {
1101            all_circuits.insert(k.as_str());
1102        }
1103    }
1104
1105    let mut out = Vec::new();
1106    for circ in all_circuits {
1107        let b = base_c.and_then(|c| c.circuits.get(circ));
1108        let cur = curr_c.and_then(|c| c.circuits.get(circ));
1109        match (b, cur) {
1110            (Some(b), Some(cur)) => {
1111                let k_delta = i16::from(cur.k) - i16::from(b.k);
1112                let rows_delta = signed_delta_usize(b.rows, cur.rows);
1113                let rows_pct = pct_change_u128(b.rows as u128, cur.rows as u128);
1114                let vk_delta = signed_delta_u64(b.verifier_key_bytes, cur.verifier_key_bytes);
1115                let pk_delta = signed_delta_u64(b.prover_key_bytes, cur.prover_key_bytes);
1116                let status = if k_delta == 0 && rows_delta == 0 && vk_delta == 0 && pk_delta == 0 {
1117                    "unchanged"
1118                } else {
1119                    "changed"
1120                };
1121
1122                if !policy.allow_k_increase && k_delta > 0 {
1123                    regressions.push(Regression {
1124                        contract: cname.to_owned(),
1125                        circuit: Some(circ.to_owned()),
1126                        message: format!(
1127                            "Halo2 k increased from {} to {} (+{k_delta}, doubling proving domain)",
1128                            b.k, cur.k
1129                        ),
1130                    });
1131                }
1132                if let (Some(max_pct), Some(pct)) = (policy.max_row_growth_pct, rows_pct) {
1133                    if rows_delta > 0 && pct > max_pct {
1134                        regressions.push(Regression {
1135                            contract: cname.to_owned(),
1136                            circuit: Some(circ.to_owned()),
1137                            message: format!(
1138                                "rows grew from {} to {} (+{rows_delta}, +{pct:.2}% > max {max_pct:.2}%)",
1139                                b.rows, cur.rows
1140                            ),
1141                        });
1142                    }
1143                }
1144
1145                out.push(CircuitDiff {
1146                    circuit: circ.to_owned(),
1147                    status: status.to_owned(),
1148                    baseline_k: Some(b.k),
1149                    current_k: Some(cur.k),
1150                    k_delta,
1151                    baseline_rows: Some(b.rows),
1152                    current_rows: Some(cur.rows),
1153                    rows_delta,
1154                    rows_pct_change: rows_pct,
1155                    vk_bytes_delta: vk_delta,
1156                    pk_bytes_delta: pk_delta,
1157                });
1158            }
1159            (None, Some(cur)) => {
1160                out.push(CircuitDiff {
1161                    circuit: circ.to_owned(),
1162                    status: "added".to_owned(),
1163                    baseline_k: None,
1164                    current_k: Some(cur.k),
1165                    k_delta: i16::from(cur.k),
1166                    baseline_rows: None,
1167                    current_rows: Some(cur.rows),
1168                    rows_delta: i64::try_from(cur.rows).unwrap_or(i64::MAX),
1169                    rows_pct_change: None,
1170                    vk_bytes_delta: i64::try_from(cur.verifier_key_bytes).unwrap_or(i64::MAX),
1171                    pk_bytes_delta: i64::try_from(cur.prover_key_bytes).unwrap_or(i64::MAX),
1172                });
1173            }
1174            (Some(b), None) => {
1175                out.push(CircuitDiff {
1176                    circuit: circ.to_owned(),
1177                    status: "removed".to_owned(),
1178                    baseline_k: Some(b.k),
1179                    current_k: None,
1180                    k_delta: -i16::from(b.k),
1181                    baseline_rows: Some(b.rows),
1182                    current_rows: None,
1183                    rows_delta: -i64::try_from(b.rows).unwrap_or(i64::MAX),
1184                    rows_pct_change: None,
1185                    vk_bytes_delta: -i64::try_from(b.verifier_key_bytes).unwrap_or(i64::MAX),
1186                    pk_bytes_delta: -i64::try_from(b.prover_key_bytes).unwrap_or(i64::MAX),
1187                });
1188            }
1189            (None, None) => {}
1190        }
1191    }
1192    out
1193}
1194
1195fn diff_contract_deploy(
1196    cname: &str,
1197    base_c: Option<&ContractProfile>,
1198    curr_c: Option<&ContractProfile>,
1199    policy: &SnapshotPolicy,
1200    regressions: &mut Vec<Regression>,
1201) -> Option<DeployDiff> {
1202    let b = base_c.and_then(|c| c.deploy.as_ref())?;
1203    let cur = curr_c.and_then(|c| c.deploy.as_ref())?;
1204
1205    let transactions_delta = signed_delta_usize(b.total_transactions, cur.total_transactions);
1206    let tx_bytes_delta = signed_delta_u64(b.tx_bytes.used, cur.tx_bytes.used);
1207    let bytes_written_delta = signed_delta_u64(b.bytes_written.used, cur.bytes_written.used);
1208    let dust_delta = i128::try_from(cur.estimated_dust_specks).unwrap_or(i128::MAX)
1209        - i128::try_from(b.estimated_dust_specks).unwrap_or(i128::MAX);
1210    let dust_pct = pct_change_u128(b.estimated_dust_specks, cur.estimated_dust_specks);
1211
1212    if !policy.allow_pass_increase && transactions_delta > 0 {
1213        regressions.push(Regression {
1214            contract: cname.to_owned(),
1215            circuit: None,
1216            message: format!(
1217                "deploy transaction count increased from {} to {} (+{transactions_delta})",
1218                b.total_transactions, cur.total_transactions
1219            ),
1220        });
1221    }
1222    if let (Some(max_pct), Some(pct)) = (policy.max_dust_growth_pct, dust_pct) {
1223        if dust_delta > 0 && pct > max_pct {
1224            regressions.push(Regression {
1225                contract: cname.to_owned(),
1226                circuit: None,
1227                message: format!(
1228                    "deploy DUST fee grew from {} to {} Specks (+{pct:.2}% > max {max_pct:.2}%)",
1229                    b.estimated_dust_specks, cur.estimated_dust_specks
1230                ),
1231            });
1232        }
1233    }
1234
1235    Some(DeployDiff {
1236        baseline_transactions: b.total_transactions,
1237        current_transactions: cur.total_transactions,
1238        transactions_delta,
1239        tx_bytes_delta,
1240        bytes_written_delta,
1241        dust_delta_specks: dust_delta,
1242        dust_pct_change: dust_pct,
1243    })
1244}
1245
1246// =====================================================================
1247// Tests against real compiled fixtures
1248// =====================================================================
1249
1250#[cfg(test)]
1251mod tests {
1252    use super::*;
1253
1254    fn test_fixtures_contracts_dir() -> PathBuf {
1255        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1256        p.pop();
1257        p.push("test-fixtures/contracts");
1258        p
1259    }
1260
1261    fn runtime_ir_fixtures_dir() -> PathBuf {
1262        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1263        p.pop();
1264        p.push("runtime-ir/tests/fixtures");
1265        p
1266    }
1267
1268    #[tokio::test]
1269    async fn profiles_real_counter_fixture_with_opcodes_cost_and_dust() {
1270        if !moonproof_ledger::HAS_ZKIR_V3 {
1271            return;
1272        }
1273        let dir = test_fixtures_contracts_dir().join("counter");
1274        let opts = ProfileOptions {
1275            include_opcodes: true,
1276            ..ProfileOptions::default()
1277        };
1278        let profile = profile_contract_dir("counter", &dir, &opts).await.unwrap();
1279        assert_eq!(profile.name, "counter");
1280        assert!(profile.deploy_note.is_none());
1281
1282        let inc = profile
1283            .circuits
1284            .get("increment")
1285            .expect("increment circuit");
1286        assert_eq!(inc.zkir_version, 3);
1287        assert!(inc.k >= 4 && inc.k <= 20, "unexpected k={}", inc.k);
1288        assert_eq!(inc.domain_size, 1u64 << inc.k);
1289        assert!(inc.rows > 0 && (inc.rows as u64) <= inc.domain_size);
1290        assert_eq!(inc.headroom_rows, inc.domain_size - inc.rows as u64);
1291        assert!(inc.prover_key_bytes > 0);
1292        assert!(inc.verifier_key_bytes > 0);
1293        assert!(inc.bzkir_bytes > 0);
1294        assert_eq!(inc.instruction_count, Some(3));
1295        assert_eq!(inc.opcode_histogram.get("impact"), Some(&3));
1296
1297        let deploy = profile.deploy.expect("deploy profile");
1298        assert!(deploy.single_shot_fits);
1299        assert_eq!(deploy.total_transactions, 1);
1300        assert_eq!(deploy.maintenance_passes, 0);
1301        assert!(deploy.tx_bytes.used > 0);
1302        assert!(deploy.bytes_written.used > 0);
1303        assert!(deploy.compute_time_ps.used > 0);
1304        assert!(deploy.estimated_dust_specks > 0);
1305        assert!(deploy.estimated_dust_with_margin_specks >= deploy.estimated_dust_specks);
1306    }
1307
1308    #[tokio::test]
1309    async fn profiles_vault_opcodes_and_detects_persistent_hash() {
1310        if !moonproof_ledger::HAS_ZKIR_V3 {
1311            return;
1312        }
1313        let dir = test_fixtures_contracts_dir().join("vault");
1314        let opts = ProfileOptions {
1315            include_opcodes: true,
1316            ..ProfileOptions::default()
1317        };
1318        let profile = profile_contract_dir("vault", &dir, &opts).await.unwrap();
1319        let deposit = profile.circuits.get("deposit").expect("deposit circuit");
1320        assert_eq!(deposit.public_inputs, Some(5));
1321        assert_eq!(deposit.opcode_histogram.get("constrain_bits"), Some(&5));
1322        assert_eq!(deposit.opcode_histogram.get("persistent_hash"), Some(&1));
1323        assert_eq!(deposit.opcode_histogram.get("impact"), Some(&9));
1324    }
1325
1326    #[tokio::test]
1327    async fn detects_real_incremental_deploy_split_when_over_budget() {
1328        if !moonproof_ledger::HAS_ZKIR_V3 {
1329            return;
1330        }
1331        // (1) Real cost-driven split under default INITIAL_PARAMETERS:
1332        // the 13-circuit `extracted_foreign_curves_provable` contract fits
1333        // well under the byte cap yet exceeds the per-tx `bytes_written`
1334        // limit, forcing incremental deploy.
1335        let fc_root = runtime_ir_fixtures_dir();
1336        let fc_assets = fc_root.join("extracted_foreign_curves_provable");
1337        let tmp = tempfile::tempdir().unwrap();
1338        std::fs::copy(
1339            fc_root.join("extracted_foreign_curves_provable.cbor"),
1340            tmp.path().join("contract.mpir"),
1341        )
1342        .unwrap();
1343        #[cfg(unix)]
1344        {
1345            std::os::unix::fs::symlink(fc_assets.join("compiler"), tmp.path().join("compiler"))
1346                .unwrap();
1347            std::os::unix::fs::symlink(fc_assets.join("keys"), tmp.path().join("keys")).unwrap();
1348            std::os::unix::fs::symlink(fc_assets.join("zkir"), tmp.path().join("zkir")).unwrap();
1349        }
1350        #[cfg(unix)]
1351        {
1352            let profile =
1353                profile_contract_dir("foreign_curves", tmp.path(), &ProfileOptions::default())
1354                    .await
1355                    .unwrap();
1356            assert_eq!(profile.circuits.len(), 13);
1357            let deploy = profile.deploy.unwrap_or_else(|| {
1358                panic!("expected deploy profile, note: {:?}", profile.deploy_note)
1359            });
1360            assert!(!deploy.single_shot_fits);
1361            assert!(deploy.total_transactions > 1);
1362            assert_eq!(deploy.total_transactions, 1 + deploy.maintenance_passes);
1363            assert_eq!(deploy.bottleneck_dimension, "bytes_written");
1364            assert!(deploy.bytes_written.exceeded());
1365            assert!(deploy.estimated_dust_specks > 0);
1366            assert!(deploy.estimated_dust_with_margin_specks >= deploy.estimated_dust_specks);
1367        }
1368
1369        // (2) Graceful circuit-only profiling when `contract.mpir` is absent.
1370        let fc_no_ir =
1371            profile_contract_dir("foreign_curves", &fc_assets, &ProfileOptions::default())
1372                .await
1373                .unwrap();
1374        assert_eq!(fc_no_ir.circuits.len(), 13);
1375        assert!(fc_no_ir.deploy.is_none());
1376        assert!(fc_no_ir.deploy_note.is_some());
1377    }
1378
1379    #[tokio::test]
1380    async fn snapshot_json_is_deterministic_across_runs() {
1381        if !moonproof_ledger::HAS_ZKIR_V3 {
1382            return;
1383        }
1384        let dir = test_fixtures_contracts_dir().join("counter");
1385        let opts = ProfileOptions::default();
1386
1387        let mut s1 = SnapshotFile::new(&opts.params_source);
1388        s1.contracts.insert(
1389            "counter".to_owned(),
1390            profile_contract_dir("counter", &dir, &opts).await.unwrap(),
1391        );
1392        let mut s2 = SnapshotFile::new(&opts.params_source);
1393        s2.contracts.insert(
1394            "counter".to_owned(),
1395            profile_contract_dir("counter", &dir, &opts).await.unwrap(),
1396        );
1397
1398        let j1 = s1.to_pretty_json().unwrap();
1399        let j2 = s2.to_pretty_json().unwrap();
1400        assert_eq!(j1, j2);
1401        let roundtrip = SnapshotFile::from_json(&j1).unwrap();
1402        assert_eq!(roundtrip, s1);
1403    }
1404
1405    #[test]
1406    fn diff_snapshots_enforces_k_rows_passes_and_dust_policy() {
1407        let mut base = SnapshotFile::new("initial-parameters");
1408        let mut circuits = BTreeMap::new();
1409        circuits.insert(
1410            "mint".to_owned(),
1411            CircuitProfile {
1412                name: "mint".to_owned(),
1413                zkir_version: 3,
1414                k: 12,
1415                domain_size: 4096,
1416                rows: 3000,
1417                headroom_rows: 1096,
1418                utilization_bps: 7324,
1419                near_cliff: false,
1420                prover_key_bytes: 100_000,
1421                verifier_key_bytes: 2_000,
1422                bzkir_bytes: 500,
1423                public_inputs: None,
1424                public_outputs: None,
1425                instruction_count: None,
1426                opcode_histogram: BTreeMap::new(),
1427            },
1428        );
1429        base.contracts.insert(
1430            "token".to_owned(),
1431            ContractProfile {
1432                name: "token".to_owned(),
1433                circuits,
1434                deploy: Some(DeployProfile {
1435                    params_source: "initial-parameters".to_owned(),
1436                    single_shot_fits: true,
1437                    total_transactions: 1,
1438                    maintenance_passes: 0,
1439                    tx_bytes: CostDimension::new(5000, 786_421),
1440                    read_time_ps: CostDimension::new(100, 1000),
1441                    compute_time_ps: CostDimension::new(100, 1000),
1442                    block_usage: CostDimension::new(5000, 100_000),
1443                    bytes_written: CostDimension::new(2000, 37_260),
1444                    bytes_churned: CostDimension::new(0, 100_000),
1445                    bottleneck_dimension: "bytes_written".to_owned(),
1446                    estimated_dust_specks: 1_000_000,
1447                    estimated_dust_with_margin_specks: 1_200_000,
1448                    deploy_batch: vec!["mint".to_owned()],
1449                    maintenance_batches: Vec::new(),
1450                }),
1451                deploy_note: None,
1452            },
1453        );
1454
1455        // Identical snapshot passes strict default policy.
1456        let strict = SnapshotPolicy::default();
1457        assert!(diff_snapshots(&base, &base, &strict).passed());
1458
1459        // Improvement (fewer rows, lower dust) passes strict policy.
1460        let mut improved = base.clone();
1461        improved
1462            .contracts
1463            .get_mut("token")
1464            .unwrap()
1465            .circuits
1466            .get_mut("mint")
1467            .unwrap()
1468            .rows = 2800;
1469        improved
1470            .contracts
1471            .get_mut("token")
1472            .unwrap()
1473            .deploy
1474            .as_mut()
1475            .unwrap()
1476            .estimated_dust_specks = 900_000;
1477        assert!(diff_snapshots(&base, &improved, &strict).passed());
1478
1479        // Regressed k (+1), rows (+10%), passes (1 -> 2), and dust (+20%) all flagged.
1480        let mut regressed = base.clone();
1481        let mc = regressed
1482            .contracts
1483            .get_mut("token")
1484            .unwrap()
1485            .circuits
1486            .get_mut("mint")
1487            .unwrap();
1488        mc.k = 13;
1489        mc.domain_size = 8192;
1490        mc.rows = 3300;
1491        let dep = regressed
1492            .contracts
1493            .get_mut("token")
1494            .unwrap()
1495            .deploy
1496            .as_mut()
1497            .unwrap();
1498        dep.single_shot_fits = false;
1499        dep.total_transactions = 2;
1500        dep.maintenance_passes = 1;
1501        dep.estimated_dust_specks = 1_200_000;
1502
1503        let policy = SnapshotPolicy {
1504            max_row_growth_pct: Some(5.0),
1505            max_dust_growth_pct: Some(10.0),
1506            allow_k_increase: false,
1507            allow_pass_increase: false,
1508        };
1509        let diff = diff_snapshots(&base, &regressed, &policy);
1510        assert!(!diff.passed());
1511        assert_eq!(diff.regressions.len(), 4, "{:?}", diff.regressions);
1512    }
1513}