openstreetmap-ng icon indicating copy to clipboard operation
openstreetmap-ng copied to clipboard

feat: background recompression of trace files

Open Finesssee opened this issue 6 months ago • 0 comments

Resolves #100.

What

Adds an async background task that recompresses a freshly uploaded trace file with a heavier zstd level (22) without delaying the upload response, mirroring the existing fire-and-forget pattern used by AuditService / ImageProxyService.

How

  • TraceFile.compress(buffer, *, level=...) — new optional level argument. The default (level 6) path is unchanged and still reuses the cached options/metadata; the heavy path builds level-derived options and records the real zstd_level in the file metadata.
  • TraceService.upload — once the DB transaction has committed and trace_id is known, it schedules _recompress_trace(trace_id, file_id, file) on a module-level TaskGroup and returns immediately. The response is not delayed by heavy compression.
  • _recompress_trace — recompresses off the event loop (to_thread, GIL released by the zstd C extension), saves the new file, then swaps trace.file_id and deletes the now-unreferenced file.
  • TraceService.context() — registered in the app lifespan so the background tasks are awaited on shutdown (DB pool is still open at that point).

Correctness / race handling

  • The swap is UPDATE ... WHERE id = trace_id AND file_id = old_file_id. If the trace was deleted or its file already changed, the update affects 0 rows and the freshly written file is removed instead — no dangling reference, no orphan.
  • If the new file is saved but the DB swap fails, the new file is cleaned up.
  • TraceService.delete now deletes atomically with DELETE ... RETURNING file_id and removes exactly the file the row referenced at deletion time, closing the delete/recompression race that could otherwise orphan the recompressed file. Existing trace_not_found vs trace_access_denied behaviour is preserved.
  • Read path is unaffected: decompress_if_needed keys off the .zst suffix and is level-agnostic.

Tests

tests/services/test_trace_service.py::test_trace_background_recompression uploads a trace, waits for the background task to settle, and asserts the stored file matches a level-22 reference and still round-trips back to the original bytes.

Finesssee avatar May 29 '26 06:05 Finesssee