File size: 5,117 Bytes
49c552a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7347da4
49c552a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare local mixed-folder search against the original full scan.

Uses the checked-in catalog only; never reads book bodies or contacts a server.
The reported times are local compute timings, not end-to-end device latency.
"""
from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import os
from pathlib import Path
import statistics
import sys
import time
from unittest.mock import patch


ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
os.chdir(ROOT)

from backend import app  # noqa: E402
from backend.search.corpus.domain.formats import decode_search_payload  # noqa: E402


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, help='optional output JSON outside the source tree')
    args = parser.parse_args()
    with gzip.open(ROOT / 'data/search_data.json.gz', 'rt') as handle:
        app.records = decode_search_payload(json.load(handle))
    app.build_indexes(build_words=False, build_reader=False)
    app._search_generation = 'local-comparison'

    cases = []
    for repo in ('VoiceOfML/VOMEBOOK', 'VoiceOfML/MLMRL-Hub', 'VoiceOfML/SovMaterials'):
        folders = sorted((len(indices), path) for path, indices in app.folder_index.get(repo, {}).items() if path)
        if not folders:
            continue
        for fraction in (.1, .5, .9):
            size, path = folders[min(len(folders) - 1, int(len(folders) * fraction))]
            for scoped in (False, True):
                for mode in ('self', 'subtree'):
                    cases.append((f'{repo}:{size}:{scoped}:{mode}', dict(
                        q='', repos=[repo] if scoped else None, folder_match_mode='mixed',
                        folder_selfs=[path] if mode == 'self' else [],
                        folder_subtrees=[path] if mode == 'subtree' else [])))
    cases.extend([
        ('wide-root', dict(q='', repos=['VoiceOfML/VOMEBOOK'], folder_match_mode='mixed', folder_selfs=[''])),
        ('empty-filters', dict(q='', repos=['VoiceOfML/VOMEBOOK'], folder_match_mode='mixed')),
        ('missing-repo', dict(q='', repos=['VoiceOfML/Missing'], folder_match_mode='mixed', folder_selfs=['none'])),
        ('many-paths', dict(q='', folder_match_mode='mixed', folder_subtrees=[f'missing-{i}' for i in range(80)])),
    ])
    report = {'scope': 'local catalog, in-process ABBA; first page and cached pages; '
                       'no document I/O or network; not end-to-end mobile timing',
              'records': len(app.records), 'cases': []}
    for name, base in cases:
        for modifier in ('default', 'name-pdf', 'size'):
            options = dict(base)
            if modifier == 'name-pdf':
                options.update(sort='name', extensions=['pdf'])
            elif modifier == 'size':
                options.update(sort='size', min_size=1, max_size=10000000)
            order = app._search_order_uncached(**options)
            if order:
                record = app.records[order[0]]
                options['anchor_id'] = record['Repo'] + '\0' + app.build_record_relative_path(record)
            options['page_size'] = 50
            runs = []
            expected = None
            for variant in ('baseline', 'candidate', 'candidate', 'baseline'):
                app._search_cache.clear()
                app._search_order_cache.clear()
                app._search_anchor_cache.clear()
                comparison = (patch.object(app, 'mixed_folder_index_candidates', return_value=None)
                              if variant == 'baseline' else
                              patch.object(app, 'mixed_folder_index_candidates', wraps=app.mixed_folder_index_candidates))
                with comparison:
                    responses, elapsed = [], []
                    for page in (1, 2, 1):
                        start = time.perf_counter()
                        responses.append(app.search(**{**options, 'page': page}))
                        elapsed.append(round((time.perf_counter() - start) * 1000, 3))
                digest = hashlib.sha256(json.dumps(responses, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
                if expected is not None and digest != expected:
                    raise AssertionError(f'{name}/{modifier}: result mismatch')
                expected = digest
                runs.append({'variant':variant, 'first_ms':elapsed[0], 'second_ms':elapsed[1],
                             'repeat_ms':elapsed[2], 'sha256':digest})
            report['cases'].append({'name':name, 'modifier':modifier, 'total':responses[0]['total'], 'runs':runs,
                'baseline_ms':round(statistics.median(row['first_ms'] for row in runs if row['variant']=='baseline'),3),
                'candidate_ms':round(statistics.median(row['first_ms'] for row in runs if row['variant']=='candidate'),3)})
    encoded = json.dumps(report, ensure_ascii=False, indent=2)
    if args.output:
        args.output.write_text(encoded + '\n', encoding='utf-8')
    else:
        print(encoded)


if __name__ == '__main__':
    main()