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
//! Lock-context seam: one mutation ordering for facade (`Owned`) and
//! `atomic()` (`Held`). See docs/superpowers/specs/26-07-30-collection-contexts-and-rpc-adapter.md.
use crate::DbResult;
use crate::sync;
/// Shard guards, released in **reverse acquisition order** (LIFO).
///
/// The Map families take the engine shard mutex first and the per-shard index
/// mutex second, and carry both in a `Locked` tuple. A plain `drop` of that
/// tuple releases `.0` before `.1` — the **outer** lock while the inner one is
/// still held. A waiter then takes the engine shard only to park again on the
/// index, turning one wakeup per operation into two. Measured cost when the
/// seam did that: −52% throughput on `typed_map`/`var_map` at eight writers
/// (`armdb/docs/ctx-seam-bench.md`).
///
/// Releasing through this trait instead of `drop` makes the order a property of
/// the guard shape rather than of each family's teardown code, so a family
/// cannot get it wrong — including families added later.
pub(crate) trait ShardGuards {
/// Drop the guards, innermost (acquired last) first.
fn release(self);
}
impl ShardGuards for () {
#[inline]
fn release(self) {}
}
impl<T> ShardGuards for sync::MutexGuard<'_, T> {
#[inline]
fn release(self) {
drop(self);
}
}
/// `.0` is acquired first and `.1` second, so `.1` is released first.
impl<A: ShardGuards, B: ShardGuards> ShardGuards for (A, B) {
#[inline]
fn release(self) {
let (outer, inner) = self;
inner.release();
outer.release();
}
}
pub(crate) trait Family {
/// Mutex guards held for one shard. Family-specific: one for Tree
/// families, two (engine shard + per-shard index) for Maps.
///
/// Released via [`ShardGuards::release`], never `drop` — see the trait.
type Locked<'a>: ShardGuards
where
Self: 'a;
/// Borrowed view of a mutation, produced under the lock. May borrow the
/// caller's input (`&'v [u8]`), which outlives the locked section.
type Event<'v>;
/// Owned form the held context buffers for later replay.
type Owned;
fn lock_shard(&self, sid: usize) -> Self::Locked<'_>;
fn should_sync<'a>(_locked: &Self::Locked<'a>) -> bool
where
Self: 'a,
{
false
}
fn sync(&self, _sid: usize) -> DbResult<()> {
Ok(())
}
fn fire(&self, ev: Self::Event<'_>);
fn own(ev: Self::Event<'_>) -> Self::Owned;
fn fire_owned(&self, ev: &Self::Owned);
}
/// `'l` is a trait parameter — do NOT write `f: impl FnOnce(&mut F::Locked<'_>)`
/// (that HRB forces `F: 'static` via the GAT bound; E0309/E0311).
pub(crate) trait Ctx<'l, F: Family + 'l> {
/// Run `f` under the shard lock, then apply this context's teardown.
///
/// The mutation event leaves through the `&mut Option<Event>` out parameter
/// rather than the return value. Returning `(R, Option<Event>)` instead made
/// the closure hand a fat aggregate back across a generic boundary the
/// optimizer would not collapse, and cost a measurable ~5% on the tightest
/// benchmark row (`const_tree/4`); the out parameter removes it. See
/// `armdb/docs/ctx-seam-bench.md`.
fn with_shard<'v, R>(
&mut self,
family: &'l F,
sid: usize,
f: impl FnOnce(&mut F::Locked<'l>, &mut Option<F::Event<'v>>) -> DbResult<R>,
) -> DbResult<R>;
}
/// Facade context — ZST. Fires borrowed events after unlock; never calls `own`.
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct Owned;
impl<'l, F: Family + 'l> Ctx<'l, F> for Owned {
#[inline]
fn with_shard<'v, R>(
&mut self,
family: &'l F,
sid: usize,
f: impl FnOnce(&mut F::Locked<'l>, &mut Option<F::Event<'v>>) -> DbResult<R>,
) -> DbResult<R> {
let mut locked = family.lock_shard(sid);
let mut ev: Option<F::Event<'v>> = None;
// Not `f(...)?`: an early return would drop the guards through their
// destructor, which for the Map families' tuple is the inverted order.
// `should_sync` stays off the error path so the ctx-gates counts hold.
let r = match f(&mut locked, &mut ev) {
Ok(r) => r,
Err(e) => {
locked.release();
return Err(e);
}
};
let needs_sync = F::should_sync(&locked);
locked.release();
if let Some(ev) = ev {
family.fire(ev);
}
if needs_sync {
family.sync(sid)?;
}
Ok(r)
}
}
/// Held context inside `atomic()` — lock already acquired for `sid`.
pub(crate) struct Held<'a, F: Family + 'a> {
pub locked: F::Locked<'a>,
pub sid: usize,
pub events: Vec<F::Owned>,
}
impl<'a, F: Family + 'a> Ctx<'a, F> for Held<'a, F> {
#[inline]
fn with_shard<'v, R>(
&mut self,
family: &'a F,
sid: usize,
f: impl FnOnce(&mut F::Locked<'a>, &mut Option<F::Event<'v>>) -> DbResult<R>,
) -> DbResult<R> {
if sid != self.sid {
// Callers should check_shard before this; belt-and-suspenders.
return Err(crate::DbError::ShardMismatch);
}
let mut ev: Option<F::Event<'v>> = None;
let r = f(&mut self.locked, &mut ev)?;
if let Some(ev) = ev {
self.events.push(F::own(ev));
}
let _ = family; // sync deferred to atomic() teardown
Ok(r)
}
}
#[cfg(test)]
mod release_order {
use std::cell::RefCell;
use std::rc::Rc;
use super::*;
/// Records its label when released, so a `ShardGuards` release order is
/// observable without depending on timing.
struct Recorder(&'static str, Rc<RefCell<Vec<&'static str>>>);
impl ShardGuards for Recorder {
fn release(self) {
self.1.borrow_mut().push(self.0);
}
}
/// A two-guard `Locked` must release the **inner** guard (acquired last)
/// before the outer one. Releasing the outer first lets a waiter take it and
/// immediately park on the still-held inner guard — two wakeups per
/// operation instead of one, measured at −52% throughput on the Map
/// families at eight writers.
#[test]
fn pair_releases_inner_guard_first() {
let log = Rc::new(RefCell::new(Vec::new()));
let pair = (
Recorder("outer/engine_shard", log.clone()),
Recorder("inner/index", log.clone()),
);
pair.release();
assert_eq!(*log.borrow(), ["inner/index", "outer/engine_shard"]);
}
/// Nested pairs stay LIFO all the way down.
#[test]
fn nested_pairs_release_innermost_first() {
let log = Rc::new(RefCell::new(Vec::new()));
let nested = (
Recorder("a", log.clone()),
(Recorder("b", log.clone()), Recorder("c", log.clone())),
);
nested.release();
assert_eq!(*log.borrow(), ["c", "b", "a"]);
}
/// The real guard pair unlocks both mutexes, in LIFO order: after
/// `release`, both are free.
#[test]
fn real_guard_pair_unlocks_both() {
let engine_shard = sync::Mutex::new(1u32);
let index = sync::Mutex::new(2u32);
let guards = (sync::lock(&engine_shard), sync::lock(&index));
guards.release();
assert!(engine_shard.try_lock().is_some());
assert!(index.try_lock().is_some());
}
}
#[cfg(test)]
mod compile_gate {
use super::*;
struct StubFamily;
impl Family for StubFamily {
type Locked<'a> = ();
type Event<'v> = &'v [u8];
type Owned = Vec<u8>;
fn lock_shard(&self, _sid: usize) -> Self::Locked<'_> {}
fn fire(&self, _ev: Self::Event<'_>) {}
fn own(ev: Self::Event<'_>) -> Self::Owned {
ev.to_vec()
}
fn fire_owned(&self, _ev: &Self::Owned) {}
}
#[test]
fn owned_and_held_seam_compiles() {
let family = StubFamily;
let mut owned = Owned;
owned.with_shard(&family, 0, |_locked, _ev| Ok(())).unwrap();
let locked = family.lock_shard(0);
let mut held = Held {
locked,
sid: 0,
events: Vec::new(),
};
held.with_shard(&family, 0, |_locked, ev| {
*ev = Some(b"x" as &[u8]);
Ok(())
})
.unwrap();
assert_eq!(held.events.len(), 1);
}
}