Compare commits

...

2 Commits

Author SHA1 Message Date
Cauê Faleiros
9cf4da0dea Merge render limit per part (order #20)
All checks were successful
Build and deploy / Validate source (push) Successful in 12s
Build and deploy / Integration suite on a real stack (push) Successful in 7m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m29s
2026-11-12 15:03:17 -03:00
Cauê Faleiros
a17287a118 fix: a long film's print file gets a render limit per 15 m part
Order #20 (23.6 m, 24 pieces) failed with "Falhou ao gerar": the whole
film had one 15 min limit, and two parts at 300 DPI take longer on the
server. The limit is now PRINT_RENDER_TIMEOUT_SECONDS (default 20 min)
for each part, and each claim records its deadline, so the stale-claim
check and the card's "Tempo limite" follow the same limit. A timeout, or
a final failed attempt, is logged as an error so Sentry sees it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-12 15:03:16 -03:00
4 changed files with 60 additions and 17 deletions

View File

@@ -173,8 +173,8 @@ def with_print_files(c, orders):
ids = [o['id'] for o in orders] ids = [o['id'] for o in orders]
generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at, generated = c.execute('''SELECT p.order_id,p.item_index,p.status,p.upload_id,p.detail,p.claimed_at,p.finished_at,
p.created_at, p.created_at,
(p.status='rendering' AND p.claimed_at<now()-%s) AS timed_out, (p.status='rendering' AND COALESCE(p.deadline_at,p.claimed_at+%s)<now()) AS timed_out,
p.claimed_at+%s AS timeout_at,u.name COALESCE(p.deadline_at,p.claimed_at+%s) AS timeout_at,u.name
FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id FROM dtf_local.print_files p LEFT JOIN dtf_local.uploads u ON u.id=p.upload_id
WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall() WHERE p.order_id=ANY(%s) ORDER BY p.item_index''', (CLAIM_TIMEOUT, CLAIM_TIMEOUT, ids)).fetchall()
upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items'] upload_ids = sorted({str(uid) for order in orders for item in order['snapshot']['items']

View File

@@ -0,0 +1,3 @@
-- A print file's render limit grows with its film (RENDER_SECONDS per 15 m
-- part, app/printjobs.py): each claim records when it counts as abandoned.
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS deadline_at timestamptz;

View File

@@ -2,8 +2,9 @@
A paid order queues one job per item. The worker claims a job, commits the A paid order queues one job per item. The worker claims a job, commits the
claim, and renders outside any transaction, so a long render never holds a row claim, and renders outside any transaction, so a long render never holds a row
lock or a database connection. A claim older than CLAIM_TIMEOUT is assumed to lock or a database connection. A claim past its deadline (the render limit
belong to a worker that died and is taken again. plus a margin; CLAIM_TIMEOUT for a claim made before deadlines existed) is
assumed to belong to a worker that died and is taken again.
The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a The result is a 300 DPI PNG (item 13, app/printpng.py), or its parts for a
film over 15 m: ordinary upload rows owned by an identity derived from the film over 15 m: ordinary upload rows owned by an identity derived from the
@@ -36,21 +37,36 @@ from .cart_pricing import needs_designer
from .core.auth import audit from .core.auth import audit
from .core.db import connect from .core.db import connect
from .printfile import Unsupported from .printfile import Unsupported
from .printpng import render from .printpng import part_cuts, render
from .proof import PROOF_SHEET_CM from .proof import PROOF_SHEET_CM
from .tiny import purchase_order from .tiny import purchase_order
LOCAL = ZoneInfo('America/Sao_Paulo') LOCAL = ZoneInfo('America/Sao_Paulo')
# A 15 m part takes minutes to write; a long film, several parts. # A 15 m part takes about 7 min to write on a fast core; a long film, several
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '900')) # parts. The limit is per part: order #20's 23.6 m film (2026-11-12) ran past a
CLAIM_TIMEOUT = timedelta(minutes=18) # single 15 min limit for the whole film.
RENDER_SECONDS = int(os.environ.get('PRINT_RENDER_TIMEOUT_SECONDS', '1200'))
CLAIM_MARGIN = timedelta(minutes=3)
CLAIM_TIMEOUT = timedelta(seconds=RENDER_SECONDS) + CLAIM_MARGIN
# A claim is stale once past its deadline.
STALE = 'COALESCE({p}.deadline_at, {p}.claimed_at + %s) < now()'
MAX_ATTEMPTS = 3 MAX_ATTEMPTS = 3
LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024))) LARGE_SOURCE_BYTES = int(os.environ.get('PRINT_DECODE_MAX_BYTES', str(300 * 1024 * 1024)))
# Read band by band, whatever their size. # Read band by band, whatever their size.
STREAMED = ('.png', '.pdf') STREAMED = ('.png', '.pdf')
def render_seconds(item):
"""The render limit of one item: RENDER_SECONDS for each part of its film."""
production = item.get('production') or {}
try:
parts = len(part_cuts(production)) - 1 if production.get('placements') else 1
except (KeyError, TypeError, ValueError, ArithmeticError):
parts = 1
return RENDER_SECONDS * max(1, parts)
def generated_identity(order_id): def generated_identity(order_id):
return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}') return uuid5(NAMESPACE_URL, f'dtf-print-file:{order_id}')
@@ -93,7 +109,8 @@ def queue(c, order_id, items, only_missing=False):
ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0, ON CONFLICT(order_id,item_index) DO UPDATE SET status='pending', attempts=0,
claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}' claimed_at=NULL, claim_token=NULL, finished_at=NULL, upload_id=NULL, detail='{}'
WHERE dtf_local.print_files.status IN ('failed','manual') OR WHERE dtf_local.print_files.status IN ('failed','manual') OR
(dtf_local.print_files.status='rendering' AND dtf_local.print_files.claimed_at<now()-%s)''', (dtf_local.print_files.status='rendering' AND '''
+ STALE.format(p='dtf_local.print_files') + ')',
(uuid4(), order_id, index, CLAIM_TIMEOUT)) (uuid4(), order_id, index, CLAIM_TIMEOUT))
else: else:
c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s) c.execute('''INSERT INTO dtf_local.print_files(id,order_id,item_index) VALUES(%s,%s,%s)
@@ -103,7 +120,7 @@ def queue(c, order_id, items, only_missing=False):
def claim(c): def claim(c):
return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p return c.execute('''SELECT p.*, o.snapshot, o.number, o.parent_id, o.created_at AS ordered_at FROM dtf_local.print_files p
JOIN dtf_local.orders o ON o.id=p.order_id JOIN dtf_local.orders o ON o.id=p.order_id
WHERE p.status='pending' OR (p.status='rendering' AND p.claimed_at < now()-%s) WHERE p.status='pending' OR (p.status='rendering' AND ''' + STALE.format(p='p') + ''')
ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at ORDER BY CASE WHEN o.parent_id IS NOT NULL THEN 0 ELSE 1 END, p.created_at
FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone() FOR UPDATE OF p SKIP LOCKED LIMIT 1''', (CLAIM_TIMEOUT,)).fetchone()
@@ -120,13 +137,13 @@ def _render_child(result_queue, job, item, uploads):
result_queue.put(('error', type(exc).__name__)) result_queue.put(('error', type(exc).__name__))
def render_with_timeout(job, item, uploads): def render_with_timeout(job, item, uploads, seconds=RENDER_SECONDS):
ctx = multiprocessing.get_context('spawn') ctx = multiprocessing.get_context('spawn')
result_queue = ctx.Queue() result_queue = ctx.Queue()
process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads)) process = ctx.Process(target=_render_child, args=(result_queue, job, item, uploads))
process.start() process.start()
try: try:
process.join(RENDER_SECONDS) process.join(seconds)
if process.is_alive(): if process.is_alive():
process.terminate() process.terminate()
process.join(5) process.join(5)
@@ -149,10 +166,12 @@ def render_one(storage):
if not job: if not job:
return False return False
token = uuid4() token = uuid4()
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
attempts=attempts+1,claim_token=%s WHERE id=%s''', (token, job['id']))
job['claim_token'] = token
item = job['snapshot']['items'][job['item_index']] item = job['snapshot']['items'][job['item_index']]
seconds = render_seconds(item)
c.execute('''UPDATE dtf_local.print_files SET status='rendering', claimed_at=now(),
deadline_at=now()+%s, attempts=attempts+1,claim_token=%s WHERE id=%s''',
(timedelta(seconds=seconds) + CLAIM_MARGIN, token, job['id']))
job['claim_token'] = token
source_ids = [UUID(u) for u in item['uploads']] source_ids = [UUID(u) for u in item['uploads']]
# A format such as CDR needs a human to prepare the full-size final on # A format such as CDR needs a human to prepare the full-size final on
# the parent. The child still generates its own 15 cm proof from that PNG, # the parent. The child still generates its own 15 cm proof from that PNG,
@@ -195,17 +214,23 @@ def render_one(storage):
'monte a folha a partir do original'}) 'monte a folha a partir do original'})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index']) audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True return True
outcome, result = render_with_timeout(job, item, by_id) outcome, result = render_with_timeout(job, item, by_id, seconds)
if outcome == 'manual': if outcome == 'manual':
finish(job, 'manual', {'reason': result}) finish(job, 'manual', {'reason': result})
audit('print_file_manual', order=str(job['order_id']), item=job['item_index']) audit('print_file_manual', order=str(job['order_id']), item=job['item_index'])
return True return True
if outcome == 'timeout': if outcome == 'timeout':
finish(job, 'failed', {'reason': f'Tempo limite de {RENDER_SECONDS // 60} min excedido. Gere de novo.'}) finish(job, 'failed', {'reason': f'Tempo limite de {seconds // 60} min excedido. Gere de novo.'})
audit('print_file_timeout', order=str(job['order_id']), item=job['item_index']) audit('print_file_timeout', order=str(job['order_id']), item=job['item_index'])
# The card says so too, but Sentry (and the Vigia) hear of it first.
logging.error('Print file generation timed out after %s min: order #%s item %s',
seconds // 60, job['number'], job['item_index'] + 1)
return True return True
if outcome == 'error': if outcome == 'error':
final = job['attempts'] + 1 >= MAX_ATTEMPTS final = job['attempts'] + 1 >= MAX_ATTEMPTS
if final:
logging.error('Print file generation failed: order #%s item %s: %s',
job['number'], job['item_index'] + 1, result)
finish(job, 'failed' if final else 'pending', {'error': result, finish(job, 'failed' if final else 'pending', {'error': result,
'reason': 'A geração falhou. Gere de novo.' if final else ''}) 'reason': 'A geração falhou. Gere de novo.' if final else ''})
return True return True

View File

@@ -38,5 +38,20 @@ class ProofCutTests(unittest.TestCase):
self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)]) self.assertEqual(proof_cut(100, 15, None), [Decimal(0), Decimal(15)])
class RenderLimitTests(unittest.TestCase):
"""Order #20 (2026-11-12): a 23.6 m film ran past one 15 min limit."""
def test_the_limit_grows_with_the_parts(self):
from app.printjobs import RENDER_SECONDS, render_seconds
def film(height):
return {'production': {'height_cm': height, 'placements': [
{'y_cm': 0, 'length_cm': height, 'source_index': 0}]}}
self.assertEqual(render_seconds(film(800)), RENDER_SECONDS)
self.assertEqual(render_seconds(film(2359.2)), 2 * RENDER_SECONDS)
self.assertEqual(render_seconds(film(4600)), 4 * RENDER_SECONDS)
self.assertEqual(render_seconds({'mode': 'file'}), RENDER_SECONDS)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()