awaken-stores 0.4.0

Storage backends (memory, file, PostgreSQL, SQLite mailbox) for Awaken agent state
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
//! NATS-buffered `ThreadRunStore` decorator.
//!
//! Buffers `checkpoint()` writes in a JetStream WAL + KV hot state, with a
//! background flusher that coalesces per-thread writes into the inner store.
//! Reads serve read-your-writes consistency via a WAL overlay (DB when caught
//! up, last WAL entry otherwise).
//!
//! # Example
//!
//! ```no_run
//! use std::sync::Arc;
//! use awaken_stores::{InMemoryStore, NatsBufferedThreadConfig, NatsBufferedThreadStore};
//!
//! # async fn wire() -> Result<(), Box<dyn std::error::Error>> {
//! let inner = Arc::new(InMemoryStore::new());
//! let config = NatsBufferedThreadConfig::new("nats://localhost:4222");
//! let buffered = NatsBufferedThreadStore::connect(inner, config).await?;
//! // Use `buffered` wherever a `ThreadRunStore` is expected.
//! # buffered.shutdown().await?;
//! # Ok(())
//! # }
//! ```

mod config;
mod entry;
mod flusher;
mod hierarchy_claim;
mod hot_meta;
mod keys;
mod metrics;
mod reader;
mod recovery;
mod wal_state;
mod writer;

pub use config::{NatsBufferedThreadConfig, ReadConsistency};

use std::sync::Arc;

use async_nats::jetstream::{consumer, kv, stream};
use async_trait::async_trait;
use awaken_contract::contract::message::Message;
use awaken_contract::contract::storage::{
    ChildThreadDeleteStrategy, MessagePage, MessageQuery, RunPage, RunQuery, RunRecord, RunStore,
    StorageError, ThreadPage, ThreadQuery, ThreadRunStore, ThreadStore,
};
use awaken_contract::thread::{Thread, ThreadMetadata};

#[derive(Debug, Clone, Default)]
struct HierarchyMutationTestHooks {
    after_inner_delete_pause: Arc<tokio::sync::Mutex<Option<DeletePausePoint>>>,
    before_inner_save_validated_pause: Arc<tokio::sync::Mutex<Option<SavePausePoint>>>,
}

#[derive(Debug, Clone)]
struct DeletePausePoint {
    thread_id: String,
    reached: Arc<tokio::sync::Notify>,
    release: Arc<tokio::sync::Notify>,
}

#[derive(Debug, Clone)]
struct SavePausePoint {
    thread_id: String,
    reached: Arc<tokio::sync::Notify>,
    release: Arc<tokio::sync::Notify>,
}

impl HierarchyMutationTestHooks {
    async fn set_pause_after_inner_delete(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        *self.after_inner_delete_pause.lock().await = Some(DeletePausePoint {
            thread_id: thread_id.to_string(),
            reached,
            release,
        });
    }

    async fn pause_after_inner_delete_if_configured(&self, thread_id: &str) {
        let pause = {
            let mut slot = self.after_inner_delete_pause.lock().await;
            match slot.as_ref() {
                Some(pause) if pause.thread_id == thread_id => slot.take(),
                _ => None,
            }
        };
        let Some(pause) = pause else {
            return;
        };
        pause.reached.notify_waiters();
        pause.release.notified().await;
    }

    async fn set_pause_before_inner_save_validated(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        *self.before_inner_save_validated_pause.lock().await = Some(SavePausePoint {
            thread_id: thread_id.to_string(),
            reached,
            release,
        });
    }

    async fn pause_before_inner_save_validated_if_configured(&self, thread_id: &str) {
        let pause = {
            let mut slot = self.before_inner_save_validated_pause.lock().await;
            match slot.as_ref() {
                Some(pause) if pause.thread_id == thread_id => slot.take(),
                _ => None,
            }
        };
        let Some(pause) = pause else {
            return;
        };
        pause.reached.notify_waiters();
        pause.release.notified().await;
    }
}

pub struct NatsBufferedThreadStore<T: ThreadRunStore + Send + Sync + 'static> {
    pub(crate) inner: Arc<T>,
    #[allow(dead_code)]
    pub(crate) client: async_nats::Client,
    pub(crate) jetstream: async_nats::jetstream::Context,
    pub(crate) stream: async_nats::jetstream::stream::Stream,
    pub(crate) kv_hot: async_nats::jetstream::kv::Store,
    #[allow(dead_code)]
    pub(crate) consumer: async_nats::jetstream::consumer::PullConsumer,
    pub(crate) config: config::NatsBufferedThreadConfig,
    pub(crate) hierarchy_write_lock: tokio::sync::Mutex<()>,
    pub(crate) hierarchy_claim_options: hierarchy_claim::ClaimOptions,
    pub(crate) writer_test_hooks: writer::WriterTestHooks,
    pub(crate) flush_claim_options: hierarchy_claim::ClaimOptions,
    pub(crate) flusher_test_hooks: flusher::FlusherTestHooks,
    hierarchy_mutation_test_hooks: HierarchyMutationTestHooks,
    pub(crate) flush_notify: Arc<tokio::sync::Notify>,
    pub(crate) shutdown_tx: tokio::sync::watch::Sender<bool>,
    pub(crate) flusher_handle: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
}

impl<T: ThreadRunStore + Send + Sync + 'static> NatsBufferedThreadStore<T> {
    pub async fn connect(
        inner: Arc<T>,
        config: config::NatsBufferedThreadConfig,
    ) -> Result<Self, StorageError> {
        let client =
            crate::nats_connect::connect(&config.url, config.credentials.as_deref()).await?;
        let jetstream = async_nats::jetstream::new(client.clone());

        let stream_config = stream::Config {
            name: config.stream_name.clone(),
            subjects: vec!["thread.>".to_string()],
            retention: stream::RetentionPolicy::Limits,
            max_age: config.max_age,
            storage: stream::StorageType::File,
            ..Default::default()
        };
        let stream = jetstream
            .get_or_create_stream(stream_config)
            .await
            .map_err(|e| StorageError::Io(format!("create stream: {e}")))?;

        let consumer_config = consumer::pull::Config {
            durable_name: Some(config.consumer_name.clone()),
            filter_subject: "thread.>".to_string(),
            ack_policy: consumer::AckPolicy::Explicit,
            ack_wait: config.ack_wait,
            ..Default::default()
        };
        let consumer = stream
            .get_or_create_consumer(&config.consumer_name, consumer_config)
            .await
            .map_err(|e| StorageError::Io(format!("create consumer: {e}")))?;

        let kv_hot = match jetstream.get_key_value(&config.hot_bucket).await {
            Ok(s) => s,
            Err(_) => jetstream
                .create_key_value(kv::Config {
                    bucket: config.hot_bucket.clone(),
                    history: 1,
                    ..Default::default()
                })
                .await
                .map_err(|e| StorageError::Io(format!("create bucket: {e}")))?,
        };

        let flush_notify = Arc::new(tokio::sync::Notify::new());
        let (shutdown_tx, _) = tokio::sync::watch::channel(false);
        let flush_claim_options = hierarchy_claim::ClaimOptions::default();
        let flusher_test_hooks = flusher::FlusherTestHooks::default();

        let shutdown_rx = shutdown_tx.subscribe();
        let flusher_handle = flusher::spawn_flusher(flusher::FlusherLoop {
            inner: Arc::clone(&inner),
            consumer: consumer.clone(),
            kv_hot: kv_hot.clone(),
            config: config.clone(),
            claim_options: flush_claim_options.clone(),
            test_hooks: flusher_test_hooks.clone(),
            flush_notify: Arc::clone(&flush_notify),
            shutdown_rx,
        });

        Ok(Self {
            inner,
            client,
            jetstream,
            stream,
            kv_hot,
            consumer,
            config,
            hierarchy_write_lock: tokio::sync::Mutex::new(()),
            hierarchy_claim_options: hierarchy_claim::ClaimOptions::default(),
            writer_test_hooks: writer::WriterTestHooks::default(),
            flush_claim_options,
            flusher_test_hooks,
            hierarchy_mutation_test_hooks: HierarchyMutationTestHooks::default(),
            flush_notify,
            shutdown_tx,
            flusher_handle: tokio::sync::Mutex::new(Some(flusher_handle)),
        })
    }

    pub async fn shutdown(&self) -> Result<(), StorageError> {
        let flush_result = self.force_flush_all_pending().await;
        let _ = self.shutdown_tx.send(true);
        self.flush_notify.notify_waiters();
        if let Some(handle) = self.flusher_handle.lock().await.take() {
            if flush_result.is_ok() {
                handle
                    .await
                    .map_err(|e| StorageError::Io(format!("flusher task join: {e}")))?;
            } else {
                handle.abort();
            }
        }
        flush_result
    }

    pub async fn force_flush_all_pending(&self) -> Result<(), StorageError> {
        recovery::reconcile_all_thread_tails(self).await?;
        for thread_id in hot_meta::pending_thread_ids(&self.kv_hot).await? {
            self.force_flush(&thread_id).await?;
        }
        Ok(())
    }

    /// Test-only: publish a `CheckpointEntry` to the WAL with a
    /// caller-chosen `thread_seq`, returning the JetStream stream
    /// sequence assigned to the entry. Used to reproduce the
    /// concurrent-writer race where JS arrival order diverges from
    /// reservation order.
    #[doc(hidden)]
    pub async fn __test_plant_wal_entry(
        &self,
        thread_id: &str,
        run: &RunRecord,
        messages: &[Message],
        thread_seq: u64,
    ) -> Result<u64, StorageError> {
        let wal_entry = entry::CheckpointEntry {
            thread_id: thread_id.to_string(),
            run: run.clone(),
            messages: messages.to_vec(),
            projected_thread: None,
            thread_seq,
            written_at: 0,
        };
        let payload = entry::encode(&wal_entry)?;
        let ack = self
            .jetstream
            .publish(keys::thread_subject(thread_id), payload)
            .await
            .map_err(|e| StorageError::Io(format!("publish: {e}")))?
            .await
            .map_err(|e| StorageError::Io(format!("publish ack: {e}")))?;
        wal_state::put_committed_state(&self.kv_hot, thread_id, thread_seq, ack.sequence, 0)
            .await?;
        Ok(ack.sequence)
    }

    /// Test-only: force `ThreadHotMetadata` to specific values, skipping
    /// the CAS-promote guard. Used together with `__test_plant_wal_entry`
    /// to simulate a committed seq/JS-seq pair without running the
    /// writer path.
    #[doc(hidden)]
    pub async fn __test_force_hot_meta(
        &self,
        thread_id: &str,
        reserved_seq: u64,
        latest_seq: u64,
        latest_js_seq: u64,
    ) -> Result<(), StorageError> {
        let meta = hot_meta::ThreadHotMetadata {
            reserved_seq,
            latest_seq,
            latest_js_seq,
            updated_at: 0,
        };
        let bytes = hot_meta::encode_meta(&meta)?;
        self.kv_hot
            .put(keys::hot_meta_key(thread_id), bytes)
            .await
            .map_err(|e| StorageError::Io(format!("kv put: {e}")))?;
        Ok(())
    }

    #[doc(hidden)]
    pub async fn __test_publish_raw_wal(
        &self,
        thread_id: &str,
        payload: &[u8],
    ) -> Result<u64, StorageError> {
        let ack = self
            .jetstream
            .publish(keys::thread_subject(thread_id), payload.to_vec().into())
            .await
            .map_err(|e| StorageError::Io(format!("publish raw WAL: {e}")))?
            .await
            .map_err(|e| StorageError::Io(format!("publish raw WAL ack: {e}")))?;
        Ok(ack.sequence)
    }

    #[doc(hidden)]
    pub async fn __test_list_poison_wal_records(
        &self,
    ) -> Result<Vec<(String, serde_json::Value)>, StorageError> {
        use futures::StreamExt;

        let mut key_stream = self
            .kv_hot
            .keys()
            .await
            .map_err(|error| StorageError::Io(format!("list poison WAL keys: {error}")))?;
        let mut records = Vec::new();
        while let Some(key_result) = key_stream.next().await {
            let key = key_result
                .map_err(|error| StorageError::Io(format!("poison WAL key stream: {error}")))?;
            if !key.starts_with(keys::poison_wal_prefix()) {
                continue;
            }
            let entry = match self.kv_hot.entry(&key).await {
                Ok(Some(entry)) => entry,
                Ok(None) => continue,
                Err(error) => {
                    return Err(StorageError::Io(format!(
                        "load poison WAL entry {key}: {error}"
                    )));
                }
            };
            if matches!(
                entry.operation,
                async_nats::jetstream::kv::Operation::Delete
                    | async_nats::jetstream::kv::Operation::Purge
            ) {
                continue;
            }
            let value = serde_json::from_slice(&entry.value).map_err(|error| {
                StorageError::Serialization(format!(
                    "decode poison WAL entry {key} from kv bucket: {error}"
                ))
            })?;
            records.push((key, value));
        }
        records.sort_by(|left, right| left.0.cmp(&right.0));
        Ok(records)
    }

    #[doc(hidden)]
    pub async fn __test_cache_run_if_newer(
        &self,
        run: &RunRecord,
        thread_seq: u64,
    ) -> Result<(), StorageError> {
        hot_meta::cache_run_if_newer(&self.kv_hot, run, thread_seq).await
    }

    #[doc(hidden)]
    pub async fn __test_read_flushed_seq(&self, thread_id: &str) -> Result<u64, StorageError> {
        hot_meta::read_flushed_seq(&self.kv_hot, thread_id).await
    }

    #[doc(hidden)]
    pub async fn __test_read_wal_js_seq(
        &self,
        thread_id: &str,
        thread_seq: u64,
    ) -> Result<Option<u64>, StorageError> {
        Ok(wal_state::load_state(&self.kv_hot, thread_id, thread_seq)
            .await?
            .and_then(|state| state.js_seq))
    }

    #[doc(hidden)]
    pub async fn __test_read_wal_state(
        &self,
        thread_id: &str,
        thread_seq: u64,
    ) -> Result<Option<(String, Option<u64>)>, StorageError> {
        Ok(wal_state::load_state(&self.kv_hot, thread_id, thread_seq)
            .await?
            .map(|state| {
                let status = match state.status {
                    wal_state::WalEntryStatus::Prepared => "prepared",
                    wal_state::WalEntryStatus::Committed => "committed",
                    wal_state::WalEntryStatus::Aborted => "aborted",
                };
                (status.to_string(), state.js_seq)
            }))
    }

    #[doc(hidden)]
    pub async fn __test_force_flushed_seq(
        &self,
        thread_id: &str,
        seq: u64,
    ) -> Result<(), StorageError> {
        hot_meta::write_flushed_seq(&self.kv_hot, thread_id, seq).await
    }

    #[doc(hidden)]
    pub fn __test_set_hierarchy_claim_timing(&self, lease_ms: u64, renew_interval_ms: Option<u64>) {
        self.hierarchy_claim_options
            .set_for_tests(lease_ms, renew_interval_ms);
    }

    #[doc(hidden)]
    pub fn __test_set_flush_claim_timing(&self, lease_ms: u64, renew_interval_ms: Option<u64>) {
        self.flush_claim_options
            .set_for_tests(lease_ms, renew_interval_ms);
    }

    #[doc(hidden)]
    pub async fn __test_pause_checkpoint_after_wal_publish(
        &self,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.writer_test_hooks
            .set_post_publish_pause(reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_checkpoint_after_post_publish_claim_check(
        &self,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.writer_test_hooks
            .set_post_publish_claim_check_pause(reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_checkpoint_before_wal_publish(
        &self,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.writer_test_hooks
            .set_pre_publish_pause(reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_fail_checkpoint_after_mark_committed(&self, message: impl Into<String>) {
        self.writer_test_hooks
            .set_fail_after_mark_committed(message)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_flusher_after_read_flushed_seq(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.flusher_test_hooks
            .set_pause_after_read_flushed(thread_id, reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_flusher_after_claim_check(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.flusher_test_hooks
            .set_pause_after_claim_check(thread_id, reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_delete_after_inner_delete(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.hierarchy_mutation_test_hooks
            .set_pause_after_inner_delete(thread_id, reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_pause_save_thread_validated_before_inner_save(
        &self,
        thread_id: &str,
        reached: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Notify>,
    ) {
        self.hierarchy_mutation_test_hooks
            .set_pause_before_inner_save_validated(thread_id, reached, release)
            .await;
    }

    #[doc(hidden)]
    pub async fn __test_flush_committed_thread_seqs(
        &self,
        thread_id: &str,
        thread_seqs: &[u64],
    ) -> Result<(), StorageError> {
        let mut entries = Vec::with_capacity(thread_seqs.len());
        for &thread_seq in thread_seqs {
            let state = wal_state::load_state(&self.kv_hot, thread_id, thread_seq)
                .await?
                .ok_or_else(|| {
                    StorageError::NotFound(format!(
                        "WAL state missing for thread={thread_id}, seq={thread_seq}"
                    ))
                })?;
            if state.status != wal_state::WalEntryStatus::Committed {
                return Err(StorageError::Validation(format!(
                    "WAL state not committed for thread={thread_id}, seq={thread_seq}"
                )));
            }
            let js_seq = state.js_seq.ok_or_else(|| {
                StorageError::NotFound(format!(
                    "WAL js_seq missing for thread={thread_id}, seq={thread_seq}"
                ))
            })?;
            let raw = self.stream.get_raw_message(js_seq).await.map_err(|error| {
                StorageError::Io(format!(
                    "load raw WAL entry for thread={thread_id}, seq={thread_seq}: {error}"
                ))
            })?;
            entries.push((entry::decode(&raw.payload)?, js_seq));
        }
        flusher::flush_test_entries(
            &self.inner,
            &self.kv_hot,
            &self.flush_claim_options,
            &self.flusher_test_hooks,
            thread_id,
            entries,
        )
        .await
    }

    #[doc(hidden)]
    pub async fn __test_process_wal_stream_seqs(
        &self,
        thread_id: &str,
        stream_seqs: &[u64],
    ) -> Result<(), StorageError> {
        let mut entries = Vec::with_capacity(stream_seqs.len());
        for &stream_seq in stream_seqs {
            let raw = self.stream.get_raw_message(stream_seq).await.map_err(|error| {
                StorageError::Io(format!(
                    "load raw WAL entry for thread={thread_id}, stream_seq={stream_seq}: {error}"
                ))
            })?;
            let checkpoint = entry::decode(&raw.payload)?;
            if checkpoint.thread_id != thread_id {
                return Err(StorageError::Validation(format!(
                    "WAL stream_seq {stream_seq} belongs to thread={}, not {thread_id}",
                    checkpoint.thread_id
                )));
            }
            entries.push((checkpoint, stream_seq));
        }
        flusher::process_test_entries(
            &self.inner,
            &self.kv_hot,
            &self.flush_claim_options,
            &self.flusher_test_hooks,
            thread_id,
            entries,
        )
        .await
    }

    /// Block until the flusher has drained all pending entries for the given thread.
    pub async fn force_flush(&self, thread_id: &str) -> Result<(), StorageError> {
        recovery::reconcile_thread_tail(self, thread_id).await?;
        let target = hot_meta::read_latest_seq(&self.kv_hot, thread_id).await?;
        if target == 0 {
            return Ok(());
        }
        let timeout = std::time::Duration::from_secs(10);
        let start = std::time::Instant::now();
        loop {
            self.flush_notify.notify_waiters();
            let flushed = hot_meta::read_flushed_seq(&self.kv_hot, thread_id).await?;
            if flushed >= target {
                return Ok(());
            }
            if start.elapsed() >= timeout {
                return Err(StorageError::Io(format!(
                    "force_flush timeout (thread={thread_id}, target={target}, flushed={flushed})"
                )));
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    }

    async fn clear_hot_thread_state(&self, thread_id: &str) -> Result<(), StorageError> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_millis() as u64)
            .unwrap_or(0);
        let watermark = hot_meta::write_delete_tombstone(&self.kv_hot, thread_id, now).await?;

        if watermark == 0 {
            for key in [
                keys::hot_meta_key(thread_id),
                keys::flushed_seq_key(thread_id),
            ] {
                if self
                    .kv_hot
                    .entry(&key)
                    .await
                    .map_err(|error| StorageError::Io(format!("kv entry {key}: {error}")))?
                    .is_none()
                {
                    continue;
                }
                self.kv_hot
                    .delete(&key)
                    .await
                    .map_err(|error| StorageError::Io(format!("kv delete {key}: {error}")))?;
            }
        }

        for state in wal_state::list_thread_states(&self.kv_hot, thread_id).await? {
            wal_state::delete_state(&self.kv_hot, &state.thread_id, state.thread_seq).await?;
        }
        Ok(())
    }
}

#[async_trait]
impl<T: ThreadRunStore + Send + Sync + 'static> ThreadStore for NatsBufferedThreadStore<T> {
    async fn load_thread(&self, thread_id: &str) -> Result<Option<Thread>, StorageError> {
        reader::load_thread(self, thread_id).await
    }
    async fn save_thread(&self, thread: &Thread) -> Result<(), StorageError> {
        self.force_flush(&thread.id).await?;
        self.inner.save_thread(thread).await
    }
    async fn save_thread_validated(&self, thread: &Thread) -> Result<(), StorageError> {
        let _guard = self.hierarchy_write_lock.lock().await;
        self.force_flush_all_pending().await?;
        let claim = hierarchy_claim::acquire(&self.kv_hot, &self.hierarchy_claim_options).await?;
        let result = async {
            self.force_flush_all_pending().await?;
            claim.ensure_current(&self.kv_hot).await?;
            self.hierarchy_mutation_test_hooks
                .pause_before_inner_save_validated_if_configured(&thread.id)
                .await;
            claim.ensure_current(&self.kv_hot).await?;
            self.inner.save_thread_validated(thread).await?;
            claim.ensure_current(&self.kv_hot).await?;
            Ok(())
        }
        .await;
        let release_result = hierarchy_claim::release(&self.kv_hot, claim).await;
        match result {
            Ok(()) => {
                release_result?;
                Ok(())
            }
            Err(error) => {
                if let Err(release_error) = release_result {
                    tracing::warn!(
                        operation = "save_thread_validated",
                        error = %release_error,
                        "failed to release distributed hierarchy claim after operation error"
                    );
                }
                Err(error)
            }
        }
    }
    async fn delete_thread(&self, thread_id: &str) -> Result<(), StorageError> {
        let _guard = self.hierarchy_write_lock.lock().await;
        self.force_flush_all_pending().await?;
        let claim = hierarchy_claim::acquire(&self.kv_hot, &self.hierarchy_claim_options).await?;
        let result = async {
            self.force_flush_all_pending().await?;
            claim.ensure_current(&self.kv_hot).await?;
            self.inner.delete_thread(thread_id).await?;
            self.hierarchy_mutation_test_hooks
                .pause_after_inner_delete_if_configured(thread_id)
                .await;
            claim.ensure_current(&self.kv_hot).await?;
            self.clear_hot_thread_state(thread_id).await?;
            claim.ensure_current(&self.kv_hot).await?;
            Ok(())
        }
        .await;
        let release_result = hierarchy_claim::release(&self.kv_hot, claim).await;
        match result {
            Ok(()) => {
                release_result?;
                Ok(())
            }
            Err(error) => {
                if let Err(release_error) = release_result {
                    tracing::warn!(
                        operation = "delete_thread",
                        error = %release_error,
                        "failed to release distributed hierarchy claim after operation error"
                    );
                }
                Err(error)
            }
        }
    }
    async fn delete_thread_with_strategy(
        &self,
        thread_id: &str,
        strategy: ChildThreadDeleteStrategy,
    ) -> Result<(), StorageError> {
        let _guard = self.hierarchy_write_lock.lock().await;
        self.force_flush_all_pending().await?;
        let claim = hierarchy_claim::acquire(&self.kv_hot, &self.hierarchy_claim_options).await?;
        let result = async {
            self.force_flush_all_pending().await?;
            claim.ensure_current(&self.kv_hot).await?;
            self.inner
                .delete_thread_with_strategy(thread_id, strategy)
                .await?;
            self.hierarchy_mutation_test_hooks
                .pause_after_inner_delete_if_configured(thread_id)
                .await;
            claim.ensure_current(&self.kv_hot).await?;
            self.clear_hot_thread_state(thread_id).await?;
            claim.ensure_current(&self.kv_hot).await?;
            Ok(())
        }
        .await;
        let release_result = hierarchy_claim::release(&self.kv_hot, claim).await;
        match result {
            Ok(()) => {
                release_result?;
                Ok(())
            }
            Err(error) => {
                if let Err(release_error) = release_result {
                    tracing::warn!(
                        operation = "delete_thread_with_strategy",
                        error = %release_error,
                        "failed to release distributed hierarchy claim after operation error"
                    );
                }
                Err(error)
            }
        }
    }
    async fn list_threads(&self, offset: usize, limit: usize) -> Result<Vec<String>, StorageError> {
        reader::list_threads(self, offset, limit).await
    }
    async fn list_threads_query(&self, query: &ThreadQuery) -> Result<ThreadPage, StorageError> {
        reader::list_threads_query(self, query).await
    }
    async fn load_messages(&self, thread_id: &str) -> Result<Option<Vec<Message>>, StorageError> {
        reader::load_messages(self, thread_id).await
    }
    async fn list_message_records(
        &self,
        thread_id: &str,
        query: &MessageQuery,
    ) -> Result<MessagePage, StorageError> {
        let Some(records) = self.load_message_records(thread_id).await? else {
            return Ok(MessagePage::empty());
        };
        Ok(awaken_contract::contract::storage::paginate_message_records(records, query))
    }
    async fn save_messages(
        &self,
        thread_id: &str,
        messages: &[Message],
    ) -> Result<(), StorageError> {
        self.force_flush(thread_id).await?;
        self.inner.save_messages(thread_id, messages).await
    }
    async fn delete_messages(&self, thread_id: &str) -> Result<(), StorageError> {
        self.force_flush(thread_id).await?;
        self.inner.delete_messages(thread_id).await
    }
    async fn update_thread_metadata(
        &self,
        id: &str,
        metadata: ThreadMetadata,
    ) -> Result<(), StorageError> {
        self.force_flush(id).await?;
        self.inner.update_thread_metadata(id, metadata).await
    }
}

#[async_trait]
impl<T: ThreadRunStore + Send + Sync + 'static> RunStore for NatsBufferedThreadStore<T> {
    async fn create_run(&self, record: &RunRecord) -> Result<(), StorageError> {
        self.inner.create_run(record).await
    }
    async fn load_run(&self, run_id: &str) -> Result<Option<RunRecord>, StorageError> {
        reader::load_run(self, run_id).await
    }
    async fn latest_run(&self, thread_id: &str) -> Result<Option<RunRecord>, StorageError> {
        reader::latest_run(self, thread_id).await
    }
    async fn list_runs(&self, query: &RunQuery) -> Result<RunPage, StorageError> {
        reader::list_runs(self, query).await
    }
}

#[async_trait]
impl<T: ThreadRunStore + Send + Sync + 'static> ThreadRunStore for NatsBufferedThreadStore<T> {
    async fn checkpoint(
        &self,
        thread_id: &str,
        messages: &[Message],
        run: &RunRecord,
    ) -> Result<(), StorageError> {
        let _guard = self.hierarchy_write_lock.lock().await;
        let claim = hierarchy_claim::acquire(&self.kv_hot, &self.hierarchy_claim_options).await?;
        let result = writer::checkpoint(self, &claim, thread_id, messages, run).await;
        let release_result = hierarchy_claim::release(&self.kv_hot, claim).await;

        match result {
            Ok(()) => {
                release_result?;
                Ok(())
            }
            Err(error) => {
                if let Err(release_error) = release_result {
                    tracing::warn!(
                        operation = "checkpoint",
                        error = %release_error,
                        "failed to release distributed hierarchy claim after operation error"
                    );
                }
                Err(error)
            }
        }
    }
}