acta-core 0.1.0-alpha.1

Append-only columnar file format for time-series data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["google-crc32c>=1.6"]
# ///
"""Executable framing probe and minimal fixture generator for Acta v0.2."""

from __future__ import annotations

import argparse
import struct
from dataclasses import dataclass
from pathlib import Path

import google_crc32c


FILE_MAGIC = b"ACTA\r\n\x1a\n"
FRAME_MAGIC = b"ACTAFRM\n"
COMMIT_MAGIC = b"ACTAEND\n"

PROLOGUE = struct.Struct("<8sHHIQ16sQ12sI")
PREFIX = struct.Struct("<8sHHIIIQQII")
TRAILER = struct.Struct("<QQII8s")
SCHEMA_HEADER = struct.Struct("<QIIII")
COLUMN_SCHEMA = struct.Struct("<IIHHIII")
BLOCK_HEADER = struct.Struct("<QQIIqqIIIIII")
COLUMN_DESCRIPTOR = struct.Struct("<IHHIIIHHII")
STREAM_DESCRIPTOR = struct.Struct("<HHHHQQQQII")


class Corruption(ValueError):
    pass


@dataclass(frozen=True)
class Frame:
    offset: int
    frame_type: int
    sequence: int
    header: bytes
    payload: bytes
    total_length: int


@dataclass(frozen=True)
class ScanResult:
    frames: tuple[Frame, ...]
    last_good_offset: int
    incomplete_tail: bool


def crc32c(data: bytes) -> int:
    return google_crc32c.value(data)


def pad8(data: bytes) -> bytes:
    return data + bytes((-len(data)) % 8)


def make_prologue(file_id: bytes = bytes(range(16)), feature_flags: int = 0) -> bytes:
    if len(file_id) != 16:
        raise ValueError("file ID must contain exactly 16 bytes")
    if feature_flags & ~1:
        raise ValueError("unknown v0.2 feature flags")
    without_crc = PROLOGUE.pack(
        FILE_MAGIC,
        0,
        2,
        PROLOGUE.size,
        feature_flags,
        file_id,
        PROLOGUE.size,
        bytes(12),
        0,
    )
    return without_crc[:-4] + struct.pack("<I", crc32c(without_crc[:-4]))


def make_frame(frame_type: int, sequence: int, header: bytes, payload: bytes) -> bytes:
    header = pad8(header)
    payload = pad8(payload)
    prefix = PREFIX.pack(
        FRAME_MAGIC,
        frame_type,
        0,
        0,
        len(header),
        0,
        len(payload),
        sequence,
        crc32c(header),
        0,
    )
    prefix = prefix[:-4] + struct.pack("<I", crc32c(prefix[:-4]))
    body = prefix + header + payload
    total_length = len(body) + TRAILER.size
    body_crc = crc32c(body)
    trailer_crc_input = (
        struct.pack("<QQI", total_length, sequence, body_crc) + COMMIT_MAGIC
    )
    trailer = TRAILER.pack(
        total_length,
        sequence,
        body_crc,
        crc32c(trailer_crc_input),
        COMMIT_MAGIC,
    )
    return body + trailer


def validate_prologue(data: bytes) -> None:
    if len(data) < PROLOGUE.size:
        raise Corruption("file is shorter than the 64-byte prologue")
    (
        magic,
        major,
        minor,
        size,
        flags,
        _file_id,
        schema_offset,
        reserved,
        stored_crc,
    ) = PROLOGUE.unpack_from(data)
    if magic != FILE_MAGIC:
        raise Corruption("bad file magic")
    if (major, minor, size, schema_offset) != (0, 2, 64, 64) or flags & ~1:
        raise Corruption("unsupported prologue fields")
    if reserved != bytes(12):
        raise Corruption("nonzero prologue reserved bytes")
    if stored_crc != crc32c(data[:60]):
        raise Corruption("bad prologue CRC32C")


def scan_frames(data: bytes, *, strict_body: bool = True) -> ScanResult:
    validate_prologue(data)
    frames: list[Frame] = []
    offset = PROLOGUE.size
    expected_sequence = 0
    while offset < len(data):
        remaining = len(data) - offset
        if remaining < PREFIX.size:
            return ScanResult(tuple(frames), offset, True)
        prefix_bytes = data[offset : offset + PREFIX.size]
        (
            magic,
            frame_type,
            frame_version,
            flags,
            header_length,
            reserved,
            payload_length,
            sequence,
            header_crc,
            prefix_crc,
        ) = PREFIX.unpack(prefix_bytes)
        if magic != FRAME_MAGIC:
            raise Corruption(f"bad frame magic at offset {offset}")
        if prefix_crc != crc32c(prefix_bytes[:44]):
            raise Corruption(f"bad prefix CRC32C at offset {offset}")
        if frame_version != 0 or flags != 0 or reserved != 0:
            raise Corruption(f"unsupported frame fields at offset {offset}")
        if header_length % 8 or payload_length % 8:
            raise Corruption(f"unaligned frame lengths at offset {offset}")
        if sequence != expected_sequence:
            raise Corruption(
                f"expected sequence {expected_sequence}, found {sequence} at offset {offset}"
            )
        total_length = PREFIX.size + header_length + payload_length + TRAILER.size
        if total_length < PREFIX.size + TRAILER.size:
            raise Corruption(f"frame length overflow at offset {offset}")
        if remaining < total_length:
            return ScanResult(tuple(frames), offset, True)

        header_start = offset + PREFIX.size
        payload_start = header_start + header_length
        trailer_start = payload_start + payload_length
        header = data[header_start:payload_start]
        payload = data[payload_start:trailer_start]
        trailer_bytes = data[trailer_start : trailer_start + TRAILER.size]
        (
            repeated_length,
            repeated_sequence,
            body_crc,
            trailer_crc,
            commit_magic,
        ) = TRAILER.unpack(trailer_bytes)
        if header_crc != crc32c(header):
            raise Corruption(f"bad header CRC32C at offset {offset}")
        if repeated_length != total_length or repeated_sequence != sequence:
            raise Corruption(f"mismatched trailer fields at offset {offset}")
        if commit_magic != COMMIT_MAGIC:
            raise Corruption(f"bad commit magic at offset {offset}")
        trailer_crc_input = trailer_bytes[:20] + trailer_bytes[24:]
        if trailer_crc != crc32c(trailer_crc_input):
            raise Corruption(f"bad trailer CRC32C at offset {offset}")
        if strict_body and body_crc != crc32c(data[offset:trailer_start]):
            raise Corruption(f"bad body CRC32C at offset {offset}")
        frames.append(
            Frame(
                offset,
                frame_type,
                sequence,
                header,
                payload,
                total_length,
            )
        )
        offset += total_length
        expected_sequence += 1
    return ScanResult(tuple(frames), offset, False)


def make_minimal_fixture() -> bytes:
    schema_id = 1
    timestamp_parameters = struct.pack("<BBHI", 2, 1, 0, 0)
    name = b"time"
    descriptor_length = 24 + len(name) + len(timestamp_parameters)
    descriptor_length += (-descriptor_length) % 8
    column = (
        COLUMN_SCHEMA.pack(
            descriptor_length,
            1,
            13,
            0,
            len(name),
            len(timestamp_parameters),
            0,
        )
        + name
        + timestamp_parameters
    )
    column = pad8(column)
    schema_header = SCHEMA_HEADER.pack(schema_id, 1, 1, 0, 0)
    schema_frame = make_frame(1, 0, schema_header, column)

    timestamps = (1_000_000, 2_000_000, 3_000_000)
    values = struct.pack("<qqq", *timestamps)
    statistics = struct.pack("<qq", min(timestamps), max(timestamps))
    column_table_offset = BLOCK_HEADER.size
    stream_table_offset = column_table_offset + COLUMN_DESCRIPTOR.size
    statistics_offset = stream_table_offset + STREAM_DESCRIPTOR.size
    block_header = BLOCK_HEADER.pack(
        schema_id,
        (1 << 64) - 1,
        len(timestamps),
        1,
        min(timestamps),
        max(timestamps),
        column_table_offset,
        stream_table_offset,
        statistics_offset,
        len(statistics),
        0,
        0,
    )
    column_descriptor = COLUMN_DESCRIPTOR.pack(
        1,
        0,
        3,
        0,
        len(timestamps),
        0,
        1,
        1,
        statistics_offset,
        len(statistics),
    )
    stream_descriptor = STREAM_DESCRIPTOR.pack(
        2,
        0,
        0,
        0,
        0,
        len(values),
        len(values),
        len(timestamps),
        crc32c(values),
        0,
    )
    data_header = block_header + column_descriptor + stream_descriptor + statistics
    data_frame = make_frame(2, 1, data_header, values)
    return make_prologue() + schema_frame + data_frame


def validate_minimal_fixture(data: bytes) -> None:
    result = scan_frames(data)
    if result.incomplete_tail or len(result.frames) != 2:
        raise AssertionError("minimal fixture did not contain two complete frames")
    schema, block = result.frames
    if (schema.frame_type, block.frame_type) != (1, 2):
        raise AssertionError("minimal fixture frame types are wrong")
    schema_id, column_count, time_column_id, schema_flags, schema_reserved = (
        SCHEMA_HEADER.unpack_from(schema.header)
    )
    if (schema_id, column_count, time_column_id, schema_flags, schema_reserved) != (
        1,
        1,
        1,
        0,
        0,
    ):
        raise AssertionError("minimal fixture schema header is wrong")
    (
        descriptor_length,
        column_id,
        logical_type,
        column_flags,
        name_length,
        parameter_length,
        column_reserved,
    ) = COLUMN_SCHEMA.unpack_from(schema.payload)
    if (
        descriptor_length != len(schema.payload)
        or column_id != time_column_id
        or logical_type != 13
        or column_flags != 0
        or column_reserved != 0
        or schema.payload[24 : 24 + name_length] != b"time"
        or parameter_length != 8
    ):
        raise AssertionError("minimal fixture timestamp schema is wrong")
    block_fields = BLOCK_HEADER.unpack_from(block.header)
    if (
        block_fields[0] != schema_id
        or block_fields[2] != 3
        or block_fields[3] != column_count
        or block_fields[4:6] != (1_000_000, 3_000_000)
    ):
        raise AssertionError("minimal fixture block metadata is wrong")
    column_offset, stream_offset, stats_offset, stats_length = block_fields[6:10]
    if (
        column_offset != BLOCK_HEADER.size
        or stream_offset != column_offset + COLUMN_DESCRIPTOR.size
        or stats_offset != stream_offset + STREAM_DESCRIPTOR.size
        or stats_offset + stats_length > len(block.header)
    ):
        raise AssertionError("minimal fixture header tables are out of bounds")
    column_fields = COLUMN_DESCRIPTOR.unpack_from(block.header, column_offset)
    if (
        column_fields[0] != column_id
        or column_fields[4] != block_fields[2]
        or column_fields[5] != 0
        or column_fields[6] != 1
        or column_fields[8:10] != (stats_offset, stats_length)
    ):
        raise AssertionError("minimal fixture column descriptor is wrong")
    stream_fields = STREAM_DESCRIPTOR.unpack_from(block.header, stream_offset)
    stored_offset, stored_length, stored_crc = (
        stream_fields[4],
        stream_fields[5],
        stream_fields[8],
    )
    if stored_offset + stored_length > len(block.payload):
        raise AssertionError("minimal fixture stream is out of payload bounds")
    stored = block.payload[stored_offset : stored_offset + stored_length]
    if crc32c(stored) != stored_crc:
        raise AssertionError("minimal fixture stream CRC32C is wrong")
    if struct.unpack("<qqq", stored) != (1_000_000, 2_000_000, 3_000_000):
        raise AssertionError("minimal fixture timestamp values are wrong")


def self_test() -> None:
    fixture = make_minimal_fixture()
    validate_minimal_fixture(fixture)
    result = scan_frames(fixture)
    last_frame_start = result.frames[-1].offset

    # Every possible interrupted write within the last frame preserves the
    # preceding schema frame and reports an incomplete tail.
    for cut in range(last_frame_start + 1, len(fixture)):
        truncated = scan_frames(fixture[:cut])
        if not truncated.incomplete_tail or len(truncated.frames) != 1:
            raise AssertionError(f"unexpected truncation result at byte {cut}")

    # Representative corruption in each protected region must be detected.
    corruption_offsets = [
        5,
        last_frame_start + 2,
        last_frame_start + PREFIX.size + 3,
        last_frame_start + PREFIX.size + len(result.frames[-1].header) + 3,
        len(fixture) - 2,
    ]
    for corruption_offset in corruption_offsets:
        damaged = bytearray(fixture)
        damaged[corruption_offset] ^= 0x01
        try:
            scan_frames(bytes(damaged))
        except Corruption:
            pass
        else:
            raise AssertionError(
                f"corruption at byte {corruption_offset} was not detected"
            )

    print(
        f"Acta v0.2 framing probe passed: {len(fixture)}-byte fixture, "
        f"{len(fixture) - last_frame_start - 1} truncation points, "
        f"{len(corruption_offsets)} corruption regions"
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--write-fixture", type=Path)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    self_test()
    if args.write_fixture:
        args.write_fixture.parent.mkdir(parents=True, exist_ok=True)
        fixture = make_minimal_fixture()
        args.write_fixture.write_bytes(fixture)
        print(f"wrote {len(fixture)} bytes to {args.write_fixture}")


if __name__ == "__main__":
    main()