Skip to main content

aria_operator/
harness.rs

1//! PCVC Mode 4 harness lane.
2//!
3//! Mirrors the native-binary protocol PCVC's `mode4/binaries/driver.py`
4//! enforces: canonical JSON on stdin, one JSON document on stdout, **nothing**
5//! on stderr, exit 0, bounded output, and every binding field echoed back so
6//! the worker can reject a mismatched result. Statelessness is the contract:
7//! `request bytes → result bytes`, deterministic under the seed.
8//!
9//! Capability: `aria.telemetry.project` — the worker names one or more
10//! catalog binaries (`ops`) and supplies the payload it wants organized; it
11//! receives the `aria-work-v1` callback (working verticals only) inside a
12//! result that echoes its bindings.
13
14use crate::{callback_results, run_many, OperatorError, RunOpts, WORK_V1};
15use serde::{Deserialize, Serialize};
16use serde_json::{json, Value};
17
18/// Request schema tag (stable; additive changes bump the suffix).
19pub const HARNESS_REQUEST_V1: &str = "pcvc-aria-telemetry-request-v1";
20/// Result schema tag.
21pub const HARNESS_RESULT_V1: &str = "pcvc-aria-telemetry-result-v1";
22/// The one closed capability this node registers.
23pub const HARNESS_CAPABILITY: &str = "aria.telemetry.project";
24/// Default stdout budget — matches PCVC's `_OUTPUT_BYTES` (64 KiB).
25pub const DEFAULT_OUTPUT_LIMIT: usize = 64 * 1024;
26
27/// What a PCVC worker sends on stdin. Field names are camelCase to match the
28/// harness's Pydantic aliases; unknown fields are rejected (closed model).
29#[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    /// Catalog identities to project (one or many). `["*"]` = every research op.
40    pub ops: Vec<String>,
41    /// The original anchor the worker wants organized (never rewritten).
42    pub payload: Value,
43    /// Φ steps; `0` is the identify funnel (default).
44    #[serde(default)]
45    pub steps: u64,
46    /// Seed for byte-determinism (default 1).
47    #[serde(default = "default_seed")]
48    pub seed: u64,
49    /// Output budget in bytes (default 64 KiB); may only be tightened.
50    #[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/// Bindings a harness re-checks on the way back (`driver.py` field list).
63#[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    /// `result` (≥1 working vertical) · `no-finding` (asked, nothing supports)
74    /// · `truncation` (budget trimmed the callback) · `limitation` (engine
75    /// rejected the payload; reason in `limitation`).
76    pub status: &'static str,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub limitation: Option<String>,
79    /// The production callback (`aria-work-v1`). Absent only on `limitation`.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub callback: Option<Value>,
82    /// Bytes of the callback that were dropped to honour the budget.
83    #[serde(skip_serializing_if = "is_zero")]
84    pub dropped_verticals: usize,
85}
86
87#[allow(clippy::trivially_copy_pass_by_ref)] // serde skip_serializing_if signature
88fn is_zero(n: &usize) -> bool {
89    *n == 0
90}
91
92/// Validation failures a harness treats as protocol errors (non-zero exit).
93#[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    /// Parse + validate the closed request.
119    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/// Execute one harness request. Never panics; engine rejections become a
186/// `limitation` result (still bound, still exit 0) — the harness decides.
187#[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    // Budget: drop the largest verticals last-first until the result fits.
224    // Deterministic (stable sort by size desc, then binary_id), reported.
225    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            // Even the empty callback does not fit: report as limitation.
258            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/// Full stdin → stdout lane. Returns `(exit code, stdout bytes)`; stderr is
270/// never written. Protocol errors (unparseable/unbound request) exit 2 with
271/// a JSON error object so the harness sees why without a stderr channel.
272#[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/// `aria-dispatch-v1`: the descriptor PCVC's registry / policy layer pins.
292/// Everything is a function of the frozen catalog plus this executable's
293/// identity, so the harness can record exact hashes (Mode 4 step 5).
294#[must_use]
295pub fn dispatch_json() -> Value {
296    // The executable's identity is fixed for the life of the process; hash it
297    // once (a hosted node serves /dispatch to every registry probe).
298    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}