areev_trigger/eval.rs
1//! The evaluation cycle: find due, claim, invoke, ingest, start, release.
2//!
3//! One invocation performs the whole cycle and exits. Nothing stays resident.
4//! Losing a claim race is a no-op exit, not an error — that is the steady state
5//! when several nodes share a heartbeat.
6//!
7//! ## Why correctness does not rest on the lease
8//!
9//! A lease deduplicates *"who is working right now"*. But the thing that
10//! actually needs deduplicating — a firing of trigger T for item I — has a
11//! natural identity, so the run id is derived from it. `areev run start`
12//! already refuses a duplicate run id, so two evaluators racing produce one run
13//! and one recorded skip, with no lease consulted at all: no duration to guess,
14//! no fencing token to compare, no clock-skew window.
15//!
16//! The lease then does one narrower job: stopping two nodes from both making
17//! the same expensive, side-effecting connector call. Losing it can cost a
18//! wasted API call; it can never cause a missed or duplicated firing. That is
19//! the risk profile a lease should carry.
20
21use std::collections::HashMap;
22use std::sync::Arc;
23
24use areev_cal::AreevFacade;
25use areev_core::error::{AreevError, Hash};
26use areev_core::types::{ContentRef, Event, Grain, GrainType, Observation, Trigger, TriggerKind};
27use areev_run::HostToolExecutor;
28use areev_store::TriggerState;
29use serde::Serialize;
30use sha2::{Digest, Sha256};
31
32use crate::clock::Clock;
33use crate::connector::{
34 dedup_value, rewrite_blob_refs, PollItem, PollRequest, PollResponse,
35 MAX_BLOB_BYTES_PER_ITEM, MAX_BLOB_BYTES_PER_RESPONSE,
36};
37use crate::error::{Result, TriggerError};
38use crate::schedule;
39
40/// Namespace for trigger firing records. Alongside the runtime's own
41/// `agent:harness`, so operational journalling stays out of user namespaces.
42pub const TRIGGER_NS: &str = "agent:triggers";
43
44/// How many triggers one invocation will look at. A backstop, not a policy.
45const MAX_TRIGGERS_SCANNED: usize = 4096;
46
47/// Knobs for one evaluation pass.
48#[derive(Debug, Clone)]
49pub struct EvalOptions {
50 /// Evaluate only this trigger (its content address).
51 pub only: Option<String>,
52 /// How long a claim is held before another evaluator may take over.
53 /// Deliberately generous: a lease shorter than the worst-case connector
54 /// runtime causes takeovers mid-poll, which costs duplicate API calls.
55 pub lease: std::time::Duration,
56 /// Cap on items requested per firing.
57 pub max_items: usize,
58 /// Report what would happen and touch nothing. The safe first command on a
59 /// new deployment.
60 pub dry_run: bool,
61 /// This evaluator's identity, recorded in the claim.
62 pub node: String,
63 /// Decoded-size budget for one item's connector blobs (#93). Overrun
64 /// refuses the whole poll (TRG-E011) rather than truncating.
65 pub max_blob_bytes_per_item: usize,
66 /// Decoded-size budget for one poll response's blobs (#93).
67 pub max_blob_bytes_per_response: usize,
68}
69
70impl Default for EvalOptions {
71 fn default() -> Self {
72 EvalOptions {
73 only: None,
74 lease: std::time::Duration::from_secs(300),
75 max_items: 100,
76 dry_run: false,
77 node: default_node_id(),
78 max_blob_bytes_per_item: MAX_BLOB_BYTES_PER_ITEM,
79 max_blob_bytes_per_response: MAX_BLOB_BYTES_PER_RESPONSE,
80 }
81 }
82}
83
84/// First `n` characters, safely — `&s[..n]` panics on a short string or a
85/// multi-byte boundary, and a message-formatting helper must not be what takes
86/// the process down. Declarations can arrive by bundle import from an
87/// implementation we did not write.
88fn short(s: &str, n: usize) -> &str {
89 match s.char_indices().nth(n) {
90 Some((idx, _)) => &s[..idx],
91 None => s,
92 }
93}
94
95/// A stable-ish identity for this evaluator. Host name plus pid: enough to tell
96/// two nodes apart in a claim, and to recognise our own stale claim after a
97/// restart.
98fn default_node_id() -> String {
99 let host = std::env::var("HOSTNAME")
100 .or_else(|_| std::env::var("COMPUTERNAME"))
101 .unwrap_or_else(|_| "node".into());
102 format!("{host}/{}", std::process::id())
103}
104
105/// What one evaluation pass did. Shaped like `loop run`'s report for symmetry.
106#[derive(Debug, Clone, Default, Serialize)]
107pub struct EvalReport {
108 pub claimed: usize,
109 pub skipped_not_due: usize,
110 pub skipped_locked: usize,
111 pub skipped_paused: usize,
112 pub items: usize,
113 pub duplicates: usize,
114 pub runs_started: usize,
115 /// Items recorded without starting a workflow, because no runtime is wired
116 /// in. Counted apart from `runs_started` so the report never claims a run
117 /// happened when none did.
118 pub ingested: usize,
119 /// Items the connector returned that carry no usable identity, so no run
120 /// could be minted for them. Reported rather than silently dropped: an item
121 /// nobody can name is a connector bug, and it should be visible as one.
122 pub unidentifiable: usize,
123 /// Declarations that cannot fire as written — a cron that does not parse, a
124 /// timezone this build refuses, a composite gate naming a member the
125 /// declaration does not carry.
126 ///
127 /// Counted APART from `skipped_not_due` on purpose. Folded in there, an
128 /// unusable trigger is indistinguishable from a healthy one waiting its
129 /// turn, which is the failure mode with no symptom: the work simply never
130 /// happens and every report looks green. The reason lands in `errors`.
131 pub unusable: usize,
132 /// Not fatal to the pass: one broken trigger must not stop the others.
133 pub errors: Vec<String>,
134 /// A connector reported a backlog, so this trigger is due again at once
135 /// rather than after its interval.
136 pub draining: Vec<String>,
137 /// Triggers whose cursor was deliberately left unmoved this pass because
138 /// at least one item in the firing failed to start a run (#129) — the
139 /// Event add failed, declared context was unavailable, or the run
140 /// itself refused. The same page is offered again next tick; whatever
141 /// already started comes back as a `duplicates` count rather than
142 /// double-processing, which is what makes re-polling safe — see #128's
143 /// stable run ids, a prerequisite for this.
144 pub cursor_held: Vec<String>,
145}
146
147/// One trigger considered, for `--dry-run` and `status`.
148#[derive(Debug, Clone, Serialize)]
149pub struct TriggerStatus {
150 pub trigger: String,
151 /// The declaration's `name`, when it carries one.
152 ///
153 /// `name` is what a human uses to identify a trigger, and it is accepted
154 /// on write — but nothing read it back (#73), so identity fell onto the
155 /// workflow hash, which is stable only until the plan is re-declared. It
156 /// rides in `extra_fields` rather than being a typed field: OMS §A.7 has
157 /// no Trigger `name`, and inventing one would be a spec-level decision
158 /// for a label.
159 #[serde(skip_serializing_if = "Option::is_none")]
160 pub name: Option<String>,
161 pub kind: String,
162 pub workflow: String,
163 /// The connector's name, and — when its code is a grain (#185) — the
164 /// Definition that carries it.
165 ///
166 /// Reported because a reader looking at a heartbeat needs to know which of
167 /// the two connector kinds this is: the answer decides whether the code
168 /// travelled with the memory or lives on whichever machine happens to run
169 /// the pass, and that is the first question a stale-poll investigation
170 /// asks.
171 #[serde(skip_serializing_if = "Option::is_none")]
172 pub connector: Option<String>,
173 #[serde(skip_serializing_if = "Option::is_none")]
174 pub connector_tool: Option<String>,
175 pub enabled: bool,
176 pub paused: bool,
177 pub due: bool,
178 pub leased_by: Option<String>,
179 pub next_due_at: Option<i64>,
180 pub last_fired_at: Option<i64>,
181 pub consecutive_failures: u32,
182 pub last_error: Option<String>,
183 /// Will never fire again — a one-shot past its instant.
184 pub exhausted: bool,
185 /// Never fired and no failure recorded — the state an unnoticed
186 /// misconfiguration sits in, so it is reported rather than inferred.
187 pub never_fired: bool,
188 /// Why this declaration can never fire, if it cannot.
189 ///
190 /// A trigger can become unusable without ever being written through a
191 /// validating path — it can arrive by bundle import from an implementation
192 /// that validated differently, or predate the check. So the evaluator
193 /// reports it rather than assuming the write path caught everything.
194 #[serde(skip_serializing_if = "Option::is_none")]
195 pub unusable: Option<String>,
196 /// The connector's last reported position, for a trigger that has ever
197 /// polled. Opaque and connector-defined (#128) — surfaced so an operator
198 /// can SEE the state that a re-pointed trigger's evaluation carries
199 /// forward, which before this was invisible even though nothing else
200 /// could carry it by hand.
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub cursor: Option<String>,
203 /// The op-log position, a `memory` trigger's cursor equivalent.
204 #[serde(skip_serializing_if = "Option::is_none")]
205 pub op_cursor: Option<i64>,
206 /// The hash evaluation state is actually keyed under: `trg:<chain_root>`
207 /// (#128). Equal to `trigger` for a trigger that has never been
208 /// superseded — the common case, unchanged from before this field
209 /// existed. Differs only for a trigger re-pointed by `SUPERSEDE`, where
210 /// it names the ORIGINAL declaration's hash — the identity the cursor
211 /// and dedup fence actually survive under.
212 pub chain_root: String,
213}
214
215/// The declaration's human label, if it has one.
216///
217/// Written through `extra_fields` by every surface that accepts `name` on a
218/// trigger, and read back here so `list` and `status` can print it (#73).
219/// Blank is treated as absent: a name that renders as nothing is worse than
220/// none, because it displaces the hash a reader could otherwise have used.
221pub fn trigger_name(trigger: &Trigger) -> Option<String> {
222 trigger
223 .common
224 .extra_fields
225 .get("name")
226 .and_then(|v| v.as_str())
227 .map(str::trim)
228 .filter(|s| !s.is_empty())
229 .map(str::to_string)
230}
231
232/// Starts the workflow a trigger is bound to.
233///
234/// A seam rather than a direct `areev_run::Runner` call, for the same reason
235/// the CAL executor takes a governance host: the runtime sits above this crate
236/// in the dependency order for hosts that want it, and a test needs to observe
237/// what *would* be started without spending a real run. It is also where the
238/// duplicate rule lives, which is the whole idempotency story.
239pub trait RunStarter: Send + Sync {
240 fn start(&self, workflow: &str, run_id: &str, input: serde_json::Value) -> StartResult;
241}
242
243/// What starting a run did.
244#[derive(Debug, Clone, PartialEq)]
245pub enum StartResult {
246 Started,
247 /// A run with this id already exists. **Not an error** — it is the
248 /// idempotency guarantee working: this item was already handled, by an
249 /// earlier firing or by another node that won the race.
250 Duplicate,
251 Failed(String),
252}
253
254/// How this host runs a connector that is a **grain** rather than a command
255/// (#185).
256///
257/// Host config, never in the file, for exactly the reason `--allow-executor`
258/// is host config on the run path: a bundle carries the connector's code, so a
259/// permission arriving in the same bundle as the code it authorizes is not a
260/// permission. A trigger may name any Definition it likes; nothing runs unless
261/// this host pinned its address.
262///
263/// Absent (`None` on the evaluator) means a trigger naming a connector
264/// Definition refuses with `TRG-E012` — the same fail-closed shape as a due
265/// polling trigger with no `--connector-cmd`.
266#[derive(Debug, Clone, Default)]
267pub struct ConnectorCode {
268 /// Content addresses this host will execute — `--allow-executor`, the
269 /// same comma list and the same meaning the run path gives it.
270 pub allow: Vec<String>,
271 /// Where a pinned blob is materialized (`--executor-cache`).
272 pub cache_dir: Option<std::path::PathBuf>,
273 /// The `areev-sandbox` runner, argv-split by the executor. Required for a
274 /// `wasm32-areev`/`wasm32-areev-io` connector, which is the shape this
275 /// exists for; a native pinned blob runs without one.
276 pub sandbox_cmd: Option<String>,
277 /// Per-invocation wall-clock ceiling (`--executor-timeout`), in the run
278 /// path's tri-state: `None` leaves the executor's own default standing,
279 /// `Some(None)` waits forever on request, `Some(Some(d))` overrides.
280 pub timeout: Option<Option<std::time::Duration>>,
281 /// Environment policy for a NATIVE pinned blob. The sandbox clears its
282 /// environment regardless — see `CodeExecutor`.
283 pub env: Option<areev_core::proc::EnvPolicy>,
284 /// The memory's locator, so a connector declaring `{"blob": {"read":
285 /// true}}` can be served by the per-poll broker. The evaluator holds the
286 /// memory while a connector runs, and the broker's blob read deliberately
287 /// does not open it — it goes to the `.blobs` sidecar, or to one
288 /// short-lived Postgres connection of its own (#202).
289 pub db_locator: Option<String>,
290}
291
292/// A connector Definition resolved, pinned and read — everything
293/// `execute_code` needs, gathered before a broker is started so a refusal
294/// costs no side effects.
295struct PreparedConnector {
296 /// The Definition's own content address, which is what the trigger names.
297 tool_hash: String,
298 code: areev_run::PreparedCode,
299 /// True when the pinned declaration asks to read CAS blobs, which is what
300 /// decides whether the per-poll broker serves them.
301 wants_blobs: bool,
302 /// The Definition's `config` (#231) — the connector's WIRING, as opposed
303 /// to the trigger's `config`, which is the instance. A generic blob like
304 /// `rest.poll` is made provider-specific here, beside the `capabilities`
305 /// block it has to agree with, and travels with the code rather than
306 /// with each declaration that names it.
307 config: Option<serde_json::Value>,
308}
309
310/// The `config` a connector is handed: the Definition's wiring with the
311/// trigger's own keys laid over it.
312///
313/// Shallow, and the trigger wins — the more specific instance specializes the
314/// shared declaration, which is what lets two mailboxes share one Definition.
315/// Either side alone passes through untouched, so a connector that predates
316/// Definition config sees exactly what it saw before.
317fn merged_config(
318 definition: Option<&serde_json::Value>,
319 trigger: Option<&serde_json::Value>,
320) -> Option<serde_json::Value> {
321 match (definition, trigger) {
322 (None, t) => t.cloned(),
323 (Some(d), None) => Some(d.clone()),
324 (Some(d), Some(t)) => match (d.as_object(), t.as_object()) {
325 (Some(d), Some(t)) => {
326 let mut out = d.clone();
327 for (k, v) in t {
328 out.insert(k.clone(), v.clone());
329 }
330 Some(serde_json::Value::Object(out))
331 }
332 // Neither is an object: nothing to merge key-wise, and the
333 // instance is the more specific statement.
334 _ => Some(t.clone()),
335 },
336 }
337}
338
339/// `cas://sha256:<hex>` and a bare `<hex>` are the same pin, compared the way
340/// the executor compares them.
341fn normalize_address(uri: &str) -> String {
342 uri.trim()
343 .strip_prefix("cas://sha256:")
344 .unwrap_or_else(|| uri.trim())
345 .to_ascii_lowercase()
346}
347
348/// The inner executor a connector's [`areev_run::CodeExecutor`] wraps.
349///
350/// It is never reached: this path only ever calls `execute_code`, which
351/// dispatches the blob itself. It exists because `CodeExecutor` wraps
352/// something by construction, and what it wraps on the run path — the host's
353/// `--tool-cmd` — must NOT be silently reachable here. A connector that
354/// resolved to a command would be a different program than the declaration
355/// names.
356struct NoConnectorFallback;
357
358impl HostToolExecutor for NoConnectorFallback {
359 fn execute(
360 &self,
361 tool_name: &str,
362 _hash: &str,
363 _input: &serde_json::Value,
364 _idem: &str,
365 ) -> areev_run::ExecResult {
366 areev_run::ExecResult::Err {
367 cause: areev_run::FailCause::ExecutorError,
368 detail: format!(
369 "connector {tool_name:?} is declared as a grain, so it has no host command to \
370 fall back to"
371 ),
372 }
373 }
374}
375
376/// Evaluates triggers against one memory.
377pub struct Evaluator {
378 pub facade: Arc<AreevFacade>,
379 pub clock: Arc<dyn Clock>,
380 /// Executes connector commands. `None` means a due polling trigger fails
381 /// loudly with `TRG-E003` rather than quietly doing nothing — a poll that
382 /// silently returns no items is indistinguishable from a healthy source.
383 pub connector: Option<Arc<dyn HostToolExecutor>>,
384 /// How a connector that is a GRAIN runs (#185). `None` means this host
385 /// runs host-command connectors only, and a trigger naming a connector
386 /// Definition refuses with `TRG-E012` rather than falling back to
387 /// `--connector-cmd` — a fallback would run a different program than the
388 /// declaration names, which is the failure with no symptom the pin exists
389 /// to refuse.
390 pub connector_code: Option<ConnectorCode>,
391 /// Starts the bound workflow. `None` ingests the item and records the
392 /// firing without starting anything — what `--no-start` is for, and what
393 /// the ingest-only tests use.
394 pub starter: Option<Arc<dyn RunStarter>>,
395 /// Credentials the broker may attach, by name. Values live here and never
396 /// in a grain or a connector's environment: a declaration names a
397 /// credential, it never carries one.
398 /// A SOURCE per name, not a resolved value (#113): the heartbeat is the
399 /// path that most needs short-lived credentials, because it is the one
400 /// nobody is watching. An env-var source resolves once, as before; a
401 /// `cmd:`/`vault:` source is minted per TTL window inside the broker, so a
402 /// cadence that outlives a token's hour does not start 401'ing overnight.
403 pub credentials: std::collections::BTreeMap<String, areev_run::CredentialSource>,
404 pub ns: String,
405 pub principal: String,
406}
407
408impl Evaluator {
409 /// An evaluator that can inspect but not act: no connector, no runtime, no
410 /// credentials. What `list`, `show` and `status` want, and the shape that
411 /// makes "reading cannot fire anything" true by construction rather than by
412 /// remembering to pass `None` four times.
413 pub fn read_only(facade: Arc<AreevFacade>, clock: Arc<dyn Clock>, ns: &str) -> Evaluator {
414 Evaluator {
415 facade,
416 clock,
417 connector: None,
418 connector_code: None,
419 starter: None,
420 credentials: Default::default(),
421 ns: ns.to_string(),
422 principal: "user:local".into(),
423 }
424 }
425
426 /// Every trigger declaration in the memory, newest first.
427 pub fn declarations(&self) -> Result<Vec<(String, Trigger)>> {
428 let ns = self.ns.clone();
429 let grains = self
430 .facade
431 .with_store(|m| {
432 m.recent_live_scoped(&[ns], Some(GrainType::Trigger), MAX_TRIGGERS_SCANNED)
433 })
434 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
435
436 let mut out = Vec::new();
437 for g in grains {
438 let hash = g.hash.to_hex();
439 match g.to_trigger() {
440 Ok(mut t) => {
441 // `to_trigger` reconstructs the typed fields; `extra_fields`
442 // is not restored for any grain type, so the declaration's
443 // `name` — an extra field by design, since OMS §A.7 has no
444 // Trigger `name` — has to be carried over here. Doing it in
445 // the shared deserializer would silently change what every
446 // read-modify-write re-serializes, which is the kind of
447 // change that moves content addresses.
448 if let Some(name) = g.get_str("name") {
449 t.common
450 .extra_fields
451 .insert("name".into(), serde_json::json!(name));
452 }
453 out.push((hash, t))
454 }
455 // A declaration this build cannot read is reported, never
456 // skipped silently: silence is the symptom of every trigger
457 // failure, so it must never also be the symptom of a bug.
458 Err(e) => {
459 return Err(TriggerError::Malformed {
460 what: format!("declaration {hash} is unreadable: {e}"),
461 })
462 }
463 }
464 }
465 Ok(out)
466 }
467
468 /// What every trigger's state looks like right now.
469 pub fn status(&self) -> Result<Vec<TriggerStatus>> {
470 let now = self.clock.now_ms();
471 let mut out = Vec::new();
472 // One cache for this call, same as a `run()` pass — a chain is
473 // walked at most once even though `declarations()` above may list
474 // the same workflow's triggers repeatedly.
475 let mut chains: HashMap<String, Chain> = HashMap::new();
476 for (hash, t) in self.declarations()? {
477 let chain = self.resolve_chain(&hash, &mut chains)?;
478 // Read-only: `adopt = false`. `trigger status`/`show` must not
479 // have the side effect of migrating a legacy state row — a real
480 // evaluation pass (`run`/`deliver`) does that; this only
481 // reports whatever it finds, root row or legacy.
482 let (st, _raw) = self.resolve_state(&chain, false)?;
483 let unusable = schedule::validate(&t).err().map(|e| e.to_string());
484 out.push(TriggerStatus {
485 trigger: hash,
486 name: trigger_name(&t),
487 kind: t.kind.as_str().to_string(),
488 workflow: t.workflow.clone(),
489 connector: t.connector.clone(),
490 connector_tool: t.connector_tool.clone(),
491 enabled: t.enabled,
492 paused: st.paused,
493 // An unusable declaration is never due. Saying otherwise would
494 // promise a firing that cannot happen.
495 due: unusable.is_none()
496 && t.enabled
497 && !st.leased(now)
498 && schedule::is_due(&t, &st, now).unwrap_or(false),
499 leased_by: st.leased(now).then(|| st.claimed_by.clone()).flatten(),
500 next_due_at: st.next_due_at,
501 last_fired_at: st.last_fired_at,
502 consecutive_failures: st.consecutive_failures,
503 last_error: st.last_error.clone(),
504 exhausted: st.exhausted,
505 never_fired: st.last_fired_at.is_none() && st.consecutive_failures == 0,
506 unusable,
507 cursor: st.cursor.clone(),
508 op_cursor: st.op_cursor,
509 chain_root: chain.root().to_string(),
510 });
511 }
512 Ok(out)
513 }
514
515 /// Ingest a payload delivered by the host for a `webhook` or `manual`
516 /// trigger.
517 ///
518 /// Areev never opens a port. The host already terminates TLS and
519 /// authenticates the sender — it is far better at both than a memory engine
520 /// would be — and hands the payload to a one-shot invocation. That keeps the
521 /// useful half of webhooks without a listening daemon.
522 ///
523 /// Idempotent on the same terms as a poll: the payload's dedup value mints
524 /// the run id, so a webhook delivered twice (which every provider does)
525 /// produces one run and one recorded skip.
526 pub fn deliver(&self, trigger_hash: &str, payload: serde_json::Value) -> Result<EvalReport> {
527 let now = self.clock.now_ms();
528 let (hash, trigger) = self
529 .declarations()?
530 .into_iter()
531 .find(|(h, _)| h.starts_with(trigger_hash))
532 .ok_or_else(|| TriggerError::Malformed {
533 what: format!("no trigger matching '{trigger_hash}'"),
534 })?;
535
536 if !matches!(trigger.kind, TriggerKind::Webhook | TriggerKind::Manual) {
537 return Err(TriggerError::Malformed {
538 what: format!(
539 "trigger {} is a {} trigger — only webhook and manual triggers accept a \
540 delivery; a clocked or polling trigger fires from `trigger run`",
541 short(&hash, 12),
542 trigger.kind.as_str()
543 ),
544 });
545 }
546 if !trigger.enabled {
547 return Err(TriggerError::Malformed {
548 what: format!("trigger {} is disabled", short(&hash, 12)),
549 });
550 }
551 // #128 — a single-trigger cache: `deliver` fires exactly one
552 // trigger, so this walks its chain at most once regardless of how
553 // many places below need the root.
554 let mut chains: HashMap<String, Chain> = HashMap::new();
555 let chain = self.resolve_chain(&hash, &mut chains)?;
556 let (state, _raw) = self.resolve_state(&chain, true)?;
557 if state.paused {
558 return Err(TriggerError::Malformed {
559 what: format!("trigger {} is paused", short(&hash, 12)),
560 });
561 }
562
563 let mut report = EvalReport::default();
564 let item = PollItem { id: String::new(), payload, blobs: Vec::new() };
565 report.items = 1;
566 let Some(value) = dedup_value(&item, &trigger.dedup_key) else {
567 report.unidentifiable = 1;
568 // Journal before returning. A delivery naming nothing is precisely
569 // the case the record exists for: the sender's payload shape
570 // changed under us, and stdout of whatever invoked this is not an
571 // audit record -- the replicating Observation is.
572 self.journal(
573 &hash,
574 &trigger,
575 &FireOutcome { items: 1, unidentifiable: 1, ..Default::default() },
576 Some("delivered"),
577 now,
578 )?;
579 return Ok(report);
580 };
581 // Keyed on the chain ROOT (#128), so a delivery replayed after the
582 // trigger has been re-pointed by `SUPERSEDE` still mints the same id
583 // it always would have. `legacy_run_ids` covers a trigger already
584 // superseded before this fix — the id it would have minted under
585 // its old (then-current) head.
586 let root = chain.root();
587 let run_id = run_id_for(root, trigger.connector.as_deref(), &value);
588 let legacy_run_ids: Vec<String> = chain
589 .legacy()
590 .iter()
591 .map(|h| run_id_for(h, trigger.connector.as_deref(), &value))
592 .collect();
593 match self.start_run(&trigger, &run_id, &legacy_run_ids, &item, &hash, &[]) {
594 StartOutcome::Started => report.runs_started = 1,
595 StartOutcome::Ingested => report.ingested = 1,
596 StartOutcome::Duplicate => report.duplicates = 1,
597 StartOutcome::Failed(why) => report.errors.push(why),
598 }
599
600 let outcome = FireOutcome {
601 items: 1,
602 runs_started: report.runs_started,
603 duplicates: report.duplicates,
604 ..Default::default()
605 };
606 self.journal(&hash, &trigger, &outcome, Some("delivered"), now)?;
607 Ok(report)
608 }
609
610 /// Run one evaluation pass.
611 pub fn run(&self, opts: &EvalOptions) -> Result<EvalReport> {
612 let mut report = EvalReport::default();
613 let now = self.clock.now_ms();
614 // #128 — resolved once per trigger per PASS, never once per item:
615 // every chain walk below goes through this cache, shared with
616 // `record_for_composites` (a composite may be touched by several
617 // members firing in the same pass).
618 let mut chains: HashMap<String, Chain> = HashMap::new();
619
620 let declarations = self.declarations()?;
621 // Composites are settled after their members, so a gate can be
622 // satisfied in the same pass that completes it rather than waiting a
623 // whole heartbeat. Declaration order is newest-first and says nothing
624 // about dependency, so the split is explicit.
625 let (composites, members): (Vec<_>, Vec<_>) =
626 declarations.into_iter().partition(|(_, t)| t.kind == TriggerKind::Composite);
627
628 for (hash, trigger) in members.into_iter().chain(composites) {
629 if opts.only.as_ref().is_some_and(|only| only != &hash) {
630 continue;
631 }
632 if !trigger.enabled {
633 report.skipped_not_due += 1;
634 continue;
635 }
636 // Checked BEFORE dueness, so an unusable declaration is reported as
637 // what it is rather than disappearing into `not due` — where it
638 // looks exactly like a healthy trigger waiting its turn.
639 if let Err(why) = schedule::validate(&trigger) {
640 report.unusable += 1;
641 report.errors.push(format!("{}: {why}", short(&hash, 12)));
642 continue;
643 }
644 // #128 — every read/write of this trigger's evaluation state
645 // below is keyed on the chain ROOT, not on `hash` (the
646 // declaration's current head): a trigger re-pointed by
647 // `SUPERSEDE` mints a new head for the same standing rule, and
648 // keying state on the head alone would orphan the cursor and
649 // the dedup fence on every applied recommendation. For a
650 // never-superseded trigger root == hash, so this resolves to
651 // exactly the lookup this crate always did — a byte-identical
652 // no-op (pinned by `a_never_superseded_trigger_keys_state_on_its_own_hash`).
653 // `adopt = true`: this is a real evaluation pass with write
654 // access, so a legacy (pre-#128, head-keyed) row found along the
655 // way is migrated under the root.
656 let chain = self.resolve_chain(&hash, &mut chains)?;
657 let (state, raw) = self.resolve_state(&chain, true)?;
658
659 if state.paused {
660 report.skipped_paused += 1;
661 continue;
662 }
663 // An absolute schedule seen for the first time: record when it
664 // will be due rather than re-deriving it every pass, so `trigger
665 // status` can say when it next fires and the comparison afterwards
666 // is a plain timestamp check.
667 if state.next_due_at.is_none() && !state.exhausted {
668 if let Some(first) = schedule::initial_due(&trigger, now)? {
669 let mut seeded = state.clone();
670 seeded.next_due_at = Some(first);
671 let _ = self
672 .facade
673 .with_store(|m| m.put_trigger_state(chain.root(), raw.as_deref(), &seeded))
674 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
675 report.skipped_not_due += 1;
676 continue;
677 }
678 }
679 if !schedule::is_due(&trigger, &state, now)? {
680 report.skipped_not_due += 1;
681 continue;
682 }
683 if state.leased(now) {
684 // The normal steady state with several nodes on one heartbeat,
685 // not a problem.
686 report.skipped_locked += 1;
687 continue;
688 }
689 if opts.dry_run {
690 report.claimed += 1;
691 continue;
692 }
693
694 match self.fire(&hash, &chain, &trigger, state, raw.as_deref(), now, opts) {
695 // Lost the claim between deciding it was free and taking it.
696 // Normal with several nodes on one heartbeat, and it must not
697 // be counted as work done.
698 Ok(outcome) if outcome.skipped_locked => report.skipped_locked += 1,
699 Ok(outcome) => {
700 if !outcome.fired_items.is_empty() {
701 if let Err(e) =
702 self.record_for_composites(&hash, &outcome.fired_items, now, &mut chains)
703 {
704 report.errors.push(e.to_string());
705 }
706 }
707 report.claimed += 1;
708 report.items += outcome.items;
709 report.duplicates += outcome.duplicates;
710 report.runs_started += outcome.runs_started;
711 report.ingested += outcome.ingested;
712 report.unidentifiable += outcome.unidentifiable;
713 for why in &outcome.failures {
714 report.errors.push(format!("{hash}: {why}"));
715 }
716 // #129 — any start failure in this firing means the
717 // cursor was deliberately left unmoved (see `fire`'s
718 // release logic); surfaced apart from `errors` so an
719 // operator sees WHY the same items come back next tick
720 // rather than inferring it.
721 if !outcome.failures.is_empty() {
722 report.cursor_held.push(hash.clone());
723 }
724 if outcome.draining {
725 report.draining.push(hash.clone());
726 }
727 }
728 Err(e) => {
729 // One broken trigger must not stop the others.
730 report.errors.push(e.to_string());
731 }
732 }
733 }
734 Ok(report)
735 }
736
737 // `chain` (#128) is one more independent knob on an already knob-heavy
738 // internal call, in the same spirit as the other `too_many_arguments`
739 // allows in this codebase (areev-store's tuned-recall internals, the
740 // bindings' flat FFI surfaces) — splitting it into a struct would not
741 // make any single call site more readable.
742 #[allow(clippy::too_many_arguments)]
743 fn fire(
744 &self,
745 hash: &str,
746 chain: &Chain,
747 trigger: &Trigger,
748 state: TriggerState,
749 raw: Option<&str>,
750 now: i64,
751 opts: &EvalOptions,
752 ) -> Result<FireOutcome> {
753 // #128 — the claim/release CAS below is keyed on the chain ROOT, not
754 // `hash`. This is the hazard the fix has to get right: `fire` claims
755 // with one key and releases with the same key, so if the two ever
756 // disagreed about which key that is, the release's compare-and-swap
757 // would find no row, `released_ok` would be false, and every firing
758 // of a superseded trigger would permanently report `ClaimLost` — a
759 // trigger that could never usefully claim again. `root` is resolved
760 // exactly once here and reused for every claim/release call in this
761 // function.
762 let root = chain.root();
763
764 // Claim. Losing means another evaluator got here first.
765 let mut claimed = state.clone();
766 claimed.fence = claimed.fence.wrapping_add(1);
767 claimed.claimed_by = Some(opts.node.clone());
768 claimed.lease_until = Some(now + opts.lease.as_millis() as i64);
769 let won = self
770 .facade
771 .with_store(|m| m.put_trigger_state(root, raw, &claimed))
772 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
773 if !won {
774 return Ok(FireOutcome { skipped_locked: true, ..Default::default() });
775 }
776 // What a later release must present as `expected`.
777 let claimed_raw = self
778 .facade
779 .with_store(|m| m.trigger_state(root))
780 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
781 .map(|(_, r)| r);
782
783 let result = self.collect_and_start(hash, chain, trigger, &claimed, now, opts);
784
785 // Release under the fence, whatever happened.
786 let mut released = claimed.clone();
787 released.claimed_by = None;
788 released.lease_until = None;
789 match &result {
790 // Full success: every item that resolved an identity started (or
791 // was ingested, or was recognized as a duplicate) cleanly.
792 Ok(outcome) if outcome.failures.is_empty() => {
793 released.last_fired_at = Some(now);
794 released.consecutive_failures = 0;
795 released.last_error = None;
796 if let Some(c) = &outcome.cursor {
797 released.cursor = Some(c.clone());
798 }
799 if let Some(c) = outcome.op_cursor {
800 released.op_cursor = Some(c);
801 }
802 // A satisfied gate consumes its correlation key. Leaving it
803 // would re-fire the same set on every pass; Flink calls this
804 // the after-match skip strategy, and the conservative choice —
805 // clear only the key that fired — is the one that cannot
806 // swallow an unrelated in-flight match.
807 for k in &outcome.settled_keys {
808 released.partials.remove(k);
809 }
810 prune_partials(&mut released, trigger, now);
811 released.exhausted = schedule::exhausts_after(trigger, now);
812 released.next_due_at = if outcome.draining {
813 // A backlog drains at once rather than waiting out the
814 // interval — a cold start should not take a day.
815 Some(now)
816 } else {
817 schedule::advance_after_firing(trigger, now, now)?
818 };
819 }
820 // #129 — at least one item failed to start a run: the Event add
821 // failed, declared context was unavailable, or the run itself
822 // refused (RUN-E018 and friends). All three mean the item was
823 // NOT processed, so this firing must not report itself clean —
824 // that is the opposite posture from the Err arm below, which
825 // this deliberately mirrors:
826 // - the cursor / op_cursor are left at `claimed`'s values
827 // (never assigned from `outcome`), so the next pass re-asks
828 // the connector for the same page instead of skipping past
829 // unprocessed work;
830 // - `exhausted` is left at `claimed.exhausted` (false, since a
831 // due trigger cannot already be exhausted) rather than
832 // recomputed — a `once` trigger that fails must be allowed
833 // to retry, not be marked as having had its one shot;
834 // - `settled_keys` are NOT removed from `partials` — a
835 // satisfied composite gate whose run refused must stay
836 // satisfied so it retries, not lose its correlation.
837 // Re-polling the same page is safe BECAUSE run ids are keyed on
838 // the chain root (#128): whatever already started is protected
839 // by `start_run`'s dedup fence and comes back as `Duplicate`,
840 // never a second run. What DID happen is still real —
841 // `runs_started`/`ingested`/`duplicates` in the outcome are not
842 // discarded, only the durable cursor advance is withheld.
843 Ok(outcome) => {
844 released.last_fired_at = Some(now);
845 released.consecutive_failures = claimed.consecutive_failures.saturating_add(1);
846 released.last_error = Some(summarize_failures(&outcome.failures));
847 released.next_due_at =
848 Some(schedule::backoff_until(trigger, released.consecutive_failures, now));
849 }
850 Err(e) => {
851 released.consecutive_failures = claimed.consecutive_failures.saturating_add(1);
852 released.last_error = Some(e.to_string());
853 released.next_due_at =
854 Some(schedule::backoff_until(trigger, released.consecutive_failures, now));
855 }
856 }
857 let released_ok = self
858 .facade
859 .with_store(|m| m.put_trigger_state(root, claimed_raw.as_deref(), &released))
860 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
861 if !released_ok {
862 // Our lease expired mid-firing and someone else took over. Their
863 // state stands; ours is refused. The work we did is not lost — the
864 // runs we started are journaled and idempotent — but we must not
865 // write back over the new owner.
866 self.journal(hash, trigger, &FireOutcome::default(), Some("claim lost"), now)?;
867 return Err(TriggerError::ClaimLost { trigger: hash.to_string() });
868 }
869
870 let outcome = result?;
871 self.journal(hash, trigger, &outcome, None, now)?;
872 Ok(outcome)
873 }
874
875 /// Get the items for this firing and start a run per item.
876 fn collect_and_start(
877 &self,
878 hash: &str,
879 chain: &Chain,
880 trigger: &Trigger,
881 state: &TriggerState,
882 now: i64,
883 opts: &EvalOptions,
884 ) -> Result<FireOutcome> {
885 let mut outcome = FireOutcome::default();
886
887 let items: Vec<PollItem> = match trigger.kind {
888 TriggerKind::Polling => {
889 let response = self.poll(hash, trigger, state, opts)?;
890 outcome.cursor = response.cursor.clone();
891 outcome.draining = response.more;
892 // First contact seeds the cursor and fires nothing. Otherwise
893 // declaring a mailbox trigger starts a run for every message in
894 // history — Zapier's priming poll, and for the same reason.
895 if state.cursor.is_none() {
896 outcome.seeded = true;
897 return Ok(outcome);
898 }
899 response.items
900 }
901 // A clocked trigger with no external source fires once per
902 // occurrence, carrying the occurrence itself as the item.
903 TriggerKind::Interval | TriggerKind::Schedule | TriggerKind::Once => {
904 vec![PollItem {
905 id: now.to_string(),
906 payload: serde_json::json!({ "at_ms": now }),
907 blobs: Vec::new(),
908 }]
909 }
910 TriggerKind::Memory => {
911 // Recorded so the journal says "seeded" rather than leaving a
912 // firing that produced nothing looking like a quiet memory.
913 outcome.seeded = state.op_cursor.is_none();
914 let (found, cursor) = self.scan_memory(hash, trigger, state, opts)?;
915 outcome.op_cursor = Some(cursor);
916 found
917 }
918 TriggerKind::Composite => {
919 let keys = self.satisfied_keys(hash, chain, trigger, now)?;
920 outcome.settled_keys = keys.clone();
921 keys.into_iter()
922 .map(|k| PollItem {
923 // The correlation value IS the identity: one firing per
924 // correlated set, however many members contributed.
925 id: k.clone(),
926 payload: serde_json::json!({ "correlation": k }),
927 blobs: Vec::new(),
928 })
929 .collect()
930 }
931 // These do not poll. The host owns the listener and hands the
932 // payload to `deliver`, which fires them on the same idempotency
933 // terms; an evaluation pass simply has nothing to do for one.
934 TriggerKind::Webhook | TriggerKind::Manual => Vec::new(),
935 };
936
937 // #93 — store connector blobs in the CAS and rewrite `"blob": "@N"`
938 // payload references to their addresses BEFORE identity resolution,
939 // so a `--dedup-key` pointer into a rewritten field sees the stable
940 // content address rather than a positional index. A contract
941 // violation fails the whole poll here (TRG-E011): fire() then leaves
942 // the cursor unmoved, so nothing is lost — the connector gets fixed
943 // and the same page is re-polled.
944 let mut items = items;
945 let item_refs = self.ingest_item_blobs(hash, &mut items, opts)?;
946
947 outcome.items = items.len();
948 for (item, refs) in items.into_iter().zip(item_refs) {
949 let Some(value) = dedup_value(&item, &trigger.dedup_key) else {
950 outcome.unidentifiable += 1;
951 continue;
952 };
953 outcome.fired_items.push(item.payload.clone());
954 // Keyed on the chain ROOT (#128): the same item seen again after
955 // this trigger has been re-pointed by `SUPERSEDE` still mints
956 // the id it always would have, so `start_run`'s dedup fence
957 // still recognizes it. `legacy_run_ids` is the compatibility
958 // path for a trigger already superseded BEFORE this fix — the
959 // id(s) it would have minted under an older head — and is empty
960 // (so free) for the common never-superseded case.
961 let root = chain.root();
962 let run_id = run_id_for(root, trigger.connector.as_deref(), &value);
963 let legacy_run_ids: Vec<String> = chain
964 .legacy()
965 .iter()
966 .map(|h| run_id_for(h, trigger.connector.as_deref(), &value))
967 .collect();
968 match self.start_run(trigger, &run_id, &legacy_run_ids, &item, hash, &refs) {
969 StartOutcome::Started => outcome.runs_started += 1,
970 StartOutcome::Ingested => outcome.ingested += 1,
971 StartOutcome::Duplicate => outcome.duplicates += 1,
972 StartOutcome::Failed(why) => outcome.failures.push(why),
973 }
974 }
975 Ok(outcome)
976 }
977
978 /// Note a member firing against every composite that declares it.
979 ///
980 /// The correlation value comes from the composite's own `correlate`
981 /// pointer applied to the member's item — so two composites may correlate
982 /// the same member on different fields, which is why this is resolved per
983 /// composite rather than once per member.
984 fn record_for_composites(
985 &self,
986 member: &str,
987 items: &[serde_json::Value],
988 now: i64,
989 chains: &mut HashMap<String, Chain>,
990 ) -> Result<()> {
991 for (chash, composite) in self.declarations()? {
992 let Some(alias) = composite.member_alias(member).map(str::to_string) else {
993 continue;
994 };
995 if composite.kind != TriggerKind::Composite {
996 continue;
997 }
998 // #128 — the composite's OWN chain, not the member's: state
999 // lives under the composite's root regardless of which member
1000 // just fired. Shares the pass-wide cache, so a composite with
1001 // several members touched this pass walks its chain once.
1002 let chain = self.resolve_chain(&chash, chains)?;
1003 let (mut state, raw) = self.resolve_state(&chain, true)?;
1004
1005 for item in items {
1006 // No correlate pointer means one global match — every member
1007 // firing counts toward the same gate.
1008 let key = match &composite.correlate {
1009 Some(ptr) => match item.pointer(ptr) {
1010 Some(serde_json::Value::String(s)) => s.clone(),
1011 Some(other) => other.to_string(),
1012 // An item that cannot be correlated cannot join a
1013 // correlated gate. Dropping it is right: attributing it
1014 // to an arbitrary key would pair unrelated work.
1015 None => continue,
1016 },
1017 None => String::new(),
1018 };
1019 let entry = state.partials.entry(key).or_insert_with(|| {
1020 areev_store::PartialMatch { members: Default::default(), started_ms: now }
1021 });
1022 // Recorded under the ALIAS, because that is what the gate
1023 // expression names.
1024 entry.members.insert(alias.clone(), now);
1025 }
1026 prune_partials(&mut state, &composite, now);
1027 self.facade
1028 .with_store(|m| m.put_trigger_state(chain.root(), raw.as_deref(), &state))
1029 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
1030 }
1031 Ok(())
1032 }
1033
1034 /// Which correlation keys currently satisfy this composite's gate.
1035 fn satisfied_keys(
1036 &self,
1037 hash: &str,
1038 chain: &Chain,
1039 trigger: &Trigger,
1040 now: i64,
1041 ) -> Result<Vec<String>> {
1042 let predicate = trigger
1043 .predicate
1044 .as_ref()
1045 .ok_or_else(|| TriggerError::Malformed {
1046 what: format!("composite trigger {hash} has no predicate"),
1047 })
1048 .and_then(crate::predicate::from_value)?;
1049
1050 // Refuse a gate that names a member the declaration does not carry: it
1051 // could never be satisfied, so the trigger would be silently dead.
1052 for referenced in crate::predicate::referenced_members(&predicate) {
1053 if !trigger.members.contains_key(&referenced) {
1054 return Err(TriggerError::UnknownMember {
1055 trigger: hash.to_string(),
1056 member: referenced,
1057 });
1058 }
1059 }
1060
1061 // #128 — this composite's own partials live under its chain root.
1062 // No adoption dance needed here: by the time `fire` reaches
1063 // `collect_and_start` for this trigger, `run()`'s loop has already
1064 // resolved (and, if needed, adopted) this exact root's state row.
1065 let (state, _) = self
1066 .facade
1067 .with_store(|m| m.trigger_state(chain.root()))
1068 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
1069 .unwrap_or_default();
1070
1071 let mut out = Vec::new();
1072 for (key, partial) in &state.partials {
1073 if let Some(w) = trigger.window_ms {
1074 if now - partial.started_ms > w {
1075 continue;
1076 }
1077 }
1078 let fired: Vec<String> = partial.members.keys().cloned().collect();
1079 if crate::predicate::gate_satisfied(&predicate, &fired) {
1080 out.push(key.clone());
1081 }
1082 }
1083 Ok(out)
1084 }
1085
1086 /// Grains matching the predicate that appeared since the stored op cursor.
1087 ///
1088 /// Built on the op-log rather than a scan: `changes_since` is an indexed
1089 /// primary-key range read with a monotonic exclusive cursor, so cost is
1090 /// proportional to what changed rather than to how much the memory holds.
1091 ///
1092 /// Considered and rejected: `PRAGMA data_version` as a cheap "did anything
1093 /// change" pre-check. It is documented as unchanged for commits made on the
1094 /// same connection — and Areev is single-writer with one connection, so our
1095 /// own writes are exactly what it cannot see.
1096 fn scan_memory(
1097 &self,
1098 hash: &str,
1099 trigger: &Trigger,
1100 state: &TriggerState,
1101 opts: &EvalOptions,
1102 ) -> Result<(Vec<PollItem>, i64)> {
1103 let predicate = trigger
1104 .predicate
1105 .as_ref()
1106 .ok_or_else(|| TriggerError::Malformed {
1107 what: format!("memory trigger {hash} has no predicate"),
1108 })
1109 .and_then(crate::predicate::from_value)?;
1110
1111 // First contact seeds at the head of the log and matches nothing.
1112 // Otherwise declaring a memory trigger on an established memory fires
1113 // once for every historical grain that matches — the same reason a
1114 // polling trigger primes rather than replaying a mailbox.
1115 let Some(after) = state.op_cursor else {
1116 let head = self
1117 .facade
1118 .with_store(|m| m.head_op_seq())
1119 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
1120 return Ok((Vec::new(), head));
1121 };
1122 let ops = self
1123 .facade
1124 .with_store(|m| m.changes_since(after, opts.max_items))
1125 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
1126
1127 let mut items = Vec::new();
1128 let mut cursor = after;
1129 for op in ops {
1130 cursor = cursor.max(op.op_seq);
1131 // Additions and supersessions both mean "this is true now".
1132 // A tombstone means the grain is gone, so there is nothing to match.
1133 if op.op == areev_store::OP_FORGET {
1134 continue;
1135 }
1136 let Ok(grain) = self.facade.with_store(|m| m.get(&op.hash)) else {
1137 // A grain that vanished between the op-log read and the fetch
1138 // (erasure, retention) is not an error — it simply no longer
1139 // matches anything.
1140 continue;
1141 };
1142 if !crate::predicate::grain_matches(&grain, &predicate) {
1143 continue;
1144 }
1145 let hex = op.hash.to_hex();
1146 items.push(PollItem {
1147 // The content address IS the identity: the same grain can never
1148 // fire twice, and two evaluators seeing it agree without
1149 // coordinating.
1150 id: hex.clone(),
1151 payload: serde_json::json!({
1152 "hash": hex,
1153 "grain_type": grain.grain_type.as_str(),
1154 "op_seq": op.op_seq,
1155 }),
1156 blobs: Vec::new(),
1157 });
1158 }
1159 Ok((items, cursor))
1160 }
1161
1162 /// Store an item's connector blobs in the CAS and rewrite payload
1163 /// references (#93). Returns one `ContentRef` list per item, parallel
1164 /// to `items`. Any contract violation — undecodable base64, a budget
1165 /// overrun, a dangling `"@N"` — refuses the WHOLE poll with TRG-E011,
1166 /// so the cursor stays put and nothing is silently dropped. `put_blob`
1167 /// is idempotent on content, so a re-polled page costs only the
1168 /// transfer.
1169 fn ingest_item_blobs(
1170 &self,
1171 hash: &str,
1172 items: &mut [PollItem],
1173 opts: &EvalOptions,
1174 ) -> Result<Vec<Vec<ContentRef>>> {
1175 let violation = |detail: String| TriggerError::BlobContract {
1176 trigger: short(hash, 12).to_string(),
1177 detail,
1178 };
1179 let mut response_total = 0usize;
1180 let mut all_refs = Vec::with_capacity(items.len());
1181 for (idx, item) in items.iter_mut().enumerate() {
1182 if item.blobs.is_empty() {
1183 all_refs.push(Vec::new());
1184 continue;
1185 }
1186 let mut item_total = 0usize;
1187 let mut refs = Vec::with_capacity(item.blobs.len());
1188 let mut uris = Vec::with_capacity(item.blobs.len());
1189 for (bi, blob) in item.blobs.iter().enumerate() {
1190 let name = blob.filename.as_deref().unwrap_or("unnamed");
1191 let bytes = areev_core::b64::decode(&blob.b64).ok_or_else(|| {
1192 violation(format!("item {idx} blob {bi} ({name}) is not valid base64"))
1193 })?;
1194 item_total += bytes.len();
1195 response_total += bytes.len();
1196 if item_total > opts.max_blob_bytes_per_item {
1197 return Err(violation(format!(
1198 "item {idx} blobs exceed the per-item budget ({} bytes decoded)",
1199 opts.max_blob_bytes_per_item
1200 )));
1201 }
1202 if response_total > opts.max_blob_bytes_per_response {
1203 return Err(violation(format!(
1204 "response blobs exceed the per-response budget ({} bytes decoded)",
1205 opts.max_blob_bytes_per_response
1206 )));
1207 }
1208 let uri = self
1209 .facade
1210 .with_store(|m| m.put_blob(&bytes))
1211 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
1212 refs.push(ContentRef {
1213 uri: uri.clone(),
1214 modality: None,
1215 mime_type: blob.mime.clone(),
1216 size_bytes: Some(bytes.len() as u64),
1217 checksum: Some(uri.trim_start_matches("cas://").to_string()),
1218 metadata: blob.filename.as_ref().map(|f| serde_json::json!({ "filename": f })),
1219 });
1220 uris.push(uri);
1221 }
1222 rewrite_blob_refs(&mut item.payload, &uris)
1223 .map_err(|d| violation(format!("item {idx}: {d}")))?;
1224 // The bytes are in the CAS now; drop the base64 so nothing
1225 // downstream can re-inline it into the Event or the run input.
1226 item.blobs.clear();
1227 all_refs.push(refs);
1228 }
1229 Ok(all_refs)
1230 }
1231
1232 /// Resolve a trigger's `connector_tool` into something executable, or
1233 /// `None` when the trigger names no connector grain and the host command
1234 /// polls as before.
1235 ///
1236 /// Every refusal here happens before the poll has spent anything, and each
1237 /// one names the flag that fixes it — a heartbeat is the surface where a
1238 /// vague failure costs the most, because nobody is reading it.
1239 fn prepare_connector(
1240 &self,
1241 hash: &str,
1242 trigger: &Trigger,
1243 connector_name: &str,
1244 ) -> Result<Option<PreparedConnector>> {
1245 let Some(reference) = trigger
1246 .connector_tool
1247 .as_deref()
1248 .map(str::trim)
1249 .filter(|r| !r.is_empty())
1250 else {
1251 return Ok(None);
1252 };
1253 let refuse = |detail: String| TriggerError::ConnectorCode {
1254 trigger: hash.to_string(),
1255 detail,
1256 };
1257 let Some(cfg) = self.connector_code.as_ref() else {
1258 return Err(refuse(format!(
1259 "connector {connector_name:?} is a grain ({reference}) but this host runs no \
1260 code-carrying connectors — pass --allow-executor <address> (and --sandbox-cmd \
1261 for a wasm module)"
1262 )));
1263 };
1264 let hex = areev_core::types::strip_grain_scheme(reference);
1265 let h = Hash::from_hex(hex).map_err(|e| {
1266 refuse(format!("connector_tool {reference:?} is not a content address: {e}"))
1267 })?;
1268 let g = self
1269 .facade
1270 .with_store(|m| m.get(&h))
1271 .map_err(|e| refuse(format!("connector Definition {hex} is unreadable: {e}")))?;
1272 if g.grain_type != GrainType::Tool {
1273 return Err(refuse(format!(
1274 "connector_tool {hex} is a {:?} grain, not a Tool Definition",
1275 g.grain_type
1276 )));
1277 }
1278 // ONE reader of a Definition's executable shape, shared with
1279 // `RunManifest::resolve`: a connector that ran under different rules
1280 // than a node binding the same grain would be a second implementation
1281 // of the pin, the runtime table and the capability check — and the one
1282 // that drifts is this one, because nobody is watching a poll.
1283 let pin = areev_run::pin_from_definition(connector_name, &h, &g)
1284 .map_err(|e| refuse(e.to_string()))?;
1285 let Some(uri) = pin.executor_uri.clone() else {
1286 return Err(refuse(format!(
1287 "connector Definition {hex} names no executor_uri — a connector grain IS its \
1288 code, so there is nothing to run"
1289 )));
1290 };
1291 // The host pin, checked here so the refusal can name the address to
1292 // copy. `execute_code` checks it again on the way in; that one is the
1293 // guarantee, this one is the error message.
1294 let addr = normalize_address(&uri);
1295 if !cfg.allow.iter().any(|a| normalize_address(a) == addr) {
1296 return Err(refuse(format!(
1297 "connector {connector_name:?} names {uri}, which this host did not pin — \
1298 add --allow-executor {addr}"
1299 )));
1300 }
1301 if pin.runtime.as_deref().is_some_and(areev_run::is_sandbox_runtime)
1302 && cfg.sandbox_cmd.is_none()
1303 {
1304 return Err(refuse(format!(
1305 "connector {connector_name:?} declares runtime {:?}, which needs the sandbox — \
1306 pass --sandbox-cmd areev-sandbox",
1307 pin.runtime.as_deref().unwrap_or_default()
1308 )));
1309 }
1310 // `get_blob` verifies the digest on every read, so these bytes ARE the
1311 // address the trigger named.
1312 let bytes = self
1313 .facade
1314 .with_store(|m| m.get_blob(&uri))
1315 .map_err(|e| refuse(format!("connector blob {uri} is unreadable: {e}")))?;
1316 let wants_blobs = pin
1317 .capabilities
1318 .as_ref()
1319 .and_then(|v| areev_run::Declaration::parse(v).ok())
1320 .is_some_and(|d| d.declares_blob_read());
1321 let config = g.fields.get("config").filter(|v| !v.is_null()).cloned();
1322 Ok(Some(PreparedConnector {
1323 tool_hash: h.to_hex(),
1324 code: areev_run::PreparedCode {
1325 uri,
1326 bytes,
1327 runtime: pin.runtime,
1328 limits: pin.runtime_limits,
1329 capabilities: pin.capabilities,
1330 },
1331 wants_blobs,
1332 config,
1333 }))
1334 }
1335
1336 /// The executor a grain connector runs under, bound to THIS poll's broker.
1337 ///
1338 /// Built per poll rather than once on the evaluator because the broker is
1339 /// per poll: it is started with the trigger's own allowlist and stops when
1340 /// the call returns, and a handle to a broker that has stopped would hand
1341 /// the module a dead token.
1342 fn code_executor(&self, broker: &Arc<areev_run::Broker>) -> areev_run::CodeExecutor {
1343 let cfg = self.connector_code.clone().unwrap_or_default();
1344 let mut ce = areev_run::CodeExecutor::new(Arc::new(NoConnectorFallback));
1345 for addr in &cfg.allow {
1346 ce = ce.allow(addr);
1347 }
1348 if let Some(dir) = cfg.cache_dir {
1349 ce = ce.cache_dir(dir);
1350 }
1351 if let Some(cmd) = cfg.sandbox_cmd.as_deref() {
1352 ce = ce.sandbox_cmd(cmd);
1353 }
1354 if let Some(t) = cfg.timeout {
1355 ce = ce.with_timeout(t);
1356 }
1357 if let Some(env) = cfg.env {
1358 ce = ce.with_env_policy(env);
1359 }
1360 ce.with_egress(areev_run::EgressHandle::new(Arc::clone(broker)))
1361 }
1362
1363 fn poll(
1364 &self,
1365 hash: &str,
1366 trigger: &Trigger,
1367 state: &TriggerState,
1368 opts: &EvalOptions,
1369 ) -> Result<PollResponse> {
1370 let connector_name = trigger.connector.as_deref().unwrap_or_default();
1371 // A connector named by content address (#185) is resolved, pinned and
1372 // read BEFORE a broker starts: a Definition this host did not pin must
1373 // refuse having spent nothing — no port, no token, no upstream call.
1374 let prepared = self.prepare_connector(hash, trigger, connector_name)?;
1375 if prepared.is_none() && self.connector.is_none() {
1376 return Err(TriggerError::NoConnector {
1377 trigger: hash.to_string(),
1378 connector: connector_name.to_string(),
1379 });
1380 }
1381 // Start a broker for this call, scoped to this trigger's allowlist. The
1382 // connector is handed its URL — never a token — so a compromised
1383 // connector has nothing to exfiltrate and nowhere undeclared to send
1384 // it. The broker stops when this call returns.
1385 let policy = areev_run::EgressPolicy::from_config(trigger.config.as_ref())
1386 .map_err(|what| TriggerError::Malformed { what })?;
1387 // One connector runs per pass, so there is no second caller to tell it
1388 // apart from: a default grant covers it. Its methods are whatever the
1389 // connector needs to poll, and the credentials are the ones this host
1390 // configured — naming one it was not given still fails.
1391 let grant = self.credentials.keys().fold(
1392 areev_run::CallerGrant::new()
1393 .method("GET")
1394 .method("POST")
1395 .method("PUT")
1396 .method("PATCH")
1397 .method("DELETE"),
1398 |g, name| g.credential(name),
1399 );
1400 // The same grant twice, under two names, because the broker
1401 // identifies a caller by the TOKEN it presents: the default token maps
1402 // to no caller at all, and a capability declaration is registered
1403 // under a name (#185). A grain connector declares
1404 // `{"blob": {"read": true}}` as tool `<connector>`, so it needs a
1405 // token that resolves back to `<connector>` — otherwise its own
1406 // declaration is invisible to the check that reads it, and every blob
1407 // read is refused as undeclared. The default stays for the subprocess
1408 // connector, which presents a token and names nothing.
1409 let grants = areev_run::EgressGrants::new()
1410 .default_for_all(grant.clone())
1411 .grant(connector_name, grant);
1412 let broker = Arc::new(
1413 areev_run::Broker::start(policy, self.credentials.clone(), grants, "TRG-E009")
1414 .map_err(|detail| TriggerError::Storage { detail })?,
1415 );
1416 // A connector module that declared `{"blob": {"read": true}}` reads
1417 // the memory's stored bytes through this same broker on the same
1418 // token (#106) — the attachment an earlier poll filed, by address.
1419 // The read never opens the memory, which is what makes it safe while
1420 // the evaluator holds it.
1421 if prepared.as_ref().is_some_and(|p| p.wants_blobs) {
1422 let locator = self
1423 .connector_code
1424 .as_ref()
1425 .and_then(|c| c.db_locator.as_deref())
1426 .ok_or_else(|| TriggerError::ConnectorCode {
1427 trigger: hash.to_string(),
1428 detail: format!(
1429 "connector {connector_name:?} declares {{\"blob\": {{\"read\": true}}}} \
1430 but this host wired the evaluator no memory locator, so the broker \
1431 cannot serve a blob read"
1432 ),
1433 })?;
1434 broker.serve_blobs(locator);
1435 }
1436
1437 let config = merged_config(
1438 prepared.as_ref().and_then(|p| p.config.as_ref()),
1439 trigger.config.as_ref(),
1440 );
1441 let request = PollRequest {
1442 trigger: hash,
1443 connector: connector_name,
1444 scope: trigger.scope.as_deref(),
1445 cursor: state.cursor.as_deref(),
1446 max_items: opts.max_items,
1447 config: config.as_ref(),
1448 };
1449 let payload = serde_json::to_value(&request).map_err(|e| TriggerError::ConnectorFailed {
1450 trigger: hash.to_string(),
1451 detail: format!("serialize request: {e}"),
1452 })?;
1453 // The idempotency key ties this call to this occurrence, so a connector
1454 // that deduplicates on it sees a retry as a retry.
1455 let idem = format!("{hash}:{}", state.fence);
1456 static EGRESS_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
1457 let result = match &prepared {
1458 // The connector is a grain: the pinned blob runs under the same
1459 // `CodeExecutor` the run path uses, so the sandbox argv, the
1460 // capability registration, the per-call broker handshake and the
1461 // cleared environment are ONE implementation rather than a second
1462 // one that drifts. It takes its broker token per call rather than
1463 // through the process environment, so the mutex below is not its
1464 // hazard to hold.
1465 Some(p) => self.code_executor(&broker).execute_code(
1466 connector_name,
1467 &p.tool_hash,
1468 &p.code,
1469 &payload,
1470 &idem,
1471 ),
1472 // The connector reads AREEV_EGRESS_URL out of its environment. The
1473 // spawn seam scrubs whatever `--passphrase-env` and `--token-env`
1474 // name, so this is the only network affordance it has from us.
1475 //
1476 // The variable is PROCESS-GLOBAL, and `HostToolExecutor::execute`
1477 // has no per-call environment, so two evaluators in one process
1478 // would race: one could hand its broker's URL to the other's
1479 // connector, pointing it at the wrong allowlist. The lock makes
1480 // the set→spawn→unset window exclusive. Production runs one
1481 // evaluator per process, so this serialises nothing that was
1482 // parallel; it closes a hazard that only exists in-process (and
1483 // that our own threaded tests could reach).
1484 None => {
1485 let exec = self.connector.as_ref().expect("checked above");
1486 let _guard = EGRESS_ENV.lock().unwrap_or_else(|e| e.into_inner());
1487 std::env::set_var("AREEV_EGRESS_URL", broker.url());
1488 // The broker authenticates its callers: loopback is not an
1489 // authorization, and without the token every call would 401.
1490 if let Some(t) = broker.token_for(connector_name) {
1491 std::env::set_var("AREEV_EGRESS_TOKEN", t);
1492 }
1493 let r = exec.execute(connector_name, hash, &payload, &idem);
1494 std::env::remove_var("AREEV_EGRESS_URL");
1495 std::env::remove_var("AREEV_EGRESS_TOKEN");
1496 r
1497 }
1498 };
1499
1500 // Surface a refused destination as its own error rather than letting it
1501 // read as a generic connector failure — a connector reaching somewhere
1502 // undeclared is a different problem from one that crashed.
1503 let refused = broker.refusals();
1504 if !refused.is_empty() {
1505 return Err(TriggerError::EgressRefused {
1506 trigger: hash.to_string(),
1507 host: refused
1508 .iter()
1509 .map(|r| format!("{} ({})", r.destination, r.reason))
1510 .collect::<Vec<_>>()
1511 .join(", "),
1512 });
1513 }
1514 match result {
1515 areev_run::ExecResult::Ok(v) => {
1516 // `{"error": …}` is the shape every blessed blob fails in, and
1517 // `PollResponse` would deserialize it into an empty page with
1518 // no cursor — a source that is down, reported as a source with
1519 // nothing new, on every tick, silently. A poll that answered an
1520 // error FAILED: the claim is released, the cursor stays, and
1521 // the backoff applies (#231).
1522 if let Some(detail) = v
1523 .get("error")
1524 .and_then(|e| e.as_str())
1525 .map(str::trim)
1526 .filter(|e| !e.is_empty())
1527 {
1528 let code = v.get("code").and_then(|c| c.as_str()).unwrap_or_default();
1529 let named =
1530 if code.is_empty() { String::new() } else { format!(" [{code}]") };
1531 return Err(TriggerError::ConnectorFailed {
1532 trigger: hash.to_string(),
1533 detail: format!("the connector reported an error{named}: {detail}"),
1534 });
1535 }
1536 serde_json::from_value(v).map_err(|e| TriggerError::ConnectorFailed {
1537 trigger: hash.to_string(),
1538 detail: format!("response is not a poll response: {e}"),
1539 })
1540 }
1541 areev_run::ExecResult::Err { detail, .. } => {
1542 Err(TriggerError::ConnectorFailed { trigger: hash.to_string(), detail })
1543 }
1544 }
1545 }
1546
1547 /// Record the item as an Event and start the bound workflow.
1548 ///
1549 /// `legacy_run_ids` (#128) covers a trigger that was superseded BEFORE
1550 /// this fix shipped, when the run id was minted from the (then-current)
1551 /// head rather than the chain root: each entry is the id this same item
1552 /// would have gotten under an older head. Empty for a never-superseded
1553 /// trigger, so it costs nothing in the common case.
1554 fn start_run(
1555 &self,
1556 trigger: &Trigger,
1557 run_id: &str,
1558 legacy_run_ids: &[String],
1559 item: &PollItem,
1560 trigger_hash: &str,
1561 content_refs: &[ContentRef],
1562 ) -> StartOutcome {
1563 // Idempotency has to hold whether or not a runtime is wired in. With a
1564 // starter, the runtime's duplicate-run-id refusal is the guard; without
1565 // one, nothing else would stop the same item being re-ingested on every
1566 // poll forever, because an Event's `created_at` differs per firing and
1567 // so content addressing does not collapse them.
1568 let seen = self
1569 .facade
1570 .with_store(|m| m.run_grains(&self.ns, run_id, 0, 1))
1571 .map(|g| !g.is_empty())
1572 .unwrap_or(false);
1573 if seen {
1574 return StartOutcome::Duplicate;
1575 }
1576 // #128 compat — an item already processed under a pre-fix
1577 // (head-keyed) run id must still be recognized, or a trigger
1578 // superseded before this fix reprocesses its whole backlog the
1579 // first time it is evaluated after upgrading.
1580 for legacy_id in legacy_run_ids {
1581 let seen_legacy = self
1582 .facade
1583 .with_store(|m| m.run_grains(&self.ns, legacy_id, 0, 1))
1584 .map(|g| !g.is_empty())
1585 .unwrap_or(false);
1586 if seen_legacy {
1587 return StartOutcome::Duplicate;
1588 }
1589 }
1590
1591 // The ingest Event is built here but — #129 — WRITTEN only once the
1592 // outcome is one this dedup check should treat as "seen": Ingested
1593 // (no starter, so the Event itself IS the completed unit of work),
1594 // Started, or a starter-reported Duplicate (the runtime already has
1595 // it covered, possibly from elsewhere). A starter-reported `Failed`
1596 // writes NOTHING, so a retry's `seen` check above finds nothing and
1597 // genuinely retries `starter.start()` — before this, the Event was
1598 // always written first, so a failed start still left a `run_id`-
1599 // bearing grain behind that made every future retry of the SAME
1600 // item look like an already-processed duplicate, permanently
1601 // stranding it despite #129's cursor hold.
1602 let build_event = || {
1603 let mut event = Event::new(&item.payload.to_string())
1604 .namespace(&self.ns)
1605 .extra_field("trigger", serde_json::json!(trigger_hash))
1606 .extra_field("run_id", serde_json::json!(run_id));
1607 if let Some(c) = &trigger.connector {
1608 event = event.extra_field("connector", serde_json::json!(c));
1609 }
1610 // #93 — the item's stored blobs, referenced the same way a
1611 // host-driven ingest references them: through `content_refs`,
1612 // which is what keeps them alive through GC, carries them in
1613 // bundles, and lets erasure's sole-reference reclamation find
1614 // them.
1615 for cr in content_refs {
1616 event = event.content_ref(cr.clone());
1617 }
1618 event
1619 };
1620
1621 let Some(starter) = &self.starter else {
1622 // Ingest-only: the item is recorded, nothing is executed. Reported
1623 // as ingested rather than as a run, because claiming a run started
1624 // when none did would make the report lie.
1625 return match self.facade.with_store(|m| m.add(&build_event())) {
1626 Ok(_) => StartOutcome::Ingested,
1627 Err(e) => StartOutcome::Failed(format!("ingest: {e}")),
1628 };
1629 };
1630 let mut input = serde_json::json!({
1631 "trigger": trigger_hash,
1632 "connector": trigger.connector,
1633 "scope": trigger.scope,
1634 "item": item.payload,
1635 });
1636 // Declared context (#85): the EVALUATOR assembles it, because it is
1637 // the one party that already holds the memory — on the embedded
1638 // backend a tool inside the run cannot open the file its own run
1639 // locks. Fail closed: a trigger that declared context must not fire
1640 // blind, so a missing query or a failed read refuses the firing (the
1641 // evaluator's normal retry/backoff applies) rather than starting a
1642 // run without the context its declaration promised.
1643 if let Some(spec) = &trigger.context_query {
1644 match self.assemble_context(spec, &item.payload) {
1645 Ok(ctx) => {
1646 input["context"] = ctx;
1647 }
1648 Err(why) => {
1649 return StartOutcome::Failed(format!("context_query \"{spec}\": {why}"));
1650 }
1651 }
1652 }
1653 // Read through whatever scheme prefix the declaration spelled the
1654 // reference with (#73): `sha256:<hex>` validated, listed, and reported
1655 // `waiting` forever, then died here on `FMT-E001: invalid hex hash`.
1656 match starter.start(trigger.workflow_hash(), run_id, input) {
1657 // The run is durably underway (or already was, started elsewhere)
1658 // before we ever try to write the ingest Event, so a failure to
1659 // write it here does not need to be reported as a failed firing:
1660 // a retry would find `starter.start()` itself now reporting
1661 // `Duplicate` (the runtime's own dedup), never a second run. Best
1662 // effort is enough; the Event is audit/context linkage, not the
1663 // run's own record of itself.
1664 StartResult::Started => {
1665 let _ = self.facade.with_store(|m| m.add(&build_event()));
1666 StartOutcome::Started
1667 }
1668 StartResult::Duplicate => {
1669 let _ = self.facade.with_store(|m| m.add(&build_event()));
1670 StartOutcome::Duplicate
1671 }
1672 StartResult::Failed(why) => StartOutcome::Failed(why),
1673 }
1674 }
1675
1676 /// Run the trigger's saved query (`RUN "name"($p = v, …)`) against the
1677 /// facade this evaluator already holds and return the result payload.
1678 /// The executor re-validates the saved body as read-only at execution,
1679 /// and the destructive cap is off — a context query can never mutate.
1680 ///
1681 /// #92 — the declaration may bind the query's parameters from the
1682 /// firing item (`name($session = /session)`): each JSON pointer is
1683 /// resolved against the item's payload with `--dedup-key`'s machinery
1684 /// and semantics. Fail-closed like the rest of declared context: an
1685 /// unresolvable pointer, or one landing on a non-scalar, refuses the
1686 /// firing rather than running the query with a hole in it. Values ride
1687 /// as a parsed AST (`RunQueryStmt`), never inside CAL text, so an
1688 /// untrusted payload value cannot inject CAL.
1689 fn assemble_context(
1690 &self,
1691 spec: &str,
1692 payload: &serde_json::Value,
1693 ) -> std::result::Result<serde_json::Value, String> {
1694 let spec = crate::context::parse_context_query(spec)?;
1695 let mut bindings: Vec<(String, areev_cal::ast::Value)> = Vec::new();
1696 for (param, pointer) in &spec.bindings {
1697 let v = payload.pointer(pointer).ok_or_else(|| {
1698 format!("parameter ${param}: pointer {pointer} does not resolve against the firing item")
1699 })?;
1700 let value = match v {
1701 serde_json::Value::String(s) => {
1702 areev_cal::ast::Value::String { value: s.clone() }
1703 }
1704 serde_json::Value::Number(n) => areev_cal::ast::Value::Number {
1705 value: n.as_f64().ok_or_else(|| {
1706 format!("parameter ${param}: {pointer} is not a representable number")
1707 })?,
1708 },
1709 serde_json::Value::Bool(b) => areev_cal::ast::Value::Boolean { value: *b },
1710 other => {
1711 return Err(format!(
1712 "parameter ${param}: pointer {pointer} must land on a scalar, found {}",
1713 match other {
1714 serde_json::Value::Null => "null",
1715 serde_json::Value::Array(_) => "an array",
1716 _ => "an object",
1717 }
1718 ))
1719 }
1720 };
1721 bindings.push((param.clone(), value));
1722 }
1723 let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig {
1724 allow_destructive_ops: false,
1725 ..areev_cal::CalExecutorConfig::default()
1726 });
1727 let query = areev_cal::ast::CalQuery {
1728 version: Default::default(),
1729 statement: areev_cal::ast::CalStatement::RunQuery(areev_cal::ast::RunQueryStmt {
1730 name: spec.name.clone(),
1731 bindings,
1732 span: None,
1733 }),
1734 pipeline: Vec::new(),
1735 with_options: Vec::new(),
1736 format: None,
1737 let_bindings: Vec::new(),
1738 user_vars: Default::default(),
1739 let_values: Default::default(),
1740 warnings: Vec::new(),
1741 };
1742 let res = ex
1743 .execute_parsed(query, &format!("RUN \"{}\"", spec.name), self.facade.as_ref())
1744 .map_err(|e| e.to_string())?;
1745 serde_json::to_value(&res.result).map_err(|e| e.to_string())
1746 }
1747
1748 /// One Observation per firing: what fired, what it produced, what it
1749 /// skipped. An unfired trigger is invisible otherwise.
1750 fn journal(
1751 &self,
1752 hash: &str,
1753 trigger: &Trigger,
1754 outcome: &FireOutcome,
1755 note: Option<&str>,
1756 now: i64,
1757 ) -> Result<()> {
1758 let mut obs = Observation::new("areev:trigger", "trigger:firing")
1759 .namespace(TRIGGER_NS)
1760 .created_at(now)
1761 .extra_field("trigger", serde_json::json!(hash))
1762 .extra_field("kind", serde_json::json!(trigger.kind.as_str()))
1763 .extra_field("workflow", serde_json::json!(trigger.workflow))
1764 .extra_field("items", serde_json::json!(outcome.items))
1765 .extra_field("runs_started", serde_json::json!(outcome.runs_started))
1766 .extra_field("duplicates", serde_json::json!(outcome.duplicates));
1767 // Without these, a firing where every item lacked the dedup key reads
1768 // as "items 5, runs_started 0, duplicates 0" -- and that last zero
1769 // actively misleads, saying the items were not skipped as duplicates
1770 // without saying why they were skipped at all. Emitted only when
1771 // non-zero, so an ordinary firing stays as small as it was.
1772 if outcome.unidentifiable > 0 {
1773 obs = obs.extra_field("unidentifiable", serde_json::json!(outcome.unidentifiable));
1774 }
1775 if outcome.ingested > 0 {
1776 obs = obs.extra_field("ingested", serde_json::json!(outcome.ingested));
1777 }
1778 if !outcome.failures.is_empty() {
1779 obs = obs.extra_field("failures", serde_json::json!(outcome.failures));
1780 // #129 — names WHY the cursor did not move this firing, so the
1781 // audit record does not require the reader to infer it from
1782 // `duplicates` staying flat on the next firing.
1783 obs = obs.extra_field("cursor_held", serde_json::json!(true));
1784 }
1785 if outcome.seeded {
1786 obs = obs.extra_field("seeded", serde_json::json!(true));
1787 }
1788 if let Some(n) = note {
1789 obs = obs.extra_field("note", serde_json::json!(n));
1790 }
1791 self.facade
1792 .with_store(|m| m.add_if_novel(&obs))
1793 .map(|_| ())
1794 .map_err(|e| TriggerError::Storage { detail: e.to_string() })
1795 }
1796
1797 /// Resolve (and cache) the supersession chain for one trigger's head
1798 /// hash within one evaluation pass (#128).
1799 ///
1800 /// `cache` lives on the CALLER's stack — a fresh `HashMap` per `run()`,
1801 /// `deliver()`, or `status()` invocation — so a chain is walked AT MOST
1802 /// ONCE per trigger per pass no matter how many items it fires or how
1803 /// many composites settle against it in that pass. Do not add a call
1804 /// site that walks the chain per item; thread the already-resolved
1805 /// [`Chain`] through instead, the way `fire`/`collect_and_start` do.
1806 fn resolve_chain(&self, hash: &str, cache: &mut HashMap<String, Chain>) -> Result<Chain> {
1807 if let Some(c) = cache.get(hash) {
1808 return Ok(c.clone());
1809 }
1810 let h = Hash::from_hex(hash).map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
1811 let hashes: Vec<String> = self
1812 .facade
1813 .with_store(|m| m.supersession_chain(&h))
1814 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
1815 .into_iter()
1816 .map(|hh| hh.to_hex())
1817 .collect();
1818 let chain = Chain(hashes);
1819 cache.insert(hash.to_string(), chain.clone());
1820 Ok(chain)
1821 }
1822
1823 /// Read a trigger's evaluation state through its resolved chain, with
1824 /// compatibility for a trigger superseded BEFORE #128 shipped (its state
1825 /// was keyed on the head hash of the moment, not the chain root).
1826 ///
1827 /// Always tries the ROOT key first. For a trigger that has never been
1828 /// superseded this is the ONLY path ever taken — `chain.root() ==` the
1829 /// hash this crate always keyed state on — so the common case is a
1830 /// byte-identical lookup to before this feature existed.
1831 ///
1832 /// If the root row is absent, every other hash in the chain
1833 /// (`chain.legacy()`) is checked for a row written under an older head.
1834 /// Several may exist if the trigger was superseded more than once
1835 /// before upgrading; [`state_is_more_advanced`] picks whichever
1836 /// represents the most real progress, so the survivor is never the one
1837 /// that would silently throw away a further-along cursor.
1838 ///
1839 /// `adopt = true` persists the found legacy state under the root and
1840 /// deletes the legacy row — write the new row FIRST, delete the legacy
1841 /// row SECOND, so a crash in between leaves a harmless duplicate (the
1842 /// legacy row is simply never consulted again once the root row exists)
1843 /// rather than losing the cursor. Pass `true` only from a caller that
1844 /// already owns write access for real evaluation work (`run`,
1845 /// `deliver`, composite settlement); `status`/`show` pass `false` so a
1846 /// pure inspection command has no side effect. Adoption is best-effort
1847 /// against a read-only-opened memory: `STO-E004` is swallowed and the
1848 /// found state is still returned, just not yet persisted — the next
1849 /// pass with write access adopts it.
1850 fn resolve_state(&self, chain: &Chain, adopt: bool) -> Result<(TriggerState, Option<String>)> {
1851 let root = chain.root();
1852 if let Some((state, raw)) = self
1853 .facade
1854 .with_store(|m| m.trigger_state(root))
1855 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
1856 {
1857 return Ok((state, Some(raw)));
1858 }
1859
1860 let mut best: Option<(&str, TriggerState)> = None;
1861 for legacy_hash in chain.legacy() {
1862 if let Some((state, _raw)) = self
1863 .facade
1864 .with_store(|m| m.trigger_state(legacy_hash))
1865 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
1866 {
1867 let better = best
1868 .as_ref()
1869 .is_none_or(|(_, current)| state_is_more_advanced(&state, current));
1870 if better {
1871 best = Some((legacy_hash.as_str(), state));
1872 }
1873 }
1874 }
1875 let Some((legacy_hash, state)) = best else {
1876 // No row anywhere in the chain: a genuinely new trigger.
1877 return Ok((TriggerState::default(), None));
1878 };
1879 if !adopt {
1880 return Ok((state, None));
1881 }
1882
1883 // `expected=None` only claims an ABSENT row (`INSERT OR IGNORE`), so
1884 // losing a race to another evaluator adopting the same legacy row
1885 // concurrently is a no-op, never a clobber — either way the legacy
1886 // row is redundant now.
1887 match self.facade.with_store(|m| m.put_trigger_state(root, None, &state)) {
1888 Ok(_) => {}
1889 Err(AreevError::ReadOnly(_)) => return Ok((state, None)),
1890 Err(e) => return Err(TriggerError::Storage { detail: e.to_string() }),
1891 }
1892 if let Err(e) = self.facade.with_store(|m| m.clear_trigger_state(legacy_hash)) {
1893 if !matches!(e, AreevError::ReadOnly(_)) {
1894 return Err(TriggerError::Storage { detail: e.to_string() });
1895 }
1896 }
1897 let (state, raw) = self
1898 .facade
1899 .with_store(|m| m.trigger_state(root))
1900 .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
1901 .ok_or_else(|| TriggerError::Storage {
1902 detail: format!(
1903 "adopted trigger state for {root} vanished immediately after writing"
1904 ),
1905 })?;
1906 Ok((state, Some(raw)))
1907 }
1908}
1909
1910/// A trigger's supersession chain for the duration of one evaluation pass:
1911/// every content-address hash in its edit history, HEAD (the declaration's
1912/// current hash — what the caller resolved from) first, ROOT last (#128).
1913///
1914/// Evaluation state (`trg:<hash>`) and derived run ids are keyed on the
1915/// ROOT, never the head: a Trigger grain re-pointed by `SUPERSEDE` mints a
1916/// new head hash for the SAME standing rule (`docs/loop.md`'s
1917/// propose→approve→apply cycle re-points a trigger exactly this way), and
1918/// keying on the head alone would orphan the cursor and the dedup fence
1919/// every time a recommendation is applied. For a trigger that has never
1920/// been superseded, `root() == head`, so every key derived from it is
1921/// byte-identical to what this crate always computed — the no-op guarantee
1922/// the fix has to preserve.
1923#[derive(Debug, Clone)]
1924struct Chain(Vec<String>);
1925
1926impl Chain {
1927 /// The key evaluation state and run ids are actually resolved against.
1928 fn root(&self) -> &str {
1929 self.0.last().map(String::as_str).expect("a chain always has at least its head")
1930 }
1931
1932 /// Every hash besides the root — the identities a pre-#128 evaluator
1933 /// might have keyed state or a run id under. Empty for a
1934 /// never-superseded trigger, so the compatibility paths that walk this
1935 /// cost nothing in the common case.
1936 fn legacy(&self) -> &[String] {
1937 &self.0[..self.0.len() - 1]
1938 }
1939}
1940
1941/// Which of two legacy state rows found along a chain is "further along"
1942/// and should be adopted, when more than one exists (a trigger superseded
1943/// more than once before #128 shipped). `last_fired_at` is the most direct
1944/// evidence of real progress across every trigger kind — the row that
1945/// fired most recently is the row whose cursor best reflects what has
1946/// actually been processed. `op_cursor` (a `memory` trigger's position) and
1947/// then "has this row ever polled at all" break a tie where neither
1948/// candidate has ever fired.
1949fn state_is_more_advanced(candidate: &TriggerState, current_best: &TriggerState) -> bool {
1950 (candidate.last_fired_at, candidate.op_cursor, candidate.cursor.is_some())
1951 > (current_best.last_fired_at, current_best.op_cursor, current_best.cursor.is_some())
1952}
1953
1954/// One line for `released.last_error` (#129): several items in one firing
1955/// can fail for different reasons, and `last_error` is a single string.
1956fn summarize_failures(failures: &[String]) -> String {
1957 match failures {
1958 [one] => one.clone(),
1959 many => format!("{} item(s) failed to start: {}", many.len(), many.join("; ")),
1960 }
1961}
1962
1963/// Drop partial matches past their window.
1964///
1965/// Without this, a composite that never completes accumulates keys forever and
1966/// a stale half-match eventually pairs with unrelated work — the exact failure
1967/// Argo Events' reset cron exists to paper over.
1968fn prune_partials(state: &mut TriggerState, trigger: &Trigger, now: i64) {
1969 let Some(window) = trigger.window_ms else {
1970 return;
1971 };
1972 state.partials.retain(|_, p| now - p.started_ms <= window);
1973}
1974
1975#[derive(Debug, Default, Clone)]
1976struct FireOutcome {
1977 items: usize,
1978 runs_started: usize,
1979 ingested: usize,
1980 duplicates: usize,
1981 unidentifiable: usize,
1982 failures: Vec<String>,
1983 cursor: Option<String>,
1984 /// The payloads this firing produced, so a composite can pull its
1985 /// correlation value out of them.
1986 fired_items: Vec<serde_json::Value>,
1987 /// Correlation keys a composite consumed, cleared on release.
1988 settled_keys: Vec<String>,
1989 op_cursor: Option<i64>,
1990 draining: bool,
1991 seeded: bool,
1992 skipped_locked: bool,
1993}
1994
1995enum StartOutcome {
1996 Started,
1997 /// Recorded but not executed — no runtime is wired in.
1998 Ingested,
1999 Duplicate,
2000 Failed(String),
2001}
2002
2003/// The run id for one firing of one item.
2004///
2005/// Derived from `(trigger, connector, dedup value)`, so the same item seen
2006/// twice — connector replay, overlapping cursors, two nodes racing a lease
2007/// boundary — produces the same id. `areev run start` refuses a duplicate, so
2008/// the second attempt is a recorded skip rather than a second run. At-most-once
2009/// firing with no lease, no fencing token, and no clock assumption.
2010///
2011/// The connector is part of the identity because CloudEvents made that
2012/// normative for the same reason: `source` + `id` is unique, `id` alone is only
2013/// unique within a producer. Two connectors sharing an id space must not
2014/// collide.
2015///
2016/// **`trigger_hash` is the chain ROOT (#128), not necessarily the
2017/// declaration's current head.** A `Trigger` grain re-pointed by
2018/// `SUPERSEDE` mints a new head for the same standing rule, and this
2019/// function has no way to know that on its own — a caller that passed the
2020/// head would mint a fresh id for an item already processed under the old
2021/// head, defeating the very dedup fence this function exists to provide.
2022/// Every call site resolves the root once per pass (`Evaluator::
2023/// resolve_chain`) and passes that; this function's signature and hashing
2024/// are otherwise unchanged.
2025pub fn run_id_for(trigger_hash: &str, connector: Option<&str>, dedup_value: &str) -> String {
2026 let mut h = Sha256::new();
2027 h.update(b"areev-trigger:v1");
2028 h.update([0x1f]);
2029 h.update(connector.unwrap_or_default().as_bytes());
2030 h.update([0x1f]);
2031 h.update(dedup_value.as_bytes());
2032 let digest = hex(&h.finalize());
2033 format!("{}-{}", short(trigger_hash, 8), short(&digest, 12))
2034}
2035
2036fn hex(bytes: &[u8]) -> String {
2037 bytes.iter().map(|b| format!("{b:02x}")).collect()
2038}
2039
2040#[cfg(test)]
2041mod tests {
2042 use super::*;
2043
2044 #[test]
2045 fn a_run_id_is_stable_for_the_same_item() {
2046 let a = run_id_for("abcdef1234", Some("gmail"), "m1");
2047 let b = run_id_for("abcdef1234", Some("gmail"), "m1");
2048 assert_eq!(a, b, "the same item must always mint the same id");
2049 }
2050
2051 #[test]
2052 fn different_items_get_different_ids() {
2053 let a = run_id_for("abcdef1234", Some("gmail"), "m1");
2054 let b = run_id_for("abcdef1234", Some("gmail"), "m2");
2055 assert_ne!(a, b);
2056 }
2057
2058 #[test]
2059 fn the_connector_is_part_of_the_identity() {
2060 // CloudEvents' rule: `id` alone is unique only within a producer, so two
2061 // connectors with a shared id space must not collide.
2062 let a = run_id_for("abcdef1234", Some("gmail"), "1");
2063 let b = run_id_for("abcdef1234", Some("stripe"), "1");
2064 assert_ne!(a, b);
2065 }
2066
2067 #[test]
2068 fn the_id_names_its_trigger_for_a_human_reading_a_run_list() {
2069 let id = run_id_for("abcdef1234567890", Some("gmail"), "m1");
2070 assert!(id.starts_with("abcdef12"), "{id}");
2071 assert!(id.len() < 32, "short enough to read: {id}");
2072 }
2073
2074 #[test]
2075 fn a_short_trigger_hash_does_not_panic() {
2076 let id = run_id_for("ab", None, "x");
2077 assert!(id.starts_with("ab-"));
2078 }
2079}