Skip to main content

agentmux_srv_core/backend/storage/
jekt_held.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Jekts held for an absent agent — `SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md`
5//! Phase 1. A message to a known agent of this channel that no delivery tier
6//! could take is kept here for up to 24 h and replayed when the agent
7//! registers. The trust verdicts it was accepted with are explicit columns:
8//! on `InjectionRequest` they are `skip_deserializing`, so they would not
9//! survive a JSON round-trip.
10
11use rusqlite::{params, OptionalExtension, Row};
12
13use super::error::StoreError;
14use super::store::Store;
15
16/// Held messages per target UID, and per channel (§2.2).
17pub const HELD_PER_TARGET: i64 = 64;
18pub const HELD_PER_CHANNEL: i64 = 1000;
19/// How long a message is held (§2.1).
20pub const HELD_TTL_MS: i64 = 24 * 60 * 60 * 1000;
21/// The most file bytes held for one agent for messages from other machines: the held rows keep the
22/// files in the attachment store for the hold, so what a verified peer can park there is bounded.
23pub const HELD_PEER_FILE_BYTES_PER_TARGET: u64 = 512 * 1024 * 1024;
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct HeldJekt {
27    pub request_id: String,
28    pub target_uid: String,
29    pub target_agent: String,
30    pub source_agent: String,
31    pub audit_source_uid: String,
32    pub message: String,
33    pub priority: String,
34    pub jekt_tier: String,
35    pub delivery_tier: String,
36    pub sig_verified: Option<bool>,
37    pub reagent_verified: Option<bool>,
38    pub lan_verified: Option<bool>,
39    pub channel_verified: Option<bool>,
40    /// The accept-time transcript-request fields, restored as they were: a
41    /// replay addresses the target by UID, and recomputing them by slug
42    /// would lose a forced escalation (review of #3632).
43    pub is_transcript_request: bool,
44    pub transcript_request_escalate_forced: bool,
45    /// The files sent with it, as the request's manifest JSON; '' for a
46    /// text-only jekt (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §4.5). The
47    /// files stay in this instance's attachment store meanwhile: a held
48    /// jekt always started here.
49    pub files_json: String,
50    pub sent_at_ms: i64,
51    pub expires_at_ms: i64,
52    /// The sender's own expiry for the message, epoch ms (issue #3894): a
53    /// review notice matters for ten minutes, not for however long its
54    /// recipient was unavailable. `None` — the sender said nothing — keeps
55    /// today's behaviour exactly. Checked at delivery time (the replay drops
56    /// the row instead of delivering it) and by the expiry sweep, so expired
57    /// rows cannot sit filling the per-target and per-channel caps either.
58    pub sender_expires_at_ms: Option<i64>,
59    pub attempts: i64,
60    pub last_error: String,
61    /// `idle` for a routine message held because the target's session went
62    /// cold (`backend::cold_hold`); '' for the others, which wait for the
63    /// agent to be there at all.
64    pub hold_reason: String,
65    /// The WAN verdict a message from another machine was accepted with, as JSON
66    /// (`{"verified":true,"instance":{...}}`); '' for a host or LAN message. Restored on replay,
67    /// so a held message keeps its tier and its proof (the cross-machine operations spec, §4.5).
68    pub wan_json: String,
69}
70
71impl HeldJekt {
72    /// Held because the session was cold, and delivered once it is warm.
73    pub fn is_idle(&self) -> bool {
74        self.hold_reason == crate::backend::cold_hold::REASON_IDLE
75    }
76
77    /// Held by quota mode, and delivered once the agent is active or the mode is off.
78    pub fn is_quota(&self) -> bool {
79        self.hold_reason == crate::backend::cold_hold::REASON_QUOTA
80    }
81}
82
83/// What decides which of a target's held rows go now (`Store::jekt_held_ready_for`).
84#[derive(Debug, Clone, Copy)]
85pub struct ReplayGate {
86    pub now_ms: i64,
87    /// The session is warm: rows held for it being cold go.
88    pub warm: bool,
89    /// Quota mode is off, or a turn is in flight: rows held for quota go.
90    pub quota_open: bool,
91    /// When the agent last wrote output: a quota row sent before it goes (the agent has been active since).
92    pub active_at_ms: i64,
93}
94
95/// One agent's held messages, counted by why they are held, with when the oldest was sent. Counts only: no body, no sender.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct HeldSummaryRow {
98    pub target_uid: String,
99    pub target_agent: String,
100    /// The reason stored with the hold (`idle`, `quota`), or empty for the rest: the agent's state names it then.
101    pub hold_reason: String,
102    pub count: i64,
103    pub oldest_sent_at_ms: i64,
104}
105
106/// What [`Store::jekt_held_insert`] did.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum HoldOutcome {
109    /// Stored now.
110    Held,
111    /// This `request_id` was already held — nothing stored twice.
112    AlreadyHeld,
113    /// A cap was reached — nothing stored.
114    Full,
115}
116
117fn verdict_to_sql(v: Option<bool>) -> Option<i64> {
118    v.map(i64::from)
119}
120
121fn verdict_from_sql(v: Option<i64>) -> Option<bool> {
122    v.map(|n| n != 0)
123}
124
125fn row_to_held(row: &Row) -> rusqlite::Result<HeldJekt> {
126    Ok(HeldJekt {
127        request_id: row.get("request_id")?,
128        target_uid: row.get("target_uid")?,
129        target_agent: row.get("target_agent")?,
130        source_agent: row.get("source_agent")?,
131        audit_source_uid: row.get("audit_source_uid")?,
132        message: row.get("message")?,
133        priority: row.get("priority")?,
134        jekt_tier: row.get("jekt_tier")?,
135        delivery_tier: row.get("delivery_tier")?,
136        sig_verified: verdict_from_sql(row.get("sig_verified")?),
137        reagent_verified: verdict_from_sql(row.get("reagent_verified")?),
138        lan_verified: verdict_from_sql(row.get("lan_verified")?),
139        channel_verified: verdict_from_sql(row.get("channel_verified")?),
140        is_transcript_request: row.get::<_, i64>("is_transcript_request")? != 0,
141        transcript_request_escalate_forced: row.get::<_, i64>("transcript_request_escalate_forced")? != 0,
142        files_json: row.get("files_json")?,
143        sent_at_ms: row.get("sent_at_ms")?,
144        expires_at_ms: row.get("expires_at_ms")?,
145        sender_expires_at_ms: row.get("sender_expires_at_ms")?,
146        attempts: row.get("attempts")?,
147        last_error: row.get("last_error")?,
148        hold_reason: row.get("hold_reason")?,
149        wan_json: row.get("wan_json")?,
150    })
151}
152
153/// The bytes a row's file list names.
154fn file_bytes(files_json: &str) -> u64 {
155    serde_json::from_str::<Vec<agentmux_common::jekt_files::JektFile>>(files_json)
156        .map(|files| files.iter().map(|f| f.size).sum())
157        .unwrap_or(0)
158}
159
160impl Store {
161    /// Hold `held`, unless its `request_id` is already held or a cap is
162    /// reached — decided under the one connection lock, so two concurrent
163    /// holds cannot both slip under a cap.
164    pub fn jekt_held_insert(&self, held: &HeldJekt) -> Result<HoldOutcome, StoreError> {
165        let conn = self.conn().lock().unwrap();
166        let exists: Option<i64> = conn
167            .query_row(
168                "SELECT 1 FROM db_jekt_held WHERE request_id = ?1",
169                params![held.request_id],
170                |r| r.get(0),
171            )
172            .optional()?;
173        if exists.is_some() {
174            return Ok(HoldOutcome::AlreadyHeld);
175        }
176        if matches!(held.delivery_tier.as_str(), "lan" | "wan") && !held.files_json.is_empty() {
177            let mut stmt = conn.prepare("SELECT files_json FROM db_jekt_held WHERE target_uid = ?1 AND files_json != '' AND delivery_tier IN ('lan', 'wan')")?;
178            let kept: u64 = stmt
179                .query_map(params![held.target_uid], |r| r.get::<_, String>(0))?
180                .filter_map(Result::ok)
181                .map(|json| file_bytes(&json))
182                .sum();
183            if kept.saturating_add(file_bytes(&held.files_json)) > HELD_PEER_FILE_BYTES_PER_TARGET {
184                return Ok(HoldOutcome::Full);
185            }
186        }
187        let n = conn.execute(
188            "INSERT INTO db_jekt_held
189                (request_id, target_uid, target_agent, source_agent, audit_source_uid,
190                 message, priority, jekt_tier, delivery_tier,
191                 sig_verified, reagent_verified, lan_verified, channel_verified,
192                 is_transcript_request, transcript_request_escalate_forced, files_json,
193                 sent_at_ms, expires_at_ms, sender_expires_at_ms, attempts, last_error, hold_reason, wan_json)
194             SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?18, ?19, ?20, ?14, ?15, ?23, 0, '', ?21, ?22
195              WHERE (SELECT COUNT(*) FROM db_jekt_held WHERE target_uid = ?2) < ?16
196                AND (SELECT COUNT(*) FROM db_jekt_held) < ?17",
197            params![
198                held.request_id,
199                held.target_uid,
200                held.target_agent,
201                held.source_agent,
202                held.audit_source_uid,
203                held.message,
204                held.priority,
205                held.jekt_tier,
206                held.delivery_tier,
207                verdict_to_sql(held.sig_verified),
208                verdict_to_sql(held.reagent_verified),
209                verdict_to_sql(held.lan_verified),
210                verdict_to_sql(held.channel_verified),
211                held.sent_at_ms,
212                held.expires_at_ms,
213                HELD_PER_TARGET,
214                HELD_PER_CHANNEL,
215                i64::from(held.is_transcript_request),
216                i64::from(held.transcript_request_escalate_forced),
217                held.files_json,
218                held.hold_reason,
219                held.wan_json,
220                held.sender_expires_at_ms,
221            ],
222        )?;
223        Ok(if n > 0 { HoldOutcome::Held } else { HoldOutcome::Full })
224    }
225
226    /// Delete held messages past their expiry; returns how many. A message
227    /// held for a cold session, or by quota mode, is not dropped at its expiry:
228    /// the replay delivers it then, so a quiet agent still gets it. It is dropped a
229    /// whole TTL later, if its agent never came back to receive it. A message
230    /// whose SENDER'S expiry has passed (issue #3894) is dropped whatever its
231    /// hold reason: the sender said delivering it past that point is worth less
232    /// than dropping it. A message with no sender expiry (NULL) is unaffected.
233    pub fn jekt_held_delete_expired(&self, now_ms: i64) -> Result<usize, StoreError> {
234        let conn = self.conn().lock().unwrap();
235        Ok(conn.execute(
236            "DELETE FROM db_jekt_held
237              WHERE (hold_reason NOT IN (?2, ?4) AND expires_at_ms <= ?1)
238                 OR expires_at_ms + ?3 <= ?1
239                 OR sender_expires_at_ms <= ?1",
240            params![now_ms, crate::backend::cold_hold::REASON_IDLE, HELD_TTL_MS, crate::backend::cold_hold::REASON_QUOTA],
241        )?)
242    }
243
244    /// Every target UID with a held message, the one waiting longest first.
245    pub fn jekt_held_targets(&self) -> Result<Vec<String>, StoreError> {
246        let conn = self.conn().lock().unwrap();
247        let mut stmt = conn.prepare(
248            "SELECT target_uid FROM db_jekt_held GROUP BY target_uid ORDER BY MIN(sent_at_ms)",
249        )?;
250        let rows = stmt.query_map([], |r| r.get(0))?;
251        Ok(rows.collect::<Result<Vec<String>, _>>()?)
252    }
253
254    /// Every agent's held messages as counts: per target and stored reason, how many and since when the oldest. Reads no
255    /// message body. The agent with the oldest message first.
256    pub fn jekt_held_summary(&self) -> Result<Vec<HeldSummaryRow>, StoreError> {
257        let conn = self.conn().lock().unwrap();
258        let mut stmt = conn.prepare(
259            "SELECT target_uid, MAX(target_agent), hold_reason, COUNT(*), MIN(sent_at_ms)
260               FROM db_jekt_held GROUP BY target_uid, hold_reason ORDER BY MIN(sent_at_ms)",
261        )?;
262        let rows = stmt.query_map([], |r| {
263            Ok(HeldSummaryRow {
264                target_uid: r.get(0)?,
265                target_agent: r.get(1)?,
266                hold_reason: r.get(2)?,
267                count: r.get(3)?,
268                oldest_sent_at_ms: r.get(4)?,
269            })
270        })?;
271        Ok(rows.collect::<Result<Vec<_>, _>>()?)
272    }
273
274    /// One target's held messages, oldest first, at most `limit`.
275    pub fn jekt_held_for_target(&self, target_uid: &str, limit: usize) -> Result<Vec<HeldJekt>, StoreError> {
276        self.jekt_held_ready(target_uid, limit, true, 0)
277    }
278
279    /// One target's held messages that are ready to go, oldest first, at most
280    /// `limit`: all of them when `warm`, otherwise (its session is still
281    /// cold) only those not held for the cold session, and those that have
282    /// waited out their expiry at `now_ms`.
283    pub fn jekt_held_ready(&self, target_uid: &str, limit: usize, warm: bool, now_ms: i64) -> Result<Vec<HeldJekt>, StoreError> {
284        self.jekt_held_ready_for(target_uid, limit, &ReplayGate { now_ms, warm, quota_open: warm, active_at_ms: 0 })
285    }
286
287    /// [`Self::jekt_held_ready`] with the quota gate: a row held by quota mode goes when
288    /// `gate.quota_open`, when the agent wrote output after it was sent, or at its expiry.
289    pub fn jekt_held_ready_for(&self, target_uid: &str, limit: usize, gate: &ReplayGate) -> Result<Vec<HeldJekt>, StoreError> {
290        use crate::backend::cold_hold::{REASON_IDLE, REASON_QUOTA};
291        let conn = self.conn().lock().unwrap();
292        let mut stmt = conn.prepare(
293            "SELECT * FROM db_jekt_held
294              WHERE target_uid = ?1
295                AND (hold_reason NOT IN (?5, ?6)
296                     OR (hold_reason = ?5 AND (?3 OR expires_at_ms <= ?4))
297                     OR (hold_reason = ?6 AND (?7 OR sent_at_ms <= ?8 OR expires_at_ms <= ?4)))
298              ORDER BY sent_at_ms ASC, request_id ASC LIMIT ?2",
299        )?;
300        let rows = stmt.query_map(
301            params![target_uid, limit as i64, gate.warm, gate.now_ms, REASON_IDLE, REASON_QUOTA, gate.quota_open, gate.active_at_ms],
302            row_to_held,
303        )?;
304        Ok(rows.collect::<Result<Vec<_>, _>>()?)
305    }
306
307    /// Drop the held-for-cold and held-by-quota copies of a message the sender has now sent
308    /// again to wake the agent (`urgent`), so it isn't delivered twice.
309    /// Returns how many.
310    pub fn jekt_held_delete_idle_copies(&self, target_uid: &str, source_agent: &str, message: &str) -> Result<usize, StoreError> {
311        use crate::muxbus::delivery_status::notes::without_delayed_prefix;
312        let conn = self.conn().lock().unwrap();
313        // A relayed message that came in late was held with the relay's "(sent .., delivered ..) " in front of its text,
314        // so the copies are those that end in the message and are it once that prefix is off.
315        let mut stmt = conn.prepare(
316            "SELECT request_id, message FROM db_jekt_held
317              WHERE target_uid = ?1 AND source_agent = ?2 AND hold_reason IN (?3, ?4) AND substr(message, -length(?5)) = ?5",
318        )?;
319        let copies: Vec<String> = stmt
320            .query_map(
321                params![target_uid, source_agent, crate::backend::cold_hold::REASON_IDLE, crate::backend::cold_hold::REASON_QUOTA, message],
322                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
323            )?
324            .collect::<Result<Vec<_>, _>>()?
325            .into_iter()
326            .filter(|(_, held)| held == message || without_delayed_prefix(held) == message)
327            .map(|(id, _)| id)
328            .collect();
329        for id in &copies {
330            conn.execute("DELETE FROM db_jekt_held WHERE request_id = ?1", params![id])?;
331        }
332        Ok(copies.len())
333    }
334
335    /// Remove one held message (delivered, or dropped).
336    pub fn jekt_held_delete(&self, request_id: &str) -> Result<(), StoreError> {
337        let conn = self.conn().lock().unwrap();
338        conn.execute("DELETE FROM db_jekt_held WHERE request_id = ?1", params![request_id])?;
339        Ok(())
340    }
341
342    /// Count a failed replay; returns the new attempt count.
343    pub fn jekt_held_record_failure(&self, request_id: &str, error: &str) -> Result<i64, StoreError> {
344        let conn = self.conn().lock().unwrap();
345        conn.execute(
346            "UPDATE db_jekt_held SET attempts = attempts + 1, last_error = ?2 WHERE request_id = ?1",
347            params![request_id, error],
348        )?;
349        Ok(conn
350            .query_row(
351                "SELECT attempts FROM db_jekt_held WHERE request_id = ?1",
352                params![request_id],
353                |r| r.get(0),
354            )
355            .optional()?
356            .unwrap_or(0))
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    pub(crate) fn held(id: &str, target: &str, sent_at_ms: i64) -> HeldJekt {
365        HeldJekt {
366            request_id: id.into(),
367            target_uid: target.into(),
368            target_agent: "agenty".into(),
369            source_agent: "sender".into(),
370            audit_source_uid: "uid-sender".into(),
371            message: "hello".into(),
372            priority: "normal".into(),
373            jekt_tier: String::new(),
374            delivery_tier: "host".into(),
375            sig_verified: Some(false),
376            reagent_verified: None,
377            lan_verified: None,
378            channel_verified: Some(true),
379            is_transcript_request: true,
380            transcript_request_escalate_forced: true,
381            files_json: String::new(),
382            sent_at_ms,
383            expires_at_ms: sent_at_ms + HELD_TTL_MS,
384            sender_expires_at_ms: None,
385            attempts: 0,
386            last_error: String::new(),
387            hold_reason: String::new(),
388            wan_json: String::new(),
389        }
390    }
391
392    fn peer_with_files(id: &str, tier: &str, bytes: u64) -> HeldJekt {
393        let files = vec![agentmux_common::jekt_files::JektFile { sha256: "ab".repeat(32), name: "a.bin".into(), size: bytes }];
394        HeldJekt { delivery_tier: tier.into(), files_json: serde_json::to_string(&files).unwrap(), ..held(id, "uid-y", 1) }
395    }
396
397    /// What a verified peer can park in the attachment store for one agent is bounded; a local sender's
398    /// files (already in the store, by hash) are not counted.
399    #[test]
400    fn a_peers_held_files_are_capped_per_agent() {
401        const MIB: u64 = 1024 * 1024;
402        let s = Store::open_in_memory().unwrap();
403        assert_eq!(s.jekt_held_insert(&peer_with_files("p1", "lan", 100 * MIB)).unwrap(), HoldOutcome::Held);
404        assert_eq!(s.jekt_held_insert(&peer_with_files("p2", "wan", 200 * MIB)).unwrap(), HoldOutcome::Held);
405        assert_eq!(s.jekt_held_insert(&peer_with_files("p3", "lan", 212 * MIB)).unwrap(), HoldOutcome::Held, "512 MiB is the cap, met exactly");
406        assert_eq!(s.jekt_held_insert(&peer_with_files("p4", "lan", MIB)).unwrap(), HoldOutcome::Full);
407        assert_eq!(s.jekt_held_insert(&peer_with_files("p3", "lan", 212 * MIB)).unwrap(), HoldOutcome::AlreadyHeld);
408        assert_eq!(s.jekt_held_insert(&peer_with_files("h1", "host", 200 * MIB)).unwrap(), HoldOutcome::Held, "host-tier files are the sender's own");
409        assert_eq!(s.jekt_held_insert(&HeldJekt { delivery_tier: "lan".into(), ..held("t1", "uid-y", 1) }).unwrap(), HoldOutcome::Held, "no files, no weight");
410        s.jekt_held_delete("p1").unwrap();
411        assert_eq!(s.jekt_held_insert(&peer_with_files("p4", "lan", MIB)).unwrap(), HoldOutcome::Held, "room again once one is delivered");
412    }
413
414    #[test]
415    fn holds_once_round_trips_verdicts_and_orders_oldest_first() {
416        let s = Store::open_in_memory().unwrap();
417        assert_eq!(s.jekt_held_insert(&held("r2", "uid-y", 200)).unwrap(), HoldOutcome::Held);
418        assert_eq!(s.jekt_held_insert(&held("r1", "uid-y", 100)).unwrap(), HoldOutcome::Held);
419        assert_eq!(s.jekt_held_insert(&held("r1", "uid-y", 100)).unwrap(), HoldOutcome::AlreadyHeld);
420        let rows = s.jekt_held_for_target("uid-y", 10).unwrap();
421        assert_eq!(rows.iter().map(|r| r.request_id.as_str()).collect::<Vec<_>>(), ["r1", "r2"]);
422        assert_eq!(rows[0].sig_verified, Some(false), "a failed verdict survives");
423        assert_eq!(rows[0].channel_verified, Some(true));
424        assert_eq!(rows[0].reagent_verified, None);
425        assert!(rows[0].is_transcript_request && rows[0].transcript_request_escalate_forced);
426        assert_eq!(s.jekt_held_targets().unwrap(), ["uid-y"]);
427    }
428
429    /// Deleting the target agent purges what is held for it, through both
430    /// deletion paths (Codex P1 on #3632); another agent's held rows stay.
431    #[test]
432    fn deleting_the_target_purges_its_held_messages() {
433        use crate::backend::storage::agents::test_agent_def;
434        for via_instance_delete in [false, true] {
435            let s = Store::open_in_memory().unwrap();
436            for id in ["uid-y", "uid-z"] {
437                let mut def = test_agent_def(id, id, "claude", "agent", 1, "");
438                s.agent_def_insert(&mut def).unwrap();
439            }
440            s.jekt_held_insert(&held("for-y", "uid-y", 1)).unwrap();
441            s.jekt_held_insert(&held("for-z", "uid-z", 1)).unwrap();
442            let deleted = if via_instance_delete {
443                s.instance_delete("uid-y").unwrap()
444            } else {
445                s.agent_def_delete("uid-y").unwrap()
446            };
447            assert!(deleted);
448            assert!(s.jekt_held_for_target("uid-y", 10).unwrap().is_empty(), "instance_delete={via_instance_delete}");
449            assert_eq!(s.jekt_held_for_target("uid-z", 10).unwrap().len(), 1);
450        }
451    }
452
453    #[test]
454    fn caps_refuse_rather_than_overflow() {
455        let s = Store::open_in_memory().unwrap();
456        for i in 0..HELD_PER_TARGET {
457            assert_eq!(s.jekt_held_insert(&held(&format!("r{i}"), "uid-y", i)).unwrap(), HoldOutcome::Held);
458        }
459        assert_eq!(s.jekt_held_insert(&held("one-more", "uid-y", 999)).unwrap(), HoldOutcome::Full);
460        assert_eq!(s.jekt_held_insert(&held("other-target", "uid-z", 999)).unwrap(), HoldOutcome::Held);
461    }
462
463    #[test]
464    fn expiry_failure_count_and_delete() {
465        let s = Store::open_in_memory().unwrap();
466        s.jekt_held_insert(&held("old", "uid-y", 0)).unwrap();
467        s.jekt_held_insert(&held("new", "uid-y", HELD_TTL_MS)).unwrap();
468        assert_eq!(s.jekt_held_delete_expired(HELD_TTL_MS).unwrap(), 1);
469        assert_eq!(s.jekt_held_record_failure("new", "boom").unwrap(), 1);
470        assert_eq!(s.jekt_held_record_failure("new", "boom").unwrap(), 2);
471        assert_eq!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].last_error, "boom");
472        s.jekt_held_delete("new").unwrap();
473        assert!(s.jekt_held_targets().unwrap().is_empty());
474    }
475}
476
477#[cfg(test)]
478mod idle_tests {
479    use super::tests::held;
480    use super::*;
481    use crate::backend::cold_hold::REASON_IDLE;
482
483    fn idle(id: &str, target: &str, sent_at_ms: i64) -> HeldJekt {
484        HeldJekt { hold_reason: REASON_IDLE.into(), ..held(id, target, sent_at_ms) }
485    }
486
487    #[test]
488    fn the_summary_counts_by_agent_and_reason_and_names_the_oldest() {
489        let s = Store::open_in_memory().unwrap();
490        s.jekt_held_insert(&held("a1", "uid-y", 300)).unwrap();
491        s.jekt_held_insert(&held("a2", "uid-y", 200)).unwrap();
492        s.jekt_held_insert(&idle("i1", "uid-y", 500)).unwrap();
493        s.jekt_held_insert(&held("b1", "uid-z", 100)).unwrap();
494        let rows = s.jekt_held_summary().unwrap();
495        let key = |r: &HeldSummaryRow| (r.target_uid.clone(), r.hold_reason.clone(), r.count, r.oldest_sent_at_ms);
496        assert_eq!(
497            rows.iter().map(key).collect::<Vec<_>>(),
498            vec![
499                ("uid-z".into(), String::new(), 1, 100),
500                ("uid-y".into(), String::new(), 2, 200),
501                ("uid-y".into(), REASON_IDLE.into(), 1, 500),
502            ]
503        );
504        s.jekt_held_delete("b1").unwrap();
505        assert_eq!(s.jekt_held_summary().unwrap().len(), 2);
506    }
507
508    #[test]
509    fn a_cold_hold_waits_for_a_warm_session_but_the_others_do_not() {
510        let s = Store::open_in_memory().unwrap();
511        s.jekt_held_insert(&idle("i1", "uid-y", 100)).unwrap();
512        s.jekt_held_insert(&held("a1", "uid-y", 200)).unwrap();
513        let ids = |warm: bool, now: i64| {
514            s.jekt_held_ready("uid-y", 10, warm, now).unwrap().into_iter().map(|r| r.request_id).collect::<Vec<_>>()
515        };
516        assert_eq!(ids(true, 1000), ["i1", "a1"], "warm: everything, oldest first");
517        assert_eq!(ids(false, 1000), ["a1"], "cold: only what was not held for the cold session");
518        assert_eq!(ids(false, HELD_TTL_MS + 100), ["i1", "a1"], "waited out its 24 h: delivered anyway");
519        let round_trip = s.jekt_held_for_target("uid-y", 10).unwrap();
520        assert!(round_trip[0].is_idle() && !round_trip[1].is_idle());
521    }
522
523    #[test]
524    fn a_cold_hold_is_delivered_at_its_expiry_not_dropped_until_a_ttl_later() {
525        let s = Store::open_in_memory().unwrap();
526        s.jekt_held_insert(&idle("i1", "uid-y", 0)).unwrap();
527        s.jekt_held_insert(&held("a1", "uid-y", 0)).unwrap();
528        assert_eq!(s.jekt_held_delete_expired(HELD_TTL_MS).unwrap(), 1, "only the other kind");
529        assert_eq!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].request_id, "i1");
530        assert_eq!(s.jekt_held_delete_expired(2 * HELD_TTL_MS).unwrap(), 1, "dropped a whole TTL later");
531        assert!(s.jekt_held_targets().unwrap().is_empty());
532    }
533
534    fn quota(id: &str, target: &str, sent_at_ms: i64) -> HeldJekt {
535        HeldJekt { hold_reason: crate::backend::cold_hold::REASON_QUOTA.into(), ..held(id, target, sent_at_ms) }
536    }
537
538    fn gate(quota_open: bool, active_at_ms: i64, now_ms: i64) -> ReplayGate {
539        ReplayGate { now_ms, warm: false, quota_open, active_at_ms }
540    }
541
542    #[test]
543    fn a_quota_hold_goes_when_the_mode_is_off_a_turn_is_in_flight_or_the_agent_wrote_since() {
544        let s = Store::open_in_memory().unwrap();
545        s.jekt_held_insert(&quota("q1", "uid-y", 100)).unwrap();
546        s.jekt_held_insert(&held("a1", "uid-y", 200)).unwrap();
547        let ids = |g: ReplayGate| s.jekt_held_ready_for("uid-y", 10, &g).unwrap().into_iter().map(|r| r.request_id).collect::<Vec<_>>();
548        assert_eq!(ids(gate(false, 0, 1000)), ["a1"], "tight, quiet: only the other kind goes");
549        assert_eq!(ids(gate(false, 99, 1000)), ["a1"], "it last wrote before the message was sent");
550        assert_eq!(ids(gate(false, 100, 1000)), ["q1", "a1"], "it wrote since: the next time it is active");
551        assert_eq!(ids(gate(true, 0, 1000)), ["q1", "a1"], "mode off, or a turn in flight");
552        assert_eq!(ids(gate(false, 0, HELD_TTL_MS + 100)), ["q1", "a1"], "waited out its 24 h: delivered anyway");
553        assert!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].is_quota());
554    }
555
556    #[test]
557    fn a_quota_hold_is_delivered_at_its_expiry_not_dropped_until_a_ttl_later() {
558        let s = Store::open_in_memory().unwrap();
559        s.jekt_held_insert(&quota("q1", "uid-y", 0)).unwrap();
560        s.jekt_held_insert(&held("a1", "uid-y", 0)).unwrap();
561        assert_eq!(s.jekt_held_delete_expired(HELD_TTL_MS).unwrap(), 1, "only the other kind");
562        assert_eq!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].request_id, "q1");
563        assert_eq!(s.jekt_held_delete_expired(2 * HELD_TTL_MS).unwrap(), 1, "dropped a whole TTL later");
564    }
565
566    /// Issue #3894: the sender's own expiry is honoured whatever the hold
567    /// reason — a cold or quota hold that is normally delivered at its 24 h
568    /// expiry is dropped the moment the sender's deadline passes instead of
569    /// delivered stale. A row with no sender expiry (None) is unaffected.
570    #[test]
571    fn a_senders_expiry_drops_a_cold_or_quota_hold_at_its_own_deadline() {
572        let s = Store::open_in_memory().unwrap();
573        let with_expiry = |mut row: HeldJekt| {
574            row.sender_expires_at_ms = Some(1_000);
575            row
576        };
577        s.jekt_held_insert(&with_expiry(idle("i1", "uid-y", 0))).unwrap();
578        s.jekt_held_insert(&with_expiry(quota("q1", "uid-y", 0))).unwrap();
579        s.jekt_held_insert(&with_expiry(held("a1", "uid-y", 0))).unwrap();
580        assert_eq!(s.jekt_held_delete_expired(999).unwrap(), 0, "not yet");
581        assert_eq!(s.jekt_held_delete_expired(1_000).unwrap(), 3, "whatever the hold reason");
582        assert!(s.jekt_held_for_target("uid-y", 10).unwrap().is_empty());
583    }
584
585    #[test]
586    fn a_resend_removes_a_quota_copy_as_well_as_a_cold_one() {
587        let s = Store::open_in_memory().unwrap();
588        s.jekt_held_insert(&quota("q1", "uid-y", 100)).unwrap();
589        s.jekt_held_insert(&idle("i1", "uid-y", 150)).unwrap();
590        s.jekt_held_insert(&held("a1", "uid-y", 200)).unwrap();
591        assert_eq!(s.jekt_held_delete_idle_copies("uid-y", "sender", "hello").unwrap(), 2);
592        assert_eq!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].request_id, "a1");
593    }
594
595    #[test]
596    fn a_resend_removes_the_copy_held_with_the_relays_lateness_prefix() {
597        let s = Store::open_in_memory().unwrap();
598        let late = |id: &str, text: &str| HeldJekt { message: text.into(), ..idle(id, "uid-y", 100) };
599        s.jekt_held_insert(&late("late", "(sent 09:01, delivered 09:14) hello")).unwrap();
600        s.jekt_held_insert(&late("other", "(sent 09:01, delivered 09:14) hello there")).unwrap();
601        s.jekt_held_insert(&late("not-ours", "(sent by hand, delivered later) hello")).unwrap();
602        assert_eq!(s.jekt_held_delete_idle_copies("uid-y", "sender", "hello").unwrap(), 1);
603        let mut left: Vec<String> = s.jekt_held_for_target("uid-y", 10).unwrap().into_iter().map(|r| r.request_id).collect();
604        left.sort();
605        assert_eq!(left, ["not-ours", "other"], "a longer message and a prefix that is not the relay's stay");
606    }
607
608    #[test]
609    fn identical_cold_copies_from_one_sender_are_removed_by_a_resend() {
610        let s = Store::open_in_memory().unwrap();
611        s.jekt_held_insert(&idle("i1", "uid-y", 100)).unwrap();
612        s.jekt_held_insert(&held("a1", "uid-y", 200)).unwrap();
613        assert_eq!(s.jekt_held_delete_idle_copies("uid-y", "sender", "hello").unwrap(), 1);
614        assert_eq!(s.jekt_held_delete_idle_copies("uid-y", "sender", "hello").unwrap(), 0);
615        assert_eq!(s.jekt_held_for_target("uid-y", 10).unwrap()[0].request_id, "a1", "a not-running hold is left alone");
616    }
617}