Python sqlite3 最大余数法:精确整数配额、原子落库与幂等回执

10-19 4阅读

把一批不可拆分的测试令牌按权重分给多个测试组,看起来只需要做一次除法。真正落地时,难点通常出现在边角:整数舍入后总量对不上,余数相同导致结果受输入顺序影响,某个权重为零,数据库写了一半,或者客户端超时后又把同一批请求发来一次。

本文使用 Python 标准库 sqlite3,实现一条完整路径:以最大余数法计算精确整数配额,明确输入边界,把整个批次原子落库,并为重试返回一致回执。场景始终是有限测试令牌的离线分配,不涉及真实支付、投资或金融业务。与逐个请求选择下一节点的轮询不同,这里一次性决定整批总量的比例结果,不维护轮询游标。

Python sqlite3 最大余数法:精确整数配额、原子落库与幂等回执
AI 生成的概念配图:分流托盘与数据库表示配额计算和整批保存;画面中的令牌数量不代表实际计算结果。

下面九段 Python 代码均可单独保存为文件运行,不依赖上一段的变量。实测环境为 Python 3.12.14、SQLite 3.53.1;验证命令为 python -X dev -W error 文件名.py。数据库连接均显式关闭,只使用标准库。文中的英文输出保留原样,便于复制后逐项比对。

一、先算整数底座,再决定剩余令牌给谁

设总令牌数为 T,接收方权重为 w,总权重为 W。每一方的理想配额是 T×w÷W。先用整除获得底座,再把没有分完的整数单位依次交给小数部分最大的接收方。由于所有人的分母相同,直接比较整数余数即可,不必生成任何浮点数。这就是本文采用的最大余数法;其先取整数部分、再比较余数的结构可参阅美国人口普查局对 Hamilton/Vinton 方法的说明。本文仅借用分配算法,不讨论选举或财务决策。

例如把 11 个测试令牌按 5、3、2 的权重分给三个测试组。底座之和是 10,剩下一个单位;余数最大的 alpha 获得它,最终为 6、3、2。关键不是单独对每个配额四舍五入,而是始终把总量作为必须满足的不变量。下面同时打印底座、余数和最终结果,便于人工核对。

total = 11
weights = [('alpha', 5), ('beta', 3), ('gamma', 2)]
weight_sum = sum(weight for _, weight in weights)
rows = []
for name, weight in weights:
    base, remainder = divmod(total * weight, weight_sum)
    rows.append((name, base, remainder))
left = total - sum(base for _, base, _ in rows)
ranked = sorted(rows, key=lambda row: (-row[2], row[0]))
winners = {name for name, _, _ in ranked[:left]}
result = [(name, base + int(name in winners))
          for name, base, _ in rows]
print('base_and_remainder:', rows)
print('left:', left)
print('result:', result)
assert sum(amount for _, amount in result) == total

运行输出:

base_and_remainder: [('alpha', 5, 5), ('beta', 3, 3), ('gamma', 2, 2)]
left: 1
result: [('alpha', 6), ('beta', 3), ('gamma', 2)]

还可以直接证明剩余单位的数量小于接收方数量:各余数都小于 W,而余数之和恰好等于剩余单位数乘以 W。因此每个人最多补一个单位,排序一次即可;不需要按令牌总量循环发放。对于固定宽度输入,主要排序成本随接收方数量增长,时间复杂度通常记为 O(n log n),空间为 O(n)。

二、把输入契约写进可复用的纯函数

算法之前先定义接口。本文要求总量和权重都是非负的原生整数,明确拒绝布尔值;接收方标识使用有限长度的小写 ASCII 标识,且不能重复。输入必须是非空的列表或元组,最多一万个接收方。这些限制让错误尽早出现,也避免大小写、语言排序和输入顺序悄悄改变决胜结果。重复标识必须报错,不能先转字典再让后一个值覆盖前一个值。

为了与后续 INTEGER 字段一致,总量、单个权重以及权重之和都限制在有符号 64 位非负范围内。Python 的整数可以精确承载更大的中间乘积,所以 T×w 在 Python 中计算,再把整除后的结果落库。不要把乘法搬进 SQLite 后假设仍有任意精度。对应的边界来自SQLite 64 位整数定义,而 Python 的整数精度说明见内置数值类型文档。

返回值的每一行依次为标识、权重、底座、余数和最终数量。保留中间字段有助于事后解释某个组为什么多拿一个令牌。这里返回不可变的元组快照;调用方更改原始列表不会改变已经算出的结果。

import re

MAX_INT = (1 << 63) - 1


def allocate(total, items):
    if type(total) is not int or not 0 <= total <= MAX_INT:
        raise ValueError('invalid total')
    if not isinstance(items, (list, tuple)) or not 1 <= len(items) <= 10000:
        raise ValueError('invalid recipient count')
    weights = {}
    for item in items:
        if not isinstance(item, (list, tuple)) or len(item) != 2:
            raise ValueError('invalid pair')
        name, weight = item
        if (type(name) is not str
                or re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', name) is None):
            raise ValueError('invalid recipient')
        if name in weights:
            raise ValueError('duplicate recipient')
        if type(weight) is not int or not 0 <= weight <= MAX_INT:
            raise ValueError('invalid weight')
        weights[name] = weight
    weight_sum = sum(weights.values())
    if weight_sum > MAX_INT:
        raise ValueError('weight sum overflow')
    if weight_sum == 0:
        if total != 0:
            raise ValueError('positive total needs positive weight')
        return tuple((name, 0, 0, 0, 0) for name in sorted(weights))
    rows = []
    for name, weight in sorted(weights.items()):
        base, remainder = divmod(total * weight, weight_sum)
        rows.append((name, weight, base, remainder))
    left = total - sum(row[2] for row in rows)
    order = sorted(rows, key=lambda row: (-row[3], row[0]))
    winners = {row[0] for row in order[:left]}
    return tuple((*row, row[2] + int(row[0] in winners)) for row in rows)

rows = allocate(11, [('gamma', 2), ('alpha', 5), ('beta', 3)])
print([(row[0], row[4]) for row in rows])
print('total:', sum(row[4] for row in rows))

运行输出:

[('alpha', 6), ('beta', 3), ('gamma', 2)]
total: 11

三、同余数时用稳定标识决胜

权重相同或比例巧合时,余数可能相等。只按余数排序仍不够,因为稳定排序会保留原始输入顺序,而输入可能来自不同的查询计划、集合或请求序列。本文把完整排序键固定为余数降序、标识升序;输出顺序也单独固定为标识升序。这样同一组参数无论如何排列,回执都能保持一致。

下面枚举三个接收方的六种排列。这个短函数只服务于示例中已经校验的固定输入;真实入口应使用上一节的完整校验函数。不要把教学用的简化函数直接替换到数据库写入接口里。

from itertools import permutations

def split(total, items):
    # This teaching helper accepts only the validated inputs below.
    weights = dict(items)
    denominator = sum(weights.values())
    if denominator == 0:
        return {name: 0 for name in sorted(weights)}
    parts = {name: divmod(total * weight, denominator)
             for name, weight in weights.items()}
    left = total - sum(base for base, _ in parts.values())
    ranked = sorted(parts, key=lambda name: (-parts[name][1], name))
    winners = set(ranked[:left])
    return {name: parts[name][0] + int(name in winners)
            for name in sorted(parts)}

items = [('gamma', 1), ('alpha', 1), ('beta', 1)]
results = {tuple(split(2, list(order)).items())
           for order in permutations(items)}
assert len(results) == 1
print(dict(next(iter(results))))
print('permutations:', len(list(permutations(items))))

运行输出:

{'alpha': 1, 'beta': 1, 'gamma': 0}
permutations: 6

固定决胜顺序解决的是可复现性,并不承诺跨批次的长期公平。若每批都恰好出现相同平局,较小标识会反复优先。需要跨批次轮换时,要另外设计持久化状态、版本化规则和审计口径;不能在这里偷偷加入随机数或沿用上批游标,否则相同请求不再自然对应相同结果。

四、零权重与溢出要有明确答案

零权重接收方保留在输出中,数量为零。只要总权重大于零,零权重的底座和余数都为零,不会抢走余量:如果还有单位可补,正余数的数量一定足够。所有权重都为零时,本文只接受总量也为零的请求;正总量没有可定义的比例,应返回错误,而不是随手平均分配。

总量为零也不能绕过校验。例如负权重、重复标识、溢出的权重之和仍然有问题,即使最后每个人都会拿到零。下面再次完整给出函数,保证这一段单独保存即可运行。最后一个大整数断言还验证了中间乘积超出数据库整数范围时,Python 侧计算仍然精确。

import re

MAX_INT = (1 << 63) - 1


def allocate(total, items):
    if type(total) is not int or not 0 <= total <= MAX_INT:
        raise ValueError('invalid total')
    if not isinstance(items, (list, tuple)) or not 1 <= len(items) <= 10000:
        raise ValueError('invalid recipient count')
    weights = {}
    for item in items:
        if not isinstance(item, (list, tuple)) or len(item) != 2:
            raise ValueError('invalid pair')
        name, weight = item
        if (type(name) is not str
                or re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', name) is None):
            raise ValueError('invalid recipient')
        if name in weights:
            raise ValueError('duplicate recipient')
        if type(weight) is not int or not 0 <= weight <= MAX_INT:
            raise ValueError('invalid weight')
        weights[name] = weight
    weight_sum = sum(weights.values())
    if weight_sum > MAX_INT:
        raise ValueError('weight sum overflow')
    if weight_sum == 0:
        if total != 0:
            raise ValueError('positive total needs positive weight')
        return tuple((name, 0, 0, 0, 0) for name in sorted(weights))
    rows = []
    for name, weight in sorted(weights.items()):
        base, remainder = divmod(total * weight, weight_sum)
        rows.append((name, weight, base, remainder))
    left = total - sum(row[2] for row in rows)
    order = sorted(rows, key=lambda row: (-row[3], row[0]))
    winners = {row[0] for row in order[:left]}
    return tuple((*row, row[2] + int(row[0] in winners)) for row in rows)

print('mixed_zero:', [(r[0], r[4]) for r in
                       allocate(7, [('alpha', 0), ('beta', 2)])])
print('all_zero:', [(r[0], r[4]) for r in
                     allocate(0, [('alpha', 0), ('beta', 0)])])
cases = [
    (-1, [('alpha', 1)]),
    (True, [('alpha', 1)]),
    (1, [('alpha', -1)]),
    (1, [('alpha', True)]),
    (1, [('alpha', 1), ('alpha', 2)]),
    (MAX_INT + 1, [('alpha', 1)]),
    (0, [('alpha', MAX_INT), ('beta', 1)]),
    (1, [('alpha', 0)]),
    (0, []),
    (1, [('Alpha', 1)]),
]
rejected = 0
for total, items in cases:
    try:
        allocate(total, items)
    except ValueError:
        rejected += 1
    else:
        raise AssertionError('invalid request accepted')
large = allocate(MAX_INT, [('alpha', MAX_INT)])
assert large[0][4] == MAX_INT
print('rejected:', rejected)
print('large_exact:', large[0][4])

运行输出:

mixed_zero: [('alpha', 0), ('beta', 7)]
all_zero: [('alpha', 0), ('beta', 0)]
rejected: 10
large_exact: 9223372036854775807

五、十进制权重先从字符串变成整数比例

如果配置来源写的是 0.1、0.2、0.7,不要先转成 float 再去补救。可以把受限格式的十进制字符串交给 Fraction,求分母的最小公倍数,再约去整数权重的最大公约数。整数比例 1、2、7 与原始十进制权重表达的是同一个分配关系;计算核心因此仍然只需要整数。

下面只接收一至六位整数部分、可选一至六位小数部分,不支持负号、指数形式、无穷大或其他特殊记法。这是有意设定的输入协议,避免无限精度变成无限资源消耗。Fraction 官方文档也区分了从十进制字符串构造与从已舍入的浮点数构造。示例固定三个接收方,所得整数权重很小;动态接入时还要交给完整 allocate 函数检查总权重范围。

from fractions import Fraction
from functools import reduce
from math import gcd, lcm
import re

def split(total, items):
    # This teaching helper accepts only the validated inputs below.
    weights = dict(items)
    denominator = sum(weights.values())
    if denominator == 0:
        return {name: 0 for name in sorted(weights)}
    parts = {name: divmod(total * weight, denominator)
             for name, weight in weights.items()}
    left = total - sum(base for base, _ in parts.values())
    ranked = sorted(parts, key=lambda name: (-parts[name][1], name))
    winners = set(ranked[:left])
    return {name: parts[name][0] + int(name in winners)
            for name in sorted(parts)}

raw = [('alpha', '0.1'), ('beta', '0.2'), ('gamma', '0.7')]
fractions = []
for name, text in raw:
    if (type(text) is not str
            or re.fullmatch(r'[0-9]{1,6}(?:\.[0-9]{1,6})?', text) is None):
        raise ValueError('invalid decimal weight')
    fractions.append((name, Fraction(text)))
scale = lcm(*(value.denominator for _, value in fractions))
integers = [(name, value.numerator * (scale // value.denominator))
            for name, value in fractions]
divisor = reduce(gcd, (weight for _, weight in integers)) or 1
weights = [(name, weight // divisor) for name, weight in integers]
print('integer_weights:', weights)
print('allocation:', split(13, weights))

运行输出:

integer_weights: [('alpha', 1), ('beta', 2), ('gamma', 7)]
allocation: {'alpha': 1, 'beta': 3, 'gamma': 9}

需要同时保留原始配置以供审计时,应把原始文本和规范化整数权重作为不同字段。本文的重试协议比较规范化后的整数请求,且只规范化接收方顺序,不自动约分已有的整数权重。因此整数输入 1、2 与 2、4 虽然产生同样配额,仍被视为不同请求。这是明确的身份规则,不能等到发生重试冲突时才临时决定。

六、先证明失败不会留下半个批次

只把正确的数量算出来还不够。若先写批次头,再逐行写分配明细,中途失败可能留下看似存在、实际缺行的批次。下面把批次头和全部明细放进一个显式事务,用非法的负数量模拟写入失败,再查询两张表都为空。随后提交完整批次,验证总数为 11。

所有数据库示例要求 Python 3.12 或更高版本,连接显式使用 autocommit=True,再通过 SQL 的 BEGIN IMMEDIATE、COMMIT 和 ROLLBACK 管理事务。这个模式下不能把 SQL 提交替换成连接的 commit 方法,因为后者不执行提交。连接关闭也不等于提交。相关行为见Python sqlite3 事务控制文档。建表脚本在业务事务开始前执行,避免把模式初始化混入业务写入流程。

import sqlite3

con = sqlite3.connect(':memory:', autocommit=True)
try:
    con.execute('PRAGMA foreign_keys = ON')
    assert con.execute('PRAGMA foreign_keys').fetchone()[0] == 1
    con.executescript("""
        CREATE TABLE batch (id TEXT PRIMARY KEY NOT NULL);
        CREATE TABLE item (
            batch_id TEXT NOT NULL REFERENCES batch(id),
            name TEXT NOT NULL,
            amount INTEGER NOT NULL
                CHECK(typeof(amount) = 'integer' AND amount >= 0),
            PRIMARY KEY (batch_id, name)
        );
    """)
    con.execute('BEGIN IMMEDIATE')
    try:
        con.execute('INSERT INTO batch VALUES (?)', ('demo',))
        con.executemany('INSERT INTO item VALUES (?, ?, ?)',
                        [('demo', 'alpha', 6), ('demo', 'beta', -1)])
        con.execute('COMMIT')
    except sqlite3.IntegrityError:
        if con.in_transaction:
            con.execute('ROLLBACK')
    print('after_failure:', con.execute(
        'SELECT (SELECT COUNT(*) FROM batch), '
        '(SELECT COUNT(*) FROM item)').fetchone())
    con.execute('BEGIN IMMEDIATE')
    try:
        con.execute('INSERT INTO batch VALUES (?)', ('demo',))
        con.executemany('INSERT INTO item VALUES (?, ?, ?)',
                        [('demo', 'alpha', 6), ('demo', 'beta', 3),
                         ('demo', 'gamma', 2)])
        con.execute('COMMIT')
    except BaseException:
        if con.in_transaction:
            con.execute('ROLLBACK')
        raise
    print('committed_total:', con.execute(
        'SELECT SUM(amount) FROM item').fetchone()[0])
finally:
    con.close()

运行输出:

after_failure: (0, 0)
committed_total: 11

这里的 CHECK 是第二道防线,不能替代应用层的完整请求校验;普通 SQLite 表具有类型亲和性,声明 INTEGER 并不等同于强制所有输入原本都是 Python 整数。示例显式检查存储值的类型,应用端则更早拒绝不符合协议的值。外键也必须在每个新连接上启用并核验,参见SQLite 外键启用说明与类型系统文档。

七、同一批次重试必须返回原来的回执

客户端超时并不能证明数据库没有提交。一次分配可能已经落库,只是回执尚未传回。如果重试时换一个批次号,就可能生成第二份分配。正确做法是由调用方为一次逻辑请求选择稳定批次号,并在重试时原样使用;服务端在同一个事务内检查该编号、核对请求内容、写入全部明细和回执。

下面的实现存储完整的规范化请求,而不是只存一个摘要,避免把摘要相等当成请求相等。算法版本也是请求的一部分。已有批次内容一致时返回数据库中保存的原始回执文本;同一编号搭配不同总量、权重或算法版本时直接拒绝。先计算纯函数结果,再获取写锁,可以减少持锁时间。每次读写均使用参数占位符,SQL 结构不拼接业务输入。

完整示例会关闭第一次连接,再打开同一个临时数据库,以模拟第一次响应丢失后的重试。临时目录只用于演示,程序结束后文件会被删除;真实服务应换成受管理的持久数据库路径,并保留批次和回执至少覆盖允许的重试窗口。

import re

MAX_INT = (1 << 63) - 1


def allocate(total, items):
    if type(total) is not int or not 0 <= total <= MAX_INT:
        raise ValueError('invalid total')
    if not isinstance(items, (list, tuple)) or not 1 <= len(items) <= 10000:
        raise ValueError('invalid recipient count')
    weights = {}
    for item in items:
        if not isinstance(item, (list, tuple)) or len(item) != 2:
            raise ValueError('invalid pair')
        name, weight = item
        if (type(name) is not str
                or re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', name) is None):
            raise ValueError('invalid recipient')
        if name in weights:
            raise ValueError('duplicate recipient')
        if type(weight) is not int or not 0 <= weight <= MAX_INT:
            raise ValueError('invalid weight')
        weights[name] = weight
    weight_sum = sum(weights.values())
    if weight_sum > MAX_INT:
        raise ValueError('weight sum overflow')
    if weight_sum == 0:
        if total != 0:
            raise ValueError('positive total needs positive weight')
        return tuple((name, 0, 0, 0, 0) for name in sorted(weights))
    rows = []
    for name, weight in sorted(weights.items()):
        base, remainder = divmod(total * weight, weight_sum)
        rows.append((name, weight, base, remainder))
    left = total - sum(row[2] for row in rows)
    order = sorted(rows, key=lambda row: (-row[3], row[0]))
    winners = {row[0] for row in order[:left]}
    return tuple((*row, row[2] + int(row[0] in winners)) for row in rows)

import json
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory


SCHEMA = """
CREATE TABLE batch (
    batch_id TEXT PRIMARY KEY NOT NULL,
    request TEXT NOT NULL,
    receipt TEXT NOT NULL,
    total INTEGER NOT NULL
        CHECK(typeof(total) = 'integer' AND total >= 0)
);
CREATE TABLE allocation (
    batch_id TEXT NOT NULL REFERENCES batch(batch_id),
    recipient TEXT NOT NULL,
    weight INTEGER NOT NULL CHECK(typeof(weight) = 'integer' AND weight >= 0),
    base INTEGER NOT NULL CHECK(typeof(base) = 'integer' AND base >= 0),
    remainder INTEGER NOT NULL
        CHECK(typeof(remainder) = 'integer' AND remainder >= 0),
    amount INTEGER NOT NULL CHECK(typeof(amount) = 'integer' AND amount >= 0),
    PRIMARY KEY (batch_id, recipient),
    CHECK(amount >= base AND amount - base <= 1)
);
"""


def encode(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'))


def persist(con, batch_id, total, items):
    if (type(batch_id) is not str
            or re.fullmatch(r'[a-z][a-z0-9_-]{0,63}', batch_id) is None):
        raise ValueError('invalid batch id')
    rows = allocate(total, items)
    request = encode({'algorithm': 'lr-v1', 'total': total,
                      'weights': [[r[0], r[1]] for r in rows]})
    receipt = encode({'algorithm': 'lr-v1', 'batch_id': batch_id,
                      'total': total,
                      'units': [[r[0], r[4]] for r in rows]})
    if con.in_transaction:
        raise RuntimeError('dedicated idle connection required')
    con.execute('BEGIN IMMEDIATE')
    try:
        old = con.execute(
            'SELECT request, receipt FROM batch WHERE batch_id = ?',
            (batch_id,)).fetchone()
        if old is not None:
            if old[0] != request:
                raise ValueError('batch id reused with different request')
            con.execute('COMMIT')
            return old[1]
        con.execute('INSERT INTO batch VALUES (?, ?, ?, ?)',
                    (batch_id, request, receipt, total))
        con.executemany('INSERT INTO allocation VALUES (?, ?, ?, ?, ?, ?)',
                        [(batch_id, *row) for row in rows])
        check = con.execute(
            'SELECT COUNT(*), SUM(amount) FROM allocation WHERE batch_id = ?',
            (batch_id,)).fetchone()
        if check != (len(rows), total):
            raise RuntimeError('allocation invariant failed')
        con.execute('COMMIT')
        return receipt
    except BaseException:
        if con.in_transaction:
            con.execute('ROLLBACK')
        raise

with TemporaryDirectory() as folder:
    path = Path(folder) / 'allocation.db'
    con = sqlite3.connect(path, autocommit=True)
    try:
        con.execute('PRAGMA foreign_keys = ON')
        assert con.execute('PRAGMA foreign_keys').fetchone()[0] == 1
        con.executescript(SCHEMA)
        first = persist(con, 'test-001', 11,
                        [('alpha', 5), ('beta', 3), ('gamma', 2)])
    finally:
        con.close()
    con = sqlite3.connect(path, autocommit=True)
    try:
        con.execute('PRAGMA foreign_keys = ON')
        assert con.execute('PRAGMA foreign_keys').fetchone()[0] == 1
        again = persist(con, 'test-001', 11,
                        [('gamma', 2), ('beta', 3), ('alpha', 5)])
        assert first == again
        print('same_receipt:', first == again)
        print(again)
        try:
            persist(con, 'test-001', 12,
                    [('alpha', 5), ('beta', 3), ('gamma', 2)])
        except ValueError as error:
            print('conflict:', str(error))
        print('rows:', con.execute(
            'SELECT (SELECT COUNT(*) FROM batch), '
            '(SELECT COUNT(*) FROM allocation)').fetchone())
    finally:
        con.close()

运行输出:

same_receipt: True
{"algorithm":"lr-v1","batch_id":"test-001","total":11,"units":[["alpha",6],["beta",3],["gamma",2]]}
conflict: batch id reused with different request
rows: (1, 3)

查询批次与写入新批次必须处于同一个写事务。BEGIN IMMEDIATE 会先尝试取得写事务资格,另一个写者不能在当前事务检查与插入之间抢先提交同编号批次。复合主键和批次主键仍然保留,作为数据约束,而不是仅靠应用约定。表内的行数和总量检查只核对本批次;不要用跨所有批次的 SUM 当作无界审计累计值,否则其整数聚合也可能溢出。

事务原子性保证这个数据库中的头、明细和回执一起成功或回滚,不等于令牌已经被远端执行器消费。若之后还要发送任务,必须另行设计可恢复投递与消费去重。数据库损坏、人工改表、删除回执、备份恢复丢失新数据也不在此简化实现的重试保证范围内;生产系统要限制写入入口,并制定备份与保留策略。

八、遇到写锁时重试整个事务

BEGIN IMMEDIATE 不是无条件成功的承诺。SQLite 允许多个读事务,但同一时刻只有一个写事务;无法取得写锁时可能返回 SQLITE_BUSY,相关语义见SQLite 事务文档。不能看到数据库异常就把所有错误都重试,更不能只重试最后一条 INSERT,让先前的语句留在不确定状态。

下面用两个真实文件连接制造确定性的锁竞争。第一个连接写入尚未提交的回执,第二个连接的第一次尝试必然遇到忙状态;演示程序随后让第一个连接提交,第二次尝试便读取已经保存的相同回执。为了把重点放在锁和回执上,此处只使用简化回执表,输入已经固定;完整分配仍使用上一节的实现。这里没有线程调度时序或依赖运气的等待。

import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory


def request_once(con, batch_id, request, receipt):
    if con.in_transaction:
        raise RuntimeError('idle connection required')
    con.execute('BEGIN IMMEDIATE')
    try:
        old = con.execute('SELECT request, receipt FROM receipt WHERE id = ?',
                          (batch_id,)).fetchone()
        if old is None:
            con.execute('INSERT INTO receipt VALUES (?, ?, ?)',
                        (batch_id, request, receipt))
            result = receipt
        else:
            if old[0] != request:
                raise ValueError('request conflict')
            result = old[1]
        con.execute('COMMIT')
        return result
    except BaseException:
        if con.in_transaction:
            con.execute('ROLLBACK')
        raise


with TemporaryDirectory() as folder:
    path = Path(folder) / 'busy.db'
    holder = sqlite3.connect(path, autocommit=True, timeout=0)
    client = sqlite3.connect(path, autocommit=True, timeout=0)
    try:
        holder.execute('CREATE TABLE receipt ('
                       'id TEXT PRIMARY KEY NOT NULL, '
                       'request TEXT NOT NULL, receipt TEXT NOT NULL)')
        holder.execute('BEGIN IMMEDIATE')
        holder.execute('INSERT INTO receipt VALUES (?, ?, ?)',
                       ('batch-a', 'total=2;alpha=1;beta=1', 'alpha=1;beta=1'))
        busy_count = 0
        for attempt in range(2):
            try:
                result = request_once(client, 'batch-a',
                                      'total=2;alpha=1;beta=1', 'unused')
                break
            except sqlite3.OperationalError as error:
                code = getattr(error, 'sqlite_errorcode', -1)
                if (code & 255) != sqlite3.SQLITE_BUSY:
                    raise
                busy_count += 1
                # Test fixture: allow the competing writer to finish.
                holder.execute('COMMIT')
        else:
            raise RuntimeError('retry budget exhausted')
        assert result == 'alpha=1;beta=1'
        print('busy_count:', busy_count)
        print('receipt:', result)
        print('stored_batches:', client.execute(
            'SELECT COUNT(*) FROM receipt').fetchone()[0])
    finally:
        client.close()
        holder.close()

运行输出:

busy_count: 1
receipt: alpha=1;beta=1
stored_batches: 1

生产重试应带总截止时间、有限退避和必要的抖动,并沿用相同批次号与请求快照。这里只为可重复测试手动释放竞争连接,不是让业务代码替其他连接提交事务。写锁长期不释放时应报出可观测的失败,不要无限循环。处理异常后如果本连接仍在事务中,应先回滚自身事务;若连回滚也失败,丢弃连接并查明原因,不要继续拿它处理新请求。

九、用性质测试覆盖总量、配额与边界

测试不仅应断言几个固定输出,还要验证广泛成立的性质:分配总和等于输入总量,每个数量非负,零权重始终为零,每个人得到理想配额的向下取整或向上取整,输入排列不会改变结果。下面用固定随机种子生成五百组样本,并用 Fraction 计算精确理想配额,避免测试本身引入浮点误差。核心函数再次完整给出,所以这一段也不依赖前文的文件或运行状态。

最后还展示一个容易忽略的边界:权重为 1、3、3 时,总量从 3 增加到 4,alpha 的数量会从 1 降为 0。最大余数法满足本批次的配额边界,但不保证总量增加时每个接收方的份额都不下降。算法选择必须符合业务语义;若测试组已经消耗了前一批配额,不能用新的整批结果直接覆盖旧的已执行事实。

import re

MAX_INT = (1 << 63) - 1


def allocate(total, items):
    if type(total) is not int or not 0 <= total <= MAX_INT:
        raise ValueError('invalid total')
    if not isinstance(items, (list, tuple)) or not 1 <= len(items) <= 10000:
        raise ValueError('invalid recipient count')
    weights = {}
    for item in items:
        if not isinstance(item, (list, tuple)) or len(item) != 2:
            raise ValueError('invalid pair')
        name, weight = item
        if (type(name) is not str
                or re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', name) is None):
            raise ValueError('invalid recipient')
        if name in weights:
            raise ValueError('duplicate recipient')
        if type(weight) is not int or not 0 <= weight <= MAX_INT:
            raise ValueError('invalid weight')
        weights[name] = weight
    weight_sum = sum(weights.values())
    if weight_sum > MAX_INT:
        raise ValueError('weight sum overflow')
    if weight_sum == 0:
        if total != 0:
            raise ValueError('positive total needs positive weight')
        return tuple((name, 0, 0, 0, 0) for name in sorted(weights))
    rows = []
    for name, weight in sorted(weights.items()):
        base, remainder = divmod(total * weight, weight_sum)
        rows.append((name, weight, base, remainder))
    left = total - sum(row[2] for row in rows)
    order = sorted(rows, key=lambda row: (-row[3], row[0]))
    winners = {row[0] for row in order[:left]}
    return tuple((*row, row[2] + int(row[0] in winners)) for row in rows)

from fractions import Fraction
from random import Random

rng = Random(20261018)
for _ in range(500):
    count = rng.randint(1, 12)
    items = [(f'group{i:02d}', rng.randint(0, 50)) for i in range(count)]
    if not any(weight for _, weight in items):
        items[0] = (items[0][0], 1)
    total = rng.randint(0, 1000)
    rows = allocate(total, items)
    denominator = sum(weight for _, weight in items)
    assert sum(row[4] for row in rows) == total
    for name, weight, base, remainder, amount in rows:
        ideal = Fraction(total * weight, denominator)
        floor = ideal.numerator // ideal.denominator
        ceiling = -(-ideal.numerator // ideal.denominator)
        assert amount in {floor, ceiling}
        assert amount >= 0
        assert weight != 0 or amount == 0
        assert base * denominator + remainder == total * weight
    shuffled = items[:]
    rng.shuffle(shuffled)
    assert allocate(total, shuffled) == rows
print('property_cases:', 500)
weights = [('alpha', 1), ('beta', 3), ('gamma', 3)]
print('total_3:', [(r[0], r[4]) for r in allocate(3, weights)])
print('total_4:', [(r[0], r[4]) for r in allocate(4, weights)])

运行输出:

property_cases: 500
total_3: [('alpha', 1), ('beta', 1), ('gamma', 1)]
total_4: [('alpha', 0), ('beta', 2), ('gamma', 2)]

还应针对数据库层补充进程崩溃、磁盘空间不足、长事务竞争、重复请求风暴和备份恢复测试。本文展示的断言是可执行的基础验证,并不替代服务的容量规划与故障演练。尤其是回执已经成功保存但客户端没有收到的情况,必须纳入接口测试,而不是只测试无异常的第一次调用。

落地前的最后检查

把这套方案接入服务之前,先确认四件事。第一,令牌是不可拆分的整数单位,权重代表本批次比例,而不是绝对上限或最低保障。第二,接收方标识和同余数决胜规则已经固定,变更算法必须升级版本。第三,调用方会保存同一个逻辑请求的批次号,服务端会保存对应请求快照和原始回执。第四,所有会改变批次的写入都走受控入口,并有足够长的回执保留期。

如果某个测试组还有独立容量上限,简单裁剪分配结果会破坏总量约束,需要另外设计带容量的再分配算法。若要求连续多批次的长期均衡,也应单独建模历史误差。本文的边界是单批次比例分配:纯整数计算负责可核对的结果,稳定规则负责可复现,数据库事务负责整批一致,持久化回执负责安全重试。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。