Skip to content

fix: write array-valued data to CSV as parseable lists - #2707

Merged
Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/csv-sink-array-data
Oct 12, 2026
Merged

Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/csv-sink-array-data

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

Description

sv.CSVSink wrote NumPy arrays from detections.data / custom_data through numpy's str(): a 1536-d
float32 embedding came out as a summarised string with an ellipsis (6 of 1536 values recoverable) and OBB
corner arrays contained newlines.

Minimal repro (full script in the issue):

  • Before: the embedding cell is '[0.8506242 0.63696164 ... 0.91254586' and json.loads fails.
  • After: the cell is a JSON list that round-trips to the original array exactly.

Motivation and Context

Embeddings and OBB corners are common in data, and JSONSink already writes them correctly.

Closes #2706

Changes Made

  • New CSVSink._format_cell, applied where append() writes each row: an np.ndarray with ndim > 0 is
    written as json.dumps(value.tolist()), i.e. the same values JSONSink emits (default separators, one line).
  • Arrays JSON cannot represent (complex, datetime, bytes, object arrays holding arrays) fall back to the old
    str() form instead of raising.
  • Unchanged on purpose: numpy scalars, 0-d arrays, strings, bools, None, dicts and Python lists/tuples keep
    their previous output (existing tests pin them); parse_detection_data and _slice_value are untouched.

Testing

Ran (not the whole suite, not pre-commit --all-files):

  • pytest tests/detection/tools tests/detection/test_csv.py: 182 passed, 1 skipped.
  • pytest --doctest-modules src/supervision/detection/tools/csv_sink.py: 1 passed.
  • ruff check, ruff format --check and mypy (strict) on csv_sink.py: clean.
  • Round trip is bit-exact for float32 (checked on 2M random values from 1e-30 to 1e30, 0.8 s).
  • Not run: pre-commit's mdformat for the changelog; mypy on the tests (the repo config ignores them).

New TestCSVSinkArrayData (11 cases): 1536-d float32 exact round trip, OBB corners without newlines, int /
bool / str / empty arrays, NaN/inf, a broadcast array, complex fallback, unchanged scalar/string output and
consistency with JSONSink. On develop: 8 failed, 3 passed (the 3 are regression cases that must stay
unchanged); with this change: 11 passed.

  • Added/updated tests, and the full suite passes locally
  • Updated docs (docstrings / mkdocs entry) for new or changed public API
  • Added a changelog entry in docs/changelog.md under Unreleased (skip for lint/type/format-only or pure doc changes)

(Tick the first box only after you run the full suite yourself.)

Additional Notes

  • float32 values go through tolist(), so they are written as the exact double (0.6369617 becomes
    0.6369616389274597): about 31 KB per 1536-d embedding, roughly twice the shortest float32 repr, but identical
    to JSONSink and exactly round-trippable.
  • NaN/inf are written as NaN / Infinity / -Infinity, as JSONSink does; Python's json parses them, strict
    JSON parsers do not.
  • Users who parsed the old numpy-repr cells will see a format change; the old format was lossy.
  • Lists and tuples keep their Python repr; happy to make them JSON too for consistency with JSONSink (it would
    change existing pinned test output).

@avanish-garg
avanish-garg requested a review from SkalskiP as a code owner October 8, 2026 20:13
CSVSink passed NumPy arrays from Detections.data and custom_data to
csv.writer, which calls str(). Arrays of more than 1000 elements were
abbreviated with "...", smaller ones were space separated without commas,
and 2-D arrays such as oriented-box corners spanned several lines.

Arrays with ndim > 0 are now written as json.dumps(array.tolist()), the
same values JSONSink emits. Scalars, strings, 0-d arrays, lists, tuples,
dicts and arrays JSON cannot represent keep their previous output.
@avanish-garg
avanish-garg force-pushed the fix/csv-sink-array-data branch from 3166e04 to 25d6475 Compare October 8, 2026 20:21
@Borda
Borda requested a balanced review from Copilot October 8, 2026 22:29
@Borda Borda added the bug Something isn't working label Oct 8, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The focused implementation matches the stated behavior and has comprehensive regression coverage.

0 open findings

What changed in this PR

Fixes CSVSink to preserve array-valued detection data as parseable JSON.

Changes:

  • Serializes non-scalar NumPy arrays with json.dumps(value.tolist()).
  • Adds round-trip and regression coverage.
  • Documents the behavior change.
File Description
src/​supervision/​detection/​tools/​csv_sink.py Adds array cell formatting.
tests/​detection/​test_csv.py Tests serialization and compatibility.
docs/​changelog.md Records the fix.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Changes:
- Integrate fetched develop tip 8b94622 into the PR branch, carrying its 47-file target change set.
- Preserve both target Unreleased entries and PR roboflow#2707's CSV array-data entry while resolving the changelog conflict.

Impact:
- Bring the PR branch current with the target's dataset, depth, metrics, documentation, and configuration work.
- Keep the CSV fix and its regression tests intact on the integrated branch.

Verification:
- .venv/bin/python -m pytest -p no:xdist tests/detection/test_csv.py: 39 passed.
- git diff --cached --check: clean; no unmerged paths remain.
- Reviewed merge index tree 335245b and verified its first-parent path set matches fetched develop.

Residual limits:
- The requested assessed review report is unavailable (missing-matching-review-report); current PR metadata still says REVIEW_REQUIRED.

---

Co-authored-by: Codex <[email protected]>
@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93%. Comparing base (8b94622) to head (3e3617d).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2707   +/-   ##
=======================================
  Coverage       93%     93%           
=======================================
  Files           83      83           
  Lines        13109   13073   -36     
=======================================
- Hits         12253   12220   -33     
+ Misses         856     853    -3     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Changes:
- Keep NumPy object-array values in CSV fallback when JSON conversion raises TypeError or ValueError.
- Add a circular object-array regression spanning two detection rows.

Impact:
- CSVSink.append can write circular array values using csv.writer string conversion instead of aborting.
- Serializable arrays and existing unsupported-type handling keep their established behavior.

Verification:
- The circular-array regression failed before the fix and passed after it; tests/detection/test_csv.py passed (40 tests).
- Canonical gates passed: lint, formatting, mypy, full suite (5,440 passed, 79 skipped), and diff check.

Residual limits:
- Requested independent review coverage and historical source-context separation remain unresolved.
- This commit does not claim independent review.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit fa29a13 into roboflow:develop Oct 12, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: CSVSink truncates and mangles array-valued data (embeddings, OBB corners); JSONSink does not

3 participants