Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Server: temporaries a crash left beside notes and the `--slide-graph` file are cleared when the server opens their folders, only the server's own and only when their process is gone (#3132).

- LFM2.5-24B-A2B on CUDA: the five prompt-stream writes whose state a prompt-cache keep copies (a slot clear, a prompt chunk, a one-row step, a verify round and a commit) take their stream from one helper that first waits for the keeps' copies, and a host test fails if a write skips it. Replies are unchanged (#2989, after #1503). Thanks to @jschmied.

- Environment: the Metal Qwen KV paging and slot-resume switches and the slide checks refuse a malformed value by name, and `TF_SLIDE_TAKE_OUT_CHECK` is read once at start with `--slide` (#3018, for #2370).
Expand Down
44 changes: 44 additions & 0 deletions zig/src/platform/atomic_file.zig
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,50 @@ pub fn replacePrivate(a: Allocator, path: []const u8, parts: []const []const u8)
try commit(a, try stagePrivate(a, path, parts), path);
}

/// Clears the `<file>.tmp.<pid>.<serial>` a crash left in `dir` (only `only`'s when given); live writers keep theirs.
pub fn discardStale(io: std.Io, dir: []const u8, only: ?[]const u8) void {
var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return;
defer d.close(io);
var it = d.iterate();
while (it.next(io) catch null) |entry| {
if (entry.kind != .file) continue;
const staged = stagedBy(entry.name) orelse continue;
if (only) |file| if (!std.mem.eql(u8, staged.file, file)) continue;
const stale = if (platform.windows) blk: {
// no portable way to ask whether a pid lives: a day-old temporary is stale
const cutoff = std.Io.Clock.real.now(io).subDuration(.{ .nanoseconds = 86_400 * std.time.ns_per_s });
const st = d.statFile(io, entry.name, .{}) catch continue;
break :blk st.mtime.nanoseconds < cutoff.nanoseconds;
} else writerGone(staged.pid);
if (stale) d.deleteFile(io, entry.name) catch {};
}
}

/// The file and writer's pid when `name` is exactly `<file>.tmp.<pid>.<serial>`, as `stageAs` prints them.
fn stagedBy(name: []const u8) ?struct { file: []const u8, pid: i32 } {
const at = std.mem.lastIndexOf(u8, name, ".tmp.") orelse return null;
if (at == 0) return null;
const rest = name[at + ".tmp.".len ..];
const dot = std.mem.indexOfScalar(u8, rest, '.') orelse return null;
if (!decimal(rest[0..dot]) or !decimal(rest[dot + 1 ..])) return null;
const pid = std.fmt.parseInt(i32, rest[0..dot], 10) catch return null;
if (pid <= 0) return null;
return .{ .file = name[0..at], .pid = pid };
}

/// Digits as `{d}` prints them: at least one, no sign, separator or leading zero.
fn decimal(text: []const u8) bool {
if (text.len == 0 or (text.len > 1 and text[0] == '0')) return false;
for (text) |ch| if (!std.ascii.isDigit(ch)) return false;
return true;
}

fn writerGone(pid: i32) bool {
if (platform.windows) return false; // discardStale uses the age fallback there
if (platform.c.kill(pid, @fromBackingInt(@intCast(0))) == 0) return false;
return platform.c.errno(-1) == .SRCH;
}

fn writeAll(fd: platform.c.fd_t, bytes: []const u8) !void {
var done: usize = 0;
while (done < bytes.len) {
Expand Down
10 changes: 5 additions & 5 deletions zig/src/server/compact_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ const Stay = struct {
}
};

const Text = struct {
pub const Text = struct {
reasoning: bool = false,
fn text(t: *@This()) model_text.Text {
pub fn text(t: *@This()) model_text.Text {
return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } };
}

Expand Down Expand Up @@ -126,15 +126,15 @@ const Text = struct {
}
};

const Eng = struct {
pub const Eng = struct {
window: u32,
cache: bool = false,
prompts: std.ArrayList([]u8) = .empty,
opened: bool = false,
early: usize = 0,
late: usize = 0,

fn engine(e: *Eng) api.Engine {
pub fn engine(e: *Eng) api.Engine {
return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } };
}

Expand Down Expand Up @@ -165,7 +165,7 @@ const Eng = struct {
}
};

fn freePrompts(e: *Eng) void {
pub fn freePrompts(e: *Eng) void {
for (e.prompts.items) |p| gpa.free(p);
e.prompts.deinit(gpa);
}
Expand Down
42 changes: 42 additions & 0 deletions zig/src/server/private_files_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const json = @import("json");
const compact_mem = @import("compact_mem.zig");
const server = @import("server.zig");
const Graph = @import("slide_graph.zig").Graph;
const fakes = @import("compact_test.zig");
const testing = std.testing;
const io = testing.io;

Expand Down Expand Up @@ -95,3 +96,44 @@ test "security: the fact graph is owner-only and is not written through a plante
defer again.deinit();
try testing.expectEqual(@as(usize, 1), again.facts.items.len);
}

test "a server open clears a crash's stale temporaries but keeps a live writer's and every other file" {
// the pid check is POSIX's; Windows' day-old fallback would need Dir.setTimestamps, which Zig 0.17 lacks there
if (platform.windows) return error.SkipZigTest;
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(io, "notes");
try tmp.dir.createDirPath(io, "graphs");
const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
const live = try std.fmt.allocPrint(a, ".tmp.{d}.0", .{platform.c.getpid()});
// no process has pid 999999999 (Linux's pid_max is at most 2^22, macOS's 99999)
const stale = [_][]const u8{ "notes/k.md.tmp.999999999.0", "notes/k.json.tmp.999999999.12", "graphs/graph.json.tmp.999999999.3" };
const kept = [_][]const u8{
"notes/k.md", "notes/k.md.tmp.not-a-pid.0",
"notes/k.md.tmp.+999999999.0", "notes/k.md.tmp.999999999.0.extra",
"notes/k.md.tmp.0999999999.0", "notes/k.md.tmp.999_999_999.0",
"notes/k.md.tmp.0.0", "notes/k.md.tmp.4294967295.0",
"notes/.tmp.999999999.0",
"graphs/other.json.tmp.999999999.0", // another file's, in a folder the graph may share
try std.fmt.allocPrint(a, "notes/k.md{s}", .{live}),
try std.fmt.allocPrint(a, "graphs/graph.json{s}", .{live}),
};
for (stale ++ kept) |name| try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "x" });

var eng: fakes.Eng = .{ .window = 256 };
defer fakes.freePrompts(&eng);
var text: fakes.Text = .{};
const srv = try server.Server.init(testing.allocator, io, eng.engine(), text.text(), .{
.served_name = "m",
.model_ids = &.{"m"},
.compact_memory = try std.fmt.allocPrint(a, "{s}/notes", .{root}),
.slide_graph = try std.fmt.allocPrint(a, "{s}/graphs/graph.json", .{root}),
}, null);
defer srv.deinit();

for (stale) |name| try testing.expectError(error.FileNotFound, tmp.dir.statFile(io, name, .{}));
for (kept) |name| _ = try tmp.dir.statFile(io, name, .{});
}
4 changes: 2 additions & 2 deletions zig/src/server/server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ pub const Config = struct {
silence_mid: bool = false,
silence_guard: bool = false,
cfg: ?@import("drama_cfg.zig").Options = null,
/// --prompt-seed keeps historical prompt-keyed sampling when a request omits its seed.
prompt_seed: bool = false,
prompt_seed: bool = false, // --prompt-seed: historical prompt-keyed sampling when a request omits its seed
/// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere.
request_log: ?[]const u8 = null,
/// TENSORFOLD_PHASE_METRICS=1: /metrics adds the queue phase's histogram; unset, its families are as before.
Expand Down Expand Up @@ -201,6 +200,7 @@ pub const Server = struct {
srv.* = .{ .tool_ids = tool_ids, .gpa = gpa, .io = io, .engine = engine, .info = engine.info(), .text = text, .config = config, .keys = keys, .metrics = .{ .gpa = gpa, .phases = config.phase_metrics }, .load = .init(io), .store = .{ .gpa = gpa }, .arena = .init(gpa), .slide = .init(gpa, io, config.slide_graph), .teacher = .init(gpa) };
srv.config.tool_id_key = null; // its key is zeroed: `tool_ids` is the one copy
errdefer srv.deinit(); // a later step's failure stops the keepalive before the caller closes the engine
@import("stale_temps.zig").discard(io, config); // a crash's temporaries beside the note and the graph
if (srv.info.embeddings != null and srv.info.capability(.text_generation)) return error.InvalidEmbeddingCapabilities;
if (srv.info.readouts != null and (srv.info.capability(.text_generation) or srv.info.embeddings != null)) return error.InvalidReadoutCapabilities;
if (srv.info.vision) |vision| if (@import("vision_markers.zig").firstUnsafe(text, vision)) |id| {
Expand Down
10 changes: 10 additions & 0 deletions zig/src/server/stale_temps.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! A crash between a note's or the graph's write and its rename leaves a temporary: cleared at server open.
const std = @import("std");
const platform = @import("sys");
const Config = @import("server.zig").Config;

/// Each temporary left in the stored note's folder and beside the fact graph, removed.
pub fn discard(io: std.Io, config: Config) void {
if (config.compact_memory) |dir| platform.atomic_file.discardStale(io, dir, null);
if (config.slide_graph) |path| platform.atomic_file.discardStale(io, std.fs.path.dirname(path) orelse ".", std.fs.path.basename(path));
}
Loading