Skip to content

feat(pyo3-arrow): convert interval scalars to Python objects - #549

Merged
kylebarron merged 10 commits into
kylebarron:mainfrom
ump45nose:feat/interval-scalar-as-py
Oct 29, 2026
Merged

kylebarron merged 10 commits into
kylebarron:mainfrom
ump45nose:feat/interval-scalar-as-py

Conversation

@ump45nose

Copy link
Copy Markdown
Contributor

Closes #409.

Scalar.as_py() currently panics for every interval type (todo!("interval is not yet fully documented [ARROW-3097]")), so e.g. Array(pa.array([pa.MonthDayNano([1, 2, 3])]))[0].as_py() raises a PanicException.

This converts each interval unit to plain Python values that keep all of its components, so nothing is lost and no new Python type is needed:

  • MonthDayNano -> (months, days, nanoseconds) tuple. This compares equal to pyarrow's MonthDayNano named tuple, which is a tuple of the same three fields.
  • DayTime -> (days, milliseconds) tuple.
  • YearMonth -> int number of months.

I didn't map these to datetime.timedelta: month-based intervals can't be expressed as a timedelta, and keeping all three as their raw fields seemed more consistent. Happy to switch DayTime to a timedelta or return named tuples instead if you'd prefer.

The behavior is documented in the Scalar.as_py docstring in _scalar.pyi, and I added an entry under Unreleased in the pyo3-arrow changelog.

Testing

  • New test_as_py_month_day_nano_interval in tests/core/test_scalar.py checks positive, negative and null values and compares against pyarrow's as_py().
  • pyarrow can't build year_month or day_time arrays from Python, so I checked those two by hand by importing int32/int64 arrays through the C data interface with the tiM/tiD formats: they gave [14, -3, None] and [(5, 1500), (-1, -250), None].
  • In pyo3-arrow: cargo fmt --check and cargo clippy --all-features --tests -- -D warnings are clean. ruff format/ruff check are clean on the test file.

One note on CI: since #544 the workspace builds arro3-core against pyo3-arrow pinned at 5475f33 (with pyo3 0.29), not the local pyo3-arrow directory. To run the tests locally, I pointed the workspace at the path dependency and bumped pyo3/numpy to 0.30 (core only), then got 138 passed in tests/core (excluding the two modules that need arro3-compute). Without that change the new test hits the old todo!(), so the Python test job will likely fail on it until arro3 uses the local pyo3-arrow again. I can mark the test as skipped or drop it from this PR if you'd rather land the Rust change first.


AI disclosure: I made this change with help from an AI coding assistant (Grok Bot), which wrote the edits and the PR text. I reviewed the diff and ran the checks above locally.

`PyScalar::as_py` hit a `todo!()` for every interval type, so calling
`as_py()` on an interval scalar raised a pyo3 PanicException. Convert
each interval unit to plain Python values holding its components:

- MonthDayNano -> (months, days, nanoseconds)
- DayTime -> (days, milliseconds)
- YearMonth -> int number of months

Closes kylebarron#409

Signed-off-by: Vincent <[email protected]>
@github-actions github-actions Bot added the feat label Oct 24, 2026
CI builds arro3 against pyo3-arrow pinned at git rev 5475f33, which still
hits todo!() for interval scalars, so the new test panics there. Skip it
until the workspace moves to pyo3 0.30 and uses the in-tree pyo3-arrow.

Signed-off-by: Vincent <[email protected]>
@ump45nose

Copy link
Copy Markdown
Contributor Author

CI was failing because arro3 still builds against pyo3-arrow pinned at git rev 5475f33 (the workspace is on pyo3 0.29), so the new interval test hit the old todo!() there. I've marked that test as skipped with a reason in 792f93b, so it can be turned back on once the workspace moves to pyo3 0.30. Happy to drop the test from this PR entirely if you'd prefer.

(AI-assisted reply.)

@ump45nose

Copy link
Copy Markdown
Contributor Author

Same CI failure as on #548: docs build aborts in strict mode because DuckDB's objects.inv returns 404. Not caused by the interval scalar changes here; can rebase after that inventory is fixed.

(AI-assisted reply.)

@ump45nose

Copy link
Copy Markdown
Contributor Author

CI note: the Python workflow failure is in mkdocs build --strict, not in the pytest suite (207 passed).

Root cause looks external to this PR: mkdocstrings cannot fetch https://duckdb.org/docs/current/clients/python/reference/objects.inv (HTTP 404). Same failure mode on #548. Happy to help with a docs-inventory pin/workaround if maintainers want that tracked separately.

kylebarron and others added 2 commits October 28, 2026 15:34
Since kylebarron#552, the workspace builds arro3-core against the in-tree pyo3-arrow,
so the skip is no longer needed. Also add the PR number to the pyo3-arrow
changelog entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread tests/core/test_scalar.py Outdated
Comment on lines +82 to +93
def _import_with_format(pa_arr: pa.Array, format: bytes) -> Array:
"""Import `pa_arr` with its C schema format string replaced by `format`.

pyarrow can't create year-month or day-time interval arrays, which have the
same memory layout as int32 and int64 arrays.
"""
schema_capsule, array_capsule = pa_arr.__arrow_c_array__()
schema_ptr = _capsule_get_pointer(schema_capsule, b"arrow_schema")
format_buf = ctypes.create_string_buffer(format)
# `format` is the first field of the ArrowSchema C struct
ctypes.c_void_p.from_address(schema_ptr).value = ctypes.addressof(format_buf)
return Array.from_arrow_pycapsule(schema_capsule, array_capsule)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This looks super hacky. I don't want to do this.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note

This comment was written by Claude (Claude Code), not by @kylebarron.

Dropped that commit. day_time and year_month are now tested against nanoarrow instead (98b705a). nanoarrow builds those arrays from Python values, and its to_pylist() is the reference. It is a new dev dependency.

🤖 Written by Claude Code

pyarrow's `as_py()` returns `pyarrow.MonthDayNano`, a tuple subclass with
`months`, `days` and `nanoseconds` attributes. `arro3.core.MonthDayNano` is
a `NamedTuple` with the same fields and repr. It compares equal both to
pyarrow's value and to the plain tuple that nanoarrow returns. pyo3-arrow
imports it from `arro3.core`, like its `to_arro3` exports do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kylebarron
kylebarron force-pushed the feat/interval-scalar-as-py branch from 792d9ed to f566251 Compare October 28, 2026 20:50

- `month_day_nano` intervals become a `(months, days, nanoseconds)` tuple.
- `month_day_nano` intervals become a [`MonthDayNano`][arro3.core.MonthDayNano].
- `day_time` intervals become a `(days, milliseconds)` tuple.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

I think this should also be a named tuple

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note

This comment was written by Claude (Claude Code), not by @kylebarron.

Done in 67680ef. day_time intervals now become arro3.core.DayTime(days, milliseconds), with the field names from arrow-rs's IntervalDayTime.

🤖 Written by Claude Code

- `month_day_nano` intervals become a `(months, days, nanoseconds)` tuple.
- `month_day_nano` intervals become a [`MonthDayNano`][arro3.core.MonthDayNano].
- `day_time` intervals become a `(days, milliseconds)` tuple.
- `year_month` intervals become an `int` number of months.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Should this become (year, month)? As a named tuple?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note

This comment was written by Claude (Claude Code), not by @kylebarron.

Kept it an int. Arrow stores year_month as a single count of whole months ("the number of elapsed whole months, stored as 4-byte signed integers"). A (years, months) split has no canonical form for negative values: arrow-rs's display floors, so -3 months prints as -1 years 9 mons, while truncating would give (0, -3). nanoarrow also returns an int.

🤖 Written by Claude Code



class MonthDayNano(NamedTuple):
"""A month, day, and nanosecond interval, matching `pyarrow.MonthDayNano`.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Suggested change
"""A month, day, and nanosecond interval, matching `pyarrow.MonthDayNano`.
"""A month, day, and nanosecond interval.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note

This comment was written by Claude (Claude Code), not by @kylebarron.

Applied in ad12579.

🤖 Written by Claude Code

class MonthDayNano(NamedTuple):
"""A month, day, and nanosecond interval, matching `pyarrow.MonthDayNano`.

It compares equal to a plain `(months, days, nanoseconds)` tuple.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Suggested change
It compares equal to a plain `(months, days, nanoseconds)` tuple.

I don't think we need this; it's a named tuple so it follows named tuple rules

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note

This comment was written by Claude (Claude Code), not by @kylebarron.

Applied in ad12579. The docstring is now one line.

🤖 Written by Claude Code

kylebarron and others added 5 commits October 29, 2026 10:34
Apply review suggestions.

Co-authored-by: Kyle Barron <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`DayTime` has the same fields as arrow-rs's `IntervalDayTime`: `days` and
`milliseconds`. Like `MonthDayNano`, it compares equal to the plain tuple
that nanoarrow returns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pyarrow can't create day_time or year_month interval arrays, so add
nanoarrow as a dev dependency. It builds them from Python values, and its
`to_pylist()` is the reference. Locked with uv 0.12 so the lockfile stays
at revision 3; `uv lock --check` with uv 0.8.24 passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nanoarrow 0.9.0 hasn't declared free-threading support, so importing it
re-enables the GIL for the whole run. Importing it at module level meant
the 3.14t job ran every test with the GIL enabled. Import it in a fixture
that skips on free-threaded builds instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@kylebarron kylebarron left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

✅

@kylebarron
kylebarron merged commit 26172dc into kylebarron:main Oct 29, 2026
22 checks passed
datapointchris added a commit to datapointchris/doppeldata that referenced this pull request Nov 2, 2026
`cargo audit` fails on main. Every arrow-rs 59 crate requires zstd 0.13.
zstd 0.13 with zstd-safe 7 carries
RUSTSEC-2026-0391, RUSTSEC-2026-0398 and RUSTSEC-2026-0403. A file in
`crates/.cargo/` ignored all three until the
crates could reach arrow 60, whose zstd 0.14 and zstd-safe 8 fix them.
pyo3-arrow held the workspace on arrow 59,
because its latest crates.io release builds on it.

This moves arrow and parquet to 60.1 and zstd to 0.14, and deletes the
ignore file. pyo3-arrow comes from a pinned
commit of arro3's main branch. At that commit it requires arrow 60.1 and
pyo3 0.30, and it is not yet released.

Session: 1c7b885a-84ba-42d1-9eb8-bca920ebfabf

## What to look at

- `crates/python/Cargo.toml`: the git pin on pyo3-arrow. Check the rev
is the arro3 commit to trust until a crates.io
  release requires arrow 60.
- `crates/Cargo.lock`: zstd 0.14.3 and zstd-safe 8.2.0 should be the
only versions, with no arrow 59 crate left. atoi
  3 and comfy-table 8 arrive through arrow 60.
- `crates/core/Cargo.toml`: the comment now says pyo3-arrow's arrow
major is read from the pinned commit's manifest.
`cargo info pyo3-arrow` reports the crates.io release, which is still on
arrow 59.

## How it was verified

- `cargo audit` 0.22.2 from `crates/`, as CI runs it: exit 0, no
advisory, 322 crates scanned.
- `cargo tree -i zstd` from `crates/`: zstd v0.14.3 alone.
- `cargo test` in `crates/`: 13 passed, 1 ignored. The determinism
contract's six pins pass at stream version 18.
- pytest over `library/tests` and `cli/tests`: 92 passed.
- `task lint` and `task check-generated`: both exit 0. The extension's
stub is unchanged.
- Bytes: the every-column-kind fixture at 70,000 rows, seed 7 and one
thread, written by the extension built on the
base commit and on this one. JSON and NDJSON files, uncompressed, gzip
and zstd, are byte-identical. Parquet and
Arrow IPC files differ. Read back, their tables are equal with their
schema and metadata.
- `spark-parity/check-spark-parity.sh` on `apache/spark:4.1.3-python3`,
with a manylinux2014 wheel built from this
branch, at 1,000,000 rows and 100,000 rows per file: all 14 checks
identical. They cover `generate` and `write` at 7
and 40 partitions, the column types, the bundle and `to_spark`. The
Arrow C stream `mapInArrow` reads crosses from
  arrow-rs 60 to Spark's Arrow Java there.

## What changes

- **pyarrow 26 reads no bounds for a Parquet file's float columns.**
parquet 60 declares IEEE 754 total order on
every FLOAT and DOUBLE column. It writes their bounds only as
`min_value` and `max_value`. pyarrow 26 then reports
no min or max for those columns, and keeps every row group on a float
predicate. On the fixture,
`split_by_row_group(ds.field('fit_norm') > 1000)` keeps 1 row group,
where the arrow 59 file kept 0. DuckDB 2.0
still reads the bounds and prunes. parquet 60 has no writer setting to
declare the older order. Statistics on every
  other type are unchanged.
- **Arrow IPC files are smaller.** arrow-ipc 60 pads a record batch's
buffers differently. Each of the fixture's two
batch bodies is 7,232 bytes shorter, under zstd and lz4 alike. The
schema message, the values and the compression
  are unchanged.
- **Values hold.** The stream version stays 18. A dataset's identity and
its file names do not move.
- **`regenerate()` names every Parquet and Arrow file written before
this as moved**, as it does after any encoder
  upgrade. The values it regenerates are the same.
- **pyo3-arrow's Python classes changed between 0.20.0 and the pinned
commit. None of the changes reaches
doppeldata's own code.** The extension builds only a `Table`, from
`generate` and `sample`, and a
`RecordBatchReader`, from `stream`. It takes no Array or ChunkedArray
from Python. So the input cast
(kylebarron/arro3#570) and the `ChunkedArray([])` ValueError
(kylebarron/arro3#569) never run. The library hands
both objects to pyarrow or Polars through `__arrow_c_stream__`. That
export path changed only to follow arrow 60's
  API.
- **A caller using the returned table's own methods sees two changes.**
`Table.drop_columns` takes a single name
(kylebarron/arro3#571), and `Array.buffer` is gone
(kylebarron/arro3#568). The engine generates no interval column,
so interval scalars converting to Python objects (kylebarron/arro3#549)
reach no doppeldata output.

## Decisions, and what they rejected

- **pyo3-arrow from a git commit** — it rejected waiting for a
pyo3-arrow release on arrow 60. Nothing dates one,
  and the three advisories stayed ignored meanwhile.
- **Smallest change that would work** — this one. With only the
manifests moved, `cargo check --all-targets` and
  clippy pass with no warning, so arrow 60 forces no code change.

## Risk and rollback

A revert restores the advisory ignores and arrow 59. Files written by
either build stay readable by both, and hold
the same values. Building from the sdist fetches arro3 from GitHub at
the pinned commit, where it needed only
crates.io before.

## What this does not do

- It does not move pyo3-arrow back to a crates.io release. That waits on
one requiring arrow 60.
- It does not restore pyarrow's float row-group pruning, for which
parquet 60 offers no setting.
kylebarron added a commit that referenced this pull request Nov 4, 2026
…nges

The pyo3-arrow changelog is for crates that use pyo3-arrow to move Arrow
data between Rust and Python. Changes to the arro3 Python API that lives
in pyo3-arrow (#549, #568, #569, #570, #571) belong in arro3's release
notes instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kylebarron added a commit that referenced this pull request Nov 4, 2026
* chore: Bump pyo3-arrow to 0.21

Release with pyo3 0.30 and arrow 60.1. It's a minor bump because #551
moves to arrow 60 and #559 replaces pyo3-arrow's ArrayReader and
ArrayIterator with the arrow-rs types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(pyo3-arrow): Limit the 0.21.0 changelog to import and export changes

The pyo3-arrow changelog is for crates that use pyo3-arrow to move Arrow
data between Rust and Python. Changes to the arro3 Python API that lives
in pyo3-arrow (#549, #568, #569, #570, #571) belong in arro3's release
notes instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support converting arrow Interval scalars to Python objects

2 participants