第196回 再送データで在庫を直接更新しない:PythonとSQLiteで通常受信箱へ合流する

第195回では、再送要求と完全に一致した応答だけを受信ステージへ保存しました。今回は、受理済みの再送イベントを、通常配送で届いたイベントと同じ受信箱へ合流させます。

再送イベントから在庫を直接更新すると、通常経路と再送経路に別々の重複判定や順序制御が生まれます。再送であることは配送履歴として残し、イベントの同一性は通常受信と同じ規則で判定します。

ここで行うのは受信箱への引き渡しまでです。在庫数量の更新や連番の読み飛ばしは行いません。連番11、12、14を受信箱へ入れても、13が欠けていれば、第190回のような後段処理は14を保留できます。

配送経路とイベントの同一性を分ける

項目 用途 今回の扱い
event_id イベント自体の識別 受信経路に関係なく一意
skuとsequence 商品ごとの適用順 同じ組み合わせへ別のイベントIDを割り当てない
received_via 最初に受理した経路 liveまたはreplay
source_request_id 新規登録の起点になった再送要求 再送から新規登録した行だけに保存
replay_handoffs 再送バッチ単位の引き渡し履歴 新規登録と既存一致をイベントごとに記録

同じevent_idが受信箱に存在する場合は、商品、連番、JSONのバイト列、SHA-256がすべて一致したときだけ重複として扱います。キー順や空白だけが異なるJSONも別のバイト列なので競合です。署名やハッシュの対象を、後から別の正規化規則で解釈しないための判定です。

状態 結果 受信箱
未登録のイベント inserted 追加する
同じイベントID、同じ内容 duplicate 既存行を維持する
同じイベントID、異なる内容 event_id_conflict バッチ全体をロールバック
同じ商品・連番、別イベントID sequence_conflict バッチ全体をロールバック
unavailableのバッチ batch_not_accepted 変更しない
引き渡し済みバッチの再実行 already_promoted 保存済みの件数を返す

今回の実行契約

項目 仕様
動作環境 Python 3.11以上、標準ライブラリのみ
データベース 受信ステージ、通常受信箱、引き渡し履歴を同じSQLiteファイルへ置く
バッチ上限 1~1000イベント
ペイロード UTF-8のJSONオブジェクト、1件16KiB以下。重複キーとNaN・Infinityを拒否する
トランザクション BEGIN IMMEDIATEから検証、登録、履歴作成、完了記録までを実行
ロック待ち busy_timeoutを5000ミリ秒に設定し、解消しないロック競合は終了コード7にする
業務処理 在庫更新、連番適用、外部送信は行わない

別のSQLiteファイルや外部キューへ書き込む場合、このトランザクションでは原子性を保てません。その場合は、第187回で扱ったアウトボックスのように、同じデータベースへ配送予定を確定してから別処理で送ります。

デモ用スキーマを作る

次の内容をschema.sqlとして保存します。既存システムへそのまま適用する移行スクリプトではなく、今回の入出力を再現するための最小スキーマです。

PRAGMA foreign_keys = ON;

CREATE TABLE replay_batches (
    request_id TEXT PRIMARY KEY,
    status TEXT NOT NULL CHECK (status IN ('accepted', 'unavailable')),
    event_count INTEGER NOT NULL CHECK (event_count BETWEEN 0 AND 1000),
    accepted_at TEXT NOT NULL,
    promoted_at TEXT,
    inserted_count INTEGER,
    duplicate_count INTEGER,
    CHECK (
        (promoted_at IS NULL
         AND inserted_count IS NULL
         AND duplicate_count IS NULL)
        OR
        (promoted_at IS NOT NULL
         AND status = 'accepted'
         AND inserted_count IS NOT NULL
         AND duplicate_count IS NOT NULL
         AND inserted_count >= 0
         AND duplicate_count >= 0
         AND inserted_count + duplicate_count = event_count)
    )
);

CREATE TABLE replay_stage (
    request_id TEXT NOT NULL,
    position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 999),
    event_id TEXT NOT NULL CHECK (length(event_id) BETWEEN 1 AND 64),
    sku TEXT NOT NULL CHECK (length(sku) BETWEEN 1 AND 64),
    sequence INTEGER NOT NULL CHECK (sequence BETWEEN 1 AND 2147483647),
    payload_json BLOB NOT NULL
        CHECK (typeof(payload_json) = 'blob' AND length(payload_json) BETWEEN 2 AND 16384),
    payload_sha256 TEXT NOT NULL
        CHECK (length(payload_sha256) = 64
               AND payload_sha256 NOT GLOB '*[^0-9a-f]*'),
    PRIMARY KEY (request_id, position),
    UNIQUE (request_id, event_id),
    UNIQUE (request_id, position, event_id),
    FOREIGN KEY (request_id) REFERENCES replay_batches(request_id)
);

CREATE TABLE event_inbox (
    event_id TEXT PRIMARY KEY CHECK (length(event_id) BETWEEN 1 AND 64),
    sku TEXT NOT NULL CHECK (length(sku) BETWEEN 1 AND 64),
    sequence INTEGER NOT NULL CHECK (sequence BETWEEN 1 AND 2147483647),
    payload_json BLOB NOT NULL
        CHECK (typeof(payload_json) = 'blob' AND length(payload_json) BETWEEN 2 AND 16384),
    payload_sha256 TEXT NOT NULL
        CHECK (length(payload_sha256) = 64
               AND payload_sha256 NOT GLOB '*[^0-9a-f]*'),
    received_via TEXT NOT NULL CHECK (received_via IN ('live', 'replay')),
    source_request_id TEXT,
    imported_at TEXT NOT NULL,
    UNIQUE (sku, sequence),
    CHECK (
        (received_via = 'live' AND source_request_id IS NULL)
        OR
        (received_via = 'replay' AND source_request_id IS NOT NULL)
    ),
    FOREIGN KEY (source_request_id) REFERENCES replay_batches(request_id)
);

CREATE TABLE replay_handoffs (
    request_id TEXT NOT NULL,
    position INTEGER NOT NULL,
    event_id TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK (outcome IN ('inserted', 'duplicate')),
    handed_off_at TEXT NOT NULL,
    PRIMARY KEY (request_id, position),
    FOREIGN KEY (request_id, position, event_id)
        REFERENCES replay_stage(request_id, position, event_id),
    FOREIGN KEY (event_id) REFERENCES event_inbox(event_id)
);

replay_handoffsは、通常配送で先に登録済みだったイベントも含めて、再送バッチの各行をどう扱ったか残します。外部キーを有効にした接続では、対応するステージ行や受信箱行だけを削除する操作も拒否されます。

通常受信箱へ合流するCLI

次をpromote_replay.pyとして保存します。ペイロード内の業務項目は後段の責務とし、このCLIではevent_id、sku、sequenceがステージ列と一致することを確認します。

#!/usr/bin/env python3
from __future__ import annotations

import argparse
import hashlib
import json
import re
import sqlite3
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path

ID_RE = re.compile(r'[A-Za-z0-9][A-Za-z0-9._:-]{0,63}')
SKU_RE = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]{0,63}')
SHA_RE = re.compile(r'[0-9a-f]{64}')


@dataclass(frozen=True)
class Event:
    position: int
    event_id: str
    sku: str
    sequence: int
    payload: bytes
    payload_sha256: str


class PromotionError(Exception):
    def __init__(self, status: str, exit_code: int, **details: object) -> None:
        super().__init__(status)
        self.exit_code = exit_code
        self.result = {'status': status, **details}


def emit(value: dict[str, object]) -> None:
    sys.stdout.write(
        json.dumps(value, ensure_ascii=False, separators=(',', ':')) + '\n'
    )


def request_id_arg(value: str) -> str:
    if ID_RE.fullmatch(value) is None:
        raise argparse.ArgumentTypeError(
            'request_id must be 1-64 ASCII letters, digits, dot, underscore, colon or hyphen'
        )
    return value


def malformed(request_id: str, reason: str, **details: object) -> None:
    raise PromotionError(
        'malformed_batch',
        5,
        request_id=request_id,
        reason=reason,
        **details,
    )


def no_duplicate_keys(pairs: list[tuple[str, object]]) -> dict[str, object]:
    result: dict[str, object] = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate JSON key')
        result[key] = value
    return result


def reject_constant(value: str) -> None:
    raise ValueError(f'non-finite number: {value}')


def validate_event(row: sqlite3.Row, request_id: str) -> Event:
    position = row['position']
    event_id = row['event_id']
    sku = row['sku']
    sequence = row['sequence']
    raw = row['payload_json']
    digest = row['payload_sha256']

    if type(position) is not int or not 0 <= position < 1000:
        malformed(request_id, 'invalid_position')
    if not isinstance(event_id, str) or ID_RE.fullmatch(event_id) is None:
        malformed(request_id, 'invalid_event_id', position=position)
    if not isinstance(sku, str) or SKU_RE.fullmatch(sku) is None:
        malformed(request_id, 'invalid_sku', position=position)
    if type(sequence) is not int or not 1 <= sequence <= 2147483647:
        malformed(request_id, 'invalid_sequence', position=position)
    if not isinstance(raw, bytes) or not 2 <= len(raw) <= 16384:
        malformed(request_id, 'invalid_payload_blob', position=position)
    if not isinstance(digest, str) or SHA_RE.fullmatch(digest) is None:
        malformed(request_id, 'invalid_payload_sha256', position=position)
    if hashlib.sha256(raw).hexdigest() != digest:
        malformed(request_id, 'payload_sha256_mismatch', position=position)

    try:
        document = json.loads(
            raw.decode('utf-8'),
            object_pairs_hook=no_duplicate_keys,
            parse_constant=reject_constant,
        )
    except (UnicodeDecodeError, ValueError, RecursionError):
        malformed(request_id, 'payload_is_not_strict_utf8_json', position=position)

    if type(document) is not dict:
        malformed(request_id, 'payload_is_not_object', position=position)
    if document.get('event_id') != event_id:
        malformed(request_id, 'payload_event_id_mismatch', position=position)
    if document.get('sku') != sku:
        malformed(request_id, 'payload_sku_mismatch', position=position)
    if type(document.get('sequence')) is not int or document['sequence'] != sequence:
        malformed(request_id, 'payload_sequence_mismatch', position=position)

    return Event(position, event_id, sku, sequence, raw, digest)


def open_database(path: Path) -> sqlite3.Connection:
    if not path.is_file():
        raise PromotionError('database_not_found', 3, database=str(path))

    uri = path.resolve().as_uri() + '?mode=rw'
    connection = sqlite3.connect(
        uri,
        uri=True,
        timeout=5.0,
        isolation_level=None,
    )
    try:
        connection.row_factory = sqlite3.Row
        connection.execute('PRAGMA foreign_keys = ON')
        connection.execute('PRAGMA busy_timeout = 5000')
    except BaseException:
        connection.close()
        raise
    return connection


def same_event(row: sqlite3.Row, event: Event) -> bool:
    return (
        row['event_id'] == event.event_id
        and row['sku'] == event.sku
        and row['sequence'] == event.sequence
        and row['payload_json'] == event.payload
        and row['payload_sha256'] == event.payload_sha256
    )


def completed_result(
    connection: sqlite3.Connection,
    batch: sqlite3.Row,
    request_id: str,
    event_count: int,
) -> dict[str, object]:
    inserted = batch['inserted_count']
    duplicates = batch['duplicate_count']
    promoted_at = batch['promoted_at']

    if (
        type(inserted) is not int
        or type(duplicates) is not int
        or inserted < 0
        or duplicates < 0
        or inserted + duplicates != event_count
        or not isinstance(promoted_at, str)
        or not promoted_at
    ):
        malformed(request_id, 'invalid_completion_summary')

    stats = connection.execute(
        '''
        SELECT
            COUNT(*) AS total,
            COALESCE(SUM(CASE WHEN outcome = 'inserted' THEN 1 ELSE 0 END), 0)
                AS inserted,
            COALESCE(SUM(CASE WHEN outcome = 'duplicate' THEN 1 ELSE 0 END), 0)
                AS duplicates
        FROM replay_handoffs
        WHERE request_id = ?
        ''',
        (request_id,),
    ).fetchone()

    if (
        stats['total'] != event_count
        or stats['inserted'] != inserted
        or stats['duplicates'] != duplicates
    ):
        malformed(request_id, 'handoff_summary_mismatch')

    return {
        'status': 'already_promoted',
        'request_id': request_id,
        'inserted': inserted,
        'duplicates': duplicates,
    }


def promote(connection: sqlite3.Connection, request_id: str) -> dict[str, object]:
    connection.execute('BEGIN IMMEDIATE')
    try:
        batch = connection.execute(
            '''
            SELECT status, event_count, promoted_at, inserted_count, duplicate_count
            FROM replay_batches
            WHERE request_id = ?
            ''',
            (request_id,),
        ).fetchone()

        if batch is None:
            raise PromotionError('batch_not_found', 3, request_id=request_id)
        if not isinstance(batch['status'], str):
            malformed(request_id, 'invalid_batch_status')
        if batch['status'] != 'accepted':
            raise PromotionError(
                'batch_not_accepted',
                4,
                request_id=request_id,
                batch_status=batch['status'],
            )

        event_count = batch['event_count']
        if type(event_count) is not int or not 1 <= event_count <= 1000:
            malformed(request_id, 'invalid_event_count')

        if batch['promoted_at'] is not None:
            result = completed_result(connection, batch, request_id, event_count)
            connection.commit()
            return result

        rows = connection.execute(
            '''
            SELECT position, event_id, sku, sequence, payload_json, payload_sha256
            FROM replay_stage
            WHERE request_id = ?
            ORDER BY position
            ''',
            (request_id,),
        ).fetchall()

        if len(rows) != event_count:
            malformed(
                request_id,
                'stage_count_mismatch',
                expected=event_count,
                actual=len(rows),
            )

        events: list[Event] = []
        seen_ids: set[str] = set()
        seen_sequences: set[tuple[str, int]] = set()
        for expected_position, row in enumerate(rows):
            if row['position'] != expected_position:
                malformed(
                    request_id,
                    'stage_position_gap',
                    expected=expected_position,
                    actual=row['position'],
                )
            event = validate_event(row, request_id)
            if event.event_id in seen_ids:
                malformed(request_id, 'duplicate_event_id', event_id=event.event_id)
            sequence_key = (event.sku, event.sequence)
            if sequence_key in seen_sequences:
                malformed(
                    request_id,
                    'duplicate_sku_sequence',
                    sku=event.sku,
                    sequence=event.sequence,
                )
            seen_ids.add(event.event_id)
            seen_sequences.add(sequence_key)
            events.append(event)

        handed_off_at = datetime.now(timezone.utc).replace(microsecond=0).strftime(
            '%Y-%m-%dT%H:%M:%SZ'
        )
        inserted = 0
        duplicates = 0

        for event in events:
            existing = connection.execute(
                '''
                SELECT event_id, sku, sequence, payload_json, payload_sha256
                FROM event_inbox
                WHERE event_id = ?
                ''',
                (event.event_id,),
            ).fetchone()

            if existing is not None:
                if not same_event(existing, event):
                    raise PromotionError(
                        'event_id_conflict',
                        6,
                        request_id=request_id,
                        event_id=event.event_id,
                    )
                outcome = 'duplicate'
                duplicates += 1
            else:
                sequence_owner = connection.execute(
                    '''
                    SELECT event_id
                    FROM event_inbox
                    WHERE sku = ? AND sequence = ?
                    ''',
                    (event.sku, event.sequence),
                ).fetchone()
                if sequence_owner is not None:
                    raise PromotionError(
                        'sequence_conflict',
                        6,
                        request_id=request_id,
                        sku=event.sku,
                        sequence=event.sequence,
                        existing_event_id=sequence_owner['event_id'],
                    )

                try:
                    connection.execute(
                        '''
                        INSERT INTO event_inbox (
                            event_id, sku, sequence, payload_json, payload_sha256,
                            received_via, source_request_id, imported_at
                        ) VALUES (?, ?, ?, ?, ?, 'replay', ?, ?)
                        ''',
                        (
                            event.event_id,
                            event.sku,
                            event.sequence,
                            sqlite3.Binary(event.payload),
                            event.payload_sha256,
                            request_id,
                            handed_off_at,
                        ),
                    )
                except sqlite3.IntegrityError as error:
                    raise PromotionError(
                        'destination_constraint_conflict',
                        6,
                        request_id=request_id,
                        event_id=event.event_id,
                    ) from error
                outcome = 'inserted'
                inserted += 1

            try:
                connection.execute(
                    '''
                    INSERT INTO replay_handoffs (
                        request_id, position, event_id, outcome, handed_off_at
                    ) VALUES (?, ?, ?, ?, ?)
                    ''',
                    (
                        request_id,
                        event.position,
                        event.event_id,
                        outcome,
                        handed_off_at,
                    ),
                )
            except sqlite3.IntegrityError as error:
                raise PromotionError(
                    'destination_constraint_conflict',
                    6,
                    request_id=request_id,
                    event_id=event.event_id,
                ) from error

        cursor = connection.execute(
            '''
            UPDATE replay_batches
            SET promoted_at = ?, inserted_count = ?, duplicate_count = ?
            WHERE request_id = ? AND promoted_at IS NULL
            ''',
            (handed_off_at, inserted, duplicates, request_id),
        )
        if cursor.rowcount != 1:
            malformed(request_id, 'batch_state_changed')

        connection.commit()
        return {
            'status': 'promoted',
            'request_id': request_id,
            'inserted': inserted,
            'duplicates': duplicates,
        }
    except BaseException:
        if connection.in_transaction:
            connection.rollback()
        raise


def is_busy(error: sqlite3.Error) -> bool:
    code = getattr(error, 'sqlite_errorcode', None)
    if not isinstance(code, int):
        return False
    return code % 256 in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED)


def main() -> int:
    parser = argparse.ArgumentParser(
        description='Merge one accepted replay batch into the normal event inbox.'
    )
    parser.add_argument('database', type=Path)
    parser.add_argument('request_id', type=request_id_arg)
    args = parser.parse_args()

    try:
        connection = open_database(args.database)
        try:
            result = promote(connection, args.request_id)
        finally:
            connection.close()
    except PromotionError as error:
        emit(error.result)
        return error.exit_code
    except sqlite3.Error as error:
        if is_busy(error):
            emit({'status': 'database_busy', 'request_id': args.request_id})
            return 7
        emit({'status': 'database_error', 'request_id': args.request_id})
        return 8
    except OSError:
        emit({'status': 'database_error', 'request_id': args.request_id})
        return 8

    emit(result)
    return 0


if __name__ == '__main__':
    raise SystemExit(main())

再現用データを用意する

次をmake_demo.pyとして、ほかの2ファイルと同じディレクトリへ保存します。指定先がすでに存在する場合は上書きしません。

#!/usr/bin/env python3
from __future__ import annotations

import argparse
import hashlib
import json
import sqlite3
import sys
from pathlib import Path

REQUEST_ID = 'req-demo-001'
FIXED_TIME = '2026-11-25T00:00:00Z'


def emit(value: dict[str, object]) -> None:
    sys.stdout.write(
        json.dumps(value, ensure_ascii=False, separators=(',', ':')) + '\n'
    )


def encode_payload(event: dict[str, object]) -> bytes:
    return json.dumps(
        event,
        ensure_ascii=False,
        sort_keys=True,
        separators=(',', ':'),
    ).encode('utf-8')


def add_inbox(connection: sqlite3.Connection, event: dict[str, object]) -> None:
    raw = encode_payload(event)
    connection.execute(
        '''
        INSERT INTO event_inbox (
            event_id, sku, sequence, payload_json, payload_sha256,
            received_via, source_request_id, imported_at
        ) VALUES (?, ?, ?, ?, ?, 'live', NULL, ?)
        ''',
        (
            event['event_id'],
            event['sku'],
            event['sequence'],
            sqlite3.Binary(raw),
            hashlib.sha256(raw).hexdigest(),
            FIXED_TIME,
        ),
    )


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('database', type=Path)
    parser.add_argument('mode', choices=('good', 'conflict'))
    args = parser.parse_args()

    if args.database.exists():
        emit({'status': 'database_exists', 'database': str(args.database)})
        return 2

    schema_file = Path(__file__).with_name('schema.sql')
    try:
        schema = schema_file.read_text(encoding='utf-8')
    except OSError:
        emit({'status': 'schema_read_error', 'schema': str(schema_file)})
        return 8

    events = [
        {'event_id': 'evt-011', 'sku': 'SKU-001', 'sequence': 11, 'quantity': 24},
        {'event_id': 'evt-012', 'sku': 'SKU-001', 'sequence': 12, 'quantity': 30},
        {'event_id': 'evt-014', 'sku': 'SKU-001', 'sequence': 14, 'quantity': 35},
    ]

    connection: sqlite3.Connection | None = None
    try:
        connection = sqlite3.connect(args.database)
        connection.executescript(schema)
        connection.execute(
            '''
            INSERT INTO replay_batches (
                request_id, status, event_count, accepted_at
            ) VALUES (?, 'accepted', ?, ?)
            ''',
            (REQUEST_ID, len(events), FIXED_TIME),
        )

        for position, event in enumerate(events):
            raw = encode_payload(event)
            connection.execute(
                '''
                INSERT INTO replay_stage (
                    request_id, position, event_id, sku, sequence,
                    payload_json, payload_sha256
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
                ''',
                (
                    REQUEST_ID,
                    position,
                    event['event_id'],
                    event['sku'],
                    event['sequence'],
                    sqlite3.Binary(raw),
                    hashlib.sha256(raw).hexdigest(),
                ),
            )

        if args.mode == 'good':
            add_inbox(connection, events[0])
        else:
            add_inbox(
                connection,
                {
                    'event_id': 'evt-other-012',
                    'sku': 'SKU-001',
                    'sequence': 12,
                    'quantity': 999,
                },
            )

        connection.commit()
    except sqlite3.Error:
        if connection is not None and connection.in_transaction:
            connection.rollback()
        emit({'status': 'database_error', 'database': str(args.database)})
        return 8
    finally:
        if connection is not None:
            connection.close()

    emit(
        {
            'status': 'created',
            'database': str(args.database),
            'mode': args.mode,
            'request_id': REQUEST_ID,
        }
    )
    return 0


if __name__ == '__main__':
    raise SystemExit(main())

通常受信と再送を合流させる

最初にPythonのバージョンを確認し、2本のPythonファイルを構文チェックします。py_compileは成功時に何も出力しません。

python3 --version
python3 -m py_compile promote_replay.py make_demo.py

goodデータベースには、通常配送で受理済みの連番11と、再送ステージの11、12、14が入ります。

python3 make_demo.py good.db good
python3 promote_replay.py good.db req-demo-001
{"status":"created","database":"good.db","mode":"good","request_id":"req-demo-001"}
{"status":"promoted","request_id":"req-demo-001","inserted":2,"duplicates":1}

連番11は既存行と完全に一致するため重複です。12と14は新規登録されます。受信箱と引き渡し履歴を確認します。

python3 -c 'import json,sqlite3,sys; db=sqlite3.connect(sys.argv[1]); result={"inbox":db.execute("SELECT event_id,sequence FROM event_inbox ORDER BY sequence").fetchall(),"handoffs":db.execute("SELECT position,event_id,outcome FROM replay_handoffs ORDER BY position").fetchall()}; db.close(); print(json.dumps(result,separators=(",",":")))' good.db
{"inbox":[["evt-011",11],["evt-012",12],["evt-014",14]],"handoffs":[[0,"evt-011","duplicate"],[1,"evt-012","inserted"],[2,"evt-014","inserted"]]}

同じバッチを再実行しても、受信箱や履歴を追加せず、初回の件数を返します。

python3 promote_replay.py good.db req-demo-001
{"status":"already_promoted","request_id":"req-demo-001","inserted":2,"duplicates":1}

途中で競合したら全件を戻す

conflictデータベースには、同じ商品・連番12を持つ別イベントIDを先に登録します。CLIは連番11を一度追加した後で12の競合を検出しますが、トランザクション全体をロールバックします。

python3 make_demo.py conflict.db conflict
python3 promote_replay.py conflict.db req-demo-001
echo $?
{"status":"created","database":"conflict.db","mode":"conflict","request_id":"req-demo-001"}
{"status":"sequence_conflict","request_id":"req-demo-001","sku":"SKU-001","sequence":12,"existing_event_id":"evt-other-012"}
6

連番11と引き渡し履歴は残らず、バッチも未完了のままです。

python3 -c 'import json,sqlite3,sys; db=sqlite3.connect(sys.argv[1]); result={"inbox":db.execute("SELECT event_id,sequence FROM event_inbox ORDER BY sequence").fetchall(),"handoffs":db.execute("SELECT event_id FROM replay_handoffs").fetchall(),"promoted_at":db.execute("SELECT promoted_at FROM replay_batches WHERE request_id=?",("req-demo-001",)).fetchone()[0]}; db.close(); print(json.dumps(result,separators=(",",":")))' conflict.db
{"inbox":[["evt-other-012",12]],"handoffs":[],"promoted_at":null}

終了コードを運用判断へ使う

終了コード 状態 対応
0 promotedまたはalready_promoted 後段の通常処理へ任せる
2 コマンド引数が不正 引数を修正する
3 DBまたは要求IDが存在しない 対象の指定を確認する
4 受理済みバッチではない 受信結果を確認する
5 ステージ件数、位置、JSON、ハッシュなどが不整合 自動削除せず原因を調べる
6 イベントIDまたは商品連番が競合 内容が変わらない限り再実行しない
7 書き込みロックの競合 別の書き込み完了後に再試行する
8 そのほかのSQLiteまたはファイルエラー DB、権限、スキーマを点検する

SHA-256は、保存したバイト列と記録値の不一致を検出するために使っています。データベースを書き換えられる主体はペイロードとハッシュの両方を変更できるため、署名やアクセス制御の代わりにはなりません。

また、このスキーマは受信箱の行を保持して重複を判定します。処理済み行を削除する運用では、event_idと商品連番を保持する別の永続台帳が必要です。ステージ、引き渡し履歴、受信箱の保存期間も、監査要件に合わせて別途決めます。

確認に使った一次資料

次に行うこと

  1. 通常配送の受信処理も、同じevent_inboxの一意制約と内容照合を使う。
  2. 後段処理は配送経路を条件にせず、商品別連番に従って受信箱を処理する。
  3. 連番13が届いた場合は、適用済み連番の次から、13、14のように途切れず並ぶ範囲だけを一つのトランザクションで進める。

再送は、欠けたイベントを通常経路へ戻す手段に限定します。再送専用の在庫更新ロジックは持ちません。