vomebook commited on
Commit ·
49c552a
1
Parent(s): 179cd5b
Use directory index for narrow folder filters
Browse files
backend/app.py
CHANGED
|
@@ -1125,6 +1125,43 @@ def apply_mixed_folder_filters(indices, self_folders=None, subtree_folders=None)
|
|
| 1125 |
result.append(idx)
|
| 1126 |
return result
|
| 1127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1128 |
def search(q="", repos=None, extensions=None, folders=None, min_size=None, max_size=None, page=1, page_size=100, search_folders=True, sort="relevance", exact=False, folder_match_mode="prefix", folder_selfs=None, folder_subtrees=None, anchor_id=None):
|
| 1129 |
global _search_logged_generation
|
| 1130 |
started = time.perf_counter()
|
|
@@ -1304,11 +1341,14 @@ def _search_order_uncached(q="", repos=None, extensions=None, folders=None, min_
|
|
| 1304 |
indices = range(len(records))
|
| 1305 |
return indices
|
| 1306 |
else:
|
| 1307 |
-
indices = get_initial_indices(repos)
|
| 1308 |
if folder_match_mode == "mixed":
|
|
|
|
|
|
|
|
|
|
| 1309 |
filtered = apply_mixed_folder_filters(indices, folder_selfs, folder_subtrees)
|
| 1310 |
filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size)
|
| 1311 |
else:
|
|
|
|
| 1312 |
filtered = apply_filters(indices, repos, extensions, folders, min_size, max_size, folder_match_mode)
|
| 1313 |
if sort == "name":
|
| 1314 |
filtered.sort(key=sort_key_name)
|
|
|
|
| 1125 |
result.append(idx)
|
| 1126 |
return result
|
| 1127 |
|
| 1128 |
+
|
| 1129 |
+
def mixed_folder_index_candidates(repos, self_folders=None, subtree_folders=None):
|
| 1130 |
+
"""Return a small corpus-ordered superset, or None to retain the full scan.
|
| 1131 |
+
|
| 1132 |
+
The directory index is built from actual Folder component boundaries for
|
| 1133 |
+
the current corpus. It contains each subtree, so it is also a safe
|
| 1134 |
+
superset for direct-only selections. The existing predicate remains the
|
| 1135 |
+
authority on direct vs descendant semantics (including unusual names).
|
| 1136 |
+
"""
|
| 1137 |
+
if len(self_folders or ()) + len(subtree_folders or ()) > 64:
|
| 1138 |
+
return None
|
| 1139 |
+
paths = {str(path).strip("/") for path in (self_folders or [])}
|
| 1140 |
+
paths.update(str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/"))
|
| 1141 |
+
if not paths:
|
| 1142 |
+
return None
|
| 1143 |
+
selected_repos = canonical_repos(repos) if repos else list(repo_records_map)
|
| 1144 |
+
scope_size = sum(len(repo_records_map.get(repo, ())) for repo in selected_repos) if repos else len(records)
|
| 1145 |
+
# Keep wide selections and overlapping directory trees on the old path;
|
| 1146 |
+
# do not allocate an unbounded deduplication set for broad requests.
|
| 1147 |
+
limit = min(32768, max(64, scope_size // 2))
|
| 1148 |
+
postings = []
|
| 1149 |
+
estimated = 0
|
| 1150 |
+
for repo in selected_repos:
|
| 1151 |
+
folders = folder_index.get(repo, {})
|
| 1152 |
+
for path in paths:
|
| 1153 |
+
indices = folders.get(path, ())
|
| 1154 |
+
estimated += len(indices)
|
| 1155 |
+
if estimated > limit:
|
| 1156 |
+
return None
|
| 1157 |
+
if indices:
|
| 1158 |
+
postings.append(indices)
|
| 1159 |
+
candidates = set()
|
| 1160 |
+
for indices in postings:
|
| 1161 |
+
candidates.update(indices)
|
| 1162 |
+
return sorted(candidates)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
def search(q="", repos=None, extensions=None, folders=None, min_size=None, max_size=None, page=1, page_size=100, search_folders=True, sort="relevance", exact=False, folder_match_mode="prefix", folder_selfs=None, folder_subtrees=None, anchor_id=None):
|
| 1166 |
global _search_logged_generation
|
| 1167 |
started = time.perf_counter()
|
|
|
|
| 1341 |
indices = range(len(records))
|
| 1342 |
return indices
|
| 1343 |
else:
|
|
|
|
| 1344 |
if folder_match_mode == "mixed":
|
| 1345 |
+
indices = mixed_folder_index_candidates(repos, folder_selfs, folder_subtrees)
|
| 1346 |
+
if indices is None:
|
| 1347 |
+
indices = get_initial_indices(repos)
|
| 1348 |
filtered = apply_mixed_folder_filters(indices, folder_selfs, folder_subtrees)
|
| 1349 |
filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size)
|
| 1350 |
else:
|
| 1351 |
+
indices = get_initial_indices(repos)
|
| 1352 |
filtered = apply_filters(indices, repos, extensions, folders, min_size, max_size, folder_match_mode)
|
| 1353 |
if sort == "name":
|
| 1354 |
filtered.sort(key=sort_key_name)
|
scripts/benchmarks/benchmark_mixed_folder_search.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare local mixed-folder search against the original full scan.
|
| 2 |
+
|
| 3 |
+
Uses the checked-in catalog only; never reads book bodies or contacts a server.
|
| 4 |
+
The reported times are local compute timings, not end-to-end device latency.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import gzip
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import statistics
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 21 |
+
sys.path.insert(0, str(ROOT))
|
| 22 |
+
os.chdir(ROOT)
|
| 23 |
+
|
| 24 |
+
from backend import app # noqa: E402
|
| 25 |
+
from backend.data_formats import decode_search_payload # noqa: E402
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 30 |
+
parser.add_argument('--output', type=Path, help='optional output JSON outside the source tree')
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
with gzip.open(ROOT / 'data/search_data.json.gz', 'rt') as handle:
|
| 33 |
+
app.records = decode_search_payload(json.load(handle))
|
| 34 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 35 |
+
app._search_generation = 'local-comparison'
|
| 36 |
+
|
| 37 |
+
cases = []
|
| 38 |
+
for repo in ('VoiceOfML/VOMEBOOK', 'VoiceOfML/MLMRL-Hub', 'VoiceOfML/SovMaterials'):
|
| 39 |
+
folders = sorted((len(indices), path) for path, indices in app.folder_index.get(repo, {}).items() if path)
|
| 40 |
+
if not folders:
|
| 41 |
+
continue
|
| 42 |
+
for fraction in (.1, .5, .9):
|
| 43 |
+
size, path = folders[min(len(folders) - 1, int(len(folders) * fraction))]
|
| 44 |
+
for scoped in (False, True):
|
| 45 |
+
for mode in ('self', 'subtree'):
|
| 46 |
+
cases.append((f'{repo}:{size}:{scoped}:{mode}', dict(
|
| 47 |
+
q='', repos=[repo] if scoped else None, folder_match_mode='mixed',
|
| 48 |
+
folder_selfs=[path] if mode == 'self' else [],
|
| 49 |
+
folder_subtrees=[path] if mode == 'subtree' else [])))
|
| 50 |
+
cases.extend([
|
| 51 |
+
('wide-root', dict(q='', repos=['VoiceOfML/VOMEBOOK'], folder_match_mode='mixed', folder_selfs=[''])),
|
| 52 |
+
('empty-filters', dict(q='', repos=['VoiceOfML/VOMEBOOK'], folder_match_mode='mixed')),
|
| 53 |
+
('missing-repo', dict(q='', repos=['VoiceOfML/Missing'], folder_match_mode='mixed', folder_selfs=['none'])),
|
| 54 |
+
('many-paths', dict(q='', folder_match_mode='mixed', folder_subtrees=[f'missing-{i}' for i in range(80)])),
|
| 55 |
+
])
|
| 56 |
+
report = {'scope': 'local catalog, in-process ABBA; first page and cached pages; '
|
| 57 |
+
'no document I/O or network; not end-to-end mobile timing',
|
| 58 |
+
'records': len(app.records), 'cases': []}
|
| 59 |
+
for name, base in cases:
|
| 60 |
+
for modifier in ('default', 'name-pdf', 'size'):
|
| 61 |
+
options = dict(base)
|
| 62 |
+
if modifier == 'name-pdf':
|
| 63 |
+
options.update(sort='name', extensions=['pdf'])
|
| 64 |
+
elif modifier == 'size':
|
| 65 |
+
options.update(sort='size', min_size=1, max_size=10000000)
|
| 66 |
+
order = app._search_order_uncached(**options)
|
| 67 |
+
if order:
|
| 68 |
+
record = app.records[order[0]]
|
| 69 |
+
options['anchor_id'] = record['Repo'] + '\0' + app.build_record_relative_path(record)
|
| 70 |
+
options['page_size'] = 50
|
| 71 |
+
runs = []
|
| 72 |
+
expected = None
|
| 73 |
+
for variant in ('baseline', 'candidate', 'candidate', 'baseline'):
|
| 74 |
+
app._search_cache.clear()
|
| 75 |
+
app._search_order_cache.clear()
|
| 76 |
+
app._search_anchor_cache.clear()
|
| 77 |
+
comparison = (patch.object(app, 'mixed_folder_index_candidates', return_value=None)
|
| 78 |
+
if variant == 'baseline' else
|
| 79 |
+
patch.object(app, 'mixed_folder_index_candidates', wraps=app.mixed_folder_index_candidates))
|
| 80 |
+
with comparison:
|
| 81 |
+
responses, elapsed = [], []
|
| 82 |
+
for page in (1, 2, 1):
|
| 83 |
+
start = time.perf_counter()
|
| 84 |
+
responses.append(app.search(**{**options, 'page': page}))
|
| 85 |
+
elapsed.append(round((time.perf_counter() - start) * 1000, 3))
|
| 86 |
+
digest = hashlib.sha256(json.dumps(responses, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
| 87 |
+
if expected is not None and digest != expected:
|
| 88 |
+
raise AssertionError(f'{name}/{modifier}: result mismatch')
|
| 89 |
+
expected = digest
|
| 90 |
+
runs.append({'variant':variant, 'first_ms':elapsed[0], 'second_ms':elapsed[1],
|
| 91 |
+
'repeat_ms':elapsed[2], 'sha256':digest})
|
| 92 |
+
report['cases'].append({'name':name, 'modifier':modifier, 'total':responses[0]['total'], 'runs':runs,
|
| 93 |
+
'baseline_ms':round(statistics.median(row['first_ms'] for row in runs if row['variant']=='baseline'),3),
|
| 94 |
+
'candidate_ms':round(statistics.median(row['first_ms'] for row in runs if row['variant']=='candidate'),3)})
|
| 95 |
+
encoded = json.dumps(report, ensure_ascii=False, indent=2)
|
| 96 |
+
if args.output:
|
| 97 |
+
args.output.write_text(encoded + '\n', encoding='utf-8')
|
| 98 |
+
else:
|
| 99 |
+
print(encoded)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
main()
|
tests/test_mixed_folder_browser.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise the actual search UI against the real local mixed-folder API."""
|
| 2 |
+
import copy
|
| 3 |
+
import threading
|
| 4 |
+
import unittest
|
| 5 |
+
from unittest import mock
|
| 6 |
+
|
| 7 |
+
from playwright.sync_api import sync_playwright
|
| 8 |
+
import uvicorn
|
| 9 |
+
|
| 10 |
+
from backend import app
|
| 11 |
+
from tests import test_mixed_folder_performance as mixed
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MixedFolderBrowserTests(unittest.TestCase):
|
| 15 |
+
@classmethod
|
| 16 |
+
def setUpClass(cls):
|
| 17 |
+
cls.saved = {name: copy.deepcopy(getattr(app, name)) for name in mixed.REBUILD_STATE}
|
| 18 |
+
app.records = [
|
| 19 |
+
dict(Repo='VoiceOfML/Test', File=f'direct-{i:03}', Extension='txt',
|
| 20 |
+
Folder=['docs'], Size=i + 1, HasTxt=True) for i in range(140)
|
| 21 |
+
] + [
|
| 22 |
+
dict(Repo='VoiceOfML/Test', File='child', Extension='pdf', Folder=['docs', 'child'], Size=50, HasTxt=False),
|
| 23 |
+
dict(Repo='VoiceOfML/Test', File='sibling', Extension='txt', Folder=['docs-other'], Size=50, HasTxt=True),
|
| 24 |
+
]
|
| 25 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 26 |
+
cls.assets = mock.patch.object(app, 'get_reader_assets', mock.AsyncMock(return_value={'v':1, 'f':{}}))
|
| 27 |
+
cls.assets.start()
|
| 28 |
+
cls.addClassCleanup(cls.assets.stop)
|
| 29 |
+
cls.addClassCleanup(cls.restore_records)
|
| 30 |
+
local = app.FastAPI(lifespan=None)
|
| 31 |
+
local.include_router(app.app.router)
|
| 32 |
+
cls.server = uvicorn.Server(uvicorn.Config(local, host='127.0.0.1', port=0, log_level='error', lifespan='off'))
|
| 33 |
+
cls.thread = threading.Thread(target=cls.server.run, daemon=True)
|
| 34 |
+
cls.thread.start()
|
| 35 |
+
cls.addClassCleanup(cls.stop_server)
|
| 36 |
+
for _ in range(100):
|
| 37 |
+
if cls.server.started:
|
| 38 |
+
break
|
| 39 |
+
threading.Event().wait(.05)
|
| 40 |
+
if not cls.server.started:
|
| 41 |
+
raise RuntimeError('local test server did not start')
|
| 42 |
+
cls.origin = f"http://127.0.0.1:{cls.server.servers[0].sockets[0].getsockname()[1]}"
|
| 43 |
+
cls.playwright = sync_playwright().start()
|
| 44 |
+
cls.addClassCleanup(cls.playwright.stop)
|
| 45 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=['--no-sandbox'])
|
| 46 |
+
cls.addClassCleanup(cls.browser.close)
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def stop_server(cls):
|
| 50 |
+
cls.server.should_exit = True
|
| 51 |
+
cls.thread.join(timeout=10)
|
| 52 |
+
if cls.thread.is_alive():
|
| 53 |
+
raise RuntimeError('local test server did not stop')
|
| 54 |
+
|
| 55 |
+
@classmethod
|
| 56 |
+
def restore_records(cls):
|
| 57 |
+
for name, value in cls.saved.items():
|
| 58 |
+
setattr(app, name, value)
|
| 59 |
+
app._search_cache.clear()
|
| 60 |
+
app._search_order_cache.clear()
|
| 61 |
+
app._search_anchor_cache.clear()
|
| 62 |
+
|
| 63 |
+
def test_mobile_folder_filters_hit_real_api_with_complete_counts(self):
|
| 64 |
+
context = self.browser.new_context(viewport={'width':390, 'height':844}, is_mobile=True,
|
| 65 |
+
has_touch=True, service_workers='block')
|
| 66 |
+
page = context.new_page()
|
| 67 |
+
errors, requests = [], []
|
| 68 |
+
page.on('pageerror', lambda error: errors.append(str(error)))
|
| 69 |
+
|
| 70 |
+
def track(request):
|
| 71 |
+
if request.method == 'POST' and '/api/search' in request.url:
|
| 72 |
+
requests.append(request.post_data_json)
|
| 73 |
+
page.on('request', track)
|
| 74 |
+
page.route('https://**/*', lambda route: route.fulfill(status=503, body='offline'))
|
| 75 |
+
try:
|
| 76 |
+
page.goto(self.origin + '/', wait_until='domcontentloaded')
|
| 77 |
+
page.wait_for_function('() => typeof STATE !== "undefined" && !STATE.isLoading', timeout=15000)
|
| 78 |
+
for selection, count in [({'self':['docs'], 'sub':[]}, 140),
|
| 79 |
+
({'self':[], 'sub':['docs']}, 141),
|
| 80 |
+
({'self':['missing'], 'sub':[]}, 0)]:
|
| 81 |
+
page.evaluate('''selection => {
|
| 82 |
+
cancelSearchPrefetch(); searchAbortController?.abort();
|
| 83 |
+
STATE.query=''; STATE.filterFolderSelfs=selection.self;
|
| 84 |
+
STATE.filterFolderSubtrees=selection.sub; STATE.filterFolders=[];
|
| 85 |
+
STATE.filterRepos=[]; STATE.filterExtensions=[];
|
| 86 |
+
STATE.filterMinSize=null; STATE.filterMaxSize=null;
|
| 87 |
+
doSearch(false, true);
|
| 88 |
+
}''', selection)
|
| 89 |
+
page.wait_for_function('count => !STATE.isLoading && STATE.total === count', arg=count, timeout=15000)
|
| 90 |
+
self.assertEqual(page.evaluate('STATE.filterFolderSelfs'), selection['self'])
|
| 91 |
+
self.assertEqual(page.evaluate('STATE.filterFolderSubtrees'), selection['sub'])
|
| 92 |
+
self.assertTrue(any(r.get('folder_match_mode') == 'mixed' and
|
| 93 |
+
(r.get('folder_selfs') or []) == selection['self'] and
|
| 94 |
+
(r.get('folder_subtrees') or []) == selection['sub'] for r in requests))
|
| 95 |
+
if count:
|
| 96 |
+
self.assertEqual(page.locator('#results-list .result-item').first.count(), 1)
|
| 97 |
+
self.assertTrue(all(r['Folder'][0] == 'docs' for r in page.evaluate('STATE.results.filter(Boolean)')))
|
| 98 |
+
self.assertEqual(errors, [])
|
| 99 |
+
finally:
|
| 100 |
+
context.close()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == '__main__':
|
| 104 |
+
unittest.main()
|
tests/test_mixed_folder_performance.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Indexed folder filtering keeps the full-scan contract and bounded fallback."""
|
| 2 |
+
import asyncio
|
| 3 |
+
import copy
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
import unittest
|
| 7 |
+
from unittest import mock
|
| 8 |
+
|
| 9 |
+
from backend import app
|
| 10 |
+
|
| 11 |
+
REBUILD_STATE = (
|
| 12 |
+
'records', 'word_index', 'word_index_buffer', 'folder_index', 'repo_counts', 'repo_list',
|
| 13 |
+
'repo_records_map', 'sorted_by_name', 'sorted_by_size', 'repo_sorted_by_name',
|
| 14 |
+
'repo_sorted_by_size', 'vocab_by_len', 'extension_counts', 'extension_list',
|
| 15 |
+
'repo_extension_counts', 'txt_record_indices', 'repo_txt_record_indices',
|
| 16 |
+
'reader_record_indices', 'repo_reader_record_indices', 'reader_record_key_indices',
|
| 17 |
+
'reader_source_id_indices', 'reader_legacy_source_id_indices', '_reader_indexes_ready',
|
| 18 |
+
'_reader_index_build', '_data_generation', '_search_generation', '_search_logged_generation',
|
| 19 |
+
'api_response_cache',
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class MixedFolderIndexTests(unittest.TestCase):
|
| 24 |
+
def setUp(self):
|
| 25 |
+
self.saved = {name: copy.deepcopy(getattr(app, name)) for name in REBUILD_STATE}
|
| 26 |
+
self.rng = random.Random(20261102)
|
| 27 |
+
folders = [[], ['docs'], ['docs', 'child'], ['docs-other'], [''],
|
| 28 |
+
['a/b'], ['a', 'b'], ['a/', 'b'], ['a', '', 'b'],
|
| 29 |
+
['中文'], ['中文', '嵌套'], ['/'], ['space here']]
|
| 30 |
+
app.records = [dict(Repo=f'VoiceOfML/{"A" if i % 2 else "B"}',
|
| 31 |
+
File=f'name-{i % 11}', Extension=('pdf', 'txt', 'epub')[i % 3],
|
| 32 |
+
Folder=self.rng.choice(folders), Size=(0, 1, 100)[i % 3],
|
| 33 |
+
HasTxt=i % 3 == 1) for i in range(300)]
|
| 34 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 35 |
+
|
| 36 |
+
def tearDown(self):
|
| 37 |
+
app._search_cache.clear()
|
| 38 |
+
app._search_order_cache.clear()
|
| 39 |
+
app._search_anchor_cache.clear()
|
| 40 |
+
for name, value in self.saved.items():
|
| 41 |
+
setattr(app, name, value)
|
| 42 |
+
|
| 43 |
+
@staticmethod
|
| 44 |
+
def full_scan(**kwargs):
|
| 45 |
+
with mock.patch.object(app, 'mixed_folder_index_candidates', return_value=None):
|
| 46 |
+
return app._search_order_uncached(**kwargs)
|
| 47 |
+
|
| 48 |
+
def test_small_selection_matches_full_scan_across_filter_and_sort_options(self):
|
| 49 |
+
paths = ['', '/', 'docs', 'docs/child', '/docs/', 'docs-other', 'a', 'a/b',
|
| 50 |
+
'a//b', '中文', '中文/嵌套', 'missing', 'space here']
|
| 51 |
+
repos = [None, ['VoiceOfML/A'], ['VoiceOfML/B', 'VoiceOfML/A'],
|
| 52 |
+
['VoiceOfML/A', 'VoiceOfML/A'], ['VoiceOfML/Missing']]
|
| 53 |
+
indexed = 0
|
| 54 |
+
for _ in range(500):
|
| 55 |
+
options = dict(q='', repos=self.rng.choice(repos),
|
| 56 |
+
folder_match_mode='mixed',
|
| 57 |
+
folder_selfs=self.rng.sample(paths, self.rng.randrange(4)),
|
| 58 |
+
folder_subtrees=self.rng.sample(paths, self.rng.randrange(4)),
|
| 59 |
+
extensions=self.rng.choice([None, ['pdf'], ['TXT', 'epub']]),
|
| 60 |
+
min_size=self.rng.choice([None, 1, 20]),
|
| 61 |
+
max_size=self.rng.choice([None, 1, 50]),
|
| 62 |
+
sort=self.rng.choice(['relevance', 'name', 'size']),
|
| 63 |
+
exact=self.rng.choice([True, False]))
|
| 64 |
+
with self.subTest(options=options):
|
| 65 |
+
indexed += app.mixed_folder_index_candidates(options['repos'], options['folder_selfs'],
|
| 66 |
+
options['folder_subtrees']) is not None
|
| 67 |
+
self.assertEqual(app._search_order_uncached(**options), self.full_scan(**options))
|
| 68 |
+
self.assertGreater(indexed, 100)
|
| 69 |
+
|
| 70 |
+
def test_narrow_uses_index_and_wide_uses_existing_scan(self):
|
| 71 |
+
options = dict(q='', repos=['VoiceOfML/A'], folder_match_mode='mixed',
|
| 72 |
+
folder_subtrees=['中文/嵌套'])
|
| 73 |
+
expected = self.full_scan(**options)
|
| 74 |
+
candidates = app.mixed_folder_index_candidates(options['repos'], [], options['folder_subtrees'])
|
| 75 |
+
self.assertIsNotNone(candidates)
|
| 76 |
+
self.assertGreater(len(candidates), 0)
|
| 77 |
+
with mock.patch.object(app, 'get_initial_indices', side_effect=AssertionError('full scan')):
|
| 78 |
+
self.assertEqual(app._search_order_uncached(**options), expected)
|
| 79 |
+
self.assertIsNone(app.mixed_folder_index_candidates(None, [''], []))
|
| 80 |
+
self.assertIsNone(app.mixed_folder_index_candidates(None, [], [str(i) for i in range(65)]))
|
| 81 |
+
empty = dict(q='', folder_match_mode='mixed', folder_selfs=[], folder_subtrees=[])
|
| 82 |
+
self.assertEqual(app._search_order_uncached(**empty), self.full_scan(**empty))
|
| 83 |
+
|
| 84 |
+
def test_overlapping_paths_missing_repos_and_pages_match(self):
|
| 85 |
+
cases = [dict(folder_selfs=['docs'], folder_subtrees=['docs', 'docs/child']),
|
| 86 |
+
dict(folder_selfs=[''], folder_subtrees=['docs']),
|
| 87 |
+
dict(folder_selfs=['/'], folder_subtrees=[]),
|
| 88 |
+
dict(folder_selfs=['missing'], folder_subtrees=['missing']),
|
| 89 |
+
dict(folder_selfs=[], folder_subtrees=['中文/嵌套'])]
|
| 90 |
+
for case in cases:
|
| 91 |
+
options = dict(q='', folder_match_mode='mixed', sort='name', **case)
|
| 92 |
+
expected_order = self.full_scan(**options)
|
| 93 |
+
app._search_order_cache.clear()
|
| 94 |
+
app._search_cache.clear()
|
| 95 |
+
pages = [app.search(**options, page=n, page_size=7) for n in range(1, 5)]
|
| 96 |
+
self.assertEqual(pages[0]['total'], len(expected_order))
|
| 97 |
+
self.assertEqual([r for page in pages for r in page['results']],
|
| 98 |
+
app.trim_results([app.records[i] for i in expected_order[:28]]))
|
| 99 |
+
self.assertEqual(app._search_order_uncached(**{**options, 'repos':['VoiceOfML/Missing']}), [])
|
| 100 |
+
|
| 101 |
+
def test_api_pages_anchors_and_generation_match_full_scan(self):
|
| 102 |
+
async def exercise():
|
| 103 |
+
from backend.search_execution import SearchExecutor
|
| 104 |
+
import httpx
|
| 105 |
+
async with SearchExecutor() as executor:
|
| 106 |
+
with mock.patch.object(app.app.state, 'search_executor', executor, create=True), \
|
| 107 |
+
mock.patch.object(app, 'get_reader_assets', mock.AsyncMock(return_value={'v':1, 'f':{}})):
|
| 108 |
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client:
|
| 109 |
+
for request in [
|
| 110 |
+
dict(q='', folder_match_mode='mixed', folder_subtrees=['docs'],
|
| 111 |
+
sort='name', page_size=7),
|
| 112 |
+
dict(q='', folder_match_mode='mixed', folder_selfs=['中文/嵌套'],
|
| 113 |
+
extensions=['txt'], sort='size', page_size=7),
|
| 114 |
+
dict(q='', folder_match_mode='mixed', folder_selfs=['missing'], page_size=7),
|
| 115 |
+
]:
|
| 116 |
+
for page in (1, 2, 50):
|
| 117 |
+
body = {**request, 'page':page,
|
| 118 |
+
'anchor_id':'VoiceOfML/A\0docs/name-1.txt'}
|
| 119 |
+
app._search_cache.clear()
|
| 120 |
+
app._search_order_cache.clear()
|
| 121 |
+
app.api_response_cache.clear()
|
| 122 |
+
with mock.patch.object(app, 'mixed_folder_index_candidates', return_value=None):
|
| 123 |
+
baseline = await client.post('/api/search', json=body)
|
| 124 |
+
app._search_cache.clear()
|
| 125 |
+
app._search_order_cache.clear()
|
| 126 |
+
app.api_response_cache.clear()
|
| 127 |
+
candidate = await client.post('/api/search', json=body)
|
| 128 |
+
self.assertEqual(candidate.status_code, 200)
|
| 129 |
+
self.assertEqual(json.loads(candidate.content), json.loads(baseline.content))
|
| 130 |
+
self.assertIn('search;dur=', candidate.headers['server-timing'])
|
| 131 |
+
asyncio.run(exercise())
|
| 132 |
+
|
| 133 |
+
def test_rebuild_uses_only_current_generation_folder_index(self):
|
| 134 |
+
options = dict(q='', folder_match_mode='mixed', folder_subtrees=['docs'], page_size=500)
|
| 135 |
+
before = app.search(**options)
|
| 136 |
+
app.records = [dict(Repo='VoiceOfML/New', File='replacement', Extension='txt',
|
| 137 |
+
Folder=['docs'], Size=1, HasTxt=True)]
|
| 138 |
+
app.build_indexes(build_words=False, build_reader=False)
|
| 139 |
+
after = app.search(**options)
|
| 140 |
+
self.assertNotEqual(before['generation'], after['generation'])
|
| 141 |
+
self.assertEqual(after['total'], 1)
|
| 142 |
+
self.assertEqual(after['results'][0]['File'], 'replacement')
|
| 143 |
+
self.assertEqual(app._search_order_uncached(**{k: v for k, v in options.items() if k != 'page_size'}),
|
| 144 |
+
self.full_scan(**{k: v for k, v in options.items() if k != 'page_size'}))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == '__main__':
|
| 148 |
+
unittest.main()
|