Skip to main content

hawdb/api/
concurrent.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::sql::{Expr, ExprKind};
16use hawdb_core::{TransactionRetryError, TransactionRetryReason};
17mod autocommit;
18#[cfg(test)]
19pub(crate) use autocommit::AutocommitMutationPhase;
20#[cfg(test)]
21mod composite_lock_tests;
22mod coordinator;
23#[cfg(test)]
24mod graph_preparation_tests;
25#[cfg(test)]
26mod key_range_tests;
27#[cfg(test)]
28mod lock_dependency_tests;
29mod metrics;
30mod owner;
31mod publication;
32mod range_locks;
33
34pub use metrics::{ConcurrentDatabaseMetrics, ConcurrentPhaseMetrics};
35pub(crate) use owner::{SharedDatabaseGuard, SharedDatabaseOwner};
36pub(crate) use publication::PublishedConcurrentRead;
37
38use self::coordinator::{CommitSequencer, LockManager, TransactionIdAllocator};
39use super::system_sql;
40use super::transaction_locks::{
41    GraphAdjacencyDirection, GraphAllocationKind, LockMode, LockRequest, LockTarget,
42    DEFAULT_LOCK_ESCALATION_ENTRIES_PER_TABLE,
43};
44use super::{
45    commit_prepared_database_transaction_state, execute_database_transaction_prepared_sql,
46    Database, DatabaseConfig, DatabaseReadTransaction, DatabaseTransactionRuntime,
47    DatabaseTransactionSqlOptions, DatabaseTransactionState, PreparedGraphTransactionRequest,
48    QueryOutput, StatementExecutionContext, TransactionCommitResult,
49};
50use crate::error::{HawDBError, Result};
51use crate::sql::{
52    SelectStatement, SqlComparisonOp, SqlLockStrength, SqlPredicate, SqlStatement, SqlTableName,
53    SqlValue, UpdateStatement,
54};
55use crate::store::DurabilityPolicy;
56use crate::value::Value;
57use hawdb_core::time::{Duration, Instant};
58pub use hawdb_storage::wal::{
59    WalGroupCommitActivation, WalGroupCommitAdaptiveColdStartEvidence,
60    WalGroupCommitAdaptivePolicyEvidence, WalGroupCommitAdaptiveSteadyStateEvidence,
61    WalGroupCommitConfig, WalGroupCommitDelayPolicy, WalGroupCommitEvidence,
62    WalGroupCommitSnapshot, WalGroupCommitTailLatencyEvidence, WalGroupCommitWaitDecision,
63    DEFAULT_WAL_GROUP_COMMIT_MAX_BYTES, DEFAULT_WAL_GROUP_COMMIT_MAX_DELAY,
64    DEFAULT_WAL_GROUP_COMMIT_MAX_ENTRIES,
65};
66use hawdb_storage::{
67    append_table::AppendTransaction,
68    pressure::StoragePressureSnapshot,
69    projection::StorageRecoveryReport,
70    relational::{
71        RelationalConflictAction, RelationalIndexRole, RelationalKey, RelationalRow,
72        RelationalState, RelationalTableSchema, RelationalTransaction, RelationalValue,
73        RelationalWrite,
74    },
75};
76use std::collections::BTreeMap;
77use std::ops::Bound;
78use std::path::Path;
79#[cfg(test)]
80use std::sync::{mpsc::Sender, Barrier, Condvar};
81use std::sync::{Arc, Mutex};
82
83#[cfg(test)]
84thread_local! {
85    static GRAPH_COMMIT_PREPARATION_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
86}
87
88#[cfg(test)]
89fn set_graph_commit_preparation_hook(hook: Box<dyn FnOnce()>) {
90    GRAPH_COMMIT_PREPARATION_HOOK.with(|slot| *slot.borrow_mut() = Some(hook));
91}
92
93#[cfg(test)]
94thread_local! {
95    static COMMIT_BOUNDARY_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
96}
97
98/// Runs `hook` on this thread once a transaction commit has passed its last
99/// task check, just before the commit is applied.
100#[cfg(test)]
101pub(crate) fn set_commit_boundary_hook(hook: Box<dyn FnOnce()>) {
102    COMMIT_BOUNDARY_HOOK.with(|slot| *slot.borrow_mut() = Some(hook));
103}
104
105pub const DEFAULT_PESSIMISTIC_LOCK_TIMEOUT: Duration = Duration::from_secs(5);
106
107#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
108pub enum ConcurrentTransactionMode {
109    Optimistic,
110    #[default]
111    Pessimistic,
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct ConcurrentTransactionOptions {
116    pub mode: ConcurrentTransactionMode,
117    pub lock_timeout: Duration,
118    pub isolation: super::TransactionIsolation,
119    pub read_dependency_limits: super::TransactionReadDependencyLimits,
120}
121
122impl ConcurrentTransactionOptions {
123    pub const fn with_isolation(mut self, isolation: super::TransactionIsolation) -> Self {
124        self.isolation = isolation;
125        self
126    }
127
128    pub const fn optimistic() -> Self {
129        Self {
130            isolation: super::TransactionIsolation::SnapshotIsolation,
131            read_dependency_limits: super::TransactionReadDependencyLimits::DEFAULT,
132            mode: ConcurrentTransactionMode::Optimistic,
133            lock_timeout: DEFAULT_PESSIMISTIC_LOCK_TIMEOUT,
134        }
135    }
136
137    pub const fn pessimistic(lock_timeout: Duration) -> Self {
138        Self {
139            isolation: super::TransactionIsolation::SnapshotIsolation,
140            read_dependency_limits: super::TransactionReadDependencyLimits::DEFAULT,
141            mode: ConcurrentTransactionMode::Pessimistic,
142            lock_timeout,
143        }
144    }
145}
146
147impl Default for ConcurrentTransactionOptions {
148    fn default() -> Self {
149        Self::pessimistic(DEFAULT_PESSIMISTIC_LOCK_TIMEOUT)
150    }
151}
152
153#[derive(Debug, Clone)]
154pub struct ConcurrentDatabase {
155    inner: Arc<ConcurrentDatabaseInner>,
156}
157
158pub(crate) struct ExclusiveDatabaseLease {
159    inner: Arc<ConcurrentDatabaseInner>,
160    transaction_id: u64,
161}
162
163impl Drop for ExclusiveDatabaseLease {
164    fn drop(&mut self) {
165        self.inner.locks.release(self.transaction_id);
166    }
167}
168
169#[derive(Debug)]
170struct ConcurrentDatabaseInner {
171    commits: CommitSequencer,
172    locks: LockManager,
173    transaction_ids: TransactionIdAllocator,
174    checkpoint_serial: Mutex<()>,
175    #[cfg(test)]
176    autocommit_read_gate: Mutex<Option<AutocommitReadGate>>,
177    #[cfg(test)]
178    autocommit_mutation_gate: Mutex<Option<autocommit::AutocommitMutationGate>>,
179}
180
181#[cfg(test)]
182#[derive(Debug, Clone)]
183struct AutocommitReadGate {
184    snapshot_acquired: Sender<()>,
185    release: Arc<(Mutex<bool>, Condvar)>,
186}
187
188#[derive(Debug)]
189pub struct ConcurrentDatabaseTransaction {
190    inner: Arc<ConcurrentDatabaseInner>,
191    transaction_id: u64,
192    base_commit_epoch: u64,
193    options: ConcurrentTransactionOptions,
194    runtime: DatabaseTransactionRuntime,
195    state: DatabaseTransactionState,
196    // Registered from the canonical owner before any future write can omit
197    // read summaries. Retains the original epoch through incremental locking.
198    lock_dependencies: Option<crate::store::GraphReadDependencies>,
199    successful_statements: usize,
200    abort_reason: Option<TransactionAbortReason>,
201    finished: bool,
202    task_context: Option<hawdb_core::RuntimeTaskContext>,
203    // Dropped after workspace fields; queued requests retain another owner.
204    admission: Option<Arc<hawdb_qos::RuntimePermit>>,
205}
206
207impl ConcurrentDatabase {
208    pub fn new(database: Database) -> Self {
209        Self::new_with_wal_group_commit(database, WalGroupCommitConfig::default())
210    }
211
212    pub fn new_with_wal_group_commit(
213        database: Database,
214        wal_group_commit: WalGroupCommitConfig,
215    ) -> Self {
216        Self::with_sequencer(CommitSequencer::new(database, wal_group_commit))
217    }
218
219    pub(crate) fn with_shared_owner(owner: Arc<dyn SharedDatabaseOwner>) -> Result<Self> {
220        Ok(Self::with_sequencer(CommitSequencer::shared(
221            owner,
222            WalGroupCommitConfig::default(),
223        )?))
224    }
225
226    fn with_sequencer(commits: CommitSequencer) -> Self {
227        Self {
228            inner: Arc::new(ConcurrentDatabaseInner {
229                commits,
230                locks: LockManager::default(),
231                transaction_ids: TransactionIdAllocator::default(),
232                checkpoint_serial: Mutex::new(()),
233                #[cfg(test)]
234                autocommit_read_gate: Mutex::new(None),
235                #[cfg(test)]
236                autocommit_mutation_gate: Mutex::new(None),
237            }),
238        }
239    }
240
241    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
242        Database::open(path).map(Self::new)
243    }
244
245    pub fn open_with_config(path: impl AsRef<Path>, config: DatabaseConfig) -> Result<Self> {
246        Database::open_with_config(path, config).map(Self::new)
247    }
248
249    pub fn open_with_durability(
250        path: impl AsRef<Path>,
251        durability: DurabilityPolicy,
252    ) -> Result<Self> {
253        Database::open_with_durability(path, durability).map(Self::new)
254    }
255
256    pub fn open_with_durability_and_config(
257        path: impl AsRef<Path>,
258        durability: DurabilityPolicy,
259        config: DatabaseConfig,
260    ) -> Result<Self> {
261        Database::open_with_durability_and_config(path, durability, config).map(Self::new)
262    }
263
264    /// Returns the last completed publication, without waiting for an active writer.
265    pub fn commit_epoch(&self) -> Result<u64> {
266        Ok(self.published_read_view()?.visible_commit_epoch())
267    }
268
269    /// Returns the newest commit epoch that changed graph data or schema; see
270    /// [`Database::graph_change_commit_epoch`]. Waits for an active writer.
271    pub fn graph_change_commit_epoch(&self) -> Result<u64> {
272        self.inner.commits.lock()?.graph_change_commit_epoch()
273    }
274
275    /// Includes the physical generation refreshed by completed checkpoints.
276    pub fn published_read_view(&self) -> Result<crate::store::PublishedReadView> {
277        Ok(self
278            .inner
279            .commits
280            .read_view()?
281            .snapshot
282            .0
283            .published_read_view())
284    }
285
286    pub fn wal_group_commit_snapshot(&self) -> Result<WalGroupCommitSnapshot> {
287        self.inner.commits.group_commit_snapshot()
288    }
289
290    /// Enables recording for future coordinator phases and graph executions.
291    /// This is idempotent and shared by cloned handles. Recording starts at
292    /// phase entry; already-active phases are not included retroactively.
293    pub fn enable_concurrency_metrics(&self) {
294        self.inner.commits.metrics.enable();
295    }
296
297    /// Returns cumulative phase timings and graph replay counts without waiting
298    /// for an active writer. Recording is disabled by default; enable it with
299    /// [`Self::enable_concurrency_metrics`]. Clones observe the same counters.
300    pub fn concurrency_metrics(&self) -> ConcurrentDatabaseMetrics {
301        self.inner.commits.metrics.snapshot()
302    }
303
304    #[cfg(test)]
305    pub(crate) fn cancel_after_next_group_flush(
306        &self,
307        token: hawdb_core::RuntimeCancellationToken,
308    ) -> Result<()> {
309        self.inner.commits.cancel_after_next_group_flush(token)
310    }
311
312    #[cfg(test)]
313    pub(crate) fn set_group_commit_post_enqueue_barrier(
314        &self,
315        barrier: Arc<Barrier>,
316    ) -> Result<()> {
317        self.inner
318            .commits
319            .set_group_commit_post_enqueue_barrier(barrier)
320    }
321
322    #[cfg(test)]
323    pub(crate) fn set_group_commit_enqueue_gate(
324        &self,
325        gate: Arc<(Mutex<bool>, Condvar)>,
326    ) -> Result<()> {
327        self.inner.commits.set_group_commit_enqueue_gate(gate)
328    }
329
330    #[cfg(test)]
331    pub(crate) fn set_autocommit_read_gate(
332        &self,
333        snapshot_acquired: Sender<()>,
334        release: Arc<(Mutex<bool>, Condvar)>,
335    ) -> Result<()> {
336        let mut gate = self
337            .inner
338            .autocommit_read_gate
339            .lock()
340            .map_err(|_| autocommit_read_gate_poisoned_error())?;
341        *gate = Some(AutocommitReadGate {
342            snapshot_acquired,
343            release,
344        });
345        Ok(())
346    }
347
348    #[cfg(test)]
349    pub(crate) fn clear_autocommit_read_gate(&self) -> Result<()> {
350        self.inner
351            .autocommit_read_gate
352            .lock()
353            .map_err(|_| autocommit_read_gate_poisoned_error())?
354            .take();
355        Ok(())
356    }
357
358    /// Returns storage debt and cache accounting from the same serialized
359    /// commit view used by writers. The reader epoch excludes the idle internal
360    /// publication, but includes borrowed queries and explicit reader/writer pins.
361    pub fn storage_pressure_snapshot(&self) -> Result<StoragePressureSnapshot> {
362        self.inner.commits.storage_pressure_snapshot()
363    }
364
365    /// Returns the generation-pinned storage residency view without scanning
366    /// candidate artifacts or materializing rows.
367    pub fn storage_residency_report(&self) -> Result<crate::store::StorageResidencyReport> {
368        self.inner.commits.lock()?.storage_residency_report()
369    }
370
371    /// Returns the recovery boundary observed by the currently published
372    /// database handle.
373    pub fn storage_recovery_report(&self) -> Result<StorageRecoveryReport> {
374        self.inner.commits.lock()?.storage_recovery_report()
375    }
376
377    pub fn automatic_checkpoint_report(&self) -> Result<Option<super::AutomaticCheckpointReport>> {
378        self.inner.commits.lock()?.automatic_checkpoint_report()
379    }
380
381    /// Pins the last completed publication while a writer or group sync is active.
382    pub fn begin_read_transaction(&self) -> Result<DatabaseReadTransaction> {
383        let view = self.inner.commits.read_view()?;
384        let snapshot = view.begin_read_transaction();
385        self.inner.commits.finish_read(&view, snapshot)
386    }
387
388    /// Completes a caller-triggered checkpoint through the writer coordinator.
389    ///
390    /// Like [`Database::checkpoint`], this blocking call works below automatic
391    /// thresholds and with background maintenance disabled. A successful return
392    /// follows durable publication of the captured source. It serializes manual
393    /// callers and coordinates with the automatic owner, preserving read pins.
394    /// Concurrent source changes and storage/resource errors remain errors; a
395    /// failed attempt does not undo already committed writes.
396    pub fn checkpoint(&self) -> Result<()> {
397        let _checkpoint_serial = self
398            .inner
399            .checkpoint_serial
400            .lock()
401            .map_err(|_| checkpoint_coordinator_poisoned_error())?;
402        let source = self.inner.commits.lock()?.checkpoint_source()?;
403        let prepared = source.prepare()?;
404        let Some(prepared) = prepared else {
405            let mut database = self.inner.commits.lock()?;
406            let mut runtime = database.runtime.get_mut()?;
407            runtime.store.reclaim_version_history();
408            // Nothing new to publish: still retry object debt left by an
409            // earlier post-publication sweep (#1736).
410            runtime.store.retry_pending_object_reclamation();
411            return Ok(());
412        };
413        self.inner
414            .commits
415            .lock()?
416            .publish_prepared_checkpoint(prepared)
417    }
418
419    /// Runs project reclamation through the writer coordinator. Active readers,
420    /// transactions and checkpoint candidates retain their reachability pins.
421    pub fn reclaim_branch_storage(
422        &self,
423        limits: super::BranchReclamationLimits,
424    ) -> Result<super::BranchReclamationReport> {
425        self.inner.commits.reclaim_branch_storage(limits)
426    }
427
428    /// Reads the last pending-create scan without admitting a data runtime.
429    pub fn branch_create_recovery_report(
430        &self,
431    ) -> Result<Option<super::BranchCreateRecoveryReport>> {
432        Ok(self
433            .inner
434            .commits
435            .lock()?
436            .branch_create_recovery_report()
437            .cloned())
438    }
439
440    /// Retries pending child receipts under the writer coordinator. Existing
441    /// data publications and reader pins are unaffected by metadata recovery.
442    pub fn recover_pending_branch_creates(
443        &self,
444        limits: super::BranchCreateRecoveryLimits,
445    ) -> Result<super::BranchCreateRecoveryReport> {
446        self.inner
447            .commits
448            .lock()?
449            .recover_pending_branch_creates(limits)
450    }
451
452    pub fn begin_transaction(
453        &self,
454        options: ConcurrentTransactionOptions,
455    ) -> Result<ConcurrentDatabaseTransaction> {
456        let transaction_id = self.inner.transaction_ids.allocate()?;
457        self.begin_transaction_with_id(options, transaction_id)
458    }
459
460    fn begin_transaction_with_id(
461        &self,
462        options: ConcurrentTransactionOptions,
463        transaction_id: u64,
464    ) -> Result<ConcurrentDatabaseTransaction> {
465        let database = self.inner.commits.lock()?;
466        let base_commit_epoch = database.commit_epoch()?;
467        let lock_dependencies = capture_lock_dependencies(&database, options)?;
468        Ok(ConcurrentDatabaseTransaction {
469            inner: Arc::clone(&self.inner),
470            transaction_id,
471            base_commit_epoch,
472            options,
473            runtime: DatabaseTransactionRuntime::from_database(&database)?,
474            state: DatabaseTransactionState::from_database_with_isolation(
475                &database,
476                options.isolation,
477                options.read_dependency_limits,
478            )?,
479            lock_dependencies,
480            successful_statements: 0,
481            abort_reason: None,
482            finished: false,
483            task_context: None,
484            admission: None,
485        })
486    }
487
488    /// Begins one transaction using a permit already admitted by the host's
489    /// RuntimeGovernor. The transaction does not acquire a second permit.
490    ///
491    /// Admission precedes snapshot creation and lasts through queued commit,
492    /// durability and result delivery. The caller owns admission waiting and
493    /// must supply a Mutation request with suitable statement/result budgets.
494    /// Existing mutation limits still bound private staging; this permit does
495    /// not account every COW allocation or bound host thread count.
496    pub fn begin_admitted_transaction(
497        &self,
498        options: ConcurrentTransactionOptions,
499        permit: hawdb_qos::RuntimePermit,
500        task_context: hawdb_core::RuntimeTaskContext,
501    ) -> Result<ConcurrentDatabaseTransaction> {
502        if permit.request().kind != hawdb_qos::RuntimeWorkKind::Mutation {
503            return Err(HawDBError::Execution(
504                "concurrent transaction admission requires a mutation permit".into(),
505            ));
506        }
507        let task_context = permit.bind_task_context(task_context);
508        super::query_runtime::query_runtime_checkpoint(Some(&task_context))?;
509        let mut transaction = self.begin_transaction(options)?;
510        super::query_runtime::query_runtime_checkpoint(Some(&task_context))?;
511        transaction.task_context = Some(task_context);
512        transaction.admission = Some(Arc::new(permit));
513        Ok(transaction)
514    }
515
516    pub fn query(&self, cypher_text: &str) -> Result<QueryOutput> {
517        self.query_with_params(cypher_text, &BTreeMap::new())
518    }
519
520    pub fn query_with_params(
521        &self,
522        cypher_text: &str,
523        parameters: &BTreeMap<String, Value>,
524    ) -> Result<QueryOutput> {
525        self.query_request(super::QueryRequest::new(cypher_text).with_params(parameters))
526    }
527
528    pub fn query_request(&self, request: super::QueryRequest<'_>) -> Result<QueryOutput> {
529        super::query_runtime::query_runtime_checkpoint(request.task_context)?;
530        let cypher_text = request.cypher;
531        let started = Instant::now();
532        let view = self.inner.commits.read_view()?;
533        let mut prepared = match view.prepare(request) {
534            Ok(prepared) => prepared,
535            Err(_) => {
536                // Failed preparation cannot prove that the statement is read-only. Re-run it
537                // through the original exclusive path so planning failures retain their
538                // statement-observability behavior and uncertain statements fail closed.
539                drop(view);
540                return self.with_autocommit_exclusive(|database| database.query_request(request));
541            }
542        };
543        if prepared.uses_transaction_kernel() {
544            drop(view);
545            return self
546                .query_prepared_mutation(prepared, request, false, None, None)
547                .map(|(output, _)| output);
548        }
549        if !prepared.uses_read_snapshot() {
550            drop(view);
551            return self.with_autocommit_exclusive(move |database| {
552                database.query_prepared_request(prepared, request)
553            });
554        }
555        let statement_kind = prepared.statement_kind();
556        let parse_nanos = prepared.parse_nanos();
557        let query_identity = prepared.take_query_identity(cypher_text);
558        #[cfg(test)]
559        self.wait_after_autocommit_read_snapshot()?;
560        let result = self
561            .inner
562            .commits
563            .finish_read(&view, view.query_prepared_request(prepared, request));
564        view.recorder.record_statement_execution(
565            "cypher",
566            cypher_text,
567            statement_kind,
568            started,
569            result.as_ref().map(|profiled| &profiled.output),
570            StatementExecutionContext {
571                query_identity: query_identity.as_ref(),
572                execution_profile: result
573                    .as_ref()
574                    .ok()
575                    .map(|profiled| &profiled.execution_profile),
576                retained_profile: None,
577                access_control: request.access_control,
578                parse_nanos,
579            },
580        );
581        self.inner
582            .commits
583            .finish_read(&view, result.map(|profiled| profiled.output))
584    }
585
586    pub fn query_sql(&self, sql_text: &str) -> Result<QueryOutput> {
587        self.query_sql_with_params(sql_text, &[])
588    }
589
590    pub fn query_sql_with_params(
591        &self,
592        sql_text: &str,
593        parameters: &[Value],
594    ) -> Result<QueryOutput> {
595        self.query_sql_request(super::SqlQueryRequest::new(sql_text).with_params(parameters))
596    }
597
598    pub fn query_sql_request(&self, request: super::SqlQueryRequest<'_>) -> Result<QueryOutput> {
599        super::query_runtime::query_runtime_checkpoint(request.task_context)?;
600        let sql_text = request.sql;
601        let started = Instant::now();
602        let prepared = self.inner.commits.prepare_sql(sql_text)?;
603        self.query_prepared_sql_request(request, prepared, started)
604    }
605
606    pub(crate) fn query_prepared_sql_request(
607        &self,
608        request: super::SqlQueryRequest<'_>,
609        prepared: crate::relational_sql::PreparedRelationalSql,
610        started: Instant,
611    ) -> Result<QueryOutput> {
612        super::query_runtime::query_runtime_checkpoint(request.task_context)?;
613        let sql_text = request.sql;
614        if let SqlStatement::Branch(statement) = prepared.statement() {
615            if matches!(statement, crate::sql::BranchSqlStatement::UseBranch(_)) {
616                return Err(HawDBError::BranchCommandUnsupported {
617                    command: "USE BRANCH",
618                    context: "shared concurrent runtime",
619                });
620            }
621            // Catalog statements have no schema/data dependency. Keep them
622            // usable while the default branch is busy or requires repair.
623            #[cfg(test)]
624            if !statement.changes_context_or_catalog() {
625                self.wait_after_autocommit_read_snapshot()?;
626            }
627            return self.with_autocommit_exclusive(|database| {
628                database.query_sql_with_prepared_request(request, prepared)
629            });
630        }
631        let view = self.inner.commits.read_view()?;
632        if !sql_statement_uses_snapshot(prepared.statement()) {
633            return self.query_prepared_sql_mutation(request, prepared, view, started);
634        }
635        let statement_kind = super::observability::sql_statement_kind(prepared.statement());
636        #[cfg(test)]
637        self.wait_after_autocommit_read_snapshot()?;
638        let result = self
639            .inner
640            .commits
641            .finish_read(&view, view.query_sql(request, prepared));
642        view.recorder.record_statement_execution(
643            "sql",
644            sql_text,
645            statement_kind,
646            started,
647            result.as_ref(),
648            StatementExecutionContext::default(),
649        );
650        self.inner.commits.finish_read(&view, result)
651    }
652
653    /// Commits one strict append transaction through the same serialized WAL
654    /// sequencer used by other concurrent writers. When group commit is
655    /// enabled, success is returned only after the shared durability barrier.
656    pub fn append_transaction(&self, transaction: AppendTransaction) -> Result<()> {
657        self.append_transaction_with_result(transaction).map(|_| ())
658    }
659
660    /// Commits a strict append transaction and returns durable generated keys.
661    pub fn append_transaction_with_result(
662        &self,
663        transaction: AppendTransaction,
664    ) -> Result<super::AppendCommitResult> {
665        let committed_result = Arc::new(Mutex::new(None));
666        let result_slot = Arc::clone(&committed_result);
667        self.inner
668            .commits
669            .execute_grouped(move |database| {
670                let result = database.append_transaction_with_result(transaction)?;
671                *result_slot.lock().map_err(|_| {
672                    HawDBError::Execution("concurrent append result slot is poisoned".to_string())
673                })? = Some(result);
674                Ok(QueryOutput {
675                    rows: Vec::new().into(),
676                })
677            })
678            .map(|_| ())?;
679        committed_result
680            .lock()
681            .map_err(|_| {
682                HawDBError::Execution("concurrent append result slot is poisoned".to_string())
683            })?
684            .take()
685            .ok_or_else(|| {
686                HawDBError::Execution(
687                    "concurrent append completed without a commit result".to_string(),
688                )
689            })
690    }
691
692    pub(crate) fn with_autocommit_exclusive(
693        &self,
694        execute: impl FnOnce(&mut Database) -> Result<QueryOutput>,
695    ) -> Result<QueryOutput> {
696        let _lease = self.exclusive_database_lease()?;
697        self.inner
698            .commits
699            .lock()
700            .and_then(|mut database| execute(&mut database))
701    }
702
703    pub(crate) fn exclusive_database_lease(&self) -> Result<ExclusiveDatabaseLease> {
704        let transaction_id = self.inner.transaction_ids.allocate()?;
705        self.inner.locks.acquire(
706            transaction_id,
707            &[LockRequest::database(LockMode::Exclusive)],
708            Instant::now(),
709            DEFAULT_PESSIMISTIC_LOCK_TIMEOUT,
710        )?;
711        Ok(ExclusiveDatabaseLease {
712            inner: Arc::clone(&self.inner),
713            transaction_id,
714        })
715    }
716
717    #[cfg(test)]
718    fn wait_after_autocommit_read_snapshot(&self) -> Result<()> {
719        let gate = self
720            .inner
721            .autocommit_read_gate
722            .lock()
723            .map_err(|_| autocommit_read_gate_poisoned_error())?
724            .clone();
725        if let Some(gate) = gate {
726            gate.snapshot_acquired.send(()).map_err(|_| {
727                HawDBError::Execution(
728                    "concurrent autocommit read gate receiver was dropped".to_string(),
729                )
730            })?;
731            let (released, available) = &*gate.release;
732            let mut released = released
733                .lock()
734                .map_err(|_| autocommit_read_gate_poisoned_error())?;
735            while !*released {
736                released = available
737                    .wait(released)
738                    .map_err(|_| autocommit_read_gate_poisoned_error())?;
739            }
740        }
741        Ok(())
742    }
743}
744
745#[derive(Debug)]
746enum TransactionAbortReason {
747    Retryable(Box<TransactionRetryError>),
748    Other(String),
749}
750
751impl ConcurrentDatabaseTransaction {
752    pub fn read_dependency_usage(&self) -> Option<super::TransactionReadDependencyUsage> {
753        self.state.read_dependency_usage()
754    }
755
756    pub fn transaction_id(&self) -> u64 {
757        self.transaction_id
758    }
759
760    pub fn base_commit_epoch(&self) -> u64 {
761        self.base_commit_epoch
762    }
763
764    /// Returns the graph change commit epoch of this transaction's base
765    /// snapshot (see [`Database::graph_change_commit_epoch`]) and makes the
766    /// commit conditional on it, for compare-and-publish. If a commit that
767    /// changed graph data or schema is published after the base snapshot, this
768    /// transaction's commit fails with the retryable
769    /// `HawDBError::TransactionConflict` whose key is
770    /// [`crate::GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY`] (matched by
771    /// `HawDBError::is_graph_change_conflict`) and writes nothing.
772    /// Relational-only commits never cause that refusal. The
773    /// transaction's own graph writes do not count. Refused with the storage
774    /// error if the database is poisoned, for example after a failed group
775    /// commit durability barrier.
776    pub fn graph_change_commit_epoch(&mut self) -> Result<u64> {
777        self.inner.commits.lock()?.graph_change_commit_epoch()?;
778        Ok(self.state.guard_graph_change_commit_epoch())
779    }
780
781    pub fn mode(&self) -> ConcurrentTransactionMode {
782        self.options.mode
783    }
784
785    pub fn query(&mut self, cypher_text: &str) -> Result<QueryOutput> {
786        self.query_with_params(cypher_text, &BTreeMap::new())
787    }
788
789    pub fn query_with_params(
790        &mut self,
791        cypher_text: &str,
792        parameters: &BTreeMap<String, Value>,
793    ) -> Result<QueryOutput> {
794        self.query_request(super::QueryRequest::new(cypher_text).with_params(parameters))
795    }
796
797    pub fn query_request(&mut self, request: super::QueryRequest<'_>) -> Result<QueryOutput> {
798        let result = self.query_request_inner(request);
799        if result.is_err() {
800            self.state.fail_read_dependencies();
801        }
802        result
803    }
804
805    fn query_request_inner(&mut self, request: super::QueryRequest<'_>) -> Result<QueryOutput> {
806        self.ensure_active()?;
807        let lock_savepoint = (self.options.mode == ConcurrentTransactionMode::Pessimistic)
808            .then(|| self.inner.locks.savepoint(self.transaction_id))
809            .transpose()?;
810        self.inner.commits.metrics.graph_execution();
811        let task = super::query_request::bind_request_context(
812            self.task_context.as_ref(),
813            request.task_context,
814        )?;
815        let request = super::QueryRequest {
816            task_context: task.as_ref(),
817            ..request
818        };
819        let prepared =
820            PreparedGraphTransactionRequest::prepare(&self.runtime, &mut self.state, request)?;
821        let execution = prepared.execute(&self.runtime, &mut self.state);
822        let outcome = match execution {
823            Ok(outcome) => outcome,
824            Err(error) => {
825                if let Some(lock_savepoint) = lock_savepoint {
826                    self.inner
827                        .locks
828                        .restore(self.transaction_id, lock_savepoint);
829                }
830                return Err(error);
831            }
832        };
833        if self.options.mode == ConcurrentTransactionMode::Pessimistic {
834            let requests = graph_lock_requests(&outcome.lock_footprint);
835            if requests.is_empty() {
836                self.successful_statements = self.successful_statements.saturating_add(1);
837                return Ok(outcome.output);
838            }
839            let graph_savepoint = outcome
840                .savepoint
841                .expect("a staged graph mutation must retain its statement savepoint");
842            let covered = if lock_savepoint
843                .as_ref()
844                .is_some_and(coordinator::LockSavepoint::is_empty)
845            {
846                // A first mutation has no reusable locks; avoid a second
847                // lock-manager acquisition just to establish that fact.
848                Ok(false)
849            } else {
850                self.inner.locks.covers_all(self.transaction_id, &requests)
851            };
852            match covered {
853                Ok(true) => {
854                    // This execution already ran under every required lock. Keep
855                    // its staged result and read dependencies; no lock is released
856                    // until this transaction finishes. New targets/upgrades still
857                    // use the acquisition, epoch fence and replay below.
858                    self.inner.commits.metrics.graph_reuse();
859                    self.successful_statements = self.successful_statements.saturating_add(1);
860                    return Ok(outcome.output);
861                }
862                Ok(false) => {}
863                Err(error) => {
864                    self.state.restore_graph_statement(graph_savepoint);
865                    if let Some(lock_savepoint) = lock_savepoint {
866                        self.inner
867                            .locks
868                            .restore(self.transaction_id, lock_savepoint);
869                    }
870                    return Err(error);
871                }
872            }
873            self.state.restore_graph_statement(graph_savepoint);
874            self.acquire_graph_statement_locks(&requests, lock_savepoint.clone())?;
875            self.inner.commits.metrics.graph_replay();
876            // Restoring the statement savepoint preserves the preparation's
877            // schema and parameters. The epoch fence prevents a new snapshot
878            // from being substituted under the already-derived lock set.
879            let replayed = prepared.execute(&self.runtime, &mut self.state);
880            let replayed = match replayed {
881                Ok(replayed) => replayed,
882                Err(error) => {
883                    if let Some(lock_savepoint) = lock_savepoint {
884                        self.inner
885                            .locks
886                            .restore(self.transaction_id, lock_savepoint);
887                    }
888                    return Err(error);
889                }
890            };
891            self.successful_statements = self.successful_statements.saturating_add(1);
892            return Ok(replayed.output);
893        }
894        self.successful_statements = self.successful_statements.saturating_add(1);
895        Ok(outcome.output)
896    }
897
898    pub fn query_sql(&mut self, sql_text: &str) -> Result<QueryOutput> {
899        self.query_sql_with_params(sql_text, &[])
900    }
901
902    pub fn query_sql_with_params(
903        &mut self,
904        sql_text: &str,
905        parameters: &[Value],
906    ) -> Result<QueryOutput> {
907        self.query_sql_with_result_and_params(sql_text, parameters)
908            .map(|result| result.output)
909    }
910
911    /// Executes SQL and returns both PostgreSQL rows and a provisional mutation outcome.
912    pub fn query_sql_with_result(&mut self, sql_text: &str) -> Result<super::SqlStatementResult> {
913        self.query_sql_with_result_and_params(sql_text, &[])
914    }
915
916    /// Parameterized form of [`Self::query_sql_with_result`].
917    pub fn query_sql_with_result_and_params(
918        &mut self,
919        sql_text: &str,
920        parameters: &[Value],
921    ) -> Result<super::SqlStatementResult> {
922        self.query_sql_request_with_result(
923            super::SqlQueryRequest::new(sql_text).with_params(parameters),
924        )
925    }
926
927    pub fn query_sql_request(
928        &mut self,
929        request: super::SqlQueryRequest<'_>,
930    ) -> Result<QueryOutput> {
931        self.query_sql_request_with_result(request)
932            .map(|result| result.output)
933    }
934
935    pub fn query_sql_request_with_result(
936        &mut self,
937        request: super::SqlQueryRequest<'_>,
938    ) -> Result<super::SqlStatementResult> {
939        let result = self.query_sql_request_inner(request);
940        if result.is_err() {
941            self.state.fail_read_dependencies();
942        }
943        result
944    }
945
946    fn query_sql_request_inner(
947        &mut self,
948        request: super::SqlQueryRequest<'_>,
949    ) -> Result<super::SqlStatementResult> {
950        self.ensure_active()?;
951        let task = super::query_request::bind_request_context(
952            self.task_context.as_ref(),
953            request.task_context,
954        )?;
955        super::query_runtime::query_runtime_checkpoint(task.as_ref())?;
956        let sql_text = request.sql;
957        let parameters = request.parameters;
958        if let Some(dependencies) = &mut self.state.read_dependencies {
959            super::query_runtime::query_runtime_checkpoint(task.as_ref())?;
960            dependencies.admit_sql(sql_text, parameters)?;
961        }
962        let prepared = self
963            .runtime
964            .relational_plan_template_cache
965            .prepare(sql_text)?;
966        if self.options.mode == ConcurrentTransactionMode::Pessimistic {
967            self.acquire_sql_locks(&prepared, parameters, task.as_ref())?;
968        } else {
969            reject_optimistic_locking_select(&prepared)?;
970        }
971        self.ensure_active()?;
972        let result = execute_database_transaction_prepared_sql(
973            &self.runtime,
974            &mut self.state,
975            sql_text,
976            prepared,
977            parameters,
978            DatabaseTransactionSqlOptions {
979                allow_system_schema_registry_write: false,
980                allow_locking_select: true,
981                task_context: task.as_ref(),
982                output_limits: request.output_limits,
983                join_planning: request.join_planning,
984            },
985        );
986        if result.is_ok() {
987            self.successful_statements = self.successful_statements.saturating_add(1);
988        }
989        result
990    }
991
992    pub fn commit(self) -> Result<QueryOutput> {
993        self.commit_with_result().map(|result| result.output)
994    }
995
996    /// Commits and returns outcomes recomputed by the serialized commit sequencer.
997    pub fn commit_with_result(mut self) -> Result<TransactionCommitResult> {
998        self.ensure_active()?;
999        if let Some(dependencies) = &self.state.read_dependencies {
1000            dependencies.ensure_complete()?;
1001        }
1002        let started = Instant::now();
1003        if self.options.mode == ConcurrentTransactionMode::Optimistic
1004            && let Err(error) = self.inner.locks.acquire_with_task(
1005                self.transaction_id,
1006                &[LockRequest::database(LockMode::OptimisticCommit)],
1007                started,
1008                self.options.lock_timeout,
1009                self.task_context.as_ref(),
1010            )
1011        {
1012            self.finished = true;
1013            return Err(error.into());
1014        }
1015
1016        let retry_safe_conflict_noop = self.options.mode == ConcurrentTransactionMode::Optimistic
1017            && self.successful_statements == self.state.relational_transaction.writes.len()
1018            && self
1019                .state
1020                .graph_transaction
1021                .as_ref()
1022                .is_some_and(crate::store::GraphMutationTransaction::is_read_only)
1023            && self.state.append_transaction.writes.is_empty()
1024            && self.state.relational_transaction.is_conflict_noop_only();
1025        let allow_stale_rebase =
1026            self.options.mode == ConcurrentTransactionMode::Pessimistic || retry_safe_conflict_noop;
1027        let inner = Arc::clone(&self.inner);
1028        let mut state = self.state.take_for_commit();
1029        super::query_runtime::query_runtime_checkpoint(self.task_context.as_ref())?;
1030        let graph_only = state.relational_transaction.writes.is_empty()
1031            && state.append_transaction.writes.is_empty();
1032        let mut prepared = state
1033            .graph_transaction
1034            .take()
1035            .expect("concurrent transaction owns a graph workspace")
1036            .compact_for_commit(self.runtime.config.mutation_limits)?;
1037        #[cfg(test)]
1038        GRAPH_COMMIT_PREPARATION_HOOK.with(|hook| {
1039            if let Some(hook) = hook.borrow_mut().take() {
1040                hook();
1041            }
1042        });
1043        prepared.encode_graph_wal(graph_only)?;
1044        super::query_runtime::query_runtime_checkpoint(self.task_context.as_ref())?;
1045        let committed_result = Arc::new(Mutex::new(None));
1046        let result_slot = Arc::clone(&committed_result);
1047        let task_context = self.task_context.clone();
1048        let result =
1049            inner
1050                .commits
1051                .execute_grouped_with_admission(self.admission.clone(), move |database| {
1052                    // Cancellation before the commit boundary rejects without WAL.
1053                    // Never turn a durable success into cancellation afterward.
1054                    super::query_runtime::query_runtime_checkpoint(task_context.as_ref())?;
1055                    #[cfg(test)]
1056                    COMMIT_BOUNDARY_HOOK.with(|hook| {
1057                        if let Some(hook) = hook.borrow_mut().take() {
1058                            hook();
1059                        }
1060                    });
1061                    let result = commit_prepared_database_transaction_state(
1062                        database,
1063                        &mut state,
1064                        prepared,
1065                        allow_stale_rebase,
1066                        task_context.as_ref(),
1067                    )?;
1068                    let output = result.output.clone();
1069                    *result_slot.lock().map_err(|_| {
1070                        HawDBError::Execution(
1071                            "concurrent transaction result slot is poisoned".to_string(),
1072                        )
1073                    })? = Some(result);
1074                    Ok(output)
1075                });
1076        self.inner.locks.release(self.transaction_id);
1077        self.finished = true;
1078        result?;
1079        committed_result
1080            .lock()
1081            .map_err(|_| {
1082                HawDBError::Execution("concurrent transaction result slot is poisoned".to_string())
1083            })?
1084            .take()
1085            .ok_or_else(|| {
1086                HawDBError::Execution(
1087                    "concurrent transaction completed without a commit result".to_string(),
1088                )
1089            })
1090    }
1091
1092    pub fn rollback(mut self) {
1093        self.state.rollback();
1094        self.finish_without_commit();
1095    }
1096
1097    fn acquire_locks(&mut self, requests: &[LockRequest]) -> Result<()> {
1098        let started = Instant::now();
1099        let inner = Arc::clone(&self.inner);
1100        let requests_already_covered = inner.locks.covers_all(self.transaction_id, requests)?;
1101        if let Err(error) = inner.locks.acquire_with_task(
1102            self.transaction_id,
1103            requests,
1104            started,
1105            self.options.lock_timeout,
1106            self.task_context.as_ref(),
1107        ) {
1108            let error: HawDBError = error.into();
1109            self.abort_after_lock_failure(&error);
1110            return Err(error);
1111        }
1112
1113        let database = match inner.commits.lock() {
1114            Ok(database) => database,
1115            Err(error) => {
1116                self.abort_after_lock_failure(&error);
1117                return Err(error);
1118            }
1119        };
1120        let current_epoch = database.commit_epoch()?;
1121        if current_epoch != self.base_commit_epoch
1122            // A lock escalation can cover keys that were not validated when
1123            // the table guard was granted. Coverage alone is not proof that a
1124            // later statement's key still belongs to the original snapshot.
1125            && (!requests_already_covered || self.successful_statements != 0)
1126            && self.options.isolation == super::TransactionIsolation::SnapshotIsolation
1127        {
1128            if self.successful_statements == 0 {
1129                // Construct the complete replacement before releasing the old
1130                // history lease or changing any part of the transaction view.
1131                let dependencies = capture_lock_dependencies(&database, self.options)?;
1132                let runtime = DatabaseTransactionRuntime::from_database(&database)?;
1133                let mut state = DatabaseTransactionState::from_database(&database)?;
1134                // A graph change epoch the caller already read stays the
1135                // commit condition; the refreshed snapshot must not reset it.
1136                state.keep_graph_change_guard(&self.state);
1137                self.base_commit_epoch = current_epoch;
1138                self.runtime = runtime;
1139                self.state = state;
1140                self.lock_dependencies = dependencies;
1141            } else {
1142                use crate::store::GraphReadDependencyError;
1143                let validation = database
1144                    .runtime
1145                    .get()
1146                    .map_err(GraphReadDependencyError::Unavailable)
1147                    .and_then(|runtime| match &self.lock_dependencies {
1148                        Some(dependencies) => runtime
1149                            .store
1150                            .validate_locked_snapshot(dependencies, requests),
1151                        None => Err(GraphReadDependencyError::CaptureRefused),
1152                    });
1153                if let Err(error) = validation {
1154                    let error = match error {
1155                        GraphReadDependencyError::Unavailable(error) => error,
1156                        _ => {
1157                            HawDBError::TransactionRetryRequired(Box::new(TransactionRetryError {
1158                                transaction_id: self.transaction_id,
1159                                reason: TransactionRetryReason::SnapshotChanged {
1160                                    read_epoch: self.base_commit_epoch,
1161                                    committed_epoch: current_epoch,
1162                                },
1163                                already_aborted: false,
1164                            }))
1165                        }
1166                    };
1167                    drop(database);
1168                    self.abort_after_lock_failure(&error);
1169                    return Err(error);
1170                }
1171            }
1172        }
1173        Ok(())
1174    }
1175
1176    fn acquire_graph_statement_locks(
1177        &mut self,
1178        requests: &[LockRequest],
1179        lock_savepoint: Option<coordinator::LockSavepoint>,
1180    ) -> Result<()> {
1181        let started = Instant::now();
1182        let inner = Arc::clone(&self.inner);
1183        let requests_already_covered = inner.locks.covers_all(self.transaction_id, requests)?;
1184        if let Err(error) = inner.locks.acquire_with_task(
1185            self.transaction_id,
1186            requests,
1187            started,
1188            self.options.lock_timeout,
1189            self.task_context.as_ref(),
1190        ) {
1191            let abort_transaction = error.aborts_transaction();
1192            let error: HawDBError = error.into();
1193            if let Some(lock_savepoint) = lock_savepoint {
1194                inner.locks.restore(self.transaction_id, lock_savepoint);
1195            }
1196            if abort_transaction {
1197                self.abort_after_lock_failure(&error);
1198            }
1199            return Err(error);
1200        }
1201
1202        let database = match inner.commits.lock() {
1203            Ok(database) => database,
1204            Err(error) => {
1205                self.abort_after_lock_failure(&error);
1206                return Err(error);
1207            }
1208        };
1209        let current_epoch = database.commit_epoch()?;
1210        if current_epoch != self.base_commit_epoch && !requests_already_covered {
1211            // The requests were derived by executing the statement against the
1212            // pinned snapshot. Refreshing here could change the matched graph
1213            // entities and make that access set incomplete. Fail closed and let
1214            // the caller retry from a new transaction instead.
1215            let error = HawDBError::TransactionRetryRequired(Box::new(TransactionRetryError {
1216                transaction_id: self.transaction_id,
1217                reason: TransactionRetryReason::SnapshotChanged {
1218                    read_epoch: self.base_commit_epoch,
1219                    committed_epoch: current_epoch,
1220                },
1221                already_aborted: false,
1222            }));
1223            drop(database);
1224            self.abort_after_lock_failure(&error);
1225            return Err(error);
1226        }
1227        Ok(())
1228    }
1229
1230    fn abort_after_lock_failure(&mut self, error: &HawDBError) {
1231        self.state.rollback();
1232        self.lock_dependencies = None;
1233        self.abort_reason = Some(match error {
1234            HawDBError::TransactionRetryRequired(error) => {
1235                TransactionAbortReason::Retryable(error.clone())
1236            }
1237            _ => TransactionAbortReason::Other(error.to_string()),
1238        });
1239        self.inner.locks.release(self.transaction_id);
1240    }
1241
1242    fn ensure_active(&self) -> Result<()> {
1243        if self.finished {
1244            return Err(HawDBError::Execution(format!(
1245                "concurrent transaction {} is already finished",
1246                self.transaction_id
1247            )));
1248        }
1249        if let Some(reason) = &self.abort_reason {
1250            return Err(match reason {
1251                TransactionAbortReason::Retryable(error) => {
1252                    let mut error = error.clone();
1253                    error.already_aborted = true;
1254                    HawDBError::TransactionRetryRequired(error)
1255                }
1256                TransactionAbortReason::Other(reason) => HawDBError::Execution(format!(
1257                    "concurrent transaction {} is aborted: {reason}",
1258                    self.transaction_id
1259                )),
1260            });
1261        }
1262        super::query_runtime::query_runtime_checkpoint(self.task_context.as_ref())
1263    }
1264
1265    fn finish_without_commit(&mut self) {
1266        if self.finished {
1267            return;
1268        }
1269        self.inner.locks.release(self.transaction_id);
1270        self.finished = true;
1271        self.lock_dependencies = None;
1272    }
1273}
1274
1275fn capture_lock_dependencies(
1276    database: &Database,
1277    options: ConcurrentTransactionOptions,
1278) -> Result<Option<crate::store::GraphReadDependencies>> {
1279    if options.mode == ConcurrentTransactionMode::Pessimistic
1280        && options.isolation == super::TransactionIsolation::SnapshotIsolation
1281    {
1282        // Bounds are validated on demand; only the source lease and history pin
1283        // survive between statements. Serializable uses its existing collector.
1284        database
1285            .runtime
1286            .get()?
1287            .store
1288            .capture_read_dependencies(0, 0)
1289            .map(Some)
1290    } else {
1291        Ok(None)
1292    }
1293}
1294
1295fn reject_optimistic_locking_select(
1296    prepared: &crate::relational_sql::PreparedRelationalSql,
1297) -> Result<()> {
1298    let locking_select = match prepared.statement() {
1299        SqlStatement::Select(select) => select.lock_strength.is_some(),
1300        SqlStatement::Query(query) => query.contains_locking_clause(),
1301        SqlStatement::Explain(explain) => match explain.statement.as_ref() {
1302            SqlStatement::Select(select) => select.lock_strength.is_some(),
1303            SqlStatement::Query(query) => query.contains_locking_clause(),
1304            _ => false,
1305        },
1306        _ => false,
1307    };
1308    if locking_select {
1309        return Err(HawDBError::Semantic(
1310            "FOR UPDATE/SHARE requires a pessimistic concurrent transaction".to_string(),
1311        ));
1312    }
1313    Ok(())
1314}
1315
1316pub(super) fn sql_statement_uses_snapshot(statement: &SqlStatement) -> bool {
1317    match statement {
1318        SqlStatement::Select(select) => select.lock_strength.is_none(),
1319        SqlStatement::Query(query) => !query.contains_locking_clause(),
1320        SqlStatement::Explain(explain) => sql_statement_uses_snapshot(&explain.statement),
1321        SqlStatement::Insert(_)
1322        | SqlStatement::CreateMaterializedView(_)
1323        | SqlStatement::DropMaterializedView(_)
1324        | SqlStatement::CreateSearchIndex(_)
1325        | SqlStatement::DropSearchIndex(_)
1326        | SqlStatement::Update(_)
1327        | SqlStatement::Delete(_)
1328        | SqlStatement::CreateTable(_)
1329        | SqlStatement::CreateIndex(_)
1330        | SqlStatement::AlterTableAddColumn(_) => false,
1331        // Branch catalog inspection uses the immutable read view. Lifecycle
1332        // mutations use the exclusive sequencer; USE BRANCH is rejected before
1333        // routing because a shared runtime cannot change its branch context.
1334        SqlStatement::Branch(statement) => !statement.changes_context_or_catalog(),
1335    }
1336}
1337
1338fn graph_lock_requests(footprint: &crate::store::GraphMutationLockFootprint) -> Vec<LockRequest> {
1339    if footprint.requires_database_lock {
1340        return vec![LockRequest::database(LockMode::Exclusive)];
1341    }
1342    let mut requests = Vec::new();
1343    if footprint.allocates_node_ids {
1344        requests.push(LockRequest::graph_allocation(GraphAllocationKind::Node));
1345    }
1346    if footprint.allocates_relationship_ids {
1347        requests.push(LockRequest::graph_allocation(
1348            GraphAllocationKind::Relationship,
1349        ));
1350    }
1351    requests.extend(footprint.node_label_names.iter().cloned().map(|label| {
1352        LockRequest::graph_label(
1353            if footprint.exclusive_node_label_names.contains(&label) {
1354                LockMode::Exclusive
1355            } else {
1356                LockMode::Shared
1357            },
1358            label,
1359        )
1360    }));
1361    requests.extend(
1362        footprint
1363            .node_label_read_names
1364            .difference(&footprint.node_label_names)
1365            .cloned()
1366            .map(|label| LockRequest::graph_label(LockMode::Shared, label)),
1367    );
1368    requests.extend(
1369        footprint
1370            .relationship_type_names
1371            .iter()
1372            .cloned()
1373            .map(|rel_type| {
1374                LockRequest::graph_relationship_type(
1375                    if footprint
1376                        .exclusive_relationship_type_names
1377                        .contains(&rel_type)
1378                    {
1379                        LockMode::Exclusive
1380                    } else {
1381                        LockMode::Shared
1382                    },
1383                    rel_type,
1384                )
1385            }),
1386    );
1387    requests.extend(
1388        footprint
1389            .node_writes
1390            .iter()
1391            .map(|id| LockRequest::graph_node(LockMode::Exclusive, id.0)),
1392    );
1393    requests.extend(
1394        footprint
1395            .relationship_writes
1396            .iter()
1397            .map(|id| LockRequest::graph_relationship(LockMode::Exclusive, id.0)),
1398    );
1399    requests.extend(
1400        footprint
1401            .node_delete_guard_reads
1402            .difference(&footprint.node_delete_guard_writes)
1403            .map(|id| LockRequest::graph_node_delete_guard(LockMode::Shared, id.0)),
1404    );
1405    requests.extend(
1406        footprint
1407            .node_delete_guard_writes
1408            .iter()
1409            .map(|id| LockRequest::graph_node_delete_guard(LockMode::Exclusive, id.0)),
1410    );
1411    requests.extend(footprint.adjacency_writes.iter().map(|adjacency| {
1412        LockRequest::graph_adjacency(
1413            LockMode::Exclusive,
1414            adjacency.node_id.0,
1415            adjacency.rel_type.map(|rel_type| rel_type.0),
1416            match adjacency.direction {
1417                crate::store::AdjacencyDirection::Outgoing => GraphAdjacencyDirection::Outgoing,
1418                crate::store::AdjacencyDirection::Incoming => GraphAdjacencyDirection::Incoming,
1419            },
1420        )
1421    }));
1422    requests
1423}
1424
1425impl Drop for ConcurrentDatabaseTransaction {
1426    fn drop(&mut self) {
1427        if !self.finished {
1428            self.state.rollback();
1429            self.finish_without_commit();
1430        }
1431    }
1432}
1433
1434fn sql_lock_requests(
1435    prepared: &crate::relational_sql::PreparedRelationalSql,
1436    parameters: &[Value],
1437    state: &RelationalState,
1438    append_state: &hawdb_storage::append_table::AppendState,
1439) -> Result<Vec<LockRequest>> {
1440    if prepared.template.parameters.len() != parameters.len() {
1441        return Err(HawDBError::Semantic(format!(
1442            "PostgreSQL statement requires {} parameters, but {} parameters were supplied",
1443            prepared.template.parameters.len(),
1444            parameters.len()
1445        )));
1446    }
1447    let append_lock_mode = match prepared.statement() {
1448        SqlStatement::Select(select)
1449            if select
1450                .from
1451                .as_ref()
1452                .is_some_and(|from| append_state.schema(&from.name).is_some()) =>
1453        {
1454            Some(LockMode::Shared)
1455        }
1456        SqlStatement::Query(query) => {
1457            let mut uses_append_table = false;
1458            query.visit_selects(&mut |select| {
1459                uses_append_table |= select
1460                    .from
1461                    .as_ref()
1462                    .is_some_and(|from| append_state.schema(&from.name).is_some());
1463            });
1464            uses_append_table.then_some(LockMode::Shared)
1465        }
1466        SqlStatement::Explain(explain) if explain.analyze => match explain.statement.as_ref() {
1467            SqlStatement::Select(select)
1468                if select
1469                    .from
1470                    .as_ref()
1471                    .is_some_and(|from| append_state.schema(&from.name).is_some()) =>
1472            {
1473                Some(LockMode::Shared)
1474            }
1475            SqlStatement::Query(query) => {
1476                let mut uses_append_table = false;
1477                query.visit_selects(&mut |select| {
1478                    uses_append_table |= select
1479                        .from
1480                        .as_ref()
1481                        .is_some_and(|from| append_state.schema(&from.name).is_some());
1482                });
1483                uses_append_table.then_some(LockMode::Shared)
1484            }
1485            _ => None,
1486        },
1487        SqlStatement::Insert(insert) if append_state.schema(&insert.table.name).is_some() => {
1488            Some(LockMode::Exclusive)
1489        }
1490        SqlStatement::Update(update) if append_state.schema(&update.table.name).is_some() => {
1491            Some(LockMode::Exclusive)
1492        }
1493        SqlStatement::Delete(delete) if append_state.schema(&delete.table.name).is_some() => {
1494            Some(LockMode::Exclusive)
1495        }
1496        SqlStatement::CreateIndex(create) if append_state.schema(&create.table.name).is_some() => {
1497            Some(LockMode::Exclusive)
1498        }
1499        SqlStatement::AlterTableAddColumn(alter)
1500            if append_state.schema(&alter.table.name).is_some() =>
1501        {
1502            Some(LockMode::Exclusive)
1503        }
1504        SqlStatement::CreateTable(create)
1505            if matches!(
1506                create.storage,
1507                crate::sql::SqlTableStorage::StrictAppend { .. }
1508            ) =>
1509        {
1510            Some(LockMode::Exclusive)
1511        }
1512        _ => None,
1513    };
1514    if let Some(mode) = append_lock_mode {
1515        return Ok(vec![LockRequest::database(mode)]);
1516    }
1517    match prepared.statement() {
1518        SqlStatement::Select(select) => {
1519            if select.lock_strength.is_some() && system_sql::is_virtual_catalog_select(select) {
1520                return Err(HawDBError::Semantic(
1521                    "system SQL does not support locking clauses".to_string(),
1522                ));
1523            }
1524            Ok(select_lock_requests(select, parameters, state))
1525        }
1526        SqlStatement::Query(query) => {
1527            if query.contains_locking_clause() {
1528                return Err(HawDBError::Semantic(
1529                    "locking clauses are not supported on CTE or set-operation queries".to_string(),
1530                ));
1531            }
1532            Ok(Vec::new())
1533        }
1534        SqlStatement::Explain(explain) => {
1535            if !explain.analyze {
1536                return Ok(Vec::new());
1537            }
1538            match explain.statement.as_ref() {
1539                SqlStatement::Select(select) => Ok(select_lock_requests(select, parameters, state)),
1540                SqlStatement::Query(query) if query.contains_locking_clause() => {
1541                    Err(HawDBError::Semantic(
1542                        "locking clauses are not supported on CTE or set-operation queries"
1543                            .to_string(),
1544                    ))
1545                }
1546                _ => Ok(Vec::new()),
1547            }
1548        }
1549        SqlStatement::Insert(_) => {
1550            let compiled =
1551                crate::relational_sql::compile_prepared_relational_statement_with_result(
1552                    &prepared.template,
1553                    parameters,
1554                    state,
1555                )?;
1556            Ok(insert_lock_requests(&compiled.transaction, state)
1557                .unwrap_or_else(|| vec![LockRequest::database(LockMode::Exclusive)]))
1558        }
1559        SqlStatement::Update(update) => {
1560            crate::relational_sql::compile_prepared_relational_statement_with_result(
1561                &prepared.template,
1562                parameters,
1563                state,
1564            )?;
1565            Ok(update_lock_requests(update, parameters, state))
1566        }
1567        SqlStatement::Delete(delete) => {
1568            crate::relational_sql::compile_prepared_relational_statement_with_result(
1569                &prepared.template,
1570                parameters,
1571                state,
1572            )?;
1573            Ok(delete_lock_requests(delete, parameters, state))
1574        }
1575        SqlStatement::CreateTable(_)
1576        | SqlStatement::CreateMaterializedView(_)
1577        | SqlStatement::DropMaterializedView(_)
1578        | SqlStatement::CreateSearchIndex(_)
1579        | SqlStatement::DropSearchIndex(_)
1580        | SqlStatement::CreateIndex(_)
1581        | SqlStatement::AlterTableAddColumn(_) => {
1582            Ok(vec![LockRequest::database(LockMode::Exclusive)])
1583        }
1584        SqlStatement::Branch(statement) if statement.changes_context_or_catalog() => {
1585            Ok(vec![LockRequest::database(LockMode::Exclusive)])
1586        }
1587        // Only catalog inspection can participate with a shared lock. The
1588        // executor separately rejects lifecycle changes in explicit transactions.
1589        SqlStatement::Branch(_) => Ok(vec![LockRequest::database(LockMode::Shared)]),
1590    }
1591}
1592
1593fn delete_lock_requests(
1594    delete: &crate::sql::DeleteStatement,
1595    parameters: &[Value],
1596    state: &RelationalState,
1597) -> Vec<LockRequest> {
1598    // Parent deletion can cascade into other tables and must coordinate with
1599    // child inserts even when the referenced key is not the primary key.
1600    if state.table_schemas().any(|schema| {
1601        schema
1602            .foreign_keys
1603            .iter()
1604            .any(|key| key.referenced_table == delete.table.name)
1605    }) {
1606        return vec![LockRequest::database(LockMode::Exclusive)];
1607    }
1608    mutation_target_lock_requests(
1609        &delete.table,
1610        delete.alias.as_deref(),
1611        delete.selection.as_ref(),
1612        parameters,
1613        state,
1614    )
1615}
1616
1617fn select_lock_requests(
1618    select: &SelectStatement,
1619    parameters: &[Value],
1620    state: &RelationalState,
1621) -> Vec<LockRequest> {
1622    let Some(strength) = select.lock_strength else {
1623        return Vec::new();
1624    };
1625    let mode = match strength {
1626        SqlLockStrength::Share => LockMode::Shared,
1627        SqlLockStrength::Update => LockMode::Exclusive,
1628    };
1629    if !select.joins.is_empty() {
1630        let mut requests = vec![LockRequest::relational_table(
1631            mode,
1632            select.from_table().name.clone(),
1633        )];
1634        requests.extend(
1635            select
1636                .joins
1637                .iter()
1638                .map(|join| LockRequest::relational_table(mode, join.table.name.clone())),
1639        );
1640        return requests;
1641    }
1642    if !is_public_table(select.from_table()) {
1643        return vec![LockRequest::database(mode)];
1644    }
1645    let Some(schema) = state.table_schema(&select.from_table().name) else {
1646        return vec![LockRequest::database(mode)];
1647    };
1648    if schema.primary_key.is_empty() {
1649        return vec![LockRequest::relational_table(
1650            mode,
1651            select.from_table().name.clone(),
1652        )];
1653    }
1654    if select.selection.is_none() {
1655        // The primary-key domain also validates write intents whose rows did
1656        // not change. Table read summaries alone do not retain those intents.
1657        return vec![LockRequest::relational_range(
1658            mode,
1659            select.from_table().name.clone(),
1660            schema.primary_key.clone(),
1661            Bound::Unbounded,
1662            Bound::Unbounded,
1663        )];
1664    }
1665    range_locks::target_lock_requests(
1666        mode,
1667        select.from_table(),
1668        select.from_alias.as_deref(),
1669        select.selection.as_ref(),
1670        parameters,
1671        schema,
1672    )
1673}
1674
1675fn update_lock_requests(
1676    update: &UpdateStatement,
1677    parameters: &[Value],
1678    state: &RelationalState,
1679) -> Vec<LockRequest> {
1680    let Some(schema) = state.table_schema(&update.table.name) else {
1681        return vec![LockRequest::database(LockMode::Exclusive)];
1682    };
1683    let assignment_changes_constraint_key = update.assignments.iter().any(|assignment| {
1684        schema.primary_key.contains(&assignment.column)
1685            || schema
1686                .unique_constraints
1687                .iter()
1688                .any(|columns| columns.contains(&assignment.column))
1689            || schema
1690                .indexes
1691                .iter()
1692                .any(|index| index.unique && index.columns.contains(&assignment.column))
1693            || schema
1694                .foreign_keys
1695                .iter()
1696                .any(|foreign_key| foreign_key.columns.contains(&assignment.column))
1697    });
1698    if assignment_changes_constraint_key {
1699        return vec![LockRequest::database(LockMode::Exclusive)];
1700    }
1701    // Literal/parameter rekeys can prove their new index entries during bounded
1702    // discovery. Other expressions retain a guard covering both row images.
1703    if update.assignments.iter().any(|assignment| {
1704        schema
1705            .indexes
1706            .iter()
1707            .any(|index| index.columns.contains(&assignment.column))
1708            && !matches!(assignment.value, crate::sql::SqlAssignmentValue::Value(_))
1709    }) {
1710        return vec![LockRequest::relational_table(
1711            LockMode::Exclusive,
1712            update.table.name.clone(),
1713        )];
1714    }
1715    mutation_target_lock_requests(
1716        &update.table,
1717        update.alias.as_deref(),
1718        update.selection.as_ref(),
1719        parameters,
1720        state,
1721    )
1722}
1723
1724fn mutation_target_lock_requests(
1725    table: &SqlTableName,
1726    alias: Option<&str>,
1727    selection: Option<&SqlPredicate>,
1728    parameters: &[Value],
1729    state: &RelationalState,
1730) -> Vec<LockRequest> {
1731    if !is_public_table(table) {
1732        return vec![LockRequest::database(LockMode::Exclusive)];
1733    }
1734    let Some(schema) = state.table_schema(&table.name) else {
1735        return vec![LockRequest::database(LockMode::Exclusive)];
1736    };
1737    range_locks::target_lock_requests(
1738        LockMode::Exclusive,
1739        table,
1740        alias,
1741        selection,
1742        parameters,
1743        schema,
1744    )
1745}
1746
1747fn insert_lock_requests(
1748    transaction: &RelationalTransaction,
1749    state: &RelationalState,
1750) -> Option<Vec<LockRequest>> {
1751    let mut requests = Vec::new();
1752    for write in &transaction.writes {
1753        let (table, rows) = match write {
1754            RelationalWrite::Insert { table, rows, .. } => (table, rows),
1755            RelationalWrite::Upsert {
1756                table,
1757                rows,
1758                action,
1759                ..
1760            } if matches!(action, RelationalConflictAction::DoNothing)
1761                || upsert_update_can_use_insert_locks(write, state) =>
1762            {
1763                (table, rows)
1764            }
1765            _ => return None,
1766        };
1767        let schema = state.table_schema(table)?;
1768        let mut key_columns = Vec::new();
1769        if schema.primary_key.is_empty() {
1770            push_unique_lock_request(
1771                &mut requests,
1772                LockRequest::relational_table(LockMode::Exclusive, table.clone()),
1773            );
1774        } else {
1775            key_columns.push(schema.primary_key.clone());
1776        }
1777        key_columns.extend(schema.unique_constraints.iter().cloned());
1778        key_columns.extend(schema.indexes.iter().map(|index| index.columns.clone()));
1779        for row in rows {
1780            for columns in &key_columns {
1781                let key = relational_row_key(schema, row, columns)?;
1782                push_unique_lock_request(
1783                    &mut requests,
1784                    LockRequest::relational_point(
1785                        LockMode::Exclusive,
1786                        table.clone(),
1787                        columns.clone(),
1788                        key,
1789                    ),
1790                );
1791            }
1792            for foreign_key in &schema.foreign_keys {
1793                let key = relational_row_key(schema, row, &foreign_key.columns)?;
1794                if key.0.iter().any(|value| value == &RelationalValue::Null) {
1795                    continue;
1796                }
1797                push_unique_lock_request(
1798                    &mut requests,
1799                    LockRequest::relational_point(
1800                        LockMode::Shared,
1801                        foreign_key.referenced_table.clone(),
1802                        foreign_key.referenced_columns.clone(),
1803                        key,
1804                    ),
1805                );
1806            }
1807        }
1808    }
1809    Some(requests)
1810}
1811
1812fn upsert_update_can_use_insert_locks(write: &RelationalWrite, state: &RelationalState) -> bool {
1813    let RelationalWrite::Upsert {
1814        table,
1815        rows,
1816        conflict_columns,
1817        action: RelationalConflictAction::Update(_),
1818    } = write
1819    else {
1820        return false;
1821    };
1822    let Some(schema) = state.table_schema(table) else {
1823        return false;
1824    };
1825    let Some(conflict_index) = schema.unique_index_definition(conflict_columns) else {
1826        return false;
1827    };
1828    // Missing entries prove absence only in an authoritative resident map.
1829    if match conflict_index.role {
1830        RelationalIndexRole::Primary => !state.materialized_rows_resident(),
1831        _ => !state.materialized_index_postings_resident(),
1832    } {
1833        return false;
1834    }
1835    let mut seen = std::collections::BTreeSet::new();
1836    rows.iter().all(|row| {
1837        let Some(conflict_key) = relational_row_key(schema, row, conflict_columns) else {
1838            return false;
1839        };
1840        if conflict_key
1841            .0
1842            .iter()
1843            .any(|value| value == &RelationalValue::Null)
1844        {
1845            return true;
1846        }
1847        let absent = match conflict_index.role {
1848            RelationalIndexRole::Primary => state.row(table, &conflict_key).is_none(),
1849            _ => state
1850                .index_prefix_cardinality_at_most(table, &conflict_index.name, &conflict_key, 1)
1851                .is_none_or(|count| count == 0),
1852        };
1853        // A later row in the same batch could update an earlier insertion into
1854        // an index key assembled from both row images, not either insert key.
1855        absent && seen.insert(conflict_key)
1856    })
1857}
1858
1859fn push_unique_lock_request(requests: &mut Vec<LockRequest>, request: LockRequest) {
1860    if !requests.contains(&request) {
1861        requests.push(request);
1862    }
1863}
1864
1865fn relational_row_key(
1866    schema: &RelationalTableSchema,
1867    row: &RelationalRow,
1868    columns: &[String],
1869) -> Option<RelationalKey> {
1870    columns
1871        .iter()
1872        .map(|column| {
1873            schema
1874                .column_position(column)
1875                .and_then(|position| row.values().get(position))
1876                .cloned()
1877        })
1878        .collect::<Option<Vec<_>>>()
1879        .map(RelationalKey)
1880}
1881
1882fn single_key_ranges(
1883    predicate: &SqlPredicate,
1884    schema: &RelationalTableSchema,
1885    table: &SqlTableName,
1886    alias: Option<&str>,
1887    parameters: &[Value],
1888) -> Option<Vec<(Bound<RelationalKey>, Bound<RelationalKey>)>> {
1889    match predicate {
1890        Expr {
1891            kind: ExprKind::And(left, right),
1892            ..
1893        } => {
1894            let left = single_key_ranges(left, schema, table, alias, parameters);
1895            let right = single_key_ranges(right, schema, table, alias, parameters);
1896            match (left, right) {
1897                (Some(left), Some(right)) => Some(
1898                    left.into_iter()
1899                        .flat_map(|left| {
1900                            right
1901                                .iter()
1902                                .filter_map(move |right| intersect_ranges(&left, right))
1903                        })
1904                        .collect(),
1905                ),
1906                // A conjunct can only narrow its sibling's key set. Retain that
1907                // conservative bound even when the residual has no key range.
1908                (Some(ranges), None) | (None, Some(ranges)) => Some(ranges),
1909                (None, None) => None,
1910            }
1911        }
1912        Expr {
1913            kind: ExprKind::Or(left, right),
1914            ..
1915        } => {
1916            let mut ranges = single_key_ranges(left, schema, table, alias, parameters)?;
1917            ranges.extend(single_key_ranges(right, schema, table, alias, parameters)?);
1918            Some(ranges)
1919        }
1920        Expr {
1921            kind: ExprKind::Compare { left, op, right },
1922            ..
1923        } if left
1924            .as_column()
1925            .is_some_and(|left| column_matches(left, &schema.primary_key[0], table, alias)) =>
1926        {
1927            let key = RelationalKey(vec![bind_sql_lock_value(
1928                right.as_value()?,
1929                parameters,
1930                schema.columns[schema.column_position(&schema.primary_key[0])?].scalar_type,
1931            )?]);
1932            match op {
1933                SqlComparisonOp::Eq => {
1934                    Some(vec![(Bound::Included(key.clone()), Bound::Included(key))])
1935                }
1936                SqlComparisonOp::Lt => Some(vec![(Bound::Unbounded, Bound::Excluded(key))]),
1937                SqlComparisonOp::Lte => Some(vec![(Bound::Unbounded, Bound::Included(key))]),
1938                SqlComparisonOp::Gt => Some(vec![(Bound::Excluded(key), Bound::Unbounded)]),
1939                SqlComparisonOp::Gte => Some(vec![(Bound::Included(key), Bound::Unbounded)]),
1940                SqlComparisonOp::NotEq => None,
1941            }
1942        }
1943        Expr {
1944            kind:
1945                ExprKind::InList {
1946                    left,
1947                    values,
1948                    negated: false,
1949                },
1950            ..
1951        } if left
1952            .as_column()
1953            .is_some_and(|left| column_matches(left, &schema.primary_key[0], table, alias)) =>
1954        {
1955            values
1956                .iter()
1957                .map(|value| {
1958                    let key = RelationalKey(vec![bind_sql_lock_value(
1959                        value.as_value()?,
1960                        parameters,
1961                        schema.columns[schema.column_position(&schema.primary_key[0])?].scalar_type,
1962                    )?]);
1963                    Some((Bound::Included(key.clone()), Bound::Included(key)))
1964                })
1965                .collect()
1966        }
1967        _ => None,
1968    }
1969}
1970
1971fn bind_sql_lock_value(
1972    value: &SqlValue,
1973    parameters: &[Value],
1974    scalar_type: hawdb_storage::relational::RelationalScalarType,
1975) -> Option<RelationalValue> {
1976    let value = hawdb_sql::bind_sql_value(value, parameters).ok()?;
1977    let value = hawdb_relational::query_value::value_to_relational_as(value, scalar_type).ok()?;
1978    (value == RelationalValue::Null || scalar_type.same_value_domain(value.scalar_type()))
1979        .then_some(value)
1980}
1981
1982fn column_matches(
1983    column: &crate::sql::SqlColumnRef,
1984    expected: &str,
1985    table: &SqlTableName,
1986    alias: Option<&str>,
1987) -> bool {
1988    column.name == expected
1989        && column
1990            .qualifier
1991            .as_deref()
1992            .is_none_or(|qualifier| Some(qualifier) == alias || qualifier == table.name)
1993}
1994
1995fn is_public_table(table: &SqlTableName) -> bool {
1996    table
1997        .schema
1998        .as_deref()
1999        .is_none_or(|schema| schema.eq_ignore_ascii_case("public"))
2000}
2001
2002fn intersect_ranges(
2003    left: &(Bound<RelationalKey>, Bound<RelationalKey>),
2004    right: &(Bound<RelationalKey>, Bound<RelationalKey>),
2005) -> Option<(Bound<RelationalKey>, Bound<RelationalKey>)> {
2006    let lower = maximum_lower_bound(&left.0, &right.0);
2007    let upper = minimum_upper_bound(&left.1, &right.1);
2008    (!upper_is_before_lower(&upper, &lower)).then_some((lower, upper))
2009}
2010
2011fn maximum_lower_bound(
2012    left: &Bound<RelationalKey>,
2013    right: &Bound<RelationalKey>,
2014) -> Bound<RelationalKey> {
2015    match (left, right) {
2016        (Bound::Unbounded, bound) | (bound, Bound::Unbounded) => bound.clone(),
2017        (Bound::Included(left), Bound::Included(right)) => Bound::Included(left.max(right).clone()),
2018        (Bound::Excluded(left), Bound::Excluded(right)) => Bound::Excluded(left.max(right).clone()),
2019        (Bound::Included(left), Bound::Excluded(right)) => match left.cmp(right) {
2020            std::cmp::Ordering::Greater => Bound::Included(left.clone()),
2021            _ => Bound::Excluded(right.clone()),
2022        },
2023        (Bound::Excluded(left), Bound::Included(right)) => match left.cmp(right) {
2024            std::cmp::Ordering::Less => Bound::Included(right.clone()),
2025            _ => Bound::Excluded(left.clone()),
2026        },
2027    }
2028}
2029
2030fn minimum_upper_bound(
2031    left: &Bound<RelationalKey>,
2032    right: &Bound<RelationalKey>,
2033) -> Bound<RelationalKey> {
2034    match (left, right) {
2035        (Bound::Unbounded, bound) | (bound, Bound::Unbounded) => bound.clone(),
2036        (Bound::Included(left), Bound::Included(right)) => Bound::Included(left.min(right).clone()),
2037        (Bound::Excluded(left), Bound::Excluded(right)) => Bound::Excluded(left.min(right).clone()),
2038        (Bound::Included(left), Bound::Excluded(right)) => match left.cmp(right) {
2039            std::cmp::Ordering::Less => Bound::Included(left.clone()),
2040            _ => Bound::Excluded(right.clone()),
2041        },
2042        (Bound::Excluded(left), Bound::Included(right)) => match left.cmp(right) {
2043            std::cmp::Ordering::Greater => Bound::Included(right.clone()),
2044            _ => Bound::Excluded(left.clone()),
2045        },
2046    }
2047}
2048
2049fn upper_is_before_lower(upper: &Bound<RelationalKey>, lower: &Bound<RelationalKey>) -> bool {
2050    match (upper, lower) {
2051        (Bound::Unbounded, _) | (_, Bound::Unbounded) => false,
2052        (Bound::Included(upper), Bound::Included(lower)) => upper < lower,
2053        (Bound::Included(upper), Bound::Excluded(lower))
2054        | (Bound::Excluded(upper), Bound::Included(lower))
2055        | (Bound::Excluded(upper), Bound::Excluded(lower)) => upper <= lower,
2056    }
2057}
2058
2059fn checkpoint_coordinator_poisoned_error() -> HawDBError {
2060    HawDBError::Execution("concurrent checkpoint coordinator is poisoned".to_string())
2061}
2062
2063#[cfg(test)]
2064fn autocommit_read_gate_poisoned_error() -> HawDBError {
2065    HawDBError::Execution("concurrent autocommit read gate is poisoned".to_string())
2066}
2067
2068#[cfg(test)]
2069mod tests {
2070    use super::*;
2071    use hawdb_storage::{
2072        append_table::{AppendTableSchema, AppendWrite},
2073        relational::{RelationalColumnSchema, RelationalScalarType},
2074    };
2075
2076    fn key(value: i64) -> RelationalKey {
2077        RelationalKey(vec![RelationalValue::BigInt(value)])
2078    }
2079
2080    #[test]
2081    fn intersects_adjacent_half_open_ranges_correctly() {
2082        assert!(intersect_ranges(
2083            &(Bound::Included(key(10)), Bound::Excluded(key(20))),
2084            &(Bound::Included(key(20)), Bound::Included(key(30))),
2085        )
2086        .is_none());
2087        assert_eq!(
2088            intersect_ranges(
2089                &(Bound::Included(key(10)), Bound::Included(key(20))),
2090                &(Bound::Included(key(20)), Bound::Included(key(30))),
2091            ),
2092            Some((Bound::Included(key(20)), Bound::Included(key(20))))
2093        );
2094    }
2095
2096    #[test]
2097    fn concurrent_append_transaction_uses_the_shared_commit_sequencer() {
2098        let path = std::env::temp_dir().join(format!(
2099            "hawdb-concurrent-append-{}-{}",
2100            std::process::id(),
2101            std::time::SystemTime::now()
2102                .duration_since(std::time::UNIX_EPOCH)
2103                .unwrap_or_default()
2104                .as_nanos()
2105        ));
2106        let mut database = Database::open(&path).expect("open append database");
2107        database
2108            .append_transaction(AppendTransaction {
2109                writes: vec![AppendWrite::CreateTable {
2110                    schema: AppendTableSchema {
2111                        name: "events".to_string(),
2112                        columns: vec![
2113                            append_column("stream", RelationalScalarType::Text),
2114                            append_column("sequence", RelationalScalarType::BigInt),
2115                        ],
2116                        partition_key: vec!["stream".to_string()],
2117                        order_key: vec!["sequence".to_string()],
2118                        order_mode: Default::default(),
2119                    },
2120                }],
2121            })
2122            .expect("create append table");
2123        let before = database.commit_epoch().unwrap();
2124        let database = ConcurrentDatabase::new(database);
2125
2126        database
2127            .append_transaction(AppendTransaction {
2128                writes: vec![AppendWrite::Append {
2129                    table: "events".to_string(),
2130                    rows: vec![RelationalRow::new(vec![
2131                        RelationalValue::Text("alpha".to_string()),
2132                        RelationalValue::BigInt(1),
2133                    ])],
2134                }],
2135            })
2136            .expect("commit concurrent append");
2137
2138        assert_eq!(
2139            database.commit_epoch().expect("read commit epoch"),
2140            before + 1
2141        );
2142        drop(database);
2143        std::fs::remove_dir_all(path).expect("remove append database");
2144    }
2145
2146    #[test]
2147    fn append_explain_analyze_takes_a_shared_database_lock() {
2148        let append_state = hawdb_storage::append_table::AppendState::default()
2149            .stage_transaction(
2150                &AppendTransaction {
2151                    writes: vec![AppendWrite::CreateTable {
2152                        schema: AppendTableSchema {
2153                            name: "events".to_string(),
2154                            columns: vec![
2155                                append_column("stream", RelationalScalarType::Text),
2156                                append_column("sequence", RelationalScalarType::BigInt),
2157                            ],
2158                            partition_key: vec!["stream".to_string()],
2159                            order_key: vec!["sequence".to_string()],
2160                            order_mode: Default::default(),
2161                        },
2162                    }],
2163                },
2164                hawdb_storage::append_table::AppendMutationLimits::default(),
2165            )
2166            .expect("stage append schema");
2167
2168        const SQL: &str = "EXPLAIN ANALYZE SELECT * FROM events \
2169                           WHERE stream = 'alpha' ORDER BY sequence LIMIT 10";
2170        let cache = crate::relational_sql::RelationalPlanTemplateCache::new(Some(4));
2171        let prepared = cache.prepare(SQL).expect("prepare append explain analyze");
2172        let requests =
2173            sql_lock_requests(&prepared, &[], &RelationalState::default(), &append_state)
2174                .expect("derive append explain analyze locks");
2175
2176        assert_eq!(requests, vec![LockRequest::database(LockMode::Shared)]);
2177    }
2178
2179    #[test]
2180    fn branch_lifecycle_lock_requests_are_exclusive_while_inspection_is_shared() {
2181        let cache = crate::relational_sql::RelationalPlanTemplateCache::new(Some(8));
2182        for (sql, mode) in [
2183            ("SHOW CURRENT BRANCH", LockMode::Shared),
2184            ("SHOW BRANCH NAME 'main'", LockMode::Shared),
2185            ("SHOW BRANCHES LIMIT 10", LockMode::Shared),
2186            ("USE BRANCH main", LockMode::Exclusive),
2187            (
2188                "CREATE BRANCH child FROM main AT REVISION 1 REQUEST KEY 'key'",
2189                LockMode::Exclusive,
2190            ),
2191            (
2192                "DROP BRANCH ID '00000000-0000-0000-0000-000000000001' AT REVISION 1",
2193                LockMode::Exclusive,
2194            ),
2195        ] {
2196            let prepared = cache.prepare(sql).unwrap();
2197            let requests = sql_lock_requests(
2198                &prepared,
2199                &[],
2200                &RelationalState::default(),
2201                &hawdb_storage::append_table::AppendState::default(),
2202            )
2203            .unwrap();
2204            assert_eq!(requests, vec![LockRequest::database(mode)], "{sql}");
2205        }
2206    }
2207
2208    fn append_column(name: &str, scalar_type: RelationalScalarType) -> RelationalColumnSchema {
2209        RelationalColumnSchema {
2210            name: name.to_string(),
2211            scalar_type,
2212            nullable: false,
2213            default: None,
2214        }
2215    }
2216}