Skip to content

Use a new session per loop in the sqlalchemy_declarative benchmark - #472

Merged
StanFromIreland merged 4 commits into
python:mainfrom
mattip:sqlachemy-expunge_all
Nov 22, 2026
Merged

StanFromIreland merged 4 commits into
python:mainfrom
mattip:sqlachemy-expunge_all

Conversation

@mattip

@mattip mattip commented May 10, 2026

Copy link
Copy Markdown
Contributor

Claude helped me come up with this fix for hundreds of emitted warnings, with the justification:

SQLite reuses primary key IDs after a full table DELETE (it has no AUTOINCREMENT sequence to preserve), the next loop iteration inserts new Person and Address objects with the same IDs (1..N) as the previous run.

On CPython this is harmless: refcounting immediately collects the old objects when new_person is reassigned each iteration, clearing the identity map's weakrefs before the next loop. On PyPy, GC is deferred - the old objects remain alive, so the identity map still holds live entries for IDs 1..N. When the new objects are committed with the same keys, SQLAlchemy's _register_persistent detects the collision and emits:

SAWarning: Identity map already had an identity for (Person, (1,), None), replacing it with newly flushed object. Are there load operations occurring inside of an event handler within the flush?

This warning fires for every inserted row on every benchmark loop, flooding stderr and causing the benchmark to fail on PyPy.

Fix: call session.expunge_all() immediately after the bulk deletes to explicitly clear the stale session state before timing begins.

It would be nice to have someone who understands more about sqlalchemy than me review this for correctness, I am not sure this is the right place for a fix.

@mattip

mattip commented May 14, 2026

Copy link
Copy Markdown
Contributor Author

What is pyperformance policy for this kind of change? It will change the benchmark results, even if slightly. Maybe this would go together with an update the sqlalchemy version in the benchmark suite?

@StanFromIreland StanFromIreland changed the title add db cleanup for PyPy Use a new session per loop in the sqlalchemy_declarative benchmark Nov 22, 2026
@StanFromIreland
StanFromIreland merged commit 498ff13 into python:main Nov 22, 2026
20 checks passed
@StanFromIreland

Copy link
Copy Markdown
Member

Merged, thanks Matti.

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.

3 participants