forge
Explore
Log in

Don't you dare go Hollow

🧹 sweep the dead cap helpers the ports orphaned

Browse files at this commit

1bd7851af2f1c7018e0ff3766b08185ea854e764Ahmet Kaan GümüşParent: a290672
  • chore
    • 🧹 sweep the dead cap helpers the ports orphaned
Show full message
chore: 🧹 sweep the dead cap helpers the ports orphaned
src/domain/cap.rsmodified+25 -77
@@ -12,9 +12,10 @@
12 //! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N12 //! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N
13 //! concurrent claimers exactly `cap` get a non-empty result and the rest are13 //! concurrent claimers exactly `cap` get a non-empty result and the rest are
14 //! refused, with no lock and no window. The counter is therefore the14 //! refused, with no lock and no window. The counter is therefore the
15-//! authority on how many slots are taken, and the child rows follow it:15+//! authority on how many slots are taken, and the child rows follow it: the
16-//! [`claim`] before the insert, [`release`] if the insert then fails, and a16+//! claim and the child's insert land in one transaction ([`claim_and_create`]
17-//! decrement in the *same transaction* as every delete of a child row.17+//! and its variants), and a decrement rides the *same transaction* as every
18+//! delete of a child row.
18 //!19 //!
19 //! The counters are `option<int>` columns on the parent table, absent meaning20 //! The counters are `option<int>` columns on the parent table, absent meaning
20 //! zero, so no Rust struct carries them and no whole-row save can clobber one21 //! zero, so no Rust struct carries them and no whole-row save can clobber one
@@ -66,51 +67,28 @@ pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> {
66 /// sentinel no roster will ever reach.67 /// sentinel no roster will ever reach.
67 pub(crate) const UNLIMITED: i64 = i64::MAX;68 pub(crate) const UNLIMITED: i64 = i64::MAX;
68 69
69-/// Take one slot on `parent`'s `field` counter. `false` means the cap is full70+/// Take one slot on `parent`'s `field` counter, and nothing else. `false` means
70-/// (or the parent row is gone) and the caller must refuse β€” nothing was71+/// the cap is full (or the parent row is gone) and the caller must refuse β€”
71-/// written. `field` is always an in-crate constant, never user input.72+/// nothing was written. `field` is always an in-crate constant, never user
73+/// input.
74+///
75+/// **Test-only.** Every production claim now lands its child row in the same
76+/// transaction ([`claim_and_create`] and its variants); a bare claim followed by
77+/// a separate insert is the leak those exist to close. What survives is the
78+/// probe: the appointment tests put the double-book question to this `WHERE`
79+/// directly (a `join!` would ask the in-memory engine instead, which forges
80+/// wins), and staging a taken seat with *no* child row β€” exactly what a booking
81+/// mid-flight looks like β€” is a state no `*_and_create` can produce.
82+#[cfg(test)]
72 pub(crate) async fn claim(83 pub(crate) async fn claim(
73 parent: &RecordId,84 parent: &RecordId,
74 field: &str,85 field: &str,
75 cap: i64,86 cap: i64,
76 db: &Database,87 db: &Database,
77 ) -> Result<bool, AppError> {88 ) -> Result<bool, AppError> {
78- claim_at(parent, field, cap, "", db).await
79-}
80-
81-/// [`claim`], but only while `guard` β€” an extra predicate on that same parent
82-/// row β€” also holds. A caller whose insert has a second precondition (a homework
83-/// submission's file add is refused once the work is graded) gets both decided
84-/// by the one conditional write, instead of by a read a concurrent write can
85-/// outrun.
86-/// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell
87-/// them apart, and only to pick the message. `guard` is always an in-crate SQL
88-/// literal, never user input.
89-pub(crate) async fn claim_when(
90- parent: &RecordId,
91- field: &str,
92- cap: i64,
93- guard: &str,
94- db: &Database,
95-) -> Result<bool, AppError> {
96- claim_at(parent, field, cap, guard, db).await
97-}
98-
99-async fn claim_at(
100- parent: &RecordId,
101- field: &str,
102- cap: i64,
103- extra: &str,
104- db: &Database,
105-) -> Result<bool, AppError> {
106- let extra = if extra.is_empty() {
107- String::new()
108- } else {
109- format!(" AND ({extra})")
110- };
111 let sql = format!(89 let sql = format!(
112 "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \90 "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
113- WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id"91+ WHERE ({field} ?? 0) < $num RETURN VALUE id"
114 );92 );
115 Ok(!write(&sql, parent, cap, db).await?.is_empty())93 Ok(!write(&sql, parent, cap, db).await?.is_empty())
116 }94 }
@@ -148,7 +126,7 @@ pub(crate) enum Claimed<T> {
148 /// Take a slot on `parent`'s `field` counter *and* write the child that fills126 /// Take a slot on `parent`'s `field` counter *and* write the child that fills
149 /// it, in one transaction.127 /// it, in one transaction.
150 ///128 ///
151-/// [`claim`] followed by a separate insert cannot promise this. Where the child129+/// A bare claim followed by a separate insert cannot promise this. Where the child
152 /// carries a deterministic id (one row per pair), two writers placing the *same*130 /// carries a deterministic id (one row per pair), two writers placing the *same*
153 /// pair both pass the claim β€” neither row exists yet β€” so on a tight cap the131 /// pair both pass the claim β€” neither row exists yet β€” so on a tight cap the
154 /// second is told "full" for a seat it was never going to need, and a release132 /// second is told "full" for a seat it was never going to need, and a release
@@ -175,9 +153,10 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>(
175 }153 }
176 154
177 /// [`claim_and_create`], but only while `guard` β€” an extra predicate on that155 /// [`claim_and_create`], but only while `guard` β€” an extra predicate on that
178-/// same parent row β€” also holds, exactly as [`claim_when`] is to [`claim`]: one156+/// same parent row β€” also holds: one conditional write decides the cap *and*
179-/// conditional write decides the cap *and* the caller's second precondition, so157+/// the caller's second precondition (a homework submission's file add is
180-/// no read a concurrent write can outrun sits between them.158+/// refused once the work is graded), so no read a concurrent write can outrun
159+/// sits between them.
181 ///160 ///
182 /// The contract that costs the caller something: [`Claimed::Full`] means "full161 /// The contract that costs the caller something: [`Claimed::Full`] means "full
183 /// **or** the guard failed **or** the parent row is gone" β€” one marker for all162 /// **or** the guard failed **or** the parent row is gone" β€” one marker for all
@@ -301,7 +280,7 @@ pub(crate) enum ClaimedTwo<T> {
301 /// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write280 /// Take a slot on *two* of `parent`'s counters, while `guard` holds, and write
302 /// the child that fills them β€” one transaction, one verdict.281 /// the child that fills them β€” one transaction, one verdict.
303 ///282 ///
304-/// Two [`claim_when`] calls cannot promise this. A parent whose children are283+/// Two separate guarded claims cannot promise this. A parent whose children are
305 /// counted twice β€” once against a resettable working set, once against a284 /// counted twice β€” once against a resettable working set, once against a
306 /// lifetime budget β€” has the two counters describing the same rows, so a writer285 /// lifetime budget β€” has the two counters describing the same rows, so a writer
307 /// that lands one increment and loses the other leaves them disagreeing286 /// that lands one increment and loses the other leaves them disagreeing
@@ -422,15 +401,6 @@ pub(crate) async fn bump(parent: &RecordId, field: &str, db: &Database) -> Resul
422 Ok(())401 Ok(())
423 }402 }
424 403
425-/// Give a claimed slot back, for the insert that never landed. Clamped at zero
426-/// so a double release can never push a counter negative and open the cap.
427-pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {
428- let sql =
429- format!("UPDATE $parent SET {field} = math::max([({field} ?? 0) - 1, 0]) RETURN VALUE id");
430- write(&sql, parent, UNLIMITED, db).await?;
431- Ok(())
432-}
433-
434 // --- reference counters --------------------------------------------------404 // --- reference counters --------------------------------------------------
435 //405 //
436 // The same single-record guard, pointed the other way. A cap asks "is there406 // The same single-record guard, pointed the other way. A cap asks "is there
@@ -445,16 +415,6 @@ pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Re
445 // retired, a retirement lands only while the count is zero. Whichever reaches415 // retired, a retirement lands only while the count is zero. Whichever reaches
446 // the record first, the other is refused β€” in any process.416 // the record first, the other is refused β€” in any process.
447 417
448-/// Take `n` references on `id`. `false` = the name is retired and the caller
449-/// must refuse; nothing was written.
450-pub(crate) async fn claim_ref(id: &RecordId, n: i64, db: &Database) -> Result<bool, AppError> {
451- let sql = format!(
452- "UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \
453- WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id"
454- );
455- Ok(!write(&sql, id, n, db).await?.is_empty())
456-}
457-
458 /// What [`claim_ref_and_create`] settled.418 /// What [`claim_ref_and_create`] settled.
459 pub(crate) enum ClaimedRef<T> {419 pub(crate) enum ClaimedRef<T> {
460 /// The reference and the row committed together.420 /// The reference and the row committed together.
@@ -474,7 +434,7 @@ pub(crate) enum ClaimedRef<T> {
474 /// Take one reference on `counter` *and* write the row that holds it, in one434 /// Take one reference on `counter` *and* write the row that holds it, in one
475 /// transaction β€” [`claim_and_create`] pointed at a name instead of a cap.435 /// transaction β€” [`claim_and_create`] pointed at a name instead of a cap.
476 ///436 ///
477-/// [`claim_ref`] followed by a separate insert cannot promise this: the claim437+/// A bare reference claim followed by a separate insert cannot promise this: it
478 /// lands, the insert then fails or the process dies, and the name is counted as438 /// lands, the insert then fails or the process dies, and the name is counted as
479 /// used by a row that does not exist β€” which is a name nobody can ever retire.439 /// used by a row that does not exist β€” which is a name nobody can ever retire.
480 /// Here the abort takes the increment with it.440 /// Here the abort takes the increment with it.
@@ -560,18 +520,6 @@ pub(crate) async fn claim_ref_and_create<T: SurrealValue + Clone>(
560 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))520 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
561 }521 }
562 522
563-/// Give `n` references back β€” the referencing rows are gone (or never landed).
564-/// Clamped at zero like [`release`], so a double release cannot push a counter
565-/// below the rows it counts and let a used name be retired.
566-pub(crate) async fn release_ref(id: &RecordId, n: i64, db: &Database) -> Result<(), AppError> {
567- let sql = format!(
568- "UPSERT $parent SET {REF_COUNT_FIELD} = \
569- math::max([({REF_COUNT_FIELD} ?? 0) - $num, 0]) RETURN VALUE id"
570- );
571- write(&sql, id, n, db).await?;
572- Ok(())
573-}
574-
575 /// Retire the name behind `id`: no further claim succeeds. `false` = something523 /// Retire the name behind `id`: no further claim succeeds. `false` = something
576 /// still references it and the caller must refuse; nothing was written.524 /// still references it and the caller must refuse; nothing was written.
577 /// Idempotent β€” retiring an already-retired unused name lands again.525 /// Idempotent β€” retiring an already-retired unused name lands again.
src/domain/chatbot_thread.rsmodified+0 -21
@@ -88,27 +88,6 @@ impl ChatbotThread {
88 self.updated_at88 self.updated_at
89 }89 }
90 90
91- /// Write a thread row and nothing else. **Bypasses the cap counter**, so it
92- /// is only for tests that need a thread without one (`tests/persistence.rs`
93- /// cascade check); every production path goes through
94- /// [`ChatbotThread::create_capped`].
95- pub async fn create(
96- user: &UserId,
97- title: Option<ChatbotThreadTitle>,
98- db: &Database,
99- ) -> Result<ChatbotThread, AppError> {
100- let now = Timestamp::now();
101- let thread = ChatbotThread {
102- id: ChatbotThreadId::generate(),
103- user_id: user.clone(),
104- title,
105- created_at: now,
106- updated_at: now,
107- };
108- let created: Option<ChatbotThread> = db.create(thread.id.record()).content(thread).await?;
109- created.ok_or_else(|| AppError::Internal("failed to create thread".into()))
110- }
111-
112 /// Start a thread unless `user` is already at the school's91 /// Start a thread unless `user` is already at the school's
113 /// `max_chatbot_threads`. The slot is taken on the user row in the same92 /// `max_chatbot_threads`. The slot is taken on the user row in the same
114 /// transaction as the thread ([`cap::claim_and_create`]) β€” an atomic93 /// transaction as the thread ([`cap::claim_and_create`]) β€” an atomic
tests/persistence.rsmodified+2 -2
@@ -925,7 +925,7 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
925 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);925 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);
926 let other = UserId::from_key(&me_id(&app, &other_cookie).await);926 let other = UserId::from_key(&me_id(&app, &other_cookie).await);
927 927
928- let thread = ChatbotThread::create(&owner, None, &db)928+ let thread = ChatbotThread::create_capped(&owner, None, &db)
929 .await929 .await
930 .expect("create");930 .expect("create");
931 let id = thread.get_id().clone();931 let id = thread.get_id().clone();
@@ -1040,7 +1040,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
1040 .unwrap();1040 .unwrap();
1041 let owner = UserId::from_key(&me_id(&app, &cookie).await);1041 let owner = UserId::from_key(&me_id(&app, &cookie).await);
1042 1042
1043- let thread = ChatbotThread::create(&owner, None, &db)1043+ let thread = ChatbotThread::create_capped(&owner, None, &db)
1044 .await1044 .await
1045 .expect("create");1045 .expect("create");
1046 let id = thread.get_id().clone();1046 let id = thread.get_id().clone();