rufio 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +8 -3
  4. data/README_ja.md +7 -3
  5. data/Rakefile +5 -0
  6. data/SECURITY.md +2 -2
  7. data/docs/guide.md +41 -8
  8. data/docs/guide_ja.md +41 -8
  9. data/docs/native_fuzzy_search_design_ja.md +684 -0
  10. data/info/help.md +13 -4
  11. data/info/keybindings.md +5 -3
  12. data/info/welcome.md +2 -2
  13. data/lib/rufio/config.rb +0 -2
  14. data/lib/rufio/config_loader.rb +24 -4
  15. data/lib/rufio/fuzzy_candidate_block.rb +131 -0
  16. data/lib/rufio/fuzzy_candidate_cache.rb +258 -0
  17. data/lib/rufio/fuzzy_file_source.rb +180 -0
  18. data/lib/rufio/fuzzy_finder.rb +313 -0
  19. data/lib/rufio/fuzzy_preview_loader.rb +107 -0
  20. data/lib/rufio/fuzzy_search.rb +327 -0
  21. data/lib/rufio/fuzzy_search_session.rb +426 -0
  22. data/lib/rufio/global_search.rb +292 -51
  23. data/lib/rufio/health_checker.rb +0 -22
  24. data/lib/rufio/help_menu.rb +5 -4
  25. data/lib/rufio/keybind_handler.rb +6 -5
  26. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  27. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  28. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  29. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  30. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  31. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  32. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  33. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  34. data/lib/rufio/native_content_search.rb +43 -7
  35. data/lib/rufio/native_scanner_zig.rb +17 -0
  36. data/lib/rufio/rga_result_source.rb +89 -0
  37. data/lib/rufio/screen.rb +5 -1
  38. data/lib/rufio/search_controller.rb +56 -54
  39. data/lib/rufio/terminal_ui.rb +70 -8
  40. data/lib/rufio/ui_renderer.rb +1 -1
  41. data/lib/rufio/version.rb +1 -1
  42. data/lib/rufio.rb +6 -0
  43. data/lib_zig/rufio_native/Makefile +16 -2
  44. data/lib_zig/rufio_native/build.zig +8 -0
  45. data/lib_zig/rufio_native/src/fuzzy.zig +520 -0
  46. data/lib_zig/rufio_native/src/fuzzy_test.zig +212 -0
  47. data/lib_zig/rufio_native/src/main.zig +27 -0
  48. data/lib_zig/rufio_native/src/search.zig +221 -44
  49. metadata +13 -2
@@ -0,0 +1,212 @@
1
+ const std = @import("std");
2
+ const fuzzy = @import("fuzzy.zig");
3
+
4
+ test "retains candidates, returns ranked top K and UTF-8 byte positions" {
5
+ var engine = fuzzy.Engine.init(std.testing.allocator);
6
+ defer engine.deinit();
7
+ try engine.add("a___ab\x00ab\x00日本語/検索.rb\x00");
8
+ try engine.query("ab", 1);
9
+ try std.testing.expectEqual(@as(u64, 2), engine.total);
10
+ try std.testing.expectEqual(@as(usize, 1), engine.matches.items.len);
11
+ try std.testing.expectEqual(@as(usize, 1), engine.matches.items[0].id);
12
+ try engine.query("日検", 10);
13
+ try std.testing.expectEqual(@as(u64, 1), engine.total);
14
+ const data = engine.output.items;
15
+ try std.testing.expectEqual(@as(u32, 0), std.mem.readInt(u32, data[32..36], .little));
16
+ try std.testing.expectEqual(@as(u32, 10), std.mem.readInt(u32, data[36..40], .little));
17
+ try engine.add("ab\x00");
18
+ try engine.query("ab", 10);
19
+ try std.testing.expectEqual(@as(usize, 1), engine.matches.items[0].id);
20
+ try std.testing.expectEqual(@as(usize, 3), engine.matches.items[1].id);
21
+ }
22
+
23
+ test "invalid UTF-8 and missing delimiters are rejected before adding" {
24
+ var engine = fuzzy.Engine.init(std.testing.allocator);
25
+ defer engine.deinit();
26
+ try std.testing.expectError(error.InvalidInput, engine.add("ok\x00\xff\x00"));
27
+ try std.testing.expectEqual(@as(usize, 0), engine.count());
28
+ try std.testing.expectError(error.InvalidInput, engine.add("unterminated"));
29
+ try std.testing.expectError(error.InvalidInput, engine.query("\xff", 1));
30
+ }
31
+
32
+ test "allocation failure releases partial candidates and search workspaces" {
33
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationScenario, .{});
34
+ }
35
+
36
+ fn allocationScenario(allocator: std.mem.Allocator) !void {
37
+ var engine = fuzzy.Engine.init(allocator);
38
+ defer engine.deinit();
39
+ try engine.add("a___ab\x00ab\x00日本語/検索.rb\x00");
40
+ try engine.query("ab", 2);
41
+ try engine.query("abb", 2);
42
+ try engine.add("xab\x00");
43
+ try engine.query("ab", 2);
44
+ try engine.query("", 1);
45
+ }
46
+
47
+ test "allocation failure during parallel scoring releases worker buffers" {
48
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, parallelAllocationScenario, .{});
49
+ }
50
+
51
+ fn parallelAllocationScenario(allocator: std.mem.Allocator) !void {
52
+ var engine = fuzzy.Engine.init(allocator);
53
+ defer engine.deinit();
54
+ engine.threads = 3;
55
+ engine.min_parallel = 0;
56
+ try engine.add("a___ab\x00ab\x00日本語/検索.rb\x00b\x00bab\x00");
57
+ try engine.query("ab", 2);
58
+ try engine.query("ab", 0);
59
+ }
60
+
61
+ /// Deterministic path-like candidates, NUL separated and terminated.
62
+ fn buildCandidates(allocator: std.mem.Allocator, count: usize, seed: u64) ![]u8 {
63
+ const parts = [_][]const u8{ "lib", "src", "search", "controller", "Screen", "_", "-", ".rb", "/", "日本", "検索", "😀", "a", "B", "ctrl", "test" };
64
+ var prng = std.Random.DefaultPrng.init(seed);
65
+ const random = prng.random();
66
+ var out: std.ArrayList(u8) = .empty;
67
+ errdefer out.deinit(allocator);
68
+ for (0..count) |_| {
69
+ const pieces = random.intRangeAtMost(usize, 1, 12);
70
+ for (0..pieces) |_| try out.appendSlice(allocator, parts[random.uintLessThan(usize, parts.len)]);
71
+ try out.append(allocator, 0);
72
+ }
73
+ return out.toOwnedSlice(allocator);
74
+ }
75
+
76
+ fn freshOutput(allocator: std.mem.Allocator, batches: []const []const u8, text: []const u8, limit: usize) ![]u8 {
77
+ var engine = fuzzy.Engine.init(allocator);
78
+ defer engine.deinit();
79
+ engine.threads = 1;
80
+ for (batches) |batch| try engine.add(batch);
81
+ try engine.query(text, limit);
82
+ return allocator.dupe(u8, engine.output.items);
83
+ }
84
+
85
+ test "narrowing from the previous query returns identical results and scores fewer candidates" {
86
+ const allocator = std.testing.allocator;
87
+ const first = try buildCandidates(allocator, 3000, 1);
88
+ defer allocator.free(first);
89
+ const second = try buildCandidates(allocator, 500, 2);
90
+ defer allocator.free(second);
91
+ var engine = fuzzy.Engine.init(allocator);
92
+ defer engine.deinit();
93
+ engine.threads = 1;
94
+ try engine.add(first);
95
+
96
+ const typing = [_][]const u8{ "s", "sc", "sct", "sctr", "sctrl" };
97
+ var previous_scanned: usize = engine.count();
98
+ for (typing, 0..) |text, index| {
99
+ try engine.query(text, 50);
100
+ const expected = try freshOutput(allocator, &.{first}, text, 50);
101
+ defer allocator.free(expected);
102
+ try std.testing.expectEqualSlices(u8, expected, engine.output.items);
103
+ if (index == 0) {
104
+ try std.testing.expectEqual(engine.count(), engine.scanned);
105
+ } else {
106
+ try std.testing.expect(engine.scanned <= previous_scanned);
107
+ }
108
+ previous_scanned = engine.total;
109
+ }
110
+ try std.testing.expect(engine.scanned < engine.count());
111
+
112
+ // Candidates added after the previous query are always scored.
113
+ try engine.add(second);
114
+ try engine.query("sctrl", 50);
115
+ const appended = try freshOutput(allocator, &.{ first, second }, "sctrl", 50);
116
+ defer allocator.free(appended);
117
+ try std.testing.expectEqualSlices(u8, appended, engine.output.items);
118
+
119
+ // Insertions anywhere keep the previous query as a subsequence.
120
+ try engine.query("sXctrl", 50);
121
+ const inserted = try freshOutput(allocator, &.{ first, second }, "sXctrl", 50);
122
+ defer allocator.free(inserted);
123
+ try std.testing.expectEqualSlices(u8, inserted, engine.output.items);
124
+
125
+ // Shorter or unrelated queries scan everything again.
126
+ for ([_][]const u8{ "sc", "日検", "", "B" }) |text| {
127
+ try engine.query(text, 50);
128
+ const expected = try freshOutput(allocator, &.{ first, second }, text, 50);
129
+ defer allocator.free(expected);
130
+ try std.testing.expectEqualSlices(u8, expected, engine.output.items);
131
+ try std.testing.expectEqual(engine.count(), engine.scanned);
132
+ }
133
+ }
134
+
135
+ test "case-folded queries narrow like the folded previous query" {
136
+ const allocator = std.testing.allocator;
137
+ var engine = fuzzy.Engine.init(allocator);
138
+ defer engine.deinit();
139
+ try engine.add("Search\x00xs\x00other\x00");
140
+ try engine.query("S", 10);
141
+ try engine.query("se", 10);
142
+ try std.testing.expectEqual(@as(u64, 1), engine.total);
143
+ try std.testing.expectEqual(@as(usize, 2), engine.scanned);
144
+ }
145
+
146
+ test "parallel scoring returns the same output as sequential scoring" {
147
+ const allocator = std.testing.allocator;
148
+ const first = try buildCandidates(allocator, 4000, 3);
149
+ defer allocator.free(first);
150
+ const second = try buildCandidates(allocator, 777, 4);
151
+ defer allocator.free(second);
152
+ var parallel = fuzzy.Engine.init(allocator);
153
+ defer parallel.deinit();
154
+ parallel.threads = 4;
155
+ parallel.min_parallel = 0;
156
+ try parallel.add(first);
157
+ try parallel.add(second);
158
+ const queries = [_][]const u8{ "", "s", "sc", "ctrl", "日検", "😀", "B", "zzzz", "lib/src" };
159
+ for (queries) |text| {
160
+ for ([_]usize{ 0, 1, 7, 1000, 10000 }) |limit| {
161
+ try parallel.query(text, limit);
162
+ const expected = try freshOutput(allocator, &.{ first, second }, text, limit);
163
+ defer allocator.free(expected);
164
+ try std.testing.expectEqualSlices(u8, expected, parallel.output.items);
165
+ }
166
+ }
167
+ }
168
+
169
+ test "candidate storage stays close to the UTF-8 size" {
170
+ const allocator = std.testing.allocator;
171
+ const batch = try buildCandidates(allocator, 2000, 5);
172
+ defer allocator.free(batch);
173
+ var engine = fuzzy.Engine.init(allocator);
174
+ defer engine.deinit();
175
+ try engine.add(batch);
176
+ try engine.query("sc", 10);
177
+ const text_bytes = batch.len - engine.count();
178
+ // At most twice the text (list growth) plus a small fixed cost per candidate.
179
+ try std.testing.expect(engine.storageBytes() <= text_bytes * 2 + engine.count() * 32);
180
+ }
181
+
182
+ test "position-limited queries rank identically and omit positions after the limit" {
183
+ var full = fuzzy.Engine.init(std.testing.allocator);
184
+ defer full.deinit();
185
+ var limited = fuzzy.Engine.init(std.testing.allocator);
186
+ defer limited.deinit();
187
+ const batch = "src/search_controller.rb\x00lib/sc.rb\x00docs/s_c_notes.md\x00test/scope_check.rb\x00";
188
+ try full.add(batch);
189
+ try limited.add(batch);
190
+ try full.query("sc", 10);
191
+ try limited.queryPositions("sc", 10, 2);
192
+ try std.testing.expectEqual(full.total, limited.total);
193
+ try std.testing.expectEqualSlices(fuzzy.Match, full.matches.items, limited.matches.items);
194
+ // Each record: id u64, score i64, count u32, positions; after 12 header bytes.
195
+ var a: usize = 12;
196
+ var b: usize = 12;
197
+ for (0..full.matches.items.len) |rank| {
198
+ const count = std.mem.readInt(u32, full.output.items[a + 16 ..][0..4], .little);
199
+ const limited_count = std.mem.readInt(u32, limited.output.items[b + 16 ..][0..4], .little);
200
+ try std.testing.expectEqualSlices(u8, full.output.items[a..][0..16], limited.output.items[b..][0..16]);
201
+ if (rank < 2) {
202
+ try std.testing.expectEqual(count, limited_count);
203
+ try std.testing.expectEqualSlices(u8, full.output.items[a + 20 ..][0 .. count * 4], limited.output.items[b + 20 ..][0 .. count * 4]);
204
+ } else {
205
+ try std.testing.expectEqual(@as(u32, 0), limited_count);
206
+ }
207
+ a += 20 + count * 4;
208
+ b += 20 + limited_count * 4;
209
+ }
210
+ try std.testing.expectEqual(full.output.items.len, a);
211
+ try std.testing.expectEqual(limited.output.items.len, b);
212
+ }
@@ -1,4 +1,7 @@
1
1
  const std = @import("std");
2
+ comptime {
3
+ _ = @import("fuzzy.zig");
4
+ }
2
5
  const c = std.c;
3
6
  const search = @import("search.zig");
4
7
  const os = @import("os.zig");
@@ -389,6 +392,23 @@ export fn core_files_create(
389
392
  return @intFromPtr(s);
390
393
  }
391
394
 
395
+ /// ファイル一覧をルートからの相対パスのラベル列で返す走査を開始する(失敗時は 0)。
396
+ /// drain のレコードは種類 4(line=件数、path=NUL 終端のラベル列)。UTF-8 でない名前は種類 1 で 1 件ずつ返す
397
+ export fn core_files_labels_create(
398
+ roots: [*]const u8,
399
+ roots_len: usize,
400
+ excluded: [*]const u8,
401
+ excluded_len: usize,
402
+ threads: u32,
403
+ ) u64 {
404
+ const s = search.Search.createFileLabels(
405
+ roots[0..roots_len],
406
+ excluded[0..excluded_len],
407
+ threads,
408
+ ) catch return 0;
409
+ return @intFromPtr(s);
410
+ }
411
+
392
412
  export fn core_search_state(handle: u64) u8 {
393
413
  if (handle == 0) return @intFromEnum(search.State.failed);
394
414
  const s: *search.Search = @ptrFromInt(handle);
@@ -435,6 +455,13 @@ export fn core_cache_bytes(handle: u64) u64 {
435
455
  return cache.cachedBytes();
436
456
  }
437
457
 
458
+ /// 検索の後でキャッシュへ格納しているスレッドの終了を待つ(テスト用)
459
+ export fn core_cache_wait(handle: u64) void {
460
+ if (handle == 0) return;
461
+ const cache: *search.Cache = @ptrFromInt(handle);
462
+ cache.wait();
463
+ }
464
+
438
465
  /// 使用中の検索をすべて destroy してから呼ぶこと
439
466
  export fn core_cache_destroy(handle: u64) void {
440
467
  if (handle == 0) return;
@@ -1,12 +1,13 @@
1
- //! G mode のコンテンツ検索エンジン。
1
+ //! G mode のコンテンツ検索エンジン & 高速ファイル列挙エンジン(rufio / usurai.nvim 共通モジュール)。
2
2
  //!
3
3
  //! Ruby 実装(GlobalSearch#scan_roots / #scan_content)と同じ結果を返しつつ、
4
- //! 次の手法で ripgrep 以上の速度を狙う:
4
+ //! 次の手法で ripgrep / fd 以上の速度を狙う:
5
5
  //! - 全 CPU コアでディレクトリを並列走査(ワークスタックで負荷分散)
6
- //! - getdirentries64 による大きなバッファでの一括ディレクトリ読み込み(macOS)
6
+ //! - getattrlistbulk / getdents64 / FindFirstFileExW による一括ディレクトリ読み込み
7
7
  //! - openat/fstatat で親ディレクトリ fd から相対オープン(パス解決を省略)
8
8
  //! - 希少バイト 2 点を SIMD で同時比較する大文字小文字無視リテラル検索
9
9
  //! - 行番号はマッチ発生時のみ SIMD で改行を数える(非マッチファイルは数えない)
10
+ //! - 2 回目以降の検索はインメモリキャッシュ(Cache)から open/read ゼロで即座に検索
10
11
  //! - スレッドローカル出力バッファでロック回数を削減し、上限超過時は背圧で待機
11
12
  const std = @import("std");
12
13
  const c = std.c;
@@ -26,6 +27,8 @@ const READ_BUFFER = 256 * 1024;
26
27
  /// サイズ不明時の初回読み込み量(多くのソースファイルが 1 回で収まる)
27
28
  const FIRST_READ = 16 * 1024;
28
29
  const LOCAL_FLUSH = 64 * 1024;
30
+ /// ラベルの最大長(検索インデックスが受け付ける候補の長さ)
31
+ const MAX_LABEL = 65536;
29
32
  /// Ruby 側が取り出していない出力がこれを超えたらワーカーは待機する
30
33
  const MAX_PENDING = 8 * 1024 * 1024;
31
34
 
@@ -39,6 +42,9 @@ pub const Kind = enum(u8) {
39
42
  match = 1,
40
43
  document = 2,
41
44
  err = 3,
45
+ /// ファイル一覧のラベルモード: 同じルートのファイルの相対パスを NUL 終端で連結したもの。
46
+ /// line に件数、path にラベル列を入れる(Ruby がファイルごとにレコードを解析せずに済む)
47
+ labels = 4,
42
48
  };
43
49
 
44
50
  pub const State = enum(u8) {
@@ -283,6 +289,8 @@ const Job = struct {
283
289
  pub const Search = struct {
284
290
  matcher: Matcher,
285
291
  files_only: bool = false,
292
+ /// files_only で、ファイルを相対パスのラベル列(Kind.labels)として出す
293
+ labels: bool = false,
286
294
  roots: StringList,
287
295
  excluded: StringList,
288
296
  documents: StringList,
@@ -314,21 +322,29 @@ pub const Search = struct {
314
322
 
315
323
  pub fn create(roots: []const u8, query: []const u8, excluded: []const u8, documents: []const u8, threads: usize, cache: ?*Cache) !*Search {
316
324
  if (query.len == 0 or query.len > MAX_NEEDLE or roots.len == 0) return error.InvalidArgument;
317
- return createInternal(roots, query, excluded, documents, threads, cache, false);
325
+ return createInternal(roots, query, excluded, documents, threads, cache, false, false);
318
326
  }
319
327
 
320
328
  /// ファイル一覧列挙モード(fd 互換・ファイル内容は開かずに高速走査)
321
329
  pub fn createFiles(roots: []const u8, excluded: []const u8, threads: usize) !*Search {
322
330
  if (roots.len == 0) return error.InvalidArgument;
323
- return createInternal(roots, "", excluded, "", threads, null, true);
331
+ return createInternal(roots, "", excluded, "", threads, null, true, false);
324
332
  }
325
333
 
326
- fn createInternal(roots: []const u8, query: []const u8, excluded: []const u8, documents: []const u8, threads: usize, cache: ?*Cache, files_only: bool) !*Search {
334
+ /// ファイル一覧をルートからの相対パスのラベル列(Kind.labels)で出す。
335
+ /// UTF-8 として正しくない・長すぎるパスだけ従来どおり 1 件ずつ Kind.match で出す
336
+ pub fn createFileLabels(roots: []const u8, excluded: []const u8, threads: usize) !*Search {
337
+ if (roots.len == 0) return error.InvalidArgument;
338
+ return createInternal(roots, "", excluded, "", threads, null, true, true);
339
+ }
340
+
341
+ fn createInternal(roots: []const u8, query: []const u8, excluded: []const u8, documents: []const u8, threads: usize, cache: ?*Cache, files_only: bool, labels: bool) !*Search {
327
342
  const self = try std.heap.c_allocator.create(Search);
328
343
  errdefer std.heap.c_allocator.destroy(self);
329
344
  self.* = .{
330
345
  .matcher = Matcher.init(query),
331
346
  .files_only = files_only,
347
+ .labels = labels,
332
348
  .roots = try StringList.init(roots),
333
349
  .excluded = try StringList.init(excluded),
334
350
  .documents = try StringList.init(documents),
@@ -493,10 +509,10 @@ fn workerMain(s: *Search) void {
493
509
  w.subdirs = null;
494
510
  w.subdirs_tail = null;
495
511
  w.subdir_count = 0;
496
- if (w.out.len >= LOCAL_FLUSH) s.publish(&w.out);
512
+ if (w.out.len >= LOCAL_FLUSH) w.flush();
497
513
  }
498
514
  } else |_| {}
499
- s.publish(&w.out);
515
+ w.flush();
500
516
  s.workerExit();
501
517
  }
502
518
 
@@ -509,6 +525,11 @@ const Worker = struct {
509
525
  subdirs_tail: ?*Job = null,
510
526
  subdir_count: usize = 0,
511
527
  key: Buf = .{},
528
+ /// 書きかけのラベル列(Kind.labels)。out 内のヘッダ位置・ルート・件数
529
+ segment_start: usize = 0,
530
+ segment_root: u32 = 0,
531
+ segment_count: u64 = 0,
532
+ segment_open: bool = false,
512
533
 
513
534
  fn init(self: *Worker) !void {
514
535
  if (!self.s.files_only) {
@@ -533,7 +554,56 @@ const Worker = struct {
533
554
  return self.s.cancelled.load(.monotonic);
534
555
  }
535
556
 
557
+ /// 書きかけのラベル列を閉じてから出力を公開する
558
+ fn flush(self: *Worker) void {
559
+ self.closeSegment();
560
+ self.s.publish(&self.out);
561
+ }
562
+
563
+ fn closeSegment(self: *Worker) void {
564
+ if (!self.segment_open) return;
565
+ self.segment_open = false;
566
+ const header = self.out.ptr[self.segment_start..][0..RECORD_HEADER];
567
+ std.mem.writeInt(u64, header[5..13], self.segment_count, .little);
568
+ std.mem.writeInt(u32, header[17..21], @intCast(self.out.len - self.segment_start - RECORD_HEADER), .little);
569
+ }
570
+
571
+ /// ルートからの相対パス(ラベル)を書きかけのラベル列に足す
572
+ fn addLabel(self: *Worker, job: *Job, name: []const u8) void {
573
+ const root = self.s.roots.items[job.root];
574
+ const dir_path = job.path();
575
+ var relative: []const u8 = if (dir_path.len >= root.len) dir_path[root.len..] else "";
576
+ while (relative.len > 0 and relative[0] == '/') relative = relative[1..];
577
+ const label_len = relative.len + @as(usize, if (relative.len > 0) 1 else 0) + name.len;
578
+ // 検索インデックスが受け付けない名前は従来のレコードで出し、Ruby 側で scrub する
579
+ if (label_len > MAX_LABEL or !std.unicode.utf8ValidateSlice(relative) or !std.unicode.utf8ValidateSlice(name)) {
580
+ self.record(.match, job.root, 1, 0, dir_path, name, "");
581
+ return;
582
+ }
583
+ if (!self.segment_open or self.segment_root != job.root) {
584
+ self.closeSegment();
585
+ self.out.reserve(self.out.len + RECORD_HEADER + label_len + 1) catch return;
586
+ self.segment_start = self.out.len;
587
+ var hdr: [RECORD_HEADER]u8 = @splat(0);
588
+ hdr[0] = @intFromEnum(Kind.labels);
589
+ std.mem.writeInt(u32, hdr[1..5], job.root, .little);
590
+ self.out.append(&hdr) catch unreachable;
591
+ self.segment_root = job.root;
592
+ self.segment_count = 0;
593
+ self.segment_open = true;
594
+ }
595
+ self.out.reserve(self.out.len + label_len + 1) catch return;
596
+ if (relative.len > 0) {
597
+ self.out.append(relative) catch unreachable;
598
+ self.out.append("/") catch unreachable;
599
+ }
600
+ self.out.append(name) catch unreachable;
601
+ self.out.append("\x00") catch unreachable;
602
+ self.segment_count += 1;
603
+ }
604
+
536
605
  fn record(self: *Worker, kind: Kind, root: u32, line: u64, offset: u32, dir: []const u8, name: []const u8, extra: []const u8) void {
606
+ self.closeSegment();
537
607
  const clean_dir = if (name.len > 0 and std.mem.eql(u8, dir, "."))
538
608
  ""
539
609
  else if (name.len > 0 and std.mem.startsWith(u8, dir, "./"))
@@ -634,8 +704,12 @@ const Worker = struct {
634
704
 
635
705
  // ファイル一覧モード(fd 互換): ファイルを開かずにパスのみ記録
636
706
  if (self.s.files_only) {
637
- self.record(.match, job.root, 1, 0, job.path(), name, "");
638
- if (self.out.len >= LOCAL_FLUSH) self.s.publish(&self.out);
707
+ if (self.s.labels) {
708
+ self.addLabel(job, name);
709
+ } else {
710
+ self.record(.match, job.root, 1, 0, job.path(), name, "");
711
+ }
712
+ if (self.out.len >= LOCAL_FLUSH) self.flush();
639
713
  return;
640
714
  }
641
715
  const ext = extname(name);
@@ -672,11 +746,10 @@ const Worker = struct {
672
746
  return;
673
747
  };
674
748
  defer file.close();
675
- if (cache) |cc| {
676
- self.searchWholeFile(file, job, name, meta.?, cc, key);
677
- } else {
678
- self.searchFile(file, job, name, size, 0);
679
- }
749
+ // キャッシュにない内容は通常どおり検索し、キャッシュへの格納は検索の完了後に別スレッドで行う
750
+ // (初回の検索がキャッシュ用の読み込みと複製を待たない)
751
+ if (cache) |cc| cc.enqueue(key, meta.?);
752
+ self.searchFile(file, job, name, size, 0);
680
753
  }
681
754
 
682
755
  fn cacheKey(self: *Worker, dir: []const u8, name: []const u8) ?[]const u8 {
@@ -689,7 +762,7 @@ const Worker = struct {
689
762
 
690
763
  /// dst を埋めるまで読む。通常ファイルの短い read は EOF なのでそこで止める(EOF 確認の read を省く)。
691
764
  /// エラー時は null
692
- fn readUpTo(file: os.File, dst: []u8) ?usize {
765
+ pub fn readUpTo(file: os.File, dst: []u8) ?usize {
693
766
  var got: usize = 0;
694
767
  while (got < dst.len) {
695
768
  const want = dst.len - got;
@@ -701,32 +774,6 @@ const Worker = struct {
701
774
  return got;
702
775
  }
703
776
 
704
- /// キャッシュ対象のファイルを丸ごと読み、判定結果と内容をキャッシュしてから検索する
705
- fn searchWholeFile(self: *Worker, file: os.File, job: *Job, name: []const u8, meta: FileMeta, cache: *Cache, key: []const u8) void {
706
- const size: usize = @intCast(meta.size);
707
- // 1 バイト余分に要求してファイルの伸長を検知する
708
- self.read.reserve(size + 1) catch return;
709
- const buf = self.read.ptr[0 .. size + 1];
710
- const first = if (size < FIRST_READ) size + 1 else BINARY_SAMPLE;
711
- var got = readUpTo(file, buf[0..first]) orelse return self.recordErrno(job.root, job.path(), name);
712
- if (std.mem.indexOfScalar(u8, buf[0..@min(got, BINARY_SAMPLE)], 0) != null) {
713
- cache.store(key, meta, null);
714
- _ = self.s.skipped.fetchAdd(1, .monotonic);
715
- return;
716
- }
717
- if (got == first and first < buf.len) {
718
- got += readUpTo(file, buf[got..]) orelse return self.recordErrno(job.root, job.path(), name);
719
- }
720
- if (got > size) {
721
- // 走査後にファイルが伸びた: キャッシュせず残りをストリーミングで処理
722
- self.searchFile(file, job, name, null, got);
723
- return;
724
- }
725
- cache.store(key, meta, buf[0..got]);
726
- var line_no: u64 = 1;
727
- self.searchLines(buf[0..got], job, name, &line_no);
728
- }
729
-
730
777
  /// 完全な行の並び(末尾は改行または EOF)を検索してマッチを記録する
731
778
  fn searchLines(self: *Worker, buf: []const u8, job: *Job, name: []const u8, line_no: *u64) void {
732
779
  const m = &self.s.matcher;
@@ -819,6 +866,12 @@ const MAX_CACHED_FILE = 16 * 1024 * 1024;
819
866
  pub const Cache = struct {
820
867
  const SHARDS = 64;
821
868
 
869
+ /// 検索中にキャッシュになかったファイル。検索の完了後に格納スレッドが読んで格納する
870
+ const Pending = struct {
871
+ path: [:0]u8,
872
+ meta: FileMeta,
873
+ };
874
+
822
875
  const Entry = struct {
823
876
  meta: FileMeta,
824
877
  /// null はバイナリ判定済み
@@ -843,6 +896,14 @@ pub const Cache = struct {
843
896
  gen: u32 = 0,
844
897
  busy: std.atomic.Value(bool) = .init(false),
845
898
 
899
+ pending_mutex: os.Mutex = .{},
900
+ pending: std.ArrayList(Pending) = .empty,
901
+ /// 格納スレッドが予算の上限に達した。エントリが減るまで格納待ちに加えない
902
+ /// (入らないファイルのために毎回格納スレッドが動き、次の検索がキャッシュを使えなくなるのを防ぐ)
903
+ full: std.atomic.Value(bool) = .init(false),
904
+ filler: ?std.Thread = null,
905
+ fill_cancel: std.atomic.Value(bool) = .init(false),
906
+
846
907
  pub fn create(max_bytes: u64) !*Cache {
847
908
  const self = try std.heap.c_allocator.create(Cache);
848
909
  self.* = .{ .max_bytes = max_bytes };
@@ -850,6 +911,9 @@ pub const Cache = struct {
850
911
  }
851
912
 
852
913
  pub fn destroy(self: *Cache) void {
914
+ self.fill_cancel.store(true, .release);
915
+ self.joinFiller();
916
+ self.clearPending();
853
917
  for (&self.shards) |*shard| {
854
918
  var it = shard.map.iterator();
855
919
  while (it.next()) |kv| freeEntry(kv.key_ptr.*, kv.value_ptr.*);
@@ -862,13 +926,110 @@ pub const Cache = struct {
862
926
  return self.bytes.load(.acquire);
863
927
  }
864
928
 
865
- /// 1 つのキャッシュを同時に使える検索は 1 つだけ
929
+ /// 1 つのキャッシュを同時に使える検索は 1 つだけ(格納スレッドの実行中も使えない)
866
930
  pub fn begin(self: *Cache) bool {
867
931
  if (self.busy.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) return false;
932
+ self.joinFiller(); // 終わっている格納スレッドを回収する
868
933
  self.gen +%= 1;
869
934
  return true;
870
935
  }
871
936
 
937
+ /// 格納スレッドの終了を待つ(テストと終了処理用)
938
+ pub fn wait(self: *Cache) void {
939
+ while (self.filler != null and self.busy.load(.acquire)) std.Thread.yield() catch {};
940
+ if (!self.busy.load(.acquire)) self.joinFiller();
941
+ }
942
+
943
+ fn joinFiller(self: *Cache) void {
944
+ if (self.filler) |thread| {
945
+ thread.join();
946
+ self.filler = null;
947
+ }
948
+ }
949
+
950
+ fn clearPending(self: *Cache) void {
951
+ for (self.pending.items) |item| std.heap.c_allocator.free(item.path);
952
+ self.pending.clearAndFree(std.heap.c_allocator);
953
+ }
954
+
955
+ /// 検索中に見つかったキャッシュにないファイルを格納待ちに加える。予算は格納するときに判定する
956
+ /// (バイナリは内容を持たないので、ここで大きさを数えると予算を無駄にする)
957
+ pub fn enqueue(self: *Cache, key: []const u8, meta: FileMeta) void {
958
+ if (self.full.load(.monotonic) or meta.size > self.max_bytes) return;
959
+ self.pending_mutex.lock();
960
+ defer self.pending_mutex.unlock();
961
+ const path = std.heap.c_allocator.dupeSentinel(u8, key, 0) catch return;
962
+ self.pending.append(std.heap.c_allocator, .{ .path = path, .meta = meta }) catch {
963
+ std.heap.c_allocator.free(path);
964
+ };
965
+ }
966
+
967
+ fn fillMain(self: *Cache) void {
968
+ var scratch: os.Scratch = .{};
969
+ const ready = if (scratch.init()) true else |_| false;
970
+ defer if (ready) scratch.deinit();
971
+ if (ready) {
972
+ for (self.pending.items) |item| {
973
+ if (self.fill_cancel.load(.acquire)) break;
974
+ self.fillOne(item, &scratch);
975
+ }
976
+ }
977
+ self.clearPending();
978
+ self.busy.store(false, .release);
979
+ }
980
+
981
+ /// 1 ファイルを丸ごと読んで格納する。走査時から大きさが変わっていれば格納しない
982
+ /// (内容が変わっても属性が変わっていれば、次の検索の lookup が属性の違いで捨てる)
983
+ fn fillOne(self: *Cache, item: Pending, scratch: *os.Scratch) void {
984
+ const size: usize = @intCast(item.meta.size);
985
+ const file = os.openRead(item.path, scratch) orelse return;
986
+ defer file.close();
987
+ // 先頭だけ読んでバイナリなら内容を持たずに判定だけ格納する(大きなバイナリを丸ごと読まない)
988
+ var sample: [BINARY_SAMPLE]u8 = undefined;
989
+ const head = @min(size + 1, BINARY_SAMPLE);
990
+ const sampled = Worker.readUpTo(file, sample[0..head]) orelse return;
991
+ if (std.mem.indexOfScalar(u8, sample[0..sampled], 0) != null) {
992
+ self.insert(item.path, item.meta, null, 0);
993
+ return;
994
+ }
995
+ if (sampled > size or (sampled < head and sampled != size)) return; // 大きさが変わった
996
+ if (!self.reserve(size)) {
997
+ self.full.store(true, .monotonic);
998
+ return;
999
+ }
1000
+ // 1 バイト余分に要求してファイルの伸長を検知する
1001
+ const memory: [*]u8 = @ptrCast(c.malloc(size + 1) orelse {
1002
+ self.unreserve(size);
1003
+ return;
1004
+ });
1005
+ @memcpy(memory[0..sampled], sample[0..sampled]);
1006
+ const rest = if (sampled < head) 0 else Worker.readUpTo(file, memory[sampled .. size + 1]) orelse {
1007
+ c.free(memory);
1008
+ self.unreserve(size);
1009
+ return;
1010
+ };
1011
+ if (sampled + rest != size) {
1012
+ c.free(memory);
1013
+ self.unreserve(size);
1014
+ return;
1015
+ }
1016
+ self.insert(item.path, item.meta, memory, size);
1017
+ }
1018
+
1019
+ /// 内容 len バイト分の予算を確保する。上限を超えるなら確保せず false
1020
+ fn reserve(self: *Cache, len: usize) bool {
1021
+ const prev = self.bytes.fetchAdd(len, .monotonic);
1022
+ if (prev + len > self.max_bytes) {
1023
+ _ = self.bytes.fetchSub(len, .monotonic);
1024
+ return false;
1025
+ }
1026
+ return true;
1027
+ }
1028
+
1029
+ fn unreserve(self: *Cache, len: usize) void {
1030
+ if (len > 0) _ = self.bytes.fetchSub(len, .monotonic);
1031
+ }
1032
+
872
1033
  /// 完走した検索のあとは、今回見つからなかった(削除・範囲外の)エントリを捨てる
873
1034
  pub fn end(self: *Cache, completed: bool) void {
874
1035
  if (completed) {
@@ -887,6 +1048,14 @@ pub const Cache = struct {
887
1048
  }
888
1049
  }
889
1050
  }
1051
+ // 完走した検索で見つかった未格納のファイルを、別スレッドで読んで格納する(その間 busy のまま)
1052
+ if (completed and self.pending.items.len > 0 and !self.fill_cancel.load(.acquire)) {
1053
+ if (std.Thread.spawn(.{ .stack_size = 512 * 1024 }, fillMain, .{self})) |thread| {
1054
+ self.filler = thread;
1055
+ return;
1056
+ } else |_| {}
1057
+ }
1058
+ self.clearPending();
890
1059
  self.busy.store(false, .release);
891
1060
  }
892
1061
 
@@ -900,7 +1069,10 @@ pub const Cache = struct {
900
1069
  }
901
1070
 
902
1071
  fn release(self: *Cache, entry: Entry) void {
903
- if (entry.data != null) _ = self.bytes.fetchSub(entry.len, .monotonic);
1072
+ if (entry.data != null) {
1073
+ _ = self.bytes.fetchSub(entry.len, .monotonic);
1074
+ self.full.store(false, .monotonic);
1075
+ }
904
1076
  }
905
1077
 
906
1078
  pub fn lookup(self: *Cache, key: []const u8, meta: FileMeta) ?Hit {
@@ -938,6 +1110,11 @@ pub const Cache = struct {
938
1110
  data = p;
939
1111
  len = bytes.len;
940
1112
  }
1113
+ self.insert(key, meta, data, len);
1114
+ }
1115
+
1116
+ /// data の予算は確保済み。失敗したら data を解放して予算を返す
1117
+ fn insert(self: *Cache, key: []const u8, meta: FileMeta, data: ?[*]u8, len: usize) void {
941
1118
  const owned_key = std.heap.c_allocator.dupe(u8, key) catch {
942
1119
  if (data) |p| {
943
1120
  c.free(p);