Fix the write count for a nightly deactivation job
Your task
An AI wrote a nightly Django command that deactivates users who have not logged in for a year. It called save() and AuditLog.objects.create() once per user, so 200,000 stale users meant 400,000 write statements on the primary database. The rewrite runs one set based update() and writes the audit rows with bulk_create in chunks. Your tests check a model of how many write statements each version sends.
An assistant wrote count_write_statements(stale_user_count, audit_batch_size, use_bulk_writes). It is in the editor. It has a bug. Find it and fix it.
Input and output:
stale_user_count: how many users the job deactivates, an integer.audit_batch_size: how many audit rows go into onebulk_createstatement, an integer. A bad config can make it 0 or negative.use_bulk_writes: true for the rewrite, false for the per-user loop.- Return the number of write statements, as an integer.
Rules the tests check:
- A negative
stale_user_countcounts as 0. With 0 stale users the job sends no writes, so return 0 in both modes. - Without bulk writes, each user costs 2 statements: return 2 times the user count.
- With bulk writes, return 1 for the
update()plus the number of audit chunks. The chunk count is the user count divided by the batch size, rounded up. - A batch size of 0 or less puts all audit rows in a single chunk.
Examples
count_write_statements(stale_user_count: int, audit_batch_size: int, use_bulk_writes: bool) -> intExample 1
Input
count_write_statements(200000, 5000, True)Output
41Example 2
Input
count_write_statements(200000, 5000, False)Output
400000Example 3
Input
count_write_statements(50, 5000, True)Output
2