Skip to main content

lean_ctx/core/a2a/
dlq.rs

1use std::collections::BTreeMap;
2use std::fs::{File, OpenOptions};
3use std::io::{Read, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, Mutex};
6
7use lean_ctx_time::{OffsetDateTime, UtcDateTime};
8use serde::{Deserialize, Serialize};
9
10use crate::core::agents::{AgentRegistry, FileLock};
11use crate::core::ocla::types::{OclaError, OclaResult};
12
13const STORE_VERSION: u16 = 1;
14const MAX_ENTRIES_PER_SCOPE: usize = 1_000;
15const MAX_STORE_BYTES: u64 = 8 * 1024 * 1024;
16const MAX_MESSAGE_BYTES: usize = 2 * 1024 * 1024;
17const MAX_IDENTIFIER_BYTES: usize = 512;
18pub(crate) const MAX_ERROR_BYTES: usize = 64 * 1024;
19const LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
20
21#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
22#[serde(deny_unknown_fields, rename_all = "snake_case")]
23pub enum DeadLetterDelivery {
24    LocalAgentBus,
25    RemoteHttp { endpoint_url: String },
26}
27
28#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct DlqScope {
31    pub tenant_id: String,
32    pub project_id: String,
33}
34
35impl DlqScope {
36    pub fn new(tenant_id: impl Into<String>, project_id: impl Into<String>) -> OclaResult<Self> {
37        let scope = Self {
38            tenant_id: tenant_id.into(),
39            project_id: project_id.into(),
40        };
41        scope.validate()?;
42        Ok(scope)
43    }
44
45    fn validate(&self) -> OclaResult<()> {
46        validate_identifier("tenant_id", &self.tenant_id)?;
47        validate_identifier("project_id", &self.project_id)
48    }
49}
50
51#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
52#[serde(deny_unknown_fields)]
53pub struct DeadLetter {
54    pub id: String,
55    #[serde(default)]
56    pub peer_id: String,
57    #[serde(default)]
58    pub delivery_id: String,
59    pub tenant_id: String,
60    pub project_id: String,
61    pub delivery: DeadLetterDelivery,
62    pub original_message: String,
63    pub target_agent: String,
64    pub error: String,
65    pub attempts: u8,
66    pub first_failed_at: String,
67    pub last_failed_at: String,
68}
69
70impl DeadLetter {
71    fn validate(&self) -> OclaResult<()> {
72        validate_identifier("id", &self.id)?;
73        validate_identifier("peer_id", &self.peer_id)?;
74        validate_identifier("delivery_id", &self.delivery_id)?;
75        DlqScope::new(self.tenant_id.clone(), self.project_id.clone())?;
76        validate_identifier("target_agent", &self.target_agent)?;
77        if self.original_message.is_empty() || self.original_message.len() > MAX_MESSAGE_BYTES {
78            return Err(OclaError::InvalidRequest(
79                "dead letter message must be non-empty and bounded".into(),
80            ));
81        }
82        if self.error.is_empty() || self.error.len() > MAX_ERROR_BYTES {
83            return Err(OclaError::InvalidRequest(
84                "dead letter error must be non-empty and bounded".into(),
85            ));
86        }
87        if self.attempts == 0 {
88            return Err(OclaError::InvalidRequest(
89                "dead letter attempts must be greater than zero".into(),
90            ));
91        }
92        let first_failed_at = OffsetDateTime::parse_from_rfc3339(&self.first_failed_at)
93            .map_err(|_| OclaError::InvalidRequest("invalid first_failed_at".into()))?;
94        let last_failed_at = OffsetDateTime::parse_from_rfc3339(&self.last_failed_at)
95            .map_err(|_| OclaError::InvalidRequest("invalid last_failed_at".into()))?;
96        if last_failed_at < first_failed_at {
97            return Err(OclaError::InvalidRequest(
98                "last_failed_at must not precede first_failed_at".into(),
99            ));
100        }
101        if let DeadLetterDelivery::RemoteHttp { endpoint_url } = &self.delivery {
102            let url = reqwest::Url::parse(endpoint_url).map_err(|_| {
103                OclaError::InvalidRequest("invalid dead letter endpoint_url".into())
104            })?;
105            if !matches!(url.scheme(), "http" | "https")
106                || url.host_str().is_none()
107                || !url.username().is_empty()
108                || url.password().is_some()
109            {
110                return Err(OclaError::InvalidRequest(
111                    "dead letter endpoint_url must be absolute HTTP(S)".into(),
112                ));
113            }
114        }
115        Ok(())
116    }
117}
118
119#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
120pub struct DlqStats {
121    pub total: usize,
122    pub max_scope_depth: usize,
123    pub oldest_age_seconds: u64,
124    pub by_target_agent: BTreeMap<String, usize>,
125}
126
127#[derive(Debug, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129struct DurableDlqV1 {
130    version: u16,
131    entries: Vec<DeadLetter>,
132}
133
134impl Default for DurableDlqV1 {
135    fn default() -> Self {
136        Self {
137            version: STORE_VERSION,
138            entries: Vec::new(),
139        }
140    }
141}
142
143#[derive(Clone)]
144enum QueueBackend {
145    Memory(Arc<Mutex<Vec<DeadLetter>>>),
146    Durable {
147        root: PathBuf,
148        process_lock: Arc<Mutex<()>>,
149    },
150    Unavailable(String),
151}
152
153#[derive(Clone)]
154pub struct DeadLetterQueue {
155    backend: QueueBackend,
156}
157
158pub struct DlqRetryGuard {
159    _lock: Option<FileLock>,
160}
161
162impl Default for DeadLetterQueue {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168impl DeadLetterQueue {
169    #[must_use]
170    pub fn new() -> Self {
171        Self {
172            backend: QueueBackend::Memory(Arc::new(Mutex::new(Vec::new()))),
173        }
174    }
175
176    pub fn persistent_default() -> std::io::Result<Self> {
177        let path = crate::core::data_dir::lean_ctx_data_dir()
178            .map_err(std::io::Error::other)?
179            .join("agents")
180            .join("a2a")
181            .join("dead-letters-v1.json");
182        Self::persistent(path)
183    }
184
185    pub fn persistent(path: impl AsRef<Path>) -> std::io::Result<Self> {
186        let path = path.as_ref();
187        let root = path.with_extension("d");
188        if path.exists() {
189            prepare_parent(&path)?;
190            prepare_store_directory(&root)?;
191            migrate_legacy_store(&path, &root)?;
192        } else {
193            for directory in [path.parent(), path.parent().and_then(Path::parent)]
194                .into_iter()
195                .flatten()
196            {
197                validate_directory(directory)?;
198            }
199            validate_directory(&root)?;
200        }
201        let queue = Self {
202            backend: QueueBackend::Durable {
203                root,
204                process_lock: Arc::new(Mutex::new(())),
205            },
206        };
207        Ok(queue)
208    }
209
210    #[must_use]
211    pub fn unavailable(error: impl Into<String>) -> Self {
212        Self {
213            backend: QueueBackend::Unavailable(error.into()),
214        }
215    }
216
217    pub fn enqueue(&self, letter: DeadLetter) -> OclaResult<()> {
218        letter.validate()?;
219        let scope = DlqScope::new(letter.tenant_id.clone(), letter.project_id.clone())?;
220        self.with_entries(Some(&scope), true, |entries| {
221            if let Some(existing) = entries.iter_mut().find(|entry| {
222                entry.peer_id == letter.peer_id
223                    && entry.delivery_id == letter.delivery_id
224                    && entry.tenant_id == letter.tenant_id
225                    && entry.project_id == letter.project_id
226            }) {
227                existing.error = letter.error;
228                existing.attempts = existing.attempts.max(letter.attempts);
229                existing.last_failed_at = letter.last_failed_at;
230                return Ok(());
231            }
232            if entries
233                .iter()
234                .filter(|entry| {
235                    entry.tenant_id == letter.tenant_id && entry.project_id == letter.project_id
236                })
237                .count()
238                >= MAX_ENTRIES_PER_SCOPE
239                && let Some(position) = entries.iter().position(|entry| {
240                    entry.tenant_id == letter.tenant_id && entry.project_id == letter.project_id
241                })
242            {
243                entries.remove(position);
244            }
245            entries.push(letter);
246            while serialized_store_size(entries)? > MAX_STORE_BYTES {
247                if entries.len() == 1 {
248                    return Err(OclaError::InvalidRequest(
249                        "dead letter exceeds per-scope store size limit".into(),
250                    ));
251                }
252                entries.remove(0);
253            }
254            Ok(())
255        })
256    }
257
258    pub fn dequeue(&self, scope: &DlqScope, id: &str) -> OclaResult<Option<DeadLetter>> {
259        scope.validate()?;
260        validate_identifier("id", id)?;
261        self.with_entries(Some(scope), true, |entries| {
262            let position = entries.iter().position(|letter| {
263                letter.id == id
264                    && letter.tenant_id == scope.tenant_id
265                    && letter.project_id == scope.project_id
266            });
267            Ok(position.map(|position| entries.remove(position)))
268        })
269    }
270
271    pub fn peek(&self, scope: &DlqScope) -> OclaResult<Vec<DeadLetter>> {
272        scope.validate()?;
273        self.with_entries(Some(scope), false, |entries| {
274            Ok(entries
275                .iter()
276                .filter(|letter| {
277                    letter.tenant_id == scope.tenant_id && letter.project_id == scope.project_id
278                })
279                .cloned()
280                .collect())
281        })
282    }
283
284    pub fn get(&self, scope: &DlqScope, id: &str) -> OclaResult<Option<DeadLetter>> {
285        scope.validate()?;
286        validate_identifier("id", id)?;
287        self.with_entries(Some(scope), false, |entries| {
288            Ok(entries
289                .iter()
290                .find(|letter| {
291                    letter.id == id
292                        && letter.tenant_id == scope.tenant_id
293                        && letter.project_id == scope.project_id
294                })
295                .cloned())
296        })
297    }
298
299    pub fn lock_retry(&self, scope: &DlqScope, id: &str) -> OclaResult<DlqRetryGuard> {
300        scope.validate()?;
301        validate_identifier("id", id)?;
302        match &self.backend {
303            QueueBackend::Durable { root, .. } => {
304                // One stable lock file per scope prevents duplicate retries across
305                // processes without globally serializing unrelated tenants or
306                // accumulating one persistent lock artifact per dead letter.
307                let path = scope_store_path(root, scope).with_extension("retry.lock");
308                let lock = FileLock::acquire_with_timeout(&path, LOCK_TIMEOUT)
309                    .map_err(|error| store_error(&std::io::Error::other(error)))?;
310                Ok(DlqRetryGuard { _lock: Some(lock) })
311            }
312            QueueBackend::Memory(_) => Ok(DlqRetryGuard { _lock: None }),
313            QueueBackend::Unavailable(error) => Err(OclaError::InvalidRequest(format!(
314                "dead letter store unavailable: {error}"
315            ))),
316        }
317    }
318
319    pub fn retry(&self, scope: &DlqScope, id: &str) -> OclaResult<()> {
320        scope.validate()?;
321        validate_identifier("id", id)?;
322        let retry_error = self.with_entries(Some(scope), true, |entries| {
323            let position = entries
324                .iter()
325                .position(|letter| letter.id == id)
326                .ok_or_else(|| OclaError::InvalidRequest(format!("dead letter not found: {id}")))?;
327            if !matches!(
328                entries[position].delivery,
329                DeadLetterDelivery::LocalAgentBus
330            ) {
331                return Err(OclaError::InvalidRequest(
332                    "remote dead letters require the configured authenticated transport".into(),
333                ));
334            }
335            match resend_local(&entries[position]) {
336                Ok(()) => {
337                    entries.remove(position);
338                    Ok(None)
339                }
340                Err(error) => {
341                    entries[position].attempts = entries[position].attempts.saturating_add(1);
342                    entries[position].last_failed_at = UtcDateTime::now().to_rfc3339();
343                    Ok(Some(error))
344                }
345            }
346        })?;
347        retry_error.map_or(Ok(()), Err)
348    }
349
350    pub fn stats(&self, scope: Option<&DlqScope>) -> OclaResult<DlqStats> {
351        if let Some(scope) = scope {
352            scope.validate()?;
353        }
354        self.with_entries(scope, false, |entries| {
355            let now = UtcDateTime::now();
356            let mut oldest_age_seconds = 0;
357            let mut by_target_agent = BTreeMap::new();
358            let mut by_scope = BTreeMap::new();
359            let mut total = 0;
360            for letter in entries.iter().filter(|letter| {
361                scope.is_none_or(|scope| {
362                    letter.tenant_id == scope.tenant_id && letter.project_id == scope.project_id
363                })
364            }) {
365                total += 1;
366                *by_scope
367                    .entry((&letter.tenant_id, &letter.project_id))
368                    .or_insert(0_usize) += 1;
369                *by_target_agent
370                    .entry(letter.target_agent.clone())
371                    .or_insert(0) += 1;
372                if let Ok(failed_at) = OffsetDateTime::parse_from_rfc3339(&letter.first_failed_at) {
373                    let age = u64::try_from((now - failed_at.to_utc()).num_seconds()).unwrap_or(0);
374                    oldest_age_seconds = oldest_age_seconds.max(age);
375                }
376            }
377            Ok(DlqStats {
378                total,
379                max_scope_depth: by_scope.values().copied().max().unwrap_or(0),
380                oldest_age_seconds,
381                by_target_agent,
382            })
383        })
384    }
385
386    pub fn ensure_writable(&self, scope: &DlqScope) -> OclaResult<()> {
387        scope.validate()?;
388        match &self.backend {
389            QueueBackend::Memory(_) => Ok(()),
390            QueueBackend::Durable { root, process_lock } => {
391                let _process_guard = process_lock
392                    .lock()
393                    .unwrap_or_else(std::sync::PoisonError::into_inner);
394                prepare_store_directory(root).map_err(|error| store_error(&error))?;
395                let path = scope_store_path(root, scope);
396                let _lock =
397                    FileLock::acquire_with_timeout(&path.with_extension("lock"), LOCK_TIMEOUT)
398                        .map_err(|error| store_error(&std::io::Error::other(error)))?;
399                load_store(&path, Some(scope)).map_err(|error| store_error(&error))?;
400                probe_store_directory(root).map_err(|error| store_error(&error))
401            }
402            QueueBackend::Unavailable(error) => Err(OclaError::InvalidRequest(format!(
403                "dead letter store unavailable: {error}"
404            ))),
405        }
406    }
407
408    fn with_entries<R>(
409        &self,
410        scope: Option<&DlqScope>,
411        mutate: bool,
412        operation: impl FnOnce(&mut Vec<DeadLetter>) -> OclaResult<R>,
413    ) -> OclaResult<R> {
414        match &self.backend {
415            QueueBackend::Memory(entries) => {
416                let mut entries = entries
417                    .lock()
418                    .unwrap_or_else(std::sync::PoisonError::into_inner);
419                operation(&mut entries)
420            }
421            QueueBackend::Durable { root, process_lock } => {
422                let _process_guard = process_lock
423                    .lock()
424                    .unwrap_or_else(std::sync::PoisonError::into_inner);
425                if !root.exists() && !mutate {
426                    return operation(&mut Vec::new());
427                }
428                prepare_store_directory(root).map_err(|error| store_error(&error))?;
429                if let Some(scope) = scope {
430                    let path = scope_store_path(root, scope);
431                    let _lock =
432                        FileLock::acquire_with_timeout(&path.with_extension("lock"), LOCK_TIMEOUT)
433                            .map_err(|error| store_error(&std::io::Error::other(error)))?;
434                    let mut store =
435                        load_store(&path, Some(scope)).map_err(|error| store_error(&error))?;
436                    let result = operation(&mut store.entries)?;
437                    if mutate {
438                        save_store(&path, &store).map_err(|error| store_error(&error))?;
439                    }
440                    Ok(result)
441                } else {
442                    if mutate {
443                        return Err(OclaError::InvalidRequest(
444                            "unscoped durable DLQ mutation is forbidden".into(),
445                        ));
446                    }
447                    let mut entries =
448                        load_all_scope_entries(root).map_err(|error| store_error(&error))?;
449                    operation(&mut entries)
450                }
451            }
452            QueueBackend::Unavailable(error) => Err(OclaError::InvalidRequest(format!(
453                "dead letter store unavailable: {error}"
454            ))),
455        }
456    }
457}
458
459fn validate_identifier(label: &str, value: &str) -> OclaResult<()> {
460    if value.trim().is_empty() || value.len() > MAX_IDENTIFIER_BYTES || value.contains('\0') {
461        return Err(OclaError::InvalidRequest(format!("invalid {label}")));
462    }
463    Ok(())
464}
465
466fn store_error(error: &std::io::Error) -> OclaError {
467    OclaError::InvalidRequest(format!("dead letter store unavailable: {error}"))
468}
469
470fn resend_local(letter: &DeadLetter) -> OclaResult<()> {
471    AgentRegistry::mutate_locked(|registry| {
472        registry
473            .post_message(
474                "dead-letter-queue",
475                Some(&letter.target_agent),
476                "retry",
477                &letter.original_message,
478            )
479            .map(|_| ())
480    })
481    .and_then(|(_, result)| result)
482    .map_err(|error| OclaError::InvalidRequest(format!("dead letter retry failed: {error}")))
483}
484
485fn prepare_parent(path: &Path) -> std::io::Result<()> {
486    let parent = path.parent().ok_or_else(|| {
487        std::io::Error::new(std::io::ErrorKind::InvalidInput, "DLQ store has no parent")
488    })?;
489    #[cfg(unix)] // only the unix permission branch below reads it
490    let parent_existed = parent.exists();
491    for directory in [Some(parent), parent.parent()].into_iter().flatten() {
492        validate_directory(directory)?;
493    }
494    std::fs::create_dir_all(parent)?;
495    for directory in [Some(parent), parent.parent()].into_iter().flatten() {
496        validate_directory(directory)?;
497    }
498    #[cfg(unix)]
499    if !parent_existed {
500        use std::os::unix::fs::PermissionsExt;
501        std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
502    }
503    Ok(())
504}
505
506fn validate_directory(path: &Path) -> std::io::Result<()> {
507    match std::fs::symlink_metadata(path) {
508        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
509            Err(std::io::Error::new(
510                std::io::ErrorKind::InvalidData,
511                "DLQ path components must be real directories",
512            ))
513        }
514        Ok(_) => Ok(()),
515        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
516        Err(error) => Err(error),
517    }
518}
519
520fn prepare_store_directory(root: &Path) -> std::io::Result<()> {
521    let parent = root.parent().ok_or_else(|| {
522        std::io::Error::new(std::io::ErrorKind::InvalidInput, "DLQ root has no parent")
523    })?;
524    validate_directory(parent)?;
525    validate_directory(root)?;
526    std::fs::create_dir_all(root)?;
527    validate_directory(root)?;
528    #[cfg(unix)]
529    {
530        use std::os::unix::fs::MetadataExt;
531        let metadata = std::fs::metadata(root)?;
532        // SAFETY: `geteuid` has no arguments and only reads process credentials.
533        if metadata.uid() != unsafe { libc::geteuid() } {
534            return Err(std::io::Error::new(
535                std::io::ErrorKind::PermissionDenied,
536                "DLQ store directory must be owned by the current user",
537            ));
538        }
539        crate::core::secure_fs::restrict_to_owner(root)?;
540    }
541    Ok(())
542}
543
544fn scope_store_path(root: &Path, scope: &DlqScope) -> PathBuf {
545    let mut material = Vec::with_capacity(scope.tenant_id.len() + scope.project_id.len() + 1);
546    material.extend_from_slice(scope.tenant_id.as_bytes());
547    material.push(0);
548    material.extend_from_slice(scope.project_id.as_bytes());
549    root.join(format!("{}.json", blake3::hash(&material).to_hex()))
550}
551
552fn serialized_store_size(entries: &[DeadLetter]) -> OclaResult<u64> {
553    serde_json::to_vec_pretty(&DurableDlqV1 {
554        version: STORE_VERSION,
555        entries: entries.to_vec(),
556    })
557    .map(|json| json.len() as u64)
558    .map_err(|error| OclaError::InvalidRequest(format!("failed to size dead letters: {error}")))
559}
560
561fn load_all_scope_entries(root: &Path) -> std::io::Result<Vec<DeadLetter>> {
562    let mut entries = Vec::new();
563    for item in std::fs::read_dir(root)? {
564        let item = item?;
565        let file_type = item.file_type()?;
566        let name = item.file_name();
567        let name = name.to_str().ok_or_else(|| {
568            std::io::Error::new(
569                std::io::ErrorKind::InvalidData,
570                "invalid DLQ store filename",
571            )
572        })?;
573        if item.path().extension() == Some(std::ffi::OsStr::new("lock"))
574            || name == "migration-v1.complete"
575        {
576            continue;
577        }
578        if file_type.is_file() && is_scope_store_temp_name(name) {
579            continue;
580        }
581        if file_type.is_symlink() || !file_type.is_file() || !is_scope_store_name(name) {
582            return Err(std::io::Error::new(
583                std::io::ErrorKind::InvalidData,
584                "DLQ root contains an unexpected entry",
585            ));
586        }
587        let store = load_store(&item.path(), None)?;
588        if let Some(first) = store.entries.first() {
589            let scope = DlqScope::new(first.tenant_id.clone(), first.project_id.clone())
590                .map_err(std::io::Error::other)?;
591            if scope_store_path(root, &scope) != item.path()
592                || store.entries.iter().any(|entry| {
593                    entry.tenant_id != scope.tenant_id || entry.project_id != scope.project_id
594                })
595            {
596                return Err(std::io::Error::new(
597                    std::io::ErrorKind::InvalidData,
598                    "DLQ scope store identity does not match its contents",
599                ));
600            }
601        }
602        entries.extend(store.entries);
603    }
604    Ok(entries)
605}
606
607fn is_scope_store_name(name: &str) -> bool {
608    let path = Path::new(name);
609    path.extension() == Some(std::ffi::OsStr::new("json"))
610        && path.file_stem().is_some_and(|stem| {
611            let bytes = stem.as_encoded_bytes();
612            bytes.len() == 64 && bytes.iter().all(u8::is_ascii_hexdigit)
613        })
614}
615
616fn is_scope_store_temp_name(name: &str) -> bool {
617    let Some((store_name, suffix)) = name.split_once(".tmp-") else {
618        return false;
619    };
620    !suffix.is_empty()
621        && suffix
622            .bytes()
623            .all(|byte| byte.is_ascii_hexdigit() || byte == b'-')
624        && store_name.len() == 64
625        && store_name.bytes().all(|byte| byte.is_ascii_hexdigit())
626}
627
628fn probe_store_directory(root: &Path) -> std::io::Result<()> {
629    let path = root.join(format!("writable-{}.lock", uuid::Uuid::new_v4()));
630    let result = (|| {
631        let mut options = OpenOptions::new();
632        options.write(true).create_new(true);
633        #[cfg(unix)]
634        {
635            use std::os::unix::fs::OpenOptionsExt;
636            options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
637        }
638        #[cfg(windows)]
639        {
640            use std::os::windows::fs::OpenOptionsExt;
641            options.custom_flags(0x0020_0000);
642        }
643        options.open(&path)?.sync_all()?;
644        std::fs::remove_file(&path)
645    })();
646    if result.is_err() {
647        let _ = std::fs::remove_file(&path);
648    }
649    result
650}
651
652fn migrate_legacy_store(legacy_path: &Path, root: &Path) -> std::io::Result<()> {
653    if !legacy_path.exists() || root.join("migration-v1.complete").exists() {
654        return Ok(());
655    }
656    let _migration_lock =
657        FileLock::acquire_with_timeout(&root.join("migration-v1.lock"), LOCK_TIMEOUT)
658            .map_err(std::io::Error::other)?;
659    let marker = root.join("migration-v1.complete");
660    if marker.exists() {
661        return Ok(());
662    }
663    let legacy = load_store(legacy_path, None)?;
664    let mut grouped: BTreeMap<(String, String), Vec<DeadLetter>> = BTreeMap::new();
665    for letter in legacy.entries {
666        grouped
667            .entry((letter.tenant_id.clone(), letter.project_id.clone()))
668            .or_default()
669            .push(letter);
670    }
671    for ((tenant_id, project_id), letters) in grouped {
672        let scope = DlqScope::new(tenant_id, project_id).map_err(std::io::Error::other)?;
673        let path = scope_store_path(root, &scope);
674        let _scope_lock =
675            FileLock::acquire_with_timeout(&path.with_extension("lock"), LOCK_TIMEOUT)
676                .map_err(std::io::Error::other)?;
677        let mut current = load_store(&path, Some(&scope))?;
678        for letter in letters {
679            if let Some(existing) = current
680                .entries
681                .iter_mut()
682                .find(|entry| entry.id == letter.id)
683            {
684                if letter.last_failed_at > existing.last_failed_at {
685                    *existing = letter;
686                }
687            } else {
688                current.entries.push(letter);
689            }
690        }
691        if current.entries.len() > MAX_ENTRIES_PER_SCOPE {
692            let excess = current.entries.len() - MAX_ENTRIES_PER_SCOPE;
693            current.entries.drain(..excess);
694        }
695        while serialized_store_size(&current.entries).map_err(std::io::Error::other)?
696            > MAX_STORE_BYTES
697        {
698            if current.entries.is_empty() {
699                break;
700            }
701            current.entries.remove(0);
702        }
703        save_store(&path, &current)?;
704    }
705    write_marker(&marker)?;
706    let backup = legacy_path.with_extension("json.migrated-v1");
707    if !backup.exists() {
708        std::fs::rename(legacy_path, backup)?;
709        sync_parent(legacy_path)?;
710    }
711    Ok(())
712}
713
714fn write_marker(path: &Path) -> std::io::Result<()> {
715    let mut options = OpenOptions::new();
716    options.write(true).create_new(true);
717    #[cfg(unix)]
718    {
719        use std::os::unix::fs::OpenOptionsExt;
720        options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
721    }
722    #[cfg(windows)]
723    {
724        use std::os::windows::fs::OpenOptionsExt;
725        options.custom_flags(0x0020_0000);
726    }
727    let mut file = options.open(path)?;
728    file.write_all(b"v1\n")?;
729    file.sync_all()?;
730    sync_parent(path)
731}
732
733fn load_store(path: &Path, expected_scope: Option<&DlqScope>) -> std::io::Result<DurableDlqV1> {
734    let metadata = match std::fs::symlink_metadata(path) {
735        Ok(metadata) => metadata,
736        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
737            return Ok(DurableDlqV1::default());
738        }
739        Err(error) => return Err(error),
740    };
741    if metadata.file_type().is_symlink() || !metadata.is_file() {
742        return Err(std::io::Error::new(
743            std::io::ErrorKind::InvalidData,
744            "DLQ store must be a regular file",
745        ));
746    }
747    if metadata.len() > MAX_STORE_BYTES {
748        return Err(std::io::Error::new(
749            std::io::ErrorKind::InvalidData,
750            "DLQ store exceeds size limit",
751        ));
752    }
753    let mut content = Vec::new();
754    open_read_nofollow(path)?
755        .take(MAX_STORE_BYTES + 1)
756        .read_to_end(&mut content)?;
757    if content.len() as u64 > MAX_STORE_BYTES {
758        return Err(std::io::Error::new(
759            std::io::ErrorKind::InvalidData,
760            "DLQ store exceeds size limit",
761        ));
762    }
763    let mut store: DurableDlqV1 =
764        serde_json::from_slice(&content).map_err(std::io::Error::other)?;
765    if store.version != STORE_VERSION || store.entries.len() > MAX_ENTRIES_PER_SCOPE {
766        return Err(std::io::Error::new(
767            std::io::ErrorKind::InvalidData,
768            "invalid DLQ store bounds or version",
769        ));
770    }
771    for entry in &mut store.entries {
772        // Older v1 entries did not carry peer-scoped delivery identity. Keep
773        // them readable while making the compatibility scope explicit.
774        if entry.peer_id.is_empty() {
775            entry.peer_id = "legacy".to_string();
776        }
777        if entry.delivery_id.is_empty() {
778            entry.delivery_id = entry.id.clone();
779        }
780        entry
781            .validate()
782            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
783        if expected_scope.is_some_and(|scope| {
784            entry.tenant_id != scope.tenant_id || entry.project_id != scope.project_id
785        }) {
786            return Err(std::io::Error::new(
787                std::io::ErrorKind::InvalidData,
788                "DLQ scope store contains an entry from another scope",
789            ));
790        }
791    }
792    Ok(store)
793}
794
795fn save_store(path: &Path, store: &DurableDlqV1) -> std::io::Result<()> {
796    if let Ok(metadata) = std::fs::symlink_metadata(path)
797        && (metadata.file_type().is_symlink() || !metadata.is_file())
798    {
799        return Err(std::io::Error::new(
800            std::io::ErrorKind::InvalidData,
801            "DLQ store must be a regular file",
802        ));
803    }
804    let json = serde_json::to_vec_pretty(store).map_err(std::io::Error::other)?;
805    if json.len() as u64 > MAX_STORE_BYTES {
806        return Err(std::io::Error::new(
807            std::io::ErrorKind::InvalidData,
808            "DLQ store exceeds size limit",
809        ));
810    }
811    let tmp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
812    let result = (|| {
813        let mut options = OpenOptions::new();
814        options.write(true).create_new(true);
815        #[cfg(unix)]
816        {
817            use std::os::unix::fs::OpenOptionsExt;
818            options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
819        }
820        #[cfg(windows)]
821        {
822            use std::os::windows::fs::OpenOptionsExt;
823            options.custom_flags(0x0020_0000);
824        }
825        let mut file = options.open(&tmp)?;
826        file.write_all(&json)?;
827        file.sync_all()?;
828        drop(file);
829        atomic_replace(&tmp, path)?;
830        sync_parent(path)
831    })();
832    if result.is_err() {
833        let _ = std::fs::remove_file(&tmp);
834    }
835    result
836}
837
838fn open_read_nofollow(path: &Path) -> std::io::Result<File> {
839    let mut options = OpenOptions::new();
840    options.read(true);
841    #[cfg(unix)]
842    {
843        use std::os::unix::fs::OpenOptionsExt;
844        options.custom_flags(libc::O_NOFOLLOW);
845    }
846    #[cfg(windows)]
847    {
848        use std::os::windows::fs::OpenOptionsExt;
849        options.custom_flags(0x0020_0000);
850    }
851    options.open(path)
852}
853
854#[cfg(not(windows))]
855fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
856    std::fs::rename(source, destination)
857}
858
859#[cfg(windows)]
860fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
861    use std::os::windows::ffi::OsStrExt;
862    use windows_sys::Win32::Storage::FileSystem::{
863        MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
864    };
865
866    let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
867    let destination: Vec<u16> = destination
868        .as_os_str()
869        .encode_wide()
870        .chain(Some(0))
871        .collect();
872    // SAFETY: both vectors own the UTF-16 buffers, include a terminating NUL,
873    // and remain alive for the duration of the call.
874    let result = unsafe {
875        MoveFileExW(
876            source.as_ptr(),
877            destination.as_ptr(),
878            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
879        )
880    };
881    if result == 0 {
882        Err(std::io::Error::last_os_error())
883    } else {
884        Ok(())
885    }
886}
887
888fn sync_parent(path: &Path) -> std::io::Result<()> {
889    #[cfg(unix)]
890    if let Some(parent) = path.parent() {
891        File::open(parent)?.sync_all()?;
892    }
893    // `MoveFileExW(MOVEFILE_WRITE_THROUGH)` above waits for the replacement to
894    // reach disk. Windows does not support `FlushFileBuffers` on directory
895    // handles, so attempting the Unix parent-fsync pattern returns ACCESS_DENIED
896    // after an otherwise successful atomic replacement.
897    #[cfg(windows)]
898    let _ = path;
899    Ok(())
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    fn scope(tenant: &str, project: &str) -> DlqScope {
907        DlqScope::new(tenant, project).unwrap()
908    }
909    fn letter(id: &str, tenant: &str, project: &str) -> DeadLetter {
910        DeadLetter {
911            id: id.into(),
912            peer_id: "legacy".into(),
913            delivery_id: id.into(),
914            tenant_id: tenant.into(),
915            project_id: project.into(),
916            delivery: DeadLetterDelivery::LocalAgentBus,
917            original_message: format!("message-{id}"),
918            target_agent: "agent-a".into(),
919            error: "delivery failed".into(),
920            attempts: 1,
921            first_failed_at: "2026-01-01T00:00:00Z".into(),
922            last_failed_at: "2026-01-01T00:00:00Z".into(),
923        }
924    }
925
926    #[test]
927    fn scoped_operations_do_not_cross_tenant_or_project() {
928        let queue = DeadLetterQueue::new();
929        queue
930            .enqueue(letter("one", "tenant-a", "project-a"))
931            .unwrap();
932        queue
933            .enqueue(letter("one", "tenant-b", "project-a"))
934            .unwrap();
935        assert_eq!(
936            queue.peek(&scope("tenant-a", "project-a")).unwrap().len(),
937            1
938        );
939        assert!(
940            queue
941                .dequeue(&scope("tenant-a", "project-b"), "one")
942                .unwrap()
943                .is_none()
944        );
945        assert_eq!(queue.stats(None).unwrap().total, 2);
946    }
947
948    #[test]
949    fn persistent_queue_survives_reopen_and_deduplicates() {
950        let dir = tempfile::tempdir().unwrap();
951        let path = dir.path().join("a2a").join("dead-letters-v1.json");
952        let queue = DeadLetterQueue::persistent(path.clone()).unwrap();
953        queue
954            .enqueue(letter("one", "tenant-a", "project-a"))
955            .unwrap();
956        queue
957            .enqueue(letter("one", "tenant-a", "project-a"))
958            .unwrap();
959        drop(queue);
960        assert_eq!(
961            DeadLetterQueue::persistent(path)
962                .unwrap()
963                .peek(&scope("tenant-a", "project-a"))
964                .unwrap()
965                .len(),
966            1
967        );
968    }
969
970    #[test]
971    fn concurrent_persistent_enqueues_do_not_lose_entries() {
972        let dir = tempfile::tempdir().unwrap();
973        let path = dir.path().join("a2a").join("dead-letters-v1.json");
974        let queue = DeadLetterQueue::persistent(path.clone()).unwrap();
975        let workers: Vec<_> = (0..8)
976            .map(|worker| {
977                let queue = queue.clone();
978                std::thread::spawn(move || {
979                    for item in 0..25 {
980                        queue
981                            .enqueue(letter(
982                                &format!("worker-{worker}-item-{item}"),
983                                "tenant-a",
984                                "project-a",
985                            ))
986                            .unwrap();
987                    }
988                })
989            })
990            .collect();
991        for worker in workers {
992            worker.join().unwrap();
993        }
994        drop(queue);
995        assert_eq!(
996            DeadLetterQueue::persistent(path)
997                .unwrap()
998                .peek(&scope("tenant-a", "project-a"))
999                .unwrap()
1000                .len(),
1001            200
1002        );
1003    }
1004
1005    #[test]
1006    fn corrupt_oversized_and_symlink_stores_fail_closed() {
1007        let dir = tempfile::tempdir().unwrap();
1008        let corrupt = dir.path().join("corrupt.json");
1009        std::fs::write(&corrupt, b"not json").unwrap();
1010        assert!(DeadLetterQueue::persistent(corrupt).is_err());
1011        let oversized = dir.path().join("oversized.json");
1012        std::fs::write(&oversized, vec![b'x'; (MAX_STORE_BYTES + 1) as usize]).unwrap();
1013        assert!(DeadLetterQueue::persistent(oversized).is_err());
1014        #[cfg(unix)]
1015        {
1016            use std::os::unix::fs::symlink;
1017            let target = dir.path().join("target.json");
1018            std::fs::write(&target, b"{}").unwrap();
1019            let link = dir.path().join("link.json");
1020            symlink(&target, &link).unwrap();
1021            assert!(DeadLetterQueue::persistent(link).is_err());
1022        }
1023    }
1024
1025    #[test]
1026    fn remote_entries_cannot_be_retried_as_local_messages() {
1027        let queue = DeadLetterQueue::new();
1028        let mut item = letter("one", "tenant-a", "project-a");
1029        item.delivery = DeadLetterDelivery::RemoteHttp {
1030            endpoint_url: "https://agent.example".into(),
1031        };
1032        queue.enqueue(item).unwrap();
1033        assert!(queue.retry(&scope("tenant-a", "project-a"), "one").is_err());
1034        assert_eq!(queue.stats(None).unwrap().total, 1);
1035    }
1036
1037    #[test]
1038    fn invalid_attempts_time_order_and_endpoint_credentials_are_rejected() {
1039        let queue = DeadLetterQueue::new();
1040        let mut zero_attempts = letter("zero", "tenant-a", "project-a");
1041        zero_attempts.attempts = 0;
1042        assert!(queue.enqueue(zero_attempts).is_err());
1043
1044        let mut reversed = letter("reversed", "tenant-a", "project-a");
1045        reversed.last_failed_at = "2025-01-01T00:00:00Z".into();
1046        assert!(queue.enqueue(reversed).is_err());
1047
1048        let mut credential_url = letter("credentials", "tenant-a", "project-a");
1049        credential_url.delivery = DeadLetterDelivery::RemoteHttp {
1050            endpoint_url: "https://user:secret@agent.example".into(),
1051        };
1052        assert!(queue.enqueue(credential_url).is_err());
1053        assert_eq!(queue.stats(None).unwrap().total, 0);
1054    }
1055
1056    #[test]
1057    fn per_scope_capacity_never_evicts_another_scope() {
1058        let queue = DeadLetterQueue::new();
1059        queue
1060            .enqueue(letter("protected", "tenant-b", "project-b"))
1061            .unwrap();
1062        for index in 0..=MAX_ENTRIES_PER_SCOPE {
1063            queue
1064                .enqueue(letter(&format!("a-{index}"), "tenant-a", "project-a"))
1065                .unwrap();
1066        }
1067        let protected = queue.peek(&scope("tenant-b", "project-b")).unwrap();
1068        assert_eq!(protected.len(), 1);
1069        assert_eq!(protected[0].id, "protected");
1070        let tenant_a = queue.peek(&scope("tenant-a", "project-a")).unwrap();
1071        assert_eq!(tenant_a.len(), MAX_ENTRIES_PER_SCOPE);
1072        assert_eq!(tenant_a.first().unwrap().id, "a-1");
1073    }
1074
1075    #[test]
1076    fn durable_scopes_use_distinct_files_and_byte_eviction_is_local() {
1077        let dir = tempfile::tempdir().unwrap();
1078        let legacy = dir.path().join("dead-letters-v1.json");
1079        let queue = DeadLetterQueue::persistent(legacy.clone()).unwrap();
1080        let mut protected = letter("protected", "tenant-b", "project-b");
1081        protected.original_message = "b".repeat(MAX_MESSAGE_BYTES);
1082        queue.enqueue(protected).unwrap();
1083        for index in 0..5 {
1084            let mut item = letter(&format!("large-{index}"), "tenant-a", "project-a");
1085            item.original_message = "a".repeat(MAX_MESSAGE_BYTES);
1086            queue.enqueue(item).unwrap();
1087        }
1088
1089        let root = legacy.with_extension("d");
1090        let scope_a = scope("tenant-a", "project-a");
1091        let scope_b = scope("tenant-b", "project-b");
1092        assert_ne!(
1093            scope_store_path(&root, &scope_a),
1094            scope_store_path(&root, &scope_b)
1095        );
1096        assert_eq!(queue.peek(&scope_b).unwrap().len(), 1);
1097        let tenant_a = queue.peek(&scope_a).unwrap();
1098        assert!(!tenant_a.is_empty(), "`tenant_a` is empty");
1099        assert!(tenant_a.len() < 5);
1100        assert!(
1101            std::fs::metadata(scope_store_path(&root, &scope_a))
1102                .unwrap()
1103                .len()
1104                <= MAX_STORE_BYTES
1105        );
1106    }
1107
1108    #[test]
1109    fn compact_legacy_boundary_is_readable_and_next_enqueue_uses_writer_size() {
1110        let dir = tempfile::tempdir().unwrap();
1111        let legacy = dir.path().join("dead-letters-v1.json");
1112        let root = legacy.with_extension("d");
1113        let scope = scope("tenant-a", "project-a");
1114        let queue = DeadLetterQueue::persistent(&legacy).unwrap();
1115        prepare_store_directory(&root).unwrap();
1116
1117        let mut entries = (0..MAX_ENTRIES_PER_SCOPE)
1118            .map(|index| {
1119                let mut item = letter(&format!("boundary-{index}"), "tenant-a", "project-a");
1120                item.original_message = "x".repeat(8_200);
1121                item
1122            })
1123            .collect::<Vec<_>>();
1124        while serde_json::to_vec(&DurableDlqV1 {
1125            version: STORE_VERSION,
1126            entries: entries.clone(),
1127        })
1128        .unwrap()
1129        .len() as u64
1130            > MAX_STORE_BYTES
1131        {
1132            entries.remove(0);
1133        }
1134        let compact = serde_json::to_vec(&DurableDlqV1 {
1135            version: STORE_VERSION,
1136            entries: entries.clone(),
1137        })
1138        .unwrap();
1139        assert!(compact.len() as u64 <= MAX_STORE_BYTES);
1140        assert!(
1141            serde_json::to_vec_pretty(&DurableDlqV1 {
1142                version: STORE_VERSION,
1143                entries,
1144            })
1145            .unwrap()
1146            .len() as u64
1147                > MAX_STORE_BYTES
1148        );
1149        std::fs::write(scope_store_path(&root, &scope), compact).unwrap();
1150
1151        queue.ensure_writable(&scope).unwrap();
1152        queue
1153            .enqueue(letter("after-boundary", "tenant-a", "project-a"))
1154            .unwrap();
1155        let stored = std::fs::metadata(scope_store_path(&root, &scope)).unwrap();
1156        assert!(stored.len() <= MAX_STORE_BYTES);
1157        assert!(queue.get(&scope, "after-boundary").unwrap().is_some());
1158    }
1159
1160    #[test]
1161    fn aggregate_stats_ignore_regular_interrupted_write_artifacts() {
1162        let dir = tempfile::tempdir().unwrap();
1163        let legacy = dir.path().join("dead-letters-v1.json");
1164        let scope = scope("tenant-a", "project-a");
1165        let queue = DeadLetterQueue::persistent(&legacy).unwrap();
1166        queue
1167            .enqueue(letter("good", "tenant-a", "project-a"))
1168            .unwrap();
1169        let store = scope_store_path(&legacy.with_extension("d"), &scope);
1170        let tmp = store.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
1171        std::fs::write(&tmp, b"partial").unwrap();
1172
1173        assert_eq!(queue.stats(None).unwrap().total, 1);
1174        std::fs::remove_file(tmp).unwrap();
1175    }
1176
1177    #[cfg(unix)]
1178    #[test]
1179    fn persistent_store_repairs_preexisting_directory_permissions() {
1180        use std::os::unix::fs::PermissionsExt;
1181
1182        let dir = tempfile::tempdir().unwrap();
1183        let legacy = dir.path().join("dead-letters-v1.json");
1184        let root = legacy.with_extension("d");
1185        std::fs::create_dir(&root).unwrap();
1186        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o777)).unwrap();
1187
1188        let queue = DeadLetterQueue::persistent(&legacy).unwrap();
1189        queue
1190            .enqueue(letter("private", "tenant-a", "project-a"))
1191            .unwrap();
1192        assert_eq!(
1193            std::fs::metadata(root).unwrap().permissions().mode() & 0o777,
1194            0o700
1195        );
1196    }
1197
1198    #[test]
1199    fn legacy_global_store_migrates_without_cross_scope_cohabitation() {
1200        let dir = tempfile::tempdir().unwrap();
1201        let legacy = dir.path().join("dead-letters-v1.json");
1202        save_store(
1203            &legacy,
1204            &DurableDlqV1 {
1205                version: STORE_VERSION,
1206                entries: vec![
1207                    letter("a", "tenant-a", "project-a"),
1208                    letter("b", "tenant-b", "project-b"),
1209                ],
1210            },
1211        )
1212        .unwrap();
1213
1214        let queue = DeadLetterQueue::persistent(legacy.clone()).unwrap();
1215        assert!(!legacy.exists());
1216        assert_eq!(
1217            queue.peek(&scope("tenant-a", "project-a")).unwrap().len(),
1218            1
1219        );
1220        assert_eq!(
1221            queue.peek(&scope("tenant-b", "project-b")).unwrap().len(),
1222            1
1223        );
1224        let stores = std::fs::read_dir(legacy.with_extension("d"))
1225            .unwrap()
1226            .filter_map(Result::ok)
1227            .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))
1228            .count();
1229        assert_eq!(stores, 2);
1230    }
1231
1232    #[test]
1233    fn corrupt_scope_does_not_block_another_scope_or_reopen() {
1234        let dir = tempfile::tempdir().unwrap();
1235        let legacy = dir.path().join("dead-letters-v1.json");
1236        let scope_a = scope("tenant-a", "project-a");
1237        let scope_b = scope("tenant-b", "project-b");
1238        let queue = DeadLetterQueue::persistent(legacy.clone()).unwrap();
1239        queue
1240            .enqueue(letter("good", "tenant-a", "project-a"))
1241            .unwrap();
1242        queue
1243            .enqueue(letter("bad", "tenant-b", "project-b"))
1244            .unwrap();
1245        std::fs::write(
1246            scope_store_path(&legacy.with_extension("d"), &scope_b),
1247            b"not json",
1248        )
1249        .unwrap();
1250
1251        let reopened = DeadLetterQueue::persistent(legacy).unwrap();
1252        assert_eq!(reopened.peek(&scope_a).unwrap()[0].id, "good");
1253        assert!(reopened.peek(&scope_b).is_err());
1254    }
1255
1256    #[test]
1257    fn read_only_stats_does_not_create_store_directory() {
1258        let dir = tempfile::tempdir().unwrap();
1259        let legacy = dir.path().join("missing").join("dead-letters-v1.json");
1260        let root = legacy.with_extension("d");
1261        let queue = DeadLetterQueue::persistent(legacy).unwrap();
1262
1263        assert_eq!(queue.stats(None).unwrap().total, 0);
1264        assert!(!root.exists());
1265    }
1266
1267    #[test]
1268    fn aggregate_stats_report_worst_scope_depth() {
1269        let queue = DeadLetterQueue::new();
1270        queue
1271            .enqueue(letter("a1", "tenant-a", "project-a"))
1272            .unwrap();
1273        queue
1274            .enqueue(letter("a2", "tenant-a", "project-a"))
1275            .unwrap();
1276        queue
1277            .enqueue(letter("b1", "tenant-b", "project-b"))
1278            .unwrap();
1279
1280        let stats = queue.stats(None).unwrap();
1281        assert_eq!(stats.total, 3);
1282        assert_eq!(stats.max_scope_depth, 2);
1283        assert_eq!(
1284            queue
1285                .stats(Some(&scope("tenant-b", "project-b")))
1286                .unwrap()
1287                .max_scope_depth,
1288            1
1289        );
1290    }
1291
1292    #[test]
1293    fn successful_local_retry_atomically_persists_removal() {
1294        // A retry persists the agent registry below the data directory: an own
1295        // one, or the run lands in whatever a parallel test set and removes.
1296        let _data = crate::core::data_dir::isolated_data_dir();
1297        let dir = tempfile::tempdir().unwrap();
1298        let legacy = dir.path().join("dead-letters-v1.json");
1299        let scope = scope("tenant-a", "project-a");
1300        let queue = DeadLetterQueue::persistent(legacy.clone()).unwrap();
1301        let mut item = letter("retry", "tenant-a", "project-a");
1302        item.target_agent = "retry-target".into();
1303        queue.enqueue(item).unwrap();
1304
1305        queue.retry(&scope, "retry").unwrap();
1306        drop(queue);
1307        let stored = DeadLetterQueue::persistent(legacy)
1308            .unwrap()
1309            .peek(&scope)
1310            .unwrap();
1311        assert!(stored.is_empty(), "{stored:?}");
1312    }
1313
1314    #[test]
1315    fn retry_lock_artifacts_are_bounded_per_scope() {
1316        let dir = tempfile::tempdir().unwrap();
1317        let legacy = dir.path().join("dead-letters-v1.json");
1318        let queue = DeadLetterQueue::persistent(&legacy).unwrap();
1319        let scope_a = scope("tenant-a", "project-a");
1320        let scope_b = scope("tenant-b", "project-b");
1321        queue
1322            .enqueue(letter("first", "tenant-a", "project-a"))
1323            .unwrap();
1324        queue
1325            .enqueue(letter("third", "tenant-b", "project-b"))
1326            .unwrap();
1327
1328        drop(queue.lock_retry(&scope_a, "first").unwrap());
1329        drop(queue.lock_retry(&scope_a, "second").unwrap());
1330        drop(queue.lock_retry(&scope_b, "third").unwrap());
1331
1332        let retry_locks = std::fs::read_dir(legacy.with_extension("d"))
1333            .unwrap()
1334            .filter_map(Result::ok)
1335            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".retry.lock"))
1336            .count();
1337        assert_eq!(retry_locks, 2);
1338    }
1339}