From c53f3025d9b9817a036137eba433bdebe86f40d9 Mon Sep 17 00:00:00 2001 From: giles Date: Wed, 25 Feb 2026 12:06:54 +0000 Subject: [PATCH] Fix no_autoflush: use manual toggle for async session AsyncSession.no_autoflush is a sync context manager, can't use with 'async with'. Toggle autoflush manually instead. Co-Authored-By: Claude Opus 4.6 --- blog/bp/blog/ghost/ghost_sync.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/blog/bp/blog/ghost/ghost_sync.py b/blog/bp/blog/ghost/ghost_sync.py index 20c8435..a1717dd 100644 --- a/blog/bp/blog/ghost/ghost_sync.py +++ b/blog/bp/blog/ghost/ghost_sync.py @@ -185,9 +185,11 @@ async def _upsert_post(sess: AsyncSession, gp: Dict[str, Any], author_map: Dict[ obj.user_id = user_id await sess.flush() - # Rebuild post_authors + post_tags inside no_autoflush to prevent - # premature INSERT from query-invoked autoflush. - async with sess.no_autoflush: + # Rebuild post_authors + post_tags with synchronize_session to keep + # identity map consistent and prevent autoflush IntegrityError. + old_autoflush = sess.autoflush + sess.autoflush = False + try: # Delete + re-add post_authors (dedup for Ghost duplicate authors) await sess.execute( delete(PostAuthor).where(PostAuthor.post_id == obj.id), @@ -212,7 +214,9 @@ async def _upsert_post(sess: AsyncSession, gp: Dict[str, Any], author_map: Dict[ seen_tags.add(tt.id) sess.add(PostTag(post_id=obj.id, tag_id=tt.id, sort_order=idx)) - await sess.flush() + await sess.flush() + finally: + sess.autoflush = old_autoflush # Auto-create PageConfig for pages if obj.is_page: