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
//! 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"));
}
}