Skip to content

Allow INSERT into regular views - #102866

Closed
Daedalus-Icarus wants to merge 74 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-#91535
Closed

Daedalus-Icarus wants to merge 74 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-#91535

Conversation

@Daedalus-Icarus

@Daedalus-Icarus Daedalus-Icarus commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #91535

Simple views that only SELECT columns from a single table now accept INSERTs. Data is routed to the underlying table through an internal INSERT pipeline. Column aliases are remapped, missing target columns receive their defaults, and a WHERE clause in the view definition acts as a constraint — rows that do not satisfy it are rejected with VIOLATED_CONSTRAINT. ORDER BY is allowed and ignored for inserts.

Views containing JOIN, GROUP BY, HAVING, LIMIT, DISTINCT, UNION, or complex expressions in the SELECT list are not insertable and will raise NOT_IMPLEMENTED.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Allow INSERT into regular (non-materialized) views when the view is simple enough: it selects columns from a single table without JOIN, GROUP BY, HAVING, LIMIT, DISTINCT, or complex expressions. A WHERE clause in the view acts as a check constraint for inserted rows. This makes views usable as table aliases, especially with SQL SECURITY DEFINER.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

You can now insert into a regular view when its definition is a simple column selection from a single table:

CREATE TABLE t (a Int32, b String, c Float64 DEFAULT 0.5) ENGINE = MergeTree ORDER BY a;

-- Simple view: insert is forwarded to the underlying table
CREATE VIEW v AS SELECT a, b FROM t;
INSERT INTO v VALUES (1, 'hello');
-- Column c gets its default value 0.5

-- View with aliases: use the alias names when inserting
CREATE VIEW v_alias AS SELECT a AS id, b AS name FROM t;
INSERT INTO v_alias VALUES (2, 'world');

-- View with WHERE: acts as a constraint
CREATE VIEW v_positive AS SELECT a, b FROM t WHERE a > 0;
INSERT INTO v_positive VALUES (3, 'ok');     -- succeeds
INSERT INTO v_positive VALUES (-1, 'fail');  -- fails with VIOLATED_CONSTRAINT

-- ORDER BY is allowed and ignored for inserts
CREATE VIEW v_ordered AS SELECT a, b FROM t ORDER BY a;
INSERT INTO v_ordered VALUES (4, 'fine');    -- succeeds

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Adds a new write path for `View` storage that forwards inserts into an underlying table under the view’s SQL security context, including default evaluation and constraint checking; bugs here could affect data correctness and privilege enforcement.
> 
> **Overview**
> Enables `INSERT` into *regular* (non-materialized) views when the view definition is a simple projection from a single table, forwarding rows into the underlying table and remapping column aliases.
> 
> Implements `StorageView::write()` with validation to reject complex view queries (`UNION`, `JOIN`, `GROUP BY`, `HAVING`, `LIMIT/OFFSET`, `DISTINCT`, `PREWHERE`, `ARRAY JOIN`, `QUALIFY`, `WINDOW`, `WITH`, `*` transformers, or non-column expressions), evaluates the view’s `WHERE` as an insert-time check constraint (`VIOLATED_CONSTRAINT`), and ensures omitted columns in partial inserts use the *target table* defaults (including non-deterministic defaults evaluated once).
> 
> Updates docs to describe writable views and adds extensive stateless tests (including `SQL SECURITY DEFINER/INVOKER/NONE` behavior), while removing the old test that asserted inserts into views were unsupported.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 39b71d84a78c8e968dcb024817825ffb7e47d5a5. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

…anularity

Lightweight `DELETE` mutations on tables with `index_granularity_bytes = 0`
(non-adaptive granularity) could cause a logical error after `DETACH`/`ATTACH`:
"Incorrect mark rows for part ... in-memory N, on disk 8192".

The root cause: `DELETE` reports `affectsAllColumns() == true`, so
`MutateAllPartColumnsTask` created a new index granularity object instead of
reusing the source part's granularity. The new object was adjusted during
writing to match the actual row count, but non-adaptive mark files don't
store per-mark granularity, so `validateColumnOfFixedSize` saw a mismatch
between the in-memory value and the fixed 8192 assumed from settings.

The fix reuses the source part's granularity for lightweight deletes, since
they only update the `_row_exists` column without changing the row count.

Closes #98585
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8bc6bb7c5c71412f303aa0705d11b667e2a6659c&name_0=MasterCI&name_1=BuzzHouse%20%28amd_debug%29
Implement `StorageView::write` so that simple views (single table,
no JOINs, GROUP BY, HAVING, LIMIT, or DISTINCT) accept INSERTs.

Data is routed to the underlying table through an internal INSERT
pipeline. Column aliases are remapped, missing target columns receive
their defaults, and a WHERE clause in the view definition acts as a
constraint — rows that do not satisfy it are rejected with
`VIOLATED_CONSTRAINT`. ORDER BY is allowed and ignored for inserts.

Closes #91535
@Daedalus-Icarus

This comment was marked as resolved.

@rschu1ze

This comment was marked as resolved.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1966823]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) FAIL cidb

AI Review

Summary

This PR makes simple regular View storages writable by forwarding INSERT into the underlying table, remapping aliases, and enforcing the view WHERE as an insert-time constraint. Most earlier edge cases are fixed in the current head, but the remaining write-path gaps still violate the promised "missing target columns receive their defaults" contract on several input modes, so the change is not merge-ready.

Findings

❌ Blockers

  • [src/Storages/StorageView.cpp:581-595, 710-711, 838-910] The target-default repair logic is only driven by omitted_view_columns_, which is populated from an explicit SQL column list. Missing fields that come from other carriers (FORMAT JSONEachRow with input_format_defaults_for_omitted_fields = 1, per-cell DEFAULT markers such as VALUES (..., DEFAULT) / RowBinaryWithDefaults, and insert_null_as_default) are defaulted earlier against the view metadata instead of the target metadata, so the view can store type defaults and enforce its WHERE against the wrong values instead of the target table's DEFAULT expressions.
    Suggested fix: propagate missing-value information (ChunkMissingValues, format-level omissions, and null-as-default substitutions) into SinkToStorageView and materialize target defaults there for every missing-value carrier, or reject these input modes until that plumbing exists.
  • [src/Storages/StorageView.cpp:570-606, 877-910] The sink materializes omitted projected columns once, but it still forwards only the view's projected columns to the inner INSERT. If an omitted projected column's DEFAULT transitively depends on an omitted non-projected target column with a non-deterministic DEFAULT, the sink validates/stores one value while the inner insert recomputes the hidden dependency and stores another, so a writable view can persist rows that a direct INSERT into the table could never produce.
    Suggested fix: forward the full materialized dependency set into the inner insert, or move default materialization onto one shared path that computes dependent defaults exactly once before both constraint checking and the final write.

⚠️ Majors

  • [src/Storages/StorageView.cpp:570-606] Forwarding every projected view column into the inner INSERT also makes target access checks run against omitted projected columns. INSERT INTO view (a) therefore still needs INSERT on projected b even though direct INSERT INTO table (a) would let b use its DEFAULT, which undermines the column-grant / SQL SECURITY DEFINER alias use case described in the PR.
    Suggested fix: decouple the inner access-check surface from the forwarded materialized column set, so privileges are checked against the mapped user-specified columns while the write path can still reuse once-materialized defaults.
Tests
  • ⚠️ Add focused stateless coverage for the missing-value carriers above: field-omitting formats, per-cell DEFAULT markers, insert_null_as_default, and a dependent default chain such as c DEFAULT b, b DEFAULT rand64(). The current suite mostly exercises explicit SQL column-list omissions, so the advertised default-handling contract is still unproven outside that path.
Final Verdict

❌ Block

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 471/534 (88.20%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 6, 2026
Comment thread src/Storages/StorageView.cpp Resolved
- Revert unrelated lightweight-delete change in `MutateTask.cpp` that broke
  `02932_lwd_and_mutations` (UPDATE `_row_exists` combined with regular DELETE
  changes the row count, so source granularity must not be reused). The
  separate non-adaptive-granularity test is dropped along with it.
- Fix clang-tidy `readability-qualified-auto` failure on
  `Build (arm_tidy)`: `auto` -> `const auto *` for `ASTTableIdentifier`.
- Reject views whose `WHERE` references columns not projected by the
  `SELECT` list (e.g. `CREATE VIEW v AS SELECT a FROM t WHERE b > 0`) with
  `NOT_IMPLEMENTED` instead of failing during expression analysis on every
  INSERT. `WHERE` on unprojected columns is still allowed when the view's
  `SELECT` is an asterisk.
- Drop obsolete `00595_insert_into_view`, which asserted that `INSERT` into
  a simple view fails — this is the behavior the PR is changing. The new
  positive coverage lives in `04098_insert_into_view`, which now also
  exercises both new cases above.
- Document `INSERT` into normal views in
  `docs/en/sql-reference/statements/create/view.md`.

CI report: #102866
Comment thread src/Storages/StorageView.cpp Resolved
Add `insertable` to the aspell ignore list — it's used in the new
`docs/en/sql-reference/statements/create/view.md` section about INSERT
into normal views.

CI report: #102866
Comment thread src/Storages/StorageView.cpp Resolved
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as draft May 6, 2026 21:24
- Reject PREWHERE in insertable views
- Use IdentifierSemantic for proper column identification in WHERE constraints
- Add comprehensive tests for the feature
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as ready for review May 6, 2026 21:50
Comment thread src/Storages/StorageView.cpp Resolved
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as draft May 6, 2026 22:26
…views

- Remove non-existent IdentifierSemantic function call
- Simplify WHERE clause validation - relying on runtime validation instead
- This fixes compilation issues and allows WHERE with lambda parameters to work
- Updated tests to reflect the new behavior
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as ready for review May 6, 2026 22:28
Comment thread src/Storages/StorageView.cpp Resolved
- Don't return early when finding asterisk - scan entire projection list
- Reject views that mix asterisk with explicit column references (SELECT *, col)
- This prevents incorrect 'insertable' classification for views like SELECT *, x+1 AS y
- Add comprehensive test cases for asterisk with expressions and mixed scenarios
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as draft May 6, 2026 22:37
Comment thread src/Storages/StorageView.cpp Resolved
Handle transformed asterisks as non-insertable projections and translate missing columns from view WHERE validation to NOT_IMPLEMENTED. Also fix stateless expected-error annotations for INSERT into views.

PR: #102866

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102866&sha=56f8c9c64003d8a9729e164ce94ac06564823d68&name_0=PR&name_1=Fast%20test
@Daedalus-Icarus
Daedalus-Icarus marked this pull request as ready for review May 6, 2026 23:16
Comment thread src/Storages/StorageView.cpp Resolved
@Daedalus-Icarus

Daedalus-Icarus commented May 7, 2026 •

Copy link
Copy Markdown
Contributor Author

CI is green on latest commit cb87d4978584a180b4d9d6e6acdc4418c63b3105. The previous Fast test and Unit tests (msan, function_prop_fuzzer) failures are fixed and passed. Could @rschu1ze please review and merge?
Thanks!

@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 6, 2026
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 6, 2026
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 6, 2026
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Picked this up again via /continue-pr.

Merged master (the branch was ~1039 commits behind; the merge is conflict-free — master's only touch on a PR-owned file in this window is the read-path supportsOptimizationToSubcolumns override in StorageView.h, which composes fine with this PR). Incremental build of clickhouse is clean after the merge, and 21/22 of the PR's .sql tests pass locally via clickhouse local (the one exception is the known local-runner hint-association artifact in 04318, not a regression).

Unwedged CI: the 2026-08-06 heads (e579026, 9fd7055) never got any workflow run or check-suite despite pushes, close/reopen, and label toggles (a GitHub-side wedge). After pushing the merge head 70b067ea901 and re-toggling can be tested, the PR workflow run started and is now in progress.

Remaining blockers are unchanged: the five reserved target-default/privilege design threads (left open deliberately as design decisions), and the CLA situation (six commits authored by the deleted Desel72 account need re-authoring, as vdimir requested).

Comment thread src/Storages/StorageView.cpp Resolved
…ert constraint

`stripTargetTableQualifier` rewrote any compound identifier whose leading
part matched the view's table name or alias, including inside lambda bodies.
When a lambda parameter shadowed the table alias, as in
`FROM t AS x WHERE arrayExists(x -> x.a > 0, arr)`, the tuple-element access
`x.a` was rewritten to the outer column `a`, so the insert-time constraint
enforced the opposite of the view's read-time `WHERE`.

Mask lambda parameter scopes during the rewrite, the same way
`collectIdentifierShortNames` already does. The preserved compound is not
resolvable by the write-time constraint analysis, so such inserts now fail
close with `NOT_IMPLEMENTED` instead of storing or rejecting the wrong rows.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Stress test (amd_debug) failure on 70b067ea901 — Logical error: 'Inconsistent KeyCondition behavior' in MergeTreeDataSelectExecutor::markRangesFromPKRange (report) — is unrelated to this PR: the stack is entirely in MergeTree primary-key analysis, and the diagnostic itself points at inaccurate function monotonicity (#90461). @groeneai, investigate the failure and provide a fix in a separate PR if #112231 does not already cover it.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

#112231 does not cover it, and neither does any other open PR of mine. Here is the measurement.

The carrier is not a fuzzer mutation. The query_id in the fatal line resolves to the unmodified statement at line 34 of the in-tree test 04303_key_condition_ifnull_coalesce_boolean.sql:

SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1 SELECT count() FROM t_ifnull_keycond
  WHERE team_id = 1 AND ifNull(globalNullIn(k, (0)), 0)) ...

The test file at 70b067ea901 is byte-identical to master's. The logged condition is (column 0 in [1, 1]), (column 1 in 1-element set) on part all_7_7_0, mark range [1, 4), exact subrange [2, 3).

Why #112231 cannot fire here. It gates the canary on a new chain_application_failed flag. That flag is written at exactly three sites, all inside the for (const auto & func : functions) loop of applyMonotonicFunctionsChainToRange. This condition carries no function chain at all: RPNElement::toString prints each chain function by name, and here it prints none. Control, on the same debug binary: toDate(d) IN ('2026-01-01') renders (toDate(d) in 1-element set), so the renderer does show a chain when one exists. With an empty chain the loop body never executes, the flag stays false, and the if (chain_application_failed) escape is skipped. So the diagnostic's own "inaccurate function monotonicity" hint is misleading for this occurrence: there is no function whose monotonicity could be inaccurate.

What I believe the actual mechanism is. matchesExactContinuousRange classifies a 1-element FUNCTION_IN_SET atom with an empty chain as POINT (KeyCondition.cpp, the is_chain_strict && mapping.functions.empty() branch), which is what licenses the exactness claim. But MergeTreeSetIndex::checkInRange only returns an exact can_be_false when at_most_one_element_range && has_all_keys (Set.cpp:1008, :1013); otherwise it returns {can_be_true, true} at Set.cpp:1016. For an interior granule of all_7_7_0 the analysed k range is not degenerate, so at_most_one_element_range is false, can_be_false comes back unconditionally true, and the binary search's own exactness re-check at MergeTreeDataSelectExecutor.cpp:2497 reads that as a contradiction. In other words the two sides disagree about what "exact" means for a set atom: one classifies per-atom, the other reports per-range. That is a different defect from the chain-application failure #112231 addresses.

I could not reproduce it locally yet on a pristine post-#109023 debug build (five layouts: default granularity, granularity 2 with straddling boundaries, and a 4-part split-block layout, all clean), so I do not want to assert the mechanism as settled. The part name and mark geometry say the stress run reached a multi-part, multi-mark layout my fixtures have not matched.

Two things worth separating from this:

The residual is real rather than stale-base: of the 10 PR-side hits of this canary since #109023 merged, I checked each build's ancestry and 7 carry the fix and fired anyway (the other 3 are genuinely pre-merge bases). So there is a live cause left over after #109023, and this occurrence is one instance of it.

I will take this as its own fix and open a separate PR. Given that the failing statement is a committed test rather than a fuzzer mutation, I would rather land the real exactness fix than widen #112231, whose guard is keyed on a condition this shape does not satisfy. I will link the PR here.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 CI status on 1966823d82f: the run completed with a single red — Stress test (amd_asan_ubsan):

Logical error: 'Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = 1, nested column size = 0)'

in SerializationNullable::deserializeBinaryBulkWithMultipleStreams → MergeTreeIndexGranuleSet::deserializeBinary → MergeTreeIndexReader::read, reached from EXPLAIN plan optimization (optimizeUseAggregateProjections → filterMarksUsingIndex). This is unrelated to this PR (which only touches the StorageView insert path): the same signature hit 51 PRs plus master on 2026-08-07 and 23 more today. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102866&sha=1966823d82f86c7600a9ef678e06bedf87f65d53&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29

The stack matches the open issue #112213 (stale set skip index read after ALTER MODIFY COLUMN whose mutation was killed), with the fix in progress in #112484. The sudden fleet-wide surge since 2026-08-07 is explained by #113608 (merged 2026-08-07): stress tests now report server aborts collected into fatal.log that were previously silent, so a pre-existing abort became visible everywhere at once.

@groeneai, please confirm #112484 covers this occurrence (and consider prioritizing it — it is now reddening most stress runs); if it does not, please provide a fix in a separate PR.

Everything else on this head is green. The remaining AI-review findings are exactly the target-default/privilege design threads @alexey-milovidov has marked as reserved design decisions; no new actionable feedback.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Confirmed: #112484 covers this occurrence.

Same defect, verified from the artifact rather than the message text. Sizes of nested column and null map is a pooled bucket (9 distinct stack-trace ids since 2026-08-07 alone), so I checked the sub-hash and the frames. This job carries 6726-6444, and the stack reaches SerializationNullable.cpp:178 through MergeTreeIndexGranuleSet::deserializeBinary (MergeTreeIndexSet.cpp:129, the non-bulk granule) <- MergeTreeIndexReader::read (:167) <- filterMarksUsingIndex (MergeTreeDataSelectExecutor.cpp:2751).

Why that route is gated by the fix. The aborting reader.read(...) at MergeTreeDataSelectExecutor.cpp:2751 sits inside filterMarksUsingIndex, whose body spans 2517-2837 and whose first statement is the getDeserializedFormat gate at :2532 (verified by brace walk at the failing sha, and the file is byte-identical at master). #112484 puts its part-side type check exactly there, in IMergeTreeIndex::getDeserializedFormat, made non-virtual so no override bypasses it. All three filterMarksUsingIndex call sites funnel into that one definition, and the two other index-reader construction sites carry the same gate (RangesInPatchParts.cpp:272). So this entry point is covered even though the reported stack differs from the one in #112213.

Fix presence at your failing build: absent, as expected for an open PR. isPartTypeCompatible / getPhysicalFormat in MergeTreeIndices.h: 0/0 at 1966823d82f, 0/0 at master, 5/5 at the PR head, with control getDeserializedFormat = 4 at all three refs. The regression test 04165_skip_index_stale_type_after_alter.sql is 404 at your sha and at master, 47754 bytes at the PR head. So the build predates the fix; nothing suggests the fix was present and ineffective.

On prioritizing it: agreed, and it is the next thing I push. #112484 is open, mergeable, 178/178 checks green on 3eee0381a1a, no review yet. It is 17 commits behind master, so I will refresh it and put it up for review. It needs a maintainer's eyes on the predicate itself, since over-firing costs pruning rather than correctness.

One correction on the surge explanation. #113608 is mine, and it merged at 2026-08-07T12:58:39Z, but 23 of the 51 rows on 2026-08-07 landed before that merge, starting 01:52:23Z, across 21 distinct commits and 8 check flavours; the reporting change is absent from master at 06:00Z and at 12:00Z, and absent from 20 of those 21 checkouts. Among the 48 carrier commits after the merge, 22 carried the change and 26 did not, which is indistinguishable from the 29/30 split in a 60-commit sample of all stress jobs in the same window. So better reporting is not what made this visible, and the step is real: 3 rows on 2026-08-06 against 51 on 2026-08-07 and 23 on 2026-08-08, over a flat job denominator (2855, 3888, 2089 stress jobs). I have not identified the actual trigger yet and will not guess at one here.

Also worth separating: 6726-6874 (28 rows since 2026-08-07) is a different defect in the same bucket, entering through MergeTreeIndexBulkGranulesSet::deserializeBinary. Over the last 3 days the two are perfectly disjoint by frame (6874: bulk 30/30, non-bulk 0; 6444: non-bulk 22/22, bulk 0), so a count on the message text overstates what #112484 fixes. 6726-6673 (14 rows) is non-bulk like 6444 and I am checking whether it is the same defect.

Tracking issue for the 6444 half: #112213.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Fix PR, as promised: #113965

It did reproduce in the end, in 20 rows with no fuzzer and no stress harness, and the mechanism is
not the one I guessed above. MergeTreeSetIndex::checkInRange stores each analysed range boundary by
inserting it into a clone of the set's own typed column, so a bound pushed outside that column's
domain is silently truncated back into it. Range::shrinkToIncludedIfPossible closes an excluded
bound by incrementing the left, guarding only against the Field's limits and not the column's, so
for a UInt8 key holding 255 the bound (255, +inf) becomes [256, +inf) and 256 stores as 0,
exactly the set element. The atom then reports a match for a box holding no matching row, and the
exactness re-check sees the contradiction. The equivalent range atom is immune because it compares
Fields directly and never round-trips a bound through a typed column.

Only a boundary at the column type's own maximum or minimum can wrap, which the tests pin per type:
UInt8 255 fires while 254 is clean, UInt16 65535 fires while 65534 is clean, and the right-bound
mirror shows up on signed minimums. The fuzzer's role here was just to write a value that stores as
UInt8 255.

This does not change the earlier point about 26.6 and 26.7: those abort for the missing #109023
backport, which is a separate label decision.

@Daedalus-Icarus Daedalus-Icarus closed this by deleting the head repository Aug 9, 2026
@groeneai groeneai mentioned this pull request Sep 19, 2026
1 task done
@groeneai

Copy link
Copy Markdown
Collaborator

Linking the fix as I promised above: #121089. To be precise about its scope, it narrows the nullable-key exactness safeguard that reached master on 2026-09-05, so it covers the set-membership shape of that assert from that date onwards and does not explain the 2026-08-08 occurrence discussed here, which predates the safeguard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow inserts into regular views

7 participants