cjungm opened a new issue, #19259:
URL: https://github.com/apache/iceberg/issues/19259
### Apache Iceberg version
1.11.0
### Query engine
Spark
### Please describe the bug 🐞
**Summary.** With `BigQueryMetastoreCatalog`, two threads committing through
the same `Table` instance at the same time can corrupt the catalog pointer and
then delete the file it points to. `rewrite_data_files` does exactly that with
`partial-progress.enabled=true` and `max-concurrent-file-group-rewrites > 1`.
`BigQueryTableOperations.updateTable` mutates a `Table` object shared between
the threads, so the PATCH sent by thread A can carry thread B's
`metadata_location`. A's commit "succeeds"; B gets HTTP 412,
`CommitFailedException`, and `doCommit`'s cleanup deletes B's metadata file,
which is now the file the catalog references. Every reader fails with
`NotFoundException` until the pointer is repaired by hand.
We hit this on a production table with Iceberg 1.11.0 (Spark 3.5.6 via Spark
Connect, `iceberg-spark-runtime-3.5_2.12-1.11.0`) about a week after raising
`max-concurrent-file-group-rewrites` from 2 to 4 for daily compaction. The
table was unreadable for about 40 minutes and every writer that touched it in
that window failed. The BigQuery audit log for the table shows one
`tables.patch` 200 followed by two 412s within 300 ms, and the location carried
by the 200 was the one that no longer existed afterwards.
**Mechanism (1.11.0 sources; `BigQueryTableOperations.java` is identical on
`main` as of 93b7553).**
1. Commits from several threads on one `Table` are normal Iceberg behaviour.
`BaseCommitService.offer()` calls `commitReadyCommitGroups()` on the calling
rewrite worker, and `commitOrClean(batch)` runs outside the `synchronized`
block
(`core/src/main/java/org/apache/iceberg/actions/BaseCommitService.java:145-151,
211-235`), so with `max-concurrent-file-group-rewrites=4` up to four workers
commit through the same `TableOperations` at once.
`BaseMetastoreTableOperations.commit` only rejects a stale `base`; Hive, Glue
and JDBC keep all per-commit state in locals and tolerate this.
2. Since #14940 (first released in 1.11.0), `doRefresh()` stores the loaded
`Table` in `private volatile Table metastoreTable`
(`bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:53,
69`) and `updateTable()` mutates that shared object in place —
`options.setParameters(...)` on its `ExternalCatalogTableOptions` and
`addConnectionIfProvided(metastoreTable, ...)` — then sends it with
`client.update(tableReference, metastoreTable)` and nulls the field
(`:170-175`). `volatile` gives visibility, not atomicity. The interleaving
A.setParameters → B.setParameters → A.update serializes B's `metadata_location`
into A's PATCH, so A returns SUCCESS for a commit the catalog does not reflect.
In 1.10.0 `updateTable()` loaded its own `Table`, so this could not happen.
3. B's PATCH carries the etag A just invalidated, BigQuery answers 412, and
`BigQueryMetastoreClientImpl.convertExceptionIfUnsuccessful` turns it into
`CommitFailedException` (`BigQueryMetastoreClientImpl.java:559-560`).
`doCommit()` rethrows `CommitFailedException` without reconciling
(`BigQueryTableOperations.java:98-99`; `checkCommitStatus` is only reached for
other `Throwable`s at `:105-107`), `commitStatus` stays `FAILURE`, and the
`finally` block runs `io().deleteFile(newMetadataLocation)` (`:116-118`) on the
file the catalog now points to.
4. Milder symptom of the same shared state: once A has nulled the field, B's
`updateTable()` fails the precondition `Table %s must be loaded during refresh
before commit` (`:159-162`).
**Reproduction.** Deterministic unit test in the existing
`TestBigQueryTableOperations` setup (mocked `BigQueryMetastoreClient`,
`HadoopFileIO` on a temp dir). Two threads commit through the same
`TableOperations`; the mocked `update` holds each caller until both have
entered it, so both `setParameters` calls have run before either request body
is read — the interleaving of two rewrite workers committing at once. The first
caller succeeds, the second gets the 412 `CommitFailedException`. Source in the
collapsed section; it will be part of the fix PR.
<details>
<summary>Test source</summary>
```java
@Test
public void concurrentCommitsSendTheirOwnMetadataLocation() throws Exception
{
Table tableWithEtag = createTestTable().setEtag("etag");
reset(client);
when(client.load(TABLE_REFERENCE)).thenReturn(tableWithEtag);
tableOps.refresh();
TableMetadata base = tableOps.current();
CountDownLatch firstInUpdate = new CountDownLatch(1);
CountDownLatch bothInUpdate = new CountDownLatch(2);
AtomicInteger arrivals = new AtomicInteger();
List<String> sentLocations = Collections.synchronizedList(new
ArrayList<>());
when(client.update(any(), any()))
.thenAnswer(
invocation -> {
int arrival = arrivals.incrementAndGet();
firstInUpdate.countDown();
bothInUpdate.countDown();
bothInUpdate.await(30, TimeUnit.SECONDS);
Table sent = invocation.getArgument(1);
sentLocations.add(
sent.getExternalCatalogTableOptions().getParameters().get(METADATA_LOCATION_PROP));
if (arrival == 1) {
return sent;
}
throw new CommitFailedException("412 Precondition Failed: etag
mismatch");
});
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> first =
executor.submit(() -> tableOps.commit(base, withProperty(base,
"writer", "first")));
assertThat(firstInUpdate.await(30, TimeUnit.SECONDS)).isTrue();
Future<?> second =
executor.submit(() -> tableOps.commit(base, withProperty(base,
"writer", "second")));
first.get(30, TimeUnit.SECONDS);
assertThatThrownBy(() -> second.get(30, TimeUnit.SECONDS))
.hasCauseInstanceOf(CommitFailedException.class);
} finally {
executor.shutdownNow();
}
assertThat(sentLocations).hasSize(2);
String committedLocation = sentLocations.get(0);
assertSoftly(
softly -> {
softly
.assertThat(sentLocations.get(1))
.as("each PATCH must carry the location written by its own
commit")
.isNotEqualTo(committedLocation);
softly
.assertThat(tableOps.io().newInputFile(committedLocation).exists())
.as("metadata file referenced by the successful PATCH must
survive the other commit")
.isTrue();
});
}
private static TableMetadata withProperty(TableMetadata base, String key,
String value) {
return TableMetadata.buildFrom(base).setProperties(ImmutableMap.of(key,
value)).build();
}
```
</details>
`./gradlew :iceberg-bigquery:test --tests
org.apache.iceberg.gcp.bigquery.TestBigQueryTableOperations` on `main`
(93b7553; temp dir shortened to `<tmp>`):
```
TestBigQueryTableOperations >
concurrentCommitsSendTheirOwnMetadataLocation() FAILED
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (2 failures)
-- failure 1 --
[each PATCH must carry the location written by its own commit]
Expecting actual:
"<tmp>/tbl/metadata/00000-8e69d9e3-1aa4-411d-a8e5-50aef4df60f7.metadata.json"
not to be equal to:
"<tmp>/tbl/metadata/00000-8e69d9e3-1aa4-411d-a8e5-50aef4df60f7.metadata.json"
-- failure 2 --
[metadata file referenced by the successful PATCH must survive the other
commit]
Expecting value to be true but was false
9 tests completed, 1 failed
```
Both PATCHes carried the second commit's location, and the second commit
deleted that file on its way out, leaving the "successful" first commit
pointing at nothing. On a cluster the same thing is reached with `CALL
catalog.system.rewrite_data_files(table => 't', options =>
map('partial-progress.enabled', 'true', 'max-concurrent-file-group-rewrites',
'4'))` on a BigQuery Metastore table with enough file groups for several to
finish close together.
**Expected.** Each commit's PATCH carries its own `metadata_location`. A
genuine 412 deletes only the loser's own, unreferenced file. A 412 whose
location the catalog already points to is reconciled as SUCCESS instead of
cleaned up, the way `HiveTableOperations` (`checkCommitStatusStrict`) and
`GlueTableOperations` (`checkCommitStatus`) already do, and as @talatuyarer
suggested for this catalog in #15308. The JDBC counterpart of the cleanup half
is #18743 / #18745.
**Proposed fix** (I can open the PR):
1. `updateTable()` works on a per-commit copy (`metastoreTable.clone()`;
`GenericData` clones deeply) instead of mutating the shared object.
2. On 412, call `checkCommitStatusStrict(newMetadataLocation, metadata)`
before failing: `SUCCESS` keeps the file and returns normally, `FAILURE` keeps
today's `CommitFailedException`, `UNKNOWN` throws `CommitStateUnknownException`
so nothing is deleted.
3. The unit test above, plus one for the 412-but-already-committed case.
**Workaround.** `partial-progress.enabled=false` (one commit per action,
from the driver thread). `max-concurrent-file-group-rewrites=1` also avoids it,
but cut our compaction throughput about 4x.
---
**AI Disclosure**
- Model: Claude Fable 5.1
- Platform/Tool: Claude Code
- Human Oversight: fully reviewed
- Prompt Summary: Analyze a production incident where a BigQuery Metastore
table pointed at a deleted metadata file after a concurrent
`rewrite_data_files` commit, locate the cause in `BigQueryTableOperations`, and
write a deterministic unit test and this report. The analysis, the test and
this write-up are generated; I verified the cited code paths against the 1.11.0
and main sources and ran the test locally.
### Willingness to contribute
- [x] I can contribute a fix for this bug independently
- [ ] I would be willing to contribute a fix for this bug with guidance from
the Iceberg community
- [ ] I cannot contribute a fix for this bug at this time
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]