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#[cfg(test)]
3372mod tests {
3373 use super::*;
3374 use crate::types::FlowId;
3375
3376 #[test]
3377 fn create_execution_args_serde() {
3378 let config = crate::partition::PartitionConfig::default();
3379 let args = CreateExecutionArgs {
3380 execution_id: ExecutionId::for_flow(&FlowId::new(), &config),
3381 namespace: Namespace::new("test"),
3382 lane_id: LaneId::new("default"),
3383 execution_kind: "llm_call".to_owned(),
3384 input_payload: b"hello".to_vec(),
3385 payload_encoding: Some("json".to_owned()),
3386 priority: 0,
3387 creator_identity: "test-user".to_owned(),
3388 idempotency_key: None,
3389 tags: HashMap::new(),
3390 policy: None,
3391 delay_until: None,
3392 execution_deadline_at: None,
3393 partition_id: 42,
3394 now: TimestampMs::now(),
3395 };
3396 let json = serde_json::to_string(&args).unwrap();
3397 let parsed: CreateExecutionArgs = serde_json::from_str(&json).unwrap();
3398 assert_eq!(args.execution_id, parsed.execution_id);
3399 }
3400
3401 #[test]
3402 fn claim_result_serde() {
3403 let config = crate::partition::PartitionConfig::default();
3404 let result = ClaimExecutionResult::Claimed(ClaimedExecution {
3405 execution_id: ExecutionId::for_flow(&FlowId::new(), &config),
3406 lease_id: LeaseId::new(),
3407 lease_epoch: LeaseEpoch::new(1),
3408 attempt_index: AttemptIndex::new(0),
3409 attempt_id: AttemptId::new(),
3410 attempt_type: AttemptType::Initial,
3411 lease_expires_at: TimestampMs::from_millis(1000),
3412 handle: crate::backend::stub_handle_fresh(),
3413 });
3414 let json = serde_json::to_string(&result).unwrap();
3415 let parsed: ClaimExecutionResult = serde_json::from_str(&json).unwrap();
3416 assert_eq!(result, parsed);
3417 }
3418
3419 // ── StreamCursor (issue #92) ──
3420
3421 #[test]
3422 fn stream_cursor_display_matches_wire_tokens() {
3423 assert_eq!(StreamCursor::Start.to_string(), "start");
3424 assert_eq!(StreamCursor::End.to_string(), "end");
3425 assert_eq!(StreamCursor::At("123".into()).to_string(), "123");
3426 assert_eq!(StreamCursor::At("123-4".into()).to_string(), "123-4");
3427 }
3428
3429 #[test]
3430 fn stream_cursor_to_wire_maps_to_valkey_markers() {
3431 assert_eq!(StreamCursor::Start.to_wire(), "-");
3432 assert_eq!(StreamCursor::End.to_wire(), "+");
3433 assert_eq!(StreamCursor::At("0-0".into()).to_wire(), "0-0");
3434 assert_eq!(StreamCursor::At("17-3".into()).to_wire(), "17-3");
3435 }
3436
3437 #[test]
3438 fn stream_cursor_from_str_accepts_wire_tokens() {
3439 use std::str::FromStr;
3440 assert_eq!(
3441 StreamCursor::from_str("start").unwrap(),
3442 StreamCursor::Start
3443 );
3444 assert_eq!(StreamCursor::from_str("end").unwrap(), StreamCursor::End);
3445 assert_eq!(
3446 StreamCursor::from_str("123").unwrap(),
3447 StreamCursor::At("123".into())
3448 );
3449 assert_eq!(
3450 StreamCursor::from_str("0-0").unwrap(),
3451 StreamCursor::At("0-0".into())
3452 );
3453 assert_eq!(
3454 StreamCursor::from_str("1713100800150-0").unwrap(),
3455 StreamCursor::At("1713100800150-0".into())
3456 );
3457 }
3458
3459 #[test]
3460 fn stream_cursor_from_str_rejects_bare_markers() {
3461 use std::str::FromStr;
3462 assert!(matches!(
3463 StreamCursor::from_str("-"),
3464 Err(StreamCursorParseError::BareMarkerRejected(s)) if s == "-"
3465 ));
3466 assert!(matches!(
3467 StreamCursor::from_str("+"),
3468 Err(StreamCursorParseError::BareMarkerRejected(s)) if s == "+"
3469 ));
3470 }
3471
3472 #[test]
3473 fn stream_cursor_from_str_rejects_empty() {
3474 use std::str::FromStr;
3475 assert_eq!(
3476 StreamCursor::from_str(""),
3477 Err(StreamCursorParseError::Empty)
3478 );
3479 }
3480
3481 #[test]
3482 fn stream_cursor_from_str_rejects_malformed() {
3483 use std::str::FromStr;
3484 for bad in [
3485 "abc", "-1", "1-", "-1-2", "1-2-3", "1.2", "1 2", "Start", "END",
3486 ] {
3487 assert!(
3488 matches!(
3489 StreamCursor::from_str(bad),
3490 Err(StreamCursorParseError::Malformed(_))
3491 ),
3492 "must reject {bad:?}",
3493 );
3494 }
3495 }
3496
3497 #[test]
3498 fn stream_cursor_from_str_rejects_non_ascii() {
3499 use std::str::FromStr;
3500 assert!(matches!(
3501 StreamCursor::from_str("1\u{2013}2"),
3502 Err(StreamCursorParseError::Malformed(_))
3503 ));
3504 }
3505
3506 #[test]
3507 fn stream_cursor_serde_round_trip() {
3508 for c in [
3509 StreamCursor::Start,
3510 StreamCursor::End,
3511 StreamCursor::At("0-0".into()),
3512 StreamCursor::At("1713100800150-0".into()),
3513 ] {
3514 let json = serde_json::to_string(&c).unwrap();
3515 let back: StreamCursor = serde_json::from_str(&json).unwrap();
3516 assert_eq!(back, c);
3517 }
3518 }
3519
3520 #[test]
3521 fn stream_cursor_serializes_as_bare_string() {
3522 assert_eq!(
3523 serde_json::to_string(&StreamCursor::Start).unwrap(),
3524 r#""start""#
3525 );
3526 assert_eq!(
3527 serde_json::to_string(&StreamCursor::End).unwrap(),
3528 r#""end""#
3529 );
3530 assert_eq!(
3531 serde_json::to_string(&StreamCursor::At("123-0".into())).unwrap(),
3532 r#""123-0""#
3533 );
3534 }
3535
3536 #[test]
3537 fn stream_cursor_deserialize_rejects_bare_markers() {
3538 assert!(serde_json::from_str::<StreamCursor>(r#""-""#).is_err());
3539 assert!(serde_json::from_str::<StreamCursor>(r#""+""#).is_err());
3540 }
3541
3542 #[test]
3543 fn stream_cursor_from_beginning_is_zero_zero() {
3544 assert_eq!(
3545 StreamCursor::from_beginning(),
3546 StreamCursor::At("0-0".into())
3547 );
3548 }
3549
3550 #[test]
3551 fn stream_cursor_is_concrete_classifies_variants() {
3552 assert!(!StreamCursor::Start.is_concrete());
3553 assert!(!StreamCursor::End.is_concrete());
3554 assert!(StreamCursor::At("0-0".into()).is_concrete());
3555 assert!(StreamCursor::At("123-0".into()).is_concrete());
3556 assert!(StreamCursor::from_beginning().is_concrete());
3557 }
3558
3559 #[test]
3560 fn stream_cursor_into_wire_string_moves_without_cloning() {
3561 assert_eq!(StreamCursor::Start.into_wire_string(), "-");
3562 assert_eq!(StreamCursor::End.into_wire_string(), "+");
3563 assert_eq!(StreamCursor::At("17-3".into()).into_wire_string(), "17-3");
3564 }
3565}
3566
3567// ─── list_executions ───
3568
3569/// Summary of an execution for list views.
3570#[derive(Clone, Debug, Serialize, Deserialize)]
3571pub struct ExecutionSummary {
3572 pub execution_id: ExecutionId,
3573 pub namespace: String,
3574 pub lane_id: String,
3575 pub execution_kind: String,
3576 pub public_state: String,
3577 pub priority: i32,
3578 pub created_at: String,
3579}
3580
3581/// Result of a list_executions query.
3582#[derive(Clone, Debug, Serialize, Deserialize)]
3583pub struct ListExecutionsResult {
3584 pub executions: Vec<ExecutionSummary>,
3585 pub total_returned: usize,
3586}
3587
3588// ─── list_lanes (issue #184) ───
3589
3590/// One page of lane ids returned by
3591/// [`crate::engine_backend::EngineBackend::list_lanes`].
3592///
3593/// Lanes are global (not partition-scoped) — the backend enumerates
3594/// every registered lane, sorts by [`LaneId`] name, and returns a
3595/// `limit`-sized slice starting after `cursor` (exclusive).
3596///
3597/// `next_cursor` is `Some(last_lane_in_page)` when more pages remain
3598/// and `None` when the caller has read the final page. Callers that
3599/// want the full list loop until `next_cursor` is `None`, threading
3600/// the previous page's `next_cursor` into the next call's `cursor`
3601/// argument.
3602///
3603/// `#[non_exhaustive]` — FF may add fields (e.g. a `total` hint) in
3604/// minor releases without a semver break.
3605#[derive(Clone, Debug, PartialEq, Eq)]
3606#[non_exhaustive]
3607pub struct ListLanesPage {
3608 /// The lanes in this page, sorted by [`LaneId`] name.
3609 pub lanes: Vec<LaneId>,
3610 /// Cursor for the next page (exclusive). `None` ⇒ final page.
3611 pub next_cursor: Option<LaneId>,
3612}
3613
3614impl ListLanesPage {
3615 /// Construct a [`ListLanesPage`]. Present so downstream crates
3616 /// (ff-backend-valkey's `list_lanes` impl) can assemble the
3617 /// struct despite the `#[non_exhaustive]` marker.
3618 pub fn new(lanes: Vec<LaneId>, next_cursor: Option<LaneId>) -> Self {
3619 Self { lanes, next_cursor }
3620 }
3621}
3622
3623// ─── list_suspended ───
3624
3625/// One entry in a [`ListSuspendedPage`] — a suspended execution and
3626/// the reason it is blocked, answering an operator's "what's this
3627/// waiting on?" without a follow-up round-trip.
3628///
3629/// `reason` carries the free-form `reason_code` recorded by the
3630/// suspending worker at `lua/suspension.lua` (HSET `suspension:current
3631/// reason_code`). It is a `String`, not a closed enum: the suspension
3632/// pipeline accepts arbitrary caller-supplied codes (typical values
3633/// are `"signal"`, `"timer"`, `"children"`, `"join"`, but consumers
3634/// embed bespoke codes). A future enum projection can classify
3635/// known codes once the set is frozen; until then, callers that want
3636/// structured routing MUST match on the string explicitly.
3637#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3638#[non_exhaustive]
3639pub struct SuspendedExecutionEntry {
3640 /// Execution currently in `lifecycle_phase=suspended`.
3641 pub execution_id: ExecutionId,
3642 /// Score stored on the per-lane suspended ZSET — the scheduled
3643 /// `timeout_at` in milliseconds, or the `9999999999999` sentinel
3644 /// when no timeout was set (see `lua/suspension.lua`).
3645 pub suspended_at_ms: i64,
3646 /// Free-form reason code from `suspension:current.reason_code`.
3647 /// Empty string when the suspension hash is absent or does not
3648 /// carry a `reason_code` field (older records). See the struct
3649 /// rustdoc for the deliberate-String rationale.
3650 pub reason: String,
3651}
3652
3653impl SuspendedExecutionEntry {
3654 /// Construct a new entry. Preferred over direct field init for
3655 /// `#[non_exhaustive]` forward-compat.
3656 pub fn new(execution_id: ExecutionId, suspended_at_ms: i64, reason: String) -> Self {
3657 Self {
3658 execution_id,
3659 suspended_at_ms,
3660 reason,
3661 }
3662 }
3663}
3664
3665/// One cursor-paginated page of suspended executions.
3666///
3667/// Pagination is cursor-based (not offset/limit) so a Valkey backend
3668/// can resume a partition scan from the last seen execution id and a
3669/// future Postgres backend can do keyset pagination on
3670/// `executions WHERE state='suspended'`. The cursor is opaque to
3671/// callers: pass `next_cursor` back as the `cursor` argument to the
3672/// next [`EngineBackend::list_suspended`] call to fetch the next
3673/// page. `None` means the stream is exhausted.
3674///
3675/// [`EngineBackend::list_suspended`]: crate::engine_backend::EngineBackend::list_suspended
3676#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3677#[non_exhaustive]
3678pub struct ListSuspendedPage {
3679 /// Entries on this page, ordered by ascending `suspended_at_ms`
3680 /// (timeout order) with `execution_id` as a lex tiebreak.
3681 pub entries: Vec<SuspendedExecutionEntry>,
3682 /// Resume-point for the next page. `None` when no further
3683 /// entries remain in the partition.
3684 pub next_cursor: Option<ExecutionId>,
3685}
3686
3687impl ListSuspendedPage {
3688 /// Construct a new page. Preferred over direct field init for
3689 /// `#[non_exhaustive]` forward-compat.
3690 pub fn new(entries: Vec<SuspendedExecutionEntry>, next_cursor: Option<ExecutionId>) -> Self {
3691 Self {
3692 entries,
3693 next_cursor,
3694 }
3695 }
3696}
3697
3698// ─── list_executions ───
3699
3700/// One page of partition-scoped execution ids returned by
3701/// [`EngineBackend::list_executions`](crate::engine_backend::EngineBackend::list_executions).
3702///
3703/// Pagination is forward-only and cursor-based. `next_cursor` carries
3704/// the last `ExecutionId` emitted in `executions` iff another page is
3705/// available; callers pass that id back as the next call's `cursor`
3706/// (exclusive start). `next_cursor = None` signals end-of-stream.
3707///
3708/// `#[non_exhaustive]` — FF may add fields (e.g. `approximate_total`)
3709/// in minor releases without a semver break. Use
3710/// [`ListExecutionsPage::new`] for cross-crate construction.
3711#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3712#[non_exhaustive]
3713pub struct ListExecutionsPage {
3714 /// Execution ids on this page, in ascending lexicographic order.
3715 pub executions: Vec<ExecutionId>,
3716 /// Exclusive cursor to request the next page. `None` ⇒ no more
3717 /// results.
3718 pub next_cursor: Option<ExecutionId>,
3719}
3720
3721impl ListExecutionsPage {
3722 /// Construct a [`ListExecutionsPage`]. Present so downstream
3723 /// crates can assemble the struct despite the `#[non_exhaustive]`
3724 /// marker.
3725 pub fn new(executions: Vec<ExecutionId>, next_cursor: Option<ExecutionId>) -> Self {
3726 Self { executions, next_cursor }
3727 }
3728}
3729
3730// ─── rotate_waitpoint_hmac_secret ───
3731
3732/// Args for `ff_rotate_waitpoint_hmac_secret`. Rotates the HMAC signing
3733/// kid on ONE partition. Callers fan out across every partition themselves
3734/// (ff-server does the parallel fan-out in `rotate_waitpoint_secret`;
3735/// direct-Valkey consumers mirror the pattern).
3736///
3737/// "now" is derived server-side from `redis.call("TIME")` inside the FCALL
3738/// (consistency with `validate_waitpoint_token` and flow scanners).
3739/// `grace_ms` is a duration, not a clock value, so carrying it from the
3740/// caller is safe.
3741#[derive(Clone, Debug)]
3742pub struct RotateWaitpointHmacSecretArgs {
3743 pub new_kid: String,
3744 pub new_secret_hex: String,
3745 /// Grace window in ms. Must be non-negative. Tokens signed by the
3746 /// outgoing kid remain valid for `grace_ms` after this rotation.
3747 pub grace_ms: u64,
3748}
3749
3750/// Outcome of a single-partition rotation.
3751#[derive(Clone, Debug, PartialEq, Eq)]
3752pub enum RotateWaitpointHmacSecretOutcome {
3753 /// Installed the new kid. `previous_kid` is `None` on bootstrap
3754 /// (no prior `current_kid`). `gc_count` counts expired kids reaped
3755 /// during this rotation.
3756 Rotated {
3757 previous_kid: Option<String>,
3758 new_kid: String,
3759 gc_count: u32,
3760 },
3761 /// Exact replay — same kid + same secret already installed. Safe
3762 /// operator retry; no state change.
3763 Noop { kid: String },
3764}
3765
3766// ─── rotate_waitpoint_hmac_secret_all ───
3767
3768/// Args for [`EngineBackend::rotate_waitpoint_hmac_secret_all`] — the
3769/// cluster-wide / backend-native rotation of the waitpoint HMAC
3770/// signing kid.
3771///
3772/// **v0.7 migration-master Q4:** a single additive trait method
3773/// replaces the per-partition fan-out that direct-Valkey consumers
3774/// hand-rolled via
3775/// [`ff_sdk::admin::rotate_waitpoint_hmac_secret_all_partitions`].
3776/// On Valkey it fans out N FCALLs (one per execution partition);
3777/// on Postgres (Wave 4) it resolves to a single INSERT against the
3778/// global `ff_waitpoint_hmac(kid, secret, rotated_at)` table (no
3779/// partition_id column). Consumers prefer this method for clarity —
3780/// the pre-existing free-fn + per-partition surface stays available
3781/// for backwards compat.
3782///
3783/// `#[non_exhaustive]` with a [`Self::new`] constructor per the
3784/// project memory-rule (unbuildable non_exhaustive types are a dead
3785/// API).
3786#[derive(Clone, Debug)]
3787#[non_exhaustive]
3788pub struct RotateWaitpointHmacSecretAllArgs {
3789 pub new_kid: String,
3790 pub new_secret_hex: String,
3791 /// Grace window in ms for tokens signed by the outgoing kid.
3792 /// Duration (not a clock value), identical to
3793 /// [`RotateWaitpointHmacSecretArgs::grace_ms`].
3794 pub grace_ms: u64,
3795}
3796
3797impl RotateWaitpointHmacSecretAllArgs {
3798 /// Build the args. Keeping the constructor so consumers don't
3799 /// struct-literal past the `#[non_exhaustive]` marker.
3800 pub fn new(
3801 new_kid: impl Into<String>,
3802 new_secret_hex: impl Into<String>,
3803 grace_ms: u64,
3804 ) -> Self {
3805 Self {
3806 new_kid: new_kid.into(),
3807 new_secret_hex: new_secret_hex.into(),
3808 grace_ms,
3809 }
3810 }
3811}
3812
3813/// Per-partition entry of [`RotateWaitpointHmacSecretAllResult`].
3814/// Mirrors [`ff_sdk::admin::PartitionRotationOutcome`] but typed at
3815/// the `ff-core` layer so both Valkey and Postgres backends return
3816/// the same shape without a Postgres→ferriskey dep.
3817///
3818/// On backends with no partition concept (Postgres) the entry list
3819/// has length 1 with `partition = 0` and the outcome of the global
3820/// row write.
3821#[derive(Debug)]
3822#[non_exhaustive]
3823pub struct RotateWaitpointHmacSecretAllEntry {
3824 pub partition: u16,
3825 /// The per-partition (or global) rotation outcome. Per-partition
3826 /// failures are surfaced as inner `Err` so the fan-out can report
3827 /// partial success — matching the existing SDK free-fn contract.
3828 pub result: Result<RotateWaitpointHmacSecretOutcome, crate::engine_error::EngineError>,
3829}
3830
3831impl RotateWaitpointHmacSecretAllEntry {
3832 pub fn new(
3833 partition: u16,
3834 result: Result<RotateWaitpointHmacSecretOutcome, crate::engine_error::EngineError>,
3835 ) -> Self {
3836 Self { partition, result }
3837 }
3838}
3839
3840/// Result of [`EngineBackend::rotate_waitpoint_hmac_secret_all`].
3841///
3842/// The Valkey backend returns one entry per execution partition. The
3843/// Postgres backend (Wave 4) will return a single-entry vec with
3844/// `partition = 0` since the Postgres schema stores one global row
3845/// per kid (Q4 §adjudication). Consumers that want a uniform "did
3846/// ALL rotations succeed?" view inspect each entry's `.result`.
3847#[derive(Debug)]
3848#[non_exhaustive]
3849pub struct RotateWaitpointHmacSecretAllResult {
3850 pub entries: Vec<RotateWaitpointHmacSecretAllEntry>,
3851}
3852
3853impl RotateWaitpointHmacSecretAllResult {
3854 pub fn new(entries: Vec<RotateWaitpointHmacSecretAllEntry>) -> Self {
3855 Self { entries }
3856 }
3857}
3858
3859// ─── seed_waitpoint_hmac_secret (issue #280) ───
3860
3861/// Args for [`EngineBackend::seed_waitpoint_hmac_secret`].
3862///
3863/// Two required fields and no optional knobs, so there is no fluent
3864/// builder — just `new(kid, secret_hex)`. `#[non_exhaustive]` is kept
3865/// (with the paired constructor, per the project memory rule) so
3866/// future additive knobs don't break callers.
3867///
3868/// Boot-time provisioning entry point for fresh deployments — see
3869/// issue #280 for why cairn needed this in addition to
3870/// [`RotateWaitpointHmacSecretAllArgs`]. Unlike rotate, seed is
3871/// idempotent: callers invoke it on every boot and the backend
3872/// decides whether to install.
3873#[derive(Clone, Debug)]
3874#[non_exhaustive]
3875pub struct SeedWaitpointHmacSecretArgs {
3876 pub kid: String,
3877 pub secret_hex: String,
3878}
3879
3880impl SeedWaitpointHmacSecretArgs {
3881 pub fn new(kid: impl Into<String>, secret_hex: impl Into<String>) -> Self {
3882 Self {
3883 kid: kid.into(),
3884 secret_hex: secret_hex.into(),
3885 }
3886 }
3887}
3888
3889/// Result of [`EngineBackend::seed_waitpoint_hmac_secret`].
3890///
3891/// * `Seeded` — the backend had no `current_kid` (or no row in the
3892/// global keystore) and installed `kid` as the active signing kid.
3893/// * `AlreadySeeded` — a row for `kid` is already installed.
3894/// `same_secret` reports whether the stored secret bytes match the
3895/// caller-supplied hex; `false` means the caller should pick a fresh
3896/// kid for rotation rather than silently re-installing under the
3897/// existing kid.
3898#[derive(Clone, Debug, PartialEq, Eq)]
3899#[non_exhaustive]
3900pub enum SeedOutcome {
3901 Seeded { kid: String },
3902 AlreadySeeded { kid: String, same_secret: bool },
3903}
3904
3905// ─── list_waitpoint_hmac_kids ───
3906
3907#[derive(Clone, Debug, PartialEq, Eq)]
3908pub struct ListWaitpointHmacKidsArgs {}
3909
3910/// Snapshot of the waitpoint HMAC keystore on ONE partition.
3911#[derive(Clone, Debug, PartialEq, Eq)]
3912pub struct WaitpointHmacKids {
3913 /// The currently-signing kid. `None` if uninitialized.
3914 pub current_kid: Option<String>,
3915 /// Kids that still validate existing tokens but no longer sign
3916 /// new ones. Order is Lua HGETALL traversal order — callers that
3917 /// need a stable sort should sort by `expires_at_ms`.
3918 pub verifying: Vec<VerifyingKid>,
3919}
3920
3921#[derive(Clone, Debug, PartialEq, Eq)]
3922pub struct VerifyingKid {
3923 pub kid: String,
3924 pub expires_at_ms: i64,
3925}
3926
3927// ═══════════════════════════════════════════════════════════════════════
3928// RFC-013 Stage 1d: EngineBackend::suspend typed args + outcome
3929// ═══════════════════════════════════════════════════════════════════════
3930//
3931// `SuspendExecutionArgs` / `SuspendExecutionResult` above remain the
3932// wire-level Lua-ARGV mirror used by the backend serializer. The types
3933// below are the public trait-surface shapes RFC-013 §2.2–§2.6 specifies.
3934//
3935// Every type in this block is `#[non_exhaustive]` per the RFC §2.2.1
3936// memory-rule compliance note; each gets a constructor so external-crate
3937// consumers can build them without struct-literal access.
3938
3939use crate::backend::WaitpointHmac;
3940
3941/// Partition-scoped idempotency key for retry-safe `EngineBackend::suspend`.
3942///
3943/// See RFC-013 §2.2 — when set on [`SuspendArgs::idempotency_key`], the
3944/// backend dedups the call on `(partition, execution_id, idempotency_key)`
3945/// and a second `suspend` with the same triple returns the first call's
3946/// [`SuspendOutcome`] verbatim. Absent a key, `suspend` is NOT retry-
3947/// idempotent; callers must describe-and-reconcile per §3.1.
3948///
3949/// Follows the `UsageDimensions::dedup_key` pattern — opaque to the
3950/// engine, byte-compared at the partition scope.
3951#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3952#[serde(transparent)]
3953pub struct IdempotencyKey(String);
3954
3955impl IdempotencyKey {
3956 /// Construct from any stringy input. Empty strings are accepted;
3957 /// the backend treats an empty key as "no dedup" at the serialize
3958 /// step so `Some(IdempotencyKey::new(""))` is functionally the same
3959 /// as `None`.
3960 pub fn new(key: impl Into<String>) -> Self {
3961 Self(key.into())
3962 }
3963
3964 /// Borrow the underlying string.
3965 pub fn as_str(&self) -> &str {
3966 &self.0
3967 }
3968}
3969
3970impl std::fmt::Display for IdempotencyKey {
3971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3972 f.write_str(&self.0)
3973 }
3974}
3975
3976/// v1 signal-match predicate inside [`ResumeCondition::Single`].
3977///
3978/// RFC-013 §2.4 — `ByName(String)` matches a single concrete signal
3979/// name; `Wildcard` matches any delivered signal. RFC-014 may extend
3980/// (payload predicates, pattern matching) — `#[non_exhaustive]`.
3981#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3982#[non_exhaustive]
3983pub enum SignalMatcher {
3984 /// Match by exact signal name.
3985 ByName(String),
3986 /// Match any signal delivered to the waitpoint.
3987 Wildcard,
3988}
3989
3990/// Hard cap on composite-condition nesting depth (RFC-014 §5.4
3991/// invariant 4; §5.5 cap rationale). Soft-cap: bumping requires only
3992/// this constant + the cap-rationale paragraph in RFC-014 §5.5 — no
3993/// wire-format change. Keep in sync.
3994pub const MAX_COMPOSITE_DEPTH: usize = 4;
3995
3996/// RFC-013 reserves this enum slot; RFC-014 populates it with the
3997/// concrete composition vocabulary (`AllOf` + `Count`). The enum is
3998/// `#[non_exhaustive]` so RFC-016 or later RFCs may add variants
3999/// (`AnyOf` has been explicitly rejected per RFC-014 §2.3 in favour of
4000/// `Count { n: 1, .. }`; the guard exists for orthogonal future work).
4001#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4002#[serde(tag = "kind")]
4003#[non_exhaustive]
4004pub enum CompositeBody {
4005 /// All listed sub-conditions must be satisfied. Order-independent.
4006 /// Once satisfied, further signals to member waitpoints are observed
4007 /// but do not re-open satisfaction. RFC-014 §2.1.
4008 AllOf {
4009 members: Vec<ResumeCondition>,
4010 },
4011 /// At least `n` distinct satisfiers (by [`CountKind`]) must match.
4012 /// `matcher` optionally constrains participating signals; `None`
4013 /// lets any signal on any of `waitpoints` count. RFC-014 §2.1.
4014 Count {
4015 n: u32,
4016 count_kind: CountKind,
4017 #[serde(default, skip_serializing_if = "Option::is_none")]
4018 matcher: Option<SignalMatcher>,
4019 waitpoints: Vec<String>,
4020 },
4021}
4022
4023/// How `Count` nodes distinguish satisfiers. RFC-014 §2.1 + §3.2.
4024#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4025#[non_exhaustive]
4026pub enum CountKind {
4027 /// n distinct `waitpoint_id`s in `waitpoints` must fire.
4028 DistinctWaitpoints,
4029 /// n distinct `signal_id`s across the waitpoint set.
4030 DistinctSignals,
4031 /// n distinct `source_type:source_identity` tuples.
4032 DistinctSources,
4033}
4034
4035impl CompositeBody {
4036 /// `AllOf { members }` constructor (RFC-014 §10.3 SDK surface).
4037 pub fn all_of(members: impl IntoIterator<Item = ResumeCondition>) -> Self {
4038 Self::AllOf {
4039 members: members.into_iter().collect(),
4040 }
4041 }
4042
4043 /// `Count` constructor with explicit kind + waitpoint set.
4044 pub fn count(
4045 n: u32,
4046 count_kind: CountKind,
4047 matcher: Option<SignalMatcher>,
4048 waitpoints: impl IntoIterator<Item = String>,
4049 ) -> Self {
4050 Self::Count {
4051 n,
4052 count_kind,
4053 matcher,
4054 waitpoints: waitpoints.into_iter().collect(),
4055 }
4056 }
4057}
4058
4059/// Declarative resume condition for [`SuspendArgs::resume_condition`].
4060///
4061/// RFC-013 §2.4 — typed replacement for the SDK's former
4062/// `ConditionMatcher` / `resume_condition_json` pair.
4063#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4064#[non_exhaustive]
4065pub enum ResumeCondition {
4066 /// Single waitpoint-key match with a predicate. `matcher` is
4067 /// evaluated against every signal delivered to `waitpoint_key`.
4068 Single {
4069 waitpoint_key: String,
4070 matcher: SignalMatcher,
4071 },
4072 /// Operator-only resume — no signal satisfies; only an explicit
4073 /// operator resume closes the waitpoint.
4074 OperatorOnly,
4075 /// Pure-timeout suspension. No signal satisfier; the waitpoint
4076 /// resolves only via `timeout_behavior` at `timeout_at`. Requires
4077 /// `SuspendArgs::timeout_at` to be `Some(_)` — otherwise the
4078 /// Rust-side validator rejects as `timeout_only_without_deadline`.
4079 TimeoutOnly,
4080 /// Multi-condition composition; RFC-014 defines the body.
4081 Composite(CompositeBody),
4082}
4083
4084/// RFC-014 §5.1 validation error shape. Emitted by
4085/// [`ResumeCondition::validate_composite`] when a composite fails a
4086/// structural / cardinality invariant at suspend-time, before any Valkey
4087/// call. Carries a human-readable `detail` per §5.1.1.
4088#[derive(Clone, Debug, PartialEq, Eq)]
4089pub struct CompositeValidationError {
4090 pub detail: String,
4091}
4092
4093impl CompositeValidationError {
4094 fn new(detail: impl Into<String>) -> Self {
4095 Self {
4096 detail: detail.into(),
4097 }
4098 }
4099}
4100
4101impl ResumeCondition {
4102 /// RFC-014 §10.3 builder — `AllOf` across N distinct waitpoints,
4103 /// each member a `Single { matcher: Wildcard }` leaf. Canonical
4104 /// Pattern 3 shape for heterogeneous-subsystem "all fired"
4105 /// semantics (e.g. `db-migration-complete` + `cache-warmed` +
4106 /// `feature-flag-set`).
4107 ///
4108 /// Callers that need per-waitpoint matchers should construct the
4109 /// tree directly via
4110 /// [`ResumeCondition::Composite(CompositeBody::all_of(..))`].
4111 pub fn all_of_waitpoints<I, S>(waitpoint_keys: I) -> Self
4112 where
4113 I: IntoIterator<Item = S>,
4114 S: Into<String>,
4115 {
4116 let members: Vec<ResumeCondition> = waitpoint_keys
4117 .into_iter()
4118 .map(|k| ResumeCondition::Single {
4119 waitpoint_key: k.into(),
4120 matcher: SignalMatcher::Wildcard,
4121 })
4122 .collect();
4123 ResumeCondition::Composite(CompositeBody::AllOf { members })
4124 }
4125
4126 /// Collect every distinct `waitpoint_key` the condition targets.
4127 /// Used at suspend-time to validate the condition's wp set against
4128 /// `SuspendArgs.waitpoints` (RFC-014 §5.1 multi-binding cross-
4129 /// check). Order follows tree DFS, de-duplicated preserving first
4130 /// occurrence.
4131 pub fn referenced_waitpoint_keys(&self) -> Vec<String> {
4132 let mut out: Vec<String> = Vec::new();
4133 let mut push = |k: &str| {
4134 if !out.iter().any(|e| e == k) {
4135 out.push(k.to_owned());
4136 }
4137 };
4138 fn walk(cond: &ResumeCondition, push: &mut dyn FnMut(&str)) {
4139 match cond {
4140 ResumeCondition::Single { waitpoint_key, .. } => push(waitpoint_key),
4141 ResumeCondition::Composite(body) => walk_body(body, push),
4142 _ => {}
4143 }
4144 }
4145 fn walk_body(body: &CompositeBody, push: &mut dyn FnMut(&str)) {
4146 match body {
4147 CompositeBody::AllOf { members } => {
4148 for m in members {
4149 walk(m, push);
4150 }
4151 }
4152 CompositeBody::Count { waitpoints, .. } => {
4153 for w in waitpoints {
4154 push(w.as_str());
4155 }
4156 }
4157 }
4158 }
4159 walk(self, &mut push);
4160 out
4161 }
4162
4163 /// Validate RFC-014 structural invariants on a composite condition.
4164 /// Single / OperatorOnly / TimeoutOnly return Ok — they carry no
4165 /// composite body. Checks cover:
4166 /// * `AllOf { members: [] }` — §5.1 `allof_empty_members`
4167 /// * `Count { n: 0 }` — §5.1 `count_n_zero`
4168 /// * `Count { waitpoints: [] }` — §5.1 `count_waitpoints_empty`
4169 /// * `Count { n > waitpoints.len(), DistinctWaitpoints }` — §5.1
4170 /// `count_exceeds_waitpoint_set`
4171 /// * depth > [`MAX_COMPOSITE_DEPTH`] — §5.1 `condition_depth_exceeded`
4172 pub fn validate_composite(&self) -> Result<(), CompositeValidationError> {
4173 match self {
4174 ResumeCondition::Composite(body) => validate_body(body, 1, ""),
4175 _ => Ok(()),
4176 }
4177 }
4178}
4179
4180fn validate_body(
4181 body: &CompositeBody,
4182 depth: usize,
4183 path: &str,
4184) -> Result<(), CompositeValidationError> {
4185 if depth > MAX_COMPOSITE_DEPTH {
4186 return Err(CompositeValidationError::new(format!(
4187 "depth {} exceeds cap {} at path {}",
4188 depth,
4189 MAX_COMPOSITE_DEPTH,
4190 if path.is_empty() { "<root>" } else { path }
4191 )));
4192 }
4193 match body {
4194 CompositeBody::AllOf { members } => {
4195 if members.is_empty() {
4196 return Err(CompositeValidationError::new(format!(
4197 "allof_empty_members at path {}",
4198 if path.is_empty() { "<root>" } else { path }
4199 )));
4200 }
4201 for (i, m) in members.iter().enumerate() {
4202 let child_path = if path.is_empty() {
4203 format!("members[{i}]")
4204 } else {
4205 format!("{path}.members[{i}]")
4206 };
4207 if let ResumeCondition::Composite(inner) = m {
4208 validate_body(inner, depth + 1, &child_path)?;
4209 }
4210 // Leaf `Single` / operator / timeout needs no further
4211 // structural checks — RFC-013 already constrains them.
4212 }
4213 Ok(())
4214 }
4215 CompositeBody::Count {
4216 n,
4217 count_kind,
4218 waitpoints,
4219 ..
4220 } => {
4221 if *n == 0 {
4222 return Err(CompositeValidationError::new(format!(
4223 "count_n_zero at path {}",
4224 if path.is_empty() { "<root>" } else { path }
4225 )));
4226 }
4227 if waitpoints.is_empty() {
4228 return Err(CompositeValidationError::new(format!(
4229 "count_waitpoints_empty at path {}",
4230 if path.is_empty() { "<root>" } else { path }
4231 )));
4232 }
4233 if matches!(count_kind, CountKind::DistinctWaitpoints)
4234 && (*n as usize) > waitpoints.len()
4235 {
4236 return Err(CompositeValidationError::new(format!(
4237 "count_exceeds_waitpoint_set: n={} > waitpoints.len()={} at path {}",
4238 n,
4239 waitpoints.len(),
4240 if path.is_empty() { "<root>" } else { path }
4241 )));
4242 }
4243 Ok(())
4244 }
4245 }
4246}
4247
4248/// Where a satisfied suspension routes back to.
4249///
4250/// v1 ships only [`ResumeTarget::Runnable`] — execution returns to
4251/// `runnable` and goes through normal scheduling.
4252#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4253#[non_exhaustive]
4254pub enum ResumeTarget {
4255 Runnable,
4256}
4257
4258/// Resume-side policy carried alongside [`ResumeCondition`].
4259///
4260/// RFC-013 §2.5 — what happens when the condition is satisfied. Fields
4261/// mirror the `resume_policy_json` the backend serializer writes to Lua
4262/// (RFC-004 §Resume policy fields).
4263#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4264#[non_exhaustive]
4265pub struct ResumePolicy {
4266 pub resume_target: ResumeTarget,
4267 pub consume_matched_signals: bool,
4268 pub retain_signal_buffer_until_closed: bool,
4269 #[serde(default, skip_serializing_if = "Option::is_none")]
4270 pub resume_delay_ms: Option<u64>,
4271 pub close_waitpoint_on_resume: bool,
4272}
4273
4274impl Default for ResumePolicy {
4275 fn default() -> Self {
4276 Self::normal()
4277 }
4278}
4279
4280impl ResumePolicy {
4281 /// Construct a [`ResumePolicy`] with the canonical v1 defaults
4282 /// (see [`Self::normal`]). Alias for [`Self::normal`] — provided
4283 /// so external consumers have a conventional `new` constructor
4284 /// against this `#[non_exhaustive]` struct.
4285 pub fn new() -> Self {
4286 Self::normal()
4287 }
4288
4289 /// Canonical v1 defaults (RFC-013 §2.2.1):
4290 /// * `resume_target = Runnable`
4291 /// * `consume_matched_signals = true`
4292 /// * `retain_signal_buffer_until_closed = false`
4293 /// * `resume_delay_ms = None`
4294 /// * `close_waitpoint_on_resume = true`
4295 pub fn normal() -> Self {
4296 Self {
4297 resume_target: ResumeTarget::Runnable,
4298 consume_matched_signals: true,
4299 retain_signal_buffer_until_closed: false,
4300 resume_delay_ms: None,
4301 close_waitpoint_on_resume: true,
4302 }
4303 }
4304}
4305
4306/// Timeout behavior at the suspension deadline (RFC-004 §Timeout Behavior).
4307#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4308#[non_exhaustive]
4309pub enum TimeoutBehavior {
4310 Fail,
4311 Cancel,
4312 Expire,
4313 AutoResumeWithTimeoutSignal,
4314 /// v2 per RFC-004 Implementation Notes; enum slot present for
4315 /// additive RFC-014/RFC-015 landing.
4316 Escalate,
4317}
4318
4319impl TimeoutBehavior {
4320 /// Lua-side string encoding. Matches the wire values Lua's
4321 /// `ff_expire_suspension` matches on.
4322 pub fn as_wire_str(self) -> &'static str {
4323 match self {
4324 Self::Fail => "fail",
4325 Self::Cancel => "cancel",
4326 Self::Expire => "expire",
4327 Self::AutoResumeWithTimeoutSignal => "auto_resume_with_timeout_signal",
4328 Self::Escalate => "escalate",
4329 }
4330 }
4331}
4332
4333/// Reason category for a suspension (RFC-004 §Suspension Reason Categories).
4334#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4335#[non_exhaustive]
4336pub enum SuspensionReasonCode {
4337 WaitingForSignal,
4338 WaitingForApproval,
4339 WaitingForCallback,
4340 WaitingForToolResult,
4341 WaitingForOperatorReview,
4342 PausedByPolicy,
4343 PausedByBudget,
4344 StepBoundary,
4345 ManualPause,
4346}
4347
4348impl SuspensionReasonCode {
4349 pub fn as_wire_str(self) -> &'static str {
4350 match self {
4351 Self::WaitingForSignal => "waiting_for_signal",
4352 Self::WaitingForApproval => "waiting_for_approval",
4353 Self::WaitingForCallback => "waiting_for_callback",
4354 Self::WaitingForToolResult => "waiting_for_tool_result",
4355 Self::WaitingForOperatorReview => "waiting_for_operator_review",
4356 Self::PausedByPolicy => "paused_by_policy",
4357 Self::PausedByBudget => "paused_by_budget",
4358 Self::StepBoundary => "step_boundary",
4359 Self::ManualPause => "manual_pause",
4360 }
4361 }
4362}
4363
4364/// Who requested the suspension.
4365#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
4366#[non_exhaustive]
4367pub enum SuspensionRequester {
4368 Worker,
4369 Operator,
4370 Policy,
4371 SystemTimeoutPolicy,
4372}
4373
4374impl SuspensionRequester {
4375 pub fn as_wire_str(self) -> &'static str {
4376 match self {
4377 Self::Worker => "worker",
4378 Self::Operator => "operator",
4379 Self::Policy => "policy",
4380 Self::SystemTimeoutPolicy => "system_timeout_policy",
4381 }
4382 }
4383}
4384
4385/// How the waitpoint resource backing a [`SuspendArgs`] is obtained.
4386///
4387/// RFC-013 §2.2 — `Fresh` mints a new waitpoint as part of `suspend`;
4388/// `UsePending` activates a waitpoint previously issued via
4389/// `EngineBackend::create_waitpoint`.
4390#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
4391#[non_exhaustive]
4392pub enum WaitpointBinding {
4393 Fresh {
4394 waitpoint_id: WaitpointId,
4395 waitpoint_key: String,
4396 },
4397 UsePending {
4398 waitpoint_id: WaitpointId,
4399 },
4400}
4401
4402impl WaitpointBinding {
4403 /// Mint a fresh binding with a random `waitpoint_id` (UUID v4) and
4404 /// `waitpoint_key = "wpk:<uuid>"`.
4405 pub fn fresh() -> Self {
4406 let wp_id = WaitpointId::new();
4407 let key = format!("wpk:{wp_id}");
4408 Self::Fresh {
4409 waitpoint_id: wp_id,
4410 waitpoint_key: key,
4411 }
4412 }
4413
4414 /// Construct a `UsePending` binding from a pending waitpoint
4415 /// previously issued by `create_waitpoint`. The HMAC token is
4416 /// resolved Lua-side from the partition's waitpoint hash at
4417 /// `suspend` time (RFC-013 §5.1).
4418 pub fn use_pending(pending: &crate::backend::PendingWaitpoint) -> Self {
4419 Self::UsePending {
4420 waitpoint_id: pending.waitpoint_id.clone(),
4421 }
4422 }
4423}
4424
4425/// Trait-surface input to [`EngineBackend::suspend`] (RFC-013 §2.2 +
4426/// RFC-014 Pattern 3 widening).
4427///
4428/// Built via [`SuspendArgs::new`] + `with_*` setters; direct struct-
4429/// literal construction across crate boundaries is not possible
4430/// (`#[non_exhaustive]`).
4431///
4432/// ## Waitpoints
4433///
4434/// `waitpoints` is a non-empty `Vec<WaitpointBinding>`. The first entry
4435/// is the "primary" binding (accessible via [`primary`](Self::primary))
4436/// and carries the `current_waitpoint_id` written onto `exec_core` for
4437/// operator visibility. Additional entries land in Valkey as their own
4438/// waitpoint hashes / signal streams / HMAC tokens, enabling RFC-014
4439/// Pattern 3 `AllOf { members: [Single{wp1}, Single{wp2}, ...] }` across
4440/// distinct heterogeneous subsystems.
4441///
4442/// [`SuspendArgs::new`] takes exactly the primary binding; call
4443/// [`with_waitpoint`](Self::with_waitpoint) to append further bindings
4444/// (the RFC-014 builder API).
4445#[derive(Clone, Debug, Serialize, Deserialize)]
4446#[non_exhaustive]
4447pub struct SuspendArgs {
4448 pub suspension_id: SuspensionId,
4449 /// RFC-014 Pattern 3: all waitpoint bindings for this suspension.
4450 /// Guaranteed non-empty; `waitpoints[0]` is the primary.
4451 pub waitpoints: Vec<WaitpointBinding>,
4452 pub resume_condition: ResumeCondition,
4453 pub resume_policy: ResumePolicy,
4454 pub reason_code: SuspensionReasonCode,
4455 pub requested_by: SuspensionRequester,
4456 #[serde(default, skip_serializing_if = "Option::is_none")]
4457 pub timeout_at: Option<TimestampMs>,
4458 pub timeout_behavior: TimeoutBehavior,
4459 #[serde(default, skip_serializing_if = "Option::is_none")]
4460 pub continuation_metadata_pointer: Option<String>,
4461 pub now: TimestampMs,
4462 #[serde(default, skip_serializing_if = "Option::is_none")]
4463 pub idempotency_key: Option<IdempotencyKey>,
4464}
4465
4466impl SuspendArgs {
4467 /// Build a minimal `SuspendArgs` for a worker-originated suspension.
4468 ///
4469 /// `waitpoint` becomes the primary binding. Append additional
4470 /// bindings with [`with_waitpoint`](Self::with_waitpoint) (RFC-014
4471 /// Pattern 3) or replace the set with
4472 /// [`with_waitpoints`](Self::with_waitpoints).
4473 ///
4474 /// Defaults: `requested_by = Worker`, `timeout_at = None`,
4475 /// `timeout_behavior = Fail`, `continuation_metadata_pointer = None`,
4476 /// `idempotency_key = None`.
4477 pub fn new(
4478 suspension_id: SuspensionId,
4479 waitpoint: WaitpointBinding,
4480 resume_condition: ResumeCondition,
4481 resume_policy: ResumePolicy,
4482 reason_code: SuspensionReasonCode,
4483 now: TimestampMs,
4484 ) -> Self {
4485 Self {
4486 suspension_id,
4487 waitpoints: vec![waitpoint],
4488 resume_condition,
4489 resume_policy,
4490 reason_code,
4491 requested_by: SuspensionRequester::Worker,
4492 timeout_at: None,
4493 timeout_behavior: TimeoutBehavior::Fail,
4494 continuation_metadata_pointer: None,
4495 now,
4496 idempotency_key: None,
4497 }
4498 }
4499
4500 /// Primary binding — `waitpoints[0]`. Guaranteed present by
4501 /// construction.
4502 pub fn primary(&self) -> &WaitpointBinding {
4503 &self.waitpoints[0]
4504 }
4505
4506 pub fn with_timeout(mut self, at: TimestampMs, behavior: TimeoutBehavior) -> Self {
4507 self.timeout_at = Some(at);
4508 self.timeout_behavior = behavior;
4509 self
4510 }
4511
4512 pub fn with_requester(mut self, requester: SuspensionRequester) -> Self {
4513 self.requested_by = requester;
4514 self
4515 }
4516
4517 pub fn with_continuation_metadata_pointer(mut self, p: String) -> Self {
4518 self.continuation_metadata_pointer = Some(p);
4519 self
4520 }
4521
4522 pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
4523 self.idempotency_key = Some(key);
4524 self
4525 }
4526
4527 /// RFC-014 Pattern 3 — append a further waitpoint binding to this
4528 /// suspension. Each additional binding yields its own waitpoint
4529 /// hash, signal stream, condition hash and HMAC token in Valkey,
4530 /// but all share the suspension record and composite evaluator
4531 /// under one `suspension:current`.
4532 ///
4533 /// Ordering: the primary (from [`SuspendArgs::new`]) stays at
4534 /// `waitpoints[0]`; subsequent `with_waitpoint` calls append at the
4535 /// tail.
4536 pub fn with_waitpoint(mut self, binding: WaitpointBinding) -> Self {
4537 self.waitpoints.push(binding);
4538 self
4539 }
4540
4541 /// RFC-014 Pattern 3 — replace the full binding vector in one call.
4542 /// Must be non-empty; an empty Vec is a programmer error and will
4543 /// be rejected by the backend's `validate_suspend_args` with
4544 /// `waitpoints_empty`.
4545 pub fn with_waitpoints(mut self, bindings: Vec<WaitpointBinding>) -> Self {
4546 self.waitpoints = bindings;
4547 self
4548 }
4549}
4550
4551/// Shared "what happened on the waitpoint" payload carried in both
4552/// [`SuspendOutcome`] variants.
4553///
4554/// For Pattern 3 (RFC-014) — multi-waitpoint suspensions — the primary
4555/// binding's identity lives at the top level (`waitpoint_id` /
4556/// `waitpoint_key` / `waitpoint_token`) and remaining bindings are
4557/// exposed via `additional_waitpoints`, each carrying its own minted
4558/// HMAC token so external signallers can deliver to any of the N
4559/// waitpoints the suspension is listening on.
4560#[derive(Clone, Debug, PartialEq, Eq)]
4561#[non_exhaustive]
4562pub struct SuspendOutcomeDetails {
4563 pub suspension_id: SuspensionId,
4564 pub waitpoint_id: WaitpointId,
4565 pub waitpoint_key: String,
4566 pub waitpoint_token: WaitpointHmac,
4567 /// RFC-014 Pattern 3 extras (beyond the primary). Empty for
4568 /// single-waitpoint suspensions (patterns 1 + 2); carries one
4569 /// entry per additional binding for Pattern 3.
4570 pub additional_waitpoints: Vec<AdditionalWaitpointBinding>,
4571}
4572
4573/// RFC-014 Pattern 3 — per-binding identity + HMAC token for
4574/// waitpoints beyond the primary. Structure mirrors the top-level
4575/// fields on [`SuspendOutcomeDetails`].
4576#[derive(Clone, Debug, PartialEq, Eq)]
4577#[non_exhaustive]
4578pub struct AdditionalWaitpointBinding {
4579 pub waitpoint_id: WaitpointId,
4580 pub waitpoint_key: String,
4581 pub waitpoint_token: WaitpointHmac,
4582}
4583
4584impl AdditionalWaitpointBinding {
4585 pub fn new(
4586 waitpoint_id: WaitpointId,
4587 waitpoint_key: String,
4588 waitpoint_token: WaitpointHmac,
4589 ) -> Self {
4590 Self {
4591 waitpoint_id,
4592 waitpoint_key,
4593 waitpoint_token,
4594 }
4595 }
4596}
4597
4598impl SuspendOutcomeDetails {
4599 pub fn new(
4600 suspension_id: SuspensionId,
4601 waitpoint_id: WaitpointId,
4602 waitpoint_key: String,
4603 waitpoint_token: WaitpointHmac,
4604 ) -> Self {
4605 Self {
4606 suspension_id,
4607 waitpoint_id,
4608 waitpoint_key,
4609 waitpoint_token,
4610 additional_waitpoints: Vec::new(),
4611 }
4612 }
4613
4614 /// Attach RFC-014 Pattern 3 additional-waitpoint bindings. The
4615 /// primary binding stays at the top-level fields; `extras` lands
4616 /// in [`additional_waitpoints`](Self::additional_waitpoints).
4617 pub fn with_additional_waitpoints(
4618 mut self,
4619 extras: Vec<AdditionalWaitpointBinding>,
4620 ) -> Self {
4621 self.additional_waitpoints = extras;
4622 self
4623 }
4624}
4625
4626/// Trait-surface output from [`EngineBackend::suspend`] (RFC-013 §2.3).
4627///
4628/// Two variants encode the "lease released" vs "lease retained" split.
4629/// See §2.3 for the runtime-enforcement semantics.
4630#[derive(Clone, Debug, PartialEq, Eq)]
4631#[non_exhaustive]
4632pub enum SuspendOutcome {
4633 /// The worker's pre-suspend handle is no longer lease-bearing; a
4634 /// fresh `HandleKind::Suspended` handle supersedes it.
4635 Suspended {
4636 details: SuspendOutcomeDetails,
4637 handle: crate::backend::Handle,
4638 },
4639 /// Buffered signals on a pending waitpoint already satisfied the
4640 /// condition at suspension time; the lease is retained and the
4641 /// caller's pre-suspend handle remains valid.
4642 AlreadySatisfied { details: SuspendOutcomeDetails },
4643}
4644
4645impl SuspendOutcome {
4646 /// Borrow the shared details regardless of variant.
4647 pub fn details(&self) -> &SuspendOutcomeDetails {
4648 match self {
4649 Self::Suspended { details, .. } => details,
4650 Self::AlreadySatisfied { details } => details,
4651 }
4652 }
4653}
4654
4655// `EngineBackend::suspend` type re-exports for `ff_core::backend::*`
4656// consumers. The `backend` module re-exports these below so external
4657// crates can reach them via the idiomatic `ff_core::backend` path that
4658// already sources the other trait-surface types (RFC-013 §9.1).
4659
4660// ─── RFC-017 Stage A — trait-expansion Args/Result types ─────────────
4661//
4662// Per RFC-017 §5.1.1: every struct/enum introduced here is
4663// `#[non_exhaustive]` and ships with a `pub fn new(...)` constructor so
4664// additive field growth post-v0.8 does not force cross-crate churn.
4665
4666// ─── claim_for_worker ───
4667
4668/// Inputs to `EngineBackend::claim_for_worker` (RFC-017 §5, §7). The
4669/// Valkey impl forwards to `ff_scheduler::Scheduler::claim_for_worker`;
4670/// the Postgres impl forwards to its own scheduler module. The trait
4671/// method hides the backend-specific dispatch behind one shape.
4672#[non_exhaustive]
4673#[derive(Clone, Debug)]
4674pub struct ClaimForWorkerArgs {
4675 pub lane_id: LaneId,
4676 pub worker_id: WorkerId,
4677 pub worker_instance_id: WorkerInstanceId,
4678 pub worker_capabilities: std::collections::BTreeSet<String>,
4679 pub grant_ttl_ms: u64,
4680}
4681
4682impl ClaimForWorkerArgs {
4683 /// Required-field constructor. Optional fields today: none — kept
4684 /// for forward-compat so a future optional (e.g. `deadline_ms`)
4685 /// does not break callers using the builder pattern.
4686 pub fn new(
4687 lane_id: LaneId,
4688 worker_id: WorkerId,
4689 worker_instance_id: WorkerInstanceId,
4690 worker_capabilities: std::collections::BTreeSet<String>,
4691 grant_ttl_ms: u64,
4692 ) -> Self {
4693 Self {
4694 lane_id,
4695 worker_id,
4696 worker_instance_id,
4697 worker_capabilities,
4698 grant_ttl_ms,
4699 }
4700 }
4701}
4702
4703/// Outcome of `EngineBackend::claim_for_worker`. `None`-like shape
4704/// modelled as an enum so additive variants (e.g. `BackPressured {
4705/// retry_after_ms }`) do not force a wire break.
4706#[non_exhaustive]
4707#[derive(Clone, Debug, PartialEq, Eq)]
4708pub enum ClaimForWorkerOutcome {
4709 /// No eligible execution on this lane at this scan cycle.
4710 NoWork,
4711 /// Grant issued — worker proceeds to `claim_from_grant`.
4712 Granted(ClaimGrant),
4713}
4714
4715impl ClaimForWorkerOutcome {
4716 /// Build the `NoWork` variant.
4717 pub fn no_work() -> Self {
4718 Self::NoWork
4719 }
4720 /// Build the `Granted` variant.
4721 pub fn granted(grant: ClaimGrant) -> Self {
4722 Self::Granted(grant)
4723 }
4724}
4725
4726// ─── list_pending_waitpoints ───
4727
4728/// Inputs to `EngineBackend::list_pending_waitpoints` (RFC-017 §5, §8).
4729/// Pagination is part of the signature so a flow with 10k pending
4730/// waitpoints cannot force a single-round-trip read regardless of
4731/// backend.
4732#[non_exhaustive]
4733#[derive(Clone, Debug)]
4734pub struct ListPendingWaitpointsArgs {
4735 pub execution_id: ExecutionId,
4736 /// Exclusive cursor — `None` starts from the beginning.
4737 pub after: Option<WaitpointId>,
4738 /// Max page size. `None` → backend default (100). Backend-enforced
4739 /// cap: 1000.
4740 pub limit: Option<u32>,
4741}
4742
4743impl ListPendingWaitpointsArgs {
4744 pub fn new(execution_id: ExecutionId) -> Self {
4745 Self {
4746 execution_id,
4747 after: None,
4748 limit: None,
4749 }
4750 }
4751 pub fn with_after(mut self, after: WaitpointId) -> Self {
4752 self.after = Some(after);
4753 self
4754 }
4755 pub fn with_limit(mut self, limit: u32) -> Self {
4756 self.limit = Some(limit);
4757 self
4758 }
4759}
4760
4761/// Page of pending-waitpoint entries. Stage A preserves the existing
4762/// `PendingWaitpointInfo` shape; the §8 schema rewrite (HMAC
4763/// sanitisation + `(token_kid, token_fingerprint)` additive fields)
4764/// ships in Stage D alongside the HTTP wire-format deprecation.
4765#[non_exhaustive]
4766#[derive(Clone, Debug)]
4767pub struct ListPendingWaitpointsResult {
4768 pub entries: Vec<PendingWaitpointInfo>,
4769 /// Forward-only continuation cursor — `None` signals end-of-stream.
4770 pub next_cursor: Option<WaitpointId>,
4771}
4772
4773impl ListPendingWaitpointsResult {
4774 pub fn new(entries: Vec<PendingWaitpointInfo>) -> Self {
4775 Self {
4776 entries,
4777 next_cursor: None,
4778 }
4779 }
4780 pub fn with_next_cursor(mut self, cursor: WaitpointId) -> Self {
4781 self.next_cursor = Some(cursor);
4782 self
4783 }
4784}
4785
4786// ─── report_usage_admin ───
4787
4788/// Inputs to `EngineBackend::report_usage_admin` (RFC-017 §5 budget+
4789/// quota admin §5, round-1 F4). Admin-path peer of `report_usage` —
4790/// both wrap `ff_report_usage_and_check` on the Valkey side but the
4791/// admin call is worker-less, so it cannot reuse the lease-bound
4792/// `report_usage(&Handle, ...)` signature. `ReportUsageAdminArgs`
4793/// carries the same fields as [`ReportUsageArgs`] without a worker
4794/// handle — kept as a distinct type so future admin-only fields (e.g.
4795/// `actor_identity`, `audit_reason`) don't pollute the worker path.
4796#[non_exhaustive]
4797#[derive(Clone, Debug)]
4798pub struct ReportUsageAdminArgs {
4799 pub dimensions: Vec<String>,
4800 pub deltas: Vec<u64>,
4801 pub dedup_key: Option<String>,
4802 pub now: TimestampMs,
4803}
4804
4805impl ReportUsageAdminArgs {
4806 pub fn new(dimensions: Vec<String>, deltas: Vec<u64>, now: TimestampMs) -> Self {
4807 Self {
4808 dimensions,
4809 deltas,
4810 dedup_key: None,
4811 now,
4812 }
4813 }
4814 pub fn with_dedup_key(mut self, key: String) -> Self {
4815 self.dedup_key = Some(key);
4816 self
4817 }
4818}
4819
4820// ─── #454 — cairn ControlPlaneBackend peer methods ──────────────────
4821//
4822// Four trait methods from cairn-rs #454 that previously routed through
4823// raw `ferriskey::*` FCALLs outside the `EngineBackend` trait. Cairn's
4824// ground-truth shapes at `cairn-fabric/src/engine/control_plane_types.rs`
4825// (commit `a4fdb638`) are mirrored below verbatim so the v0.13 trait
4826// matches cairn's existing Valkey impls 1:1.
4827//
4828// Default bodies on the trait return `EngineError::Unavailable { op }`
4829// at landing; Valkey bodies ship in Phase 3; PG + SQLite in Phases 4+5.
4830
4831// ─── record_spend ───
4832
4833/// Args for [`crate::engine_backend::EngineBackend::record_spend`].
4834///
4835/// Carries an **open-set** `BTreeMap<String, u64>` of dimension deltas
4836/// per cairn's ground-truth shape at
4837/// `cairn-fabric/src/engine/control_plane_types.rs`. Cairn budgets are
4838/// per-tenant open-schema (tenant A tracks `"tokens"` + `"cost_cents"`,
4839/// tenant B tracks `"egress_bytes"`), distinct from FF's fixed-shape
4840/// [`UsageDimensions`] which encodes the internal usage-report surface.
4841///
4842/// `BTreeMap` (not `HashMap`) gives stable iteration order — consistent
4843/// with `UsageDimensions::custom`, and critical for the PG body which
4844/// updates multiple dimension rows per call (deterministic ordering
4845/// prevents deadlocks under concurrent spend).
4846///
4847/// Return shape reuses [`ReportUsageResult`] — same four variants
4848/// (`Ok` / `SoftBreach` / `HardBreach` / `AlreadyApplied`) cairn's UI
4849/// branches on. Not a new enum.
4850#[derive(Clone, Debug, Serialize, Deserialize)]
4851#[non_exhaustive]
4852pub struct RecordSpendArgs {
4853 pub budget_id: BudgetId,
4854 pub execution_id: ExecutionId,
4855 /// Per-dimension positive deltas. Tenant-defined keys; stable
4856 /// iteration order.
4857 pub deltas: BTreeMap<String, u64>,
4858 /// Caller-computed idempotency key (cairn uses SHA-256 hex of
4859 /// `budget_id || execution_id || sorted(deltas)`). FF does not
4860 /// interpret the bytes — dedup is a simple equality check against
4861 /// the prior stamped key.
4862 pub idempotency_key: String,
4863}
4864
4865impl RecordSpendArgs {
4866 pub fn new(
4867 budget_id: BudgetId,
4868 execution_id: ExecutionId,
4869 deltas: BTreeMap<String, u64>,
4870 idempotency_key: impl Into<String>,
4871 ) -> Self {
4872 Self {
4873 budget_id,
4874 execution_id,
4875 deltas,
4876 idempotency_key: idempotency_key.into(),
4877 }
4878 }
4879}
4880
4881// ─── release_budget ───
4882
4883/// Args for [`crate::engine_backend::EngineBackend::release_budget`].
4884///
4885/// **Per-execution release-my-attribution**, not whole-budget flush.
4886/// Called when an execution terminates so the budget persists across
4887/// executions but this execution's attribution is reversed. Per cairn
4888/// clarification on #454.
4889#[derive(Clone, Debug, Serialize, Deserialize)]
4890#[non_exhaustive]
4891pub struct ReleaseBudgetArgs {
4892 pub budget_id: BudgetId,
4893 pub execution_id: ExecutionId,
4894}
4895
4896impl ReleaseBudgetArgs {
4897 pub fn new(budget_id: BudgetId, execution_id: ExecutionId) -> Self {
4898 Self {
4899 budget_id,
4900 execution_id,
4901 }
4902 }
4903}
4904
4905// ─── deliver_approval_signal ───
4906
4907/// Args for [`crate::engine_backend::EngineBackend::deliver_approval_signal`].
4908///
4909/// Pre-shaped variant of [`crate::engine_backend::EngineBackend::deliver_signal`]
4910/// for the operator-driven approval flow. Distinct from `deliver_signal`
4911/// because the caller **does not carry the waitpoint token** — the backend
4912/// reads the token from `ff_waitpoint_pending` (via
4913/// [`crate::engine_backend::EngineBackend::read_waitpoint_token`],
4914/// #434-shipped in v0.12), HMAC-verifies server-side, and dispatches. The
4915/// operator API never handles the token bytes.
4916///
4917/// `signal_name` is a flat string (`"approved"` / `"rejected"` by
4918/// convention; not an enum at the trait level — audit metadata like
4919/// `decided_by` / `note` / `reason` sits in cairn's audit log, not in
4920/// the FF signal surface).
4921#[derive(Clone, Debug, Serialize, Deserialize)]
4922#[non_exhaustive]
4923pub struct DeliverApprovalSignalArgs {
4924 pub execution_id: ExecutionId,
4925 pub lane_id: LaneId,
4926 pub waitpoint_id: WaitpointId,
4927 /// Conventional values: `"approved"` / `"rejected"`. Stored raw on
4928 /// the delivered signal; FF does not interpret.
4929 pub signal_name: String,
4930 /// Cairn-side per-decision idempotency suffix. Combined with
4931 /// `execution_id` + `signal_name` to form the dedup key.
4932 pub idempotency_suffix: String,
4933 /// Dedup TTL in milliseconds.
4934 pub signal_dedup_ttl_ms: u64,
4935 /// Signal stream MAXLEN for the suspension stream.
4936 /// `None` ⇒ backend default (matches [`DeliverSignalArgs::signal_maxlen`]).
4937 #[serde(default)]
4938 pub maxlen: Option<u64>,
4939 /// Per-execution max signal cap (operator quota).
4940 /// `None` ⇒ backend default (matches [`DeliverSignalArgs::max_signals_per_execution`]).
4941 #[serde(default)]
4942 pub max_signals_per_execution: Option<u64>,
4943}
4944
4945impl DeliverApprovalSignalArgs {
4946 #[allow(clippy::too_many_arguments)]
4947 pub fn new(
4948 execution_id: ExecutionId,
4949 lane_id: LaneId,
4950 waitpoint_id: WaitpointId,
4951 signal_name: impl Into<String>,
4952 idempotency_suffix: impl Into<String>,
4953 signal_dedup_ttl_ms: u64,
4954 maxlen: Option<u64>,
4955 max_signals_per_execution: Option<u64>,
4956 ) -> Self {
4957 Self {
4958 execution_id,
4959 lane_id,
4960 waitpoint_id,
4961 signal_name: signal_name.into(),
4962 idempotency_suffix: idempotency_suffix.into(),
4963 signal_dedup_ttl_ms,
4964 maxlen,
4965 max_signals_per_execution,
4966 }
4967 }
4968}
4969
4970// ─── issue_grant_and_claim ───
4971
4972/// Args for [`crate::engine_backend::EngineBackend::issue_grant_and_claim`].
4973///
4974/// Composes `issue_claim_grant` + `claim_execution` into a single
4975/// backend-atomic op per cairn #454 Q4. The composition **must** be
4976/// backend-atomic (not caller-chained) to prevent leaking grants when
4977/// `claim_execution` fails after `issue_claim_grant` succeeded.
4978///
4979/// Valkey: one `ff_issue_grant_and_claim` FCALL composing the two
4980/// primitives in Lua.
4981/// Postgres/SQLite: both primitives inside one tx.
4982///
4983/// Flattened shape (not `IssueClaimGrantArgs + ClaimExecutionArgs`
4984/// composition) — the two arg types overlap on `execution_id` +
4985/// `lane_id`; flattening drops the dup.
4986#[derive(Clone, Debug, Serialize, Deserialize)]
4987#[non_exhaustive]
4988pub struct IssueGrantAndClaimArgs {
4989 pub execution_id: ExecutionId,
4990 pub lane_id: LaneId,
4991 /// Lease TTL in milliseconds. Threaded into both the grant TTL and
4992 /// the claimed attempt's `lease_expires_at_ms`.
4993 pub lease_duration_ms: u64,
4994}
4995
4996impl IssueGrantAndClaimArgs {
4997 pub fn new(execution_id: ExecutionId, lane_id: LaneId, lease_duration_ms: u64) -> Self {
4998 Self {
4999 execution_id,
5000 lane_id,
5001 lease_duration_ms,
5002 }
5003 }
5004}
5005
5006/// Outcome of [`crate::engine_backend::EngineBackend::issue_grant_and_claim`].
5007///
5008/// Distinct from [`ClaimExecutionResult`] because the trait method
5009/// intentionally hides the grant-issuance step — callers only see the
5010/// resulting lease identity. If the backend's transparent dispatch
5011/// routes through `ff_claim_resumed_execution` (when the execution was
5012/// suspended), the return is identical.
5013#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
5014#[non_exhaustive]
5015pub struct ClaimGrantOutcome {
5016 pub lease_id: LeaseId,
5017 pub lease_epoch: LeaseEpoch,
5018 pub attempt_index: AttemptIndex,
5019}
5020
5021impl ClaimGrantOutcome {
5022 pub fn new(
5023 lease_id: LeaseId,
5024 lease_epoch: LeaseEpoch,
5025 attempt_index: AttemptIndex,
5026 ) -> Self {
5027 Self {
5028 lease_id,
5029 lease_epoch,
5030 attempt_index,
5031 }
5032 }
5033}
5034
5035#[cfg(test)]
5036mod rfc_014_validation_tests {
5037 use super::*;
5038
5039 fn single(wp: &str) -> ResumeCondition {
5040 ResumeCondition::Single {
5041 waitpoint_key: wp.to_owned(),
5042 matcher: SignalMatcher::ByName("x".to_owned()),
5043 }
5044 }
5045
5046 #[test]
5047 fn single_passes_validate() {
5048 assert!(single("wpk:a").validate_composite().is_ok());
5049 }
5050
5051 #[test]
5052 fn allof_empty_members_rejected() {
5053 let c = ResumeCondition::Composite(CompositeBody::AllOf { members: vec![] });
5054 let e = c.validate_composite().unwrap_err();
5055 assert!(e.detail.contains("allof_empty_members"), "{}", e.detail);
5056 }
5057
5058 #[test]
5059 fn count_n_zero_rejected() {
5060 let c = ResumeCondition::Composite(CompositeBody::Count {
5061 n: 0,
5062 count_kind: CountKind::DistinctWaitpoints,
5063 matcher: None,
5064 waitpoints: vec!["wpk:a".to_owned()],
5065 });
5066 let e = c.validate_composite().unwrap_err();
5067 assert!(e.detail.contains("count_n_zero"), "{}", e.detail);
5068 }
5069
5070 #[test]
5071 fn count_waitpoints_empty_rejected() {
5072 let c = ResumeCondition::Composite(CompositeBody::Count {
5073 n: 1,
5074 count_kind: CountKind::DistinctSources,
5075 matcher: None,
5076 waitpoints: vec![],
5077 });
5078 let e = c.validate_composite().unwrap_err();
5079 assert!(e.detail.contains("count_waitpoints_empty"), "{}", e.detail);
5080 }
5081
5082 #[test]
5083 fn count_exceeds_waitpoint_set_rejected_only_for_distinct_waitpoints() {
5084 // n=3, only 2 waitpoints, DistinctWaitpoints → reject.
5085 let c = ResumeCondition::Composite(CompositeBody::Count {
5086 n: 3,
5087 count_kind: CountKind::DistinctWaitpoints,
5088 matcher: None,
5089 waitpoints: vec!["a".into(), "b".into()],
5090 });
5091 let e = c.validate_composite().unwrap_err();
5092 assert!(e.detail.contains("count_exceeds_waitpoint_set"), "{}", e.detail);
5093
5094 // Same cardinality, DistinctSignals → allowed (no upper bound).
5095 let c2 = ResumeCondition::Composite(CompositeBody::Count {
5096 n: 3,
5097 count_kind: CountKind::DistinctSignals,
5098 matcher: None,
5099 waitpoints: vec!["a".into(), "b".into()],
5100 });
5101 assert!(c2.validate_composite().is_ok());
5102 }
5103
5104 #[test]
5105 fn depth_4_accepted_depth_5_rejected() {
5106 // Build Depth-4: AllOf { AllOf { AllOf { AllOf { Single } } } }
5107 let leaf = single("wpk:leaf");
5108 let d4 = ResumeCondition::Composite(CompositeBody::AllOf {
5109 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5110 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5111 members: vec![ResumeCondition::Composite(CompositeBody::AllOf {
5112 members: vec![leaf.clone()],
5113 })],
5114 })],
5115 })],
5116 });
5117 assert!(d4.validate_composite().is_ok());
5118
5119 // Depth-5 → reject.
5120 let d5 = ResumeCondition::Composite(CompositeBody::AllOf {
5121 members: vec![d4],
5122 });
5123 let e = d5.validate_composite().unwrap_err();
5124 assert!(e.detail.contains("exceeds cap"), "{}", e.detail);
5125 }
5126}