Skip to content

Commit 00a9e05

Browse files
jschmiedashhart
authored andcommitted
kv classes (ashhart#2444 C1): admission by owner class, the owner chosen once inside the reservation
Admit.need gives the pages a request needs a class (kv_classes.Need: one, or a spread for admission only). The lane host tests it in its ledger beside the family's fits, and refuses a request past a whole class by name even while other streams run. Gate.want takes a class, so a promise passes its class's test with the pool's bytes inside it. Pool.reserve picks the owner (a resumed prefix's class, else the roomiest) inside the reservation, and a failed one leaves the owner and every count as they were. No multi-class reclaim: joinReclaim still refuses above one class. At one class every answer is ashhart#2415's: the ledger-counted pool trace hash is the one ashhart#2415 records.
1 parent a4a76b9 commit 00a9e05

14 files changed

Lines changed: 629 additions & 34 deletions

‎zig/src/core/kv_classes.zig‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
//! Resource classes in admission (#2444 C1): the pages a request needs a class, tested by the ledger a class.
2+
const kv = @import("kv_ledger.zig");
3+
const Ledger = kv.Ledger;
4+
5+
/// Pages a request needs, by owner class (kv_pool_classes.zig: class c holds ids c, c + W, c + 2W ...).
6+
pub const Need = union(enum) {
7+
/// All `n` from one class: `in` when a resumed prefix fixed it, else the one the reservation chooses.
8+
one: One,
9+
/// Logical pages [k0, k1), page k from class k mod W (DeepSeek's span); admission only, no lease takes it yet.
10+
spread: Spread,
11+
12+
pub const One = struct { n: usize, in: ?u32 = null };
13+
pub const Spread = struct { k0: usize, k1: usize };
14+
15+
pub fn total(d: Need) usize {
16+
return switch (d) {
17+
.one => |o| o.n,
18+
.spread => |s| s.k1 - s.k0,
19+
};
20+
}
21+
22+
/// Of a spread over `w` classes, the pages class `c` gives.
23+
pub fn inClass(s: Spread, w: u32, c: u32) usize {
24+
return below(s.k1, w, c) - below(s.k0, w, c);
25+
}
26+
27+
/// Logical pages k < x with k mod w == c.
28+
fn below(x: usize, w: u32, c: u32) usize {
29+
return if (x > c) (x - c + w - 1) / w else 0;
30+
}
31+
};
32+
33+
/// Class `c` as the pool reads it; one class is the pool itself.
34+
fn class(l: *const Ledger, p: kv.Pages, c: u32) kv.Class {
35+
const k = l.pool.?;
36+
return if (k.class) |f| f(k.ctx, c) else .{ .cap = p.total, .available = p.available };
37+
}
38+
39+
/// Class `c`'s available pages at which `n` more fit there and in the pool's bytes (one class: exactly `want`).
40+
pub fn wantIn(l: *const Ledger, c: u32, n: usize) usize {
41+
const p = l.pages();
42+
if (p.classes <= 1) return l.want(n);
43+
return @max(n, class(l, p, c).available +| (l.want(n) -| p.available)); // short of the bytes: past what it has
44+
}
45+
46+
/// Whether `d` could be promised now: the pool's bytes, then each class it takes from.
47+
pub fn fitsNeed(l: *const Ledger, d: Need) bool {
48+
const p = l.pages();
49+
if (p.classes <= 1) return p.available + p.reclaimable >= l.want(d.total()); // one class: Pool.fits exactly
50+
if (p.available < l.want(d.total())) return false; // no store reclaims above one class (Pool.joinReclaim)
51+
switch (d) {
52+
.one => |o| {
53+
if (o.in) |c| return class(l, p, c).available >= o.n;
54+
for (0..p.classes) |c| if (class(l, p, @intCast(c)).available >= o.n) return true; // the roomiest's test
55+
return false;
56+
},
57+
.spread => |s| {
58+
for (0..p.classes) |c| if (class(l, p, @intCast(c)).available < Need.inClass(s, p.classes, @intCast(c))) return false;
59+
return true;
60+
},
61+
}
62+
}
63+
64+
/// The class `d` needs more of than it holds at all, so no release makes it fit (null: none; one class: never).
65+
pub fn neverNeed(l: *const Ledger, d: Need) ?u32 {
66+
const p = l.pages();
67+
if (p.classes <= 1) return null;
68+
switch (d) {
69+
.one => |o| return if (o.n > class(l, p, o.in orelse 0).cap) o.in orelse 0 else null, // classes are equal
70+
.spread => |s| {
71+
for (0..p.classes) |c| if (Need.inClass(s, p.classes, @intCast(c)) > class(l, p, @intCast(c)).cap) return @intCast(c);
72+
return null;
73+
},
74+
}
75+
}
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
//! Admission by owner class through a lane host (#2444 C1, tests 3 and 5): refused by name, or passed over in order.
2+
const std = @import("std");
3+
const lanes = @import("lanes");
4+
const api = @import("engine_api");
5+
const kv = @import("kv_pool");
6+
const LaneHost = api.LaneHost;
7+
const Reason = api.Reason;
8+
const Request = api.Request;
9+
const Need = api.kv_ledger.classes.Need;
10+
const expect = std.testing.expect;
11+
const equal = std.testing.expectEqual;
12+
13+
/// A family's pool in owner classes: a prompt's first token 100 or 101 fixes its class (a resumed prefix's), else none.
14+
const Pages = struct {
15+
pool: kv.Pool,
16+
leases: std.AutoHashMapUnmanaged(*const lanes.Stream, kv.Lease) = .empty,
17+
refused: usize = 0, // reservations that failed: admission let a request through that its class lacked
18+
19+
fn of(ctx: *anyopaque) *Pages {
20+
return @ptrCast(@alignCast(ctx));
21+
}
22+
23+
/// A page every four prompt tokens; the reply takes none (a stream may run long on a small lease).
24+
fn needOf(prompt: []const u32) Need {
25+
const in: ?u32 = if (prompt[0] == 100) 0 else if (prompt[0] == 101) 1 else null;
26+
return .{ .one = .{ .n = (prompt.len + 3) / 4, .in = in } };
27+
}
28+
29+
fn fits(ctx: *anyopaque, _: u32, _: u32) bool {
30+
return of(ctx).pool.available() > 0; // the family's own test: the class test is the host's
31+
}
32+
33+
var prompts: [8][]const u32 = undefined; // need's view of a request by its length (lengths differ in a test)
34+
fn need(_: *anyopaque, prompt: u32, _: u32) Need {
35+
for (prompts) |p| if (p.len == prompt) return needOf(p);
36+
unreachable;
37+
}
38+
39+
fn take(ctx: *anyopaque, s: *lanes.Stream) anyerror!void {
40+
const p = of(ctx);
41+
var l: kv.Lease = .{};
42+
errdefer p.pool.finish(&l);
43+
const d = needOf(s.prompt()).one;
44+
p.pool.reserve(&l, d.n, d.in) catch |e| {
45+
p.refused += 1;
46+
return e;
47+
};
48+
try p.pool.cover(&l, d.n, null);
49+
try p.leases.put(std.testing.allocator, s, l);
50+
}
51+
52+
fn give(ctx: *anyopaque, s: *lanes.Stream) void {
53+
const p = of(ctx);
54+
var e = p.leases.fetchRemove(s) orelse return;
55+
p.pool.finish(&e.value);
56+
}
57+
58+
fn deinit(p: *Pages) void {
59+
p.leases.deinit(std.testing.allocator);
60+
p.pool.deinit();
61+
}
62+
};
63+
64+
const Box = struct {
65+
mutex: std.Io.Mutex = .init,
66+
done: ?Reason = null,
67+
message: []const u8 = "",
68+
tokens: usize = 0,
69+
fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void {
70+
const b: *@This() = @ptrCast(@alignCast(ctx));
71+
b.mutex.lockUncancelable(std.testing.io);
72+
defer b.mutex.unlock(std.testing.io);
73+
switch (e.*) {
74+
.tokens => |t| b.tokens += t.len,
75+
.finished => |f| {
76+
b.done = f.reason;
77+
b.message = f.message;
78+
},
79+
else => {},
80+
}
81+
}
82+
fn state(b: *@This()) struct { usize, ?Reason } {
83+
b.mutex.lockUncancelable(std.testing.io);
84+
defer b.mutex.unlock(std.testing.io);
85+
return .{ b.tokens, b.done };
86+
}
87+
fn waitFor(b: *@This(), ms: usize) ?Reason {
88+
for (0..ms) |_| {
89+
if (b.state()[1]) |r| return r;
90+
std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {};
91+
}
92+
return b.state()[1];
93+
}
94+
fn startsWithin(b: *@This(), ms: usize) bool {
95+
for (0..ms) |_| {
96+
if (b.state()[0] > 0) return true;
97+
std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {};
98+
}
99+
return b.state()[0] > 0;
100+
}
101+
};
102+
103+
/// A host over the fake target whose lanes reserve from `pages`, its pool counted in the host's ledger.
104+
const Rig = struct {
105+
cfg: lanes.Config,
106+
target: lanes.fake.Fake,
107+
clock: lanes.fake.FixedClock = .{},
108+
core: lanes.Engine,
109+
host: LaneHost,
110+
111+
fn start(r: *Rig, pages: *Pages) !void {
112+
const gpa = std.testing.allocator;
113+
r.cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7);
114+
errdefer r.cfg.deinit(gpa);
115+
r.target = .{ .gpa = gpa, .reserve = .{ .ctx = pages, .take = Pages.take, .give = Pages.give } };
116+
errdefer r.target.deinit();
117+
r.clock = .{};
118+
r.core = lanes.Engine.init(gpa, &r.cfg, r.target.backend(), r.clock.clock());
119+
errdefer r.core.deinit();
120+
const admit: api.Admit = .{ .ctx = pages, .fits = Pages.fits, .need = Pages.need };
121+
r.host = LaneHost.init(gpa, std.testing.io, &r.core, .{ .lanes = 3, .admit = admit });
122+
try r.host.countPool(&pages.pool);
123+
try r.host.start();
124+
}
125+
126+
fn stop(r: *Rig) void {
127+
r.host.stop();
128+
r.core.deinit();
129+
r.target.deinit();
130+
r.cfg.deinit(std.testing.allocator);
131+
}
132+
};
133+
134+
const run_long = 100000; // a reply that runs until it is cancelled
135+
const small: [8]u32 = .{ 3, 1, 4, 1, 5, 9, 2, 6 }; // 2 pages, any class
136+
const nine: [36]u32 = @splat(7); // 9 pages: more than a class of 8 holds
137+
138+
/// Test 3 on `classes` classes of 16 pages: a running stream, then a request of 9 pages; its end, or null.
139+
fn pastClass(classes: u32, box: *Box) !struct { ?Reason, usize } {
140+
var pages: Pages = .{ .pool = try kv.Pool.initClasses(std.testing.allocator, 16, 4, classes) };
141+
defer pages.deinit();
142+
Pages.prompts = .{ &small, &nine, &small, &small, &small, &small, &small, &small };
143+
var rig: Rig = undefined;
144+
try rig.start(&pages);
145+
defer rig.stop();
146+
const e = rig.host.engine();
147+
var a: Box = .{};
148+
try e.submit(1, &.{ .prompt = &small, .max_tokens = run_long }, .{ .ctx = &a, .event = Box.event });
149+
try expect(a.startsWithin(2000));
150+
try e.submit(2, &.{ .prompt = &nine, .max_tokens = 4 }, .{ .ctx = box, .event = Box.event });
151+
const end = box.waitFor(1000);
152+
const promised = pages.pool.census().promised + pages.pool.census().leased; // a's 2 only, if 2 took nothing
153+
e.cancel(1);
154+
try equal(@as(?Reason, .cancelled), a.waitFor(2000));
155+
_ = box.waitFor(2000);
156+
try equal(@as(usize, 0), pages.refused);
157+
return .{ end, promised };
158+
}
159+
160+
test "kv classes 3: a request past a whole class is refused at once by name, while another stream runs" {
161+
var b: Box = .{};
162+
const end, const held = try pastClass(2, &b);
163+
try equal(@as(?Reason, .failed), end); // not left queued for room no release can give
164+
try expect(std.mem.indexOf(u8, b.message, "KV owner class") != null); // the refusal names the class
165+
try equal(@as(usize, 0), b.state()[0]);
166+
try equal(@as(usize, 2), held); // nothing promised or taken for it before the refusal
167+
var one: Box = .{};
168+
const end1, _ = try pastClass(1, &one); // one class of 16: the same request runs, as on #2415
169+
try equal(@as(?Reason, .length), end1);
170+
}
171+
172+
test "kv classes 5: a head waiting on class 0 lets a later request for class 1 go first, then runs" {
173+
var pages: Pages = .{ .pool = try kv.Pool.initClasses(std.testing.allocator, 16, 4, 2) };
174+
defer pages.deinit();
175+
const six: [24]u32 = .{100} ++ @as([23]u32, @splat(7)); // class 0, 6 pages
176+
const four: [16]u32 = .{100} ++ @as([15]u32, @splat(7)); // class 0, 4 pages: 2 left there
177+
const three: [12]u32 = .{101} ++ @as([11]u32, @splat(7)); // class 1, 3 pages
178+
Pages.prompts = .{ &six, &four, &three, &small, &small, &small, &small, &small };
179+
var rig: Rig = undefined;
180+
try rig.start(&pages);
181+
defer rig.stop();
182+
const e = rig.host.engine();
183+
var a: Box = .{};
184+
var head: Box = .{};
185+
var late: Box = .{};
186+
try e.submit(1, &.{ .prompt = &six, .max_tokens = run_long }, .{ .ctx = &a, .event = Box.event });
187+
try expect(a.startsWithin(2000));
188+
try e.submit(2, &.{ .prompt = &four, .max_tokens = 4 }, .{ .ctx = &head, .event = Box.event });
189+
try e.submit(3, &.{ .prompt = &three, .max_tokens = 4 }, .{ .ctx = &late, .event = Box.event });
190+
try equal(@as(?Reason, .length), late.waitFor(2000)); // class 1 has room: it does not wait behind the head
191+
try equal(@as(usize, 0), head.state()[0]); // 10 pages free in all, 2 in class 0: the head still waits
192+
try equal(@as(usize, 0), pages.refused); // and was never let through to a reservation that fails
193+
e.cancel(1);
194+
try equal(@as(?Reason, .cancelled), a.waitFor(2000));
195+
try equal(@as(?Reason, .length), head.waitFor(2000));
196+
try equal(@as(usize, 0), pages.refused);
197+
try expect(pages.pool.idle());
198+
}

0 commit comments

Comments
 (0)