Exercise 2: Why log_usage Needs Its Own Session, for a Different Reason Than Chapter 9 — Possible Solution ==================================================================== WHY log_usage CAN'T REUSE mark_used's OWN db PARAMETER ------------------------------ By the time background_tasks.add_task schedules log_usage to actually run, the response has already been sent back to the client, and the request is fully complete. get_db's own generator function reaches its finally: db.close() once the request finishes, closing that session entirely. If log_usage tried to use that already-closed session, it would fail, since a closed session can't be used for further queries or commits. WHY THIS IS A LIFECYCLE ISSUE, NOT A CONCURRENCY ISSUE ------------------------------ Chapter 9's lookup_ingredient needed its own session because multiple lookups were running at the same time, and a synchronous Session isn't safe to share across tasks executing concurrently - that's fundamentally about simultaneous access. Here, log_usage isn't running at the same time as anything else that's still using mark_used's session - it's running strictly after mark_used and its session are already completely finished. The problem here is that the session simply no longer exists in a usable state by the time log_usage runs, not that two things are trying to use it at once. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly explains that get_db's own session is closed once the request completes, correctly explains that log_usage runs after that point, and correctly distinguishes this lifecycle-based reason from Chapter 9's genuinely different concurrency-based reason for the same underlying "give it its own session" pattern.