infra
infra copied to clipboard
Fix TOCTOU race in template deletion causing FK violation
Bug
There is a TOCTOU (Time-of-Check-Time-of-Use) race condition in the DELETE /templates/{templateID} handler. When a Sandbox.create(snapshotId) runs concurrently with template deletion, the following sequence causes an FK constraint violation (snapshots_envs_base_env_id):
- Delete handler calls
ExistsTemplateSnapshots()— no snapshots found - Concurrently,
Sandbox.create(snapshotId)resolves the template env, settingBaseTemplateID - Delete handler calls
DeleteTemplate()— deletes the env row - The new sandbox later pauses and
UpsertSnapshottries to INSERT withbase_env_idpointing to the deleted env — FK violation
Fix
Two-pronged approach:
1. Atomic delete with row locking (template_delete.go)
- Wrap
ExistsTemplateSnapshots+DeleteTemplatein a single DB transaction (following the existingWithTxpattern fromtemplate_tags.go) - Acquire
SELECT ... FOR UPDATEon the env row at the start of the transaction, which blocks concurrentUpsertSnapshotFK checks until the transaction commits - This eliminates the TOCTOU window between the snapshot check and the delete
2. Graceful FK violation handling (pause_instance.go)
- If
UpsertSnapshotfails with an FK violation (base template was deleted after the sandbox was created but before it paused), return a typedBaseTemplateDeletedErrorinstead of propagating a raw constraint violation - Reported as a non-critical telemetry error since this is a legitimate race outcome
Files changed
| File | Change |
|---|---|
packages/api/internal/handlers/template_delete.go |
Wrap guard checks + deletion in a DB transaction with SELECT ... FOR UPDATE on the env row |
packages/api/internal/orchestrator/pause_instance.go |
Add BaseTemplateDeletedError type; catch FK violations from UpsertSnapshot and return descriptive error |
packages/db/queries/templates/lock_env_for_update.sql |
New SQL query: SELECT id FROM envs WHERE id = @env_id FOR UPDATE |
packages/db/queries/lock_env_for_update.sql.go |
Generated Go code for the LockEnvForUpdate query |
Reproduction
Racing Sandbox.create(snapshotId) against Sandbox.deleteSnapshot(snapshotId) reproduces the FK violation on nearly every first attempt.
Test plan
- [ ] Verify template deletion still works correctly when no sandboxes reference the template
- [ ] Verify template deletion returns 400 when paused sandboxes exist
- [ ] Verify concurrent
Sandbox.create(snapshotId)+ template deletion no longer causes FK violation - [ ] Verify sandbox pause returns
BaseTemplateDeletedError(not raw FK violation) when the base template was deleted - [ ] Run
make generate/dbto confirm the generated SQL code matches