stateknot-runtime 0.1.0-alpha.1

Executable registries and durable graph driving for StateKnot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Bounded tenant-scoped durable scheduler worker.

use std::{sync::Arc, time::Duration};

use stateknot_core::{AttemptId, BoxFuture, CancellationSignal, RunId, TenantId};
use stateknot_store_postgres::{
    PostgresStore, RunnableRunPageCursor, RunnableRunPageSize, StoreError,
};
use thiserror::Error;

use crate::{
    AgentLoopError, AgentLoopResult, DurableAgentLoop, DurableAgentLoopBuildError,
    DurableGraphDriverOptions, DurableGraphLifecycleOptions, ExecutableGraphRegistry,
    GraphLifecycleEvidenceProvider,
};

const MAX_CLAIM_RETRY_DELAY: Duration = Duration::from_secs(1);

/// Bounded scan and claim policy for one tenant scheduler worker.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DurableTenantSchedulerOptions {
    page_size: RunnableRunPageSize,
    maximum_pages_per_tick: u8,
    maximum_claim_attempts: u8,
    claim_retry_initial_delay: Duration,
}

impl DurableTenantSchedulerOptions {
    /// Absolute number of stable-snapshot pages one tick may inspect.
    pub const HARD_MAXIMUM_PAGES_PER_TICK: u8 = 64;
    /// Absolute number of identical lease-claim attempts.
    pub const HARD_MAXIMUM_CLAIM_ATTEMPTS: u8 = 10;

    /// Constructs an explicit resource and retry policy.
    ///
    /// # Errors
    ///
    /// Rejects zero/excessive page or claim counts, and a zero or
    /// greater-than-one-second initial retry delay.
    pub fn new(
        page_size: RunnableRunPageSize,
        maximum_pages_per_tick: u8,
        maximum_claim_attempts: u8,
        claim_retry_initial_delay: Duration,
    ) -> Result<Self, DurableTenantSchedulerOptionsError> {
        if maximum_pages_per_tick == 0 || maximum_pages_per_tick > Self::HARD_MAXIMUM_PAGES_PER_TICK
        {
            return Err(DurableTenantSchedulerOptionsError::InvalidPageCount);
        }
        if maximum_claim_attempts == 0 || maximum_claim_attempts > Self::HARD_MAXIMUM_CLAIM_ATTEMPTS
        {
            return Err(DurableTenantSchedulerOptionsError::InvalidClaimAttempts);
        }
        if claim_retry_initial_delay.is_zero() || claim_retry_initial_delay > MAX_CLAIM_RETRY_DELAY
        {
            return Err(DurableTenantSchedulerOptionsError::InvalidClaimRetryDelay);
        }
        Ok(Self {
            page_size,
            maximum_pages_per_tick,
            maximum_claim_attempts,
            claim_retry_initial_delay,
        })
    }

    /// Returns the bounded decoded candidate page size.
    #[must_use]
    pub const fn page_size(self) -> RunnableRunPageSize {
        self.page_size
    }

    /// Returns the maximum fixed-cutoff pages inspected per tick.
    #[must_use]
    pub const fn maximum_pages_per_tick(self) -> u8 {
        self.maximum_pages_per_tick
    }

    /// Returns the maximum identical attempts for one claim.
    #[must_use]
    pub const fn maximum_claim_attempts(self) -> u8 {
        self.maximum_claim_attempts
    }

    /// Returns the first exponential claim retry delay.
    #[must_use]
    pub const fn claim_retry_initial_delay(self) -> Duration {
        self.claim_retry_initial_delay
    }
}

impl Default for DurableTenantSchedulerOptions {
    fn default() -> Self {
        Self {
            page_size: RunnableRunPageSize::new(RunnableRunPageSize::MAX)
                .expect("provider maximum is a valid page size"),
            maximum_pages_per_tick: 4,
            maximum_claim_attempts: 3,
            claim_retry_initial_delay: Duration::from_millis(25),
        }
    }
}

/// Invalid tenant scheduler policy.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableTenantSchedulerOptionsError {
    /// The page-chain bound was zero or above the hard ceiling.
    #[error("tenant scheduler page count is invalid")]
    InvalidPageCount,
    /// Claim attempts were zero or above the hard ceiling.
    #[error("tenant scheduler claim attempt count is invalid")]
    InvalidClaimAttempts,
    /// Initial claim backoff was zero or above one second.
    #[error("tenant scheduler claim retry delay is invalid")]
    InvalidClaimRetryDelay,
}

/// Bounded observations made while selecting one run.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TenantSchedulerReport {
    pages_scanned: u8,
    candidates_scanned: u16,
    contention_skips: u16,
    claim_retries: u16,
}

impl TenantSchedulerReport {
    /// Returns stable-snapshot pages loaded in this tick.
    #[must_use]
    pub const fn pages_scanned(self) -> u8 {
        self.pages_scanned
    }

    /// Returns candidates inspected in durable queue order.
    #[must_use]
    pub const fn candidates_scanned(self) -> u16 {
        self.candidates_scanned
    }

    /// Returns candidates that changed or were owned before claim.
    #[must_use]
    pub const fn contention_skips(self) -> u16 {
        self.contention_skips
    }

    /// Returns transient claim retries using the same attempt identity.
    #[must_use]
    pub const fn claim_retries(self) -> u16 {
        self.claim_retries
    }
}

/// Closed result of one tenant scheduler tick.
#[derive(Debug)]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum TenantSchedulerOutcome {
    /// One claimed run reached its next agent-loop boundary.
    Executed {
        /// Exact selected run.
        run_id: RunId,
        /// Complete bounded loop result.
        result: AgentLoopResult,
    },
    /// One claimed run failed safely; the loop attempted lease cleanup.
    ExecutionFailed {
        /// Exact selected run.
        run_id: RunId,
        /// Payload-redacted run-local failure.
        error: AgentLoopError,
    },
    /// No claimable run existed in the complete stable snapshot.
    Idle,
    /// The configured scan ceiling stopped before the snapshot ended.
    ScanLimitReached,
    /// Cooperative shutdown won before a claim.
    Cancelled,
}

/// Scheduler outcome plus bounded selection counters.
#[derive(Debug)]
pub struct TenantSchedulerTick {
    outcome: TenantSchedulerOutcome,
    report: TenantSchedulerReport,
}

impl TenantSchedulerTick {
    const fn new(outcome: TenantSchedulerOutcome, report: TenantSchedulerReport) -> Self {
        Self { outcome, report }
    }

    /// Returns the tick's closed scheduling result.
    #[must_use]
    pub const fn outcome(&self) -> &TenantSchedulerOutcome {
        &self.outcome
    }

    /// Returns bounded scan and contention counters.
    #[must_use]
    pub const fn report(&self) -> TenantSchedulerReport {
        self.report
    }

    /// Consumes the tick into its outcome and report.
    #[must_use]
    pub fn into_parts(self) -> (TenantSchedulerOutcome, TenantSchedulerReport) {
        (self.outcome, self.report)
    }
}

/// One tenant-isolated durable scheduler worker.
///
/// A tick always scans the provider's `(available_at, run_id)` order under one
/// fixed database cutoff and claims at most one run. Deployments obtain bounded
/// concurrency by running a configured number of workers; database fencing
/// resolves races. Cross-tenant selection intentionally belongs to a separate
/// fairness layer so storage credentials and queue scans never cross tenant
/// scope implicitly.
#[derive(Clone)]
pub struct DurableTenantScheduler {
    store: PostgresStore,
    agent_loop: DurableAgentLoop,
    options: DurableTenantSchedulerOptions,
}

impl DurableTenantScheduler {
    /// Returns shared node-future completion accounting for this scheduler and clones.
    pub fn execution_activity(&self) -> crate::GraphExecutionActivity {
        self.agent_loop.execution_activity()
    }

    /// Builds a tenant worker and its internally consistent durable loop.
    ///
    /// # Errors
    ///
    /// Returns an exact driver/lifecycle startup binding failure.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        store: PostgresStore,
        registry: ExecutableGraphRegistry,
        evidence: Arc<dyn GraphLifecycleEvidenceProvider>,
        driver_options: DurableGraphDriverOptions,
        lifecycle_options: DurableGraphLifecycleOptions,
        options: DurableTenantSchedulerOptions,
    ) -> Result<Self, DurableTenantSchedulerBuildError> {
        let agent_loop = DurableAgentLoop::new(
            store.clone(),
            registry,
            evidence,
            driver_options,
            lifecycle_options,
        )?;
        Ok(Self {
            store,
            agent_loop,
            options,
        })
    }

    /// Returns the immutable tenant scan and claim policy.
    #[must_use]
    pub const fn options(&self) -> DurableTenantSchedulerOptions {
        self.options
    }

    /// Selects, claims, and executes at most one run for the supplied tenant.
    ///
    /// A stable attempt ID is allocated once per candidate and retained across
    /// transient database retries, preserving lost-acknowledgement convergence.
    /// Lease contention and candidates that became unavailable are normal scan
    /// skips, not scheduler failures.
    pub fn tick(
        &self,
        tenant_id: TenantId,
        shutdown: CancellationSignal,
    ) -> BoxFuture<'_, Result<TenantSchedulerTick, TenantSchedulerError>> {
        Box::pin(self.tick_inner(tenant_id, shutdown))
    }

    async fn tick_inner(
        &self,
        tenant_id: TenantId,
        shutdown: CancellationSignal,
    ) -> Result<TenantSchedulerTick, TenantSchedulerError> {
        let mut cursor: Option<RunnableRunPageCursor> = None;
        let mut report = TenantSchedulerReport::default();
        loop {
            if shutdown.is_cancelled() {
                return Ok(TenantSchedulerTick::new(
                    TenantSchedulerOutcome::Cancelled,
                    report,
                ));
            }
            let page = self
                .store
                .load_runnable_run_page(&tenant_id, cursor.as_ref(), self.options.page_size)
                .await?;
            report.pages_scanned = report.pages_scanned.saturating_add(1);
            for candidate in page.records() {
                if shutdown.is_cancelled() {
                    return Ok(TenantSchedulerTick::new(
                        TenantSchedulerOutcome::Cancelled,
                        report,
                    ));
                }
                report.candidates_scanned = report.candidates_scanned.saturating_add(1);
                let run_id = candidate.run().lifecycle().provenance().run_id();
                let attempt_id = AttemptId::generate();
                let Some(lease) = self
                    .claim_with_retry(&tenant_id, run_id, attempt_id, &mut report)
                    .await?
                else {
                    continue;
                };
                let outcome = match self
                    .agent_loop
                    .run(lease.fence().clone(), shutdown.clone())
                    .await
                {
                    Ok(result) => TenantSchedulerOutcome::Executed { run_id, result },
                    Err(error) => TenantSchedulerOutcome::ExecutionFailed { run_id, error },
                };
                return Ok(TenantSchedulerTick::new(outcome, report));
            }

            if !page.has_more() {
                return Ok(TenantSchedulerTick::new(
                    TenantSchedulerOutcome::Idle,
                    report,
                ));
            }
            if report.pages_scanned == self.options.maximum_pages_per_tick {
                return Ok(TenantSchedulerTick::new(
                    TenantSchedulerOutcome::ScanLimitReached,
                    report,
                ));
            }
            cursor = page.next_cursor();
            if cursor.is_none() {
                return Err(TenantSchedulerError::RuntimeInvariant);
            }
        }
    }

    async fn claim_with_retry(
        &self,
        tenant_id: &TenantId,
        run_id: RunId,
        attempt_id: AttemptId,
        report: &mut TenantSchedulerReport,
    ) -> Result<Option<stateknot_core::RunLease>, TenantSchedulerError> {
        let mut attempt = 1_u8;
        loop {
            match self.store.claim_lease(tenant_id, run_id, attempt_id).await {
                Ok(outcome) => return Ok(Some(outcome.lease().clone())),
                Err(error) if claim_contention(&error) => {
                    report.contention_skips = report.contention_skips.saturating_add(1);
                    return Ok(None);
                }
                Err(error)
                    if attempt < self.options.maximum_claim_attempts && error.is_retryable() =>
                {
                    report.claim_retries = report.claim_retries.saturating_add(1);
                    self.claim_backoff(attempt).await;
                    attempt = attempt.saturating_add(1);
                }
                Err(error) => return Err(error.into()),
            }
        }
    }

    async fn claim_backoff(&self, attempt: u8) {
        let multiplier = 1_u32
            .checked_shl(u32::from(attempt.saturating_sub(1)))
            .unwrap_or(u32::MAX);
        let delay = self
            .options
            .claim_retry_initial_delay
            .checked_mul(multiplier)
            .unwrap_or(MAX_CLAIM_RETRY_DELAY)
            .min(MAX_CLAIM_RETRY_DELAY);
        tokio::time::sleep(delay).await;
    }
}

fn claim_contention(error: &StoreError) -> bool {
    matches!(
        error,
        StoreError::LeaseHeld
            | StoreError::RunNotRunnable
            | StoreError::RunNotYetAvailable
            | StoreError::RunQuarantined
            | StoreError::RunNotFound
    )
}

/// Startup failure while building a tenant scheduler worker.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableTenantSchedulerBuildError {
    /// The internally consistent durable agent loop could not be built.
    #[error(transparent)]
    AgentLoop(#[from] DurableAgentLoopBuildError),
}

/// Payload-redacted scheduler infrastructure failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TenantSchedulerError {
    /// `PostgreSQL` rejected or could not complete a scan or claim.
    #[error(transparent)]
    Store {
        /// Exact payload-redacted provider failure.
        source: Box<StoreError>,
    },
    /// A provider page claimed continuation without a usable cursor.
    #[error("tenant scheduler stable page chain is internally inconsistent")]
    RuntimeInvariant,
}

impl From<StoreError> for TenantSchedulerError {
    fn from(source: StoreError) -> Self {
        Self::Store {
            source: Box::new(source),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn options_enforce_bounded_scan_and_stable_claim_retry_limits() {
        let page = RunnableRunPageSize::new(8).unwrap();
        assert_eq!(
            DurableTenantSchedulerOptions::new(page, 0, 1, Duration::from_millis(1)),
            Err(DurableTenantSchedulerOptionsError::InvalidPageCount)
        );
        assert_eq!(
            DurableTenantSchedulerOptions::new(page, 1, 0, Duration::from_millis(1)),
            Err(DurableTenantSchedulerOptionsError::InvalidClaimAttempts)
        );
        assert_eq!(
            DurableTenantSchedulerOptions::new(page, 1, 1, Duration::ZERO),
            Err(DurableTenantSchedulerOptionsError::InvalidClaimRetryDelay)
        );
        let options =
            DurableTenantSchedulerOptions::new(page, 3, 4, Duration::from_millis(50)).unwrap();
        assert_eq!(options.page_size().get(), 8);
        assert_eq!(options.maximum_pages_per_tick(), 3);
        assert_eq!(options.maximum_claim_attempts(), 4);
    }
}