duroxide 0.1.27

Durable code execution framework for Rust
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
# Management API Improvements Proposal

> **Status**: Proposed  
> **Issue**: [#10]https://github.com/microsoft/duroxide/issues/10  
> **Related**: [Core Improvements Roadmap]proposals/core-improvements-roadmap.md#3-management-api-improvements

## Overview

This proposal details improvements to the duroxide Management API to address gaps in production workloads: the N+1 query problem, missing data cleanup APIs, pagination/filtering limitations, and query performance at scale.

---

## Table of Contents

1. [Problem Statement]#problem-statement
2. [Enriched List Responses]#1-enriched-list-responses
3. [Truncate APIs]#2-truncate-apis
4. [Pagination & Filtering]#3-pagination--filtering
5. [Performance Optimizations]#4-performance-optimizations
6. [Schema Changes]#5-schema-changes
7. [Error Handling]#6-error-handling
8. [Implementation Phases]#7-implementation-phases
9. [Open Questions]#8-open-questions

---

## Problem Statement

The current management API has significant gaps that limit its usefulness for production workloads:

### N+1 Query Problem

`list_instances()` returns only instance IDs, forcing clients to make N additional calls to `get_instance_info()` for basic dashboard data:

```rust
// Current: O(N+1) queries for N instances
let ids = client.list_all_instances().await?;  // 1 query
for id in &ids {
    let info = client.get_instance_info(id).await?;  // N queries
    println!("{}: {}", info.orchestration_name, info.status);
}
```

For 1,000 instances, this means 1,001 database round-trips. Real-world dashboards become unusable.

### No Data Cleanup APIs

There's no way to:
- Delete completed/failed instances after testing
- Truncate history for eternal orchestrations (continuous/polling workflows)
- Clean up orphaned data from crashed workers
- Bulk delete instances matching criteria

Eternal orchestrations using `continue_as_new` accumulate unbounded history:

```
Instance "daily-report"
├── Execution 1: 500 events (day 1)
├── Execution 2: 500 events (day 2)
├── ... 
└── Execution 365: 500 events (day 365)
    → 182,500 events, growing forever
```

### Performance at Scale

Current implementation has no pagination or efficient filtering:
- `list_instances()` returns ALL instances in memory
- `list_instances_by_status()` scans entire table
- No indexes optimized for management queries
- Dashboard queries compete with hot-path operations

### Missing Query Capabilities

Operators cannot answer basic questions:
- "Show me all failed `OrderWorkflow` instances from last hour"
- "How many `PaymentProcessor` instances are currently running?"
- "Find instances stuck in running state for > 24 hours"

---

## Proposed Solution

This proposal introduces four categories of improvements:
1. **Enriched List Responses** — Return full metadata in single query
2. **Truncate APIs** — Delete instances and prune execution history
3. **Pagination & Filtering** — Scalable queries with cursor-based pagination
4. **Performance Optimizations** — Indexes, batching, and query patterns

---

## 1. Enriched List Responses

### 1.1 Enhanced InstanceInfo Struct

Extend the existing `InstanceInfo` to include additional useful fields:

```rust
/// Comprehensive instance metadata for management operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstanceInfo {
    // Existing fields
    pub instance_id: String,
    pub orchestration_name: String,
    pub orchestration_version: String,
    pub current_execution_id: u64,
    pub status: String,
    pub output: Option<String>,
    pub created_at: u64,
    pub updated_at: u64,
    
    // NEW: Additional metadata
    /// Total number of executions (for continue_as_new tracking)
    pub execution_count: u64,
    /// Total events across all executions (storage indicator)
    pub total_event_count: u64,
    /// Input provided when instance was started
    pub input: Option<String>,
    /// Tags for categorization (if tag support added)
    pub tags: Option<Vec<String>>,
}
```

### 1.2 Batch List API

New provider trait method to return enriched data in a single query:

```rust
#[async_trait::async_trait]
pub trait ProviderAdmin: Any + Send + Sync {
    // ... existing methods ...

    /// List all instances with full metadata in a single query.
    /// 
    /// Unlike `list_instances()` which returns only IDs, this method
    /// returns complete `InstanceInfo` for each instance, eliminating
    /// the N+1 query problem.
    ///
    /// # Performance
    /// 
    /// Single SQL query with JOINs and aggregations. For large datasets,
    /// prefer `list_instances_paginated()` to avoid memory issues.
    ///
    /// # Implementation Example
    ///
    /// ```sql
    /// SELECT 
    ///     i.instance_id,
    ///     i.orchestration_name,
    ///     i.orchestration_version,
    ///     i.current_execution_id,
    ///     i.created_at,
    ///     i.updated_at,
    ///     e.status,
    ///     e.output,
    ///     (SELECT COUNT(*) FROM executions WHERE instance_id = i.instance_id) as execution_count,
    ///     (SELECT COUNT(*) FROM history WHERE instance_id = i.instance_id) as total_event_count
    /// FROM instances i
    /// LEFT JOIN executions e ON i.instance_id = e.instance_id 
    ///     AND i.current_execution_id = e.execution_id
    /// ORDER BY i.created_at DESC
    /// ```
    async fn list_instances_with_info(&self) -> Result<Vec<InstanceInfo>, ProviderError>;
}
```

### 1.3 Client API Addition

```rust
impl Client {
    /// List all instances with full metadata.
    ///
    /// Returns complete instance information in a single database query,
    /// avoiding the N+1 problem of calling `list_all_instances()` followed
    /// by `get_instance_info()` for each.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let instances = client.list_instances_with_info().await?;
    /// for info in instances {
    ///     println!("{} ({}): {} - {} events", 
    ///         info.instance_id,
    ///         info.orchestration_name,
    ///         info.status,
    ///         info.total_event_count
    ///     );
    /// }
    /// ```
    pub async fn list_instances_with_info(&self) -> Result<Vec<InstanceInfo>, ClientError>;
}
```

---

## 2. Truncate APIs

### 2.1 Instance Deletion

Complete deletion of an instance and all associated data:

```rust
#[async_trait::async_trait]
pub trait ProviderAdmin: Any + Send + Sync {
    // ... existing methods ...

    /// Delete an instance and all its associated data.
    ///
    /// Removes:
    /// - Instance record from `instances` table
    /// - All executions from `executions` table
    /// - All history events from `history` table
    /// - All pending queue messages for this instance
    /// - Any instance locks
    ///
    /// # Safety
    ///
    /// This operation is IRREVERSIBLE. The instance and all its history
    /// will be permanently deleted.
    ///
    /// # Constraints
    ///
    /// - Instance must NOT be in "Running" status (prevents deleting active work)
    /// - Use `force = true` to override (for cleanup of stuck instances)
    ///
    /// # Returns
    ///
    /// `TruncateResult` with counts of deleted records.
    ///
    /// # Errors
    ///
    /// - `InstanceNotFound` if instance doesn't exist
    /// - `InstanceStillRunning` if instance is active and force=false
    async fn delete_instance(
        &self,
        instance_id: &str,
        force: bool,
    ) -> Result<TruncateResult, ProviderError>;
    
    /// Bulk delete instances matching criteria.
    ///
    /// Efficiently deletes multiple instances in a single transaction.
    /// Useful for cleanup operations.
    ///
    /// # Parameters
    ///
    /// * `filter` - Criteria for selecting instances to delete
    ///
    /// # Returns
    ///
    /// Total counts of deleted records across all instances.
    async fn delete_instances_bulk(
        &self,
        filter: InstanceFilter,
    ) -> Result<TruncateResult, ProviderError>;
}

/// Result of truncation/deletion operations.
#[derive(Debug, Clone, Default)]
pub struct TruncateResult {
    /// Number of instance records deleted
    pub instances_deleted: u64,
    /// Number of execution records deleted
    pub executions_deleted: u64,
    /// Number of history events deleted
    pub events_deleted: u64,
    /// Number of queue messages deleted
    pub messages_deleted: u64,
}
```

### 2.2 Execution History Pruning

For eternal orchestrations, prune old executions while keeping recent ones:

```rust
#[async_trait::async_trait]
pub trait ProviderAdmin: Any + Send + Sync {
    // ... existing methods ...

    /// Prune old executions for an instance, keeping only recent ones.
    ///
    /// This is critical for "eternal" orchestrations that use `continue_as_new`
    /// repeatedly. Without pruning, history grows unbounded.
    ///
    /// # Parameters
    ///
    /// * `instance_id` - Instance to prune
    /// * `keep_last_n` - Number of most recent executions to retain
    ///
    /// # Behavior
    ///
    /// - Deletes executions where `execution_id < (current - keep_last_n)`
    /// - Deletes associated history events
    /// - NEVER deletes the current execution (even if keep_last_n = 0)
    ///
    /// # Example
    ///
    /// Instance has executions [1, 2, 3, 4, 5], current is 5:
    /// - `prune_executions("inst", 2)` → deletes 1, 2, 3; keeps 4, 5
    /// - `prune_executions("inst", 0)` → deletes 1, 2, 3, 4; keeps 5
    ///
    /// # Returns
    ///
    /// Number of executions deleted.
    async fn prune_executions(
        &self,
        instance_id: &str,
        keep_last_n: u64,
    ) -> Result<u64, ProviderError>;

    /// Prune executions older than a specified age.
    ///
    /// # Parameters
    ///
    /// * `instance_id` - Instance to prune
    /// * `older_than` - Delete executions completed before this duration ago
    ///
    /// # Returns
    ///
    /// Number of executions deleted.
    async fn prune_executions_by_age(
        &self,
        instance_id: &str,
        older_than: Duration,
    ) -> Result<u64, ProviderError>;
}
```

### 2.3 Automatic Retention Policy

Allow configuring automatic pruning for eternal orchestrations:

```rust
/// Retention policy for automatic execution pruning.
#[derive(Debug, Clone)]
pub struct ExecutionRetentionPolicy {
    /// Keep at least this many recent executions.
    /// Set to 0 to keep only the current execution.
    pub keep_last_n: u64,
    
    /// Delete executions older than this duration.
    /// Applied after keep_last_n (both conditions must be met for deletion).
    pub keep_duration: Option<Duration>,
    
    /// Run pruning automatically after each continue_as_new.
    /// If false, pruning must be triggered manually or via scheduled job.
    pub auto_prune: bool,
}

impl Default for ExecutionRetentionPolicy {
    fn default() -> Self {
        Self {
            keep_last_n: 10,
            keep_duration: Some(Duration::from_secs(7 * 24 * 60 * 60)), // 7 days
            auto_prune: false,
        }
    }
}

/// Configure retention when starting an orchestration.
impl Client {
    pub async fn start_orchestration_with_options(
        &self,
        name: &str,
        version: &str,
        instance_id: &str,
        input: Option<&str>,
        options: StartOptions,
    ) -> Result<(), ClientError>;
}

#[derive(Debug, Clone, Default)]
pub struct StartOptions {
    /// Execution retention policy for this instance.
    /// Only meaningful for orchestrations that use continue_as_new.
    pub retention_policy: Option<ExecutionRetentionPolicy>,
    
    /// Tags for categorization and filtering.
    pub tags: Option<Vec<String>>,
}
```

### 2.4 Client API for Truncation

```rust
impl Client {
    /// Delete a completed or failed instance.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Clean up after testing
    /// client.delete_instance("test-instance-123", false).await?;
    ///
    /// // Force delete a stuck instance
    /// client.delete_instance("stuck-instance", true).await?;
    /// ```
    pub async fn delete_instance(
        &self,
        instance_id: &str,
        force: bool,
    ) -> Result<TruncateResult, ClientError>;
    
    /// Prune old executions for an eternal orchestration.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Keep only last 5 executions
    /// let deleted = client.prune_executions("daily-job", 5).await?;
    /// println!("Pruned {} old executions", deleted);
    /// ```
    pub async fn prune_executions(
        &self,
        instance_id: &str,
        keep_last_n: u64,
    ) -> Result<u64, ClientError>;
    
    /// Bulk delete instances matching criteria.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Delete all completed instances older than 30 days
    /// let filter = InstanceFilter::new()
    ///     .with_status("Completed")
    ///     .older_than(Duration::from_secs(30 * 24 * 60 * 60));
    /// let result = client.delete_instances_bulk(filter).await?;
    /// println!("Deleted {} instances", result.instances_deleted);
    /// ```
    pub async fn delete_instances_bulk(
        &self,
        filter: InstanceFilter,
    ) -> Result<TruncateResult, ClientError>;
}
```

---

## 3. Pagination & Filtering

### 3.1 Filter Criteria

```rust
/// Filter criteria for listing instances.
#[derive(Debug, Clone, Default)]
pub struct InstanceFilter {
    /// Filter by orchestration status.
    /// Multiple values = OR (matches any).
    pub status: Option<Vec<String>>,
    
    /// Filter by orchestration name (exact match).
    pub orchestration_name: Option<String>,
    
    /// Filter by orchestration name prefix.
    pub orchestration_name_prefix: Option<String>,
    
    /// Filter by instance ID prefix.
    pub instance_id_prefix: Option<String>,
    
    /// Only include instances created after this timestamp (millis).
    pub created_after: Option<u64>,
    
    /// Only include instances created before this timestamp (millis).
    pub created_before: Option<u64>,
    
    /// Only include instances updated after this timestamp (millis).
    pub updated_after: Option<u64>,
    
    /// Only include instances updated before this timestamp (millis).
    pub updated_before: Option<u64>,
    
    /// Filter by tags (if tag support is implemented).
    /// Multiple values = AND (must have all tags).
    pub tags: Option<Vec<String>>,
}

impl InstanceFilter {
    pub fn new() -> Self {
        Self::default()
    }
    
    pub fn with_status(mut self, status: &str) -> Self {
        self.status = Some(vec![status.to_string()]);
        self
    }
    
    pub fn with_statuses(mut self, statuses: Vec<&str>) -> Self {
        self.status = Some(statuses.into_iter().map(String::from).collect());
        self
    }
    
    pub fn with_orchestration_name(mut self, name: &str) -> Self {
        self.orchestration_name = Some(name.to_string());
        self
    }
    
    pub fn with_name_prefix(mut self, prefix: &str) -> Self {
        self.orchestration_name_prefix = Some(prefix.to_string());
        self
    }
    
    pub fn created_after(mut self, timestamp: u64) -> Self {
        self.created_after = Some(timestamp);
        self
    }
    
    pub fn older_than(mut self, duration: Duration) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        self.created_before = Some(now.saturating_sub(duration.as_millis() as u64));
        self
    }
    
    /// Check if any filters are set.
    pub fn is_empty(&self) -> bool {
        self.status.is_none()
            && self.orchestration_name.is_none()
            && self.orchestration_name_prefix.is_none()
            && self.instance_id_prefix.is_none()
            && self.created_after.is_none()
            && self.created_before.is_none()
            && self.updated_after.is_none()
            && self.updated_before.is_none()
            && self.tags.is_none()
    }
}
```

### 3.2 Pagination with Cursors

```rust
/// Cursor-based pagination for scalable listing.
#[derive(Debug, Clone)]
pub struct PaginationOptions {
    /// Maximum number of results to return.
    /// Default: 100, Max: 1000
    pub limit: u32,
    
    /// Opaque cursor from previous page's `next_cursor`.
    /// None = start from beginning.
    pub cursor: Option<String>,
    
    /// Sort order.
    pub order: SortOrder,
}

#[derive(Debug, Clone, Copy, Default)]
pub enum SortOrder {
    /// Newest first (by created_at DESC)
    #[default]
    CreatedDesc,
    /// Oldest first (by created_at ASC)
    CreatedAsc,
    /// Most recently updated first
    UpdatedDesc,
    /// Least recently updated first
    UpdatedAsc,
}

impl Default for PaginationOptions {
    fn default() -> Self {
        Self {
            limit: 100,
            cursor: None,
            order: SortOrder::default(),
        }
    }
}

/// Paginated result set.
#[derive(Debug, Clone)]
pub struct PaginatedResult<T> {
    /// Items in this page.
    pub items: Vec<T>,
    
    /// Cursor for fetching next page.
    /// None if this is the last page.
    pub next_cursor: Option<String>,
    
    /// Total count matching filter (if available).
    /// May be None if counting is too expensive.
    pub total_count: Option<u64>,
    
    /// Whether there are more results.
    pub has_more: bool,
}
```

### 3.3 Provider Trait Additions

```rust
#[async_trait::async_trait]
pub trait ProviderAdmin: Any + Send + Sync {
    // ... existing methods ...

    /// List instances with filtering and pagination.
    ///
    /// # Parameters
    ///
    /// * `filter` - Criteria to filter instances
    /// * `pagination` - Pagination options (limit, cursor, order)
    ///
    /// # Returns
    ///
    /// Paginated result with instances and next cursor.
    ///
    /// # Implementation Notes
    ///
    /// Cursor should encode (created_at, instance_id) for stable pagination
    /// even as new instances are created.
    ///
    /// # Example SQL (CreatedDesc order)
    ///
    /// ```sql
    /// SELECT i.*, e.status, e.output
    /// FROM instances i
    /// LEFT JOIN executions e ON i.instance_id = e.instance_id 
    ///     AND i.current_execution_id = e.execution_id
    /// WHERE 
    ///     (? IS NULL OR e.status IN (?))
    ///     AND (? IS NULL OR i.orchestration_name = ?)
    ///     AND (? IS NULL OR i.orchestration_name LIKE ? || '%')
    ///     AND (? IS NULL OR i.created_at > ?)
    ///     AND (? IS NULL OR i.created_at < ?)
    ///     AND (? IS NULL OR (i.created_at, i.instance_id) < (?, ?))  -- cursor
    /// ORDER BY i.created_at DESC, i.instance_id DESC
    /// LIMIT ?
    /// ```
    async fn list_instances_paginated(
        &self,
        filter: InstanceFilter,
        pagination: PaginationOptions,
    ) -> Result<PaginatedResult<InstanceInfo>, ProviderError>;
    
    /// Count instances matching filter.
    ///
    /// Useful for UI pagination (showing "Page X of Y").
    /// May be expensive on large datasets.
    ///
    /// # Returns
    ///
    /// Total count of instances matching filter.
    async fn count_instances(
        &self,
        filter: InstanceFilter,
    ) -> Result<u64, ProviderError>;
}
```

### 3.4 Client API

```rust
impl Client {
    /// List instances with filtering and pagination.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Get first page of running OrderWorkflow instances
    /// let filter = InstanceFilter::new()
    ///     .with_status("Running")
    ///     .with_orchestration_name("OrderWorkflow");
    /// let pagination = PaginationOptions { limit: 50, ..Default::default() };
    /// 
    /// let page1 = client.list_instances_paginated(filter.clone(), pagination).await?;
    /// println!("Found {} instances", page1.items.len());
    /// 
    /// // Get next page
    /// if let Some(cursor) = page1.next_cursor {
    ///     let page2 = client.list_instances_paginated(
    ///         filter,
    ///         PaginationOptions { cursor: Some(cursor), ..Default::default() }
    ///     ).await?;
    /// }
    /// ```
    pub async fn list_instances_paginated(
        &self,
        filter: InstanceFilter,
        pagination: PaginationOptions,
    ) -> Result<PaginatedResult<InstanceInfo>, ClientError>;
    
    /// Count instances matching filter.
    pub async fn count_instances(
        &self,
        filter: InstanceFilter,
    ) -> Result<u64, ClientError>;
}
```

---

## 4. Performance Optimizations

### 4.1 Database Indexes

Add indexes specifically for management query patterns:

```sql
-- Index for filtering by status (via JOIN with executions)
CREATE INDEX IF NOT EXISTS idx_executions_status 
    ON executions(status, instance_id);

-- Index for filtering by orchestration name
CREATE INDEX IF NOT EXISTS idx_instances_name 
    ON instances(orchestration_name, created_at DESC);

-- Index for time-range queries
CREATE INDEX IF NOT EXISTS idx_instances_created 
    ON instances(created_at DESC, instance_id);

-- Index for updated_at queries (find stale instances)
CREATE INDEX IF NOT EXISTS idx_instances_updated 
    ON instances(updated_at DESC);

-- Covering index for common listing query
CREATE INDEX IF NOT EXISTS idx_instances_list_covering 
    ON instances(created_at DESC, instance_id, orchestration_name, orchestration_version, current_execution_id);

-- Index for execution pruning
CREATE INDEX IF NOT EXISTS idx_history_execution 
    ON history(instance_id, execution_id);
```

### 4.2 Query Optimization Patterns

**Avoid COUNT(*) for pagination:**

```rust
// Instead of: SELECT COUNT(*) FROM instances WHERE ...
// Use: fetch limit+1 and check if we got more

async fn list_instances_paginated(...) -> Result<PaginatedResult<InstanceInfo>, ProviderError> {
    // Fetch one extra to determine if there are more pages
    let fetch_limit = pagination.limit + 1;
    
    let rows = sqlx::query(/* ... LIMIT ? */)
        .bind(fetch_limit)
        .fetch_all(&self.pool)
        .await?;
    
    let has_more = rows.len() > pagination.limit as usize;
    let items: Vec<InstanceInfo> = rows
        .into_iter()
        .take(pagination.limit as usize)
        .map(|r| /* convert */)
        .collect();
    
    let next_cursor = if has_more {
        items.last().map(|i| encode_cursor(&i.created_at, &i.instance_id))
    } else {
        None
    };
    
    Ok(PaginatedResult { items, next_cursor, total_count: None, has_more })
}
```

**Cursor encoding for stable pagination:**

```rust
fn encode_cursor(created_at: u64, instance_id: &str) -> String {
    // Use base64 to hide implementation details
    let raw = format!("{}:{}", created_at, instance_id);
    base64::encode(raw)
}

fn decode_cursor(cursor: &str) -> Result<(u64, String), ProviderError> {
    let raw = base64::decode(cursor)
        .map_err(|_| ProviderError::permanent("decode_cursor", "Invalid cursor"))?;
    let s = String::from_utf8(raw)
        .map_err(|_| ProviderError::permanent("decode_cursor", "Invalid cursor encoding"))?;
    let parts: Vec<&str> = s.splitn(2, ':').collect();
    if parts.len() != 2 {
        return Err(ProviderError::permanent("decode_cursor", "Malformed cursor"));
    }
    let created_at = parts[0].parse::<u64>()
        .map_err(|_| ProviderError::permanent("decode_cursor", "Invalid timestamp in cursor"))?;
    Ok((created_at, parts[1].to_string()))
}
```

### 4.3 Batched Operations

For bulk deletions, use batched transactions to avoid long-running locks:

```rust
async fn delete_instances_bulk(
    &self,
    filter: InstanceFilter,
) -> Result<TruncateResult, ProviderError> {
    const BATCH_SIZE: u32 = 100;
    let mut total_result = TruncateResult::default();
    
    loop {
        // Find next batch of instance IDs to delete
        let pagination = PaginationOptions { limit: BATCH_SIZE, ..Default::default() };
        let page = self.list_instances_paginated(filter.clone(), pagination).await?;
        
        if page.items.is_empty() {
            break;
        }
        
        // Delete this batch in a transaction
        let mut tx = self.pool.begin().await?;
        for info in &page.items {
            let result = self.delete_instance_in_tx(&mut tx, &info.instance_id).await?;
            total_result.instances_deleted += result.instances_deleted;
            total_result.executions_deleted += result.executions_deleted;
            total_result.events_deleted += result.events_deleted;
            total_result.messages_deleted += result.messages_deleted;
        }
        tx.commit().await?;
        
        if !page.has_more {
            break;
        }
    }
    
    Ok(total_result)
}
```

---

## 5. Schema Changes

### 5.1 Migration SQL

```sql
-- Migration: Add management API indexes
-- Version: 2024_xx_management_api_indexes

-- Index for status filtering
CREATE INDEX IF NOT EXISTS idx_executions_status 
    ON executions(status, instance_id);

-- Index for orchestration name filtering
CREATE INDEX IF NOT EXISTS idx_instances_name 
    ON instances(orchestration_name, created_at DESC);

-- Index for time-range queries
CREATE INDEX IF NOT EXISTS idx_instances_created 
    ON instances(created_at DESC, instance_id);

-- Index for finding stale instances
CREATE INDEX IF NOT EXISTS idx_instances_updated 
    ON instances(updated_at DESC);

-- Index for execution pruning
CREATE INDEX IF NOT EXISTS idx_history_execution 
    ON history(instance_id, execution_id);


-- Migration: Add optional instance metadata
-- Version: 2024_xx_instance_metadata

-- Add input column to track original input (optional)
ALTER TABLE instances ADD COLUMN input TEXT;

-- Add tags column for categorization (JSON array, optional)
ALTER TABLE instances ADD COLUMN tags TEXT;

-- Add retention policy (JSON, optional)
ALTER TABLE instances ADD COLUMN retention_policy TEXT;
```

### 5.2 Backward Compatibility

All new columns are nullable with no default, ensuring:
- Existing instances continue to work unchanged
- New features are opt-in
- No data migration required for existing deployments

---

## 6. Error Handling

### 6.1 New Error Variants

```rust
#[derive(Debug, Clone)]
pub enum ManagementError {
    /// Instance not found
    InstanceNotFound { instance_id: String },
    
    /// Cannot delete a running instance without force flag
    InstanceStillRunning { instance_id: String },
    
    /// Invalid filter criteria
    InvalidFilter { message: String },
    
    /// Invalid cursor format
    InvalidCursor { cursor: String },
    
    /// Operation would exceed limits
    LimitExceeded { 
        limit_name: String, 
        limit_value: u64, 
        requested: u64 
    },
}
```

---

## 7. Implementation Phases

### Phase 1: Core APIs (MVP)
- [ ] `list_instances_with_info()` — enriched listing
- [ ] `delete_instance()` — single instance deletion
- [ ] `prune_executions()` — execution history pruning
- [ ] Basic filtering by status and orchestration name

### Phase 2: Pagination & Performance
- [ ] `list_instances_paginated()` with cursor-based pagination
- [ ] `count_instances()` for total counts
- [ ] Database indexes for management queries
- [ ] Batched bulk operations

### Phase 3: Advanced Features
- [ ] `delete_instances_bulk()` with filters
- [ ] Automatic retention policies
- [ ] Tag support for instances
- [ ] Time-range filtering

---

## 8. Open Questions

1. **Retention Policy Storage**: Should retention policies be stored in the instance record, or in a separate configuration table?

2. **Automatic vs Manual Pruning**: Should auto-pruning happen during `continue_as_new`, or via a background maintenance job?

3. **Soft vs Hard Delete**: Should we support soft deletes (mark as deleted but retain data) for audit purposes?

4. **Read Replicas**: Should management queries be routable to read replicas for production workloads?

5. **Metrics Integration**: Should truncation operations emit metrics (events deleted, time taken)?