Skip to content

fix(table): populate WriteTask.SortOrderID in data file writers - #875

Merged
zeroshade merged 5 commits into
apache:mainfrom
alliasgher:fix-populate-write-task-sort-order-id
Apr 13, 2026
Merged

zeroshade merged 5 commits into
apache:mainfrom
alliasgher:fix-populate-write-task-sort-order-id

Conversation

@alliasgher

Copy link
Copy Markdown
Contributor

Summary

The SortOrderID field on WriteTask was declared but never set by any producer, so every data file written via the standard/partitioned/rolling/equality-delete paths ended up with a nil sort_order_id in the manifest entry. This leaves readers with no way to know which sort order the file was written against.

This PR threads SortOrderID end-to-end:

  • WriteFileInfo gains a SortOrderID field and DataFileStatistics.ToDataFile now calls DataFileBuilder.SortOrderID so the value lands on the final DataFile.
  • arrow_utils.filesToDataFiles, writer.writeFile, and writerFactory all pass the table's default sort order id down to WriteFileInfo, and the equality-delete / position-delete / rolling data writer paths populate the WriteTask.SortOrderID accordingly.

Fixes #842

Test plan

  • go test ./table/...
  • go vet ./...
  • New assertion: withSortOrderIDMatching added to defaultPositionDeleteMatching in TestPositionDeletePartitionedFanoutWriterProcessBatch; mockDataFile gains an overridable sort order id so this path is covered end-to-end.

Signed-off-by: Ali [email protected]

The SortOrderID field on WriteTask was declared but never set by any
producer, and the written data files therefore always had a nil
sort_order_id in the manifest entry. This left readers with no way to
know which sort order the file was written against.

Thread SortOrderID end-to-end:

* WriteFileInfo gains a SortOrderID field and DataFileStatistics.ToDataFile
  now calls DataFileBuilder.SortOrderID so the value lands on the final
  DataFile.
* arrow_utils.filesToDataFiles, writer.writeFile, and writerFactory all
  pass the table's default sort order id down to WriteFileInfo, and the
  equality/position delete and rolling data writer paths populate the
  WriteTask accordingly.

A sort-order-id matcher is added to the position delete fanout writer
test suite and the mockDataFile gains an overridable sort order id so
this path is covered by an assertion.

Fixes apache#842

Signed-off-by: Ali <[email protected]>

@laskoviymishka laskoviymishka 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.

Thanks for tackling this — the core approach is correct and the partitioned paths are threaded properly. However, I think this needs another pass before merging:

Both equalityDeleteRecordsToDataFiles (equality_delete_writer.go:201) and positionDeleteRecordsToDataFiles (arrow_utils.go:1613) construct WriteTask{} without SortOrderID in their unpartitioned branches. The zero-value means these files always get sort_order_id = 0 regardless of the table's actual default sort order.

The partitioned branches of the same functions set it correctly — this looks like an oversight.

Also needs more tests:

  • No test for the standard data write path (writerFactory / rolling data writer) with a non-zero sort order
  • No test for unpartitioned position-delete or equality-delete writes, which is exactly where the bug above lives
  • A round-trip test (write manifest, read it back, verify sort_order_id)

The unpartitioned path bug needs a fix with corresponding test coverage.

Comment thread table/equality_delete_writer.go Resolved
Comment thread table/arrow_utils.go Resolved
Comment thread table/internal/utils.go Resolved
Comment thread table/internal/interfaces.go Resolved
Adds three tests in response to review feedback on apache#875:

* TestRollingDataWriter/TestWriterFactoryPropagatesSortOrderID — covers
  the standard data write path (writerFactory + rolling data writer)
  with a non-zero default sort order and asserts the resulting DataFile
  carries the expected id.
* TestPositionDeleteUnpartitionedSortOrderID — exercises the
  unpartitioned branch of positionDeleteRecordsToDataFiles.
* TestEqualityDeleteUnpartitionedSortOrderID — same for the
  unpartitioned branch of equalityDeleteRecordsToDataFiles.
* TestManifests/TestManifestRoundTripSortOrderID — writes a data file
  with a sort_order_id through WriteManifest, reads it back via
  ReadManifest, and verifies the value round-trips.

Signed-off-by: Ali <[email protected]>
@alliasgher

Copy link
Copy Markdown
Contributor Author

Thanks for the review — pushed the extra tests:

  • TestRollingDataWriter/TestWriterFactoryPropagatesSortOrderID covers the standard data write path (writerFactory + rolling data writer) with a non-zero default sort order.
  • TestPositionDeleteUnpartitionedSortOrderID and TestEqualityDeleteUnpartitionedSortOrderID cover the unpartitioned branches of positionDeleteRecordsToDataFiles and equalityDeleteRecordsToDataFiles.
  • TestManifests/TestManifestRoundTripSortOrderID writes a data file with a sort_order_id through WriteManifest, reads it back via ReadManifest, and verifies the value round-trips.

One clarification question on the first point — could you take another look at equality_delete_writer.go line 208 and arrow_utils.go line 1620? I believe both unpartitioned WriteTask{} constructions already set SortOrderID: meta.defaultSortOrderID in the diff, but let me know if I'm missing something or if you were pointing at a different site.

Other fields in WriteFileInfo have no doc comments; singling out
SortOrderID with a three-line block is inconsistent. Removing it per
review feedback.

Signed-off-by: Ali <[email protected]>
@laskoviymishka

Copy link
Copy Markdown
Contributor

Thx! With new test it's clear now!

@laskoviymishka

Copy link
Copy Markdown
Contributor

@tanmayrauth can you also review this one, i suggest to close #885, as dupe.

Comment thread table/internal/parquet_files_test.go Resolved

@zeroshade zeroshade left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, just a couple nit pick comments

alliasgher added a commit to alliasgher/iceberg-go that referenced this pull request Apr 13, 2026
…aFileOpts

As suggested in review on apache#875, the ToDataFile signature grew to eight
positional arguments — hard to read at call sites and prone to
argument-order mistakes (especially the two int parameters, filesize
and sortOrderID).

Replace the parameters with a DataFileOpts struct:

    type DataFileOpts struct {
        Schema          *iceberg.Schema
        Spec            iceberg.PartitionSpec
        Path            string
        Format          iceberg.FileFormat
        Content         iceberg.ManifestEntryContent
        FileSize        int64
        PartitionValues map[int]any
        SortOrderID     int
    }

All six call sites (two production, four tests) are updated to the
named-field form. No behavior change.

Signed-off-by: Ali <[email protected]>
…itiveTypes

Two review nits:

- Replace the ad-hoc intPtr with a generic ptr[T any] helper in the
  internal package tests. The test_package-level generic ptr already
  exists in snapshots_test.go (package table_test) but is not reachable
  from package table internal tests.

- Use a non-zero sort order id (7) in TestMetricsPrimitiveTypes and
  assert the resulting DataFile carries it, pinning the contract in
  this file. Other files already exercised non-zero sort orders;
  parquet_files_test.go was the one stragglers test.

Signed-off-by: Ali <[email protected]>
@zeroshade
zeroshade merged commit 083e9c7 into apache:main Apr 13, 2026
11 checks passed
alliasgher added a commit to alliasgher/iceberg-go that referenced this pull request Apr 13, 2026
…aFileOpts

As suggested in review on apache#875, the ToDataFile signature grew to eight
positional arguments — hard to read at call sites and prone to
argument-order mistakes (especially the two int parameters, filesize
and sortOrderID).

Replace the parameters with a DataFileOpts struct:

    type DataFileOpts struct {
        Schema          *iceberg.Schema
        Spec            iceberg.PartitionSpec
        Path            string
        Format          iceberg.FileFormat
        Content         iceberg.ManifestEntryContent
        FileSize        int64
        PartitionValues map[int]any
        SortOrderID     int
    }

All six call sites (two production, four tests) are updated to the
named-field form. No behavior change.

Signed-off-by: Ali <[email protected]>
zeroshade pushed a commit that referenced this pull request Apr 13, 2026
…aFileOpts (#888)

## Summary

Follow-up to the review comment on
[#875](#875 (comment))
— `DataFileStatistics.ToDataFile` grew to eight positional arguments
including two adjacent `int`s (`filesize` and `sortOrderID`), which is
hard to read at call sites and easy to swap by mistake.

This PR collapses the parameters into a `DataFileOpts` struct:

```go
type DataFileOpts struct {
    Schema          *iceberg.Schema
    Spec            iceberg.PartitionSpec
    Path            string
    Format          iceberg.FileFormat
    Content         iceberg.ManifestEntryContent
    FileSize        int64
    PartitionValues map[int]any
    SortOrderID     int
}

func (d *DataFileStatistics) ToDataFile(opts DataFileOpts) iceberg.DataFile
```

All six call sites (two production, four tests) are updated to the
named-field form. Future additions are source-compatible.

## Notes

- Stacked on #875 — this PR will show both diffs until #875 merges, at
which point only the refactor remains.
- No behaviour change.

## Test plan

- [x] `go test ./...`
- [x] `gofmt` clean

Signed-off-by: Ali <[email protected]>

Signed-off-by: Ali <[email protected]>
twuebi added a commit to twuebi/iceberg-go that referenced this pull request Jun 11, 2026
…lly sort

The spec's per-file sort_order_id declares that the file's rows are fully
sorted by that order ("ID representing sort order for this file"); a
missing id means unsorted. Since apache#875 every writer stamped the table's
default sort order id unconditionally, and apache#1157's sort-on-write only
sorts each record batch individually, so the stamped claim was false for
any multi-batch file. Position delete files were stamped too, which the
spec forbids outright: their order is (file_path, pos), writers should
set the field to null and readers must ignore it.

Writers now make no claim: data files, eq-delete files, pos-delete files
and registered files (add_files) leave sort_order_id absent, matching
PyIceberg and iceberg-rust. The per-batch sort is kept as a pure layout
optimization (tighter page statistics, better encodings).
WriteTask.SortOrderID remains as an explicit caller claim for producers
that guarantee fully sorted batches, mirroring how Java/Spark stamps the
id only when the engine enforced the ordering.
laskoviymishka pushed a commit that referenced this pull request Jun 15, 2026
…lly sort (#1184)

The per-file sort_order_id declares that a file's rows are *fully*
sorted by that order; a missing id means unsorted
(https://iceberg.apache.org/spec/#sorting). Since #875 every writer
stamped the table's default sort order id unconditionally, but #1157's
sort-on-write only sorts each record batch individually, so the claim
was false for any multi-batch file. Position delete files were stamped
too, which the spec forbids outright, their order is (file_path, pos)
and writers must set the field to null
(https://iceberg.apache.org/spec/#data-file-fields). This contradicts
the community consensus: Spark stamps the id *only* when its
distribution+ordering globally sorted the whole task input, never
inferring it from the table default
(apache/iceberg#15150).

This change makes writers claim nothing by default: data files,
eq-delete files, pos-delete files, and registered files (add_files)
leave sort_order_id absent, matching PyIceberg and iceberg-rust. The
per-batch sort is kept as a pure layout optimization (tighter page
statistics, better encodings). WriteTask.SortOrderID remains as an
explicit caller claim for producers that guarantee fully sorted batches,
mirroring how Java/Spark stamps the id only when the engine enforced the
ordering. Leaving the field absent is fully spec-compliant, it was
always advisory and never assumed applied to all files
(apache/iceberg#317). The only incorrect
behavior is stamping a claim that isn't true, which a reader could trust
to wrongly skip a re-sort.

References: apache/iceberg#13634,
apache/iceberg#15150,
apache/iceberg#317,
https://iceberg.apache.org/spec/#sorting
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
iceberg-cli 0.6.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## What's Changed
* build(deps): bump the gomod_updates group with 18 updates by @dependabot[bot] in apache/iceberg-go#763
* build(deps): bump go.opentelemetry.io/otel/sdk from 1.39.0 to 1.40.0 by @dependabot[bot] in apache/iceberg-go#764
* fix: nil field Type causes unrecovered panic in MarshalJSON by @shtripat in apache/iceberg-go#765
* fix(manifest): handle lifecycle of the decoder in reader by @ferhatelmas in apache/iceberg-go#766
* feat(rest): add RegisterView to REST catalog by @shtripat in apache/iceberg-go#753
* fix(table): fix refcount leak in enrichRecordsWithPosDeleteFields by @laskoviymishka in apache/iceberg-go#762
* chore: Update copyright year in NOTICE file by @zeroshade in apache/iceberg-go#771
* refactor: make partition spec and sort order fields range friendly by @ferhatelmas in apache/iceberg-go#772
* feat(table): roll parquet files based on actual compressed size by @twuebi in apache/iceberg-go#759
* fix(table): ensure partition path is deterministic by @ferhatelmas in apache/iceberg-go#767
* build(deps): bump the gomod_updates group across 1 directory with 12 updates by @dependabot[bot] in apache/iceberg-go#782
* fix: skip pageSize query param when value is 0 by @alessandro-nori in apache/iceberg-go#778
* fix: handle LargeString columns in partition transforms by @hamilton-earthscope in apache/iceberg-go#780
* fix(table): removeSnaphosts postCommit now takes effect by @starpact in apache/iceberg-go#783
* feat: Implemented write-default and initial-default v3 by @PranjalChaitanya in apache/iceberg-go#779
* feat(table): add Scan.ReadTasks for reading pre-planned file scan tasks by @twuebi in apache/iceberg-go#781
* feat(table): export StructLike and GetPartitionRecord by @twuebi in apache/iceberg-go#791
* feat(catalog): refresh oauth tokens by @rockwotj in apache/iceberg-go#793
* feat(table): public write DataFile API by @twuebi in apache/iceberg-go#776
* fix: remove unnecessary safe-guard by @twuebi in apache/iceberg-go#775
* fix(table): don't always set schema.name-mapping.default by @rockwotj in apache/iceberg-go#803
* build(deps): bump google.golang.org/grpc from 1.79.2 to 1.79.3 by @dependabot[bot] in apache/iceberg-go#804
* feat(table): add RowDelta API for atomic row-level mutations by @laskoviymishka in apache/iceberg-go#789
* feate(hive): Add Create View for Hive catalog by @dttung2905 in apache/iceberg-go#788
* build(deps): bump the gomod_updates group with 2 updates by @dependabot[bot] in apache/iceberg-go#807
* fix(table): AddFiles: close file after usage and parallelize by @starpact in apache/iceberg-go#799
* feat(catalog): add TransactionalCatalog interface and REST multi-table commit by @laskoviymishka in apache/iceberg-go#787
* feat(catalog,io): refresh vended credentials by @rockwotj in apache/iceberg-go#795
* fix(table): AddFiles() should respect commit.manifest-merge.enabled by @RSP22 in apache/iceberg-go#806
* feat(table): configure Parquet DataPage version by @laskoviymishka in apache/iceberg-go#812
* chore: add CODEOWNERS file by @zeroshade in apache/iceberg-go#814
* fix(table): deadlock in MapExec when workers error by @laskoviymishka in apache/iceberg-go#810
* fix(table): add warnings for silent data-affecting behavior by @laskoviymishka in apache/iceberg-go#811
* build(deps): bump github.com/moby/buildkit from 0.27.1 to 0.28.1 by @dependabot[bot] in apache/iceberg-go#813
* feat(hive): adding register table in hive catalog by @Hashcode-Ankit in apache/iceberg-go#816
* feat(table): equality delete write path by @laskoviymishka in apache/iceberg-go#809
* feat(catalog): add CommitAndReload, error ctx, and 404 test for multi-tx by @laskoviymishka in apache/iceberg-go#817
* feat(types): add Parquet support for nanosecond timestamp types (v3) by @laskoviymishka in apache/iceberg-go#819
* build(deps): bump the gomod_updates group with 6 updates by @dependabot[bot] in apache/iceberg-go#822
* feat(table): enforce write-default and initial-default for required fields by @laskoviymishka in apache/iceberg-go#820
* feat(table): equality delete read path in scanner by @laskoviymishka in apache/iceberg-go#818
* feat(rest): add audience and resource params to OAuth requests by @lovromazgon in apache/iceberg-go#815
* feat(table): equality delete writing for partitioned tables by @laskoviymishka in apache/iceberg-go#823
* fix(table): goroutine leak in positionDeleteRecordsToDataFiles by @hcrosse in apache/iceberg-go#825
* fix(manifest): default to v1 files by @rockwotj in apache/iceberg-go#826
* feat(table): add Transaction.UpgradeFormatVersion by @rockwotj in apache/iceberg-go#827
* feat(table): multi-arg transforms in partition and sort fields by @laskoviymishka in apache/iceberg-go#824
* build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.3 to 4.1.4 by @dependabot[bot] in apache/iceberg-go#828
* Thread context.Context through deletedEntries() by @Herrtian in apache/iceberg-go#847
* feat(table): Add statistics files to orphan cleanup referenced set by @dttung2905 in apache/iceberg-go#848
* build(deps): bump the gomod_updates group with 5 updates by @dependabot[bot] in apache/iceberg-go#854
* fix(ci): resolve flaky integration-setup by @laskoviymishka in apache/iceberg-go#858
* bench(table): read-perf degradation under equality delete pressure by @laskoviymishka in apache/iceberg-go#852
* fix(table): read Parquet batch size from table properties by @gabrnavarro in apache/iceberg-go#849
* feat(table): Add OpReplace to updateSnapshotSummaries by @dttung2905 in apache/iceberg-go#853
* feat(table): strengthen orphan-cleanup stats referenced-set tests and document empty-path guard by @dttung2905 in apache/iceberg-go#856
* fix: require Transform in NewSortOrder and add related tests by @Narwhal-fish in apache/iceberg-go#859
* feat(table): support delete file removal in overwrite commits by @laskoviymishka in apache/iceberg-go#851
* feat(table): classify deletion vectors in scan planning by @laskoviymishka in apache/iceberg-go#855
* build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.41.0 to 1.43.0 by @dependabot[bot] in apache/iceberg-go#864
* feat(table): add bin-pack compaction strategy by @laskoviymishka in apache/iceberg-go#850
* build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp from 1.38.0 to 1.43.0 by @dependabot[bot] in apache/iceberg-go#862
* fix: handle missing format-version in NewManifestReader for v1 manifests by @rockwotj in apache/iceberg-go#868
* docs: expand CONTRIBUTING.md with issue claiming and PR guidelines by @laskoviymishka in apache/iceberg-go#887
* build(deps): bump the gomod_updates group with 4 updates by @dependabot[bot] in apache/iceberg-go#872
* fix(table): prune StatisticsList and PartitionStatsList in RemoveSnapshots by @alliasgher in apache/iceberg-go#873
* fix(table): read retention table properties as defaults in ExpireSnapshots by @alliasgher in apache/iceberg-go#877
* feat(table): wire bloom filter properties into Parquet writer by @alliasgher in apache/iceberg-go#878
* fix(table): populate WriteTask.SortOrderID in data file writers by @alliasgher in apache/iceberg-go#875
* fix(schema): reject duplicate field IDs at schema construction by @alliasgher in apache/iceberg-go#879
* fix: emit proper Avro fixed schema for FixedType partition columns (#845) by @tanmayrauth in apache/iceberg-go#881
* fix(table): delete statistics files in ExpireSnapshots PostCommit #837 by @tanmayrauth in apache/iceberg-go#882
* refactor(table): collapse DataFileStatistics.ToDataFile args into DataFileOpts by @alliasgher in apache/iceberg-go#888
* perf(table): Decrease memory pressure by releasing records by @abhirathod95 in apache/iceberg-go#886
* fix(deletes): change equality_ids array elements avro schema type from Long to Integer to match spec by @rohilsurana in apache/iceberg-go#880
* feat(avro): replace hamba/avro with twmb/avro v1.5.0 by @twmb in apache/iceberg-go#871
* feat(compaction): add Analyze for dry-run compaction planning by @laskoviymishka in https://github.com/apache/iceberg-go/pull/

See merge request: Harmonybrew/homebrew-core!9291
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.

fix: populate WriteTask.SortOrderID from table metadata

3 participants