Repository navigation
Expand file tree
/
Copy pathmodel_index.cpp
More file actions
5261 lines (4457 loc) · 184 KB
/
Copy pathmodel_index.cpp
File metadata and controls
5261 lines (4457 loc) · 184 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Purpose: File indexing engine. Scans folders, extracts metadata, keeps the in-memory item
// collection and answers queries over it - from the search index (model_search_index.cpp) where it is
// current, scanning only folders changed since it was read - and reads that index on its own queue.
// Reads films, episodes and shows from file and folder names, and fills what a video's tags leave out
// from them as items load. Duplicate prediction and presence live in model_index_duplicates.cpp; the
// summary and its vocabulary in model_index_summary.cpp.
#include "pch.h"
#include "model_index.h"
#include "model_index_internal.h"
#include "model_db.h"
#include "model_locations.h"
#include "model_property.h"
#include "model.h"
#include "metadata.h"
#include "util_crash_files_db.h"
#include "util_text.h"
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
constexpr auto max_folders_to_index = 100000;
// A row written before the quarter turns were stored carries the first hash alone. Reporting it as
// unhashed asks for the other three, rather than leaving a rotated copy permanently unrecognisable.
static df::picture_hashes_ptr picture_hashes_from_db(const crypto::phash_rotations& rotations)
{
if (rotations[0] == 0) return nullptr;
if (rotations[0] == crypto::phash_declined) return df::make_picture_hashes(rotations);
const auto complete = std::ranges::all_of(rotations, [](const uint64_t h) { return crypto::phash_is_usable(h); });
return complete ? df::make_picture_hashes(rotations) : nullptr;
}
df_assert_pod(core::file_path);
df_assert_pod(df::file_group_histogram);
df_assert_pod(search_presence_mask);
df_assert_pod(key_val);
df_assert_movable(df::index_file_item);
df_assert_movable(folder_scan_item);
df_assert_movable(index_state::query_item);
df_assert_movable(index_state::item_scan_request);
df_assert_movable(index_state::thumbnail_result);
df_assert_movable(index_state::validate_folder_result);
static_assert(sizeof(search_presence_mask) == 4);
static_assert(sizeof(core::file_path) == sizeof(core::cached) * 2);
static_assert(sizeof(key_val) == sizeof(core::cached) * 2);
// Every query walks these fields once per candidate. A type that outgrows a machine word makes
// std::atomic fall back to a lock, which x64 hides for 16 bytes and ARM64 does not, so a widened
// field would turn the hot index record into a contended mutex rather than fail here.
static_assert(std::atomic<core::date_t>::is_always_lock_free);
static_assert(std::atomic<df::duplicate_info>::is_always_lock_free);
static_assert(std::atomic<search_presence_mask>::is_always_lock_free);
std::function<void(core::folder_path folder, int attempt)> test_after_validate_folder_snapshot;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
struct query_items_result
{
// Folders whose names match are listed beside the items.
static constexpr bool lists_folders = true;
index_state::query_item_results results;
void match_item(const core::file_path id, const df::index_file_item& file, const df::search_result& match)
{
results.push_back({index_state::query_item_kind::file, id, file, {}, {}, match});
}
void match_folder(const folder_path folder_path, const df::index_folder_item_ptr& folder)
{
results.push_back({index_state::query_item_kind::folder, {}, {}, folder_path, folder, {}});
}
// A document the search index matched. One term answers with what it matched in, as the matcher does;
// several answer as their combination, which is all the matcher says of them either.
void match_doc(const df::search_index& index, const uint32_t doc, const df::search_matcher& matcher)
{
const auto& file = index.file(doc);
const auto& folder = index.folders()[index.doc_folder(doc)];
const auto& terms = matcher.search().terms();
const auto match = terms.size() == 1
? matcher.match_term(folder.path.text(), file, index.metadata(doc), terms.front())
: df::search_result{df::search_result_type::match_multiple};
core::assert_true(match.is_match());
if (match.is_match())
{
results.push_back(
{index_state::query_item_kind::file, folder.path.combine_file(file.name), file, {}, {}, match});
}
}
};
struct count_items_result
{
static constexpr bool lists_folders = false;
df::file_group_histogram summary;
void match_item(const core::file_path id, const df::index_file_item& file, const df::search_result& /*match*/)
{
summary.record(file, id);
}
static void match_folder(const folder_path /*folder_path*/, const df::index_folder_item_ptr& /*folder*/) {}
void match_doc(const df::search_index& index, const uint32_t doc, const df::search_matcher&)
{
const auto& file = index.file(doc);
summary.record(file, index.path(doc), df::thumbnail_representative_rank(file, index.metadata(doc)));
}
};
// How many, and nothing more: no sizes, no representative picture.
struct tally_items_result
{
static constexpr bool lists_folders = false;
df::file_group_histogram summary;
void match_item(const core::file_path, const df::index_file_item& file, const df::search_result&)
{
summary.record(file);
}
static void match_folder(const core::folder_path, const df::index_folder_item_ptr&) {}
void match_doc(const df::search_index& index, const uint32_t doc, const df::search_matcher&)
{
summary.record(index.file(doc));
}
};
// A related search written as text - typed, or restored from a favorite or saved search -
// carries only the path, so every field the relation axes compare is recovered from the
// index before any matching happens. Files outside the collection fall back to the path.
static const df::search_t& resolve_related(const df::search_t& search, const index_state& state, df::search_t& storage)
{
if (!search.has_related())
{
// NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter): the caller's search outlives the result
return search;
}
const auto path = search.related().path;
const auto load_index_facts = [](df::related_info& r, const df::index_file_item& found)
{
r.name = found.name;
r.size = found.size;
r.file_created = found.file_created;
r.ft = found.ft;
r.crc32c = found.crc32c.load();
const auto duplicates = found.duplicates.load();
r.group = duplicates.group;
r.exact_group = found.exact_duplicate_group.load();
r.duplicate_grade = duplicates.grade;
r.duplicate_crowded = duplicates.same_picture_crowded;
if (const auto hashes = found.phash.load())
{
r.phash = hashes->rotations;
}
const auto md = found.metadata.load();
if (md)
{
r.gps = md->coordinate;
r.metadata_created = md->created();
r.dimensions = md->dimensions();
r.album = md->album;
r.album_artist = md->album_artist;
r.show = md->show;
r.season = md->season;
r.episode = md->episode;
r.disk = md->disk;
r.track = md->track;
}
};
if (search.related().is_loaded)
{
// The snapshot was taken when the command ran, but duplicate grouping is recomputed behind it
// and perceptual groups are anchored, so the direct pair evidence is refreshed from the index.
const auto found = state.find_item(path);
if (!found.ft)
{
// NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter): the caller's search outlives the result
return search;
}
df::related_info r = search.related();
load_index_facts(r, found);
storage = search;
storage.related(r);
return storage;
}
const auto found = state.find_item(path);
df::related_info r;
r.path = path;
if (found.ft)
{
load_index_facts(r, found);
}
else
{
r.name = core::cache(path.name());
r.ft = files::file_type_from_name(path);
}
r.is_loaded = true;
storage = search;
storage.related(r);
return storage;
}
template <typename T>
static void iterate_items(const df::search_t& search_in, T& results, index_state& state, core::cancel_token token,
index_items& index, bool refresh_from_file_system, bool show_sidecars,
index_state::search_context* context = nullptr)
{
df::search_t resolved_related;
const auto& search = resolve_related(search_in, state, resolved_related);
df::search_matcher matcher(search, core::utc_now().to_days(), &state.locations());
const auto now = core::utc_now();
const auto& selectors = search.selectors();
const auto has_selector = !selectors.empty();
const auto has_related = search.has_related();
// A related search answers with the closest matches on each axis, so its results are collected
// and ranked here rather than reported as they are found. Counting shares this path so a count
// can never disagree with the set the same search displays.
struct related_payload
{
df::index_file_item file;
df::search_result match;
};
df::related_collector<related_payload> related_slots;
// Two selectors can name overlapping trees - `folders_scanned` only stops one selector walking a
// folder twice - and a file matched by both is still one file. The set is only paid for when
// there is more than one selector to overlap, and folders cannot repeat within a single walk.
core::unique_paths emitted;
core::unique_folders emitted_folders;
const auto selectors_can_overlap = selectors.size() > 1;
const auto report = [&results, &related_slots, &emitted, has_related,
selectors_can_overlap](const core::file_path id, const df::index_file_item& file,
const df::search_result& match)
{
if (selectors_can_overlap && !emitted.emplace(id).second)
{
return;
}
if (has_related)
{
related_slots.offer({df::related_axis_of(match.type), match.distance}, id, {file, match});
}
else
{
results.match_item(id, file, match);
}
};
const auto report_folder =
[&results, &emitted_folders, selectors_can_overlap](const core::folder_path path,
const df::index_folder_item_ptr& folder)
{
if (selectors_can_overlap && !emitted_folders.emplace(path).second)
{
return;
}
results.match_folder(path, folder);
};
if (has_selector)
{
for (const auto& selector : selectors)
{
if (token.is_cancelled()) break;
const auto recursive = selector.is_recursive();
const auto& wildcard = selector.wildcard();
files ff;
std::vector<core::folder_path> folders = {selector.folder()};
core::unique_folders folders_scanned;
while (!folders.empty())
{
if (token.is_cancelled()) break;
const auto current_folder = folders.back();
folders.pop_back();
if (!folders_scanned.contains(current_folder))
{
folders_scanned.emplace(current_folder);
const auto found_node = state.validate_folder(current_folder, refresh_from_file_system, now);
if (found_node.folder)
{
// Keep the snapshot alive for the whole loop: folders_snapshot() returns a
// temporary shared_ptr, and dereferencing it into the range-for only extends the
// vector's lifetime through the initializer, not the loop body. A concurrent
// replace_child() dropping the last other reference mid-loop would otherwise free
// the vector out from under the iteration.
const auto folders_snapshot = found_node.folder->folders_snapshot();
for (const auto& folder_entry : *folders_snapshot)
{
if (token.is_cancelled()) break;
const auto folder_path = current_folder.combine(folder_entry->name);
if (folder_entry->is_excluded) continue;
// The wildcard names the files being looked for, not the folders they are
// under. Gating the descent on it left "*.jpg" searching only folders called
// *.jpg, so every nested match was missed.
if (recursive && folder_entry->can_recurse)
{
folders.emplace_back(folder_path);
}
if (selector.has_wildcard() && !wildcard_icmp(folder_entry->name, wildcard))
{
continue;
}
if ((!recursive && !matcher.has_terms) ||
matcher.match_folder(folder_path.text(), folder_path.name()).is_match())
{
report_folder(folder_path, folder_entry);
}
}
if (matcher.need_metadata)
{
for (const auto& f : found_node.folder->files)
{
if (token.is_cancelled()) break;
state.scan_item(found_node.folder, {current_folder, f.name}, false, false, false, false,
{}, false, f.ft);
}
}
if (matcher.can_contain(found_node.folder->search_presence_summary))
{
for (const auto& file_node : found_node.folder->files)
{
if (token.is_cancelled()) break;
const auto& file = file_node;
if (!selector.has_wildcard() || wildcard_icmp(file_node.name, wildcard))
{
if (!(file.flags && df::index_item_flags::is_sidecar) || show_sidecars)
{
const auto id = current_folder.combine_file(file_node.name);
const auto match = matcher.match_item(id, file);
if (match.is_match())
{
report(id, file, match);
}
}
}
}
}
}
}
}
}
}
else
{
index_folders_t listed;
const auto& folders = context ? context->folders : (listed = index.all_folders());
auto* const evaluator = context && context->evaluator && !has_related ? &*context->evaluator : nullptr;
// Asks a folder's items one by one, as every folder was asked before there was a search index.
// Folder masks are an early rejection only; each surviving item is checked against its own mask
// and then by the authoritative exact matcher.
const auto scan_folder = [&](const index_folders_t::value_type& folder_node)
{
if (!has_related && !matcher.can_match_folder &&
!matcher.can_contain(folder_node.second->search_presence_summary))
{
return;
}
for (const auto& file_node : folder_node.second->files)
{
if (token.is_cancelled()) break;
if (!(file_node.flags && df::index_item_flags::is_sidecar) || show_sidecars)
{
const auto path = folder_node.first.combine_file(file_node.name);
const auto match = matcher.match_item(path, file_node);
if (match.is_match())
{
report(path, file_node, match);
}
}
}
};
if (evaluator)
{
// The search index answers below for every folder it read and has not seen change; only the
// rest are asked item by item.
for (const auto position : evaluator->view().unclean_folders())
{
if (token.is_cancelled()) break;
const auto& folder_node = folders[position];
if (!folder_node.second->is_in_collection) continue;
core::bump(df::query_perf.index_scanned_folders);
scan_folder(folder_node);
}
}
// A count asks for items alone, so only results that list folders read every folder's name.
if (!evaluator || T::lists_folders)
{
for (const auto& folder_node : folders)
{
if (token.is_cancelled()) break;
if (!folder_node.second->is_in_collection) continue;
if (!evaluator) scan_folder(folder_node);
if constexpr (T::lists_folders)
{
if (matcher.match_folder(folder_node.first.text(), folder_node.first.name()).is_match())
{
results.match_folder(folder_node.first, folder_node.second);
}
}
}
}
if (evaluator && matcher.has_terms && !token.is_cancelled())
{
core::bump(df::query_perf.index_answers);
const auto docs = evaluator->evaluate(matcher, token);
if (!token.is_cancelled())
{
const auto& snapshot = evaluator->index();
docs.for_each([&results, &snapshot, &matcher](const uint32_t doc)
{ results.match_doc(snapshot, doc, matcher); });
}
}
}
if (has_related && !token.is_cancelled())
{
related_slots.drain([&results](const core::file_path id, related_payload&& payload)
{ results.match_item(id, payload.file, payload.match); });
}
}
void index_state::query_items(const df::search_t& search,
const std::function<void(query_item_results, bool)>& found_callback,
const core::cancel_token& token, const search_execution execution)
{
core::scope_locked_inc l(searching);
_async.invalidate_view(view_invalid::view_layout);
if (search.has_related())
{
record_feature_use(features::search_related);
}
if (search.is_duplicates())
{
record_feature_use(features::search_duplicates);
}
const auto& selectors = search.selectors();
const auto has_selector = !selectors.empty();
if (has_selector)
{
record_feature_use(features::search_folder);
for (const auto& selector : selectors)
{
if (selector.is_recursive())
{
record_feature_use(features::search_flatten);
}
}
}
query_items_result results;
{
core::bump(df::query_perf.queries);
core::perf_timer timer(df::query_perf.query_us, &df::query_perf.query_max_us);
std::optional<search_context> context;
if (!has_selector && !search.has_related()) context = make_search_context(execution);
iterate_items(search, results, *this, token, _items, true, search.has_related(), context ? &*context : nullptr);
}
core::bump(df::query_perf.query_items, results.results.size());
if (search.has_related())
{
const auto id = search.related().path;
const auto folder = _items.find(id.folder());
if (!(folder && folder->is_in_collection))
{
// The item the search started at is outside the collection, so the scan never saw it. It
// still leads its own answer, which is what the negative distance orders it to.
df::search_result anchor(df::search_result_type::similar);
anchor.distance = -1;
results.results.push_back({query_item_kind::existing, id, {}, {}, {}, anchor});
}
}
if (search.has_term_type(df::search_term_type::text))
{
record_feature_use(features::search_text);
}
if (search.has_term_type(df::search_term_type::value))
{
record_feature_use(features::search_property);
}
if (search.has_term_type(df::search_term_type::has_type))
{
record_feature_use(features::search_type);
}
// The walk stops where the token was raised, so a cancelled pass has a partial set and must not
// claim otherwise. Its caller re-opens and publishes the whole answer; a partial set announced
// as complete settled the list showing fewer items than exist and said it was finished.
found_callback(std::move(results.results), !token.is_cancelled());
}
df::item_set index_state::materialize_query_items(query_item_results items, const df::unique_items& existing) const
{
core::assert_true(platform::is_ui_thread());
core::bump(df::query_perf.materializations);
core::bump(df::query_perf.materialize_items, items.size());
core::perf_timer timer(df::query_perf.materialize_us, &df::query_perf.materialize_max_us);
df::item_set results;
results.reserve(items.size());
for (auto& result : items)
{
df::item_element_ptr item;
if (result.kind == query_item_kind::file)
{
item = existing.find(result.path);
if (item)
{
item->update(result.path, result.file);
}
else
{
item = std::make_shared<df::item_element>(result.path, result.file);
}
item->search(result.match);
}
else if (result.kind == query_item_kind::folder)
{
item = existing.find(result.folder_path);
if (!item)
{
item = std::make_shared<df::item_element>(result.folder_path, std::move(result.folder));
}
}
else
{
item = existing.find(result.path);
if (item) item->search(result.match);
}
if (item) results.add(item);
}
return results;
}
df::file_group_histogram index_state::count_matches(const df::search_t& search, const core::cancel_token& token,
const search_execution execution)
{
count_items_result result;
if (is_collection_search(search))
{
core::measure_ms ms(stats.count_matches_ms);
core::bump(df::query_perf.counts);
core::perf_timer timer(df::query_perf.count_us);
std::optional<search_context> context;
if (!search.has_selector() && !search.has_related()) context = make_search_context(execution);
iterate_items(search, result, *this, token, _items, false, search.has_related(), context ? &*context : nullptr);
}
return result.summary;
}
index_state::search_context index_state::make_search_context(const search_execution execution) const
{
search_context result;
result.folders = _items.all_folders();
if (execution == search_execution::automatic)
{
if (auto snapshot = search_index())
{
result.evaluator.emplace(std::move(snapshot), result.folders);
if (!result.evaluator->is_useful()) result.evaluator.reset();
}
}
return result;
}
bool index_state::matches_collection_search(const df::search_matcher& matcher, const core::file_path path) const
{
const auto folder = _items.find(path.folder());
if (!folder || !folder->is_in_collection) return false;
if (!matcher.can_match_folder && !matcher.can_contain(folder->search_presence_summary)) return false;
const auto found = std::lower_bound(folder->files.begin(), folder->files.end(), path.name());
if (found == folder->files.end() || icmp(found->name, path.name()) != 0) return false;
if (found->flags && df::index_item_flags::is_sidecar) return false;
return matcher.match_item(path, *found).is_match();
}
// Up to this many changed items, scanning them on top of the search index costs a query less than
// reading the collection again costs.
static uint64_t search_index_stale_tolerance(const uint64_t docs)
{
return 1024 + docs / 32;
}
// Far beyond what any real collection needs, so it only stops a pathological one from holding memory
// that scanning does without.
constexpr size_t max_search_index_bytes = size_t{1} << 30;
// The least a document costs, so a collection certain to pass the ceiling is not read to find out.
constexpr size_t min_search_index_bytes_per_doc = 48;
// A burst of index changes settles before the collection is read again.
constexpr uint32_t search_index_debounce_ms = 1000;
// A prediction's count scans this many changed items at most on top of the search index.
constexpr uint64_t max_predicted_stale_docs = 20000;
// A pass counting hundreds of searches - a sidebar's rows - scans this many changed items at most per
// search; past it the pass counts as it did without the index.
constexpr uint64_t max_counted_stale_docs = 4096;
void index_state::publish_search_index(std::shared_ptr<const df::search_index> index)
{
std::shared_ptr<const df::search_index> previous;
const auto publishing = index != nullptr;
{
core::exclusive_lock lock(_summary_rw);
previous = std::move(_summary._search_index);
_summary._search_index = std::move(index);
}
// The sidebar may have counted without this snapshot - from summaries before any was read, or by
// scanning while the last was too stale to use - so it counts again from this one. Only counts: a
// snapshot changes no row.
if (publishing) _async.invalidate_view(view_invalid::sidebar_counts);
// The snapshot replaced here, with the folder nodes and metadata it held, is released after the lock.
}
void index_state::update_search_index()
{
if (platform::is_closing || !is_init_complete()) return;
// Indexing rewrites folders faster than a snapshot could follow and needs the CPU a build would take.
// Searches scan meanwhile, as they always did, and the pass that ends indexing asks again.
const auto indexing_active = [this]
{
return platform::is_closing || indexing.load() > 0 || scanning_items.load() > 0;
};
const auto folders = _items.all_folders();
if (const auto current = search_index())
{
const df::search_index_view view(*current, folders);
// Date terms are answered from the snapshot only on the day it was read, so the first pass of a new
// day reads the collection again.
const auto formats_current = current->format_signature() == df::search_index::current_format_signature() &&
current->date_day() == core::utc_now().to_days();
// A small collection's tolerance can pass the point where no search would use the snapshot, so one
// no search would use is read again however few items changed.
if (formats_current && view.is_useful() &&
view.stale_doc_count(*current) <= search_index_stale_tolerance(view.collection_doc_count()))
{
return;
}
if (indexing_active())
{
// Past use to any search, while still holding the nodes and metadata indexing has replaced.
if (!view.is_useful()) publish_search_index(nullptr);
return;
}
}
else if (indexing_active())
{
return;
}
size_t docs = 0;
for (const auto& folder : folders)
{
if (folder.second && folder.second->is_in_collection) docs += folder.second->files.size();
}
if (docs * min_search_index_bytes_per_doc > max_search_index_bytes)
{
publish_search_index(nullptr);
return;
}
const auto start_us = core::now_us();
auto built = df::search_index::build(folders, ++_search_index_generation, indexing_active);
if (!built) return;
if (built->byte_size() > max_search_index_bytes)
{
publish_search_index(nullptr);
return;
}
const auto elapsed_us = static_cast<uint64_t>(core::now_us() - start_us);
stats.search_index_docs = static_cast<int>(built->doc_count());
stats.search_index_bytes = built->byte_size();
stats.search_index_build_ms = static_cast<int>(elapsed_us / 1000);
core::bump(df::index_perf.search_index_builds);
core::bump(df::index_perf.search_index_build_us, elapsed_us);
core::record_peak(df::index_perf.search_index_build_max_us,
static_cast<uint32_t>(std::min<uint64_t>(elapsed_us, UINT32_MAX)));
df::index_perf.search_index_docs.store(built->doc_count(), std::memory_order_relaxed);
df::index_perf.search_index_bytes.store(built->byte_size(), std::memory_order_relaxed);
core::trace(std::format("Search index read {} items in {} ms, {}", built->doc_count(), elapsed_us / 1000,
platform::format_size(core::file_size(static_cast<uint64_t>(built->byte_size())))));
publish_search_index(std::move(built));
}
void index_state::queue_update_search_index()
{
_async.queue_async_after(async_queue::index_search_single, search_index_debounce_ms, [this]
{
if (platform::is_closing) return;
update_search_index();
});
}
index_state::search_context& search_counter::context()
{
if (!_context) _context = _index.make_search_context();
return *_context;
}
bool search_counter::is_indexed()
{
const auto& ctx = context();
return ctx.evaluator && ctx.evaluator->view().stale_doc_count(ctx.evaluator->index()) <= max_counted_stale_docs;
}
df::file_group_histogram search_counter::count(const df::search_t& search, const core::cancel_token& token)
{
if (search.has_selector() || search.has_related()) return _index.count_matches(search, token);
count_items_result result;
core::bump(df::query_perf.counts);
core::perf_timer timer(df::query_perf.count_us);
iterate_items(search, result, _index, token, _index._items, false, false, &context());
return result.summary;
}
std::optional<uint64_t> search_counter::try_count_items(const df::search_t& search, const core::cancel_token& token)
{
if (search.is_empty() || search.has_related()) return std::nullopt;
if (search.has_selector())
{
// One folder the index holds is read without asking the file system; a tree may be the whole
// collection, and a folder it does not hold would be enumerated. A term needing metadata would
// have each item of the folder not yet read opened and read here, keystroke after keystroke.
const auto& selectors = search.selectors();
if (selectors.size() != 1 || selectors.front().is_recursive() || !_index.is_collection_search(search))
return std::nullopt;
if (search.needs_metadata() || !_index._items.find(selectors.front().folder())) return std::nullopt;
tally_items_result result;
iterate_items(search, result, _index, token, _index._items, false, false, nullptr);
if (token.is_cancelled()) return std::nullopt;
return result.summary.total_items().count;
}
auto& ctx = context();
if (!ctx.evaluator) return std::nullopt;
// Every changed folder is scanned on top of the index, so only a nearly current one answers here.
if (ctx.evaluator->view().stale_doc_count(ctx.evaluator->index()) > max_predicted_stale_docs) return std::nullopt;
tally_items_result result;
iterate_items(search, result, _index, token, _index._items, false, false, &ctx);
if (token.is_cancelled()) return std::nullopt;
return result.summary.total_items().count;
}
search_kept_items search_counter::make_kept_items(const std::vector<core::file_path>& paths)
{
search_kept_items result;
auto& ctx = context();
const auto* const evaluator = ctx.evaluator ? &*ctx.evaluator : nullptr;
if (evaluator) result.docs = df::doc_set(evaluator->index().doc_count());
// A view lists a folder's items together more often than not, so a folder is looked up once a run.
core::folder_path last_folder;
std::optional<uint32_t> last_entry;
for (const auto& path : paths)
{
if (evaluator)
{
const auto& snapshot = evaluator->index();
if (path.folder() != last_folder || last_folder.is_empty())
{
last_folder = path.folder();
last_entry = snapshot.find_folder(last_folder);
if (last_entry && !evaluator->view().is_clean_entry(*last_entry)) last_entry.reset();
}
if (last_entry)
{
if (const auto doc = snapshot.find_doc(*last_entry, path.name()))
{
result.docs.set(*doc);
continue;
}
}
}
result.loose.emplace_back(path);
}
return result;
}
std::optional<uint64_t> search_counter::count_kept(const df::search_t& search, const search_kept_items& items,
const core::cancel_token& token)
{
auto& ctx = context();
if (search.has_selector() || search.has_related() || !ctx.evaluator) return std::nullopt;
const df::search_matcher matcher(search, core::utc_now().to_days(), &_index.locations());
const auto docs = ctx.evaluator->evaluate(matcher, token);
// Documents prepared against another snapshot number other items.
if (items.docs.size() != docs.size()) return std::nullopt;
auto result = docs.count_and(items.docs);
for (const auto& path : items.loose)
{
if (token.is_cancelled()) break;
if (_index.matches_collection_search(matcher, path)) ++result;
}
return result;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
index_state::index_state(async_strategy& as, const location_cache& locations) : _async(as), _locations(locations)
{
}
void index_state::enqueue_db_write(item_db_write write)
{
if (_db_writes.enqueue(std::move(write)))
{
// The database worker flushes writes after every task batch. One no-op task on the
// empty-to-nonempty transition gives the write queue an explicit wake without flooding it.
_async.queue_database([](database&) {});
}
}
void index_state::enqueue_db_writes(std::vector<item_db_write> writes)
{
if (writes.empty()) return;
// The worker drains the write queue on every pass, so a producer that enqueues one row at a time
// always finds it empty and wakes the database thread once per row - and each of those wakes opens
// its own transaction. Handing over the whole group keeps it to one wake and one transaction.
if (_db_writes.enqueue_all(std::move(writes)))
{
_async.queue_database([](database&) {});
}
}
void index_state::init_item_index()
{
auto summary = std::make_shared<index_metadata_summary>();
for (const auto& f : all_file_groups())
{
++summary->_distinct_words[core::cache(std::format("@{}", f->name))];
++summary->_distinct_words[core::cache(std::format("@{}", f->plural_name))];
}
summary->_distinct_text[prop::genre] = core::dense_unique_strings{"Abstract"_c,
"Action & Adventure"_c,
"Action"_c,
"Aerial"_c,
"Alternative"_c,
"Analog"_c,
"Animation"_c,
"Anime"_c,
"Architectural"_c,
"Aviation"_c,
"Blues"_c,
"Brazilian"_c,
"Candid"_c,
"Children's"_c,
"Christian & Gospel"_c,
"Classic"_c,
"Classical"_c,
"Close-up"_c,
"Cloudscape"_c,
"Comedy"_c,
"Conceptual"_c,
"Concert Films"_c,
"Concert"_c,
"Conservation"_c,
"Country"_c,
"Dance"_c,
"Documentary"_c,
"Drama"_c,
"Easy Listening"_c,
"Electronic"_c,
"Family"_c,
"Fashion"_c,
"Film Noir"_c,
"Film still"_c,
"Fine-art"_c,