Skip to content

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

fix(core): sinks apply in provider-key order, and a sink error names its target states (#2828)

LJ πŸ₯₯🌴11853dd0dfaf
diff --git a/python/tests/core/test_sink_apply_order.py b/python/tests/core/test_sink_apply_order.py
new file mode 100644
index 00000000..0b44dd9e
--- /dev/null
+++ b/python/tests/core/test_sink_apply_order.py
@@ -0,0 +1,93 @@
+"""Sinks at one provider depth apply in a fixed order: by their providers'
+stable keys from the root provider down, whatever order the target states were
+declared in. A preview lists a component's actions in that order too."""
+
+from __future__ import annotations
+
+import threading
+from dataclasses import dataclass
+from typing import Any, Collection
+
+import cocoindex as coco
+from tests import common
+
+coco_env = common.create_test_env(__file__)
+
+_applied: list[str] = []
+_applied_lock = threading.Lock()
+
+
+@dataclass(frozen=True)
+class _RecordingSink:
+ provider_name: str
+
+ async def __call__(
+ self,
+ context_provider: coco.ContextProvider,
+ actions: Collection[tuple[str, str]],
+ /,
+ ) -> None:
+ with _applied_lock:
+ _applied.extend(name for name, _ in actions)
+
+
+class _Handler:
+ def __init__(self, provider_name: str) -> None:
+ self._provider_name = provider_name
+ self._sink = coco.TargetActionSink.from_async_fn(_RecordingSink(provider_name))
+
+ def reconcile(
+ self,
+ key: Any,
+ desired_state: Any | coco.NonExistenceType,
+ prev_possible_records: Collection[Any],
+ prev_may_be_missing: bool,
+ /,
+ ) -> coco.TargetReconcileOutput[Any, Any] | None:
+ if coco.is_non_existence(desired_state):
+ return None
+ return coco.TargetReconcileOutput(
+ action=(self._provider_name, desired_state),
+ sink=self._sink,
+ tracking_record=desired_state,
+ )
+
+
+_NAMES = [f"test_sink_apply_order/{c}" for c in "hcfagbed"]
+_providers = [
+ coco.register_root_target_states_provider(name, _Handler(name)) for name in _NAMES
+]
+
+
+_run = 0
+
+
+def _declare() -> None:
+ for provider in _providers:
+ coco.declare_target_state(provider.target_state("k", f"v{_run}"))
+
+
+def test_sinks_at_one_depth_apply_in_provider_key_order() -> None:
+ global _run
+ app = coco.App(
+ coco.AppConfig(name="test_sink_apply_order", environment=coco_env),
+ _declare,
+ )
+ # With the sinks in hash-map order, eight runs would almost surely see more
+ # than one order.
+ for _run in range(8):
+ _applied.clear()
+ app.update_blocking()
+ assert _applied == sorted(_NAMES), f"run {_run}"
+
+
+def test_a_preview_lists_actions_in_apply_order() -> None:
+ global _run
+ app = coco.App(
+ coco.AppConfig(name="test_sink_apply_order_preview", environment=coco_env),
+ _declare,
+ )
+ for _run in range(8):
+ plan = app.update_blocking(preview=True)
+ assert plan is not None
+ assert [name for name, _ in plan] == sorted(_NAMES), f"run {_run}"
diff --git a/python/tests/core/test_sink_error_context.py b/python/tests/core/test_sink_error_context.py
new file mode 100644
index 00000000..c7d509a6
--- /dev/null
+++ b/python/tests/core/test_sink_error_context.py
@@ -0,0 +1,110 @@
+"""A sink's exception reaches the caller as itself, with a note that names the
+target states the sink was applying."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Collection
+
+import pytest
+
+import cocoindex as coco
+from tests import common
+
+coco_env = common.create_test_env(__file__)
+
+_PROVIDER_NAME = "test_sink_error_context/orders"
+
+
+class _SinkFailure(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class _FailingSink:
+ async def __call__(
+ self,
+ context_provider: coco.ContextProvider,
+ actions: Collection[Any],
+ /,
+ ) -> None:
+ raise _SinkFailure("the orders table is gone")
+
+
+class _Handler:
+ def __init__(self) -> None:
+ self._sink = coco.TargetActionSink.from_async_fn(_FailingSink())
+
+ def reconcile(
+ self,
+ key: Any,
+ desired_state: Any | coco.NonExistenceType,
+ prev_possible_records: Collection[Any],
+ prev_may_be_missing: bool,
+ /,
+ ) -> coco.TargetReconcileOutput[Any, Any] | None:
+ if coco.is_non_existence(desired_state):
+ return None
+ return coco.TargetReconcileOutput(
+ action=desired_state, sink=self._sink, tracking_record=desired_state
+ )
+
+
+_provider = coco.register_root_target_states_provider(_PROVIDER_NAME, _Handler())
+
+
+def _declare() -> None:
+ coco.declare_target_state(_provider.target_state("k", "v"))
+
+
+def test_a_failing_sinks_exception_names_its_target_states() -> None:
+ app = coco.App(
+ coco.AppConfig(name="test_sink_error_context", environment=coco_env),
+ _declare,
+ )
+ with pytest.raises(_SinkFailure, match="the orders table is gone") as exc_info:
+ app.update_blocking()
+ notes = getattr(exc_info.value, "__notes__", [])
+ assert any(
+ "failed to apply changes to target states under" in note
+ and _PROVIDER_NAME in note
+ for note in notes
+ ), notes
+
+
+async def _declare_in_child() -> None:
+ _declare()
+
+
+def test_the_handler_and_the_result_see_one_exception_with_its_note() -> None:
+ """A child's sink failure reaches the exception handler, which re-raises
+ it, and then the update's result: both see the same exception object, and
+ the note names the target states once."""
+ seen: list[BaseException] = []
+
+ def handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
+ seen.append(exc)
+ raise exc
+
+ async def _root() -> None:
+ async with coco.exception_handler(handler):
+ handle = await coco.mount(
+ coco.component_subpath("child"), _declare_in_child
+ )
+ # The handler re-raised: the error reaches the root through `ready()`.
+ await handle.ready()
+
+ app = coco.App(
+ coco.AppConfig(name="test_sink_error_context_twice", environment=coco_env),
+ _root,
+ )
+ with pytest.raises(_SinkFailure) as exc_info:
+ app.update_blocking()
+ assert len(seen) == 1 and seen[0] is exc_info.value
+ notes = [
+ note
+ for note in getattr(exc_info.value, "__notes__", [])
+ if "failed to apply changes to target states under" in note
+ ]
+ assert len(notes) == 1, notes
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index 9369ca88..99e69b84 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -2028,6 +2028,14 @@ mod tests {
apply_calls: Arc<AtomicUsize>,
children: Option<(ChildHandling, Arc<AtomicUsize>)>,
failing: Option<Arc<AtomicBool>>,
+ /// `apply` appends its name to a shared list of applied sinks.
+ recording: Option<Recording>,
+ }
+
+ /// Where a [`NoopSink`] records its `apply` calls, and under which name.
+ struct Recording {
+ applied: Arc<Mutex<Vec<String>>>,
+ name: String,
}
impl NoopSink {
@@ -2038,15 +2046,23 @@ mod tests {
apply_calls: apply_calls.clone(),
children: Some((child_handling, child_reconcile_calls.clone())),
failing: None,
+ recording: None,
};
(sink, apply_calls, child_reconcile_calls)
}
fn child_handler(&self) -> CountingHandler {
let (_, child_reconcile_calls) = self.children.as_ref().expect("a container sink");
+ let child_sink = NoopSink {
+ recording: self.recording.as_ref().map(|recording| Recording {
+ applied: recording.applied.clone(),
+ name: format!("{}/rows", recording.name),
+ }),
+ ..Default::default()
+ };
CountingHandler {
reconcile_calls: child_reconcile_calls.clone(),
- sink: TargetActionSinkKeeper::new(NoopSink::default()),
+ sink: TargetActionSinkKeeper::new(child_sink),
reject: false,
change_only: false,
plans_deletes: false,
@@ -2078,6 +2094,13 @@ mod tests {
actions: &[TargetActionWithChildSlot<TestProfile>],
) -> crate::prelude::Result<()> {
self.apply_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(recording) = &self.recording {
+ recording
+ .applied
+ .lock()
+ .unwrap()
+ .push(recording.name.clone());
+ }
if let Some(failing) = &self.failing
&& failing.load(Ordering::SeqCst)
{
@@ -3052,6 +3075,16 @@ mod tests {
fn container_root(
container_sink: TargetActionSinkKeeper<TestProfile>,
num_rows: i64,
+ ) -> TestProcessor {
+ container_root_with(container_sink, num_rows, None)
+ }
+
+ /// [`container_root`] that also registers a root provider `also` and
+ /// declares one target state through it, after the rows.
+ fn container_root_with(
+ container_sink: TargetActionSinkKeeper<TestProfile>,
+ num_rows: i64,
+ also: Option<(&'static str, TargetActionSinkKeeper<TestProfile>)>,
) -> TestProcessor {
let new_processor = |name: &str| {
TestProcessor::new(
@@ -3096,6 +3129,7 @@ mod tests {
}));
new_processor("root").with_on_process(Arc::new(move |ctx| {
let (table_processor, child_provider) = table_processor.lock().unwrap().take().unwrap();
+ let also = also.clone();
Box::pin(async move {
let table = ctx.component().mount_child(
&FnCallContext::new(true),
@@ -3116,6 +3150,26 @@ mod tests {
(),
)?;
}
+ if let Some((name, sink)) = also.clone() {
+ let provider = register_root_target_state_provider(
+ &ctx,
+ name.to_string(),
+ CountingHandler {
+ reconcile_calls: Default::default(),
+ sink,
+ reject: false,
+ change_only: false,
+ plans_deletes: false,
+ },
+ )?;
+ declare_target_state(
+ &ctx,
+ &FnCallContext::default(),
+ provider,
+ StableKey::Int(0),
+ (),
+ )?;
+ }
Ok(TestData(b"ret".to_vec()))
})
}))
@@ -3535,6 +3589,7 @@ mod tests {
apply_calls: apply_calls.clone(),
children: None,
failing: None,
+ recording: None,
});
let reconcile_calls = reconcile_calls.clone();
Box::pin(async move {
@@ -3606,6 +3661,7 @@ mod tests {
apply_calls: apply_calls.clone(),
children: None,
failing: None,
+ recording: None,
});
Box::pin(async move {
let provider = register_root_target_state_provider(
@@ -4229,4 +4285,140 @@ mod tests {
"nothing left to delete"
);
}
+
+ /// A root processor that registers a run-time root provider per entry of
+ /// `sinks`, in their order, and declares one target state through each.
+ fn declaring_root(
+ test: &str,
+ sinks: Vec<(&'static str, TargetActionSinkKeeper<TestProfile>)>,
+ ) -> TestProcessor {
+ TestProcessor::new(
+ "root",
+ Fingerprint::from(&test).unwrap(),
+ Arc::new(AtomicBool::new(false)),
+ false,
+ )
+ .without_memo()
+ .with_on_process(Arc::new(move |ctx| {
+ let sinks = sinks.clone();
+ Box::pin(async move {
+ for (name, sink) in sinks {
+ let provider = register_root_target_state_provider(
+ &ctx,
+ name.to_string(),
+ CountingHandler {
+ reconcile_calls: Default::default(),
+ sink,
+ reject: false,
+ change_only: false,
+ plans_deletes: true,
+ },
+ )?;
+ declare_target_state(
+ &ctx,
+ &FnCallContext::default(),
+ provider,
+ StableKey::Int(0),
+ (),
+ )?;
+ }
+ Ok(TestData(b"ret".to_vec()))
+ })
+ }))
+ }
+
+ /// Sinks of providers at one depth apply in the order of the providers'
+ /// keys, whatever order the run declared through them, on every run.
+ #[tokio::test]
+ async fn sinks_of_providers_at_one_depth_apply_in_provider_key_order() {
+ let (app, _dir) = test_app("sink_order").await;
+ let applied = Arc::new(Mutex::new(Vec::new()));
+ let sink = |name: &str| {
+ TargetActionSinkKeeper::new(NoopSink {
+ recording: Some(Recording {
+ applied: applied.clone(),
+ name: name.to_string(),
+ }),
+ ..Default::default()
+ })
+ };
+ let sinks = vec![("c", sink("c")), ("a", sink("a")), ("b", sink("b"))];
+ for run in 0..8 {
+ applied.lock().unwrap().clear();
+ let (handle, _) = app
+ .update(
+ declaring_root("sink_order", sinks.clone()),
+ AppUpdateOptions::default(),
+ Arc::new(()),
+ None,
+ )
+ .unwrap();
+ handle.result().await.unwrap();
+ assert_eq!(*applied.lock().unwrap(), ["a", "b", "c"], "run {run}");
+ }
+ }
+
+ /// Sinks of shallower providers apply first, whatever their keys: the
+ /// container's provider is keyed `tables` and the other root provider `z`,
+ /// which sorts after it, yet the rows (depth 1, under `tables`) apply
+ /// last. The key chain alone would put the rows before `z`.
+ #[tokio::test]
+ async fn sinks_of_shallower_providers_apply_first_whatever_their_keys() {
+ let (app, _dir) = test_app("sink_depth_order").await;
+ let applied = Arc::new(Mutex::new(Vec::new()));
+ let recording = |name: &str| Recording {
+ applied: applied.clone(),
+ name: name.to_string(),
+ };
+ let (mut container, _, _) = NoopSink::container(ChildHandling::Factory);
+ container.recording = Some(recording("a"));
+ let container_sink = TargetActionSinkKeeper::new(container);
+ let root_sink = TargetActionSinkKeeper::new(NoopSink {
+ recording: Some(recording("z")),
+ ..Default::default()
+ });
+ for run in 0..8 {
+ applied.lock().unwrap().clear();
+ let root =
+ container_root_with(container_sink.clone(), 2, Some(("z", root_sink.clone())));
+ let (handle, _) = app
+ .update(root, AppUpdateOptions::default(), Arc::new(()), None)
+ .unwrap();
+ handle.result().await.unwrap();
+ assert_eq!(
+ *applied.lock().unwrap(),
+ ["a", "z", "a/rows"],
+ "run {run}: containers before rows, keys within a depth"
+ );
+ }
+ }
+
+ /// A failed sink's error names the target states it was applying: the
+ /// connector's own error says what failed, not where.
+ #[tokio::test]
+ async fn a_failed_sink_names_the_target_states_it_was_applying() {
+ let (app, _dir) = test_app("failing_sink").await;
+ let sink = TargetActionSinkKeeper::new(NoopSink {
+ failing: Some(Arc::new(AtomicBool::new(true))),
+ ..Default::default()
+ });
+ let (handle, _) = app
+ .update(
+ declaring_root("failing_sink", vec![("orders", sink)]),
+ AppUpdateOptions::default(),
+ Arc::new(()),
+ None,
+ )
+ .unwrap();
+ let message = handle
+ .result()
+ .await
+ .expect_err("the sink fails")
+ .to_string();
+ assert!(
+ message.contains("failed to apply changes to target states under @orders"),
+ "{message}"
+ );
+ assert!(message.contains("injected sink failure"), "{message}");
+ }
}
diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rs
index f478a392..5fe43c43 100644
--- a/rust/core/src/engine/execution.rs
+++ b/rust/core/src/engine/execution.rs
@@ -959,10 +959,13 @@ struct SinkInput<Prof: EngineProfile> {
/// sink for the declaring action. Read back after the sink call; a slot the
/// sink left unfulfilled is an error.
pending_children: Vec<(TargetStateProvider<Prof>, ChildTargetSlot<Prof>)>,
- /// The smallest [`TargetStateProvider::depth`] of the providers whose
- /// target states sent actions to this sink: sinks apply in this order
- /// (see [`sinks_in_apply_order`]).
- provider_depth: usize,
+ /// The distinct providers of the target states that sent actions to this
+ /// sink (usually one: a table's rows), to name them when the sink fails
+ /// and to order the sink among the others (see [`sinks_in_apply_order`]).
+ providers: Vec<TargetStateProvider<Prof>>,
+ /// The providers in `providers`, by identity, for the dedup: a sink
+ /// shared by many providers gets many actions.
+ provider_ids: HashSet<usize>,
}
impl<Prof: EngineProfile> Default for SinkInput<Prof> {
@@ -971,7 +974,8 @@ impl<Prof: EngineProfile> Default for SinkInput<Prof> {
actions: Vec::new(),
factory_children: Vec::new(),
pending_children: Vec::new(),
- provider_depth: usize::MAX,
+ providers: Vec::new(),
+ provider_ids: HashSet::new(),
}
}
}
@@ -986,7 +990,12 @@ impl<Prof: EngineProfile> SinkInput<Prof> {
action: Prof::TargetAction,
child: Option<(TargetStateProvider<Prof>, ChildHandling)>,
) -> Result<()> {
- self.provider_depth = self.provider_depth.min(provider.depth());
+ if self
+ .provider_ids
+ .insert(Arc::as_ptr(&provider.inner) as usize)
+ {
+ self.providers.push(provider.clone());
+ }
let child_slot = match child {
None => None,
Some((child_provider, ChildHandling::Factory)) => {
@@ -1014,11 +1023,35 @@ impl<Prof: EngineProfile> SinkInput<Prof> {
}
}
+/// The names of `providers` for an error message, a few of them when there
+/// are many: a sink shared by many providers gets the actions of all.
+fn provider_names<'a, Prof: EngineProfile>(
+ providers: impl ExactSizeIterator<Item = &'a TargetStateProvider<Prof>>,
+) -> String {
+ const NAMED: usize = 5;
+ let total = providers.len();
+ let mut names: Vec<String> = providers
+ .take(NAMED)
+ .map(|provider| provider.display_name())
+ .collect();
+ if total > NAMED {
+ names.push(format!("and {} more", total - NAMED));
+ }
+ names.join(", ")
+}
+
/// A component's sinks in the order they apply: those of shallower providers
/// first, so a container's sink (a table) applies before the sink of the
/// target states inside it (its rows), and those before the sinks of their
/// provider's attachments (an index over the rows, which may need the rows
-/// to build). Sinks at one depth keep no particular order.
+/// to build). Sinks at one depth apply in the order of their providers'
+/// stable keys from the root provider down (e.g. table `a` before table `b`),
+/// so the order between providers is the same on every run. Two sinks fed by
+/// one provider (a handler that routes some of its target states to each)
+/// share a key and keep no particular order between them, which can differ
+/// from run to run and between a preview and the update after it. A sink fed
+/// by providers at several depths is placed by the shallowest of them, so
+/// such a sink must not depend on another provider's sink at a deeper level.
#[allow(
clippy::mutable_key_type,
reason = "`TargetActionSinkKeeper` hashes and compares by `Arc` identity"
@@ -1027,7 +1060,17 @@ fn sinks_in_apply_order<Prof: EngineProfile>(
actions_by_sinks: HashMap<TargetActionSinkKeeper<Prof>, SinkInput<Prof>>,
) -> Vec<(TargetActionSinkKeeper<Prof>, SinkInput<Prof>)> {
let mut sinks: Vec<_> = actions_by_sinks.into_iter().collect();
- sinks.sort_by_key(|(_, input)| input.provider_depth);
+ // Where a sink applies: by the depth of a provider that sent it actions,
+ // then by that provider's stable keys from the root provider down; a sink
+ // fed by several providers takes the first of them. A sink with no action
+ // is never queued; `None` would sort first.
+ sinks.sort_by_cached_key(|(_, input)| {
+ input
+ .providers
+ .iter()
+ .map(|p| (p.depth(), p.stable_key_chain()))
+ .min()
+ });
sinks
}
@@ -1058,14 +1101,14 @@ async fn build_factory_children<Prof: EngineProfile>(
.child_handlers(host_runtime_ctx, Arc::clone(comp_ctx.host_ctx()), &actions)
.await
.with_context(|| {
- let paths: Vec<String> = input
- .factory_children
- .iter()
- .map(|(child_provider, _)| child_provider.display_name())
- .collect();
format!(
"failed to build the child handlers for target states {}",
- paths.join(", ")
+ provider_names(
+ input
+ .factory_children
+ .iter()
+ .map(|(child_provider, _)| child_provider)
+ )
)
})?;
if handlers.len() != actions.len() {
@@ -2263,10 +2306,13 @@ pub(crate) async fn submit<Prof: EngineProfile>(
child_provider.fulfill_handler(handler, registry)?;
}
}
+ // The plan lists a component's actions in the order an update applies
+ // them (up to the order among sinks that share a key; see
+ // `sinks_in_apply_order`).
collector.lock().unwrap().extend(
- actions_by_sinks
- .into_values()
- .flat_map(|input| input.actions.into_iter().map(|(action, _)| action)),
+ sinks_in_apply_order(actions_by_sinks)
+ .into_iter()
+ .flat_map(|(_, input)| input.actions.into_iter().map(|(action, _)| action)),
);
return Ok(SubmitOutput {
built_target_states_providers,
@@ -2284,12 +2330,20 @@ pub(crate) async fn submit<Prof: EngineProfile>(
pending_fulfillments.extend(build_factory_children(comp_ctx, &actions_by_sinks).await?);
let host_runtime_ctx = comp_ctx.app_ctx().env().host_runtime_ctx();
for (sink, input) in sinks_in_apply_order(actions_by_sinks) {
+ // Connectors report what failed (`postgres: ...`), not which
+ // target: name the target states here, once for every connector.
sink.apply(
host_runtime_ctx,
Arc::clone(comp_ctx.host_ctx()),
input.actions,
)
- .await?;
+ .await
+ .with_context(|| {
+ format!(
+ "failed to apply changes to target states under {}",
+ provider_names(input.providers.iter())
+ )
+ })?;
for (child_provider, slot) in input.pending_children {
let Some(handler) = slot.take()? else {
client_bail!(
diff --git a/rust/py_utils/src/error.rs b/rust/py_utils/src/error.rs
index dcb5c7fd..cbb2fff7 100644
--- a/rust/py_utils/src/error.rs
+++ b/rust/py_utils/src/error.rs
@@ -91,7 +91,9 @@ impl cocoindex_utils::error::HostError for HostedPyErr {
/// Convert an engine error into the Python exception surfaced to callers.
///
/// Tunneled Python exceptions (`HostedPyErr`) pass through as the original
-/// object, including type, traceback and `__cause__`. Engine-native errors
+/// object, including type, traceback and `__cause__`, with the engine's
+/// context layers (e.g. which target states a failed sink was applying) added
+/// as notes (`__notes__`, see [`add_context_notes`]). Engine-native errors
/// map to `asyncio.CancelledError` / `DeadlineExceededError` / `ValueError`
/// (client; `AlreadyDeclaredError` for a second declaration within one run) /
/// `RuntimeError` (internal).
@@ -104,11 +106,17 @@ pub fn cerror_to_pyerr(err: CError) -> PyErr {
// too: don't synthesize a fresh one from the cancellation branch
// below; return the original.
let any: &dyn Any = host_err.as_ref();
- if let Some(hosted_py_err) = any.downcast_ref::<HostedPyErr>() {
- return Python::attach(|py| hosted_py_err.0.clone_ref(py));
- }
- if let Some(py_err) = any.downcast_ref::<PyErr>() {
- return Python::attach(|py| py_err.clone_ref(py));
+ let py_err = if let Some(hosted_py_err) = any.downcast_ref::<HostedPyErr>() {
+ Some(&hosted_py_err.0)
+ } else {
+ any.downcast_ref::<PyErr>()
+ };
+ if let Some(py_err) = py_err {
+ return Python::attach(|py| {
+ let py_err = py_err.clone_ref(py);
+ add_context_notes(py, &py_err, &err);
+ py_err
+ });
}
}
// Cancellation-flavored errors that aren't tunneled Python exceptions
@@ -141,6 +149,51 @@ pub fn cerror_to_pyerr(err: CError) -> PyErr {
PyRuntimeError::new_err(format!("{}", err))
}
+/// Add each context layer of `err`, outermost first, to the passed-through
+/// exception `py_err` as a note, so the Python traceback shows what the engine
+/// was doing (the message of an engine-native error carries its contexts
+/// already). The exception object is shared by every conversion of the same
+/// error (a component's result reaches every awaiter, and may cross into
+/// Python more than once), so a note it carries already is not added again.
+/// Best effort: a failure to add a note leaves the exception as it is.
+fn add_context_notes(py: Python<'_>, py_err: &PyErr, err: &CError) {
+ // A cancellation or a deadline is fanned out to every recipient of a
+ // batch as one shared exception object; a note naming one recipient's
+ // targets would mislead the others.
+ if err.is_cancelled() || err.is_deadline_exceeded() {
+ return;
+ }
+ let mut contexts = Vec::new();
+ let mut current = err;
+ while let CError::Context { msg, source } = current {
+ contexts.push(msg.as_str());
+ current = source.inner();
+ }
+ if contexts.is_empty() {
+ return;
+ }
+ let exc = py_err.value(py);
+ // `__notes__` may hold non-str entries (PEP 678 allows them); keep the
+ // str ones, and what this call appends, to add each note once however
+ // often the error crosses into Python.
+ let mut existing: Vec<String> = exc
+ .getattr("__notes__")
+ .ok()
+ .and_then(|notes| notes.try_iter().ok())
+ .map(|notes| {
+ notes
+ .filter_map(|note| note.ok()?.extract::<String>().ok())
+ .collect()
+ })
+ .unwrap_or_default();
+ for context in contexts {
+ if !existing.iter().any(|note| note == context) {
+ let _ = exc.call_method1("add_note", (context,));
+ existing.push(context.to_owned());
+ }
+ }
+}
+
pub fn add_error_classes(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add(
"DeadlineExceededError",
diff --git a/rust/sdk/cocoindex/src/error.rs b/rust/sdk/cocoindex/src/error.rs
index f4404027..ac2584ea 100644
--- a/rust/sdk/cocoindex/src/error.rs
+++ b/rust/sdk/cocoindex/src/error.rs
@@ -139,22 +139,64 @@ impl From<cocoindex_utils::error::Error> for Error {
if e.is_deadline_exceeded() {
return Error::DeadlineExceeded;
}
- match e {
+ // The engine wraps a sink's error in a context naming the target
+ // states; the variant to keep is the one under every context layer.
+ // An `Engine` error is its message, so the context stays in it. Any
+ // other variant comes back as the original value, without the
+ // context: the exception-handlers doc promises `Error::user(..)`
+ // arrives as `Error::User(inner)` with `inner.downcast_ref` working,
+ // and a wrapper carrying the context would break that.
+ let message = e.to_string();
+ let had_context = matches!(e, cocoindex_utils::error::Error::Context { .. });
+ match e.into_without_contexts() {
cocoindex_utils::error::Error::HostLang(host) => {
- let message = host.to_string();
let host: Box<dyn Any + Send + Sync> = host;
match host.downcast::<SdkHostError>() {
// The original error, unless another awaiter still shares it.
- Ok(sdk) => Arc::try_unwrap(sdk.0).unwrap_or(Error::Engine(message)),
+ // An `Engine` error is its message, so that one carries the
+ // context; another variant is kept as itself.
+ Ok(sdk) => match Arc::try_unwrap(sdk.0) {
+ Ok(Error::Engine(_)) if had_context => Error::Engine(message),
+ Ok(original) => original,
+ Err(_) => Error::Engine(message),
+ },
Err(_) => Error::Engine(message),
}
}
other => match other.client_kind() {
Some(cocoindex_utils::error::ClientErrorKind::AlreadyDeclared) => {
- Error::AlreadyDeclared(format!("{other}"))
+ Error::AlreadyDeclared(message)
}
- _ => Error::Engine(format!("{other}")),
+ _ => Error::Engine(message),
},
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cocoindex_utils::error::ContextExt;
+
+ #[derive(Debug, thiserror::Error)]
+ #[error("the orders table is gone")]
+ struct TableGone;
+
+ /// The engine wraps a sink's error in a context that names the target
+ /// states; the SDK error under it comes back as itself, by variant and
+ /// downcastable. The context text stays on the core error (and on an
+ /// `Engine` error's message); a `User` error keeps its value instead.
+ #[test]
+ fn an_sdk_error_keeps_its_variant_under_an_engine_context() {
+ let core: std::result::Result<(), cocoindex_utils::error::Error> =
+ Err(Error::user(TableGone).into_core());
+ let core = core
+ .with_context(|| "failed to apply changes to target states under @orders")
+ .unwrap_err();
+ assert!(core.to_string().contains("@orders"), "{core}");
+ match Error::from(core) {
+ Error::User(user) => assert!(user.downcast_ref::<TableGone>().is_some()),
+ other => panic!("the variant was lost: {other:?}"),
+ }
+ }
+}
diff --git a/rust/utils/src/error.rs b/rust/utils/src/error.rs
index ca36ab2a..f34952c3 100644
--- a/rust/utils/src/error.rs
+++ b/rust/utils/src/error.rs
@@ -205,6 +205,15 @@ impl Error {
}
}
+ /// The innermost error, by value: the error under every context layer,
+ /// for a conversion that needs to own it (a host error to downcast).
+ pub fn into_without_contexts(self) -> Error {
+ match self {
+ Error::Context { source, .. } => source.0.into_without_contexts(),
+ other => other,
+ }
+ }
+
/// Check if this error represents a cancellation (e.g. Python `CancelledError`).
pub fn is_cancelled(&self) -> bool {
let inner = self.without_contexts();