AM07 silently misses a column-count mismatch when a CTE is wildcard-referenced twice in one set expression
Summary
Rule_AM07 (ambiguous.set_columns) checks that every branch of a set expression (UNION/INTERSECT/etc.) selects the same number of columns, resolving any SELECT * by looking up the underlying CTE. If the same CTE is referenced by an unaliased wildcard more than once in one set expression, only the first reference resolves — the second silently reports "unable to resolve", and since AM07 requires every branch to resolve before it reports anything, a real, unambiguous column-count mismatch goes completely unreported.
Impact: silent-wrong-result
Entry point / who reaches it: any user running sqlfluff lint (or fix) with AM07/ambiguous.set_columns enabled (it's in the default all rule group) on a query with a WITH CTE. Triggered when a set expression (UNION, UNION ALL, INTERSECT, EXCEPT) references the same CTE via a bare, unaliased SELECT * FROM <cte> more than once.
Reproduction:
WITH cte AS (
SELECT a, b FROM t
)
SELECT * FROM cte
UNION
SELECT * FROM cte
UNION
SELECT c, d, e
FROM t2Before this fix, sqlfluff lint --dialect ansi --rules AM07 on the above reports All Finished! — no violation — even though the three branches visibly select 2, 2, and 3 columns. A single-reference version of the same query (drop the second SELECT * FROM cte branch) is correctly flagged, which is what exposes the asymmetry: the bug is specifically the repeated unaliased reference.
Root cause
Rule_AM07.__resolve_selectable_wildcard (src/sqlfluff/rules/ambiguous/AM07.py) resolves a bare wildcard's CTE via root_query.lookup_cte(cte_name). Query.lookup_cte (src/sqlfluff/utils/analysis/query.py) defaults pop=True, deleting the CTE from the query's CTE scope once found. The sibling path used for aliased wildcard references (SELECT cte_al.* FROM cte AS cte_al) goes through Query.crawl_sources, whose own pop default is False — non-destructive. Both paths exist to answer the same question ("how many columns does this CTE-backed wildcard expand to?"), but only one of them consumes the CTE, for a reason that has nothing to do with AM07's own logic — it's a mismatched default carried over from a 2023 refactor (70c4f8b05, #5112), never revisited. None of the 39 existing fixtures in test/fixtures/rules/std_rule_cases/AM07.yml reference the same bare CTE name via wildcard twice in one set expression, which is why this was never caught.
Fix
Keep the pop-then-resolve behaviour — it exists to stop a CTE that (invalidly) references itself from recursing forever while it's being resolved — but put the CTE straight back into its owning scope once that resolution finishes, so a different selectable in the same set expression can still resolve a repeated reference to it.
I checked this doesn't reopen the recursion case it protects against: a CTE that references itself via an unaliased wildcard (invalid SQL, but sqlfluff's grammar still parses it, e.g. WITH cte AS (SELECT * FROM cte UNION ALL SELECT 1 AS n) SELECT * FROM cte UNION SELECT 1) still resolves without recursing, because the CTE is only restored after its own resolution completes, not during it. Added that case as a regression test too.
Testing (negative control — Lessons on reproducing by execution)
Added two cases to test/fixtures/rules/std_rule_cases/AM07.yml: the double-unaliased-wildcard mismatch above, and the self-referencing-CTE no-crash case.
With the production fix reverted (and only the new fixtures present), running the fixture suite fails exactly the new mismatch case and nothing else — proving the test actually depends on the fix, not merely that it passes:
$ pytest test/rules/yaml_test_cases_test.py -k AM07 -q
.......................................F. [100%]
FAILED test/rules/yaml_test_cases_test.py::test__rule_test_case[AM07_test_fail_repeated_unaliased_cte_wildcard_reference]
1 failed, 40 passed, 2467 deselected in 4.13sWith the fix restored:
$ pytest test/rules/yaml_test_cases_test.py -k AM07 -q
......................................... [100%]
41 passed, 2467 deselected in 5.38sAlso ran the full AM0* rule family (254 cases, all pass) to check for cross-rule regressions, plus ruff check, ruff format --check, yamllint -c .yamllint, and mypy -p sqlfluff.rules.ambiguous.AM07 — all clean.
AI assistance disclosure
This change was AI-assisted: an AI agent located the bug by reading AM07.py and its fixtures, proposed the initial diagnosis, and drafted the fix and regression tests. I manually validated it before submitting: I independently re-read the lookup_cte/crawl_sources default-parameter asymmetry in query.py myself rather than trusting the diagnosis as given; I ran the reproduction SQL through sqlfluff lint myself and read the actual output; I independently constructed and ran the self-referencing-CTE case to check the fix doesn't reintroduce unbounded recursion (confirmed no crash, both before designing the fix and after); and I ran the full test suite (negative control, full AM0* family, ruff/yamllint/mypy) myself and read the results shown above rather than taking a report of them at face value.
Signed-off-by: Udaya Tejas [email protected]
Source: sqlfluff/sqlfluff