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
//! File-backed readers and their explicit transaction handles.
use std::sync::Arc;
use std::time::Instant;
use async_trait::async_trait;
use khive_storage::error::StorageError;
use khive_storage::types::{PageRequest, SqlRow, SqlStatement, SqlValue};
use khive_storage::StorageCapability;
use tokio::sync::OwnedSemaphorePermit;
use crate::pool::ConnectionPool;
use super::{
acquire_reader_handle_slot, admit_reader_capability_sql, cached_read_transaction_control,
execute_query_interruptibly, execute_query_page_interruptibly, execute_query_row_interruptibly,
open_standalone_reader_on_blocking, run_pool_reader_query, CachedReadTransactionControl,
SlotTimeoutClass,
};
// =============================================================================
// File-backed: pooled SqliteReader with an explicit transaction exception
// =============================================================================
pub(super) const CACHED_READ_TRANSACTION_LABEL: &str = "sql_bridge_cached_read_transaction";
/// Admission and observability guards for one explicit cached-reader
/// transaction. Both guards are installed only after SQLite accepts `BEGIN`
/// and are retained together until SQLite reports autocommit again or the
/// owning connection is closed.
///
/// Field order is deliberate: after [`StandaloneHandle::conn`] closes, the
/// reader permit is returned before the registry evidence disappears. There
/// is therefore no interval in which SQLite can still own the snapshot while
/// the transaction is absent from `tx_registry`.
pub(super) struct CachedReadTransaction {
_slot: OwnedSemaphorePermit,
_tx_handle: khive_storage::tx_registry::TxHandle,
/// When this explicit `BEGIN` was admitted. Read on every subsequent
/// reuse of the owning cached-reader handle (#1846): a transaction whose
/// age has crossed `read_tx_max_age` is rolled back instead of being
/// extended by another call, bounding how long any one reader can pin
/// the WAL snapshot regardless of how many further requests it makes.
opened_at: Instant,
}
pub(super) struct StandaloneHandle {
pub(super) conn: rusqlite::Connection,
/// Present only for a standalone read-write handle, whose one-permit
/// connection budget remains handle-scoped. Read-only connections exist
/// only for explicit deferred transactions and retain reader admission in
/// `read_transaction_slot` until terminal control.
pub(super) _retained_slot: Option<OwnedSemaphorePermit>,
/// Present only while a cached read-only connection owns one explicit
/// multi-call read transaction. Field order is load-bearing: Rust drops
/// `conn` before these guards, so cancellation or handle drop closes the
/// SQLite transaction before returning reader admission or deregistering
/// the transaction span.
pub(super) read_transaction_slot: Option<CachedReadTransaction>,
}
impl StandaloneHandle {
/// Whether this is an idle-cacheable read-only connection rather than a
/// writer connection covered by the handle-scoped writer permit.
pub(super) fn is_cached_reader(&self) -> bool {
self._retained_slot.is_none()
}
pub(super) fn has_read_transaction(&self) -> bool {
self.read_transaction_slot.is_some()
}
}
pub(super) struct SqliteReader {
/// Present only for the ADR-005/ADR-091 explicitly admitted multi-call
/// deferred transaction. Ordinary reads never populate this field and
/// route through `ConnectionPool::reader` for each operation.
pub(super) handle: Option<StandaloneHandle>,
pub(super) pool: Arc<ConnectionPool>,
/// Fail-loud compatibility state after a transaction connection could not
/// be restored safely. `None` normally means "pooled ordinary route";
/// this bit distinguishes that from "exceptional connection consumed".
pub(super) poisoned: bool,
}
pub(super) async fn open_explicit_read_transaction_handle(
pool: Arc<ConnectionPool>,
) -> khive_storage::types::StorageResult<StandaloneHandle> {
let open_slot = crate::await_request_read_phase(
"sql_bridge.reader_open",
acquire_reader_handle_slot(
&pool,
"sql_bridge.reader_open",
SlotTimeoutClass::ReaderContract,
),
)
.await??;
let (conn, open_slot) = crate::await_request_read_phase(
"sql_bridge.reader_open",
open_standalone_reader_on_blocking(pool, open_slot),
)
.await??;
drop(open_slot);
Ok(StandaloneHandle {
conn,
_retained_slot: None,
read_transaction_slot: None,
})
}
impl SqliteReader {
/// Select the standalone path only for a live or newly requested explicit
/// deferred transaction. `false` means the caller must execute this
/// operation through the bounded reader pool.
async fn use_explicit_transaction_handle(
&mut self,
transaction_control: Option<CachedReadTransactionControl>,
operation: &'static str,
) -> khive_storage::types::StorageResult<bool> {
if self.poisoned {
return Err(StorageError::Pool {
operation: operation.into(),
message: "connection already consumed".into(),
});
}
if self.handle.is_some() {
return Ok(true);
}
match transaction_control {
None => Ok(false),
Some(CachedReadTransactionControl::BeginDeferred) => {
self.handle =
Some(open_explicit_read_transaction_handle(Arc::clone(&self.pool)).await?);
Ok(true)
}
Some(CachedReadTransactionControl::Finish(keyword))
| Some(CachedReadTransactionControl::Unsupported(keyword)) => {
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: format!(
"cached read-only handle has no admitted transaction for transaction \
control ({keyword})"
),
})
}
}
}
/// A standalone connection exists only for one explicit transaction.
/// Close it immediately after a failed BEGIN, COMMIT/ROLLBACK, age
/// eviction, or cancellation cleanup restores autocommit. A later
/// ordinary query must return to pooled routing instead of silently
/// retaining a standalone cache.
fn close_inactive_transaction_handle(&mut self) {
if self
.handle
.as_ref()
.is_some_and(|handle| handle.is_cached_reader() && !handle.has_read_transaction())
{
drop(self.handle.take());
}
}
}
/// Run one file-backed read while coupling its connection state to the active
/// reader permit.
///
/// This path serves only the explicit deferred read-transaction exception and
/// reader-supertrait calls on a standalone read-write handle. Ordinary
/// read-only traffic uses [`run_pool_reader_query`]. A successful top-level
/// deferred `BEGIN` moves its operation permit into the handle; subsequent
/// reads reuse it until `COMMIT`/`END`/`ROLLBACK` restores autocommit. The
/// connection is declared before that retained permit, so dropping or
/// cancelling the handle closes SQLite first and releases admission second.
/// A standalone writer's reader calls still take active-reader admission; once
/// its connection is outside autocommit, the acquisition and SELECT are
/// completion-preserving rather than request-cancellable.
pub(super) async fn execute_standalone_read<R, F>(
handle: &mut Option<StandaloneHandle>,
pool: Arc<ConnectionPool>,
operation: &'static str,
transaction_control: Option<CachedReadTransactionControl>,
read: F,
) -> khive_storage::types::StorageResult<R>
where
R: Send + 'static,
F: FnOnce(
&crate::read_cancellation::InterruptibleReadScope,
&rusqlite::Connection,
bool,
bool,
) -> khive_storage::types::StorageResult<R>
+ Send
+ 'static,
{
if handle.is_none() {
return Err(StorageError::Pool {
operation: operation.into(),
message: "connection already consumed".into(),
});
}
let active_read_transaction = handle
.as_ref()
.is_some_and(|handle| handle.is_cached_reader() && handle.has_read_transaction());
let completion_preserving_writer_transaction = handle
.as_ref()
.is_some_and(|handle| !handle.is_cached_reader() && !handle.conn.is_autocommit());
let mut operation_slot = if active_read_transaction {
None
} else if completion_preserving_writer_transaction {
// A read inside an admitted write transaction still counts against the
// reader budget, but request cancellation cannot skip that admission
// and strand the transaction between statements.
Some(acquire_reader_handle_slot(&pool, operation, SlotTimeoutClass::ReaderContract).await?)
} else {
Some(
crate::await_request_read_phase(
operation,
acquire_reader_handle_slot(&pool, operation, SlotTimeoutClass::ReaderContract),
)
.await??,
)
};
let Some(owned_handle) = handle.take() else {
return Err(StorageError::Pool {
operation: operation.into(),
message: "connection already consumed".into(),
});
};
let origin = pool.origin();
let read_tx_max_age = pool.config().read_tx_max_age;
let (owned_handle, result) = crate::read_cancellation::run_interruptible_read(
StorageCapability::Sql,
operation,
move |scope| {
let mut owned_handle = owned_handle;
let cached_reader = owned_handle.is_cached_reader();
let entered_with_transaction = owned_handle.has_read_transaction();
let entered_autocommit = owned_handle.conn.is_autocommit();
let mut restore_handle = true;
let mut result = if cached_reader && entered_with_transaction && entered_autocommit {
// A connection cannot pin a snapshot in autocommit. Repair the
// admission state before returning the invariant failure.
drop(owned_handle.read_transaction_slot.take());
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "cached read-only handle retained transaction admission after SQLite \
had already returned to autocommit; the stale permit was released"
.into(),
})
} else if cached_reader && !entered_with_transaction && !entered_autocommit {
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "cached read-only handle entered the operation outside autocommit; \
its transaction was rolled back before releasing the reader permit"
.into(),
})
} else if cached_reader
&& entered_with_transaction
&& owned_handle
.read_transaction_slot
.as_ref()
.is_some_and(|tx| tx.opened_at.elapsed() >= read_tx_max_age)
{
// #1846: this handle's admitted read transaction has pinned a
// WAL snapshot for at least `read_tx_max_age` — reject the
// continuation and roll it back instead of extending the pin
// for another call, regardless of what the caller asked for.
crate::checkpoint::note_read_tx_max_age_eviction();
match owned_handle.conn.execute_batch("ROLLBACK") {
Ok(()) if owned_handle.conn.is_autocommit() => {
drop(owned_handle.read_transaction_slot.take());
Err(StorageError::ReadTransactionAgeEvicted {
operation: operation.into(),
max_age_secs: read_tx_max_age.as_secs(),
})
}
Ok(()) => {
restore_handle = false;
Err(StorageError::ReadTransactionAgeEvictionCleanupFailed {
operation: operation.into(),
max_age_secs: read_tx_max_age.as_secs(),
message: "rollback did not restore autocommit".into(),
})
}
Err(error) => {
restore_handle = false;
Err(StorageError::ReadTransactionAgeEvictionCleanupFailed {
operation: operation.into(),
max_age_secs: read_tx_max_age.as_secs(),
message: format!("rollback failed: {error}"),
})
}
}
} else if cached_reader && entered_with_transaction {
match transaction_control {
None | Some(CachedReadTransactionControl::Finish(_)) => {
read(scope, &owned_handle.conn, true, true)
}
Some(CachedReadTransactionControl::BeginDeferred) => {
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "cached read-only handle already owns an admitted read \
transaction; nested BEGIN is not supported"
.into(),
})
}
Some(CachedReadTransactionControl::Unsupported(keyword)) => {
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: format!(
"cached read-only transaction does not support nested or \
write-locking transaction control ({keyword})"
),
})
}
}
} else if cached_reader {
match transaction_control {
None | Some(CachedReadTransactionControl::BeginDeferred) => {
read(scope, &owned_handle.conn, false, true)
}
Some(CachedReadTransactionControl::Finish(keyword))
| Some(CachedReadTransactionControl::Unsupported(keyword)) => {
Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: format!(
"cached read-only handle has no admitted transaction for \
transaction control ({keyword})"
),
})
}
}
} else {
read(scope, &owned_handle.conn, false, entered_autocommit)
};
if scope.cleanup_failed() {
// A connection-global callback that could not be removed may
// fire for an unrelated future borrower. Closing this handle
// is the only safe recovery; its transaction, if any, ends
// before reader admission is released below.
restore_handle = false;
}
// An interrupted explicit read transaction must never be restored to
// the cached handle: it may still own a WAL snapshot and SQLite's
// interrupted flag applies to the transaction as a whole. Roll back
// before releasing its retained admission; if rollback cannot prove
// autocommit, discard the connection.
if cached_reader
&& matches!(result, Err(StorageError::Timeout { .. }))
&& !owned_handle.conn.is_autocommit()
{
match owned_handle.conn.execute_batch("ROLLBACK") {
Ok(()) if owned_handle.conn.is_autocommit() => {
drop(owned_handle.read_transaction_slot.take());
}
Ok(()) => {
restore_handle = false;
result = Err(StorageError::Transaction {
operation: operation.into(),
message:
"interrupted read transaction rollback did not restore autocommit; \
the connection was discarded"
.into(),
});
}
Err(error) => {
restore_handle = false;
result = Err(StorageError::Transaction {
operation: operation.into(),
message: format!(
"failed to roll back interrupted read transaction ({error}); \
the connection was discarded"
),
});
}
}
}
if cached_reader && entered_with_transaction {
if owned_handle.conn.is_autocommit() {
// SQLite has ended the snapshot; release only after observing
// that terminal state. This also fails closed if an ordinary
// statement unexpectedly ended the transaction.
drop(owned_handle.read_transaction_slot.take());
if result.is_ok()
&& !matches!(
transaction_control,
Some(CachedReadTransactionControl::Finish(_))
)
{
result = Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "cached read-only operation unexpectedly ended its admitted \
transaction; reader admission was released after autocommit"
.into(),
});
}
} else if result.is_ok()
&& matches!(
transaction_control,
Some(CachedReadTransactionControl::Finish(_))
)
{
result = Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "transaction-ending control completed but the cached reader \
remained outside autocommit; its reader permit remains retained"
.into(),
});
}
} else if cached_reader
&& entered_autocommit
&& matches!(
transaction_control,
Some(CachedReadTransactionControl::BeginDeferred)
)
&& result.is_ok()
{
if owned_handle.conn.is_autocommit() {
result = Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "deferred BEGIN completed without opening a read transaction"
.into(),
});
} else {
match operation_slot.take() {
Some(slot) => {
let tx_handle = khive_storage::tx_registry::register_scoped(
Some(CACHED_READ_TRANSACTION_LABEL.to_string()),
origin.clone(),
);
owned_handle.read_transaction_slot = Some(CachedReadTransaction {
_slot: slot,
_tx_handle: tx_handle,
opened_at: Instant::now(),
});
}
None => {
result = Err(StorageError::Pool {
operation: operation.into(),
message: "successful cached-reader BEGIN had no operation permit; \
its transaction was rolled back before returning"
.into(),
});
}
}
}
}
// Any non-autocommit state without its retained admission is stale or
// was opened by a statement the transaction classifier did not admit.
if cached_reader
&& owned_handle.read_transaction_slot.is_none()
&& !owned_handle.conn.is_autocommit()
{
match owned_handle.conn.execute_batch("ROLLBACK") {
Ok(()) if owned_handle.conn.is_autocommit() => {
if result.is_ok() {
result = Err(StorageError::InvalidInput {
capability: StorageCapability::Sql,
operation: operation.into(),
message: "cached read-only operation left the connection outside \
autocommit; its transaction was rolled back before \
releasing the reader permit"
.into(),
});
}
}
Ok(()) => {
restore_handle = false;
result = Err(StorageError::Transaction {
operation: operation.into(),
message: "ROLLBACK completed but the cached reader remained outside \
autocommit; the connection was discarded before releasing \
the reader permit"
.into(),
});
}
Err(error) => {
restore_handle = false;
result = Err(StorageError::Transaction {
operation: operation.into(),
message: format!(
"failed to roll back a cached reader outside autocommit ({error}); \
the connection was discarded before releasing the reader permit"
),
});
}
}
}
let owned_handle = if restore_handle {
Some(owned_handle)
} else {
// Closing the poisoned connection ends any remaining transaction.
// This must precede the active-reader permit release below.
drop(owned_handle);
None
};
// For ordinary reads and rejected controls this is the operation
// permit. A successful BEGIN moved it into `owned_handle`; poisoned
// handles were closed above before this remaining permit is released.
drop(operation_slot);
Ok((owned_handle, result))
},
)
.await?;
*handle = owned_handle;
result
}
#[async_trait]
impl khive_storage::SqlReader for SqliteReader {
async fn query_row(
&mut self,
statement: SqlStatement,
) -> khive_storage::types::StorageResult<Option<SqlRow>> {
let transaction_control = cached_read_transaction_control(&statement.sql);
admit_reader_capability_sql(&statement, transaction_control, "query_row")?;
if !self
.use_explicit_transaction_handle(transaction_control, "query_row")
.await?
{
return run_pool_reader_query(
Arc::clone(&self.pool),
"query_row",
move |scope, conn| {
execute_query_row_interruptibly(
scope,
conn,
&statement,
"query_row",
false,
true,
)
},
)
.await;
}
let result = execute_standalone_read(
&mut self.handle,
Arc::clone(&self.pool),
"query_row",
transaction_control,
move |scope, conn, rollback, interruptible| {
execute_query_row_interruptibly(
scope,
conn,
&statement,
"query_row",
rollback,
interruptible,
)
},
)
.await;
if self.handle.is_none() {
self.poisoned = true;
}
self.close_inactive_transaction_handle();
result
}
async fn query_all(
&mut self,
statement: SqlStatement,
) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
let transaction_control = cached_read_transaction_control(&statement.sql);
admit_reader_capability_sql(&statement, transaction_control, "query_all")?;
if !self
.use_explicit_transaction_handle(transaction_control, "query_all")
.await?
{
return run_pool_reader_query(
Arc::clone(&self.pool),
"query_all",
move |scope, conn| {
execute_query_interruptibly(scope, conn, &statement, "query_all", false, true)
},
)
.await;
}
let result = execute_standalone_read(
&mut self.handle,
Arc::clone(&self.pool),
"query_all",
transaction_control,
move |scope, conn, rollback, interruptible| {
execute_query_interruptibly(
scope,
conn,
&statement,
"query_all",
rollback,
interruptible,
)
},
)
.await;
if self.handle.is_none() {
self.poisoned = true;
}
self.close_inactive_transaction_handle();
result
}
async fn query_page(
&mut self,
statement: SqlStatement,
page: PageRequest,
) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
let transaction_control = cached_read_transaction_control(&statement.sql);
admit_reader_capability_sql(&statement, transaction_control, "query_page")?;
if !self
.use_explicit_transaction_handle(transaction_control, "query_page")
.await?
{
return run_pool_reader_query(
Arc::clone(&self.pool),
"query_page",
move |scope, conn| {
execute_query_page_interruptibly(
scope,
conn,
&statement,
&page,
"query_page",
false,
true,
)
},
)
.await;
}
let result = execute_standalone_read(
&mut self.handle,
Arc::clone(&self.pool),
"query_page",
transaction_control,
move |scope, conn, rollback, interruptible| {
execute_query_page_interruptibly(
scope,
conn,
&statement,
&page,
"query_page",
rollback,
interruptible,
)
},
)
.await;
if self.handle.is_none() {
self.poisoned = true;
}
self.close_inactive_transaction_handle();
result
}
async fn query_scalar(
&mut self,
statement: SqlStatement,
) -> khive_storage::types::StorageResult<Option<SqlValue>> {
let row = self.query_row(statement).await?;
Ok(row.and_then(|r| r.columns.into_iter().next().map(|c| c.value)))
}
async fn explain(
&mut self,
statement: SqlStatement,
) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
let explain_stmt = SqlStatement {
sql: format!("EXPLAIN QUERY PLAN {}", statement.sql),
params: statement.params,
label: statement.label,
};
self.query_all(explain_stmt).await
}
}