Issue #142 · branch fix/export-retry

Order export retry: uncommitted code changes

The nightly order export now retries a failed send up to three times and, if the accounting service stays down, saves the report locally instead of losing it. This page shows the code function by function and explains every important line.

+ code added line: + in front, solid bar on the left − code removed line: − in front, dashed bar on the left, struck through 1 line explained below Uncoloured lines are unchanged context. Doc comments and long comments inside functions were removed to save space; long lines continue slightly indented on the next line. The code itself is identical to the repository. Explanation level: low (brief)

1. Why this change?

Three daily reports were lost in March: the accounting service was restarting (about 30 s) when the export ran, the exporter tried once, and its fallback — an FTP server switched off in January — failed too.

2. A few concepts first

Accounting service
The finance team's server that receives the daily report.
SendError
The project's error for "the service did not take the report".
Outbox
Local folder for reports that could not be delivered.

3. The big picture

Exporter · once a night
export_daily()builds the report
↓
send_with_retry()up to 4 attempts, pauses 2 · 4 · 8 s
save_to_outbox()after the fourth failure
→POST reportup to 4 times
Accounting service
201 Createddelivered; stop
or
error / no answerwait and try again

The files are explained in this order: config.py (limits), retry.py (the rule), export.py (uses it).

4. config.py changed

exporter/config.py
config.pylines 5–7
MAX_ATTEMPTS = 41
FIRST_DELAY_S = 2
OUTBOX_DIR = "outbox"
  1. 1
    With the existing 10 s timeout per attempt, the worst case is about 54 s — longer than the 30 s restart.

5. retry.py new file

exporter/retry.py

Imports and logger

retry.pylines 2–7, new
import logging
import time

from .client import SendError1

log = logging.getLogger(__name__)
  1. 1
    Only this error is retried; any other error surfaces at once.

retry_delays(): the pauses

retry.pyline 10, new
def retry_delays(attempts, first_s):
    return [first_s * 2 ** i for i in range(attempts - 1)]1
  1. 1
    Doubling pauses, one fewer than attempts: retry_delays(4, 2) → [2, 4, 8].

send_with_retry(): the loop

retry.pyline 15, new
def send_with_retry(send, payload, attempts, first_s, sleep=time.sleep):
    delays = retry_delays(attempts, first_s)
    for attempt in range(1, attempts + 1):
        try:
            send(payload)
            return True1
        except SendError as err:
            log.warning("attempt %d of %d failed: %s", attempt, attempts, err)
            if attempt < attempts:
                sleep(delays[attempt - 1])2
    return False
  1. 1
    Stops at the first success.
  2. 2
    Pauses between attempts, never after the last one. Tests pass a stand-in for sleep so they do not wait.

6. export.py changed

exporter/export.py

Imports

export.pylines 2–9
import json
import os
from .client import AccountingClient, SendError
from .legacy_ftp import upload_backup1
from .client import AccountingClient
from .retry import send_with_retry
  1. 1
    The FTP fallback goes; its file is deleted.

export_daily(): the nightly job

export.pylines 14–22
def export_daily(orders, client=None):
    # … client and report set up as before …
    try:
        client.post(report)1
    except SendError as err:
        log.error("export failed: %s", err)
        upload_backup(report)
        return False
    return True
    if send_with_retry(client.post, report, config.MAX_ATTEMPTS, config.FIRST_DELAY_S):2
        return True
    path = save_to_outbox(report)3
    log.error("export failed after %d attempts; report saved to %s", config.MAX_ATTEMPTS, path)
    return False
  1. 1
    Before: one attempt, then the dead FTP fallback.
  2. 2
    Now: up to 4 attempts with the settings from config.py.
  3. 3
    After the fourth failure the report is kept as a file; the error line names it.

save_to_outbox(): keep the report

export.pyline 25, new
def save_to_outbox(report, outbox_dir=None):
    outbox_dir = outbox_dir or config.OUTBOX_DIR
    os.makedirs(outbox_dir, exist_ok=True)
    path = os.path.join(outbox_dir, f"report-{report['date']}.json")1
    with open(path, "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2)
    return path
  1. 1
    One JSON file per day, e.g. outbox/report-2026-03-14.json.

7. Tests new files

tests/test_retry.py · tests/test_export.py
TestWhat it proves
test_delays_double_each_timePauses [2, 4, 8].
test_success_on_third_attemptTrue, pauses [2, 4].
test_all_attempts_failFalse, pauses [2, 4, 8].
test_outbox_file_holds_the_reportFile report-2026-03-14.json holds the report.

8. Not explained line by line

FileWhyWhat changed
exporter/legacy_ftp.pydeletedThe FTP backup upload; the server no longer exists.
tests/test_retry.py, tests/test_export.pytestsNew; see Tests.

9. Scenarios: which lines run, in order?

A. The service is restarting

  1. Attempts 1 and 2 fail; send_with_retry pauses 2 s, then 4 s.
  2. Attempt 3 succeeds; export_daily returns True.

B. The service is down all night

  1. Four failures; send_with_retry returns False.
  2. save_to_outbox writes the file; one error line names it.

10. Known limits

No automatic re-send of outbox files, and a full disk still loses the report.

11. Verification status

Unit tests: 4/4 passedpytest.
Test system: openNot yet run against the service's test instance.

This is the example page of the explain-changes skill. The project, the issue and the results are invented; the code is in tests/fixtures/reference-example.