DEV Community

Cover image for A trash cleanup that deleted records a day early, and how I tested it in 2 minutes
Abhay Singh
Abhay Singh

Posted on AI-assisted

A trash cleanup that deleted records a day early, and how I tested it in 2 minutes

Twenty, the open-source CRM, keeps deleted records in the trash for 14 days before deleting them for good. At least, that's what it says. A record deleted at 23:50 was actually gone after 13 days and 20 minutes. With retention set to 1 day, a record deleted just before midnight UTC disappeared 11 minutes later.

The code looked reasonable:

private calculateCutoffDate(trashRetentionDays: number): Date {
const cutoffDate = new Date();

cutoffDate.setUTCHours(0, 0, 0, 0);
cutoffDate.setDate(cutoffDate.getDate() - trashRetentionDays + 1);

return cutoffDate;
}

A nightly job at 00:10 deletes everything with deletedAt < cutoff. The + 1 moves the cutoff forward a whole day, so anything deleted during day 0 is removed at 00:10 on day 14, whatever time it was deleted. There's a quieter second problem too: setUTCHours is mixed with the local-time setDate/getDate, so the result also depends on the server's time zone.

The fix was small: drop the + 1, and stay in UTC. Twenty merged it.

Why nobody caught it

This bug only shows up if you wait two weeks, delete records at the right time of day, and check after a real cron run. Unit tests usually mock new Date(), so they check the arithmetic, not what happens when Postgres's now(), the cron schedule and the job all run together.

So most of us test time-based features by:

  • editing timestamps in the database by hand,
  • adding a "make the trial 2 minutes long" flag, or
  • not testing them at all.

What I built

I got tired of doing the first one, so I built ChronoStack. It moves the clock forward for a whole Docker Compose stack at once (Postgres now(), Redis TTLs and your services) with no code changes. It runs a separate copy of your stack, so your real data isn't touched.

chronostack up --wait # a copy of your compose stack on a virtual clock
chronostack advance 15d # 15 days later everywhere; your nightly jobs ran on the way
chronostack run scenarios/trial.yml # a scripted, repeatable test with a report

For the Twenty bug, a scenario moves a record to the trash at 23:50, steps forward a day at a time, and checks the record is still there just before the 14 days are up. Then it sets retention to 1 day and does the same at 23:59. On Twenty's published image it fails. With the fix, it passes. A full run takes under 2 minutes instead of two weeks.

The hard part wasn't the fake clock

Faking the time is an old trick (libfaketime has done it for years). What took most of the work was everything that breaks once you do it:

  • Timers don't fire when the wall clock jumps. setTimeout and most in-process schedulers run on the monotonic clock, which ChronoStack deliberately leaves alone. So advance stops at each job's scheduled time and runs it.
  • Some waits hang forever. pthread_cond_timedwait and friends take a wall-clock deadline. Once virtual time is ahead, those deadlines are wrong, so the shim translates them back to real time. That's checked every night in C, Python, Node, the JVM, Ruby, PHP and .NET.
  • pg_cron skips jobs after a jump of more than 3 hours, so the clock stops on each job's minute.
  • BullMQ runs a job twice if you jump while it's running, because its lock expires. So advance waits for the queues to drain first.

Users, too

Real bugs often need real behaviour: people signing up over a week, coming back days later, some of them paying. So a scenario can bring simulated users along, and they act on the virtual clock:

cohorts:

  • { name: trialists, users: 20, arrive: { over: 7d }, journey: trial } journeys: trial:
    • http: { method: POST, url: "${api}/signup?email=u${user}-${run_id}@example.com" } save: { token: /token }
    • think: { between: [1h, 20h] }
    • http: { url: "${api}/me", headers: { x-session: "${token}" } } expect: { status: 200 }

In the demo, 20 trialists over 30 virtual days, with the partner's webhook endpoint down for 4 hours on day 15, take about 3 minutes. Every random choice comes from a seed, so the same seed gives the same timeline of who did what when. chronostack report diff then tells you what changed between two runs, for example before and after a fix.

Other bugs it found

I ran it against a few open-source projects' published Docker images. Besides Twenty, it found date bugs in Saleor, Chatwoot, Formbricks, tududi and Worklenz; Worklenz has merged the fix too. The full list, with issues and fix PRs, is in the README (https://github.com/Asmodeus14/ChronoStack#found-in-real-projects).

Try it

It's an alpha (0.1.0-alpha.8), open source under MIT/Apache-2.0. It works on Linux, Windows and Intel Macs; Apple-silicon Macs are untested so far (if you have one, issue #5 (https://github.com/Asmodeus14/ChronoStack/issues/5) is a 5-minute test).

brew install asmodeus14/tap/chronostack # macOS, Linux
scoop bucket add chronostack https://github.com/Asmodeus14/scoop-bucket # Windows
scoop install chronostack/chronostack
cargo install chronostack@0.1.0-alpha.8 # anywhere with Rust

If you try it on your own stack, I'd love to hear what breaks, especially the output of chronostack doctor.

And yes i used AI specifically Claude Code but only for testing the codes , pipelines and finding bugs in chronostack and fixing them .

Top comments (20)

Collapse
 
delayrun profile image
delay.run •

The setUTCHours plus setDate mix worries me more than the + 1, because the same build deletes on a different day depending on the container's TZ. Did the merged fix switch to setUTCDate(getUTCDate() - days), or does it still rely on the server running in UTC?

Collapse
 
asmodeus14 profile image
Abhay Singh •

It's fully UTC now. The merged fix replaced it with new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - trashRetentionDays)), so the container's TZ no longer matters. It also dropped the + 1 and added a unit test for the 23:50 case.

Collapse
 
dafili profile image
Renhua Wei •

A count assertion cannot catch the day-early delete: one record too many and one too few and the number still matches. Assert the set instead — DELETE ... RETURNING id and diff it against the expected id list — so the boundary record shows up as a diff rather than a total that happens to be right.

Collapse
 
asmodeus14 profile image
Abhay Singh •

Good point. With a batch of records spread across multiple days, a shifted window could delete one record too early and retain another too long while still passing a COUNT(*) check.

In the Twenty scenario, we tested specific boundary records: one soft-deleted at 00:05 and another at 23:50 for 14-day retention, plus a 23:59 record for 1-day retention. After each 00:10 cron run, we checked whether those specific records survived rather than relying on an aggregate table count.

For larger multi-record or cohort scenarios, asserting the exact surviving ID set (SELECT id ... ORDER BY id) is definitely the safer pattern.

Since ChronoStack runs against the unmodified published Docker image (twentycrm/twenty:v2.58.0), we can't rewrite Twenty's internal DELETE statement to use RETURNING id. Comparing the remaining ID set externally is the closest equivalent.

Thanks for suggesting the stronger assertion pattern!

Collapse
 
dafili profile image
Renhua Wei •

External set comparison beats the count, but only as an exact set: diff two sorted id lists and treat any line as a failure, not a length match. The digest matters more than the tag here — the retention window lives inside the image, so twentycrm/twenty@sha256:... is what makes the assertion still mean something next quarter.

Thread Thread
 
asmodeus14 profile image
Abhay Singh •

Agreed on both. An exact diff of sorted IDs is the right assertion: any line in the diff is a failure. And the digest point is a good one. The retention logic lives in the image, so twenty@sha256:… is what keeps the scenario meaning the same thing later. A tag can move under you.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

pg_cron skipping jobs after a jump of more than 3 hours is the quiet failure here. the off-by-one is easy to spot, the skipped run is not.

Collapse
 
asmodeus14 profile image
Abhay Singh •

Exactly. That one cost me the most time: no error, nothing in the logs, the job just never ran. pg_cron (like Vixie cron) treats a jump of more than 3 hours as a clock change and skips the missed runs instead of catching up. ChronoStack works around it by stopping the clock on each job's minute, and advance --dry-run shows which jobs will run, so a skipped run at least becomes visible.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

advance --dry-run making the skipped run visible is the real fix here. does it flag the ones that would have been skipped, or just list what will run?

Thread Thread
 
asmodeus14 profile image
Abhay Singh •

Both. For a job with a fixed time (say 0 3 * * ), it plans a clock stop on that job's minute, so it doesn't get skipped, and the dry run lists it at each stop. Jobs like * * * * * or */5 * * * * are the tricky ones: stopping on every minute of a 30-day jump would mean 43,200 stops. pg_cron runs a wildcard job once per stop, so the dry run flags the gap:
pg_cron: job '
/5 * * * *' is due 8640 time(s) but will run about 30 (... use --pg-cron-all or --step to run more)
--pg-cron-all stops on every occurrence, up to a limit of 2,000 stops. --step 1h is a cheaper middle ground. --dry-run --json has the same numbers under pg_cron_wildcards, so CI can fail on them.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

--step 1h as the middle ground makes sense, and pg_cron_wildcards under --dry-run --json means CI can catch it instead of someone noticing a month later.

Thread Thread
 
asmodeus14 profile image
Abhay Singh •

That's the idea. If you have a stack with pg_cron, I'd be curious what the dry run says about it. Wildcard schedules turn up more often than you'd expect.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

no pg_cron running on my side to dry-run against, so i can't give you a real reading. the wildcard schedules are the ones i'd want it to catch first, the ones that look fine until they fire twice.

Thread Thread
 
asmodeus14 profile image
Abhay Singh •

Fair enough, thanks for the back-and-forth. If you ever want a quick check without pg_cron, the same dry run works for any scheduled trigger. And if a job in your stack does fire twice after a jump, I'd like to hear about it. That's exactly the kind of bug it should catch.

Collapse
 
lycore profile image
Lycore Development •

The mix of setUTCHours with local-time setDate/getDate is a subtle one, and it's a good illustration of why mocking new Date() hides this class of bug. A cheap extra safeguard is to run the cleanup comparison in SQL against now() with an interval, so the boundary lives in one place and uses the database clock. It would also be worth a test that runs the job under two different TZ settings. How does your tool handle jobs that depend on both the DB clock and the app server clock?

Collapse
 
asmodeus14 profile image
Abhay Singh •

Thanks, good points on both. On your question: that's the case it's built for. The database and the app containers read the same virtual clock (the shim is loaded into every service in the stack), so a job comparing Postgres now() with the app's new Date() sees the same moment on both sides, and chronostack doctor / probe check that every service agrees. Two exceptions: Go and other static binaries can't be shimmed (doctor flags them), and monotonic clocks are deliberately left alone. ChronoStack doesn't change time zones itself, but your two-TZ idea works well with it: run the same scenario twice with a different TZ in a compose override and compare the runs with chronostack report diff.

Collapse
 
lycore profile image
Lycore Development •

That's useful, thanks. Having Postgres now() and the app clock read the same virtual time is exactly what makes these boundary bugs reproducible. Running the same scenario under two TZ values and diffing the reports sounds like a cheap way to catch the setUTCHours vs local-time class of issue, so I'll try that.

Thread Thread
 
asmodeus14 profile image
Abhay Singh •

That's exactly the kind of scenario I'd love ChronoStack to make easier to reproduce. Would be interesting to see what differences show up between the two TZ configurations, especially around date boundaries and DST transitions.

If you get a chance to try it and find it useful, a GitHub star would certainly help the project reach more developers. Either way, I'd genuinely appreciate any feedback from your testing!

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

A retention window that is a day short only shows up if someone waits two weeks and deletes at the right minute, which is exactly why it survived. Renhua's point about asserting the exact set of deleted ids rather than a count is the test I would copy first.

Ascendra Ventures built CleanSync, which keeps Google Drive in two-way sync with a server you own, around the same worry that a cleanup job can remove the wrong thing quietly. Every sync is rehearsed as a dry run first. If a run would delete more files than your limit, it stops and shows the list instead of proceeding. Anything replaced or deleted goes to a Recovery folder before it is gone, so a boundary bug costs a restore rather than a record.

Did the Twenty maintainers discuss a second safety stage like that, or is the 14 day trash itself considered the safety net?

Collapse
 
asmodeus14 profile image
Abhay Singh •

As far as I saw, no. The fix was scoped to the cutoff calculation, and the 14-day trash is the safety net. That's also why the bug mattered: the safety net was itself a day short. A dry run or a cap on deletions per run would be a sensible second layer, but that's a design change for the maintainers rather than part of this fix.