Python sqlite3 双向最近时间戳连接:两个索引候选、确定性平局与精确整数距离

10-19 4阅读

两张表都带有时间,并不意味着它们能用相等连接对齐。设备采样通常不同步,最近的一条记录可能在事件之前,也可能在之后。本文用 Python 标准库 sqlite3 实现按设备分区的双向最近时间戳连接:每个事件只查两个索引候选,再用精确整数决定胜负,并在容差拒绝匹配时仍保留事件。

九个示例都可以单独保存为 Python 文件运行,不依赖前一节留下的变量;仅使用标准库和内存数据库。示例在 Python 3.12.14、SQLite 3.53.1 上执行验证,涉及 STRICT 表的部分要求 SQLite 3.37.0 或更新版本。检查的是 Python 实际链接的 SQLite 版本,而不是电脑上另一个 sqlite3 命令的版本。文中整数时间统一按微秒理解,算法本身不依赖特定日期范围。

Python sqlite3 双向最近时间戳连接:两个索引候选、确定性平局与精确整数距离
AI 生成的概念配图:独立设备轨道与双向候选,仅用于说明匹配思路,不代表数据库真实执行计划。

一、先定义最近,避免把它写成只向过去查找

假设事件发生在时间一百,设备甲的样本分别落在九十和一百零八。只向过去查找会得到九十,双向最近匹配则必须选择一百零八。设备乙即使在一百零一有样本,也不能参与甲的候选集。这个差异会直接影响离线传感器校准、日志关联和不同采样频率的数据对齐。

本文约定的排序键依次是绝对时间差、样本时间、样本编号。距离相同取较早时间,同一时间存在多行则取较小编号。这个编号必须是数据中稳定保存的身份,不能临时按读取顺序生成。右侧样本允许重复服务多个事件;本题不是消耗样本的一对一分配,也不做插值。

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE samples(id INTEGER, device TEXT, ts INTEGER)")
con.executemany("INSERT INTO samples VALUES (?, ?, ?)", [
    (1, "A", 90), (2, "A", 108), (3, "B", 101)
])
previous = con.execute(
    "SELECT id, ts FROM samples WHERE device = ? AND ts <= ? "
    "ORDER BY ts DESC, id ASC LIMIT 1", ("A", 100)
).fetchone()
following = con.execute(
    "SELECT id, ts FROM samples WHERE device = ? AND ts > ? "
    "ORDER BY ts ASC, id ASC LIMIT 1", ("A", 100)
).fetchone()
candidates = [row for row in (previous, following) if row is not None]
nearest = min(candidates, key=lambda row: (abs(row[1] - 100), row[1], row[0]))
assert previous == (1, 90)
assert nearest == (2, 108)
print("previous:", previous)
print("nearest:", nearest)
con.close()

运行输出:

previous: (1, 90)
nearest: (2, 108)

这里特意让未来样本胜出,用最小反例区分语义。若业务是交易回测、实时决策或任何不能使用未来信息的流程,应继续使用只向过去查找的契约,不能因为最近匹配更贴近数值就替换它。对离线对齐来说,未来候选本身不是错误,关键是读者和调用方知道它被允许。

二、把时间统一为整数微秒,转换过程也不用浮点

距离可比较之前,要先统一时间单位和时间基准。下例将带时区的时间转换为相对 UTC 纪元的整数微秒,通过天、秒、微秒三个整数分量计算。不要先得到浮点秒再乘一百万并强制转整数;丢失的低位精度不会因为最后一次类型转换而回来。

代码拒绝没有时区的时间,避免把机器本地设置偷偷变成数据含义。微秒只是本例约定;若数据源提供整数纳秒,可以沿用后文算法,但应重新审视有符号六十四位范围所能覆盖的日期。不同单位混用即使完全没有类型报错,也足以让结果全部失真。

from datetime import datetime, timezone

EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
MIN_I64 = -(1 << 63)
MAX_I64 = (1 << 63) - 1


def to_microseconds(value):
    if value.tzinfo is None or value.utcoffset() is None:
        raise ValueError("timezone required")
    delta = value.astimezone(timezone.utc) - EPOCH
    result = ((delta.days * 86400 + delta.seconds) * 1_000_000
              + delta.microseconds)
    if not MIN_I64 <= result <= MAX_I64:
        raise OverflowError("outside SQLite INTEGER range")
    return result


values = [
    "1970-01-01T00:00:00.000001+00:00",
    "1969-12-31T23:59:59.999999+00:00",
    "1970-01-01T08:00:00+08:00",
]
actual = [to_microseconds(datetime.fromisoformat(value)) for value in values]
assert actual == [1, -1, 0]
print(actual)
try:
    to_microseconds(datetime(1970, 1, 1))
except ValueError as exc:
    print(str(exc))

运行输出:

[1, -1, 0]
timezone required

纪元前一微秒得到负一,这也是必须覆盖的边界,不能把负数时间当成无效记录。后文只比较这些整数,不再对它们调用日期格式化或时区函数。对闰秒、设备时钟漂移和时间校准的处理应在输入协议中定义,最近查找本身不会修复这些上游问题。

三、让存储类型、重复时间和复合索引各司其职

样本表要求设备和时间非空;事件表允许这两个字段缺失,因为左侧事件仍要出现在结果中。示例使用 SQLite 3.37.0 起支持的 STRICT 表,但严格表并不等于拒绝所有类型转换:能够无损转换的文本数字仍可能被接受。因此应用入口另外检查原始对象,明确拒绝布尔值、浮点值和数字字符串。

时间戳只要求在有符号六十四位整数范围内,不要求每个设备的时间唯一。重复时间由稳定的样本编号打破平局。两个索引分别对应时间降序、时间升序,且都保持编号升序;不能认为把一个复合索引整体反向扫描后,编号仍然保持原来的方向。所有数据值用参数绑定,设备名称从不拼进 SQL。相关行为可查阅 SQLite STRICT 表说明和 Python sqlite3 文档。

import sqlite3

MIN_I64 = -(1 << 63)
MAX_I64 = (1 << 63) - 1


def checked_timestamp(value):
    if type(value) is not int:
        raise TypeError("an exact int is required")
    if not MIN_I64 <= value <= MAX_I64:
        raise OverflowError("outside SQLite INTEGER range")
    return value


con = sqlite3.connect(":memory:")
con.executescript("""CREATE TABLE samples(
    sample_id INTEGER PRIMARY KEY,
    device TEXT NOT NULL,
    ts INTEGER NOT NULL
) STRICT;
CREATE TABLE events(
    event_id INTEGER PRIMARY KEY,
    device TEXT,
    ts INTEGER
) STRICT;
CREATE INDEX sample_prev ON samples(device, ts DESC, sample_id ASC);
CREATE INDEX sample_next ON samples(device, ts ASC, sample_id ASC);""")
for sample_id in (9, 2):
    con.execute("INSERT INTO samples VALUES (?, ?, ?)",
                (sample_id, "A", checked_timestamp(100)))
print(con.execute(
    "SELECT sample_id, typeof(ts) FROM samples ORDER BY sample_id"
).fetchall())
rejected = []
for value in (True, 100.0, "100", 1 << 63):
    try:
        checked_timestamp(value)
    except (TypeError, OverflowError) as exc:
        rejected.append(type(exc).__name__)
assert rejected == ["TypeError", "TypeError", "TypeError", "OverflowError"]
print(rejected)
con.close()

运行输出:

[(2, 'integer'), (9, 'integer')]
['TypeError', 'TypeError', 'TypeError', 'OverflowError']

生产导入流程还应验证设备编码和业务主键;这里的检查函数只负责时间这一列。若允许空字符串作为设备名,它就是一个真实分区,不会自动等同于缺失。大小写是否代表同一设备也必须在入库前统一,本文使用默认的精确文本比较,不自行合并设备。

四、为什么两个候选已经足够

固定设备和事件时间后,把右侧样本切成不晚于事件、晚于事件两个集合。在前一集合中,时间越靠后距离越小;在后一集合中,时间越靠前距离越小。所以每侧只需要取一个边界时间,再按编号升序选出该时间的代表。这个结论来自一维距离的单调性,与样本数量无关。

前驱查询使用小于等于,后继查询使用严格大于,因此精确命中的时间只进入前驱侧。两边都使用相同的设备等值条件,缺任何一处都可能造成跨设备串线。下例故意把同时间的小编号排在插入顺序之后,验证结果不依赖插入顺序。

import sqlite3

con = sqlite3.connect(":memory:", isolation_level=None)
con.executescript("""CREATE TABLE samples(
    sample_id INTEGER PRIMARY KEY,
    device TEXT NOT NULL,
    ts INTEGER NOT NULL
) STRICT;
CREATE TABLE events(
    event_id INTEGER PRIMARY KEY,
    device TEXT,
    ts INTEGER
) STRICT;
CREATE INDEX sample_prev ON samples(device, ts DESC, sample_id ASC);
CREATE INDEX sample_next ON samples(device, ts ASC, sample_id ASC);""")
con.executemany("INSERT INTO samples VALUES (?, ?, ?)", [
    (9, "A", 100), (2, "A", 100),
    (8, "A", 110), (3, "A", 110), (1, "B", 105)
])
previous_sql = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts <= ?
ORDER BY ts DESC, sample_id ASC LIMIT 1"""
following_sql = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts > ?
ORDER BY ts ASC, sample_id ASC LIMIT 1"""
con.execute("BEGIN")
try:
    previous = con.execute(previous_sql, ("A", 105)).fetchone()
    following = con.execute(following_sql, ("A", 105)).fetchone()
    assert (previous, following) == ((2, 100), (3, 110))
    print("candidates:", previous, following)
    exact = con.execute(previous_sql, ("A", 100)).fetchone()
    assert exact == (2, 100)
    print("exact:", exact)
finally:
    con.execute("ROLLBACK")
    con.close()

运行输出:

candidates: (2, 100) (3, 110)
exact: (2, 100)

两个查询放进同一个显式只读事务,避免在两次查询之间看到不同提交版本。这里用回滚结束只读事务,没有业务写入需要撤销。运行期间不要让其他代码借用同一连接执行写入;同连接操作并不会互相隔离。SQLite 隔离文档解释了不同连接的可见性与 WAL 快照行为。本文不更改日志模式,也不为只读匹配申请写事务。

五、完整连接函数:每个左侧事件恰好输出一行

把查询和选择规则组合起来,结果列依次是事件编号、设备、事件时间、样本编号、样本时间、有符号偏移和状态。偏移定义为样本时间减事件时间,负数代表更早、正数代表更晚。无匹配时三个样本相关字段统一为 None,状态进一步说明缺键、无样本或超过容差。

函数接收空闲的专用连接并自行管理只读事务;调用方若已经开启事务,它会直接拒绝,而不会擅自提交或回滚调用方的工作。结果按事件编号输出,既不丢失空键,也不把一个左侧事件展开成多行。代码只将两个候选带回 Python,然后利用任意精度整数计算差值;这是整套实现最关键的数值边界。

import sqlite3

SCHEMA = """CREATE TABLE samples(
    sample_id INTEGER PRIMARY KEY,
    device TEXT NOT NULL,
    ts INTEGER NOT NULL
) STRICT;
CREATE TABLE events(
    event_id INTEGER PRIMARY KEY,
    device TEXT,
    ts INTEGER
) STRICT;
CREATE INDEX sample_prev ON samples(device, ts DESC, sample_id ASC);
CREATE INDEX sample_next ON samples(device, ts ASC, sample_id ASC);"""
PREV = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts <= ?
ORDER BY ts DESC, sample_id ASC LIMIT 1"""
NEXT = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts > ?
ORDER BY ts ASC, sample_id ASC LIMIT 1"""


def nearest_join(con, tolerance=None):
    if tolerance is not None:
        if type(tolerance) is not int or tolerance < 0:
            raise ValueError("tolerance must be a nonnegative int or None")
    if con.in_transaction:
        raise ValueError("use an idle, dedicated connection")
    result = []
    con.execute("BEGIN")
    try:
        events = con.execute(
            "SELECT event_id, device, ts FROM events ORDER BY event_id"
        ).fetchall()
        for event_id, device, ts in events:
            prefix = (event_id, device, ts)
            if device is None or ts is None:
                result.append(prefix + (None, None, None, "missing_key"))
                continue
            candidates = []
            for query in (PREV, NEXT):
                row = con.execute(query, (device, ts)).fetchone()
                if row is not None:
                    candidates.append(row)
            if not candidates:
                result.append(prefix + (None, None, None, "no_sample"))
                continue
            sample_id, sample_ts = min(
                candidates,
                key=lambda row: (abs(row[1] - ts), row[1], row[0]),
            )
            delta = sample_ts - ts
            if tolerance is not None and abs(delta) > tolerance:
                result.append(prefix + (None, None, None, "outside_tolerance"))
            else:
                result.append(prefix + (sample_id, sample_ts, delta, "matched"))
        return result
    finally:
        con.execute("ROLLBACK")

con = sqlite3.connect(":memory:", isolation_level=None)
con.executescript(SCHEMA)
con.executemany("INSERT INTO samples VALUES (?, ?, ?)", [
    (7, "A", 100), (2, "A", 100), (3, "A", 110),
    (4, "B", 107), (5, "A", 130)
])
con.executemany("INSERT INTO events VALUES (?, ?, ?)", [
    (1, "A", 105), (2, "A", 108), (3, "A", 100), (4, "B", 105),
    (5, "C", 105), (6, None, 105), (7, "A", None), (8, "A", 200)
])
rows = nearest_join(con, tolerance=8)
assert len(rows) == 8
assert [row[3] for row in rows] == [2, 3, 2, 4, None, None, None, None]
for row in rows:
    print((row[0],) + row[3:])
assert not con.in_transaction
con.close()

运行输出:

(1, 2, 100, -5, 'matched')
(2, 3, 110, 2, 'matched')
(3, 2, 100, 0, 'matched')
(4, 4, 107, 2, 'matched')
(5, None, None, None, 'no_sample')
(6, None, None, None, 'missing_key')
(7, None, None, None, 'missing_key')
(8, None, None, None, 'outside_tolerance')

空表也不需要特别的 SQL 分支:没有事件就返回空列表,有事件但没有样本就输出无样本状态。精确命中和同时间重复行的优先级由查询顺序及排序键共同保证。不要再对结果做只保留样本编号非空的过滤,否则原本承诺的左连接语义会被自己破坏。

这份实现为了便于审计,把所有事件和结果保存在内存中。大批量任务可以改成分批读取、分批写出,但要先决定是否要求整批共享同一个快照。每批新开事务能缩短读取时间,却允许批与批之间看到不同的样本版本;这属于业务一致性选择,不是单纯的性能开关。

六、容差是闭区间,None 与零不能混淆

容差与时间戳使用相同单位,接受条件是绝对偏移小于等于容差。距离恰好等于边界必须匹配,零表示只接受精确命中,None 才表示不限制距离。判断时要显式比较 None,不能使用参数的真假值,否则零很容易被误解释成无限制。

先选出全局最近候选,再应用容差即可:如果最近候选都超出距离上限,其余候选更不可能通过。容差不绑定进 SQL,所以可以是超过 SQLite INTEGER 上限的 Python 整数;只要是非负整数,算法仍然能精确判断。下例单独测试这项选择契约,候选列表视为上一节索引查找已经完成的结果。

def select_candidate(ts, candidates, tolerance):
    if tolerance is not None:
        if type(tolerance) is not int or tolerance < 0:
            raise ValueError("invalid tolerance")
    if not candidates:
        return None
    row = min(candidates, key=lambda item: (abs(item[1] - ts), item[1], item[0]))
    if tolerance is not None and abs(row[1] - ts) > tolerance:
        return None
    return row[0]


candidates = [(2, 100), (3, 110)]
for tolerance in (4, 5, 0, None):
    print(tolerance, select_candidate(105, candidates, tolerance))
assert select_candidate(100, candidates, 0) == 2
assert select_candidate(105, [], None) is None
assert select_candidate(105, candidates, 1 << 80) == 2
errors = []
for tolerance in (-1, True, 1.5):
    try:
        select_candidate(105, candidates, tolerance)
    except ValueError:
        errors.append("rejected")
print("exact at zero:", select_candidate(100, candidates, 0))
print("invalid:", errors)

运行输出:

4 None
5 2
0 None
None 2
exact at zero: 2
invalid: ['rejected', 'rejected', 'rejected']

拒绝布尔值不是吹毛求疵:Python 中布尔值属于整数的子类,而配置文件里的 true 通常并不表示一微秒。参数验证要在处理空输入之前发生,确保错误配置不会因为某一批恰好没有事件而长期潜伏。第五节函数也遵循了这一顺序。

七、两个合法时间戳的差,未必是合法的 SQLite 整数

有符号六十四位整数的最小值到最大值相差 18446744073709551615,超过了同一类型能够表示的最大正数。关键结论是:每个输入单独合法,并不代表它们相减也能放进同一类型。

SQLite 的整数算术在溢出时可能改用浮点运算;另一方面,对最小有符号整数直接调用 abs 会报整数溢出。不要把整数列和整数参数当成整个表达式都精确的保证。下面用两条相邻的极小时间与极大目标时间构造反例:朴素 SQL 距离排序会因浮点舍入制造平局,进而选择实际更远的样本。

import sqlite3

low = -(1 << 63)
high = (1 << 63) - 1
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE samples(id INTEGER PRIMARY KEY, ts INTEGER NOT NULL)")
con.executemany("INSERT INTO samples VALUES (?, ?)", [(1, low), (2, low + 1)])
naive = con.execute(
    "SELECT id, typeof(ts - ?) FROM samples "
    "ORDER BY abs(ts - ?), ts, id LIMIT 1", (high, high)
).fetchone()
rows = con.execute("SELECT id, ts FROM samples").fetchall()
exact = min(rows, key=lambda row: (abs(row[1] - high), row[1], row[0]))
assert naive == (1, "real")
assert exact[0] == 2
print("SQL rounded choice:", naive)
print("Python exact choice:", exact[0])
print("exact distance:", abs(exact[1] - high))
print("full endpoint distance:", high - low)
try:
    con.execute("SELECT abs(?)", (low,)).fetchone()
except sqlite3.OperationalError:
    print("abs(min_i64): overflow")
con.close()

运行输出:

SQL rounded choice: (1, 'real')
Python exact choice: 2
exact distance: 18446744073709551614
full endpoint distance: 18446744073709551615
abs(min_i64): overflow

第五节不会执行 SQL 时间减法,也不会构造目标时间加减容差的边界,因此避开了上述溢出路径。数据库只做精确的整数大小比较,Python 再计算差值和绝对值。若把偏移重新落库,超过范围的值不能硬塞回 INTEGER;应明确采用十进制文本等存储协议,并保留其数值含义,不能悄悄改成浮点。

这项限制可分别核对 SQLite 算术表达式规则、abs 函数说明和 Python 整数精度说明。反例中的全表排序只用于暴露错误,生产查找仍然使用前驱与后继两个边界。

八、检查查询计划,而不是靠索引名称猜性能

索引存在不代表每个查询都会按预期利用它。下面读取两条查询的 EXPLAIN QUERY PLAN,检查是否是索引搜索、是否出现临时排序,并打印实际使用的索引名。查询只取样本编号与时间,两个字段都在索引中,因此本例可以使用覆盖索引。

设备等值条件在第一列,时间范围条件在下一列,排序方向又与对应索引一致。这使每个事件的每一侧都能从边界定位后取一行,而不是为整台设备计算绝对距离再排序。索引会增加写入和空间成本,若修改了重复时间的选择规则,也必须重新检查索引方向。

import sqlite3

con = sqlite3.connect(":memory:")
con.executescript("""CREATE TABLE samples(
    sample_id INTEGER PRIMARY KEY,
    device TEXT NOT NULL,
    ts INTEGER NOT NULL
) STRICT;
CREATE TABLE events(
    event_id INTEGER PRIMARY KEY,
    device TEXT,
    ts INTEGER
) STRICT;
CREATE INDEX sample_prev ON samples(device, ts DESC, sample_id ASC);
CREATE INDEX sample_next ON samples(device, ts ASC, sample_id ASC);""")
con.executemany("INSERT INTO samples VALUES (?, ?, ?)",
                [(i, "A", i // 2) for i in range(1, 201)])
queries = [
    ("sample_prev", """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts <= ?
ORDER BY ts DESC, sample_id ASC LIMIT 1"""),
    ("sample_next", """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts > ?
ORDER BY ts ASC, sample_id ASC LIMIT 1"""),
]
for index_name, query in queries:
    details = [row[3] for row in con.execute(
        "EXPLAIN QUERY PLAN " + query, ("A", 50)
    )]
    indexed = any("SEARCH" in detail and index_name in detail for detail in details)
    temp_sort = any("USE TEMP B-TREE" in detail for detail in details)
    print(index_name, "indexed:", indexed, "temporary sort:", temp_sort)
con.close()

运行输出:

sample_prev indexed: True temporary sort: False
sample_next indexed: True temporary sort: False

预期输出来自本文测试环境,查询计划格式和优化器选择并不是跨版本稳定接口。部署时若看到不同结果,应查看完整计划和真实数据分布,而不是依赖打印文本做业务判定。官方查询计划文档也明确提醒输出可能变化。

在索引被采用的前提下,可把查找工作理解为每个有效事件两次树上定位,额外的候选比较是常数规模;整个任务还包含读取左表、输出结果和 Python 调用开销。这不是对墙钟耗时的保证。两次本地 sqlite3 调用并非网络往返,但事件数很大时仍值得实测吞吐。有关复合索引顺序及搜索排序关系,可继续阅读 SQLite 查询规划说明。

九、用独立的穷举 oracle 检查随机输入和整数端点

正确性测试不能只复述两个查询的输出。下面保留完整生产函数,同时实现一个只在测试中使用的 oracle:对每个事件枚举同设备的全部样本,按已经声明的排序键选出答案。它很慢,却不依赖前驱后继缩减逻辑,适合用来发现边界取错、设备条件遗漏和重复时间排序方向错误。

固定随机种子保证重现,输入既包含重复的小整数,也包含两个整数端点及其邻居,并混入空设备、空时间、没有样本的设备和空右表。每组数据分别测试不限距离、零容差、普通容差、极大容差;最后还验证空左表。所有比较都使用完整结果行,不能只检查命中数量。

import sqlite3

SCHEMA = """CREATE TABLE samples(
    sample_id INTEGER PRIMARY KEY,
    device TEXT NOT NULL,
    ts INTEGER NOT NULL
) STRICT;
CREATE TABLE events(
    event_id INTEGER PRIMARY KEY,
    device TEXT,
    ts INTEGER
) STRICT;
CREATE INDEX sample_prev ON samples(device, ts DESC, sample_id ASC);
CREATE INDEX sample_next ON samples(device, ts ASC, sample_id ASC);"""
PREV = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts <= ?
ORDER BY ts DESC, sample_id ASC LIMIT 1"""
NEXT = """SELECT sample_id, ts FROM samples
WHERE device = ? AND ts > ?
ORDER BY ts ASC, sample_id ASC LIMIT 1"""


def nearest_join(con, tolerance=None):
    if tolerance is not None:
        if type(tolerance) is not int or tolerance < 0:
            raise ValueError("tolerance must be a nonnegative int or None")
    if con.in_transaction:
        raise ValueError("use an idle, dedicated connection")
    result = []
    con.execute("BEGIN")
    try:
        events = con.execute(
            "SELECT event_id, device, ts FROM events ORDER BY event_id"
        ).fetchall()
        for event_id, device, ts in events:
            prefix = (event_id, device, ts)
            if device is None or ts is None:
                result.append(prefix + (None, None, None, "missing_key"))
                continue
            candidates = []
            for query in (PREV, NEXT):
                row = con.execute(query, (device, ts)).fetchone()
                if row is not None:
                    candidates.append(row)
            if not candidates:
                result.append(prefix + (None, None, None, "no_sample"))
                continue
            sample_id, sample_ts = min(
                candidates,
                key=lambda row: (abs(row[1] - ts), row[1], row[0]),
            )
            delta = sample_ts - ts
            if tolerance is not None and abs(delta) > tolerance:
                result.append(prefix + (None, None, None, "outside_tolerance"))
            else:
                result.append(prefix + (sample_id, sample_ts, delta, "matched"))
        return result
    finally:
        con.execute("ROLLBACK")

import random


def oracle(events, samples, tolerance):
    result = []
    for event_id, device, ts in sorted(events):
        prefix = (event_id, device, ts)
        if device is None or ts is None:
            result.append(prefix + (None, None, None, "missing_key"))
            continue
        eligible = [(sid, stamp) for sid, dev, stamp in samples if dev == device]
        eligible.sort(key=lambda row: (abs(row[1] - ts), row[1], row[0]))
        if not eligible:
            result.append(prefix + (None, None, None, "no_sample"))
        else:
            sid, stamp = eligible[0]
            delta = stamp - ts
            if tolerance is not None and abs(delta) > tolerance:
                result.append(prefix + (None, None, None, "outside_tolerance"))
            else:
                result.append(prefix + (sid, stamp, delta, "matched"))
    return result


rng = random.Random(20261019)
low, high = -(1 << 63), (1 << 63) - 1
pool = [low, low + 1, -3, -1, 0, 1, 3, high - 1, high]
tolerances = [None, 0, 1, 5, high, 1 << 64]
con = sqlite3.connect(":memory:", isolation_level=None)
con.executescript(SCHEMA)
compared = 0
for case in range(120):
    samples = [(sid, rng.choice(["A", "B"]), rng.choice(pool))
               for sid in range(1, rng.randrange(0, 35) + 1)]
    events = [(eid, rng.choice(["A", "B", "C", None]),
               rng.choice(pool + [None])) for eid in range(1, 25)]
    con.execute("DELETE FROM samples")
    con.execute("DELETE FROM events")
    con.executemany("INSERT INTO samples VALUES (?, ?, ?)", samples)
    con.executemany("INSERT INTO events VALUES (?, ?, ?)", events)
    for tolerance in tolerances:
        actual = nearest_join(con, tolerance)
        expected = oracle(events, samples, tolerance)
        assert actual == expected, (case, tolerance, actual, expected)
        assert len(actual) == len(events)
        compared += len(events)
con.execute("DELETE FROM events")
assert nearest_join(con, None) == []
assert not con.in_transaction
print("datasets:", 120)
print("tolerances:", len(tolerances))
print("event comparisons:", compared)
print("oracle: PASS")
con.close()

运行输出:

datasets: 120
tolerances: 6
event comparisons: 17280
oracle: PASS

穷举版本刻意留在测试里,不应拿到生产环境替代索引搜索。随机测试也不是数学证明:双候选充分性的论证、明确的平局规则、输入类型约束和端点反例仍各有作用。以后增加租户键、改变设备归一化或支持另一种平局策略时,先修改书面契约,再修改 oracle,最后调整查询和索引。

落地前的检查清单

  • 明确允许匹配未来样本,并接受同一右侧样本被多个事件重复使用。

  • 统一时间基准与单位,拒绝含糊的浮点或文本时间入口。

  • 每个方向都带设备条件,精确命中只放进一个候选集合。

  • 等距离选较早时间,同时间选较小稳定编号,并为两个排序方向建立对应索引。

  • 在 Python 中计算差值和容差,不让 SQLite 溢出算术参与候选比较。

  • 保留所有左侧事件,用明确状态区分未匹配原因,并在同一只读事务里完成一批查找。

  • 把端点、重复、空值、分区、容差边界和独立 oracle 纳入回归测试。

最近匹配的重点不是写出最短的距离表达式,而是把选择规则做成稳定、可复现的契约。让数据库负责有序定位,让 Python 负责超出六十四位范围也精确的整数比较,两者的职责边界清楚,正确性和性能才有共同的检查依据。

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