scouter-dataframe 0.25.0

DataFusion client for long-term storage of scouter data
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use crate::error::TraceEngineError;
use crate::parquet::tracing::traits::arrow_schema_to_delta;
use crate::parquet::utils::register_cloud_logstore_factories;
use crate::storage::ObjectStore;
use arrow::array::*;
use arrow::datatypes::*;
use arrow_array::RecordBatch;
use chrono::{DateTime, Duration, Utc};
use datafusion::logical_expr::{col, lit};
use datafusion::prelude::SessionContext;
use deltalake::{DeltaTable, DeltaTableBuilder, TableProperty};
use std::sync::Arc;
use tokio::sync::RwLock as AsyncRwLock;
use tracing::{debug, info, warn};
use url::Url;

const CONTROL_TABLE_NAME: &str = "_scouter_control";

/// Stale lock threshold: if a task has been "processing" for longer than this,
/// it is considered abandoned and can be reclaimed by another pod.
const STALE_LOCK_MINUTES: i64 = 30;

/// Status values for task records in the control table.
mod status {
    pub const IDLE: &str = "idle";
    pub const PROCESSING: &str = "processing";
}

/// A task record in the control table.
#[derive(Debug, Clone)]
pub struct TaskRecord {
    pub task_name: String,
    pub status: String,
    pub pod_id: String,
    pub claimed_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
    pub next_run_at: DateTime<Utc>,
}

/// Arrow schema for the control table.
///
/// Simple, flat schema — no dictionary encoding or bloom filters needed.
/// This table will only ever have a handful of rows (one per task type).
fn control_schema() -> Schema {
    Schema::new(vec![
        Field::new("task_name", DataType::Utf8, false),
        Field::new("status", DataType::Utf8, false),
        Field::new("pod_id", DataType::Utf8, false),
        Field::new(
            "claimed_at",
            DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
            false,
        ),
        Field::new(
            "completed_at",
            DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
            true,
        ),
        Field::new(
            "next_run_at",
            DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
            false,
        ),
    ])
}

fn build_task_batch(
    schema: &SchemaRef,
    record: &TaskRecord,
) -> Result<RecordBatch, TraceEngineError> {
    let task_name = StringArray::from(vec![record.task_name.as_str()]);
    let status = StringArray::from(vec![record.status.as_str()]);
    let pod_id = StringArray::from(vec![record.pod_id.as_str()]);
    let claimed_at = TimestampMicrosecondArray::from(vec![record.claimed_at.timestamp_micros()])
        .with_timezone("UTC");
    let completed_at = if let Some(ts) = record.completed_at {
        TimestampMicrosecondArray::from(vec![Some(ts.timestamp_micros())]).with_timezone("UTC")
    } else {
        TimestampMicrosecondArray::from(vec![None::<i64>]).with_timezone("UTC")
    };
    let next_run_at = TimestampMicrosecondArray::from(vec![record.next_run_at.timestamp_micros()])
        .with_timezone("UTC");

    RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(task_name),
            Arc::new(status),
            Arc::new(pod_id),
            Arc::new(claimed_at),
            Arc::new(completed_at),
            Arc::new(next_run_at),
        ],
    )
    .map_err(Into::into)
}

/// Get a stable pod identifier for distributed locking.
///
/// Resolution order: `HOSTNAME` (K8s default) → `POD_NAME` (custom override) →
/// `local-{pid}` for local dev.
pub fn get_pod_id() -> String {
    std::env::var("HOSTNAME")
        .or_else(|_| std::env::var("POD_NAME"))
        .unwrap_or_else(|_| format!("local-{}", std::process::id()))
}

/// Distributed coordination engine backed by a Delta Lake table.
///
/// Uses Delta Lake's optimistic concurrency control (OCC) to implement
/// distributed task locking across multiple K8s pods. The transaction log
/// serializes concurrent claims — if two pods race to claim the same task,
/// one commit succeeds and the other gets a `TransactionError`.
///
/// The control table lives at `{storage_uri}/_scouter_control/` alongside
/// the trace data tables.
pub struct ControlTableEngine {
    schema: SchemaRef,
    #[allow(dead_code)] // Used for future vacuum/maintenance operations
    table: Arc<AsyncRwLock<DeltaTable>>,
    ctx: Arc<SessionContext>,
    pod_id: String,
}

impl ControlTableEngine {
    /// Create or load the control table.
    ///
    /// The `pod_id` identifies this instance for distributed locking. In K8s,
    /// pass the pod hostname (`std::env::var("HOSTNAME")`).
    pub async fn new(object_store: &ObjectStore, pod_id: String) -> Result<Self, TraceEngineError> {
        let schema = Arc::new(control_schema());
        let table = build_or_create_control_table(object_store, schema.clone()).await?;
        let ctx = object_store.get_session()?;

        if let Ok(provider) = table.table_provider().await {
            ctx.register_table(CONTROL_TABLE_NAME, provider)?;
        } else {
            info!("Empty control table at init — deferring registration until first write");
        }

        Ok(Self {
            schema,
            table: Arc::new(AsyncRwLock::new(table)),
            ctx: Arc::new(ctx),
            pod_id,
        })
    }

    /// Try to claim a task for exclusive execution.
    ///
    /// Returns `true` if this pod successfully claimed the task.
    /// Returns `false` if:
    /// - Another pod is already processing (and the lock is not stale)
    /// - The task is not yet due (`next_run_at` is in the future)
    /// - A concurrent pod won the Delta OCC race
    ///
    /// This is the distributed equivalent of `SELECT ... FOR UPDATE SKIP LOCKED`.
    pub async fn try_claim_task(&self, task_name: &str) -> Result<bool, TraceEngineError> {
        let mut table_guard = self.table.write().await;

        // Refresh from storage to see commits from other pods
        if let Err(e) = table_guard.update_incremental(None).await {
            debug!("Control table update skipped (new table): {}", e);
        }

        // Re-register so DataFusion sees latest state
        let _ = self.ctx.deregister_table(CONTROL_TABLE_NAME);
        if let Ok(provider) = table_guard.table_provider().await {
            self.ctx.register_table(CONTROL_TABLE_NAME, provider)?;
        }

        // Read current task state
        let current = self
            .read_task(&table_guard_to_ctx(&self.ctx), task_name)
            .await?;

        let now = Utc::now();

        match current {
            Some(record) => {
                // Check if another pod is actively processing
                if record.status == status::PROCESSING {
                    let stale_threshold = now - Duration::minutes(STALE_LOCK_MINUTES);
                    if record.claimed_at > stale_threshold {
                        debug!(
                            "Task '{}' is being processed by pod '{}' (not stale), skipping",
                            task_name, record.pod_id
                        );
                        return Ok(false);
                    }
                    warn!(
                        "Task '{}' claimed by pod '{}' is stale (claimed_at: {}), reclaiming",
                        task_name, record.pod_id, record.claimed_at
                    );
                }

                // Check if task is due
                if now < record.next_run_at {
                    debug!(
                        "Task '{}' not due until {}, skipping",
                        task_name, record.next_run_at
                    );
                    return Ok(false);
                }

                // Claim the task by overwriting the entire table content for this task.
                // Delta OCC ensures only one pod wins.
                let claimed = TaskRecord {
                    task_name: task_name.to_string(),
                    status: status::PROCESSING.to_string(),
                    pod_id: self.pod_id.clone(),
                    claimed_at: now,
                    completed_at: None,
                    next_run_at: record.next_run_at,
                };

                match self.write_task_update(&mut table_guard, &claimed).await {
                    Ok(()) => {
                        info!("Successfully claimed task '{}'", task_name);
                        Ok(true)
                    }
                    Err(TraceEngineError::DataTableError(ref e))
                        if e.to_string().contains("Transaction") =>
                    {
                        info!("Lost OCC race for task '{}' to another pod", task_name);
                        Ok(false)
                    }
                    Err(e) => Err(e),
                }
            }
            None => {
                // Task doesn't exist yet — create it in "processing" state.
                // The first pod to reach here wins via OCC.
                let claimed = TaskRecord {
                    task_name: task_name.to_string(),
                    status: status::PROCESSING.to_string(),
                    pod_id: self.pod_id.clone(),
                    claimed_at: now,
                    completed_at: None,
                    next_run_at: now, // Will be updated on release
                };

                match self.write_task_update(&mut table_guard, &claimed).await {
                    Ok(()) => {
                        info!("Created and claimed new task '{}'", task_name);
                        Ok(true)
                    }
                    Err(TraceEngineError::DataTableError(ref e))
                        if e.to_string().contains("Transaction") =>
                    {
                        info!("Lost OCC race for new task '{}' to another pod", task_name);
                        Ok(false)
                    }
                    Err(e) => Err(e),
                }
            }
        }
    }

    /// Release a task after successful completion, scheduling the next run.
    ///
    /// Sets status to "idle" and updates `next_run_at` based on the provided interval.
    pub async fn release_task(
        &self,
        task_name: &str,
        next_run_interval: Duration,
    ) -> Result<(), TraceEngineError> {
        let mut table_guard = self.table.write().await;
        let now = Utc::now();

        let released = TaskRecord {
            task_name: task_name.to_string(),
            status: status::IDLE.to_string(),
            pod_id: self.pod_id.clone(),
            claimed_at: now,
            completed_at: Some(now),
            next_run_at: now + next_run_interval,
        };

        self.write_task_update(&mut table_guard, &released).await?;

        info!(
            "Released task '{}', next run at {}",
            task_name, released.next_run_at
        );
        Ok(())
    }

    /// Release a task after a failure, keeping the original `next_run_at` so it
    /// can be retried immediately by any pod.
    pub async fn release_task_on_failure(&self, task_name: &str) -> Result<(), TraceEngineError> {
        let mut table_guard = self.table.write().await;

        // Refresh to get current next_run_at
        if let Err(e) = table_guard.update_incremental(None).await {
            debug!("Control table update skipped: {}", e);
        }

        let _ = self.ctx.deregister_table(CONTROL_TABLE_NAME);
        if let Ok(provider) = table_guard.table_provider().await {
            self.ctx.register_table(CONTROL_TABLE_NAME, provider)?;
        }

        let current = self
            .read_task(&table_guard_to_ctx(&self.ctx), task_name)
            .await?;

        let now = Utc::now();
        let next_run = current.map(|r| r.next_run_at).unwrap_or(now);

        let released = TaskRecord {
            task_name: task_name.to_string(),
            status: status::IDLE.to_string(),
            pod_id: self.pod_id.clone(),
            claimed_at: now,
            completed_at: Some(now),
            next_run_at: next_run,
        };

        self.write_task_update(&mut table_guard, &released).await?;

        warn!(
            "Released task '{}' after failure, next_run_at unchanged: {}",
            task_name, next_run
        );
        Ok(())
    }

    /// Check if a task is due and not currently being processed.
    pub async fn is_task_due(&self, task_name: &str) -> Result<bool, TraceEngineError> {
        let mut table_guard = self.table.write().await;

        if let Err(e) = table_guard.update_incremental(None).await {
            debug!("Control table update skipped: {}", e);
        }

        let _ = self.ctx.deregister_table(CONTROL_TABLE_NAME);
        if let Ok(provider) = table_guard.table_provider().await {
            self.ctx.register_table(CONTROL_TABLE_NAME, provider)?;
        }

        let current = self
            .read_task(&table_guard_to_ctx(&self.ctx), task_name)
            .await?;

        let now = Utc::now();
        match current {
            Some(record) => {
                if record.status == status::PROCESSING {
                    let stale_threshold = now - Duration::minutes(STALE_LOCK_MINUTES);
                    // Due only if the lock is stale
                    Ok(record.claimed_at <= stale_threshold)
                } else {
                    Ok(now >= record.next_run_at)
                }
            }
            // Never registered = due (first run)
            None => Ok(true),
        }
    }

    /// Read a single task record from the control table via DataFusion.
    async fn read_task(
        &self,
        ctx: &SessionContext,
        task_name: &str,
    ) -> Result<Option<TaskRecord>, TraceEngineError> {
        let table_exists = ctx.table_exist(CONTROL_TABLE_NAME)?;
        if !table_exists {
            return Ok(None);
        }

        let df = ctx
            .table(CONTROL_TABLE_NAME)
            .await
            .map_err(TraceEngineError::DatafusionError)?;

        let df = df
            .filter(col("task_name").eq(lit(task_name)))
            .map_err(TraceEngineError::DatafusionError)?;

        let batches = df
            .collect()
            .await
            .map_err(TraceEngineError::DatafusionError)?;

        // Extract the first (and only) row if it exists.
        // DataFusion may return Utf8View instead of Utf8 for string columns,
        // so cast to Utf8 before downcast to StringArray.
        for batch in &batches {
            if batch.num_rows() == 0 {
                continue;
            }

            let get_string = |col_name: &'static str| -> Result<String, TraceEngineError> {
                let col = batch
                    .column_by_name(col_name)
                    .ok_or(TraceEngineError::DowncastError(col_name))?;
                let casted = arrow::compute::cast(col, &DataType::Utf8)
                    .map_err(TraceEngineError::ArrowError)?;
                let arr = casted
                    .as_any()
                    .downcast_ref::<StringArray>()
                    .ok_or(TraceEngineError::DowncastError(col_name))?;
                Ok(arr.value(0).to_string())
            };

            let get_timestamp =
                |col_name: &'static str| -> Result<Option<DateTime<Utc>>, TraceEngineError> {
                    let col = batch
                        .column_by_name(col_name)
                        .ok_or(TraceEngineError::DowncastError(col_name))?;
                    if col.is_null(0) {
                        return Ok(None);
                    }
                    let arr = col
                        .as_any()
                        .downcast_ref::<TimestampMicrosecondArray>()
                        .ok_or(TraceEngineError::DowncastError(col_name))?;
                    Ok(DateTime::from_timestamp_micros(arr.value(0)))
                };

            let task_name_val = get_string("task_name")?;
            let status_val = get_string("status")?;
            let pod_id_val = get_string("pod_id")?;
            let claimed_at = get_timestamp("claimed_at")?.unwrap_or_else(Utc::now);
            let completed_at = get_timestamp("completed_at")?;
            let next_run_at = get_timestamp("next_run_at")?.unwrap_or_else(Utc::now);

            return Ok(Some(TaskRecord {
                task_name: task_name_val,
                status: status_val,
                pod_id: pod_id_val,
                claimed_at,
                completed_at,
                next_run_at,
            }));
        }

        Ok(None)
    }

    /// Write a task update using Delta Lake MERGE-like semantics.
    ///
    /// Strategy: DELETE the existing row for this task_name, then APPEND the new row.
    /// Delta OCC ensures atomicity — if two pods race, one commit fails with
    /// `TransactionError` and the caller can retry or back off.
    async fn write_task_update(
        &self,
        table_guard: &mut DeltaTable,
        record: &TaskRecord,
    ) -> Result<(), TraceEngineError> {
        let batch = build_task_batch(&self.schema, record)?;

        // First, delete the existing row for this task (if any).
        // On a brand-new table with no data, delete will fail — that's fine.
        // Safety: task_name is always an internal constant (e.g. "summary_optimize").
        // The delta-rs delete API takes a String predicate, not a parameterized Expr,
        // so we assert the invariant defensively.
        debug_assert!(
            record
                .task_name
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_'),
            "task_name must be alphanumeric + underscore, got: {}",
            record.task_name
        );
        let predicate = format!("task_name = '{}'", record.task_name);
        let delete_result = table_guard.clone().delete().with_predicate(predicate).await;

        match delete_result {
            Ok((updated_table, _metrics)) => {
                // Delete succeeded — now append the new row to the updated table
                let updated_table = updated_table
                    .write(vec![batch])
                    .with_save_mode(deltalake::protocol::SaveMode::Append)
                    .await?;

                let _ = self.ctx.deregister_table(CONTROL_TABLE_NAME);
                if let Ok(provider) = updated_table.table_provider().await {
                    self.ctx.register_table(CONTROL_TABLE_NAME, provider)?;
                }
                *table_guard = updated_table;
            }
            Err(e) => {
                let err_msg = e.to_string();
                // On a brand-new table with no data, delete fails because there's nothing
                // to remove — this is expected and we fall through to append.
                // All other errors are real failures and must be propagated.
                if !err_msg.contains("No data") && !err_msg.contains("empty") {
                    warn!(
                        "Delete before write_task_update failed unexpectedly: {}",
                        err_msg
                    );
                    return Err(TraceEngineError::DataTableError(e));
                }

                let updated_table = table_guard
                    .clone()
                    .write(vec![batch])
                    .with_save_mode(deltalake::protocol::SaveMode::Append)
                    .await?;

                let _ = self.ctx.deregister_table(CONTROL_TABLE_NAME);
                if let Ok(provider) = updated_table.table_provider().await {
                    self.ctx.register_table(CONTROL_TABLE_NAME, provider)?;
                }
                *table_guard = updated_table;
            }
        }

        Ok(())
    }
}

/// Helper to avoid borrow issues — just returns the ctx reference.
fn table_guard_to_ctx(ctx: &Arc<SessionContext>) -> SessionContext {
    ctx.as_ref().clone()
}

/// Build or load the control table at `{base_url}/_scouter_control/`.
async fn build_or_create_control_table(
    object_store: &ObjectStore,
    schema: SchemaRef,
) -> Result<DeltaTable, TraceEngineError> {
    // Reuse the cloud logstore factories registered by the trace engine.
    // Safe to call repeatedly — existing entries are not overwritten.
    register_cloud_logstore_factories();

    let base_url = object_store.get_base_url()?;
    let control_url = append_path_to_url(&base_url, CONTROL_TABLE_NAME)?;

    info!(
        "Loading control table [{}://.../{} ]",
        control_url.scheme(),
        control_url
            .path_segments()
            .and_then(|mut s| s.next_back())
            .unwrap_or(CONTROL_TABLE_NAME)
    );

    let store = object_store.as_dyn_object_store();

    let is_delta_table = if control_url.scheme() == "file" {
        if let Ok(path) = control_url.to_file_path() {
            if !path.exists() {
                info!("Creating directory for control table: {:?}", path);
                std::fs::create_dir_all(&path)?;
            }
            path.join("_delta_log").exists()
        } else {
            false
        }
    } else {
        match DeltaTableBuilder::from_url(control_url.clone()) {
            Ok(builder) => builder
                .with_storage_backend(store.clone(), control_url.clone())
                .load()
                .await
                .is_ok(),
            Err(_) => false,
        }
    };

    if is_delta_table {
        info!(
            "Loaded existing control table [{}://.../{} ]",
            control_url.scheme(),
            control_url
                .path_segments()
                .and_then(|mut s| s.next_back())
                .unwrap_or(CONTROL_TABLE_NAME)
        );
        let table = DeltaTableBuilder::from_url(control_url.clone())?
            .with_storage_backend(store, control_url)
            .load()
            .await?;
        Ok(table)
    } else {
        info!("Creating new control table");
        let table = DeltaTableBuilder::from_url(control_url.clone())?
            .with_storage_backend(store, control_url)
            .build()?;

        let delta_fields = arrow_schema_to_delta(&schema);

        table
            .create()
            .with_table_name(CONTROL_TABLE_NAME)
            .with_columns(delta_fields)
            .with_configuration_property(TableProperty::CheckpointInterval, Some("5"))
            .await
            .map_err(Into::into)
    }
}

/// Append a path segment to a URL, handling trailing slashes correctly.
fn append_path_to_url(base: &Url, segment: &str) -> Result<Url, TraceEngineError> {
    let mut url = base.clone();
    // Ensure the base path ends with '/'
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    url = url.join(segment)?;
    Ok(url)
}

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

    fn make_test_object_store(storage_settings: &ObjectStorageSettings) -> ObjectStore {
        ObjectStore::new(storage_settings).unwrap()
    }

    fn cleanup() {
        let storage_settings = ObjectStorageSettings::default();
        let current_dir = std::env::current_dir().unwrap();
        let storage_path = current_dir.join(storage_settings.storage_root());
        if storage_path.exists() {
            let _ = std::fs::remove_dir_all(storage_path);
        }
    }

    #[tokio::test]
    async fn test_control_table_init() -> Result<(), TraceEngineError> {
        cleanup();

        let settings = ObjectStorageSettings::default();
        let object_store = make_test_object_store(&settings);
        let engine = ControlTableEngine::new(&object_store, "pod-1".to_string()).await?;

        // No tasks should exist yet
        let due = engine.is_task_due("optimize").await?;
        assert!(due, "New task should be due (never run before)");

        cleanup();
        Ok(())
    }

    #[tokio::test]
    async fn test_claim_and_release() -> Result<(), TraceEngineError> {
        cleanup();

        let settings = ObjectStorageSettings::default();
        let object_store = make_test_object_store(&settings);
        let engine = ControlTableEngine::new(&object_store, "pod-1".to_string()).await?;

        // Claim a new task
        let claimed = engine.try_claim_task("optimize").await?;
        assert!(claimed, "First claim should succeed");

        // Second claim from same engine should fail (task is processing)
        let claimed_again = engine.try_claim_task("optimize").await?;
        assert!(
            !claimed_again,
            "Second claim should fail (already processing)"
        );

        // Release with 1-hour interval
        engine.release_task("optimize", Duration::hours(1)).await?;

        // Task should not be due yet (next_run_at is 1 hour from now)
        let due = engine.is_task_due("optimize").await?;
        assert!(!due, "Task should not be due yet");

        cleanup();
        Ok(())
    }

    #[tokio::test]
    async fn test_claim_release_then_due() -> Result<(), TraceEngineError> {
        cleanup();

        let settings = ObjectStorageSettings::default();
        let object_store = make_test_object_store(&settings);
        let engine = ControlTableEngine::new(&object_store, "pod-1".to_string()).await?;

        // Claim and release with 0-second interval (immediately due again)
        let claimed = engine.try_claim_task("vacuum").await?;
        assert!(claimed);

        engine.release_task("vacuum", Duration::seconds(0)).await?;

        // Should be due now
        let due = engine.is_task_due("vacuum").await?;
        assert!(due, "Task should be due after 0-second interval");

        // Should be claimable again
        let claimed = engine.try_claim_task("vacuum").await?;
        assert!(claimed, "Task should be claimable after release");

        // Release on failure — next_run_at stays the same
        engine.release_task_on_failure("vacuum").await?;

        cleanup();
        Ok(())
    }

    #[tokio::test]
    async fn test_multiple_tasks() -> Result<(), TraceEngineError> {
        cleanup();

        let settings = ObjectStorageSettings::default();
        let object_store = make_test_object_store(&settings);
        let engine = ControlTableEngine::new(&object_store, "pod-1".to_string()).await?;

        // Claim two different tasks
        let claimed_opt = engine.try_claim_task("optimize").await?;
        let claimed_vac = engine.try_claim_task("vacuum").await?;
        assert!(claimed_opt, "Optimize claim should succeed");
        assert!(claimed_vac, "Vacuum claim should succeed");

        // Release both
        engine.release_task("optimize", Duration::hours(24)).await?;
        engine.release_task("vacuum", Duration::hours(168)).await?;

        cleanup();
        Ok(())
    }
}