Repository navigation
Description
Continuum decides whether a flush needs a transaction row by change-detecting
every versioned object in the session, including the clean ones. If a
transaction flushes many times, that walk repeats, and the cost grows with the
session rather than with the number of changes.
A batch job here loads a working set of rows and flushes several times per row
while processing them. Both numbers grow together, so the change detection went
quadratic: a 400-row batch spent 12 of its 18 seconds inside is_modified.
Reproducing it
The script at the bottom loads N rows, then does one flush per row with a single
row dirtied each time. It counts calls to utils.is_modified and the version
rows produced, so you can see the work and the output side by side.
is_modified calls wall version rows
rows/flushes upstream narrowed upstream narrowed (both)
50 1,275 50 0.038s 0.032s 100
100 17,550 150 0.234s 0.066s 300
200 102,600 350 1.358s 0.132s 700
400 482,700 750 6.187s 0.270s 1500
482,700 change-detection calls to record 400 modifications. The call count grows
roughly N^2.9 while the real work is linear.
Why it happens
UnitOfWork.is_modified is only ever a gate. process_before_flush does:
if not self.is_modified(session):
returnThat reaches utils.is_session_modified, which walks versioned_objects:
def versioned_objects(session):
for obj in session: # every object in the identity map
if is_versioned(obj):
yield objfor obj in session iterates the whole identity map, so every flush
change-detects every versioned object in the session, column by column, whether
or not it has been touched.
Suggested fix
A clean persistent object cannot produce a version row, and the rows themselves
come from make_versions via operation tracking rather than from this walk. So
the gate's answer only depends on what is pending:
def versioned_objects(session):
for obj in (*session.new, *session.dirty, *session.deleted):
if is_versioned(obj):
yield objRun the script with --narrow for the right-hand columns above. The version row
counts come out identical at every size (100 / 300 / 700 / 1500), which is the
part that matters: this changes how long the gate takes, not what gets written.
Narrowing this same check has precedent in CHANGES.rst, which is part of why I
think it is an oversight rather than deliberate:
- 0.8.3 - "Fixed UnitOfWork changed entities handling (now checks only for
versioned attributes not all object attributes)" - 1.2.0 - "Removed is_modified checking from insert operations"
We are running the narrowed version locally through
VersioningManager(unit_of_work_cls=...) and the version rows it writes are
byte-identical to before. Happy to turn this into a PR with a test if the
approach looks right to you.
Versions
sqlalchemy-continuum 1.8.0 (the walk is unchanged on master), SQLAlchemy 2.x,
Python 3.14, SQLite for the repro.
continuum_repro.py
"""Minimal repro: Continuum's flush gate scans the whole identity map.
python continuum_repro.py
"""
import time
import sqlalchemy as sa
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy_continuum import make_versioned
import sqlalchemy_continuum.utils as cu
make_versioned(user_cls=None)
Base = declarative_base()
class Thing(Base):
__tablename__ = "thing"
__versioned__ = {}
id = sa.Column(sa.Integer, primary_key=True)
a = sa.Column(sa.String(50))
b = sa.Column(sa.String(50))
c = sa.Column(sa.String(50))
sa.orm.configure_mappers()
engine = sa.create_engine("sqlite://")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
calls = 0
_real = cu.is_modified
def counting(obj, *a, **k):
global calls
calls += 1
return _real(obj, *a, **k)
cu.is_modified = counting
NARROW = "--narrow" in __import__("sys").argv
if NARROW:
# The proposed fix: only objects this flush could version.
def versioned_objects(session):
for obj in (*session.new, *session.dirty, *session.deleted):
if cu.is_versioned(obj):
yield obj
cu.versioned_objects = versioned_objects
print(f"{'rows in session':>16} {'flushes':>8} {'is_modified calls':>18} {'wall':>9} {'version rows':>13}")
for n in (50, 100, 200, 400):
s = Session()
s.add_all([Thing(a="x", b="y", c="z") for _ in range(n)])
s.commit()
rows = s.query(Thing).all() # whole table in the identity map
calls = 0
t = time.perf_counter()
for i, row in enumerate(rows): # one flush per row, one row dirty each
row.a = f"v{i}"
s.flush()
dt = time.perf_counter() - t
s.commit()
vrows = s.execute(sa.text("SELECT count(*) FROM thing_version")).scalar()
s.close()
print(f"{n:>16} {n:>8} {calls:>18} {dt:>8.3f}s {vrows:>13}")
Activity