Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

fix(oci): record logic_version only after a startup scan that completed (#2825)

Jiangzhou42770c97d6ae
diff --git a/docs/src/content/docs/connectors/oci_object_storage.mdx b/docs/src/content/docs/connectors/oci_object_storage.mdx
index b8523041..f1dd162b 100644
--- a/docs/src/content/docs/connectors/oci_object_storage.mdx
+++ b/docs/src/content/docs/connectors/oci_object_storage.mdx
@@ -707,7 +707,7 @@ ctx.mount_each_live(&"objects", feed, move |_ctx, file: OciFile| {
`events` is any `LiveStream<Vec<u8>>` of raw OCI event JSON payloads, one event per item, such as the Kafka connector's `topic_as_stream(..).payloads()`. Each event is confirmed with a `HEAD` of the object: a present object is an update, a `404` a delete. The walker acknowledges each event to the stream once the object it names has synced (at once when the event is filtered out), so a consumer group's committed offset never passes an unprocessed event.
-`OciLiveWalker::logic_version(version)` opts into skipping the startup scan on a rerun whose recorded version matches, and relies on the durable stream to replay the backlog. Bump the version whenever the processing logic changes.
+`OciLiveWalker::logic_version(version)` opts into skipping the startup scan on a rerun whose recorded version matches, and relies on the durable stream to replay the backlog. The version is recorded only after a startup scan in which nothing failed, so a rerun after a failed scan (even one whose failures an exception handler absorbed) scans again. Bump the version whenever the processing logic changes.
</Fragment>
</LangTabs>
diff --git a/python/cocoindex/_internal/core.pyi b/python/cocoindex/_internal/core.pyi
index eb0863b8..aba86e31 100644
--- a/python/cocoindex/_internal/core.pyi
+++ b/python/cocoindex/_internal/core.pyi
@@ -372,7 +372,7 @@ class LiveComponentController:
self,
processor: ComponentProcessor[Any],
handler_callback: Callable[[BaseException], Awaitable[None]] | None = None,
- ) -> Coroutine[Any, Any, None]: ...
+ ) -> Coroutine[Any, Any, bool]: ...
def update_async(
self,
stable_path: StablePath,
diff --git a/python/cocoindex/_internal/live_component.py b/python/cocoindex/_internal/live_component.py
index 07c047f3..59d37009 100644
--- a/python/cocoindex/_internal/live_component.py
+++ b/python/cocoindex/_internal/live_component.py
@@ -307,6 +307,17 @@ class LiveComponentOperator:
patterns (e.g. `coco.auto_refresh`) keep looping when a single
cycle fails, while still surfacing the failure to operators.
"""
+ await self._update_full()
+
+ async def _update_full(self) -> bool:
+ """:meth:`update_full`, returning whether the pass completed.
+
+ ``False`` when ``process()`` or a component under it failed (the
+ failure went to the exception handler chain, which absorbed it, or to
+ the log) or the pass was cancelled. A connector records durable
+ bootstrap state (an OCI view's ``logic_version``) only after a pass
+ that completed.
+ """
controller = self._require_controller()
processor = create_core_component_processor(
self._instance.process, self._env, self._path, (), {}
@@ -315,7 +326,7 @@ class LiveComponentOperator:
prev = _in_process_live.get()
_in_process_live.set(False)
try:
- await controller.update_full_async(processor, on_error)
+ return await controller.update_full_async(processor, on_error)
finally:
_in_process_live.set(prev)
@@ -522,7 +533,12 @@ class LiveMapSubscriber(Generic[_K, _V]):
async def update_all(self) -> None:
"""Trigger a full re-iteration of all items."""
- await self._operator.update_full()
+ await self._update_all()
+
+ async def _update_all(self) -> bool:
+ """:meth:`update_all`, returning whether the pass completed (see
+ :meth:`LiveComponentOperator._update_full`)."""
+ return await self._operator._update_full()
async def mark_ready(self) -> None:
"""Signal readiness. In catch-up mode, this terminates ``watch()``."""
diff --git a/python/cocoindex/connectors/oci_object_storage/_source.py b/python/cocoindex/connectors/oci_object_storage/_source.py
index 617a2058..f34d6041 100644
--- a/python/cocoindex/connectors/oci_object_storage/_source.py
+++ b/python/cocoindex/connectors/oci_object_storage/_source.py
@@ -392,8 +392,8 @@ class _LiveOCIItems:
run committed the same ``logic_version``, steps 1+3 are replaced β€” the scan
is skipped and ``cutoff`` is ``None`` so the durable stream's replayed
backlog (resumed from its committed cursor) is processed rather than
- dropped. The committed version is (re)written after step 4 on any run that
- actually scans.
+ dropped. The committed version is (re)written after step 4 on any run whose
+ scan completed (no failure in the listing or in any object's processing).
"""
__slots__ = ("_walker", "_live_stream", "_watch_guard")
@@ -430,12 +430,15 @@ class _LiveOCIItems:
adapter = _OCIStreamSubscriber(self._walker, subscriber, cutoff)
stream_task = asyncio.create_task(self._live_stream.watch(adapter))
try:
+ scan_completed = False
if not skip_scan:
- await subscriber.update_all()
+ scan_completed = await subscriber._update_all()
await subscriber.mark_ready()
# Record the version only after mark_ready (the scan has committed),
- # so a later run skips only when the bootstrap durably landed.
- if not skip_scan and logic_version is not None:
+ # and only after a scan that completed: a failure the exception
+ # handler absorbed leaves an object unprocessed (or unlisted), so a
+ # later run must scan again.
+ if scan_completed and logic_version is not None:
await subscriber.write_committed_state(_SCAN_VERSION_KEY, logic_version)
adapter.mark_ready_complete()
await stream_task
@@ -674,8 +677,10 @@ def list_objects(
max_file_size: Skip objects larger than this size in bytes.
live_stream: Optional ``LiveStream[bytes]`` of OCI Object Storage events.
logic_version: Opt into skipping the startup full scan on reruns. When
- set, the live view records this version after a successful scan and,
- on a later run, skips the scan if the recorded version matches β€”
+ set, the live view records this version after a scan in which
+ nothing failed (neither the listing nor any object's processing,
+ even when an exception handler absorbed the failure) and, on a
+ later run, skips the scan if the recorded version matches β€”
relying on the durable stream to replay the downtime backlog from
its committed cursor. You MUST bump this whenever your processing
logic changes (otherwise stale state is silently kept), and the
diff --git a/python/tests/connectors/test_oci_object_storage.py b/python/tests/connectors/test_oci_object_storage.py
index 0b2212c2..3368735c 100644
--- a/python/tests/connectors/test_oci_object_storage.py
+++ b/python/tests/connectors/test_oci_object_storage.py
@@ -377,8 +377,9 @@ class _MockMapSubscriber:
self.deletes: list[str] = []
self.committed: dict[Any, Any] = {} if committed is None else committed
- async def update_all(self) -> None:
+ async def _update_all(self) -> bool:
self.update_all_called = True
+ return True
async def mark_ready(self) -> None:
self.mark_ready_called = True
@@ -509,9 +510,9 @@ async def test_oci_live_view_event_after_cutoff_blocks_until_ready(
scan_gate = asyncio.Event()
class _SlowSub(_MockMapSubscriber):
- async def update_all(self) -> None:
+ async def _update_all(self) -> bool:
await scan_gate.wait()
- await super().update_all()
+ return await super()._update_all()
sub = _SlowSub()
items = _live_items(walker)
@@ -612,12 +613,13 @@ async def test_oci_live_view_ready_complete_set_after_mark_ready(
observations: list[tuple[str, bool, bool]] = []
class _ObservingSub(_MockMapSubscriber):
- async def update_all(self) -> None:
+ async def _update_all(self) -> bool:
observations.append(("update_all_enter", False, False))
- await super().update_all()
+ completed = await super()._update_all()
observations.append(
("update_all_exit", self.update_all_called, self.mark_ready_called)
)
+ return completed
async def mark_ready(self) -> None:
observations.append(
@@ -904,9 +906,9 @@ async def test_oci_live_view_cancel_while_send_blocked_on_ready(
scan_gate = asyncio.Event()
class _SlowSub(_MockMapSubscriber):
- async def update_all(self) -> None:
+ async def _update_all(self) -> bool:
await scan_gate.wait()
- await super().update_all()
+ return await super()._update_all()
class _SendingStream:
"""Simulates a stream that delivers one post-cutoff event inline."""
@@ -948,7 +950,7 @@ async def test_oci_live_view_scan_failure_propagates(
stream = _ManualLiveStream()
class _FailingSub(_MockMapSubscriber):
- async def update_all(self) -> None:
+ async def _update_all(self) -> bool:
raise RuntimeError("scan boom")
walker = list_objects(oci_client, "ns", "bucket", live_stream=stream)
@@ -1144,6 +1146,125 @@ def test_oci_walker_scan_through_real_mount_each() -> None:
)
+# --- logic_version across restarts ---
+
+
+# Object names whose processing raises.
+_failing_objects: set[str] = set()
+
+
+async def _declare_object(file: OCIFile) -> None:
+ name = file.file_path.object_name
+ if name in _failing_objects:
+ raise RuntimeError(f"processing {name} failed")
+ coco.declare_target_state(GlobalDictTarget.target_state(name, await file.read()))
+
+
+class _NoEvents:
+ """A ``LiveStream[bytes]`` with no events that ends at once: a live view over
+ it stops right after its startup (the scan or its skip, then the version
+ write), so a test can run an app live and start it again on the same state.
+ """
+
+ async def watch(self, subscriber: LiveStreamSubscriber[bytes]) -> None:
+ return
+
+
+def _versioned_live_app(
+ env: coco.Environment, client: MockObjectStorageClient
+) -> coco.App[Any, Any]:
+ """An app that watches the bucket with ``logic_version="v1"``."""
+
+ @coco.fn
+ async def app_main() -> None:
+ walker = list_objects(
+ client, "ns", "bucket", live_stream=_NoEvents(), logic_version="v1"
+ )
+ await coco.mount_each(_declare_object, walker.items())
+
+ return coco.App(
+ coco.AppConfig(name="oci_versioned_live", environment=env), app_main
+ )
+
+
+async def _run_live(app: coco.App[Any, Any]) -> None:
+ await asyncio.wait_for(app.update(live=True).result(), timeout=30)
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
[email protected]("failure", ["item", "listing"])
+async def test_oci_live_view_rescans_after_a_failed_scan(
+ request: pytest.FixtureRequest,
+ monkeypatch: pytest.MonkeyPatch,
+ oci_client: MockObjectStorageClient,
+ failure: str,
+) -> None:
+ """A scan whose failure an exception handler absorbs does not record the
+ version, so the next start scans again and processes what the failed scan
+ missed: an item whose processing raised, or one the listing never reached.
+ """
+ GlobalDictTarget.store.clear()
+ oci_client.put("a.txt", b"a")
+ oci_client.put("b.txt", b"b")
+ handled: list[BaseException] = []
+ env = common.create_test_env(
+ __file__,
+ suffix=request.node.name,
+ exception_handler=lambda exc, ctx: handled.append(exc),
+ )
+ app = _versioned_live_app(env, oci_client)
+
+ if failure == "item":
+ _failing_objects.add("b.txt")
+ else:
+ # One object per page, and the second page fails: b.txt is never listed.
+ oci_client.set_page_size(1)
+ list_page = oci_client.list_objects
+
+ def list_first_page_only(**kwargs: Any) -> _MockListObjectsResponse:
+ if "start" in kwargs:
+ raise RuntimeError("listing failed")
+ return list_page(**kwargs)
+
+ monkeypatch.setattr(oci_client, "list_objects", list_first_page_only)
+ try:
+ await _run_live(app)
+ finally:
+ _failing_objects.clear()
+ monkeypatch.undo()
+ assert handled
+ assert _stored() == {"a.txt": b"a"}
+
+ await _run_live(app)
+ assert _stored() == {"a.txt": b"a", "b.txt": b"b"}
+
+
+async def test_oci_live_view_skips_scan_after_a_clean_scan(
+ request: pytest.FixtureRequest, oci_client: MockObjectStorageClient
+) -> None:
+ """After a scan that completed, the next start with the same version skips
+ the scan: an object put while the app was down (with no event) stays out."""
+ GlobalDictTarget.store.clear()
+ oci_client.put("a.txt", b"a")
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ app = _versioned_live_app(env, oci_client)
+
+ await _run_live(app)
+ assert _stored() == {"a.txt": b"a"}
+
+ oci_client.put("b.txt", b"b")
+ oci_client.list_objects_calls.clear()
+ await _run_live(app)
+ assert oci_client.list_objects_calls == []
+ assert _stored() == {"a.txt": b"a"}
+
+
# ===========================================================================
# Item keys: scan and live events agree
# ===========================================================================
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index c94a606b..9369ca88 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -658,6 +658,17 @@ impl<Prof: EngineProfile> ComponentMountRunHandle<Prof> {
}
}
+/// Whether a run reached every component under it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RunCompleteness {
+ /// The component and every component under it ran without a failure.
+ Complete,
+ /// The component or one under it failed, and the failure went to an
+ /// exception handler that absorbed it, or to the log, rather than to the
+ /// caller; or the run was cancelled.
+ Incomplete,
+}
+
pub struct ComponentExecutionHandle {
fut: Pin<Box<dyn Future<Output = SharedResult<()>> + Send + Sync>>,
}
@@ -1183,6 +1194,22 @@ impl<Prof: EngineProfile> Component<Prof> {
context: ComponentProcessorContext<Prof>,
on_error: Option<OnError>,
) -> Result<ComponentExecutionHandle> {
+ let run = self
+ .run_in_background_to_completeness(processor, context, on_error)
+ .await?;
+ Ok(ComponentExecutionHandle::new(async move {
+ run.await.map(|_| ())
+ }))
+ }
+
+ /// [`Self::run_in_background`], resolving to whether the run reached every
+ /// component under it.
+ pub(crate) async fn run_in_background_to_completeness(
+ self,
+ processor: Prof::ComponentProc,
+ context: ComponentProcessorContext<Prof>,
+ on_error: Option<OnError>,
+ ) -> Result<impl Future<Output = SharedResult<RunCompleteness>> + Send + Sync + 'static> {
// TODO: Skip building and reuse cached result if the component is already built and up to date.
let started = self.start_task(&context)?;
self.admit_before_spawn(&context, &started).await?;
@@ -1232,6 +1259,11 @@ impl<Prof: EngineProfile> Component<Prof> {
(ComponentRunOutcome::exception(), task_result)
}
};
+ let completeness = if outcome.has_exception {
+ RunCompleteness::Incomplete
+ } else {
+ RunCompleteness::Complete
+ };
context.admission().finish();
drop(processor);
drop(context);
@@ -1242,13 +1274,13 @@ impl<Prof: EngineProfile> Component<Prof> {
if let Some(guard) = child_readiness_guard {
guard.resolve(outcome);
}
- task_result
+ task_result.map(|()| completeness)
});
- Ok(ComponentExecutionHandle::new(async move {
+ Ok(async move {
join_handle
.await
.map_err(|e| SharedError::new(internal_error!("task panicked: {e}")))?
- }))
+ })
}
pub fn delete(
diff --git a/rust/core/src/engine/live_component.rs b/rust/core/src/engine/live_component.rs
index 067db1c8..2218d5fe 100644
--- a/rust/core/src/engine/live_component.rs
+++ b/rust/core/src/engine/live_component.rs
@@ -5,7 +5,7 @@ use std::future::Future;
use crate::engine::admission::{Lender, LiveShare};
use crate::engine::component::{
ActivityGuard, Component, ComponentBgChildReadinessChildGuard, ComponentExecutionHandle,
- OnError,
+ OnError, RunCompleteness,
};
use crate::engine::context::{
ComponentProcessingAction, ComponentProcessorContext, FnCallContext, PreviewActionCollector,
@@ -18,7 +18,7 @@ use crate::state::component_selector::{ComponentSelector, MountDecision};
use crate::state::stable_path::{StableKey, StablePath};
use crate::state::target_state_path::TargetStatePath;
use crate::state_store::AppStore;
-use cocoindex_utils::error::{SharedError, SharedResult};
+use cocoindex_utils::error::{SharedError, SharedResult, SharedResultExt};
use tokio::sync::oneshot;
@@ -720,11 +720,15 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
/// Full processing cycle. Acquires `update_full_lock` (serializes with
/// concurrent `update_full()` calls), waits for any in-flight subpath
/// drains to quiesce, then runs `process()` via `run_in_background`.
+ ///
+ /// Returns whether the pass reached every component under it: a failure
+ /// that `on_error` absorbs (or that is only logged) does not fail the call,
+ /// so a host that records its source as fully processed checks this first.
pub async fn update_full(
&self,
processor: Prof::ComponentProc,
on_error: Option<OnError>,
- ) -> Result<()> {
+ ) -> Result<RunCompleteness> {
let _full_guard = self.state.update_full_lock.lock().await;
// A catch-up incarnation beside a running live one also holds the
// live one's lock (always after its own: one lock order).
@@ -780,15 +784,12 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
self.update_refusal.clone(),
);
- let handle = self
+ let run = self
.component
.clone()
- .run_in_background(processor, context, on_error)
+ .run_in_background_to_completeness(processor, context, on_error)
.await?;
-
- handle.ready().await?;
-
- Ok(())
+ run.await.into_result()
}
/// The update's selector leaves out a mount at `subpath`. [`Self::update`]
diff --git a/rust/py/src/live_component.rs b/rust/py/src/live_component.rs
index 6bf1aef6..12b54069 100644
--- a/rust/py/src/live_component.rs
+++ b/rust/py/src/live_component.rs
@@ -6,6 +6,7 @@ use crate::{
stable_path::{PyStableKey, PyStablePath},
};
+use cocoindex_core::engine::component::RunCompleteness;
use cocoindex_core::engine::live_component::LiveComponentController;
use cocoindex_py_utils::from_py_future;
use pyo3_async_runtimes::tokio::future_into_py;
@@ -30,10 +31,11 @@ impl PyLiveComponentController {
let host_runtime_ctx = ctrl.component().app_ctx().env().host_runtime_ctx().clone();
let on_error = build_on_error(host_runtime_ctx, handler_callback);
future_into_py(py, async move {
- ctrl.update_full(processor, on_error)
+ let completeness = ctrl
+ .update_full(processor, on_error)
.await
.into_py_result()?;
- Ok(())
+ Ok(completeness == RunCompleteness::Complete)
})
}
diff --git a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs
index e7d53571..de625554 100644
--- a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs
+++ b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs
@@ -41,6 +41,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
+use cocoindex_core::engine::component::RunCompleteness;
use cocoindex_utils::fingerprint::Fingerprint;
use rsa::RsaPrivateKey;
use rsa::pkcs1::DecodeRsaPrivateKey;
@@ -1440,9 +1441,6 @@ pub struct OciLiveWalker {
/// Opt-in version for skipping the startup scan on reruns (see
/// [`OciLiveWalker::logic_version`]). `None` always scans.
logic_version: Option<String>,
- /// Decision recorded by `skip_initial_scan`, read by `watch` to know whether
- /// the scan ran (so the event cutoff and version write can branch on it).
- skip_scan: tokio::sync::Mutex<bool>,
}
/// Build a live view over an OCI bucket, driven by `events`: a [`LiveStream`]
@@ -1470,20 +1468,21 @@ pub fn list_objects_live(
cutoff: tokio::sync::Mutex::new(0),
watch_guard: SingleWatcherGuard::new("OciLiveWalker"),
logic_version: None,
- skip_scan: tokio::sync::Mutex::new(false),
}
}
/// Committed-state key under which the live view records `logic_version` after a
-/// successful full scan, read back on a later run to decide whether the startup
-/// scan can be skipped.
+/// full scan that completed, read back on a later run to decide whether the
+/// startup scan can be skipped.
const OCI_SCAN_VERSION_KEY: &str = "__coco_oci_scan_version__";
impl OciLiveWalker {
/// Opt into skipping the startup full scan on reruns. When set, the live view
- /// records this version after a successful scan and, on a later run, skips the
- /// scan if the recorded version matches β€” relying on the durable event stream
- /// to replay the downtime backlog from its committed cursor.
+ /// records this version after a scan in which nothing failed (neither the
+ /// listing nor any object's processing, even when a handler absorbed the
+ /// failure) and, on a later run, skips the scan if the recorded version
+ /// matches β€” relying on the durable event stream to replay the downtime
+ /// backlog from its committed cursor.
///
/// You MUST bump this whenever your processing logic changes (otherwise stale
/// state is silently kept), and the stream MUST be durable (e.g. a Kafka
@@ -1602,18 +1601,18 @@ impl LiveMapFeed<String, OciFile> for OciLiveWalker {
return Ok(false);
};
let stored: Option<String> = operator.read_committed_state(OCI_SCAN_VERSION_KEY).await?;
- let skip = stored.as_deref() == Some(version.as_str());
- *self.skip_scan.lock().await = skip;
- Ok(skip)
+ Ok(stored.as_deref() == Some(version.as_str()))
}
async fn watch(&self, subscriber: LiveMapSubscriber<String, OciFile>) -> Result<()> {
let _watch_token = self.watch_guard.enter()?;
- let skip_scan = *self.skip_scan.lock().await;
- // Record the version only after a real scan (which has already committed
- // β€” `mark_ready` ran before `watch`), so a later run skips only when the
- // bootstrap durably landed.
- if !skip_scan && let Some(version) = &self.logic_version {
+ // Record the version only after a scan that completed (it has already
+ // committed β€” `mark_ready` ran before `watch`): a failure a handler
+ // absorbed leaves an object unprocessed, or unlisted, so a later run
+ // must scan again.
+ if subscriber.startup_scan == Some(RunCompleteness::Complete)
+ && let Some(version) = &self.logic_version
+ {
subscriber
.write_committed_state(OCI_SCAN_VERSION_KEY, version)
.await?;
@@ -1621,7 +1620,7 @@ impl LiveMapFeed<String, OciFile> for OciLiveWalker {
// In skip-scan mode there is no scan to dedupe against, so the wall-clock
// cutoff must not fire β€” the durable stream replays the downtime backlog
// and every replayed event must be processed. `i64::MIN` drops nothing.
- let cutoff = if skip_scan {
+ let cutoff = if subscriber.startup_scan.is_none() {
i64::MIN
} else {
*self.cutoff.lock().await
diff --git a/rust/sdk/cocoindex/src/ctx.rs b/rust/sdk/cocoindex/src/ctx.rs
index adf8ec5a..44ec7465 100644
--- a/rust/sdk/cocoindex/src/ctx.rs
+++ b/rust/sdk/cocoindex/src/ctx.rs
@@ -1096,7 +1096,7 @@ impl Ctx {
source: ExceptionSource::Component,
});
match controller.update_full(processor, on_error).await {
- Ok(()) => {
+ Ok(_) => {
controller.mark_ready().await;
ready_marked = true;
}
diff --git a/rust/sdk/cocoindex/src/live_component.rs b/rust/sdk/cocoindex/src/live_component.rs
index 44b5c0f6..12abfcd5 100644
--- a/rust/sdk/cocoindex/src/live_component.rs
+++ b/rust/sdk/cocoindex/src/live_component.rs
@@ -30,7 +30,7 @@ use std::pin::Pin;
use std::sync::Arc;
use async_trait::async_trait;
-use cocoindex_core::engine::component::OnError;
+use cocoindex_core::engine::component::{OnError, RunCompleteness};
use cocoindex_core::engine::deadline::DeadlineContext;
use cocoindex_core::engine::live_component::LiveComponentController;
use cocoindex_core::state::stable_path::{StableKey, StablePath};
@@ -253,6 +253,14 @@ impl LiveComponentOperator {
/// logged at error level and this returns `Ok(())`, as in the Python SDK.
/// Register a handler that returns `Err` to make failures propagate.
pub async fn update_full(&self) -> Result<()> {
+ self.update_full_to_completeness().await?;
+ Ok(())
+ }
+
+ /// [`Self::update_full`], returning whether the pass reached every
+ /// component under it: a failure the handlers absorbed, or one only
+ /// logged, makes it [`RunCompleteness::Incomplete`].
+ pub(crate) async fn update_full_to_completeness(&self) -> Result<RunCompleteness> {
let instance = self.instance.clone();
let state = self.state.clone();
let chain = self.handler_chain.clone();
@@ -560,6 +568,11 @@ type ProcessItemFn<V> =
pub struct LiveMapSubscriber<K, V> {
operator: LiveComponentOperator,
process_fn: ProcessItemFn<V>,
+ /// How the scan that ran before [`LiveMapFeed::watch`] ended; `None` when
+ /// the feed skipped it ([`LiveMapFeed::skip_initial_scan`]).
+ // Read only by feature-gated connectors (oci_object_storage today).
+ #[allow(dead_code)]
+ pub(crate) startup_scan: Option<RunCompleteness>,
_key: PhantomData<fn() -> K>,
}
@@ -783,13 +796,16 @@ where
// A durable feed may skip the scan and replay from its committed cursor,
// but only in live mode: in catch-up mode `watch` never runs, so a
// skipped scan would leave every change since the last run unprocessed.
- if !(operator.is_live() && self.feed.skip_initial_scan(&operator).await?) {
- operator.update_full().await?;
- }
+ let startup_scan = if operator.is_live() && self.feed.skip_initial_scan(&operator).await? {
+ None
+ } else {
+ Some(operator.update_full_to_completeness().await?)
+ };
operator.mark_ready().await;
let subscriber = LiveMapSubscriber {
operator,
process_fn: self.process_fn.clone(),
+ startup_scan,
_key: PhantomData,
};
self.feed.watch(subscriber).await
diff --git a/rust/sdk/cocoindex/tests/oci_live.rs b/rust/sdk/cocoindex/tests/oci_live.rs
index ba0c4b49..0e5249ed 100644
--- a/rust/sdk/cocoindex/tests/oci_live.rs
+++ b/rust/sdk/cocoindex/tests/oci_live.rs
@@ -11,7 +11,9 @@
//! * an event older than the scan cutoff is dropped,
//! * a cross-bucket event is dropped (no `HEAD`),
//! * a malformed payload is skipped,
-//! * every event is acknowledged to the stream once handled.
+//! * every event is acknowledged to the stream once handled,
+//! * with `logic_version`, a restart skips the scan only after one that
+//! completed.
//!
//! The instance-principal tests stand in for the instance metadata service and
//! the identity service's federation endpoint too.
@@ -26,7 +28,7 @@ use cocoindex::connectors::oci_object_storage::{
};
use cocoindex::resources::file::PatternFilePathMatcher;
use cocoindex::{
- App, LiveMapView, LiveStream, LiveStreamSubscriber, Result, UpdateOptions, async_trait,
+ App, Error, LiveMapView, LiveStream, LiveStreamSubscriber, Result, UpdateOptions, async_trait,
};
use rsa::RsaPrivateKey;
use rsa::pkcs8::{EncodePrivateKey, LineEnding};
@@ -460,6 +462,157 @@ async fn oci_live_view_scan_failure_propagates() -> Result<()> {
Ok(())
}
+/// A `LiveStream` with no events that ends at once: a live view over it stops
+/// right after its startup (the scan or its skip, then the version write), so
+/// a test can run an app live and start it again on the same state.
+struct NoEvents;
+
+#[async_trait]
+impl LiveStream<Vec<u8>> for NoEvents {
+ async fn watch(&self, _subscriber: &dyn LiveStreamSubscriber<Vec<u8>>) -> Result<()> {
+ Ok(())
+ }
+}
+
+/// Serve a ListObjects response listing `names`.
+async fn mount_listing(server: &MockServer, names: &[&str]) {
+ let objects: Vec<_> = names
+ .iter()
+ .map(|name| json!({"name": name, "size": 1, "timeModified": "2020-01-01T00:00:00Z"}))
+ .collect();
+ Mock::given(method("GET"))
+ .and(path("/n/ns/b/bucket/o"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "objects": objects })))
+ .mount(server)
+ .await;
+}
+
+/// Run `app` live over the bucket with `logic_version("v1")` until the view has
+/// started up, and return the objects processed, sorted. Processing `failing`
+/// fails, and with no handler registered the failure is logged and absorbed.
+async fn run_versioned_live(
+ app: &App,
+ client: &OciClient,
+ failing: Option<&'static str>,
+) -> Vec<String> {
+ let processed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ let handle = app
+ .start_update_with_options(
+ UpdateOptions {
+ live: true,
+ ..UpdateOptions::default()
+ },
+ {
+ let processed = processed.clone();
+ let client = client.clone();
+ move |ctx| {
+ let processed = processed.clone();
+ let client = client.clone();
+ async move {
+ let feed = list_objects_live(
+ &client,
+ "ns",
+ "bucket",
+ ListOptions::default(),
+ NoEvents,
+ )
+ .logic_version("v1");
+ ctx.mount_each_live(&"objects", feed, move |_ctx, file: OciFile| {
+ let processed = processed.clone();
+ async move {
+ let key = file.file_path().path().to_string();
+ if failing == Some(key.as_str()) {
+ return Err(Error::engine(format!("processing {key} failed")));
+ }
+ processed.lock().unwrap().push(key);
+ Ok(())
+ }
+ })
+ .await
+ }
+ }
+ },
+ )
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(20), handle.result())
+ .await
+ .expect("the live view did not stop after its startup")
+ .unwrap();
+ let mut processed = processed.lock().unwrap().clone();
+ processed.sort();
+ processed
+}
+
+async fn list_requests(server: &MockServer) -> usize {
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .filter(|r| r.method.as_str() == "GET" && r.url.path() == "/n/ns/b/bucket/o")
+ .count()
+}
+
+/// A scan in which an item fails, or the listing itself, records no version:
+/// the next start scans again and processes what the failed scan missed.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn oci_live_view_rescans_after_a_failed_scan() -> Result<()> {
+ let tmp = tempfile::tempdir().unwrap();
+
+ // An item fails.
+ let server = MockServer::start().await;
+ mount_listing(&server, &["a.txt", "b.txt"]).await;
+ let client = client_for(&server.uri(), &tmp.path().join("key.pem"));
+ let app = App::builder("OciLiveItemFails")
+ .db_path(tmp.path().join("item_db"))
+ .build()
+ .await?;
+ assert_eq!(
+ run_versioned_live(&app, &client, Some("b.txt")).await,
+ ["a.txt"]
+ );
+ assert_eq!(
+ run_versioned_live(&app, &client, None).await,
+ ["a.txt", "b.txt"]
+ );
+
+ // The listing fails, once.
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/n/ns/b/bucket/o"))
+ .respond_with(ResponseTemplate::new(500))
+ .up_to_n_times(1)
+ .with_priority(1)
+ .mount(&server)
+ .await;
+ mount_listing(&server, &["a.txt"]).await;
+ let client = client_for(&server.uri(), &tmp.path().join("key.pem"));
+ let app = App::builder("OciLiveListingFails")
+ .db_path(tmp.path().join("listing_db"))
+ .build()
+ .await?;
+ assert!(run_versioned_live(&app, &client, None).await.is_empty());
+ assert_eq!(run_versioned_live(&app, &client, None).await, ["a.txt"]);
+ Ok(())
+}
+
+/// After a scan that completed, the next start with the same version skips it.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn oci_live_view_skips_scan_after_a_clean_scan() -> Result<()> {
+ let server = MockServer::start().await;
+ mount_listing(&server, &["a.txt"]).await;
+ let tmp = tempfile::tempdir().unwrap();
+ let client = client_for(&server.uri(), &tmp.path().join("key.pem"));
+ let app = App::builder("OciLiveClean")
+ .db_path(tmp.path().join("db"))
+ .build()
+ .await?;
+ assert_eq!(run_versioned_live(&app, &client, None).await, ["a.txt"]);
+ assert!(run_versioned_live(&app, &client, None).await.is_empty());
+ assert_eq!(list_requests(&server).await, 1);
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn oci_file_exists_heads_once_and_caches_the_verdict() -> Result<()> {
let server = MockServer::start().await;