~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
298 lines · 11.1 KB Raw History
//! Durable single-job timestamp-import records and resume checkpoints.
//!
//! Keyspace (in Stream's unified metadata RocksDB):
//!   timestamp-import/current
//!   timestamp-import/job/<id>/record
//!   timestamp-import/job/<id>/segment/<u64 big endian>
//!
//! Every mutation is a synchronous RocksDB write. A segment marker is written
//! only after its JSS rename and parent-directory fsync have completed.

const std = @import("std");
const rocksdb = @import("rocksdb");
const meta_store = @import("../storage/meta_store.zig");
const parse = @import("parse.zig");

const Allocator = std.mem.Allocator;

pub const current_key = "timestamp-import/current";
const job_prefix = "timestamp-import/job/";

pub const State = enum {
    running,
    complete,
    failed,

    pub fn terminal(self: State) bool {
        return self != .running;
    }
};

pub const Phase = enum {
    parse_bucket,
    apply,
};

pub const Record = struct {
    id: []const u8,
    csv_path: []const u8,
    state: State = .running,
    phase: Phase = .parse_bucket,
    error_message: []const u8 = "",
    submitted_at_us: i64,
    finished_at_us: i64 = 0,
    bucketed: bool = false,
    segments_to_apply: u64 = 0,
    segments_applied: u64 = 0,
    rows_total: u64 = 0,
    rows_valid: u64 = 0,
    rows_rejected: u64 = 0,
    rejects_by_reason: [@typeInfo(parse.RejectReason).@"enum".field_names.len]u64 = @splat(0),
    segments_examined: u64 = 0,
    segments_patched: u64 = 0,
    rows_mutated: u64 = 0,
    rows_matched_all_versions: u64 = 0,
    rows_matched_specific: u64 = 0,
    specific_cids_unmatched: u64 = 0,
    rows_corrupt_offset: u64 = 0,
    bytes_rewritten: u64 = 0,
};

pub const ParsedRecord = std.json.Parsed(Record);

pub const Store = struct {
    allocator: Allocator,
    meta: *meta_store.Store,

    pub fn init(allocator: Allocator, meta: *meta_store.Store) Store {
        return .{ .allocator = allocator, .meta = meta };
    }

    pub fn begin(self: *Store, record: Record) !void {
        const key = try recordKey(self.allocator, record.id);
        defer self.allocator.free(key);
        const encoded = try encodeRecord(self.allocator, record);
        defer self.allocator.free(encoded);
        var batch = self.meta.batch();
        defer batch.deinit();
        batch.put(key, encoded);
        batch.put(current_key, record.id);
        try batch.commitDurable();
    }

    pub fn put(self: *Store, record: Record) !void {
        const key = try recordKey(self.allocator, record.id);
        defer self.allocator.free(key);
        const encoded = try encodeRecord(self.allocator, record);
        defer self.allocator.free(encoded);
        try self.meta.putDurable(key, encoded);
    }

    pub fn get(self: *Store, id: []const u8) !?ParsedRecord {
        const key = try recordKey(self.allocator, id);
        defer self.allocator.free(key);
        const encoded = try self.meta.getAlloc(self.allocator, key) orelse return null;
        defer self.allocator.free(encoded);
        // The RocksDB value is released on return, so every string in the
        // parsed record must be owned by ParsedRecord's arena.
        return try std.json.parseFromSlice(Record, self.allocator, encoded, .{
            .allocate = .alloc_always,
        });
    }

    pub fn current(self: *Store) !?[]u8 {
        return self.meta.getAlloc(self.allocator, current_key);
    }

    pub fn checkpointSegment(self: *Store, id: []const u8, index: u64) !void {
        const key = try segmentKey(self.allocator, id, index);
        defer self.allocator.free(key);
        try self.meta.putDurable(key, &.{1});
    }

    pub fn loadDone(self: *Store) !std.AutoHashMapUnmanaged(u64, void) {
        const id = try self.current() orelse return .empty;
        defer self.allocator.free(id);
        return self.loadDoneFor(id);
    }

    pub fn loadDoneFor(self: *Store, id: []const u8) !std.AutoHashMapUnmanaged(u64, void) {
        const prefix = try segmentPrefix(self.allocator, id);
        defer self.allocator.free(prefix);
        var done: std.AutoHashMapUnmanaged(u64, void) = .empty;
        errdefer done.deinit(self.allocator);
        var error_data: ?rocksdb.Data = null;
        defer if (error_data) |data| data.deinit();
        var iterator = self.meta.iterator(prefix);
        defer iterator.deinit();
        while (try iterator.next(&error_data)) |entry| {
            const key = entry[0].data;
            if (!std.mem.startsWith(u8, key, prefix)) break;
            if (key.len != prefix.len + 8) return error.CorruptSegmentCheckpoint;
            try done.put(self.allocator, std.mem.readInt(u64, key[prefix.len..][0..8], .big), {});
        }
        return done;
    }

    pub fn dropDone(self: *Store, id: []const u8) !void {
        const prefix = try segmentPrefix(self.allocator, id);
        defer self.allocator.free(prefix);
        var keys: std.ArrayList([]u8) = .empty;
        defer {
            for (keys.items) |key| self.allocator.free(key);
            keys.deinit(self.allocator);
        }
        var error_data: ?rocksdb.Data = null;
        defer if (error_data) |data| data.deinit();
        var iterator = self.meta.iterator(prefix);
        defer iterator.deinit();
        while (try iterator.next(&error_data)) |entry| {
            const key = entry[0].data;
            if (!std.mem.startsWith(u8, key, prefix)) break;
            try keys.append(self.allocator, try self.allocator.dupe(u8, key));
        }
        if (keys.items.len == 0) return;
        var batch = self.meta.batch();
        defer batch.deinit();
        for (keys.items) |key| batch.delete(key);
        try batch.commitDurable();
    }
};

fn encodeRecord(allocator: Allocator, record: Record) ![]u8 {
    var output: std.Io.Writer.Allocating = .init(allocator);
    errdefer output.deinit();
    var stringify: std.json.Stringify = .{ .writer = &output.writer };
    try stringify.write(record);
    return output.toOwnedSlice();
}

fn recordKey(allocator: Allocator, id: []const u8) ![]u8 {
    return std.fmt.allocPrint(allocator, "{s}{s}/record", .{ job_prefix, id });
}

fn segmentPrefix(allocator: Allocator, id: []const u8) ![]u8 {
    return std.fmt.allocPrint(allocator, "{s}{s}/segment/", .{ job_prefix, id });
}

fn segmentKey(allocator: Allocator, id: []const u8, index: u64) ![]u8 {
    const prefix = try segmentPrefix(allocator, id);
    defer allocator.free(prefix);
    const key = try allocator.alloc(u8, prefix.len + 8);
    @memcpy(key[0..prefix.len], prefix);
    std.mem.writeInt(u64, key[prefix.len..][0..8], index, .big);
    return key;
}

test "durable job record current pointer and segment done-set survive reopen" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var root_buffer: [std.fs.max_path_bytes]u8 = undefined;
    const root_len = try tmp.dir.realPath(testing.io, &root_buffer);
    const root = root_buffer[0..root_len];
    const initial: Record = .{
        .id = "job-1",
        .csv_path = "/data/imports/a.csv",
        .submitted_at_us = 100,
        .rows_valid = 7,
    };
    {
        var meta = try meta_store.Store.open(testing.allocator, root);
        defer meta.deinit();
        var jobs = Store.init(testing.allocator, &meta);
        try jobs.begin(initial);
        try jobs.checkpointSegment(initial.id, 9);
        try jobs.checkpointSegment(initial.id, 2);
    }
    {
        var meta = try meta_store.Store.open(testing.allocator, root);
        defer meta.deinit();
        var jobs = Store.init(testing.allocator, &meta);
        const current = (try jobs.current()).?;
        defer testing.allocator.free(current);
        try testing.expectEqualStrings("job-1", current);
        var parsed = (try jobs.get(current)).?;
        defer parsed.deinit();
        try testing.expectEqualStrings(initial.csv_path, parsed.value.csv_path);
        try testing.expectEqual(@as(u64, 7), parsed.value.rows_valid);
        try testing.expectEqual(State.running, parsed.value.state);
        var done = try jobs.loadDoneFor(current);
        defer done.deinit(testing.allocator);
        try testing.expectEqual(@as(usize, 2), done.count());
        try testing.expect(done.contains(2));
        try testing.expect(done.contains(9));

        var complete = parsed.value;
        complete.state = .complete;
        complete.phase = .apply;
        complete.finished_at_us = 200;
        try jobs.put(complete);
        try jobs.dropDone(current);
        var empty = try jobs.loadDoneFor(current);
        defer empty.deinit(testing.allocator);
        try testing.expectEqual(@as(usize, 0), empty.count());
    }
    {
        var meta = try meta_store.Store.open(testing.allocator, root);
        defer meta.deinit();
        var jobs = Store.init(testing.allocator, &meta);
        var parsed = (try jobs.get("job-1")).?;
        defer parsed.deinit();
        try testing.expectEqual(State.complete, parsed.value.state);
        try testing.expectEqual(@as(i64, 200), parsed.value.finished_at_us);
    }
}

// The import job store is metadata like any other, so it owes the same
// fail-closed guarantee the lifecycle phase, relay cursor, compaction
// watermark and merge cursor already prove: a read that fails, or a value that
// cannot be decoded, must propagate rather than be reported as absence.
// Reporting absence here would restart a partially-applied import from
// scratch, or resume one whose done-set could not be read.
test "job metadata read failure and corruption never read as absence" {
    const testing = std.testing;
    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();
    var root_buffer: [std.fs.max_path_bytes]u8 = undefined;
    const root_len = try tmp.dir.realPath(testing.io, &root_buffer);
    const root = root_buffer[0..root_len];

    var meta = try meta_store.Store.open(testing.allocator, root);
    defer meta.deinit();
    var jobs = Store.init(testing.allocator, &meta);
    try jobs.begin(.{
        .id = "job-fault",
        .csv_path = "/data/imports/a.csv",
        .submitted_at_us = 100,
        .rows_valid = 3,
    });

    // Absence is still absence: an id that was never written reads as null.
    try testing.expectEqual(@as(?ParsedRecord, null), try jobs.get("job-never-existed"));

    // A storage failure on the record is not absence.
    {
        const key = try recordKey(testing.allocator, "job-fault");
        defer testing.allocator.free(key);
        try testing.expect(meta_store.armReadFault(key, 1));
        defer meta_store.disarmReadFault();
        try testing.expectError(error.InjectedStoreFault, jobs.get("job-fault"));
    }

    // Nor is a storage failure on the current-job pointer.
    {
        try testing.expect(meta_store.armReadFault(current_key, 1));
        defer meta_store.disarmReadFault();
        try testing.expectError(error.InjectedStoreFault, jobs.current());
    }

    // An undecodable record surfaces rather than being skipped: resuming an
    // import whose record cannot be parsed would silently redo applied work.
    {
        const key = try recordKey(testing.allocator, "job-fault");
        defer testing.allocator.free(key);
        try meta.putDurable(key, "{not valid json");
        try testing.expectError(error.SyntaxError, jobs.get("job-fault"));
    }
}