Skip to main content

fusillade_core/
manager.rs

1//! Main traits for the batching system.
2//!
3//! This module defines the `Storage` and `RequestManager` traits, which provide the interface
4//! for persisting requests, creating files, launching batches, and checking execution status.
5
6use crate::batch::{
7    Batch, BatchId, BatchInput, BatchStatus, File, FileContentItem, FileFilter, FileId,
8    FileStreamItem, FileStreamResult, ListBatchesFilter, OutputFileType, RequestTemplateInput,
9};
10use crate::daemon_record::{AnyDaemonRecord, DaemonRecord, DaemonState, DaemonStatus};
11use crate::error::Result;
12use crate::request::{
13    AnyRequest, CascadeTargetState, Claimed, CreateFlexInput, CreateRealtimeInput, DaemonId,
14    ListRequestsFilter, PersistCompletedRealtimeInput, Request, RequestDetail, RequestId,
15    RequestListResult, RequestState, ServiceTierFilter,
16};
17use async_trait::async_trait;
18use chrono::{DateTime, Utc};
19use futures::stream::Stream;
20use std::collections::HashMap;
21use std::pin::Pin;
22
23/// Outcome of [`DaemonStorage::archive_batch`]. Skips are NORMAL sweeper
24/// flow, not errors: candidates are selected outside the move transaction,
25/// so by the time the batch row is locked the world may have moved on (a
26/// retry un-froze it, another sweeper archived it, a partition is missing).
27/// Callers log/alert per variant; only `SkippedNoPartition` warrants an
28/// alert (partitions-ahead runway failed), the rest are informational.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ArchiveOutcome {
31    /// Rows moved and location stamped; carries the row count moved.
32    Archived { rows: u64 },
33    /// Batch missing or soft-deleted (purge owns its rows, not the archive).
34    SkippedNotFound,
35    /// `location` was `'archive'` — already fully archived (idempotent
36    /// no-op). Split batches ARE valid candidates: re-archiving after a
37    /// retry resumes moves the remaining live rows into the same bucket.
38    SkippedNotLive,
39    /// Counts not frozen: the batch is active again (retry) or was never
40    /// finalized. It will re-candidate once frozen.
41    SkippedNotFrozen,
42    /// The weekly partition for this batch's bucket does not exist. The
43    /// batch stays live and fully served; fix partition creation and it
44    /// archives on a later pass. Alert-worthy.
45    SkippedNoPartition,
46    /// Some row is referenced by `response_steps`; the batch stays live
47    /// until the batchless store re-homes those rows.
48    SkippedResponseSteps,
49    /// The `retry_version` CAS on the final stamp failed — a retry raced
50    /// the move. Transaction rolled back; nothing moved.
51    SkippedRetryRaced,
52}
53
54/// Liveness state of a model on internal (self-hosted) infrastructure, as
55/// published by the controller into the `model_filters` append-only event log.
56///
57/// `model_filters` is an event log, not a current-state table: the CURRENT
58/// state of a model is the latest event for it. An `Absent` event is an
59/// explicit tombstone (the controller retracted the model); a model with no events at
60/// all is also treated as absent. The daemon treats absence as "claim now,
61/// route to OpenRouter".
62#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
63#[serde(rename_all = "lowercase")]
64pub enum ModelFilterState {
65    /// Internal infrastructure is serving this model now.
66    Live,
67    /// Internal infrastructure will serve this model soon; `expected_ready_at`
68    /// carries the ETA.
69    Coming,
70    /// The controller is draining this model: it has decided to scale the model to
71    /// zero, but the workers are still up finishing their in-flight requests (so it
72    /// stays listed in the gateway's `/v1/models`). Distinguished from `Absent` so
73    /// observers and the controller can tell "scaling down, still serving" from
74    /// "gone", but treated identically to `Coming`/`Absent` by the claim gate
75    /// (not-live → no new full-capacity claims).
76    Leaving,
77    /// Explicit tombstone: the controller is no longer deploying this model.
78    /// Appended (instead of deleting rows) to retract a model from the log. Treated
79    /// by the claim gate as NOT-LIVE — the same leaky-bucket + deadline-ramp path as
80    /// `Coming`/`Leaving`. NOTE: this is *not* the same as a model with **no events
81    /// at all**: the gate claims a no-events model at full capacity (it is unmanaged
82    /// — `mf.state IS NULL`), whereas an `Absent` model is explicitly held not-live.
83    Absent,
84}
85
86impl ModelFilterState {
87    /// The textual value stored in `model_filters.state`.
88    pub fn as_str(self) -> &'static str {
89        match self {
90            ModelFilterState::Live => "live",
91            ModelFilterState::Coming => "coming",
92            ModelFilterState::Leaving => "leaving",
93            ModelFilterState::Absent => "absent",
94        }
95    }
96
97    /// Parse the textual `model_filters.state` value.
98    pub fn parse_state(s: &str) -> Option<Self> {
99        match s {
100            "live" => Some(ModelFilterState::Live),
101            "coming" => Some(ModelFilterState::Coming),
102            "leaving" => Some(ModelFilterState::Leaving),
103            "absent" => Some(ModelFilterState::Absent),
104            _ => None,
105        }
106    }
107}
108
109/// A single `model_filters` event describing a model's internal-liveness
110/// transition.
111///
112/// `expected_ready_at` is only meaningful when `state == Coming`; for `Live`
113/// and `Absent` it should be `None`.
114#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
115pub struct ModelFilter {
116    /// Model name (NOT unique — many events per model in the log).
117    pub model: String,
118    /// Liveness state recorded by this event.
119    pub state: ModelFilterState,
120    /// ETA when `state == Coming`.
121    pub expected_ready_at: Option<chrono::DateTime<chrono::Utc>>,
122}
123
124/// Storage trait for persisting and querying requests.
125///
126/// This trait provides atomic operations for request lifecycle management.
127/// The type system ensures valid state transitions, so implementations don't
128/// need to validate them.
129#[async_trait]
130pub trait Storage: Send + Sync {
131    /// Create a new file with templates.
132    async fn create_file(
133        &self,
134        name: String,
135        description: Option<String>,
136        templates: Vec<RequestTemplateInput>,
137    ) -> Result<FileId>;
138
139    /// Create a new file with templates from a stream.
140    ///
141    /// The stream yields FileStreamItem which can be either:
142    /// - Metadata: File metadata (can appear anywhere, will be accumulated)
143    /// - Template: Request templates (processed as they arrive)
144    /// - Abort: Producer initiated rollback without treating it as a fusillade error
145    async fn create_file_stream<S: Stream<Item = FileStreamItem> + Send + Unpin>(
146        &self,
147        stream: S,
148    ) -> Result<FileStreamResult>;
149
150    /// Get a file by ID.
151    async fn get_file(&self, file_id: FileId) -> Result<File>;
152
153    /// Get a file by ID from the primary pool for read-after-write consistency.
154    ///
155    /// Use this immediately after creating or modifying a file to ensure you read
156    /// the latest committed data. For normal reads, use `get_file()` which may use
157    /// read replicas for better performance.
158    async fn get_file_from_primary_pool(&self, file_id: FileId) -> Result<File>;
159
160    /// List files with optional filtering.
161    async fn list_files(&self, filter: FileFilter) -> Result<Vec<File>>;
162
163    /// Get all content for a file.
164    async fn get_file_content(&self, file_id: FileId) -> Result<Vec<FileContentItem>>;
165
166    /// Stream file content.
167    /// Returns different content types based on the file's purpose:
168    /// - Regular files (purpose='batch'): RequestTemplateInput
169    /// - Batch output files (purpose='batch_output'): BatchOutputItem
170    /// - Batch error files (purpose='batch_error'): BatchErrorItem
171    ///
172    /// # Arguments
173    /// * `file_id` - The file ID to stream content from
174    /// * `offset` - Number of lines to skip (0-indexed)
175    /// * `search` - Optional filter by custom_id (case-insensitive substring match)
176    fn get_file_content_stream(
177        &self,
178        file_id: FileId,
179        offset: usize,
180        search: Option<String>,
181    ) -> Pin<Box<dyn Stream<Item = Result<FileContentItem>> + Send>>;
182
183    /// Get aggregated statistics for request templates grouped by model.
184    /// This is optimized for cost estimation - it only fetches model names and body sizes,
185    /// avoiding the overhead of streaming full template data.
186    ///
187    /// Returns a vector of per-model statistics including request count and total body bytes.
188    async fn get_file_template_stats(
189        &self,
190        file_id: FileId,
191    ) -> Result<Vec<crate::batch::ModelTemplateStats>>;
192
193    /// Delete a file (cascades to batches and executions).
194    async fn delete_file(&self, file_id: FileId) -> Result<()>;
195
196    /// Create a batch from a file's current templates.
197    ///
198    /// Convenience method that calls [`create_batch_record`] to insert the batch
199    /// row, then [`populate_batch`] to copy templates into requests. Returns the
200    /// fully-populated batch.
201    async fn create_batch(&self, input: BatchInput) -> Result<Batch>;
202
203    /// Create a batch record with virtual output/error files, without populating requests.
204    ///
205    /// Inserts the batch row and creates virtual output/error files so their IDs
206    /// are available in the API response immediately.
207    /// Returns a batch in `"validating"` status (`requests_started_at` is NULL).
208    /// `total_requests` will be set from `input.total_requests` if provided, or `0` otherwise.
209    /// Use [`populate_batch`] to copy templates into requests afterward.
210    async fn create_batch_record(&self, input: BatchInput) -> Result<Batch>;
211
212    /// Populate an existing batch with requests from its file's templates.
213    ///
214    /// Copies templates into the requests table and updates the batch with
215    /// total_requests and requests_started_at.
216    /// If the file has no templates, returns a [`ValidationError`](crate::FusilladeError::ValidationError)
217    /// and the caller is responsible for marking the batch as failed.
218    async fn populate_batch(&self, batch_id: BatchId, file_id: FileId) -> Result<()>;
219
220    /// Get a batch by ID.
221    ///
222    /// # Arguments
223    /// * `batch_id` - The batch ID to retrieve
224    async fn get_batch(&self, batch_id: BatchId) -> Result<Batch>;
225
226    /// Get batch status.
227    ///
228    /// # Arguments
229    /// * `batch_id` - The batch ID to retrieve status for
230    async fn get_batch_status(&self, batch_id: BatchId) -> Result<BatchStatus>;
231
232    /// List all batches for a file.
233    ///
234    /// # Arguments
235    /// * `file_id` - The file ID to list batches for
236    async fn list_file_batches(&self, file_id: FileId) -> Result<Vec<BatchStatus>>;
237
238    /// List batches with optional filtering and cursor-based pagination.
239    /// Returns batches sorted by created_at DESC (or active-first when `active_first` is set).
240    ///
241    /// See [`ListBatchesFilter`] for available filter options including:
242    /// - `created_by` - Filter by batch creator user ID
243    /// - `search` - Case-insensitive substring match against metadata JSON text,
244    ///   input filename, or batch ID
245    /// - `after` / `limit` - Cursor-based pagination (limit defaults to 100 if not set)
246    /// - `api_key_ids` - Filter by API key UUID(s) that created the batch (for per-member attribution)
247    /// - `status` - Filter by batch status. Supported values:
248    ///   `"in_progress"`, `"completed"`, `"failed"`, `"cancelled"`, `"expired"`.
249    ///   `"in_progress"` covers all non-terminal batches (including validating and finalizing
250    ///   sub-states). `"cancelled"` includes batches that are still cancelling.
251    ///   `"expired"` matches batches with SLA issues: in-progress past their deadline,
252    ///   or terminal batches that finished after their deadline.
253    ///   Unrecognized values return an error.
254    /// - `created_after` / `created_before` - Time range filter on batch creation timestamp
255    /// - `active_first` - When true, sorts active batches before terminal ones
256    ///   (completed, failed, cancelled, or cancelling), with each group sorted by
257    ///   created_at DESC. Cancelling batches are terminal because cancel_batch sets
258    ///   both timestamps atomically. Cursor pagination respects this ordering.
259    async fn list_batches(&self, filter: ListBatchesFilter) -> Result<Vec<Batch>>;
260
261    /// Get a batch by its output or error file ID.
262    async fn get_batch_by_output_file_id(
263        &self,
264        file_id: FileId,
265        file_type: OutputFileType,
266    ) -> Result<Option<Batch>>;
267
268    /// Get all requests for a batch.
269    async fn get_batch_requests(&self, batch_id: BatchId) -> Result<Vec<AnyRequest>>;
270
271    /// Stream batch results with merged input/output data.
272    ///
273    /// Returns a stream of BatchResultItem, each containing:
274    /// - The original input body from the request template
275    /// - The response body (for completed requests)
276    /// - The error message (for failed requests)
277    /// - The current status
278    ///
279    /// # Arguments
280    /// * `batch_id` - The batch to get results for
281    /// * `offset` - Number of results to skip (for pagination)
282    /// * `search` - Optional custom_id filter (case-insensitive substring match)
283    /// * `status` - Optional status filter (completed, failed, pending, in_progress)
284    fn get_batch_results_stream(
285        &self,
286        batch_id: BatchId,
287        offset: usize,
288        search: Option<String>,
289        status: Option<String>,
290    ) -> Pin<Box<dyn Stream<Item = Result<crate::batch::BatchResultItem>> + Send>>;
291
292    /// Given a list of batch IDs, return those that have been cancelled (cancelling_at IS NOT NULL).
293    async fn get_cancelled_batch_ids(&self, batch_ids: &[BatchId]) -> Result<Vec<BatchId>>;
294
295    /// Cancel all pending/in-progress requests for a batch.
296    async fn cancel_batch(&self, batch_id: BatchId) -> Result<()>;
297
298    /// Transition in-flight child requests (pending, claimed, processing) to a
299    /// terminal state after a batch has been cancelled, failed, or expired.
300    ///
301    /// Intended to be called asynchronously by the caller after the batch has
302    /// already reached a terminal state. Requests already in a terminal state
303    /// (completed, failed, canceled) are left untouched.
304    ///
305    /// Returns the number of rows updated.
306    async fn cascade_batch_state_to_requests(
307        &self,
308        batch_id: BatchId,
309        target_state: CascadeTargetState,
310    ) -> Result<u64>;
311
312    /// Soft-delete a batch by setting `deleted_at`.
313    ///
314    /// The batch row is marked deleted and (if not already terminal) cancelled
315    /// in the same UPDATE. Child requests and their templates are not touched
316    /// inline — they are hidden from active views via the `deleted_at` filter
317    /// and hard-deleted asynchronously by the orphan-purge daemon (see
318    /// `purge_orphaned_rows`) for right-to-erasure compliance.
319    async fn delete_batch(&self, batch_id: BatchId) -> Result<()>;
320
321    /// Hard-delete a single request row for right-to-erasure compliance.
322    ///
323    /// Removes the `requests` row and, if its template is batchless
324    /// (`file_id IS NULL`, dedicated 1:1 to this request), the
325    /// `request_templates` row as well — batchless templates carry the
326    /// prompt body, so leaving them defeats the erasure. File-backed
327    /// templates (shared across siblings in a batch) are not touched here;
328    /// the orphan-purge daemon cleans those up after the parent file is
329    /// soft-deleted.
330    ///
331    /// FK behavior on the deleted `requests` row:
332    /// * `response_steps.request_id` → `ON DELETE CASCADE`: removes only the
333    ///   step row(s) whose `request_id` matches this request. After migration
334    ///   `20260430000000` (response_steps re-anchoring), each step points at
335    ///   its own per-step sub-request fusillade row, so deleting one request
336    ///   only cascade-removes that step. Callers wanting to erase a whole
337    ///   multi-step response chain must walk the chain and call this method
338    ///   for each backing request.
339    /// * Self-references `escalated_from_request_id` / `superseded_by_request_id`
340    ///   → `ON DELETE SET NULL`, so sibling rows lose their pointer cleanly.
341    ///
342    /// In-flight handling: this is an unconditional hard delete. A daemon mid-
343    /// update on the row sees 0 rows affected on its next write; a streaming
344    /// proxy mid-INSERT of `response_steps` FK-violates (logged, not corrupted).
345    /// Both are acceptable for explicit user-initiated erasure.
346    ///
347    /// Unlike [`Self::delete_batch`] (soft-delete + async purge), this is
348    /// immediate because the caller has resolved a specific request to erase.
349    ///
350    /// Returns `RequestNotFound` if the request does not exist (or was already
351    /// deleted).
352    async fn delete_request(&self, request_id: RequestId) -> Result<()>;
353
354    /// Erase all of a creator's fusillade data, for right-to-erasure compliance.
355    ///
356    /// Processes up to `batch_size` rows per category per call, using
357    /// `FOR UPDATE SKIP LOCKED` so it is safe to run concurrently and under
358    /// load. Returns the count of *top-level* rows processed this call —
359    /// batchless requests deleted plus batches and files soft-deleted. It does
360    /// NOT include the batchless templates removed alongside those requests, nor
361    /// the batch/file child rows the purge daemon reaps later. It is purely a
362    /// loop-termination signal: callers should loop until it returns 0 to drain
363    /// everything. A `batch_size < 1` returns 0 (nothing to do). Idempotent.
364    ///
365    /// Three categories, keyed on `created_by` / `uploaded_by = creator_id`:
366    /// * **Batchless requests** (`batch_id IS NULL` — realtime/flex) are
367    ///   *hard*-deleted along with their batchless `request_templates` (which
368    ///   carry the prompt body). The orphan-purge daemon never reaches these
369    ///   because they have no soft-deleted parent batch, so they must be
370    ///   removed here or the erasure is incomplete.
371    /// * **Batches** are soft-deleted (cancelled if active) with `metadata`
372    ///   nullified (it can contain the user's email). Their child requests are
373    ///   hard-deleted afterwards by the orphan-purge daemon (`purge_orphaned_rows`).
374    /// * **Files** are soft-deleted; their `request_templates` are likewise
375    ///   reaped by the orphan-purge daemon once `files.deleted_at` is set.
376    ///
377    /// Note: completion is therefore eventually-consistent — when this returns
378    /// 0, all batches/files are soft-deleted and batchless rows are gone, but
379    /// batch/file child rows are erased on the next purge-daemon pass.
380    async fn bulk_delete_data(&self, creator_id: &str, batch_size: i64) -> Result<u64>;
381
382    /// Retry failed requests by resetting them to pending state.
383    ///
384    /// This resets the specified failed requests to pending state with retry_attempt = 0,
385    /// allowing them to be picked up by the daemon for reprocessing.
386    ///
387    /// # Arguments
388    /// * `ids` - Request IDs to retry
389    ///
390    /// # Returns
391    /// A vector of results, one for each request ID. Each result indicates whether
392    /// the retry succeeded or failed.
393    ///
394    /// # Errors
395    /// Individual retry results may fail if:
396    /// - Request ID doesn't exist
397    /// - Request is not in failed state
398    async fn retry_failed_requests(&self, ids: Vec<RequestId>) -> Result<Vec<Result<()>>>;
399
400    /// Retry a batch: re-pend its FAILED and CANCELED requests in a single
401    /// database operation (completed requests are never redone).
402    ///
403    /// Retry drives the batch back toward completion and overturns
404    /// cancellation — the batch's terminal timestamps, cancellation stamps,
405    /// and frozen counts are all reset, so cancel can serve as a pause that
406    /// retry resumes. (The name predates canceled-row support and is kept
407    /// for API stability.)
408    ///
409    /// This is much more efficient than `retry_failed_requests`, as it
410    /// performs bulk UPDATEs instead of loading requests into memory.
411    ///
412    /// # Returns
413    /// The number of requests that were retried (failed + canceled).
414    async fn retry_failed_requests_for_batch(&self, batch_id: BatchId) -> Result<u64>;
415
416    /// Get request counts grouped by model and deadline window.
417    ///
418    /// Each window is the half-open interval `[now + start_secs, now + end_secs)`
419    /// applied to each request's deadline. A request is counted in a
420    /// window if its deadline falls inside that range. Because the end is
421    /// exclusive, adjacent windows (e.g. `(_, Some(0), 3600)` and
422    /// `(_, Some(3600), 86400)`) never double-count a request sitting on the
423    /// boundary.
424    ///
425    /// A request's deadline is its batch's `expires_at`. Batchless rows
426    /// (flex/async responses, `batch_id IS NULL`) have no batch expiry, so their
427    /// deadline is synthesized as `created_at + W`, where `W` is mapped from the
428    /// row's `service_tier` via `DaemonConfig.service_tier_completion_windows_ms`
429    /// (`'flex'` → 1h by default, NULL/unmapped → `default_completion_window_ms`,
430    /// 24h) — the same window the claim path uses, so reported queue depth
431    /// matches what the daemon will claim.
432    ///
433    /// `start_secs` is optional. When `None`, the lower bound is unbounded
434    /// (the query matches every request with a deadline strictly before
435    /// `now + end_secs`, including overdue ones). Callers that want the
436    /// legacy "due within N, including overdue" semantics pass
437    /// `(label, None, N)`. Callers that specifically want the "future N
438    /// seconds" starting at `now` pass `(label, Some(0), N)`.
439    ///
440    /// - `windows`: Vec of `(label, start_secs, end_secs)`. When `start_secs`
441    ///   is `Some(s)`, `s` must be `<= end_secs`.
442    /// - `states`: request states to include (e.g. `["pending"]`, or
443    ///   `["pending","claimed","processing"]`).
444    /// - `model_filter`: optional model whitelist (empty = all).
445    /// - `service_tier_filter`: filter on `service_tier`. `Any` (default) applies
446    ///   no filter; `Include`/`Exclude` use `Option<String>` where `None`
447    ///   represents the batch tier (`service_tier IS NULL`).
448    /// - `priority_decay_window`: optional lookback in seconds. When set,
449    ///   recently completed `service_tier = 'flex'` requests are added to
450    ///   the `"1h"` bucket so realtime traffic can decay out of scheduling
451    ///   pressure after successful completion. No effect if the requested
452    ///   windows do not include a `"1h"` label.
453    /// - `strict`: bool. For critical/sensitive operations, set `true` to
454    ///   use the write pool and avoid read lags.
455    ///
456    /// Excludes:
457    /// - Requests without a template_id
458    /// - Requests in batches being cancelled
459    async fn get_pending_request_counts_by_model_and_window(
460        &self,
461        windows: &[(String, Option<i64>, i64)],
462        states: &[String],
463        model_filter: &[String],
464        service_tier_filter: &ServiceTierFilter,
465        priority_decay_window: Option<i64>,
466        strict: bool,
467    ) -> Result<HashMap<String, HashMap<String, i64>>>;
468
469    /// Sum the `total_requests` of a creditor's batches for a given completion
470    /// window created on or after `cutoff`.
471    ///
472    /// Used by the control layer to enforce the unverified upload-volume cap at
473    /// batch creation: an unverified creditor may submit at most
474    /// `unverified_requests_per_completion_hour * window_hours` requests within
475    /// a rolling window equal to the completion window. Served by
476    /// `idx_batches_completion_window (completion_window, created_by)`.
477    ///
478    /// - `owner`: the batch `created_by` — the creditor (organization id for org
479    ///   members, user id otherwise).
480    /// - `cutoff`: only batches with `created_at >= cutoff` are counted.
481    /// - `strict`: set `true` to read from the write pool and avoid read lag, so
482    ///   a just-created batch is reflected immediately (required for enforcement).
483    async fn sum_owner_batch_requests_in_window(
484        &self,
485        owner: &str,
486        completion_window: &str,
487        cutoff: DateTime<Utc>,
488        strict: bool,
489    ) -> Result<i64>;
490
491    /// Count a creditor's batchless `flex` requests created on or after `cutoff`.
492    ///
493    /// The flex counterpart of [`Storage::sum_owner_batch_requests_in_window`]:
494    /// flex requests are batchless (`batch_id IS NULL`, attribution via
495    /// `requests.created_by`) and always map to the 1h completion window. Served
496    /// by `idx_requests_user_created_sort (created_by, created_at DESC, id DESC,
497    /// service_tier) WHERE created_by IS NOT NULL`.
498    ///
499    /// - `owner`: the request `created_by` — the creditor id.
500    /// - `cutoff`: only requests with `created_at >= cutoff` are counted.
501    /// - `strict`: set `true` to read from the write pool and avoid read lag.
502    async fn count_owner_flex_requests_since(
503        &self,
504        owner: &str,
505        cutoff: DateTime<Utc>,
506        strict: bool,
507    ) -> Result<i64>;
508    ///
509    /// Cancel one or more individual pending or in-progress requests.
510    ///
511    /// Requests that have already completed or failed cannot be canceled.
512    /// This is a best-effort operation - some requests may have already been processed.
513    ///
514    /// Returns a result for each request ID indicating whether cancellation succeeded.
515    ///
516    /// # Errors
517    /// Individual cancellation results may fail if:
518    /// - Request ID doesn't exist
519    /// - Request is already in a terminal state (completed/failed)
520    #[tracing::instrument(skip(self, ids), fields(count = ids.len()))]
521    async fn cancel_requests(&self, ids: Vec<RequestId>) -> Result<Vec<Result<()>>> {
522        tracing::debug!(count = ids.len(), "Cancelling requests");
523
524        let mut results = Vec::new();
525
526        for id in ids {
527            // Get the request from storage
528            let get_results = self.get_requests(vec![id]).await?;
529            let request_result = get_results.into_iter().next().unwrap();
530
531            let result = match request_result {
532                Ok(any_request) => match any_request {
533                    AnyRequest::Pending(req) => {
534                        req.cancel(self).await?;
535                        Ok(())
536                    }
537                    AnyRequest::Claimed(req) => {
538                        req.cancel(self).await?;
539                        Ok(())
540                    }
541                    AnyRequest::Processing(req) => {
542                        req.cancel(self).await?;
543                        Ok(())
544                    }
545                    AnyRequest::Completed(_) | AnyRequest::Failed(_) | AnyRequest::Canceled(_) => {
546                        Err(crate::error::FusilladeError::InvalidState(
547                            id,
548                            "terminal state".to_string(),
549                            "cancellable state".to_string(),
550                        ))
551                    }
552                },
553                Err(e) => Err(e),
554            };
555
556            results.push(result);
557        }
558
559        Ok(results)
560    }
561
562    /// Get in progress requests by IDs.
563    async fn get_requests(&self, ids: Vec<RequestId>) -> Result<Vec<Result<AnyRequest>>>;
564
565    // These methods are used by the DaemonExecutor for pulling requests, and then persisting their
566    // states as they iterate through them
567
568    /// Atomically claim pending batchless requests for processing.
569    ///
570    /// `available_capacity` maps model names to the number of permits the daemon
571    /// is currently holding for that model. Only models present in this map will
572    /// be claimed — this is the authoritative set of models to process.
573    ///
574    /// `user_active_counts` maps user identifiers to their current number of
575    /// in-flight requests across all models. Used to prioritise users with fewer
576    /// active requests for per-user fair scheduling. Pass an empty map to disable
577    /// user-level prioritisation (falls back to deadline-only ordering).
578    ///
579    /// Implementations may blend user-fairness with SLA urgency (batch deadline
580    /// proximity) via `DaemonConfig::urgency_weight`. See the PostgreSQL
581    /// implementation for the composite scoring formula.
582    ///
583    /// The claim gate consults the latest `model_filters` event per model:
584    /// `state = 'live'` **or no events at all** ⇒ claim at full capacity (a
585    /// model with no events is unmanaged by the controller, so there is no
586    /// internal capacity to wait for — it flows straight through to OpenRouter).
587    /// An EXPLICIT not-live event (`coming`/`absent`) ⇒ the request is either
588    /// claimed at full capacity (→ OpenRouter) when within `ramp(W)` of its
589    /// completion-window deadline, or otherwise released only via the
590    /// per-`(user, window-class, model)` leaky bucket. So with an empty `model_filters`
591    /// table the gate is a no-op (everything claims at full capacity) — it only
592    /// engages once the controller starts writing not-live events.
593    ///
594    /// `leak_cooldown` is the set of `(user, window-class, model)` triples whose
595    /// leaky bucket has no token this cycle (the daemon stamped `next_token_at`
596    /// in the future after a recent leak). Source B skips these triples, claiming
597    /// ≤ 1 per `(user, window-class, model)` not in cooldown. Pass an empty set
598    /// to allow every bucket its first token. Claimed rows carry a `leaked` flag
599    /// (via the returned request) so the daemon knows which buckets to stamp.
600    async fn claim_batchless_requests(
601        &self,
602        limit: usize,
603        daemon_id: DaemonId,
604        available_capacity: &std::collections::HashMap<String, usize>,
605        user_active_counts: &std::collections::HashMap<String, usize>,
606        leak_cooldown: &std::collections::HashSet<(String, String, String)>,
607    ) -> Result<Vec<Request<Claimed>>> {
608        self.claim_requests(
609            limit,
610            daemon_id,
611            available_capacity,
612            user_active_counts,
613            leak_cooldown,
614        )
615        .await
616    }
617
618    /// Compatibility method for callers and storage implementations that have
619    /// not yet moved to the explicit request daemon API.
620    ///
621    /// New daemon code should call [`Storage::claim_batchless_requests`] or
622    /// [`Storage::claim_batch_requests`] directly. This method is kept
623    /// as a batchless-only alias so the request and batch policies cannot be
624    /// accidentally recombined.
625    async fn claim_requests(
626        &self,
627        limit: usize,
628        daemon_id: DaemonId,
629        available_capacity: &std::collections::HashMap<String, usize>,
630        user_active_counts: &std::collections::HashMap<String, usize>,
631        leak_cooldown: &std::collections::HashSet<(String, String, String)>,
632    ) -> Result<Vec<Request<Claimed>>>;
633
634    /// Atomically claim pending requests that belong to live-model batches.
635    ///
636    /// The batch daemon owns this policy. Implementations should select
637    /// candidate batches before probing request rows, limit selected batches by
638    /// `batch_limit`, and gate on model liveness: models whose latest
639    /// `model_filters` event is `live` are always eligible; models with **no**
640    /// filter event (external / always-on providers that scouter does not
641    /// manage) are eligible unless `DaemonConfig::batch_claim_require_live` is
642    /// set; models whose latest event is `coming`/`absent` are eligible only
643    /// once the batch is within the deadline ramp (`claim_ramp_exponent`) —
644    /// the SLA escape hatch to fallback providers. No leaky-bucket trickle
645    /// applies to batched rows.
646    async fn claim_batch_requests(
647        &self,
648        limit: usize,
649        batch_limit: usize,
650        daemon_id: DaemonId,
651        available_capacity: &std::collections::HashMap<String, usize>,
652        user_active_counts: &std::collections::HashMap<String, usize>,
653    ) -> Result<Vec<Request<Claimed>>> {
654        let _ = (
655            limit,
656            batch_limit,
657            daemon_id,
658            available_capacity,
659            user_active_counts,
660        );
661        // Fail loud rather than silently claiming nothing: a backend that
662        // doesn't override this would otherwise run a batch daemon that never
663        // claims a row — invisible in production until batches stall.
664        Err(crate::error::FusilladeError::Other(anyhow::anyhow!(
665            "claim_batch_requests is not implemented for this storage backend \
666             (override it, or return false from supports_batch_claims to run \
667             the daemon request-only)"
668        )))
669    }
670
671    /// Whether this backend implements [`Storage::claim_batch_requests`].
672    ///
673    /// The daemon only spawns its batch claim loop when this returns true.
674    /// Defaults to true so a backend that forgets to override BOTH methods
675    /// fails loudly (the default `claim_batch_requests` errors) instead of
676    /// silently never claiming batched rows. A deliberately request-only
677    /// backend should override this to return false.
678    fn supports_batch_claims(&self) -> bool {
679        true
680    }
681
682    /// Append a single event to the `model_filters` log. Used by the controller
683    /// when a model's internal liveness CHANGES (live / coming / absent).
684    ///
685    /// The gate reads only `state` (live ⇒ claim full; coming/absent ⇒ not-live).
686    /// `expected_ready_at` is retained on the type/column for the controller's own
687    /// use but is **not read by the claim gate** — callers may leave it `None`.
688    ///
689    /// This is append-only: there is no delete and no upsert. Retraction is
690    /// appending an `Absent` event. Appending **only on change** (so the log
691    /// stays a transition log rather than a poll log) is the caller's
692    /// responsibility — this function always inserts a row.
693    async fn append_model_filter_event(&self, entry: &ModelFilter) -> Result<()>;
694
695    /// Append a batch of events to the `model_filters` log (one row each, in
696    /// order). Convenience for the controller publishing several transitions in
697    /// one sync. Same append-only / append-on-change semantics as
698    /// [`Storage::append_model_filter_event`].
699    async fn append_model_filter_events(&self, entries: &[ModelFilter]) -> Result<()>;
700
701    /// List the CURRENT state of every model (the latest event per model),
702    /// excluding models whose latest event is an `Absent` tombstone
703    /// (observability / tests).
704    async fn list_model_filters(&self) -> Result<Vec<ModelFilter>>;
705
706    /// The CURRENT state of every model **and when that state began**: the latest
707    /// event per model as `(state, since)`, where `since` is that event's
708    /// `created_at`. Includes `Absent` (a model's latest event may be a tombstone);
709    /// the caller decides what to do with each state.
710    ///
711    /// This is the controller's read for time-based decisions off the log — a
712    /// `Live` model's `since` is when it went live (minimum-lifetime / anti-thrash),
713    /// a `Coming` model's `since` is when it started launching (a stuck-`coming`
714    /// watchdog). The timestamp comes from the persisted log, not in-memory state,
715    /// so it survives controller restarts.
716    async fn current_filter_states(
717        &self,
718    ) -> Result<std::collections::HashMap<String, (ModelFilterState, chrono::DateTime<chrono::Utc>)>>;
719
720    /// Update an existing request's state in storage.
721    ///
722    /// Returns `Some(request_id)` if a racing pair was superseded (for cancellation purposes).
723    async fn persist<T: RequestState + Clone>(
724        &self,
725        request: &Request<T>,
726    ) -> Result<Option<RequestId>>
727    where
728        AnyRequest: From<Request<T>>;
729
730    /// Reschedule an in-flight request back to `pending` for an automatic retry,
731    /// fenced on the worker that currently owns it.
732    ///
733    /// This is the daemon's per-attempt retry path. Unlike [`Storage::persist`]
734    /// (which matches on `id` only, so the manual retry path can intentionally
735    /// resurrect a `failed` row), this transition is guarded by
736    /// `state = 'processing' AND daemon_id = <owner>`: it applies ONLY if the row
737    /// is still the in-flight claim held by `daemon_id`.
738    ///
739    /// The guard prevents a finalize-then-resurrect race: if another writer (a
740    /// zombie/duplicate worker, or a stale-claim reclaim) has already moved the
741    /// row to a terminal state — and a finalizer has sealed the parent batch as a
742    /// result — a late retry from this worker must NOT flip it back to `pending`,
743    /// orphaning it under a completed batch.
744    ///
745    /// Returns `true` if the row was rescheduled, `false` if the worker no longer
746    /// owns it (lost the race). A `false` result is normal under contention and
747    /// should be logged, not treated as an error.
748    async fn reschedule_for_retry(
749        &self,
750        request_id: RequestId,
751        owner: DaemonId,
752        retry_attempt: u32,
753        not_before: Option<chrono::DateTime<chrono::Utc>>,
754    ) -> Result<bool>;
755
756    /// List individual requests across batches with filtering and pagination.
757    ///
758    /// Supports filtering by creator, completion window, status, model(s),
759    /// date range, and active-first sorting. Uses offset-based pagination.
760    ///
761    /// Note: Token and cost metrics are NOT included — callers should join
762    /// against their own analytics tables for that data.
763    async fn list_requests(&self, filter: ListRequestsFilter) -> Result<RequestListResult>;
764
765    /// Get a single request by ID with full detail (body, response, error).
766    async fn get_request_detail(&self, request_id: RequestId) -> Result<RequestDetail>;
767
768    /// Create a realtime response that the proxy is already handling.
769    ///
770    /// Inserts a request template (no parent file) and a request row with
771    /// `batch_id = NULL` in `processing` state. The proxy completes/fails
772    /// the row directly via `complete_request` / `fail_request`; the daemon
773    /// never claims it.
774    async fn create_realtime(&self, input: CreateRealtimeInput) -> Result<RequestId>;
775
776    /// Create a flex (async) response that the daemon will process.
777    ///
778    /// Inserts a request template (no parent file) and a request row with
779    /// `batch_id = NULL` in `pending` state. The daemon claims and processes
780    /// it via the standard flex pipeline.
781    async fn create_flex(&self, input: CreateFlexInput) -> Result<RequestId>;
782
783    /// Complete a processing request with the response body.
784    ///
785    /// Transitions the request from "processing" to "completed" and stores the
786    /// response body and HTTP status code.
787    async fn complete_request(
788        &self,
789        request_id: RequestId,
790        response_body: &str,
791        status_code: u16,
792    ) -> Result<()>;
793
794    /// Fail a processing request with an error message and HTTP status code.
795    ///
796    /// Transitions the request from "processing" to "failed" and stores the
797    /// error as a `NonRetriableHttpStatus` JSON object with the given status code.
798    async fn fail_request(
799        &self,
800        request_id: RequestId,
801        error: &str,
802        status_code: u16,
803    ) -> Result<()>;
804
805    /// Persist a batch of already-completed realtime responses in one transaction.
806    ///
807    /// Designed for the dwctl responses writer: dwctl proxies a realtime
808    /// request, captures the upstream response, and flushes a buffer of
809    /// completed records here. Two cases are handled together:
810    ///
811    ///   * Background realtime: a `processing` row exists (created inline by
812    ///     `create_realtime` before the 202 response). UPDATEd to `completed`.
813    ///   * Non-background realtime: no row exists. INSERTed (template + request)
814    ///     directly in `completed` state.
815    ///
816    /// Rows already in a terminal state (rare: duplicate enqueues, late
817    /// completions for flex slip-through) are left alone via `ON CONFLICT`.
818    ///
819    /// All work runs in a single transaction so commit overhead amortises
820    /// across the batch. An empty input is a no-op.
821    async fn persist_completed_realtime_batch(
822        &self,
823        records: &[PersistCompletedRealtimeInput],
824    ) -> Result<()>;
825}
826
827/// Daemon lifecycle persistence.
828///
829/// This trait provides storage operations for tracking daemon state,
830/// including registration, heartbeat updates, and graceful shutdown.
831#[async_trait]
832pub trait DaemonStorage: Send + Sync {
833    /// Persist daemon state update.
834    ///
835    /// This is a low-level method used by state transition methods.
836    /// The type parameter `T` ensures type-safe state transitions.
837    async fn persist_daemon<T: DaemonState + Clone>(&self, record: &DaemonRecord<T>) -> Result<()>
838    where
839        AnyDaemonRecord: From<DaemonRecord<T>>;
840
841    /// Get daemon by ID.
842    ///
843    /// Returns an `AnyDaemonRecord` which can hold the daemon in any state.
844    async fn get_daemon(&self, daemon_id: DaemonId) -> Result<AnyDaemonRecord>;
845
846    /// List all daemons with optional status filter.
847    ///
848    /// If `status_filter` is `None`, returns all daemons regardless of status.
849    /// Otherwise, returns only daemons matching the specified status.
850    async fn list_daemons(
851        &self,
852        status_filter: Option<DaemonStatus>,
853    ) -> Result<Vec<AnyDaemonRecord>>;
854
855    /// Purge orphaned request_templates and requests whose parent (file or batch)
856    /// has been soft-deleted or whose FK is NULL.
857    ///
858    /// Deletes at most `batch_size` rows from each table per call.
859    /// Returns total rows deleted across both tables. Called periodically by
860    /// the daemon purge task for right-to-erasure compliance.
861    async fn purge_orphaned_rows(&self, batch_size: i64) -> Result<u64>;
862
863    /// Move one terminal batch's request rows from `requests` (live) into
864    /// `batch_requests_archive` in a single bounded transaction (batches are
865    /// capped at 50k rows), stamping `batches.location = 'archive'` and
866    /// `batches.archive_bucket`.
867    ///
868    /// Preconditions are checked inside the transaction; violations return a
869    /// `Skipped*` outcome rather than an error — the sweeper treats skips as
870    /// normal flow:
871    /// - batch exists, not soft-deleted, `location = 'live'`, counts frozen
872    ///   (`counts_frozen_at` set). **Only frozen batches move**: freezing
873    ///   guarantees rows are settled and the counters are the durable
874    ///   record, and it carries Phase 2's `retry_version` protection — any
875    ///   retry un-freezes and bumps the version first.
876    /// - the weekly archive partition for the batch's bucket exists;
877    ///   otherwise the batch simply stays live (fully served, exactly as
878    ///   today) and the caller alerts — graceful degradation, no failure.
879    /// - no row is referenced by `response_steps` (those stay live until the
880    ///   batchless store gives them a home).
881    ///
882    /// Transaction invariants (fusillade-requests-phase3-plan.md §1):
883    /// - forward move is `INSERT ... SELECT r.*, $bucket` with
884    ///   `ON CONFLICT DO NOTHING` — idempotent under crash-resume replay.
885    /// - the DELETE removes only rows verifiably present in the archive and
886    ///   the transaction aborts if any row would be left behind: a row lives
887    ///   in exactly one table, always.
888    /// - the location stamp re-checks `retry_version` (CAS) even though the
889    ///   batch-row lock makes a race impossible on this path — belt and
890    ///   braces against future callers taking weaker locks.
891    async fn archive_batch(&self, batch_id: BatchId) -> Result<ArchiveOutcome>;
892
893    /// List batches eligible for archiving (`location = 'live'`, counts
894    /// frozen, not soft-deleted). Both production movers — the steady-state
895    /// sweeper AND the historical backfill — pass `oldest_first = true`: in
896    /// steady state the sweeper drains its whole candidate set every few
897    /// ticks so order is cosmetic, and under any backlog the
898    /// least-recently-created batches are the least likely to ever be read
899    /// again, so early issues have minimal blast radius. `false`
900    /// (newest-first) exists as an ordering choice for other callers.
901    ///
902    /// `cancel_grace_secs` is the cancellation grace window: a batch is NOT
903    /// a candidate while it has canceled rows that were IN FLIGHT at cancel
904    /// (the cascade leaves `claimed_at` set on them; pending-canceled rows
905    /// have it NULL) with `canceled_at` younger than the grace. Cancellation
906    /// is async and best-effort, and billed in-flight results SUPERSEDE the
907    /// cancel (see the persist() transition matrix, fusillade 21.2.1) — the
908    /// supersede lands on the LIVE row, so the rows must not move until all
909    /// in-flight work has had time to declare itself. Default the grace to
910    /// the processing timeout (~10 min): only cancelled batches archive
911    /// later, fully served from live meanwhile; normal batches have no such
912    /// rows and are unaffected. A frozen batch can never GAIN such a row
913    /// (the cascade only touches non-terminal rows and freezing requires
914    /// all-terminal), so this selection-time check cannot be raced by the
915    /// move itself.
916    /// `min_frozen_age_secs` is the post-freeze dwell: 0 means frozen
917    /// batches are candidates immediately (the default — reads are mid-move
918    /// safe by construction and the sweep cadence provides organic dwell).
919    async fn list_archivable_batches(
920        &self,
921        limit: i64,
922        oldest_first: bool,
923        cancel_grace_secs: f64,
924        min_frozen_age_secs: f64,
925    ) -> Result<Vec<BatchId>>;
926
927    /// Count of batches currently eligible for archiving (same predicate as
928    /// [`Self::list_archivable_batches`] minus the ordering/limit) — the
929    /// sweep-backlog gauge. Index-only on the partial sweep index.
930    async fn count_archivable_batches(&self, cancel_grace_secs: f64) -> Result<i64>;
931
932    /// Ensure weekly archive partitions exist through now + `weeks_ahead`
933    /// (create -> bounds CHECK -> attach; advisory-locked; idempotent).
934    /// Returns `(created, ahead)`: partitions created this call, and how
935    /// many future weeks (including the current one) now have partitions —
936    /// the `fusillade_archive_partitions_ahead` gauge, alert-worthy when it
937    /// shrinks below 2.
938    async fn ensure_archive_partitions(&self, weeks_ahead: i32) -> Result<(i64, i64)>;
939
940    /// Purge old `model_filters` events, ALWAYS retaining, per model, the most
941    /// recent `keep_per_model` events (so the current-state lookup and a short
942    /// history window survive) AND every event newer than `retention_secs`
943    /// regardless of count.
944    ///
945    /// Deletes at most `batch_size` rows per call. Returns rows deleted.
946    /// Called periodically by the daemon purge task to bound the append-only
947    /// log. `keep_per_model >= 1` guarantees the latest event per model is
948    /// never purged, so the claim gate never loses a model's current state.
949    async fn purge_model_filter_events(
950        &self,
951        batch_size: i64,
952        keep_per_model: i64,
953        retention_secs: f64,
954    ) -> Result<u64>;
955}