query/commands/wire: trim the scan and request paths
Matching allocated an ArrayList per filter field per candidate document,
on the process-wide allocator, to hold what is almost always a single
value. Candidates now collect into a stack buffer that spills to the heap
only for arrays: measured 15.7 -> 12.0ms on a 65,536-document range scan.
The OOM-propagation test moves with it. Its point is that a failed
collection must surface as an error rather than an empty candidate list,
which would make $ne and $exists:false report a match -- a wrong answer
rather than a failed one. That invariant still holds on the spill path, so
the test now uses an array long enough to reach the allocator, and a new
test pins the flip side: the common single-value match now completes
correctly even when the allocator always fails, because it never calls it.
Query operators were dispatched by a chain of up to fourteen mem.eql per
value per document, with $gt/$gte/$lt/$lte re-comparing the operator name
inside the loop over candidate values. Names resolve to an enum once per
filter field. Command dispatch likewise walked a 30-entry table comparing
strings; it is a comptime StaticStringMap now.
Each request built a fresh reply arena and handed its pages straight back.
One reply per connection, reset between requests, keeps them.
countDocuments() arrives as [{$match: F}?, {$group: {_id: <literal>,
n: {$sum: 1}}}], which the general path answered by materializing every
matching document and discarding them all. It is now recognized and
answered from a counting scan: countDocuments({}) 2.3 -> 1.5ms.
The detector is deliberately conservative -- grouping by "$field", summing
a field, an unmodelled accumulator or any extra stage all fall through to
the general path, since those need the documents themselves. A unit test
pins each accept and reject, and the whole count path was checked against
the general one through the real driver, including the shapes that must
not take it.
The filtered range-scan row does not move: it is bound by walking 65,536
documents that each live in their own arena, not by the matcher. That is
Phase 4 work.
Verified: 77 unit tests under ReleaseFast and ReleaseSafe, e2e
29/16/17/3/2, the crash pair, e2e6 72/72.
This commit is contained in:
161
src/query.zig
161
src/query.zig
@@ -79,10 +79,20 @@ fn is_operator_doc(value: bson.Value) ?[]const bson.Pair {
|
||||
return pairs;
|
||||
}
|
||||
|
||||
/// Values a path yields before spilling to the heap. A document almost
|
||||
/// always contributes exactly one value per field; arrays make it a
|
||||
/// handful. Collecting those on the stack removes an allocate/free pair per
|
||||
/// filter field per candidate document, which is the dominant cost of a
|
||||
/// collection scan.
|
||||
const inline_candidates = 8;
|
||||
|
||||
fn field_matches(gpa: std.mem.Allocator, path: []const u8, expected: bson.Value, doc: *const bson.Document) QueryError!bool {
|
||||
var stack_fallback = std.heap.stackFallback(inline_candidates * @sizeOf(bson.Value), gpa);
|
||||
const alloc = stack_fallback.get();
|
||||
|
||||
var candidates: std.ArrayListUnmanaged(bson.Value) = .empty;
|
||||
defer candidates.deinit(gpa);
|
||||
try collect_values(gpa, doc.pairs, path, &candidates, 0);
|
||||
defer candidates.deinit(alloc);
|
||||
try collect_values(alloc, doc.pairs, path, &candidates, 0);
|
||||
// MongoDB applies queries to array elements as well as the array itself.
|
||||
// Index the snapshot length, re-reading items each iteration: appending
|
||||
// may reallocate the buffer, which would invalidate a captured slice.
|
||||
@@ -91,20 +101,21 @@ fn field_matches(gpa: std.mem.Allocator, path: []const u8, expected: bson.Value,
|
||||
while (i < direct_count) : (i += 1) {
|
||||
const a = candidates.items[i];
|
||||
if (a == .array) {
|
||||
for (a.array) |elem| try candidates.append(gpa, elem);
|
||||
for (a.array) |elem| try candidates.append(alloc, elem);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_operator_doc(expected)) |pairs| {
|
||||
// $options modifies $regex wherever it appears in the document, so
|
||||
// it has to be known before any operator runs.
|
||||
var options: []const u8 = "";
|
||||
for (pairs) |p| {
|
||||
if (std.mem.eql(u8, p.key, "$options")) {
|
||||
if (p.value == .string) options = p.value.string;
|
||||
}
|
||||
if (parse_op(p.key) == .options and p.value == .string) options = p.value.string;
|
||||
}
|
||||
for (pairs) |p| {
|
||||
if (std.mem.eql(u8, p.key, "$options")) continue;
|
||||
if (!try match_operator(gpa, p.key, p.value, candidates.items, options)) return false;
|
||||
const op = parse_op(p.key);
|
||||
if (op == .options) continue;
|
||||
if (!try match_operator(gpa, op, p.value, candidates.items, options)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -122,33 +133,79 @@ fn field_matches(gpa: std.mem.Allocator, path: []const u8, expected: bson.Value,
|
||||
return false;
|
||||
}
|
||||
|
||||
fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, actuals: []const bson.Value, regex_options: []const u8) QueryError!bool {
|
||||
if (std.mem.eql(u8, op, "$eq")) {
|
||||
/// The query operators, resolved from their names once per filter field
|
||||
/// instead of re-comparing strings for every candidate document.
|
||||
const Op = enum {
|
||||
eq,
|
||||
ne,
|
||||
gt,
|
||||
gte,
|
||||
lt,
|
||||
lte,
|
||||
in,
|
||||
nin,
|
||||
exists,
|
||||
regex,
|
||||
options,
|
||||
not,
|
||||
size,
|
||||
all,
|
||||
elem_match,
|
||||
/// Not an operator we implement; matches nothing, as before.
|
||||
unknown,
|
||||
};
|
||||
|
||||
const op_names = std.StaticStringMap(Op).initComptime(.{
|
||||
.{ "$eq", .eq },
|
||||
.{ "$ne", .ne },
|
||||
.{ "$gt", .gt },
|
||||
.{ "$gte", .gte },
|
||||
.{ "$lt", .lt },
|
||||
.{ "$lte", .lte },
|
||||
.{ "$in", .in },
|
||||
.{ "$nin", .nin },
|
||||
.{ "$exists", .exists },
|
||||
.{ "$regex", .regex },
|
||||
.{ "$options", .options },
|
||||
.{ "$not", .not },
|
||||
.{ "$size", .size },
|
||||
.{ "$all", .all },
|
||||
.{ "$elemMatch", .elem_match },
|
||||
});
|
||||
|
||||
fn parse_op(name: []const u8) Op {
|
||||
return op_names.get(name) orelse .unknown;
|
||||
}
|
||||
|
||||
fn match_operator(gpa: std.mem.Allocator, op: Op, value: bson.Value, actuals: []const bson.Value, regex_options: []const u8) QueryError!bool {
|
||||
if (op == .eq) {
|
||||
for (actuals) |a| if (bson.compare(a, value) == .eq) return true;
|
||||
return false;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$ne")) {
|
||||
if (op == .ne) {
|
||||
for (actuals) |a| if (bson.compare(a, value) == .eq) return false;
|
||||
return true;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$gt") or std.mem.eql(u8, op, "$gte") or
|
||||
std.mem.eql(u8, op, "$lt") or std.mem.eql(u8, op, "$lte"))
|
||||
{
|
||||
if (op == .gt or op == .gte or op == .lt or op == .lte) {
|
||||
for (actuals) |a| {
|
||||
const o = bson.compare(a, value);
|
||||
if (std.mem.eql(u8, op, "$gt") and o == .gt) return true;
|
||||
if (std.mem.eql(u8, op, "$gte") and o != .lt) return true;
|
||||
if (std.mem.eql(u8, op, "$lt") and o == .lt) return true;
|
||||
if (std.mem.eql(u8, op, "$lte") and o != .gt) return true;
|
||||
const hit = switch (op) {
|
||||
.gt => o == .gt,
|
||||
.gte => o != .lt,
|
||||
.lt => o == .lt,
|
||||
.lte => o != .gt,
|
||||
else => unreachable,
|
||||
};
|
||||
if (hit) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$in") or std.mem.eql(u8, op, "$nin")) {
|
||||
if (op == .in or op == .nin) {
|
||||
const members = switch (value) {
|
||||
.array => |arr| arr,
|
||||
else => return false,
|
||||
};
|
||||
const want_in = std.mem.eql(u8, op, "$in");
|
||||
const want_in = op == .in;
|
||||
for (actuals) |a| {
|
||||
for (members) |m| {
|
||||
if (bson.compare(a, m) == .eq) return want_in;
|
||||
@@ -156,14 +213,14 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
}
|
||||
return !want_in;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$exists")) {
|
||||
if (op == .exists) {
|
||||
const want = switch (value) {
|
||||
.bool => |b| b,
|
||||
else => return false,
|
||||
};
|
||||
return (actuals.len > 0) == want;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$regex")) {
|
||||
if (op == .regex) {
|
||||
const pattern = switch (value) {
|
||||
.string => |s| s,
|
||||
.doc => |pairs| blk: {
|
||||
@@ -180,7 +237,7 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$not")) {
|
||||
if (op == .not) {
|
||||
const pairs = is_operator_doc(value) orelse {
|
||||
// $not with a bare value means $ne-ish semantics; treat as
|
||||
// "not equal to this regex or value".
|
||||
@@ -193,11 +250,11 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
return false;
|
||||
};
|
||||
for (pairs) |p| {
|
||||
if (try match_operator(gpa, p.key, p.value, actuals, regex_options)) return false;
|
||||
if (try match_operator(gpa, parse_op(p.key), p.value, actuals, regex_options)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$size")) {
|
||||
if (op == .size) {
|
||||
const want = switch (value) {
|
||||
.int32 => |i| i,
|
||||
.int64 => |i| @as(i32, @intCast(i)),
|
||||
@@ -208,7 +265,7 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$all")) {
|
||||
if (op == .all) {
|
||||
const members = switch (value) {
|
||||
.array => |arr| arr,
|
||||
else => return false,
|
||||
@@ -225,7 +282,7 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (std.mem.eql(u8, op, "$elemMatch")) {
|
||||
if (op == .elem_match) {
|
||||
const operand = switch (value) {
|
||||
.doc => |pairs| pairs,
|
||||
else => return false,
|
||||
@@ -238,7 +295,7 @@ fn match_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, act
|
||||
var single: [1]bson.Value = .{elem};
|
||||
var ok = true;
|
||||
for (operand) |p| {
|
||||
if (!try match_operator(gpa, p.key, p.value, single[0..], "")) {
|
||||
if (!try match_operator(gpa, parse_op(p.key), p.value, single[0..], "")) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
@@ -930,12 +987,18 @@ test "multikey path with several array candidates does not use-after-free" {
|
||||
}
|
||||
|
||||
test "OOM during value collection propagates, not a false match" {
|
||||
// A tiny FixedBufferAllocator makes the candidate collection fail; the
|
||||
// error must surface instead of leaving an empty candidate list, which
|
||||
// would make negating operators like $ne report a match.
|
||||
const d = doc_of(&.{.{ .key = "x", .value = .{ .int32 = 5 } }});
|
||||
const ne = doc_of(&.{.{ .key = "x", .value = .{ .doc = &.{.{ .key = "$ne", .value = .{ .int32 = 5 } }} } }});
|
||||
// Candidate collection failing must surface as an error rather than
|
||||
// leaving an empty candidate list, which would make negating operators
|
||||
// like $ne and $exists:false report a match — a wrong answer, not a
|
||||
// failed one.
|
||||
//
|
||||
// Collection only reaches the allocator once a path yields more than
|
||||
// `inline_candidates` values, so use an array long enough to spill.
|
||||
var many: [32]bson.Value = undefined;
|
||||
for (&many, 0..) |*v, i| v.* = .{ .int32 = @intCast(i) };
|
||||
const d = doc_of(&.{.{ .key = "x", .value = .{ .array = &many } }});
|
||||
|
||||
const ne = doc_of(&.{.{ .key = "x", .value = .{ .doc = &.{.{ .key = "$ne", .value = .{ .int32 = 999 } }} } }});
|
||||
var buf: [16]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
||||
try testing.expectError(error.OutOfMemory, matches(fba.allocator(), &ne, &d));
|
||||
@@ -944,6 +1007,36 @@ test "OOM during value collection propagates, not a false match" {
|
||||
try testing.expectError(error.OutOfMemory, matches(fba.allocator(), &ex, &d));
|
||||
}
|
||||
|
||||
test "the common single-value match needs no allocator at all" {
|
||||
// The counterpart to the test above: a field yielding a handful of
|
||||
// values is collected on the stack, so a scan does not allocate per
|
||||
// filter field per document. A failing allocator must therefore still
|
||||
// produce the correct answer rather than an error.
|
||||
const d = doc_of(&.{
|
||||
.{ .key = "x", .value = .{ .int32 = 5 } },
|
||||
.{ .key = "s", .value = .{ .string = "hi" } },
|
||||
});
|
||||
|
||||
var buf: [0]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&buf);
|
||||
const failing = fba.allocator();
|
||||
|
||||
const eq = doc_of(&.{.{ .key = "x", .value = .{ .int32 = 5 } }});
|
||||
try testing.expect(try matches(failing, &eq, &d));
|
||||
|
||||
const ne = doc_of(&.{.{ .key = "x", .value = .{ .doc = &.{.{ .key = "$ne", .value = .{ .int32 = 5 } }} } }});
|
||||
try testing.expect(!try matches(failing, &ne, &d));
|
||||
|
||||
const missing = doc_of(&.{.{ .key = "zz", .value = .{ .doc = &.{.{ .key = "$exists", .value = .{ .bool = false } }} } }});
|
||||
try testing.expect(try matches(failing, &missing, &d));
|
||||
|
||||
const range = doc_of(&.{.{ .key = "x", .value = .{ .doc = &.{
|
||||
.{ .key = "$gte", .value = .{ .int32 = 1 } },
|
||||
.{ .key = "$lt", .value = .{ .int32 = 10 } },
|
||||
} } }});
|
||||
try testing.expect(try matches(failing, &range, &d));
|
||||
}
|
||||
|
||||
test "documents compare by field name too" {
|
||||
try testing.expectEqual(std.math.Order.lt, bson.compare(
|
||||
.{ .doc = &.{.{ .key = "a", .value = .{ .int32 = 1 } }} },
|
||||
@@ -1195,5 +1288,5 @@ test "and/or filters" {
|
||||
/// Public single-value operator matcher, used by $pull and $elemMatch.
|
||||
pub fn value_matches_operator(gpa: std.mem.Allocator, op: []const u8, value: bson.Value, actual: bson.Value) QueryError!bool {
|
||||
var single: [1]bson.Value = .{actual};
|
||||
return match_operator(gpa, op, value, single[0..], "");
|
||||
return match_operator(gpa, parse_op(op), value, single[0..], "");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user