Repository navigation
[Data] Fix write_json for non-nanosecond timestamps and durations - #68007
Conversation
On pandas < 3, DataFrame.to_json() treats non-nanosecond timestamps and durations as nanoseconds (pandas-dev/pandas#55827), so write_json wrote a timestamp[us] 2024-01-01 12:00:00 as 1704110400, which reads back as 1970. Before to_json(), cast these columns with pyarrow to integers in date_unit for epoch output, following pandas 3, so dates outside the nanosecond range such as 9999-12-31 still write. For ISO output, cast only durations to nanoseconds. orient="table" is already correct and is left alone. Both Arrow and pandas blocks are covered. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: hzmsh <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a workaround in JSONDatasink for pandas < 3, addressing an issue where non-nanosecond timestamps and durations are incorrectly written as nanoseconds. It adds a helper function _fix_non_nanosecond_columns to cast these columns to the appropriate unit before writing, along with corresponding regression tests. The review feedback suggests a more robust way to convert pandas Series to PyArrow arrays using pyarrow.Table.from_pandas to avoid potential TypeError exceptions when dealing with chunked pd.ArrowDtype columns.
|
Hi @owenowenisme, could you please take a look at this when you have time? I noticed you reviewed the recent JSON read change (#66878), and this one fixes a bug on the JSON write side. Thanks! |
rayo5o
left a comment
There was a problem hiding this comment.
Approving. The description says the fix follows pandas 3, so I used pandas 3's output as the reference and compared against it.
Setup: pandas 2.3.3 (the lock version) and pandas 3.0.6, pyarrow 26.0.0, each on the PR head (ba465e7) and the merge base (38af0c3). I called JSONDatasink.write_block_to_file on 12 small tables, each as an Arrow block, a pandas block, and an Arrow block with enable_arrow_backed_pandas_conversion=False, with 11 sets of to_json args (default, date_unit s/us/ns, date_format epoch/iso, iso with date_unit="s", orient split/columns/values/table). 396 outputs per run.
- pandas 3: head and merge base write the same output in all 396, so the version gate does what it should.
- pandas 2.3.3 with this PR vs pandas 3: 96 outputs go from wrong to matching pandas 3, and none that matched before stops matching. Also identical to pandas 3: tz-aware columns (including
Asia/Taipeiinus), timestamps and durations inside a struct, all-null and 0-row columns. - What still differs is what the description already lists (list and dictionary columns,
date_unit="ns"past 2262 now raising), plusdate32, where pandas 3 itself raisesNotImplementedError: as_unit not implemented for date32[day]. - The new tests: 8 fail on the merge base and pass on the head with pandas 2.3.3. The rest of
test_json.pymatches the description (2httpservererrors are my env). - A 3-chunk column with an empty and an all-null chunk (Gemini's comment) also writes correctly.
|
Hi, a short status update: this PR still merges cleanly into master and CI is green. rayo5o also verified the fix on pandas 2.3.3 and 3.0.6 (thanks!). I notice that #68089 changes the same function in |
Fixes #42920
Summary
On pandas < 3,
write_jsontreats non-nanosecond timestamp (without time zone) and duration columns as nanoseconds, so2024-01-01 12:00:00read from Parquet (timestamp[us]) is written as1704110400, which reads back as1970-01-20, instead of1704110400000. This PR converts those columns to the output unit before callingto_json()(integers indate_unitfor the default epoch output), so the written values are correct.Before
Ray's
write_jsonhands each block to pandas:JSONDatasink.write_block_to_filecallsblock.to_pandas().to_json(...). In pandas < 3,to_json()itself treats non-nanosecond timestamps (without time zone) and durations as nanoseconds (pandas-dev/pandas#55827, fixed in pandas 3.0).Ray requires pandas >= 2.2.3 with no upper bound, so anyone on pandas 2.2.3 to 2.3.x hits this bug.
pip install "ray[data]"installs pandas 3 on Python 3.11+, but on Python 3.10, which Ray still supports, it installs pandas 2.3.3 (pandas 3 needs Python >= 3.11). Ray's own lock file,python/requirements_compiled.txt, also pinspandas==2.3.3, so anyone installing with it hits this bug.For example, writing a
timestamp[us]column, the usual type in Parquet files:The same happens with
timestamp[s](the usual type fromread_json) and with durations. For2024-01-01 12:00:00and a 90-second duration, this is what is written today:timestamp[s]1704(1970-01-01 00:00:01.704)1704110400000timestamp[us]1704110400(1970-01-20)1704110400000timestamp[ns]17041104000001704110400000duration[s]090000duration[s]withdate_format="iso""P0DT0H0M0.000000090S"(90 ns)"P0DT0H1M30S"Also, setting
date_unitdoesn't help users avoid it. For example, withdate_unit="s",2024-01-01 12:00:00(timestamp[s]) should be written as1704110400, but it is written as1. This is becauseto_json()still reads the value as nanoseconds (1704110400 ns is about 1.7 seconds) and only then converts it to seconds. Both Arrow blocks and pandas blocks are affected, so nowrite_jsonargument gives correct epoch numbers for these columns.After
To fix this,
write_jsonnow first calls_fix_non_nanosecond_columnson a shallow copy of the DataFrame, and then callsto_json(). This step only runs on pandas < 3. What it does depends on the output format:pyarrow.compute.castto integers indate_unit.9999-12-31"no end date" value, which writes without error today, would start raisingOutOfBoundsDatetime.date_format="iso"):Everything else is unchanged.
One behavior changes: when the target unit is nanoseconds (durations with
date_format="iso", or any column withdate_unit="ns"), values outside the int64 nanosecond range (about 292 years, so dates outside 1677-2262 such as9999-12-31) now raiseArrowInvalidinstead of being written as wrong numbers.This PR doesn't cover timestamps or durations inside list columns or dictionary-encoded columns; those are still written in the wrong unit. Happy to handle these in a follow-up PR if needed.
flowchart TB subgraph Before subgraph BS[Subsystem: IO] subgraph BC[Component: JSONDatasink.write_block_to_file] direction LR B1["block.to_pandas()"] --> B2["df.to_json()<br/>timestamp[us] 2024-01-01 12:00:00 -> 1704110400"] end end end subgraph After subgraph AS[Subsystem: IO] subgraph AC[Component: JSONDatasink.write_block_to_file] direction LR A1["block.to_pandas()"] --> A3["_fix_non_nanosecond_columns<br/>(pandas < 3)"] --> A2["df.to_json()<br/>timestamp[us] 2024-01-01 12:00:00 -> 1704110400000"] end end end Before ~~~ After classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A3 added class A2 changedSubsystems
IO (
_internal/datasource/json_datasink.py)Testing
To check this, I added two tests to
datasource/test_json.py, each run with an Arrow block and a pandas block:test_json_write_non_nanosecond_temporal_columns:s/ms/us/nstimestamps, austimestamp with a sub-millisecond part, a UTC timestamp, ands/ms/us/nsdurations, each with a null row, written with the default settings and withdate_unit="s".test_json_write_date_outside_nanosecond_range:9999-12-31and a duration, written with the default settings,date_format="iso"andorient="table".On master, 8 of the 10 cases fail. The other 2 are the
orient="table"cases (ato_jsonlayout that writes dates as ISO strings), which pass on master too; they check that this layout is left alone.I also ran
pytest python/ray/data/tests/datasource/test_json.py: 74 passed on both pandas 2.3.3 and pandas 2.2.3 (Ray's minimum).Why this is not a duplicate
On 2026-11-07 and again on 2026-11-09 I searched open and closed issues and PRs for
write_jsonwith timestamp/datetime/epoch,JSONDatasink,to_jsondate_unit,55827and "non-nanosecond". No PR addresses #42920, andjson_datasink.pyis the only place Ray Data calls pandasto_json.AI assistance
AI use: I worked with Claude Code (
claude opus 5.5 (high)). Together we identified the root cause, wrote the fix and tests, and ran the tests. It also helped turn my thoughts into this description. I also usedgemini argon (high)for an additional review.