Skip to content

Conversation

@khj809
Copy link

@khj809 khj809 commented Dec 17, 2025

This PR introduces a Rust implementation of the Array container.

Key Features

  • Memory Safety: Correctly handles reference counting for ObjectRef elements. It ensures inc_ref is called during retrieval (get) and dec_ref is called when elements are removed or the array is cleared.
  • Dynamic Mutation: Implements push, pop, insert, remove, and clear. It handles internal growth and reallocation while maintaining compatibility with the underlying C++ memory layout.
  • FFI Compatibility: Explicitly manages the data pointer within ArrayObj to allow C++ TVM functions to traverse the array using standard pointer arithmetic.
  • Type System Integration:
    • Implements AnyCompatible, allowing Array<T> to be erased into Any and AnyView and recovered via TryFrom.
    • Implements FromIterator and Extend, enabling seamless integration with Rust's iterator ecosystem.

Tests

Verified with a comprehensive test suite in tvm-ffi/tests/test_array.rs covering:

  • Basic creation and iteration.
  • Out-of-bounds safety.
  • Dynamic growth and reallocation (push/insert).
  • Memory integrity after element shifting (remove/insert).
  • Roundtrip conversions through Any and AnyView.
  • Parametric support for both Tensor and Shape types.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @khj809, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request delivers a robust and memory-safe Rust binding for the Array<T> container, crucial for managing collections of TVM objects. It focuses on providing dynamic array functionalities while ensuring compatibility with the existing C++ FFI memory model and integrating smoothly with Rust's type system and iterator patterns. The changes enable more idiomatic Rust usage for array-like structures within the TVM framework.

Highlights

  • New Rust Array Binding: Introduces a new Rust implementation of the Array container, designed for interoperability within the TVM FFI ecosystem.
  • Memory Safety and Reference Counting: The Array implementation correctly handles reference counting for ObjectRef elements, ensuring inc_ref is called on retrieval and dec_ref on removal or clearing, preventing memory leaks or double-frees.
  • Dynamic Mutation Operations: Provides a full suite of dynamic mutation methods including push, pop, insert, remove, and clear, with internal logic for growth and reallocation while maintaining compatibility with the underlying C++ memory layout.
  • FFI Compatibility: Explicitly manages the data pointer within ArrayObj to allow C++ TVM functions to traverse the array using standard pointer arithmetic, ensuring seamless integration across language boundaries.
  • Rust Type System Integration: Implements AnyCompatible for Array<T>, enabling conversion to and from Any and AnyView. It also supports Rust's iterator ecosystem through FromIterator and Extend traits.
  • Comprehensive Test Coverage: A new test suite (test_array.rs) has been added to verify basic creation, iteration, out-of-bounds safety, dynamic growth, memory integrity, roundtrip conversions, and parametric support for various ObjectRefCore types like Tensor and Shape.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a Rust binding for the Array<T> container, a fundamental component for TVM's FFI. The implementation includes core functionalities like dynamic mutation and integration with Rust's type system. However, the review has uncovered several critical issues concerning memory safety and correctness, primarily within the unsafe blocks. Specifically, there's a missing Drop implementation for ArrayObj which will cause memory leaks. The mutable methods lack copy-on-write (COW) semantics, leading to potentially unsound shared state mutation. Furthermore, the type casting logic is flawed, permitting unsafe casts between different Array specializations. I have also provided suggestions for performance improvements and API consistency. These critical issues should be addressed to ensure the implementation is safe and robust.

@junrushao
Copy link
Member

junrushao commented Dec 17, 2025

Nice work! Likely we will need Apache license headers on each file :)

ERROR: Missing ASF header in rust/tvm-ffi/src/collections/array.rs
Run `python tests/lint/check_asf_header.py --fix` to add the header
ERROR: Missing ASF header in rust/tvm-ffi/tests/test_array.rs
Run `python tests/lint/check_asf_header.py --fix` to add the header

@khj809
Copy link
Author

khj809 commented Dec 18, 2025

@junrushao Thanks. I added it :)

@junrushao
Copy link
Member

Looks like there's a test failure:

---- test_array_parametric_heterogeneity stdout ----

thread 'test_array_parametric_heterogeneity' (10146) panicked at tvm-ffi/tests/test_array.rs:145:46:
called `Result::unwrap()` on an `Err` value: Traceback (most recent call last):

  File "tvm-ffi/src/function.rs", line 190, in tvm_ffi::function::Function::get_global
RuntimeError: Function testing.echo not found
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    test_array_parametric_heterogeneity

error: test failed, to rerun pass `-p tvm-ffi --test test_array`

@khj809
Copy link
Author

khj809 commented Dec 19, 2025

@junrushao Hmm it's strange because tvm_ffi_testing target is already linked in tvm-ffi-sys crate, and testing.echo is already used in test_function.rs too. Is there anything I've missed to enable testing functions during cargo test?

@khj809
Copy link
Author

khj809 commented Dec 22, 2025

@junrushao Due to the unexpected link errors of testing functions on CI environment, I decided to use global functions which definitely exist in libtvm_ffi dylib.

@junrushao
Copy link
Member

CC @tqchen please take a look when you got time, as I'm not very experienced in Rust

@tqchen
Copy link
Member

tqchen commented Dec 22, 2025

Thanks a lot for contributions, i maybe a bit off recently but should be able to come back and take closer look around Jan. would be good to also get some eyes for rust reviews. cc @DarkSharpness @Ubospica if u have bandwidth

Some high-level feedbacks:

  • Likely we can use Index overload, so we can do array[i]
  • Avoid doing the object-type-index generic conversion in get(or index), since sometimes T can be backed by both special and Object, instead use AnyCompatible trait, which is meant to define conversion rule of T from/to any
  • Keep array immutable for now, as of now we are still discussing mutable handling, so let us keep array immutable

@khj809
Copy link
Author

khj809 commented Dec 23, 2025

@tqchen Thanks for the review.

  • About Index trait, the fn index requires to return the reference of output type, but it's technically impossible to return &T because ArrayObj does not store the buffer of T directly. Instead it's possible to return a reference of either TVMFFIAny or AnyView, so I implemented it to return &AnyView for now.
  • As you mentioned, I tried to use AnyCompatible instead of the previous ObjectRefCore. While doing this, I found the issue that Any::into_raw_ffi_any drops the data immediately and makes the array of objects having invalid data. Hence I added ManuallyDrop to prevent the destructor from running at the end of the scope.
  • As you mentioned, I removed all the mutable methods for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants