Forráskód Böngészése

fix(storage): 新增 segment_files(),证据分段按写入顺序取(ext4 readdir 是哈希序)

frames.jsonl 与 frames-<ts>-<idx>.jsonl 的一维名字序 == 写入序('-'(0x2D) < '.'(0x2E)),但 os.listdir() 的顺序由文件系统决定:NTFS 上像有序,ext4 上是哈希序(板端实测 [6,7,4,5,0,1,2,3])。

* StorageWriter.segment_files():返回全部分段(归档 + 当前)并按名字排序,文档里写明别用 listdir 复原顺序;

* tests/test_storage.py 改用 writer.segment_files(),板端与开发机结果一致。
Administrator 1 hete
szülő
commit
322895c576
2 módosított fájl, 22 hozzáadás és 3 törlés
  1. 18 0
      portcv/storage.py
  2. 4 3
      tests/test_storage.py

+ 18 - 0
portcv/storage.py

@@ -112,6 +112,24 @@ class SegmentingJsonlWriter:
             if name.startswith("frames-") and name.endswith(".jsonl")
         )
 
+    def segment_files(self) -> List[str]:
+        """按**写入顺序**返回全部分段文件(含当前正在写的 ``frames.jsonl``)。
+
+        归档段命名为 ``frames-<时间戳>-<序号>.jsonl``,字符 ``'-'``(0x2D) 小于
+        ``'.'``(0x2E),所以按文件名排序正好是「旧归档段 → 当前段」。外部读取证据
+        (现场复盘、脚本抽样)必须走这个函数:``os.listdir`` 的顺序在 ext4 上是
+        目录哈希序,跨机器/跨文件系统都不稳定,直接拼接会把记录读乱。
+        """
+
+        current = os.path.basename(self.path)
+        names = [
+            name
+            for name in os.listdir(self.directory)
+            if name.endswith(".jsonl")
+            and (name == current or name.startswith("frames-"))
+        ]
+        return [os.path.join(self.directory, name) for name in sorted(names)]
+
     def _repair_tail(self) -> None:
         """断电时最后一行可能只写了一半;补换行,保留原始字节供排查。"""
 

+ 4 - 3
tests/test_storage.py

@@ -37,11 +37,12 @@ class SegmentingJsonlWriterTests(unittest.TestCase):
         writer.close()
         self.assertTrue(os.path.exists(writer.path))
         self.assertGreaterEqual(writer.segments, 2)
-        files = [name for name in os.listdir(self.tmp) if name.endswith(".jsonl")]
+        # 必须按写入顺序读:os.listdir 在 ext4 上是哈希序,跨机器不稳定
+        files = writer.segment_files()
         self.assertGreaterEqual(len(files), 2)
         records = []
-        for name in files:
-            with open(os.path.join(self.tmp, name), "r", encoding="utf-8") as fh:
+        for path in files:
+            with open(path, "r", encoding="utf-8") as fh:
                 for line in fh:
                     line = line.strip()
                     if line: