Skip to content

Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) - #1582

Merged
laughingman7743 merged 16 commits into
masterfrom
fix/1575-time-travel-hint-placement
Nov 30, 2026
Merged

laughingman7743 merged 16 commits into
masterfrom
fix/1575-time-travel-hint-placement

Conversation

@laughingman7743

@laughingman7743 laughingman7743 commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

WHAT

AthenaStatementCompiler.format_from_hint_text() places a time-travel hint (FOR TIMESTAMP AS OF, FOR SYSTEM_TIME AS OF, FOR VERSION AS OF, FOR SYSTEM_VERSION AS OF) before an alias in two more cases. The change stays inside format_from_hint_text(). It uses no private SQLAlchemy API, renders the hint text unchanged, and keeps the fallback to SQLAlchemy's default placement.

  • Alias generated by SQLAlchemy. In a SELECT, SQLAlchemy can alias a table without a schema when the FROM clause also has an unaliased table of the same name with a schema (FROM events AS events_1, db.events). SQLCompiler.visit_table() then passes the table followed by that alias.
    • For a time-travel hint on such a table, the text is split after SQLCompiler.visit_table(self, table, asfrom=True), which renders the table without the generated alias. The hint goes between the two parts: FROM events FOR VERSION AS OF 1 AS events_1, db.events.
    • The split needs whitespace, AS in any case, and whitespace right after the table.
    • Everything else keeps SQLAlchemy's default placement:
      • a table without an alias
      • a table that is a DML target (SQLAlchemy can generate an alias for one inside a CTE)
      • text that a subclass hook appended
      • a table that a hook renders under another name (the table is rendered again only when the text has AS, and an error from that rendering falls back)
  • Whitespace. The hint is recognized by matching hint.upper() against [ \t\r\n]*FOR[ \t\r\n]+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)[ \t\r\n]+AS[ \t\r\n]+OF. This replaces the four startswith() prefixes. The only change in recognition is whitespace: leading whitespace, and line breaks, tabs or repeated spaces between the keywords (as in a triple-quoted string). Upper-casing (hint.upper(), which keeps the case of a quoted_name with quote=True) and prefix matching are the merge base's.
    • for version as of, FOR VERſION AS OF (U+017F, which str.upper() folds to S) and FOR VERSION AS OFTEN are recognized as before.
    • FOR VERSİON AS OF (U+0130) and a NO-BREAK SPACE between the keywords are not recognized, as before.
  • docs/sqlalchemy.md (time travel) states when SQLAlchemy can generate the alias and that the table itself goes to with_hint().

The split check, the recognition and the scope below were decided by the maintainer after Codex and Claude Fable 5.2 were consulted.

Scope of the guarantee.

  • PyAthena guarantees the placement for SQLAlchemy's own SELECT rendering, with explicit and generated aliases.
  • A compiler hook that renders a table itself gets the same placement only when its text continues the table, as SQLCompiler.visit_table() renders it, with AS and a name.
  • Any other text keeps SQLAlchemy's default placement, with the original text and hint. This includes text without AS, and a table or alias that SQLAlchemy cannot render: the comparison with the hook's text (_split_alias()) falls back on any error.
  • Hints and names are compared only as str (subclasses included), as SQLAlchemy annotates them. Types are checked with type(), which a proxy or mock cannot fake. A hint of any other type (UserString, bytes, None, a mock) is not read, and a table or alias whose name or schema is of another type is not rendered again; both keep the default placement. For such inputs PyAthena guarantees only that it adds no exception; differences in their output are not regressions.
  • A str subclass that overrides str methods (for example markupsafe.Markup) is out of scope. SQLAlchemy's identifier preparer caches such a name whenever SQLAlchemy itself renders the table, with the same effect on later statements.
  • For a time-travel hint placed before an alias, super().format_from_hint_text() receives the table text without the alias, whatever made the alias, as for explicit aliases since Render the time-travel hint of an aliased table before its alias #1547. A hook later in the MRO that overrides format_from_hint_text() and reads an alias from its sqltext is out of scope, even if the statement compiled on the merge base: its output there put the hint after the alias, which Athena rejects.
  • The comparison renders the table or alias with SQLCompiler.visit_table()/visit_alias(), which caches names in the dialect's identifier preparer exactly as SQLAlchemy does when it renders that element, one of its columns, or any same-named table in any statement. What a later rendering gets back from that cache, including its str subclass, is out of scope.
  • Hook support is best effort and outside this guarantee.

Review stop rule (maintainer decision after consulting Codex and Claude Fable 5.2). The next independent round is the final one. After it, only these are actionable:

  • A difference from the merge base, in output or in a raised exception, for statements compiled without compiler hooks whose names and hints are str or quoted_name.
  • Inaccurate comments, docs, or tests in this diff.

Findings that need a subclass hook, another name or hint type, or shared preparer state are recorded on the PR and not fixed. Repairs are checked by one round limited to the repair diff.

Not changed:

WHY

Fixes #1575 (part of #1494). Both cases rendered the hint after the alias, which Athena rejects with a syntax error. Before #1547, the generated-alias case raised AttributeError.

This is a compatible fix for 4.x too. The 4.x backport of #1503 (#1578) has been merged, so this PR needs its own 4.x backport. The patch applies cleanly to the current 4.x (a23d009), and the differential check gives the same output there.

TEST

Tested commit: 6dcc562 (rebased onto master 244632e; the patch series is unchanged by git range-diff, apart from the context of one test helper).

  • just lint and just docs lint: passed.

  • just test offline: 4811 passed, 2 skipped (after the rebase).

  • tests/pyathena/sqlalchemy/test_compiler.py -k "time_travel or hint", offline:

    • 36 passed on SQLAlchemy 2.0.52 (the master minimum) and 2.1.9 after the rebase. Before it, 36 passed on 2.0.44, 2.0.46 and 2.0.52.
    • With the test changes applied to the current 4.x (a23d009, which supports SQLAlchemy 2.0.23 or later): 36 passed on 2.0.23 and 2.1.9, under Python 3.12. SQLAlchemy 2.0.23 does not import on Python 3.15, the project's default.
  • New tests:

    • Generated alias (2). Fails on the merge base.
    • Whitespace cases (2). Fails on the merge base.
    • A generated alias rendered by a hook with a lower-case as and a comment that reads the alias name (1). Fails on the merge base.
    • A table renamed by a hook (6). Passes on the merge base. The cases are: a plain rename; a rename with an alias; a schema that SQLAlchemy cannot render under schema_translate_map; an empty name; an int name; and AS without a name.
    • A hooked table named by a UserString or by a proxy that reports str as its class, next to a table named events (2). Passes on the merge base. It checks that the comparison leaves the identifier preparer's quoting cache alone.
    • An alias that only a hook can name (2: an int name and a UserString name), which also checks that the name is not left in the identifier cache. Fails on the merge base, which raised there.
    • update(t).with_hint(None) renders no hint (1). Passes on the merge base.
    • An empty UserString or bytes hint on a table renders no hint (2). Passes on the merge base.
    • A hint that only passes isinstance(x, str) (a mock whose upper() raises) is not read (1). Fails on the merge base, which read it.
    • A hook after the Athena compiler receives the table text of a generated alias as a plain str (1). Fails without the fix.
    • An UPDATE target inside a CTE, which SQLAlchemy gives a generated alias, keeps the default placement (1). Passes on the merge base.
    • The extended appending-hook test (1). Passes on the merge base.
  • Mutation check of format_from_hint_text(). Each mutant fails at least one test:

    • dropping not iscrud
    • reading a hint that is not a str, or checking it with isinstance()
    • rendering a table whose name is not a str again, or checking it with isinstance()
    • probing get_render_as_alias_suffix("")
    • dropping the AS check
    • matching only upper-case AS
    • matching only a literal AS
    • dropping .upper()
    • dropping the leading whitespace
    • single spaces only
    • handling aliases only
    • replacing the alias endswith() check with True

    Four mutants are not caught by a test.

    • Splitting an alias with endswith() changes only the output for a name that is not a str, which the scope excludes.
    • Narrowing except Exception to CompileError, IndexError and AttributeError survives, because the str checks now stop the tested non-string names first; the broad except stays as decided.
    • The AS pre-check and the lookbehind change only the running time and were measured instead. Dropping the lookbehind of the AS pattern: a hook returning events plus 8192 spaces compiles in 0.2 ms, and without the lookbehind in 132 ms (36 ms at 4096 spaces). Dropping the AS pre-check: it only skips a needless rendering.
  • Live, -n 1: tests/pyathena/sqlalchemy/test_base.py -k temporal: 3 passed (at eb46fa4). These three tests only compile statements and do not query AWS. No live query runs a time-travel clause. That Athena rejects a hint after an alias, and accepts the moved form, follows from Render the time-travel hint of an aliased table before its alias #1547 and Trino's grammar.

  • Differential check (/tmp/pyathena-1575/harness.py, not committed). It covers 9193 cases (rebuilt after a machine restart wiped /tmp). Each case gives the SQL, or an exception, for 10 dialects (5 sync, 5 aio), and all dialects agree in every case.

    • Matrix:
      • Single FROM element: tables {db.events, no schema, "My Schema"."Weird Table", BASIC, "my AS t", "AS"} × aliases {none, a, anonymous, "My Alias", "x AS y", nested} × 35 hints × compile-time schema_translate_map {none, translate, to None}. The hints are:
        • the 4 forms, in lower and mixed case
        • 8 whitespace variants and OF(1)
        • 12 lookalikes (FORVERSION, ASOF, OFFICE, OF1, VERSIONS, leading comments, NBSP, ſ, İ, …)
        • WITH (NOLOCK), TABLESAMPLE, empty, blank and %(name)s
      • Same-named table pairs: 6 names (quoted, AS, events_1) × 2 schemas × hint target {schemaless, qualified, both} × order {schemaless first, qualified first, JOIN} × 18 hints × 3 maps.
      • Execution-time schema_translate_map, through the offline recording engine.
      • Neighbors, each × 3 hints: joins, two aliases, subqueries, a correlated subquery, tablesample, dialect-specific hints, UPDATE/DELETE, an UPDATE inside a CTE, ORM aliased() (nested, anonymous, in a pair), an ORM pair, table().
      • Subclass hooks: hooks that append to visit_table() or visit_alias() in SELECT, UPDATE and DELETE, and a visit_table() hook that renders the table under another name.
    • After the rebase, the new merge base (244632e), run twice, gives identical output on SQLAlchemy 2.0.52, 2.0.58 and 2.1.9. That output equals the old merge base's, and the rebased head equals the head before the rebase.
    • Stability before the rebase: the merge base (d653ea7), run twice, gives identical output on SQLAlchemy 2.0.23 (Python 3.12), 2.0.44, 2.0.46, 2.0.52 and 2.1.9. The current 4.x (a23d009) gives the same output as master, both without and with this patch.
    • The expected differences were written down before each branch run. On every version, 2536 cases differ, all expected:
      • generated alias: 1879
      • whitespace on an alias: 570
      • neighbors: 64
      • execution-time map: 19
      • hooks: 4
    • Each differing case equals the base output with the alias moved after the hint, with one exception on SQLAlchemy 2.0.23 described below.
    • The other 6657 cases are unchanged. They include:
      • every case without a time-travel hint
      • every lookalike on an alias
      • a hint on the qualified table
      • maps that give the schemaless table a schema
      • subqueries
      • DML targets, including the CTE
      • all hook cases other than the generated and explicit alias
    • Quirk on SQLAlchemy 2.0.23, upstream and fixed in later 2.0 releases: a Core alias of the schemaless table in a pair renders as events AS events_1 ... AS a, on both the base and the branch. In that one case, the comparison script also moved the hint of the alias half, which the branch correctly leaves as on the base.
  • Not run: just test sqla / just test sqla-async and the full live suite (left to CI when the PR is marked Ready).

🤖 Generated with Claude Code

Comment thread pyathena/sqlalchemy/compiler.py Outdated
if prefix != sqltext:
if element is table:
# The table as visit_table() renders it without the alias.
prefix = SQLCompiler.visit_table(self, table, asfrom=True)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round one (implementation behavior, contracts, simplicity, tests): FINDINGS, repaired.

Scope: d653ea7132ee007bb7dee780badc6c5a19810888..eb46fa4e (initial pass, full diff: compiler, tests, docs), repairs at 169f0e119b715622fc3f3792b9624521a0fa0302. /code-review (high) found no correctness defects. It checked joins, %(name)s hints, INSERT FROM SELECT, UPDATE with an IN subquery, schema_translate_map, truncated 200-character names, an alias and an ambiguous table in one statement, and prepending hooks. /simplify ran 4 angles (reuse, simplification, efficiency, altitude).

Repaired in 169f0e1:

  • The docstring now gives the exact generated-alias condition: a table of the same name with a schema.
  • The DML comment moved next to the iscrud condition (line 1243).
  • A comment explains the split check (line 1261).
  • Docs: see the docs/sqlalchemy.md thread.

Rejected, with reasons:

Validation after the repairs: just lint, just docs lint, tests/pyathena/sqlalchemy/test_compiler.py (284 passed). Harness on SQLAlchemy 2.0.23/2.0.46/2.1.9: identical to eb46fa4e (0 of 9112 differ).

Comment thread docs/sqlalchemy.md Outdated

To query an aliased table, pass the alias to `with_hint()`. The hint is rendered between the table name and the alias.
When a statement uses a table without a schema and a table of the same name with a schema, SQLAlchemy gives the table
without a schema an alias such as `events_1`. Pass that table to `with_hint()`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Round one repair: the first version said that "the same applies" to the generated alias. That suggested passing an alias, which the caller cannot name. The text now says which table gets the alias and that the table itself goes to with_hint(). A clause repeating the previous sentence was dropped (/simplify, reuse angle).

Comment thread pyathena/sqlalchemy/compiler.py Outdated
element = table
while isinstance(element, FromClauseAlias):
element = element.element
# A DML target table has no generated alias, and its text may end with

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round two (claims, existing callers, documentation reader, evidence): FINDINGS in the PR text only, corrected. No code change.

Scope: d653ea7132ee007bb7dee780badc6c5a19810888..169f0e119b715622fc3f3792b9624521a0fa0302, full pass over the PR body, the docstring and comments, docs/sqlalchemy.md and both commit messages.

Claims checked against evidence:

  • A DML target never gets a generated alias (line 1243). On SQLAlchemy 2.0.23 and 2.1.9, only the SELECT path passes ambiguous_table_name_map to visit_table(). visit_update() and visit_delete() never mention it. The harness UPDATE/DELETE rows are unchanged.
  • The generated alias needs a same-named table with a schema; a map that gives the schemaless table a schema removes it. Harness pair|*|map=translate and exec|none_to_tenant|* are unchanged. Exception: a lightweight table() ignores the map (recorded in the PR).
  • Before Render the time-travel hint of an aliased table before its alias #1547 this raised AttributeError. The pre-Render the time-travel hint of an aliased table before its alias #1547 code called table.original.fullname on a Table.
  • _TIME_TRAVEL_HINTS was never released. It was added in 1535f6f (Render the time-travel hint of an aliased table before its alias #1547); v4.3.0, v4.2.x and origin/4.x do not have it. removeprefix needs Python 3.9, and 4.x requires 3.11 or later.
  • Mutation claims. I ran the mutant that removes the prefix + suffix == sqltext check: the hook test kills it. Skipping the check only for a table survives, as the PR says.

Corrected in the PR body:

  • "Athena rejects the statement in both placements" was a grammar inference, not a measurement. It is now worded as such.
  • "2.0.23 does not import on Python 3.13 or later" was observed only on 3.15. It is narrowed to 3.15.
  • One harness case on 2.0.23 does not follow the stated transformation (the AS events_1 AS a quirk). It is now named as the exception.
  • The tested commit is now 169f0e1. just test offline was rerun there: 4434 passed.

Not measured: whether Athena accepts the moved clauses (events FOR VERSION AS OF 1 AS events_1, line breaks between the keywords). The clause order is the one #1547 already uses for aliases; only the alias source and the whitespace differ. A small parse-only live probe is pending the maintainer's approval.

@laughingman7743
laughingman7743 force-pushed the fix/1575-time-travel-hint-placement branch from 43991d8 to 05170fd Compare November 30, 2026 09:07
Comment thread pyathena/sqlalchemy/compiler.py Outdated
# hook appended or a name that it rendered differently.
prefix = SQLCompiler.visit_table(self, table, asfrom=True)
suffix = sqltext.removeprefix(prefix)
split = sqltext.startswith(prefix + self.get_render_as_alias_suffix(""))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent review (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22b9a-8a1a-7da3-ad01-36b3a7b4c095. This was a static review plus offline statement compilation on SQLAlchemy 2.0.23, 2.0.44, 2.0.46 and 2.1.9.
Scope: d653ea7132ee007bb7dee780badc6c5a19810888..169f0e119b715622fc3f3792b9624521a0fa0302, a full pass on a detached snapshot (left unchanged). The prompt had no PR number, PR text or prior findings.
Covered: SELECT/DML hint dispatch, explicit and generated aliases, ORM and cloned elements, truncated names, schema translation, compiled cache, CTEs, subqueries, lateral and table-valued aliases, TABLESAMPLE, and compiler hooks. Result: FINDINGS (6).

Finding 1 (verified, regression, fixed in 05170fd). A visit_table hook that renders events_archive and calls the hint hook itself got FROM events FOR VERSION AS OF 1_archive; the merge base gave FROM events_archive FOR VERSION AS OF 1. The table split now needs the alias marker of get_render_as_alias_suffix("") (AS) after the table. test_time_travel_hint_of_table_renamed_by_hook covers it. The test passes on the merge base and fails when the marker is dropped.
The marker check also leaves hook text appended to a DML target in place (UPDATE events /* table */ FOR ...). The iscrud check therefore became equivalent and was removed: the mutant without it survived. The harness output is identical to the version with the check (0 of 9115 differ on 2.0.23, 2.0.44, 2.0.46 and 2.1.9).

Comment thread pyathena/sqlalchemy/compiler.py Outdated
# any ASCII whitespace between and before them.
_TIME_TRAVEL_HINT_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
r"\s*FOR\s+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)\s+AS\s+OF\b",
re.ASCII | re.IGNORECASE,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Finding 4 (verified, fixed in 05170fd). With Unicode IGNORECASE, FOR VERSİON AS OF 1 (U+0130) was recognized and moved before an alias; the merge base left it after. The pattern is now re.ASCII | re.IGNORECASE, so keywords and whitespace are the ASCII ones Athena lexes.
Side effect, recorded in the PR as a behavior change: FOR VERſION AS OF 1 was recognized on the merge base through str.upper() and is not recognized now. NBSP is no longer recognized either, as on the merge base. Athena rejects all of these texts in either place.

Finding 6 (rejected). It asks for a test of the \b boundary. \b, and now re.ASCII, only decide where a text that is not a time-travel clause goes (AS OFFICE, AS OF1, VERSİON). Athena rejects that text in either place, so the placement is not a caller-observable contract (docs/testing.md, Choose what to test). The differential check pins these rows (like_*).

Comment thread docs/sqlalchemy.md Outdated
```

To query an aliased table, pass the alias to `with_hint()`. The hint is rendered between the table name and the alias.
When a SELECT uses a table without a schema and an unaliased table of the same name with a schema, SQLAlchemy gives

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Finding 5 (verified, fixed in 05170fd). With b = db_events.alias("b"), no alias is generated: SQLAlchemy builds _ambiguous_table_name_map from FROM objects that are tables with a schema, and an alias is not one (SelectState._normalize_froms, 2.0.46). The docs and the docstring now say "an unaliased table of the same name with a schema".

Comment thread pyathena/sqlalchemy/compiler.py Outdated
)
prefix = sqltext.removesuffix(suffix)
if prefix != sqltext:
if isinstance(element, TableClause) and self._TIME_TRAVEL_HINT_PATTERN.match(hint):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Finding 2 (rejected: a property of raw hint text, not of this placement). It reports that with_hint(events, "FOR VERSION AS OF 1 -- audit") in a pair emits FROM events FOR VERSION AS OF 1 -- audit AS events_1, db.events, and the comment removes db.events. A hint is raw SQL. A line comment in it comments out the rest of the line in every placement, including SQLAlchemy's default for any unaliased table followed by another FROM element. On the merge base, select_from(events, other).with_hint(events, "FOR VERSION AS OF 1 -- audit") already gives FROM events FOR VERSION AS OF 1 -- audit, other. Explicit aliases behave the same since #1547.

Finding 3 (rejected: consistent with #1547). It reports that delete(a).with_hint(" FOR VERSION AS OF 1") on an aliased target now goes before AS a. That is the placement #1547 already gives the canonical hint on an aliased DML target. Whitespace recognition only makes the spaced variant consistent with it. Athena's UPDATE/DELETE accept neither an alias nor a time-travel clause.

Pre-existing, noted by the reviewer: on 2.0.23, an explicit alias of the schemaless table in a pair renders events AS events_1 FOR VERSION AS OF 1 AS a, on both revisions. This is an upstream quirk (no enclosing_alias check in 2.0.23) and is recorded in the PR.

"UPDATE events /* table */ FOR VERSION AS OF 1 SET "
)

def test_time_travel_hint_of_table_renamed_by_hook(self):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Repair review, both perspectives (169f0e11..05170fdc).

  • Implementation:
    • The marker check keeps every SQLAlchemy-produced split: a generated alias always renders through get_render_as_alias_suffix().
    • A table without an alias and a DML target without a hook have no text after the table, so they keep the default placement.
    • Limitation: a dialect subclass whose get_render_as_alias_suffix() drops AS (a bare space) would accept any text that starts with a space after the table. No Athena dialect does this.
    • Mutants are killed: no marker (both hook tests), endswith → True (hook test), leading \s*, single spaces, aliases only.
  • Claims:
    • The docs and docstring wording was checked against SelectState._normalize_froms (2.0.46) and visit_table() (2.0.23 and 2.1.9).
    • The commit message claims match the mutants.
    • The PR body now has the new counts (9114 cases, 2486 differ, all expected; written before the rerun in expected.md), the tested commit, and the ASCII behavior change.
  • Validation:
    • just lint and just docs lint pass, and just test offline gives 4435 passed.
    • On 4.x ([4.x] Backport #1547, #1566, #1567 and #1551 #1578 head with the patch), 20 passed on 2.0.23 and 2.1.9.
    • The harness gives the same output on master and 4.x for every version.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
split = (
not iscrud
and sqltext.startswith(prefix)
and self._ALIAS_KEYWORD_PATTERN.match(suffix) is not None

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 1 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, fresh session. This was a static review plus offline compilation on SQLAlchemy 2.0.23, 2.0.44, 2.0.46–2.0.48, 2.0.58 and 2.1.9.
Scope: the repair 169f0e11..05170fdc, on a detached snapshot (left unchanged). Codex confirmed earlier findings 1 (events_archive) and 4 (İ) fixed. Result: FINDINGS (3).

  • F1: get_render_as_alias_suffix("") broke subclasses that read the name (an override using name[0] raised IndexError even for SELECT 1 FROM events FOR VERSION AS OF 1). An override returning f" AS {name} /* trace */" no longer got the hint before the generated alias, a regression from 169f0e1. Verified.
  • F2: with the hinted table last, -- audit comments out AS events_1 (FROM db.events, events FOR VERSION AS OF 1 -- audit AS events_1).
  • F3: the docs promised an alias too broadly; schema_translate_map={None: "tenant"} gives none. Verified.

The A/B design choices were then put to Codex and Claude Fable 5.2 in parallel, two rounds (prompts /tmp/pyathena-1575/consult*.md, read-only):

  • Split check. Both agreed on keeping not iscrud and on not calling the hook with a made-up name. Fable found the CTE case: SQLAlchemy leaks the generated alias to an UPDATE inside a CTE, which disproved my earlier claim that "a DML target never gets one". Fable proposed a literal AS; Codex proposed whitespace + case-insensitive AS (counterexample: an extension rendering as name).
  • Recognition. Both agreed on hint.upper() with Trino's [ \t\r\n], which keeps the merge base's ſ handling whatever Athena does with it. Fable said to drop \b (exact parity with the merge base); Codex said to keep it and add a test.
  • Line comment (R2). Fable said to keep rejecting it here: a newline before the alias would not fix the comma/JOIN paths that exist on the merge base. Codex proposed the newline.

Maintainer decisions: whitespace + case-insensitive AS, drop \b, line comments to a separate issue (#1598, sub-issue of #1494). Implemented in 5065068.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
)
prefix = sqltext.removesuffix(suffix)
if prefix != sqltext:
if isinstance(element, TableClause) and self._TIME_TRAVEL_HINT_PATTERN.match(hint.upper()):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Repair review, both perspectives (05170fdc..50650688).

  • Implementation:
    • The table split is not iscrud and sqltext.startswith(prefix) and _ALIAS_KEYWORD_PATTERN.match(suffix); the alias branch is unchanged.
    • Every mutant is killed by a test: no iscrud, no AS check, upper-case or literal AS only, no .upper(), no leading whitespace, single spaces, aliases only, endswith → True.
    • Two hook tests were added for the decided contract: the lower-case as hook (fails on the merge base) and the DML target aliased by a hook (pins iscrud).
  • Claims:
    • The commit message, docstring and docs now say "can generate".
    • "DML target keeps the default placement" replaces the disproved "never gets a generated alias".
    • The PR body was rewritten for the final design, its counts and tests.
  • Differential check: expected differences were written before the run.
    • 9120 cases. On 2.0.23, 2.0.44, 2.0.46 and 2.1.9, 2536 differ, all expected; the only exception is the known 2.0.23 quirk.
    • The new update_cte_pair row is unchanged from the merge base.
    • The merge base is stable over two runs, and 4.x gives identical output.
  • Tests:
    • just test offline: 4437 passed.
    • Time-travel/hint tests: 22 passed on 2.0.44 and 2.1.9 (master), and on 2.0.23 and 2.1.9 (4.x).
    • just lint and just docs lint pass.
  • F2: the hinted-last variant is the same raw-SQL hazard and is folded into A SQLAlchemy FROM hint that ends with a line comment swallows the rest of its line #1598. It fails at run time on both revisions (events_1 unresolved, or the hint after the alias on the merge base).

@laughingman7743
laughingman7743 force-pushed the fix/1575-time-travel-hint-placement branch 2 times, most recently from 0e9d40d to 0eee58e Compare November 30, 2026 10:22
Comment thread pyathena/sqlalchemy/compiler.py Outdated
# subclass hook rendered differently, keeps the default
# placement; a DML target and text without AS keep it without
# rendering the table again.
if iscrud or self._ALIAS_KEYWORD_PATTERN.search(sqltext) is None:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 2 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22be9-139f-79f0-8d99-5963b4b63379.

  • Scope: 05170fdc..506506882, on a detached snapshot (left unchanged).
  • Method: static review plus offline compilation across 37 cached SQLAlchemy releases, including 2.0.23, 2.0.44, 2.1.0 and 2.1.9.
  • Earlier findings F1 and F3: resolved. Hint recognition matches the merge base's apart from whitespace.
  • Result: FINDINGS (4), all verified and fixed in 0eee58e4 (tested at 68e84b6; the head differs only in this comment).
  1. CompileError (regression). A renaming hook on a table whose schema SQLAlchemy cannot render under schema_translate_map (tenant[42]) raised CompileError from the re-render. The merge base compiled it (FROM events_archive FOR VERSION AS OF 1).
    • Fix: a DML target, and text with no AS keyword, now return the default placement before the table is rendered again.
    • Test: test_time_travel_hint_of_table_renamed_by_hook[unrenderable_schema]. The pre-check mutant fails it.
  2. Docstring. It now says "unaliased DML target tables". An aliased DML target follows the alias branch, unchanged since Render the time-travel hint of an aliased table before its alias #1547.
  3. Comment. It now describes the text that is split: it continues the rendered table with AS and a name. It no longer attributes every such alias to SQLAlchemy.
  4. Test hook. The suffix hook in test_time_travel_hint_precedes_generated_alias_of_hook now reads alias_name_text[0], so probing with "" (the old F1) fails the test. A second rename case, [aliased] (events_archive AS events), pins the anchored AS check, which the pre-check had made unprotected.

Validation:

  • All 11 mutants are killed.
  • The harness (9120 cases) gives the same output as 5065068 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9. 2536 cases differ from the merge base, all expected. 4.x is identical.
  • just test offline: 4438 passed. Time-travel/hint tests: 23 passed on 2.0.44 and 2.1.9 (master) and on 2.0.23 and 2.1.9 (4.x).
  • just lint and just docs lint pass.

Both self-review perspectives on the repair:

  • No caller-visible change for SQLAlchemy's own rendering: harness 0 of 9121 differ from 5065068.
  • Claims in the commit message and the PR body were updated (tested commit, counts, mutants).

Comment thread pyathena/sqlalchemy/compiler.py Outdated
return super().format_from_hint_text(sqltext, table, hint, iscrud)
try:
prefix = SQLCompiler.visit_table(self, table, asfrom=True)
except exc.CompileError:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 3 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22bfb-27c3-7a31-982c-7879906f2eea.

  • Scope: 506506882..0eee58e4, on a detached snapshot (left unchanged). It compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.1.0 and 2.1.9.
  • Previous (2)–(4): resolved.
  • Result: FINDINGS (2), both verified:
    1. A hook rendering "events AS archive" on a table whose schema SQLAlchemy cannot render (tenant[42] under schema_translate_map) still raised CompileError. The merge base compiled it.
    2. The unanchored AS search was quadratic: 132 ms for a hook text with 8192 spaces.

Consultation, round 3 (Codex and Claude Fable 5.2, in parallel):

  • Fable recommended (a): drop the pre-check and catch CompileError from the re-render.
  • Codex recommended (c): (a) plus a linear pre-check. Its counterexample: a table without a name raises IndexError on the re-render, so the pre-check is observable.
  • Both agreed to state a scope and stop the chain of hook findings.
  • Maintainer decisions: (c), and the scope now written in the PR body. Hook-related findings are fixed only when they change the output without hooks, or when a statement that compiled on the merge base raises.

Repair in 5d55abb:

  • The re-render is wrapped in try/except exc.CompileError, which falls back to the default placement.
  • The pre-check pattern gets the lookbehind (?<![ \t\r\n]), so it starts only at the first whitespace of a run (8192 spaces: 0.2 ms).
  • The rename test gained the cases unrenderable_schema_with_as (kills the except mutant) and empty_name (kills the pre-check mutant).

Validation:

  • 13 of 14 mutants are killed. The lookbehind mutant only changes the running time; that was measured instead.
  • The harness gives the same output as 0eee58e on 2.0.23, 2.0.44, 2.0.46 and 2.1.9 (2536 differ from the merge base, all expected), and 4.x is identical.
  • just test offline: 4440 passed. Time-travel/hint tests: 25 passed on 2.0.44 and 2.1.9 (master) and on 2.0.23 and 2.1.9 (4.x).

Both self-review perspectives: the output for SQLAlchemy's own rendering is unchanged (harness). The commit message, comments and PR body state the scope and the fallback.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
SQLCompiler.visit_alias(self, table, ashint=True)
)
except Exception:
# An alias that only a subclass hook can render.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 4 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c26-b9fe-7b01-b36e-59cf17fbc837.
Scope: 0eee58e4..5d55abb4, compiled offline on 35 SQLAlchemy releases from 2.0.23 to 2.0.58, plus 2.1.0 and 2.1.9. The earlier findings (1) and (2) are resolved, and the lookbehind changes no match result. FINDINGS (2), both within the agreed scope: a statement that compiled on the merge base raised.

  1. Table(""), with a hook that renders events AS archive, raises IndexError from the comparison render on SQLAlchemy 2.0.
  2. events.alias(""), with a visit_alias hook that supplies the name and the hint " FOR VERSION AS OF 1", raises IndexError from SQLCompiler.visit_alias(). The canonical hint already raised on the merge base.

It also noted two minor points. A comment implied the re-render is skipped for an unrenderable table. The test case with a bracketed schema and no AS duplicated a neighbor.

Consultation, round 4 (Codex and Claude Fable 5.2, in parallel): both recommended Z, catching any exception around the two comparison renders only.

  • X (an empty-name check) changes the output without hooks: events.alias(quoted_name("", True)) would move the hint after AS "".
  • Y (CompileError + IndexError) leaves the next error. table(1) raises AttributeError, and a quote() hook can raise ValueError.
  • Without hooks, these calls render what SQLAlchemy has just rendered, so Z changes no output.

Maintainer decision: Z. Implemented in 20c3d4f.

  • Both comparison renders fall back to the default placement on any exception.
  • The comment is corrected.
  • The rename test now covers a plain rename, a rename with an alias, an unrenderable schema, an empty name and a name that is not a string; the duplicate case is gone. The new test_time_travel_hint_of_alias_named_by_hook covers the alias branch.

Validation.

  • Mutants: 12 of 14 are killed. The two CompileError+IndexError mutants, one per branch, fail the non-string name tests. The AS pre-check and the lookbehind only skip work or change the running time; measured at 8192 spaces, 0.2 ms.
  • Harness: 0 of 9121 cases differ from 5d55abb on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and 4.x is identical.
  • Tests: just test offline gives 4442 passed. The time-travel and hint tests pass 27 on master (2.0.44 and 2.1.9) and on 4.x (2.0.23 and 2.1.9).

Both self-review perspectives:

  • There is no change without hooks, per the harness.
  • The scope in the PR body now says "any error", and the commit message, the comments and the PR counts are updated.

prefix = sqltext.removesuffix(suffix)
if prefix != sqltext:
try:
parts = self._split_alias(sqltext, table, element is table)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 5 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c41-cdac-7301-aff7-36ff24f33392.

  • Scope: 5d55abb4..20c3d4f9, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46–2.0.48, 2.0.58 and 2.1.9.
  • Confirmed:
    • The IndexError cases are resolved.
    • Exceptions from the first render and from the hint formatting still propagate.
  • Result: FINDINGS (2). Both are within the agreed scope: a statement that compiled on the merge base raised. Both are verified and fixed in 5abb9239.

1. UserString names. SQLAlchemy renders a UserString name as a UserString, so removeprefix()/removesuffix() raised TypeError after the guarded call.

  • Fix: the whole comparison (pre-check, rendering, string operations) moved into _split_alias(), called inside the single fallback. This is the decided Z applied to the whole comparison, not only the render.
  • Tests: [user_string_name] and test_time_travel_hint_of_alias_named_by_hook[user_string].

2. update(t).values(id=1).with_hint(None). It compiled without a hint on the merge base; the branch raised AttributeError at hint.upper().

  • Fix: the unaliased DML target is checked first.
  • Test: test_none_hint_of_dml_target_renders_no_hint.
  • A SELECT with a None hint raises inside SQLAlchemy's own hint formatting (None % {...}), on the merge base too, so no change there.
  • I briefly added isinstance(hint, str). I removed it again because its mutant survived: it only changed an aliased DML target with None, which also raised on the merge base.

Pre-existing, noted: on 2.0.23, an explicit alias beside a same-named schema table renders two AS clauses even without a hint. This is upstream and already in the PR body.

Validation:

  • Mutants: 11 of 13 are killed. These include a narrowed except (killed by the UserString tests), no iscrud, no AS check, case-sensitive AS, no .upper(), whitespace, aliases only, endswith → True, and the empty-name probe. The pre-check and the lookbehind only skip work or change running time (8192 spaces: 0.2 ms).
  • Harness: 0 of 9121 differ from 20c3d4f on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and 4.x is identical.
  • Tests: just test offline gives 4445 passed. Time-travel/hint tests: 30 passed on master (2.0.44, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Both self-review perspectives: no output change without hooks; the PR body counts and the scope wording are updated.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
and not (element is table and iscrud)
# A hint that is not a string, unlike SQLAlchemy's annotation, is
# not read.
and isinstance(hint, str)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 6 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c53-7db5-75b1-a3dc-1ca5c34483fd.

  • Scope: 20c3d4f9..5abb9239, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.58, 2.1.0 and 2.1.9.
  • Earlier repairs: confirmed fixed.
  • Result: FINDINGS (3):
    1. A tablesample named UserString("s") moved the hint after its alias without hooks, because UserString.endswith() rejects a UserString suffix and the code fell back.
    2. Hints that are not str (UserString, bytes, None from a hook) raised at hint.upper() or at the regex; some of these compiled on the merge base.
    3. The DML comment ignored the generated alias inside a CTE.

Consultation, round 5 (Codex and Claude Fable 5.2, in parallel). Both recommended R: a type boundary, plus the merge base's removesuffix()/!= alias split.

  • Fable's R: isinstance(hint, str) gate only. One remaining difference: a UserString hint on a tablesample goes after the alias; there is no exception, and SQLAlchemy itself already raised for a UserString hint on an ordinary alias.
  • Codex's R: keeps full parity through the merge base's startswith() recognition for non-str hints, at the cost of a second recognition path.
  • Rejected option P (handle the types): a str Enum hint would break, because str() returns "H.VERSION".
  • Maintainer decision: Fable's R, with the type rule now in the PR scope.

Repair in 6e5d283:

  • Recognition is isinstance(hint, str) and PATTERN.match(hint.upper()).
  • The alias split is back to removesuffix() + prefix != sqltext.
  • The DML comment is corrected.
  • New test test_empty_hint_that_is_not_a_string_renders_no_hint (UserString(""), b""). It fails without the str check.

Validation:

  • Mutants: 13 of 16 are killed. The endswith() split changes only output for non-str names, which the scope excludes. The pre-check and the lookbehind only skip work or change running time.
  • Harness: 0 of 9121 differ from 5abb923 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and 4.x is identical.
  • just test offline: 4447 passed. Time-travel/hint tests: 32 passed on master (2.0.44, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Both self-review perspectives: no output change for str inputs; the PR body states the type rule and the updated counts.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
text does not split.
"""
schema = table.schema if is_table else None
if not isinstance(table.name, str) or not isinstance(schema, (str, type(None))):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 7 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c75-3b63-7fa3-a135-db4dba0143c8. Scope: 5abb9239..6e5d2835, offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0 and 2.1.9. The previous findings are resolved. FINDINGS (2):

  1. Verified, fixed in 6d80811. A hook-rendered table named UserString("events"), followed by table("events") in the same SELECT, raised TypeError in the FROM join. The merge base compiled it. Cause: the comparison render quoted the UserString, the identifier preparer cached it, and the cache returned it for the later plain "events"; the cache persists for later statements on the dialect.
    • Fix: _split_alias() compares only tables and aliases whose name, and table schema, are str, as the agreed type rule says. Others keep the default placement without rendering again.
    • Test: test_time_travel_hint_of_hooked_table_keeps_quoting_cache fails on 6e5d283 and on the gate-removal mutant. The rename test's UserString case, now duplicate, is dropped.
  2. Rejected. The finding says the None DML hint test and the empty non-string hint tests pin SQLAlchemy's formatting beyond "no added exception". The PR scope states that such hints "are not read and keep the default placement", and these tests check that stated behavior. The file's convention compares the full compiled SQL, and the expected values are SQLAlchemy's own default output, independent of this change.

Validation:

  • Mutants: 13 of 17 are killed. The survivors are the endswith() alias split (non-str names only), the narrowed except (the str checks stop the tested inputs first), the pre-check and the lookbehind (performance).
  • Harness: 0 of 9121 differ from 6e5d283 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and 4.x is identical.
  • just test offline: 4447 passed. Time-travel/hint tests: 32 passed on master (2.0.44, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Both self-review perspectives: no output change for str inputs. The PR scope now names the str-only rendering.

"""
# The type itself, not isinstance(), which a proxy can satisfy.
schema = table.schema if is_table else None
if not issubclass(type(table.name), str) or not (

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 8 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c88-8d0d-7511-b0e8-3a1e862220d3.

  • Scope: 6e5d2835..6d808110, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0 and 2.1.9.
  • Previous findings: the UserString cache case is fixed, and the rejected point (2) was not raised again.
  • Result: FINDINGS (1), verified and fixed in bf6bb10.
    • Finding: a Werkzeug LocalProxy(lambda: "events") passes isinstance(name, str). The comparison render cached the proxy, and a later plain table("events") raised TypeError. The merge base compiled the statement.
    • Fix: names and schemas are checked with issubclass(type(...), str), which a proxy cannot fake and which still accepts str subclasses.
    • Test: a minimal _StrProxy (the same __class__ trick) parametrizes the cache test. It fails on 6d80811 and passes now.
    • Placement: the helper class sits before _VersionHint, so the test patch applies cleanly to 4.x.

Validation:

  • Harness: 0 of 9121 differ from 6d80811 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and 4.x is identical.
  • Tests: just test offline gives 4448 passed. The time-travel and hint tests give 33 passed on master (2.0.44, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Both self-review perspectives: no output change for str inputs. The PR scope names the type() check.

Note for the maintainer: this was the third successive finding about inputs outside SQLAlchemy's str annotation (UserString, then a quoting-cache side effect, then an isinstance proxy). The fix stayed within the agreed type rule. If the next round reports another impersonating type, I will ask whether objects that fake str should be declared out of scope.

# A hint that is not a string, unlike SQLAlchemy's annotation, is
# not read. The type itself, not isinstance(), which a proxy can
# satisfy.
and issubclass(type(hint), str)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 9 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c9a-d287-7f91-90d8-38010a8fb85d. Scope: 6d808110..bf6bb108, offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0, 2.1.9. The LocalProxy cache case is resolved for names and schemas. FINDINGS (2):

  1. A table named by markupsafe.Markup("events") (a real str subclass that overrides methods) with a hook: the comparison render caches the Markup in the identifier preparer, so a later ordinary SELECT on the same dialect renders &#34;My Schema&#34;.events.
  2. update(a).values(id=1).with_hint(MagicMock(spec=str)) on an aliased target: isinstance(hint, str) accepts the mock, and the pattern raises TypeError on hint.upper(). The merge base compiled it.

Consultation, round 6 (Codex and Claude Fable 5.2, in parallel):

  • Both: fix 2 with issubclass(type(hint), str).
  • On 1, Fable: out of scope. Offline, SQLAlchemy alone (select(table(Markup("events"))), no PyAthena, no hook) already poisons the cache the same way, so the cause is the name type. A fix would need excluding str subclasses (SQLAlchemy's own quoted_name/_anonymous_label are subclasses) or touching the private cache.
  • On 1, Codex: rebuild the comparison from quoted_name(str.__str__(x)) with quote/quote_schema/schema_for_object. That reimplements visit_table() rendering in PyAthena and still leaves SQLAlchemy's own poisoning.

Maintainer decision: 1 is out of scope; the scope in the PR body now names str subclasses that override str methods. Fix 2.

Repair in 983013a: the hint is read only when issubclass(type(hint), str). New test: test_hint_that_only_passes_isinstance_is_not_read fails on bf6bb10 and on an isinstance() mutant.

Validation after a machine restart that wiped /tmp:

  • Harness rebuilt (9193 cases). The merge base is stable over two runs on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9.
  • Head: 2536 cases differ from the merge base, all expected; the only exception is the known 2.0.23 transform case. The head is identical to bf6bb10, and the current 4.x (a23d009), with and without the patch, matches master.
  • just test offline: 4449 passed. Time-travel/hint tests: 34 passed on master (2.0.44, 2.0.52, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Mutants: the type() checks for hints and names are each killed, by the mock test and the proxy test. A narrowed except survives, as recorded.

Both self-review perspectives: no output change for str inputs. The PR body now states that #1578 has merged, so this PR needs its own 4.x backport; the current master minimum (SQLAlchemy 2.0.52) is in the test list.

parts = None
if parts is not None:
prefix, suffix = parts
return super().format_from_hint_text(prefix, table, hint, iscrud) + suffix

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 10 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22ce2-ec97-7021-96d4-571b116580d8. Scope: bf6bb108..983013a0, offline on seven SQLAlchemy releases from 2.0.23 through 2.1.9, including 2.0.44 and 2.0.52. The MagicMock(spec=str) regression is resolved, and the added test has a distinct contract. FINDINGS (2):

  1. Rejected; maintainer decision after consulting Codex and Claude Fable 5.2, who agreed. A compiler mixin later in the MRO overrides format_from_hint_text() and expands {alias} in the hint by sqltext.rsplit(" AS ", 1). For the generated alias it now receives only events and raises ValueError; on the merge base it received events AS events_1. Reasons for rejecting:

    • To put the hint before the alias, super() must receive the table text only. That is the contract for explicit aliases since Render the time-travel hint of an aliased table before its alias #1547, where the same mixin already fails on the merge base.
    • The merge base output put the hint after the alias, which Athena rejects.
    • Catching the error and retrying with the full text would silently emit Athena-invalid SQL and hide the hook's bug.

    The PR scope now states this ("A hook later in the MRO that overrides format_from_hint_text() and reads an alias from its sqltext is out of scope, even if the statement compiled on the merge base").

  2. Fixed in a6d6316. Two test comments claimed SQLAlchemy cannot render a name that is not a string; a proxy of a string renders. They now name the int case.

Validation: the change is comment-only (just lint passes; tests/pyathena/sqlalchemy/test_compiler.py 299 passed). The harness and test results of 983013a apply.

if sqltext.startswith(prefix) and self._ALIAS_KEYWORD_PATTERN.match(suffix):
# The caller's text, not the rendering, which can be a
# quoted_name.
return sqltext[: len(prefix)], suffix

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 11 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22cf6-12ac-7b62-becc-fdc299ef92a6.

  • Scope: a final full pass of d653ea71..a6d63168 within the stated scope. Compiled offline on 45 SQLAlchemy releases from 2.0.23 to 2.1.9, without hooks, and matched the intended behavior.
  • Previous finding: the test comments now name the int case accurately.
  • Result: FINDINGS (2), both verified and fixed in aeecb57. Neither needed a design decision.
  1. Table text passed to the next hint hook. For a generated alias, the table text passed on was the quoted_name returned by the comparison render. A hook calling sys.intern(sqltext) compiled on the merge base and now raised TypeError.
    • Fix: the table text is now the caller's own span, sqltext[: len(prefix)], a plain str with the same characters.
    • Test: test_time_travel_hint_of_generated_alias_passes_text_of_its_own fails on a6d6316.
  2. The mock hint test did not detect a read. The merge base reads the hint and still produces the same SQL.
    • Fix: the mock's upper() now raises AssertionError.
    • The test fails on the merge base and on an isinstance() mutant.

Validation:

  • Harness: no change from a6d6316 on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9, with the same 2536 expected differences from the merge base. The current 4.x gives identical output.
  • Tests: just test offline passed 4450. The time-travel and hint tests passed 35 on master (2.0.44, 2.0.52, 2.1.9) and on 4.x (2.0.23, 2.1.9).
  • Both self-review perspectives: there is no output change. The PR body now lists the new tests and counts.

# The AS keyword and the name of an alias after a rendered table. A match
# starts only at the first whitespace of a run, so a search stays linear.
_ALIAS_KEYWORD_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
r"(?<![ \t\r\n])[ \t\r\n]+[Aa][Ss][ \t\r\n]+[^ \t\r\n]"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent follow-up 12 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d08-c917-7b90-905d-710fc887bba0.

  • Scope: a6d63168..aeecb57d plus a full pass, offline on eight SQLAlchemy releases (2.0.23–2.1.9). Ordinary SQLAlchemy rendering matched the intended placement.
  • Previous findings: both resolved.
  • Result: FINDINGS (4).
  1. Rejected (maintainer decision after consulting Codex and Claude Fable 5.2, who both recommended rejection). A class Name(str) table name with a hook: the comparison render caches Name("events") in the identifier preparer, and a hook that sys.intern()s a later plain events raises.
    • Fable confirmed offline that SQLAlchemy itself shares that cache across statements, so the same happens without this change once any statement renders the table or one of its columns.
    • There is no fix without private API.
    • The scope now states that the effect of the comparison render on the identifier cache is SQLAlchemy's own.
  2. Fixed in 8f3d62f. Hooked text events AS (AS without a name) was split. The alias keyword pattern now needs a name character after AS (test [as_without_name]).
  3. Fixed. The alias-name guard was untested for its cache effect. test_time_travel_hint_of_alias_named_by_hook now uses a fresh dialect and checks that a later table("archive") still renders; this fails without the guard.
  4. Fixed. A self.isupdate mutant passed the DML tests. The synthetic hook test is replaced by a hook-free test of an UPDATE inside a CTE that SQLAlchemy gives a generated alias; that test fails on the mutant.

Stop rule (maintainer decision, from the same consultation; Fable's wording). The next independent round is the final one. After it, only these are actionable:

  • a difference from the merge base, in output or in a raised exception, for hook-free statements with str/quoted_name names and hints;
  • inaccurate comments, docs or tests in this diff.

Hook, other-type and shared-preparer-state findings are recorded, not fixed. Repairs get one round limited to the repair diff. This is now in the PR body.

Validation:

  • Mutants for 2, 3 and 4 are each killed by the new tests.
  • Harness: no change from aeecb57 on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9 (2536 expected differences from the merge base), and 4.x is identical.
  • just test offline: 4451 passed. Time-travel/hint tests: 36 passed on master (2.0.44, 2.0.52, 2.1.9) and on 4.x (2.0.23, 2.1.9).

@laughingman7743 laughingman7743 modified the milestones: 5.0.1, 5.0.0 Nov 30, 2026
r"[ \t\r\n]*FOR[ \t\r\n]+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)"
r"[ \t\r\n]+AS[ \t\r\n]+OF"
)
# Whitespace, AS, whitespace, and the first character of a name, as an

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Final independent round (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d27-00c1-71b2-9c8d-5c16da568c81.

  • Scope: the full diff d653ea71..8f3d62f6, under the stop rule in the PR body. The reviewer compared 3,842 offline compilation cases per version across seven SQLAlchemy releases (2.0.23–2.1.9).
  • Result: every difference in compiled SQL or exceptions matched the intended placement changes. FINDINGS (3), all wording, actionable under the stop rule and fixed in 12f69a7:
    1. docs/sqlalchemy.md. "Pass that table to with_hint()" holds only when the SELECT uses the table itself. The docs now say to pass the alias when the SELECT uses an alias of the table.
    2. Pattern comment. The comment said "upper-cased hint text"; the pattern is matched against hint.upper(), which keeps the case of a quoted_name with quote=True, as on the merge base. Comment and PR body corrected.
    3. Alias pattern comment. The pattern checks only the first character of a name, and the rendered-table prefix marks the alias boundary. Comment corrected.
  • Note on the hook-recorder test: it checked only the type, so the merge base's full text would also pass. It now asserts (str, "events").

Validation: comment, doc and test changes only. The harness on 2.0.46 gives 0 differences from 8f3d62f. just test offline passed 4451, and just lint and just docs lint pass.

Per the stop rule, this repair gets one round limited to the repair diff.

Comment thread docs/sqlalchemy.md

To query an aliased table, pass the alias to `with_hint()`. The hint is rendered between the table name and the alias.
When a SELECT uses a table without a schema and an unaliased table of the same name with a schema, SQLAlchemy can give
the table without a schema an alias such as `events_1`. When the SELECT uses that table itself, pass the table to

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Repair check (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d39-a9d4-7933-b83f-230116171e79. Scope, per the stop rule: the repair diff 8f3d62f6..12f69a70 only. The reviewer checked that the three wording issues and the test note from the final round are resolved, and that the repair introduces nothing inaccurate and no behavior change. Result: CLEAN.

The independent review is complete under the stop rule recorded in the PR body.

laughingman7743 and others added 6 commits December 1, 2026 01:12
…r whitespace (GH-1575)

format_from_hint_text() placed a time-travel hint before the alias of an
aliased table only. In a SELECT, SQLAlchemy also gives a table without a
schema an alias when another table in the statement has the same name,
and passes the plain table with that alias; the hint followed the alias.
For a table, the text is split after the table as
SQLCompiler.visit_table() renders it without the generated alias. A DML
target has no generated alias and keeps the default placement.

The hint is recognized with an anchored, case-insensitive pattern, so
leading whitespace and any whitespace between the keywords (a line
break, a tab, repeated spaces) are accepted. The hint text is rendered
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…iew (GH-1575)

State the generated-alias condition precisely (a table of the same name
with a schema), move the DML comment next to the iscrud check, explain
the split check, and tell readers to pass the table itself to
with_hint() for a generated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nly (GH-1575)

A compiler hook that renders the table under another name and calls the
hint hook itself (events_archive) had its name split after "events".
The text is now split only when the table is followed by the alias
marker of get_render_as_alias_suffix(). This also leaves the text that
a hook appends to a DML target in place, so the iscrud check is no
longer needed.

The hint pattern matches ASCII keywords and whitespace only, as Athena
reads them; Unicode case folding no longer turns a lookalike such as
"VERSİON" into a time-travel hint.

The docs and docstring state that the generated alias needs an
unaliased table of the same name with a schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1575)

Decided with the maintainer after consulting Codex and Claude Fable 5.2:

- The hint is matched against hint.upper(), as the merge base did, with
  the whitespace that Athena reads ([ \t\r\n]) before and between the
  keywords and no word boundary. Only irregular whitespace changes the
  recognition; FOR VERſION and FOR VERSION AS OFTEN are recognized
  as before, and FOR VERSİON is not.
- A table's text is split only when it is not a DML target and the
  rendered table is followed by whitespace, AS in any case, and
  whitespace. get_render_as_alias_suffix() is no longer called with an
  empty name, which broke subclasses that read the name. SQLAlchemy can
  give a DML target a generated alias inside a CTE; it keeps the default
  placement.
- The docs say that SQLAlchemy can generate the alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ses (GH-1575)

The plain-table branch rendered the table with SQLCompiler.visit_table()
before it checked anything. A hook that renders the table under another
name bypasses that rendering, and for a table that SQLCompiler cannot
render (a schema name with square brackets under schema_translate_map)
the hint then raised CompileError where the merge base compiled. The
branch now leaves a DML target and text without an AS keyword at the
default placement before it renders the table again.

The docstring names unaliased DML target tables, which keep the default
placement, and the comment describes the text that is split. The hook
tests cover a table renamed with an alias and a suffix hook that reads
the alias name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…AS check linear (GH-1575)

Decided with the maintainer after consulting Codex and Claude Fable 5.2:

- The table is rendered again inside try/except CompileError. A hook
  that renders a table SQLAlchemy cannot render (a schema name with
  square brackets under schema_translate_map) and puts AS in its text
  (a quoted "events AS archive") now gets the default placement, as on
  the merge base, instead of an error.
- The AS pre-check stays, so a hooked table without AS is never rendered
  again (a table without a name raised IndexError there). Its pattern
  starts only at the first whitespace of a run, so a search over a long
  run of whitespace is linear instead of quadratic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
laughingman7743 and others added 10 commits December 1, 2026 01:12
Decided with the maintainer after consulting Codex and Claude Fable 5.2:
the two calls that render the table or the alias again only to compare
it with the text of a subclass hook now fall back to SQLAlchemy's
default placement on any exception, not only CompileError. SQLAlchemy
2.0 raises IndexError for an empty name, and a name that is not a
string raises AttributeError; listing exception types would leave the
next one. Without hooks, these calls render what SQLAlchemy has just
rendered, so they do not fail and the output does not change.

The rename test drops the case without AS that duplicated its neighbor
and adds an empty name and a name that is not a string; a new test
covers an alias that only the hook can name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the hint (GH-1575)

- The whole comparison with the text of a subclass hook, including the
  string operations after the rendering, now runs in
  AthenaStatementCompiler._split_alias() inside the fallback. SQLAlchemy
  renders a UserString name as a UserString, which made removeprefix()
  and removesuffix() raise TypeError after the guarded call.
- An unaliased DML target is checked before the hint is read, so
  update(t).with_hint(None) renders no hint again, as on the merge base,
  instead of raising AttributeError at hint.upper().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1575)

Decided with the maintainer after consulting Codex and Claude Fable 5.2:

- A hint is recognized only when it is a str (str subclasses such as a
  str Enum included), as SQLAlchemy annotates it. Any other hint, such
  as a UserString or bytes, or None passed by a subclass hook, is not
  read and keeps SQLAlchemy's default placement; an empty one no longer
  raises where the merge base compiled.
- The alias suffix is removed with removesuffix() and compared with !=,
  as on the merge base. UserString.endswith() rejects a UserString
  suffix, which moved the hint of a tablesample named by a UserString
  after its alias.
- The DML comment no longer claims that a DML target never has a
  generated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The comparison with the text of a subclass hook rendered the table or
alias again even when its name or schema was not a str. SQLAlchemy's
identifier preparer caches what it quotes, so a UserString name stayed
in the cache and was returned for a later table named "events", which
made the FROM clause raise TypeError where the merge base compiled.
Only str names and schemas, as SQLAlchemy annotates them, are compared
now; others keep the default placement without rendering again.

The rename test drops its UserString case, which the new cache test
covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isinstance() accepts a proxy that reports str as its __class__, such as
Werkzeug's LocalProxy. Rendering a table named by such a proxy to
compare it cached the proxy in the identifier preparer, and a later
plain table of the same name raised TypeError in the FROM clause, where
the merge base compiled. The name and schema are now checked with
issubclass(type(...), str), which still accepts str subclasses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isinstance() accepts an object that only reports str as its class, such
as MagicMock(spec=str). Such a hint on an aliased UPDATE target was read
with hint.upper(), and the pattern raised TypeError on the result, where
the merge base compiled the statement. The hint is now read only when
issubclass(type(hint), str), as for names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1575)

SQLAlchemy cannot render an int name; it renders other objects, such as
a proxy of a string, so the comments name the int case instead of every
name that is not a string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For a generated alias, the text before the alias was the rendering of
SQLCompiler.visit_table(), which can be a quoted_name, and that object
went to the next format_from_hint_text() in the MRO. A hook that
requires an exact str, such as one calling sys.intern(), raised where
the merge base compiled. The table text is now the same span of the
text the caller passed.

The mock hint test now fails if the hint is read, as its name says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…uard (GH-1575)

- A hooked text that ends with AS and no name, such as "events AS ",
  no longer splits; the alias keyword pattern now needs a name
  character after AS, as the docstring says.
- An UPDATE inside a CTE gets the generated alias from SQLAlchemy;
  a hook-free test now pins that its hint keeps the default placement,
  replacing the synthetic hook test, which a check of self.isupdate
  instead of iscrud also passed.
- The alias test with a hook-named alias now also checks that the
  comparison did not quote a UserString name into the identifier cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The time-travel pattern is matched against hint.upper(), which keeps
  the case of a quoted_name with quote=True.
- The alias pattern checks the first character of a name; the rendered
  table before the match marks where the alias starts.
- The docs say to pass the table itself when the SELECT uses it, and
  the alias when it uses an alias of the table.
- The hook test checks the text it receives, not only its type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@laughingman7743
laughingman7743 force-pushed the fix/1575-time-travel-hint-placement branch from 12f69a7 to 6dcc562 Compare November 30, 2026 16:18
"FOR SYSTEM_VERSION AS OF",
# The start of a time-travel hint, matched against hint.upper(), with any
# of the whitespace that Athena reads before and between the keywords.
_TIME_TRAVEL_HINT_PATTERN: ClassVar[re.Pattern[str]] = re.compile(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rebase before Ready. The PR conflicted with master (tests/pyathena/sqlalchemy/test_compiler.py: #1612 added a CreateView check next to where this PR added _StrProxy). I rebased onto master 244632e and pushed with --force-with-lease against 12f69a7.

No new review round: the patches are unchanged, and the upstream changes do not affect the reviewed contracts.

@laughingman7743
laughingman7743 marked this pull request as ready for review November 30, 2026 16:24
@laughingman7743
laughingman7743 merged commit fdd2f3c into master Nov 30, 2026
16 checks passed
@laughingman7743
laughingman7743 deleted the fix/1575-time-travel-hint-placement branch November 30, 2026 23:32
laughingman7743 added a commit that referenced this pull request Dec 1, 2026
laughingman7743 added a commit that referenced this pull request Dec 1, 2026
Appending the line break first made a quoted_name hint a plain str, so
the time-travel recognition upper-cased a quote=True hint that #1582
leaves in its own case and moved it before the alias. Recognition now
reads the hint as given, and only the text passed on to SQLAlchemy ends
with the line break.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLAlchemy time-travel hint follows a SQLAlchemy-generated alias and misses hints with irregular whitespace

1 participant