Skip to main content

kivi/
lib.rs

1//! kivi Rust SDK — the untrusting client for the kivi event ledger.
2//!
3//! The SDK constitution, enforced here and tested by the conformance suite:
4//!   - an answer without a trace is UNREPRESENTABLE (`TracedAnswer::new`
5//!     refuses an empty trace);
6//!   - client-side verification is ON by default: `replay` re-hashes every
7//!     record, checks chain linkage and gapless numbering, and verifies
8//!     Ed25519 seals — a lying server or wire returns `KiviError::Verification`;
9//!   - honest refusals map to a typed `KiviError` — `NotFound` is never a
10//!     silent `None`;
11//!   - identity: a bearer token at dial time, `login()` for kivi-user
12//!     sessions, and `with_bearer()` views for per-caller credentials over
13//!     one shared channel — the server decides everything, per call.
14//!
15//! Numbers travel as JSON strings end to end and are decoded with
16//! `serde_json`, whose default `Number` holds any i64/u64 exactly (no float
17//! detour) — int64 values round-trip exactly (conformance S2).
18
19pub mod pb {
20    tonic::include_proto!("kivi.v1");
21}
22mod verify;
23
24pub use verify::{ChainChecker, RecordIntegrityChecker};
25
26use futures_core::Stream;
27use pb::kivi_client::KiviClient as RawKiviClient;
28use serde_json::Value;
29use std::pin::Pin;
30use std::sync::{Arc, Mutex};
31use tonic::metadata::MetadataValue;
32use tonic::service::Interceptor;
33use tonic::transport::Channel;
34use tonic::{Request, Status};
35
36/// Honest refusals, typed. `NotFound` is never a fabricated `None`.
37#[derive(Debug)]
38pub enum KiviError {
39    NotFound(String),
40    Unauthenticated(String),
41    PreconditionFailed(String),
42    InvalidArgument(String),
43    Unavailable(String),
44    RateLimited(String),
45    Verification(String),
46    Other(String),
47}
48
49impl std::fmt::Display for KiviError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        let (kind, msg) = match self {
52            KiviError::NotFound(m) => ("not found", m),
53            KiviError::Unauthenticated(m) => ("unauthenticated", m),
54            KiviError::PreconditionFailed(m) => ("precondition failed", m),
55            KiviError::InvalidArgument(m) => ("invalid argument", m),
56            KiviError::Unavailable(m) => ("unavailable", m),
57            KiviError::RateLimited(m) => ("rate limited", m),
58            KiviError::Verification(m) => ("verification failed — the server or the wire lied", m),
59            KiviError::Other(m) => ("error", m),
60        };
61        write!(f, "kivi: {kind}: {msg}")
62    }
63}
64impl std::error::Error for KiviError {}
65
66impl From<Status> for KiviError {
67    fn from(s: Status) -> Self {
68        let msg = s.message().to_string();
69        match s.code() {
70            tonic::Code::NotFound => KiviError::NotFound(msg),
71            tonic::Code::Unauthenticated => KiviError::Unauthenticated(msg),
72            tonic::Code::FailedPrecondition => KiviError::PreconditionFailed(msg),
73            tonic::Code::InvalidArgument => KiviError::InvalidArgument(msg),
74            tonic::Code::Unavailable => KiviError::Unavailable(msg),
75            tonic::Code::ResourceExhausted => KiviError::RateLimited(msg),
76            _ => KiviError::Other(format!("{}: {}", s.code(), msg)),
77        }
78    }
79}
80
81fn json_err(e: serde_json::Error) -> KiviError {
82    KiviError::Other(format!("json: {e}"))
83}
84
85/// Decode an already-fetched record's BODY into a TYPED entity `T` — the
86/// "entity out" for records from `replay`, `subscribe`, `why` or
87/// `get_record`. Zero extra dependency (serde).
88///
89///     let e: ClaimReserveChanged = kivi::body_as(&rec)?;
90pub fn body_as<T: serde::de::DeserializeOwned>(rec: &Value) -> Result<T, KiviError> {
91    let body = rec.get("body").cloned().unwrap_or(Value::Null);
92    serde_json::from_value(body).map_err(json_err)
93}
94
95/// The proof of a write: record number, byte offset, hash.
96#[derive(Debug, Clone)]
97pub struct Receipt {
98    pub no: i64,
99    pub offset: i64,
100    pub hash: String,
101}
102
103/// Value + the events that established it + the ledger scope it was derived
104/// from. Constructing one without a trace is refused — by design (the whole
105/// point of the second constitutional rule above).
106#[derive(Debug, Clone)]
107pub struct TracedAnswer {
108    pub value: Value,
109    pub trace: Vec<i64>,
110    pub scope: i64,
111}
112
113impl TracedAnswer {
114    pub fn new(value: Value, trace: Vec<i64>, scope: i64) -> Result<Self, KiviError> {
115        if trace.is_empty() {
116            return Err(KiviError::Verification(
117                "an answer without a trace is unrepresentable".into(),
118            ));
119        }
120        Ok(TracedAnswer {
121            value,
122            trace,
123            scope,
124        })
125    }
126}
127
128/// A whole compiled view plus its canonical digest.
129#[derive(Debug, Clone)]
130pub struct ViewState {
131    pub state: Value,
132    pub scope: i64,
133    pub hash: String,
134}
135
136/// Mirrors the server's dataset-wide audit.
137#[derive(Debug, Clone)]
138pub struct VerifyReport {
139    pub ok: bool,
140    pub records: i64,
141    pub seals: i64,
142    pub unsealed_tail: i64,
143    pub torn_tail: bool,
144    pub has_defect: bool,
145    pub defect_no: i64,
146    pub defect_reason: String,
147}
148
149/// The cheap orientation answer: last record number + head hash (no audit).
150#[derive(Debug, Clone)]
151pub struct Head {
152    pub no: i64,
153    pub hash: String,
154}
155
156/// The result of a login: the bearer token plus its honest envelope.
157#[derive(Debug, Clone)]
158pub struct Session {
159    pub token: String,
160    pub role: String,
161    pub expires_unix: i64,
162}
163
164/// One traced similarity hit: the record's address, its score, and the raw
165/// receipt itself — an untraced score does not exist.
166#[derive(Debug, Clone)]
167pub struct SimilarHit {
168    pub no: i64,
169    pub score: f32,
170    pub record: Option<Value>,
171}
172
173#[derive(Debug, Clone)]
174pub struct SimilarAnswer {
175    pub hits: Vec<SimilarHit>,
176    pub scope: i64,
177    pub model: String,
178}
179
180/// One row of a paged view read: canonical key + decoded value (trace inside).
181#[derive(Debug, Clone)]
182pub struct ViewEntry {
183    pub key: String,
184    pub value: Value,
185}
186
187/// One directed, traced relation edge: source —relation→ target, set by record `no`.
188#[derive(Debug, Clone)]
189pub struct GraphEdge {
190    pub relation: String,
191    pub target: String,
192    pub no: i64,
193}
194
195/// A node found by a traversal, with its depth and the edge record numbers
196/// along the shortest discovering path (the proof).
197#[derive(Debug, Clone)]
198pub struct GraphReached {
199    pub node: String,
200    pub depth: i64,
201    pub trace: Vec<i64>,
202}
203
204/// One step of a path: `from` —relation→ `to`, via edge record `no`.
205#[derive(Debug, Clone)]
206pub struct GraphHop {
207    pub from: String,
208    pub relation: String,
209    pub to: String,
210    pub no: i64,
211}
212
213/// One page of a keyset walk over a compiled view. `next_key` empty = done.
214/// `scope`/`hash` stamp the SNAPSHOT: pass `scope` back as `as_of` and every
215/// later page keeps describing that same moment.
216#[derive(Debug, Clone)]
217pub struct ViewPage {
218    pub entries: Vec<ViewEntry>,
219    pub next_key: String,
220    pub scope: i64,
221    pub hash: String,
222}
223
224/// Per-call bearer credential, carried through tonic's interceptor mechanism
225/// so one `Client` (one channel) can serve many callers — the credential
226/// travels with the CALL, not the connection. `""` = no credential.
227#[derive(Clone)]
228struct BearerInterceptor {
229    token: Arc<Mutex<String>>,
230}
231
232impl Interceptor for BearerInterceptor {
233    fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
234        let token = self.token.lock().unwrap().clone();
235        if !token.is_empty() {
236            let val = MetadataValue::try_from(format!("Bearer {token}"))
237                .map_err(|_| Status::invalid_argument("bad bearer token"))?;
238            req.metadata_mut().insert("authorization", val);
239        }
240        Ok(req)
241    }
242}
243
244type Stub =
245    RawKiviClient<tonic::service::interceptor::InterceptedService<Channel, BearerInterceptor>>;
246
247/// The kivi client for Rust. Async-first (tokio). Cheap to clone: clones
248/// share the underlying channel (tonic channels are already connection-pooled
249/// and cloneable), and `with_bearer` gives a clone with its OWN credential.
250///
251/// Implementation note: the channel is kept separate from the interceptor and
252/// a fresh intercepted stub is built per call from `self.token` — this is
253/// what makes `with_bearer` correct: each `Client` value's OWN `token` Arc is
254/// the one consulted, never a stale interceptor captured by an earlier clone.
255#[derive(Clone)]
256pub struct Client {
257    channel: Channel,
258    token: Arc<Mutex<String>>,
259    pub verify_streams: bool,
260}
261
262impl Client {
263    /// Connect (insecure transport; put TLS termination in front, or extend
264    /// with tonic's TLS config when needed).
265    pub async fn connect(addr: &str, token: impl Into<String>) -> Result<Self, KiviError> {
266        let endpoint = if addr.starts_with("http") {
267            addr.to_string()
268        } else {
269            format!("http://{addr}")
270        };
271        let channel = Channel::from_shared(endpoint)
272            .map_err(|e| KiviError::Other(e.to_string()))?
273            .connect()
274            .await
275            .map_err(|e| KiviError::Unavailable(e.to_string()))?;
276        Ok(Client {
277            channel,
278            token: Arc::new(Mutex::new(token.into())),
279            verify_streams: true,
280        })
281    }
282
283    fn stub(&self) -> Stub {
284        RawKiviClient::with_interceptor(
285            self.channel.clone(),
286            BearerInterceptor {
287                token: self.token.clone(),
288            },
289        )
290    }
291
292    /// Disable client-side stream verification — only when you consciously
293    /// trust the server and the wire.
294    pub fn without_stream_verification(mut self) -> Self {
295        self.verify_streams = false;
296        self
297    }
298
299    /// Swap the bearer credential (after login or on rotation).
300    pub fn set_token(&self, token: impl Into<String>) {
301        *self.token.lock().unwrap() = token.into();
302    }
303
304    /// A view of this client over the SAME channel with ANOTHER identity —
305    /// per-caller credentials for stateless multi-tenant frontends. Dropping
306    /// a view never closes the shared channel (it is reference-counted).
307    pub fn with_bearer(&self, token: impl Into<String>) -> Self {
308        Client {
309            channel: self.channel.clone(),
310            token: Arc::new(Mutex::new(token.into())),
311            verify_streams: self.verify_streams,
312        }
313    }
314
315    // -- identity plane ------------------------------------------------------
316
317    /// Authenticate as a kivi USER and install the session token on this
318    /// client: from here on every call runs with that user's role and every
319    /// write is receipted under their name. Security stays in ONE center —
320    /// the server's identity plane; the client only carries the credential.
321    pub async fn login(&self, username: &str, password: &str) -> Result<Session, KiviError> {
322        let r = self
323            .stub()
324            .login(pb::LoginRequest {
325                username: username.into(),
326                password: password.into(),
327            })
328            .await?
329            .into_inner();
330        self.set_token(r.token.clone());
331        Ok(Session {
332            token: r.token,
333            role: r.role,
334            expires_unix: r.expires_unix,
335        })
336    }
337
338    // -- write plane ----------------------------------------------------------
339
340    pub async fn append(&self, event_type: &str, body: &Value) -> Result<Receipt, KiviError> {
341        let r = self
342            .stub()
343            .append(pb::AppendRequest {
344                r#type: event_type.into(),
345                body_json: body.to_string(),
346                ..Default::default()
347            })
348            .await?
349            .into_inner();
350        Ok(Receipt {
351            no: r.no,
352            offset: r.offset,
353            hash: r.hash,
354        })
355    }
356
357    /// Append a TYPED entity (serde `Serialize`) — the "entity in" write: you
358    /// pass a struct, kivi serializes it (and re-canonicalizes server-side,
359    /// so your field order never matters). Zero extra dependency: serde is
360    /// already the crate's serialization framework.
361    pub async fn append_typed<T: serde::Serialize>(
362        &self,
363        event_type: &str,
364        entity: &T,
365    ) -> Result<Receipt, KiviError> {
366        let body = serde_json::to_value(entity).map_err(json_err)?;
367        self.append(event_type, &body).await
368    }
369
370    pub async fn append_private(
371        &self,
372        event_type: &str,
373        body: &Value,
374    ) -> Result<Receipt, KiviError> {
375        let r = self
376            .stub()
377            .append_private(pb::AppendRequest {
378                r#type: event_type.into(),
379                body_json: body.to_string(),
380                ..Default::default()
381            })
382            .await?
383            .into_inner();
384        Ok(Receipt {
385            no: r.no,
386            offset: r.offset,
387            hash: r.hash,
388        })
389    }
390
391    /// Append a private (per-record encrypted) TYPED entity — the "entity in"
392    /// for erasable bodies. Pass a struct, not a hand-written JSON string;
393    /// parity with [`append_typed`](Self::append_typed).
394    pub async fn append_private_typed<T: serde::Serialize>(
395        &self,
396        event_type: &str,
397        entity: &T,
398    ) -> Result<Receipt, KiviError> {
399        let body = serde_json::to_value(entity).map_err(json_err)?;
400        self.append_private(event_type, &body).await
401    }
402
403    /// Crypto-erase a private record. A reason is mandatory — even
404    /// forgetting leaves a trace.
405    pub async fn erase(&self, no: i64, reason: &str) -> Result<Receipt, KiviError> {
406        let r = self
407            .stub()
408            .erase(pb::EraseRequest {
409                no,
410                reason: reason.into(),
411            })
412            .await?
413            .into_inner();
414        Ok(Receipt {
415            no: r.no,
416            offset: r.offset,
417            hash: r.hash,
418        })
419    }
420
421    pub async fn seal(&self) -> Result<Receipt, KiviError> {
422        let r = self.stub().seal(pb::Empty {}).await?.into_inner();
423        Ok(Receipt {
424            no: r.no,
425            offset: r.offset,
426            hash: r.hash,
427        })
428    }
429
430    // -- read plane -----------------------------------------------------------
431
432    pub async fn verify_ledger(&self) -> Result<VerifyReport, KiviError> {
433        let r = self.stub().verify(pb::Empty {}).await?.into_inner();
434        Ok(VerifyReport {
435            ok: r.ok,
436            records: r.records,
437            seals: r.seals,
438            unsealed_tail: r.unsealed_tail,
439            torn_tail: r.torn_tail,
440            has_defect: r.has_defect,
441            defect_no: r.defect_no,
442            defect_reason: r.defect_reason,
443        })
444    }
445
446    /// The cheap orientation call: last record number + head hash — no audit
447    /// runs. Use it to page a tail; use `verify_ledger` when integrity itself
448    /// is the question.
449    pub async fn head(&self) -> Result<Head, KiviError> {
450        let r = self.stub().head(pb::Empty {}).await?.into_inner();
451        Ok(Head {
452            no: r.head_no,
453            hash: r.head_hash,
454        })
455    }
456
457    /// Traced read of the CURRENT value.
458    pub async fn table(&self, subject: &str, attribute: &str) -> Result<TracedAnswer, KiviError> {
459        self.table_at(subject, attribute, None).await
460    }
461
462    /// Time travel: the answer AS OF record `as_of` — "what did we know when
463    /// the ledger stopped there?" (`None` = the current head).
464    pub async fn table_at(
465        &self,
466        subject: &str,
467        attribute: &str,
468        as_of: Option<i64>,
469    ) -> Result<TracedAnswer, KiviError> {
470        let r = self
471            .stub()
472            .query_table(pb::TableRequest {
473                subject: subject.into(),
474                attribute: attribute.into(),
475                as_of,
476            })
477            .await?
478            .into_inner();
479        let value: Value = serde_json::from_str(&r.value_json).map_err(json_err)?;
480        TracedAnswer::new(value, r.trace, r.scope)
481    }
482
483    /// `table`'s whole-row sibling (G15): every attribute known about one
484    /// subject, plus the union of every event that established one of them —
485    /// "what do we know about X?" without knowing which attributes to ask
486    /// for first.
487    pub async fn subject(&self, subject: &str) -> Result<TracedAnswer, KiviError> {
488        self.subject_at(subject, None).await
489    }
490
491    /// Time travel, same contract as `table_at`.
492    pub async fn subject_at(
493        &self,
494        subject: &str,
495        as_of: Option<i64>,
496    ) -> Result<TracedAnswer, KiviError> {
497        let r = self
498            .stub()
499            .query_subject(pb::SubjectRequest {
500                subject: subject.into(),
501                as_of,
502            })
503            .await?
504            .into_inner();
505        let value: Value = serde_json::from_str(&r.value_json).map_err(json_err)?;
506        TracedAnswer::new(value, r.trace, r.scope)
507    }
508
509    /// Fetch the receipt records behind a trace — the raw immutable events.
510    pub async fn why(&self, trace: &[i64]) -> Result<Vec<Value>, KiviError> {
511        let r = self
512            .stub()
513            .why(pb::WhyRequest {
514                trace: trace.to_vec(),
515            })
516            .await?
517            .into_inner();
518        r.records
519            .into_iter()
520            .map(|x| serde_json::from_str(&x.record_json).map_err(json_err))
521            .collect()
522    }
523
524    /// One record by number (`unseal=true` opens a private body if the key
525    /// still exists).
526    pub async fn get_record(&self, no: i64, unseal: bool) -> Result<Value, KiviError> {
527        let r = self
528            .stub()
529            .get_record(pb::GetRecordRequest { no, unseal })
530            .await?
531            .into_inner();
532        serde_json::from_str(&r.record_json).map_err(json_err)
533    }
534
535    /// Fetch record `no` and decode its body into a TYPED entity `T` — the
536    /// "entity out" read. Zero extra dependency (serde).
537    pub async fn get_record_as<T: serde::de::DeserializeOwned>(
538        &self,
539        no: i64,
540        unseal: bool,
541    ) -> Result<T, KiviError> {
542        body_as(&self.get_record(no, unseal).await?)
543    }
544
545    pub async fn graph(&self) -> Result<ViewState, KiviError> {
546        let r = self.stub().query_graph(pb::Empty {}).await?.into_inner();
547        Ok(ViewState {
548            state: serde_json::from_str(&r.state_json).map_err(json_err)?,
549            scope: r.scope,
550            hash: r.hash,
551        })
552    }
553
554    /// Direct outgoing relation edges of `node`. `as_of` pins the graph to a
555    /// record number (`None` = current). Returns `(edges, truncated)`.
556    pub async fn graph_neighbors(
557        &self,
558        node: &str,
559        as_of: Option<i64>,
560    ) -> Result<(Vec<GraphEdge>, bool), KiviError> {
561        let r = self
562            .stub()
563            .graph_neighbors(pb::GraphNeighborsRequest {
564                node: node.into(),
565                as_of,
566            })
567            .await?
568            .into_inner();
569        let edges = r
570            .edges
571            .into_iter()
572            .map(|e| GraphEdge {
573                relation: e.relation,
574                target: e.target,
575                no: e.no,
576            })
577            .collect();
578        Ok((edges, r.truncated))
579    }
580
581    /// Every node reachable from `node` within `depth` hops (0 = server default),
582    /// each with its edge trace. `limit` 0 = server default. Returns
583    /// `(nodes, truncated)`.
584    pub async fn graph_reachable(
585        &self,
586        node: &str,
587        depth: i64,
588        limit: i64,
589        as_of: Option<i64>,
590    ) -> Result<(Vec<GraphReached>, bool), KiviError> {
591        let r = self
592            .stub()
593            .graph_reachable(pb::GraphReachableRequest {
594                node: node.into(),
595                depth,
596                limit,
597                as_of,
598            })
599            .await?
600            .into_inner();
601        let nodes = r
602            .nodes
603            .into_iter()
604            .map(|n| GraphReached {
605                node: n.node,
606                depth: n.depth,
607                trace: n.trace,
608            })
609            .collect();
610        Ok((nodes, r.truncated))
611    }
612
613    /// Shortest edge path from `from` to `to` within `depth` hops (0 = server
614    /// default). Returns `(hops, found, truncated)`.
615    pub async fn graph_path(
616        &self,
617        from: &str,
618        to: &str,
619        depth: i64,
620        as_of: Option<i64>,
621    ) -> Result<(Vec<GraphHop>, bool, bool), KiviError> {
622        let r = self
623            .stub()
624            .graph_path(pb::GraphPathRequest {
625                from: from.into(),
626                to: to.into(),
627                depth,
628                as_of,
629            })
630            .await?
631            .into_inner();
632        let hops = r
633            .hops
634            .into_iter()
635            .map(|h| GraphHop {
636                from: h.from,
637                relation: h.relation,
638                to: h.to,
639                no: h.no,
640            })
641            .collect();
642        Ok((hops, r.found, r.truncated))
643    }
644
645    pub async fn series(&self, series: &str) -> Result<ViewState, KiviError> {
646        let r = self
647            .stub()
648            .query_series(pb::SeriesRequest {
649                series: series.into(),
650            })
651            .await?
652            .into_inner();
653        Ok(ViewState {
654            state: serde_json::from_str(&r.state_json).map_err(json_err)?,
655            scope: r.scope,
656            hash: r.hash,
657        })
658    }
659
660    /// Keyset pagination over a compiled view (table|graph|series) at the
661    /// current head. `limit` 0 = server default (100, capped at 1000).
662    pub async fn view_page(
663        &self,
664        view: &str,
665        after_key: &str,
666        limit: i64,
667    ) -> Result<ViewPage, KiviError> {
668        self.view_page_at(view, after_key, limit, None).await
669    }
670
671    /// Keyset pagination PINNED to a snapshot: pass page 1's `scope` as
672    /// `as_of` and every later page keeps describing that same moment, no
673    /// matter what writers do in between.
674    pub async fn view_page_at(
675        &self,
676        view: &str,
677        after_key: &str,
678        limit: i64,
679        as_of: Option<i64>,
680    ) -> Result<ViewPage, KiviError> {
681        let r = self
682            .stub()
683            .query_view_page(pb::ViewPageRequest {
684                view: view.into(),
685                after_key: after_key.into(),
686                limit,
687                as_of,
688            })
689            .await?
690            .into_inner();
691        let mut entries = Vec::with_capacity(r.entries.len());
692        for e in r.entries {
693            entries.push(ViewEntry {
694                key: e.key,
695                value: serde_json::from_str(&e.value_json).map_err(json_err)?,
696            });
697        }
698        Ok(ViewPage {
699            entries,
700            next_key: r.next_key,
701            scope: r.scope,
702            hash: r.hash,
703        })
704    }
705
706    /// Traced semantic search: every hit is a record number + score + the
707    /// raw receipt; the answer names the model and the covered scope.
708    pub async fn similar(&self, query: &str, k: i64) -> Result<SimilarAnswer, KiviError> {
709        let r = self
710            .stub()
711            .similar(pb::SimilarRequest {
712                query: query.into(),
713                k,
714            })
715            .await?
716            .into_inner();
717        let mut hits = Vec::with_capacity(r.hits.len());
718        for h in r.hits {
719            let record = if h.record_json.is_empty() {
720                None
721            } else {
722                Some(serde_json::from_str(&h.record_json).map_err(json_err)?)
723            };
724            hits.push(SimilarHit {
725                no: h.no,
726                score: h.score,
727                record,
728            });
729        }
730        Ok(SimilarAnswer {
731            hits,
732            scope: r.scope,
733            model: r.model,
734        })
735    }
736
737    // -- streams: verified replay (the untrusting client) ----------------------
738
739    /// Stream records from `start`; `follow=true` never ends (CDC). With
740    /// verification on (the client default), every record is re-hashed,
741    /// chain and numbering are checked and seals are Ed25519-verified
742    /// CLIENT-SIDE before you see it — a lying stream yields
743    /// `KiviError::Verification`.
744    pub async fn replay(
745        &self,
746        start: i64,
747        follow: bool,
748    ) -> Result<Pin<Box<dyn Stream<Item = Result<Value, KiviError>> + Send>>, KiviError> {
749        let verify = self.verify_streams;
750        let inbound = self
751            .stub()
752            .replay(pb::ReplayRequest {
753                from: start,
754                follow,
755            })
756            .await?
757            .into_inner();
758        let mut checker = ChainChecker::new(true);
759        let out = async_stream::try_stream! {
760            tokio::pin!(inbound);
761            use tokio_stream::StreamExt;
762            while let Some(msg) = inbound.next().await {
763                let reply = msg.map_err(KiviError::from)?;
764                if verify {
765                    checker.check(&reply.record_json)?;
766                }
767                let v: Value = serde_json::from_str(&reply.record_json).map_err(json_err)?;
768                yield v;
769            }
770        };
771        Ok(Box::pin(out))
772    }
773
774    /// `replay`'s type-filtered sibling (G14): the server drops non-matching
775    /// records before they cross the wire, so a consumer that only cares
776    /// about one or two event types never receives (and discards)
777    /// everything else.
778    ///
779    /// Honesty note: because the server may drop records, this does NOT
780    /// carry `replay`'s gapless/chain-adjacency guarantee. With
781    /// verification on (the client default), each delivered record's OWN
782    /// hash is recomputed (and its Ed25519 signature checked, for
783    /// kivi.seal records) — proving "byte-exact what the ledger holds" —
784    /// but numbering gaps and prev_hash discontinuities are EXPECTED and
785    /// never yield `KiviError::Verification`. A consumer that must prove
786    /// it received every record uses `replay` instead.
787    pub async fn subscribe(
788        &self,
789        start: i64,
790        follow: bool,
791        types: Vec<String>,
792    ) -> Result<Pin<Box<dyn Stream<Item = Result<Value, KiviError>> + Send>>, KiviError> {
793        let verify = self.verify_streams;
794        let inbound = self
795            .stub()
796            .subscribe(pb::SubscribeRequest {
797                from: start,
798                follow,
799                types,
800            })
801            .await?
802            .into_inner();
803        let mut checker = RecordIntegrityChecker::new(true);
804        let out = async_stream::try_stream! {
805            tokio::pin!(inbound);
806            use tokio_stream::StreamExt;
807            while let Some(msg) = inbound.next().await {
808                let reply = msg.map_err(KiviError::from)?;
809                if verify {
810                    checker.check(&reply.record_json)?;
811                }
812                let v: Value = serde_json::from_str(&reply.record_json).map_err(json_err)?;
813                yield v;
814            }
815        };
816        Ok(Box::pin(out))
817    }
818}