1use crate::{callback_results, run_many, OperatorError, RunOpts, WORK_V1};
15use serde::{Deserialize, Serialize};
16use serde_json::{json, Value};
17
18pub const HARNESS_REQUEST_V1: &str = "pcvc-aria-telemetry-request-v1";
20pub const HARNESS_RESULT_V1: &str = "pcvc-aria-telemetry-result-v1";
22pub const HARNESS_CAPABILITY: &str = "aria.telemetry.project";
24pub const DEFAULT_OUTPUT_LIMIT: usize = 64 * 1024;
26
27#[derive(Debug, Clone, Deserialize, Serialize)]
30#[serde(deny_unknown_fields, rename_all = "camelCase")]
31pub struct HarnessRequest {
32 pub schema_version: String,
33 pub capability: String,
34 pub run_id: String,
35 pub plan_hash: String,
36 pub attempt_id: String,
37 pub fencing_token: u64,
38 pub requirement_id: String,
39 pub ops: Vec<String>,
41 pub payload: Value,
43 #[serde(default)]
45 pub steps: u64,
46 #[serde(default = "default_seed")]
48 pub seed: u64,
49 #[serde(default = "default_limit")]
51 pub output_limit_bytes: usize,
52}
53
54fn default_seed() -> u64 {
55 1
56}
57
58fn default_limit() -> usize {
59 DEFAULT_OUTPUT_LIMIT
60}
61
62#[derive(Debug, Clone, Serialize)]
64#[serde(rename_all = "camelCase")]
65pub struct HarnessResult {
66 pub schema_version: &'static str,
67 pub capability: String,
68 pub run_id: String,
69 pub plan_hash: String,
70 pub attempt_id: String,
71 pub fencing_token: u64,
72 pub requirement_id: String,
73 pub status: &'static str,
77 #[serde(skip_serializing_if = "Option::is_none")]
78 pub limitation: Option<String>,
79 #[serde(skip_serializing_if = "Option::is_none")]
81 pub callback: Option<Value>,
82 #[serde(skip_serializing_if = "is_zero")]
84 pub dropped_verticals: usize,
85}
86
87#[allow(clippy::trivially_copy_pass_by_ref)] fn is_zero(n: &usize) -> bool {
89 *n == 0
90}
91
92#[derive(Debug, thiserror::Error)]
94pub enum HarnessError {
95 #[error("request is not valid JSON: {0}")]
96 Json(#[from] serde_json::Error),
97 #[error("schemaVersion must be {HARNESS_REQUEST_V1}")]
98 Schema,
99 #[error("capability must be {HARNESS_CAPABILITY}")]
100 Capability,
101 #[error("{0} is not a 64-hex sha256")]
102 Hex(&'static str),
103 #[error("{0} must be non-empty")]
104 Empty(&'static str),
105 #[error("fencingToken must be ≥ 1")]
106 Fence,
107 #[error("outputLimitBytes must be in 1..={DEFAULT_OUTPUT_LIMIT}")]
108 Limit,
109 #[error("unknown binary {0}")]
110 UnknownBinary(String),
111}
112
113fn is_hex64(s: &str) -> bool {
114 s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
115}
116
117impl HarnessRequest {
118 pub fn parse(raw: &[u8]) -> Result<Self, HarnessError> {
120 let req: Self = serde_json::from_slice(raw)?;
121 if req.schema_version != HARNESS_REQUEST_V1 {
122 return Err(HarnessError::Schema);
123 }
124 if req.capability != HARNESS_CAPABILITY {
125 return Err(HarnessError::Capability);
126 }
127 if !is_hex64(&req.plan_hash) {
128 return Err(HarnessError::Hex("planHash"));
129 }
130 for (name, v) in [
131 ("runId", &req.run_id),
132 ("attemptId", &req.attempt_id),
133 ("requirementId", &req.requirement_id),
134 ] {
135 if v.trim().is_empty() {
136 return Err(HarnessError::Empty(name));
137 }
138 }
139 if req.fencing_token == 0 {
140 return Err(HarnessError::Fence);
141 }
142 if req.output_limit_bytes == 0 || req.output_limit_bytes > DEFAULT_OUTPUT_LIMIT {
143 return Err(HarnessError::Limit);
144 }
145 if req.ops.is_empty() {
146 return Err(HarnessError::Empty("ops"));
147 }
148 for id in &req.ops {
149 if id != "*" && crate::spec_by_id(id).is_none() {
150 return Err(HarnessError::UnknownBinary(id.clone()));
151 }
152 }
153 Ok(req)
154 }
155
156 fn resolved_ops(&self) -> Vec<String> {
157 if self.ops.iter().any(|o| o == "*") {
158 crate::catalog()
159 .iter()
160 .filter(|s| s.layer != "HOST")
161 .map(|s| s.binary_id.clone())
162 .collect()
163 } else {
164 self.ops.clone()
165 }
166 }
167
168 fn bound(&self, status: &'static str) -> HarnessResult {
169 HarnessResult {
170 schema_version: HARNESS_RESULT_V1,
171 capability: self.capability.clone(),
172 run_id: self.run_id.clone(),
173 plan_hash: self.plan_hash.clone(),
174 attempt_id: self.attempt_id.clone(),
175 fencing_token: self.fencing_token,
176 requirement_id: self.requirement_id.clone(),
177 status,
178 limitation: None,
179 callback: None,
180 dropped_verticals: 0,
181 }
182 }
183}
184
185#[must_use]
188pub fn execute_harness(req: &HarnessRequest) -> HarnessResult {
189 let opts = RunOpts {
190 steps: req.steps,
191 seed: Some(req.seed),
192 plan_hash: Some(req.plan_hash.clone()),
193 requirement_id: Some(req.requirement_id.clone()),
194 include_telemetry: false,
195 ..RunOpts::default()
196 };
197 let payload = match serde_json::to_vec(&req.payload) {
198 Ok(b) => b,
199 Err(e) => {
200 let mut r = req.bound("limitation");
201 r.limitation = Some(format!("payload not serializable: {e}"));
202 return r;
203 }
204 };
205 let binaries = req.resolved_ops();
206 let envs = match run_many(&binaries, &payload, &opts) {
207 Ok(e) => e,
208 Err(e) => {
209 let mut r = req.bound("limitation");
210 r.limitation = Some(match &e {
211 OperatorError::UnknownBinary(id) => format!("unknown binary {id}"),
212 other => other.to_string(),
213 });
214 return r;
215 }
216 };
217 let asked = envs.len();
218 let mut working: Vec<Value> = callback_results(&envs)
219 .into_iter()
220 .filter_map(|e| serde_json::to_value(e).ok())
221 .collect();
222
223 let mut dropped = 0usize;
226 let organize = crate::organize_slop(&payload);
227 let build = |results: &Vec<Value>| {
228 json!({
229 "schema": WORK_V1,
230 "phi_once": true,
231 "asked": asked,
232 "ops": results.len(),
233 "organize": organize,
234 "results": results,
235 })
236 };
237 let fits = |r: &HarnessResult| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len()) <= req.output_limit_bytes;
238 let mut result = req.bound(if working.is_empty() { "no-finding" } else { "result" });
239 result.callback = Some(build(&working));
240 if !fits(&result) {
241 working.sort_by(|a, b| {
242 let sa = serde_json::to_vec(a).map_or(0, |v| v.len());
243 let sb = serde_json::to_vec(b).map_or(0, |v| v.len());
244 sb.cmp(&sa).then_with(|| a["binary_id"].as_str().cmp(&b["binary_id"].as_str()))
245 });
246 while !working.is_empty() {
247 working.remove(0);
248 dropped += 1;
249 result.callback = Some(build(&working));
250 result.dropped_verticals = dropped;
251 result.status = "truncation";
252 if fits(&result) {
253 break;
254 }
255 }
256 if working.is_empty() {
257 result.status = "limitation";
259 result.callback = None;
260 result.limitation = Some(format!(
261 "output budget {} B too small for a bound result",
262 req.output_limit_bytes
263 ));
264 }
265 }
266 result
267}
268
269#[must_use]
273pub fn harness_lane(raw: &[u8]) -> (i32, Vec<u8>) {
274 match HarnessRequest::parse(raw) {
275 Ok(req) => {
276 let result = execute_harness(&req);
277 (0, serde_json::to_vec(&result).unwrap_or_default())
278 }
279 Err(e) => (
280 2,
281 serde_json::to_vec(&json!({
282 "schemaVersion": HARNESS_RESULT_V1,
283 "status": "failure",
284 "error": e.to_string(),
285 }))
286 .unwrap_or_default(),
287 ),
288 }
289}
290
291#[must_use]
295pub fn dispatch_json() -> Value {
296 static EXE: std::sync::OnceLock<(Option<std::path::PathBuf>, Option<String>)> =
299 std::sync::OnceLock::new();
300 let (exe, exe_sha) = EXE.get_or_init(|| {
301 let exe = std::env::current_exe().ok();
302 let sha = exe
303 .as_ref()
304 .and_then(|p| std::fs::read(p).ok())
305 .map(|b| aria_engine_backends::ipo::sha256_hex(&b));
306 (exe, sha)
307 });
308 let (exe, exe_sha) = (exe.clone(), exe_sha.clone());
309 let binaries: Vec<Value> = crate::catalog()
310 .iter()
311 .map(|s| {
312 json!({
313 "binary_id": s.binary_id,
314 "operator": s.operator,
315 "package": s.package,
316 "class": s.class,
317 "layer": s.layer,
318 "verify": s.verify,
319 "resultDefinitionRef": s.result_definition_ref,
320 "node_types": s.node_types,
321 "relationship_types": s.relationship_types,
322 "anchor_tags": s.anchor_tags,
323 "default_limit": s.default_limit,
324 "graph": crate::OperatorGraph::from_spec(s),
325 })
326 })
327 .collect();
328 json!({
329 "schema": "aria-dispatch-v1",
330 "crate": "aria-json-telemetry",
331 "version": env!("CARGO_PKG_VERSION"),
332 "capability": {
333 "name": HARNESS_CAPABILITY,
334 "version": "v1",
335 "request_schema": HARNESS_REQUEST_V1,
336 "result_schema": HARNESS_RESULT_V1,
337 "callback_schema": WORK_V1,
338 "stdin": "canonical JSON request",
339 "stdout": "one JSON result; nothing else",
340 "stderr": "always empty",
341 "exit": {"0": "bound result (result | no-finding | truncation | limitation)", "2": "protocol error (unbound)"},
342 "output_limit_bytes": DEFAULT_OUTPUT_LIMIT,
343 "default_steps": 0,
344 "deterministic": "equal request bytes ⇒ equal result bytes",
345 "state": "none (stateless node; Neo4j is memory)",
346 },
347 "executable": {
348 "name": "work",
349 "path": exe.map(|p| p.display().to_string()),
350 "sha256": exe_sha,
351 "system": std::env::consts::OS,
352 "machine": std::env::consts::ARCH,
353 },
354 "catalog": binaries.len(),
355 "binaries": binaries,
356 })
357}