Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(rust-sdk): LiveStream, and Kafka and Iggy source and target gaps (#2719)
LJ π₯₯π΄2c5003799b6d
diff --git a/examples/rust/csv_to_iggy/src/main.rs b/examples/rust/csv_to_iggy/src/main.rsindex e753594b..aa97e09c 100644--- a/examples/rust/csv_to_iggy/src/main.rs+++ b/examples/rust/csv_to_iggy/src/main.rs@@ -119,12 +119,13 @@ async fn index(producer: IggyProducer, stream: String, topic: String) -> Result<let options = iggy::IggyTopicOptions {partition: PARTITION,// Iggy has no tombstone; emit a delete marker for removed rows.- deletion_value_fn: Some(Arc::new(|key: &str| {- format!("{{\"_deleted\":\"{key}\"}}").into_bytes()+ deletion_value_fn: Some(Arc::new(|key: &[u8]| {+ format!("{{\"_deleted\":\"{}\"}}", String::from_utf8_lossy(key)).into_bytes()})),};let target =- iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)?;+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)+ .await?;let files = cocoindex::resources::fs::walk_items("./data", &["**/*.csv"])?;println!("found {} CSV file(s)", files.len());diff --git a/examples/rust/csv_to_kafka/src/main.rs b/examples/rust/csv_to_kafka/src/main.rsindex 54403663..678edc93 100644--- a/examples/rust/csv_to_kafka/src/main.rs+++ b/examples/rust/csv_to_kafka/src/main.rs@@ -92,7 +92,8 @@ async fn index(producer: KafkaProducer, topic: String) -> Result<()> {&PRODUCER,topic,kafka::KafkaTopicOptions::default(),- )?;+ )+ .await?;// The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).let files = walk_dir("./data")diff --git a/rust/sdk/SHOWCASE.md b/rust/sdk/SHOWCASE.mdindex c4820444..8649bd2a 100644--- a/rust/sdk/SHOWCASE.md+++ b/rust/sdk/SHOWCASE.md@@ -580,9 +580,26 @@ ctx.mount_each_live(&"orders", kafka::topic_as_map(&consumer, "orders"), |ctx, m.await?;```+`topic_as_stream` is also a `LiveStream` (the Rust form of Python's+`LiveStream` protocol): `watch` delivers every record to a+`LiveStreamSubscriber`, polling the partitions at the same time, acknowledges a+record once the `ReadyHandle` its `send` returned is ready, and marks the+subscriber ready once every partition has caught up. `.payloads()` is the+`LiveStream<Vec<u8>>` view of the values, the input of a live object-store+view. An Iggy map derives keys and deletions from the whole+`IggyReceivedMessage`, and a client the caller built is wrapped with+`KafkaConsumer::from_client` / `IggyConsumer::from_client`.++```rust+let events = kafka::topic_as_stream(&consumer, ["bucket-events"]).payloads();+let walker = oci_object_storage::list_objects_live(&client, "ns", "bucket", ListOptions::default(), events);+```+The Kafka and Iggy targets take their producer as a `ContextKey`, like everyother connector target: `provide_key(&PRODUCER, producer)` once, name the key-in `mount_kafka_topic_target(&ctx, &PRODUCER, topic, options)`.+in `mount_kafka_topic_target(&ctx, &PRODUCER, topic, options)`. `kafka_topic_target` / `iggy_topic_target` build the+topic's `TargetState` for `mount_target`, and `declare_message_bytes` declares a+message under a binary key.A personal Google account signs in once with `UserAccount::sign_in`(`client_secret.json` of a Desktop-app OAuth client), to the same token filediff --git a/rust/sdk/cocoindex/src/connectors/iggy.rs b/rust/sdk/cocoindex/src/connectors/iggy.rsindex 6fa11015..7ae19a5d 100644--- a/rust/sdk/cocoindex/src/connectors/iggy.rs+++ b/rust/sdk/cocoindex/src/connectors/iggy.rs@@ -1,4 +1,6 @@-//! Apache Iggy topic target connector.+//! Apache Iggy connector: a topic target and topic sources.+//!+//! # Target//!//! Streams and topics are user-managed: CocoIndex never creates or drops them//! during target reconciliation. Messages declared with@@ -13,14 +15,26 @@//! requires a `deletion_value_fn`; deleting a declared message without one is an//! error (mirroring the Python `iggy` connector).//!-//! Use [`declare_iggy_topic_target`] / [`mount_iggy_topic_target`] to get a handle-//! for declaring messages.+//! [`iggy_topic_target`] builds the topic's [`TargetState`] for `mount_target` /+//! `declare_target_state_with_child`; [`declare_iggy_topic_target`] /+//! [`mount_iggy_topic_target`] wrap those and return a handle for declaring+//! messages.+//!+//! # Sources//!-//! This is the Rust analogue of Python's `cocoindex.connectors.iggy` target,-//! plus a keyed-map source over one topic partition.+//! [`topic_as_stream`] reads a topic as a [`LiveStream`] of every message+//! ([`IggyTopicStream`]; [`payloads`](IggyTopicStream::payloads) is the+//! `LiveStream<Vec<u8>>` view) and [`topic_as_map`] reads one partition as a+//! keyed map, the key and deletions derived from each [`IggyReceivedMessage`]+//! by the caller's functions, as Iggy messages have no key or tombstone. Both+//! are also [`LiveMapView`]s for [`Ctx::mount_each_live`](crate::Ctx::mount_each_live).+//! The consumer group's offsets are stored on the server once a polled batch+//! has been processed, and a later live run resumes from them.+//!+//! This is the Rust analogue of Python's `cocoindex.connectors.iggy`.use std::collections::BTreeMap;-use std::sync::Arc;+use std::sync::{Arc, Mutex};use std::time::Duration;use bytes::Bytes;@@ -37,14 +51,17 @@ use serde::{Deserialize, Serialize};/// `cocoindex::connectors::iggy::prelude::{StreamClient, TopicClient}`.pub use ::iggy::prelude;+use crate::connectors::partition_tail::{PartitionSource, PartitionTail, watch_partitions};use crate::ctx::{ContextKey, ContextStore, Ctx};use crate::error::{Error, Result};use crate::live_component::{- LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, SingleWatcherGuard,+ LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream,+ LiveStreamSubscriber, ReadyHandle, SingleWatcherGuard,};use crate::target_state::{- SinkCache, StableKey, TargetAction, TargetActionSink, TargetHandler, TargetReconcileOutput,- TargetStateProvider, declare_target_state, register_root_target_states_provider,+ ChildTargetDef, STATIC_ROOT_PROVIDERS, SinkCache, StableKey, StaticRootProvider, TargetAction,+ TargetActionSink, TargetHandler, TargetReconcileOutput, TargetState, TargetStateProvider,+ declare_target_state, declare_target_state_with_child, mount_target,};// ---------------------------------------------------------------------------@@ -77,6 +94,16 @@ impl IggyProducer {})}+ /// Wrap a connected `IggyClient` the caller built, as the Python target+ /// takes the caller's client. `state_id` is the stable identity of the+ /// server (its address), never a credential.+ pub fn from_client(client: IggyClient, state_id: impl Into<String>) -> Self {+ Self {+ client: Arc::new(client),+ state_id: Arc::from(state_id.into()),+ }+ }+/// Stable identity (the server address, with any embedded credentials/// removed).pub fn state_id(&self) -> &str {@@ -108,9 +135,10 @@ fn sanitize_state_id(connection_string: &str) -> String {// Public API: options + target + the constructor/declaration/mount split// ----------------------------------------------------------------------------/// Callback producing the deletion value for a given message key. Iggy has no-/// tombstone, so this is required to delete a previously-declared message.-pub type DeletionValueFn = Arc<dyn Fn(&str) -> Vec<u8> + Send + Sync>;+/// Callback producing the deletion value for a message key (a `&str` key is+/// its UTF-8 bytes). Iggy has no tombstone, so this is required to delete a+/// previously-declared message.+pub type DeletionValueFn = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;/// Options for the Iggy topic target.#[derive(Clone, Default)]@@ -119,6 +147,10 @@ pub struct IggyTopicOptions {pub partition: u32,/// Value to send when a previously-declared message is removed. Iggy has no/// tombstone, so deleting a declared message without this is an error.+ ///+ /// The callback lives in this process: a run that declares the topic target+ /// (or drops the app from a process that did) applies it; `App::drop_state`+ /// from a process that never declared the topic target cannot delete.pub deletion_value_fn: Option<DeletionValueFn>,}@@ -131,9 +163,36 @@ pub struct IggyTopicTarget {topic: Arc<str>,}-/// Declare an Iggy topic target and return a ready same-component handle.-/// No external setup is needed, so this uses the same immediate provider path as-/// [`mount_iggy_topic_target`].+/// Build the composable [`TargetState`] of an Iggy topic partition (the spec+/// constructor), for `mount_target` / `declare_target_state_with_child`.+/// `producer` names the [`IggyProducer`] provided in the environment; it is+/// resolved when the messages are sent.+pub fn iggy_topic_target(+ ctx: &Ctx,+ producer: &ContextKey<IggyProducer>,+ stream: impl Into<String>,+ topic: impl Into<String>,+ options: IggyTopicOptions,+) -> Result<TargetState<TopicSpec>> {+ let stream = stream.into();+ let topic = topic.into();+ if stream.is_empty() || topic.is_empty() {+ return Err(Error::engine("iggy stream and topic must be non-empty"));+ }+ let key = TopicKey {+ producer_key: producer.name().to_string(),+ stream,+ topic,+ partition: options.partition,+ };+ set_deletion_value_fn(&key, options.deletion_value_fn);+ let provider = TOPIC_PROVIDER.get(ctx)?;+ Ok(provider.target_state(key.stable_key(), TopicSpec {}))+}++/// Declare an Iggy topic target in the current component and return a handle+/// for declaring messages (the message provider resolves at this component's+/// commit).pub fn declare_iggy_topic_target(ctx: &Ctx,producer: &ContextKey<IggyProducer>,@@ -141,13 +200,20 @@ pub fn declare_iggy_topic_target(topic: impl Into<String>,options: IggyTopicOptions,) -> Result<IggyTopicTarget> {- mount_iggy_topic_target(ctx, producer, stream, topic, options)+ let stream = stream.into();+ let topic = topic.into();+ let ts = iggy_topic_target(ctx, producer, stream.clone(), topic.clone(), options)?;+ let messages = declare_target_state_with_child::<TopicSpec, Vec<u8>>(ctx, ts)?;+ Ok(IggyTopicTarget {+ messages,+ stream: Arc::from(stream),+ topic: Arc::from(topic),+ })}-/// Declare an Iggy topic target in the current component and return a handle for-/// declaring messages. `producer` names the [`IggyProducer`] provided in the-/// environment; it is resolved when the messages are sent.-pub fn mount_iggy_topic_target(+/// Mount an Iggy topic target **foreground** (messages can be declared at once)+/// and return a handle for declaring messages.+pub async fn mount_iggy_topic_target(ctx: &Ctx,producer: &ContextKey<IggyProducer>,stream: impl Into<String>,@@ -156,25 +222,8 @@ pub fn mount_iggy_topic_target() -> Result<IggyTopicTarget> {let stream = stream.into();let topic = topic.into();- let messages = register_root_target_states_provider(- ctx,- // Stable connection identity = the ContextKey's name; the client is- // resolved at apply time from the host context, as the other targets do.- format!(- "cocoindex/iggy/topic/{}/{}/{}/{}",- producer.name(),- stream,- topic,- options.partition- ),- MessageHandler::new(- producer.name().to_string(),- stream.clone(),- topic.clone(),- options.partition,- options.deletion_value_fn,- ),- )?;+ let ts = iggy_topic_target(ctx, producer, stream.clone(), topic.clone(), options)?;+ let messages = mount_target::<TopicSpec, Vec<u8>>(ctx, ts).await?;Ok(IggyTopicTarget {messages,stream: Arc::from(stream),@@ -207,12 +256,179 @@ impl IggyTopicTarget {self.messages.target_state(key, value.as_ref().to_vec()),)}++ /// [`declare_message`](Self::declare_message) with a binary key. A `&str`+ /// key and its UTF-8 bytes are distinct target states.+ pub fn declare_message_bytes(+ &self,+ ctx: &Ctx,+ key: &[u8],+ value: impl AsRef<[u8]>,+ ) -> Result<()> {+ if key.is_empty() {+ return Err(Error::engine(+ "iggy declare_message_bytes: key must be non-empty",+ ));+ }+ declare_target_state(+ ctx,+ self.messages+ .target_state(StableKey::Bytes(Arc::from(key)), value.as_ref().to_vec()),+ )+ }}// ----------------------------------------------------------------------------// Message handler (root)+// Topic handler (root, static) and its message child handler// ---------------------------------------------------------------------------+/// Spec of an Iggy topic target (the declared container value). Streams and+/// topics are user-managed, so the spec carries nothing: the target's identity+/// is in its key.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct TopicSpec {}++#[linkme::distributed_slice(STATIC_ROOT_PROVIDERS)]+static TOPIC_PROVIDER: StaticRootProvider =+ StaticRootProvider::new::<TopicSpec, TopicHandler>("cocoindex/iggy/topic");++/// A topic target state's key: the producer's `ContextKey` name, the stream,+/// the topic and the partition. Mirrors Python's `_TopicKey`.+#[derive(Clone, PartialEq, Eq, Hash)]+struct TopicKey {+ producer_key: String,+ stream: String,+ topic: String,+ partition: u32,+}++impl TopicKey {+ fn stable_key(self) -> StableKey {+ StableKey::Array(Arc::from([+ StableKey::Str(Arc::from(self.producer_key)),+ StableKey::Str(Arc::from(self.stream)),+ StableKey::Str(Arc::from(self.topic)),+ StableKey::Int(i64::from(self.partition)),+ ]))+ }++ fn from_stable_key(key: &StableKey) -> Result<Self> {+ if let StableKey::Array(parts) = key+ && let [+ StableKey::Str(producer_key),+ StableKey::Str(stream),+ StableKey::Str(topic),+ StableKey::Int(partition),+ ] = &parts[..]+ && let Ok(partition) = u32::try_from(*partition)+ {+ return Ok(Self {+ producer_key: producer_key.to_string(),+ stream: stream.to_string(),+ topic: topic.to_string(),+ partition,+ });+ }+ Err(Error::engine(format!("unexpected iggy topic key: {key:?}")))+ }+}++/// The deletion-value callbacks of the topic targets this process declared,+/// looked up when a topic's message handler is built (the spec is persisted,+/// a closure cannot be).+static DELETION_VALUE_FNS: Mutex<Option<std::collections::HashMap<TopicKey, DeletionValueFn>>> =+ Mutex::new(None);++fn set_deletion_value_fn(key: &TopicKey, f: Option<DeletionValueFn>) {+ let mut guard = DELETION_VALUE_FNS.lock().unwrap_or_else(|e| e.into_inner());+ let fns = guard.get_or_insert_with(Default::default);+ match f {+ Some(f) => {+ fns.insert(key.clone(), f);+ }+ None => {+ fns.remove(key);+ }+ }+}++fn deletion_value_fn(key: &TopicKey) -> Option<DeletionValueFn> {+ DELETION_VALUE_FNS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|fns| fns.get(key).cloned())+}++/// The topic-level action: nothing to apply (topics are user-managed); it+/// carries the key the message child handler is built from.+#[derive(Serialize, Deserialize)]+struct TopicAction {+ producer_key: String,+ stream: String,+ topic: String,+ partition: u32,+}++#[derive(Default)]+struct TopicHandler {+ sink: SinkCache<TopicAction>,+}++impl TargetHandler<TopicSpec> for TopicHandler {+ type TrackingRecord = ();+ type Action = TopicAction;++ fn reconcile(+ &self,+ key: StableKey,+ desired: Option<TopicSpec>,+ _prev: Vec<()>,+ _prev_may_be_missing: bool,+ ) -> Result<Option<TargetReconcileOutput<TopicAction, ()>>> {+ let topic_key = TopicKey::from_stable_key(&key)?;+ let action = TopicAction {+ producer_key: topic_key.producer_key,+ stream: topic_key.stream,+ topic: topic_key.topic,+ partition: topic_key.partition,+ };+ // Always emit when declared, so the sink builds the message child.+ Ok(Some(TargetReconcileOutput {+ action: match desired {+ Some(_) => TargetAction::Update(action),+ None => TargetAction::Delete(action),+ },+ sink: self.sink.get(topic_sink),+ tracking_record: desired.map(|_| ()),+ child_invalidation: None,+ }))+ }+}++fn topic_sink() -> TargetActionSink<TopicAction> {+ TargetActionSink::from_async_fn_with_child_handler(+ // Topics are not created or deleted, so there is nothing to apply.+ |_actions| async { Ok(()) },+ |action: &TopicAction| {+ let key = TopicKey {+ producer_key: action.producer_key.clone(),+ stream: action.stream.clone(),+ topic: action.topic.clone(),+ partition: action.partition,+ };+ let deletion_value_fn = deletion_value_fn(&key);+ Ok(ChildTargetDef::new::<Vec<u8>, _>(MessageHandler::new(+ key.producer_key,+ key.stream,+ key.topic,+ key.partition,+ deletion_value_fn,+ )))+ },+ )+}+/// What the sink should send for one message: a record with this value.#[derive(Serialize, Deserialize)]struct MessageAction {@@ -248,6 +464,17 @@ impl MessageHandler {}}+/// The bytes of a message target state's key: a `Str` key is its UTF-8 bytes.+fn message_key_bytes(key: &StableKey) -> Result<Vec<u8>> {+ match key {+ StableKey::Str(s) => Ok(s.as_bytes().to_vec()),+ StableKey::Bytes(b) => Ok(b.to_vec()),+ other => Err(Error::engine(format!(+ "unexpected iggy message key: {other:?}"+ ))),+ }+}+impl TargetHandler<Vec<u8>> for MessageHandler {type TrackingRecord = Fingerprint;type Action = MessageAction;@@ -259,13 +486,7 @@ impl TargetHandler<Vec<u8>> for MessageHandler {prev: Vec<Fingerprint>,prev_may_be_missing: bool,) -> Result<Option<TargetReconcileOutput<MessageAction, Fingerprint>>> {- let StableKey::Str(key) = &key else {- return Err(Error::engine(format!(- "unexpected iggy message key: {key:?}"- )));- };- let key = key.to_string();-+ let key = message_key_bytes(&key)?;let Some(decision) = decide_message(&key,desired.as_deref(),@@ -317,10 +538,7 @@ impl MessageHandler {return Ok(());}let client = resolve_producer(&host_ctx, &producer_key)?.client.clone();- let stream_id = Identifier::from_str_value(&stream)- .map_err(|e| Error::engine(format!("iggy stream id {stream:?}: {e}")))?;- let topic_id = Identifier::from_str_value(&topic)- .map_err(|e| Error::engine(format!("iggy topic id {topic:?}: {e}")))?;+ let (stream_id, topic_id) = topic_ids(&stream, &topic)?;let partitioning = Partitioning::partition_id(partition);let mut messages = Vec::with_capacity(actions.len());@@ -370,7 +588,7 @@ struct MessageDecision {/// * other deletes send `deletion_value_fn(key)`, or error if none is set/// (Iggy has no tombstone).fn decide_message(- key: &str,+ key: &[u8],desired_value: Option<&[u8]>,prev_fps: &[Fingerprint],prev_may_be_missing: bool,@@ -378,7 +596,7 @@ fn decide_message() -> Result<Option<MessageDecision>> {// Upsert path.if let Some(value) = desired_value {- let fp = Fingerprint::from(&value.to_vec()).map_err(Error::from)?;+ let fp = Fingerprint::from_bytes(value);if !prev_may_be_missing && !prev_fps.is_empty() && prev_fps.iter().all(|p| *p == fp) {return Ok(None);}@@ -394,8 +612,9 @@ fn decide_message(}let Some(deletion_value_fn) = deletion_value_fn else {return Err(Error::engine(format!(- "iggy: cannot delete message {key:?} β Iggy has no tombstone; \- set IggyTopicOptions::deletion_value_fn or encode deletes in the payload"+ "iggy: cannot delete message {:?} β Iggy has no tombstone; \+ set IggyTopicOptions::deletion_value_fn or encode deletes in the payload",+ String::from_utf8_lossy(key))));};Ok(Some(MessageDecision {@@ -432,19 +651,61 @@ impl IggyConsumer {})}+ /// Wrap a connected `IggyClient` the caller built, as the Python sources+ /// take the caller's client. `state_id` is the stable identity of the+ /// server (its address), never a credential.+ pub fn from_client(client: IggyClient, state_id: impl Into<String>) -> Self {+ Self {+ client: Arc::new(client),+ state_id: Arc::from(state_id.into()),+ }+ }+/// Stable identity (the server address, credentials stripped).pub fn state_id(&self) -> &str {&self.state_id}}-/// Extracts a map key from a message payload. Iggy messages have no native key,-/// so a key function is required (returning `None` skips the message).-pub type IggyKeyFn = Arc<dyn Fn(&[u8]) -> Option<String> + Send + Sync>;+/// A polled Iggy message, as the sources yield it: the Rust analogue of the+/// Python SDK's `ReceiveMessage`.+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]+pub struct IggyReceivedMessage {+ pub partition: u32,+ pub offset: u64,+ /// The message id the producer set (`0` when none).+ pub id: u128,+ /// The server's receive time, in microseconds since the Unix epoch.+ pub timestamp: u64,+ pub checksum: u64,+ pub payload: Vec<u8>,+}-/// Decides whether a message payload represents a *deletion* of its key-/// (defaults to "never" β Iggy has no tombstone).-pub type IggyIsDeletionFn = Arc<dyn Fn(&[u8]) -> bool + Send + Sync>;+impl IggyReceivedMessage {+ fn from_message(partition: u32, message: &IggyMessage) -> Self {+ Self {+ partition,+ offset: message.header.offset,+ id: message.header.id,+ timestamp: message.header.timestamp,+ checksum: message.header.checksum,+ payload: message.payload.to_vec(),+ }+ }++ /// The payload as text (lossy on invalid UTF-8).+ pub fn payload_str(&self) -> String {+ String::from_utf8_lossy(&self.payload).into_owned()+ }+}++/// Extracts a map key from a message. Iggy messages have no native key, so a+/// key function is required (returning `None` skips the message).+pub type IggyKeyFn = Arc<dyn Fn(&IggyReceivedMessage) -> Option<String> + Send + Sync>;++/// Decides whether a message represents a *deletion* of its key (defaults to+/// "never" β Iggy has no tombstone).+pub type IggyIsDeletionFn = Arc<dyn Fn(&IggyReceivedMessage) -> bool + Send + Sync>;/// How the sources poll a topic; the same knobs as the Python connector's/// `topic_as_stream` / `topic_as_map`.@@ -489,7 +750,7 @@ pub struct IggySourceOptions {/// Partition to consume (default `0`).pub partition: u32,pub poll: IggyPollOptions,- /// Custom deletion predicate over the payload (default: never delete).+ /// Custom deletion predicate over the message (default: never delete).pub is_deletion: Option<IggyIsDeletionFn>,}@@ -592,6 +853,30 @@ impl TopicPoller {Ok(ids)}+ /// Each partition's end (the offset its next message gets), from the topic+ /// details: the initial high watermark readiness is measured against.+ async fn high_watermarks(&self, partitions: &[u32]) -> Result<BTreeMap<u32, u64>> {+ let details = self.topic_details().await?;+ Ok(partitions+ .iter()+ .map(|&pid| {+ let end = details+ .partitions+ .iter()+ .find(|p| p.id == pid)+ .map(|p| {+ if p.messages_count == 0 {+ 0+ } else {+ p.current_offset + 1+ }+ })+ .unwrap_or(0);+ (pid, end)+ })+ .collect())+ }+/// Create the consumer group when it does not exist, and join it, so its/// offsets can be stored and read.async fn ensure_group(&self) -> Result<Identifier> {@@ -695,8 +980,8 @@ impl TopicPoller {}/// Read `partitions` from offset 0 to their current end, passing each- /// `(partition, message)` to `f`, and record where each ended for `watch`.- async fn scan(&self, partitions: &[u32], mut f: impl FnMut(u32, &IggyMessage)) -> Result<()> {+ /// message to `f`, and record where each ended for `watch`.+ async fn scan(&self, partitions: &[u32], mut f: impl FnMut(IggyReceivedMessage)) -> Result<()> {let mut ends: BTreeMap<u32, u64> = BTreeMap::new();for &pid in partitions {let mut offset = 0u64;@@ -708,7 +993,7 @@ impl TopicPoller {let hwm = polled.current_offset;for m in &polled.messages {offset = m.header.offset + 1;- f(pid, m);+ f(IggyReceivedMessage::from_message(pid, m));}if offset > hwm {break;@@ -735,67 +1020,117 @@ impl TopicPoller {Ok(true)}- /// Tail `partitions` from `watch_start`, delivering each message through- /// `deliver`; after each delivered batch the partition's last offset is- /// stored for the consumer group.+ /// Tail `partitions` from `watch_start`, delivering each message to+ /// `subscriber`; after each polled batch has been processed the+ /// partition's last offset is stored for the consumer group.async fn watch(&self,partitions: &[u32],- deliver: &dyn Deliver,- subscriber: &LiveMapSubscriber<String, Vec<u8>>,+ subscriber: &dyn LiveStreamSubscriber<IggyReceivedMessage>,) -> Result<()> {let _watch_token = self.watch_guard.enter()?;self.ensure_group().await?;- let mut offsets = self.watch_start.lock().await.clone();+ let starts = self.watch_start.lock().await.clone();+ let high_watermarks = self.high_watermarks(partitions).await?;+ let mut tails = Vec::new();for &pid in partitions {- let next = *offsets.entry(pid).or_insert(0);+ let start = starts.get(&pid).copied().unwrap_or(0);+ let source = IggyPartition {+ poller: self,+ partition: pid,+ };// The scan's end is the position the next run resumes from if// nothing new arrives.- if next > 0 {- self.store_offset(pid, next - 1).await?;- }+ source.commit(start as i64).await?;+ tails.push(PartitionTail {+ source,+ start: start as i64,+ high_watermark: high_watermarks.get(&pid).copied().unwrap_or(0) as i64,+ });}- loop {- let mut got_any = false;- for &pid in partitions {- let offset = *offsets.get(&pid).unwrap_or(&0);- let polled = self.poll(pid, offset).await?;- if polled.messages.is_empty() {- continue;- }- got_any = true;- let mut last = offset;- for m in &polled.messages {- last = m.header.offset;- deliver.deliver(pid, m, subscriber).await?;- }- offsets.insert(pid, last + 1);- self.store_offset(pid, last).await?;- }- if !got_any {- tokio::time::sleep(self.options.poll_interval).await;- }+ watch_partitions(tails, subscriber).await+ }+}++/// One partition of a watch, polled through its poller; the consumer group's+/// offset is stored on the server.+struct IggyPartition<'a> {+ poller: &'a TopicPoller,+ partition: u32,+}++#[crate::async_trait]+impl PartitionSource<IggyReceivedMessage> for IggyPartition<'_> {+ async fn fetch(&self, offset: i64) -> Result<Vec<(i64, IggyReceivedMessage)>> {+ let polled = self.poller.poll(self.partition, offset as u64).await?;+ if polled.messages.is_empty() {+ // Iggy answers an empty poll at once; pace the loop as Python's+ // `poll_interval` does.+ tokio::time::sleep(self.poller.options.poll_interval).await;}+ Ok(polled+ .messages+ .iter()+ .map(|m| {+ (+ m.header.offset as i64,+ IggyReceivedMessage::from_message(self.partition, m),+ )+ })+ .collect())}++ async fn commit(&self, next: i64) -> Result<()> {+ // Iggy stores the last consumed offset, not the next one to read.+ if next > 0 {+ self.poller+ .store_offset(self.partition, (next - 1) as u64)+ .await?;+ }+ Ok(())+ }+}++/// Delivers a stream's messages to a [`LiveMapSubscriber`]: each message is+/// keyed by `key_of`, mounted as a child (`Some(value)`) or deleted (`None`),+/// and skipped when `key_of` yields nothing.+struct StreamToMap<'a, F> {+ map: &'a LiveMapSubscriber<String, IggyReceivedMessage>,+ key_of: F,}-/// How a source delivers one polled message to its subscriber.#[crate::async_trait]-trait Deliver: Send + Sync {- async fn deliver(- &self,- partition: u32,- message: &IggyMessage,- subscriber: &LiveMapSubscriber<String, Vec<u8>>,- ) -> Result<()>;+impl<F> LiveStreamSubscriber<IggyReceivedMessage> for StreamToMap<'_, F>+where+ F: Fn(IggyReceivedMessage) -> Option<(String, Option<IggyReceivedMessage>)> + Send + Sync,+{+ async fn send(&self, message: IggyReceivedMessage) -> Result<ReadyHandle> {+ match (self.key_of)(message) {+ None => Ok(ReadyHandle::immediate()),+ Some((key, Some(value))) => self.map.start_update(key, value).await,+ Some((key, None)) => self.map.start_delete(key).await,+ }+ }++ async fn mark_ready(&self) {+ self.map.mark_ready().await;+ }++ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ self.map.read_committed_state(key).await+ }++ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ self.map.write_committed_state(key, &value.to_vec()).await+ }}-/// A keyed change feed over an Iggy topic partition: the latest payload per key+/// A keyed change feed over an Iggy topic partition: the latest message per key/// (as derived by the key function), with [`IggySourceOptions::is_deletion`]/// removing keys. The Rust analogue of Python's `topic_as_map`.////// As a [`LiveMapView`], [`scan`](LiveMapView::scan) reads the partition log up-/// to its current offset (compacted to the latest payload per key) and+/// to its current offset (compacted to the latest message per key) and/// [`watch`](LiveMapFeed::watch) tails new messages from there. The consumer/// group's offset is stored on the server once a polled batch's children have/// synced, and a later live run resumes from it instead of scanning. Feed it to@@ -851,50 +1186,36 @@ pub fn topic_as_map_with_options(}}-impl IggyTopicMap {- /// Classify a payload into `(key, Some(value))` upsert or `(key, None)`- /// delete; `None` when `key_fn` yields no key (message skipped).- fn classify(&self, payload: &[u8]) -> Option<(String, Option<Vec<u8>>)> {- let key = (self.key_fn)(payload)?;- let is_delete = self.is_deletion.as_ref().is_some_and(|f| f(payload));- Some((- key,- if is_delete {- None- } else {- Some(payload.to_vec())- },- ))- }+/// Classify a message into `(key, Some(message))` upsert or `(key, None)`+/// delete; `None` when `key_fn` yields no key (message skipped).+fn classify_message(+ key_fn: &IggyKeyFn,+ is_deletion: Option<&IggyIsDeletionFn>,+ message: IggyReceivedMessage,+) -> Option<(String, Option<IggyReceivedMessage>)> {+ let key = key_fn(&message)?;+ let is_delete = is_deletion.is_some_and(|f| f(&message));+ Some((key, if is_delete { None } else { Some(message) }))}-#[crate::async_trait]-impl Deliver for IggyTopicMap {- async fn deliver(+impl IggyTopicMap {+ fn classify(&self,- _partition: u32,- message: &IggyMessage,- subscriber: &LiveMapSubscriber<String, Vec<u8>>,- ) -> Result<()> {- let Some((key, value)) = self.classify(message.payload.as_ref()) else {- return Ok(());- };- match value {- Some(v) => subscriber.update(key, v).await,- None => subscriber.delete(key).await,- }+ message: IggyReceivedMessage,+ ) -> Option<(String, Option<IggyReceivedMessage>)> {+ classify_message(&self.key_fn, self.is_deletion.as_ref(), message)}}#[crate::async_trait]-impl LiveMapView<String, Vec<u8>> for IggyTopicMap {- async fn scan(&self) -> Result<Vec<(String, Vec<u8>)>> {+impl LiveMapView<String, IggyReceivedMessage> for IggyTopicMap {+ async fn scan(&self) -> Result<Vec<(String, IggyReceivedMessage)>> {// The partition must exist; `topic_details` also applies the init retries.self.poller.topic_details().await?;- let mut latest: BTreeMap<String, Vec<u8>> = BTreeMap::new();+ let mut latest: BTreeMap<String, IggyReceivedMessage> = BTreeMap::new();self.poller- .scan(&[self.partition], |_pid, m| {- if let Some((key, value)) = self.classify(m.payload.as_ref()) {+ .scan(&[self.partition], |m| {+ if let Some((key, value)) = self.classify(m) {match value {Some(v) => {latest.insert(key, v);@@ -911,34 +1232,44 @@ impl LiveMapView<String, Vec<u8>> for IggyTopicMap {}#[crate::async_trait]-impl LiveMapFeed<String, Vec<u8>> for IggyTopicMap {+impl LiveMapFeed<String, IggyReceivedMessage> for IggyTopicMap {async fn skip_initial_scan(&self, _operator: &LiveComponentOperator) -> Result<bool> {self.poller.topic_details().await?;self.poller.skip_initial_scan(&[self.partition]).await}- async fn watch(&self, subscriber: LiveMapSubscriber<String, Vec<u8>>) -> Result<()> {+ async fn watch(+ &self,+ subscriber: LiveMapSubscriber<String, IggyReceivedMessage>,+ ) -> Result<()> {self.poller- .watch(&[self.partition], self, &subscriber)+ .watch(+ &[self.partition],+ &StreamToMap {+ map: &subscriber,+ key_of: |message| self.classify(message),+ },+ ).await}}-/// A **keyless, append-only** payload feed over **all partitions** of an Iggy-/// topic β the Rust analogue of Python's `topic_as_stream(...).payloads()`,-/// extended to read every partition (like the Rust Kafka stream) instead of one.+/// A **keyless, append-only** [`LiveStream`] of every message of an Iggy+/// topic, across **all partitions** β the Rust analogue of Python's+/// `topic_as_stream`, extended to read every partition instead of one.+/// [`payloads`](Self::payloads) is the `LiveStream<Vec<u8>>` view.///-/// Unlike [`IggyTopicMap`] (which is keyed and per-partition), no key function or-/// deletion predicate is needed and nothing is compacted: every message is-/// delivered exactly once, keyed by its `"{partition}:{offset}"` position, so-/// each becomes a distinct child under-/// [`Ctx::mount_each_live`](crate::Ctx::mount_each_live).+/// [`watch`](LiveStream::watch) delivers each message to the subscriber,+/// stores a partition's offset for the consumer group once the messages up to+/// it are processed, and marks the subscriber ready once every partition has+/// caught up to the end it had when the watch started.///-/// As a [`LiveMapView`], [`scan`](LiveMapView::scan) reads every partition up to-/// its current offset (so readiness reflects all partitions being caught up) and-/// [`watch`](LiveMapFeed::watch) round-robins new messages across partitions,-/// storing each partition's offset for the consumer group as it goes. Re-running-/// is idempotent: the `partition:offset` keys are stable.+/// It is also a [`LiveMapView`] for+/// [`Ctx::mount_each_live`](crate::Ctx::mount_each_live): each message becomes+/// a distinct child keyed by its `"{partition}:{offset}"` position;+/// [`scan`](LiveMapView::scan) reads every partition up to its current offset+/// and the feed's `watch` tails new messages from there. Re-running is+/// idempotent: the position keys are stable.pub struct IggyTopicStream {poller: TopicPoller,}@@ -980,49 +1311,102 @@ pub fn topic_as_stream_with_options(}}+impl IggyTopicStream {+ /// The `LiveStream<Vec<u8>>` view of this stream: each message's payload.+ /// Python's `TopicStream.payloads()`.+ pub fn payloads(self) -> IggyPayloadStream {+ IggyPayloadStream { stream: self }+ }+}+/// The stream's child key for a message: its position.-fn position_key(partition: u32, message: &IggyMessage) -> String {- format!("{partition}:{}", message.header.offset)+fn position_key(message: &IggyReceivedMessage) -> String {+ format!("{}:{}", message.partition, message.offset)}#[crate::async_trait]-impl Deliver for IggyTopicStream {- async fn deliver(+impl LiveStream<IggyReceivedMessage> for IggyTopicStream {+ async fn watch(&self,- partition: u32,- message: &IggyMessage,- subscriber: &LiveMapSubscriber<String, Vec<u8>>,+ subscriber: &dyn LiveStreamSubscriber<IggyReceivedMessage>,) -> Result<()> {- subscriber- .update(position_key(partition, message), message.payload.to_vec())- .await+ let ids = self.poller.partition_ids().await?;+ self.poller.watch(&ids, subscriber).await}}#[crate::async_trait]-impl LiveMapView<String, Vec<u8>> for IggyTopicStream {- async fn scan(&self) -> Result<Vec<(String, Vec<u8>)>> {+impl LiveMapView<String, IggyReceivedMessage> for IggyTopicStream {+ async fn scan(&self) -> Result<Vec<(String, IggyReceivedMessage)>> {let ids = self.poller.partition_ids().await?;- let mut out: Vec<(String, Vec<u8>)> = Vec::new();+ let mut out: Vec<(String, IggyReceivedMessage)> = Vec::new();self.poller- .scan(&ids, |pid, m| {- out.push((position_key(pid, m), m.payload.to_vec()));- })+ .scan(&ids, |m| out.push((position_key(&m), m))).await?;Ok(out)}}#[crate::async_trait]-impl LiveMapFeed<String, Vec<u8>> for IggyTopicStream {+impl LiveMapFeed<String, IggyReceivedMessage> for IggyTopicStream {async fn skip_initial_scan(&self, _operator: &LiveComponentOperator) -> Result<bool> {let ids = self.poller.partition_ids().await?;self.poller.skip_initial_scan(&ids).await}- async fn watch(&self, subscriber: LiveMapSubscriber<String, Vec<u8>>) -> Result<()> {+ async fn watch(+ &self,+ subscriber: LiveMapSubscriber<String, IggyReceivedMessage>,+ ) -> Result<()> {let ids = self.poller.partition_ids().await?;- self.poller.watch(&ids, self, &subscriber).await+ self.poller+ .watch(+ &ids,+ &StreamToMap {+ map: &subscriber,+ key_of: |message| Some((position_key(&message), Some(message))),+ },+ )+ .await+ }+}++/// The `LiveStream<Vec<u8>>` view of an [`IggyTopicStream`]: each message's+/// payload. From [`IggyTopicStream::payloads`].+pub struct IggyPayloadStream {+ stream: IggyTopicStream,+}++/// Adapts a payload subscriber to the message-level stream.+struct PayloadsAdapter<'a>(&'a dyn LiveStreamSubscriber<Vec<u8>>);++#[crate::async_trait]+impl LiveStreamSubscriber<IggyReceivedMessage> for PayloadsAdapter<'_> {+ async fn send(&self, message: IggyReceivedMessage) -> Result<ReadyHandle> {+ self.0.send(message.payload).await+ }++ async fn mark_ready(&self) {+ self.0.mark_ready().await;+ }++ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ self.0.read_committed_state(key).await+ }++ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ self.0.write_committed_state(key, value).await+ }+}++#[crate::async_trait]+impl LiveStream<Vec<u8>> for IggyPayloadStream {+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<Vec<u8>>) -> Result<()> {+ let ids = self.stream.poller.partition_ids().await?;+ self.stream+ .poller+ .watch(&ids, &PayloadsAdapter(subscriber))+ .await}}@@ -1031,13 +1415,13 @@ mod tests {use super::*;fn fp(bytes: &[u8]) -> Fingerprint {- Fingerprint::from(&bytes.to_vec()).unwrap()+ Fingerprint::from_bytes(bytes)}// Upsert new state (no previous record, prev_may_be_missing).#[test]fn upsert_new_state() {- let d = decide_message("k1", Some(b"v1"), &[], true, None)+ let d = decide_message(b"k1", Some(b"v1"), &[], true, None).unwrap().expect("should send");assert_eq!(d.value, b"v1");@@ -1047,14 +1431,14 @@ mod tests {// Unchanged value with a matching previous fingerprint β skip.#[test]fn upsert_unchanged_skips() {- let d = decide_message("k1", Some(b"v1"), &[fp(b"v1")], false, None).unwrap();+ let d = decide_message(b"k1", Some(b"v1"), &[fp(b"v1")], false, None).unwrap();assert_eq!(d, None);}// Changed value β send the new value.#[test]fn upsert_changed_value() {- let d = decide_message("k1", Some(b"v2"), &[fp(b"v1")], false, None)+ let d = decide_message(b"k1", Some(b"v2"), &[fp(b"v1")], false, None).unwrap().expect("should send");assert_eq!(d.value, b"v2");@@ -1064,22 +1448,23 @@ mod tests {// prev_may_be_missing forces a send even when the fingerprint matches.#[test]fn upsert_prev_may_be_missing_forces_send() {- let d = decide_message("k1", Some(b"v1"), &[fp(b"v1")], true, None).unwrap();+ let d = decide_message(b"k1", Some(b"v1"), &[fp(b"v1")], true, None).unwrap();assert!(d.is_some());}// Delete without a deletion_value_fn β error (Iggy has no tombstone).#[test]fn delete_without_callback_errors() {- let err = decide_message("k1", None, &[fp(b"v1")], false, None).unwrap_err();+ let err = decide_message(b"k1", None, &[fp(b"v1")], false, None).unwrap_err();assert!(err.to_string().contains("tombstone"));}// Delete with a deletion_value_fn β send that value, no tracking record.#[test]fn delete_with_callback_uses_value() {- let f: DeletionValueFn = Arc::new(|k: &str| format!("deleted:{k}").into_bytes());- let d = decide_message("k1", None, &[fp(b"v1")], false, Some(&f))+ let f: DeletionValueFn =+ Arc::new(|k: &[u8]| format!("deleted:{}", String::from_utf8_lossy(k)).into_bytes());+ let d = decide_message(b"k1", None, &[fp(b"v1")], false, Some(&f)).unwrap().expect("should send deletion value");assert_eq!(d.value, b"deleted:k1");@@ -1089,10 +1474,72 @@ mod tests {// Delete with no previous record and prev known-present β skip.#[test]fn delete_no_prev_skips() {- let d = decide_message("k1", None, &[], false, None).unwrap();+ let d = decide_message(b"k1", None, &[], false, None).unwrap();assert_eq!(d, None);}+ // The tracking record is the raw-bytes fingerprint, as Python's+ // `fingerprint_bytes` computes it, not a serde encoding of the bytes.+ #[test]+ fn tracking_record_is_the_raw_bytes_fingerprint() {+ let d = decide_message(b"k", Some(b"v1"), &[], true, None)+ .unwrap()+ .unwrap();+ assert_ne!(+ d.tracking,+ Some(Fingerprint::from(&b"v1".to_vec()).unwrap())+ );+ }++ #[test]+ fn topic_key_round_trips_through_the_stable_key() {+ let key = TopicKey {+ producer_key: "p".into(),+ stream: "s".into(),+ topic: "t".into(),+ partition: 3,+ };+ let back = TopicKey::from_stable_key(&key.clone().stable_key()).unwrap();+ assert!(back == key);+ assert!(TopicKey::from_stable_key(&StableKey::Int(1)).is_err());+ }++ fn message(offset: u64, payload: &str) -> IggyReceivedMessage {+ IggyReceivedMessage {+ partition: 2,+ offset,+ id: 0,+ timestamp: 0,+ checksum: 0,+ payload: payload.as_bytes().to_vec(),+ }+ }++ // The key and deletion functions see the whole message, not only its+ // payload; a message without a key is skipped.+ #[test]+ fn map_keys_and_deletes_from_the_whole_message() {+ let key_fn: IggyKeyFn = Arc::new(|m| {+ m.payload_str()+ .split_once('=')+ .map(|(k, _)| format!("{}:{k}", m.partition))+ });+ let is_deletion: IggyIsDeletionFn = Arc::new(|m| m.payload_str().ends_with("=DEL"));+ assert_eq!(+ classify_message(&key_fn, Some(&is_deletion), message(1, "k=DEL")),+ Some(("2:k".into(), None))+ );+ let kept = classify_message(&key_fn, Some(&is_deletion), message(1, "k=v")).unwrap();+ assert_eq!(kept.0, "2:k");+ assert_eq!(kept.1.unwrap().payload_str(), "k=v");+ assert_eq!(classify_message(&key_fn, None, message(1, "nokey")), None);+ }++ #[test]+ fn stream_position_key_names_partition_and_offset() {+ assert_eq!(position_key(&message(7, "")), "2:7");+ }+#[test]fn sanitize_state_id_strips_credentials() {assert_eq!(diff --git a/rust/sdk/cocoindex/src/connectors/kafka.rs b/rust/sdk/cocoindex/src/connectors/kafka.rsindex e294df64..cbcf6e25 100644--- a/rust/sdk/cocoindex/src/connectors/kafka.rs+++ b/rust/sdk/cocoindex/src/connectors/kafka.rs@@ -13,18 +13,22 @@//! [`KafkaTopicOptions::deletion_value_fn`].//!//! The producer is provided under a [`ContextKey`] (as every connection in the-//! Rust SDK is) and resolved when the target's actions apply. Use-//! [`declare_kafka_topic_target`] / [`mount_kafka_topic_target`] to get a-//! handle for declaring messages. [`KafkaProducer::ensure_topic`] is an-//! explicit, idempotent topic-creation helper outside reconciliation.+//! Rust SDK is) and resolved when the target's actions apply. [`kafka_topic_target`]+//! builds the topic's [`TargetState`] for `mount_target` /+//! `declare_target_state_with_child`; [`declare_kafka_topic_target`] /+//! [`mount_kafka_topic_target`] wrap those and return a handle for declaring+//! messages. [`KafkaProducer::ensure_topic`] is an explicit, idempotent+//! topic-creation helper outside reconciliation.//!//! # Sources//!-//! [`topic_as_map`] reads one topic as a keyed map (the latest value per message-//! key; a tombstone removes the key) and [`topic_as_stream`] reads one or more-//! topics as an append-only stream of every record. Both yield the full-//! [`KafkaMessage`] (key, value, headers, partition, offset, timestamp), and both-//! read every partition.+//! [`topic_as_stream`] reads one or more topics as a [`LiveStream`] of every+//! record ([`KafkaTopicStream`]; [`payloads`](KafkaTopicStream::payloads) is the+//! `LiveStream<Vec<u8>>` view of the values) and [`topic_as_map`] reads one topic+//! as a keyed map (the latest value per message key; a tombstone removes the+//! key). Both yield the full [`KafkaMessage`] (key, value, headers, partition,+//! offset, timestamp), both read every partition, and both are also+//! [`LiveMapView`]s for [`Ctx::mount_each_live`](crate::Ctx::mount_each_live).//!//! A [`KafkaConsumer`] built with a//! [`consumer_group`](KafkaConsumerOptions::consumer_group) keeps its position:@@ -38,14 +42,17 @@//!//! Uses [`rskafka`], a pure-Rust async Kafka client with no `librdkafka`/C//! dependency. SASL (PLAIN, SCRAM) and TLS are configured with-//! [`KafkaConnectOptions`]. `rskafka` does not speak the consumer-group-//! protocol, so a consumer group here is CocoIndex's own durable cursor, not a-//! broker-side group: the broker does not see its lag, and two processes with-//! the same group name do not share partitions between them.+//! [`KafkaConnectOptions`]; a client built by the caller is wrapped with+//! [`KafkaProducer::from_client`] / [`KafkaConsumer::from_client`]. `rskafka`+//! does not speak the consumer-group protocol, so a consumer group here is+//! CocoIndex's own durable cursor, not a broker-side group: the broker does not+//! see its lag, and two processes with the same group name do not share+//! partitions between them.use std::collections::BTreeMap;+use std::future::Future;use std::path::PathBuf;-use std::sync::Arc;+use std::sync::{Arc, Mutex};use cocoindex_utils::fingerprint::Fingerprint;use rskafka::client::partition::{Compression, OffsetAt, PartitionClient, UnknownTopicHandling};@@ -54,14 +61,17 @@ use rskafka::record::{Record, RecordAndOffset};use serde::{Deserialize, Serialize};use tokio::sync::OnceCell;+use crate::connectors::partition_tail::{PartitionSource, PartitionTail, watch_partitions};use crate::ctx::{ContextKey, ContextStore, Ctx};use crate::error::{Error, Result};use crate::live_component::{- LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, SingleWatcherGuard,+ LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream,+ LiveStreamSubscriber, ReadyHandle, SingleWatcherGuard,};use crate::target_state::{- SinkCache, StableKey, TargetAction, TargetActionSink, TargetHandler, TargetReconcileOutput,- TargetStateProvider, declare_target_state, register_root_target_states_provider,+ ChildTargetDef, STATIC_ROOT_PROVIDERS, SinkCache, StableKey, StaticRootProvider, TargetAction,+ TargetActionSink, TargetHandler, TargetReconcileOutput, TargetState, TargetStateProvider,+ declare_target_state, declare_target_state_with_child, mount_target,};// ---------------------------------------------------------------------------@@ -246,6 +256,17 @@ impl KafkaProducer {Ok(Self { client, state_id })}+ /// Wrap an `rskafka` client the caller built (with a connection setup the+ /// options cannot express), as the Python target takes the caller's+ /// `AIOProducer`. `state_id` is the stable identity of the cluster (e.g.+ /// its bootstrap-server list), never a credential.+ pub fn from_client(client: Client, state_id: impl Into<String>) -> Self {+ Self {+ client: Arc::new(client),+ state_id: Arc::from(state_id.into()),+ }+ }+/// Stable identity (the bootstrap-server list).pub fn state_id(&self) -> &str {&self.state_id@@ -294,8 +315,9 @@ impl KafkaProducer {// Public API: options + target + the constructor/declaration/mount split// ----------------------------------------------------------------------------/// Callback producing the value of a deletion record for a given message key.-pub type DeletionValueFn = Arc<dyn Fn(&str) -> Vec<u8> + Send + Sync>;+/// Callback producing the value of a deletion record for a message key (the+/// key as Kafka stores it: a `&str` key is its UTF-8 bytes).+pub type DeletionValueFn = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;/// Options for the Kafka topic target.#[derive(Clone, Default)]@@ -303,6 +325,10 @@ pub struct KafkaTopicOptions {/// How to represent a deletion. `None` (default) produces a *tombstone* β a/// record with the message key and a null value. When set, the callback's/// return value is used as the record value instead.+ ///+ /// The callback lives in this process: a run that declares the topic target+ /// (or drops the app from a process that did) applies it; `App::drop_state`+ /// from a process that never declared the topic target produces tombstones.pub deletion_value_fn: Option<DeletionValueFn>,}@@ -314,39 +340,58 @@ pub struct KafkaTopicTarget {topic: Arc<str>,}-/// Declare a Kafka topic target and return a ready same-component handle.-/// No external setup is needed, so this uses the same immediate provider path as-/// [`mount_kafka_topic_target`].+/// Build the composable [`TargetState`] of a Kafka topic (the spec+/// constructor), for `mount_target` / `declare_target_state_with_child`.+/// `producer` names the [`KafkaProducer`] provided in the environment; it is+/// resolved when the messages are produced.+pub fn kafka_topic_target(+ ctx: &Ctx,+ producer: &ContextKey<KafkaProducer>,+ topic: impl Into<String>,+ options: KafkaTopicOptions,+) -> Result<TargetState<TopicSpec>> {+ let topic = topic.into();+ if topic.is_empty() {+ return Err(Error::engine("kafka topic name must be non-empty"));+ }+ let key = TopicKey {+ producer_key: producer.name().to_string(),+ topic,+ };+ set_deletion_value_fn(&key, options.deletion_value_fn);+ let provider = TOPIC_PROVIDER.get(ctx)?;+ Ok(provider.target_state(key.stable_key(), TopicSpec {}))+}++/// Declare a Kafka topic target in the current component and return a handle+/// for declaring messages (the message provider resolves at this component's+/// commit).pub fn declare_kafka_topic_target(ctx: &Ctx,producer: &ContextKey<KafkaProducer>,topic: impl Into<String>,options: KafkaTopicOptions,) -> Result<KafkaTopicTarget> {- mount_kafka_topic_target(ctx, producer, topic, options)+ let topic = topic.into();+ let ts = kafka_topic_target(ctx, producer, topic.clone(), options)?;+ let messages = declare_target_state_with_child::<TopicSpec, Vec<u8>>(ctx, ts)?;+ Ok(KafkaTopicTarget {+ messages,+ topic: Arc::from(topic),+ })}-/// Declare a Kafka topic target in the current component and return a handle-/// for declaring messages. `producer` names the [`KafkaProducer`] provided in-/// the environment; it is resolved when the messages are produced.-pub fn mount_kafka_topic_target(+/// Mount a Kafka topic target **foreground** (messages can be declared at once)+/// and return a handle for declaring messages.+pub async fn mount_kafka_topic_target(ctx: &Ctx,producer: &ContextKey<KafkaProducer>,topic: impl Into<String>,options: KafkaTopicOptions,) -> Result<KafkaTopicTarget> {let topic = topic.into();- let messages = register_root_target_states_provider(- ctx,- // Stable connection identity = the ContextKey's name; the client is- // resolved at apply time from the host context, as the other targets do.- format!("cocoindex/kafka/topic/{}/{}", producer.name(), topic),- MessageHandler::new(- producer.name().to_string(),- topic.clone(),- options.deletion_value_fn,- ),- )?;+ let ts = kafka_topic_target(ctx, producer, topic.clone(), options)?;+ let messages = mount_target::<TopicSpec, Vec<u8>>(ctx, ts).await?;Ok(KafkaTopicTarget {messages,topic: Arc::from(topic),@@ -375,17 +420,167 @@ impl KafkaTopicTarget {self.messages.target_state(key, value.as_ref().to_vec()),)}++ /// [`declare_message`](Self::declare_message) with a binary key. A `&str`+ /// key and its UTF-8 bytes are distinct target states but one Kafka key;+ /// a key that switches between the two forms across runs is republished,+ /// not deleted.+ pub fn declare_message_bytes(+ &self,+ ctx: &Ctx,+ key: &[u8],+ value: impl AsRef<[u8]>,+ ) -> Result<()> {+ if key.is_empty() {+ return Err(Error::engine(+ "kafka declare_message_bytes: key must be non-empty",+ ));+ }+ declare_target_state(+ ctx,+ self.messages+ .target_state(StableKey::Bytes(Arc::from(key)), value.as_ref().to_vec()),+ )+ }}// ----------------------------------------------------------------------------// Message handler (root)+// Topic handler (root, static) and its message child handler// ---------------------------------------------------------------------------+/// Spec of a Kafka topic target (the declared container value). Topics are+/// user-managed, so the spec carries nothing: the topic's identity is in its key.+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]+pub struct TopicSpec {}++#[linkme::distributed_slice(STATIC_ROOT_PROVIDERS)]+static TOPIC_PROVIDER: StaticRootProvider =+ StaticRootProvider::new::<TopicSpec, TopicHandler>("cocoindex/kafka/topic");++/// A topic target state's key: the producer's `ContextKey` name plus the topic+/// name. Mirrors Python's `_TopicKey`.+#[derive(Clone, PartialEq, Eq, Hash)]+struct TopicKey {+ producer_key: String,+ topic: String,+}++impl TopicKey {+ fn stable_key(self) -> StableKey {+ StableKey::Array(Arc::from([+ StableKey::Str(Arc::from(self.producer_key)),+ StableKey::Str(Arc::from(self.topic)),+ ]))+ }++ fn from_stable_key(key: &StableKey) -> Result<Self> {+ if let StableKey::Array(parts) = key+ && let [StableKey::Str(producer_key), StableKey::Str(topic)] = &parts[..]+ {+ return Ok(Self {+ producer_key: producer_key.to_string(),+ topic: topic.to_string(),+ });+ }+ Err(Error::engine(format!(+ "unexpected kafka topic key: {key:?}"+ )))+ }+}++/// The deletion-value callbacks of the topic targets this process declared,+/// looked up when a topic's message handler is built (the spec is persisted,+/// a closure cannot be).+static DELETION_VALUE_FNS: Mutex<Option<std::collections::HashMap<TopicKey, DeletionValueFn>>> =+ Mutex::new(None);++fn set_deletion_value_fn(key: &TopicKey, f: Option<DeletionValueFn>) {+ let mut guard = DELETION_VALUE_FNS.lock().unwrap_or_else(|e| e.into_inner());+ let fns = guard.get_or_insert_with(Default::default);+ match f {+ Some(f) => {+ fns.insert(key.clone(), f);+ }+ None => {+ fns.remove(key);+ }+ }+}++fn deletion_value_fn(key: &TopicKey) -> Option<DeletionValueFn> {+ DELETION_VALUE_FNS+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_ref()+ .and_then(|fns| fns.get(key).cloned())+}++/// The topic-level action: nothing to apply (topics are user-managed); it+/// carries the key the message child handler is built from.+#[derive(Serialize, Deserialize)]+struct TopicAction {+ producer_key: String,+ topic: String,+}++#[derive(Default)]+struct TopicHandler {+ sink: SinkCache<TopicAction>,+}++impl TargetHandler<TopicSpec> for TopicHandler {+ type TrackingRecord = ();+ type Action = TopicAction;++ fn reconcile(+ &self,+ key: StableKey,+ desired: Option<TopicSpec>,+ _prev: Vec<()>,+ _prev_may_be_missing: bool,+ ) -> Result<Option<TargetReconcileOutput<TopicAction, ()>>> {+ let topic_key = TopicKey::from_stable_key(&key)?;+ let action = TopicAction {+ producer_key: topic_key.producer_key,+ topic: topic_key.topic,+ };+ // Always emit when declared, so the sink builds the message child.+ Ok(Some(TargetReconcileOutput {+ action: match desired {+ Some(_) => TargetAction::Update(action),+ None => TargetAction::Delete(action),+ },+ sink: self.sink.get(topic_sink),+ tracking_record: desired.map(|_| ()),+ child_invalidation: None,+ }))+ }+}++fn topic_sink() -> TargetActionSink<TopicAction> {+ TargetActionSink::from_async_fn_with_child_handler(+ // Topics are not created or deleted, so there is nothing to apply.+ |_actions| async { Ok(()) },+ |action: &TopicAction| {+ let key = TopicKey {+ producer_key: action.producer_key.clone(),+ topic: action.topic.clone(),+ };+ let deletion_value_fn = deletion_value_fn(&key);+ Ok(ChildTargetDef::new::<Vec<u8>, _>(MessageHandler::new(+ key.producer_key,+ key.topic,+ deletion_value_fn,+ )))+ },+ )+}+/// What the sink should do for one message: produce a record with this value/// (`None` value = tombstone).#[derive(Serialize, Deserialize)]struct MessageAction {- key: String,+ key: Vec<u8>,value: Option<Vec<u8>>,}@@ -412,6 +607,17 @@ impl MessageHandler {}}+/// The Kafka key of a message target state: a `Str` key is its UTF-8 bytes.+fn message_key_bytes(key: &StableKey) -> Result<Vec<u8>> {+ match key {+ StableKey::Str(s) => Ok(s.as_bytes().to_vec()),+ StableKey::Bytes(b) => Ok(b.to_vec()),+ other => Err(Error::engine(format!(+ "unexpected kafka message key: {other:?}"+ ))),+ }+}+impl TargetHandler<Vec<u8>> for MessageHandler {type TrackingRecord = Fingerprint;type Action = MessageAction;@@ -423,21 +629,14 @@ impl TargetHandler<Vec<u8>> for MessageHandler {prev: Vec<Fingerprint>,prev_may_be_missing: bool,) -> Result<Option<TargetReconcileOutput<MessageAction, Fingerprint>>> {- let StableKey::Str(key) = &key else {- return Err(Error::engine(format!(- "unexpected kafka message key: {key:?}"- )));- };- let key = key.to_string();-+ let key = message_key_bytes(&key)?;let Some(decision) = decide_message(&key,desired.as_deref(),&prev,prev_may_be_missing,self.deletion_value_fn.as_ref(),- )?- else {+ ) else {return Ok(None);};@@ -494,35 +693,79 @@ impl MessageHandler {.await?;let timestamp = current_timestamp();let mut by_partition: BTreeMap<i32, Vec<Record>> = BTreeMap::new();- for action in actions {- let msg = match action {- TargetAction::Create(m)- | TargetAction::Update(m)- | TargetAction::Delete(m) => m,- };- let partition = partitions.partition_for_key(msg.key.as_bytes()).await?;+ for msg in dedupe_switched_keys(actions) {+ let partition = partitions.partition_for_key(&msg.key).await?;by_partition.entry(partition).or_default().push(Record {- key: Some(msg.key.into_bytes()),+ key: Some(msg.key),value: msg.value,headers: BTreeMap::new(),timestamp,});}- for (partition, records) in by_partition {- partitions- .client(partition)- .await?- .produce(records, Compression::NoCompression)- .await- .map_err(|e| Error::engine(format!("kafka produce: {e}")))?;- }- Ok(())+ produce_batches(by_partition, |partition, records| {+ let partitions = partitions.clone();+ async move {+ partitions+ .client(partition)+ .await?+ .produce(records, Compression::NoCompression)+ .await+ .map_err(|e| Error::engine(format!("kafka produce: {e}")))?;+ Ok(())+ }+ })+ .await}},)}}+/// A `Str` key and its UTF-8 bytes are distinct target states but one Kafka+/// key. When a key switches between the two forms across runs, one batch+/// carries both the new form's publish and the old form's deletion; the+/// deletion would erase the record just published, so it is dropped.+fn dedupe_switched_keys(actions: Vec<TargetAction<MessageAction>>) -> Vec<MessageAction> {+ let messages: Vec<MessageAction> = actions+ .into_iter()+ .map(|action| match action {+ TargetAction::Create(m) | TargetAction::Update(m) | TargetAction::Delete(m) => m,+ })+ .collect();+ let published: std::collections::HashSet<&[u8]> = messages+ .iter()+ .filter(|m| m.value.is_some())+ .map(|m| m.key.as_slice())+ .collect();+ let mut out = Vec::with_capacity(messages.len());+ for m in &messages {+ if m.value.is_none() && published.contains(m.key.as_slice()) {+ continue;+ }+ out.push(MessageAction {+ key: m.key.clone(),+ value: m.value.clone(),+ });+ }+ out+}++/// Produce every partition's batch at the same time, not one partition after+/// another: a batch's round trip overlaps the others'.+async fn produce_batches<F, Fut>(by_partition: BTreeMap<i32, Vec<Record>>, produce: F) -> Result<()>+where+ F: Fn(i32, Vec<Record>) -> Fut,+ Fut: Future<Output = Result<()>>,+{+ futures::future::try_join_all(+ by_partition+ .into_iter()+ .map(|(partition, records)| produce(partition, records)),+ )+ .await?;+ Ok(())+}+/// A topic's partitions and their clients, loaded lazily on first produce.struct TopicPartitions {client: Arc<Client>,@@ -596,6 +839,13 @@ async fn earliest_offset(pc: &PartitionClient) -> Result<i64> {.map_err(|e| Error::engine(format!("kafka get_offset: {e}")))}+/// The partition's high watermark: the offset the next produced record gets.+async fn latest_offset(pc: &PartitionClient) -> Result<i64> {+ pc.get_offset(OffsetAt::Latest)+ .await+ .map_err(|e| Error::engine(format!("kafka get_offset: {e}")))+}+/// The partition index for a record key: librdkafka's default/// `consistent_random` partitioner (CRC32 of the key modulo the partition/// count), so the Rust and Python connectors place a key in the same@@ -627,40 +877,33 @@ struct MessageDecision {/// * known-absent deletes are skipped,/// * other deletes produce a tombstone or `deletion_value_fn(key)`.fn decide_message(- key: &str,+ key: &[u8],desired_value: Option<&[u8]>,prev_fps: &[Fingerprint],prev_may_be_missing: bool,deletion_value_fn: Option<&DeletionValueFn>,-) -> Result<Option<MessageDecision>> {- let desired_fp = match desired_value {- Some(v) => Some(Fingerprint::from(&v.to_vec()).map_err(Error::from)?),- None => None,- };-+) -> Option<MessageDecision> {// Upsert path.if let Some(value) = desired_value {- let fp = desired_fp- .as_ref()- .expect("desired_fp set when value present");- if !prev_may_be_missing && !prev_fps.is_empty() && prev_fps.iter().all(|p| p == fp) {- return Ok(None);+ let fp = Fingerprint::from_bytes(value);+ if !prev_may_be_missing && !prev_fps.is_empty() && prev_fps.iter().all(|p| *p == fp) {+ return None;}- return Ok(Some(MessageDecision {+ return Some(MessageDecision {value: Some(value.to_vec()),- tracking: desired_fp,- }));+ tracking: Some(fp),+ });}// Delete path.if prev_fps.is_empty() && !prev_may_be_missing {- return Ok(None);+ return None;}let value = deletion_value_fn.map(|f| f(key));- Ok(Some(MessageDecision {+ Some(MessageDecision {value,tracking: None,- }))+ })}/// Current wall-clock time as a chrono UTC timestamp, without requiring chrono's@@ -750,14 +993,35 @@ impl KafkaConsumer {bootstrap_servers: &[&str],options: KafkaConsumerOptions,) -> Result<Self> {- if options.consumer_group.as_deref() == Some("") {+ let (client, state_id) = build_client(bootstrap_servers, options.connect).await?;+ Self::with_group(client, state_id, options.consumer_group)+ }++ /// Wrap an `rskafka` client the caller built (with a connection setup the+ /// options cannot express), as the Python sources take the caller's+ /// `AIOConsumer`. `state_id` is the stable identity of the cluster (e.g.+ /// its bootstrap-server list), never a credential; `consumer_group` is as+ /// in [`KafkaConsumerOptions`].+ pub fn from_client(+ client: Client,+ state_id: impl Into<String>,+ consumer_group: Option<String>,+ ) -> Result<Self> {+ Self::with_group(Arc::new(client), Arc::from(state_id.into()), consumer_group)+ }++ fn with_group(+ client: Arc<Client>,+ state_id: Arc<str>,+ consumer_group: Option<String>,+ ) -> Result<Self> {+ if consumer_group.as_deref() == Some("") {return Err(Error::engine("kafka: consumer_group must be non-empty"));}- let (client, state_id) = build_client(bootstrap_servers, options.connect).await?;Ok(Self {client,state_id,- consumer_group: options.consumer_group.map(Arc::from),+ consumer_group: consumer_group.map(Arc::from),})}@@ -790,14 +1054,62 @@ fn offset_state_key(group: &str, topic: &str, partition: i32) -> String {format!("cocoindex/kafka/offset/{group}/{topic}/{partition}")}-/// How a source delivers one consumed message to its subscriber.+/// The committed next offset, as the subscriber stores it (decimal text).+fn encode_offset(offset: i64) -> Vec<u8> {+ offset.to_string().into_bytes()+}++fn decode_offset(bytes: &[u8]) -> Result<i64> {+ std::str::from_utf8(bytes)+ .ok()+ .and_then(|s| s.parse().ok())+ .ok_or_else(|| Error::engine("kafka: committed offset is not a number"))+}++/// How long one fetch waits at the broker for a record before it returns+/// empty; also the loop's pacing while a partition is idle.+const FETCH_MAX_WAIT_MS: i32 = 250;++/// One partition of a watch: its client, and where the consumer group's+/// cursor is committed (through the subscriber's live component).+struct KafkaPartition<'a> {+ topic: String,+ partition: i32,+ client: PartitionClient,+ group: Option<&'a str>,+ subscriber: &'a dyn LiveStreamSubscriber<KafkaMessage>,+}+#[crate::async_trait]-trait Deliver: Send + Sync {- async fn deliver(- &self,- message: KafkaMessage,- subscriber: &LiveMapSubscriber<String, KafkaMessage>,- ) -> Result<()>;+impl PartitionSource<KafkaMessage> for KafkaPartition<'_> {+ async fn fetch(&self, offset: i64) -> Result<Vec<(i64, KafkaMessage)>> {+ let (records, _hwm) = self+ .client+ .fetch_records(offset, 1..1_000_000, FETCH_MAX_WAIT_MS)+ .await+ .map_err(|e| Error::engine(format!("kafka fetch_records: {e}")))?;+ Ok(records+ .into_iter()+ .map(|r| {+ (+ r.offset,+ KafkaMessage::from_record(&self.topic, self.partition, r),+ )+ })+ .collect())+ }++ async fn commit(&self, next: i64) -> Result<()> {+ if let Some(group) = self.group {+ self.subscriber+ .write_committed_state(+ &offset_state_key(group, &self.topic, self.partition),+ &encode_offset(next),+ )+ .await?;+ }+ Ok(())+ }}/// The partition reading shared by [`KafkaTopicMap`] and [`KafkaTopicStream`]:@@ -880,7 +1192,7 @@ impl TopicReader {};let mut starts: BTreeMap<(String, i32), i64> = BTreeMap::new();for (topic, id) in self.partitions().await? {- let committed: Option<i64> = operator+ let committed: Option<Vec<u8>> = operator.read_committed_state(offset_state_key(group, &topic, id)).await?;let Some(offset) = committed else {@@ -888,82 +1200,83 @@ impl TopicReader {// since) needs the scan.return Ok(false);};- starts.insert((topic, id), offset);+ starts.insert((topic, id), decode_offset(&offset)?);}*self.watch_start.lock().await = starts;Ok(true)}- /// Tail every partition from `watch_start`, delivering each record through- /// `deliver`. With a consumer group, each partition's next offset is- /// committed after every fetched batch has been delivered (and so its child- /// components synced).- async fn watch(- &self,- deliver: &dyn Deliver,- subscriber: &LiveMapSubscriber<String, KafkaMessage>,- ) -> Result<()> {+ /// Tail every partition from `watch_start` (the scan's end, the committed+ /// cursor, or else the earliest retained record), delivering each record to+ /// `subscriber`. With a consumer group, each partition's next offset is+ /// committed after every fetched batch has been processed.+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<KafkaMessage>) -> Result<()> {let _watch_token = self.watch_guard.enter()?;- let mut offsets = self.watch_start.lock().await.clone();- let mut clients = Vec::new();+ let starts = self.watch_start.lock().await.clone();+ let group = self.consumer_group.as_deref();+ let mut tails = Vec::new();for (topic, id) in self.partitions().await? {let pc = self.partition_client(&topic, id).await?;// A partition without a scan snapshot or cursor starts at its// earliest retained record, not offset 0, which retention may have// removed.- if let std::collections::btree_map::Entry::Vacant(slot) =- offsets.entry((topic.clone(), id))- {- slot.insert(earliest_offset(&pc).await?);- }- clients.push((topic, id, pc));- }- if let Some(group) = &self.consumer_group {+ let start = match starts.get(&(topic.clone(), id)) {+ Some(&offset) => offset,+ None => earliest_offset(&pc).await?,+ };+ let high_watermark = latest_offset(&pc).await?;+ let source = KafkaPartition {+ topic,+ partition: id,+ client: pc,+ group,+ subscriber,+ };// The scan's end (or the cursor read back) is the position the next// run resumes from if nothing new arrives.- for ((topic, id), offset) in &offsets {- subscriber- .write_committed_state(offset_state_key(group, topic, *id), offset)- .await?;- }+ source.commit(start).await?;+ tails.push(PartitionTail {+ source,+ start,+ high_watermark,+ });}- // Round-robin all partitions on one loop (one subscriber, used- // sequentially). Each partition fetch uses a short max-wait so the- // cycle stays responsive; an empty full cycle backs off briefly.- loop {- let mut got_any = false;- for (topic, id, pc) in &clients {- let key = (topic.clone(), *id);- let Some(&offset) = offsets.get(&key) else {- continue;- };- let (records, _hwm) = pc- .fetch_records(offset, 1..1_000_000, 250)- .await- .map_err(|e| Error::engine(format!("kafka fetch_records: {e}")))?;- if records.is_empty() {- continue;- }- got_any = true;- let mut next = offset;- for r in records {- next = r.offset + 1;- deliver- .deliver(KafkaMessage::from_record(topic, *id, r), subscriber)- .await?;- }- offsets.insert(key, next);- if let Some(group) = &self.consumer_group {- subscriber- .write_committed_state(offset_state_key(group, topic, *id), &next)- .await?;- }- }- if !got_any {- tokio::time::sleep(std::time::Duration::from_millis(250)).await;- }+ watch_partitions(tails, subscriber).await+ }+}++/// Delivers a stream's messages to a [`LiveMapSubscriber`]: each message is+/// keyed by `key_of`, mounted as a child (`Some(value)`) or deleted (`None`),+/// and skipped when `key_of` yields nothing.+struct StreamToMap<'a, F> {+ map: &'a LiveMapSubscriber<String, KafkaMessage>,+ key_of: F,+}++#[crate::async_trait]+impl<F> LiveStreamSubscriber<KafkaMessage> for StreamToMap<'_, F>+where+ F: Fn(KafkaMessage) -> Option<(String, Option<KafkaMessage>)> + Send + Sync,+{+ async fn send(&self, message: KafkaMessage) -> Result<ReadyHandle> {+ match (self.key_of)(message) {+ None => Ok(ReadyHandle::immediate()),+ Some((key, Some(value))) => self.map.start_update(key, value).await,+ Some((key, None)) => self.map.start_delete(key).await,}}++ async fn mark_ready(&self) {+ self.map.mark_ready().await;+ }++ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ self.map.read_committed_state(key).await+ }++ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ self.map.write_committed_state(key, &value.to_vec()).await+ }}/// A keyed change feed over **all partitions** of a Kafka topic: the latest@@ -1018,23 +1331,6 @@ impl KafkaTopicMap {}}-#[crate::async_trait]-impl Deliver for KafkaTopicMap {- async fn deliver(- &self,- message: KafkaMessage,- subscriber: &LiveMapSubscriber<String, KafkaMessage>,- ) -> Result<()> {- let Some((key, value)) = self.classify(message) else {- return Ok(());- };- match value {- Some(v) => subscriber.update(key, v).await,- None => subscriber.delete(key).await,- }- }-}-#[crate::async_trait]impl LiveMapFeed<String, KafkaMessage> for KafkaTopicMap {async fn skip_initial_scan(&self, operator: &LiveComponentOperator) -> Result<bool> {@@ -1042,7 +1338,12 @@ impl LiveMapFeed<String, KafkaMessage> for KafkaTopicMap {}async fn watch(&self, subscriber: LiveMapSubscriber<String, KafkaMessage>) -> Result<()> {- self.reader.watch(self, &subscriber).await+ self.reader+ .watch(&StreamToMap {+ map: &subscriber,+ key_of: |message| self.classify(message),+ })+ .await}}@@ -1068,21 +1369,24 @@ impl LiveMapView<String, KafkaMessage> for KafkaTopicMap {}}-/// A **keyless, append-only** feed over **all partitions** of one or more Kafka-/// topics β the Rust analogue of Python's `topic_as_stream`.+/// A **keyless, append-only** [`LiveStream`] of every record of one or more+/// Kafka topics, across **all partitions** β the Rust analogue of Python's+/// `topic_as_stream`. Tombstones (records with a `None` value) are delivered+/// too, as Python's message-level stream does; [`payloads`](Self::payloads) is+/// the `LiveStream<Vec<u8>>` view of the values, without them.///-/// Unlike [`KafkaTopicMap`], nothing is compacted or deleted: every record is-/// delivered exactly once, keyed by its `"{topic}:{partition}:{offset}"`-/// position, so each message becomes a distinct child under-/// [`Ctx::mount_each_live`](crate::Ctx::mount_each_live). Tombstones (records-/// with a `None` value) are delivered too, as Python's message-level stream-/// does; filter on [`KafkaMessage::value`] for the payloads view.+/// [`watch`](LiveStream::watch) delivers each record to the subscriber,+/// commits a partition's offset (with a consumer group) once the records up to+/// it are processed, and marks the subscriber ready once every partition has+/// caught up to the high watermark it had when the watch started.///-/// As a [`LiveMapView`], [`scan`](LiveMapView::scan) reads every partition up to-/// its high-watermark and [`watch`](LiveMapFeed::watch) tails new records from-/// there, or from the committed offsets of the consumer group. Re-running is-/// idempotent: the position keys are stable, so a replayed catch-up reconciles-/// to no-ops.+/// It is also a [`LiveMapView`] for+/// [`Ctx::mount_each_live`](crate::Ctx::mount_each_live): each record becomes+/// a distinct child keyed by its `"{topic}:{partition}:{offset}"` position;+/// [`scan`](LiveMapView::scan) reads every partition up to its high-watermark+/// and the feed's `watch` tails new records from there, or from the committed+/// offsets of the consumer group. Re-running is idempotent: the position keys+/// are stable, so a replayed catch-up reconciles to no-ops.pub struct KafkaTopicStream {reader: TopicReader,}@@ -1101,19 +1405,24 @@ pub fn topic_as_stream(}}+impl KafkaTopicStream {+ /// The `LiveStream<Vec<u8>>` view of this stream: each record's value.+ /// Tombstones are left out; subscribe at the [`KafkaMessage`] level for+ /// them. Python's `TopicStream.payloads()`.+ pub fn payloads(self) -> KafkaPayloadStream {+ KafkaPayloadStream { stream: self }+ }+}+/// The stream's child key for a message: its position.fn position_key(message: &KafkaMessage) -> String {format!("{}:{}:{}", message.topic, message.partition, message.offset)}#[crate::async_trait]-impl Deliver for KafkaTopicStream {- async fn deliver(- &self,- message: KafkaMessage,- subscriber: &LiveMapSubscriber<String, KafkaMessage>,- ) -> Result<()> {- subscriber.update(position_key(&message), message).await+impl LiveStream<KafkaMessage> for KafkaTopicStream {+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<KafkaMessage>) -> Result<()> {+ self.reader.watch(subscriber).await}}@@ -1135,13 +1444,59 @@ impl LiveMapFeed<String, KafkaMessage> for KafkaTopicStream {}async fn watch(&self, subscriber: LiveMapSubscriber<String, KafkaMessage>) -> Result<()> {- self.reader.watch(self, &subscriber).await+ self.reader+ .watch(&StreamToMap {+ map: &subscriber,+ key_of: |message| Some((position_key(&message), Some(message))),+ })+ .await+ }+}++/// The `LiveStream<Vec<u8>>` view of a [`KafkaTopicStream`]: each record's+/// value, tombstones left out. From [`KafkaTopicStream::payloads`].+pub struct KafkaPayloadStream {+ stream: KafkaTopicStream,+}++/// Adapts a payload subscriber to the message-level stream, acknowledging a+/// tombstone at once.+struct PayloadsAdapter<'a>(&'a dyn LiveStreamSubscriber<Vec<u8>>);++#[crate::async_trait]+impl LiveStreamSubscriber<KafkaMessage> for PayloadsAdapter<'_> {+ async fn send(&self, message: KafkaMessage) -> Result<ReadyHandle> {+ match message.value {+ Some(value) => self.0.send(value).await,+ None => Ok(ReadyHandle::immediate()),+ }+ }++ async fn mark_ready(&self) {+ self.0.mark_ready().await;+ }++ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ self.0.read_committed_state(key).await+ }++ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ self.0.write_committed_state(key, value).await+ }+}++#[crate::async_trait]+impl LiveStream<Vec<u8>> for KafkaPayloadStream {+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<Vec<u8>>) -> Result<()> {+ self.stream.reader.watch(&PayloadsAdapter(subscriber)).await}}#[cfg(test)]mod tests {use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;#[test]fn partition_index_matches_librdkafka_consistent_partitioner() {@@ -1153,15 +1508,13 @@ mod tests {}fn fp(bytes: &[u8]) -> Fingerprint {- Fingerprint::from(&bytes.to_vec()).unwrap()+ Fingerprint::from_bytes(bytes)}// U1: upsert new state (no previous record, prev_may_be_missing).#[test]fn upsert_new_state() {- let d = decide_message("k1", Some(b"v1"), &[], true, None)- .unwrap()- .expect("should produce");+ let d = decide_message(b"k1", Some(b"v1"), &[], true, None).expect("should produce");assert_eq!(d.value.as_deref(), Some(&b"v1"[..]));assert_eq!(d.tracking, Some(fp(b"v1")));}@@ -1169,16 +1522,15 @@ mod tests {// U2: unchanged value with a matching previous fingerprint β skip.#[test]fn upsert_unchanged_skips() {- let d = decide_message("k1", Some(b"v1"), &[fp(b"v1")], false, None).unwrap();+ let d = decide_message(b"k1", Some(b"v1"), &[fp(b"v1")], false, None);assert_eq!(d, None);}// U3: changed value β produce the new value.#[test]fn upsert_changed_value() {- let d = decide_message("k1", Some(b"v2"), &[fp(b"v1")], false, None)- .unwrap()- .expect("should produce");+ let d =+ decide_message(b"k1", Some(b"v2"), &[fp(b"v1")], false, None).expect("should produce");assert_eq!(d.value.as_deref(), Some(&b"v2"[..]));assert_eq!(d.tracking, Some(fp(b"v2")));}@@ -1186,16 +1538,14 @@ mod tests {// U4: prev_may_be_missing forces a produce even when the fingerprint matches.#[test]fn upsert_prev_may_be_missing_forces_produce() {- let d = decide_message("k1", Some(b"v1"), &[fp(b"v1")], true, None).unwrap();+ let d = decide_message(b"k1", Some(b"v1"), &[fp(b"v1")], true, None);assert!(d.is_some());}// U5: delete without a callback β tombstone (null value), no tracking record.#[test]fn delete_without_callback_is_tombstone() {- let d = decide_message("k1", None, &[fp(b"v1")], false, None)- .unwrap()- .expect("should tombstone");+ let d = decide_message(b"k1", None, &[fp(b"v1")], false, None).expect("should tombstone");assert_eq!(d.value, None);assert_eq!(d.tracking, None);}@@ -1203,9 +1553,9 @@ mod tests {// U6: delete with a deletion_value_fn β produce that value.#[test]fn delete_with_callback_uses_value() {- let f: DeletionValueFn = Arc::new(|k: &str| format!("deleted:{k}").into_bytes());- let d = decide_message("k1", None, &[fp(b"v1")], false, Some(&f))- .unwrap()+ let f: DeletionValueFn =+ Arc::new(|k: &[u8]| format!("deleted:{}", String::from_utf8_lossy(k)).into_bytes());+ let d = decide_message(b"k1", None, &[fp(b"v1")], false, Some(&f)).expect("should produce deletion value");assert_eq!(d.value.as_deref(), Some(&b"deleted:k1"[..]));assert_eq!(d.tracking, None);@@ -1214,10 +1564,60 @@ mod tests {// U7: delete with no previous record and prev known-present β skip.#[test]fn delete_no_prev_skips() {- let d = decide_message("k1", None, &[], false, None).unwrap();+ let d = decide_message(b"k1", None, &[], false, None);assert_eq!(d, None);}+ // The tracking record is the raw-bytes fingerprint, as Python's+ // `fingerprint_bytes` computes it, not a serde encoding of the bytes.+ #[test]+ fn tracking_record_is_the_raw_bytes_fingerprint() {+ let d = decide_message(b"k", Some(b"v1"), &[], true, None).unwrap();+ assert_eq!(d.tracking, Some(Fingerprint::from_bytes(b"v1")));+ assert_ne!(+ d.tracking,+ Some(Fingerprint::from(&b"v1".to_vec()).unwrap())+ );+ }++ #[test]+ fn message_keys_are_str_or_bytes() {+ assert_eq!(+ message_key_bytes(&StableKey::Str(Arc::from("k"))).unwrap(),+ b"k"+ );+ assert_eq!(+ message_key_bytes(&StableKey::Bytes(Arc::from(&b"\x00k"[..]))).unwrap(),+ b"\x00k"+ );+ assert!(message_key_bytes(&StableKey::Int(1)).is_err());+ }++ // A key that switched from `&str` to bytes (or back) between runs is+ // published once, and the old form's deletion in the same batch is dropped.+ #[test]+ fn switched_key_form_drops_the_deletion() {+ let out = dedupe_switched_keys(vec![+ TargetAction::Delete(MessageAction {+ key: b"k".to_vec(),+ value: None,+ }),+ TargetAction::Create(MessageAction {+ key: b"k".to_vec(),+ value: Some(b"v".to_vec()),+ }),+ TargetAction::Delete(MessageAction {+ key: b"gone".to_vec(),+ value: None,+ }),+ ]);+ let keys: Vec<(&[u8], bool)> = out+ .iter()+ .map(|m| (m.key.as_slice(), m.value.is_some()))+ .collect();+ assert_eq!(keys, vec![(&b"k"[..], true), (&b"gone"[..], false)]);+ }+fn message(key: Option<&[u8]>, value: Option<&[u8]>) -> KafkaMessage {KafkaMessage {topic: "t".into(),@@ -1281,4 +1681,54 @@ mod tests {);assert!(s.contains("PLAIN") && s.contains("\"u\"") && !s.contains("hunter2"));}++ #[test]+ fn committed_offsets_round_trip_as_text() {+ assert_eq!(decode_offset(&encode_offset(42)).unwrap(), 42);+ assert!(decode_offset(b"x").is_err());+ }++ // Each partition's batch is produced at the same time as the others'.+ #[tokio::test]+ async fn produce_batches_overlaps_partitions() {+ let in_flight = Arc::new(AtomicUsize::new(0));+ let max_in_flight = Arc::new(AtomicUsize::new(0));+ let by_partition: BTreeMap<i32, Vec<Record>> = (0..3).map(|p| (p, Vec::new())).collect();+ produce_batches(by_partition, |_partition, _records| {+ let in_flight = in_flight.clone();+ let max_in_flight = max_in_flight.clone();+ async move {+ let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ max_in_flight.fetch_max(now, Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(20)).await;+ in_flight.fetch_sub(1, Ordering::SeqCst);+ Ok(())+ }+ })+ .await+ .unwrap();+ assert_eq!(max_in_flight.load(Ordering::SeqCst), 3);+ }++ // The payloads view hands each value through and acknowledges a tombstone+ // without delivering it.+ #[tokio::test]+ async fn payloads_adapter_skips_tombstones() {+ struct Collect(Mutex<Vec<Vec<u8>>>);+ #[crate::async_trait]+ impl LiveStreamSubscriber<Vec<u8>> for Collect {+ async fn send(&self, message: Vec<u8>) -> Result<ReadyHandle> {+ self.0.lock().unwrap().push(message);+ Ok(ReadyHandle::immediate())+ }+ async fn mark_ready(&self) {}+ }+ let collect = Collect(Mutex::new(Vec::new()));+ let adapter = PayloadsAdapter(&collect);+ let h = adapter.send(message(Some(b"k"), None)).await.unwrap();+ assert!(h.is_immediate());+ let h = adapter.send(message(Some(b"k"), Some(b"v"))).await.unwrap();+ assert!(h.is_immediate());+ assert_eq!(collect.0.lock().unwrap().clone(), vec![b"v".to_vec()]);+ }}diff --git a/rust/sdk/cocoindex/src/connectors/mod.rs b/rust/sdk/cocoindex/src/connectors/mod.rsindex 254c358d..ac1b2af1 100644--- a/rust/sdk/cocoindex/src/connectors/mod.rs+++ b/rust/sdk/cocoindex/src/connectors/mod.rs@@ -22,6 +22,8 @@ pub mod lancedb;pub mod neo4j;#[cfg(feature = "oci_object_storage")]pub mod oci_object_storage;+#[cfg(any(feature = "kafka", feature = "iggy"))]+mod partition_tail;#[cfg(feature = "postgres")]pub mod postgres;#[cfg(feature = "qdrant")]diff --git a/rust/sdk/cocoindex/src/connectors/partition_tail.rs b/rust/sdk/cocoindex/src/connectors/partition_tail.rsnew file mode 100644index 00000000..e15109c4--- /dev/null+++ b/rust/sdk/cocoindex/src/connectors/partition_tail.rs@@ -0,0 +1,349 @@+//! The tail loop the partitioned stream sources (Kafka, Iggy) share: every+//! partition of a [`LiveStream`](crate::live_component::LiveStream) is polled+//! at the same time, each polled batch is delivered in order and acknowledged+//! once processed, and readiness is signalled once every partition has caught+//! up to the end it had when the watch started.++use std::sync::Mutex;++use crate::error::Result;+use crate::live_component::LiveStreamSubscriber;++/// What one partition tail reads and commits. Abstracted from the broker so+/// the loop can be tested without one.+#[crate::async_trait]+pub(crate) trait PartitionSource<M>: Send + Sync {+ /// The records from `offset` on, each with its offset, in order; empty when+ /// none arrived within the broker's wait.+ async fn fetch(&self, offset: i64) -> Result<Vec<(i64, M)>>;++ /// Record that every record before `next` has been processed, where the+ /// source keeps its position (a consumer group's cursor).+ async fn commit(&self, next: i64) -> Result<()>;+}++/// A partition a watch tails: where to start, and the end it had when the+/// watch started (the offset the next record gets).+pub(crate) struct PartitionTail<S> {+ pub(crate) source: S,+ pub(crate) start: i64,+ pub(crate) high_watermark: i64,+}++/// Readiness across the partitions of one watch: each partition's committed+/// next offset against its initial high watermark.+struct Readiness {+ /// `(committed, high_watermark)` per partition.+ partitions: Mutex<Vec<(i64, i64)>>,+ signaled: std::sync::atomic::AtomicBool,+}++impl Readiness {+ fn new<S>(tails: &[PartitionTail<S>]) -> Self {+ Self {+ partitions: Mutex::new(tails.iter().map(|t| (t.start, t.high_watermark)).collect()),+ signaled: std::sync::atomic::AtomicBool::new(false),+ }+ }++ /// Record a partition's commit; `true` the one time every partition has+ /// caught up, so the caller signals readiness.+ fn committed(&self, index: usize, next: i64) -> bool {+ let mut partitions = self.partitions.lock().unwrap_or_else(|e| e.into_inner());+ partitions[index].0 = next;+ let caught_up = partitions.iter().all(|(committed, hwm)| committed >= hwm);+ caught_up+ && !self+ .signaled+ .swap(true, std::sync::atomic::Ordering::AcqRel)+ }+}++/// Tail every partition at the same time: each partition's fetches and+/// deliveries overlap the others'. Per partition, a fetched batch is delivered+/// in order, the batch's handles are awaited together, and the partition's next+/// offset is then committed and counted toward readiness; so at most one batch+/// per partition is in flight, and a committed offset never precedes an+/// unprocessed record. Returns only on an error.+pub(crate) async fn watch_partitions<M, S>(+ tails: Vec<PartitionTail<S>>,+ subscriber: &dyn LiveStreamSubscriber<M>,+) -> Result<()>+where+ M: Send + 'static,+ S: PartitionSource<M>,+{+ let readiness = Readiness::new(&tails);+ // An empty topic, or a cursor already at the end, is ready at once.+ if tails.iter().all(|t| t.start >= t.high_watermark)+ && !readiness+ .signaled+ .swap(true, std::sync::atomic::Ordering::AcqRel)+ {+ subscriber.mark_ready().await;+ }+ let readiness = &readiness;+ futures::future::try_join_all(+ tails+ .iter()+ .enumerate()+ .map(|(index, tail)| tail_partition(index, tail, subscriber, readiness)),+ )+ .await?;+ Ok(())+}++/// One partition's tail loop (see [`watch_partitions`]); ends only on an error.+async fn tail_partition<M, S>(+ index: usize,+ tail: &PartitionTail<S>,+ subscriber: &dyn LiveStreamSubscriber<M>,+ readiness: &Readiness,+) -> Result<()>+where+ M: Send + 'static,+ S: PartitionSource<M>,+{+ let mut offset = tail.start;+ loop {+ let messages = tail.source.fetch(offset).await?;+ if messages.is_empty() {+ continue;+ }+ let mut handles = Vec::new();+ for (message_offset, message) in messages {+ offset = message_offset + 1;+ let handle = subscriber.send(message).await?;+ if !handle.is_immediate() {+ handles.push(handle.ready());+ }+ }+ futures::future::try_join_all(handles).await?;+ tail.source.commit(offset).await?;+ if readiness.committed(index, offset) {+ subscriber.mark_ready().await;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::live_component::ReadyHandle;+ use std::collections::BTreeSet;+ use std::sync::Arc;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;++ /// A fake partition: a fixed log served one record per fetch, counting+ /// how many fetches are in flight at once across the fakes sharing the+ /// counter, and recording what it committed and what had been processed by+ /// then.+ struct FakePartition {+ name: &'static str,+ log: Vec<&'static str>,+ in_flight: Arc<AtomicUsize>,+ max_in_flight: Arc<AtomicUsize>,+ processed: Arc<Mutex<BTreeSet<(&'static str, i64)>>>,+ /// `(next, the records of this partition processed by then)`.+ commits: Mutex<Vec<(i64, Vec<i64>)>>,+ }++ #[crate::async_trait]+ impl PartitionSource<(&'static str, i64)> for FakePartition {+ async fn fetch(&self, offset: i64) -> Result<Vec<(i64, (&'static str, i64))>> {+ let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ self.max_in_flight.fetch_max(now, Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(20)).await;+ self.in_flight.fetch_sub(1, Ordering::SeqCst);+ Ok(if (offset as usize) < self.log.len() {+ vec![(offset, (self.name, offset))]+ } else {+ Vec::new()+ })+ }++ async fn commit(&self, next: i64) -> Result<()> {+ let processed = self+ .processed+ .lock()+ .unwrap()+ .iter()+ .filter(|(name, _)| *name == self.name)+ .map(|(_, offset)| *offset)+ .collect();+ self.commits.lock().unwrap().push((next, processed));+ Ok(())+ }+ }++ /// Records what a watch delivered and signalled; every message is+ /// processed by a task that finishes a little later, so a commit that did+ /// not wait for processing would see it missing.+ struct Recorder {+ delivered: Mutex<Vec<(&'static str, i64)>>,+ processed: Arc<Mutex<BTreeSet<(&'static str, i64)>>>,+ ready: AtomicUsize,+ }++ #[crate::async_trait]+ impl LiveStreamSubscriber<(&'static str, i64)> for Recorder {+ async fn send(&self, message: (&'static str, i64)) -> Result<ReadyHandle> {+ self.delivered.lock().unwrap().push(message);+ let processed = self.processed.clone();+ Ok(ReadyHandle::from_future(async move {+ tokio::time::sleep(Duration::from_millis(10)).await;+ processed.lock().unwrap().insert(message);+ Ok(())+ }))+ }++ async fn mark_ready(&self) {+ self.ready.fetch_add(1, Ordering::SeqCst);+ }+ }++ struct Fakes {+ tails: Vec<PartitionTail<Arc<FakePartition>>>,+ max_in_flight: Arc<AtomicUsize>,+ recorder: Recorder,+ }++ fn fakes(logs: Vec<(&'static str, Vec<&'static str>)>) -> Fakes {+ let in_flight = Arc::new(AtomicUsize::new(0));+ let max_in_flight = Arc::new(AtomicUsize::new(0));+ let processed = Arc::new(Mutex::new(BTreeSet::new()));+ let tails = logs+ .into_iter()+ .map(|(name, log)| PartitionTail {+ start: 0,+ high_watermark: log.len() as i64,+ source: Arc::new(FakePartition {+ name,+ log,+ in_flight: in_flight.clone(),+ max_in_flight: max_in_flight.clone(),+ processed: processed.clone(),+ commits: Mutex::new(Vec::new()),+ }),+ })+ .collect();+ Fakes {+ tails,+ max_in_flight,+ recorder: Recorder {+ delivered: Mutex::new(Vec::new()),+ processed,+ ready: AtomicUsize::new(0),+ },+ }+ }++ #[crate::async_trait]+ impl<M: Send + 'static, S: PartitionSource<M>> PartitionSource<M> for Arc<S> {+ async fn fetch(&self, offset: i64) -> Result<Vec<(i64, M)>> {+ S::fetch(self, offset).await+ }+ async fn commit(&self, next: i64) -> Result<()> {+ S::commit(self, next).await+ }+ }++ /// Run `watch` until `done` holds, within five seconds.+ async fn watch_until(+ tails: Vec<PartitionTail<Arc<FakePartition>>>,+ recorder: &Recorder,+ done: impl Fn() -> bool,+ ) {+ let outcome = tokio::time::timeout(Duration::from_secs(5), async {+ tokio::select! {+ r = watch_partitions(tails, recorder) => r,+ _ = async {+ while !done() {+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ } => Ok(()),+ }+ })+ .await;+ assert!(outcome.is_ok(), "the watch did not finish in time");+ outcome.unwrap().unwrap();+ }++ // Partitions are polled at the same time (two fetches in flight at once),+ // every record is delivered in partition order, a partition's offset is+ // committed only after its records are processed, and readiness is+ // signalled exactly once, when every partition reached its initial end.+ #[tokio::test]+ async fn partitions_are_polled_concurrently_and_committed_after_processing() {+ let Fakes {+ tails,+ max_in_flight,+ recorder,+ } = fakes(vec![+ ("a", vec!["x", "y", "z"]),+ ("b", vec!["x", "y"]),+ ("c", vec![]),+ ]);+ let sources: Vec<Arc<FakePartition>> = tails.iter().map(|t| t.source.clone()).collect();+ watch_until(tails, &recorder, || {+ recorder.processed.lock().unwrap().len() == 5+ && recorder.ready.load(Ordering::SeqCst) > 0+ })+ .await;++ assert!(+ max_in_flight.load(Ordering::SeqCst) >= 2,+ "partitions were polled one after another"+ );+ let delivered = recorder.delivered.lock().unwrap().clone();+ let per_partition = |name: &str| -> Vec<i64> {+ delivered+ .iter()+ .filter(|(n, _)| *n == name)+ .map(|(_, o)| *o)+ .collect()+ };+ assert_eq!(per_partition("a"), vec![0, 1, 2]);+ assert_eq!(per_partition("b"), vec![0, 1]);+ for source in &sources {+ let commits = source.commits.lock().unwrap().clone();+ for (next, processed_by_then) in &commits {+ assert_eq!(+ processed_by_then,+ &(0..*next).collect::<Vec<i64>>(),+ "partition {} committed {next} before processing its records",+ source.name+ );+ }+ assert_eq!(+ commits.last().map(|(next, _)| *next),+ if source.log.is_empty() {+ None+ } else {+ Some(source.log.len() as i64)+ }+ );+ }+ assert_eq!(recorder.ready.load(Ordering::SeqCst), 1);+ }++ // A watch that starts at the end of every partition is ready at once,+ // before any record arrives.+ #[tokio::test]+ async fn a_watch_at_the_end_is_ready_at_once() {+ let Fakes {+ mut tails,+ recorder,+ ..+ } = fakes(vec![("a", vec!["x"])]);+ tails[0].start = 1;+ let source = tails[0].source.clone();+ watch_until(tails, &recorder, || {+ recorder.ready.load(Ordering::SeqCst) > 0+ })+ .await;+ assert_eq!(recorder.ready.load(Ordering::SeqCst), 1);+ assert!(source.commits.lock().unwrap().is_empty());+ }+}diff --git a/rust/sdk/cocoindex/src/lib.rs b/rust/sdk/cocoindex/src/lib.rsindex bdc1caff..2f3ac27c 100644--- a/rust/sdk/cocoindex/src/lib.rs+++ b/rust/sdk/cocoindex/src/lib.rs@@ -90,7 +90,8 @@ pub use runner::{pub use linkme;pub use live_component::{ExceptionContext, ExceptionHandler, ExceptionSource, LiveComponent, LiveComponentOperator,- LiveMapFeed, LiveMapSubscriber, LiveMapView, MountKind, SingleWatcherGuard, SingleWatcherToken,+ LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream, LiveStreamSubscriber, MountKind,+ ReadyHandle, SingleWatcherGuard, SingleWatcherToken,};#[doc(hidden)]pub use logic::{COCO_FN_LOGIC, FnDeps, FnLogicEntry};diff --git a/rust/sdk/cocoindex/src/live_component.rs b/rust/sdk/cocoindex/src/live_component.rsindex 3144f7c3..7add4649 100644--- a/rust/sdk/cocoindex/src/live_component.rs+++ b/rust/sdk/cocoindex/src/live_component.rs@@ -12,7 +12,7 @@//!//! Mirrors the Python `_internal/live_component.py` surface//! (`LiveComponent` / `LiveComponentOperator` / `LiveMapFeed` / `LiveMapView` /-//! `LiveMapSubscriber`) and the `exception_handler` / `ExceptionContext`+//! `LiveMapSubscriber` / `LiveStream` / `LiveStreamSubscriber`) and the `exception_handler` / `ExceptionContext`//! error-routing model from `_internal/component_ctx.py`, adapted to Rust://!//! - A `LiveComponent` is a trait with `process` (one full pass) and@@ -276,11 +276,12 @@ impl LiveComponentOperator {.map_err(engine_err)}- /// Incrementally mount (or replace) a single child under `key`, running- /// `f` to declare its state. Same-key rapid calls coalesce. Awaits until the- /// child's state has synced. A failure in `f` follows the same routing as- /// [`Self::update_full`]: logged, not returned, unless a handler propagates it.- pub async fn update<K, F, Fut>(&self, key: K, f: F) -> Result<()>+ /// [`update`](Self::update) without waiting: the child mount is queued and+ /// the returned handle's [`ready`](ReadyHandle::ready) awaits its sync, so a+ /// stream source can keep polling while earlier messages are processed and+ /// acknowledge each once its handle is ready (the Python+ /// `LiveMapSubscriber.update` returns such a handle).+ pub async fn start_update<K, F, Fut>(&self, key: K, f: F) -> Result<ReadyHandle>whereK: Display,F: FnOnce(Ctx) -> Fut + Send + 'static,@@ -314,13 +315,27 @@ impl LiveComponentOperator {.update(child_path, processor, on_error).await.map_err(engine_err)?;- handle.ready().await.map_err(engine_err)+ Ok(ReadyHandle::from_future(async move {+ handle.ready().await.map_err(engine_err)+ }))}- /// Incrementally remove the child mounted under `key`, cleaning up its- /// target states. Awaits until the deletion has synced. Failures follow the- /// same routing as [`Self::update_full`].- pub async fn delete<K: Display>(&self, key: K) -> Result<()> {+ /// Incrementally mount (or replace) a single child under `key`, running+ /// `f` to declare its state. Same-key rapid calls coalesce. Awaits until the+ /// child's state has synced. A failure in `f` follows the same routing as+ /// [`Self::update_full`]: logged, not returned, unless a handler propagates it.+ pub async fn update<K, F, Fut>(&self, key: K, f: F) -> Result<()>+ where+ K: Display,+ F: FnOnce(Ctx) -> Fut + Send + 'static,+ Fut: Future<Output = Result<()>> + Send + 'static,+ {+ self.start_update(key, f).await?.ready().await+ }++ /// [`delete`](Self::delete) without waiting: the deletion is queued and the+ /// returned handle's [`ready`](ReadyHandle::ready) awaits its sync.+ pub async fn start_delete<K: Display>(&self, key: K) -> Result<ReadyHandle> {let child_path = self.child_path(&key);let on_error = build_chained_on_error(&self.handler_chain,@@ -331,7 +346,16 @@ impl LiveComponentOperator {.delete(child_path, on_error).await.map_err(engine_err)?;- handle.ready().await.map_err(engine_err)+ Ok(ReadyHandle::from_future(async move {+ handle.ready().await.map_err(engine_err)+ }))+ }++ /// Incrementally remove the child mounted under `key`, cleaning up its+ /// target states. Awaits until the deletion has synced. Failures follow the+ /// same routing as [`Self::update_full`].+ pub async fn delete<K: Display>(&self, key: K) -> Result<()> {+ self.start_delete(key).await?.ready().await}/// Signal that the initial catch-up is complete. Idempotent. In catch-up@@ -422,6 +446,102 @@ pub(crate) fn start_process_live(controller.start(async move { instance.process_live(operator).await.map_err(to_core_error) });}+// ---------------------------------------------------------------------------+// Live streams: a keyless message stream with acknowledgement+// ---------------------------------------------------------------------------++/// Awaits the processing of one message a [`LiveStreamSubscriber`] accepted.+/// The Rust form of the Python `ReadyAwaitable`.+///+/// [`immediate`](Self::immediate) means "no work was needed; acknowledge the+/// message now", as returning `_IMMEDIATE_READY` does in Python; a stream may+/// check [`is_immediate`](Self::is_immediate) to skip tracking such a message.+#[must_use = "a message is acknowledged once its handle is ready; drop it and the stream never learns"]+pub struct ReadyHandle(Option<Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>>);++impl ReadyHandle {+ /// A handle that is ready at once: the message needs no further work.+ pub const fn immediate() -> Self {+ Self(None)+ }++ /// A handle that is ready once `future` completes (a child mount's sync).+ pub fn from_future(future: impl Future<Output = Result<()>> + Send + 'static) -> Self {+ Self(Some(Box::pin(future)))+ }++ /// Whether this handle was made with [`immediate`](Self::immediate).+ pub fn is_immediate(&self) -> bool {+ self.0.is_none()+ }++ /// Await the message's processing; its error, if the work failed.+ pub async fn ready(self) -> Result<()> {+ match self.0 {+ Some(future) => future.await,+ None => Ok(()),+ }+ }+}++impl std::fmt::Debug for ReadyHandle {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("ReadyHandle")+ .field("immediate", &self.is_immediate())+ .finish()+ }+}++/// Receives the messages of a [`LiveStream`]. The Rust form of the Python+/// `LiveStreamSubscriber` protocol.+#[async_trait]+pub trait LiveStreamSubscriber<M>: Send + Sync {+ /// Accept a message; the returned handle is ready once the message has been+ /// processed, and the stream acknowledges the message to its source then.+ /// Return [`ReadyHandle::immediate`] for a message that needs no work.+ async fn send(&self, message: M) -> Result<ReadyHandle>;++ /// The stream has caught up to the position it had when `watch` started.+ /// Must return promptly: the stream awaits it inline in its poll loop.+ async fn mark_ready(&self);++ /// A value the stream committed under `key` on an earlier run (see+ /// [`write_committed_state`](Self::write_committed_state)), or `None`.+ /// The default has no store and returns `None`.+ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ let _ = key;+ Ok(None)+ }++ /// Commit `value` under `key` for a later run of the stream to read back:+ /// where a stream keeps its own durable cursor (the Rust Kafka source,+ /// whose client has no broker-side consumer group), as+ /// [`LiveComponentOperator::write_committed_state`] does for a live+ /// component. A subscriber backed by a live component forwards it there;+ /// the default has no store and drops the value, so the stream starts over+ /// on the next run.+ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ let _ = (key, value);+ Ok(())+ }+}++/// A keyless stream of messages with in-memory processing-watermark tracking:+/// the stream delivers every message to its subscriber, acknowledges a message+/// to its source once the subscriber's handle for it (and the handles of the+/// messages before it) are ready, and signals readiness once it has caught up+/// to the position it had when the watch started. The Rust form of the Python+/// `LiveStream` protocol (a Kafka or Iggy topic; the event feed of a live+/// object-store view).+///+/// Single-subscriber: one active `watch` at a time (implementations enforce+/// this with [`SingleWatcherGuard`]).+#[async_trait]+pub trait LiveStream<M: Send + 'static>: Send + Sync + 'static {+ /// Deliver messages to `subscriber` until cancelled.+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<M>) -> Result<()>;+}+// ---------------------------------------------------------------------------// Live maps: feed / view / subscriber// ---------------------------------------------------------------------------@@ -443,15 +563,28 @@ pub struct LiveMapSubscriber<K, V> {impl<K: Display, V: Send + 'static> LiveMapSubscriber<K, V> {/// Incrementally upsert one entry.pub async fn update(&self, key: K, value: V) -> Result<()> {+ self.start_update(key, value).await?.ready().await+ }++ /// [`update`](Self::update) without waiting; the handle's+ /// [`ready`](ReadyHandle::ready) awaits the entry's sync. See+ /// [`LiveComponentOperator::start_update`].+ pub async fn start_update(&self, key: K, value: V) -> Result<ReadyHandle> {let process_fn = self.process_fn.clone();self.operator- .update(key, move |ctx| process_fn(ctx, value))+ .start_update(key, move |ctx| process_fn(ctx, value)).await}/// Incrementally remove one entry.pub async fn delete(&self, key: K) -> Result<()> {- self.operator.delete(key).await+ self.start_delete(key).await?.ready().await+ }++ /// [`delete`](Self::delete) without waiting; the handle's+ /// [`ready`](ReadyHandle::ready) awaits the removal's sync.+ pub async fn start_delete(&self, key: K) -> Result<ReadyHandle> {+ self.operator.start_delete(key).await}/// Re-scan all entries (a full pass). Use after a change that can't bediff --git a/rust/sdk/cocoindex/src/prelude.rs b/rust/sdk/cocoindex/src/prelude.rsindex e45d2308..7ce03c3d 100644--- a/rust/sdk/cocoindex/src/prelude.rs+++ b/rust/sdk/cocoindex/src/prelude.rs@@ -10,7 +10,8 @@ pub use crate::entity_resolution::{pub use crate::error::{Error, Result};pub use crate::live_component::{ExceptionContext, ExceptionHandler, ExceptionSource, LiveComponent, LiveComponentOperator,- LiveMapFeed, LiveMapSubscriber, LiveMapView, MountKind, SingleWatcherGuard, SingleWatcherToken,+ LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream, LiveStreamSubscriber, MountKind,+ ReadyHandle, SingleWatcherGuard, SingleWatcherToken,};pub use crate::resources::chunk::{Chunk, TextPosition};pub use crate::resources::embedder::Embedder;diff --git a/rust/sdk/cocoindex/tests/iggy_source.rs b/rust/sdk/cocoindex/tests/iggy_source.rsindex cdac78a0..02c52903 100644--- a/rust/sdk/cocoindex/tests/iggy_source.rs+++ b/rust/sdk/cocoindex/tests/iggy_source.rs@@ -15,7 +15,7 @@use std::sync::{Arc, Mutex};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};-use cocoindex::connectors::iggy::{self, IggyConsumer, IggyProducer};+use cocoindex::connectors::iggy::{self, IggyConsumer, IggyProducer, IggyReceivedMessage};use cocoindex::{App, Environment, Result, UpdateOptions};use iggy::prelude::{CompressionAlgorithm, Identifier, IggyExpiry, MaxTopicSize, StreamClient, TopicClient,@@ -91,7 +91,8 @@ async fn declare(partition: PARTITION,..Default::default()},- )?;+ )+ .await?;for (k, payload) in &messages {target.declare_message(&ctx, k, payload)?;}@@ -104,9 +105,11 @@ async fn declare(/// `key_fn` recovering the key from a `"<key>=<value>"` payload.fn key_fn() -> iggy::IggyKeyFn {- Arc::new(|payload: &[u8]| {- let s = String::from_utf8_lossy(payload);- s.split_once('=').map(|(k, _)| k.to_string())+ Arc::new(|message: &IggyReceivedMessage| {+ message+ .payload_str()+ .split_once('=')+ .map(|(k, _)| k.to_string())})}@@ -163,16 +166,17 @@ async fn iggy_source_catch_up_scan_compacts_log() -> Result<()> {let stream = stream.clone();async move {let feed = iggy::topic_as_map(&consumer, GROUP, stream, topic, key_fn());- ctx.mount_each_live(&"messages", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"messages",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -234,16 +238,17 @@ async fn iggy_source_live_watch_tails_new_messages() -> Result<()> {let stream = stream.clone();async move {let feed = iggy::topic_as_map(&consumer, GROUP, stream, topic, key_fn());- ctx.mount_each_live(&"messages", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"messages",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -326,16 +331,17 @@ async fn iggy_source_stream_reads_all_payloads_keyless() -> Result<()> {let stream = stream.clone();async move {let feed = iggy::topic_as_stream(&consumer, GROUP, stream, topic);- ctx.mount_each_live(&"stream", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"stream",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -429,7 +435,8 @@ async fn iggy_source_stream_reads_all_partitions() -> Result<()> {partition: pid,..Default::default()},- )?;+ )+ .await?;target.declare_message(&ctx, &format!("k{i}"), &value)?;Ok(())}@@ -454,16 +461,17 @@ async fn iggy_source_stream_reads_all_partitions() -> Result<()> {let stream = stream.clone();async move {let feed = iggy::topic_as_stream(&consumer, GROUP, stream, topic);- ctx.mount_each_live(&"stream", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"stream",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -547,16 +555,17 @@ async fn iggy_source_consumer_group_resumes_from_stored_offset() -> Result<()> {is_deletion: None,},);- ctx.mount_each_live(&"messages", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"messages",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -636,8 +645,12 @@ async fn iggy_source_init_retries_wait_for_a_late_topic() -> Result<()> {let stream = stream.clone();async move {let feed = iggy::topic_as_stream(&consumer, GROUP, stream, topic);- ctx.mount_each_live(&"stream", feed, |_ctx, _value: Vec<u8>| async { Ok(()) })- .await+ ctx.mount_each_live(+ &"stream",+ feed,+ |_ctx, _message: IggyReceivedMessage| async { Ok(()) },+ )+ .await}}})@@ -681,16 +694,17 @@ async fn iggy_source_init_retries_wait_for_a_late_topic() -> Result<()> {..Default::default()},);- ctx.mount_each_live(&"stream", feed, move |_ctx, value: Vec<u8>| {- let processed = processed.clone();- async move {- processed- .lock()- .unwrap()- .push(String::from_utf8_lossy(&value).into_owned());- Ok(())- }- })+ ctx.mount_each_live(+ &"stream",+ feed,+ move |_ctx, message: IggyReceivedMessage| {+ let processed = processed.clone();+ async move {+ processed.lock().unwrap().push(message.payload_str());+ Ok(())+ }+ },+ ).await}}@@ -700,3 +714,77 @@ async fn iggy_source_init_retries_wait_for_a_late_topic() -> Result<()> {assert_eq!(processed.lock().unwrap().clone(), vec!["k1=v1".to_string()]);Ok(())}++/// Records what a `LiveStream<Vec<u8>>` delivered and when it became ready.+#[derive(Default)]+struct PayloadRecorder {+ payloads: Mutex<Vec<Vec<u8>>>,+ ready: std::sync::atomic::AtomicBool,+}++#[cocoindex::async_trait]+impl cocoindex::LiveStreamSubscriber<Vec<u8>> for PayloadRecorder {+ async fn send(&self, message: Vec<u8>) -> Result<cocoindex::ReadyHandle> {+ self.payloads.lock().unwrap().push(message);+ Ok(cocoindex::ReadyHandle::immediate())+ }++ async fn mark_ready(&self) {+ self.ready.store(true, std::sync::atomic::Ordering::SeqCst);+ }+}++/// `topic_as_stream(..).payloads()` watched directly as a `LiveStream`: every+/// payload is delivered and readiness is signalled once the messages that+/// existed when the watch started are processed.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn iggy_stream_payloads_watch_delivers_values_and_marks_ready() -> Result<()> {+ let Ok(conn) = std::env::var("IGGY_CONNECTION_STRING") else {+ eprintln!("skipping live Iggy payload stream test; IGGY_CONNECTION_STRING is not set");+ return Ok(());+ };+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let stream = format!("coco_src_payloads_{nonce}");+ let topic = "rows";+ let producer = IggyProducer::connect(&conn).await?;+ ensure_stream_topic(&producer, &stream, topic).await;+ let tmp = tempfile::tempdir().unwrap();+ declare(+ &producer,+ &tmp.path().join("populate_db"),+ &stream,+ topic,+ vec![("k1", "v1"), ("k2", "v2")],+ )+ .await;++ let consumer = IggyConsumer::connect(&conn).await?;+ let payloads = iggy::topic_as_stream(&consumer, GROUP, stream, topic).payloads();+ let recorder = PayloadRecorder::default();+ let outcome = tokio::time::timeout(Duration::from_secs(20), async {+ tokio::select! {+ r = cocoindex::LiveStream::watch(&payloads, &recorder) => r,+ _ = async {+ while !recorder.ready.load(std::sync::atomic::Ordering::SeqCst) {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ } => Ok(()),+ }+ })+ .await;+ assert!(outcome.is_ok(), "the stream did not become ready in time");+ outcome.unwrap()?;+ let mut got: Vec<String> = recorder+ .payloads+ .lock()+ .unwrap()+ .iter()+ .map(|p| String::from_utf8_lossy(p).into_owned())+ .collect();+ got.sort();+ assert_eq!(got, vec!["k1=v1".to_string(), "k2=v2".to_string()]);+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/iggy_target.rs b/rust/sdk/cocoindex/tests/iggy_target.rsindex db56e708..70c36001 100644--- a/rust/sdk/cocoindex/tests/iggy_target.rs+++ b/rust/sdk/cocoindex/tests/iggy_target.rs@@ -129,7 +129,8 @@ async fn iggy_target_sends_skips_and_updates_when_available() -> Result<()> {..Default::default()};let target =- iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)?;+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)+ .await?;for (k, v) in &messages {target.declare_message(&ctx, k, v)?;}@@ -199,12 +200,13 @@ async fn iggy_target_custom_delete_value_when_available() -> Result<()> {async move {let options = iggy::IggyTopicOptions {partition: PARTITION,- deletion_value_fn: Some(Arc::new(|key: &str| {- format!("{key}=<deleted>").into_bytes()+ deletion_value_fn: Some(Arc::new(|key: &[u8]| {+ format!("{}=<deleted>", String::from_utf8_lossy(key)).into_bytes()})),};let target =- iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)?;+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, stream, topic, options)+ .await?;for (k, v) in &messages {target.declare_message(&ctx, k, v)?;}diff --git a/rust/sdk/cocoindex/tests/kafka_source.rs b/rust/sdk/cocoindex/tests/kafka_source.rsindex 1c8a9851..eb1f6569 100644--- a/rust/sdk/cocoindex/tests/kafka_source.rs+++ b/rust/sdk/cocoindex/tests/kafka_source.rs@@ -71,7 +71,8 @@ async fn declare(&PRODUCER,topic,kafka::KafkaTopicOptions::default(),- )?;+ )+ .await?;for (k, v) in &messages {target.declare_message(&ctx, k, v)?;}@@ -510,3 +511,66 @@ async fn kafka_source_consumer_group_resumes_from_committed_offsets() -> Result<);Ok(())}++/// Records what a `LiveStream<Vec<u8>>` delivered and when it became ready.+#[derive(Default)]+struct PayloadRecorder {+ payloads: Mutex<Vec<Vec<u8>>>,+ ready: std::sync::atomic::AtomicBool,+}++#[cocoindex::async_trait]+impl cocoindex::LiveStreamSubscriber<Vec<u8>> for PayloadRecorder {+ async fn send(&self, message: Vec<u8>) -> Result<cocoindex::ReadyHandle> {+ self.payloads.lock().unwrap().push(message);+ Ok(cocoindex::ReadyHandle::immediate())+ }++ async fn mark_ready(&self) {+ self.ready.store(true, std::sync::atomic::Ordering::SeqCst);+ }+}++/// `topic_as_stream(..).payloads()` watched directly as a `LiveStream`, with a+/// consumer wrapped around a caller-built client: every value is delivered+/// (the tombstone is not), and readiness is signalled once the records that+/// existed when the watch started are processed.+#[tokio::test]+async fn kafka_stream_payloads_watch_delivers_values_and_marks_ready() -> Result<()> {+ let Some(brokers) = brokers() else {+ eprintln!("skipping live Kafka payload stream test; KAFKA_BOOTSTRAP_SERVERS is not set");+ return Ok(());+ };+ let broker_refs: Vec<&str> = brokers.iter().map(String::as_str).collect();+ let topic = unique_topic("payloads");+ let producer = kafka::KafkaProducer::connect(&broker_refs).await?;+ producer.ensure_topic(&topic, 2).await?;+ produce_raw(&brokers, &topic, 0, Some("k"), Some("a"), BTreeMap::new()).await?;+ produce_raw(&brokers, &topic, 1, Some("k"), None, BTreeMap::new()).await?;+ produce_raw(&brokers, &topic, 1, None, Some("b"), BTreeMap::new()).await?;++ let client = ClientBuilder::new(brokers.clone())+ .build()+ .await+ .map_err(|e| cocoindex::Error::engine(format!("client: {e}")))?;+ let consumer = kafka::KafkaConsumer::from_client(client, brokers.join(","), None)?;+ let stream = kafka::topic_as_stream(&consumer, [topic.clone()]).payloads();+ let recorder = PayloadRecorder::default();+ let outcome = tokio::time::timeout(Duration::from_secs(20), async {+ tokio::select! {+ r = cocoindex::LiveStream::watch(&stream, &recorder) => r,+ _ = async {+ while !recorder.ready.load(std::sync::atomic::Ordering::SeqCst) {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ } => Ok(()),+ }+ })+ .await;+ assert!(outcome.is_ok(), "the stream did not become ready in time");+ outcome.unwrap()?;+ let mut got = recorder.payloads.lock().unwrap().clone();+ got.sort();+ assert_eq!(got, vec![b"a".to_vec(), b"b".to_vec()]);+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/kafka_target.rs b/rust/sdk/cocoindex/tests/kafka_target.rsindex 494f6f80..6756dae3 100644--- a/rust/sdk/cocoindex/tests/kafka_target.rs+++ b/rust/sdk/cocoindex/tests/kafka_target.rs@@ -123,7 +123,8 @@ async fn kafka_target_produces_skips_updates_and_tombstones_when_available() ->&PRODUCER,topic,kafka::KafkaTopicOptions::default(),- )?;+ )+ .await?;for (k, v) in &messages {target.declare_message(&ctx, k, v)?;}@@ -203,11 +204,12 @@ async fn kafka_target_custom_delete_value_when_available() -> Result<()> {let messages = messages.clone();async move {let options = kafka::KafkaTopicOptions {- deletion_value_fn: Some(Arc::new(|key: &str| {- format!("deleted:{key}").into_bytes()+ deletion_value_fn: Some(Arc::new(|key: &[u8]| {+ format!("deleted:{}", String::from_utf8_lossy(key)).into_bytes()})),};- let target = kafka::mount_kafka_topic_target(&ctx, &PRODUCER, topic, options)?;+ let target =+ kafka::mount_kafka_topic_target(&ctx, &PRODUCER, topic, options).await?;for (k, v) in &messages {target.declare_message(&ctx, k, v)?;}@@ -233,3 +235,59 @@ async fn kafka_target_custom_delete_value_when_available() -> Result<()> {Ok(())}++/// The topic target as a composable `TargetState` (`kafka_topic_target` ++/// `mount_target`), with a binary message key.+#[tokio::test]+async fn kafka_topic_target_state_and_bytes_keys_when_available() -> Result<()> {+ let Ok(brokers) = std::env::var("KAFKA_BOOTSTRAP_SERVERS") else {+ eprintln!("skipping live Kafka target-state test; KAFKA_BOOTSTRAP_SERVERS is not set");+ return Ok(());+ };+ let broker_refs: Vec<&str> = brokers.split(',').collect();+ let producer = kafka::KafkaProducer::connect(&broker_refs).await?;+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let topic = format!("cocoindex_kafka_target_state_{nonce}");+ producer.ensure_topic(&topic, 1).await?;+ let consumer = ClientBuilder::new(broker_refs.iter().map(|s| s.to_string()).collect())+ .build()+ .await+ .map_err(|e| cocoindex::Error::engine(format!("consumer connect: {e}")))?;+ let tempdir = tempfile::tempdir().unwrap();+ let app = app("KafkaTargetState", &tempdir.path().join("db"), &producer).await;+ app.run({+ let topic = topic.clone();+ move |ctx| {+ let topic = topic.clone();+ async move {+ let ts = kafka::kafka_topic_target(+ &ctx,+ &PRODUCER,+ topic,+ kafka::KafkaTopicOptions::default(),+ )?;+ let messages: cocoindex::TargetStateProvider<Vec<u8>> =+ cocoindex::mount_target(&ctx, ts).await?;+ cocoindex::declare_target_state(+ &ctx,+ messages.target_state(+ cocoindex::StableKey::Bytes(std::sync::Arc::from(&b"\x00\x01"[..])),+ b"binary".to_vec(),+ ),+ )?;+ Ok(())+ }+ }+ })+ .await+ .unwrap();+ let (records, hw) = consume_all(&consumer, &topic).await;+ assert_eq!(hw, 1);+ // `consume_all` decodes the key lossily; the two bytes survive as they are.+ assert_eq!(records[0].0, "\u{0}\u{1}");+ assert_eq!(records[0].1.as_deref(), Some("binary"));+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/live_stream.rs b/rust/sdk/cocoindex/tests/live_stream.rsnew file mode 100644index 00000000..96ff1765--- /dev/null+++ b/rust/sdk/cocoindex/tests/live_stream.rs@@ -0,0 +1,168 @@+//! Hermetic test of the `LiveStream` plumbing through the engine: an in-memory+//! stream drives a live map through a `LiveStreamSubscriber`, each message is+//! mounted with `start_update` and acknowledged (its handle awaited) once its+//! child has synced, and readiness reaches the live component. No broker.++use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use cocoindex::live_component::{+ LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream, LiveStreamSubscriber, ReadyHandle,+ SingleWatcherGuard,+};+use cocoindex::{App, Result, UpdateOptions, async_trait};++/// What the test observed, in order: deliveries, acknowledgements, readiness.+type Log = Arc<Mutex<Vec<String>>>;++/// A finite in-memory `LiveStream<String>`: delivers its messages, awaits each+/// handle on a task of its own (so a slow child does not block the next+/// delivery) and logs the acknowledgement, then marks the subscriber ready and+/// waits until cancelled.+struct VecStream {+ messages: Vec<String>,+ log: Log,+ guard: SingleWatcherGuard,+}++#[async_trait]+impl LiveStream<String> for VecStream {+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<String>) -> Result<()> {+ let _token = self.guard.enter()?;+ let mut handles = Vec::new();+ for message in &self.messages {+ self.log.lock().unwrap().push(format!("send {message}"));+ let handle = subscriber.send(message.clone()).await?;+ let immediate = handle.is_immediate();+ let log = self.log.clone();+ let message = message.clone();+ handles.push(async move {+ handle.ready().await?;+ log.lock()+ .unwrap()+ .push(format!("acked {message} immediate={immediate}"));+ Ok::<(), cocoindex::Error>(())+ });+ }+ futures::future::try_join_all(handles).await?;+ subscriber.mark_ready().await;+ self.log.lock().unwrap().push("ready".to_string());+ std::future::pending::<()>().await;+ Ok(())+ }+}++/// A live map over the stream: an empty scan, then the stream's messages as+/// children keyed by the message itself (an `x` message is skipped: it needs+/// no work, so its handle is immediate).+struct StreamMap {+ stream: VecStream,+}++struct ToMap<'a>(&'a LiveMapSubscriber<String, String>);++#[async_trait]+impl LiveStreamSubscriber<String> for ToMap<'_> {+ async fn send(&self, message: String) -> Result<ReadyHandle> {+ if message == "x" {+ return Ok(ReadyHandle::immediate());+ }+ self.0.start_update(message.clone(), message).await+ }++ async fn mark_ready(&self) {+ self.0.mark_ready().await;+ }+}++#[async_trait]+impl LiveMapFeed<String, String> for StreamMap {+ async fn watch(&self, subscriber: LiveMapSubscriber<String, String>) -> Result<()> {+ self.stream.watch(&ToMap(&subscriber)).await+ }+}++#[async_trait]+impl LiveMapView<String, String> for StreamMap {+ async fn scan(&self) -> Result<Vec<(String, String)>> {+ Ok(Vec::new())+ }+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn stream_messages_are_mounted_and_acknowledged_in_a_live_run() -> Result<()> {+ let tmp = tempfile::tempdir().unwrap();+ let log: Log = Arc::new(Mutex::new(Vec::new()));+ let processed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));+ let app = App::builder("LiveStream")+ .db_path(tmp.path().join("db"))+ .build()+ .await?;+ let handle = app+ .start_update_with_options(+ UpdateOptions {+ full_reprocess: false,+ live: true,+ ..UpdateOptions::default()+ },+ {+ let log = log.clone();+ let processed = processed.clone();+ move |ctx| {+ let log = log.clone();+ let processed = processed.clone();+ async move {+ let feed = StreamMap {+ stream: VecStream {+ messages: vec!["a".into(), "x".into(), "b".into()],+ log,+ guard: SingleWatcherGuard::new("VecStream"),+ },+ };+ ctx.mount_each_live(&"messages", feed, move |_ctx, value: String| {+ let processed = processed.clone();+ async move {+ // Slow children: an acknowledgement must wait.+ tokio::time::sleep(Duration::from_millis(50)).await;+ processed.lock().unwrap().push(value);+ Ok(())+ }+ })+ .await+ }+ }+ },+ )+ .unwrap();++ let deadline = Instant::now() + Duration::from_secs(20);+ while !log.lock().unwrap().iter().any(|l| l == "ready") {+ assert!(Instant::now() < deadline, "the stream never became ready");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ let _ = app.drop_state().await;+ let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;++ let log = log.lock().unwrap().clone();+ let position = |entry: &str| log.iter().position(|l| l == entry).unwrap();+ // Every message was delivered before any was acknowledged: the stream did+ // not wait for a child before sending the next message.+ assert!(+ position("send b") < position("acked a immediate=false"),+ "{log:?}"+ );+ // A skipped message is acknowledged at once; a mounted one only after its+ // child ran.+ assert!(+ log.contains(&"acked x immediate=true".to_string()),+ "{log:?}"+ );+ assert!(+ position("acked b immediate=false") < position("ready"),+ "{log:?}"+ );+ let mut processed = processed.lock().unwrap().clone();+ processed.sort();+ assert_eq!(processed, vec!["a".to_string(), "b".to_string()]);+ Ok(())+}