1use decl_lang::allocation_diagnostics::{snapshot, CountingAllocator, Snapshot};
3use decl_lang::session::{BindSource, Mode, Op, Session};
4use serde_json::json;
5use std::io::Write;
6use std::path::Path;
7
8#[global_allocator]
9static ALLOC: CountingAllocator = CountingAllocator;
10
11#[derive(Clone, Copy, Default)]
12struct Stamp {
13 wall_ns: u64,
14 cpu_ns: u64,
15 sampled_until_ns: u64,
16 allocation: Snapshot,
17}
18fn clock_ns(id: libc::clockid_t) -> u64 {
19 let mut time = libc::timespec {
20 tv_sec: 0,
21 tv_nsec: 0,
22 };
23 assert_eq!(unsafe { libc::clock_gettime(id, &mut time) }, 0);
25 assert!(time.tv_sec >= 0 && time.tv_nsec >= 0);
26 (time.tv_sec as u64)
27 .checked_mul(1_000_000_000)
28 .and_then(|s| s.checked_add(time.tv_nsec as u64))
29 .unwrap()
30}
31fn stamp() -> Stamp {
32 let wall_ns = clock_ns(libc::CLOCK_MONOTONIC);
33 let cpu_ns = clock_ns(libc::CLOCK_PROCESS_CPUTIME_ID);
34 let sampled_until_ns = clock_ns(libc::CLOCK_MONOTONIC);
35 Stamp {
36 wall_ns,
37 cpu_ns,
38 sampled_until_ns,
39 allocation: snapshot(),
40 }
41}
42fn seconds(a: Stamp, b: Stamp) -> f64 {
43 b.wall_ns.checked_sub(a.wall_ns).unwrap() as f64 / 1e9
44}
45fn write_new(path: &Path, data: &[u8]) {
46 std::fs::OpenOptions::new()
47 .write(true)
48 .create_new(true)
49 .open(path)
50 .unwrap()
51 .write_all(data)
52 .unwrap();
53}
54const PHASES: [&str; 8] = [
55 "setup",
56 "full_run",
57 "engine_lookup",
58 "serialize",
59 "scalar_capture",
60 "output_write",
61 "request_owner_release",
62 "session_owner_release",
63];
64
65fn main() {
66 std::thread::Builder::new()
67 .stack_size(1 << 30)
68 .spawn(run)
69 .unwrap()
70 .join()
71 .unwrap();
72}
73fn run() {
74 assert_eq!(std::env::var("DECL_QENGINE").as_deref(), Ok("1"));
75 assert_eq!(std::env::var("DECL_QENGINE_STRICT").as_deref(), Ok("1"));
76 let args: Vec<String> = std::env::args().collect();
77 assert_eq!(
78 args.len(),
79 5,
80 "usage: session-initial MODEL INPUT_ROOT=INPUT_FILE OUTPUT_ROOT OUTPUT_PREFIX"
81 );
82 let model = Path::new(&args[1]).canonicalize().unwrap();
83 let (input_root, input_path) = args[2]
85 .split_once('=')
86 .expect("the input is written INPUT_ROOT=INPUT_FILE");
87 let input = Path::new(input_path).canonicalize().unwrap();
88 let output_root = args[3].as_str();
89 let output_file = format!("{}-{output_root}.json", args[4]);
90 let metrics_file = format!("{}-initial.json", args[4]);
91 assert!(!Path::new(&output_file).exists() && !Path::new(&metrics_file).exists());
92 let mut stamps = [Stamp::default(); 9];
93 stamps[0] = stamp();
94 let mut session = Session::new(Some(model.to_str().unwrap()));
95 session
96 .apply(Op::Bind {
97 name: input_root.into(),
98 src: BindSource::Inline {
99 text: std::fs::read_to_string(&input).unwrap(),
100 },
101 })
102 .unwrap();
103 stamps[1] = stamp();
104 let run = session.run(Mode::Full);
105 stamps[2] = stamp();
106 let eng = run.eng.as_ref().expect("Session did not return an engine");
107 stamps[3] = stamp();
108 let output = eng.serialize(
109 &eng.env
110 .root(output_root)
111 .expect("the model declares no such output root"),
112 output_root,
113 false,
114 );
115 stamps[4] = stamp();
116
117 let edits = eng.edits.borrow().as_ref().unwrap().clone();
119 let rev = &edits.revisions;
120 let counters = [
121 rev.revision.get(),
122 rev.verified_cutoffs.get(),
123 rev.value_cutoffs.get(),
124 rev.recomputed.get(),
125 edits.slot_computes.get(),
126 edits.prepared_queries.get(),
127 edits.retained_records.get(),
128 ];
129 let diagnostics = [
130 run.load_diags.len(),
131 run.checks.len(),
132 run.session_checks.len(),
133 run.diags.len(),
134 ];
135 let post_serialize_diags = eng.env.diag_len();
136 let timing = run.timing;
137 let output_bytes = output.len();
138 let module_count = run.modules.len();
139 stamps[5] = stamp();
140 write_new(Path::new(&output_file), output.as_bytes());
141 stamps[6] = stamp();
142 drop(edits);
145 drop(output);
146 drop(run);
147 stamps[7] = stamp();
148 drop(session);
149 stamps[8] = stamp();
150
151 let gc = decl_lang::semantics::take_gc_diagnostics();
153 let evaluation = decl_lang::evaluation_diagnostics::take_evaluation_diagnostics();
154 assert_eq!(diagnostics, [0; 4], "initial Session diagnostics");
155 assert_eq!(post_serialize_diags, 0, "serialization diagnostics");
156 let setup_s = seconds(stamps[0], stamps[1]);
157 let full_s = seconds(stamps[1], stamps[2]);
158 let serialize_s = seconds(stamps[3], stamps[4]);
159 let request = json!({
160 "operation": "initial", "index": 0, "value": null,
161 "setup_s": setup_s, "apply_s": 0.0,
162 "evaluate_validate_s": full_s, "serialize_s": serialize_s,
163 "total_s": full_s + serialize_s,
164 "measurement_boundary": "apply + Session.run(Full) + serialize the output root; setup, counters, diagnostics inspection, output writes, and teardown excluded",
165 "internal_timing_s": timing.total / 1000.0,
166 "internal_recomputed": timing.recomputed, "internal_slots": timing.slots,
167 "revision_total": counters[0],
168 "revision_delta": {"revision": counters[0], "verified_cutoffs": counters[1],
169 "value_cutoffs": counters[2], "recomputed": counters[3]},
170 "revision_counters_total": {"verified_cutoffs": counters[1],
171 "value_cutoffs": counters[2], "recomputed": counters[3]},
172 "prepared_queries_latest_edit": counters[5], "prepared_queries_this_request": 0,
173 "prepared_counter_semantics": "latest-edit gauge; this_request is zero when the revision did not advance",
174 "slot_computes_total": counters[4], "slot_computes_delta": counters[4],
175 "retained_records_latest_edit": counters[6],
176 "diagnostics": {"load": diagnostics[0], "check": diagnostics[1],
177 "session_check": diagnostics[2], "evaluation": diagnostics[3]},
178 "output_bytes": output_bytes,
179 });
180 let boundaries: Vec<_> = stamps
181 .iter()
182 .enumerate()
183 .map(|(i, s)| {
184 json!({
185 "after": if i == 0 { "start" } else { PHASES[i - 1] },
186 "wall_ns": s.wall_ns, "cpu_ns": s.cpu_ns,
187 "sampled_until_ns": s.sampled_until_ns, "allocation": s.allocation,
188 })
189 })
190 .collect();
191 let row = json!({
192 "schema": 1, "role": "initial-session-support", "primary_timing": false,
193 "build_manifest_dir": env!("CARGO_MANIFEST_DIR"), "model": model, "input": input,
194 "input_root": input_root, "output_root": output_root,
195 "output_file": output_file, "output_bytes": output_bytes,
196 "module_count": module_count, "request": request,
197 "diagnostic_counts": diagnostics, "post_serialize_diags": post_serialize_diags,
198 "run_timing_ms": {"load": timing.load, "check": timing.check,
199 "bind": timing.bind, "evaluate": timing.evaluate, "total": timing.total},
200 "phase_order": PHASES, "boundaries": boundaries,
201 "gc": gc, "evaluation": evaluation,
202 "wall_clock": "CLOCK_MONOTONIC; first sample defines boundary",
203 "cpu_clock": "CLOCK_PROCESS_CPUTIME_ID; process user+system across threads",
204 "ownership": "Normal request Edits/output/Run release, then Session release; no explicit collection; scalar metrics emitted afterwards",
205 "limits": "Instrumented initial request only; Run.timing.bind is closure/setup, actual binding is inside evaluation round spans; not native paired timing",
206 });
207 let text = format!("{}\n", serde_json::to_string(&row).unwrap());
208 write_new(Path::new(&metrics_file), text.as_bytes());
209 print!("{text}");
210}