Stop a retry from becoming a second trade

A timeout means the reply is missing, not that the brokerage said no. Save the trade, mark its outcome unknown and check before you send it again.

By Galore. Reviewed 3 December 2026. Source and tests on GitHub.

Run it

Download order_retry_journal.py, read it, and run it with Python 3.10 or later. It uses SQLite and the standard library, cleans up its temporary database, and makes no network calls or orders.

python3 order_retry_journal.py

Put the twelve behavior checks in the same folder and run:

python3 order_retry_journal_test.py

Expected results: thirteen cases, one simulated send, zero broker calls.

One ID for one trade

Pick a stable ID before sending and reuse it for every retry. Tie it to the account, the AI, the rules, the symbol, the quantity and the limit price. Reusing the ID with different details is an idempotency conflict. A unique database key stops local duplicates; it does not make the brokerage idempotent.

Save the uncertainty first

  1. Save the exact trade in a database transaction.
  2. Check the rules again just before sending. If they were turned off first, the trade stops.
  3. Save UNKNOWN before calling the brokerage.
  4. After a timeout or restart, look the trade up at the brokerage by its stable ID. If you still cannot tell, keep it unknown.
  5. Record acceptance and fills separately. A repeated delivery reads the saved state and never sends again.

The example stops at step three and takes outcomes as inputs. If it crashes after saving UNKNOWN but before sending, the trade waits for a person to resolve it. That is on purpose.

Results

Thirteen cases from the downloadable program
CaseResult
first_intentreserved_for_simulation
first_dispatch_claimdispatch_once_for_simulation
retry_after_unknown_outcomereconcile_required
second_dispatch_claimreconcile_required
same_key_changed_orderidempotency_conflict
retry_after_restartreconcile_required
acknowledged_is_not_filledACKNOWLEDGED
retry_after_fillalready_recorded
wrong_agentidentity_mismatch
invalid_quantityinvalid_intent
new_order_after_revokepermission_revoked
revoke_between_reserve_and_dispatchpermission_revoked
expiry_boundarypermission_expired

Turning rules off, and the record

SQLite transactions put saving, turning rules off and sending in one order. Rules are checked again at send time. Turning them off after that cannot pull back a trade already sent. A real executor has to handle that gap.

Every event goes into a local table that blocks ordinary edits and deletes. A database administrator can still change it, so this is not an immutable archive.

Read the code

Show the full SQLite example
"""Educational local order journal. No broker, credentials, network or SDK.

Demonstrates durable intent identity and conservative retry handling in SQLite.
Permission creation/revocation and outcome recording require a trusted caller.
There is no authentication, portfolio risk engine or live execution adapter here.
"""
from contextlib import contextmanager
from dataclasses import dataclass, replace
import json
from pathlib import Path
import re
import sqlite3
from tempfile import TemporaryDirectory


def identifier(value):
    return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_.:-]{1,96}", value) is not None


def positive_int(value):
    return type(value) is int and 0 < value <= 10**12


@dataclass(frozen=True)
class Intent:
    account: str
    agent: str
    symbol: str
    quantity: int
    limit_cents: int


class Journal:
    def __init__(self, path):
        self.db = sqlite3.connect(path, isolation_level=None, timeout=10)
        self.db.execute("PRAGMA synchronous=FULL")
        self.db.executescript("""
            CREATE TABLE IF NOT EXISTS permissions (
                id TEXT PRIMARY KEY, account TEXT NOT NULL, agent TEXT NOT NULL,
                expires_at INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
            CREATE TABLE IF NOT EXISTS attempts (
                id TEXT PRIMARY KEY, permission_id TEXT NOT NULL,
                payload TEXT NOT NULL, state TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS audit (
                seq INTEGER PRIMARY KEY, operation_id TEXT NOT NULL, event TEXT NOT NULL);
            CREATE TRIGGER IF NOT EXISTS audit_no_update BEFORE UPDATE ON audit
                BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
            CREATE TRIGGER IF NOT EXISTS audit_no_delete BEFORE DELETE ON audit
                BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
        """)

    def close(self):
        self.db.close()

    @contextmanager
    def transaction(self):
        # Serializes competing local writers, including revoke and dispatch claims.
        self.db.execute("BEGIN IMMEDIATE")
        try:
            yield
            self.db.execute("COMMIT")
        except BaseException:
            self.db.execute("ROLLBACK")
            raise

    def event(self, key, event):
        self.db.execute("INSERT INTO audit(operation_id,event) VALUES (?,?)", (key, event))

    def create_permission(self, permission_id, account, agent, expires_at):
        if not all(map(identifier, (permission_id, account, agent))) or not positive_int(expires_at):
            raise ValueError("invalid permission")
        with self.transaction():
            # Never upsert: a revoked permission identifier cannot be resurrected.
            self.db.execute("INSERT INTO permissions VALUES (?,?,?,?,0)",
                            (permission_id, account, agent, expires_at))
            self.event(permission_id, "permission_created")

    def revoke(self, permission_id):
        with self.transaction():
            changed = self.db.execute("UPDATE permissions SET revoked=1 WHERE id=?",
                                      (permission_id,)).rowcount
            if changed != 1:
                raise ValueError("unknown permission")
            self.event(permission_id, "permission_revoked")

    def permission_error(self, permission_id, intent, now):
        row = self.db.execute("SELECT account,agent,expires_at,revoked FROM permissions WHERE id=?",
                              (permission_id,)).fetchone()
        if row is None:
            return "permission_unknown"
        account, agent, expires_at, revoked = row
        if (account, agent) != (intent.account, intent.agent):
            return "identity_mismatch"
        if revoked:
            return "permission_revoked"
        if now >= expires_at:
            return "permission_expired"
        return None

    def reserve(self, key, permission_id, intent, *, now):
        if (not isinstance(intent, Intent) or not all(map(identifier,
                (key, permission_id, intent.account, intent.agent, intent.symbol)))
                or not positive_int(intent.quantity) or not positive_int(intent.limit_cents)
                or type(now) is not int or not 0 <= now <= 10**12):
            return "invalid_intent"
        payload = json.dumps([permission_id, intent.account, intent.agent, intent.symbol,
                              intent.quantity, intent.limit_cents], separators=(",", ":"))
        with self.transaction():
            existing = self.db.execute("SELECT payload,state FROM attempts WHERE id=?", (key,)).fetchone()
            if existing:
                if existing[0] != payload:
                    return "idempotency_conflict"
                # A repeat is an observation, never another dispatch permission.
                return "reconcile_required" if existing[1] in ("RESERVED", "UNKNOWN") else "already_recorded"
            error = self.permission_error(permission_id, intent, now)
            if error:
                return error
            self.db.execute("INSERT INTO attempts VALUES (?,?,?,?)", (key, permission_id, payload, "RESERVED"))
            self.event(key, "intent_reserved")
            return "reserved_for_simulation"

    def claim_dispatch(self, key, *, now):
        if not identifier(key) or type(now) is not int or not 0 <= now <= 10**12:
            return "invalid_intent"
        with self.transaction():
            row = self.db.execute("SELECT permission_id,payload,state FROM attempts WHERE id=?", (key,)).fetchone()
            if row is None:
                return "intent_unknown"
            permission_id, payload, state = row
            if state != "RESERVED":
                return "reconcile_required" if state == "UNKNOWN" else "already_recorded"
            fields = json.loads(payload)
            error = self.permission_error(permission_id, Intent(*fields[1:]), now)
            if error:
                self.db.execute("UPDATE attempts SET state='BLOCKED' WHERE id=?", (key,))
                self.event(key, error)
                return error
            # Persist uncertainty BEFORE a hypothetical external call. A crash
            # here can hold an unsent order, but cannot grant a blind second send.
            self.db.execute("UPDATE attempts SET state='UNKNOWN' WHERE id=?", (key,))
            self.event(key, "dispatch_claimed_for_simulation")
            return "dispatch_once_for_simulation"

    def record_outcome(self, key, outcome):
        if outcome not in ("ACKNOWLEDGED", "FILLED", "REJECTED"):
            raise ValueError("invalid outcome")
        with self.transaction():
            row = self.db.execute("SELECT state FROM attempts WHERE id=?", (key,)).fetchone()
            if row is None or (row[0] not in ("UNKNOWN", "ACKNOWLEDGED") and row[0] != outcome):
                raise ValueError("invalid outcome transition")
            if row[0] != outcome:
                self.db.execute("UPDATE attempts SET state=? WHERE id=?", (outcome, key))
                self.event(key, outcome)


def scenarios():
    rows = []
    def observed(name, value):
        rows.append({"scenario": name, "result": value})
    with TemporaryDirectory(prefix="galore-journal-") as directory:
        path = str(Path(directory) / "paper.sqlite")
        j = Journal(path)
        intent = Intent("paper-account", "example-agent", "EXAMPLE", 1, 10000)
        j.create_permission("p1", intent.account, intent.agent, 100)
        observed("first_intent", j.reserve("order-1", "p1", intent, now=10))
        observed("first_dispatch_claim", j.claim_dispatch("order-1", now=11))
        observed("retry_after_unknown_outcome", j.reserve("order-1", "p1", intent, now=12))
        observed("second_dispatch_claim", j.claim_dispatch("order-1", now=12))
        observed("same_key_changed_order", j.reserve("order-1", "p1", replace(intent, quantity=2), now=12))
        j.close()
        j = Journal(path)
        observed("retry_after_restart", j.reserve("order-1", "p1", intent, now=13))
        j.record_outcome("order-1", "ACKNOWLEDGED")
        observed("acknowledged_is_not_filled", j.db.execute("SELECT state FROM attempts WHERE id='order-1'").fetchone()[0])
        j.record_outcome("order-1", "FILLED")
        observed("retry_after_fill", j.reserve("order-1", "p1", intent, now=14))
        observed("wrong_agent", j.reserve("order-2", "p1", replace(intent, agent="other"), now=14))
        observed("invalid_quantity", j.reserve("order-2", "p1", replace(intent, quantity=True), now=14))
        j.revoke("p1")
        observed("new_order_after_revoke", j.reserve("order-2", "p1", intent, now=14))
        j.create_permission("p2", intent.account, intent.agent, 20)
        j.reserve("order-3", "p2", intent, now=19)
        j.revoke("p2")
        observed("revoke_between_reserve_and_dispatch", j.claim_dispatch("order-3", now=19))
        j.create_permission("p3", intent.account, intent.agent, 20)
        observed("expiry_boundary", j.reserve("order-4", "p3", intent, now=20))
        j.close()
    return {"example": "local SQLite retry journal", "broker_requests": 0,
            "dispatch_claims_for_simulation": 1, "results": rows}


if __name__ == "__main__":
    print(json.dumps(scenarios(), indent=2))

What it does not do

It trusts its caller and clock, and has no authentication, signatures, brokerage IDs, reservations, partial fills or live sending. Only the person, never the AI, should turn rules on or off. Never make a new ID just because a call timed out.

This is teaching code, not the Galore runtime. To check trades against rules a person approved, run Galore locally.

Check a trade before sending it · Compare approaches · Developer docs

Read this guide as Markdown · Combined developer reference

Reviewed 3 December 2026