1use std::ffi::OsString;
2use std::fs;
3use std::io::{Read, Write};
4use std::path::PathBuf;
5
6use clap::{Parser, Subcommand, ValueEnum, error::ErrorKind};
7use serde::Serialize;
8
9mod decode;
10#[cfg(feature = "benchmark-tools")]
11#[doc(hidden)]
12pub use decode::benchmark::{export_decoder_oracle_dataset, export_matching_dataset};
13mod pipeline;
14
15pub const SCHEMA_VERSION: &str = "rustqec.cli.v1";
16const CIRCUIT_STATS_COMMAND: &str = "circuit.stats";
17
18#[derive(Debug, Parser)]
19#[command(
20 name = "rustqec",
21 version,
22 about = "Unified RustQEC command line interface"
23)]
24pub struct Cli {
25 #[arg(long, global = true, value_enum)]
27 error_format: Option<ErrorFormat>,
28 #[command(subcommand)]
29 command: Command,
30}
31
32#[derive(Debug, Subcommand)]
33enum Command {
34 Circuit {
36 #[command(subcommand)]
37 command: CircuitCommand,
38 },
39 Capabilities {
41 #[arg(long, value_enum)]
42 format: CapabilitiesFormat,
43 },
44 Decode {
46 #[arg(long, value_enum)]
48 decoder: DecodeDecoder,
49 #[arg(long)]
51 dataset: PathBuf,
52 #[arg(long)]
54 out: PathBuf,
55 #[arg(long = "stats-out")]
57 stats_out: PathBuf,
58 #[arg(long = "shot-timeout-ms")]
60 shot_timeout_ms: Option<u64>,
61 },
62 Dataset {
64 #[command(subcommand)]
65 command: DatasetCommand,
66 },
67}
68
69#[derive(Debug, Subcommand)]
70enum DatasetCommand {
71 Export {
73 #[arg(long)]
75 circuit: PathBuf,
76 #[arg(long)]
78 shots: u64,
79 #[arg(long)]
81 mode: String,
82 #[arg(long = "public-out")]
84 public_out: PathBuf,
85 #[arg(long = "private-out")]
87 private_out: PathBuf,
88 #[arg(long)]
90 seed: Option<u64>,
91 #[arg(long = "logical-x-qubits")]
93 logical_x_qubits: Option<String>,
94 #[arg(long = "logical-z-qubits")]
96 logical_z_qubits: Option<String>,
97 #[arg(long = "error-trace")]
99 error_trace: bool,
100 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
102 format: pipeline::PipelineFormat,
103 },
104 Import {
106 #[arg(long)]
108 circuit: PathBuf,
109 #[arg(long)]
111 shots: PathBuf,
112 #[arg(long = "shots-format", default_value = "01")]
114 shots_format: String,
115 #[arg(long)]
117 out: PathBuf,
118 #[arg(long = "loss-log")]
120 loss_log: Option<PathBuf>,
121 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
123 format: pipeline::PipelineFormat,
124 },
125}
126
127#[derive(Debug, Subcommand)]
128enum CircuitCommand {
129 Stats {
131 #[arg(long = "in")]
133 input: Option<PathBuf>,
134 #[arg(long, value_enum, default_value_t = StatsFormat::Human)]
136 format: StatsFormat,
137 },
138 Gen {
140 #[arg(long)]
142 code: String,
143 #[arg(long)]
145 task: String,
146 #[arg(long)]
148 distance: usize,
149 #[arg(long)]
151 rounds: usize,
152 #[arg(long, default_value = "0")]
154 noise: f64,
155 #[arg(long, default_value = "0")]
157 before_round_data_depolarization: f64,
158 #[arg(
160 long = "before-round-data-loss-probability",
161 visible_alias = "before-round-data-loss",
162 default_value = "0"
163 )]
164 before_round_data_loss_probability: f64,
165 #[arg(long, default_value = "0")]
167 before_measure_flip_probability: f64,
168 #[arg(long, default_value = "0")]
170 after_reset_flip_probability: f64,
171 #[arg(long, default_value = "0")]
173 after_clifford_loss_probability: f64,
174 #[arg(long, default_value = "0")]
176 operation_loss_probability: f64,
177 #[arg(long, default_value = "0")]
179 measurement_loss_probability: f64,
180 #[arg(long)]
182 out: PathBuf,
183 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
185 format: pipeline::PipelineFormat,
186 },
187 Sample {
189 #[arg(long)]
191 shots: u64,
192 #[arg(long = "in")]
194 input: Option<PathBuf>,
195 #[arg(long)]
197 out: PathBuf,
198 #[arg(long = "out-format", default_value = "01")]
200 out_format: String,
201 #[arg(long)]
203 seed: Option<u64>,
204 #[arg(long = "skip-reference-sample")]
206 skip_reference_sample: bool,
207 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
209 format: pipeline::PipelineFormat,
210 },
211 Detect {
213 #[arg(long)]
215 shots: u64,
216 #[arg(long = "in")]
218 input: Option<PathBuf>,
219 #[arg(long)]
221 out: PathBuf,
222 #[arg(long = "out-format", default_value = "01")]
224 out_format: String,
225 #[arg(long)]
227 seed: Option<u64>,
228 #[arg(long = "append-observables")]
230 append_observables: bool,
231 #[arg(long = "obs-out")]
233 obs_out: Option<PathBuf>,
234 #[arg(long = "obs-out-format", default_value = "01")]
236 obs_out_format: String,
237 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
239 format: pipeline::PipelineFormat,
240 },
241 Dem {
243 #[arg(long = "in")]
245 input: Option<PathBuf>,
246 #[arg(long)]
248 out: PathBuf,
249 #[arg(long = "approximate-disjoint-errors")]
251 approximate_disjoint_errors: bool,
252 #[arg(long = "allow-gauge-detectors")]
254 allow_gauge_detectors: bool,
255 #[arg(long = "decompose-errors")]
257 decompose_errors: bool,
258 #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
260 format: pipeline::PipelineFormat,
261 },
262}
263
264#[derive(Clone, Copy, Debug, ValueEnum)]
265enum StatsFormat {
266 Human,
267 Json,
268}
269
270#[derive(Clone, Copy, Debug, ValueEnum)]
271enum CapabilitiesFormat {
272 Json,
273}
274
275#[derive(Clone, Copy, Debug, ValueEnum)]
276enum ErrorFormat {
277 Human,
278 Json,
279}
280
281#[derive(Clone, Copy, Debug, ValueEnum)]
282enum DecodeDecoder {
283 EnvelopeMatching,
284 #[cfg(feature = "ilp")]
285 EnvelopeMle,
286}
287
288impl From<DecodeDecoder> for decode::DecoderKind {
289 fn from(value: DecodeDecoder) -> Self {
290 match value {
291 DecodeDecoder::EnvelopeMatching => Self::EnvelopeMatching,
292 #[cfg(feature = "ilp")]
293 DecodeDecoder::EnvelopeMle => Self::EnvelopeMle,
294 }
295 }
296}
297
298fn available_decoders() -> Vec<&'static str> {
299 let decoders = vec!["envelope-matching"];
300 #[cfg(feature = "ilp")]
301 let decoders = {
302 let mut decoders = decoders;
303 decoders.push("envelope-mle");
304 decoders
305 };
306 decoders
307}
308
309#[derive(Debug)]
310pub enum RunError {
311 Clap {
312 error: clap::Error,
313 command: &'static str,
314 json: bool,
315 },
316 Command(CommandError),
317}
318
319#[derive(Debug)]
320pub struct CommandError {
321 pub command: &'static str,
322 pub code: &'static str,
323 pub message: String,
324 json: bool,
325 exit_code: u8,
326}
327
328#[derive(Serialize)]
329struct SuccessEnvelope<T> {
330 schema_version: &'static str,
331 status: &'static str,
332 command: &'static str,
333 result: T,
334 warnings: Vec<String>,
335 artifacts: Vec<String>,
336}
337
338#[derive(Serialize)]
339struct ErrorEnvelope<'a> {
340 schema_version: &'static str,
341 status: &'static str,
342 command: &'static str,
343 error: ErrorBody<'a>,
344}
345
346#[derive(Serialize)]
347struct ErrorBody<'a> {
348 code: &'static str,
349 message: &'a str,
350}
351
352#[derive(Serialize)]
353struct CapabilitiesDocument {
354 schema_version: &'static str,
355 global_arguments: Vec<ArgumentCapability>,
356 commands: Vec<Capability>,
357}
358
359#[derive(Serialize)]
360struct Capability {
361 name: &'static str,
362 argv: Vec<&'static str>,
363 input_sources: Vec<&'static str>,
364 formats: Vec<&'static str>,
365 output_schema: &'static str,
366 arguments: Vec<ArgumentCapability>,
367 success_exit_code: u8,
368 errors: Vec<ErrorCapability>,
369 #[serde(skip_serializing_if = "Vec::is_empty")]
370 decoders: Vec<&'static str>,
371 #[serde(skip_serializing_if = "Vec::is_empty")]
372 artifacts: Vec<ArtifactCapability>,
373}
374
375#[derive(Serialize)]
376struct ArtifactCapability {
377 name: &'static str,
378 flag: &'static str,
379 format: &'static str,
380}
381
382#[derive(Serialize)]
383struct ArgumentCapability {
384 name: &'static str,
385 flag: &'static str,
386 required: bool,
387 values: Vec<&'static str>,
388 default: Option<&'static str>,
389}
390
391#[derive(Serialize)]
392struct ErrorCapability {
393 code: &'static str,
394 exit_code: u8,
395 channel: &'static str,
396}
397
398pub fn run<I, T>(args: I, stdin: &mut dyn Read, stdout: &mut dyn Write) -> Result<(), RunError>
399where
400 I: IntoIterator<Item = T>,
401 T: Into<OsString> + Clone,
402{
403 let args = args.into_iter().map(Into::into).collect::<Vec<OsString>>();
404 let (parse_command, parse_json) = parse_error_context(&args);
405 let cli = Cli::try_parse_from(&args).map_err(|error| RunError::Clap {
406 error,
407 command: parse_command,
408 json: parse_json,
409 })?;
410 let error_format = cli.error_format;
411 match cli.command {
412 Command::Circuit {
413 command: CircuitCommand::Stats { input, format },
414 } => {
415 run_circuit_stats(input, format, error_format, stdin, stdout).map_err(RunError::Command)
416 }
417 Command::Circuit {
418 command:
419 CircuitCommand::Gen {
420 code,
421 task,
422 distance,
423 rounds,
424 noise,
425 before_round_data_depolarization,
426 before_round_data_loss_probability,
427 before_measure_flip_probability,
428 after_reset_flip_probability,
429 after_clifford_loss_probability,
430 operation_loss_probability,
431 measurement_loss_probability,
432 out,
433 format,
434 },
435 } => {
436 let options = pipeline::GenOptions {
437 code,
438 task,
439 distance,
440 rounds,
441 noise,
442 before_round_data_depolarization,
443 before_round_data_loss_probability,
444 before_measure_flip_probability,
445 after_reset_flip_probability,
446 after_clifford_loss_probability,
447 operation_loss_probability,
448 measurement_loss_probability,
449 out,
450 format,
451 };
452 let artifacts = vec![options.out.display().to_string()];
453 pipeline::run_gen(&options, error_format)
454 .and_then(|result| {
455 write_pipeline_success(
456 pipeline::CIRCUIT_GEN_COMMAND,
457 &result,
458 artifacts,
459 format,
460 error_format,
461 stdout,
462 )
463 })
464 .map_err(RunError::Command)
465 }
466 Command::Circuit {
467 command:
468 CircuitCommand::Sample {
469 shots,
470 input,
471 out,
472 out_format,
473 seed,
474 skip_reference_sample,
475 format,
476 },
477 } => {
478 let options = pipeline::SampleOptions {
479 shots,
480 input,
481 out,
482 out_format,
483 seed,
484 skip_reference_sample,
485 format,
486 };
487 let artifacts = vec![options.out.display().to_string()];
488 pipeline::run_sample(&options, error_format, stdin)
489 .and_then(|result| {
490 write_pipeline_success(
491 pipeline::CIRCUIT_SAMPLE_COMMAND,
492 &result,
493 artifacts,
494 format,
495 error_format,
496 stdout,
497 )
498 })
499 .map_err(RunError::Command)
500 }
501 Command::Circuit {
502 command:
503 CircuitCommand::Detect {
504 shots,
505 input,
506 out,
507 out_format,
508 seed,
509 append_observables,
510 obs_out,
511 obs_out_format,
512 format,
513 },
514 } => {
515 let mut artifacts = vec![out.display().to_string()];
516 if let Some(obs_out) = &obs_out {
517 artifacts.push(obs_out.display().to_string());
518 }
519 let options = pipeline::DetectOptions {
520 shots,
521 input,
522 out,
523 out_format,
524 seed,
525 append_observables,
526 obs_out,
527 obs_out_format,
528 format,
529 };
530 pipeline::run_detect(&options, error_format, stdin)
531 .and_then(|result| {
532 write_pipeline_success(
533 pipeline::CIRCUIT_DETECT_COMMAND,
534 &result,
535 artifacts,
536 format,
537 error_format,
538 stdout,
539 )
540 })
541 .map_err(RunError::Command)
542 }
543 Command::Circuit {
544 command:
545 CircuitCommand::Dem {
546 input,
547 out,
548 approximate_disjoint_errors,
549 allow_gauge_detectors,
550 decompose_errors,
551 format,
552 },
553 } => {
554 let options = pipeline::DemOptions {
555 input,
556 out,
557 approximate_disjoint_errors,
558 allow_gauge_detectors,
559 decompose_errors,
560 format,
561 };
562 let artifacts = vec![options.out.display().to_string()];
563 pipeline::run_dem(&options, error_format, stdin)
564 .and_then(|result| {
565 write_pipeline_success(
566 pipeline::CIRCUIT_DEM_COMMAND,
567 &result,
568 artifacts,
569 format,
570 error_format,
571 stdout,
572 )
573 })
574 .map_err(RunError::Command)
575 }
576 Command::Dataset {
577 command:
578 DatasetCommand::Export {
579 circuit,
580 shots,
581 mode,
582 public_out,
583 private_out,
584 seed,
585 logical_x_qubits,
586 logical_z_qubits,
587 error_trace,
588 format,
589 },
590 } => {
591 let artifacts = vec![
592 public_out.display().to_string(),
593 private_out.display().to_string(),
594 ];
595 let options = pipeline::DatasetExportOptions {
596 circuit,
597 shots,
598 mode,
599 public_out,
600 private_out,
601 seed,
602 logical_x_qubits,
603 logical_z_qubits,
604 error_trace,
605 format,
606 };
607 pipeline::run_dataset_export(&options, error_format)
608 .and_then(|result| {
609 write_pipeline_success(
610 pipeline::DATASET_EXPORT_COMMAND,
611 &result,
612 artifacts,
613 format,
614 error_format,
615 stdout,
616 )
617 })
618 .map_err(RunError::Command)
619 }
620 Command::Dataset {
621 command:
622 DatasetCommand::Import {
623 circuit,
624 shots,
625 shots_format,
626 out,
627 loss_log,
628 format,
629 },
630 } => {
631 let artifacts = vec![out.display().to_string()];
632 let options = pipeline::DatasetImportOptions {
633 circuit,
634 shots,
635 shots_format,
636 out,
637 loss_log,
638 format,
639 };
640 pipeline::run_dataset_import(&options, error_format)
641 .and_then(|result| {
642 write_pipeline_success(
643 pipeline::DATASET_IMPORT_COMMAND,
644 &result,
645 artifacts,
646 format,
647 error_format,
648 stdout,
649 )
650 })
651 .map_err(RunError::Command)
652 }
653 Command::Capabilities { format } => {
654 write_capabilities(format, error_format, stdout).map_err(RunError::Command)
655 }
656 Command::Decode {
657 decoder,
658 dataset,
659 out,
660 stats_out,
661 shot_timeout_ms,
662 } => decode::run(&decode::DecodeOptions {
663 decoder: decoder.into(),
664 dataset,
665 predictions_out: out,
666 stats_out,
667 shot_timeout_ms,
668 })
669 .map(|_| ())
670 .map_err(|failure| {
671 RunError::Command(CommandError {
672 command: decode::COMMAND,
673 code: failure.code,
674 message: failure.message,
675 json: !matches!(error_format, Some(ErrorFormat::Human)),
676 exit_code: if matches!(failure.code, "decode_timeout" | "decode_infeasible") {
677 3
678 } else {
679 2
680 },
681 })
682 }),
683 }
684}
685
686fn run_circuit_stats(
687 input: Option<PathBuf>,
688 format: StatsFormat,
689 error_format: Option<ErrorFormat>,
690 stdin: &mut dyn Read,
691 stdout: &mut dyn Write,
692) -> Result<(), CommandError> {
693 let json = match error_format {
694 Some(ErrorFormat::Human) => false,
695 Some(ErrorFormat::Json) => true,
696 None => matches!(format, StatsFormat::Json),
697 };
698 let text = match input {
699 Some(path) => fs::read_to_string(&path).map_err(|error| CommandError {
700 command: CIRCUIT_STATS_COMMAND,
701 code: "input_error",
702 message: format!("failed to read {}: {error}", path.display()),
703 json,
704 exit_code: 2,
705 })?,
706 None => {
707 let mut text = String::new();
708 stdin
709 .read_to_string(&mut text)
710 .map_err(|error| CommandError {
711 command: CIRCUIT_STATS_COMMAND,
712 code: "input_error",
713 message: format!("failed to read stdin: {error}"),
714 json,
715 exit_code: 2,
716 })?;
717 text
718 }
719 };
720
721 let summary = rstim::stats::summarize_text(&text).map_err(|message| CommandError {
722 command: CIRCUIT_STATS_COMMAND,
723 code: "invalid_circuit",
724 message,
725 json,
726 exit_code: 2,
727 })?;
728
729 match format {
730 StatsFormat::Human => rstim::stats::write_human(&summary, stdout),
731 StatsFormat::Json => write_json(
732 stdout,
733 &SuccessEnvelope {
734 schema_version: SCHEMA_VERSION,
735 status: "ok",
736 command: CIRCUIT_STATS_COMMAND,
737 result: summary,
738 warnings: Vec::new(),
739 artifacts: Vec::new(),
740 },
741 ),
742 }
743 .map_err(|message| CommandError {
744 command: CIRCUIT_STATS_COMMAND,
745 code: "output_error",
746 message,
747 json,
748 exit_code: 2,
749 })
750}
751
752fn write_pipeline_success<T: Serialize>(
753 command: &'static str,
754 result: &T,
755 artifacts: Vec<String>,
756 format: pipeline::PipelineFormat,
757 error_format: Option<ErrorFormat>,
758 stdout: &mut dyn Write,
759) -> Result<(), CommandError> {
760 let json = format.is_json(error_format);
761 let outcome = match format {
762 pipeline::PipelineFormat::Json => write_json(
763 stdout,
764 &SuccessEnvelope {
765 schema_version: SCHEMA_VERSION,
766 status: "ok",
767 command,
768 result,
769 warnings: Vec::new(),
770 artifacts,
771 },
772 ),
773 pipeline::PipelineFormat::Human => serde_json::to_value(result)
774 .map_err(|error| error.to_string())
775 .and_then(|value| {
776 let mut text = String::from("status: ok\n");
777 if let serde_json::Value::Object(fields) = value {
778 for (key, field) in fields {
779 let rendered = match field {
780 serde_json::Value::String(text) => text,
781 serde_json::Value::Null => continue,
782 other => other.to_string(),
783 };
784 text.push_str(&format!("{key}: {rendered}\n"));
785 }
786 }
787 for artifact in &artifacts {
788 text.push_str(&format!("artifact: {artifact}\n"));
789 }
790 stdout
791 .write_all(text.as_bytes())
792 .map_err(|error| error.to_string())
793 }),
794 };
795 outcome.map_err(|message| CommandError {
796 command,
797 code: "output_error",
798 message,
799 json,
800 exit_code: 2,
801 })
802}
803
804fn write_capabilities(
805 _format: CapabilitiesFormat,
806 error_format: Option<ErrorFormat>,
807 stdout: &mut dyn Write,
808) -> Result<(), CommandError> {
809 let json = !matches!(error_format, Some(ErrorFormat::Human));
810 write_json(
811 stdout,
812 &CapabilitiesDocument {
813 schema_version: SCHEMA_VERSION,
814 global_arguments: vec![ArgumentCapability {
815 name: "error_format",
816 flag: "--error-format",
817 required: false,
818 values: vec!["human", "json"],
819 default: None,
820 }],
821 commands: vec![
822 Capability {
823 name: CIRCUIT_STATS_COMMAND,
824 argv: vec!["circuit", "stats"],
825 input_sources: vec!["stdin", "file"],
826 formats: vec!["human", "json"],
827 output_schema: SCHEMA_VERSION,
828 arguments: vec![
829 ArgumentCapability {
830 name: "input",
831 flag: "--in",
832 required: false,
833 values: vec!["path"],
834 default: Some("stdin"),
835 },
836 ArgumentCapability {
837 name: "format",
838 flag: "--format",
839 required: false,
840 values: vec!["human", "json"],
841 default: Some("human"),
842 },
843 ],
844 success_exit_code: 0,
845 errors: vec![
846 ErrorCapability {
847 code: "invalid_arguments",
848 exit_code: 2,
849 channel: "stderr",
850 },
851 ErrorCapability {
852 code: "invalid_circuit",
853 exit_code: 2,
854 channel: "stderr",
855 },
856 ErrorCapability {
857 code: "input_error",
858 exit_code: 2,
859 channel: "stderr",
860 },
861 ErrorCapability {
862 code: "output_error",
863 exit_code: 2,
864 channel: "stderr",
865 },
866 ],
867 decoders: Vec::new(),
868 artifacts: Vec::new(),
869 },
870 Capability {
871 name: pipeline::CIRCUIT_GEN_COMMAND,
872 argv: vec!["circuit", "gen"],
873 input_sources: vec!["built_in_generators"],
874 formats: vec!["human", "json"],
875 output_schema: SCHEMA_VERSION,
876 arguments: vec![
877 ArgumentCapability {
878 name: "code",
879 flag: "--code",
880 required: true,
881 values: vec!["surface_code", "repetition_code", "color_code"],
882 default: None,
883 },
884 ArgumentCapability {
885 name: "task",
886 flag: "--task",
887 required: true,
888 values: vec![
889 "rotated_memory_z_midswap",
890 "rotated_memory_x",
891 "rotated_memory_z",
892 "unrotated_memory_x",
893 "unrotated_memory_z",
894 "memory",
895 "memory_xyz",
896 ],
897 default: None,
898 },
899 ArgumentCapability {
900 name: "distance",
901 flag: "--distance",
902 required: true,
903 values: vec!["positive_integer"],
904 default: None,
905 },
906 ArgumentCapability {
907 name: "rounds",
908 flag: "--rounds",
909 required: true,
910 values: vec!["non_negative_integer"],
911 default: None,
912 },
913 ArgumentCapability {
914 name: "noise",
915 flag: "--noise",
916 required: false,
917 values: vec!["probability"],
918 default: Some("0"),
919 },
920 ArgumentCapability {
921 name: "before_round_data_depolarization",
922 flag: "--before-round-data-depolarization",
923 required: false,
924 values: vec!["probability"],
925 default: Some("0"),
926 },
927 ArgumentCapability {
928 name: "before_round_data_loss_probability",
929 flag: "--before-round-data-loss-probability",
930 required: false,
931 values: vec!["probability"],
932 default: Some("0"),
933 },
934 ArgumentCapability {
935 name: "before_measure_flip_probability",
936 flag: "--before-measure-flip-probability",
937 required: false,
938 values: vec!["probability"],
939 default: Some("0"),
940 },
941 ArgumentCapability {
942 name: "after_reset_flip_probability",
943 flag: "--after-reset-flip-probability",
944 required: false,
945 values: vec!["probability"],
946 default: Some("0"),
947 },
948 ArgumentCapability {
949 name: "after_clifford_loss_probability",
950 flag: "--after-clifford-loss-probability",
951 required: false,
952 values: vec!["probability"],
953 default: Some("0"),
954 },
955 ArgumentCapability {
956 name: "operation_loss_probability",
957 flag: "--operation-loss-probability",
958 required: false,
959 values: vec!["probability"],
960 default: Some("0"),
961 },
962 ArgumentCapability {
963 name: "measurement_loss_probability",
964 flag: "--measurement-loss-probability",
965 required: false,
966 values: vec!["probability"],
967 default: Some("0"),
968 },
969 ArgumentCapability {
970 name: "out",
971 flag: "--out",
972 required: true,
973 values: vec!["path"],
974 default: None,
975 },
976 ArgumentCapability {
977 name: "format",
978 flag: "--format",
979 required: false,
980 values: vec!["human", "json"],
981 default: Some("json"),
982 },
983 ],
984 success_exit_code: 0,
985 errors: vec![
986 ErrorCapability {
987 code: "invalid_arguments",
988 exit_code: 2,
989 channel: "stderr",
990 },
991 ErrorCapability {
992 code: "output_error",
993 exit_code: 2,
994 channel: "stderr",
995 },
996 ],
997 decoders: Vec::new(),
998 artifacts: vec![ArtifactCapability {
999 name: "circuit",
1000 flag: "--out",
1001 format: "stim",
1002 }],
1003 },
1004 Capability {
1005 name: pipeline::CIRCUIT_SAMPLE_COMMAND,
1006 argv: vec!["circuit", "sample"],
1007 input_sources: vec!["stdin", "file"],
1008 formats: vec!["human", "json"],
1009 output_schema: SCHEMA_VERSION,
1010 arguments: vec![
1011 ArgumentCapability {
1012 name: "shots",
1013 flag: "--shots",
1014 required: true,
1015 values: vec!["non_negative_integer"],
1016 default: None,
1017 },
1018 ArgumentCapability {
1019 name: "input",
1020 flag: "--in",
1021 required: false,
1022 values: vec!["path"],
1023 default: Some("stdin"),
1024 },
1025 ArgumentCapability {
1026 name: "out",
1027 flag: "--out",
1028 required: true,
1029 values: vec!["path"],
1030 default: None,
1031 },
1032 ArgumentCapability {
1033 name: "out_format",
1034 flag: "--out-format",
1035 required: false,
1036 values: vec!["01", "b8", "r8", "hits", "ptb64"],
1037 default: Some("01"),
1038 },
1039 ArgumentCapability {
1040 name: "seed",
1041 flag: "--seed",
1042 required: false,
1043 values: vec!["non_negative_integer"],
1044 default: None,
1045 },
1046 ArgumentCapability {
1047 name: "skip_reference_sample",
1048 flag: "--skip-reference-sample",
1049 required: false,
1050 values: vec!["flag"],
1051 default: None,
1052 },
1053 ArgumentCapability {
1054 name: "format",
1055 flag: "--format",
1056 required: false,
1057 values: vec!["human", "json"],
1058 default: Some("json"),
1059 },
1060 ],
1061 success_exit_code: 0,
1062 errors: vec![
1063 ErrorCapability {
1064 code: "invalid_arguments",
1065 exit_code: 2,
1066 channel: "stderr",
1067 },
1068 ErrorCapability {
1069 code: "invalid_circuit",
1070 exit_code: 2,
1071 channel: "stderr",
1072 },
1073 ErrorCapability {
1074 code: "input_error",
1075 exit_code: 2,
1076 channel: "stderr",
1077 },
1078 ErrorCapability {
1079 code: "execution_error",
1080 exit_code: 2,
1081 channel: "stderr",
1082 },
1083 ErrorCapability {
1084 code: "output_error",
1085 exit_code: 2,
1086 channel: "stderr",
1087 },
1088 ],
1089 decoders: Vec::new(),
1090 artifacts: vec![ArtifactCapability {
1091 name: "measurements",
1092 flag: "--out",
1093 format: "01|b8|r8|hits|ptb64",
1094 }],
1095 },
1096 Capability {
1097 name: pipeline::CIRCUIT_DETECT_COMMAND,
1098 argv: vec!["circuit", "detect"],
1099 input_sources: vec!["stdin", "file"],
1100 formats: vec!["human", "json"],
1101 output_schema: SCHEMA_VERSION,
1102 arguments: vec![
1103 ArgumentCapability {
1104 name: "shots",
1105 flag: "--shots",
1106 required: true,
1107 values: vec!["non_negative_integer"],
1108 default: None,
1109 },
1110 ArgumentCapability {
1111 name: "input",
1112 flag: "--in",
1113 required: false,
1114 values: vec!["path"],
1115 default: Some("stdin"),
1116 },
1117 ArgumentCapability {
1118 name: "out",
1119 flag: "--out",
1120 required: true,
1121 values: vec!["path"],
1122 default: None,
1123 },
1124 ArgumentCapability {
1125 name: "out_format",
1126 flag: "--out-format",
1127 required: false,
1128 values: vec!["01", "b8", "r8", "hits", "dets", "ptb64"],
1129 default: Some("01"),
1130 },
1131 ArgumentCapability {
1132 name: "seed",
1133 flag: "--seed",
1134 required: false,
1135 values: vec!["non_negative_integer"],
1136 default: None,
1137 },
1138 ArgumentCapability {
1139 name: "append_observables",
1140 flag: "--append-observables",
1141 required: false,
1142 values: vec!["flag"],
1143 default: None,
1144 },
1145 ArgumentCapability {
1146 name: "obs_out",
1147 flag: "--obs-out",
1148 required: false,
1149 values: vec!["path"],
1150 default: None,
1151 },
1152 ArgumentCapability {
1153 name: "obs_out_format",
1154 flag: "--obs-out-format",
1155 required: false,
1156 values: vec!["01", "b8", "r8", "hits", "dets", "ptb64"],
1157 default: Some("01"),
1158 },
1159 ArgumentCapability {
1160 name: "format",
1161 flag: "--format",
1162 required: false,
1163 values: vec!["human", "json"],
1164 default: Some("json"),
1165 },
1166 ],
1167 success_exit_code: 0,
1168 errors: vec![
1169 ErrorCapability {
1170 code: "invalid_arguments",
1171 exit_code: 2,
1172 channel: "stderr",
1173 },
1174 ErrorCapability {
1175 code: "invalid_circuit",
1176 exit_code: 2,
1177 channel: "stderr",
1178 },
1179 ErrorCapability {
1180 code: "input_error",
1181 exit_code: 2,
1182 channel: "stderr",
1183 },
1184 ErrorCapability {
1185 code: "execution_error",
1186 exit_code: 2,
1187 channel: "stderr",
1188 },
1189 ErrorCapability {
1190 code: "output_error",
1191 exit_code: 2,
1192 channel: "stderr",
1193 },
1194 ],
1195 decoders: Vec::new(),
1196 artifacts: vec![
1197 ArtifactCapability {
1198 name: "detection_events",
1199 flag: "--out",
1200 format: "01|b8|r8|hits|dets|ptb64",
1201 },
1202 ArtifactCapability {
1203 name: "observable_flips",
1204 flag: "--obs-out",
1205 format: "01|b8|r8|hits|dets|ptb64",
1206 },
1207 ],
1208 },
1209 Capability {
1210 name: pipeline::CIRCUIT_DEM_COMMAND,
1211 argv: vec!["circuit", "dem"],
1212 input_sources: vec!["stdin", "file"],
1213 formats: vec!["human", "json"],
1214 output_schema: SCHEMA_VERSION,
1215 arguments: vec![
1216 ArgumentCapability {
1217 name: "input",
1218 flag: "--in",
1219 required: false,
1220 values: vec!["path"],
1221 default: Some("stdin"),
1222 },
1223 ArgumentCapability {
1224 name: "out",
1225 flag: "--out",
1226 required: true,
1227 values: vec!["path"],
1228 default: None,
1229 },
1230 ArgumentCapability {
1231 name: "approximate_disjoint_errors",
1232 flag: "--approximate-disjoint-errors",
1233 required: false,
1234 values: vec!["flag"],
1235 default: None,
1236 },
1237 ArgumentCapability {
1238 name: "allow_gauge_detectors",
1239 flag: "--allow-gauge-detectors",
1240 required: false,
1241 values: vec!["flag"],
1242 default: None,
1243 },
1244 ArgumentCapability {
1245 name: "decompose_errors",
1246 flag: "--decompose-errors",
1247 required: false,
1248 values: vec!["flag"],
1249 default: None,
1250 },
1251 ArgumentCapability {
1252 name: "format",
1253 flag: "--format",
1254 required: false,
1255 values: vec!["human", "json"],
1256 default: Some("json"),
1257 },
1258 ],
1259 success_exit_code: 0,
1260 errors: vec![
1261 ErrorCapability {
1262 code: "invalid_arguments",
1263 exit_code: 2,
1264 channel: "stderr",
1265 },
1266 ErrorCapability {
1267 code: "invalid_circuit",
1268 exit_code: 2,
1269 channel: "stderr",
1270 },
1271 ErrorCapability {
1272 code: "input_error",
1273 exit_code: 2,
1274 channel: "stderr",
1275 },
1276 ErrorCapability {
1277 code: "execution_error",
1278 exit_code: 2,
1279 channel: "stderr",
1280 },
1281 ErrorCapability {
1282 code: "output_error",
1283 exit_code: 2,
1284 channel: "stderr",
1285 },
1286 ],
1287 decoders: Vec::new(),
1288 artifacts: vec![ArtifactCapability {
1289 name: "detector_error_model",
1290 flag: "--out",
1291 format: "dem",
1292 }],
1293 },
1294 Capability {
1295 name: pipeline::DATASET_EXPORT_COMMAND,
1296 argv: vec!["dataset", "export"],
1297 input_sources: vec!["file"],
1298 formats: vec!["human", "json"],
1299 output_schema: SCHEMA_VERSION,
1300 arguments: vec![
1301 ArgumentCapability {
1302 name: "circuit",
1303 flag: "--circuit",
1304 required: true,
1305 values: vec!["path"],
1306 default: None,
1307 },
1308 ArgumentCapability {
1309 name: "shots",
1310 flag: "--shots",
1311 required: true,
1312 values: vec!["non_negative_integer"],
1313 default: None,
1314 },
1315 ArgumentCapability {
1316 name: "mode",
1317 flag: "--mode",
1318 required: true,
1319 values: vec!["detectors", "measurements_blinded"],
1320 default: None,
1321 },
1322 ArgumentCapability {
1323 name: "public_out",
1324 flag: "--public-out",
1325 required: true,
1326 values: vec!["path"],
1327 default: None,
1328 },
1329 ArgumentCapability {
1330 name: "private_out",
1331 flag: "--private-out",
1332 required: true,
1333 values: vec!["path"],
1334 default: None,
1335 },
1336 ArgumentCapability {
1337 name: "seed",
1338 flag: "--seed",
1339 required: false,
1340 values: vec!["non_negative_integer"],
1341 default: None,
1342 },
1343 ArgumentCapability {
1344 name: "logical_x_qubits",
1345 flag: "--logical-x-qubits",
1346 required: false,
1347 values: vec!["qubit_index_list"],
1348 default: None,
1349 },
1350 ArgumentCapability {
1351 name: "logical_z_qubits",
1352 flag: "--logical-z-qubits",
1353 required: false,
1354 values: vec!["qubit_index_list"],
1355 default: None,
1356 },
1357 ArgumentCapability {
1358 name: "error_trace",
1359 flag: "--error-trace",
1360 required: false,
1361 values: vec!["boolean"],
1362 default: Some("false"),
1363 },
1364 ArgumentCapability {
1365 name: "format",
1366 flag: "--format",
1367 required: false,
1368 values: vec!["human", "json"],
1369 default: Some("json"),
1370 },
1371 ],
1372 success_exit_code: 0,
1373 errors: vec![
1374 ErrorCapability {
1375 code: "invalid_arguments",
1376 exit_code: 2,
1377 channel: "stderr",
1378 },
1379 ErrorCapability {
1380 code: "invalid_circuit",
1381 exit_code: 2,
1382 channel: "stderr",
1383 },
1384 ErrorCapability {
1385 code: "input_error",
1386 exit_code: 2,
1387 channel: "stderr",
1388 },
1389 ErrorCapability {
1390 code: "execution_error",
1391 exit_code: 2,
1392 channel: "stderr",
1393 },
1394 ],
1395 decoders: Vec::new(),
1396 artifacts: vec![
1397 ArtifactCapability {
1398 name: "public_dataset",
1399 flag: "--public-out",
1400 format: "directory",
1401 },
1402 ArtifactCapability {
1403 name: "private_answers",
1404 flag: "--private-out",
1405 format: "directory",
1406 },
1407 ],
1408 },
1409 Capability {
1410 name: pipeline::DATASET_IMPORT_COMMAND,
1411 argv: vec!["dataset", "import"],
1412 input_sources: vec!["file"],
1413 formats: vec!["human", "json"],
1414 output_schema: SCHEMA_VERSION,
1415 arguments: vec![
1416 ArgumentCapability {
1417 name: "circuit",
1418 flag: "--circuit",
1419 required: true,
1420 values: vec!["path"],
1421 default: None,
1422 },
1423 ArgumentCapability {
1424 name: "shots",
1425 flag: "--shots",
1426 required: true,
1427 values: vec!["path"],
1428 default: None,
1429 },
1430 ArgumentCapability {
1431 name: "shots_format",
1432 flag: "--shots-format",
1433 required: false,
1434 values: vec!["01", "b8"],
1435 default: Some("01"),
1436 },
1437 ArgumentCapability {
1438 name: "out",
1439 flag: "--out",
1440 required: true,
1441 values: vec!["path"],
1442 default: None,
1443 },
1444 ArgumentCapability {
1445 name: "loss_log",
1446 flag: "--loss-log",
1447 required: false,
1448 values: vec!["path"],
1449 default: None,
1450 },
1451 ArgumentCapability {
1452 name: "format",
1453 flag: "--format",
1454 required: false,
1455 values: vec!["human", "json"],
1456 default: Some("json"),
1457 },
1458 ],
1459 success_exit_code: 0,
1460 errors: vec![
1461 ErrorCapability {
1462 code: "invalid_arguments",
1463 exit_code: 2,
1464 channel: "stderr",
1465 },
1466 ErrorCapability {
1467 code: "invalid_circuit",
1468 exit_code: 2,
1469 channel: "stderr",
1470 },
1471 ErrorCapability {
1472 code: "input_error",
1473 exit_code: 2,
1474 channel: "stderr",
1475 },
1476 ErrorCapability {
1477 code: "invalid_dataset",
1478 exit_code: 2,
1479 channel: "stderr",
1480 },
1481 ErrorCapability {
1482 code: "unsupported_circuit",
1483 exit_code: 2,
1484 channel: "stderr",
1485 },
1486 ErrorCapability {
1487 code: "loss_log_mismatch",
1488 exit_code: 2,
1489 channel: "stderr",
1490 },
1491 ErrorCapability {
1492 code: "output_error",
1493 exit_code: 2,
1494 channel: "stderr",
1495 },
1496 ],
1497 decoders: Vec::new(),
1498 artifacts: vec![ArtifactCapability {
1499 name: "public_dataset",
1500 flag: "--out",
1501 format: "directory",
1502 }],
1503 },
1504 Capability {
1505 name: decode::COMMAND,
1506 argv: vec!["decode"],
1507 input_sources: vec!["public_decoder_dataset_directory"],
1508 formats: vec!["b8", "json"],
1509 output_schema: decode::STATS_SCHEMA_VERSION,
1510 arguments: vec![
1511 ArgumentCapability {
1512 name: "decoder",
1513 flag: "--decoder",
1514 required: true,
1515 values: available_decoders(),
1516 default: None,
1517 },
1518 ArgumentCapability {
1519 name: "dataset",
1520 flag: "--dataset",
1521 required: true,
1522 values: vec!["path"],
1523 default: None,
1524 },
1525 ArgumentCapability {
1526 name: "predictions",
1527 flag: "--out",
1528 required: true,
1529 values: vec!["path"],
1530 default: None,
1531 },
1532 ArgumentCapability {
1533 name: "stats",
1534 flag: "--stats-out",
1535 required: true,
1536 values: vec!["path"],
1537 default: None,
1538 },
1539 ArgumentCapability {
1540 name: "shot_timeout_ms",
1541 flag: "--shot-timeout-ms",
1542 required: false,
1543 values: vec!["non_negative_integer"],
1544 default: None,
1545 },
1546 ],
1547 success_exit_code: 0,
1548 errors: vec![
1549 ErrorCapability {
1550 code: "invalid_arguments",
1551 exit_code: 2,
1552 channel: "stderr",
1553 },
1554 ErrorCapability {
1555 code: "missing_dataset_file",
1556 exit_code: 2,
1557 channel: "stderr",
1558 },
1559 ErrorCapability {
1560 code: "invalid_dataset",
1561 exit_code: 2,
1562 channel: "stderr",
1563 },
1564 ErrorCapability {
1565 code: "unsupported_dataset_mode",
1566 exit_code: 2,
1567 channel: "stderr",
1568 },
1569 ErrorCapability {
1570 code: "unsupported_circuit",
1571 exit_code: 2,
1572 channel: "stderr",
1573 },
1574 ErrorCapability {
1575 code: "decode_timeout",
1576 exit_code: 3,
1577 channel: "stderr",
1578 },
1579 ErrorCapability {
1580 code: "decode_infeasible",
1581 exit_code: 3,
1582 channel: "stderr",
1583 },
1584 ErrorCapability {
1585 code: "decode_error",
1586 exit_code: 2,
1587 channel: "stderr",
1588 },
1589 ErrorCapability {
1590 code: "output_error",
1591 exit_code: 2,
1592 channel: "stderr",
1593 },
1594 ],
1595 decoders: available_decoders(),
1596 artifacts: vec![
1597 ArtifactCapability {
1598 name: "predictions",
1599 flag: "--out",
1600 format: "b8",
1601 },
1602 ArtifactCapability {
1603 name: "stats",
1604 flag: "--stats-out",
1605 format: "rustqec.decode-stats.v1+json",
1606 },
1607 ],
1608 },
1609 ],
1610 },
1611 )
1612 .map_err(|message| CommandError {
1613 command: "capabilities",
1614 code: "output_error",
1615 message,
1616 json,
1617 exit_code: 2,
1618 })
1619}
1620
1621fn write_json(out: &mut dyn Write, value: &impl Serialize) -> Result<(), String> {
1622 serde_json::to_writer_pretty(&mut *out, value).map_err(|error| error.to_string())?;
1623 out.write_all(b"\n").map_err(|error| error.to_string())
1624}
1625
1626pub fn write_error(error: &RunError, stdout: &mut dyn Write, stderr: &mut dyn Write) {
1627 match error {
1628 RunError::Clap { error, .. }
1629 if matches!(
1630 error.kind(),
1631 ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
1632 ) =>
1633 {
1634 let _ = write!(stdout, "{error}");
1635 }
1636 RunError::Clap {
1637 error,
1638 command,
1639 json: true,
1640 } => {
1641 let message = error.to_string();
1642 let envelope = ErrorEnvelope {
1643 schema_version: SCHEMA_VERSION,
1644 status: "error",
1645 command,
1646 error: ErrorBody {
1647 code: "invalid_arguments",
1648 message: &message,
1649 },
1650 };
1651 let _ = write_json(stderr, &envelope);
1652 }
1653 RunError::Clap { error, .. } => {
1654 let _ = write!(stderr, "{error}");
1655 }
1656 RunError::Command(error) if error.json => {
1657 let envelope = ErrorEnvelope {
1658 schema_version: SCHEMA_VERSION,
1659 status: "error",
1660 command: error.command,
1661 error: ErrorBody {
1662 code: error.code,
1663 message: &error.message,
1664 },
1665 };
1666 let _ = write_json(stderr, &envelope);
1667 }
1668 RunError::Command(error) => {
1669 let _ = writeln!(stderr, "{}", error.message);
1670 }
1671 }
1672}
1673
1674pub fn exit_code(error: &RunError) -> u8 {
1675 match error {
1676 RunError::Clap { error, .. } => error.exit_code() as u8,
1677 RunError::Command(error) => error.exit_code,
1678 }
1679}
1680
1681fn parse_error_context(args: &[OsString]) -> (&'static str, bool) {
1682 let words = args
1683 .iter()
1684 .skip(1)
1685 .map(|value| value.to_string_lossy())
1686 .collect::<Vec<_>>();
1687 let command_words = words_without_global_options(&words);
1688 let is_stats = command_words
1689 .windows(2)
1690 .any(|pair| pair[0] == "circuit" && pair[1] == "stats");
1691 let pipeline_command = ["gen", "sample", "detect", "dem"].iter().find_map(|verb| {
1692 command_words
1693 .windows(2)
1694 .any(|pair| pair[0] == "circuit" && pair[1] == *verb)
1695 .then_some(match *verb {
1696 "gen" => pipeline::CIRCUIT_GEN_COMMAND,
1697 "sample" => pipeline::CIRCUIT_SAMPLE_COMMAND,
1698 "detect" => pipeline::CIRCUIT_DETECT_COMMAND,
1699 _ => pipeline::CIRCUIT_DEM_COMMAND,
1700 })
1701 });
1702 let is_dataset_export = command_words
1703 .windows(2)
1704 .any(|pair| pair[0] == "dataset" && pair[1] == "export");
1705 let is_capabilities = command_words.contains(&"capabilities");
1706 let is_decode = command_words.contains(&"decode");
1707 let command = if is_stats {
1708 CIRCUIT_STATS_COMMAND
1709 } else if let Some(pipeline_command) = pipeline_command {
1710 pipeline_command
1711 } else if is_dataset_export {
1712 pipeline::DATASET_EXPORT_COMMAND
1713 } else if is_capabilities {
1714 "capabilities"
1715 } else if is_decode {
1716 decode::COMMAND
1717 } else {
1718 "rustqec"
1719 };
1720
1721 let explicit_error_format = option_value(&words, "--error-format");
1722 let explicit_output_format = option_value(&words, "--format");
1723 let json = match explicit_error_format {
1724 Some(Some("human")) => false,
1725 Some(_) => true,
1726 None if is_capabilities || is_decode => true,
1727 None if pipeline_command.is_some() || is_dataset_export => {
1728 !matches!(explicit_output_format, Some(Some("human")))
1729 }
1730 None if is_stats => match explicit_output_format {
1731 Some(Some("human")) => false,
1732 Some(_) => true,
1733 None => false,
1734 },
1735 None => false,
1736 };
1737 (command, json)
1738}
1739
1740fn words_without_global_options<'a>(words: &'a [std::borrow::Cow<'a, str>]) -> Vec<&'a str> {
1741 let mut command_words = Vec::new();
1742 let mut index = 0;
1743 while index < words.len() {
1744 let word = words[index].as_ref();
1745 if word == "--error-format" {
1746 index += 2;
1747 } else if word.starts_with("--error-format=") {
1748 index += 1;
1749 } else {
1750 command_words.push(word);
1751 index += 1;
1752 }
1753 }
1754 command_words
1755}
1756
1757fn option_value<'a>(words: &'a [std::borrow::Cow<'a, str>], flag: &str) -> Option<Option<&'a str>> {
1758 for (index, word) in words.iter().enumerate() {
1759 if word == flag {
1760 return Some(words.get(index + 1).map(|value| value.as_ref()));
1761 }
1762 if let Some(value) = word
1763 .strip_prefix(flag)
1764 .and_then(|rest| rest.strip_prefix('='))
1765 {
1766 return Some(Some(value));
1767 }
1768 }
1769 None
1770}