Skip to main content

laser_wire/
kv.rs

1use crate::error::InvalidError;
2use crate::limits::MAX_NAMESPACE_BYTES;
3use crate::mutation::MutationPosition;
4use serde::{Deserialize, Serialize};
5
6/// The memory scope a read-view row carries, stamped by the fold from the
7/// record's headers so recall reconstructs a memory item and narrows by scope.
8/// Absent on a generic key-value entry, which carries no scope.
9#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
10#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
11pub struct MemoryRowScope {
12    /// The item kind word, from the record body.
13    #[serde(default, skip_serializing_if = "Option::is_none")]
14    pub kind: Option<String>,
15    /// The producing agent, from `gen_ai.agent.id`.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub agent: Option<String>,
18    /// The user scope layer, from `agdx.mem.user`.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub user: Option<String>,
21    /// The app scope layer, from `agdx.mem.app`.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub app: Option<String>,
24    /// The conversation that wrote the record, from `gen_ai.conversation.id`.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub conversation: Option<String>,
27    /// The origin log record this memory item was folded from (stream, topic,
28    /// partition, offset), so a reader can navigate back to the source message
29    /// while it is still on the log. Absent when unknown.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub source: Option<crate::graph::SourceRef>,
32    /// The server append time of the source record in microseconds. With the
33    /// source address, it orders items remembered on different partitions.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub timestamp_micros: Option<u64>,
36    /// The feedback weight folded for this item, the sum of every feedback
37    /// record that targets it. Recall ranks every strategy except recent by it.
38    /// Absent when no feedback was recorded.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub weight: Option<f32>,
41}
42
43/// One stored entry: an arbitrary-bytes key and value plus optional expiry. The
44/// key and value are owned `Vec<u8>`, so the public API never leaks the `bytes`
45/// crate, and they ride the wire as CBOR byte strings, byte-exact.
46#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48pub struct KvEntry {
49    #[cfg_attr(
50        feature = "schemars",
51        schemars(schema_with = "crate::encoding::bytes_schema")
52    )]
53    #[serde(with = "crate::encoding::bin_bytes")]
54    pub key: Vec<u8>,
55    #[cfg_attr(
56        feature = "schemars",
57        schemars(schema_with = "crate::encoding::bytes_schema")
58    )]
59    #[serde(with = "crate::encoding::bin_bytes")]
60    pub value: Vec<u8>,
61    /// Absolute expiry in epoch microseconds, or `None` for no expiry. Expired
62    /// entries are hidden on read.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub expires_at_micros: Option<u64>,
65    /// Optimistic-concurrency version, assigned by the store and bumped on every
66    /// successful mutation of this key. The token a [`KvCas`] precondition
67    /// matches against. A versioned managed backend reports `>= 1` for a live
68    /// entry and reserves `0` solely for "unversioned": a store that does not
69    /// track versions, or an entry written before versioning. A caller must
70    /// therefore never treat `0` as a valid compare token. The field is skipped
71    /// on the wire when `0` so those entries stay byte-identical.
72    #[serde(default, skip_serializing_if = "is_zero_u64")]
73    pub version: u64,
74    /// The memory scope, present only on a memory read-view row. Recall reads it
75    /// to rebuild the item and filter by scope. A generic entry leaves it `None`.
76    /// Boxed so a generic entry stays small (the scope is five optional strings).
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub scope: Option<Box<MemoryRowScope>>,
79    /// The origin log record this entry was folded from (stream, topic,
80    /// partition, offset). Every managed write goes log-first through a
81    /// mutation topic, so a stored entry points back to the record that wrote
82    /// it, the same provenance a memory row carries. Absent on an entry
83    /// written before provenance stamping, or read from a store that does not
84    /// track it. Boxed, like `scope`, so a generic entry stays small.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub source: Option<Box<crate::graph::SourceRef>>,
87}
88
89fn is_zero_u64(value: &u64) -> bool {
90    *value == 0
91}
92
93impl KvEntry {
94    /// The key decoded as UTF-8, or `None` when it is not valid UTF-8. Keys are
95    /// arbitrary bytes, so a binary key has no string form.
96    pub fn key_str(&self) -> Option<&str> {
97        std::str::from_utf8(&self.key).ok()
98    }
99}
100
101/// One page of scanned entries in key order. `page` counts from 1, and
102/// `total_results` counts every live match of the scan, so a caller reads any
103/// page directly.
104#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106pub struct KvPage {
107    pub items: Vec<KvEntry>,
108    pub page: u32,
109    pub total_pages: u32,
110    pub total_results: u32,
111}
112
113/// Request to read the value at `key` in `namespace`. With `if_none_match` set to
114/// a version, the read returns [`KvOutcome::NotModified`] instead of the value
115/// when the live version matches (a conditional GET), so an up-to-date cache
116/// skips the body transfer.
117///
118/// With `min_position` set, the read is barriered: the answering fold must have
119/// applied at least that [`MutationPosition`] before reading, so a takeover
120/// reader cannot observe a fold that predates its own lease acquisition. The
121/// server waits a short bound and answers [`KvError::Stale`] when the fold does
122/// not catch up, never an absent value. Only a deployment advertising the
123/// `KV_FENCED_LEASES` capability honors the barrier: a pre-fencing backend
124/// ignores the field, so a client must not send it unless the bit is
125/// advertised. Absent keeps today's immediate local read, byte-identical.
126#[derive(Clone, Debug, Serialize, Deserialize)]
127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
128pub struct KvGet {
129    pub v: u32,
130    pub namespace: String,
131    #[cfg_attr(
132        feature = "schemars",
133        schemars(schema_with = "crate::encoding::bytes_schema")
134    )]
135    #[serde(with = "crate::encoding::bin_bytes")]
136    pub key: Vec<u8>,
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub if_none_match: Option<u64>,
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub min_position: Option<MutationPosition>,
141}
142
143/// Request to write `value` at `key` in `namespace`, with an optional expiry.
144#[derive(Clone, Debug, Serialize, Deserialize)]
145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
146pub struct KvSet {
147    pub v: u32,
148    pub namespace: String,
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub session: Option<crate::agent::SessionRef>,
151    #[cfg_attr(
152        feature = "schemars",
153        schemars(schema_with = "crate::encoding::bytes_schema")
154    )]
155    #[serde(with = "crate::encoding::bin_bytes")]
156    pub key: Vec<u8>,
157    #[cfg_attr(
158        feature = "schemars",
159        schemars(schema_with = "crate::encoding::bytes_schema")
160    )]
161    #[serde(with = "crate::encoding::bin_bytes")]
162    pub value: Vec<u8>,
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub expires_at_micros: Option<u64>,
165    /// Expire the entry this long after the mutation's server timestamp. The
166    /// relative form a client clock cannot skew, resolved once at fold time
167    /// so every replica stores the same expiry. Mutually exclusive with
168    /// `expires_at_micros`, a request carrying both is refused.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub ttl_micros: Option<u64>,
171}
172
173/// The precondition a [`KvCas`] write must satisfy to apply. The compare half
174/// of compare-and-swap: lock-free optimistic concurrency for callers contending
175/// on one key.
176#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
178pub enum CasExpect {
179    /// Apply only if the key currently holds this exact [`KvEntry::version`].
180    Match(u64),
181    /// Apply only if the key does not currently exist (a create-if-absent).
182    Absent,
183}
184
185/// Compare-and-swap write at `key` in `namespace`: apply `value` (with optional
186/// expiry) only if `expect` holds, else fail with
187/// [`KvError::VersionConflict`]. The swap half of optimistic concurrency, paired
188/// with [`KvEntry::version`] as the compare token.
189#[derive(Clone, Debug, Serialize, Deserialize)]
190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
191pub struct KvCas {
192    pub v: u32,
193    pub namespace: String,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub session: Option<crate::agent::SessionRef>,
196    #[cfg_attr(
197        feature = "schemars",
198        schemars(schema_with = "crate::encoding::bytes_schema")
199    )]
200    #[serde(with = "crate::encoding::bin_bytes")]
201    pub key: Vec<u8>,
202    #[cfg_attr(
203        feature = "schemars",
204        schemars(schema_with = "crate::encoding::bytes_schema")
205    )]
206    #[serde(with = "crate::encoding::bin_bytes")]
207    pub value: Vec<u8>,
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub expires_at_micros: Option<u64>,
210    /// Expire the entry this long after the mutation's server timestamp. The
211    /// relative form a client clock cannot skew, resolved once at fold time
212    /// so every replica stores the same expiry. Mutually exclusive with
213    /// `expires_at_micros`, a request carrying both is refused.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub ttl_micros: Option<u64>,
216    pub expect: CasExpect,
217}
218
219/// Fenced compare-and-swap: the [`KvCas`] write and precondition, applied in
220/// one backend transaction that also requires a **live** lease at
221/// (`fence_namespace`, `fence_key`) and a fence sequence still equal to
222/// `fence_token`. A released or expired lease, or a stale token, maps to
223/// [`KvError::LeaseLost`] even before another holder acquires, and a failed
224/// precondition to [`KvError::VersionConflict`]. The request uses
225/// [`crate::codes::KV_LEASE_OP_VERSION`]. Required fence fields have no decode
226/// defaults and any other `v` fails [`crate::validate::Validate`] fail-closed.
227#[derive(Clone, Debug, Serialize, Deserialize)]
228#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
229pub struct KvCasFenced {
230    pub v: u32,
231    pub namespace: String,
232    /// The session this write is linked to, as on [`KvCas`].
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub session: Option<crate::agent::SessionRef>,
235    #[cfg_attr(
236        feature = "schemars",
237        schemars(schema_with = "crate::encoding::bytes_schema")
238    )]
239    #[serde(with = "crate::encoding::bin_bytes")]
240    pub key: Vec<u8>,
241    #[cfg_attr(
242        feature = "schemars",
243        schemars(schema_with = "crate::encoding::bytes_schema")
244    )]
245    #[serde(with = "crate::encoding::bin_bytes")]
246    pub value: Vec<u8>,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub expires_at_micros: Option<u64>,
249    /// Expire the entry this long after the mutation's server timestamp. The
250    /// relative form a client clock cannot skew, resolved once at fold time
251    /// so every replica stores the same expiry. Mutually exclusive with
252    /// `expires_at_micros`, a request carrying both is refused.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub ttl_micros: Option<u64>,
255    pub expect: CasExpect,
256    /// The coordination namespace holding the lease and fence rows. Authorized
257    /// separately from the target `namespace` (`kv_fence:read`), so a state
258    /// writer can present a fence without being able to mutate it.
259    pub fence_namespace: String,
260    /// The lease key whose live row and fence sequence gate this write.
261    #[cfg_attr(
262        feature = "schemars",
263        schemars(schema_with = "crate::encoding::bytes_schema")
264    )]
265    #[serde(with = "crate::encoding::bin_bytes")]
266    pub fence_key: Vec<u8>,
267    /// The fencing token: the fence-sequence value the holder was granted.
268    /// Strictly monotonic per key, never the lease-row version.
269    pub fence_token: u64,
270}
271
272/// Request to remove `key` from `namespace`. With `if_match` set to a version,
273/// the delete applies only when the live version matches (a conditional delete),
274/// returning [`KvError::VersionConflict`] otherwise.
275#[derive(Clone, Debug, Serialize, Deserialize)]
276#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
277pub struct KvDelete {
278    pub v: u32,
279    pub namespace: String,
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub session: Option<crate::agent::SessionRef>,
282    #[cfg_attr(
283        feature = "schemars",
284        schemars(schema_with = "crate::encoding::bytes_schema")
285    )]
286    #[serde(with = "crate::encoding::bin_bytes")]
287    pub key: Vec<u8>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub if_match: Option<u64>,
290}
291
292/// Request to test presence and read metadata without the value. The cheap way
293/// to check a precondition before transferring a large value (the formal
294/// `EXISTS` primitive).
295#[derive(Clone, Debug, Serialize, Deserialize)]
296#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
297pub struct KvExists {
298    pub v: u32,
299    pub namespace: String,
300    #[cfg_attr(
301        feature = "schemars",
302        schemars(schema_with = "crate::encoding::bytes_schema")
303    )]
304    #[serde(with = "crate::encoding::bin_bytes")]
305    pub key: Vec<u8>,
306}
307
308/// Request to set, refresh, or clear a key's expiry in place without rewriting
309/// its value. `expires_at_micros` of `None` clears the expiry (the formal
310/// `EXPIRE` primitive).
311#[derive(Clone, Debug, Serialize, Deserialize)]
312#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
313pub struct KvExpire {
314    pub v: u32,
315    pub namespace: String,
316    #[cfg_attr(
317        feature = "schemars",
318        schemars(schema_with = "crate::encoding::bytes_schema")
319    )]
320    #[serde(with = "crate::encoding::bin_bytes")]
321    pub key: Vec<u8>,
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub expires_at_micros: Option<u64>,
324    /// Expire the entry this long after the mutation's server timestamp. The
325    /// relative form a client clock cannot skew, resolved once at fold time
326    /// so every replica stores the same expiry. Mutually exclusive with
327    /// `expires_at_micros`, a request carrying both is refused.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub ttl_micros: Option<u64>,
330}
331
332/// Request to apply a merge patch to a structured value without transferring the
333/// whole object. `patch` is a codec-specific patch document (the `content_type`
334/// names the format). With `if_match` set, the patch applies only at that version
335/// (the formal `PATCH` primitive).
336#[derive(Clone, Debug, Serialize, Deserialize)]
337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
338pub struct KvPatch {
339    pub v: u32,
340    pub namespace: String,
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub session: Option<crate::agent::SessionRef>,
343    #[cfg_attr(
344        feature = "schemars",
345        schemars(schema_with = "crate::encoding::bytes_schema")
346    )]
347    #[serde(with = "crate::encoding::bin_bytes")]
348    pub key: Vec<u8>,
349    #[cfg_attr(
350        feature = "schemars",
351        schemars(schema_with = "crate::encoding::bytes_schema")
352    )]
353    #[serde(with = "crate::encoding::bin_bytes")]
354    pub patch: Vec<u8>,
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub if_match: Option<u64>,
357}
358
359/// Request to copy the value at `key` to `to_key` (optionally into another
360/// namespace via `to_namespace`) in a single backend transaction. `Committed`
361/// on success, `NotFound` when the source is absent. The destination is
362/// overwritten (a guarded copy composes `exists` + `cas` instead).
363#[derive(Clone, Debug, Serialize, Deserialize)]
364#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
365pub struct KvCopy {
366    pub v: u32,
367    pub namespace: String,
368    #[cfg_attr(
369        feature = "schemars",
370        schemars(schema_with = "crate::encoding::bytes_schema")
371    )]
372    #[serde(with = "crate::encoding::bin_bytes")]
373    pub key: Vec<u8>,
374    /// The destination namespace. Absent means the source `namespace`.
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub to_namespace: Option<String>,
377    #[cfg_attr(
378        feature = "schemars",
379        schemars(schema_with = "crate::encoding::bytes_schema")
380    )]
381    #[serde(with = "crate::encoding::bin_bytes")]
382    pub to_key: Vec<u8>,
383}
384
385/// Request to move the value at `key` to `to_key`: copy plus delete of the
386/// source, one backend transaction, the same outcomes as [`KvCopy`].
387#[derive(Clone, Debug, Serialize, Deserialize)]
388#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
389pub struct KvMove {
390    pub v: u32,
391    pub namespace: String,
392    #[cfg_attr(
393        feature = "schemars",
394        schemars(schema_with = "crate::encoding::bytes_schema")
395    )]
396    #[serde(with = "crate::encoding::bin_bytes")]
397    pub key: Vec<u8>,
398    /// The destination namespace. Absent means the source `namespace`.
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub to_namespace: Option<String>,
401    #[cfg_attr(
402        feature = "schemars",
403        schemars(schema_with = "crate::encoding::bytes_schema")
404    )]
405    #[serde(with = "crate::encoding::bin_bytes")]
406    pub to_key: Vec<u8>,
407}
408
409/// Request to acquire a revocable lease (a bounded-TTL distributed lock) on
410/// `key`. On success the store atomically creates the live lease row and bumps
411/// the never-expiring fence sequence. The holder gets the new `lease_token`
412/// and the granted TTL (the formal `LEASE` primitive). A live lease always
413/// conflicts: renewal is [`KvLeaseRenew`], never re-acquisition. The request
414/// uses [`crate::codes::KV_LEASE_OP_VERSION`] and requires holder identity.
415#[derive(Clone, Debug, Serialize, Deserialize)]
416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
417pub struct KvLease {
418    pub v: u32,
419    pub namespace: String,
420    #[cfg_attr(
421        feature = "schemars",
422        schemars(schema_with = "crate::encoding::bytes_schema")
423    )]
424    #[serde(with = "crate::encoding::bin_bytes")]
425    pub key: Vec<u8>,
426    /// Requested maximum lifetime, within
427    /// [`MIN_LEASE_TTL_MICROS`](crate::limits::MIN_LEASE_TTL_MICROS)`..=`[`MAX_LEASE_TTL_MICROS`](crate::limits::MAX_LEASE_TTL_MICROS).
428    /// A successful grant is nonzero and never exceeds this duration, so this
429    /// remains a conservative expiry bound when the grant reply is lost. The
430    /// store may grant less but never more, which is why the range is
431    /// validated on the request rather than clamped.
432    pub lease_ttl_micros: u64,
433    /// Stable identity of the acquiring holder (a node or worker id, never a
434    /// connection-scoped value). Renewal and release must present the same
435    /// holder, so a different process cannot extend or drop a lease it does
436    /// not hold.
437    pub holder_id: String,
438    /// The user the lease protects mutations for. `None` leases for the
439    /// authenticated caller. `Some` is a delegated acquisition (an operator
440    /// leasing on behalf of a runtime user) and requires the `kv_lease:admin`
441    /// grant. The fence then validates against the subject's rows.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub subject_user_id: Option<u32>,
444}
445
446/// Request to extend a held lease without changing its token (the formal
447/// `RENEW` primitive). The store requires the same holder (and subject), a
448/// live lease row, and the current fence token, then moves the expiry forward
449/// and returns [`KvOutcome::Renewed`] with the same token: renewal never bumps
450/// the fence. An expired or re-acquired lease answers
451/// [`KvError::LeaseLost`], so a deposed holder learns immediately.
452#[derive(Clone, Debug, Serialize, Deserialize)]
453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
454pub struct KvLeaseRenew {
455    pub v: u32,
456    pub namespace: String,
457    #[cfg_attr(
458        feature = "schemars",
459        schemars(schema_with = "crate::encoding::bytes_schema")
460    )]
461    #[serde(with = "crate::encoding::bin_bytes")]
462    pub key: Vec<u8>,
463    pub holder_id: String,
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub subject_user_id: Option<u32>,
466    pub lease_token: u64,
467    /// Requested maximum extended lifetime, within the same
468    /// [`MIN_LEASE_TTL_MICROS`](crate::limits::MIN_LEASE_TTL_MICROS)`..=`[`MAX_LEASE_TTL_MICROS`](crate::limits::MAX_LEASE_TTL_MICROS)
469    /// range as acquisition. A successful renewal is nonzero and never exceeds
470    /// this duration.
471    pub lease_ttl_micros: u64,
472}
473
474/// Request to release a held lease early, presenting the same `holder_id` and
475/// the `lease_token` the grant returned (the formal `RELEASE` primitive). The
476/// token is validated against the fence sequence, never the lease-row version
477/// (which resets on re-acquire), and the live row is physically removed in the
478/// same transaction. A missing or expired row under a still-current fence is
479/// the idempotent [`KvOutcome::Released`]`(false)`. A stale fence is
480/// [`KvError::LeaseLost`].
481#[derive(Clone, Debug, Serialize, Deserialize)]
482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
483pub struct KvRelease {
484    pub v: u32,
485    pub namespace: String,
486    #[cfg_attr(
487        feature = "schemars",
488        schemars(schema_with = "crate::encoding::bytes_schema")
489    )]
490    #[serde(with = "crate::encoding::bin_bytes")]
491    pub key: Vec<u8>,
492    pub lease_token: u64,
493    pub holder_id: String,
494}
495
496/// One key's metadata without its value: version, expiry, and value size. The
497/// reply to [`KvExists`].
498#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
499#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
500pub struct KvMetadata {
501    pub version: u64,
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub expires_at_micros: Option<u64>,
504    pub size_bytes: usize,
505}
506
507/// Request to list every namespace that holds at least one entry for the caller.
508#[derive(Clone, Debug, Serialize, Deserialize)]
509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
510pub struct KvNamespaces {
511    pub v: u32,
512    /// The stream whose resources the listing covers. Required in stream
513    /// tenancy, where the server authorizes the stream and lists only its
514    /// resources.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub stream: Option<String>,
517}
518
519/// One namespace summary in a `Namespaces` reply.
520#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
521#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
522pub struct KvNamespaceInfo {
523    pub namespace: String,
524    pub entries: usize,
525}
526
527/// Request to list entries in `namespace`. With no bounds it lists the whole
528/// namespace. `prefix` matches keys that start with it in byte order. `start`
529/// and `end` bound an inclusive-start, exclusive-end key range. `key_contains`
530/// keeps only keys that are valid UTF-8 and contain the substring (binary keys
531/// are skipped). All bounds compose.
532#[derive(Clone, Debug, Serialize, Deserialize)]
533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
534pub struct KvScan {
535    pub v: u32,
536    pub namespace: String,
537    #[cfg_attr(
538        feature = "schemars",
539        schemars(schema_with = "crate::encoding::opt_bytes_schema")
540    )]
541    #[serde(
542        default,
543        skip_serializing_if = "Option::is_none",
544        with = "crate::encoding::opt_bin_bytes"
545    )]
546    pub prefix: Option<Vec<u8>>,
547    #[cfg_attr(
548        feature = "schemars",
549        schemars(schema_with = "crate::encoding::opt_bytes_schema")
550    )]
551    #[serde(
552        default,
553        skip_serializing_if = "Option::is_none",
554        with = "crate::encoding::opt_bin_bytes"
555    )]
556    pub start: Option<Vec<u8>>,
557    #[cfg_attr(
558        feature = "schemars",
559        schemars(schema_with = "crate::encoding::opt_bytes_schema")
560    )]
561    #[serde(
562        default,
563        skip_serializing_if = "Option::is_none",
564        with = "crate::encoding::opt_bin_bytes"
565    )]
566    pub end: Option<Vec<u8>>,
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub key_contains: Option<String>,
569    /// The conversation lens: keep only rows the given conversation wrote (the
570    /// text form of its `gen_ai.conversation.id`). The memory read view stamps
571    /// this on each record it materializes, generic key-value rows leave it
572    /// unset, so a scan narrows to one conversation's memory. Absent on the wire
573    /// when unfiltered, so a pre-lens scan stays byte-identical.
574    #[serde(default, skip_serializing_if = "Option::is_none")]
575    pub conversation: Option<String>,
576    /// The stream the lens conversation belongs to. Set alongside
577    /// `conversation` by a client that scopes its resources to a stream.
578    /// Absent on the wire when unset.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub stream: Option<String>,
581    /// The memory scope lenses: keep only memory-view rows stamped with this
582    /// user (`agdx.mem.user`), agent (`gen_ai.agent.id`), or app
583    /// (`agdx.mem.app`). Generic key-value rows carry none, so a lens filters
584    /// them out. Absent on the wire when unfiltered.
585    #[serde(default, skip_serializing_if = "Option::is_none")]
586    pub user: Option<String>,
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub agent: Option<String>,
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub app: Option<String>,
591    /// The 1-based page, over the matches in key order. Zero reads the first
592    /// page.
593    #[serde(default)]
594    pub page: u32,
595    /// The entries per page, at most [`MAX_SCAN_LIMIT`](crate::limits::MAX_SCAN_LIMIT).
596    /// Zero reads [`DEFAULT_SCAN_LIMIT`](crate::limits::DEFAULT_SCAN_LIMIT).
597    pub results: u32,
598}
599
600/// Request to bulk-delete entries in `namespace` matching the same composed
601/// bounds as a scan (`prefix`/`start`/`end`/`key_contains`). With no bounds it
602/// clears the whole namespace. No `page`/`results`, and expiry is ignored (a
603/// matching expired entry is removed too).
604#[derive(Clone, Debug, Serialize, Deserialize)]
605#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
606pub struct KvDeleteMany {
607    pub v: u32,
608    pub namespace: String,
609    #[cfg_attr(
610        feature = "schemars",
611        schemars(schema_with = "crate::encoding::opt_bytes_schema")
612    )]
613    #[serde(
614        default,
615        skip_serializing_if = "Option::is_none",
616        with = "crate::encoding::opt_bin_bytes"
617    )]
618    pub prefix: Option<Vec<u8>>,
619    #[cfg_attr(
620        feature = "schemars",
621        schemars(schema_with = "crate::encoding::opt_bytes_schema")
622    )]
623    #[serde(
624        default,
625        skip_serializing_if = "Option::is_none",
626        with = "crate::encoding::opt_bin_bytes"
627    )]
628    pub start: Option<Vec<u8>>,
629    #[cfg_attr(
630        feature = "schemars",
631        schemars(schema_with = "crate::encoding::opt_bytes_schema")
632    )]
633    #[serde(
634        default,
635        skip_serializing_if = "Option::is_none",
636        with = "crate::encoding::opt_bin_bytes"
637    )]
638    pub end: Option<Vec<u8>>,
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub key_contains: Option<String>,
641    /// The conversation lens over a bulk delete: clear only the rows a given
642    /// conversation wrote. See [`KvScan::conversation`]. Absent when unfiltered.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub conversation: Option<String>,
645    /// The stream the lens conversation belongs to. See [`KvScan::stream`].
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub stream: Option<String>,
648}
649
650/// The result of a key-value operation: `Ok` with the operation's outcome, or
651/// `Err` with a structured failure.
652#[derive(Clone, Debug, Serialize, Deserialize)]
653#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
654#[non_exhaustive]
655pub enum KvReply {
656    Ok(KvOutcome),
657    Err(KvError),
658}
659
660/// The successful outcome of a KV command, shaped per op.
661#[derive(Clone, Debug, Serialize, Deserialize)]
662#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
663#[non_exhaustive]
664pub enum KvOutcome {
665    /// `get`: the live entry, or `None` when absent or expired.
666    Value(Option<KvEntry>),
667    /// `set`: the write was applied.
668    Written,
669    /// `cas`: the compare-and-swap applied. Carries the entry's new version, so
670    /// the caller can chain a further conditional write without a re-read.
671    Committed { version: u64 },
672    /// `delete`: `true` when a live entry was removed, `false` when none existed.
673    Deleted(bool),
674    /// `delete_many`: the number of entries removed by a filtered bulk delete.
675    DeletedMany(usize),
676    /// `scan`: one page of entries.
677    Page(KvPage),
678    /// `namespaces`: every namespace holding at least one entry for the
679    /// caller with its entry count, sorted by name.
680    Namespaces(Vec<KvNamespaceInfo>),
681    /// `get` with `if_none_match`: the live version matched, so the body is
682    /// unchanged and not transferred (a conditional-GET hit).
683    NotModified,
684    /// `exists`: the key's metadata, or `None` when absent or expired.
685    Metadata(Option<KvMetadata>),
686    /// `expire` / `patch`: applied, carrying the entry's version. `expire` leaves
687    /// the version unchanged, `patch` bumps it.
688    Versioned { version: u64 },
689    /// `lease`: the lease was granted, carrying the fencing token, the granted
690    /// nonzero TTL (which the store may clamp down from, but never above, the
691    /// request), and the mutation
692    /// position at which the answering fold applied the grant, the barrier a
693    /// takeover read passes back as [`KvGet::min_position`].
694    Leased {
695        lease_token: u64,
696        granted_ttl_micros: u64,
697        position: MutationPosition,
698    },
699    /// `lease_renew`: the lease was extended, carrying the unchanged token,
700    /// the granted TTL, and the renewal's applied mutation position. A caller
701    /// treating an unexpected variant here as success would trust an
702    /// unextended deadline, so decode fail-closed.
703    Renewed {
704        lease_token: u64,
705        granted_ttl_micros: u64,
706        position: MutationPosition,
707    },
708    /// `release`: `true` when a held lease was released, `false` when none was
709    /// held (idempotent release).
710    Released(bool),
711}
712
713/// Why a key-value operation failed.
714#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
715#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
716#[non_exhaustive]
717pub enum KvError {
718    #[error("kv not supported: {0}")]
719    Unsupported(String),
720    #[error("invalid key: {0}")]
721    InvalidKey(String),
722    /// The request named a namespace that fails [`validate_namespace`].
723    #[error("invalid namespace: {0}")]
724    InvalidNamespace(String),
725    #[error("{what} is {size}B, exceeds cap {cap}B")]
726    TooLarge {
727        what: String,
728        size: usize,
729        cap: usize,
730    },
731    #[error("kv backend error: {0}")]
732    Backend(String),
733    /// The request could not be served right now and the identical request may
734    /// succeed later: the store was momentarily out of reach, a connection was
735    /// refused or dropped, or a concurrency conflict was aborted. Retry with
736    /// backoff rather than treating it as a fault.
737    #[error("temporarily unavailable: {0}")]
738    Unavailable(String),
739    #[error("unsupported kv op version (expected {expected}, got {got})")]
740    Version { expected: u32, got: u32 },
741    /// A [`KvCas`] precondition was not met. `current` is the key's present
742    /// version (`Some`) or `None` when the key does not exist, so the caller can
743    /// re-read and retry, or learn that an `Absent` precondition lost a race.
744    #[error("kv version conflict (current: {current:?})")]
745    VersionConflict { current: Option<u64> },
746    /// A held [`KvLease`] expired, was released, or was re-acquired by another
747    /// holder, so its token no longer protects mutations. The caller must stop
748    /// its protected work. A new epoch needs a fresh acquisition.
749    #[error("kv lease lost")]
750    LeaseLost,
751    /// A [`KvLease`] found the key held by a live lease. `expires_at_micros`
752    /// is the holder's expiry in log time, the earliest a fresh acquisition can
753    /// succeed unless the holder renews.
754    #[error("kv lease held (expires at: {expires_at_micros:?})")]
755    LeaseHeld { expires_at_micros: Option<u64> },
756    /// A barriered [`KvGet`] could not be answered: the local fold did not
757    /// reach `required` within the server's wait bound. Explicitly never mapped
758    /// to an absent value. Retry against a caught-up fold.
759    #[error("kv read barrier not reached (required: {required:?})")]
760    Stale { required: MutationPosition },
761    /// A barriered [`KvGet`] named a position no wait can reach: an older
762    /// topic generation of the mutation log, or a partition it does not use.
763    /// Never retryable. The caller acquires again for a position on the
764    /// current log.
765    #[error("kv read barrier unreachable (required: {required:?})")]
766    BarrierUnreachable { required: MutationPosition },
767    /// An in-place op (`expire`, `patch`) targeted a key that is absent or
768    /// expired (the formal `NOT_FOUND`).
769    #[error("kv key not found")]
770    NotFound,
771    /// This managed backend does not own the mutation partition for the key. The caller
772    /// may retry after the streaming client refreshes partition leadership.
773    #[error("not the partition leader for this key")]
774    NotLeader,
775    /// The caller authenticated but lacks the grant the operation needs on
776    /// the namespace (`kv:write`, `kv_lease:admin`, `kv_fence:read`).
777    #[error("kv operation not permitted: {0}")]
778    Forbidden(String),
779    /// A write named both an absolute expiry and a relative TTL.
780    #[error("invalid kv expiry: {0}")]
781    InvalidExpiry(String),
782}
783
784/// The absolute expiry a write stores: `expires_at_micros` as given, or
785/// `ttl_micros` after `now_micros`, the mutation's server timestamp, so every
786/// replica folding the same record stores the same expiry. A write naming
787/// both is refused.
788pub fn resolve_expiry(
789    expires_at_micros: Option<u64>,
790    ttl_micros: Option<u64>,
791    now_micros: u64,
792) -> Result<Option<u64>, InvalidError> {
793    match (expires_at_micros, ttl_micros) {
794        (Some(_), Some(_)) => Err(InvalidError::new(
795            "a write names either expires_at_micros or ttl_micros, not both",
796        )),
797        (Some(expires_at_micros), None) => Ok(Some(expires_at_micros)),
798        (None, ttl_micros) => Ok(ttl_micros.map(|ttl| now_micros.saturating_add(ttl))),
799    }
800}
801
802/// The canonical namespace rule, shared by the SDK client edge and every
803/// serving tier: non-empty, at most [`MAX_NAMESPACE_BYTES`] bytes, no ASCII
804/// control characters. The charset is otherwise open, so `/`-style hierarchy
805/// stays legal. The bound is a size and sanity cap, not a safelist.
806pub fn validate_namespace(namespace: &str) -> Result<(), InvalidError> {
807    if namespace.is_empty() {
808        return Err(InvalidError::new("namespace must not be empty"));
809    }
810    if namespace.len() > MAX_NAMESPACE_BYTES {
811        return Err(InvalidError::new(format!(
812            "namespace is {}B, exceeds cap {MAX_NAMESPACE_BYTES}B",
813            namespace.len()
814        )));
815    }
816    if namespace.bytes().any(|byte| byte.is_ascii_control()) {
817        return Err(InvalidError::new(
818            "namespace must not contain ASCII control characters",
819        ));
820    }
821    Ok(())
822}
823
824#[cfg(all(test, feature = "cbor"))]
825mod tests {
826    use super::*;
827    use crate::codes::KV_OP_VERSION;
828    use crate::framing::{decode_named, encode_named};
829    use crate::result::ResultCode;
830
831    #[test]
832    fn given_a_held_lease_or_an_unreachable_barrier_when_round_tripped_then_should_keep_fields_and_codes()
833     {
834        let required = MutationPosition {
835            topic_generation: 7,
836            partition: 0,
837            offset: 3,
838        };
839        for (error, code) in [
840            (
841                KvError::LeaseHeld {
842                    expires_at_micros: Some(1_700_000_000_000_000),
843                },
844                ResultCode::Conflict,
845            ),
846            (
847                KvError::BarrierUnreachable { required },
848                ResultCode::StaleGeneration,
849            ),
850        ] {
851            let bytes = encode_named(&KvReply::Err(error.clone())).expect("serializes");
852            let back: KvReply = decode_named(&bytes).expect("deserializes");
853            assert!(matches!(back, KvReply::Err(ref decoded) if *decoded == error));
854            assert_eq!(ResultCode::from(&error), code);
855        }
856        assert!(
857            !ResultCode::StaleGeneration.is_retryable(),
858            "an unreachable barrier is never retried"
859        );
860    }
861
862    #[test]
863    fn given_an_absolute_expiry_or_a_ttl_when_resolved_then_should_store_one_expiry_and_refuse_both()
864     {
865        assert_eq!(resolve_expiry(Some(9), None, 100), Ok(Some(9)));
866        assert_eq!(
867            resolve_expiry(None, Some(30), 100),
868            Ok(Some(130)),
869            "a TTL counts from the server timestamp of the write"
870        );
871        assert_eq!(resolve_expiry(None, None, 100), Ok(None));
872        assert_eq!(
873            resolve_expiry(None, Some(u64::MAX), 100),
874            Ok(Some(u64::MAX))
875        );
876        assert!(resolve_expiry(Some(9), Some(30), 100).is_err());
877    }
878
879    #[test]
880    fn given_kv_delete_many_when_round_tripped_then_should_preserve_bounds() {
881        let request = KvDeleteMany {
882            v: KV_OP_VERSION,
883            namespace: "sessions".to_owned(),
884            prefix: Some(b"user:".to_vec()),
885            start: None,
886            end: None,
887            key_contains: Some("stale".to_owned()),
888            conversation: None,
889            stream: None,
890        };
891        let bytes = encode_named(&request).expect("serializes");
892        let back: KvDeleteMany = decode_named(&bytes).expect("deserializes");
893        assert_eq!(back.prefix, Some(b"user:".to_vec()));
894        assert_eq!(back.key_contains.as_deref(), Some("stale"));
895    }
896
897    #[test]
898    fn given_kv_deleted_many_reply_when_round_tripped_then_should_preserve_count() {
899        let reply = KvReply::Ok(KvOutcome::DeletedMany(7));
900        let bytes = encode_named(&reply).expect("serializes");
901        let back: KvReply = decode_named(&bytes).expect("deserializes");
902        match back {
903            KvReply::Ok(KvOutcome::DeletedMany(n)) => assert_eq!(n, 7),
904            other => panic!("expected DeletedMany, got {other:?}"),
905        }
906    }
907
908    #[test]
909    fn given_a_set_request_when_round_tripped_then_should_preserve_value_and_expiry() {
910        let request = KvSet {
911            v: KV_OP_VERSION,
912            namespace: "sessions".to_owned(),
913            session: None,
914            key: b"user:42".to_vec(),
915            value: b"online".to_vec(),
916            expires_at_micros: Some(1_700_000_000_000_000),
917            ttl_micros: None,
918        };
919        let bytes = encode_named(&request).expect("the request serializes");
920        let back: KvSet = decode_named(&bytes).expect("the request deserializes");
921        assert_eq!(back.key, b"user:42");
922        assert_eq!(back.value, b"online");
923        assert_eq!(back.expires_at_micros, Some(1_700_000_000_000_000));
924    }
925
926    #[test]
927    fn given_a_binary_key_entry_when_round_tripped_then_should_preserve_raw_bytes() {
928        let reply = KvReply::Ok(KvOutcome::Value(Some(KvEntry {
929            key: vec![0xff, 0x00, 0xfe],
930            value: vec![0x00, 0x01, 0x02],
931            expires_at_micros: None,
932            version: 0,
933            scope: None,
934            source: None,
935        })));
936        let bytes = encode_named(&reply).expect("the reply serializes");
937        let back: KvReply = decode_named(&bytes).expect("the reply deserializes");
938        let KvReply::Ok(KvOutcome::Value(Some(entry))) = back else {
939            panic!("expected an Ok(Value(Some)) reply");
940        };
941        assert_eq!(entry.key, vec![0xff, 0x00, 0xfe]);
942        assert_eq!(entry.key_str(), None, "non-UTF-8 key has no string form");
943        assert_eq!(entry.value, vec![0x00, 0x01, 0x02]);
944    }
945
946    #[test]
947    fn given_a_scan_page_when_round_tripped_then_should_preserve_the_page_and_totals() {
948        let page = KvPage {
949            items: vec![KvEntry {
950                key: b"a".to_vec(),
951                value: b"1".to_vec(),
952                expires_at_micros: None,
953                version: 0,
954                scope: None,
955                source: None,
956            }],
957            page: 2,
958            total_pages: 3,
959            total_results: 21,
960        };
961        let bytes = encode_named(&KvReply::Ok(KvOutcome::Page(page.clone()))).expect("serializes");
962        let back: KvReply = decode_named(&bytes).expect("deserializes");
963        let KvReply::Ok(KvOutcome::Page(decoded)) = back else {
964            panic!("expected an Ok(Page) reply");
965        };
966        assert_eq!(decoded, page);
967    }
968
969    #[test]
970    fn given_a_cas_request_when_round_tripped_then_should_preserve_the_precondition() {
971        for expect in [CasExpect::Match(7), CasExpect::Absent] {
972            let request = KvCas {
973                v: KV_OP_VERSION,
974                namespace: "counters".to_owned(),
975                session: None,
976                key: b"hits".to_vec(),
977                value: b"42".to_vec(),
978                expires_at_micros: None,
979                ttl_micros: None,
980                expect,
981            };
982            let bytes = encode_named(&request).expect("serializes");
983            let back: KvCas = decode_named(&bytes).expect("deserializes");
984            assert_eq!(back.expect, expect);
985            assert_eq!(back.key, b"hits");
986        }
987    }
988
989    #[test]
990    fn given_a_committed_reply_when_round_tripped_then_should_preserve_the_version() {
991        let reply = KvReply::Ok(KvOutcome::Committed { version: 9 });
992        let bytes = encode_named(&reply).expect("serializes");
993        let back: KvReply = decode_named(&bytes).expect("deserializes");
994        match back {
995            KvReply::Ok(KvOutcome::Committed { version }) => assert_eq!(version, 9),
996            other => panic!("expected Committed, got {other:?}"),
997        }
998    }
999
1000    #[test]
1001    fn given_an_exists_metadata_reply_when_round_tripped_then_should_preserve_metadata() {
1002        let reply = KvReply::Ok(KvOutcome::Metadata(Some(KvMetadata {
1003            version: 4,
1004            expires_at_micros: Some(1_700_000_000_000_000),
1005            size_bytes: 128,
1006        })));
1007        let bytes = encode_named(&reply).expect("serializes");
1008        let back: KvReply = decode_named(&bytes).expect("deserializes");
1009        let KvReply::Ok(KvOutcome::Metadata(Some(meta))) = back else {
1010            panic!("expected Ok(Metadata(Some))");
1011        };
1012        assert_eq!(meta.version, 4);
1013        assert_eq!(meta.size_bytes, 128);
1014    }
1015
1016    #[test]
1017    fn given_a_patch_request_when_round_tripped_then_should_preserve_patch_and_precondition() {
1018        let request = KvPatch {
1019            v: KV_OP_VERSION,
1020            namespace: "docs".to_owned(),
1021            session: None,
1022            key: b"doc:1".to_vec(),
1023            patch: br#"{"status":"closed"}"#.to_vec(),
1024            if_match: Some(3),
1025        };
1026        let bytes = encode_named(&request).expect("serializes");
1027        let back: KvPatch = decode_named(&bytes).expect("deserializes");
1028        assert_eq!(back.patch, br#"{"status":"closed"}"#);
1029        assert_eq!(back.if_match, Some(3));
1030    }
1031
1032    #[test]
1033    fn given_a_lease_reply_when_round_tripped_then_should_preserve_token_ttl_and_position() {
1034        let position = MutationPosition {
1035            topic_generation: 3,
1036            partition: 1,
1037            offset: 4_200,
1038        };
1039        for reply in [
1040            KvReply::Ok(KvOutcome::Leased {
1041                lease_token: 77,
1042                granted_ttl_micros: 30_000_000,
1043                position,
1044            }),
1045            KvReply::Ok(KvOutcome::Renewed {
1046                lease_token: 77,
1047                granted_ttl_micros: 30_000_000,
1048                position,
1049            }),
1050        ] {
1051            let bytes = encode_named(&reply).expect("serializes");
1052            let back: KvReply = decode_named(&bytes).expect("deserializes");
1053            match back {
1054                KvReply::Ok(
1055                    KvOutcome::Leased {
1056                        lease_token,
1057                        granted_ttl_micros,
1058                        position: got,
1059                    }
1060                    | KvOutcome::Renewed {
1061                        lease_token,
1062                        granted_ttl_micros,
1063                        position: got,
1064                    },
1065                ) => {
1066                    assert_eq!(lease_token, 77);
1067                    assert_eq!(granted_ttl_micros, 30_000_000);
1068                    assert_eq!(got, position);
1069                }
1070                other => panic!("expected Leased or Renewed, got {other:?}"),
1071            }
1072        }
1073    }
1074
1075    #[test]
1076    fn given_a_reshaped_lease_request_when_round_tripped_then_should_preserve_holder_and_subject() {
1077        let request = KvLease {
1078            v: crate::codes::KV_LEASE_OP_VERSION,
1079            namespace: "connectors.coordination".to_owned(),
1080            key: b"source-owner".to_vec(),
1081            lease_ttl_micros: 30_000_000,
1082            holder_id: "node-1".to_owned(),
1083            subject_user_id: Some(42),
1084        };
1085        let bytes = encode_named(&request).expect("serializes");
1086        let back: KvLease = decode_named(&bytes).expect("deserializes");
1087        assert_eq!(back.holder_id, "node-1");
1088        assert_eq!(back.subject_user_id, Some(42));
1089        // A self-lease omits the subject on the wire.
1090        let own = KvLease {
1091            subject_user_id: None,
1092            ..request
1093        };
1094        let json = serde_json::to_string(&own).expect("json");
1095        assert!(!json.contains("subject_user_id"), "absent subject omitted");
1096    }
1097
1098    #[test]
1099    fn given_a_renew_request_when_round_tripped_then_should_preserve_token_and_holder() {
1100        let request = KvLeaseRenew {
1101            v: crate::codes::KV_LEASE_OP_VERSION,
1102            namespace: "connectors.coordination".to_owned(),
1103            key: b"source-owner".to_vec(),
1104            holder_id: "node-1".to_owned(),
1105            subject_user_id: None,
1106            lease_token: 7,
1107            lease_ttl_micros: 30_000_000,
1108        };
1109        let bytes = encode_named(&request).expect("serializes");
1110        let back: KvLeaseRenew = decode_named(&bytes).expect("deserializes");
1111        assert_eq!(back.lease_token, 7);
1112        assert_eq!(back.holder_id, "node-1");
1113    }
1114
1115    #[test]
1116    fn given_a_pre_fencing_lease_payload_when_decoded_then_should_fail_closed() {
1117        // The v1 shapes, re-declared locally: no holder identity on lease and
1118        // release, no coordination namespace on the fenced CAS. The reshape
1119        // made those fields required, so an old payload must fail decode
1120        // rather than fill in defaults.
1121        #[derive(Serialize)]
1122        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1123        struct LegacyLease<'a> {
1124            v: u32,
1125            namespace: &'a str,
1126            #[cfg_attr(
1127                feature = "schemars",
1128                schemars(schema_with = "crate::encoding::bytes_schema")
1129            )]
1130            #[serde(with = "crate::encoding::bin_bytes")]
1131            key: &'a [u8],
1132            lease_ttl_micros: u64,
1133        }
1134        let legacy = encode_named(&LegacyLease {
1135            v: KV_OP_VERSION,
1136            namespace: "sessions",
1137            key: b"job",
1138            lease_ttl_micros: 30_000_000,
1139        })
1140        .expect("legacy shape serializes");
1141        assert!(
1142            decode_named::<KvLease>(&legacy).is_err(),
1143            "a holder-less lease payload must not decode"
1144        );
1145
1146        #[derive(Serialize)]
1147        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1148        struct LegacyRelease<'a> {
1149            v: u32,
1150            namespace: &'a str,
1151            #[cfg_attr(
1152                feature = "schemars",
1153                schemars(schema_with = "crate::encoding::bytes_schema")
1154            )]
1155            #[serde(with = "crate::encoding::bin_bytes")]
1156            key: &'a [u8],
1157            lease_token: u64,
1158        }
1159        let legacy = encode_named(&LegacyRelease {
1160            v: KV_OP_VERSION,
1161            namespace: "sessions",
1162            key: b"job",
1163            lease_token: 7,
1164        })
1165        .expect("legacy shape serializes");
1166        assert!(
1167            decode_named::<KvRelease>(&legacy).is_err(),
1168            "a holder-less release payload must not decode"
1169        );
1170
1171        #[derive(Serialize)]
1172        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1173        struct LegacyCasFenced<'a> {
1174            v: u32,
1175            namespace: &'a str,
1176            #[cfg_attr(
1177                feature = "schemars",
1178                schemars(schema_with = "crate::encoding::bytes_schema")
1179            )]
1180            #[serde(with = "crate::encoding::bin_bytes")]
1181            key: &'a [u8],
1182            #[cfg_attr(
1183                feature = "schemars",
1184                schemars(schema_with = "crate::encoding::bytes_schema")
1185            )]
1186            #[serde(with = "crate::encoding::bin_bytes")]
1187            value: &'a [u8],
1188            expect: CasExpect,
1189            #[cfg_attr(
1190                feature = "schemars",
1191                schemars(schema_with = "crate::encoding::bytes_schema")
1192            )]
1193            #[serde(with = "crate::encoding::bin_bytes")]
1194            fence_key: &'a [u8],
1195            fence_token: u64,
1196        }
1197        let legacy = encode_named(&LegacyCasFenced {
1198            v: KV_OP_VERSION,
1199            namespace: "sessions",
1200            key: b"cursor",
1201            value: b"42",
1202            expect: CasExpect::Absent,
1203            fence_key: b"job",
1204            fence_token: 7,
1205        })
1206        .expect("legacy shape serializes");
1207        assert!(
1208            decode_named::<KvCasFenced>(&legacy).is_err(),
1209            "a fence-only CAS payload must not decode"
1210        );
1211    }
1212
1213    #[test]
1214    fn given_a_stale_reply_when_round_tripped_then_should_preserve_the_required_position() {
1215        let required = MutationPosition {
1216            topic_generation: 2,
1217            partition: 0,
1218            offset: 99,
1219        };
1220        let reply = KvReply::Err(KvError::Stale { required });
1221        let bytes = encode_named(&reply).expect("serializes");
1222        let back: KvReply = decode_named(&bytes).expect("deserializes");
1223        match back {
1224            KvReply::Err(KvError::Stale { required: got }) => assert_eq!(got, required),
1225            other => panic!("expected Stale, got {other:?}"),
1226        }
1227    }
1228
1229    #[test]
1230    fn given_a_conditional_get_when_round_tripped_then_should_preserve_if_none_match() {
1231        let request = KvGet {
1232            v: KV_OP_VERSION,
1233            namespace: "sessions".to_owned(),
1234            key: b"user:1".to_vec(),
1235            if_none_match: Some(5),
1236            min_position: None,
1237        };
1238        let bytes = encode_named(&request).expect("serializes");
1239        let back: KvGet = decode_named(&bytes).expect("deserializes");
1240        assert_eq!(back.if_none_match, Some(5));
1241        // A plain get omits the precondition and the barrier on the wire, so
1242        // the pre-conditional contract stays byte-identical.
1243        let plain = KvGet {
1244            if_none_match: None,
1245            ..request
1246        };
1247        let json = serde_json::to_string(&plain).expect("json");
1248        assert!(
1249            !json.contains("if_none_match"),
1250            "absent precondition omitted"
1251        );
1252        assert!(!json.contains("min_position"), "absent barrier omitted");
1253    }
1254
1255    #[test]
1256    fn given_a_barriered_get_when_round_tripped_then_should_preserve_the_minimum_position() {
1257        let request = KvGet {
1258            v: KV_OP_VERSION,
1259            namespace: "connectors.state".to_owned(),
1260            key: b"source_state/pg".to_vec(),
1261            if_none_match: None,
1262            min_position: Some(MutationPosition {
1263                topic_generation: 1,
1264                partition: 0,
1265                offset: 512,
1266            }),
1267        };
1268        let bytes = encode_named(&request).expect("serializes");
1269        let back: KvGet = decode_named(&bytes).expect("deserializes");
1270        assert_eq!(
1271            back.min_position,
1272            Some(MutationPosition {
1273                topic_generation: 1,
1274                partition: 0,
1275                offset: 512,
1276            })
1277        );
1278    }
1279
1280    #[test]
1281    fn given_a_version_conflict_when_round_tripped_then_should_preserve_the_current_version() {
1282        for current in [Some(3u64), None] {
1283            let reply = KvReply::Err(KvError::VersionConflict { current });
1284            let bytes = encode_named(&reply).expect("serializes");
1285            let back: KvReply = decode_named(&bytes).expect("deserializes");
1286            match back {
1287                KvReply::Err(KvError::VersionConflict { current: got }) => assert_eq!(got, current),
1288                other => panic!("expected VersionConflict, got {other:?}"),
1289            }
1290        }
1291    }
1292
1293    #[test]
1294    fn given_a_versioned_entry_when_round_tripped_then_should_preserve_version_and_skip_zero() {
1295        let entry = KvEntry {
1296            key: b"k".to_vec(),
1297            value: b"v".to_vec(),
1298            expires_at_micros: None,
1299            version: 5,
1300            scope: None,
1301            source: None,
1302        };
1303        let bytes = encode_named(&entry).expect("serializes");
1304        let back: KvEntry = decode_named(&bytes).expect("deserializes");
1305        assert_eq!(back.version, 5);
1306        // An unversioned entry (version 0) omits the field on the wire, so a
1307        // pre-versioning store stays byte-identical.
1308        let unversioned = KvEntry {
1309            version: 0,
1310            ..entry
1311        };
1312        let json = serde_json::to_string(&unversioned).expect("json");
1313        assert!(
1314            !json.contains("version"),
1315            "version 0 must be omitted: {json}"
1316        );
1317    }
1318
1319    #[test]
1320    fn given_a_scan_with_bounds_when_round_tripped_then_should_preserve_filters() {
1321        let scan = KvScan {
1322            v: KV_OP_VERSION,
1323            namespace: "sessions".to_owned(),
1324            prefix: Some(b"user:".to_vec()),
1325            start: None,
1326            end: None,
1327            key_contains: Some("admin".to_owned()),
1328            conversation: None,
1329            stream: None,
1330            user: None,
1331            agent: None,
1332            app: None,
1333            page: 3,
1334            results: 50,
1335        };
1336        let bytes = encode_named(&scan).expect("serializes");
1337        let back: KvScan = decode_named(&bytes).expect("deserializes");
1338        assert_eq!(back.prefix.as_deref(), Some(b"user:".as_ref()));
1339        assert_eq!(back.key_contains.as_deref(), Some("admin"));
1340        assert_eq!((back.page, back.results), (3, 50));
1341        assert_eq!(back.stream, None);
1342    }
1343
1344    #[test]
1345    fn given_a_lens_with_a_stream_when_round_tripped_then_should_preserve_it_and_omit_it_when_unset()
1346     {
1347        let scan = KvScan {
1348            v: KV_OP_VERSION,
1349            namespace: "stream:acme/memory".to_owned(),
1350            prefix: None,
1351            start: None,
1352            end: None,
1353            key_contains: None,
1354            conversation: Some("01KWM3K3XEP3NP5TN850J17YBP".to_owned()),
1355            stream: Some("acme".to_owned()),
1356            user: Some("reader".to_owned()),
1357            agent: Some("planner".to_owned()),
1358            app: Some("desk".to_owned()),
1359            page: 0,
1360            results: 10,
1361        };
1362        let back: KvScan =
1363            decode_named(&encode_named(&scan).expect("serializes")).expect("deserializes");
1364        assert_eq!(back.stream.as_deref(), Some("acme"));
1365        assert_eq!(
1366            (
1367                back.user.as_deref(),
1368                back.agent.as_deref(),
1369                back.app.as_deref()
1370            ),
1371            (Some("reader"), Some("planner"), Some("desk"))
1372        );
1373        let delete = KvDeleteMany {
1374            v: KV_OP_VERSION,
1375            namespace: "stream:acme/memory".to_owned(),
1376            prefix: None,
1377            start: None,
1378            end: None,
1379            key_contains: None,
1380            conversation: Some("01KWM3K3XEP3NP5TN850J17YBP".to_owned()),
1381            stream: Some("acme".to_owned()),
1382        };
1383        let back: KvDeleteMany =
1384            decode_named(&encode_named(&delete).expect("serializes")).expect("deserializes");
1385        assert_eq!(back.stream.as_deref(), Some("acme"));
1386        let unset = KvDeleteMany {
1387            stream: None,
1388            ..delete
1389        };
1390        assert!(
1391            !serde_json::to_string(&unset)
1392                .expect("serializes")
1393                .contains("\"stream\":"),
1394            "an unset stream is omitted"
1395        );
1396    }
1397}