ff_core/contracts/mod.rs
1//! Phase 1 function contracts — Args + Result types for each FCALL.
2//!
3//! Each Args struct defines the typed inputs to a Valkey Function.
4//! Each Result enum defines the possible outcomes (success variants + error codes).
5
6pub mod decode;
7
8use crate::policy::ExecutionPolicy;
9use crate::state::{AttemptType, PublicState, StateVector};
10use crate::types::{
11 AttemptId, AttemptIndex, BudgetId, CancelSource, EdgeId, ExecutionId, FlowId, LaneId, LeaseEpoch,
12 LeaseFence, LeaseId, Namespace, SignalId, SuspensionId, TimestampMs, WaitpointId,
13 WaitpointToken, WorkerId, WorkerInstanceId,
14};
15use serde::{Deserialize, Serialize};
16use std::collections::{BTreeMap, BTreeSet, HashMap};
17
18// ─── create_execution ───
19
20#[derive(Clone, Debug, Serialize, Deserialize)]
21pub struct CreateExecutionArgs {
22 pub execution_id: ExecutionId,
23 pub namespace: Namespace,
24 pub lane_id: LaneId,
25 pub execution_kind: String,
26 pub input_payload: Vec<u8>,
27 #[serde(default)]
28 pub payload_encoding: Option<String>,
29 pub priority: i32,
30 pub creator_identity: String,
31 #[serde(default)]
32 pub idempotency_key: Option<String>,
33 #[serde(default)]
34 pub tags: HashMap<String, String>,
35 /// Execution policy (retry, timeout, suspension, routing, etc.).
36 #[serde(default)]
37 pub policy: Option<ExecutionPolicy>,
38 /// If set and in the future, execution starts delayed.
39 #[serde(default)]
40 pub delay_until: Option<TimestampMs>,
41 /// Absolute deadline timestamp (ms). Execution expires if not complete by this time.
42 #[serde(default)]
43 pub execution_deadline_at: Option<TimestampMs>,
44 /// Partition ID (pre-computed).
45 pub partition_id: u16,
46 pub now: TimestampMs,
47}
48
49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50pub enum CreateExecutionResult {
51 /// Execution created successfully.
52 Created {
53 execution_id: ExecutionId,
54 public_state: PublicState,
55 },
56 /// Idempotent duplicate — existing execution returned.
57 Duplicate { execution_id: ExecutionId },
58}
59
60// ─── issue_claim_grant ───
61
62/// Inputs to [`crate::engine_backend::EngineBackend::issue_claim_grant`]
63/// — the trait-level entry point v0.12 PR-5 lifted out of the SDK-side
64/// `FlowFabricWorker::claim_next` inline helper.
65///
66/// `#[non_exhaustive]` + `::new` per
67/// `feedback_non_exhaustive_needs_constructor`: future fields may be
68/// added in minor releases; consumers MUST construct via
69/// [`Self::new`] and populate optional fields (`capability_hash`,
70/// `route_snapshot_json`, `admission_summary`) by direct field
71/// assignment on the returned value. Struct-literal construction is
72/// blocked by `#[non_exhaustive]`; `..Default::default()` is not
73/// available for the same reason.
74///
75/// Carries the execution's [`crate::partition::Partition`] so the
76/// Valkey backend can derive `exec_core` / `claim_grant` / the lane's
77/// `eligible_zset` KEYS without a second round-trip.
78///
79/// Does NOT derive `Serialize` / `Deserialize` — this is a
80/// trait-boundary args struct, not a wire-format type; the
81/// `#[non_exhaustive]` marker already blocks cross-crate struct-
82/// literal construction, which matters more than JSON round-trip
83/// for a scanner hot-path primitive.
84#[derive(Clone, Debug)]
85#[non_exhaustive]
86pub struct IssueClaimGrantArgs {
87 pub execution_id: ExecutionId,
88 pub lane_id: LaneId,
89 pub worker_id: WorkerId,
90 pub worker_instance_id: WorkerInstanceId,
91 /// Partition context for KEYS derivation. v0.12 PR-5.
92 pub partition: crate::partition::Partition,
93 pub capability_hash: Option<String>,
94 pub route_snapshot_json: Option<String>,
95 pub admission_summary: Option<String>,
96 /// Capabilities this worker advertises. Serialized as a sorted,
97 /// comma-separated string to the Lua FCALL (see scheduling.lua
98 /// ff_issue_claim_grant). An empty set matches only executions whose
99 /// `required_capabilities` is also empty.
100 pub worker_capabilities: BTreeSet<String>,
101 pub grant_ttl_ms: u64,
102 /// Caller-side timestamp for bookkeeping. NOT passed to the Lua FCALL —
103 /// ff_issue_claim_grant uses `redis.call("TIME")` for grant_expires_at.
104 pub now: TimestampMs,
105}
106
107impl IssueClaimGrantArgs {
108 /// Construct an `IssueClaimGrantArgs`. Added alongside
109 /// `#[non_exhaustive]` per `feedback_non_exhaustive_needs_constructor`
110 /// so the SDK worker (and any future caller) can build the args
111 /// without the struct literal becoming a cross-crate breaking
112 /// change on every minor release.
113 #[allow(clippy::too_many_arguments)]
114 pub fn new(
115 execution_id: ExecutionId,
116 lane_id: LaneId,
117 worker_id: WorkerId,
118 worker_instance_id: WorkerInstanceId,
119 partition: crate::partition::Partition,
120 worker_capabilities: BTreeSet<String>,
121 grant_ttl_ms: u64,
122 now: TimestampMs,
123 ) -> Self {
124 Self {
125 execution_id,
126 lane_id,
127 worker_id,
128 worker_instance_id,
129 partition,
130 capability_hash: None,
131 route_snapshot_json: None,
132 admission_summary: None,
133 worker_capabilities,
134 grant_ttl_ms,
135 now,
136 }
137 }
138}
139
140/// Typed outcome of [`crate::engine_backend::EngineBackend::issue_claim_grant`].
141///
142/// Single-variant today — the Valkey FCALL either writes the grant
143/// and returns `Granted`, or the Lua reject (capability mismatch,
144/// already-granted, etc.) surfaces as a typed [`crate::engine_error::EngineError`]
145/// on the outer `Result`. `#[non_exhaustive]` reserves room for
146/// future additive variants without a breaking match-arm churn on
147/// consumers.
148#[derive(Clone, Debug, PartialEq, Eq)]
149#[non_exhaustive]
150pub enum IssueClaimGrantOutcome {
151 /// Grant issued.
152 Granted { execution_id: ExecutionId },
153}
154
155/// Legacy name for `IssueClaimGrantOutcome` — retained for
156/// `ff-script`'s `FromFcallResult` plumbing. Prefer
157/// [`IssueClaimGrantOutcome`] in trait-level code.
158#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159pub enum IssueClaimGrantResult {
160 /// Grant issued.
161 Granted { execution_id: ExecutionId },
162}
163
164// ─── scan_eligible_executions + block_route (v0.12 PR-5) ───
165
166/// Inputs to [`crate::engine_backend::EngineBackend::scan_eligible_executions`].
167///
168/// Lifted from the SDK-side `ZRANGEBYSCORE` inline on the
169/// `claim_next` scanner (v0.12 PR-5). The backend reads the lane's
170/// eligible ZSET on the given partition and returns up to `limit`
171/// execution ids in priority order (Valkey: score = `-(priority *
172/// 1e12) + created_at_ms`, so `+inf`-bounded ZRANGEBYSCORE with
173/// `LIMIT 0 <limit>` yields highest-priority-first).
174#[derive(Clone, Debug)]
175#[non_exhaustive]
176pub struct ScanEligibleArgs {
177 pub lane_id: LaneId,
178 pub partition: crate::partition::Partition,
179 /// Maximum number of execution ids to return. Backends MAY
180 /// return fewer when the partition has less work.
181 pub limit: u32,
182}
183
184impl ScanEligibleArgs {
185 /// Construct a `ScanEligibleArgs`. Added alongside
186 /// `#[non_exhaustive]` per
187 /// `feedback_non_exhaustive_needs_constructor`.
188 pub fn new(
189 lane_id: LaneId,
190 partition: crate::partition::Partition,
191 limit: u32,
192 ) -> Self {
193 Self {
194 lane_id,
195 partition,
196 limit,
197 }
198 }
199}
200
201/// Inputs to [`crate::engine_backend::EngineBackend::block_route`].
202///
203/// Lifted from the SDK-side `ff_block_execution_for_admission`
204/// inline helper on the `claim_next` scanner (v0.12 PR-5). Moves an
205/// execution from the lane's eligible ZSET into its blocked_route
206/// ZSET after a `CapabilityMismatch` reject — the engine's unblock
207/// scanner promotes blocked_route back to eligible once a worker
208/// with matching caps registers.
209#[derive(Clone, Debug)]
210#[non_exhaustive]
211pub struct BlockRouteArgs {
212 pub execution_id: ExecutionId,
213 pub lane_id: LaneId,
214 pub partition: crate::partition::Partition,
215 /// Free-form block reason code (e.g. `"waiting_for_capable_worker"`).
216 pub reason_code: String,
217 /// Human-readable reason detail for operator logs.
218 pub reason_detail: String,
219 pub now: TimestampMs,
220}
221
222impl BlockRouteArgs {
223 /// Construct a `BlockRouteArgs`.
224 pub fn new(
225 execution_id: ExecutionId,
226 lane_id: LaneId,
227 partition: crate::partition::Partition,
228 reason_code: String,
229 reason_detail: String,
230 now: TimestampMs,
231 ) -> Self {
232 Self {
233 execution_id,
234 lane_id,
235 partition,
236 reason_code,
237 reason_detail,
238 now,
239 }
240 }
241}
242
243/// Typed outcome of [`crate::engine_backend::EngineBackend::block_route`].
244///
245/// `LuaRejected` captures the logical-reject case (e.g. the execution
246/// went terminal between pick and block — eligible ZSET is left
247/// unchanged and the caller should simply `continue` to the next
248/// partition). Transport faults surface on the outer `Result` as
249/// [`crate::engine_error::EngineError::Transport`]; callers that
250/// want the pre-PR-5 "best-effort, log-and-continue" semantic wrap
251/// the call in a `match` and swallow non-success variants.
252#[derive(Clone, Debug, PartialEq, Eq)]
253#[non_exhaustive]
254pub enum BlockRouteOutcome {
255 /// Execution moved from eligible → blocked_route successfully.
256 Blocked { execution_id: ExecutionId },
257 /// Lua returned a non-success result (e.g. execution went
258 /// terminal between pick and block). `message` carries the Lua
259 /// reject code for operator visibility.
260 LuaRejected { message: String },
261}
262
263/// A claim grant issued by the scheduler for a specific execution.
264///
265/// The worker uses this to call `ff_claim_execution` (or
266/// `ff_acquire_lease`), which atomically consumes the grant and
267/// creates the lease.
268///
269/// Shared wire-level type between `ff-scheduler` (issuer) and
270/// `ff-sdk` (consumer, via `FlowFabricWorker::claim_from_grant`).
271/// Lives in `ff-core` so neither crate needs a dep on the other.
272///
273/// **Lane asymmetry with [`ResumeGrant`]:** `ClaimGrant` does NOT
274/// carry `lane_id`. The issuing scheduler's caller already picked
275/// a lane (that's how admission reached this grant) and passes it
276/// through to `claim_from_grant` as a separate argument. The grant
277/// handle stays narrow to what uniquely identifies the admission
278/// decision. The matching field on [`ResumeGrant`] is an
279/// intentional divergence — see the note on that type.
280#[derive(Clone, Debug, PartialEq, Eq)]
281#[non_exhaustive]
282pub struct ClaimGrant {
283 /// The execution that was granted.
284 pub execution_id: ExecutionId,
285 /// Opaque partition handle for this execution's hash-tag slot.
286 ///
287 /// Public wire type: consumers pass it back to FlowFabric but
288 /// must not parse the interior hash tag for routing decisions.
289 /// Internal consumers that need the typed
290 /// [`crate::partition::Partition`] call [`Self::partition`].
291 pub partition_key: crate::partition::PartitionKey,
292 /// The Valkey key holding the grant hash (for the worker to
293 /// reference).
294 pub grant_key: String,
295 /// When the grant expires if not consumed.
296 pub expires_at_ms: u64,
297}
298
299impl ClaimGrant {
300 /// Construct a fresh-claim grant. Added alongside `#[non_exhaustive]`
301 /// per RFC-024 §3.1 + `feedback_non_exhaustive_needs_constructor`.
302 pub fn new(
303 execution_id: ExecutionId,
304 partition_key: crate::partition::PartitionKey,
305 grant_key: String,
306 expires_at_ms: u64,
307 ) -> Self {
308 Self {
309 execution_id,
310 partition_key,
311 grant_key,
312 expires_at_ms,
313 }
314 }
315
316 /// Parse `partition_key` into a typed
317 /// [`crate::partition::Partition`]. Intended for internal
318 /// consumers (scheduler emitter, SDK worker claim path) that
319 /// need the family/index pair. Fails only on malformed keys
320 /// (which indicates a producer bug).
321 ///
322 /// Alias collapse applies: a grant issued against `Execution`
323 /// family round-trips to `Flow` (see [`crate::partition::PartitionKey`]
324 /// for the rationale — routing is preserved, only the metadata
325 /// family label normalises).
326 pub fn partition(
327 &self,
328 ) -> Result<crate::partition::Partition, crate::partition::PartitionKeyParseError> {
329 self.partition_key.parse()
330 }
331}
332
333/// A resume grant issued for a resumed (attempt_interrupted) execution.
334///
335/// Issued by a producer (typically `ff-scheduler` once a Batch-C
336/// reclaim scanner is in place; test fixtures in the interim — no
337/// production Rust caller exists in-tree today). Consumed by
338/// [`FlowFabricWorker::claim_from_resume_grant`], which calls
339/// `ff_claim_resumed_execution` atomically: that FCALL validates the
340/// grant, consumes it, and transitions `attempt_interrupted` →
341/// `started` while preserving the existing `attempt_index` +
342/// `attempt_id` (a resumed execution re-uses its attempt; it does
343/// not start a new one).
344///
345/// **Naming history (RFC-024).** This type was historically called
346/// `ReclaimGrant`, but its semantic has always been resume-after-
347/// suspend (the routing FCALL is `ff_claim_resumed_execution`, not
348/// `ff_reclaim_execution`). RFC-024 PR-A renamed the type to
349/// `ResumeGrant` — the name now matches the semantic. RFC-024 PR-B+C
350/// dropped the transitional `ReclaimGrant = ResumeGrant` alias and
351/// introduced a distinct new [`ReclaimGrant`] for the lease-reclaim
352/// path (`reclaim_execution` / `ff_reclaim_execution`).
353///
354/// Mirrors [`ClaimGrant`] for the resume path. Differences:
355///
356/// * [`ClaimGrant`] is issued against a freshly-eligible
357/// execution and `ff_claim_execution` creates a new attempt.
358/// * `ResumeGrant` is issued against an `attempt_interrupted`
359/// execution; `ff_claim_resumed_execution` re-uses the existing
360/// attempt and bumps the lease epoch.
361///
362/// The grant itself is written to the same `claim_grant` Valkey key
363/// that [`ClaimGrant`] uses; the distinction is which Lua FCALL
364/// consumes it (`ff_claim_execution` for new attempts,
365/// `ff_claim_resumed_execution` for resumes).
366///
367/// **Lane asymmetry with [`ClaimGrant`]:** `ResumeGrant` CARRIES
368/// `lane_id` as a field. The issuing path already knows the lane
369/// (it's read from `exec_core` at grant time); carrying it here
370/// spares the consumer a `HGET exec_core lane_id` round trip on
371/// the hot claim path. The asymmetry is intentional — prefer
372/// one-fewer-HGET on a type that already lives with the resumer's
373/// lifecycle over strict handle symmetry with `ClaimGrant`.
374///
375/// Shared wire-level type between the eventual `ff-scheduler`
376/// producer (Batch-C reclaim scanner — not yet in-tree; test
377/// fixtures construct this type today) and `ff-sdk` (consumer, via
378/// `FlowFabricWorker::claim_from_resume_grant`). Lives in
379/// `ff-core` so neither crate needs a dep on the other.
380///
381/// [`FlowFabricWorker::claim_from_resume_grant`]: https://docs.rs/ff-sdk
382#[derive(Clone, Debug, PartialEq, Eq)]
383#[non_exhaustive]
384pub struct ResumeGrant {
385 /// The execution granted for resumption.
386 pub execution_id: ExecutionId,
387 /// Opaque partition handle for this execution's hash-tag slot.
388 ///
389 /// Same wire-opacity contract as [`ClaimGrant::partition_key`].
390 /// Internal consumers call [`Self::partition`] for the parsed
391 /// form.
392 pub partition_key: crate::partition::PartitionKey,
393 /// Valkey key of the grant hash — same key shape as
394 /// [`ClaimGrant`].
395 pub grant_key: String,
396 /// Monotonic ms when the grant expires; unconsumed grants
397 /// vanish.
398 pub expires_at_ms: u64,
399 /// Lane the execution belongs to. Needed by
400 /// `ff_claim_resumed_execution` for `KEYS[3]` (eligible_zset)
401 /// and `KEYS[9]` (active_index).
402 pub lane_id: LaneId,
403}
404
405impl ResumeGrant {
406 /// Construct a resume grant. Added alongside `#[non_exhaustive]`
407 /// per RFC-024 §3.1 + `feedback_non_exhaustive_needs_constructor`.
408 pub fn new(
409 execution_id: ExecutionId,
410 partition_key: crate::partition::PartitionKey,
411 grant_key: String,
412 expires_at_ms: u64,
413 lane_id: LaneId,
414 ) -> Self {
415 Self {
416 execution_id,
417 partition_key,
418 grant_key,
419 expires_at_ms,
420 lane_id,
421 }
422 }
423
424 /// Parse `partition_key` into a typed
425 /// [`crate::partition::Partition`]. See [`ClaimGrant::partition`]
426 /// for the alias-collapse note.
427 pub fn partition(
428 &self,
429 ) -> Result<crate::partition::Partition, crate::partition::PartitionKeyParseError> {
430 self.partition_key.parse()
431 }
432}
433
434/// A lease-reclaim grant issued for an execution in
435/// `lease_expired_reclaimable` or `lease_revoked` state (RFC-024 §3.1).
436///
437/// Distinct from [`ResumeGrant`]: the reclaim grant routes to
438/// `ff_reclaim_execution` (Valkey) / the new-attempt reclaim impl
439/// (PG/SQLite), which creates a NEW attempt row and bumps the
440/// execution's `lease_reclaim_count`. The resume grant, by contrast,
441/// re-uses the existing attempt under `ff_claim_resumed_execution`.
442///
443/// Carries `lane_id` for symmetry with [`ResumeGrant`] — the Lua
444/// `ff_reclaim_execution` needs the lane for key construction, and
445/// the consuming worker would otherwise pay a round-trip to recover
446/// it from `exec_core`.
447///
448/// Backend impl bodies ship under PR-D (PG) / PR-E (SQLite) / PR-F
449/// (Valkey). This PR lands only the type + trait surface; default
450/// [`crate::engine_backend::EngineBackend::issue_reclaim_grant`] and
451/// [`crate::engine_backend::EngineBackend::reclaim_execution`] return
452/// [`crate::engine_error::EngineError::Unavailable`] until each
453/// backend PR wires its real body.
454#[derive(Clone, Debug, PartialEq, Eq)]
455#[non_exhaustive]
456pub struct ReclaimGrant {
457 /// The execution granted for lease-reclaim.
458 pub execution_id: ExecutionId,
459 /// Opaque partition handle for this execution's hash-tag slot.
460 pub partition_key: crate::partition::PartitionKey,
461 /// Backend-scoped grant key (Valkey key / PG+SQLite
462 /// `ff_claim_grant.grant_id`).
463 pub grant_key: String,
464 /// Monotonic ms when the grant expires; unconsumed grants vanish.
465 pub expires_at_ms: u64,
466 /// Lane the execution belongs to — needed by
467 /// `ff_reclaim_execution` for `KEYS[*]` construction.
468 pub lane_id: LaneId,
469}
470
471impl ReclaimGrant {
472 /// Construct a reclaim grant. Added alongside `#[non_exhaustive]`
473 /// per RFC-024 §3.1 + `feedback_non_exhaustive_needs_constructor`.
474 pub fn new(
475 execution_id: ExecutionId,
476 partition_key: crate::partition::PartitionKey,
477 grant_key: String,
478 expires_at_ms: u64,
479 lane_id: LaneId,
480 ) -> Self {
481 Self {
482 execution_id,
483 partition_key,
484 grant_key,
485 expires_at_ms,
486 lane_id,
487 }
488 }
489
490 /// Parse `partition_key` into a typed
491 /// [`crate::partition::Partition`].
492 pub fn partition(
493 &self,
494 ) -> Result<crate::partition::Partition, crate::partition::PartitionKeyParseError> {
495 self.partition_key.parse()
496 }
497}
498
499// ─── claim_execution ───
500
501#[derive(Clone, Debug, Serialize, Deserialize)]
502#[non_exhaustive]
503pub struct ClaimExecutionArgs {
504 pub execution_id: ExecutionId,
505 pub worker_id: WorkerId,
506 pub worker_instance_id: WorkerInstanceId,
507 pub lane_id: LaneId,
508 pub lease_id: LeaseId,
509 pub lease_ttl_ms: u64,
510 pub attempt_id: AttemptId,
511 /// Expected attempt index (pre-read from exec_core.total_attempt_count).
512 /// Used for KEYS construction — must match what the Lua computes.
513 pub expected_attempt_index: AttemptIndex,
514 /// JSON-encoded attempt policy snapshot.
515 #[serde(default)]
516 pub attempt_policy_json: String,
517 /// Per-attempt timeout in ms.
518 #[serde(default)]
519 pub attempt_timeout_ms: Option<u64>,
520 /// Total execution deadline (absolute timestamp ms).
521 #[serde(default)]
522 pub execution_deadline_at: Option<i64>,
523 pub now: TimestampMs,
524}
525
526impl ClaimExecutionArgs {
527 /// Construct a `ClaimExecutionArgs`. Added alongside
528 /// `#[non_exhaustive]` per `feedback_non_exhaustive_needs_constructor`
529 /// so consumers (SDK worker, backend impls) can still build the
530 /// args after the struct was sealed for forward-compat.
531 #[allow(clippy::too_many_arguments)]
532 pub fn new(
533 execution_id: ExecutionId,
534 worker_id: WorkerId,
535 worker_instance_id: WorkerInstanceId,
536 lane_id: LaneId,
537 lease_id: LeaseId,
538 lease_ttl_ms: u64,
539 attempt_id: AttemptId,
540 expected_attempt_index: AttemptIndex,
541 attempt_policy_json: String,
542 attempt_timeout_ms: Option<u64>,
543 execution_deadline_at: Option<i64>,
544 now: TimestampMs,
545 ) -> Self {
546 Self {
547 execution_id,
548 worker_id,
549 worker_instance_id,
550 lane_id,
551 lease_id,
552 lease_ttl_ms,
553 attempt_id,
554 expected_attempt_index,
555 attempt_policy_json,
556 attempt_timeout_ms,
557 execution_deadline_at,
558 now,
559 }
560 }
561}
562
563#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
564#[non_exhaustive]
565pub struct ClaimedExecution {
566 pub execution_id: ExecutionId,
567 pub lease_id: LeaseId,
568 pub lease_epoch: LeaseEpoch,
569 pub attempt_index: AttemptIndex,
570 pub attempt_id: AttemptId,
571 pub attempt_type: AttemptType,
572 pub lease_expires_at: TimestampMs,
573 /// Backend-populated attempt handle for this claim (v0.12 PR-5.5).
574 /// Valkey fills in an encoded `HandleKind::Fresh`; PG/SQLite are
575 /// `Unavailable` on `claim_execution` at runtime per
576 /// `project_claim_from_grant_pg_sqlite_gap.md`, so the field stays
577 /// a stub on those paths.
578 #[serde(default = "crate::backend::stub_handle_fresh")]
579 pub handle: crate::backend::Handle,
580}
581
582impl ClaimedExecution {
583 /// Construct a `ClaimedExecution`. Added alongside
584 /// `#[non_exhaustive]` per `feedback_non_exhaustive_needs_constructor`
585 /// so consumers (backend impls building a claim outcome) can still
586 /// build the struct after it was sealed for forward-compat.
587 #[allow(clippy::too_many_arguments)]
588 pub fn new(
589 execution_id: ExecutionId,
590 lease_id: LeaseId,
591 lease_epoch: LeaseEpoch,
592 attempt_index: AttemptIndex,
593 attempt_id: AttemptId,
594 attempt_type: AttemptType,
595 lease_expires_at: TimestampMs,
596 handle: crate::backend::Handle,
597 ) -> Self {
598 Self {
599 execution_id,
600 lease_id,
601 lease_epoch,
602 attempt_index,
603 attempt_id,
604 attempt_type,
605 lease_expires_at,
606 handle,
607 }
608 }
609}
610
611/// Typed outcome of [`crate::engine_backend::EngineBackend::claim_execution`].
612///
613/// Single-variant today; `#[non_exhaustive]` reserves room for future
614/// outcomes (e.g. an explicit `NoGrant` variant if RFC-024 splits it
615/// out of `InvalidClaimGrant`) without a breaking match-arm churn on
616/// consumers.
617#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
618#[non_exhaustive]
619pub enum ClaimExecutionResult {
620 /// Successfully claimed.
621 Claimed(ClaimedExecution),
622}
623
624// ─── complete_execution ───
625
626#[derive(Clone, Debug, Serialize, Deserialize)]
627pub struct CompleteExecutionArgs {
628 pub execution_id: ExecutionId,
629 /// RFC #58.5 — fence triple. `Some` for SDK worker paths (standard
630 /// stale-lease fence). `None` for operator overrides, in which case
631 /// `source` must be `CancelSource::OperatorOverride` or the Lua
632 /// returns `fence_required`.
633 #[serde(default)]
634 pub fence: Option<LeaseFence>,
635 pub attempt_index: AttemptIndex,
636 #[serde(default)]
637 pub result_payload: Option<Vec<u8>>,
638 #[serde(default)]
639 pub result_encoding: Option<String>,
640 /// RFC #58.5 — unfenced-call gate. Ignored when `fence` is `Some`.
641 #[serde(default)]
642 pub source: CancelSource,
643 pub now: TimestampMs,
644}
645
646#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
647pub enum CompleteExecutionResult {
648 /// Execution completed successfully.
649 Completed {
650 execution_id: ExecutionId,
651 public_state: PublicState,
652 },
653}
654
655// ─── renew_lease ───
656
657#[derive(Clone, Debug, Serialize, Deserialize)]
658pub struct RenewLeaseArgs {
659 pub execution_id: ExecutionId,
660 pub attempt_index: AttemptIndex,
661 /// RFC #58.5 — fence triple. Required (no operator override path for
662 /// renew). `None` returns `fence_required`.
663 pub fence: Option<LeaseFence>,
664 /// How long to extend the lease (milliseconds).
665 pub lease_ttl_ms: u64,
666 /// Grace period after lease_expires_at before the lease_current key is auto-deleted.
667 #[serde(default = "default_lease_history_grace_ms")]
668 pub lease_history_grace_ms: u64,
669}
670
671fn default_lease_history_grace_ms() -> u64 {
672 60_000
673}
674
675#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
676pub enum RenewLeaseResult {
677 /// Lease renewed.
678 Renewed { expires_at: TimestampMs },
679}
680
681// ─── mark_lease_expired_if_due ───
682
683#[derive(Clone, Debug, Serialize, Deserialize)]
684pub struct MarkLeaseExpiredArgs {
685 pub execution_id: ExecutionId,
686}
687
688#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
689pub enum MarkLeaseExpiredResult {
690 /// Lease was marked as expired.
691 MarkedExpired,
692 /// No action needed (already expired, not yet due, not active, etc.).
693 AlreadySatisfied { reason: String },
694}
695
696// ─── cancel_execution ───
697
698#[derive(Clone, Debug, Serialize, Deserialize)]
699pub struct CancelExecutionArgs {
700 pub execution_id: ExecutionId,
701 pub reason: String,
702 #[serde(default)]
703 pub source: CancelSource,
704 /// Required if not operator_override and execution is active.
705 #[serde(default)]
706 pub lease_id: Option<LeaseId>,
707 #[serde(default)]
708 pub lease_epoch: Option<LeaseEpoch>,
709 /// Required if not operator_override and execution is active.
710 #[serde(default)]
711 pub attempt_id: Option<AttemptId>,
712 pub now: TimestampMs,
713}
714
715#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
716pub enum CancelExecutionResult {
717 /// Execution cancelled.
718 Cancelled {
719 execution_id: ExecutionId,
720 public_state: PublicState,
721 },
722}
723
724// ─── revoke_lease ───
725
726#[derive(Clone, Debug, Serialize, Deserialize)]
727pub struct RevokeLeaseArgs {
728 pub execution_id: ExecutionId,
729 /// If set, only revoke if this matches the current lease. Empty string skips check.
730 #[serde(default)]
731 pub expected_lease_id: Option<String>,
732 /// Worker instance whose lease set to clean up. Read from exec_core before calling.
733 pub worker_instance_id: WorkerInstanceId,
734 pub reason: String,
735}
736
737#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
738pub enum RevokeLeaseResult {
739 /// Lease revoked.
740 Revoked {
741 lease_id: String,
742 lease_epoch: String,
743 },
744 /// Already revoked or expired — no action needed.
745 AlreadySatisfied { reason: String },
746}
747
748// ─── delay_execution ───
749
750#[derive(Clone, Debug, Serialize, Deserialize)]
751pub struct DelayExecutionArgs {
752 pub execution_id: ExecutionId,
753 /// RFC #58.5 — fence triple. `None` requires `source ==
754 /// CancelSource::OperatorOverride`.
755 #[serde(default)]
756 pub fence: Option<LeaseFence>,
757 pub attempt_index: AttemptIndex,
758 pub delay_until: TimestampMs,
759 #[serde(default)]
760 pub source: CancelSource,
761 pub now: TimestampMs,
762}
763
764#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
765pub enum DelayExecutionResult {
766 /// Execution delayed.
767 Delayed {
768 execution_id: ExecutionId,
769 public_state: PublicState,
770 },
771}
772
773// ─── move_to_waiting_children ───
774
775#[derive(Clone, Debug, Serialize, Deserialize)]
776pub struct MoveToWaitingChildrenArgs {
777 pub execution_id: ExecutionId,
778 /// RFC #58.5 — fence triple. `None` requires `source ==
779 /// CancelSource::OperatorOverride`.
780 #[serde(default)]
781 pub fence: Option<LeaseFence>,
782 pub attempt_index: AttemptIndex,
783 #[serde(default)]
784 pub source: CancelSource,
785 pub now: TimestampMs,
786}
787
788#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
789pub enum MoveToWaitingChildrenResult {
790 /// Moved to waiting children.
791 Moved {
792 execution_id: ExecutionId,
793 public_state: PublicState,
794 },
795}
796
797// ─── change_priority ───
798
799#[derive(Clone, Debug, Serialize, Deserialize)]
800pub struct ChangePriorityArgs {
801 pub execution_id: ExecutionId,
802 pub new_priority: i32,
803 pub lane_id: LaneId,
804 pub now: TimestampMs,
805}
806
807#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
808pub enum ChangePriorityResult {
809 /// Priority changed and re-scored.
810 Changed { execution_id: ExecutionId },
811}
812
813// ─── update_progress ───
814
815#[derive(Clone, Debug, Serialize, Deserialize)]
816pub struct UpdateProgressArgs {
817 pub execution_id: ExecutionId,
818 pub lease_id: LeaseId,
819 pub lease_epoch: LeaseEpoch,
820 pub attempt_id: AttemptId,
821 #[serde(default)]
822 pub progress_pct: Option<u8>,
823 #[serde(default)]
824 pub progress_message: Option<String>,
825 pub now: TimestampMs,
826}
827
828#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
829pub enum UpdateProgressResult {
830 /// Progress updated.
831 Updated,
832}
833
834// ═══════════════════════════════════════════════════════════════════════
835// Phase 2 contracts: fail, reclaim, expire
836// ═══════════════════════════════════════════════════════════════════════
837
838// ─── fail_execution ───
839
840#[derive(Clone, Debug, Serialize, Deserialize)]
841pub struct FailExecutionArgs {
842 pub execution_id: ExecutionId,
843 /// RFC #58.5 — fence triple. `None` requires `source ==
844 /// CancelSource::OperatorOverride`.
845 #[serde(default)]
846 pub fence: Option<LeaseFence>,
847 pub attempt_index: AttemptIndex,
848 pub failure_reason: String,
849 pub failure_category: String,
850 /// JSON-encoded retry policy (from execution policy). Empty = no retries.
851 #[serde(default)]
852 pub retry_policy_json: String,
853 /// JSON-encoded attempt policy for the next retry attempt.
854 #[serde(default)]
855 pub next_attempt_policy_json: String,
856 #[serde(default)]
857 pub source: CancelSource,
858}
859
860/// Outcome of a fail_execution call.
861#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
862pub enum FailExecutionResult {
863 /// Retry was scheduled — execution is delayed with backoff.
864 RetryScheduled {
865 delay_until: TimestampMs,
866 next_attempt_index: AttemptIndex,
867 },
868 /// No retries left — execution is terminal failed.
869 TerminalFailed,
870}
871
872// ─── issue_reclaim_grant ───
873
874#[derive(Clone, Debug, Serialize, Deserialize)]
875#[non_exhaustive]
876pub struct IssueReclaimGrantArgs {
877 pub execution_id: ExecutionId,
878 pub worker_id: WorkerId,
879 pub worker_instance_id: WorkerInstanceId,
880 pub lane_id: LaneId,
881 #[serde(default)]
882 pub capability_hash: Option<String>,
883 pub grant_ttl_ms: u64,
884 #[serde(default)]
885 pub route_snapshot_json: Option<String>,
886 #[serde(default)]
887 pub admission_summary: Option<String>,
888 /// Worker capabilities (parity with `IssueClaimGrantArgs`). The
889 /// Lua primitive `ff_issue_reclaim_grant` reads these at ARGV[9].
890 /// Populated by the SDK admin path from the registered worker's
891 /// `WorkerRegistration::capabilities` per RFC-024 §3.2 (B-2).
892 #[serde(default)]
893 pub worker_capabilities: BTreeSet<String>,
894 /// Caller-side timestamp for bookkeeping. NOT passed to the Lua FCALL —
895 /// ff_issue_reclaim_grant uses `redis.call("TIME")` for grant_expires_at
896 /// (same as ff_issue_claim_grant). Kept for contract symmetry with
897 /// IssueClaimGrantArgs and scheduler audit logging.
898 pub now: TimestampMs,
899}
900
901impl IssueReclaimGrantArgs {
902 /// Construct an `IssueReclaimGrantArgs`. Added alongside
903 /// `#[non_exhaustive]` per RFC-024 §3.2 +
904 /// `feedback_non_exhaustive_needs_constructor`.
905 #[allow(clippy::too_many_arguments)]
906 pub fn new(
907 execution_id: ExecutionId,
908 worker_id: WorkerId,
909 worker_instance_id: WorkerInstanceId,
910 lane_id: LaneId,
911 capability_hash: Option<String>,
912 grant_ttl_ms: u64,
913 route_snapshot_json: Option<String>,
914 admission_summary: Option<String>,
915 worker_capabilities: BTreeSet<String>,
916 now: TimestampMs,
917 ) -> Self {
918 Self {
919 execution_id,
920 worker_id,
921 worker_instance_id,
922 lane_id,
923 capability_hash,
924 grant_ttl_ms,
925 route_snapshot_json,
926 admission_summary,
927 worker_capabilities,
928 now,
929 }
930 }
931}
932
933#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
934pub enum IssueReclaimGrantResult {
935 /// Reclaim grant issued.
936 Granted { expires_at_ms: TimestampMs },
937}
938
939/// Typed outcome of [`crate::engine_backend::EngineBackend::issue_reclaim_grant`]
940/// (RFC-024 §3.2).
941///
942/// Construction surface: backends produce variants; consumers match
943/// on variants. No `::new()` — variants ARE the surface.
944#[derive(Clone, Debug, PartialEq, Eq)]
945#[non_exhaustive]
946pub enum IssueReclaimGrantOutcome {
947 /// Grant issued — hand the carried [`ReclaimGrant`] to
948 /// [`crate::engine_backend::EngineBackend::reclaim_execution`].
949 Granted(ReclaimGrant),
950 /// Execution is not in a reclaimable state (not
951 /// `lease_expired_reclaimable` / `lease_revoked`).
952 NotReclaimable {
953 execution_id: ExecutionId,
954 detail: String,
955 },
956 /// `max_reclaim_count` exceeded; execution transitioned to
957 /// terminal_failed by the backend primitive.
958 ReclaimCapExceeded {
959 execution_id: ExecutionId,
960 reclaim_count: u32,
961 },
962}
963
964// ─── reclaim_execution ───
965
966#[derive(Clone, Debug, Serialize, Deserialize)]
967#[non_exhaustive]
968pub struct ReclaimExecutionArgs {
969 pub execution_id: ExecutionId,
970 pub worker_id: WorkerId,
971 pub worker_instance_id: WorkerInstanceId,
972 pub lane_id: LaneId,
973 #[serde(default)]
974 pub capability_hash: Option<String>,
975 pub lease_id: LeaseId,
976 pub lease_ttl_ms: u64,
977 pub attempt_id: AttemptId,
978 /// JSON-encoded attempt policy for the reclaim attempt.
979 #[serde(default)]
980 pub attempt_policy_json: String,
981 /// Maximum reclaim count before terminal failure. `None` ⇒ backend
982 /// applies the Rust-surface default of 1000 per RFC-024 §4.6. The
983 /// Lua fallback remains 100 for pre-RFC ARGV-omitted call sites;
984 /// the two-default coexistence is explicit by design.
985 #[serde(default)]
986 pub max_reclaim_count: Option<u32>,
987 /// Old worker instance (for old_worker_leases key construction).
988 pub old_worker_instance_id: WorkerInstanceId,
989 /// Current attempt index (for old_attempt/old_stream_meta key construction).
990 pub current_attempt_index: AttemptIndex,
991}
992
993impl ReclaimExecutionArgs {
994 /// Construct a `ReclaimExecutionArgs`. Added alongside
995 /// `#[non_exhaustive]` per RFC-024 §3.2 +
996 /// `feedback_non_exhaustive_needs_constructor`.
997 #[allow(clippy::too_many_arguments)]
998 pub fn new(
999 execution_id: ExecutionId,
1000 worker_id: WorkerId,
1001 worker_instance_id: WorkerInstanceId,
1002 lane_id: LaneId,
1003 capability_hash: Option<String>,
1004 lease_id: LeaseId,
1005 lease_ttl_ms: u64,
1006 attempt_id: AttemptId,
1007 attempt_policy_json: String,
1008 max_reclaim_count: Option<u32>,
1009 old_worker_instance_id: WorkerInstanceId,
1010 current_attempt_index: AttemptIndex,
1011 ) -> Self {
1012 Self {
1013 execution_id,
1014 worker_id,
1015 worker_instance_id,
1016 lane_id,
1017 capability_hash,
1018 lease_id,
1019 lease_ttl_ms,
1020 attempt_id,
1021 attempt_policy_json,
1022 max_reclaim_count,
1023 old_worker_instance_id,
1024 current_attempt_index,
1025 }
1026 }
1027}
1028
1029/// Typed outcome of [`crate::engine_backend::EngineBackend::reclaim_execution`]
1030/// (RFC-024 §3.2).
1031///
1032/// Distinct from the wire-level [`ReclaimExecutionResult`]; this enum
1033/// is the trait-surface shape consumers match on.
1034#[derive(Clone, Debug, PartialEq, Eq)]
1035#[non_exhaustive]
1036pub enum ReclaimExecutionOutcome {
1037 /// Execution reclaimed — carries the new-attempt
1038 /// [`crate::backend::Handle`] (kind = `Reclaimed`).
1039 Claimed(crate::backend::Handle),
1040 /// Execution is not in a reclaimable state.
1041 NotReclaimable {
1042 execution_id: ExecutionId,
1043 detail: String,
1044 },
1045 /// `max_reclaim_count` exceeded; execution transitioned to
1046 /// terminal_failed.
1047 ReclaimCapExceeded {
1048 execution_id: ExecutionId,
1049 reclaim_count: u32,
1050 },
1051 /// The supplied grant was not found / already consumed / expired.
1052 GrantNotFound { execution_id: ExecutionId },
1053}
1054
1055#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1056pub enum ReclaimExecutionResult {
1057 /// Execution reclaimed — new attempt + new lease.
1058 Reclaimed {
1059 new_attempt_index: AttemptIndex,
1060 new_attempt_id: AttemptId,
1061 new_lease_id: LeaseId,
1062 new_lease_epoch: LeaseEpoch,
1063 lease_expires_at: TimestampMs,
1064 },
1065 /// Max reclaims exceeded — execution moved to terminal.
1066 MaxReclaimsExceeded,
1067}
1068
1069// ─── expire_execution ───
1070
1071#[derive(Clone, Debug, Serialize, Deserialize)]
1072pub struct ExpireExecutionArgs {
1073 pub execution_id: ExecutionId,
1074 /// "attempt_timeout" or "execution_deadline"
1075 pub expire_reason: String,
1076}
1077
1078#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1079pub enum ExpireExecutionResult {
1080 /// Execution expired.
1081 Expired { execution_id: ExecutionId },
1082 /// Already terminal — no-op.
1083 AlreadyTerminal,
1084}
1085
1086// ═══════════════════════════════════════════════════════════════════════
1087// Phase 3 contracts: suspend, signal, resume, waitpoint
1088// ═══════════════════════════════════════════════════════════════════════
1089
1090// ─── suspend_execution ───
1091
1092#[derive(Clone, Debug, Serialize, Deserialize)]
1093pub struct SuspendExecutionArgs {
1094 pub execution_id: ExecutionId,
1095 /// RFC #58.5 — fence triple. Required (no operator override path for
1096 /// suspend). `None` returns `fence_required`.
1097 pub fence: Option<LeaseFence>,
1098 pub attempt_index: AttemptIndex,
1099 pub suspension_id: SuspensionId,
1100 pub waitpoint_id: WaitpointId,
1101 pub waitpoint_key: String,
1102 pub reason_code: String,
1103 pub requested_by: String,
1104 pub resume_condition_json: String,
1105 pub resume_policy_json: String,
1106 #[serde(default)]
1107 pub continuation_metadata_pointer: Option<String>,
1108 #[serde(default)]
1109 pub timeout_at: Option<TimestampMs>,
1110 /// true to activate a pending waitpoint, false to create new.
1111 #[serde(default)]
1112 pub use_pending_waitpoint: bool,
1113 /// Timeout behavior: "fail", "cancel", "expire", "auto_resume", "escalate".
1114 #[serde(default = "default_timeout_behavior")]
1115 pub timeout_behavior: String,
1116}
1117
1118fn default_timeout_behavior() -> String {
1119 "fail".to_owned()
1120}
1121
1122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1123pub enum SuspendExecutionResult {
1124 /// Execution suspended, waitpoint active.
1125 Suspended {
1126 suspension_id: SuspensionId,
1127 waitpoint_id: WaitpointId,
1128 waitpoint_key: String,
1129 /// HMAC-SHA1 token bound to (waitpoint_id, waitpoint_key, created_at).
1130 /// Required by signal-delivery callers to authenticate against this
1131 /// waitpoint (RFC-004 §Waitpoint Security).
1132 waitpoint_token: WaitpointToken,
1133 },
1134 /// Buffered signals already satisfied the condition — suspension skipped.
1135 /// Lease is still held. Token comes from the pending waitpoint record.
1136 AlreadySatisfied {
1137 suspension_id: SuspensionId,
1138 waitpoint_id: WaitpointId,
1139 waitpoint_key: String,
1140 waitpoint_token: WaitpointToken,
1141 },
1142}
1143
1144// ─── resume_execution ───
1145
1146#[derive(Clone, Debug, Serialize, Deserialize)]
1147pub struct ResumeExecutionArgs {
1148 pub execution_id: ExecutionId,
1149 /// "signal", "operator", "auto_resume"
1150 #[serde(default = "default_trigger_type")]
1151 pub trigger_type: String,
1152 /// Optional delay before becoming eligible (ms).
1153 #[serde(default)]
1154 pub resume_delay_ms: u64,
1155}
1156
1157fn default_trigger_type() -> String {
1158 "signal".to_owned()
1159}
1160
1161#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1162pub enum ResumeExecutionResult {
1163 /// Execution resumed to runnable.
1164 Resumed { public_state: PublicState },
1165}
1166
1167// ─── create_pending_waitpoint ───
1168
1169#[derive(Clone, Debug, Serialize, Deserialize)]
1170pub struct CreatePendingWaitpointArgs {
1171 pub execution_id: ExecutionId,
1172 pub lease_id: LeaseId,
1173 pub lease_epoch: LeaseEpoch,
1174 pub attempt_index: AttemptIndex,
1175 pub attempt_id: AttemptId,
1176 pub waitpoint_id: WaitpointId,
1177 pub waitpoint_key: String,
1178 /// Short expiry for the pending waitpoint (ms).
1179 pub expires_in_ms: u64,
1180}
1181
1182#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1183pub enum CreatePendingWaitpointResult {
1184 /// Pending waitpoint created.
1185 Created {
1186 waitpoint_id: WaitpointId,
1187 waitpoint_key: String,
1188 /// HMAC-SHA1 token bound to the pending waitpoint. Required for
1189 /// `buffer_signal_for_pending_waitpoint` and carried forward when
1190 /// the waitpoint is activated by `suspend_execution`.
1191 waitpoint_token: WaitpointToken,
1192 },
1193}
1194
1195// ─── close_waitpoint ───
1196
1197#[derive(Clone, Debug, Serialize, Deserialize)]
1198pub struct CloseWaitpointArgs {
1199 pub waitpoint_id: WaitpointId,
1200 pub reason: String,
1201}
1202
1203#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1204pub enum CloseWaitpointResult {
1205 /// Waitpoint closed.
1206 Closed,
1207}
1208
1209// ─── deliver_signal ───
1210
1211#[derive(Clone, Debug, Serialize, Deserialize)]
1212pub struct DeliverSignalArgs {
1213 pub execution_id: ExecutionId,
1214 pub waitpoint_id: WaitpointId,
1215 pub signal_id: SignalId,
1216 pub signal_name: String,
1217 pub signal_category: String,
1218 pub source_type: String,
1219 pub source_identity: String,
1220 #[serde(default)]
1221 pub payload: Option<Vec<u8>>,
1222 #[serde(default)]
1223 pub payload_encoding: Option<String>,
1224 #[serde(default)]
1225 pub correlation_id: Option<String>,
1226 #[serde(default)]
1227 pub idempotency_key: Option<String>,
1228 pub target_scope: String,
1229 #[serde(default)]
1230 pub created_at: Option<TimestampMs>,
1231 /// Dedup TTL for idempotency key (ms).
1232 #[serde(default)]
1233 pub dedup_ttl_ms: Option<u64>,
1234 /// Resume delay after signal satisfaction (ms).
1235 #[serde(default)]
1236 pub resume_delay_ms: Option<u64>,
1237 /// Max signals per execution (default 10000).
1238 #[serde(default)]
1239 pub max_signals_per_execution: Option<u64>,
1240 /// MAXLEN for the waitpoint signal stream.
1241 #[serde(default)]
1242 pub signal_maxlen: Option<u64>,
1243 /// HMAC-SHA1 token issued when the waitpoint was created. Required for
1244 /// signal delivery; missing/tampered/rotated-past-grace tokens are
1245 /// rejected with `invalid_token` or `token_expired` (RFC-004).
1246 ///
1247 /// Defense-in-depth: `WaitpointToken` is a transparent string newtype,
1248 /// so an empty string deserializes successfully from JSON. The
1249 /// validation boundary is in Lua (`validate_waitpoint_token` returns
1250 /// `missing_token` on empty input); this type intentionally does NOT
1251 /// pre-reject at the Rust layer so callers get a consistent typed
1252 /// error regardless of how they constructed the args.
1253 pub waitpoint_token: WaitpointToken,
1254 pub now: TimestampMs,
1255}
1256
1257#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1258pub enum DeliverSignalResult {
1259 /// Signal accepted with the given effect.
1260 Accepted { signal_id: SignalId, effect: String },
1261 /// Duplicate signal (idempotency key matched).
1262 Duplicate { existing_signal_id: SignalId },
1263}
1264
1265// ─── buffer_signal_for_pending_waitpoint ───
1266
1267#[derive(Clone, Debug, Serialize, Deserialize)]
1268pub struct BufferSignalArgs {
1269 pub execution_id: ExecutionId,
1270 pub waitpoint_id: WaitpointId,
1271 pub signal_id: SignalId,
1272 pub signal_name: String,
1273 pub signal_category: String,
1274 pub source_type: String,
1275 pub source_identity: String,
1276 #[serde(default)]
1277 pub payload: Option<Vec<u8>>,
1278 #[serde(default)]
1279 pub payload_encoding: Option<String>,
1280 #[serde(default)]
1281 pub idempotency_key: Option<String>,
1282 pub target_scope: String,
1283 /// HMAC-SHA1 token issued when `create_pending_waitpoint` ran. Required
1284 /// to authenticate early signals targeting the pending waitpoint.
1285 pub waitpoint_token: WaitpointToken,
1286 pub now: TimestampMs,
1287}
1288
1289#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1290pub enum BufferSignalResult {
1291 /// Signal buffered for pending waitpoint.
1292 Buffered { signal_id: SignalId },
1293 /// Duplicate signal.
1294 Duplicate { existing_signal_id: SignalId },
1295}
1296
1297// ─── list_pending_waitpoints ───
1298
1299/// One entry in the read-only view of an execution's active waitpoints.
1300///
1301/// Returned by `EngineBackend::list_pending_waitpoints` (and the
1302/// `GET /v1/executions/{id}/pending-waitpoints` REST endpoint).
1303///
1304/// **RFC-017 §8 schema rewrite (Stage D1).** This struct no longer
1305/// carries the raw HMAC `waitpoint_token` at the trait boundary — the
1306/// backend emits only the sanitised `(token_kid, token_fingerprint)`
1307/// pair. The HTTP handler (see `ff-server::api::list_pending_waitpoints`)
1308/// wraps the trait response and re-injects the real token on the
1309/// v0.7.x wire for one-release deprecation warning; the wire field is
1310/// removed entirely at v0.8.0.
1311#[non_exhaustive]
1312#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1313pub struct PendingWaitpointInfo {
1314 pub waitpoint_id: WaitpointId,
1315 pub waitpoint_key: String,
1316 /// Current waitpoint state: `pending`, `active`, `closed`. Callers
1317 /// typically filter to `pending` or `active`.
1318 pub state: String,
1319 /// Signal names the resume condition is waiting for. Reviewers that
1320 /// need to drive a specific waitpoint — particularly when multiple
1321 /// concurrent waitpoints exist on one execution — filter on this to
1322 /// pick the right target.
1323 ///
1324 /// An EMPTY vec means the condition matches any signal (wildcard, per
1325 /// `lua/helpers.lua` `initialize_condition`). Callers must not infer
1326 /// "no waitpoint" from empty; check `state` / length of the outer
1327 /// list for that.
1328 #[serde(default)]
1329 pub required_signal_names: Vec<String>,
1330 /// Timestamp when the waitpoint record was first written.
1331 pub created_at: TimestampMs,
1332 /// Timestamp when the waitpoint was activated (suspension landed).
1333 /// `None` while the waitpoint is still `pending`.
1334 #[serde(default, skip_serializing_if = "Option::is_none")]
1335 pub activated_at: Option<TimestampMs>,
1336 /// Scheduled expiration timestamp. `None` if no timeout configured.
1337 #[serde(default, skip_serializing_if = "Option::is_none")]
1338 pub expires_at: Option<TimestampMs>,
1339 /// Owning execution — surfaces without a separate lookup.
1340 pub execution_id: ExecutionId,
1341 /// HMAC key identifier (the `<kid>` prefix of the stored
1342 /// `waitpoint_token`). Safe to expose — identifies which signing
1343 /// key minted the token without revealing the key material.
1344 pub token_kid: String,
1345 /// 16-hex-char (8-byte) fingerprint of the HMAC digest. Audit-friendly
1346 /// handle that correlates across logs without being replayable.
1347 pub token_fingerprint: String,
1348}
1349
1350impl PendingWaitpointInfo {
1351 /// Construct a `PendingWaitpointInfo` with the 7 required fields.
1352 /// Optional fields (`activated_at`, `expires_at`) default to
1353 /// `None`; use [`Self::with_activated_at`] / [`Self::with_expires_at`]
1354 /// to populate them. `required_signal_names` defaults to empty
1355 /// (wildcard condition); use [`Self::with_required_signal_names`]
1356 /// to set it.
1357 pub fn new(
1358 waitpoint_id: WaitpointId,
1359 waitpoint_key: String,
1360 state: String,
1361 created_at: TimestampMs,
1362 execution_id: ExecutionId,
1363 token_kid: String,
1364 token_fingerprint: String,
1365 ) -> Self {
1366 Self {
1367 waitpoint_id,
1368 waitpoint_key,
1369 state,
1370 required_signal_names: Vec::new(),
1371 created_at,
1372 activated_at: None,
1373 expires_at: None,
1374 execution_id,
1375 token_kid,
1376 token_fingerprint,
1377 }
1378 }
1379
1380 pub fn with_activated_at(mut self, activated_at: TimestampMs) -> Self {
1381 self.activated_at = Some(activated_at);
1382 self
1383 }
1384
1385 pub fn with_expires_at(mut self, expires_at: TimestampMs) -> Self {
1386 self.expires_at = Some(expires_at);
1387 self
1388 }
1389
1390 pub fn with_required_signal_names(mut self, names: Vec<String>) -> Self {
1391 self.required_signal_names = names;
1392 self
1393 }
1394}
1395
1396// ─── expire_suspension ───
1397
1398#[derive(Clone, Debug, Serialize, Deserialize)]
1399pub struct ExpireSuspensionArgs {
1400 pub execution_id: ExecutionId,
1401}
1402
1403#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1404pub enum ExpireSuspensionResult {
1405 /// Suspension expired with the given behavior applied.
1406 Expired { behavior_applied: String },
1407 /// Already resolved — no action needed.
1408 AlreadySatisfied { reason: String },
1409}
1410
1411// ─── claim_resumed_execution ───
1412
1413#[derive(Clone, Debug, Serialize, Deserialize)]
1414pub struct ClaimResumedExecutionArgs {
1415 pub execution_id: ExecutionId,
1416 pub worker_id: WorkerId,
1417 pub worker_instance_id: WorkerInstanceId,
1418 pub lane_id: LaneId,
1419 pub lease_id: LeaseId,
1420 pub lease_ttl_ms: u64,
1421 /// Current attempt index (for KEYS construction — from exec_core).
1422 pub current_attempt_index: AttemptIndex,
1423 /// Remaining attempt timeout from before suspension (ms). 0 = no timeout.
1424 #[serde(default)]
1425 pub remaining_attempt_timeout_ms: Option<u64>,
1426 pub now: TimestampMs,
1427}
1428
1429#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1430#[non_exhaustive]
1431pub struct ClaimedResumedExecution {
1432 pub execution_id: ExecutionId,
1433 pub lease_id: LeaseId,
1434 pub lease_epoch: LeaseEpoch,
1435 pub attempt_index: AttemptIndex,
1436 pub attempt_id: AttemptId,
1437 pub lease_expires_at: TimestampMs,
1438 /// Backend-populated attempt handle for this resumed claim
1439 /// (v0.12 PR-5.5). Valkey fills in `HandleKind::Resumed`; PG/SQLite
1440 /// populate a backend-tagged real handle via
1441 /// `ff_core::handle_codec::encode`.
1442 #[serde(default = "crate::backend::stub_handle_resumed")]
1443 pub handle: crate::backend::Handle,
1444}
1445
1446impl ClaimedResumedExecution {
1447 /// Construct a `ClaimedResumedExecution`. Added alongside
1448 /// `#[non_exhaustive]` per `feedback_non_exhaustive_needs_constructor`
1449 /// so consumers (backend impls building a resumed-claim outcome)
1450 /// can still build the struct after it was sealed for forward-compat.
1451 #[allow(clippy::too_many_arguments)]
1452 pub fn new(
1453 execution_id: ExecutionId,
1454 lease_id: LeaseId,
1455 lease_epoch: LeaseEpoch,
1456 attempt_index: AttemptIndex,
1457 attempt_id: AttemptId,
1458 lease_expires_at: TimestampMs,
1459 handle: crate::backend::Handle,
1460 ) -> Self {
1461 Self {
1462 execution_id,
1463 lease_id,
1464 lease_epoch,
1465 attempt_index,
1466 attempt_id,
1467 lease_expires_at,
1468 handle,
1469 }
1470 }
1471}
1472
1473#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1474pub enum ClaimResumedExecutionResult {
1475 /// Successfully claimed resumed execution (same attempt continues).
1476 Claimed(ClaimedResumedExecution),
1477}
1478
1479// ═══════════════════════════════════════════════════════════════════════
1480// Phase 4 contracts: stream
1481// ═══════════════════════════════════════════════════════════════════════
1482
1483// ─── append_frame ───
1484
1485#[derive(Clone, Debug, Serialize, Deserialize)]
1486pub struct AppendFrameArgs {
1487 pub execution_id: ExecutionId,
1488 pub attempt_index: AttemptIndex,
1489 pub lease_id: LeaseId,
1490 pub lease_epoch: LeaseEpoch,
1491 pub attempt_id: AttemptId,
1492 pub frame_type: String,
1493 pub timestamp: TimestampMs,
1494 pub payload: Vec<u8>,
1495 #[serde(default)]
1496 pub encoding: Option<String>,
1497 /// Optional structured metadata for the frame (JSON blob).
1498 #[serde(default)]
1499 pub metadata_json: Option<String>,
1500 #[serde(default)]
1501 pub correlation_id: Option<String>,
1502 #[serde(default)]
1503 pub source: Option<String>,
1504 /// MAXLEN for the stream. 0 = no trim.
1505 #[serde(default)]
1506 pub retention_maxlen: Option<u32>,
1507 /// Max payload bytes per frame. Default: 65536.
1508 #[serde(default)]
1509 pub max_payload_bytes: Option<u32>,
1510}
1511
1512#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1513pub enum AppendFrameResult {
1514 /// Frame appended successfully.
1515 Appended {
1516 /// Valkey Stream entry ID (e.g. "1713100800150-0").
1517 entry_id: String,
1518 /// Total frame count after this append.
1519 frame_count: u64,
1520 },
1521}
1522
1523// ─── StreamCursor (issue #92) ───
1524
1525/// Opaque cursor for attempt-stream reads/tails.
1526///
1527/// Replaces the bare `&str` / `String` stream-id parameters previously
1528/// carried on `read_stream` / `tail_stream` / `ReadStreamParams` /
1529/// `TailStreamParams`. The wire form is a flat string — serde is
1530/// transparent via `try_from`/`into` — so `?from=start&to=end` and
1531/// `?after=123-0` continue to work for REST clients.
1532///
1533/// # Public wire grammar
1534///
1535/// The ONLY accepted tokens are:
1536///
1537/// * `"start"` — first entry in the stream (XRANGE `-` equivalent).
1538/// Valid in `read_stream` / `ReadStreamParams`.
1539/// * `"end"` — latest entry in the stream (XRANGE `+` equivalent).
1540/// Valid in `read_stream` / `ReadStreamParams`.
1541/// * `"<ms>"` or `"<ms>-<seq>"` — a concrete Valkey Stream entry id.
1542/// Valid everywhere.
1543///
1544/// The bare XRANGE/XREAD markers `"-"` and `"+"` are **NOT** accepted
1545/// on the wire. The opaque `StreamCursor` grammar is the public
1546/// contract; the Valkey `-`/`+` markers are an internal implementation
1547/// detail carried only inside the Lua-adjacent [`ReadFramesArgs`] /
1548/// `xread_block` path via [`StreamCursor::to_wire`].
1549///
1550/// For XREAD (tail), the documented "from the beginning" convention is
1551/// `StreamCursor::At("0-0".into())` — use the convenience constructor
1552/// [`StreamCursor::from_beginning`] which returns exactly that value.
1553/// `Start` / `End` are rejected by the SDK's `tail_stream` boundary
1554/// because XREAD does not accept `-` / `+` as cursors. The
1555/// [`StreamCursor::is_concrete`] helper centralises this
1556/// Start/End-vs-At decision for boundary-validation call sites.
1557///
1558/// # Why an enum instead of a string
1559///
1560/// A string parameter lets malformed ids escape to the Lua/Valkey
1561/// layer, surfacing as a script error and HTTP 500. An enum with
1562/// fallible `FromStr` / `TryFrom<String>` catches every malformed input
1563/// at the wire boundary with a structured error, and prevents bare `-`
1564/// / `+` from leaking into consumer code as tacit extensions of the
1565/// public API.
1566#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1567pub enum StreamCursor {
1568 /// First entry in the stream (XRANGE start marker).
1569 Start,
1570 /// Latest entry in the stream (XRANGE end marker).
1571 End,
1572 /// A concrete Valkey Stream entry id (`<ms>` or `<ms>-<seq>`).
1573 ///
1574 /// For XREAD-style tails, the documented "from the beginning"
1575 /// convention is `At("0-0".to_owned())` — see
1576 /// [`StreamCursor::from_beginning`].
1577 At(String),
1578}
1579
1580impl StreamCursor {
1581 /// Convenience constructor for the XREAD-from-beginning convention
1582 /// (`"0-0"`). XREAD's `last_id` is exclusive, so passing this as
1583 /// the `after` cursor returns every entry in the stream.
1584 pub fn from_beginning() -> Self {
1585 Self::At("0-0".to_owned())
1586 }
1587
1588 /// Serde default helper — emits `StreamCursor::Start`. Used as
1589 /// `#[serde(default = "StreamCursor::start")]` on REST query
1590 /// structs.
1591 pub fn start() -> Self {
1592 Self::Start
1593 }
1594
1595 /// Serde default helper — emits `StreamCursor::End`.
1596 pub fn end() -> Self {
1597 Self::End
1598 }
1599
1600 /// Serde default helper — emits
1601 /// `StreamCursor::from_beginning()`. Used as the default for
1602 /// `TailStreamParams::after`.
1603 pub fn beginning() -> Self {
1604 Self::from_beginning()
1605 }
1606
1607 /// Internal-only: lower the cursor to the XRANGE/XREAD marker
1608 /// string Valkey expects. `Start → "-"`, `End → "+"`,
1609 /// `At(s) → s`.
1610 ///
1611 /// Used at the ff-script adapter edge (right before constructing
1612 /// `ReadFramesArgs` or calling `xread_block`) to translate the
1613 /// opaque wire grammar into the Lua-ABI form. NOT part of the
1614 /// public wire — do not emit these raw characters to consumers.
1615 /// Hidden from the generated docs to discourage external use;
1616 /// external consumers should never need to see the raw `-` / `+`.
1617 #[doc(hidden)]
1618 pub fn to_wire(&self) -> &str {
1619 match self {
1620 Self::Start => "-",
1621 Self::End => "+",
1622 Self::At(s) => s.as_str(),
1623 }
1624 }
1625
1626 /// Internal-only owned variant of [`Self::to_wire`] — moves the
1627 /// inner `String` out of `At(s)` without cloning. Use at adapter
1628 /// edges that construct an owned wire string (e.g.
1629 /// `ReadFramesArgs.from_id`) from a `StreamCursor` that is about
1630 /// to be dropped.
1631 #[doc(hidden)]
1632 pub fn into_wire_string(self) -> String {
1633 match self {
1634 Self::Start => "-".to_owned(),
1635 Self::End => "+".to_owned(),
1636 Self::At(s) => s,
1637 }
1638 }
1639
1640 /// True iff this cursor is a concrete entry id
1641 /// (`"<ms>"` / `"<ms>-<seq>"`). False for the open markers
1642 /// `Start` / `End`.
1643 ///
1644 /// Used by boundaries like XREAD (tailing) that do not accept
1645 /// open markers — rejecting a cursor is equivalent to
1646 /// `!cursor.is_concrete()`. Centralised here to keep the SDK and
1647 /// REST guards in lock-step.
1648 pub fn is_concrete(&self) -> bool {
1649 matches!(self, Self::At(_))
1650 }
1651}
1652
1653impl std::fmt::Display for StreamCursor {
1654 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1655 match self {
1656 Self::Start => f.write_str("start"),
1657 Self::End => f.write_str("end"),
1658 Self::At(s) => f.write_str(s),
1659 }
1660 }
1661}
1662
1663/// Error produced when parsing a [`StreamCursor`] from a string.
1664#[derive(Clone, Debug, PartialEq, Eq)]
1665pub enum StreamCursorParseError {
1666 /// Empty input.
1667 Empty,
1668 /// Input matched a rejected bare-marker alias (`"-"`, `"+"`).
1669 /// The public wire requires `"start"` / `"end"`; the raw Valkey
1670 /// markers are internal-only.
1671 BareMarkerRejected(String),
1672 /// Input was neither a recognized keyword nor a well-formed
1673 /// Stream entry id. Entry ids must match `^\d+(?:-\d+)?$`.
1674 Malformed(String),
1675}
1676
1677impl std::fmt::Display for StreamCursorParseError {
1678 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1679 match self {
1680 Self::Empty => f.write_str("stream cursor must not be empty"),
1681 Self::BareMarkerRejected(s) => write!(
1682 f,
1683 "bare marker '{s}' is not a valid stream cursor; use 'start' or 'end'"
1684 ),
1685 Self::Malformed(s) => write!(
1686 f,
1687 "invalid stream cursor '{s}' (expected 'start', 'end', '<ms>', or '<ms>-<seq>')"
1688 ),
1689 }
1690 }
1691}
1692
1693impl std::error::Error for StreamCursorParseError {}
1694
1695/// Shared grammar check — classifies `s` as `Start` / `End` / a
1696/// concrete-id shape / malformed / empty, WITHOUT allocating. The
1697/// owned vs borrowed entry points ([`StreamCursor::from_str`],
1698/// [`StreamCursor::try_from`]) consume this classification and move
1699/// the owned `String` into `At` when applicable, avoiding a
1700/// round-trip `String → &str → String::to_owned` for the common
1701/// REST-query path.
1702enum StreamCursorClass {
1703 Start,
1704 End,
1705 Concrete,
1706 BareMarker,
1707 Empty,
1708 Malformed,
1709}
1710
1711fn classify_stream_cursor(s: &str) -> StreamCursorClass {
1712 if s.is_empty() {
1713 return StreamCursorClass::Empty;
1714 }
1715 if s == "-" || s == "+" {
1716 return StreamCursorClass::BareMarker;
1717 }
1718 if s == "start" {
1719 return StreamCursorClass::Start;
1720 }
1721 if s == "end" {
1722 return StreamCursorClass::End;
1723 }
1724 if !s.is_ascii() {
1725 return StreamCursorClass::Malformed;
1726 }
1727 let (ms_part, seq_part) = match s.split_once('-') {
1728 Some((ms, seq)) => (ms, Some(seq)),
1729 None => (s, None),
1730 };
1731 let ms_ok = !ms_part.is_empty() && ms_part.bytes().all(|b| b.is_ascii_digit());
1732 let seq_ok = seq_part
1733 .map(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
1734 .unwrap_or(true);
1735 if ms_ok && seq_ok {
1736 StreamCursorClass::Concrete
1737 } else {
1738 StreamCursorClass::Malformed
1739 }
1740}
1741
1742impl std::str::FromStr for StreamCursor {
1743 type Err = StreamCursorParseError;
1744
1745 fn from_str(s: &str) -> Result<Self, Self::Err> {
1746 match classify_stream_cursor(s) {
1747 StreamCursorClass::Start => Ok(Self::Start),
1748 StreamCursorClass::End => Ok(Self::End),
1749 StreamCursorClass::Concrete => Ok(Self::At(s.to_owned())),
1750 StreamCursorClass::BareMarker => {
1751 Err(StreamCursorParseError::BareMarkerRejected(s.to_owned()))
1752 }
1753 StreamCursorClass::Empty => Err(StreamCursorParseError::Empty),
1754 StreamCursorClass::Malformed => Err(StreamCursorParseError::Malformed(s.to_owned())),
1755 }
1756 }
1757}
1758
1759impl TryFrom<String> for StreamCursor {
1760 type Error = StreamCursorParseError;
1761
1762 fn try_from(s: String) -> Result<Self, Self::Error> {
1763 // Owned parsing path — the `At` variant moves `s` in directly,
1764 // avoiding the `&str → String::to_owned` re-allocation that a
1765 // blind forward to `FromStr::from_str(&s)` would force. Error
1766 // paths still pay one allocation to describe the offending
1767 // input.
1768 match classify_stream_cursor(&s) {
1769 StreamCursorClass::Start => Ok(Self::Start),
1770 StreamCursorClass::End => Ok(Self::End),
1771 StreamCursorClass::Concrete => Ok(Self::At(s)),
1772 StreamCursorClass::BareMarker => Err(StreamCursorParseError::BareMarkerRejected(s)),
1773 StreamCursorClass::Empty => Err(StreamCursorParseError::Empty),
1774 StreamCursorClass::Malformed => Err(StreamCursorParseError::Malformed(s)),
1775 }
1776 }
1777}
1778
1779impl From<StreamCursor> for String {
1780 fn from(c: StreamCursor) -> Self {
1781 c.to_string()
1782 }
1783}
1784
1785impl Serialize for StreamCursor {
1786 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1787 serializer.collect_str(self)
1788 }
1789}
1790
1791impl<'de> Deserialize<'de> for StreamCursor {
1792 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1793 let s = String::deserialize(deserializer)?;
1794 Self::try_from(s).map_err(serde::de::Error::custom)
1795 }
1796}
1797
1798// ─── read_attempt_stream / tail_attempt_stream ───
1799
1800/// Hard cap on the number of frames returned by a single read/tail call.
1801///
1802/// Single source of truth across the Rust layer (ff-script, ff-server,
1803/// ff-sdk). The Lua side in `lua/stream.lua` keeps a matching literal with
1804/// an inline reference back here; bump both together if you ever need to
1805/// lift the cap.
1806pub const STREAM_READ_HARD_CAP: u64 = 10_000;
1807
1808/// A single frame read from an attempt-scoped stream.
1809///
1810/// Field set mirrors what `ff_append_frame` writes: `frame_type`, `ts`,
1811/// `payload`, `encoding`, `source`, and optionally `correlation_id`. Stored
1812/// as an ordered map so field order is deterministic across read calls.
1813#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1814pub struct StreamFrame {
1815 /// Valkey Stream entry ID, e.g. "1713100800150-0".
1816 pub id: String,
1817 /// Frame fields in sorted order.
1818 pub fields: std::collections::BTreeMap<String, String>,
1819}
1820
1821/// Inputs to `ff_read_attempt_stream` (XRANGE wrapper).
1822#[derive(Clone, Debug, Serialize, Deserialize)]
1823pub struct ReadFramesArgs {
1824 pub execution_id: ExecutionId,
1825 pub attempt_index: AttemptIndex,
1826 /// XRANGE start ID. Use "-" for earliest.
1827 pub from_id: String,
1828 /// XRANGE end ID. Use "+" for latest.
1829 pub to_id: String,
1830 /// XRANGE COUNT limit. MUST be `>= 1`. The REST and SDK layers reject
1831 /// `0` at the boundary; the Lua side rejects it too. `STREAM_READ_HARD_CAP`
1832 /// is the upper bound.
1833 pub count_limit: u64,
1834}
1835
1836/// Result of reading frames from an attempt stream — frames plus terminal
1837/// signal so consumers can stop polling without a timeout fallback.
1838#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1839pub struct StreamFrames {
1840 /// Entries in the requested range (possibly empty).
1841 pub frames: Vec<StreamFrame>,
1842 /// Timestamp when the upstream writer closed the stream. `None` if the
1843 /// stream is still open (or has never been written).
1844 #[serde(default, skip_serializing_if = "Option::is_none")]
1845 pub closed_at: Option<TimestampMs>,
1846 /// Reason from the closing writer. Current values:
1847 /// `attempt_success`, `attempt_failure`, `attempt_cancelled`,
1848 /// `attempt_interrupted`. `None` iff the stream is still open.
1849 #[serde(default, skip_serializing_if = "Option::is_none")]
1850 pub closed_reason: Option<String>,
1851}
1852
1853impl StreamFrames {
1854 /// Construct an empty open-stream result (no frames, no terminal
1855 /// markers). Useful for fast-path peek helpers.
1856 pub fn empty_open() -> Self {
1857 Self {
1858 frames: Vec::new(),
1859 closed_at: None,
1860 closed_reason: None,
1861 }
1862 }
1863
1864 /// True iff the producer has closed this stream. Consumers should stop
1865 /// polling and drain once this returns true.
1866 pub fn is_closed(&self) -> bool {
1867 self.closed_at.is_some()
1868 }
1869}
1870
1871#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1872pub enum ReadFramesResult {
1873 /// Frames returned (possibly empty) plus optional closed markers.
1874 Frames(StreamFrames),
1875}
1876
1877// ═══════════════════════════════════════════════════════════════════════
1878// Phase 5 contracts: budget, quota, block/unblock
1879// ═══════════════════════════════════════════════════════════════════════
1880
1881// ─── create_budget ───
1882
1883#[derive(Clone, Debug, Serialize, Deserialize)]
1884pub struct CreateBudgetArgs {
1885 pub budget_id: crate::types::BudgetId,
1886 pub scope_type: String,
1887 pub scope_id: String,
1888 pub enforcement_mode: String,
1889 pub on_hard_limit: String,
1890 pub on_soft_limit: String,
1891 pub reset_interval_ms: u64,
1892 /// Dimension names.
1893 pub dimensions: Vec<String>,
1894 /// Hard limits per dimension (parallel with dimensions).
1895 pub hard_limits: Vec<u64>,
1896 /// Soft limits per dimension (parallel with dimensions).
1897 pub soft_limits: Vec<u64>,
1898 pub now: TimestampMs,
1899}
1900
1901#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1902pub enum CreateBudgetResult {
1903 /// Budget created.
1904 Created { budget_id: crate::types::BudgetId },
1905 /// Already exists (idempotent).
1906 AlreadySatisfied { budget_id: crate::types::BudgetId },
1907}
1908
1909// ─── create_quota_policy ───
1910
1911#[derive(Clone, Debug, Serialize, Deserialize)]
1912pub struct CreateQuotaPolicyArgs {
1913 pub quota_policy_id: crate::types::QuotaPolicyId,
1914 pub window_seconds: u64,
1915 pub max_requests_per_window: u64,
1916 pub max_concurrent: u64,
1917 pub now: TimestampMs,
1918}
1919
1920#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1921pub enum CreateQuotaPolicyResult {
1922 /// Quota policy created.
1923 Created {
1924 quota_policy_id: crate::types::QuotaPolicyId,
1925 },
1926 /// Already exists (idempotent).
1927 AlreadySatisfied {
1928 quota_policy_id: crate::types::QuotaPolicyId,
1929 },
1930}
1931
1932// ─── budget_status (read-only) ───
1933
1934/// Operator-facing budget status snapshot (not an FCALL — direct HGETALL reads).
1935#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1936pub struct BudgetStatus {
1937 pub budget_id: String,
1938 pub scope_type: String,
1939 pub scope_id: String,
1940 pub enforcement_mode: String,
1941 /// Current usage per dimension: {dimension_name: current_value}.
1942 pub usage: HashMap<String, u64>,
1943 /// Hard limits per dimension: {dimension_name: limit}.
1944 pub hard_limits: HashMap<String, u64>,
1945 /// Soft limits per dimension: {dimension_name: limit}.
1946 pub soft_limits: HashMap<String, u64>,
1947 pub breach_count: u64,
1948 pub soft_breach_count: u64,
1949 pub last_breach_at: Option<String>,
1950 pub last_breach_dim: Option<String>,
1951 pub next_reset_at: Option<String>,
1952 pub created_at: Option<String>,
1953}
1954
1955// ─── report_usage_and_check ───
1956
1957#[derive(Clone, Debug, Serialize, Deserialize)]
1958pub struct ReportUsageArgs {
1959 /// Dimension names to increment.
1960 pub dimensions: Vec<String>,
1961 /// Increment values (parallel with dimensions).
1962 pub deltas: Vec<u64>,
1963 pub now: TimestampMs,
1964 /// Optional idempotency key to prevent double-counting on retries.
1965 /// Pass the raw dedup id (e.g. `"retry-42"`); the typed FCALL wrapper
1966 /// wraps it into `ff:usagededup:{b:M}:<id>` using the budget
1967 /// partition's hash tag so it co-locates with the other budget keys
1968 /// (#108).
1969 #[serde(default)]
1970 pub dedup_key: Option<String>,
1971}
1972
1973#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1974#[non_exhaustive]
1975pub enum ReportUsageResult {
1976 /// All increments applied, no breach.
1977 Ok,
1978 /// Soft limit breached on a dimension (advisory, increments applied).
1979 SoftBreach {
1980 dimension: String,
1981 current_usage: u64,
1982 soft_limit: u64,
1983 },
1984 /// Hard limit breached (increments NOT applied).
1985 HardBreach {
1986 dimension: String,
1987 current_usage: u64,
1988 hard_limit: u64,
1989 },
1990 /// Dedup key matched — usage already applied in a prior call.
1991 AlreadyApplied,
1992}
1993
1994// ─── reset_budget ───
1995
1996#[derive(Clone, Debug, Serialize, Deserialize)]
1997pub struct ResetBudgetArgs {
1998 pub budget_id: crate::types::BudgetId,
1999 pub now: TimestampMs,
2000}
2001
2002#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2003pub enum ResetBudgetResult {
2004 /// Budget reset successfully.
2005 Reset { next_reset_at: TimestampMs },
2006}
2007
2008// ─── check_admission_and_record ───
2009
2010#[derive(Clone, Debug, Serialize, Deserialize)]
2011pub struct CheckAdmissionArgs {
2012 pub execution_id: ExecutionId,
2013 pub now: TimestampMs,
2014 pub window_seconds: u64,
2015 pub rate_limit: u64,
2016 pub concurrency_cap: u64,
2017 #[serde(default)]
2018 pub jitter_ms: Option<u64>,
2019}
2020
2021#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2022pub enum CheckAdmissionResult {
2023 /// Admitted — execution may proceed.
2024 Admitted,
2025 /// Already admitted in this window (idempotent).
2026 AlreadyAdmitted,
2027 /// Rate limit exceeded.
2028 RateExceeded { retry_after_ms: u64 },
2029 /// Concurrency cap hit.
2030 ConcurrencyExceeded,
2031}
2032
2033// ─── release_admission ───
2034
2035#[derive(Clone, Debug, Serialize, Deserialize)]
2036pub struct ReleaseAdmissionArgs {
2037 pub execution_id: ExecutionId,
2038}
2039
2040#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2041pub enum ReleaseAdmissionResult {
2042 Released,
2043}
2044
2045// ─── block_execution_for_admission ───
2046
2047#[derive(Clone, Debug, Serialize, Deserialize)]
2048pub struct BlockExecutionArgs {
2049 pub execution_id: ExecutionId,
2050 pub blocking_reason: String,
2051 #[serde(default)]
2052 pub blocking_detail: Option<String>,
2053 pub now: TimestampMs,
2054}
2055
2056#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2057pub enum BlockExecutionResult {
2058 /// Execution blocked.
2059 Blocked,
2060}
2061
2062// ─── unblock_execution ───
2063
2064#[derive(Clone, Debug, Serialize, Deserialize)]
2065pub struct UnblockExecutionArgs {
2066 pub execution_id: ExecutionId,
2067 pub now: TimestampMs,
2068 /// Expected blocking reason (prevents stale unblock).
2069 #[serde(default)]
2070 pub expected_blocking_reason: Option<String>,
2071}
2072
2073#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2074pub enum UnblockExecutionResult {
2075 /// Execution unblocked and moved to eligible.
2076 Unblocked,
2077}
2078
2079// ═══════════════════════════════════════════════════════════════════════
2080// Phase 6 contracts: flow coordination and dependencies
2081// ═══════════════════════════════════════════════════════════════════════
2082
2083// ─── create_flow ───
2084
2085#[derive(Clone, Debug, Serialize, Deserialize)]
2086pub struct CreateFlowArgs {
2087 pub flow_id: crate::types::FlowId,
2088 pub flow_kind: String,
2089 pub namespace: Namespace,
2090 pub now: TimestampMs,
2091}
2092
2093#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2094pub enum CreateFlowResult {
2095 /// Flow created successfully.
2096 Created { flow_id: crate::types::FlowId },
2097 /// Flow already exists (idempotent).
2098 AlreadySatisfied { flow_id: crate::types::FlowId },
2099}
2100
2101// ─── add_execution_to_flow ───
2102
2103#[derive(Clone, Debug, Serialize, Deserialize)]
2104pub struct AddExecutionToFlowArgs {
2105 pub flow_id: crate::types::FlowId,
2106 pub execution_id: ExecutionId,
2107 pub now: TimestampMs,
2108}
2109
2110#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2111pub enum AddExecutionToFlowResult {
2112 /// Execution added to flow.
2113 Added {
2114 execution_id: ExecutionId,
2115 new_node_count: u32,
2116 },
2117 /// Already a member (idempotent).
2118 AlreadyMember {
2119 execution_id: ExecutionId,
2120 node_count: u32,
2121 },
2122}
2123
2124// ─── cancel_flow ───
2125
2126#[derive(Clone, Debug, Serialize, Deserialize)]
2127pub struct CancelFlowArgs {
2128 pub flow_id: crate::types::FlowId,
2129 pub reason: String,
2130 pub cancellation_policy: String,
2131 pub now: TimestampMs,
2132}
2133
2134#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2135pub enum CancelFlowResult {
2136 /// Flow cancelled and all member cancellations (if any) have completed
2137 /// synchronously. Used when `cancellation_policy != "cancel_all"`, when
2138 /// the flow has no members, when the caller opted into synchronous
2139 /// dispatch (e.g. `?wait=true`), or when the flow was already in a
2140 /// terminal state (idempotent retry).
2141 ///
2142 /// On the idempotent-retry path `member_execution_ids` may be *capped*
2143 /// at the server (default 1000 entries) to bound response bandwidth on
2144 /// flows with very large membership. The first (non-idempotent) call
2145 /// always returns the full list, so clients that need every member id
2146 /// should persist the initial response.
2147 Cancelled {
2148 cancellation_policy: String,
2149 member_execution_ids: Vec<String>,
2150 },
2151 /// Flow state was flipped to cancelled atomically, but member
2152 /// cancellations are dispatched asynchronously in the background.
2153 /// Clients may poll `GET /v1/executions/{id}/state` for each member
2154 /// execution id to track terminal state.
2155 CancellationScheduled {
2156 cancellation_policy: String,
2157 member_count: u32,
2158 member_execution_ids: Vec<String>,
2159 },
2160 /// `?wait=true` dispatch completed but one or more member cancellations
2161 /// failed mid-loop (e.g. ghost member, Lua error, transport fault after
2162 /// retries exhausted). The flow itself is still flipped to cancelled
2163 /// (atomic Lua already ran); callers SHOULD inspect
2164 /// `failed_member_execution_ids` and either retry those ids directly
2165 /// via `cancel_execution` or wait for the cancel-backlog reconciler
2166 /// to retry them in the background.
2167 ///
2168 /// Only emitted by the synchronous wait path
2169 /// ([`crate::CancelFlowArgs`] via `?wait=true`). The async path returns
2170 /// [`CancelFlowResult::CancellationScheduled`] and delegates retries
2171 /// to the reconciler — there is no visible "partial" state on the
2172 /// async path because the dispatch result is not observed inline.
2173 PartiallyCancelled {
2174 cancellation_policy: String,
2175 /// All member execution ids that the cancel_flow FCALL returned
2176 /// (i.e. the full membership at the moment of cancellation).
2177 member_execution_ids: Vec<String>,
2178 /// Strict subset of `member_execution_ids` whose per-member cancel
2179 /// FCALL returned an error. Order is deterministic (matches the
2180 /// iteration order over `member_execution_ids`).
2181 failed_member_execution_ids: Vec<String>,
2182 },
2183}
2184
2185/// RFC-017 Stage E2: result of the "header" portion of a cancel_flow
2186/// operation — the atomic flow-state flip + member enumeration.
2187///
2188/// The Server composes this with its own wait/async member-dispatch
2189/// machinery to build the wire-level [`CancelFlowResult`]. Backends
2190/// implement [`crate::engine_backend::EngineBackend::cancel_flow_header`]
2191/// (default: `Unavailable`) so the Valkey-native `ff_cancel_flow`
2192/// FCALL (with its `flow_already_terminal` idempotency branch) can be
2193/// driven through the trait without re-shaping the existing public
2194/// `cancel_flow(id, policy, wait)` signature.
2195#[derive(Clone, Debug, PartialEq, Eq)]
2196#[non_exhaustive]
2197pub enum CancelFlowHeader {
2198 /// Flow-state flipped this call. `member_execution_ids` is the
2199 /// full (uncapped) membership at flip time.
2200 Cancelled {
2201 cancellation_policy: String,
2202 member_execution_ids: Vec<String>,
2203 },
2204 /// Flow was already in a terminal state on entry. The backend has
2205 /// surfaced the *stored* `cancellation_policy`, `cancel_reason`,
2206 /// and full membership so the Server can return an idempotent
2207 /// [`CancelFlowResult::Cancelled`] without re-doing the flip.
2208 AlreadyTerminal {
2209 /// `None` only for flows cancelled by pre-E2 Lua that never
2210 /// persisted the policy field.
2211 stored_cancellation_policy: Option<String>,
2212 /// `None` when the flow was never cancel-reason-stamped.
2213 stored_cancel_reason: Option<String>,
2214 /// Full membership. Server caps to
2215 /// `ALREADY_TERMINAL_MEMBER_CAP` before wiring.
2216 member_execution_ids: Vec<String>,
2217 },
2218}
2219
2220// ─── stage_dependency_edge ───
2221
2222#[derive(Clone, Debug, Serialize, Deserialize)]
2223pub struct StageDependencyEdgeArgs {
2224 pub flow_id: crate::types::FlowId,
2225 pub edge_id: crate::types::EdgeId,
2226 pub upstream_execution_id: ExecutionId,
2227 pub downstream_execution_id: ExecutionId,
2228 #[serde(default = "default_dependency_kind")]
2229 pub dependency_kind: String,
2230 #[serde(default)]
2231 pub data_passing_ref: Option<String>,
2232 pub expected_graph_revision: u64,
2233 pub now: TimestampMs,
2234}
2235
2236fn default_dependency_kind() -> String {
2237 "success_only".to_owned()
2238}
2239
2240#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2241pub enum StageDependencyEdgeResult {
2242 /// Edge staged, new graph revision.
2243 Staged {
2244 edge_id: crate::types::EdgeId,
2245 new_graph_revision: u64,
2246 },
2247}
2248
2249// ─── apply_dependency_to_child ───
2250
2251#[derive(Clone, Debug, Serialize, Deserialize)]
2252pub struct ApplyDependencyToChildArgs {
2253 pub flow_id: crate::types::FlowId,
2254 pub edge_id: crate::types::EdgeId,
2255 /// The child execution that receives the dependency.
2256 pub downstream_execution_id: ExecutionId,
2257 pub upstream_execution_id: ExecutionId,
2258 pub graph_revision: u64,
2259 #[serde(default = "default_dependency_kind")]
2260 pub dependency_kind: String,
2261 #[serde(default)]
2262 pub data_passing_ref: Option<String>,
2263 pub now: TimestampMs,
2264}
2265
2266#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2267pub enum ApplyDependencyToChildResult {
2268 /// Dependency applied, N unsatisfied deps remaining.
2269 Applied { unsatisfied_count: u32 },
2270 /// Already applied (idempotent).
2271 AlreadyApplied,
2272}
2273
2274// ─── resolve_dependency ───
2275
2276/// Inputs to [`crate::engine_backend::EngineBackend::resolve_dependency`]
2277/// — the trait-level entry point PR-7b Step 0 lifted out of the two
2278/// inline FCALL call sites (`ff-engine::partition_router::
2279/// dispatch_dependency_resolution` and
2280/// `ff-engine::scanner::dependency_reconciler::resolve_eligible_edges`).
2281///
2282/// Both Valkey call sites build identical KEYS[14]+ARGV[5] arrays.
2283/// The fields below are the minimum they need to survive a trait-
2284/// boundary hand-off: `partition` drives the Valkey key-tagging,
2285/// `downstream_execution_id` + `lane_id` + `current_attempt_index`
2286/// pin the child's KEYS, `upstream_execution_id` derives KEYS[11]
2287/// (`upstream_result` for server-side `data_passing_ref` copy),
2288/// `flow_id` supplies the RFC-016 Stage C ARGV[4] + edgegroup/incoming
2289/// KEYS.
2290///
2291/// `#[non_exhaustive]` + `::new` per
2292/// `feedback_non_exhaustive_needs_constructor`. Does NOT derive
2293/// `Serialize` / `Deserialize` — this is a trait-boundary args
2294/// struct, not a wire-format type.
2295#[derive(Clone, Debug)]
2296#[non_exhaustive]
2297pub struct ResolveDependencyArgs {
2298 /// Child (downstream) execution's partition. Flow + exec partitions
2299 /// co-locate on `{fp:N}` post-RFC-011 so the FCALL stays single-slot.
2300 pub partition: crate::partition::Partition,
2301 pub flow_id: crate::types::FlowId,
2302 pub downstream_execution_id: ExecutionId,
2303 pub upstream_execution_id: ExecutionId,
2304 pub edge_id: crate::types::EdgeId,
2305 pub lane_id: LaneId,
2306 /// Child's current attempt index — selects `attempt_hash` +
2307 /// `stream_meta` KEYS so late satisfaction updates the active
2308 /// attempt (race-safe under renewal).
2309 pub current_attempt_index: AttemptIndex,
2310 /// "success", "failed", "cancelled", "expired", "skipped"
2311 pub upstream_outcome: String,
2312 pub now: TimestampMs,
2313}
2314
2315impl ResolveDependencyArgs {
2316 /// Construct a `ResolveDependencyArgs`. Added alongside
2317 /// `#[non_exhaustive]` per
2318 /// `feedback_non_exhaustive_needs_constructor`.
2319 #[allow(clippy::too_many_arguments)]
2320 pub fn new(
2321 partition: crate::partition::Partition,
2322 flow_id: crate::types::FlowId,
2323 downstream_execution_id: ExecutionId,
2324 upstream_execution_id: ExecutionId,
2325 edge_id: crate::types::EdgeId,
2326 lane_id: LaneId,
2327 current_attempt_index: AttemptIndex,
2328 upstream_outcome: String,
2329 now: TimestampMs,
2330 ) -> Self {
2331 Self {
2332 partition,
2333 flow_id,
2334 downstream_execution_id,
2335 upstream_execution_id,
2336 edge_id,
2337 lane_id,
2338 current_attempt_index,
2339 upstream_outcome,
2340 now,
2341 }
2342 }
2343}
2344
2345/// Typed outcome of
2346/// [`crate::engine_backend::EngineBackend::resolve_dependency`].
2347///
2348/// `#[non_exhaustive]` so additional variants (e.g. `ChildSkipped`
2349/// cascade hints) can be added in minor releases without forcing
2350/// match-arm churn on consumers.
2351#[derive(Clone, Debug, PartialEq, Eq)]
2352#[non_exhaustive]
2353pub enum ResolveDependencyOutcome {
2354 /// Edge satisfied — downstream may become eligible.
2355 Satisfied,
2356 /// Edge made impossible — downstream becomes skipped.
2357 Impossible,
2358 /// Already resolved (idempotent).
2359 AlreadyResolved,
2360}
2361
2362/// Legacy name retained for `ff-script`'s `FromFcallResult` plumbing.
2363/// Prefer [`ResolveDependencyOutcome`] in trait-level code.
2364#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2365pub enum ResolveDependencyResult {
2366 /// Edge satisfied — downstream may become eligible.
2367 Satisfied,
2368 /// Edge made impossible — downstream becomes skipped.
2369 Impossible,
2370 /// Already resolved (idempotent).
2371 AlreadyResolved,
2372}
2373
2374impl From<ResolveDependencyResult> for ResolveDependencyOutcome {
2375 fn from(r: ResolveDependencyResult) -> Self {
2376 match r {
2377 ResolveDependencyResult::Satisfied => ResolveDependencyOutcome::Satisfied,
2378 ResolveDependencyResult::Impossible => ResolveDependencyOutcome::Impossible,
2379 ResolveDependencyResult::AlreadyResolved => ResolveDependencyOutcome::AlreadyResolved,
2380 }
2381 }
2382}
2383
2384// ─── cascade_completion (PR-7b Cluster 4) ─────────────────────────────
2385
2386/// Typed outcome of
2387/// [`crate::engine_backend::EngineBackend::cascade_completion`].
2388///
2389/// Observable result of cascading a terminal-execution completion into
2390/// its downstream edges. Counters are best-effort — they describe what
2391/// the backend actually did on this call, not an authoritative graph
2392/// state (the `dependency_reconciler` remains the correctness safety
2393/// net for both backends).
2394///
2395/// # Timing semantics
2396///
2397/// The two in-tree backends differ in *when* cascade work is observable
2398/// to the caller. This is an accepted architectural divergence; consumer
2399/// code that needs synchronous cascade either targets Valkey explicitly
2400/// or inspects Postgres's observability surface (outbox drain) to
2401/// verify.
2402///
2403/// - **Valkey (`synchronous = true`):** the FCALL cascade runs
2404/// inline — when `cascade_completion` returns, every directly
2405/// resolvable edge has been advanced and every `child_skipped`
2406/// transitive descendant has been recursively cascaded up to the
2407/// `MAX_CASCADE_DEPTH` cap. `resolved` + `cascaded_children`
2408/// reflect the full subtree walked on this invocation.
2409/// - **Postgres (`synchronous = false`):** the call enqueues a
2410/// dispatch against the `ff_completion_event` outbox row; actual
2411/// downstream `ff_edge_group` advancement is performed by
2412/// `ff_backend_postgres::dispatch::dispatch_completion` in per-hop
2413/// transactions. `resolved` is the number of edge groups advanced
2414/// during this invocation's outbox drain; `cascaded_children` is
2415/// always `0` (PG does not self-recurse — further hops go through
2416/// their own outbox events emitted by the completing transaction).
2417///
2418/// `#[non_exhaustive]` so additional counters (e.g. an explicit
2419/// `dispatched_event_id` for PG, or a `depth_reached` for Valkey) can
2420/// be added without breaking consumers.
2421#[derive(Clone, Debug, Default, PartialEq, Eq)]
2422#[non_exhaustive]
2423pub struct CascadeOutcome {
2424 /// Edges whose resolution observably advanced on this call.
2425 pub resolved: usize,
2426 /// Transitive descendants cascaded synchronously (Valkey only;
2427 /// always `0` on Postgres — see Timing semantics).
2428 pub cascaded_children: usize,
2429 /// `true` when the caller observed the cascade inline (Valkey);
2430 /// `false` when the call only enqueued dispatch (Postgres outbox).
2431 pub synchronous: bool,
2432}
2433
2434impl CascadeOutcome {
2435 /// Construct an outcome describing a synchronous (Valkey) cascade.
2436 pub fn synchronous(resolved: usize, cascaded_children: usize) -> Self {
2437 Self { resolved, cascaded_children, synchronous: true }
2438 }
2439
2440 /// Construct an outcome describing an async (Postgres outbox)
2441 /// dispatch. `advanced` is the per-call outbox-drain count.
2442 pub fn async_dispatched(advanced: usize) -> Self {
2443 Self { resolved: advanced, cascaded_children: 0, synchronous: false }
2444 }
2445}
2446
2447// ─── promote_blocked_to_eligible ───
2448
2449#[derive(Clone, Debug, Serialize, Deserialize)]
2450pub struct PromoteBlockedToEligibleArgs {
2451 pub execution_id: ExecutionId,
2452 pub now: TimestampMs,
2453}
2454
2455#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2456pub enum PromoteBlockedToEligibleResult {
2457 Promoted,
2458}
2459
2460// ─── evaluate_flow_eligibility ───
2461
2462#[derive(Clone, Debug, Serialize, Deserialize)]
2463pub struct EvaluateFlowEligibilityArgs {
2464 pub execution_id: ExecutionId,
2465}
2466
2467#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2468pub enum EvaluateFlowEligibilityResult {
2469 /// Execution eligibility status.
2470 Status { status: String },
2471}
2472
2473// ─── replay_execution ───
2474
2475#[derive(Clone, Debug, Serialize, Deserialize)]
2476pub struct ReplayExecutionArgs {
2477 pub execution_id: ExecutionId,
2478 pub now: TimestampMs,
2479}
2480
2481#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2482pub enum ReplayExecutionResult {
2483 /// Replayed to runnable.
2484 Replayed { public_state: PublicState },
2485}
2486
2487// ─── get_execution (full read) ───
2488
2489/// Full execution info returned by `Server::get_execution`.
2490#[derive(Clone, Debug, Serialize, Deserialize)]
2491pub struct ExecutionInfo {
2492 pub execution_id: ExecutionId,
2493 pub namespace: String,
2494 pub lane_id: String,
2495 pub priority: i32,
2496 pub execution_kind: String,
2497 pub state_vector: StateVector,
2498 pub public_state: PublicState,
2499 pub created_at: String,
2500 /// TimestampMs (ms since epoch) when the execution's first attempt
2501 /// was started by a worker claim. Empty string until the first
2502 /// claim lands. Serialised as `Option<String>` so pre-claim reads
2503 /// deserialise cleanly even if the field is absent from the wire.
2504 #[serde(default, skip_serializing_if = "Option::is_none")]
2505 pub started_at: Option<String>,
2506 /// TimestampMs when the execution reached a terminal
2507 /// `completed`/`failed`/`cancelled`/`expired` state. Empty /
2508 /// absent while still in flight.
2509 #[serde(default, skip_serializing_if = "Option::is_none")]
2510 pub completed_at: Option<String>,
2511 pub current_attempt_index: u32,
2512 pub flow_id: Option<String>,
2513 pub blocking_detail: String,
2514}
2515
2516// ─── set_execution_tags / set_flow_tags (issue #58.4) ───
2517
2518/// Args for `ff_set_execution_tags`. Tag keys MUST match
2519/// `^[a-z][a-z0-9_]*\.` — the caller-namespace rule — or the FCALL
2520/// returns `invalid_tag_key`. Values are arbitrary strings. The map is
2521/// ordered (`BTreeMap`) so two callers submitting the same logical set
2522/// of tags produce identical ARGV.
2523#[derive(Clone, Debug, Serialize, Deserialize)]
2524pub struct SetExecutionTagsArgs {
2525 pub execution_id: ExecutionId,
2526 pub tags: BTreeMap<String, String>,
2527}
2528
2529/// Result of `ff_set_execution_tags`.
2530#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2531pub enum SetExecutionTagsResult {
2532 /// Tags written. `count` is the number of key-value pairs applied.
2533 Ok { count: u32 },
2534}
2535
2536/// Args for `ff_set_flow_tags`. Same namespace rule as
2537/// [`SetExecutionTagsArgs`]. The Lua function also lazy-migrates any
2538/// pre-58.4 reserved-namespace fields stashed inline on `flow_core` into
2539/// the new tags key.
2540#[derive(Clone, Debug, Serialize, Deserialize)]
2541pub struct SetFlowTagsArgs {
2542 pub flow_id: FlowId,
2543 pub tags: BTreeMap<String, String>,
2544}
2545
2546/// Result of `ff_set_flow_tags`.
2547#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2548pub enum SetFlowTagsResult {
2549 /// Tags written. `count` is the number of key-value pairs applied.
2550 Ok { count: u32 },
2551}
2552
2553// ─── describe_execution (issue #58.1) ───
2554
2555/// Engine-decoupled read-model for one execution.
2556///
2557/// Returned by `ff_sdk::FlowFabricWorker::describe_execution`. Consumers
2558/// consult this struct instead of reaching into Valkey's exec_core hash
2559/// directly — the engine is free to rename fields or restructure storage
2560/// under this surface.
2561///
2562/// `#[non_exhaustive]` — FF may add fields in minor releases without a
2563/// semver break. Match with `..` or use field-by-field construction.
2564#[derive(Clone, Debug, PartialEq, Eq)]
2565#[non_exhaustive]
2566pub struct ExecutionSnapshot {
2567 pub execution_id: ExecutionId,
2568 pub flow_id: Option<FlowId>,
2569 pub lane_id: LaneId,
2570 pub namespace: Namespace,
2571 pub public_state: PublicState,
2572 /// Blocking reason string (e.g. `"waiting_for_worker"`,
2573 /// `"waiting_for_delay"`, `"waiting_for_dependencies"`). `None` when
2574 /// the exec_core field is empty.
2575 pub blocking_reason: Option<String>,
2576 /// Free-form operator-readable detail explaining `blocking_reason`.
2577 /// `None` when the exec_core field is empty.
2578 pub blocking_detail: Option<String>,
2579 /// Summary of the execution's currently-active attempt. `None` when
2580 /// no attempt has been started (pre-claim) or when the exec_core
2581 /// attempt fields are all empty.
2582 pub current_attempt: Option<AttemptSummary>,
2583 /// Summary of the execution's currently-held lease. `None` when the
2584 /// execution is not held by a worker.
2585 pub current_lease: Option<LeaseSummary>,
2586 /// The waitpoint this execution is currently suspended on, if any.
2587 pub current_waitpoint: Option<WaitpointId>,
2588 pub created_at: TimestampMs,
2589 /// Timestamp of the last write that mutated exec_core. Engine-maintained.
2590 pub last_mutation_at: TimestampMs,
2591 pub total_attempt_count: u32,
2592 /// Caller-owned labels. The prefix `^[a-z][a-z0-9_]*\.` is reserved for
2593 /// consumer metadata (e.g. `cairn.task_id`); FF guarantees it will not
2594 /// write keys matching that shape. FF's own fields stay in snake_case
2595 /// without dots. Empty when no tags are set.
2596 pub tags: BTreeMap<String, String>,
2597}
2598
2599impl ExecutionSnapshot {
2600 /// Construct an [`ExecutionSnapshot`]. Present so downstream crates
2601 /// (ff-sdk's `describe_execution`) can assemble the struct despite
2602 /// the `#[non_exhaustive]` marker. Prefer adding builder-style
2603 /// helpers here over loosening `non_exhaustive`.
2604 #[allow(clippy::too_many_arguments)]
2605 pub fn new(
2606 execution_id: ExecutionId,
2607 flow_id: Option<FlowId>,
2608 lane_id: LaneId,
2609 namespace: Namespace,
2610 public_state: PublicState,
2611 blocking_reason: Option<String>,
2612 blocking_detail: Option<String>,
2613 current_attempt: Option<AttemptSummary>,
2614 current_lease: Option<LeaseSummary>,
2615 current_waitpoint: Option<WaitpointId>,
2616 created_at: TimestampMs,
2617 last_mutation_at: TimestampMs,
2618 total_attempt_count: u32,
2619 tags: BTreeMap<String, String>,
2620 ) -> Self {
2621 Self {
2622 execution_id,
2623 flow_id,
2624 lane_id,
2625 namespace,
2626 public_state,
2627 blocking_reason,
2628 blocking_detail,
2629 current_attempt,
2630 current_lease,
2631 current_waitpoint,
2632 created_at,
2633 last_mutation_at,
2634 total_attempt_count,
2635 tags,
2636 }
2637 }
2638}
2639
2640/// Currently-active attempt summary inside an [`ExecutionSnapshot`].
2641///
2642/// `#[non_exhaustive]`.
2643#[derive(Clone, Debug, PartialEq, Eq)]
2644#[non_exhaustive]
2645pub struct AttemptSummary {
2646 pub attempt_id: AttemptId,
2647 pub attempt_index: AttemptIndex,
2648}
2649
2650impl AttemptSummary {
2651 /// Construct an [`AttemptSummary`]. See [`ExecutionSnapshot::new`]
2652 /// for the rationale — `#[non_exhaustive]` blocks cross-crate
2653 /// struct-literal construction.
2654 pub fn new(attempt_id: AttemptId, attempt_index: AttemptIndex) -> Self {
2655 Self {
2656 attempt_id,
2657 attempt_index,
2658 }
2659 }
2660}
2661
2662/// Currently-held lease summary inside an [`ExecutionSnapshot`].
2663///
2664/// `#[non_exhaustive]`. New fields may be added in minor releases — use
2665/// [`LeaseSummary::new`] plus the fluent `with_*` setters to construct
2666/// one, and match with `..` in destructuring.
2667///
2668/// # Field provenance (FF#278)
2669///
2670/// * `lease_id` — minted at claim time (`ff_claim_execution` /
2671/// `ff_claim_resumed_execution`), cleared atomically with the other
2672/// lease fields on revoke/expire/complete. Stable for the lifetime
2673/// of a single lease; a fresh one is minted per re-claim. Defaults
2674/// to the nil UUID when a backend does not surface per-lease ids
2675/// (treat as "field not populated").
2676/// * `attempt_index` — the 1-based attempt counter (`current_attempt_index`
2677/// on `exec_core`). Set atomically with `current_attempt_id` at claim
2678/// time; always populated while a Valkey-backed lease is held.
2679/// * `last_heartbeat_at` — the most recent `ff_renew_lease` timestamp
2680/// (`lease_last_renewed_at` on `exec_core`). `None` when the field
2681/// is empty (e.g. legacy data pre-0.9, or a backend that does not
2682/// surface per-renewal heartbeats).
2683#[derive(Clone, Debug, PartialEq, Eq)]
2684#[non_exhaustive]
2685pub struct LeaseSummary {
2686 pub lease_epoch: LeaseEpoch,
2687 pub worker_instance_id: WorkerInstanceId,
2688 pub expires_at: TimestampMs,
2689 /// Per-lease unique identity. Correlates audit-log entries,
2690 /// reclaim events, and recovery traces.
2691 pub lease_id: LeaseId,
2692 /// 1-based attempt counter; `.0` mirrors `current_attempt_index`
2693 /// on `exec_core`.
2694 pub attempt_index: AttemptIndex,
2695 /// Most recent heartbeat (lease-renewal) timestamp. `None` when the
2696 /// backend does not surface per-renewal ticks on this lease.
2697 pub last_heartbeat_at: Option<TimestampMs>,
2698}
2699
2700impl LeaseSummary {
2701 /// Construct a [`LeaseSummary`] with the three always-present
2702 /// fields. Use the `with_*` setters to populate the FF#278
2703 /// additions (`lease_id`, `attempt_index`, `last_heartbeat_at`);
2704 /// otherwise they default to the nil / zero / empty forms, which
2705 /// callers should treat as "field not surfaced by this backend".
2706 ///
2707 /// See [`ExecutionSnapshot::new`] for the broader `#[non_exhaustive]`
2708 /// construction rationale.
2709 pub fn new(
2710 lease_epoch: LeaseEpoch,
2711 worker_instance_id: WorkerInstanceId,
2712 expires_at: TimestampMs,
2713 ) -> Self {
2714 Self {
2715 lease_epoch,
2716 worker_instance_id,
2717 expires_at,
2718 lease_id: LeaseId::from_uuid(uuid::Uuid::nil()),
2719 attempt_index: AttemptIndex::new(0),
2720 last_heartbeat_at: None,
2721 }
2722 }
2723
2724 /// Set the lease's unique identity (FF#278).
2725 #[must_use]
2726 pub fn with_lease_id(mut self, lease_id: LeaseId) -> Self {
2727 self.lease_id = lease_id;
2728 self
2729 }
2730
2731 /// Set the 1-based attempt counter (FF#278).
2732 #[must_use]
2733 pub fn with_attempt_index(mut self, attempt_index: AttemptIndex) -> Self {
2734 self.attempt_index = attempt_index;
2735 self
2736 }
2737
2738 /// Set the most recent heartbeat timestamp (FF#278).
2739 #[must_use]
2740 pub fn with_last_heartbeat_at(mut self, ts: TimestampMs) -> Self {
2741 self.last_heartbeat_at = Some(ts);
2742 self
2743 }
2744}
2745
2746// ─── read_execution_context (v0.12 agnostic-SDK prep, PR-1) ───
2747
2748/// Point-read bundle of the three execution-scoped fields the SDK
2749/// worker needs to construct a `ClaimedTask` (see `ff_sdk::ClaimedTask`):
2750/// `input_payload`, `execution_kind`, and `tags`.
2751///
2752/// Returned by
2753/// [`EngineBackend::read_execution_context`](crate::engine_backend::EngineBackend::read_execution_context).
2754/// All three fields are execution-scoped (not per-attempt) across
2755/// Valkey, Postgres, and SQLite — there is no per-attempt variant in
2756/// the data model.
2757///
2758/// `#[non_exhaustive]` — FF may add fields in minor releases without a
2759/// semver break. Construct via [`ExecutionContext::new`]; match with
2760/// `..` when destructuring.
2761#[derive(Clone, Debug, PartialEq, Eq)]
2762#[non_exhaustive]
2763pub struct ExecutionContext {
2764 /// Opaque payload handed to the execution body. Empty when the
2765 /// execution was created with no payload.
2766 pub input_payload: Vec<u8>,
2767 /// Caller-supplied `execution_kind` label — free-form string
2768 /// identifying which handler the worker should dispatch to.
2769 pub execution_kind: String,
2770 /// Caller-owned tag map. Tag key conventions mirror
2771 /// [`ExecutionSnapshot::tags`]; empty when no tags are set.
2772 pub tags: HashMap<String, String>,
2773}
2774
2775impl ExecutionContext {
2776 /// Construct an [`ExecutionContext`]. Present so downstream crates
2777 /// (concrete `EngineBackend` impls) can assemble the struct despite
2778 /// the `#[non_exhaustive]` marker. Prefer adding builder-style
2779 /// helpers here over loosening `non_exhaustive`.
2780 pub fn new(
2781 input_payload: Vec<u8>,
2782 execution_kind: String,
2783 tags: HashMap<String, String>,
2784 ) -> Self {
2785 Self {
2786 input_payload,
2787 execution_kind,
2788 tags,
2789 }
2790 }
2791}
2792
2793// ─── Common sub-types ───
2794
2795// ─── describe_flow (issue #58.2) ───
2796
2797/// Engine-decoupled read-model for one flow.
2798///
2799/// Returned by `ff_sdk::FlowFabricWorker::describe_flow`. Consumers
2800/// consult this struct instead of reaching into Valkey's flow_core hash
2801/// directly — the engine is free to rename fields or restructure storage
2802/// under this surface.
2803///
2804/// `#[non_exhaustive]` — FF may add fields in minor releases without a
2805/// semver break. Match with `..` or use [`FlowSnapshot::new`].
2806///
2807/// # `public_flow_state`
2808///
2809/// Stored as an engine-written string literal on `flow_core`. Known
2810/// values today: `open`, `running`, `blocked`, `cancelled`, `completed`,
2811/// `failed`. Surfaced as `String` (not a typed enum) because FF does
2812/// not yet expose a `PublicFlowState` type — callers that need to act
2813/// on specific values should match on the literal. The flow_projector
2814/// writes a parallel `public_flow_state` into the flow's summary hash;
2815/// this field reflects the authoritative value on `flow_core`, which
2816/// is what mutation guards (cancel/add-member) consult.
2817///
2818/// # `tags`
2819///
2820/// Unlike [`ExecutionSnapshot::tags`] (which has a dedicated tags
2821/// hash), flow tags live inline on `flow_core`. FF's own fields are
2822/// snake_case without a `.`; any field whose name starts with
2823/// `<lowercase>.` (e.g. `cairn.task_id`) is treated as consumer-owned
2824/// metadata and routed here. An empty map means no namespaced tags
2825/// were written. The prefix convention mirrors
2826/// [`ExecutionSnapshot::tags`] — consumers should keep tag keys
2827/// namespaced (`cairn.*`, `operator.*`, etc.) so future FF field
2828/// additions don't collide.
2829#[derive(Clone, Debug, PartialEq, Eq)]
2830#[non_exhaustive]
2831pub struct FlowSnapshot {
2832 pub flow_id: FlowId,
2833 /// The `flow_kind` literal passed to `create_flow` (e.g. `dag`,
2834 /// `pipeline`). Preserved as-is; FF does not interpret it.
2835 pub flow_kind: String,
2836 pub namespace: Namespace,
2837 /// Authoritative flow state on `flow_core`. See the struct-level
2838 /// docs for the set of known values.
2839 pub public_flow_state: String,
2840 /// Monotonically increasing revision bumped on every structural
2841 /// mutation (add-member, stage-edge). Used by optimistic-concurrency
2842 /// writers via `expected_graph_revision`.
2843 pub graph_revision: u64,
2844 /// Number of member executions added so far. Never decremented.
2845 pub node_count: u32,
2846 /// Number of dependency edges staged so far. Never decremented.
2847 pub edge_count: u32,
2848 pub created_at: TimestampMs,
2849 /// Timestamp of the last write that mutated `flow_core`.
2850 /// Engine-maintained.
2851 pub last_mutation_at: TimestampMs,
2852 /// When the flow reached a terminal state via `cancel_flow`. `None`
2853 /// while the flow is live. Only written by the cancel path today;
2854 /// `completed`/`failed` terminal states do not populate this field
2855 /// (the flow_projector derives them from membership).
2856 pub cancelled_at: Option<TimestampMs>,
2857 /// Operator-supplied reason from the `cancel_flow` call. `None`
2858 /// when the flow has not been cancelled.
2859 pub cancel_reason: Option<String>,
2860 /// The `cancellation_policy` value persisted by `cancel_flow`
2861 /// (e.g. `cancel_all`, `cancel_flow_only`). `None` for flows
2862 /// cancelled before this field was persisted, or not yet cancelled.
2863 pub cancellation_policy: Option<String>,
2864 /// Consumer-owned namespaced metadata (e.g. `cairn.task_id`). See
2865 /// the struct-level docs for the routing rule.
2866 pub tags: BTreeMap<String, String>,
2867 /// RFC-016 Stage A: inbound edge groups known on this flow.
2868 ///
2869 /// One entry per downstream execution that has at least one staged
2870 /// inbound dependency edge. Populated from the
2871 /// `ff:flow:{fp:N}:<flow_id>:edgegroup:<downstream_eid>` hash —
2872 /// when that hash is absent (existing flows created before Stage A),
2873 /// the backend falls back to reading the legacy
2874 /// `deps_meta.unsatisfied_required_count` counter on the
2875 /// downstream's exec partition and reports the group as
2876 /// [`EdgeDependencyPolicy::AllOf`] with the derived counters
2877 /// (backward-compat shim — see RFC-016 §11 Stage A).
2878 ///
2879 /// Every entry in Stage A reports `policy = AllOf`; Stage B/C/D/E
2880 /// extend the variants and wire the quorum counters.
2881 pub edge_groups: Vec<EdgeGroupSnapshot>,
2882}
2883
2884impl FlowSnapshot {
2885 /// Construct a [`FlowSnapshot`]. Present so downstream crates
2886 /// (ff-sdk's `describe_flow`) can assemble the struct despite the
2887 /// `#[non_exhaustive]` marker.
2888 #[allow(clippy::too_many_arguments)]
2889 pub fn new(
2890 flow_id: FlowId,
2891 flow_kind: String,
2892 namespace: Namespace,
2893 public_flow_state: String,
2894 graph_revision: u64,
2895 node_count: u32,
2896 edge_count: u32,
2897 created_at: TimestampMs,
2898 last_mutation_at: TimestampMs,
2899 cancelled_at: Option<TimestampMs>,
2900 cancel_reason: Option<String>,
2901 cancellation_policy: Option<String>,
2902 tags: BTreeMap<String, String>,
2903 edge_groups: Vec<EdgeGroupSnapshot>,
2904 ) -> Self {
2905 Self {
2906 flow_id,
2907 flow_kind,
2908 namespace,
2909 public_flow_state,
2910 graph_revision,
2911 node_count,
2912 edge_count,
2913 created_at,
2914 last_mutation_at,
2915 cancelled_at,
2916 cancel_reason,
2917 cancellation_policy,
2918 tags,
2919 edge_groups,
2920 }
2921 }
2922}
2923
2924// ─── describe_edge / list_*_edges (issue #58.3) ───
2925
2926/// Engine-decoupled read-model for one dependency edge.
2927///
2928/// Returned by `ff_sdk::FlowFabricWorker::describe_edge`,
2929/// `list_incoming_edges`, and `list_outgoing_edges`. Consumers consult
2930/// this struct instead of reaching into Valkey's per-flow `edge:` hash
2931/// directly — the engine is free to rename hash fields or restructure
2932/// key layout under this surface.
2933///
2934/// `#[non_exhaustive]` — FF may add fields in minor releases without a
2935/// semver break. Match with `..` or use [`EdgeSnapshot::new`].
2936///
2937/// # Fields
2938///
2939/// The struct mirrors the immutable edge record written by
2940/// `ff_stage_dependency_edge` (see `lua/flow.lua`). The flow-scoped
2941/// edge hash is only ever written once, at staging time; per-execution
2942/// resolution state lives on a separate `dep:<edge_id>` hash and is not
2943/// surfaced here. The `edge_state` field therefore reflects the
2944/// staging-time literal (currently `pending`), not the downstream
2945/// execution's dep-edge state.
2946#[derive(Clone, Debug, PartialEq, Eq)]
2947#[non_exhaustive]
2948pub struct EdgeSnapshot {
2949 pub edge_id: EdgeId,
2950 pub flow_id: FlowId,
2951 pub upstream_execution_id: ExecutionId,
2952 pub downstream_execution_id: ExecutionId,
2953 /// The `dependency_kind` literal (e.g. `success_only`) from
2954 /// `stage_dependency_edge`. Preserved as-is; FF does not interpret
2955 /// it on reads.
2956 pub dependency_kind: String,
2957 /// The satisfaction-condition literal stamped at staging time
2958 /// (e.g. `all_required`).
2959 pub satisfaction_condition: String,
2960 /// Optional opaque handle to a data-passing artifact. `None` when
2961 /// the stored field is empty (the most common case).
2962 pub data_passing_ref: Option<String>,
2963 /// Edge-state literal on the flow-scoped edge hash. Written once
2964 /// at staging as `pending`; this hash is immutable on the flow
2965 /// side. Per-execution resolution state is tracked separately on
2966 /// the child's `dep:<edge_id>` hash.
2967 pub edge_state: String,
2968 pub created_at: TimestampMs,
2969 /// Origin of the edge (e.g. `engine`). Preserved as-is.
2970 pub created_by: String,
2971}
2972
2973/// Direction marker for [`crate::engine_backend::EngineBackend::list_edges`].
2974///
2975/// Carries the subject execution whose adjacency side the caller wants
2976/// to list — mirrors the internal `AdjacencySide + subject_eid` pair
2977/// the ff-sdk free-fn `list_edges_from_set` already uses. Keeping
2978/// direction + subject fused in one enum means the trait method has a
2979/// single `direction` parameter rather than a `(side, eid)` pair, and
2980/// the backend impl can't forget one of the two.
2981///
2982/// * `Outgoing { from_node }` — the caller wants every edge whose
2983/// `upstream_execution_id == from_node`. Corresponds to the
2984/// `out:<execution_id>` adjacency SET under the execution's flow
2985/// partition.
2986/// * `Incoming { to_node }` — the caller wants every edge whose
2987/// `downstream_execution_id == to_node`. Corresponds to the
2988/// `in:<execution_id>` adjacency SET under the execution's flow
2989/// partition.
2990#[derive(Clone, Debug, PartialEq, Eq)]
2991pub enum EdgeDirection {
2992 /// Edges leaving `from_node` — `out:` adjacency SET.
2993 Outgoing {
2994 /// The subject execution whose outgoing edges to list.
2995 from_node: ExecutionId,
2996 },
2997 /// Edges landing on `to_node` — `in:` adjacency SET.
2998 Incoming {
2999 /// The subject execution whose incoming edges to list.
3000 to_node: ExecutionId,
3001 },
3002}
3003
3004impl EdgeDirection {
3005 /// Return the subject execution id regardless of direction. Shared
3006 /// helper for backend impls that need the execution id for the
3007 /// initial `HGET exec_core.flow_id` lookup (flow routing) before
3008 /// they know which adjacency SET to read.
3009 pub fn subject(&self) -> &ExecutionId {
3010 match self {
3011 Self::Outgoing { from_node } => from_node,
3012 Self::Incoming { to_node } => to_node,
3013 }
3014 }
3015}
3016
3017impl EdgeSnapshot {
3018 /// Construct an [`EdgeSnapshot`]. Present so downstream crates
3019 /// (ff-sdk's `describe_edge` / `list_*_edges`) can assemble the
3020 /// struct despite the `#[non_exhaustive]` marker.
3021 #[allow(clippy::too_many_arguments)]
3022 pub fn new(
3023 edge_id: EdgeId,
3024 flow_id: FlowId,
3025 upstream_execution_id: ExecutionId,
3026 downstream_execution_id: ExecutionId,
3027 dependency_kind: String,
3028 satisfaction_condition: String,
3029 data_passing_ref: Option<String>,
3030 edge_state: String,
3031 created_at: TimestampMs,
3032 created_by: String,
3033 ) -> Self {
3034 Self {
3035 edge_id,
3036 flow_id,
3037 upstream_execution_id,
3038 downstream_execution_id,
3039 dependency_kind,
3040 satisfaction_condition,
3041 data_passing_ref,
3042 edge_state,
3043 created_at,
3044 created_by,
3045 }
3046 }
3047}
3048
3049// ─── RFC-016 edge-group policy (Stage A) ───
3050
3051/// Policy controlling how an inbound edge group's satisfaction is
3052/// decided.
3053///
3054/// Stage A honours only [`EdgeDependencyPolicy::AllOf`] — the two
3055/// quorum variants exist so the wire/snapshot surface is stable for
3056/// Stage B/C/D's resolver extensions, but
3057/// [`crate::engine_backend::EngineBackend::set_edge_group_policy`]
3058/// rejects them with [`crate::engine_error::EngineError::Validation`]
3059/// until Stage B lands.
3060///
3061/// `#[non_exhaustive]` — future stages may add variants (e.g.
3062/// `Threshold` — see RFC-016 §10.3) without a semver break. Construct
3063/// via the [`EdgeDependencyPolicy::all_of`], [`EdgeDependencyPolicy::any_of`],
3064/// and [`EdgeDependencyPolicy::quorum`] helpers.
3065#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3066#[non_exhaustive]
3067#[serde(tag = "kind", rename_all = "snake_case")]
3068pub enum EdgeDependencyPolicy {
3069 /// Today's behavior: every edge in the inbound group must be
3070 /// satisfied (RFC-007 `all_required` + `success_only`).
3071 AllOf,
3072 /// k-of-n where k==1 — satisfied on the first upstream success.
3073 /// Stage A: rejected on
3074 /// [`crate::engine_backend::EngineBackend::set_edge_group_policy`];
3075 /// resolver emits nothing for this variant yet.
3076 AnyOf {
3077 #[serde(rename = "on_satisfied")]
3078 on_satisfied: OnSatisfied,
3079 },
3080 /// k-of-n quorum. Stage A: rejected on
3081 /// [`crate::engine_backend::EngineBackend::set_edge_group_policy`].
3082 Quorum {
3083 k: u32,
3084 #[serde(rename = "on_satisfied")]
3085 on_satisfied: OnSatisfied,
3086 },
3087}
3088
3089impl EdgeDependencyPolicy {
3090 /// Construct the default all-of policy (RFC-007 behavior).
3091 pub fn all_of() -> Self {
3092 Self::AllOf
3093 }
3094
3095 /// Construct an any-of policy — reserved for Stage B.
3096 pub fn any_of(on_satisfied: OnSatisfied) -> Self {
3097 Self::AnyOf { on_satisfied }
3098 }
3099
3100 /// Construct a quorum policy — reserved for Stage B.
3101 pub fn quorum(k: u32, on_satisfied: OnSatisfied) -> Self {
3102 Self::Quorum { k, on_satisfied }
3103 }
3104
3105 /// Stable string label used for wire format + metric labels.
3106 /// `all_of` | `any_of` | `quorum`.
3107 pub fn variant_str(&self) -> &'static str {
3108 match self {
3109 Self::AllOf => "all_of",
3110 Self::AnyOf { .. } => "any_of",
3111 Self::Quorum { .. } => "quorum",
3112 }
3113 }
3114}
3115
3116/// Policy for unfinished sibling upstreams once the quorum is met.
3117///
3118/// `#[non_exhaustive]` — RFC-016 §10.5 rejects a third variant today
3119/// but keeps the door open. Construct via [`OnSatisfied::cancel_remaining`]
3120/// / [`OnSatisfied::let_run`].
3121#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3122#[non_exhaustive]
3123#[serde(rename_all = "snake_case")]
3124pub enum OnSatisfied {
3125 /// Default. Cancel any still-running siblings once quorum met.
3126 CancelRemaining,
3127 /// Let stragglers finish; their terminals update counters for
3128 /// observability only (one-shot downstream).
3129 LetRun,
3130}
3131
3132impl OnSatisfied {
3133 /// Construct the default `cancel_remaining` disposition.
3134 pub fn cancel_remaining() -> Self {
3135 Self::CancelRemaining
3136 }
3137
3138 /// Construct the `let_run` disposition.
3139 pub fn let_run() -> Self {
3140 Self::LetRun
3141 }
3142
3143 /// Stable string label for wire format.
3144 pub fn variant_str(&self) -> &'static str {
3145 match self {
3146 Self::CancelRemaining => "cancel_remaining",
3147 Self::LetRun => "let_run",
3148 }
3149 }
3150}
3151
3152/// Edge-group lifecycle state (Stage A exposes only `pending` +
3153/// `satisfied` + `impossible`; `cancelled` reserved for Stage C).
3154#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
3155#[non_exhaustive]
3156#[serde(rename_all = "snake_case")]
3157pub enum EdgeGroupState {
3158 Pending,
3159 Satisfied,
3160 Impossible,
3161 Cancelled,
3162}
3163
3164impl EdgeGroupState {
3165 pub fn from_literal(s: &str) -> Self {
3166 match s {
3167 "satisfied" => Self::Satisfied,
3168 "impossible" => Self::Impossible,
3169 "cancelled" => Self::Cancelled,
3170 _ => Self::Pending,
3171 }
3172 }
3173
3174 pub fn as_str(&self) -> &'static str {
3175 match self {
3176 Self::Pending => "pending",
3177 Self::Satisfied => "satisfied",
3178 Self::Impossible => "impossible",
3179 Self::Cancelled => "cancelled",
3180 }
3181 }
3182}
3183
3184/// Snapshot of one inbound edge group (per downstream execution).
3185///
3186/// Exposed via [`FlowSnapshot::edge_groups`]. Stage A only populates
3187/// `AllOf` groups and their counters; Stage B/C add `failed` /
3188/// `skipped` / `satisfied_at` wiring for the quorum variants.
3189///
3190/// `#[non_exhaustive]` — future stages will add fields (`satisfied_at`,
3191/// `failed_count` write-path, `cancel_siblings_pending`). Match with
3192/// `..` or use [`EdgeGroupSnapshot::new`].
3193#[derive(Clone, Debug, PartialEq, Eq)]
3194#[non_exhaustive]
3195pub struct EdgeGroupSnapshot {
3196 pub downstream_execution_id: ExecutionId,
3197 pub policy: EdgeDependencyPolicy,
3198 pub total_deps: u32,
3199 pub satisfied_count: u32,
3200 pub failed_count: u32,
3201 pub skipped_count: u32,
3202 pub running_count: u32,
3203 pub group_state: EdgeGroupState,
3204}
3205
3206impl EdgeGroupSnapshot {
3207 #[allow(clippy::too_many_arguments)]
3208 pub fn new(
3209 downstream_execution_id: ExecutionId,
3210 policy: EdgeDependencyPolicy,
3211 total_deps: u32,
3212 satisfied_count: u32,
3213 failed_count: u32,
3214 skipped_count: u32,
3215 running_count: u32,
3216 group_state: EdgeGroupState,
3217 ) -> Self {
3218 Self {
3219 downstream_execution_id,
3220 policy,
3221 total_deps,
3222 satisfied_count,
3223 failed_count,
3224 skipped_count,
3225 running_count,
3226 group_state,
3227 }
3228 }
3229}
3230
3231// ─── set_edge_group_policy (RFC-016 §6.1) ───
3232
3233#[derive(Clone, Debug, Serialize, Deserialize)]
3234pub struct SetEdgeGroupPolicyArgs {
3235 pub flow_id: FlowId,
3236 pub downstream_execution_id: ExecutionId,
3237 pub policy: EdgeDependencyPolicy,
3238 pub now: TimestampMs,
3239}
3240
3241#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3242pub enum SetEdgeGroupPolicyResult {
3243 /// Policy stored (fresh write).
3244 Set,
3245 /// Policy already stored with an identical value (idempotent).
3246 AlreadySet,
3247}
3248
3249// ─── list_flows (issue #185) ───
3250
3251/// Typed flow-lifecycle status surfaced on [`FlowSummary`].
3252///
3253/// Mirrors the free-form `public_flow_state` literal that FF's flow
3254/// lifecycle writes onto `flow_core` (known values: `open`, `running`,
3255/// `blocked`, `cancelled`, `completed`, `failed` — see [`FlowSnapshot`]).
3256/// The three "active" runtime states (`open`, `running`, `blocked`)
3257/// collapse to [`FlowStatus::Active`] here — callers that need the
3258/// exact runtime sub-state should use [`FlowSnapshot::public_flow_state`]
3259/// via [`crate::engine_backend::EngineBackend::describe_flow`]. `failed`
3260/// maps to [`FlowStatus::Failed`].
3261///
3262/// `#[non_exhaustive]` so future lifecycle states (if FF introduces
3263/// any) can be added without a semver break.
3264#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3265#[non_exhaustive]
3266pub enum FlowStatus {
3267 /// `open` / `running` / `blocked` — flow is still live on the engine.
3268 Active,
3269 /// Terminal success: all members reached a successful terminal state
3270 /// and the flow projector flipped `public_flow_state` to `completed`.
3271 Completed,
3272 /// Terminal failure: one or more members failed and the flow
3273 /// projector flipped `public_flow_state` to `failed`.
3274 Failed,
3275 /// Cancelled by an operator via `cancel_flow`.
3276 Cancelled,
3277 /// The stored `public_flow_state` literal is present but not a
3278 /// known value. The raw literal is preserved on
3279 /// [`FlowSnapshot::public_flow_state`] — callers that need to act
3280 /// on it should fall back to [`crate::engine_backend::EngineBackend::describe_flow`].
3281 Unknown,
3282}
3283
3284impl FlowStatus {
3285 /// Map the raw `public_flow_state` literal stored on `flow_core`
3286 /// to a typed [`FlowStatus`]. Unknown literals surface as
3287 /// [`FlowStatus::Unknown`] so the list surface stays forwards-
3288 /// compatible with future engine-side state additions.
3289 pub fn from_public_flow_state(raw: &str) -> Self {
3290 match raw {
3291 "open" | "running" | "blocked" => Self::Active,
3292 "completed" => Self::Completed,
3293 "failed" => Self::Failed,
3294 "cancelled" => Self::Cancelled,
3295 _ => Self::Unknown,
3296 }
3297 }
3298}
3299
3300/// Lightweight per-flow projection returned by
3301/// [`crate::engine_backend::EngineBackend::list_flows`].
3302///
3303/// Deliberately narrower than [`FlowSnapshot`] — listing pages serve
3304/// dashboard-style enumerations where the caller does not want to pay
3305/// for the full `flow_core` hash on every row. Consumers that need
3306/// revision / node-count / tags / cancel metadata should fan out to
3307/// [`crate::engine_backend::EngineBackend::describe_flow`] for the
3308/// specific ids they care about.
3309///
3310/// `#[non_exhaustive]` — FF may add fields in minor releases without
3311/// a semver break. Match with `..` or use [`FlowSummary::new`].
3312#[derive(Clone, Debug, PartialEq, Eq)]
3313#[non_exhaustive]
3314pub struct FlowSummary {
3315 pub flow_id: FlowId,
3316 /// Timestamp (ms since unix epoch) `flow_core.created_at` was
3317 /// stamped. Mirrors [`FlowSnapshot::created_at`]; kept typed so
3318 /// callers that want raw millis can read `.0`.
3319 pub created_at: TimestampMs,
3320 /// Typed projection of `flow_core.public_flow_state`. See
3321 /// [`FlowStatus`] for the mapping.
3322 pub status: FlowStatus,
3323}
3324
3325impl FlowSummary {
3326 /// Construct a [`FlowSummary`]. Present so downstream crates can
3327 /// assemble the struct despite the `#[non_exhaustive]` marker.
3328 pub fn new(flow_id: FlowId, created_at: TimestampMs, status: FlowStatus) -> Self {
3329 Self {
3330 flow_id,
3331 created_at,
3332 status,
3333 }
3334 }
3335}
3336
3337/// One page of [`FlowSummary`] rows returned by
3338/// [`crate::engine_backend::EngineBackend::list_flows`].
3339///
3340/// `next_cursor` is `Some(last_flow_id)` when at least one more row
3341/// may exist on the partition — callers forward it verbatim as the
3342/// next call's `cursor` argument to continue iteration. `None` means
3343/// the listing is exhausted. Cursor semantics match the Postgres
3344/// `WHERE flow_id > $cursor ORDER BY flow_id LIMIT $limit` pattern
3345/// (see the trait method's rustdoc).
3346///
3347/// `#[non_exhaustive]` — FF may add summary-level fields (total count,
3348/// partition hint) in future minor releases without a semver break.
3349#[derive(Clone, Debug, PartialEq, Eq)]
3350#[non_exhaustive]
3351pub struct ListFlowsPage {
3352 pub flows: Vec<FlowSummary>,
3353 pub next_cursor: Option<FlowId>,
3354}
3355
3356impl ListFlowsPage {
3357 /// Construct a [`ListFlowsPage`]. Present so downstream crates can
3358 /// assemble the struct despite the `#[non_exhaustive]` marker.
3359 pub fn new(flows: Vec<FlowSummary>, next_cursor: Option<FlowId>) -> Self {
3360 Self { flows, next_cursor }
3361 }
3362}
3363
3364/// Summary of state after a mutation, returned by many functions.
3365#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3366pub struct StateSummary {
3367 pub state_vector: StateVector,
3368 pub current_attempt_index: AttemptIndex,
3369}
3370
3371// ─── RFC-025 worker registry ───
3372
3373/// Inputs to [`crate::engine_backend::EngineBackend::register_worker`]
3374/// (RFC-025). Feature gate: `core`.
3375///
3376/// `worker_instance_id` is process identity (unique per-boot);
3377/// `worker_id` is pool / logical identity (stable across restarts).
3378/// See RFC-025 §7 terminology glossary.
3379///
3380/// `liveness_ttl_ms` is stored alongside the registration so
3381/// `heartbeat_worker` refreshes to the same value without the caller
3382/// re-supplying it.
3383///
3384/// Re-registering with the same `worker_instance_id` is
3385/// **idempotent** (RFC-025 §9.3): caps/lanes/TTL overwritten,
3386/// `Refreshed` returned. Re-registering with the same
3387/// `worker_instance_id` under a DIFFERENT `worker_id` is rejected
3388/// with `Validation(InvalidInput, "instance_id reassigned")`.
3389#[non_exhaustive]
3390#[derive(Clone, Debug, PartialEq, Eq)]
3391pub struct RegisterWorkerArgs {
3392 pub worker_id: WorkerId,
3393 pub worker_instance_id: WorkerInstanceId,
3394 /// Workers serve one-or-more lanes. `BTreeSet` for stable
3395 /// iteration + dedup.
3396 pub lanes: BTreeSet<LaneId>,
3397 pub capabilities: BTreeSet<String>,
3398 /// Stored for subsequent `heartbeat_worker` TTL refresh.
3399 pub liveness_ttl_ms: u64,
3400 pub namespace: Namespace,
3401 pub now: TimestampMs,
3402}
3403
3404impl RegisterWorkerArgs {
3405 pub fn new(
3406 worker_id: WorkerId,
3407 worker_instance_id: WorkerInstanceId,
3408 lanes: BTreeSet<LaneId>,
3409 capabilities: BTreeSet<String>,
3410 liveness_ttl_ms: u64,
3411 namespace: Namespace,
3412 now: TimestampMs,
3413 ) -> Self {
3414 Self {
3415 worker_id,
3416 worker_instance_id,
3417 lanes,
3418 capabilities,
3419 liveness_ttl_ms,
3420 namespace,
3421 now,
3422 }
3423 }
3424}
3425
3426#[non_exhaustive]
3427#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3428pub enum RegisterWorkerOutcome {
3429 /// No prior live key for this `worker_instance_id` (fresh boot
3430 /// or post-TTL-expiry).
3431 Registered,
3432 /// Existing live key was found; TTL reset + caps/lanes
3433 /// overwritten (in-process hot-restart, RFC-025 §9.3).
3434 Refreshed,
3435}
3436
3437/// Inputs to [`crate::engine_backend::EngineBackend::heartbeat_worker`]
3438/// (RFC-025). Feature gate: `core`.
3439#[non_exhaustive]
3440#[derive(Clone, Debug, PartialEq, Eq)]
3441pub struct HeartbeatWorkerArgs {
3442 pub worker_instance_id: WorkerInstanceId,
3443 pub namespace: Namespace,
3444 pub now: TimestampMs,
3445}
3446
3447impl HeartbeatWorkerArgs {
3448 pub fn new(
3449 worker_instance_id: WorkerInstanceId,
3450 namespace: Namespace,
3451 now: TimestampMs,
3452 ) -> Self {
3453 Self {
3454 worker_instance_id,
3455 namespace,
3456 now,
3457 }
3458 }
3459}
3460
3461#[non_exhaustive]
3462#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3463pub enum HeartbeatWorkerOutcome {
3464 /// TTL refreshed. `next_expiry_ms = now + stored-ttl`; callers
3465 /// schedule the next heartbeat from this value.
3466 Refreshed { next_expiry_ms: TimestampMs },
3467 /// Liveness key was absent — TTL ran out or `mark_worker_dead`
3468 /// landed earlier. Caller re-registers, not re-heartbeats.
3469 NotRegistered,
3470}
3471
3472/// Inputs to [`crate::engine_backend::EngineBackend::mark_worker_dead`]
3473/// (RFC-025). Feature gate: `core`.
3474///
3475/// `reason` is capped at 256 bytes and must not contain control
3476/// characters; oversize / invalid reject with
3477/// `Validation(InvalidInput, "reason: …")`. Mirrors
3478/// `fail_execution`'s `failure_reason` discipline.
3479#[non_exhaustive]
3480#[derive(Clone, Debug, PartialEq, Eq)]
3481pub struct MarkWorkerDeadArgs {
3482 pub worker_instance_id: WorkerInstanceId,
3483 pub namespace: Namespace,
3484 pub reason: String,
3485 pub now: TimestampMs,
3486}
3487
3488impl MarkWorkerDeadArgs {
3489 pub fn new(
3490 worker_instance_id: WorkerInstanceId,
3491 namespace: Namespace,
3492 reason: String,
3493 now: TimestampMs,
3494 ) -> Self {
3495 Self {
3496 worker_instance_id,
3497 namespace,
3498 reason,
3499 now,
3500 }
3501 }
3502}
3503
3504/// Max bytes for `MarkWorkerDeadArgs.reason`. Mirrors
3505/// `FailExecutionArgs::failure_reason` ceiling.
3506pub const MARK_WORKER_DEAD_REASON_MAX_BYTES: usize = 256;
3507
3508#[non_exhaustive]
3509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3510pub enum MarkWorkerDeadOutcome {
3511 Marked,
3512 /// Liveness key already absent — no-op, idempotent. Unified
3513 /// variant name with `HeartbeatWorkerOutcome::NotRegistered`.
3514 NotRegistered,
3515}
3516
3517/// Cursor for [`crate::engine_backend::EngineBackend::list_expired_leases`]
3518/// (RFC-025 §9-locked). Tuple (not bare `ExecutionId`) so pagination
3519/// is stable under equal-expiry: `ZRANGEBYSCORE` with `LIMIT` keyed
3520/// on score alone duplicates or skips when two leases share a
3521/// millisecond.
3522///
3523/// Backends order strictly by
3524/// `(expires_at_ms ASC, execution_id ASC)`.
3525#[non_exhaustive]
3526#[derive(Clone, Debug, PartialEq, Eq)]
3527pub struct ExpiredLeasesCursor {
3528 pub expires_at_ms: TimestampMs,
3529 pub execution_id: ExecutionId,
3530}
3531
3532impl ExpiredLeasesCursor {
3533 pub fn new(expires_at_ms: TimestampMs, execution_id: ExecutionId) -> Self {
3534 Self {
3535 expires_at_ms,
3536 execution_id,
3537 }
3538 }
3539}
3540
3541/// Default fan-out for `list_expired_leases` when
3542/// `max_partitions_per_call` is `None` (RFC-025 §9.2).
3543pub const LIST_EXPIRED_LEASES_DEFAULT_MAX_PARTITIONS: u32 = 32;
3544
3545/// Default page size when `limit` is `None`.
3546pub const LIST_EXPIRED_LEASES_DEFAULT_LIMIT: u32 = 1_000;
3547
3548/// Backend cap for `limit`.
3549pub const LIST_EXPIRED_LEASES_MAX_LIMIT: u32 = 10_000;
3550
3551/// Inputs to [`crate::engine_backend::EngineBackend::list_expired_leases`]
3552/// (RFC-025). Feature gate: `suspension`.
3553///
3554/// `namespace = None` = cross-namespace sweep for operator tooling
3555/// (auth enforced at the ff-server admin route, NOT the trait
3556/// boundary). `Some(ns)` = per-tenant scope.
3557#[non_exhaustive]
3558#[derive(Clone, Debug, PartialEq, Eq)]
3559pub struct ListExpiredLeasesArgs {
3560 /// Every returned lease has `expires_at_ms <= as_of`.
3561 pub as_of: TimestampMs,
3562 /// Exclusive pagination cursor. `None` = scan from earliest.
3563 pub after: Option<ExpiredLeasesCursor>,
3564 /// Default [`LIST_EXPIRED_LEASES_DEFAULT_LIMIT`] when `None`;
3565 /// backend cap [`LIST_EXPIRED_LEASES_MAX_LIMIT`].
3566 pub limit: Option<u32>,
3567 /// Default [`LIST_EXPIRED_LEASES_DEFAULT_MAX_PARTITIONS`] when
3568 /// `None`.
3569 pub max_partitions_per_call: Option<u32>,
3570 pub namespace: Option<Namespace>,
3571}
3572
3573impl ListExpiredLeasesArgs {
3574 pub fn new(as_of: TimestampMs) -> Self {
3575 Self {
3576 as_of,
3577 after: None,
3578 limit: None,
3579 max_partitions_per_call: None,
3580 namespace: None,
3581 }
3582 }
3583}
3584
3585#[non_exhaustive]
3586#[derive(Clone, Debug, PartialEq, Eq)]
3587pub struct ExpiredLeaseInfo {
3588 pub execution_id: ExecutionId,
3589 pub lease_id: LeaseId,
3590 pub lease_epoch: LeaseEpoch,
3591 pub worker_instance_id: WorkerInstanceId,
3592 pub expires_at_ms: TimestampMs,
3593 pub attempt_index: AttemptIndex,
3594}
3595
3596impl ExpiredLeaseInfo {
3597 pub fn new(
3598 execution_id: ExecutionId,
3599 lease_id: LeaseId,
3600 lease_epoch: LeaseEpoch,
3601 worker_instance_id: WorkerInstanceId,
3602 expires_at_ms: TimestampMs,
3603 attempt_index: AttemptIndex,
3604 ) -> Self {
3605 Self {
3606 execution_id,
3607 lease_id,
3608 lease_epoch,
3609 worker_instance_id,
3610 expires_at_ms,
3611 attempt_index,
3612 }
3613 }
3614}
3615
3616#[non_exhaustive]
3617#[derive(Clone, Debug, PartialEq, Eq)]
3618pub struct ListExpiredLeasesResult {
3619 pub entries: Vec<ExpiredLeaseInfo>,
3620 pub cursor: Option<ExpiredLeasesCursor>,
3621}
3622
3623impl ListExpiredLeasesResult {
3624 pub fn new(entries: Vec<ExpiredLeaseInfo>, cursor: Option<ExpiredLeasesCursor>) -> Self {
3625 Self { entries, cursor }
3626 }
3627}
3628
3629/// Inputs to [`crate::engine_backend::EngineBackend::list_workers`]
3630/// (RFC-025 Phase 6, §9.4).
3631#[non_exhaustive]
3632#[derive(Clone, Debug, PartialEq, Eq)]
3633pub struct ListWorkersArgs {
3634 /// `None` = cross-namespace sweep for operator tooling.
3635 pub namespace: Option<Namespace>,
3636 /// Exclusive pagination cursor.
3637 pub after: Option<WorkerInstanceId>,
3638 /// Default 1000 when `None`.
3639 pub limit: Option<u32>,
3640}
3641
3642impl ListWorkersArgs {
3643 pub fn new() -> Self {
3644 Self {
3645 namespace: None,
3646 after: None,
3647 limit: None,
3648 }
3649 }
3650}
3651
3652impl Default for ListWorkersArgs {
3653 fn default() -> Self {
3654 Self::new()
3655 }
3656}
3657
3658#[non_exhaustive]
3659#[derive(Clone, Debug, PartialEq, Eq)]
3660pub struct WorkerInfo {
3661 pub worker_id: WorkerId,
3662 pub worker_instance_id: WorkerInstanceId,
3663 pub namespace: Namespace,
3664 pub lanes: BTreeSet<LaneId>,
3665 pub capabilities: BTreeSet<String>,
3666 pub last_heartbeat_ms: TimestampMs,
3667 pub liveness_ttl_ms: u64,
3668 pub registered_at_ms: TimestampMs,
3669}
3670
3671impl WorkerInfo {
3672 #[allow(clippy::too_many_arguments)]
3673 pub fn new(
3674 worker_id: WorkerId,
3675 worker_instance_id: WorkerInstanceId,
3676 namespace: Namespace,
3677 lanes: BTreeSet<LaneId>,
3678 capabilities: BTreeSet<String>,
3679 last_heartbeat_ms: TimestampMs,
3680 liveness_ttl_ms: u64,
3681 registered_at_ms: TimestampMs,
3682 ) -> Self {
3683 Self {
3684 worker_id,
3685 worker_instance_id,
3686 namespace,
3687 lanes,
3688 capabilities,
3689 last_heartbeat_ms,
3690 liveness_ttl_ms,
3691 registered_at_ms,
3692 }
3693 }
3694}
3695
3696#[non_exhaustive]
3697#[derive(Clone, Debug, PartialEq, Eq)]
3698pub struct ListWorkersResult {
3699 pub entries: Vec<WorkerInfo>,
3700 pub cursor: Option<WorkerInstanceId>,
3701}
3702
3703impl ListWorkersResult {
3704 pub fn new(entries: Vec<WorkerInfo>, cursor: Option<WorkerInstanceId>) -> Self {
3705 Self { entries, cursor }
3706 }
3707}
3708
3709#[cfg(test)]
3710mod tests {
3711 use super::*;
3712 use crate::types::FlowId;
3713
3714 #[test]
3715 fn create_execution_args_serde() {
3716 let config = crate::partition::PartitionConfig::default();
3717 let args = CreateExecutionArgs {
3718 execution_id: ExecutionId::for_flow(&FlowId::new(), &config),
3719 namespace: Namespace::new("test"),
3720 lane_id: LaneId::new("default"),
3721 execution_kind: "llm_call".to_owned(),
3722 input_payload: b"hello".to_vec(),
3723 payload_encoding: Some("json".to_owned()),
3724 priority: 0,
3725 creator_identity: "test-user".to_owned(),
3726 idempotency_key: None,
3727 tags: HashMap::new(),
3728 policy: None,
3729 delay_until: None,
3730 execution_deadline_at: None,
3731 partition_id: 42,
3732 now: TimestampMs::now(),
3733 };
3734 let json = serde_json::to_string(&args).unwrap();
3735 let parsed: CreateExecutionArgs = serde_json::from_str(&json).unwrap();
3736 assert_eq!(args.execution_id, parsed.execution_id);
3737 }
3738
3739 #[test]
3740 fn claim_result_serde() {
3741 let config = crate::partition::PartitionConfig::default();
3742 let result = ClaimExecutionResult::Claimed(ClaimedExecution {
3743 execution_id: ExecutionId::for_flow(&FlowId::new(), &config),
3744 lease_id: LeaseId::new(),
3745 lease_epoch: LeaseEpoch::new(1),
3746 attempt_index: AttemptIndex::new(0),
3747 attempt_id: AttemptId::new(),
3748 attempt_type: AttemptType::Initial,
3749 lease_expires_at: TimestampMs::from_millis(1000),
3750 handle: crate::backend::stub_handle_fresh(),
3751 });
3752 let json = serde_json::to_string(&result).unwrap();
3753 let parsed: ClaimExecutionResult = serde_json::from_str(&json).unwrap();
3754 assert_eq!(result, parsed);
3755 }
3756
3757 // ── StreamCursor (issue #92) ──
3758
3759 #[test]
3760 fn stream_cursor_display_matches_wire_tokens() {
3761 assert_eq!(StreamCursor::Start.to_string(), "start");
3762 assert_eq!(StreamCursor::End.to_string(), "end");
3763 assert_eq!(StreamCursor::At("123".into()).to_string(), "123");
3764 assert_eq!(StreamCursor::At("123-4".into()).to_string(), "123-4");
3765 }
3766
3767 #[test]
3768 fn stream_cursor_to_wire_maps_to_valkey_markers() {
3769 assert_eq!(StreamCursor::Start.to_wire(), "-");
3770 assert_eq!(StreamCursor::End.to_wire(), "+");
3771 assert_eq!(StreamCursor::At("0-0".into()).to_wire(), "0-0");
3772 assert_eq!(StreamCursor::At("17-3".into()).to_wire(), "17-3");
3773 }
3774
3775 #[test]
3776 fn stream_cursor_from_str_accepts_wire_tokens() {
3777 use std::str::FromStr;
3778 assert_eq!(
3779 StreamCursor::from_str("start").unwrap(),
3780 StreamCursor::Start
3781 );
3782 assert_eq!(StreamCursor::from_str("end").unwrap(), StreamCursor::End);
3783 assert_eq!(
3784 StreamCursor::from_str("123").unwrap(),
3785 StreamCursor::At("123".into())
3786 );
3787 assert_eq!(
3788 StreamCursor::from_str("0-0").unwrap(),
3789 StreamCursor::At("0-0".into())
3790 );
3791 assert_eq!(
3792 StreamCursor::from_str("1713100800150-0").unwrap(),
3793 StreamCursor::At("1713100800150-0".into())
3794 );
3795 }
3796
3797 #[test]
3798 fn stream_cursor_from_str_rejects_bare_markers() {
3799 use std::str::FromStr;
3800 assert!(matches!(
3801 StreamCursor::from_str("-"),
3802 Err(StreamCursorParseError::BareMarkerRejected(s)) if s == "-"
3803 ));
3804 assert!(matches!(
3805 StreamCursor::from_str("+"),
3806 Err(StreamCursorParseError::BareMarkerRejected(s)) if s == "+"
3807 ));
3808 }
3809
3810 #[test]
3811 fn stream_cursor_from_str_rejects_empty() {
3812 use std::str::FromStr;
3813 assert_eq!(
3814 StreamCursor::from_str(""),
3815 Err(StreamCursorParseError::Empty)
3816 );
3817 }
3818
3819 #[test]
3820 fn stream_cursor_from_str_rejects_malformed() {
3821 use std::str::FromStr;
3822 for bad in [
3823 "abc", "-1", "1-", "-1-2", "1-2-3", "1.2", "1 2", "Start", "END",
3824 ] {
3825 assert!(
3826 matches!(
3827 StreamCursor::from_str(bad),
3828 Err(StreamCursorParseError::Malformed(_))
3829 ),
3830 "must reject {bad:?}",
3831 );
3832 }
3833 }
3834
3835 #[test]
3836 fn stream_cursor_from_str_rejects_non_ascii() {
3837 use std::str::FromStr;
3838 assert!(matches!(
3839 StreamCursor::from_str("1\u{2013}2"),
3840 Err(StreamCursorParseError::Malformed(_))
3841 ));
3842 }
3843
3844 #[test]
3845 fn stream_cursor_serde_round_trip() {
3846 for c in [
3847 StreamCursor::Start,
3848 StreamCursor::End,
3849 StreamCursor::At("0-0".into()),
3850 StreamCursor::At("1713100800150-0".into()),
3851 ] {
3852 let json = serde_json::to_string(&c).unwrap();
3853 let back: StreamCursor = serde_json::from_str(&json).unwrap();
3854 assert_eq!(back, c);
3855 }
3856 }
3857
3858 #[test]
3859 fn stream_cursor_serializes_as_bare_string() {
3860 assert_eq!(
3861 serde_json::to_string(&StreamCursor::Start).unwrap(),
3862 r#""start""#
3863 );
3864 assert_eq!(
3865 serde_json::to_string(&StreamCursor::End).unwrap(),
3866 r#""end""#
3867 );
3868 assert_eq!(
3869 serde_json::to_string(&StreamCursor::At("123-0".into())).unwrap(),
3870 r#""123-0""#
3871 );
3872 }
3873
3874 #[test]
3875 fn stream_cursor_deserialize_rejects_bare_markers() {
3876 assert!(serde_json::from_str::<StreamCursor>(r#""-""#).is_err());
3877 assert!(serde_json::from_str::<StreamCursor>(r#""+""#).is_err());
3878 }
3879
3880 #[test]
3881 fn stream_cursor_from_beginning_is_zero_zero() {
3882 assert_eq!(
3883 StreamCursor::from_beginning(),
3884 StreamCursor::At("0-0".into())
3885 );
3886 }
3887
3888 #[test]
3889 fn stream_cursor_is_concrete_classifies_variants() {
3890 assert!(!StreamCursor::Start.is_concrete());
3891 assert!(!StreamCursor::End.is_concrete());
3892 assert!(StreamCursor::At("0-0".into()).is_concrete());
3893 assert!(StreamCursor::At("123-0".into()).is_concrete());
3894 assert!(StreamCursor::from_beginning().is_concrete());
3895 }
3896
3897 #[test]
3898 fn stream_cursor_into_wire_string_moves_without_cloning() {
3899 assert_eq!(StreamCursor::Start.into_wire_string(), "-");
3900 assert_eq!(StreamCursor::End.into_wire_string(), "+");
3901 assert_eq!(StreamCursor::At("17-3".into()).into_wire_string(), "17-3");
3902 }
3903}
3904
3905// ─── list_executions ───
3906
3907/// Summary of an execution for list views.
3908#[derive(Clone, Debug, Serialize, Deserialize)]
3909pub struct ExecutionSummary {
3910 pub execution_id: ExecutionId,
3911 pub namespace: String,
3912 pub lane_id: String,
3913 pub execution_kind: String,
3914 pub public_state: String,
3915 pub priority: i32,
3916 pub created_at: String,
3917}
3918
3919/// Result of a list_executions query.
3920#[derive(Clone, Debug, Serialize, Deserialize)]
3921pub struct ListExecutionsResult {
3922 pub executions: Vec<ExecutionSummary>,
3923 pub total_returned: usize,
3924}
3925
3926// ─── list_lanes (issue #184) ───
3927
3928/// One page of lane ids returned by
3929/// [`crate::engine_backend::EngineBackend::list_lanes`].
3930///
3931/// Lanes are global (not partition-scoped) — the backend enumerates
3932/// every registered lane, sorts by [`LaneId`] name, and returns a
3933/// `limit`-sized slice starting after `cursor` (exclusive).
3934///
3935/// `next_cursor` is `Some(last_lane_in_page)` when more pages remain
3936/// and `None` when the caller has read the final page. Callers that
3937/// want the full list loop until `next_cursor` is `None`, threading
3938/// the previous page's `next_cursor` into the next call's `cursor`
3939/// argument.
3940///
3941/// `#[non_exhaustive]` — FF may add fields (e.g. a `total` hint) in
3942/// minor releases without a semver break.
3943#[derive(Clone, Debug, PartialEq, Eq)]
3944#[non_exhaustive]
3945pub struct ListLanesPage {
3946 /// The lanes in this page, sorted by [`LaneId`] name.
3947 pub lanes: Vec<LaneId>,
3948 /// Cursor for the next page (exclusive). `None` ⇒ final page.
3949 pub next_cursor: Option<LaneId>,
3950}
3951
3952impl ListLanesPage {
3953 /// Construct a [`ListLanesPage`]. Present so downstream crates
3954 /// (ff-backend-valkey's `list_lanes` impl) can assemble the
3955 /// struct despite the `#[non_exhaustive]` marker.
3956 pub fn new(lanes: Vec<LaneId>, next_cursor: Option<LaneId>) -> Self {
3957 Self { lanes, next_cursor }
3958 }
3959}
3960
3961// ─── list_suspended ───
3962
3963/// One entry in a [`ListSuspendedPage`] — a suspended execution and
3964/// the reason it is blocked, answering an operator's "what's this
3965/// waiting on?" without a follow-up round-trip.
3966///
3967/// `reason` carries the free-form `reason_code` recorded by the
3968/// suspending worker at `lua/suspension.lua` (HSET `suspension:current
3969/// reason_code`). It is a `String`, not a closed enum: the suspension
3970/// pipeline accepts arbitrary caller-supplied codes (typical values
3971/// are `"signal"`, `"timer"`, `"children"`, `"join"`, but consumers
3972/// embed bespoke codes). A future enum projection can classify
3973/// known codes once the set is frozen; until then, callers that want
3974/// structured routing MUST match on the string explicitly.
3975#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3976#[non_exhaustive]
3977pub struct SuspendedExecutionEntry {
3978 /// Execution currently in `lifecycle_phase=suspended`.
3979 pub execution_id: ExecutionId,
3980 /// Score stored on the per-lane suspended ZSET — the scheduled
3981 /// `timeout_at` in milliseconds, or the `9999999999999` sentinel
3982 /// when no timeout was set (see `lua/suspension.lua`).
3983 pub suspended_at_ms: i64,
3984 /// Free-form reason code from `suspension:current.reason_code`.
3985 /// Empty string when the suspension hash is absent or does not
3986 /// carry a `reason_code` field (older records). See the struct
3987 /// rustdoc for the deliberate-String rationale.
3988 pub reason: String,
3989}
3990
3991impl SuspendedExecutionEntry {
3992 /// Construct a new entry. Preferred over direct field init for
3993 /// `#[non_exhaustive]` forward-compat.
3994 pub fn new(execution_id: ExecutionId, suspended_at_ms: i64, reason: String) -> Self {
3995 Self {
3996 execution_id,
3997 suspended_at_ms,
3998 reason,
3999 }
4000 }
4001}
4002
4003/// One cursor-paginated page of suspended executions.
4004///
4005/// Pagination is cursor-based (not offset/limit) so a Valkey backend
4006/// can resume a partition scan from the last seen execution id and a
4007/// future Postgres backend can do keyset pagination on
4008/// `executions WHERE state='suspended'`. The cursor is opaque to
4009/// callers: pass `next_cursor` back as the `cursor` argument to the
4010/// next [`EngineBackend::list_suspended`] call to fetch the next
4011/// page. `None` means the stream is exhausted.
4012///
4013/// [`EngineBackend::list_suspended`]: crate::engine_backend::EngineBackend::list_suspended
4014#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4015#[non_exhaustive]
4016pub struct ListSuspendedPage {
4017 /// Entries on this page, ordered by ascending `suspended_at_ms`
4018 /// (timeout order) with `execution_id` as a lex tiebreak.
4019 pub entries: Vec<SuspendedExecutionEntry>,
4020 /// Resume-point for the next page. `None` when no further
4021 /// entries remain in the partition.
4022 pub next_cursor: Option<ExecutionId>,
4023}
4024
4025impl ListSuspendedPage {
4026 /// Construct a new page. Preferred over direct field init for
4027 /// `#[non_exhaustive]` forward-compat.
4028 pub fn new(entries: Vec<SuspendedExecutionEntry>, next_cursor: Option<ExecutionId>) -> Self {
4029 Self {
4030 entries,
4031 next_cursor,
4032 }
4033 }
4034}
4035
4036// ─── list_executions ───
4037
4038/// One page of partition-scoped execution ids returned by
4039/// [`EngineBackend::list_executions`](crate::engine_backend::EngineBackend::list_executions).
4040///
4041/// Pagination is forward-only and cursor-based. `next_cursor` carries
4042/// the last `ExecutionId` emitted in `executions` iff another page is
4043/// available; callers pass that id back as the next call's `cursor`
4044/// (exclusive start). `next_cursor = None` signals end-of-stream.
4045///
4046/// `#[non_exhaustive]` — FF may add fields (e.g. `approximate_total`)
4047/// in minor releases without a semver break. Use
4048/// [`ListExecutionsPage::new`] for cross-crate construction.
4049#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4050#[non_exhaustive]
4051pub struct ListExecutionsPage {
4052 /// Execution ids on this page, in ascending lexicographic order.
4053 pub executions: Vec<ExecutionId>,
4054 /// Exclusive cursor to request the next page. `None` ⇒ no more
4055 /// results.
4056 pub next_cursor: Option<ExecutionId>,
4057}
4058
4059impl ListExecutionsPage {
4060 /// Construct a [`ListExecutionsPage`]. Present so downstream
4061 /// crates can assemble the struct despite the `#[non_exhaustive]`
4062 /// marker.
4063 pub fn new(executions: Vec<ExecutionId>, next_cursor: Option<ExecutionId>) -> Self {
4064 Self { executions, next_cursor }
4065 }
4066}
4067
4068// ─── rotate_waitpoint_hmac_secret ───
4069
4070/// Args for `ff_rotate_waitpoint_hmac_secret`. Rotates the HMAC signing
4071/// kid on ONE partition. Callers fan out across every partition themselves
4072/// (ff-server does the parallel fan-out in `rotate_waitpoint_secret`;
4073/// direct-Valkey consumers mirror the pattern).
4074///
4075/// "now" is derived server-side from `redis.call("TIME")` inside the FCALL
4076/// (consistency with `validate_waitpoint_token` and flow scanners).
4077/// `grace_ms` is a duration, not a clock value, so carrying it from the
4078/// caller is safe.
4079#[derive(Clone, Debug)]
4080pub struct RotateWaitpointHmacSecretArgs {
4081 pub new_kid: String,
4082 pub new_secret_hex: String,
4083 /// Grace window in ms. Must be non-negative. Tokens signed by the
4084 /// outgoing kid remain valid for `grace_ms` after this rotation.
4085 pub grace_ms: u64,
4086}
4087
4088/// Outcome of a single-partition rotation.
4089#[derive(Clone, Debug, PartialEq, Eq)]
4090pub enum RotateWaitpointHmacSecretOutcome {
4091 /// Installed the new kid. `previous_kid` is `None` on bootstrap
4092 /// (no prior `current_kid`). `gc_count` counts expired kids reaped
4093 /// during this rotation.
4094 Rotated {
4095 previous_kid: Option<String>,
4096 new_kid: String,
4097 gc_count: u32,
4098 },
4099 /// Exact replay — same kid + same secret already installed. Safe
4100 /// operator retry; no state change.
4101 Noop { kid: String },
4102}
4103
4104// ─── rotate_waitpoint_hmac_secret_all ───
4105
4106/// Args for [`EngineBackend::rotate_waitpoint_hmac_secret_all`] — the
4107/// cluster-wide / backend-native rotation of the waitpoint HMAC
4108/// signing kid.
4109///
4110/// **v0.7 migration-master Q4:** a single additive trait method
4111/// replaces the per-partition fan-out that direct-Valkey consumers
4112/// hand-rolled via
4113/// [`ff_sdk::admin::rotate_waitpoint_hmac_secret_all_partitions`].
4114/// On Valkey it fans out N FCALLs (one per execution partition);
4115/// on Postgres (Wave 4) it resolves to a single INSERT against the
4116/// global `ff_waitpoint_hmac(kid, secret, rotated_at)` table (no
4117/// partition_id column). Consumers prefer this method for clarity —
4118/// the pre-existing free-fn + per-partition surface stays available
4119/// for backwards compat.
4120///
4121/// `#[non_exhaustive]` with a [`Self::new`] constructor per the
4122/// project memory-rule (unbuildable non_exhaustive types are a dead
4123/// API).
4124#[derive(Clone, Debug)]
4125#[non_exhaustive]
4126pub struct RotateWaitpointHmacSecretAllArgs {
4127 pub new_kid: String,
4128 pub new_secret_hex: String,
4129 /// Grace window in ms for tokens signed by the outgoing kid.
4130 /// Duration (not a clock value), identical to
4131 /// [`RotateWaitpointHmacSecretArgs::grace_ms`].
4132 pub grace_ms: u64,
4133}
4134
4135impl RotateWaitpointHmacSecretAllArgs {
4136 /// Build the args. Keeping the constructor so consumers don't
4137 /// struct-literal past the `#[non_exhaustive]` marker.
4138 pub fn new(
4139 new_kid: impl Into<String>,
4140 new_secret_hex: impl Into<String>,
4141 grace_ms: u64,
4142 ) -> Self {
4143 Self {
4144 new_kid: new_kid.into(),
4145 new_secret_hex: new_secret_hex.into(),
4146 grace_ms,
4147 }
4148 }
4149}
4150
4151/// Per-partition entry of [`RotateWaitpointHmacSecretAllResult`].
4152/// Mirrors [`ff_sdk::admin::PartitionRotationOutcome`] but typed at
4153/// the `ff-core` layer so both Valkey and Postgres backends return
4154/// the same shape without a Postgres→ferriskey dep.
4155///
4156/// On backends with no partition concept (Postgres) the entry list
4157/// has length 1 with `partition = 0` and the outcome of the global
4158/// row write.
4159#[derive(Debug)]
4160#[non_exhaustive]
4161pub struct RotateWaitpointHmacSecretAllEntry {
4162 pub partition: u16,
4163 /// The per-partition (or global) rotation outcome. Per-partition
4164 /// failures are surfaced as inner `Err` so the fan-out can report
4165 /// partial success — matching the existing SDK free-fn contract.
4166 pub result: Result<RotateWaitpointHmacSecretOutcome, crate::engine_error::EngineError>,
4167}
4168
4169impl RotateWaitpointHmacSecretAllEntry {
4170 pub fn new(
4171 partition: u16,
4172 result: Result<RotateWaitpointHmacSecretOutcome, crate::engine_error::EngineError>,
4173 ) -> Self {
4174 Self { partition, result }
4175 }
4176}
4177
4178/// Result of [`EngineBackend::rotate_waitpoint_hmac_secret_all`].
4179///
4180/// The Valkey backend returns one entry per execution partition. The
4181/// Postgres backend (Wave 4) will return a single-entry vec with
4182/// `partition = 0` since the Postgres schema stores one global row
4183/// per kid (Q4 §adjudication). Consumers that want a uniform "did
4184/// ALL rotations succeed?" view inspect each entry's `.result`.
4185#[derive(Debug)]
4186#[non_exhaustive]
4187pub struct RotateWaitpointHmacSecretAllResult {
4188 pub entries: Vec<RotateWaitpointHmacSecretAllEntry>,
4189}
4190
4191impl RotateWaitpointHmacSecretAllResult {
4192 pub fn new(entries: Vec<RotateWaitpointHmacSecretAllEntry>) -> Self {
4193 Self { entries }
4194 }
4195}
4196
4197// ─── seed_waitpoint_hmac_secret (issue #280) ───
4198
4199/// Args for [`EngineBackend::seed_waitpoint_hmac_secret`].
4200///
4201/// Two required fields and no optional knobs, so there is no fluent
4202/// builder — just `new(kid, secret_hex)`. `#[non_exhaustive]` is kept
4203/// (with the paired constructor, per the project memory rule) so
4204/// future additive knobs don't break callers.
4205///
4206/// Boot-time provisioning entry point for fresh deployments — see
4207/// issue #280 for why cairn needed this in addition to
4208/// [`RotateWaitpointHmacSecretAllArgs`]. Unlike rotate, seed is
4209/// idempotent: callers invoke it on every boot and the backend
4210/// decides whether to install.
4211#[derive(Clone, Debug)]
4212#[non_exhaustive]
4213pub struct SeedWaitpointHmacSecretArgs {
4214 pub kid: String,
4215 pub secret_hex: String,
4216}
4217
4218impl SeedWaitpointHmacSecretArgs {
4219 pub fn new(kid: impl Into<String>, secret_hex: impl Into<String>) -> Self {
4220 Self {
4221 kid: kid.into(),
4222 secret_hex: secret_hex.into(),
4223 }
4224 }
4225}
4226
4227/// Result of [`EngineBackend::seed_waitpoint_hmac_secret`].
4228///
4229/// * `Seeded` — the backend had no `current_kid` (or no row in the
4230/// global keystore) and installed `kid` as the active signing kid.
4231/// * `AlreadySeeded` — a row for `kid` is already installed.
4232/// `same_secret` reports whether the stored secret bytes match the
4233/// caller-supplied hex; `false` means the caller should pick a fresh
4234/// kid for rotation rather than silently re-installing under the
4235/// existing kid.
4236#[derive(Clone, Debug, PartialEq, Eq)]
4237#[non_exhaustive]
4238pub enum SeedOutcome {
4239 Seeded { kid: String },
4240 AlreadySeeded { kid: String, same_secret: bool },
4241}
4242
4243// ─── list_waitpoint_hmac_kids ───
4244
4245#[derive(Clone, Debug, PartialEq, Eq)]
4246pub struct ListWaitpointHmacKidsArgs {}
4247
4248/// Snapshot of the waitpoint HMAC keystore on ONE partition.
4249#[derive(Clone, Debug, PartialEq, Eq)]
4250pub struct WaitpointHmacKids {
4251 /// The currently-signing kid. `None` if uninitialized.
4252 pub current_kid: Option<String>,
4253 /// Kids that still validate existing tokens but no longer sign
4254 /// new ones. Order is Lua HGETALL traversal order — callers that
4255 /// need a stable sort should sort by `expires_at_ms`.
4256 pub verifying: Vec<VerifyingKid>,
4257}
4258
4259#[derive(Clone, Debug, PartialEq, Eq)]
4260pub struct VerifyingKid {
4261 pub kid: String,
4262 pub expires_at_ms: i64,
4263}
4264
4265// ═══════════════════════════════════════════════════════════════════════
4266// RFC-013 Stage 1d: EngineBackend::suspend typed args + outcome
4267// ═══════════════════════════════════════════════════════════════════════
4268//
4269// `SuspendExecutionArgs` / `SuspendExecutionResult` above remain the
4270// wire-level Lua-ARGV mirror used by the backend serializer. The types
4271// below are the public trait-surface shapes RFC-013 §2.2–§2.6 specifies.
4272//
4273// Every type in this block is `#[non_exhaustive]` per the RFC §2.2.1
4274// memory-rule compliance note; each gets a constructor so external-crate
4275// consumers can build them without struct-literal access.
4276
4277use crate::backend::WaitpointHmac;
4278
4279/// Partition-scoped idempotency key for retry-safe `EngineBackend::suspend`.
4280///
4281/// See RFC-013 §2.2 — when set on [`SuspendArgs::idempotency_key`], the
4282/// backend dedups the call on `(partition, execution_id, idempotency_key)`
4283/// and a second `suspend` with the same triple returns the first call's
4284/// [`SuspendOutcome`] verbatim. Absent a key, `suspend` is NOT retry-
4285/// idempotent; callers must describe-and-reconcile per §3.1.
4286///
4287/// Follows the `UsageDimensions::dedup_key` pattern — opaque to the
4288/// engine, byte-compared at the partition scope.
4289#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
4290#[serde(transparent)]
4291pub struct IdempotencyKey(String);
4292
4293impl IdempotencyKey {
4294 /// Construct from any stringy input. Empty strings are accepted;
4295 /// the backend treats an empty key as "no dedup" at the serialize
4296 /// step so `Some(IdempotencyKey::new(""))` is functionally the same
4297 /// as `None`.
4298 pub fn new(key: impl Into<String>) -> Self {
4299 Self(key.into())
4300 }
4301
4302 /// Borrow the underlying string.
4303 pub fn as_str(&self) -> &str {
4304 &self.0
4305 }
4306}
4307
4308impl std::fmt::Display for IdempotencyKey {
4309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4310 f.write_str(&self.0)
4311 }
4312}
4313
4314/// v1 signal-match predicate inside [`ResumeCondition::Single`].
4315///
4316/// RFC-013 §2.4 — `ByName(String)` matches a single concrete signal
4317/// name; `Wildcard` matches any delivered signal. RFC-014 may extend
4318/// (payload predicates, pattern matching) — `#[non_exhaustive]`.
4319#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4320#[non_exhaustive]
4321pub enum SignalMatcher {
4322 /// Match by exact signal name.
4323 ByName(String),
4324 /// Match any signal delivered to the waitpoint.
4325 Wildcard,
4326}
4327
4328/// Hard cap on composite-condition nesting depth (RFC-014 §5.4
4329/// invariant 4; §5.5 cap rationale). Soft-cap: bumping requires only
4330/// this constant + the cap-rationale paragraph in RFC-014 §5.5 — no
4331/// wire-format change. Keep in sync.
4332pub const MAX_COMPOSITE_DEPTH: usize = 4;
4333
4334/// RFC-013 reserves this enum slot; RFC-014 populates it with the
4335/// concrete composition vocabulary (`AllOf` + `Count`). The enum is
4336/// `#[non_exhaustive]` so RFC-016 or later RFCs may add variants
4337/// (`AnyOf` has been explicitly rejected per RFC-014 §2.3 in favour of
4338/// `Count { n: 1, .. }`; the guard exists for orthogonal future work).
4339#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4340#[serde(tag = "kind")]
4341#[non_exhaustive]
4342pub enum CompositeBody {
4343 /// All listed sub-conditions must be satisfied. Order-independent.
4344 /// Once satisfied, further signals to member waitpoints are observed
4345 /// but do not re-open satisfaction. RFC-014 §2.1.
4346 AllOf {
4347 members: Vec<ResumeCondition>,
4348 },
4349 /// At least `n` distinct satisfiers (by [`CountKind`]) must match.
4350 /// `matcher` optionally constrains participating signals; `None`
4351 /// lets any signal on any of `waitpoints` count. RFC-014 §2.1.
4352 Count {
4353 n: u32,
4354 count_kind: CountKind,
4355 #[serde(default, skip_serializing_if = "Option::is_none")]
4356 matcher: Option<SignalMatcher>,
4357 waitpoints: Vec<String>,
4358 },
4359}
4360
4361/// How `Count` nodes distinguish satisfiers. RFC-014 §2.1 + §3.2.
4362#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4363#[non_exhaustive]
4364pub enum CountKind {
4365 /// n distinct `waitpoint_id`s in `waitpoints` must fire.
4366 DistinctWaitpoints,
4367 /// n distinct `signal_id`s across the waitpoint set.
4368 DistinctSignals,
4369 /// n distinct `source_type:source_identity` tuples.
4370 DistinctSources,
4371}
4372
4373impl CompositeBody {
4374 /// `AllOf { members }` constructor (RFC-014 §10.3 SDK surface).
4375 pub fn all_of(members: impl IntoIterator<Item = ResumeCondition>) -> Self {
4376 Self::AllOf {
4377 members: members.into_iter().collect(),
4378 }
4379 }
4380
4381 /// `Count` constructor with explicit kind + waitpoint set.
4382 pub fn count(
4383 n: u32,
4384 count_kind: CountKind,
4385 matcher: Option<SignalMatcher>,
4386 waitpoints: impl IntoIterator<Item = String>,
4387 ) -> Self {
4388 Self::Count {
4389 n,
4390 count_kind,
4391 matcher,
4392 waitpoints: waitpoints.into_iter().collect(),
4393 }
4394 }
4395}
4396
4397/// Declarative resume condition for [`SuspendArgs::resume_condition`].
4398///
4399/// RFC-013 §2.4 — typed replacement for the SDK's former
4400/// `ConditionMatcher` / `resume_condition_json` pair.
4401#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4402#[non_exhaustive]
4403pub enum ResumeCondition {
4404 /// Single waitpoint-key match with a predicate. `matcher` is
4405 /// evaluated against every signal delivered to `waitpoint_key`.
4406 Single {
4407 waitpoint_key: String,
4408 matcher: SignalMatcher,
4409 },
4410 /// Operator-only resume — no signal satisfies; only an explicit
4411 /// operator resume closes the waitpoint.
4412 OperatorOnly,
4413 /// Pure-timeout suspension. No signal satisfier; the waitpoint
4414 /// resolves only via `timeout_behavior` at `timeout_at`. Requires
4415 /// `SuspendArgs::timeout_at` to be `Some(_)` — otherwise the
4416 /// Rust-side validator rejects as `timeout_only_without_deadline`.
4417 TimeoutOnly,
4418 /// Multi-condition composition; RFC-014 defines the body.
4419 Composite(CompositeBody),
4420}
4421
4422/// RFC-014 §5.1 validation error shape. Emitted by
4423/// [`ResumeCondition::validate_composite`] when a composite fails a
4424/// structural / cardinality invariant at suspend-time, before any Valkey
4425/// call. Carries a human-readable `detail` per §5.1.1.
4426#[derive(Clone, Debug, PartialEq, Eq)]
4427pub struct CompositeValidationError {
4428 pub detail: String,
4429}
4430
4431impl CompositeValidationError {
4432 fn new(detail: impl Into<String>) -> Self {
4433 Self {
4434 detail: detail.into(),
4435 }
4436 }
4437}
4438
4439impl ResumeCondition {
4440 /// RFC-014 §10.3 builder — `AllOf` across N distinct waitpoints,
4441 /// each member a `Single { matcher: Wildcard }` leaf. Canonical
4442 /// Pattern 3 shape for heterogeneous-subsystem "all fired"
4443 /// semantics (e.g. `db-migration-complete` + `cache-warmed` +
4444 /// `feature-flag-set`).
4445 ///
4446 /// Callers that need per-waitpoint matchers should construct the
4447 /// tree directly via
4448 /// [`ResumeCondition::Composite(CompositeBody::all_of(..))`].
4449 pub fn all_of_waitpoints<I, S>(waitpoint_keys: I) -> Self
4450 where
4451 I: IntoIterator<Item = S>,
4452 S: Into<String>,
4453 {
4454 let members: Vec<ResumeCondition> = waitpoint_keys
4455 .into_iter()
4456 .map(|k| ResumeCondition::Single {
4457 waitpoint_key: k.into(),
4458 matcher: SignalMatcher::Wildcard,
4459 })
4460 .collect();
4461 ResumeCondition::Composite(CompositeBody::AllOf { members })
4462 }
4463
4464 /// Collect every distinct `waitpoint_key` the condition targets.
4465 /// Used at suspend-time to validate the condition's wp set against
4466 /// `SuspendArgs.waitpoints` (RFC-014 §5.1 multi-binding cross-
4467 /// check). Order follows tree DFS, de-duplicated preserving first
4468 /// occurrence.
4469 pub fn referenced_waitpoint_keys(&self) -> Vec<String> {
4470 let mut out: Vec<String> = Vec::new();
4471 let mut push = |k: &str| {
4472 if !out.iter().any(|e| e == k) {
4473 out.push(k.to_owned());
4474 }
4475 };
4476 fn walk(cond: &ResumeCondition, push: &mut dyn FnMut(&str)) {
4477 match cond {
4478 ResumeCondition::Single { waitpoint_key, .. } => push(waitpoint_key),
4479 ResumeCondition::Composite(body) => walk_body(body, push),
4480 _ => {}
4481 }
4482 }
4483 fn walk_body(body: &CompositeBody, push: &mut dyn FnMut(&str)) {
4484 match body {
4485 CompositeBody::AllOf { members } => {
4486 for m in members {
4487 walk(m, push);
4488 }
4489 }
4490 CompositeBody::Count { waitpoints, .. } => {
4491 for w in waitpoints {
4492 push(w.as_str());
4493 }
4494 }
4495 }
4496 }
4497 walk(self, &mut push);
4498 out
4499 }
4500
4501 /// Validate RFC-014 structural invariants on a composite condition.
4502 /// Single / OperatorOnly / TimeoutOnly return Ok — they carry no
4503 /// composite body. Checks cover:
4504 /// * `AllOf { members: [] }` — §5.1 `allof_empty_members`
4505 /// * `Count { n: 0 }` — §5.1 `count_n_zero`
4506 /// * `Count { waitpoints: [] }` — §5.1 `count_waitpoints_empty`
4507 /// * `Count { n > waitpoints.len(), DistinctWaitpoints }` — §5.1
4508 /// `count_exceeds_waitpoint_set`
4509 /// * depth > [`MAX_COMPOSITE_DEPTH`] — §5.1 `condition_depth_exceeded`
4510 pub fn validate_composite(&self) -> Result<(), CompositeValidationError> {
4511 match self {
4512 ResumeCondition::Composite(body) => validate_body(body, 1, ""),
4513 _ => Ok(()),
4514 }
4515 }
4516}
4517
4518fn validate_body(
4519 body: &CompositeBody,
4520 depth: usize,
4521 path: &str,
4522) -> Result<(), CompositeValidationError> {
4523 if depth > MAX_COMPOSITE_DEPTH {
4524 return Err(CompositeValidationError::new(format!(
4525 "depth {} exceeds cap {} at path {}",
4526 depth,
4527 MAX_COMPOSITE_DEPTH,
4528 if path.is_empty() { "<root>" } else { path }
4529 )));
4530 }
4531 match body {
4532 CompositeBody::AllOf { members } => {
4533 if members.is_empty() {
4534 return Err(CompositeValidationError::new(format!(
4535 "allof_empty_members at path {}",
4536 if path.is_empty() { "<root>" } else { path }
4537 )));
4538 }
4539 for (i, m) in members.iter().enumerate() {
4540 let child_path = if path.is_empty() {
4541 format!("members[{i}]")
4542 } else {
4543 format!("{path}.members[{i}]")
4544 };
4545 if let ResumeCondition::Composite(inner) = m {
4546 validate_body(inner, depth + 1, &child_path)?;
4547 }
4548 // Leaf `Single` / operator / timeout needs no further
4549 // structural checks — RFC-013 already constrains them.
4550 }
4551 Ok(())
4552 }
4553 CompositeBody::Count {
4554 n,
4555 count_kind,
4556 waitpoints,
4557 ..
4558 } => {
4559 if *n == 0 {
4560 return Err(CompositeValidationError::new(format!(
4561 "count_n_zero at path {}",
4562 if path.is_empty() { "<root>" } else { path }
4563 )));
4564 }
4565 if waitpoints.is_empty() {
4566 return Err(CompositeValidationError::new(format!(
4567 "count_waitpoints_empty at path {}",
4568 if path.is_empty() { "<root>" } else { path }
4569 )));
4570 }
4571 if matches!(count_kind, CountKind::DistinctWaitpoints)
4572 && (*n as usize) > waitpoints.len()
4573 {
4574 return Err(CompositeValidationError::new(format!(
4575 "count_exceeds_waitpoint_set: n={} > waitpoints.len()={} at path {}",
4576 n,
4577 waitpoints.len(),
4578 if path.is_empty() { "<root>" } else { path }
4579 )));
4580 }
4581 Ok(())
4582 }
4583 }
4584}
4585
4586/// Where a satisfied suspension routes back to.
4587///
4588/// v1 ships only [`ResumeTarget::Runnable`] — execution returns to
4589/// `runnable` and goes through normal scheduling.
4590#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4591#[non_exhaustive]
4592pub enum ResumeTarget {
4593 Runnable,
4594}
4595
4596/// Resume-side policy carried alongside [`ResumeCondition`].
4597///
4598/// RFC-013 §2.5 — what happens when the condition is satisfied. Fields
4599/// mirror the `resume_policy_json` the backend serializer writes to Lua
4600/// (RFC-004 §Resume policy fields).
4601#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4602#[non_exhaustive]
4603pub struct ResumePolicy {
4604 pub resume_target: ResumeTarget,
4605 pub consume_matched_signals: bool,
4606 pub retain_signal_buffer_until_closed: bool,
4607 #[serde(default, skip_serializing_if = "Option::is_none")]
4608 pub resume_delay_ms: Option<u64>,
4609 pub close_waitpoint_on_resume: bool,
4610}
4611
4612impl Default for ResumePolicy {
4613 fn default() -> Self {
4614 Self::normal()
4615 }
4616}
4617
4618impl ResumePolicy {
4619 /// Construct a [`ResumePolicy`] with the canonical v1 defaults
4620 /// (see [`Self::normal`]). Alias for [`Self::normal`] — provided
4621 /// so external consumers have a conventional `new` constructor
4622 /// against this `#[non_exhaustive]` struct.
4623 pub fn new() -> Self {
4624 Self::normal()
4625 }
4626
4627 /// Canonical v1 defaults (RFC-013 §2.2.1):
4628 /// * `resume_target = Runnable`
4629 /// * `consume_matched_signals = true`
4630 /// * `retain_signal_buffer_until_closed = false`
4631 /// * `resume_delay_ms = None`
4632 /// * `close_waitpoint_on_resume = true`
4633 pub fn normal() -> Self {
4634 Self {
4635 resume_target: ResumeTarget::Runnable,
4636 consume_matched_signals: true,
4637 retain_signal_buffer_until_closed: false,
4638 resume_delay_ms: None,
4639 close_waitpoint_on_resume: true,
4640 }
4641 }
4642}
4643
4644/// Timeout behavior at the suspension deadline (RFC-004 §Timeout Behavior).
4645#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4646#[non_exhaustive]
4647pub enum TimeoutBehavior {
4648 Fail,
4649 Cancel,
4650 Expire,
4651 AutoResumeWithTimeoutSignal,
4652 /// v2 per RFC-004 Implementation Notes; enum slot present for
4653 /// additive RFC-014/RFC-015 landing.
4654 Escalate,
4655}
4656
4657impl TimeoutBehavior {
4658 /// Lua-side string encoding. Matches the wire values Lua's
4659 /// `ff_expire_suspension` matches on.
4660 pub fn as_wire_str(self) -> &'static str {
4661 match self {
4662 Self::Fail => "fail",
4663 Self::Cancel => "cancel",
4664 Self::Expire => "expire",
4665 Self::AutoResumeWithTimeoutSignal => "auto_resume_with_timeout_signal",
4666 Self::Escalate => "escalate",
4667 }
4668 }
4669}
4670
4671/// Reason category for a suspension (RFC-004 §Suspension Reason Categories).
4672#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4673#[non_exhaustive]
4674pub enum SuspensionReasonCode {
4675 WaitingForSignal,
4676 WaitingForApproval,
4677 WaitingForCallback,
4678 WaitingForToolResult,
4679 WaitingForOperatorReview,
4680 PausedByPolicy,
4681 PausedByBudget,
4682 StepBoundary,
4683 ManualPause,
4684}
4685
4686impl SuspensionReasonCode {
4687 pub fn as_wire_str(self) -> &'static str {
4688 match self {
4689 Self::WaitingForSignal => "waiting_for_signal",
4690 Self::WaitingForApproval => "waiting_for_approval",
4691 Self::WaitingForCallback => "waiting_for_callback",
4692 Self::WaitingForToolResult => "waiting_for_tool_result",
4693 Self::WaitingForOperatorReview => "waiting_for_operator_review",
4694 Self::PausedByPolicy => "paused_by_policy",
4695 Self::PausedByBudget => "paused_by_budget",
4696 Self::StepBoundary => "step_boundary",
4697 Self::ManualPause => "manual_pause",
4698 }
4699 }
4700}
4701
4702/// Who requested the suspension.
4703#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4704#[non_exhaustive]
4705pub enum SuspensionRequester {
4706 Worker,
4707 Operator,
4708 Policy,
4709 SystemTimeoutPolicy,
4710}
4711
4712impl SuspensionRequester {
4713 pub fn as_wire_str(self) -> &'static str {
4714 match self {
4715 Self::Worker => "worker",
4716 Self::Operator => "operator",
4717 Self::Policy => "policy",
4718 Self::SystemTimeoutPolicy => "system_timeout_policy",
4719 }
4720 }
4721}
4722
4723/// How the waitpoint resource backing a [`SuspendArgs`] is obtained.
4724///
4725/// RFC-013 §2.2 — `Fresh` mints a new waitpoint as part of `suspend`;
4726/// `UsePending` activates a waitpoint previously issued via
4727/// `EngineBackend::create_waitpoint`.
4728#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4729#[non_exhaustive]
4730pub enum WaitpointBinding {
4731 Fresh {
4732 waitpoint_id: WaitpointId,
4733 waitpoint_key: String,
4734 },
4735 UsePending {
4736 waitpoint_id: WaitpointId,
4737 },
4738}
4739
4740impl WaitpointBinding {
4741 /// Mint a fresh binding with a random `waitpoint_id` (UUID v4) and
4742 /// `waitpoint_key = "wpk:<uuid>"`.
4743 pub fn fresh() -> Self {
4744 let wp_id = WaitpointId::new();
4745 let key = format!("wpk:{wp_id}");
4746 Self::Fresh {
4747 waitpoint_id: wp_id,
4748 waitpoint_key: key,
4749 }
4750 }
4751
4752 /// Construct a `UsePending` binding from a pending waitpoint
4753 /// previously issued by `create_waitpoint`. The HMAC token is
4754 /// resolved Lua-side from the partition's waitpoint hash at
4755 /// `suspend` time (RFC-013 §5.1).
4756 pub fn use_pending(pending: &crate::backend::PendingWaitpoint) -> Self {
4757 Self::UsePending {
4758 waitpoint_id: pending.waitpoint_id.clone(),
4759 }
4760 }
4761}
4762
4763/// Trait-surface input to [`EngineBackend::suspend`] (RFC-013 §2.2 +
4764/// RFC-014 Pattern 3 widening).
4765///
4766/// Built via [`SuspendArgs::new`] + `with_*` setters; direct struct-
4767/// literal construction across crate boundaries is not possible
4768/// (`#[non_exhaustive]`).
4769///
4770/// ## Waitpoints
4771///
4772/// `waitpoints` is a non-empty `Vec<WaitpointBinding>`. The first entry
4773/// is the "primary" binding (accessible via [`primary`](Self::primary))
4774/// and carries the `current_waitpoint_id` written onto `exec_core` for
4775/// operator visibility. Additional entries land in Valkey as their own
4776/// waitpoint hashes / signal streams / HMAC tokens, enabling RFC-014
4777/// Pattern 3 `AllOf { members: [Single{wp1}, Single{wp2}, ...] }` across
4778/// distinct heterogeneous subsystems.
4779///
4780/// [`SuspendArgs::new`] takes exactly the primary binding; call
4781/// [`with_waitpoint`](Self::with_waitpoint) to append further bindings
4782/// (the RFC-014 builder API).
4783#[derive(Clone, Debug, Serialize, Deserialize)]
4784#[non_exhaustive]
4785pub struct SuspendArgs {
4786 pub suspension_id: SuspensionId,
4787 /// RFC-014 Pattern 3: all waitpoint bindings for this suspension.
4788 /// Guaranteed non-empty; `waitpoints[0]` is the primary.
4789 pub waitpoints: Vec<WaitpointBinding>,
4790 pub resume_condition: ResumeCondition,
4791 pub resume_policy: ResumePolicy,
4792 pub reason_code: SuspensionReasonCode,
4793 pub requested_by: SuspensionRequester,
4794 #[serde(default, skip_serializing_if = "Option::is_none")]
4795 pub timeout_at: Option<TimestampMs>,
4796 pub timeout_behavior: TimeoutBehavior,
4797 #[serde(default, skip_serializing_if = "Option::is_none")]
4798 pub continuation_metadata_pointer: Option<String>,
4799 pub now: TimestampMs,
4800 #[serde(default, skip_serializing_if = "Option::is_none")]
4801 pub idempotency_key: Option<IdempotencyKey>,
4802}
4803
4804impl SuspendArgs {
4805 /// Build a minimal `SuspendArgs` for a worker-originated suspension.
4806 ///
4807 /// `waitpoint` becomes the primary binding. Append additional
4808 /// bindings with [`with_waitpoint`](Self::with_waitpoint) (RFC-014
4809 /// Pattern 3) or replace the set with
4810 /// [`with_waitpoints`](Self::with_waitpoints).
4811 ///
4812 /// Defaults: `requested_by = Worker`, `timeout_at = None`,
4813 /// `timeout_behavior = Fail`, `continuation_metadata_pointer = None`,
4814 /// `idempotency_key = None`.
4815 pub fn new(
4816 suspension_id: SuspensionId,
4817 waitpoint: WaitpointBinding,
4818 resume_condition: ResumeCondition,
4819 resume_policy: ResumePolicy,
4820 reason_code: SuspensionReasonCode,
4821 now: TimestampMs,
4822 ) -> Self {
4823 Self {
4824 suspension_id,
4825 waitpoints: vec![waitpoint],
4826 resume_condition,
4827 resume_policy,
4828 reason_code,
4829 requested_by: SuspensionRequester::Worker,
4830 timeout_at: None,
4831 timeout_behavior: TimeoutBehavior::Fail,
4832 continuation_metadata_pointer: None,
4833 now,
4834 idempotency_key: None,
4835 }
4836 }
4837
4838 /// Primary binding — `waitpoints[0]`. Guaranteed present by
4839 /// construction.
4840 pub fn primary(&self) -> &WaitpointBinding {
4841 &self.waitpoints[0]
4842 }
4843
4844 pub fn with_timeout(mut self, at: TimestampMs, behavior: TimeoutBehavior) -> Self {
4845 self.timeout_at = Some(at);
4846 self.timeout_behavior = behavior;
4847 self
4848 }
4849
4850 pub fn with_requester(mut self, requester: SuspensionRequester) -> Self {
4851 self.requested_by = requester;
4852 self
4853 }
4854
4855 pub fn with_continuation_metadata_pointer(mut self, p: String) -> Self {
4856 self.continuation_metadata_pointer = Some(p);
4857 self
4858 }
4859
4860 pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
4861 self.idempotency_key = Some(key);
4862 self
4863 }
4864
4865 /// RFC-014 Pattern 3 — append a further waitpoint binding to this
4866 /// suspension. Each additional binding yields its own waitpoint
4867 /// hash, signal stream, condition hash and HMAC token in Valkey,
4868 /// but all share the suspension record and composite evaluator
4869 /// under one `suspension:current`.
4870 ///
4871 /// Ordering: the primary (from [`SuspendArgs::new`]) stays at
4872 /// `waitpoints[0]`; subsequent `with_waitpoint` calls append at the
4873 /// tail.
4874 pub fn with_waitpoint(mut self, binding: WaitpointBinding) -> Self {
4875 self.waitpoints.push(binding);
4876 self
4877 }
4878
4879 /// RFC-014 Pattern 3 — replace the full binding vector in one call.
4880 /// Must be non-empty; an empty Vec is a programmer error and will
4881 /// be rejected by the backend's `validate_suspend_args` with
4882 /// `waitpoints_empty`.
4883 pub fn with_waitpoints(mut self, bindings: Vec<WaitpointBinding>) -> Self {
4884 self.waitpoints = bindings;
4885 self
4886 }
4887}
4888
4889/// Shared "what happened on the waitpoint" payload carried in both
4890/// [`SuspendOutcome`] variants.
4891///
4892/// For Pattern 3 (RFC-014) — multi-waitpoint suspensions — the primary
4893/// binding's identity lives at the top level (`waitpoint_id` /
4894/// `waitpoint_key` / `waitpoint_token`) and remaining bindings are
4895/// exposed via `additional_waitpoints`, each carrying its own minted
4896/// HMAC token so external signallers can deliver to any of the N
4897/// waitpoints the suspension is listening on.
4898#[derive(Clone, Debug, PartialEq, Eq)]
4899#[non_exhaustive]
4900pub struct SuspendOutcomeDetails {
4901 pub suspension_id: SuspensionId,
4902 pub waitpoint_id: WaitpointId,
4903 pub waitpoint_key: String,
4904 pub waitpoint_token: WaitpointHmac,
4905 /// RFC-014 Pattern 3 extras (beyond the primary). Empty for
4906 /// single-waitpoint suspensions (patterns 1 + 2); carries one
4907 /// entry per additional binding for Pattern 3.
4908 pub additional_waitpoints: Vec<AdditionalWaitpointBinding>,
4909}
4910
4911/// RFC-014 Pattern 3 — per-binding identity + HMAC token for
4912/// waitpoints beyond the primary. Structure mirrors the top-level
4913/// fields on [`SuspendOutcomeDetails`].
4914#[derive(Clone, Debug, PartialEq, Eq)]
4915#[non_exhaustive]
4916pub struct AdditionalWaitpointBinding {
4917 pub waitpoint_id: WaitpointId,
4918 pub waitpoint_key: String,
4919 pub waitpoint_token: WaitpointHmac,
4920}
4921
4922impl AdditionalWaitpointBinding {
4923 pub fn new(
4924 waitpoint_id: WaitpointId,
4925 waitpoint_key: String,
4926 waitpoint_token: WaitpointHmac,
4927 ) -> Self {
4928 Self {
4929 waitpoint_id,
4930 waitpoint_key,
4931 waitpoint_token,
4932 }
4933 }
4934}
4935
4936impl SuspendOutcomeDetails {
4937 pub fn new(
4938 suspension_id: SuspensionId,
4939 waitpoint_id: WaitpointId,
4940 waitpoint_key: String,
4941 waitpoint_token: WaitpointHmac,
4942 ) -> Self {
4943 Self {
4944 suspension_id,
4945 waitpoint_id,
4946 waitpoint_key,
4947 waitpoint_token,
4948 additional_waitpoints: Vec::new(),
4949 }
4950 }
4951
4952 /// Attach RFC-014 Pattern 3 additional-waitpoint bindings. The
4953 /// primary binding stays at the top-level fields; `extras` lands
4954 /// in [`additional_waitpoints`](Self::additional_waitpoints).
4955 pub fn with_additional_waitpoints(
4956 mut self,
4957 extras: Vec<AdditionalWaitpointBinding>,
4958 ) -> Self {
4959 self.additional_waitpoints = extras;
4960 self
4961 }
4962}
4963
4964/// Trait-surface output from [`EngineBackend::suspend`] (RFC-013 §2.3).
4965///
4966/// Two variants encode the "lease released" vs "lease retained" split.
4967/// See §2.3 for the runtime-enforcement semantics.
4968#[derive(Clone, Debug, PartialEq, Eq)]
4969#[non_exhaustive]
4970pub enum SuspendOutcome {
4971 /// The worker's pre-suspend handle is no longer lease-bearing; a
4972 /// fresh `HandleKind::Suspended` handle supersedes it.
4973 Suspended {
4974 details: SuspendOutcomeDetails,
4975 handle: crate::backend::Handle,
4976 },
4977 /// Buffered signals on a pending waitpoint already satisfied the
4978 /// condition at suspension time; the lease is retained and the
4979 /// caller's pre-suspend handle remains valid.
4980 AlreadySatisfied { details: SuspendOutcomeDetails },
4981}
4982
4983impl SuspendOutcome {
4984 /// Borrow the shared details regardless of variant.
4985 pub fn details(&self) -> &SuspendOutcomeDetails {
4986 match self {
4987 Self::Suspended { details, .. } => details,
4988 Self::AlreadySatisfied { details } => details,
4989 }
4990 }
4991}
4992
4993// `EngineBackend::suspend` type re-exports for `ff_core::backend::*`
4994// consumers. The `backend` module re-exports these below so external
4995// crates can reach them via the idiomatic `ff_core::backend` path that
4996// already sources the other trait-surface types (RFC-013 §9.1).
4997
4998// ─── RFC-017 Stage A — trait-expansion Args/Result types ─────────────
4999//
5000// Per RFC-017 §5.1.1: every struct/enum introduced here is
5001// `#[non_exhaustive]` and ships with a `pub fn new(...)` constructor so
5002// additive field growth post-v0.8 does not force cross-crate churn.
5003
5004// ─── claim_for_worker ───
5005
5006/// Inputs to `EngineBackend::claim_for_worker` (RFC-017 §5, §7). The
5007/// Valkey impl forwards to `ff_scheduler::Scheduler::claim_for_worker`;
5008/// the Postgres impl forwards to its own scheduler module. The trait
5009/// method hides the backend-specific dispatch behind one shape.
5010#[non_exhaustive]
5011#[derive(Clone, Debug)]
5012pub struct ClaimForWorkerArgs {
5013 pub lane_id: LaneId,
5014 pub worker_id: WorkerId,
5015 pub worker_instance_id: WorkerInstanceId,
5016 pub worker_capabilities: std::collections::BTreeSet<String>,
5017 pub grant_ttl_ms: u64,
5018}
5019
5020impl ClaimForWorkerArgs {
5021 /// Required-field constructor. Optional fields today: none — kept
5022 /// for forward-compat so a future optional (e.g. `deadline_ms`)
5023 /// does not break callers using the builder pattern.
5024 pub fn new(
5025 lane_id: LaneId,
5026 worker_id: WorkerId,
5027 worker_instance_id: WorkerInstanceId,
5028 worker_capabilities: std::collections::BTreeSet<String>,
5029 grant_ttl_ms: u64,
5030 ) -> Self {
5031 Self {
5032 lane_id,
5033 worker_id,
5034 worker_instance_id,
5035 worker_capabilities,
5036 grant_ttl_ms,
5037 }
5038 }
5039}
5040
5041/// Outcome of `EngineBackend::claim_for_worker`. `None`-like shape
5042/// modelled as an enum so additive variants (e.g. `BackPressured {
5043/// retry_after_ms }`) do not force a wire break.
5044#[non_exhaustive]
5045#[derive(Clone, Debug, PartialEq, Eq)]
5046pub enum ClaimForWorkerOutcome {
5047 /// No eligible execution on this lane at this scan cycle.
5048 NoWork,
5049 /// Grant issued — worker proceeds to `claim_from_grant`.
5050 Granted(ClaimGrant),
5051}
5052
5053impl ClaimForWorkerOutcome {
5054 /// Build the `NoWork` variant.
5055 pub fn no_work() -> Self {
5056 Self::NoWork
5057 }
5058 /// Build the `Granted` variant.
5059 pub fn granted(grant: ClaimGrant) -> Self {
5060 Self::Granted(grant)
5061 }
5062}
5063
5064// ─── list_pending_waitpoints ───
5065
5066/// Inputs to `EngineBackend::list_pending_waitpoints` (RFC-017 §5, §8).
5067/// Pagination is part of the signature so a flow with 10k pending
5068/// waitpoints cannot force a single-round-trip read regardless of
5069/// backend.
5070#[non_exhaustive]
5071#[derive(Clone, Debug)]
5072pub struct ListPendingWaitpointsArgs {
5073 pub execution_id: ExecutionId,
5074 /// Exclusive cursor — `None` starts from the beginning.
5075 pub after: Option<WaitpointId>,
5076 /// Max page size. `None` → backend default (100). Backend-enforced
5077 /// cap: 1000.
5078 pub limit: Option<u32>,
5079}
5080
5081impl ListPendingWaitpointsArgs {
5082 pub fn new(execution_id: ExecutionId) -> Self {
5083 Self {
5084 execution_id,
5085 after: None,
5086 limit: None,
5087 }
5088 }
5089 pub fn with_after(mut self, after: WaitpointId) -> Self {
5090 self.after = Some(after);
5091 self
5092 }
5093 pub fn with_limit(mut self, limit: u32) -> Self {
5094 self.limit = Some(limit);
5095 self
5096 }
5097}
5098
5099/// Page of pending-waitpoint entries. Stage A preserves the existing
5100/// `PendingWaitpointInfo` shape; the §8 schema rewrite (HMAC
5101/// sanitisation + `(token_kid, token_fingerprint)` additive fields)
5102/// ships in Stage D alongside the HTTP wire-format deprecation.
5103#[non_exhaustive]
5104#[derive(Clone, Debug)]
5105pub struct ListPendingWaitpointsResult {
5106 pub entries: Vec<PendingWaitpointInfo>,
5107 /// Forward-only continuation cursor — `None` signals end-of-stream.
5108 pub next_cursor: Option<WaitpointId>,
5109}
5110
5111impl ListPendingWaitpointsResult {
5112 pub fn new(entries: Vec<PendingWaitpointInfo>) -> Self {
5113 Self {
5114 entries,
5115 next_cursor: None,
5116 }
5117 }
5118 pub fn with_next_cursor(mut self, cursor: WaitpointId) -> Self {
5119 self.next_cursor = Some(cursor);
5120 self
5121 }
5122}
5123
5124// ─── report_usage_admin ───
5125
5126/// Inputs to `EngineBackend::report_usage_admin` (RFC-017 §5 budget+
5127/// quota admin §5, round-1 F4). Admin-path peer of `report_usage` —
5128/// both wrap `ff_report_usage_and_check` on the Valkey side but the
5129/// admin call is worker-less, so it cannot reuse the lease-bound
5130/// `report_usage(&Handle, ...)` signature. `ReportUsageAdminArgs`
5131/// carries the same fields as [`ReportUsageArgs`] without a worker
5132/// handle — kept as a distinct type so future admin-only fields (e.g.
5133/// `actor_identity`, `audit_reason`) don't pollute the worker path.
5134#[non_exhaustive]
5135#[derive(Clone, Debug)]
5136pub struct ReportUsageAdminArgs {
5137 pub dimensions: Vec<String>,
5138 pub deltas: Vec<u64>,
5139 pub dedup_key: Option<String>,
5140 pub now: TimestampMs,
5141}
5142
5143impl ReportUsageAdminArgs {
5144 pub fn new(dimensions: Vec<String>, deltas: Vec<u64>, now: TimestampMs) -> Self {
5145 Self {
5146 dimensions,
5147 deltas,
5148 dedup_key: None,
5149 now,
5150 }
5151 }
5152 pub fn with_dedup_key(mut self, key: String) -> Self {
5153 self.dedup_key = Some(key);
5154 self
5155 }
5156}
5157
5158// ─── #454 — cairn ControlPlaneBackend peer methods ──────────────────
5159//
5160// Four trait methods from cairn-rs #454 that previously routed through
5161// raw `ferriskey::*` FCALLs outside the `EngineBackend` trait. Cairn's
5162// ground-truth shapes at `cairn-fabric/src/engine/control_plane_types.rs`
5163// (commit `a4fdb638`) are mirrored below verbatim so the v0.13 trait
5164// matches cairn's existing Valkey impls 1:1.
5165//
5166// Default bodies on the trait return `EngineError::Unavailable { op }`
5167// at landing; Valkey bodies ship in Phase 3; PG + SQLite in Phases 4+5.
5168
5169// ─── record_spend ───
5170
5171/// Args for [`crate::engine_backend::EngineBackend::record_spend`].
5172///
5173/// Carries an **open-set** `BTreeMap<String, u64>` of dimension deltas
5174/// per cairn's ground-truth shape at
5175/// `cairn-fabric/src/engine/control_plane_types.rs`. Cairn budgets are
5176/// per-tenant open-schema (tenant A tracks `"tokens"` + `"cost_cents"`,
5177/// tenant B tracks `"egress_bytes"`), distinct from FF's fixed-shape
5178/// [`UsageDimensions`] which encodes the internal usage-report surface.
5179///
5180/// `BTreeMap` (not `HashMap`) gives stable iteration order — consistent
5181/// with `UsageDimensions::custom`, and critical for the PG body which
5182/// updates multiple dimension rows per call (deterministic ordering
5183/// prevents deadlocks under concurrent spend).
5184///
5185/// Return shape reuses [`ReportUsageResult`] — same four variants
5186/// (`Ok` / `SoftBreach` / `HardBreach` / `AlreadyApplied`) cairn's UI
5187/// branches on. Not a new enum.
5188#[derive(Clone, Debug, Serialize, Deserialize)]
5189#[non_exhaustive]
5190pub struct RecordSpendArgs {
5191 pub budget_id: BudgetId,
5192 pub execution_id: ExecutionId,
5193 /// Per-dimension positive deltas. Tenant-defined keys; stable
5194 /// iteration order.
5195 pub deltas: BTreeMap<String, u64>,
5196 /// Caller-computed idempotency key (cairn uses SHA-256 hex of
5197 /// `budget_id || execution_id || sorted(deltas)`). FF does not
5198 /// interpret the bytes — dedup is a simple equality check against
5199 /// the prior stamped key.
5200 pub idempotency_key: String,
5201}
5202
5203impl RecordSpendArgs {
5204 pub fn new(
5205 budget_id: BudgetId,
5206 execution_id: ExecutionId,
5207 deltas: BTreeMap<String, u64>,
5208 idempotency_key: impl Into<String>,
5209 ) -> Self {
5210 Self {
5211 budget_id,
5212 execution_id,
5213 deltas,
5214 idempotency_key: idempotency_key.into(),
5215 }
5216 }
5217}
5218
5219// ─── release_budget ───
5220
5221/// Args for [`crate::engine_backend::EngineBackend::release_budget`].
5222///
5223/// **Per-execution release-my-attribution**, not whole-budget flush.
5224/// Called when an execution terminates so the budget persists across
5225/// executions but this execution's attribution is reversed. Per cairn
5226/// clarification on #454.
5227#[derive(Clone, Debug, Serialize, Deserialize)]
5228#[non_exhaustive]
5229pub struct ReleaseBudgetArgs {
5230 pub budget_id: BudgetId,
5231 pub execution_id: ExecutionId,
5232}
5233
5234impl ReleaseBudgetArgs {
5235 pub fn new(budget_id: BudgetId, execution_id: ExecutionId) -> Self {
5236 Self {
5237 budget_id,
5238 execution_id,
5239 }
5240 }
5241}
5242
5243// ─── deliver_approval_signal ───
5244
5245/// Args for [`crate::engine_backend::EngineBackend::deliver_approval_signal`].
5246///
5247/// Pre-shaped variant of [`crate::engine_backend::EngineBackend::deliver_signal`]
5248/// for the operator-driven approval flow. Distinct from `deliver_signal`
5249/// because the caller **does not carry the waitpoint token** — the backend
5250/// reads the token from `ff_waitpoint_pending` (via
5251/// [`crate::engine_backend::EngineBackend::read_waitpoint_token`],
5252/// #434-shipped in v0.12), HMAC-verifies server-side, and dispatches. The
5253/// operator API never handles the token bytes.
5254///
5255/// `signal_name` is a flat string (`"approved"` / `"rejected"` by
5256/// convention; not an enum at the trait level — audit metadata like
5257/// `decided_by` / `note` / `reason` sits in cairn's audit log, not in
5258/// the FF signal surface).
5259#[derive(Clone, Debug, Serialize, Deserialize)]
5260#[non_exhaustive]
5261pub struct DeliverApprovalSignalArgs {
5262 pub execution_id: ExecutionId,
5263 pub lane_id: LaneId,
5264 pub waitpoint_id: WaitpointId,
5265 /// Conventional values: `"approved"` / `"rejected"`. Stored raw on
5266 /// the delivered signal; FF does not interpret.
5267 pub signal_name: String,
5268 /// Cairn-side per-decision idempotency suffix. Combined with
5269 /// `execution_id` + `signal_name` to form the dedup key.
5270 pub idempotency_suffix: String,
5271 /// Dedup TTL in milliseconds.
5272 pub signal_dedup_ttl_ms: u64,
5273 /// Signal stream MAXLEN for the suspension stream.
5274 /// `None` ⇒ backend default (matches [`DeliverSignalArgs::signal_maxlen`]).
5275 #[serde(default)]
5276 pub maxlen: Option<u64>,
5277 /// Per-execution max signal cap (operator quota).
5278 /// `None` ⇒ backend default (matches [`DeliverSignalArgs::max_signals_per_execution`]).
5279 #[serde(default)]
5280 pub max_signals_per_execution: Option<u64>,
5281}
5282
5283impl DeliverApprovalSignalArgs {
5284 #[allow(clippy::too_many_arguments)]
5285 pub fn new(
5286 execution_id: ExecutionId,
5287 lane_id: LaneId,
5288 waitpoint_id: WaitpointId,
5289 signal_name: impl Into<String>,
5290 idempotency_suffix: impl Into<String>,
5291 signal_dedup_ttl_ms: u64,
5292 maxlen: Option<u64>,
5293 max_signals_per_execution: Option<u64>,
5294 ) -> Self {
5295 Self {
5296 execution_id,
5297 lane_id,
5298 waitpoint_id,
5299 signal_name: signal_name.into(),
5300 idempotency_suffix: idempotency_suffix.into(),
5301 signal_dedup_ttl_ms,
5302 maxlen,
5303 max_signals_per_execution,
5304 }
5305 }
5306}
5307
5308// ─── issue_grant_and_claim ───
5309
5310/// Args for [`crate::engine_backend::EngineBackend::issue_grant_and_claim`].
5311///
5312/// Composes `issue_claim_grant` + `claim_execution` into a single
5313/// backend-atomic op per cairn #454 Q4. The composition **must** be
5314/// backend-atomic (not caller-chained) to prevent leaking grants when
5315/// `claim_execution` fails after `issue_claim_grant` succeeded.
5316///
5317/// Valkey: one `ff_issue_grant_and_claim` FCALL composing the two
5318/// primitives in Lua.
5319/// Postgres/SQLite: both primitives inside one tx.
5320///
5321/// Flattened shape (not `IssueClaimGrantArgs + ClaimExecutionArgs`
5322/// composition) — the two arg types overlap on `execution_id` +
5323/// `lane_id`; flattening drops the dup.
5324#[derive(Clone, Debug, Serialize, Deserialize)]
5325#[non_exhaustive]
5326pub struct IssueGrantAndClaimArgs {
5327 pub execution_id: ExecutionId,
5328 pub lane_id: LaneId,
5329 /// Lease TTL in milliseconds. Threaded into both the grant TTL and
5330 /// the claimed attempt's `lease_expires_at_ms`.
5331 pub lease_duration_ms: u64,
5332}
5333
5334impl IssueGrantAndClaimArgs {
5335 pub fn new(execution_id: ExecutionId, lane_id: LaneId, lease_duration_ms: u64) -> Self {
5336 Self {
5337 execution_id,
5338 lane_id,
5339 lease_duration_ms,
5340 }
5341 }
5342}
5343
5344/// Outcome of [`crate::engine_backend::EngineBackend::issue_grant_and_claim`].
5345///
5346/// Distinct from [`ClaimExecutionResult`] because the trait method
5347/// intentionally hides the grant-issuance step — callers only see the
5348/// resulting lease identity. If the backend's transparent dispatch
5349/// routes through `ff_claim_resumed_execution` (when the execution was
5350/// suspended), the return is identical.
5351#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
5352#[non_exhaustive]
5353pub struct ClaimGrantOutcome {
5354 pub lease_id: LeaseId,
5355 pub lease_epoch: LeaseEpoch,
5356 pub attempt_index: AttemptIndex,
5357}
5358
5359impl ClaimGrantOutcome {
5360 pub fn new(
5361 lease_id: LeaseId,
5362 lease_epoch: LeaseEpoch,
5363 attempt_index: AttemptIndex,
5364 ) -> Self {
5365 Self {
5366 lease_id,
5367 lease_epoch,
5368 attempt_index,
5369 }
5370 }
5371}
5372
5373#[cfg(test)]
5374mod rfc_014_validation_tests {
5375 use super::*;
5376
5377 fn single(wp: &str) -> ResumeCondition {
5378 ResumeCondition::Single {
5379 waitpoint_key: wp.to_owned(),
5380 matcher: SignalMatcher::ByName("x".to_owned()),
5381 }
5382 }
5383
5384 #[test]
5385 fn single_passes_validate() {
5386 assert!(single("wpk:a").validate_composite().is_ok());
5387 }
5388
5389 #[test]
5390 fn allof_empty_members_rejected() {
5391 let c = ResumeCondition::Composite(CompositeBody::AllOf { members: vec![] });
5392 let e = c.validate_composite().unwrap_err();
5393 assert!(e.detail.contains("allof_empty_members"), "{}", e.detail);
5394 }
5395
5396 #[test]
5397 fn count_n_zero_rejected() {
5398 let c = ResumeCondition::Composite(CompositeBody::Count {
5399 n: 0,
5400 count_kind: CountKind::DistinctWaitpoints,
5401 matcher: None,
5402 waitpoints: vec!["wpk:a".to_owned()],
5403 });
5404 let e = c.validate_composite().unwrap_err();
5405 assert!(e.detail.contains("count_n_zero"), "{}", e.detail);
5406 }
5407
5408 #[test]
5409 fn count_waitpoints_empty_rejected() {
5410 let c = ResumeCondition::Composite(CompositeBody::Count {
5411 n: 1,
5412 count_kind: CountKind::DistinctSources,
5413 matcher: None,
5414 waitpoints: vec![],
5415 });
5416 let e = c.validate_composite().unwrap_err();
5417 assert!(e.detail.contains("count_waitpoints_empty"), "{}", e.detail);
5418 }
5419
5420 #[test]
5421 fn count_exceeds_waitpoint_set_rejected_only_for_distinct_waitpoints() {
5422 // n=3, only 2 waitpoints, DistinctWaitpoints → reject.
5423 let c = ResumeCondition::Composite(CompositeBody::Count {
5424 n: 3,
5425 count_kind: CountKind::DistinctWaitpoints,
5426 matcher: None,
5427 waitpoints: vec!["a".into(), "b".into()],
5428 });
5429 let e = c.validate_composite().unwrap_err();
5430 assert!(e.detail.contains("count_exceeds_waitpoint_set"), "{}", e.detail);
5431
5432 // Same cardinality, DistinctSignals → allowed (no upper bound).
5433 let c2 = ResumeCondition::Composite(CompositeBody::Count {
5434 n: 3,
5435 count_kind: CountKind::DistinctSignals,
5436 matcher: None,
5437 waitpoints: vec!["a".into(), "b".into()],
5438 });
5439 assert!(c2.validate_composite().is_ok());
5440 }
5441
5442 #[test]
5443 fn depth_4_accepted_depth_5_rejected() {
5444 // Build Depth-4: AllOf { AllOf { AllOf { AllOf { Single } } } }
5445 let leaf = single("wpk:leaf");
5446 let d4 = ResumeCondition::Composite(CompositeBody::AllOf {
5447 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5448 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5449 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5450 members: vec![leaf.clone()],
5451 })],
5452 })],
5453 })],
5454 });
5455 assert!(d4.validate_composite().is_ok());
5456
5457 // Depth-5 → reject.
5458 let d5 = ResumeCondition::Composite(CompositeBody::AllOf {
5459 members: vec![d4],
5460 });
5461 let e = d5.validate_composite().unwrap_err();
5462 assert!(e.detail.contains("exceeds cap"), "{}", e.detail);
5463 }
5464}