Compaction-enabled catalog caches Delta tables: new columns never appear
Describe what's wrong
- In a
DataLakeCatalogdatabase withcatalog_type = 'unity'andallow_experimental_iceberg_compaction = 1the statement belowSELECT */DESCRIBEsilently omit the new column andSELECT bfails withUNKNOWN_IDENTIFIER. - The same catalog without the setting shows the new column immediately.
, a Delta table keeps the column set from its first access. After a column is added in the catalog and the Delta log,Root cause: The stateful cache gate at DatabaseDataLake.cpp:917-919 admits non-Iceberg tables. Before the PR every catalog access rebuilt the storage from the catalog's current columns; the cached storage relies on per-query schema reload, which Delta does not do by default.
Why we believe this is a bug: DatabaseDataLake::tryGetTable (DatabaseDataLake.cpp:732) -> tryGetTableImpl: want_stateful (:917-919) keys only on the Iceberg-only allow_experimental_iceberg_compaction, never on table_metadata.getTableFormat(), so the Delta table is built once with the catalog columns (:1054, is_table_function = !want_stateful) and then returned from the cache (:932-936) on every later query. The only schema refresh left is StorageObjectStorage::updateExternalDynamicMetadataIfExists (StorageObjectStorage.cpp:650), which rebuilds columns only if shouldReloadSchemaForConsistency: always true for Iceberg (IcebergMetadata.cpp:1461-1464), but for Delta it is delta_lake_reload_schema_for_consistency (DeltaLakeMetadataDeltaKernel.cpp:316-319, default 0).
Affected locations:
src/Databases/DataLake/DatabaseDataLake.cpp:917— want_stateful gate ignores table formatsrc/Databases/DataLake/DatabaseDataLake.cpp:932— cache hit returns storage with columns frozen at creationsrc/Databases/DataLake/DatabaseDataLake.cpp:1068— is_table_function/lazy_init flipped for stateful tablessrc/Storages/ObjectStorage/StorageObjectStorage.cpp:650— columns reloaded only when shouldReloadSchemaForConsistencysrc/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp:316— Delta reload gated by delta_lake_reload_schema_for_consistency (default 0)
Impact: Delta tables in a Unity catalog database with the compaction setting show a stale schema until the database is re-created, detached/attached, altered, or the server restarts: SELECT * silently drops added columns (wrong result), queries naming them are rejected. Iceberg tables are not affected (their schema is reloaded per query). Paimon tables reload too (PaimonMetadata::shouldReloadSchemaForConsistency returns true).
Does it reproduce on most recent release?
Yes — confirmed on current master (commit 589d85bc7b8235).
How to reproduce
# Tag no-fasttest: needs the Parquet and DeltaLake readers.
# A Delta table read through a Unity DataLakeCatalog database must pick up a new column after a schema
# change, also when the database enables `allow_experimental_iceberg_compaction`.
USER_FILES=$(clickhouse-client --query "SELECT value FROM system.server_settings WHERE name = 'user_files_path'")
REL_DIR="test_repro/t"
TABLE_DIR="${USER_FILES%/}/${REL_DIR}"
STATE_FILE="${CLICKHOUSE_TMP}/test_repro_columns.json"
DB_PLAIN="default_unity_plain"
DB_COMPACTION="default_unity_compaction"
HTTP_PORT=$(python3 -c "
import socket
s = socket.socket()
s.bind(('127.0.0.1', 0))
print(s.getsockname()[1])
s.close()
")
echo '[["a", "long"]]' > "${STATE_FILE}"
python3 -c "
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
-- def table():
with open('${STATE_FILE}') as f:
cols = json.load(f)
return {'name': 't', 'catalog_name': 'unity', 'schema_name': 'default', 'table_type': 'EXTERNAL',
'data_source_format': 'DELTA', 'storage_location': 'file://${TABLE_DIR}',
'table_id': '11111111-2222-4333-8444-555555555555',
'columns': [{'name': n, 'nullable': True,
'type_json': json.dumps({'name': n, 'type': t, 'nullable': True, 'metadata': {}})} for n, t in cols]}
-- class Handler(BaseHTTPRequestHandler):
-- def do_GET(self):
-- if self.path.startswith('/api/2.1/unity-catalog/tables/unity.default.t'):
code, body = 200, table()
-- else:
code, body = 404, {'error_code': 'NOT_FOUND'}
data = json.dumps(body).encode()
self.send_response(code)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
-- def log_message(self, *args):
pass
HTTPServer(('127.0.0.1', ${HTTP_PORT}), Handler).serve_forever()
" &
HTTP_PID=$!
cleanup() {
kill $HTTP_PID 2>/dev/null
wait $HTTP_PID 2>/dev/null
clickhouse-client --query "DROP DATABASE IF EXISTS ${DB_PLAIN}; DROP DATABASE IF EXISTS ${DB_COMPACTION}" 2>/dev/null
rm -rf "${USER_FILES%/}/test_repro" "${STATE_FILE}"
}
trap cleanup EXIT
for _ in $(seq 1 50); do
curl -s "http://127.0.0.1:${HTTP_PORT}/" -o /dev/null 2>/dev/null && break
sleep 0.1
done
mkdir -p "${TABLE_DIR}/_delta_log"
clickhouse-client --query "
INSERT INTO FUNCTION file('${REL_DIR}/part-0.parquet', Parquet, 'a Nullable(Int64)') SELECT number + 1 FROM numbers(3);
INSERT INTO FUNCTION file('${REL_DIR}/part-1.parquet', Parquet, 'a Nullable(Int64), b Nullable(String)') SELECT number + 10, concat('v', toString(number)) FROM numbers(2);
"
# commit_file <version> <schema fields> <data file>
write_commit() {
python3 -c "
import json, os
fields = [{'name': n, 'type': t, 'nullable': True, 'metadata': {}} for n, t in json.loads('$2')]
actions = []
-- if $1 == 0:
actions.append({'protocol': {'minReaderVersion': 1, 'minWriterVersion': 2}})
actions.append({'metaData': {'id': '8c1a1f5e-0000-4000-8000-000000000001', 'format': {'provider': 'parquet', 'options': {}},
'schemaString': json.dumps({'type': 'struct', 'fields': fields}), 'partitionColumns': [], 'configuration': {}, 'createdTime': 1700000000000}})
actions.append({'add': {'path': '$3', 'partitionValues': {}, 'size': os.path.getsize('${TABLE_DIR}/$3'),
'modificationTime': 1700000000000 + $1, 'dataChange': True}})
with open('${TABLE_DIR}/_delta_log/%020d.json' % $1, 'w') as f:
f.write('\n'.join(json.dumps(a) for a in actions) + '\n')
"
}
write_commit 0 '[["a", "long"]]' part-0.parquet
CATALOG="DataLakeCatalog('http://127.0.0.1:${HTTP_PORT}/api/2.1/unity-catalog')"
SETTINGS="catalog_type = 'unity', warehouse = 'unity', vended_credentials = 0"
clickhouse-client --allow_database_unity_catalog 1 --query "
CREATE DATABASE ${DB_PLAIN} ENGINE = ${CATALOG} SETTINGS ${SETTINGS};
CREATE DATABASE ${DB_COMPACTION} ENGINE = ${CATALOG} SETTINGS ${SETTINGS}, allow_experimental_iceberg_compaction = 1;
"
run_queries() {
for db in ${DB_PLAIN} ${DB_COMPACTION}; do
label=$([ "$db" = "${DB_PLAIN}" ] && echo plain || echo compaction)
echo "$label columns: $(clickhouse-client --delta_lake_reload_schema_for_consistency 0 \
--query "DESCRIBE TABLE ${db}.\`default.t\`" | cut -f1 | paste -sd, -)"
clickhouse-client --delta_lake_reload_schema_for_consistency 0 \
--query "SELECT '$label', count(), sum(a) FROM ${db}.\`default.t\`"
done
}
echo "-- before the schema change"
run_queries
write_commit 1 '[["a", "long"], ["b", "string"]]' part-1.parquet
echo '[["a", "long"], ["b", "string"]]' > "${STATE_FILE}"
echo "-- after adding column b"
run_queries
for db in ${DB_PLAIN} ${DB_COMPACTION}; do
label=$([ "$db" = "${DB_PLAIN}" ] && echo plain || echo compaction)
clickhouse-client --delta_lake_reload_schema_for_consistency 0 \
--query "SELECT '$label', a, b FROM ${db}.\`default.t\` WHERE b IS NOT NULL ORDER BY a" 2>&1 \
| grep -oE "^$label.*|UNKNOWN_IDENTIFIER" | uniq
doneNote: an automated re-run of this exact block on current master (589d85bc7b82) did not show the failure; the analyst's run did (outputs below). Environment or ordering may matter.
Expected behavior
Expected output of the reproducer above:
-- before the schema change
plain columns: a
plain 3 6
compaction columns: a
compaction 3 6
-- after adding column b
plain columns: a,b
plain 5 27
compaction columns: a,b
compaction 5 27
plain 10 v0
plain 11 v1
compaction 10 v0
compaction 11 v1Error message and/or stacktrace
Actual output of the reproducer above on master (589d85bc7b8235):
-- before the schema change
plain columns: a
plain 3 6
compaction columns: a
compaction 3 6
-- after adding column b
plain columns: a,b
plain 5 27
compaction columns: a
compaction 5 27
plain 10 v0
plain 11 v1
UNKNOWN_IDENTIFIERGate want_stateful on the table format as well, e.g. add && table_metadata.getTableFormat() == DataLake::DataLakeTableFormat::ICEBERG (the setting is Iceberg-only and nothing else benefits from the long-lived storage). Alternative: keep caching but refresh the cached storage's columns from table_metadata.getSchema() on each hit; that costs an extra setInMemoryMetadata per query.
Same pattern as #121641 (found by: vector, fix_path; vector: cosine distance 0.22), #122547 (found by: lexical, vector; vector: cosine distance 0.25 (agrees with the lexical leg)).
Open risks:
- Other Delta properties captured at creation (partition columns of the legacy reader, catalog-vended static credentials) are frozen the same way for cached Delta tables; not tested.
Found during automated review of PR #122446; whether that PR introduced it could not be established, so nobody is tagged. Severity P2 · Finding h_pr122446_101
Source: ClickHouse/ClickHouse