Skip to main content

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::sync::Arc;
22
23use areev_cal::AreevFacade;
24use areev_core::types::{ContentRef, Event, Grain, GrainType, Observation, Trigger, TriggerKind};
25use areev_run::HostToolExecutor;
26use areev_store::TriggerState;
27use serde::Serialize;
28use sha2::{Digest, Sha256};
29
30use crate::clock::Clock;
31use crate::connector::{
32    dedup_value, rewrite_blob_refs, PollItem, PollRequest, PollResponse,
33    MAX_BLOB_BYTES_PER_ITEM, MAX_BLOB_BYTES_PER_RESPONSE,
34};
35use crate::error::{Result, TriggerError};
36use crate::schedule;
37
38/// Namespace for trigger firing records. Alongside the runtime's own
39/// `agent:harness`, so operational journalling stays out of user namespaces.
40pub const TRIGGER_NS: &str = "agent:triggers";
41
42/// How many triggers one invocation will look at. A backstop, not a policy.
43const MAX_TRIGGERS_SCANNED: usize = 4096;
44
45/// Knobs for one evaluation pass.
46#[derive(Debug, Clone)]
47pub struct EvalOptions {
48    /// Evaluate only this trigger (its content address).
49    pub only: Option<String>,
50    /// How long a claim is held before another evaluator may take over.
51    /// Deliberately generous: a lease shorter than the worst-case connector
52    /// runtime causes takeovers mid-poll, which costs duplicate API calls.
53    pub lease: std::time::Duration,
54    /// Cap on items requested per firing.
55    pub max_items: usize,
56    /// Report what would happen and touch nothing. The safe first command on a
57    /// new deployment.
58    pub dry_run: bool,
59    /// This evaluator's identity, recorded in the claim.
60    pub node: String,
61    /// Decoded-size budget for one item's connector blobs (#93). Overrun
62    /// refuses the whole poll (TRG-E011) rather than truncating.
63    pub max_blob_bytes_per_item: usize,
64    /// Decoded-size budget for one poll response's blobs (#93).
65    pub max_blob_bytes_per_response: usize,
66}
67
68impl Default for EvalOptions {
69    fn default() -> Self {
70        EvalOptions {
71            only: None,
72            lease: std::time::Duration::from_secs(300),
73            max_items: 100,
74            dry_run: false,
75            node: default_node_id(),
76            max_blob_bytes_per_item: MAX_BLOB_BYTES_PER_ITEM,
77            max_blob_bytes_per_response: MAX_BLOB_BYTES_PER_RESPONSE,
78        }
79    }
80}
81
82/// First `n` characters, safely — `&s[..n]` panics on a short string or a
83/// multi-byte boundary, and a message-formatting helper must not be what takes
84/// the process down. Declarations can arrive by bundle import from an
85/// implementation we did not write.
86fn short(s: &str, n: usize) -> &str {
87    match s.char_indices().nth(n) {
88        Some((idx, _)) => &s[..idx],
89        None => s,
90    }
91}
92
93/// A stable-ish identity for this evaluator. Host name plus pid: enough to tell
94/// two nodes apart in a claim, and to recognise our own stale claim after a
95/// restart.
96fn default_node_id() -> String {
97    let host = std::env::var("HOSTNAME")
98        .or_else(|_| std::env::var("COMPUTERNAME"))
99        .unwrap_or_else(|_| "node".into());
100    format!("{host}/{}", std::process::id())
101}
102
103/// What one evaluation pass did. Shaped like `loop run`'s report for symmetry.
104#[derive(Debug, Clone, Default, Serialize)]
105pub struct EvalReport {
106    pub claimed: usize,
107    pub skipped_not_due: usize,
108    pub skipped_locked: usize,
109    pub skipped_paused: usize,
110    pub items: usize,
111    pub duplicates: usize,
112    pub runs_started: usize,
113    /// Items recorded without starting a workflow, because no runtime is wired
114    /// in. Counted apart from `runs_started` so the report never claims a run
115    /// happened when none did.
116    pub ingested: usize,
117    /// Items the connector returned that carry no usable identity, so no run
118    /// could be minted for them. Reported rather than silently dropped: an item
119    /// nobody can name is a connector bug, and it should be visible as one.
120    pub unidentifiable: usize,
121    /// Declarations that cannot fire as written — a cron that does not parse, a
122    /// timezone this build refuses, a composite gate naming a member the
123    /// declaration does not carry.
124    ///
125    /// Counted APART from `skipped_not_due` on purpose. Folded in there, an
126    /// unusable trigger is indistinguishable from a healthy one waiting its
127    /// turn, which is the failure mode with no symptom: the work simply never
128    /// happens and every report looks green. The reason lands in `errors`.
129    pub unusable: usize,
130    /// Not fatal to the pass: one broken trigger must not stop the others.
131    pub errors: Vec<String>,
132    /// A connector reported a backlog, so this trigger is due again at once
133    /// rather than after its interval.
134    pub draining: Vec<String>,
135}
136
137/// One trigger considered, for `--dry-run` and `status`.
138#[derive(Debug, Clone, Serialize)]
139pub struct TriggerStatus {
140    pub trigger: String,
141    /// The declaration's `name`, when it carries one.
142    ///
143    /// `name` is what a human uses to identify a trigger, and it is accepted
144    /// on write — but nothing read it back (#73), so identity fell onto the
145    /// workflow hash, which is stable only until the plan is re-declared. It
146    /// rides in `extra_fields` rather than being a typed field: OMS §A.7 has
147    /// no Trigger `name`, and inventing one would be a spec-level decision
148    /// for a label.
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub name: Option<String>,
151    pub kind: String,
152    pub workflow: String,
153    pub enabled: bool,
154    pub paused: bool,
155    pub due: bool,
156    pub leased_by: Option<String>,
157    pub next_due_at: Option<i64>,
158    pub last_fired_at: Option<i64>,
159    pub consecutive_failures: u32,
160    pub last_error: Option<String>,
161    /// Will never fire again — a one-shot past its instant.
162    pub exhausted: bool,
163    /// Never fired and no failure recorded — the state an unnoticed
164    /// misconfiguration sits in, so it is reported rather than inferred.
165    pub never_fired: bool,
166    /// Why this declaration can never fire, if it cannot.
167    ///
168    /// A trigger can become unusable without ever being written through a
169    /// validating path — it can arrive by bundle import from an implementation
170    /// that validated differently, or predate the check. So the evaluator
171    /// reports it rather than assuming the write path caught everything.
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub unusable: Option<String>,
174}
175
176/// The declaration's human label, if it has one.
177///
178/// Written through `extra_fields` by every surface that accepts `name` on a
179/// trigger, and read back here so `list` and `status` can print it (#73).
180/// Blank is treated as absent: a name that renders as nothing is worse than
181/// none, because it displaces the hash a reader could otherwise have used.
182pub fn trigger_name(trigger: &Trigger) -> Option<String> {
183    trigger
184        .common
185        .extra_fields
186        .get("name")
187        .and_then(|v| v.as_str())
188        .map(str::trim)
189        .filter(|s| !s.is_empty())
190        .map(str::to_string)
191}
192
193/// Starts the workflow a trigger is bound to.
194///
195/// A seam rather than a direct `areev_run::Runner` call, for the same reason
196/// the CAL executor takes a governance host: the runtime sits above this crate
197/// in the dependency order for hosts that want it, and a test needs to observe
198/// what *would* be started without spending a real run. It is also where the
199/// duplicate rule lives, which is the whole idempotency story.
200pub trait RunStarter: Send + Sync {
201    fn start(&self, workflow: &str, run_id: &str, input: serde_json::Value) -> StartResult;
202}
203
204/// What starting a run did.
205#[derive(Debug, Clone, PartialEq)]
206pub enum StartResult {
207    Started,
208    /// A run with this id already exists. **Not an error** — it is the
209    /// idempotency guarantee working: this item was already handled, by an
210    /// earlier firing or by another node that won the race.
211    Duplicate,
212    Failed(String),
213}
214
215/// Evaluates triggers against one memory.
216pub struct Evaluator {
217    pub facade: Arc<AreevFacade>,
218    pub clock: Arc<dyn Clock>,
219    /// Executes connector commands. `None` means a due polling trigger fails
220    /// loudly with `TRG-E003` rather than quietly doing nothing — a poll that
221    /// silently returns no items is indistinguishable from a healthy source.
222    pub connector: Option<Arc<dyn HostToolExecutor>>,
223    /// Starts the bound workflow. `None` ingests the item and records the
224    /// firing without starting anything — what `--no-start` is for, and what
225    /// the ingest-only tests use.
226    pub starter: Option<Arc<dyn RunStarter>>,
227    /// Credentials the broker may attach, by name. Values live here and never
228    /// in a grain or a connector's environment: a declaration names a
229    /// credential, it never carries one.
230    pub credentials: std::collections::BTreeMap<String, areev_run::Credential>,
231    pub ns: String,
232    pub principal: String,
233}
234
235impl Evaluator {
236    /// An evaluator that can inspect but not act: no connector, no runtime, no
237    /// credentials. What `list`, `show` and `status` want, and the shape that
238    /// makes "reading cannot fire anything" true by construction rather than by
239    /// remembering to pass `None` four times.
240    pub fn read_only(facade: Arc<AreevFacade>, clock: Arc<dyn Clock>, ns: &str) -> Evaluator {
241        Evaluator {
242            facade,
243            clock,
244            connector: None,
245            starter: None,
246            credentials: Default::default(),
247            ns: ns.to_string(),
248            principal: "user:local".into(),
249        }
250    }
251
252    /// Every trigger declaration in the memory, newest first.
253    pub fn declarations(&self) -> Result<Vec<(String, Trigger)>> {
254        let ns = self.ns.clone();
255        let grains = self
256            .facade
257            .with_store(|m| {
258                m.recent_live_scoped(&[ns], Some(GrainType::Trigger), MAX_TRIGGERS_SCANNED)
259            })
260            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
261
262        let mut out = Vec::new();
263        for g in grains {
264            let hash = g.hash.to_hex();
265            match g.to_trigger() {
266                Ok(mut t) => {
267                    // `to_trigger` reconstructs the typed fields; `extra_fields`
268                    // is not restored for any grain type, so the declaration's
269                    // `name` — an extra field by design, since OMS §A.7 has no
270                    // Trigger `name` — has to be carried over here. Doing it in
271                    // the shared deserializer would silently change what every
272                    // read-modify-write re-serializes, which is the kind of
273                    // change that moves content addresses.
274                    if let Some(name) = g.get_str("name") {
275                        t.common
276                            .extra_fields
277                            .insert("name".into(), serde_json::json!(name));
278                    }
279                    out.push((hash, t))
280                }
281                // A declaration this build cannot read is reported, never
282                // skipped silently: silence is the symptom of every trigger
283                // failure, so it must never also be the symptom of a bug.
284                Err(e) => {
285                    return Err(TriggerError::Malformed {
286                        what: format!("declaration {hash} is unreadable: {e}"),
287                    })
288                }
289            }
290        }
291        Ok(out)
292    }
293
294    /// What every trigger's state looks like right now.
295    pub fn status(&self) -> Result<Vec<TriggerStatus>> {
296        let now = self.clock.now_ms();
297        let mut out = Vec::new();
298        for (hash, t) in self.declarations()? {
299            let st = self
300                .facade
301                .with_store(|m| m.trigger_state(&hash))
302                .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
303                .map(|(s, _)| s)
304                .unwrap_or_default();
305            let unusable = schedule::validate(&t).err().map(|e| e.to_string());
306            out.push(TriggerStatus {
307                trigger: hash,
308                name: trigger_name(&t),
309                kind: t.kind.as_str().to_string(),
310                workflow: t.workflow.clone(),
311                enabled: t.enabled,
312                paused: st.paused,
313                // An unusable declaration is never due. Saying otherwise would
314                // promise a firing that cannot happen.
315                due: unusable.is_none()
316                    && t.enabled
317                    && !st.leased(now)
318                    && schedule::is_due(&t, &st, now).unwrap_or(false),
319                leased_by: st.leased(now).then(|| st.claimed_by.clone()).flatten(),
320                next_due_at: st.next_due_at,
321                last_fired_at: st.last_fired_at,
322                consecutive_failures: st.consecutive_failures,
323                last_error: st.last_error.clone(),
324                exhausted: st.exhausted,
325                never_fired: st.last_fired_at.is_none() && st.consecutive_failures == 0,
326                unusable,
327            });
328        }
329        Ok(out)
330    }
331
332    /// Ingest a payload delivered by the host for a `webhook` or `manual`
333    /// trigger.
334    ///
335    /// Areev never opens a port. The host already terminates TLS and
336    /// authenticates the sender — it is far better at both than a memory engine
337    /// would be — and hands the payload to a one-shot invocation. That keeps the
338    /// useful half of webhooks without a listening daemon.
339    ///
340    /// Idempotent on the same terms as a poll: the payload's dedup value mints
341    /// the run id, so a webhook delivered twice (which every provider does)
342    /// produces one run and one recorded skip.
343    pub fn deliver(&self, trigger_hash: &str, payload: serde_json::Value) -> Result<EvalReport> {
344        let now = self.clock.now_ms();
345        let (hash, trigger) = self
346            .declarations()?
347            .into_iter()
348            .find(|(h, _)| h.starts_with(trigger_hash))
349            .ok_or_else(|| TriggerError::Malformed {
350                what: format!("no trigger matching '{trigger_hash}'"),
351            })?;
352
353        if !matches!(trigger.kind, TriggerKind::Webhook | TriggerKind::Manual) {
354            return Err(TriggerError::Malformed {
355                what: format!(
356                    "trigger {} is a {} trigger — only webhook and manual triggers accept a \
357                     delivery; a clocked or polling trigger fires from `trigger run`",
358                    short(&hash, 12),
359                    trigger.kind.as_str()
360                ),
361            });
362        }
363        if !trigger.enabled {
364            return Err(TriggerError::Malformed {
365                what: format!("trigger {} is disabled", short(&hash, 12)),
366            });
367        }
368        let (state, _) = self
369            .facade
370            .with_store(|m| m.trigger_state(&hash))
371            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
372            .unwrap_or_default();
373        if state.paused {
374            return Err(TriggerError::Malformed {
375                what: format!("trigger {} is paused", short(&hash, 12)),
376            });
377        }
378
379        let mut report = EvalReport::default();
380        let item = PollItem { id: String::new(), payload, blobs: Vec::new() };
381        report.items = 1;
382        let Some(value) = dedup_value(&item, &trigger.dedup_key) else {
383            report.unidentifiable = 1;
384            // Journal before returning. A delivery naming nothing is precisely
385            // the case the record exists for: the sender's payload shape
386            // changed under us, and stdout of whatever invoked this is not an
387            // audit record -- the replicating Observation is.
388            self.journal(
389                &hash,
390                &trigger,
391                &FireOutcome { items: 1, unidentifiable: 1, ..Default::default() },
392                Some("delivered"),
393                now,
394            )?;
395            return Ok(report);
396        };
397        let run_id = run_id_for(&hash, trigger.connector.as_deref(), &value);
398        match self.start_run(&trigger, &run_id, &item, &hash, &[]) {
399            StartOutcome::Started => report.runs_started = 1,
400            StartOutcome::Ingested => report.ingested = 1,
401            StartOutcome::Duplicate => report.duplicates = 1,
402            StartOutcome::Failed(why) => report.errors.push(why),
403        }
404
405        let outcome = FireOutcome {
406            items: 1,
407            runs_started: report.runs_started,
408            duplicates: report.duplicates,
409            ..Default::default()
410        };
411        self.journal(&hash, &trigger, &outcome, Some("delivered"), now)?;
412        Ok(report)
413    }
414
415    /// Run one evaluation pass.
416    pub fn run(&self, opts: &EvalOptions) -> Result<EvalReport> {
417        let mut report = EvalReport::default();
418        let now = self.clock.now_ms();
419
420        let declarations = self.declarations()?;
421        // Composites are settled after their members, so a gate can be
422        // satisfied in the same pass that completes it rather than waiting a
423        // whole heartbeat. Declaration order is newest-first and says nothing
424        // about dependency, so the split is explicit.
425        let (composites, members): (Vec<_>, Vec<_>) =
426            declarations.into_iter().partition(|(_, t)| t.kind == TriggerKind::Composite);
427
428        for (hash, trigger) in members.into_iter().chain(composites) {
429            if opts.only.as_ref().is_some_and(|only| only != &hash) {
430                continue;
431            }
432            if !trigger.enabled {
433                report.skipped_not_due += 1;
434                continue;
435            }
436            // Checked BEFORE dueness, so an unusable declaration is reported as
437            // what it is rather than disappearing into `not due` — where it
438            // looks exactly like a healthy trigger waiting its turn.
439            if let Err(why) = schedule::validate(&trigger) {
440                report.unusable += 1;
441                report.errors.push(format!("{}: {why}", short(&hash, 12)));
442                continue;
443            }
444            let stored = self
445                .facade
446                .with_store(|m| m.trigger_state(&hash))
447                .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
448            let (state, raw) = match stored {
449                Some((s, r)) => (s, Some(r)),
450                None => (TriggerState::default(), None),
451            };
452
453            if state.paused {
454                report.skipped_paused += 1;
455                continue;
456            }
457            // An absolute schedule seen for the first time: record when it
458            // will be due rather than re-deriving it every pass, so `trigger
459            // status` can say when it next fires and the comparison afterwards
460            // is a plain timestamp check.
461            if state.next_due_at.is_none() && !state.exhausted {
462                if let Some(first) = schedule::initial_due(&trigger, now)? {
463                    let mut seeded = state.clone();
464                    seeded.next_due_at = Some(first);
465                    let _ = self
466                        .facade
467                        .with_store(|m| m.put_trigger_state(&hash, raw.as_deref(), &seeded))
468                        .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
469                    report.skipped_not_due += 1;
470                    continue;
471                }
472            }
473            if !schedule::is_due(&trigger, &state, now)? {
474                report.skipped_not_due += 1;
475                continue;
476            }
477            if state.leased(now) {
478                // The normal steady state with several nodes on one heartbeat,
479                // not a problem.
480                report.skipped_locked += 1;
481                continue;
482            }
483            if opts.dry_run {
484                report.claimed += 1;
485                continue;
486            }
487
488            match self.fire(&hash, &trigger, state, raw.as_deref(), now, opts) {
489                // Lost the claim between deciding it was free and taking it.
490                // Normal with several nodes on one heartbeat, and it must not
491                // be counted as work done.
492                Ok(outcome) if outcome.skipped_locked => report.skipped_locked += 1,
493                Ok(outcome) => {
494                    if !outcome.fired_items.is_empty() {
495                        if let Err(e) = self.record_for_composites(&hash, &outcome.fired_items, now)
496                        {
497                            report.errors.push(e.to_string());
498                        }
499                    }
500                    report.claimed += 1;
501                    report.items += outcome.items;
502                    report.duplicates += outcome.duplicates;
503                    report.runs_started += outcome.runs_started;
504                    report.ingested += outcome.ingested;
505                    report.unidentifiable += outcome.unidentifiable;
506                    for why in &outcome.failures {
507                        report.errors.push(format!("{hash}: {why}"));
508                    }
509                    if outcome.draining {
510                        report.draining.push(hash.clone());
511                    }
512                }
513                Err(e) => {
514                    // One broken trigger must not stop the others.
515                    report.errors.push(e.to_string());
516                }
517            }
518        }
519        Ok(report)
520    }
521
522    fn fire(
523        &self,
524        hash: &str,
525        trigger: &Trigger,
526        state: TriggerState,
527        raw: Option<&str>,
528        now: i64,
529        opts: &EvalOptions,
530    ) -> Result<FireOutcome> {
531        // Claim. Losing means another evaluator got here first.
532        let mut claimed = state.clone();
533        claimed.fence = claimed.fence.wrapping_add(1);
534        claimed.claimed_by = Some(opts.node.clone());
535        claimed.lease_until = Some(now + opts.lease.as_millis() as i64);
536        let won = self
537            .facade
538            .with_store(|m| m.put_trigger_state(hash, raw, &claimed))
539            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
540        if !won {
541            return Ok(FireOutcome { skipped_locked: true, ..Default::default() });
542        }
543        // What a later release must present as `expected`.
544        let claimed_raw = self
545            .facade
546            .with_store(|m| m.trigger_state(hash))
547            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
548            .map(|(_, r)| r);
549
550        let result = self.collect_and_start(hash, trigger, &claimed, now, opts);
551
552        // Release under the fence, whatever happened.
553        let mut released = claimed.clone();
554        released.claimed_by = None;
555        released.lease_until = None;
556        match &result {
557            Ok(outcome) => {
558                released.last_fired_at = Some(now);
559                released.consecutive_failures = 0;
560                released.last_error = None;
561                if let Some(c) = &outcome.cursor {
562                    released.cursor = Some(c.clone());
563                }
564                if let Some(c) = outcome.op_cursor {
565                    released.op_cursor = Some(c);
566                }
567                // A satisfied gate consumes its correlation key. Leaving it
568                // would re-fire the same set on every pass; Flink calls this
569                // the after-match skip strategy, and the conservative choice —
570                // clear only the key that fired — is the one that cannot
571                // swallow an unrelated in-flight match.
572                for k in &outcome.settled_keys {
573                    released.partials.remove(k);
574                }
575                prune_partials(&mut released, trigger, now);
576                released.exhausted = schedule::exhausts_after(trigger, now);
577                released.next_due_at = if outcome.draining {
578                    // A backlog drains at once rather than waiting out the
579                    // interval — a cold start should not take a day.
580                    Some(now)
581                } else {
582                    schedule::advance_after_firing(trigger, now, now)?
583                };
584            }
585            Err(e) => {
586                released.consecutive_failures = claimed.consecutive_failures.saturating_add(1);
587                released.last_error = Some(e.to_string());
588                released.next_due_at =
589                    Some(schedule::backoff_until(trigger, released.consecutive_failures, now));
590            }
591        }
592        let released_ok = self
593            .facade
594            .with_store(|m| m.put_trigger_state(hash, claimed_raw.as_deref(), &released))
595            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
596        if !released_ok {
597            // Our lease expired mid-firing and someone else took over. Their
598            // state stands; ours is refused. The work we did is not lost — the
599            // runs we started are journaled and idempotent — but we must not
600            // write back over the new owner.
601            self.journal(hash, trigger, &FireOutcome::default(), Some("claim lost"), now)?;
602            return Err(TriggerError::ClaimLost { trigger: hash.to_string() });
603        }
604
605        let outcome = result?;
606        self.journal(hash, trigger, &outcome, None, now)?;
607        Ok(outcome)
608    }
609
610    /// Get the items for this firing and start a run per item.
611    fn collect_and_start(
612        &self,
613        hash: &str,
614        trigger: &Trigger,
615        state: &TriggerState,
616        now: i64,
617        opts: &EvalOptions,
618    ) -> Result<FireOutcome> {
619        let mut outcome = FireOutcome::default();
620
621        let items: Vec<PollItem> = match trigger.kind {
622            TriggerKind::Polling => {
623                let response = self.poll(hash, trigger, state, opts)?;
624                outcome.cursor = response.cursor.clone();
625                outcome.draining = response.more;
626                // First contact seeds the cursor and fires nothing. Otherwise
627                // declaring a mailbox trigger starts a run for every message in
628                // history — Zapier's priming poll, and for the same reason.
629                if state.cursor.is_none() {
630                    outcome.seeded = true;
631                    return Ok(outcome);
632                }
633                response.items
634            }
635            // A clocked trigger with no external source fires once per
636            // occurrence, carrying the occurrence itself as the item.
637            TriggerKind::Interval | TriggerKind::Schedule | TriggerKind::Once => {
638                vec![PollItem {
639                    id: now.to_string(),
640                    payload: serde_json::json!({ "at_ms": now }),
641                    blobs: Vec::new(),
642                }]
643            }
644            TriggerKind::Memory => {
645                // Recorded so the journal says "seeded" rather than leaving a
646                // firing that produced nothing looking like a quiet memory.
647                outcome.seeded = state.op_cursor.is_none();
648                let (found, cursor) = self.scan_memory(hash, trigger, state, opts)?;
649                outcome.op_cursor = Some(cursor);
650                found
651            }
652            TriggerKind::Composite => {
653                let keys = self.satisfied_keys(hash, trigger, now)?;
654                outcome.settled_keys = keys.clone();
655                keys.into_iter()
656                    .map(|k| PollItem {
657                        // The correlation value IS the identity: one firing per
658                        // correlated set, however many members contributed.
659                        id: k.clone(),
660                        payload: serde_json::json!({ "correlation": k }),
661                        blobs: Vec::new(),
662                    })
663                    .collect()
664            }
665            // These do not poll. The host owns the listener and hands the
666            // payload to `deliver`, which fires them on the same idempotency
667            // terms; an evaluation pass simply has nothing to do for one.
668            TriggerKind::Webhook | TriggerKind::Manual => Vec::new(),
669        };
670
671        // #93 — store connector blobs in the CAS and rewrite `"blob": "@N"`
672        // payload references to their addresses BEFORE identity resolution,
673        // so a `--dedup-key` pointer into a rewritten field sees the stable
674        // content address rather than a positional index. A contract
675        // violation fails the whole poll here (TRG-E011): fire() then leaves
676        // the cursor unmoved, so nothing is lost — the connector gets fixed
677        // and the same page is re-polled.
678        let mut items = items;
679        let item_refs = self.ingest_item_blobs(hash, &mut items, opts)?;
680
681        outcome.items = items.len();
682        for (item, refs) in items.into_iter().zip(item_refs) {
683            let Some(value) = dedup_value(&item, &trigger.dedup_key) else {
684                outcome.unidentifiable += 1;
685                continue;
686            };
687            outcome.fired_items.push(item.payload.clone());
688            let run_id = run_id_for(hash, trigger.connector.as_deref(), &value);
689            match self.start_run(trigger, &run_id, &item, hash, &refs) {
690                StartOutcome::Started => outcome.runs_started += 1,
691                StartOutcome::Ingested => outcome.ingested += 1,
692                StartOutcome::Duplicate => outcome.duplicates += 1,
693                StartOutcome::Failed(why) => outcome.failures.push(why),
694            }
695        }
696        Ok(outcome)
697    }
698
699    /// Note a member firing against every composite that declares it.
700    ///
701    /// The correlation value comes from the composite's own `correlate`
702    /// pointer applied to the member's item — so two composites may correlate
703    /// the same member on different fields, which is why this is resolved per
704    /// composite rather than once per member.
705    fn record_for_composites(
706        &self,
707        member: &str,
708        items: &[serde_json::Value],
709        now: i64,
710    ) -> Result<()> {
711        for (chash, composite) in self.declarations()? {
712            let Some(alias) = composite.member_alias(member).map(str::to_string) else {
713                continue;
714            };
715            if composite.kind != TriggerKind::Composite {
716                continue;
717            }
718            let (mut state, raw) = self
719                .facade
720                .with_store(|m| m.trigger_state(&chash))
721                .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
722                .map(|(s, r)| (s, Some(r)))
723                .unwrap_or_default();
724
725            for item in items {
726                // No correlate pointer means one global match — every member
727                // firing counts toward the same gate.
728                let key = match &composite.correlate {
729                    Some(ptr) => match item.pointer(ptr) {
730                        Some(serde_json::Value::String(s)) => s.clone(),
731                        Some(other) => other.to_string(),
732                        // An item that cannot be correlated cannot join a
733                        // correlated gate. Dropping it is right: attributing it
734                        // to an arbitrary key would pair unrelated work.
735                        None => continue,
736                    },
737                    None => String::new(),
738                };
739                let entry = state.partials.entry(key).or_insert_with(|| {
740                    areev_store::PartialMatch { members: Default::default(), started_ms: now }
741                });
742                // Recorded under the ALIAS, because that is what the gate
743                // expression names.
744                entry.members.insert(alias.clone(), now);
745            }
746            prune_partials(&mut state, &composite, now);
747            self.facade
748                .with_store(|m| m.put_trigger_state(&chash, raw.as_deref(), &state))
749                .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
750        }
751        Ok(())
752    }
753
754    /// Which correlation keys currently satisfy this composite's gate.
755    fn satisfied_keys(&self, hash: &str, trigger: &Trigger, now: i64) -> Result<Vec<String>> {
756        let predicate = trigger
757            .predicate
758            .as_ref()
759            .ok_or_else(|| TriggerError::Malformed {
760                what: format!("composite trigger {hash} has no predicate"),
761            })
762            .and_then(crate::predicate::from_value)?;
763
764        // Refuse a gate that names a member the declaration does not carry: it
765        // could never be satisfied, so the trigger would be silently dead.
766        for referenced in crate::predicate::referenced_members(&predicate) {
767            if !trigger.members.contains_key(&referenced) {
768                return Err(TriggerError::UnknownMember {
769                    trigger: hash.to_string(),
770                    member: referenced,
771                });
772            }
773        }
774
775        let (state, _) = self
776            .facade
777            .with_store(|m| m.trigger_state(hash))
778            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?
779            .unwrap_or_default();
780
781        let mut out = Vec::new();
782        for (key, partial) in &state.partials {
783            if let Some(w) = trigger.window_ms {
784                if now - partial.started_ms > w {
785                    continue;
786                }
787            }
788            let fired: Vec<String> = partial.members.keys().cloned().collect();
789            if crate::predicate::gate_satisfied(&predicate, &fired) {
790                out.push(key.clone());
791            }
792        }
793        Ok(out)
794    }
795
796    /// Grains matching the predicate that appeared since the stored op cursor.
797    ///
798    /// Built on the op-log rather than a scan: `changes_since` is an indexed
799    /// primary-key range read with a monotonic exclusive cursor, so cost is
800    /// proportional to what changed rather than to how much the memory holds.
801    ///
802    /// Considered and rejected: `PRAGMA data_version` as a cheap "did anything
803    /// change" pre-check. It is documented as unchanged for commits made on the
804    /// same connection — and Areev is single-writer with one connection, so our
805    /// own writes are exactly what it cannot see.
806    fn scan_memory(
807        &self,
808        hash: &str,
809        trigger: &Trigger,
810        state: &TriggerState,
811        opts: &EvalOptions,
812    ) -> Result<(Vec<PollItem>, i64)> {
813        let predicate = trigger
814            .predicate
815            .as_ref()
816            .ok_or_else(|| TriggerError::Malformed {
817                what: format!("memory trigger {hash} has no predicate"),
818            })
819            .and_then(crate::predicate::from_value)?;
820
821        // First contact seeds at the head of the log and matches nothing.
822        // Otherwise declaring a memory trigger on an established memory fires
823        // once for every historical grain that matches — the same reason a
824        // polling trigger primes rather than replaying a mailbox.
825        let Some(after) = state.op_cursor else {
826            let head = self
827                .facade
828                .with_store(|m| m.head_op_seq())
829                .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
830            return Ok((Vec::new(), head));
831        };
832        let ops = self
833            .facade
834            .with_store(|m| m.changes_since(after, opts.max_items))
835            .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
836
837        let mut items = Vec::new();
838        let mut cursor = after;
839        for op in ops {
840            cursor = cursor.max(op.op_seq);
841            // Additions and supersessions both mean "this is true now".
842            // A tombstone means the grain is gone, so there is nothing to match.
843            if op.op == areev_store::OP_FORGET {
844                continue;
845            }
846            let Ok(grain) = self.facade.with_store(|m| m.get(&op.hash)) else {
847                // A grain that vanished between the op-log read and the fetch
848                // (erasure, retention) is not an error — it simply no longer
849                // matches anything.
850                continue;
851            };
852            if !crate::predicate::grain_matches(&grain, &predicate) {
853                continue;
854            }
855            let hex = op.hash.to_hex();
856            items.push(PollItem {
857                // The content address IS the identity: the same grain can never
858                // fire twice, and two evaluators seeing it agree without
859                // coordinating.
860                id: hex.clone(),
861                payload: serde_json::json!({
862                    "hash": hex,
863                    "grain_type": grain.grain_type.as_str(),
864                    "op_seq": op.op_seq,
865                }),
866                blobs: Vec::new(),
867            });
868        }
869        Ok((items, cursor))
870    }
871
872    /// Store an item's connector blobs in the CAS and rewrite payload
873    /// references (#93). Returns one `ContentRef` list per item, parallel
874    /// to `items`. Any contract violation — undecodable base64, a budget
875    /// overrun, a dangling `"@N"` — refuses the WHOLE poll with TRG-E011,
876    /// so the cursor stays put and nothing is silently dropped. `put_blob`
877    /// is idempotent on content, so a re-polled page costs only the
878    /// transfer.
879    fn ingest_item_blobs(
880        &self,
881        hash: &str,
882        items: &mut [PollItem],
883        opts: &EvalOptions,
884    ) -> Result<Vec<Vec<ContentRef>>> {
885        let violation = |detail: String| TriggerError::BlobContract {
886            trigger: short(hash, 12).to_string(),
887            detail,
888        };
889        let mut response_total = 0usize;
890        let mut all_refs = Vec::with_capacity(items.len());
891        for (idx, item) in items.iter_mut().enumerate() {
892            if item.blobs.is_empty() {
893                all_refs.push(Vec::new());
894                continue;
895            }
896            let mut item_total = 0usize;
897            let mut refs = Vec::with_capacity(item.blobs.len());
898            let mut uris = Vec::with_capacity(item.blobs.len());
899            for (bi, blob) in item.blobs.iter().enumerate() {
900                let name = blob.filename.as_deref().unwrap_or("unnamed");
901                let bytes = areev_core::b64::decode(&blob.b64).ok_or_else(|| {
902                    violation(format!("item {idx} blob {bi} ({name}) is not valid base64"))
903                })?;
904                item_total += bytes.len();
905                response_total += bytes.len();
906                if item_total > opts.max_blob_bytes_per_item {
907                    return Err(violation(format!(
908                        "item {idx} blobs exceed the per-item budget ({} bytes decoded)",
909                        opts.max_blob_bytes_per_item
910                    )));
911                }
912                if response_total > opts.max_blob_bytes_per_response {
913                    return Err(violation(format!(
914                        "response blobs exceed the per-response budget ({} bytes decoded)",
915                        opts.max_blob_bytes_per_response
916                    )));
917                }
918                let uri = self
919                    .facade
920                    .with_store(|m| m.put_blob(&bytes))
921                    .map_err(|e| TriggerError::Storage { detail: e.to_string() })?;
922                refs.push(ContentRef {
923                    uri: uri.clone(),
924                    modality: None,
925                    mime_type: blob.mime.clone(),
926                    size_bytes: Some(bytes.len() as u64),
927                    checksum: Some(uri.trim_start_matches("cas://").to_string()),
928                    metadata: blob.filename.as_ref().map(|f| serde_json::json!({ "filename": f })),
929                });
930                uris.push(uri);
931            }
932            rewrite_blob_refs(&mut item.payload, &uris)
933                .map_err(|d| violation(format!("item {idx}: {d}")))?;
934            // The bytes are in the CAS now; drop the base64 so nothing
935            // downstream can re-inline it into the Event or the run input.
936            item.blobs.clear();
937            all_refs.push(refs);
938        }
939        Ok(all_refs)
940    }
941
942    fn poll(
943        &self,
944        hash: &str,
945        trigger: &Trigger,
946        state: &TriggerState,
947        opts: &EvalOptions,
948    ) -> Result<PollResponse> {
949        let connector_name = trigger.connector.as_deref().unwrap_or_default();
950        let Some(exec) = &self.connector else {
951            return Err(TriggerError::NoConnector {
952                trigger: hash.to_string(),
953                connector: connector_name.to_string(),
954            });
955        };
956        // Start a broker for this call, scoped to this trigger's allowlist. The
957        // connector is handed its URL — never a token — so a compromised
958        // connector has nothing to exfiltrate and nowhere undeclared to send
959        // it. The broker stops when this call returns.
960        let policy = areev_run::EgressPolicy::from_config(trigger.config.as_ref())
961            .map_err(|what| TriggerError::Malformed { what })?;
962        // One connector runs per pass, so there is no second caller to tell it
963        // apart from: a default grant covers it. Its methods are whatever the
964        // connector needs to poll, and the credentials are the ones this host
965        // configured — naming one it was not given still fails.
966        let grants = areev_run::EgressGrants::new().default_for_all(
967            self.credentials.keys().fold(
968                areev_run::CallerGrant::new()
969                    .method("GET")
970                    .method("POST")
971                    .method("PUT")
972                    .method("PATCH")
973                    .method("DELETE"),
974                |g, name| g.credential(name),
975            ),
976        );
977        let broker = areev_run::Broker::start(
978            policy,
979            self.credentials.clone(),
980            grants,
981            "TRG-E009",
982        )
983        .map_err(|detail| TriggerError::Storage { detail })?;
984
985        let request = PollRequest {
986            trigger: hash,
987            connector: connector_name,
988            scope: trigger.scope.as_deref(),
989            cursor: state.cursor.as_deref(),
990            max_items: opts.max_items,
991            config: trigger.config.as_ref(),
992        };
993        let payload = serde_json::to_value(&request).map_err(|e| TriggerError::ConnectorFailed {
994            trigger: hash.to_string(),
995            detail: format!("serialize request: {e}"),
996        })?;
997        // The idempotency key ties this call to this occurrence, so a connector
998        // that deduplicates on it sees a retry as a retry.
999        let idem = format!("{hash}:{}", state.fence);
1000        // The connector reads AREEV_EGRESS_URL out of its environment. The
1001        // spawn seam scrubs whatever `--passphrase-env` and `--token-env` name,
1002        // so this is the only network affordance it has from us.
1003        //
1004        // The variable is PROCESS-GLOBAL, and `HostToolExecutor::execute` has no
1005        // per-call environment, so two evaluators in one process would race:
1006        // one could hand its broker's URL to the other's connector, pointing it
1007        // at the wrong allowlist. The lock makes the set→spawn→unset window
1008        // exclusive. Production runs one evaluator per process, so this
1009        // serialises nothing that was parallel; it closes a hazard that only
1010        // exists in-process (and that our own threaded tests could reach).
1011        static EGRESS_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
1012        let result = {
1013            let _guard = EGRESS_ENV.lock().unwrap_or_else(|e| e.into_inner());
1014            std::env::set_var("AREEV_EGRESS_URL", broker.url());
1015            // The broker authenticates its callers: loopback is not an
1016            // authorization, and without the token every call would 401.
1017            if let Some(t) = broker.token_for(connector_name) {
1018                std::env::set_var("AREEV_EGRESS_TOKEN", t);
1019            }
1020            let r = exec.execute(connector_name, hash, &payload, &idem);
1021            std::env::remove_var("AREEV_EGRESS_URL");
1022            std::env::remove_var("AREEV_EGRESS_TOKEN");
1023            r
1024        };
1025
1026        // Surface a refused destination as its own error rather than letting it
1027        // read as a generic connector failure — a connector reaching somewhere
1028        // undeclared is a different problem from one that crashed.
1029        let refused = broker.refusals();
1030        if !refused.is_empty() {
1031            return Err(TriggerError::EgressRefused {
1032                trigger: hash.to_string(),
1033                host: refused
1034                    .iter()
1035                    .map(|r| format!("{} ({})", r.destination, r.reason))
1036                    .collect::<Vec<_>>()
1037                    .join(", "),
1038            });
1039        }
1040        match result {
1041            areev_run::ExecResult::Ok(v) => {
1042                serde_json::from_value(v).map_err(|e| TriggerError::ConnectorFailed {
1043                    trigger: hash.to_string(),
1044                    detail: format!("response is not a poll response: {e}"),
1045                })
1046            }
1047            areev_run::ExecResult::Err { detail, .. } => {
1048                Err(TriggerError::ConnectorFailed { trigger: hash.to_string(), detail })
1049            }
1050        }
1051    }
1052
1053    /// Record the item as an Event and start the bound workflow.
1054    fn start_run(
1055        &self,
1056        trigger: &Trigger,
1057        run_id: &str,
1058        item: &PollItem,
1059        trigger_hash: &str,
1060        content_refs: &[ContentRef],
1061    ) -> StartOutcome {
1062        // Idempotency has to hold whether or not a runtime is wired in. With a
1063        // starter, the runtime's duplicate-run-id refusal is the guard; without
1064        // one, nothing else would stop the same item being re-ingested on every
1065        // poll forever, because an Event's `created_at` differs per firing and
1066        // so content addressing does not collapse them.
1067        let seen = self
1068            .facade
1069            .with_store(|m| m.run_grains(&self.ns, run_id, 0, 1))
1070            .map(|g| !g.is_empty())
1071            .unwrap_or(false);
1072        if seen {
1073            return StartOutcome::Duplicate;
1074        }
1075
1076        let mut event = Event::new(&item.payload.to_string())
1077            .namespace(&self.ns)
1078            .extra_field("trigger", serde_json::json!(trigger_hash))
1079            .extra_field("run_id", serde_json::json!(run_id));
1080        if let Some(c) = &trigger.connector {
1081            event = event.extra_field("connector", serde_json::json!(c));
1082        }
1083        // #93 — the item's stored blobs, referenced the same way a
1084        // host-driven ingest references them: through `content_refs`, which
1085        // is what keeps them alive through GC, carries them in bundles, and
1086        // lets erasure's sole-reference reclamation find them.
1087        for cr in content_refs {
1088            event = event.content_ref(cr.clone());
1089        }
1090        if let Err(e) = self.facade.with_store(|m| m.add(&event)) {
1091            return StartOutcome::Failed(format!("ingest: {e}"));
1092        }
1093        let Some(starter) = &self.starter else {
1094            // Ingest-only: the item is recorded, nothing is executed. Reported
1095            // as ingested rather than as a run, because claiming a run started
1096            // when none did would make the report lie.
1097            return StartOutcome::Ingested;
1098        };
1099        let mut input = serde_json::json!({
1100            "trigger": trigger_hash,
1101            "connector": trigger.connector,
1102            "scope": trigger.scope,
1103            "item": item.payload,
1104        });
1105        // Declared context (#85): the EVALUATOR assembles it, because it is
1106        // the one party that already holds the memory — on the embedded
1107        // backend a tool inside the run cannot open the file its own run
1108        // locks. Fail closed: a trigger that declared context must not fire
1109        // blind, so a missing query or a failed read refuses the firing (the
1110        // evaluator's normal retry/backoff applies) rather than starting a
1111        // run without the context its declaration promised.
1112        if let Some(spec) = &trigger.context_query {
1113            match self.assemble_context(spec, &item.payload) {
1114                Ok(ctx) => {
1115                    input["context"] = ctx;
1116                }
1117                Err(why) => {
1118                    return StartOutcome::Failed(format!("context_query \"{spec}\": {why}"));
1119                }
1120            }
1121        }
1122        // Read through whatever scheme prefix the declaration spelled the
1123        // reference with (#73): `sha256:<hex>` validated, listed, and reported
1124        // `waiting` forever, then died here on `FMT-E001: invalid hex hash`.
1125        match starter.start(trigger.workflow_hash(), run_id, input) {
1126            StartResult::Started => StartOutcome::Started,
1127            StartResult::Duplicate => StartOutcome::Duplicate,
1128            StartResult::Failed(why) => StartOutcome::Failed(why),
1129        }
1130    }
1131
1132    /// Run the trigger's saved query (`RUN "name"($p = v, …)`) against the
1133    /// facade this evaluator already holds and return the result payload.
1134    /// The executor re-validates the saved body as read-only at execution,
1135    /// and the destructive cap is off — a context query can never mutate.
1136    ///
1137    /// #92 — the declaration may bind the query's parameters from the
1138    /// firing item (`name($session = /session)`): each JSON pointer is
1139    /// resolved against the item's payload with `--dedup-key`'s machinery
1140    /// and semantics. Fail-closed like the rest of declared context: an
1141    /// unresolvable pointer, or one landing on a non-scalar, refuses the
1142    /// firing rather than running the query with a hole in it. Values ride
1143    /// as a parsed AST (`RunQueryStmt`), never inside CAL text, so an
1144    /// untrusted payload value cannot inject CAL.
1145    fn assemble_context(
1146        &self,
1147        spec: &str,
1148        payload: &serde_json::Value,
1149    ) -> std::result::Result<serde_json::Value, String> {
1150        let spec = crate::context::parse_context_query(spec)?;
1151        let mut bindings: Vec<(String, areev_cal::ast::Value)> = Vec::new();
1152        for (param, pointer) in &spec.bindings {
1153            let v = payload.pointer(pointer).ok_or_else(|| {
1154                format!("parameter ${param}: pointer {pointer} does not resolve against the firing item")
1155            })?;
1156            let value = match v {
1157                serde_json::Value::String(s) => {
1158                    areev_cal::ast::Value::String { value: s.clone() }
1159                }
1160                serde_json::Value::Number(n) => areev_cal::ast::Value::Number {
1161                    value: n.as_f64().ok_or_else(|| {
1162                        format!("parameter ${param}: {pointer} is not a representable number")
1163                    })?,
1164                },
1165                serde_json::Value::Bool(b) => areev_cal::ast::Value::Boolean { value: *b },
1166                other => {
1167                    return Err(format!(
1168                        "parameter ${param}: pointer {pointer} must land on a scalar, found {}",
1169                        match other {
1170                            serde_json::Value::Null => "null",
1171                            serde_json::Value::Array(_) => "an array",
1172                            _ => "an object",
1173                        }
1174                    ))
1175                }
1176            };
1177            bindings.push((param.clone(), value));
1178        }
1179        let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig {
1180            allow_destructive_ops: false,
1181            ..areev_cal::CalExecutorConfig::default()
1182        });
1183        let query = areev_cal::ast::CalQuery {
1184            version: Default::default(),
1185            statement: areev_cal::ast::CalStatement::RunQuery(areev_cal::ast::RunQueryStmt {
1186                name: spec.name.clone(),
1187                bindings,
1188                span: None,
1189            }),
1190            pipeline: Vec::new(),
1191            with_options: Vec::new(),
1192            format: None,
1193            let_bindings: Vec::new(),
1194            user_vars: Default::default(),
1195            let_values: Default::default(),
1196            warnings: Vec::new(),
1197        };
1198        let res = ex
1199            .execute_parsed(query, &format!("RUN \"{}\"", spec.name), self.facade.as_ref())
1200            .map_err(|e| e.to_string())?;
1201        serde_json::to_value(&res.result).map_err(|e| e.to_string())
1202    }
1203
1204    /// One Observation per firing: what fired, what it produced, what it
1205    /// skipped. An unfired trigger is invisible otherwise.
1206    fn journal(
1207        &self,
1208        hash: &str,
1209        trigger: &Trigger,
1210        outcome: &FireOutcome,
1211        note: Option<&str>,
1212        now: i64,
1213    ) -> Result<()> {
1214        let mut obs = Observation::new("areev:trigger", "trigger:firing")
1215            .namespace(TRIGGER_NS)
1216            .created_at(now)
1217            .extra_field("trigger", serde_json::json!(hash))
1218            .extra_field("kind", serde_json::json!(trigger.kind.as_str()))
1219            .extra_field("workflow", serde_json::json!(trigger.workflow))
1220            .extra_field("items", serde_json::json!(outcome.items))
1221            .extra_field("runs_started", serde_json::json!(outcome.runs_started))
1222            .extra_field("duplicates", serde_json::json!(outcome.duplicates));
1223        // Without these, a firing where every item lacked the dedup key reads
1224        // as "items 5, runs_started 0, duplicates 0" -- and that last zero
1225        // actively misleads, saying the items were not skipped as duplicates
1226        // without saying why they were skipped at all. Emitted only when
1227        // non-zero, so an ordinary firing stays as small as it was.
1228        if outcome.unidentifiable > 0 {
1229            obs = obs.extra_field("unidentifiable", serde_json::json!(outcome.unidentifiable));
1230        }
1231        if outcome.ingested > 0 {
1232            obs = obs.extra_field("ingested", serde_json::json!(outcome.ingested));
1233        }
1234        if !outcome.failures.is_empty() {
1235            obs = obs.extra_field("failures", serde_json::json!(outcome.failures));
1236        }
1237        if outcome.seeded {
1238            obs = obs.extra_field("seeded", serde_json::json!(true));
1239        }
1240        if let Some(n) = note {
1241            obs = obs.extra_field("note", serde_json::json!(n));
1242        }
1243        self.facade
1244            .with_store(|m| m.add_if_novel(&obs))
1245            .map(|_| ())
1246            .map_err(|e| TriggerError::Storage { detail: e.to_string() })
1247    }
1248}
1249
1250/// Drop partial matches past their window.
1251///
1252/// Without this, a composite that never completes accumulates keys forever and
1253/// a stale half-match eventually pairs with unrelated work — the exact failure
1254/// Argo Events' reset cron exists to paper over.
1255fn prune_partials(state: &mut TriggerState, trigger: &Trigger, now: i64) {
1256    let Some(window) = trigger.window_ms else {
1257        return;
1258    };
1259    state.partials.retain(|_, p| now - p.started_ms <= window);
1260}
1261
1262#[derive(Debug, Default, Clone)]
1263struct FireOutcome {
1264    items: usize,
1265    runs_started: usize,
1266    ingested: usize,
1267    duplicates: usize,
1268    unidentifiable: usize,
1269    failures: Vec<String>,
1270    cursor: Option<String>,
1271    /// The payloads this firing produced, so a composite can pull its
1272    /// correlation value out of them.
1273    fired_items: Vec<serde_json::Value>,
1274    /// Correlation keys a composite consumed, cleared on release.
1275    settled_keys: Vec<String>,
1276    op_cursor: Option<i64>,
1277    draining: bool,
1278    seeded: bool,
1279    skipped_locked: bool,
1280}
1281
1282enum StartOutcome {
1283    Started,
1284    /// Recorded but not executed — no runtime is wired in.
1285    Ingested,
1286    Duplicate,
1287    Failed(String),
1288}
1289
1290/// The run id for one firing of one item.
1291///
1292/// Derived from `(trigger, connector, dedup value)`, so the same item seen
1293/// twice — connector replay, overlapping cursors, two nodes racing a lease
1294/// boundary — produces the same id. `areev run start` refuses a duplicate, so
1295/// the second attempt is a recorded skip rather than a second run. At-most-once
1296/// firing with no lease, no fencing token, and no clock assumption.
1297///
1298/// The connector is part of the identity because CloudEvents made that
1299/// normative for the same reason: `source` + `id` is unique, `id` alone is only
1300/// unique within a producer. Two connectors sharing an id space must not
1301/// collide.
1302pub fn run_id_for(trigger_hash: &str, connector: Option<&str>, dedup_value: &str) -> String {
1303    let mut h = Sha256::new();
1304    h.update(b"areev-trigger:v1");
1305    h.update([0x1f]);
1306    h.update(connector.unwrap_or_default().as_bytes());
1307    h.update([0x1f]);
1308    h.update(dedup_value.as_bytes());
1309    let digest = hex(&h.finalize());
1310    format!("{}-{}", short(trigger_hash, 8), short(&digest, 12))
1311}
1312
1313fn hex(bytes: &[u8]) -> String {
1314    bytes.iter().map(|b| format!("{b:02x}")).collect()
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320
1321    #[test]
1322    fn a_run_id_is_stable_for_the_same_item() {
1323        let a = run_id_for("abcdef1234", Some("gmail"), "m1");
1324        let b = run_id_for("abcdef1234", Some("gmail"), "m1");
1325        assert_eq!(a, b, "the same item must always mint the same id");
1326    }
1327
1328    #[test]
1329    fn different_items_get_different_ids() {
1330        let a = run_id_for("abcdef1234", Some("gmail"), "m1");
1331        let b = run_id_for("abcdef1234", Some("gmail"), "m2");
1332        assert_ne!(a, b);
1333    }
1334
1335    #[test]
1336    fn the_connector_is_part_of_the_identity() {
1337        // CloudEvents' rule: `id` alone is unique only within a producer, so two
1338        // connectors with a shared id space must not collide.
1339        let a = run_id_for("abcdef1234", Some("gmail"), "1");
1340        let b = run_id_for("abcdef1234", Some("stripe"), "1");
1341        assert_ne!(a, b);
1342    }
1343
1344    #[test]
1345    fn the_id_names_its_trigger_for_a_human_reading_a_run_list() {
1346        let id = run_id_for("abcdef1234567890", Some("gmail"), "m1");
1347        assert!(id.starts_with("abcdef12"), "{id}");
1348        assert!(id.len() < 32, "short enough to read: {id}");
1349    }
1350
1351    #[test]
1352    fn a_short_trigger_hash_does_not_panic() {
1353        let id = run_id_for("ab", None, "x");
1354        assert!(id.starts_with("ab-"));
1355    }
1356}