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