Skip to content

joined eager loading wrapped in a subquery populates an aliased joined-inheritance subclass from another row's columns when ordering by the alias #13798

Closed

Description

@sqlalchemy-bot

Found by the orm-strategies fuzzer in https://github.com/sqlalchemy/sqlalchemy-fuzz (see sqlalchemy/sqlalchemy-fuzz#5; tracked there as sqlalchemy/sqlalchemy-fuzz#19, sqlalchemy/sqlalchemy-fuzz#20). In run https://github.com/sqlalchemy/sqlalchemy-fuzz/actions/runs/42929224679 this is part of the mapping check (40 of seeds 0:20000 on main, 39 on rel_2_0) and the options check. sqla-fuzz orm-strategies --replay 3959 shows one.

When joined eager loading has to wrap the statement in a subquery (LIMIT
/ OFFSET / DISTINCT), and the statement joins to an aliased() joined
inheritance subclass and orders by that alias's column, the objects of
that subclass loaded as the main entity are populated from the wrong
columns: the identity is right but the column values are those of another
row. No error, just wrong data.

The alias's ORDER BY column is added to the inner subquery as anon_1.id_1,
and the outer ORMStatementAdapter then matches the subclass table's id
to that column (_compound_eager_statement() in orm/context.py). It
reproduces without flat=True and without DISTINCT, but not without the
alias's column in ORDER BY.

import sys
import sqlalchemy
from sqlalchemy import Column, create_engine, ForeignKey, Integer, select
from sqlalchemy import inspect, String
from sqlalchemy.orm import aliased, declarative_base, joinedload
from sqlalchemy.orm import relationship, Session

Base = declarative_base()


class Person(Base):
    __tablename__ = "person"
    id = Column(Integer, primary_key=True)
    manager_id = Column(ForeignKey("manager.id"))
    name = Column(String(20))
    type = Column(String(20))
    paperwork = relationship("Paperwork")
    manager = relationship(
        "Manager",
        primaryjoin="Person.manager_id == Manager.id",
        foreign_keys=manager_id,
        remote_side="Manager.id",
    )
    __mapper_args__ = {
        "polymorphic_on": type,
        "polymorphic_identity": "person",
    }


class Manager(Person):
    __tablename__ = "manager"
    id = Column(ForeignKey("person.id"), primary_key=True)
    manager_name = Column(String(20))
    __mapper_args__ = {
        "polymorphic_identity": "manager",
        "inherit_condition": id == Person.id,
    }


class Paperwork(Base):
    __tablename__ = "paperwork"
    id = Column(Integer, primary_key=True)
    person_id = Column(ForeignKey("person.id"))


e = create_engine("sqlite://", echo="-v" in sys.argv)
Base.metadata.create_all(e)
with Session(e) as s:
    boss = Manager(id=1, name="p1", manager_name="mn1")
    s.add_all(
        [
            boss,
            Manager(id=2, name="p2", manager_name="mn2", manager=boss),
            Person(id=3, name="p3", manager=boss),
            Person(id=4, name="p4", manager=boss),
        ]
    )
    s.commit()

print(sqlalchemy.__version__)
for opts in ((), (joinedload(Person.paperwork),)):
    with Session(e) as s:
        m = aliased(Manager, flat=True)
        stmt = (
            select(Person)
            .join(Person.manager.of_type(m))
            .order_by(m.id, Person.id.desc())
            .offset(1)
            .options(*opts)
        )
        print(
            "with joinedload" if opts else "plain",
            [
                (type(p).__name__, inspect(p).identity, p.id, getattr(p, "manager_name", None))
                for p in s.scalars(stmt).unique()
            ],
        )

Output, current main (2.1.9) and rel_2_0 (2.0.58), identical:

plain [('Person', (3,), 3, None), ('Manager', (2,), 2, 'mn2')]
with joinedload [('Person', (3,), 3, None), ('Manager', (2,), 1, 'mn1')]

Manager with identity (2,) comes back with id 1 and manager_name
'mn1', which belong to row 1.

Activity

  1. added this to the 2.0.x milestone on Nov 14, 2026
  2. added
    bug
    loader options
    inheritance
    on Nov 14, 2026
  3. sqla-tester commented on Nov 14, 2026

    @sqla-tester
    Collaborator

    Mike Bayer has proposed a fix for this issue in the main branch:

    don't adapt subclass table to aliased columns in compound eager https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7219

  4. sqla-tester commented on Nov 14, 2026

    @sqla-tester
    Collaborator

    Mike Bayer has proposed a fix for this issue in the rel_2_0 branch:

    don't adapt subclass table to aliased columns in compound eager https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7220

  5. added a commit that references this issue on Nov 16, 2026
    c5dd1a3
  6. added a commit that references this issue on Nov 17, 2026
    0933c81
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugfuzzerinheritanceloader optionsorm

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions