Skip to content

Horizon Support in ClickHouse - #114547

Merged
asya-ch merged 5 commits into
ClickHouse:masterfrom
melvynator:feature/horizon-iceberg-catalog
Aug 21, 2026
Merged

asya-ch merged 5 commits into
ClickHouse:masterfrom
melvynator:feature/horizon-iceberg-catalog

Conversation

@melvynator

@melvynator melvynator commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Add support for Snowflake Horizon. It support read and write path. I tested it against my own catalog.

Changelog category (leave one):

  • New Feature

Changelog entry (a [user-readable short description]):

Add support for Snowflake Horizon. You can now query Iceberg table in Iceberg behind the horizon catalog. You can also write to the Iceberg table via the catalog.


Workflow [PR]
Sync PR [sync-upstream/pr/114547]

Version info

  • Merged into: 26.8.1.1869 (included in 26.8 and later)

@CLAassistant

CLAassistant commented Aug 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0667af]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3796) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

Adds catalog_type = 'horizon' support plus a fixed-Content-Length path for REST-catalog mutations, and improves the OAuth error surfaced for expired credentials. The read-side auth wiring is mostly coherent, but the write path is still unsafe under ambiguous commit failures, and the recommended PAT/JWT auth mode still bypasses the proxy-aware transport path it depends on.

Missing context / blind spots
  • ⚠️ The current clickhouse-gh issue comment only exposed a Build profile diff Praktika report, so I could not cross-check this branch against the usual functional/integration CI matrix. The focused regression requested below would close the main behavior gap anyway.
Findings

❌ Blockers

  • [src/Databases/DataLake/RestCatalog.cpp:1766-1796, src/Databases/DataLake/RestCatalog.cpp:1953-1965, src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1143-1176, src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1337-1352] [dismissed by author -- https://github.com/Horizon Support in ClickHouse #114547#discussion_r3773616627] Horizon writes still go through ReadWriteBufferFromHTTP's retryable POST path, and the caller still treats an ambiguous commit as something it can clean up locally. If the first updateMetadata POST commits and the connection fails before the response is read, the retry/cleanup path can delete the committed snapshot's manifest list / manifest files, and on the new non-409 branch even the data files, before retrying or throwing. That is not just a duplicate-append risk; it can leave the catalog pointing at objects we just removed.
    Suggested fix: keep the fixed Content-Length change, but send mutating catalog requests through a no-retry path or add an idempotency / de-dup mechanism, and never delete manifest / data objects after an ambiguous commit until the catalog state has been re-read and proven not to reference them.

⚠️ Majors

  • [src/Databases/DataLake/RestCatalog.cpp:799-823] [dismissed by author -- https://github.com/Horizon Support in ClickHouse #114547#discussion_r3772027912] The new Horizon catalog_credential mode still acquires its OAuth token through raw makeHTTPSession(..., {}), so it bypasses the proxy resolution / retry / backoff / default User-Agent path that the catalog requests use. In environments that can reach Snowflake only through an HTTPS proxy, the recommended PAT/JWT setup fails before the first catalog request is sent.
    Suggested fix: route token acquisition through the same BuilderRWBufferFromHTTP-based transport setup, or through a shared helper that at least resolves the proxy configuration and retries safely.
Tests
  • ⚠️ [src/Databases/DataLake/tests/gtest_rest_catalog.cpp:769] The added tests still stop at auth parsing and a metadata GET. The contract of this PR is that Horizon writes now work because commit requests are sent with a fixed Content-Length, but there is still no focused regression that sends createTable / updateMetadata to a fake server rejecting chunked bodies and passes only when the non-chunked write path is wired correctly.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 211/274 (77.01%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 12, 2026
@melvynator

Copy link
Copy Markdown
Member Author

Closes: #95341

@asya-ch asya-ch self-assigned this Aug 12, 2026
Comment thread src/Databases/DataLake/RestCatalog.cpp Resolved
Comment thread src/Databases/DataLake/RestCatalog.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c0667afb0 with master efcdc7def (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.51 MiB 701.46 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

26 object files changed (+49.39 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DataLake/RestCatalog.cpp.o 1.07 MiB 1.11 MiB +38.61 KiB (+3.52%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1870 translation units recompiled, 11328 s compile time in total, 1870 of them have a recent master baseline.

Job report

Adds catalog_type = 'horizon' for the Snowflake Horizon Iceberg REST
catalog: secret-only OAuth client credentials (PAT / key-pair JWT) with
session:role:<ROLE> scopes, plus auth_header for pre-exchanged tokens.

Catalog commit requests (createTable / updateMetadata / updateSchema /
dropTable) are now sent with an explicit Content-Length instead of
chunked transfer encoding, via a new BuilderRWBufferFromHTTP option,
because Horizon rejects chunked commit bodies with HTTP 500. The
builder path keeps proxy resolution, retries, redirects and User-Agent.

Catalog commit failures now surface the HTTP error to the client
(409 conflicts still trigger the optimistic-concurrency retry), and
best-effort cleanup after a failed commit no longer masks the original
error when the storage credentials lack DeleteObject.

Tested against a live Snowflake Horizon account (read and write) and
Databricks Unity Catalog (read and write) plus AWS Glue-style REST unit
tests.
@melvynator
melvynator force-pushed the feature/horizon-iceberg-catalog branch from 076424e to 344e80f Compare August 13, 2026 02:13
{"client_id", client_id},
{"client_secret", client_secret},
};
/// Snowflake Horizon OAuth uses secret-only credentials (PAT/JWT); omit empty client_id.

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.

The new Horizon catalog_credential mode still obtains its OAuth token through a raw makeHTTPSession(..., {}) call. That means the recommended PAT/JWT path bypasses the proxy resolution and retry/backoff plumbing that sendRequest now preserves through BuilderRWBufferFromHTTP: a deployment that can only reach Snowflake through an HTTPS proxy will still fail during the initial token exchange, before any catalog request is sent. Please route token acquisition through the same transport setup as the catalog requests (or a shared helper that resolves the proxy configuration) instead of hard-coding an empty ProxyConfiguration.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Existing issue, would be nice to fix here, but not a blocker for the PR.

}
}

TEST(RestCatalog, HorizonCatalogAuthenticatesWithBarePAT)

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.

The tests added here only cover auth parsing and a metadata GET, but the contract of this PR is that Horizon writes now work because commit requests are sent with a fixed Content-Length. There is still no regression that exercises createTable / updateMetadata against a fake server that rejects chunked request bodies, so the main behavior change in sendRequest and ReadWriteBufferFromHTTP is still unproven and could regress silently. Please add a focused test that fails on chunked bodies and passes only when the non-chunked write path is wired correctly.

.withOutCallback(out_stream_callback)
/// Send the JSON body with an explicit Content-Length: Snowflake Horizon rejects
/// chunked transfer encoding on catalog commits with HTTP 500 and an empty body.
.withOutCallbackFixedContentLength(body_str.size())

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.

Moving these mutating catalog requests onto BuilderRWBufferFromHTTP also opts them into ReadWriteBufferFromHTTP's generic retry loop. That is unsafe for updateMetadata: if the first POST reaches the catalog and commits, but the connection drops before we read the response, the client will replay the same body, the second attempt will hit 409, and IcebergWrites will treat that as a concurrent conflict and retry with the same data files. The result is a duplicated append even though the original commit already succeeded. Please keep the fixed Content-Length change, but route POST/DELETE through a no-retry path (or add an idempotency/de-dup mechanism) instead of reusing the read-path retry policy here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Existing issue, would be nice to fix here, but not a blocker for the PR.

@asya-ch asya-ch left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could you please leave a comment with the manual tests you ran? (With credentials and PII obscured.)

Not a blocker for the PR: In a follow-up, could consider adding a test to tests/integration/test_e2e_catalogs.

Otherwise everything looks good, just have a couple nits.

if (!catalog_credential_.empty())
{
std::tie(initial_state.client_id, initial_state.client_secret) = parseHorizonCredential(catalog_credential_);
if (initial_state.client_id.empty() && initial_state.client_secret.empty())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit:

Suggested change
if (initial_state.client_id.empty() && initial_state.client_secret.empty())
if (initial_state.client_secret.empty())

state.set(std::make_unique<const CatalogState>(std::move(initial_state)));
}

void HorizonCatalog::validateSettingsChanges(const DB::SettingsChanges & changes, bool credential_mode, bool header_mode)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: We can remove this function, and it'll call directly into the base class.

@asya-ch

asya-ch commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

Found a bug: the error message for expired credentials is confusing. I ran:

:) CREATE DATABASE horizon_live
ENGINE = DataLakeCatalog('...')
SETTINGS
    catalog_type = 'horizon',
    warehouse = 'ICEBERG_TEST_DB',
    catalog_credential = '{expired PAT token}',
    auth_scope = '...';
Received exception from server (version 26.8.1):
Code: 1000. DB::Exception: Received from localhost:9000. DB::Exception: Invalid access: Can not extract empty value.. (POCO_EXCEPTION)

I suggest the following to fix:

+    /// The body of a failed response is an OAuth error object, safe to show.
+    /// The URL is omitted: its query string can carry `client_secret`.
+    if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK)
+        throw DB::Exception(
+            DB::ErrorCodes::DATALAKE_DATABASE_ERROR,
+            "OAuth token request failed with status {} ({}): {}",
+            static_cast<int>(response.getStatus()), response.getReason(), json_str);
+
     Poco::JSON::Parser parser;
     Poco::Dynamic::Var res_json = parser.parse(json_str);
     const Poco::JSON::Object::Ptr & object = res_json.extract<Poco::JSON::Object::Ptr>();
 
+    if (!object->has("access_token"))
+        throw DB::Exception(
+            DB::ErrorCodes::DATALAKE_DATABASE_ERROR,
+            "OAuth token response has no `access_token` field: {}",
+            json_str);
+
     AccessToken token;
-    token.token = object->get("access_token").extract<String>();
+    token.token = object->getValue<String>("access_token");

@asya-ch

asya-ch commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

I will pick up the PR and fix the issue above. I also successfully ran the following on a test database:

CREATE DATABASE horizon_live
ENGINE = DataLakeCatalog('https://ixhmfwu-wp08988.snowflakecomputing.com/polaris/api/catalog')
SETTINGS
    catalog_type = 'horizon',
    warehouse = 'ICEBERG_TEST_DB',
    catalog_credential = '[redacted, not empty]',
    auth_scope = 'session:role:DATA_ENGINEER';
    
show tables from horizon_live;
 
select * from horizon_live.`PUBLIC.TEST_TABLE`;

INSERT INTO horizon_live.`PUBLIC.TEST_TABLE` VALUES (42, 'test_asya');

@asya-ch
asya-ch enabled auto-merge August 20, 2026 00:22
@asya-ch
asya-ch disabled auto-merge August 20, 2026 00:22
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

This is a sync of public PR #114547, which adds Snowflake Horizon Iceberg REST catalog support: new catalog type and auth handling, an optional fixed Content-Length for HTTP request bodies, best-effort Iceberg write cleanup, and docs. None of that touches the local MergeTree query-execution path that TPC-H exercises, so neither flagged delta is plausibly caused by this change. Q17's flagged +59.4% regression is downgraded to not-sure (the source measurements were also very noisy), and Q7's +16.4% stayed within the baseline variance band. No real performance impact expected from this PR.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 78 +16.4% <0.0001 This PR only adds Snowflake Horizon Iceberg catalog plumbing and HTTP handling, which Q7 never executes, so the +16.4% is run-to-run variance within the baseline band.
⚠️ 17 not_sure 64 102 +59.4% <0.0001 The +59.4% delta cannot come from this PR: it only touches DataLakeCatalog/Iceberg REST and HTTP content-length plumbing, not the local join/aggregation path Q17 runs, and the source runs were very noisy.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 2f264b94-3738-4a1d-8ccc-1a91a672a858
  • MIRAI run: 5c81b69c-4247-4728-8659-bbefbbfdfa4e
  • PR check IDs:
    • clickbench_377043_1787284644
    • clickbench_377049_1787284644
    • clickbench_377060_1787284644
    • tpch_adapted_1_official_377070_1787284644
    • tpch_adapted_1_official_377083_1787284644
    • tpch_adapted_1_official_377113_1787284644

@asya-ch
asya-ch enabled auto-merge August 21, 2026 17:01
@asya-ch
asya-ch added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 342d96b Aug 21, 2026
176 of 178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
Resolves one content conflict in RestCatalog::updateMetadata, where master's
Snowflake Horizon support (ClickHouse#114547) rewrote the same catch (HTTPException)
block this branch replaces.

Master's rewrite kept 409 returning false and made every other HTTP failure
throw a wrapped DATALAKE_DATABASE_ERROR instead of returning false. This
branch's classification is a strict superset of that intent: an undispatched
request rethrows its own error, a 409 returns false, a non-retryable status
rethrows, and only a dispatched retryable failure is classified against a
read-back of the main ref. The single behavioural difference is the case the
branch exists to fix, where the read-back proves the snapshot did commit and
master would report a failure for a commit that took effect.

The rest of master's changes to the function auto-merged and are kept: the
unconditional assert-ref-snapshot-id requirement, the explicit Content-Length
on catalog commits, the X-Iceberg-Access-Delegation header and the request
body trace. HorizonCatalog inherits updateMetadata and sendRequest unchanged,
so the new read_settings parameter needs no adjustment there.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 24, 2026
Master's ClickHouse#114547-era docs rework restructured the Iceberg support matrix from
three columns (Feature | Status | Notes) to four (Feature | ClickHouse Cloud |
Self-managed | Notes), rewriting every row this branch had edited. Resolved by
taking master's structure and re-applying this branch's four corrections on top
of it, so none of master's new per-tier statuses are lost:

- Compaction: master's row no longer says what compaction does. Data compaction
  is behind #if CLICKHOUSE_CLOUD (IcebergMetadata.cpp:455), so the self-managed
  build reports NOT_IMPLEMENTED. Stated against the Self-managed column, which
  expresses the split more precisely than the single column this branch had.
- UPDATE / MERGE: dropped the "See Compaction" pointer, which pointed readers at
  an operation that also refuses.
- Expire snapshots: added that a transactional catalog is rejected
  (ExpireSnapshotsExecute.cpp:674).
- Remove orphan files: added that reachability resolves through version-hint.text
  (Utils.cpp:1322 via SnapshotFilesTraversal.cpp:132), so a stale hint can
  classify committed files as orphans.

The two source files auto-merged. Verified that every master addition to them is
present in the result and that this branch's NOT_IMPLEMENTED refusal survives
intact. Master did not touch any of the ten test files this branch changes, so
the merge removes no test coverage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants