1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// SPDX-License-Identifier: BUSL-1.1
//! Transaction lifecycle methods on SessionStore.
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use nodedb_cluster::calvin::types::TxnIdWire;
use crate::types::{Lsn, TxnId, VShardId};
use nodedb_physical::physical_task::PhysicalTask;
use super::read_set::ReadSetEntry;
use super::state::{SavepointEntry, TransactionState};
use super::store::SessionStore;
/// Global monotonic counter minting `TxnId`s across all sessions on this
/// shard. Unique per shard for the lifetime of the process — sufficient
/// for keying the per-transaction staging overlay, which is scoped to a
/// single shard's in-memory state.
static NEXT_TXN_ID: AtomicU64 = AtomicU64::new(1);
impl SessionStore {
/// Get transaction state for a connection.
pub fn transaction_state(&self, addr: &SocketAddr) -> TransactionState {
self.read_session(addr, |s| s.tx_state)
.unwrap_or(TransactionState::Idle)
}
/// BEGIN — enter transaction block with snapshot isolation.
///
/// Captures the current WAL LSN as the local snapshot point (single-shard
/// fast path) and the last globally-applied Calvin `snapshot_epoch` as the
/// cross-shard-valid version anchor. All reads within this transaction see
/// data as of this LSN.
pub fn begin(
&self,
addr: &SocketAddr,
current_lsn: Lsn,
snapshot_epoch: u64,
) -> Result<(), &'static str> {
self.write_session(addr, |session| match session.tx_state {
TransactionState::Idle => {
session.tx_state = TransactionState::InBlock;
session.tx_snapshot_lsn = Some(current_lsn);
session.tx_snapshot_epoch = Some(snapshot_epoch);
session.tx_read_set.clear();
session.tx_reservation_vshards.clear();
session.tx_reservation_owner = None;
session.tx_id = Some(TxnId::new(NEXT_TXN_ID.fetch_add(1, Ordering::Relaxed)));
session.tx_vshards.clear();
Ok(())
}
TransactionState::InBlock => {
// PostgreSQL issues a WARNING here, not an error.
Ok(())
}
TransactionState::Failed => Err(
"current transaction is aborted, commands ignored until end of transaction block",
),
})
.unwrap_or(Ok(()))
}
/// Append captured read-set entries for write conflict detection.
///
/// The single write path behind [`super::read_set::record_read_set`]: the
/// neutral capture helper builds one [`ReadSetEntry`] per observed shard and
/// hands them here. Guarded on the connection being inside a transaction
/// block — outside one, the entries are dropped (autocommit reads never
/// enter validation).
pub fn record_read_entries(&self, addr: &SocketAddr, entries: Vec<ReadSetEntry>) {
if entries.is_empty() {
return;
}
self.write_session(addr, |session| {
if session.tx_state == TransactionState::InBlock {
session.tx_read_set.extend(entries);
}
});
}
/// Whether the connection at `addr` is inside a transaction block. Mirrors
/// the `tx_state == InBlock` gate the read-set recording uses internally, so
/// the hot-key reservation seam can skip autocommit reads without duplicating
/// the predicate.
pub fn is_in_transaction_block(&self, addr: &SocketAddr) -> bool {
self.read_session(addr, |s| s.tx_state == TransactionState::InBlock)
.unwrap_or(false)
}
/// The reservation owner id minted for the current transaction, if a hot-key
/// read has already reserved one. `None` before the first hot-key read (or
/// outside a transaction block). Short lock scope — reads and drops.
pub fn current_reservation_owner(&self, addr: &SocketAddr) -> Option<TxnIdWire> {
self.read_session(addr, |s| s.tx_reservation_owner)
.flatten()
}
/// Record a sequenced SHARED reservation taken on a hot point key. Inserts
/// the reservation's owning `vshard` into the transaction's touched-vShard set
/// and, on the FIRST reservation, adopts `owner` as the transaction's single
/// reservation owner so every later hot-key read reuses the same `lock_owner`.
/// Short lock scope — mutates and drops.
pub fn record_reservation(&self, addr: &SocketAddr, vshard: u32, owner: TxnIdWire) {
self.write_session(addr, |session| {
session.tx_reservation_vshards.insert(vshard);
if session.tx_reservation_owner.is_none() {
session.tx_reservation_owner = Some(owner);
}
});
}
/// Drain the current transaction's read reservations for release. Takes the
/// single reservation `owner` (leaving `None`) and drains the set of distinct
/// vShards it reserved on (leaving empty), returning `(owner, vshards)`. Short
/// lock scope, no await held — the async release routes one
/// `ReleaseReservation` per vShard AFTER this returns. Draining makes a repeat
/// call a no-op, so two graceful-exit paths releasing is idempotent.
pub fn take_reservations(&self, addr: &SocketAddr) -> (Option<TxnIdWire>, Vec<u32>) {
self.write_session(addr, |session| {
let owner = session.tx_reservation_owner.take();
let vshards = std::mem::take(&mut session.tx_reservation_vshards)
.into_iter()
.collect();
(owner, vshards)
})
.unwrap_or((None, Vec::new()))
}
/// Get the snapshot LSN for the current transaction.
pub fn snapshot_lsn(&self, addr: &SocketAddr) -> Option<Lsn> {
self.read_session(addr, |s| s.tx_snapshot_lsn)?
}
/// Get the cross-shard snapshot epoch for the current transaction.
pub fn snapshot_epoch(&self, addr: &SocketAddr) -> Option<u64> {
self.read_session(addr, |s| s.tx_snapshot_epoch)?
}
/// Current transaction's overlay id, for stamping a `StageWrite` task
/// before it is dispatched. `None` outside a transaction block.
pub fn tx_id(&self, addr: &SocketAddr) -> Option<TxnId> {
self.read_session(addr, |s| s.tx_id).flatten()
}
/// Snapshot the current transaction's overlay identity (id + the SET of
/// vShards it has staged writes to) WITHOUT clearing it. Called before
/// `rollback()` releases session state so the caller can dispatch
/// `MetaOp::DropTxnOverlay` to EVERY vShard hosting a staging overlay, and by
/// savepoint mark/rewind to fan the overlay meta-op over all staged vShards.
/// The returned Vec is empty when no write has staged yet.
pub fn txn_identity(&self, addr: &SocketAddr) -> (Option<TxnId>, Vec<VShardId>) {
self.read_session(addr, |s| (s.tx_id, s.tx_vshards.iter().copied().collect()))
.unwrap_or((None, Vec::new()))
}
/// Collect a value from each buffered write task's plan. Used at commit to
/// gather the collections this transaction wrote, so its own reads of those
/// collections are excluded from snapshot-isolation conflict detection
/// (a read-your-own-write is not a serialization conflict).
pub fn buffered_collections<F>(
&self,
addr: &SocketAddr,
extract: F,
) -> std::collections::HashSet<String>
where
F: Fn(&nodedb_physical::physical_plan::PhysicalPlan) -> Option<String>,
{
self.read_session(addr, |s| {
s.tx_buffer
.iter()
.filter_map(|task| extract(&task.plan))
.collect()
})
.unwrap_or_default()
}
/// Clone the current transaction's buffered write tasks WITHOUT consuming
/// them or transitioning session state, so COMMIT can classify dispatch off
/// the buffered writes while still holding the option to `rollback` on a
/// conflict. `commit()` remains the consuming drain.
pub fn buffered_tasks(&self, addr: &SocketAddr) -> Vec<PhysicalTask> {
self.read_session(addr, |s| s.tx_buffer.clone())
.unwrap_or_default()
}
/// Drain the read-set for conflict checking at COMMIT time.
pub fn take_read_set(&self, addr: &SocketAddr) -> Vec<ReadSetEntry> {
self.write_session(addr, |session| std::mem::take(&mut session.tx_read_set))
.unwrap_or_default()
}
/// COMMIT — drain the write buffer and pending offset commits, return to idle.
///
/// Returns the buffered write tasks for atomic dispatch.
pub fn commit(&self, addr: &SocketAddr) -> Result<Vec<PhysicalTask>, &'static str> {
self.write_session(addr, |session| {
let buffer = std::mem::take(&mut session.tx_buffer);
session.tx_state = TransactionState::Idle;
session.tx_snapshot_lsn = None;
session.tx_snapshot_epoch = None;
session.tx_id = None;
session.tx_vshards.clear();
session.tx_reservation_vshards.clear();
session.tx_reservation_owner = None;
session.savepoints.clear();
// Note: pending_sequence_reservations are taken separately via
// take_pending_reservations() so the caller can finalize them
// with the GAP_FREE manager (which requires Arc<SequenceRegistry>).
Ok(buffer)
})
.unwrap_or(Ok(Vec::new()))
}
/// Take pending GAP_FREE sequence reservations (called after successful COMMIT).
pub fn take_pending_reservations(
&self,
addr: &SocketAddr,
) -> Vec<crate::control::sequence::gap_free::ReservationHandle> {
self.write_session(addr, |session| {
std::mem::take(&mut session.pending_sequence_reservations)
})
.unwrap_or_default()
}
/// Take pending offset commits (called after successful COMMIT dispatch).
pub fn take_pending_offsets(&self, addr: &SocketAddr) -> Vec<(u64, String, String, u32, u64)> {
self.write_session(addr, |session| {
std::mem::take(&mut session.pending_offset_commits)
})
.unwrap_or_default()
}
/// Defer an offset commit until the current transaction commits.
///
/// Returns `true` if deferred (in transaction), `false` if not (commit immediately).
pub fn defer_offset_commit(
&self,
addr: &SocketAddr,
tenant_id: u64,
stream: String,
group: String,
partition_id: u32,
lsn: u64,
) -> bool {
self.write_session(addr, |session| {
if session.tx_state == TransactionState::InBlock {
session
.pending_offset_commits
.push((tenant_id, stream, group, partition_id, lsn));
true
} else {
false
}
})
.unwrap_or(false)
}
/// Buffer a write task during a transaction block.
///
/// Stamps the task's `txn_id` from the session's active transaction
/// identity before buffering, inside the same session-lock scope, so
/// there is no separate lock acquisition that could race or deadlock
/// against `buffer_write`'s own lock.
///
/// Returns `true` if buffered (in transaction), `false` if not (dispatch immediately).
pub fn buffer_write(&self, addr: &SocketAddr, mut task: PhysicalTask) -> bool {
self.write_session(addr, |session| {
if session.tx_state == TransactionState::InBlock {
task.txn_id = session.tx_id;
session.tx_vshards.insert(task.vshard_id);
session.tx_buffer.push(task);
true
} else {
false
}
})
.unwrap_or(false)
}
/// ROLLBACK — discard the write buffer and return to idle.
/// Returns any pending GAP_FREE reservations that need to be rolled back.
pub fn rollback(
&self,
addr: &SocketAddr,
) -> Result<Vec<crate::control::sequence::gap_free::ReservationHandle>, &'static str> {
let reservations = self
.write_session(addr, |session| {
session.tx_buffer.clear();
session.tx_state = TransactionState::Idle;
session.tx_snapshot_lsn = None;
session.tx_snapshot_epoch = None;
session.tx_id = None;
session.tx_vshards.clear();
session.tx_read_set.clear();
session.tx_reservation_vshards.clear();
session.tx_reservation_owner = None;
session.savepoints.clear();
session.pending_offset_commits.clear();
std::mem::take(&mut session.pending_sequence_reservations)
})
.unwrap_or_default();
Ok(reservations)
}
/// Mark the current transaction as failed (after a query error inside BEGIN).
pub fn fail_transaction(&self, addr: &SocketAddr) {
self.write_session(addr, |session| {
if session.tx_state == TransactionState::InBlock {
session.tx_state = TransactionState::Failed;
}
});
}
/// Create a savepoint at the current tx_buffer position.
///
/// `markers` maps each vShard that had staged writes at savepoint time to its
/// Data-Plane value/TTL and GRAPH overlay undo-journal lengths (captured via
/// `MetaOp::MarkSavepoint`), so a later ROLLBACK TO can rewind every staging
/// overlay to exactly this point.
pub fn create_savepoint(
&self,
addr: &SocketAddr,
name: String,
markers: BTreeMap<VShardId, (usize, usize)>,
) {
self.write_session(addr, |session| {
let buffer_len = session.tx_buffer.len();
session.savepoints.push(SavepointEntry {
name,
buffer_len,
markers,
});
});
}
/// Release a savepoint: destroy the named savepoint and every savepoint
/// established after it, keeping their buffered/staged effects (PostgreSQL
/// semantics). Returns `Err` (SQLSTATE 3B001) if the name does not exist.
pub fn release_savepoint(&self, addr: &SocketAddr, name: &str) -> crate::Result<()> {
self.write_session(addr, |session| {
let pos = session
.savepoints
.iter()
.rposition(|e| e.name == name)
.ok_or_else(|| crate::Error::BadRequest {
detail: format!("savepoint \"{name}\" does not exist"),
})?;
session.savepoints.truncate(pos);
Ok(())
})
.unwrap_or_else(|| {
Err(crate::Error::BadRequest {
detail: "no active session".to_string(),
})
})
}
/// Rollback to a savepoint: truncate tx_buffer to the saved position and
/// return the per-vShard `(value_marker, graph_marker)` overlay journal
/// markers the caller must rewind each staged vShard's Data-Plane staging
/// overlays to. A vShard first staged AFTER the savepoint is absent from the
/// returned map; the caller rewinds it to `(0, 0)`.
///
/// Returns `Err` if the savepoint does not exist (matches PostgreSQL behavior).
pub fn rollback_to_savepoint(
&self,
addr: &SocketAddr,
name: &str,
) -> crate::Result<BTreeMap<VShardId, (usize, usize)>> {
self.write_session(addr, |session| {
let pos = session
.savepoints
.iter()
.rposition(|e| e.name == name)
.ok_or_else(|| crate::Error::BadRequest {
detail: format!("savepoint \"{name}\" does not exist"),
})?;
let buffer_len = session.savepoints[pos].buffer_len;
let markers = session.savepoints[pos].markers.clone();
session.tx_buffer.truncate(buffer_len);
session.savepoints.truncate(pos + 1);
Ok(markers)
})
.unwrap_or_else(|| {
Err(crate::Error::BadRequest {
detail: "no active session".to_string(),
})
})
}
}