Repository navigation
fix(parquet): return error instead of panicking on first-write failure - #824
Conversation
apacheGH-820) (*file.Writer).startFile() previously panicked with "failed to write magic number" when the underlying sink's first Write returned an error or short-wrote. Because NewParquetWriter has no error return, callers on flaky network sinks (e.g. cloud-storage upload writers) had no idiomatic recovery path, and the higher-level pqarrow.NewFileWriter propagated the panic unchanged through its (*FileWriter, error) return. Add a sibling constructor file.NewParquetWriterWithError that returns (*Writer, error). The legacy file.NewParquetWriter is now a thin wrapper that panics with the original message string for back-compat. Switch pqarrow.NewFileWriter to the error-returning constructor so its error return finally covers this failure mode without any change to its own public signature. Closes apache#820.
Uhh, so @zeroshade do you (or your agent) want to file that issue? 😅 |
|
Filed #826 🫤 |
| // cloud-storage upload writer or other network-attached writer) should | ||
| // prefer [NewParquetWriterWithError], which surfaces the failure as a | ||
| // returned error instead. | ||
| func NewParquetWriter(w io.Writer, sc *schema.GroupNode, opts ...WriteOption) *Writer { |
There was a problem hiding this comment.
Should we deprecate this as well?
There was a problem hiding this comment.
My preference would be to not deprecate this unless we provide a similar short-named function, The new NewParquetWriterWithError function is a bit long to be the canonical function to use. Given the only difference is just having an error return instead of a panic, we could either rename the new function or keep both as relevant.
Address review feedback on PR apache#824: rewrite NewParquetWriterWithError's godoc so a reader unfamiliar with the codebase can understand it without cross-referencing NewParquetWriter. The new doc opens with what the function does, then describes the failure mode (sink write fails or short-writes, e.g. a flaky or network-attached writer). NewParquetWriter retains the historical context: it documents the preserved panic value ("failed to write magic number") for back-compat with existing recover() string-match callers, and points new code at NewParquetWriterWithError.
…ailures (#852) ### Rationale for this change Closes #826. Across all 8 generated `*ColumnChunkWriter` types in `parquet/file/column_writer_types.gen.go`, `WriteBatch` and `WriteBatchSpaced` are an asymmetric pair: - `WriteBatch` returns `(valueOffset int64, err error)` and opens with a `defer recover()` that converts any panic into a returned `error` via `utils.FormatRecoveredError`. - `WriteBatchSpaced` returns nothing, has no `defer recover()`, and on the `doBatches` (non-byte-array) path silently discards the `error` returned by `commitWriteAndCheckPageLimit`. So a write failure during a spaced write is either **silently discarded** (numeric/boolean/fixed paths) or **escapes as a panic out of the calling goroutine** (the byte-array branch's `panic(err)`, plus other internal panics such as dictionary-fallback bookkeeping) — because, unlike `WriteBatch`, there is no `recover()` to turn it into an `error`. This is the same class of "panic escapes / error lost on the public API" bug as #820 (fixed in #824), on a different code path. It is reachable through `pqarrow` — `(*pqarrow.FileWriter)` drives `WriteBatchSpaced` for **nullable** columns — so for consumers writing nullable columns to a network-attached sink (GCS, S3 multipart, HDFS, etc.), a transient downstream failure on the spaced path crashes the worker process or silently drops the error instead of returning it. The Boolean-only `WriteBitmapBatchSpaced` has the same void-signature / no-recover shape and is fixed here too. ### What changes are included in this PR? 1. **New method `WriteBatchSpacedWithError(values, defLevels, repLevels, validBits, validBitsOffset) (int64, error)`** generated for all 8 column-writer types from `column_writer_types.gen.go.tmpl`. It mirrors `WriteBatch`: - opens with `defer func() { if r := recover(); r != nil { err = utils.FormatRecoveredError(...) } }()`, and - checks the `error` from `commitWriteAndCheckPageLimit` on **every** branch (the `doBatches` branch previously ignored it), `panic`-ing so the deferred recover surfaces it as a returned `error`. 2. **New method `WriteBitmapBatchSpacedWithError(...) (int64, error)`** on `*BooleanColumnChunkWriter`, applying the same treatment to the bitmap spaced-write path. 3. **`WriteBatchSpaced` and `WriteBitmapBatchSpaced` are left byte-for-byte unchanged** — same signatures, same behavior. This keeps the change **non-breaking and purely additive**, exactly the approach #824 took with `NewParquetWriter` / `NewParquetWriterWithError`. Existing callers are unaffected; callers that want error handling opt into the `…WithError` variants. 4. **`pqarrow`'s dense-array encoder (`writeDenseArrow`) now calls `WriteBatchSpacedWithError`** at all 12 spaced-write sites and propagates the error through its existing `(err error)` return, so nullable-column writes report sink failures as errors instead of crashing the goroutine or losing the error. (`WriteBitmapBatchSpaced` has no internal callers, so nothing to rewire there.) The diff to the generated file and the template is additions-only (no existing generated method bodies change). ### Are these changes tested? Yes. Two new tests in `parquet/file/column_writer_test.go` use the existing `mockpagewriter` to fail `WriteDataPage`, with a tiny `DataPageSize` and dictionary disabled to force a flush mid-call: - `TestWriteBatchSpacedWithErrorPropagatesWriteFailure` - `TestWriteBitmapBatchSpacedWithErrorPropagatesWriteFailure` Each asserts that the `…WithError` variant returns the wrapped failure (`errors.Is(err, failureErr)`) rather than panicking or discarding it, and that the legacy method does **not** panic out of the call (its original behavior is preserved). The full `parquet/file/...` and `parquet/pqarrow/...` suites pass (`PARQUET_TEST_DATA` pointed at `parquet-testing/data`), and `go vet` is clean. ### Are there any user-facing changes? **No breaking changes.** - `WriteBatchSpaced(...)` and `WriteBitmapBatchSpaced(...)` — signatures and behavior unchanged. - `WriteBatchSpacedWithError(...) (int64, error)` (all 8 types) and `WriteBitmapBatchSpacedWithError(...) (int64, error)` (Boolean) — new exported methods. Adding exported methods is non-breaking in Go. - `pqarrow` public signatures are unchanged; the dense-array nullable write path now returns transient sink failures as an `error` (callers already checking `err` get strictly better behavior).
Rationale for this change
Closes #820.
(*file.Writer).startFile()panics with the literal string"failed to write magic number"when the underlying sink's firstWritecall returns an error or short-writes. Becausefile.NewParquetWritercallsstartFilesynchronously inside the constructor and has noerrorreturn, callers had no idiomatic Go recovery path. The higher-levelpqarrow.NewFileWriteralready returns(*FileWriter, error), but the panic propagated through it unchanged, so itserrorreturn was never reached for this failure mode.In production this manifests when the sink is a network-attached writer (
*storage.Writerfrom GCS, an S3 multipart upload, an HDFS client, etc.). A transient network blip on the first 4-byte magic-header write reliably crashes the worker process, orphans any in-flight upload session, and forces a container restart.What changes are included in this PR?
(*Writer).startFile()now returnserrorinstead of panicking on sink-write failures. The configuration-validation panic for "encrypted column not found in file schema" is preserved — that path is a programmer error, not an I/O failure.file.NewParquetWriterWithError(w, sc, opts...) (*Writer, error)is the preferred entry point for callers whose sink may transiently fail.file.NewParquetWriteris now a thin wrapper overNewParquetWriterWithErrorthat panics with the exact same string ("failed to write magic number") on init failure. Any consumer with arecover()block that string-matches the panic value continues to work unchanged.pqarrow.NewFileWriterswitches toNewParquetWriterWithErrorinternally. Its public signature is unchanged; itserrorreturn now meaningfully covers transient sink failures, with no API change for any of its callers.Are these changes tested?
Yes. Six new tests in
parquet/file/file_writer_test.goexercise the new behavior using aflakyMagicSinktest helper modeled on the existingerrCloseWriterpattern in the same file:TestNewParquetWriterWithError_Success— happy path on abytes.Buffer.TestNewParquetWriterWithError_FirstWriteFails— firstWritereturnsio.ErrUnexpectedEOF; constructor returns a wrapped error and does not panic.TestNewParquetWriterWithError_FirstWriteShortWrites— firstWritereturnsn=len(p)-1, nil; constructor returns an error mentioning the short write.TestNewParquetWriter_PreservesPanicMessage— the legacy constructor still panics, the panic value is still astring, and the message is still the literal"failed to write magic number"(back-compat guard).TestPqarrowNewFileWriter_PropagatesInitError—pqarrow.NewFileWriterreturns the wrapped sink error rather than panicking.TestPqarrowNewFileWriter_PropagatesShortWrite— same for the short-write case.The existing
TestCloseError, fullparquet/file/...andparquet/pqarrow/...test suites all pass (withPARQUET_TEST_DATApointed atparquet-testing/data).Are there any user-facing changes?
No breaking changes.
file.NewParquetWriter(w, sc, opts...) *Writer— signature unchanged, still panics on first-write failure with the identical literal string"failed to write magic number". Existingrecover()workarounds keep working.file.NewParquetWriterWithError(w, sc, opts...) (*Writer, error)— new exported symbol. Adding an exported function is non-breaking in Go.pqarrow.NewFileWriter(...) (*FileWriter, error)— signature unchanged. Itserrorreturn now also covers the magic-header-write failure that previously escaped as a panic. Callers who already checkerrget strictly better behavior.The new constructor's docstring is the recommended path for users on cloud-storage upload sinks. The legacy constructor's docstring now documents the panic behavior the original issue called out as undocumented.
Out of scope (separate follow-up)
While investigating, I noticed
WriteBatchSpacedinparquet/file/column_writer_types.gen.golacks thedefer recover()thatWriteBatchhas, so an I/O error during a spaced write panics out of the calling goroutine instead of returning an error. Same class of bug as #820 but a different code path; happy to file a separate issue.