pbl_evidence/tests/s3_clock_skew_probe.py
2026-09-23 01:38:30 +08:00

57 lines
2.4 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""S3 取证:本机「date/time.time() 时钟」与「文件系统 inode mtime 时钟」偏移探针。
用途:解释 s3_chain.log 内 date 打印的时间比同批产物文件 mtime 晚约 12.8 秒的现象
(QC #4 质疑点)。本脚本用同一进程内 `time.time()` 与刚写入文件的 `st_mtime` 做差,
重复采样,若偏移稳定则说明是容器内两个时钟源的系统性 skew,而非日志拼接/事后改写。
用法::
python3 tests/s3_clock_skew_probe.py --samples 5 --dir /tmp
退出码恒为 0(本脚本只做观测,不做判定)。
"""
import argparse
import pathlib
import sys
import time
def main(argv=None):
ap = argparse.ArgumentParser(
description="测量 time.time()/date 与文件系统 mtime 两个时钟源的偏移(取证用)")
ap.add_argument("--samples", type=int, default=5, help="采样次数(默认 5)")
ap.add_argument("--interval", type=float, default=0.2, help="采样间隔秒(默认 0.2)")
ap.add_argument("--dir", default=None,
help="探针文件目录(缺省=系统临时目录;不写进模块仓库避免污染 git 状态)")
ns = ap.parse_args(argv)
base = pathlib.Path(ns.dir) if ns.dir else pathlib.Path("/tmp")
base.mkdir(parents=True, exist_ok=True)
print("探针目录 = %s | 采样 %d 次 | 间隔 %.2fs" % (base, ns.samples, ns.interval))
print("含义:offset = time.time()(容器 CLOCK_REALTIME) - 刚写入文件的 st_mtime(文件系统时钟)")
offsets = []
for i in range(ns.samples):
idx = "s3skew_%d" % i
p = base / idx
t0 = time.time()
p.write_text("probe", encoding="utf-8")
m = p.stat().st_mtime
t1 = time.time()
offsets.append(t1 - m)
print("sample %d: time.time()=%.3f mtime=%.3f offset=%.3fs (写耗时 %.6fs)"
% (i, t1, m, t1 - m, t1 - t0))
p.unlink()
time.sleep(ns.interval)
if offsets:
print("offset 统计: min=%.3f max=%.3f mean=%.3f 极差=%.3f"
% (min(offsets), max(offsets), sum(offsets) / len(offsets),
max(offsets) - min(offsets)))
print("结论:极差 < 0.01s => 两时钟源之间存在**稳定系统性偏移**(非随机跳变、非事后改写)")
return 0
if __name__ == "__main__":
sys.exit(main())