This is an automated email from the ASF dual-hosted git repository.

tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git


The following commit(s) were added to refs/heads/main by this push:
     new 69be48a2 [FEAT] Enrich structural traversal errors through root type 
hooks (#889)
69be48a2 is described below

commit 69be48a2931505255733bfc5a18d6e0e5cc1a033
Author: Tianqi Chen <[email protected]>
AuthorDate: Sat Oct 31 13:33:26 2026 -0400

    [FEAT] Enrich structural traversal errors through root type hooks (#889)
---
 .github/actions/build-wheel-for-publish/action.yml |  2 +-
 .github/workflows/ci_mainline_only.yml             |  4 +-
 .github/workflows/ci_test.yml                      |  4 +-
 .github/workflows/publish_crates.yml               |  2 +-
 .github/workflows/publish_orcjit_wheel.yml         |  2 +-
 .github/workflows/publish_wheel.yml                |  2 +-
 .github/workflows/torch_c_dlpack.yml               |  2 +-
 include/tvm/ffi/extra/dataclass.h                  |  1 +
 include/tvm/ffi/extra/structural_mutate.h          | 16 +++-
 include/tvm/ffi/extra/structural_visit.h           | 20 ++++-
 include/tvm/ffi/extra/visit_error_context.h        | 52 +++++++++++++
 python/tvm_ffi/dataclasses/py_class.py             |  1 +
 python/tvm_ffi/structural.py                       | 32 ++++++++
 src/ffi/extra/structural_mutate.cc                 | 16 +++-
 src/ffi/extra/structural_visit.cc                  | 30 +++++++-
 src/ffi/extra/visit_error_context.cc               | 89 +++++++++-------------
 tests/cpp/extra/test_visit_error_context.cc        | 10 +++
 tests/python/test_structural.py                    | 89 ++++++++++++++++++++++
 18 files changed, 301 insertions(+), 73 deletions(-)

diff --git a/.github/actions/build-wheel-for-publish/action.yml 
b/.github/actions/build-wheel-for-publish/action.yml
index 04b98cde..3ac2cc22 100644
--- a/.github/actions/build-wheel-for-publish/action.yml
+++ b/.github/actions/build-wheel-for-publish/action.yml
@@ -22,7 +22,7 @@ description: >
 
 inputs:
   os:
-    description: "Runner operating system (e.g., ubuntu-latest, macos-14, 
windows-latest)"
+    description: "Runner operating system (e.g., ubuntu-latest, macos-latest, 
windows-latest)"
     required: true
   arch:
     description: "Target architecture for cibuildwheel (e.g., x86_64, aarch64, 
arm64, AMD64)"
diff --git a/.github/workflows/ci_mainline_only.yml 
b/.github/workflows/ci_mainline_only.yml
index c919e9da..fca697d2 100644
--- a/.github/workflows/ci_mainline_only.yml
+++ b/.github/workflows/ci_mainline_only.yml
@@ -72,7 +72,7 @@ jobs:
           - {os: ubuntu-latest, arch: x86_64, linux_image: manylinux_2_28, 
build_sdist: "true"}
           - {os: ubuntu-24.04-arm, arch: aarch64, linux_image: manylinux_2_28, 
build_sdist: "false"}
           - {os: windows-latest, arch: AMD64, linux_image: "", build_sdist: 
"false"}
-          - {os: macos-14, arch: arm64, linux_image: "", build_sdist: "false"}
+          - {os: macos-latest, arch: arm64, linux_image: "", build_sdist: 
"false"}
 
     steps:
       - name: Checkout repository (for local composite action)
@@ -98,7 +98,7 @@ jobs:
       matrix:
         include:
           - {os: ubuntu-latest, python_version: "3.14"}
-          - {os: macos-14, python_version: "3.13"}
+          - {os: macos-latest, python_version: "3.13"}
           - {os: windows-latest, python_version: "3.12"}
     steps:
       - uses: actions/checkout@v5
diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml
index 32d994eb..67712295 100644
--- a/.github/workflows/ci_test.yml
+++ b/.github/workflows/ci_test.yml
@@ -134,7 +134,7 @@ jobs:
           - {os: ubuntu-latest, arch: x86_64, python_version: '3.14t'}
           - {os: ubuntu-24.04-arm, arch: aarch64, python_version: '3.14'}
           - {os: windows-latest, arch: AMD64, python_version: '3.9'}
-          - {os: macos-14, arch: arm64, python_version: '3.13'}
+          - {os: macos-latest, arch: arm64, python_version: '3.13'}
 
     steps:
       - uses: actions/checkout@v5
@@ -243,7 +243,7 @@ jobs:
         include:
           - {os: ubuntu-latest, arch: x86_64, build: "cp312-manylinux_x86_64"}
           - {os: ubuntu-24.04-arm, arch: aarch64, build: 
"cp312-manylinux_aarch64"}
-          - {os: macos-14, arch: arm64, build: "cp312-macosx_arm64"}
+          - {os: macos-latest, arch: arm64, build: "cp312-macosx_arm64"}
           - {os: windows-latest, arch: AMD64, build: "cp312-win_amd64"}
           - {os: windows-11-vs2026-arm, arch: ARM64, build: "cp312-win_arm64"}
 
diff --git a/.github/workflows/publish_crates.yml 
b/.github/workflows/publish_crates.yml
index a8f0afff..d09785de 100644
--- a/.github/workflows/publish_crates.yml
+++ b/.github/workflows/publish_crates.yml
@@ -53,7 +53,7 @@ jobs:
           - {os: ubuntu-latest, arch: x86_64}
           - {os: ubuntu-24.04-arm, arch: aarch64}
           - {os: windows-latest, arch: AMD64}
-          - {os: macos-14, arch: arm64}
+          - {os: macos-latest, arch: arm64}
 
     steps:
       - name: Check out release source
diff --git a/.github/workflows/publish_orcjit_wheel.yml 
b/.github/workflows/publish_orcjit_wheel.yml
index 04721a12..cc6babcc 100644
--- a/.github/workflows/publish_orcjit_wheel.yml
+++ b/.github/workflows/publish_orcjit_wheel.yml
@@ -34,7 +34,7 @@ jobs:
         include:
           - {os: ubuntu-latest, arch: x86_64, build: "cp312-manylinux_x86_64"}
           - {os: ubuntu-24.04-arm, arch: aarch64, build: 
"cp312-manylinux_aarch64"}
-          - {os: macos-14, arch: arm64, build: "cp312-macosx_arm64"}
+          - {os: macos-latest, arch: arm64, build: "cp312-macosx_arm64"}
           - {os: windows-latest, arch: AMD64, build: "cp312-win_amd64"}
           - {os: windows-11-vs2026-arm, arch: ARM64, build: "cp312-win_arm64"}
 
diff --git a/.github/workflows/publish_wheel.yml 
b/.github/workflows/publish_wheel.yml
index 50ba0c1d..53481144 100644
--- a/.github/workflows/publish_wheel.yml
+++ b/.github/workflows/publish_wheel.yml
@@ -35,7 +35,7 @@ jobs:
           - {os: ubuntu-24.04-arm, arch: aarch64, linux_image: manylinux_2_28, 
build_sdist: "false"}
           - {os: windows-latest, arch: AMD64, linux_image: "", build_sdist: 
"false"}
           - {os: windows-11-arm, arch: ARM64, linux_image: "", build_sdist: 
"false"}
-          - {os: macos-14, arch: arm64, linux_image: "", build_sdist: "false"}
+          - {os: macos-latest, arch: arm64, linux_image: "", build_sdist: 
"false"}
 
     steps:
       - name: Checkout repository (for local composite action)
diff --git a/.github/workflows/torch_c_dlpack.yml 
b/.github/workflows/torch_c_dlpack.yml
index c48687a8..ebc1e0c1 100644
--- a/.github/workflows/torch_c_dlpack.yml
+++ b/.github/workflows/torch_c_dlpack.yml
@@ -99,7 +99,7 @@ jobs:
       matrix:
         arch: ["arm64"]
         python-version: ["cp39", "cp310", "cp311", "cp312", "cp313", "cp314"]
-    runs-on: macos-14
+    runs-on: macos-latest
     steps:
       - uses: actions/checkout@v5
         with:
diff --git a/include/tvm/ffi/extra/dataclass.h 
b/include/tvm/ffi/extra/dataclass.h
index c2409a97..c6a33d44 100644
--- a/include/tvm/ffi/extra/dataclass.h
+++ b/include/tvm/ffi/extra/dataclass.h
@@ -149,6 +149,7 @@ namespace type_attr {
 inline constexpr reflection::AttrKey<
     TypedFunction<String(const Object*, const 
TypedFunction<String(AnyView)>&)>>
     kRepr{"__ffi_repr__"};
+
 /*!
  * \brief Custom recursive hash hook.
  *
diff --git a/include/tvm/ffi/extra/structural_mutate.h 
b/include/tvm/ffi/extra/structural_mutate.h
index 482cdd9e..f9fceef1 100644
--- a/include/tvm/ffi/extra/structural_mutate.h
+++ b/include/tvm/ffi/extra/structural_mutate.h
@@ -1864,7 +1864,13 @@ Expected<Any> StructuralMapExpected(
   using Mutator = StructuralMapEngine<StructuralMapEngineBase, order, 
std::decay_t<Callbacks>...>;
   StructuralMutator 
mutator(make_object<Mutator>(std::forward<Callbacks>(callbacks)...));
   auto result = mutator->MutateExpected(root, InplaceMode::kAllow);
-  if (TVM_FFI_PREDICT_FALSE(result.is_err())) return 
Unexpected(std::move(result).error());
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
   UnchangedOr<Any> mapped = 
detail::AnyUnsafe::MoveFromAnyAfterCheck<UnchangedOr<Any>>(
       std::move(detail::ExpectedUnsafe::GetData(result)));
   return std::move(mapped).ValueOrUnchanged(std::move(root));
@@ -1931,7 +1937,13 @@ Expected<Any> StructuralMutateExpected(
   using Mutator = StructuralMutateEngine<StructuralMapEngineBase, 
std::decay_t<Callbacks>...>;
   StructuralMutator 
mutator(make_object<Mutator>(std::forward<Callbacks>(callbacks)...));
   auto result = mutator->MutateExpected(root, InplaceMode::kAllow);
-  if (TVM_FFI_PREDICT_FALSE(result.is_err())) return 
Unexpected(std::move(result).error());
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
   UnchangedOr<Any> mapped = 
detail::AnyUnsafe::MoveFromAnyAfterCheck<UnchangedOr<Any>>(
       std::move(detail::ExpectedUnsafe::GetData(result)));
   return std::move(mapped).ValueOrUnchanged(std::move(root));
diff --git a/include/tvm/ffi/extra/structural_visit.h 
b/include/tvm/ffi/extra/structural_visit.h
index ef8b20b7..699c0803 100644
--- a/include/tvm/ffi/extra/structural_visit.h
+++ b/include/tvm/ffi/extra/structural_visit.h
@@ -767,7 +767,15 @@ Expected<Optional<VisitInterrupt>> 
StructuralWalkExpected(AnyView root,
   static_assert(sizeof...(Callbacks) != 0, "StructuralWalk requires at least 
one callback");
   using Visitor = StructuralWalkEngine<StructuralVisitorObj, order, 
std::decay_t<Callbacks>...>;
   StructuralVisitor 
visitor(make_object<Visitor>(std::forward<Callbacks>(callbacks)...));
-  return visitor->VisitExpected(root);
+  auto result = visitor->VisitExpected(root);
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
+  return result;
 }
 
 /*!
@@ -935,7 +943,15 @@ Expected<Optional<VisitInterrupt>> 
StructuralVisitExpected(AnyView root,
   static_assert(sizeof...(Callbacks) != 0, "StructuralVisit requires at least 
one callback");
   using Engine = StructuralVisitEngine<StructuralVisitorObj, 
std::decay_t<Callbacks>...>;
   StructuralVisitor 
visitor(make_object<Engine>(std::forward<Callbacks>(callbacks)...));
-  return visitor->VisitExpected(root);
+  auto result = visitor->VisitExpected(root);
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
+  return result;
 }
 
 /*!
diff --git a/include/tvm/ffi/extra/visit_error_context.h 
b/include/tvm/ffi/extra/visit_error_context.h
index 176d8ab4..249eca50 100644
--- a/include/tvm/ffi/extra/visit_error_context.h
+++ b/include/tvm/ffi/extra/visit_error_context.h
@@ -28,13 +28,35 @@
 #include <tvm/ffi/container/list.h>
 #include <tvm/ffi/error.h>
 #include <tvm/ffi/extra/base.h>
+#include <tvm/ffi/function.h>
 #include <tvm/ffi/memory.h>
 #include <tvm/ffi/object.h>
 #include <tvm/ffi/optional.h>
 #include <tvm/ffi/reflection/access_path.h>
+#include <tvm/ffi/reflection/accessor.h>
 
 namespace tvm {
 namespace ffi {
+namespace type_attr {
+
+/*!
+ * \brief Enrich an escaping structural visit or mutation error at its root.
+ *
+ * Called once at the outer public structural-operation error boundary, after
+ * recursive traversal has collected VisitErrorContext breadcrumbs. Arguments
+ * are (error, root), where root is the original operation input. Hook lookup
+ * uses only the exact root dynamic type, without parent lookup. Recursive
+ * visitor and mutator methods only collect context; they do not invoke this 
hook.
+ *
+ * The hook returns the original or an enriched error. An absent or failing
+ * hook leaves the original error unchanged, as does an error without visit
+ * context. Successful enrichment should remove the visit context to avoid
+ * rendering it again at an enclosing boundary.
+ */
+inline constexpr reflection::AttrKey<TypedFunction<Error(Error, ObjectRef)>> 
kEnrichVisitError{
+    "__ffi_enrich_visit_error__"};
+
+}  // namespace type_attr
 
 /*!
  * \brief Object class for VisitErrorContext.
@@ -101,6 +123,36 @@ class VisitErrorContext : public ObjectRef {
     return std::nullopt;
   }
 
+  /*!
+   * \brief Invoke the exact root type's visit-error enrichment hook.
+   *
+   * Public structural operations call this once at their outer error boundary,
+   * after recursive traversal has accumulated VisitErrorContext breadcrumbs,
+   * with the original operation input as root. Recursive visitor and mutator
+   * methods collect context without calling this helper.
+   *
+   * Only errors carrying VisitErrorContext and defined object roots 
participate.
+   * Lookup uses only the exact root dynamic type's attribute entry. An absent
+   * or failing hook leaves the original error unchanged. The borrowed
+   * root avoids changing successful mutation ownership semantics.
+   */
+  TVM_FFI_COLD_CODE
+  static Error EnrichVisitError(Error error, const ObjectRef& root) noexcept {
+    if (!root.defined() || !VisitErrorContext::TryGetFromError(error)) {
+      return error;
+    }
+    // Diagnostics must not replace the original failure if the hook itself 
fails.
+    try {
+      static reflection::TypeAttrColumn column(type_attr::kEnrichVisitError);
+      if (auto hook = 
type_attr::kEnrichVisitError.ValueFrom(column[root->type_index()])) {
+        return (*hook)(error, root);
+      }
+    } catch (...) {
+      return error;
+    }
+    return error;
+  }
+
   /*! \brief Find all access paths that match the pattern specified in the
    *         VisitErrorContext.
    *  \param root The root ObjectRef to search from.
diff --git a/python/tvm_ffi/dataclasses/py_class.py 
b/python/tvm_ffi/dataclasses/py_class.py
index 4329ba42..6820e698 100644
--- a/python/tvm_ffi/dataclasses/py_class.py
+++ b/python/tvm_ffi/dataclasses/py_class.py
@@ -56,6 +56,7 @@ _STRUCTURE_KIND_MAP: dict[str | None, int] = {
 _FFI_TYPE_ATTR_NAMES: frozenset[str] = frozenset(
     {
         "__ffi_repr__",
+        "__ffi_enrich_visit_error__",
         "__ffi_hash__",
         "__ffi_eq__",
         "__ffi_compare__",
diff --git a/python/tvm_ffi/structural.py b/python/tvm_ffi/structural.py
index fc10596a..8abcd78d 100644
--- a/python/tvm_ffi/structural.py
+++ b/python/tvm_ffi/structural.py
@@ -592,6 +592,14 @@ def structural_walk(
     Deduplication can be composed with a pre-order callback whose own visited
     set returns :attr:`WalkResult.SKIP` on repeats.
 
+    At the outer error boundary, after recursive traversal collects visit
+    context, errors are offered once to the original input root type's
+    ``__ffi_enrich_visit_error__(error, root)`` hook. Only the exact root 
dynamic
+    type's attribute is used; parent types are not searched.
+    The hook receives the original input root and returns the original or
+    enriched FFI error. An absent or failing hook leaves the original error
+    unchanged. Recursive visitor/mutator methods only collect context.
+
     Parameters
     ----------
     root
@@ -687,6 +695,14 @@ def structural_visit(
     :meth:`StructuralVisitor.default_visit` for the value's registered/default
     descent. Returning without either call prunes that value's subtree.
 
+    At the outer error boundary, after recursive traversal collects visit
+    context, errors are offered once to the original input root type's
+    ``__ffi_enrich_visit_error__(error, root)`` hook. Only the exact root 
dynamic
+    type's attribute is used; parent types are not searched.
+    The hook receives the original input root and returns the original or
+    enriched FFI error. An absent or failing hook leaves the original error
+    unchanged. Recursive visitor/mutator methods only collect context.
+
     Parameters
     ----------
     root
@@ -727,6 +743,14 @@ def structural_mutate(
     use ``structural_map`` matching rules, and an unmatched value follows
     registered/default mutation.
 
+    At the outer error boundary, after recursive traversal collects visit
+    context, errors are offered once to the original input root type's
+    ``__ffi_enrich_visit_error__(error, root)`` hook. Only the exact root 
dynamic
+    type's attribute is used; parent types are not searched.
+    The hook receives the original input root and returns the original or
+    enriched FFI error. An absent or failing hook leaves the original error
+    unchanged. Recursive visitor/mutator methods only collect context.
+
     Parameters
     ----------
     root
@@ -768,6 +792,14 @@ def structural_map(
     only default descent ``D`` reads or writes the variable-remap cache. A
     graph rewrite that must preserve sharing keeps its own callback memo.
 
+    At the outer error boundary, after recursive traversal collects visit
+    context, errors are offered once to the original input root type's
+    ``__ffi_enrich_visit_error__(error, root)`` hook. Only the exact root 
dynamic
+    type's attribute is used; parent types are not searched.
+    The hook receives the original input root and returns the original or
+    enriched FFI error. An absent or failing hook leaves the original error
+    unchanged. Recursive visitor/mutator methods only collect context.
+
     Parameters
     ----------
     root
diff --git a/src/ffi/extra/structural_mutate.cc 
b/src/ffi/extra/structural_mutate.cc
index a86177ac..f133d28f 100644
--- a/src/ffi/extra/structural_mutate.cc
+++ b/src/ffi/extra/structural_mutate.cc
@@ -63,7 +63,13 @@ Expected<Any> StructuralMapExpected(
     StructuralMutator mutator(make_object<Mutator>(callbacks, 
callbacks_with_def_region_kind));
     return mutator->MutateExpected(root, InplaceMode::kAllow);
   }();
-  if (TVM_FFI_PREDICT_FALSE(result.is_err())) return 
Unexpected(std::move(result).error());
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
   UnchangedOr<Any> mapped = AnyUnsafe::MoveFromAnyAfterCheck<UnchangedOr<Any>>(
       std::move(ExpectedUnsafe::GetData(result)));
   return std::move(mapped).ValueOrUnchanged(std::move(root));
@@ -150,7 +156,13 @@ Expected<Any> StructuralMutateExpected(
   using Mutator = StructuralMutateDynEngine<StructuralMapEngineBase>;
   StructuralMutator mutator(make_object<Mutator>(callbacks));
   auto result = mutator->MutateExpected(root, InplaceMode::kAllow);
-  if (TVM_FFI_PREDICT_FALSE(result.is_err())) return 
Unexpected(std::move(result).error());
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
   UnchangedOr<Any> mapped = AnyUnsafe::MoveFromAnyAfterCheck<UnchangedOr<Any>>(
       std::move(ExpectedUnsafe::GetData(result)));
   return std::move(mapped).ValueOrUnchanged(std::move(root));
diff --git a/src/ffi/extra/structural_visit.cc 
b/src/ffi/extra/structural_visit.cc
index c19c62bc..84f218e4 100644
--- a/src/ffi/extra/structural_visit.cc
+++ b/src/ffi/extra/structural_visit.cc
@@ -77,12 +77,28 @@ Expected<Optional<VisitInterrupt>> StructuralWalkExpected(
     using Visitor =
         StructuralWalkEngine<StructuralVisitorObj, WalkOrder::kPreOrder, 
decltype(dispatch)>;
     StructuralVisitor visitor(make_object<Visitor>(std::move(dispatch)));
-    return visitor->VisitExpected(root);
+    auto result = visitor->VisitExpected(root);
+    if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+      if (auto object_root = root.as<ObjectRef>()) {
+        return Unexpected(
+            VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+      }
+      return Unexpected(std::move(result).error());
+    }
+    return result;
   } else {
     using Visitor =
         StructuralWalkEngine<StructuralVisitorObj, WalkOrder::kPostOrder, 
decltype(dispatch)>;
     StructuralVisitor visitor(make_object<Visitor>(std::move(dispatch)));
-    return visitor->VisitExpected(root);
+    auto result = visitor->VisitExpected(root);
+    if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+      if (auto object_root = root.as<ObjectRef>()) {
+        return Unexpected(
+            VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+      }
+      return Unexpected(std::move(result).error());
+    }
+    return result;
   }
 }
 
@@ -107,7 +123,15 @@ Expected<Optional<VisitInterrupt>> StructuralVisitExpected(
 
   using Visitor = StructuralVisitEngine<StructuralVisitorObj, 
decltype(dispatch)>;
   StructuralVisitor visitor(make_object<Visitor>(std::move(dispatch)));
-  return visitor->VisitExpected(root);
+  auto result = visitor->VisitExpected(root);
+  if (TVM_FFI_PREDICT_FALSE(result.is_err())) {
+    if (auto object_root = root.as<ObjectRef>()) {
+      return Unexpected(
+          VisitErrorContext::EnrichVisitError(std::move(result).error(), 
*object_root));
+    }
+    return Unexpected(std::move(result).error());
+  }
+  return result;
 }
 
 /*! \brief Visit entries in a sequence container. */
diff --git a/src/ffi/extra/visit_error_context.cc 
b/src/ffi/extra/visit_error_context.cc
index ee43a4ca..f57da780 100644
--- a/src/ffi/extra/visit_error_context.cc
+++ b/src/ffi/extra/visit_error_context.cc
@@ -142,82 +142,60 @@ class VisitErrorAccessPathFinder {
   };
 
   void VisitAny(Any value) {
-    // Skip null Any silently — error-path defensive.
-    if (value == nullptr) return;
-    const int32_t type_index = value.type_index();
-    if (type_index < TypeIndex::kTVMFFIStaticObjectBegin) {
-      // Primitive — cannot hold an ObjectRef chain entry.
-      return;
-    }
-    switch (type_index) {
-      case TypeIndex::kTVMFFIArray:
-        
this->VisitSequence(detail::AnyUnsafe::MoveFromAnyAfterCheck<Array<Any>>(std::move(value)));
-        break;
-      case TypeIndex::kTVMFFIList:
-        
this->VisitSequence(detail::AnyUnsafe::MoveFromAnyAfterCheck<List<Any>>(std::move(value)));
-        break;
-      case TypeIndex::kTVMFFIMap:
-        this->VisitMap(detail::AnyUnsafe::MoveFromAnyAfterCheck<Map<Any, 
Any>>(std::move(value)));
-        break;
-      case TypeIndex::kTVMFFIDict:
-        this->VisitMap(detail::AnyUnsafe::MoveFromAnyAfterCheck<Dict<Any, 
Any>>(std::move(value)));
-        break;
-      default:
-        if (type_index >= TypeIndex::kTVMFFIStaticObjectBegin) {
-          ObjectRef obj = 
detail::AnyUnsafe::MoveFromAnyAfterCheck<ObjectRef>(std::move(value));
-          this->VisitObject(obj);
-        }
-        break;
+    if (value.type_index() >= TypeIndex::kTVMFFIStaticObjectBegin) {
+      
this->VisitObject(detail::AnyUnsafe::MoveFromAnyAfterCheck<ObjectRef>(std::move(value)));
     }
   }
 
   void VisitObject(const ObjectRef& node) {
-    // Defensive: error path; never throw.
     if (!node.defined()) return;
-    const TVMFFITypeInfo* type_info = TVMFFIGetTypeInfo(node->type_index());
-    if (type_info == nullptr || type_info->metadata == nullptr) return;
-
     bool matched_step = num_pattern_step_matched_ < records_.size() &&
                         node.same_as(records_[records_.size() - 1 - 
num_pattern_step_matched_]);
     if (matched_step) {
       ++num_pattern_step_matched_;
       if (num_pattern_step_matched_ == records_.size()) {
-        // Full match — materialize the AccessPath and record.
         results_.push_back(this->MaterializeAccessPath());
         --num_pattern_step_matched_;
         return;
       }
     }
 
-    this->VisitChildrenFields(node, type_info);
-
-    if (matched_step) --num_pattern_step_matched_;
-  }
-
-  void VisitChildrenFields(ObjectRef node, const TVMFFITypeInfo* type_info) {
-    // Snapshot results_.size() before descent to detect any inner full or
-    // prefix match recorded by a deeper call. If results_ grew, some inner
-    // node was recorded — we do not record again here.
+    // Containers are breadcrumb anchors too, even though their children use
+    // item steps rather than reflected fields. Sparse patterns may omit them.
     size_t results_before = results_.size();
-    reflection::ForEachFieldInfo(type_info, [&](const TVMFFIFieldInfo* 
field_info) {
-      reflection::FieldGetter getter(field_info);
-      Any child_val = getter(node);
-      this->PushStep(TempAccessStep::Attr(field_info));
-      this->VisitAny(std::move(child_val));
-      this->PopStep();
-    });
+    switch (node->type_index()) {
+      case TypeIndex::kTVMFFIArray:
+        this->VisitSequence(node.as_or_throw<Array<Any>>());
+        break;
+      case TypeIndex::kTVMFFIList:
+        this->VisitSequence(node.as_or_throw<List<Any>>());
+        break;
+      case TypeIndex::kTVMFFIMap:
+        this->VisitMap(node.as_or_throw<Map<Any, Any>>());
+        break;
+      case TypeIndex::kTVMFFIDict:
+        this->VisitMap(node.as_or_throw<Dict<Any, Any>>());
+        break;
+      default: {
+        const TVMFFITypeInfo* type_info = 
TVMFFIGetTypeInfo(node->type_index());
+        if (type_info != nullptr && type_info->metadata != nullptr) {
+          reflection::ForEachFieldInfo(type_info, [&](const TVMFFIFieldInfo* 
field_info) {
+            reflection::FieldGetter getter(field_info);
+            this->PushStep(TempAccessStep::Attr(field_info));
+            this->VisitAny(getter(node));
+            this->PopStep();
+          });
+        }
+      }
+    }
 
-    // Leaf-with-prefix-match: this node contributed a match step, but no
-    // inner result was recorded from its subtree. Record the current node's
-    // path as the best-effort prefix. path_steps_ reflects the path TO this
-    // node (the step leading here was pushed by our caller), so
-    // MaterializeAccessPath() yields the correct prefix path.
-    // Skip when path_steps_ is empty — AccessPath::Root() gives no useful 
info.
-    if (allow_prefix_match_ && num_pattern_step_matched_ > 0 &&
-        num_pattern_step_matched_ < records_.size() && !path_steps_.empty() &&
+    // Only an actual matched anchor can be a partial result. Unrelated leaves
+    // under an earlier matched ancestor do not identify the failing subtree.
+    if (allow_prefix_match_ && matched_step && !path_steps_.empty() &&
         results_.size() == results_before) {
       results_.push_back(this->MaterializeAccessPath());
     }
+    if (matched_step) --num_pattern_step_matched_;
   }
 
   template <typename SeqType>
@@ -319,6 +297,7 @@ Array<reflection::AccessPath> 
VisitErrorContext::FindAccessPaths(
 
 TVM_FFI_STATIC_INIT_BLOCK() {
   namespace refl = tvm::ffi::reflection;
+  refl::EnsureTypeAttrColumn(type_attr::kEnrichVisitError);
   refl::ObjectDef<VisitErrorContextObj>()
       .def_ro("reverse_visit_pattern", 
&VisitErrorContextObj::reverse_visit_pattern)
       .def_ro("prev_error_context", &VisitErrorContextObj::prev_error_context);
diff --git a/tests/cpp/extra/test_visit_error_context.cc 
b/tests/cpp/extra/test_visit_error_context.cc
index 5ea7f169..e10b9b81 100644
--- a/tests/cpp/extra/test_visit_error_context.cc
+++ b/tests/cpp/extra/test_visit_error_context.cc
@@ -649,4 +649,14 @@ TEST(VisitErrorContext, TryGetFromError) {
   EXPECT_TRUE(StructuralEqual::Equal(expected, paths[0]));
 }
 
+TEST(VisitErrorContext, EnrichmentLeavesContextFreeErrorsUnchanged) {
+  Error original("ValueError", "plain failure", "trace");
+  Array<ObjectRef> root;
+  EXPECT_TRUE(VisitErrorContext::EnrichVisitError(original, 
root).same_as(original));
+  auto contextual = Error("ValueError", "contextual failure", "trace");
+  detail::UpdateVisitErrorContext(contextual, root);
+  EXPECT_TRUE(VisitErrorContext::EnrichVisitError(contextual, 
root).same_as(contextual));
+  EXPECT_TRUE(VisitErrorContext::EnrichVisitError(contextual, 
ObjectRef()).same_as(contextual));
+}
+
 }  // namespace
diff --git a/tests/python/test_structural.py b/tests/python/test_structural.py
index 197b5157..f5fbaa0e 100644
--- a/tests/python/test_structural.py
+++ b/tests/python/test_structural.py
@@ -787,3 +787,92 @@ def 
test_structural_map_handles_inline_and_heap_strings_and_bytes() -> None:
         root = tvm_ffi.Array(values)
         replaced = tvm_ffi.structural_map(root, [(str, len), (bytes, len)], 
order=order)
         assert list(replaced) == [1, 7, 8, 7, 8]
+
+
+def test_structural_walk_error_array_paths() -> None:
+    @py_class(structural_eq="tree")
+    class ErrorLeaf(Object):
+        value: int
+
+    @py_class(structural_eq="tree")
+    class ErrorRoot(Object):
+        child: Any
+        unrelated: Any
+
+    leaf = ErrorLeaf(1)
+    children = tvm_ffi.Array([leaf])
+    root = ErrorRoot(children, ErrorLeaf(2))
+
+    def fail(*args: Any) -> None:
+        raise ValueError("container callback failure")
+
+    with pytest.raises(ValueError, match="container callback failure") as 
caught:
+        tvm_ffi.structural_walk(root, (ErrorLeaf, fail))
+    context = getattr(caught.value, "__tvm_ffi_error__").extra_context
+    find = tvm_ffi.get_global_func("ffi.VisitErrorContext.FindAccessPaths")
+    assert [str(path) for path in find(root, context, False)] == 
["<root>.child[0]"]
+    assert [str(path) for path in find(root, context, True)] == 
["<root>.child[0]"]
+
+
[email protected]("operation", ["walk", "visit", "map", "mutate"])
+def test_structural_error_exact_type_enrichment(operation: str) -> None:
+    calls: list[tuple[Any, Any]] = []
+
+    @py_class(f"test.EnrichBase.{operation}", structural_eq="tree")
+    class EnrichBase(Object):
+        child: Any
+
+        @staticmethod
+        def __ffi_enrich_visit_error__(error: Any, root: Any) -> Any:
+            calls.append((error, root))
+            return tvm_ffi.core.Error(
+                error.kind, error.message + " [root location]", error.backtrace
+            )
+
+    @py_class(f"test.EnrichDerived.{operation}", structural_eq="tree")
+    class EnrichDerived(EnrichBase):
+        tag: int
+
+    @py_class(f"test.EnrichRegistered.{operation}", structural_eq="tree")
+    class EnrichRegistered(EnrichDerived):
+        __ffi_enrich_visit_error__ = 
staticmethod(EnrichBase.__ffi_enrich_visit_error__)
+
+    root = EnrichRegistered(EnrichBase(tvm_ffi.Array([1])), 0)
+
+    def fail(*args: Any) -> None:
+        raise ValueError("callback failure")
+
+    with pytest.raises(ValueError, match=r"callback failure \[root 
location\]") as caught:
+        getattr(tvm_ffi, "structural_" + operation)(root, (int, fail))
+    assert len(calls) == 1
+    original, hook_root = calls[0]
+    assert hook_root.same_as(root)
+    assert original.kind == "ValueError"
+    assert original.message == "callback failure"
+    assert original.extra_context is not None
+    enriched = getattr(caught.value, "__tvm_ffi_error__")
+    assert enriched.extra_context is None
+    assert enriched.backtrace == original.backtrace
+
+    calls.clear()
+    for no_hook_root in (EnrichDerived(root.child, 0), 1):
+        with pytest.raises(ValueError, match=r"^callback failure$"):
+            getattr(tvm_ffi, "structural_" + operation)(no_hook_root, (int, 
fail))
+        assert not calls
+
+
+def test_structural_error_enrichment_failure_preserves_error() -> None:
+    @py_class(structural_eq="tree")
+    class BrokenEnricher(Object):
+        value: int
+
+        @staticmethod
+        def __ffi_enrich_visit_error__(error: Any, root: Any) -> Any:
+            raise RuntimeError("broken diagnostic")
+
+    def fail(value: int) -> None:
+        raise ValueError("original failure")
+
+    with pytest.raises(ValueError, match=r"^original failure$") as caught:
+        tvm_ffi.structural_walk(BrokenEnricher(1), (int, fail))
+    assert getattr(caught.value, "__tvm_ffi_error__").extra_context is not None

Reply via email to