Fix comment eager loading

Following #485, we began investigating post/comment rendering
bottlenecks. The most immediate issue is the eager comment loading
(merged in 23a8fb9663) did not seem fully operative: query logs
showed comments and associated FKs were being lazy loaded again
(linear query quantity in number of rendered comments). In fact,
CPU load seemed even worse than previous lazy loading.

Bisect revealed first bad commit: fb77cbcc2b
which fixed post view counters by committing the SQLAlchemy session
instead of flushing, following upstream's fix. However, committing
a session has the unfortunate side effect of dumping cached session
objects, such as the previously loaded comment objects and their
relationships, causing fallback to the old lazy behavior.

We fix this here by explicitly telling SQLAlchemy to not expire
the session on commit.

Hopefully this will simultaneously resolve the elevated DB CPU load
observed in production and speed up page rendering again.
This commit is contained in:
TLSM 2023-02-07 05:56:01 -05:00
parent 175f9c1d22
commit 509332e9cc
No known key found for this signature in database
GPG key ID: E745A82778055C7E

View file

@ -235,6 +235,7 @@ def post_id(pid, anything=None, v=None, sub=None):
post.replies = get_comment_trees_eager(top_comment_ids, sort, v)
post.views += 1
g.db.expire_on_commit = False
g.db.add(post)
g.db.commit()