fix: one file the worker may not delete no longer stops the cleanup of every other file
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 7m23s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m34s

CI run 318 failed in retention_test: an expired upload outside the
storage policy's prefixes (originals/, videos/) made delete_object raise
AccessDenied, and the cleanup stopped there on every tick, so no file
behind it was ever deleted. The worker now logs it as an error (so it
reaches Sentry), tries that file again a day later and goes on with the
rest; retention_test covers it. The test fixtures that wrote keys under
test/, machine-test/, machine-log-test/ and reset-test/ now use
originals/, where the worker may delete them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-16 17:41:49 -03:00
parent 0e7b6eb019
commit 2439948249
7 changed files with 28 additions and 7 deletions

View File

@@ -6,6 +6,7 @@ import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import psycopg
from botocore.exceptions import ClientError
from psycopg.types.json import Jsonb
from . import mail, observability, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
@@ -40,7 +41,16 @@ def cleanup():
AND (expires_at<=now() OR (NOT complete AND created_at<now()-interval '1 day'))
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 50""").fetchall()
for row in rows:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
# A file this worker may not delete (outside the storage policy's
# prefixes, or a storage refusal) must not stop the cleanup of
# every file after it: it is reported and tried again tomorrow.
try:
storage.discard(row['object_key'],row['multipart_id'],row['complete'])
except ClientError as exc:
logging.error('Cleanup could not delete upload %s (%s): %s', row['id'],
row['object_key'].split('/')[0], exc.response.get('Error',{}).get('Code'))
c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '1 day' WHERE id=%s", (row['id'],))
continue
# A generated PNG's pieces for the Kanban's viewer go with it (item 7).
if row['name'].lower().endswith('.png'):
storage.discard_prefix(f"originals/tiles/{row['id']}/")

View File

@@ -32,7 +32,7 @@ def run():
video_id = next(name for name in ('retirada', 'sala', 'nota', 'avulsas', 'subindo', 'png') if name not in taken)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at)
VALUES(%s,%s,'reset-video.mp4',1,%s,'',true,now()+interval '30 days')''',
(video_upload, owner, f'reset-test/{video_upload}.mp4'))
(video_upload, owner, f'originals/reset-test-{video_upload}'))
c.execute("INSERT INTO dtf_local.site_videos(id,upload_id) VALUES(%s,%s)", (video_id, video_upload))
lines = []

View File

@@ -13,7 +13,7 @@ def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-log-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-log-test/{uid}'))
(uid, owner, f'originals/machine-log-test-{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine log test','test')''', (uuid4(), oid, uid))

View File

@@ -12,7 +12,7 @@ def final_stub(c, oid, owner):
uid = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'machine-test.png',1,%s,'',true,now()+interval '1 day','clean')''',
(uid, owner, f'machine-test/{uid}'))
(uid, owner, f'originals/machine-test-{uid}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','machine test','test')''', (uuid4(), oid, uid))

View File

@@ -123,7 +123,7 @@ def run():
for name, fid in files.items():
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,%s,1,%s,'m',true,now()+interval '20 days','clean')''',
(fid, owner, name + '.png', f'test/{fid}'))
(fid, owner, name + '.png', f'originals/test-{fid}'))
def place(quote, order, uploads, provider, cancelled):
content = {'customer': {'mail': mail}, 'items': [{'mode': 'file', 'uploads': [str(u) for u in uploads]}],
'total_cents': 1490}

View File

@@ -18,6 +18,13 @@ def run():
with connect() as c:
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at) VALUES(%s,%s,%s,%s,%s,%s,true,%s)',
(uid,uuid4(),'LOCAL-RETENTION-TEST.txt',len(b'LOCAL RETENTION TEST'),key,upload,expiry))
# A file outside the storage policy's prefixes cannot be deleted: it must
# not stop the cleanup of the others, and is tried again a day later.
denied=uuid4()
with connect() as c:
c.execute('INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,expires_at,created_at) VALUES(%s,%s,%s,1,%s,%s,true,%s,%s)',
(denied,uuid4(),'LOCAL-RETENTION-DENIED.txt',f'retention-denied/{denied}','',
datetime.now(timezone.utc)-timedelta(days=1),datetime.now(timezone.utc)-timedelta(days=400)))
# Cleanup takes 50 at a time, oldest first: the suites before this one
# leave their own expired files ahead of the fixture.
for _ in range(100):
@@ -27,6 +34,10 @@ def run():
with connect() as c:
assert c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[0],)).fetchone()['purged_at']
assert not c.execute('SELECT purged_at FROM dtf_local.uploads WHERE id=%s',(ids[1],)).fetchone()['purged_at']
with connect() as c:
row=c.execute('SELECT purged_at,expires_at>now() AS later FROM dtf_local.uploads WHERE id=%s',(denied,)).fetchone()
assert not row['purged_at'] and row['later'],row
c.execute('DELETE FROM dtf_local.uploads WHERE id=%s',(denied,))
try:storage.size(f'originals/{ids[0]}');raise AssertionError('Expired bytes still exist')
except ClientError as exc:assert exc.response['ResponseMetadata']['HTTPStatusCode']==404
assert storage.size(f'originals/{ids[1]}')==len(b'LOCAL RETENTION TEST')

View File

@@ -389,7 +389,7 @@ def run():
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
(upload, owner, f'test/{upload}'))
(upload, owner, f'originals/test-{upload}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
@@ -453,7 +453,7 @@ def run():
upload = uuid4()
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete,
expires_at,scan_state) VALUES(%s,%s,'final.pdf',1,%s,'m',true,now()+interval '20 days','clean')''',
(upload, owner, f'test/{upload}'))
(upload, owner, f'originals/test-{upload}'))
c.execute('''INSERT INTO dtf_local.order_files(id,order_id,upload_id,item_index,kind,note,created_by)
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",