diff --git a/.github/scripts/ci-safety.test.cjs b/.github/scripts/ci-safety.test.cjs index 9da3438392..c561064dfb 100644 --- a/.github/scripts/ci-safety.test.cjs +++ b/.github/scripts/ci-safety.test.cjs @@ -532,3 +532,46 @@ for (const kind of ['squash', 'rebase', 'merge', 'direct']) { if (kind === 'rebase') assert.equal(existsSync(path.join(repo, 'feature-A')), true); }); } + +test('indexing before/after proof runs only while introducing the probe', t => { + const workflow = readFileSync(path.join(workflows, 'perf_probe.yml'), 'utf8'); + const selector = scripts('perf_probe.yml').find(script => + script.includes('run_indexing_pair.py') && script.includes('git ls-tree')); + assert.ok(selector, 'Run the PR-only comparison only if the probe is new to the base'); + assert.match(workflow, /needs\.contracts\.outputs\.indexing_probe_added == 'true'/); + assert.match(workflow, /github\.event_name == 'workflow_dispatch' && inputs\.indexing_baseline != ''/); + assert.match(workflow, /if: github\.event_name == 'pull_request'\s+shell: pwsh\s+env:[\s\S]*?verify_indexing_recovery_regression\.py/); + const dir = mkdtempSync(path.join(tmpdir(), 'otzaria-indexing-probe-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const git = (...args) => { + const result = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + return result.stdout.trim(); + }; + git('init', '-q'); + git('config', 'user.name', 'CI Test'); + git('config', 'user.email', 'ci-test@example.invalid'); + git('remote', 'add', 'origin', dir); + writeFileSync(path.join(dir, 'pubspec.lock'), 'original'); + git('add', '.'); + git('commit', '-qm', 'base before the probe'); + const before = git('rev-parse', 'HEAD'); + mkdirSync(path.join(dir, 'tool/perf_probe'), { recursive: true }); + writeFileSync(path.join(dir, 'tool/perf_probe/run_indexing_pair.py'), '# installed'); + git('add', '.'); + git('commit', '-qm', 'base after the probe'); + const after = git('rev-parse', 'HEAD'); + writeFileSync(path.join(dir, 'pubspec.lock'), 'changed candidate lock'); + git('commit', '-qam', 'future PR with different dependencies'); + + for (const [base, expected] of [[before, 'added=true'], [after, 'added=false']]) { + const output = path.join(dir, base); + const result = spawnSync('bash', ['-e', '-c', selector], { + cwd: dir, + env: { ...process.env, INDEX_BASELINE: base, GITHUB_OUTPUT: output }, + encoding: 'utf8', + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.equal(readFileSync(output, 'utf8').trim(), expected); + } +}); diff --git a/.github/workflows/perf_probe.yml b/.github/workflows/perf_probe.yml index c87d54243a..88d4114e8a 100644 --- a/.github/workflows/perf_probe.yml +++ b/.github/workflows/perf_probe.yml @@ -3,6 +3,9 @@ name: Performance probe tools on: pull_request: paths: + - 'test/tool/perf_probe/indexing_native_probe_test.dart' + - 'integration_test/indexing_native_probe_test.dart' + - 'test_driver/indexing_native_probe.dart' - 'tool/perf_probe/**' - 'tool/ci/prepare_native_build_dependencies.py' - 'tool/release/download_release_asset.sh' @@ -48,6 +51,9 @@ on: - '.github/workflows/perf_probe.yml' workflow_dispatch: inputs: + indexing_baseline: + description: Run indexing comparisons against this optional full baseline SHA + type: string mode: description: Build mode (results are never compared across modes) type: choice @@ -91,6 +97,55 @@ concurrency: cancel-in-progress: true jobs: + indexing_pair: + name: Native indexing pairs (debug and profile, same Windows host) + needs: [gate, contracts] + if: >- + needs.gate.outputs.run == 'true' && + (needs.contracts.outputs.indexing_probe_added == 'true' || + (github.event_name == 'workflow_dispatch' && inputs.indexing_baseline != '')) + runs-on: windows-2025 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - uses: ./.github/actions/setup-flutter + with: + flutter-version: 3.47.9 + - uses: dtolnay/rust-toolchain@stable + - name: Prove the original recovery regression + if: github.event_name == 'pull_request' + shell: pwsh + env: + INDEX_BASELINE: ${{ github.event.pull_request.base.sha }} + run: | + git config --global core.longpaths true + flutter pub get --enforce-lockfile + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python -B tool/perf_probe/verify_indexing_recovery_regression.py --baseline $env:INDEX_BASELINE --output (Join-Path $env:RUNNER_TEMP 'indexing-pair/regression') + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Compare immutable sources with alternating launches + shell: pwsh + env: + INDEX_BASELINE: ${{ github.event.pull_request.base.sha || inputs.indexing_baseline }} + INDEX_CANDIDATE: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + git config --global core.longpaths true + python -B tool/perf_probe/run_indexing_pair.py --baseline $env:INDEX_BASELINE --candidate $env:INDEX_CANDIDATE --output (Join-Path $env:RUNNER_TEMP 'indexing-pair') --warmups 1 --repetitions 5 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python -B tool/perf_probe/run_indexing_pair.py --baseline $env:INDEX_BASELINE --candidate $env:INDEX_CANDIDATE --output (Join-Path $env:RUNNER_TEMP 'indexing-pair/profile') --mode profile --pdf-pages 600 --warmups 1 --repetitions 5 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Preserve raw timings, completeness and partial failures + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: indexing-native-pair + retention-days: 14 + if-no-files-found: warn + path: ${{ runner.temp }}/indexing-pair/** + gate: uses: ./.github/workflows/ci_gate.yml permissions: @@ -103,8 +158,26 @@ jobs: if: needs.gate.outputs.run == 'true' runs-on: ubuntu-latest timeout-minutes: 5 + outputs: + indexing_probe_added: ${{ steps.indexing_probe.outputs.added }} steps: - uses: actions/checkout@v7.0.1 + - name: Detect the first indexing probe comparison + id: indexing_probe + if: github.event_name == 'pull_request' + env: + INDEX_BASELINE: ${{ github.event.pull_request.base.sha }} + run: | + git cat-file -e "${INDEX_BASELINE}^{commit}" || + git fetch --no-tags --depth=1 origin "$INDEX_BASELINE" + probe=$(git ls-tree "$INDEX_BASELINE" -- tool/perf_probe/run_indexing_pair.py) + if [ -z "$probe" ]; then + echo 'added=true' >> "$GITHUB_OUTPUT" + else + echo 'added=false' >> "$GITHUB_OUTPUT" + fi + - name: Validate indexing comparison contracts + run: python3 -B -m unittest tool.perf_probe.test_indexing_pair -v - name: Validate process identity and invariant CSV formatting shell: pwsh run: ./tool/perf_probe/test_sample_resources.ps1 diff --git a/docs/screenshots/issue6187/after-compact-dark.png b/docs/screenshots/issue6187/after-compact-dark.png new file mode 100644 index 0000000000..a246671ee3 Binary files /dev/null and b/docs/screenshots/issue6187/after-compact-dark.png differ diff --git a/docs/screenshots/issue6187/after-compact-light.png b/docs/screenshots/issue6187/after-compact-light.png new file mode 100644 index 0000000000..f77e141387 Binary files /dev/null and b/docs/screenshots/issue6187/after-compact-light.png differ diff --git a/docs/screenshots/issue6187/after-desktop-dark.png b/docs/screenshots/issue6187/after-desktop-dark.png new file mode 100644 index 0000000000..84a41b677c Binary files /dev/null and b/docs/screenshots/issue6187/after-desktop-dark.png differ diff --git a/docs/screenshots/issue6187/after-desktop-light.png b/docs/screenshots/issue6187/after-desktop-light.png new file mode 100644 index 0000000000..0849818988 Binary files /dev/null and b/docs/screenshots/issue6187/after-desktop-light.png differ diff --git a/docs/screenshots/issue6187/before-compact-dark.png b/docs/screenshots/issue6187/before-compact-dark.png new file mode 100644 index 0000000000..a73ee637af Binary files /dev/null and b/docs/screenshots/issue6187/before-compact-dark.png differ diff --git a/docs/screenshots/issue6187/before-compact-light.png b/docs/screenshots/issue6187/before-compact-light.png new file mode 100644 index 0000000000..f1b85e9f89 Binary files /dev/null and b/docs/screenshots/issue6187/before-compact-light.png differ diff --git a/docs/screenshots/issue6187/before-desktop-dark.png b/docs/screenshots/issue6187/before-desktop-dark.png new file mode 100644 index 0000000000..0e66251227 Binary files /dev/null and b/docs/screenshots/issue6187/before-desktop-dark.png differ diff --git a/docs/screenshots/issue6187/before-desktop-light.png b/docs/screenshots/issue6187/before-desktop-light.png new file mode 100644 index 0000000000..7facfc1614 Binary files /dev/null and b/docs/screenshots/issue6187/before-desktop-light.png differ diff --git a/docs/screenshots/issue6187/retry-compact-dark.png b/docs/screenshots/issue6187/retry-compact-dark.png new file mode 100644 index 0000000000..2552e3a9ec Binary files /dev/null and b/docs/screenshots/issue6187/retry-compact-dark.png differ diff --git a/docs/screenshots/issue6187/retry-compact-light.png b/docs/screenshots/issue6187/retry-compact-light.png new file mode 100644 index 0000000000..8f71b45a92 Binary files /dev/null and b/docs/screenshots/issue6187/retry-compact-light.png differ diff --git a/docs/screenshots/issue6187/retry-desktop-dark.png b/docs/screenshots/issue6187/retry-desktop-dark.png new file mode 100644 index 0000000000..e073f962af Binary files /dev/null and b/docs/screenshots/issue6187/retry-desktop-dark.png differ diff --git a/docs/screenshots/issue6187/retry-desktop-light.png b/docs/screenshots/issue6187/retry-desktop-light.png new file mode 100644 index 0000000000..39100c65fb Binary files /dev/null and b/docs/screenshots/issue6187/retry-desktop-light.png differ diff --git a/integration_test/indexing_native_probe_test.dart b/integration_test/indexing_native_probe_test.dart new file mode 100644 index 0000000000..ebbe5fe61b --- /dev/null +++ b/integration_test/indexing_native_probe_test.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/tool/perf_probe/indexing_native_probe_test.dart' + as native_probe; + +import 'support/webview_probe_window.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + testWidgets('native indexing report completed and verified', (tester) async { + final root = Platform.environment['OTZARIA_INDEXING_PROBE_ROOT']; + if (root != null) { + Directory.current = root; + } + final output = Platform.environment['OTZARIA_INDEXING_PROBE_OUT']; + expect(output, isNotNull, reason: 'Set OTZARIA_INDEXING_PROBE_OUT'); + final file = File(output!); + expect(await file.exists(), isFalse, reason: 'Use a fresh output path'); + await tester.pumpWidget(const SizedBox.shrink()); + final window = await prepareWebViewProbeWindow( + platform: Platform.operatingSystem, + pumpFrame: () => tester.pump(const Duration(milliseconds: 16)), + ); + expect(window['ready'], isTrue); + final report = await native_probe.runNativeIndexingMeasurement(file.path); + expect(report['schemaVersion'], 2); + final pdfPageCount = report['pdfPageCount'] as int; + expect(pdfPageCount, greaterThan(0)); + final rows = (report['rows'] as List).cast>(); + expect(rows, hasLength(8)); + final cases = {}; + final titles = {for (var i = 0; i < 8; i++) 'book$i'}; + for (final row in rows) { + cases.add('${row['case']}:${row['economy']}'); + expect(row['books'], 8); + final expectedHits = (row['case'] as String).startsWith('pdf') + ? 8 * pdfPageCount + : 8000; + expect(row['documentsMatched'], expectedHits); + expect(row['elapsedUs'], greaterThan(0)); + expect(row['segmentCount'], greaterThan(0)); + final stamps = (row['textFingerprints'] as Map).cast(); + expect(stamps.keys.toSet(), titles); + expect( + stamps.values.map(BigInt.parse), + everyElement(greaterThan(BigInt.zero)), + ); + final hits = row['hitsPerBook'] as Map; + expect(hits.keys.toSet(), titles); + expect(hits.values, everyElement(expectedHits ~/ 8)); + expect( + row['hitContentSha256'], + matches(RegExp(r'^[a-f0-9]{64}$')), + ); + } + expect(cases, { + for (final kind in ['txt', 'docx', 'pdf', 'pdf-recovery']) + for (final economy in [false, true]) '$kind:$economy', + }); + report['buildMode'] = kProfileMode + ? 'integration-test-profile-aot/native-build-hook' + : kReleaseMode + ? 'integration-test-release-aot/native-build-hook' + : 'integration-test-debug/native-build-hook'; + report['window'] = window; + report['executionHarness'] = + 'minimal native window; no UI responsiveness measurement'; + await file.writeAsString(jsonEncode(report)); + binding.reportData = report; + await tester.pumpWidget(const SizedBox.shrink()); + }, timeout: const Timeout(Duration(minutes: 15))); +} diff --git a/integration_test/support/installed_plugin_pdf_fixture.dart b/integration_test/support/installed_plugin_pdf_fixture.dart index 29d999625a..0fc4034e73 100644 --- a/integration_test/support/installed_plugin_pdf_fixture.dart +++ b/integration_test/support/installed_plugin_pdf_fixture.dart @@ -12,15 +12,19 @@ const installedPdfQuery = 'bundleruntime'; String installedPdfPageToken(int pageNumber) => 'bundlepage$pageNumber'; /// מסמך קבוע עם טקסט ומלבן שחור; ללא גופני מערכת, תאריכים או רשת. -Uint8List createInstalledPdfFixture() { +Uint8List createInstalledPdfFixture({int? pageCount}) { + final count = pageCount ?? installedPdfPageSizes.length; + if (count <= 0) { + throw ArgumentError.value(pageCount, 'pageCount'); + } final objects = [ '<< /Type /Catalog /Pages 2 0 R >>', - '<< /Type /Pages /Count ${installedPdfPageSizes.length} /Kids [ ' - '${List.generate(installedPdfPageSizes.length, (i) => '${4 + i * 2} 0 R').join(' ')} ] >>', + '<< /Type /Pages /Count $count /Kids [ ' + '${List.generate(count, (i) => '${4 + i * 2} 0 R').join(' ')} ] >>', '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', ]; - for (var i = 0; i < installedPdfPageSizes.length; i++) { - final size = installedPdfPageSizes[i]; + for (var i = 0; i < count; i++) { + final size = installedPdfPageSizes[i % installedPdfPageSizes.length]; final content = '1 g 0 0 ${size.width} ${size.height} re f 0 g\n' 'BT /F1 12 Tf 20 ${size.height - 30} Td ' diff --git a/lib/indexing/bloc/indexing_bloc.dart b/lib/indexing/bloc/indexing_bloc.dart index ea7b7c1457..90be4da774 100644 --- a/lib/indexing/bloc/indexing_bloc.dart +++ b/lib/indexing/bloc/indexing_bloc.dart @@ -1,3 +1,5 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; + import 'dart:async'; import 'package:bloc_concurrency/bloc_concurrency.dart'; @@ -29,6 +31,9 @@ class IndexingBloc extends Bloc { int? _activeWorkId; bool _isPaused = false; bool _isFinalizing = false; + int? _pdfPagesProcessed; + int? _pdfTotalPages; + PdfIndexingPhase _pdfPhase = PdfIndexingPhase.extraction; // ביטול מנקז את ריצות האינדוקס שכבר בתור: הן נשלחו לפני שהמשתמש עצר. final _enqueuedAtCancelCount = Expando(); @@ -66,6 +71,7 @@ class IndexingBloc extends Bloc { on(_onActualIndexingStarted); on(_onFinalizing); on(_onUpdateProgress); + on(_onPdfProgress); } /// Factory constructor that creates an IndexingBloc with a default repository @@ -98,6 +104,9 @@ class IndexingBloc extends Bloc { isPaused: _isPaused, isEconomy: _repository.isEconomyIndexing, isFinalizing: _isFinalizing, + pdfPagesProcessed: _pdfPagesProcessed, + pdfTotalPages: _pdfTotalPages, + pdfPhase: _pdfPhase, ); Future _onIndexingWork( @@ -268,6 +277,9 @@ class IndexingBloc extends Bloc { Emitter emit, ) async { final workId = ++_nextWorkId; + _pdfPagesProcessed = null; + _pdfTotalPages = null; + _pdfPhase = PdfIndexingPhase.extraction; final runClock = Stopwatch()..start(); _activeWorkId = workId; @@ -300,6 +312,11 @@ class IndexingBloc extends Bloc { }, onActualIndexingStarted: () => add(ActualIndexingStarted(workId)), onProgress: _progressOf(workId), + onPdfProgress: (progress) { + if (!isClosed && _activeWorkId == workId) { + add(UpdatePdfIndexingProgress(workId, progress)); + } + }, onFinalizing: () => add(IndexingFinalizing(workId)), ), ); @@ -370,6 +387,9 @@ class IndexingBloc extends Bloc { final currentState = state; if (currentState is! IndexingInProgress) return; _isFinalizing = true; + _pdfPagesProcessed = null; + _pdfTotalPages = null; + _pdfPhase = PdfIndexingPhase.extraction; emit( _inProgress( booksProcessed: currentState.booksProcessed, @@ -459,6 +479,9 @@ class IndexingBloc extends Bloc { void _cancelWork() { _activeWorkId = null; + _pdfPagesProcessed = null; + _pdfTotalPages = null; + _pdfPhase = PdfIndexingPhase.extraction; _isPaused = false; _cancelCount++; _repository.cancelIndexing(); @@ -540,4 +563,25 @@ class IndexingBloc extends Bloc { ); } } + + void _onPdfProgress( + UpdatePdfIndexingProgress event, + Emitter emit, + ) { + if (_activeWorkId != event.workId || + state is! IndexingInProgress || + _isFinalizing) { + return; + } + final progress = event.progress; + if (progress != null && !_repository.isIndexing()) return; + _pdfTotalPages = progress != null && progress.total > 0 + ? progress.total + : null; + _pdfPagesProcessed = _pdfTotalPages == null + ? null + : progress!.processed.clamp(0, progress.total); + _pdfPhase = progress?.phase ?? PdfIndexingPhase.extraction; + _reemitProgressFlags(emit); + } } diff --git a/lib/indexing/bloc/indexing_event.dart b/lib/indexing/bloc/indexing_event.dart index 4f5a17a51e..0de7ca8328 100644 --- a/lib/indexing/bloc/indexing_event.dart +++ b/lib/indexing/bloc/indexing_event.dart @@ -1,3 +1,4 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:equatable/equatable.dart'; import 'package:otzaria/indexing/models/index_check_scope.dart'; import 'package:otzaria/library/models/library.dart'; @@ -207,3 +208,13 @@ class UpdateIndexingProgress extends IndexingEvent { total, ]; } + +class UpdatePdfIndexingProgress extends IndexingEvent { + const UpdatePdfIndexingProgress(this.workId, this.progress); + + final int workId; + final PdfIndexingProgress? progress; + + @override + List get props => [workId, progress]; +} diff --git a/lib/indexing/bloc/indexing_state.dart b/lib/indexing/bloc/indexing_state.dart index a5c376ecd7..8bfbf41ef9 100644 --- a/lib/indexing/bloc/indexing_state.dart +++ b/lib/indexing/bloc/indexing_state.dart @@ -1,3 +1,4 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:equatable/equatable.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; @@ -27,6 +28,9 @@ class IndexingInProgress extends IndexingState { this.isPaused = false, this.isEconomy = false, this.isFinalizing = false, + this.pdfPagesProcessed, + this.pdfTotalPages, + this.pdfPhase = PdfIndexingPhase.extraction, }); /// שלב הבדיקה של ריצת אינדוקס — אילו ספרים מאונדקסים התיישנו. @@ -43,6 +47,27 @@ class IndexingInProgress extends IndexingState { /// אין לשלב זה התקדמות מדידה, ולכן המונה מוחלף בהודעה נפרדת. final bool isFinalizing; + final int? pdfPagesProcessed; + final int? pdfTotalPages; + final PdfIndexingPhase pdfPhase; + + /// מסנן עדכוני עמודים אצל צרכנים שמציגים רק התקדמות של ספרים. + static bool bookProgressChanged( + IndexingState previous, + IndexingState current, + ) { + if (previous is! IndexingInProgress || current is! IndexingInProgress) { + return true; + } + return previous.booksProcessed != current.booksProcessed || + previous.totalBooks != current.totalBooks || + previous.isCreatingIndex != current.isCreatingIndex || + previous.isScanning != current.isScanning || + previous.isPaused != current.isPaused || + previous.isEconomy != current.isEconomy || + previous.isFinalizing != current.isFinalizing; + } + @override List get props => [ ...super.props, @@ -50,6 +75,9 @@ class IndexingInProgress extends IndexingState { isPaused, isEconomy, isFinalizing, + pdfPagesProcessed, + pdfTotalPages, + pdfPhase, ]; } diff --git a/lib/indexing/indexing_work_status.dart b/lib/indexing/indexing_work_status.dart index 8dafc66f2b..494900ac42 100644 --- a/lib/indexing/indexing_work_status.dart +++ b/lib/indexing/indexing_work_status.dart @@ -1,3 +1,4 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; import 'package:flutter/foundation.dart'; import 'package:otzaria/indexing/bloc/indexing_state.dart'; @@ -6,6 +7,9 @@ import 'package:otzaria/work_status/work_status_item.dart'; /// מזהה פריט חיווי העבודה של האינדוקס. const kIndexingWorkStatusId = 'indexing'; +bool shouldShowIndexingWorkStatus(IndexingInProgress state) => + state.isCreatingIndex || state.isScanning || state.pdfTotalPages != null; + /// פריט חיווי העבודה לאינדוקס, כולל לחצני השהיה/המשך ומצב חסכוני /// (issue #834). WorkStatusItem indexingWorkStatusItem( @@ -35,11 +39,17 @@ WorkStatusItem indexingWorkStatusItem( } else { message = state.isPaused ? 'האינדוקס מושהה' : 'התוכנה בתהליך אינדוקס'; } + final pdfLabel = state.pdfPhase == PdfIndexingPhase.retry + ? 'ניסיון חוזר לחילוץ PDF' + : 'חילוץ PDF ברקע'; return WorkStatusItem( id: kIndexingWorkStatusId, title: 'אינדוקס ספרים', message: message, - detail: 'התקדמות: $processed/$total', + detail: state.pdfTotalPages != null && !state.isScanning + ? 'התקדמות: $processed/$total · $pdfLabel: ' + '${state.pdfPagesProcessed}/${state.pdfTotalPages} עמודים' + : 'התקדמות: $processed/$total', progress: total > 0 ? (processed / total).clamp(0.0, 1.0) : null, onTap: onTap, actions: [ diff --git a/lib/indexing/models/indexing_resource_policy.dart b/lib/indexing/models/indexing_resource_policy.dart index 846905dcb5..98de6ab447 100644 --- a/lib/indexing/models/indexing_resource_policy.dart +++ b/lib/indexing/models/indexing_resource_policy.dart @@ -13,6 +13,17 @@ enum IndexingResourceMode { }; } +enum IndexingResourceReason { + explicitEconomy, + explicitNormal, + mobile, + lowCpu, + unknownRam, + lowRam, + lowAvailableRam, + normal, +} + class IndexingResourcePolicy { const IndexingResourcePolicy({ required this.cpuCount, @@ -26,15 +37,26 @@ class IndexingResourcePolicy { final int? totalRamMb; final int? availableRamMb; - bool useEconomy(IndexingResourceMode mode) => switch (mode) { - IndexingResourceMode.economy => true, - IndexingResourceMode.normal => false, - IndexingResourceMode.automatic => - mobile || - cpuCount <= 4 || - totalRamMb == null || - totalRamMb! <= 4096 || - (availableRamMb != null && availableRamMb! < 1024), + IndexingResourceReason reason(IndexingResourceMode mode) => switch (mode) { + IndexingResourceMode.economy => IndexingResourceReason.explicitEconomy, + IndexingResourceMode.normal => IndexingResourceReason.explicitNormal, + IndexingResourceMode.automatic when mobile => IndexingResourceReason.mobile, + IndexingResourceMode.automatic when cpuCount <= 4 => + IndexingResourceReason.lowCpu, + IndexingResourceMode.automatic when totalRamMb == null => + IndexingResourceReason.unknownRam, + IndexingResourceMode.automatic when totalRamMb! <= 4096 => + IndexingResourceReason.lowRam, + IndexingResourceMode.automatic + when availableRamMb != null && availableRamMb! < 1024 => + IndexingResourceReason.lowAvailableRam, + IndexingResourceMode.automatic => IndexingResourceReason.normal, + }; + + bool useEconomy(IndexingResourceMode mode) => switch (reason(mode)) { + IndexingResourceReason.explicitNormal || + IndexingResourceReason.normal => false, + _ => true, }; static IndexingResourcePolicy conservative() => IndexingResourcePolicy( diff --git a/lib/indexing/models/indexing_run_diagnostics.dart b/lib/indexing/models/indexing_run_diagnostics.dart new file mode 100644 index 0000000000..9730a6d1dc --- /dev/null +++ b/lib/indexing/models/indexing_run_diagnostics.dart @@ -0,0 +1,125 @@ +import 'package:equatable/equatable.dart'; +import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; + +enum IndexingStage { + preparation, + scan, + sourceLoading, + engine, + pdfExtraction, + commit, + optimize, +} + +enum IndexingCounter { + // כתיבות שהמנוע אישר; ביטול או התאוששות עשויים להסירן בהמשך. + documents, + pdfPages, + droppedPdfPages, + prefetchedPdfBooks, +} + +/// החלטת משאבים והדגימה שעליה היא מבוססת, ללא נתוני ספרים אישיים. +class IndexingResourceDecision extends Equatable { + IndexingResourceDecision(IndexingResourcePolicy policy, this.mode) + : reason = policy.reason(mode), + cpuCount = policy.cpuCount, + totalRamMb = policy.totalRamMb, + availableRamMb = policy.availableRamMb; + + final IndexingResourceMode mode; + final IndexingResourceReason reason; + final int cpuCount; + final int? totalRamMb; + final int? availableRamMb; + + @override + List get props => [ + mode, + reason, + cpuCount, + totalRamMb, + availableRamMb, + ]; +} + +/// זמני עבודה עשויים לחפוף בגלל חילוץ מוקדם; סכומם אינו זמן הריצה. +class IndexingRunDiagnostics extends Equatable { + IndexingRunDiagnostics({ + Map stageTimes = const {}, + Map counters = const {}, + List resourceDecisions = const [], + this.recoveryStarted = false, + }) : stageTimes = Map.unmodifiable(stageTimes), + counters = Map.unmodifiable(counters), + resourceDecisions = List.unmodifiable(resourceDecisions); + + final Map stageTimes; + final Map counters; + final List resourceDecisions; + final bool recoveryStarted; + + @override + List get props => [ + stageTimes, + counters, + resourceDecisions, + recoveryStarted, + ]; +} + +/// אוסף מקומי לריצה; תמונת מצב אינה משתנה כשעבודת רקע מסתיימת מאוחר. +class IndexingRunDiagnosticsCollector { + final _stageTimes = {}; + final _counters = {}; + final _resourceDecisions = []; + IndexingResourcePolicy? _lastPolicy; + bool recoveryStarted = false; + + void addTime(IndexingStage stage, Duration elapsed) { + _stageTimes.update( + stage, + (value) => value + elapsed, + ifAbsent: () => elapsed, + ); + } + + Future measure(IndexingStage stage, Future Function() action) async { + final watch = Stopwatch()..start(); + try { + return await action(); + } finally { + addTime(stage, watch.elapsed); + } + } + + void increment(IndexingCounter counter, [int amount = 1]) { + _counters.update( + counter, + (value) => value + amount, + ifAbsent: () => amount, + ); + } + + void recordResources( + IndexingResourcePolicy policy, + IndexingResourceMode mode, + ) { + if (identical(_lastPolicy, policy) && + _resourceDecisions.last.mode == mode) { + return; + } + _lastPolicy = policy; + final decision = IndexingResourceDecision(policy, mode); + if (_resourceDecisions.isEmpty || _resourceDecisions.last != decision) { + _resourceDecisions.add(decision); + } + } + + IndexingRunDiagnostics snapshot() => IndexingRunDiagnostics( + stageTimes: _stageTimes, + counters: _counters, + resourceDecisions: _resourceDecisions, + recoveryStarted: recoveryStarted, + ); +} diff --git a/lib/indexing/models/indexing_run_result.dart b/lib/indexing/models/indexing_run_result.dart index b3ee40e4d5..4f7bb43524 100644 --- a/lib/indexing/models/indexing_run_result.dart +++ b/lib/indexing/models/indexing_run_result.dart @@ -1,4 +1,5 @@ import 'package:equatable/equatable.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; enum IndexingFailureKind { partialPdf(isRetryable: false, preventedIndexing: false), @@ -51,6 +52,7 @@ class IndexingRunResult extends Equatable { required this.totalBooks, required this.indexedBooks, this.failures = const [], + this.diagnostics, }) : cancelled = false; const IndexingRunResult.cancelled({ @@ -58,6 +60,7 @@ class IndexingRunResult extends Equatable { required this.totalBooks, required this.indexedBooks, this.failures = const [], + this.diagnostics, }) : cancelled = true; final int processedBooks; @@ -65,6 +68,7 @@ class IndexingRunResult extends Equatable { final int indexedBooks; final bool cancelled; final List failures; + final IndexingRunDiagnostics? diagnostics; bool get completed => !cancelled; bool get isClean => completed && failures.isEmpty; @@ -85,5 +89,6 @@ class IndexingRunResult extends Equatable { indexedBooks, cancelled, failures, + diagnostics, ]; } diff --git a/lib/indexing/models/pdf_indexing_progress.dart b/lib/indexing/models/pdf_indexing_progress.dart new file mode 100644 index 0000000000..70a938a092 --- /dev/null +++ b/lib/indexing/models/pdf_indexing_progress.dart @@ -0,0 +1,19 @@ +import 'package:equatable/equatable.dart'; + +enum PdfIndexingPhase { extraction, retry } + +/// מספר העמודים שהטיפול בהם הסתיים בשלב הנוכחי, כולל עמודים ללא טקסט. +class PdfIndexingProgress extends Equatable { + const PdfIndexingProgress({ + required this.processed, + required this.total, + this.phase = PdfIndexingPhase.extraction, + }); + + final int processed; + final int total; + final PdfIndexingPhase phase; + + @override + List get props => [processed, total, phase]; +} diff --git a/lib/indexing/repository/indexing_repository.dart b/lib/indexing/repository/indexing_repository.dart index 65fadd5af3..f1ae20c5b5 100644 --- a/lib/indexing/repository/indexing_repository.dart +++ b/lib/indexing/repository/indexing_repository.dart @@ -1,3 +1,4 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; import 'package:otzaria/indexing/services/indexing_resource_sampler.dart'; import 'package:otzaria/indexing/utils/indexing_yield.dart'; @@ -12,12 +13,14 @@ import 'package:otzaria/library/hidden/hidden_library_store.dart'; import 'package:otzaria/indexing/models/index_update_mode.dart'; import 'package:otzaria/indexing/models/pdf_index_setting.dart'; import 'package:otzaria/utils/file/disk_free_space.dart'; + import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; + import 'package:flutter/foundation.dart' hide Category; import 'package:otzaria/core/app_paths.dart'; import 'package:otzaria/core/info/personal_folders_info.dart'; @@ -40,6 +43,7 @@ import 'package:otzaria/indexing/models/index_check_scope.dart'; import 'package:otzaria/indexing/utils/book_source_hashes.dart'; import 'package:otzaria/indexing/models/index_commit_policy.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; import 'package:otzaria/attached_libraries/models/attached_library.dart'; import 'package:otzaria/attached_libraries/repository/attached_library_registry.dart'; import 'package:otzaria/models/book_source.dart'; @@ -196,12 +200,16 @@ class IndexingRepository { } @visibleForTesting - Future prepareIndexingResources() async { + Future prepareIndexingResources([ + IndexingRunDiagnosticsCollector? diagnostics, + ]) async { _resources = await sampleResources(); - await _applyResourcePolicy(); + await _applyResourcePolicy(diagnostics); } - Future _applyResourcePolicy() async { + Future _applyResourcePolicy([ + IndexingRunDiagnosticsCollector? diagnostics, + ]) async { final resources = _resources; if (resources == null) return; final mode = IndexingResourceMode.fromStorage( @@ -215,6 +223,7 @@ class IndexingRepository { if (_tantivyDataProvider.isEconomyIndexing != economy) { await _tantivyDataProvider.setEconomyIndexing(economy); } + diagnostics?.recordResources(resources, mode); } Future _waitWhilePaused() async { @@ -537,6 +546,7 @@ class IndexingRepository { bool includePdfBooks = true, void Function(int processed, int total)? onScanProgress, void Function(int total)? onWorkListReady, + void Function(PdfIndexingProgress? progress)? onPdfProgress, void Function()? onActualIndexingStarted, required void Function(int processed, int total) onProgress, void Function()? onFinalizing, @@ -549,10 +559,12 @@ class IndexingRepository { ); } final cancellationGeneration = _cancellationGeneration; + final diagnostics = IndexingRunDiagnosticsCollector(); _runStarted(); try { - return await _runIndexing( + final result = await _runIndexing( library, + diagnostics: diagnostics, cancellationGeneration: cancellationGeneration, books: books, changedBooks: changedBooks, @@ -560,10 +572,26 @@ class IndexingRepository { includePdfBooks: includePdfBooks, onScanProgress: onScanProgress, onWorkListReady: onWorkListReady, + onPdfProgress: onPdfProgress, onActualIndexingStarted: onActualIndexingStarted, onProgress: onProgress, onFinalizing: onFinalizing, ); + return result.cancelled + ? IndexingRunResult.cancelled( + processedBooks: result.processedBooks, + totalBooks: result.totalBooks, + indexedBooks: result.indexedBooks, + failures: result.failures, + diagnostics: diagnostics.snapshot(), + ) + : IndexingRunResult.completed( + processedBooks: result.processedBooks, + totalBooks: result.totalBooks, + indexedBooks: result.indexedBooks, + failures: result.failures, + diagnostics: diagnostics.snapshot(), + ); } finally { _runEnded(); } @@ -571,6 +599,7 @@ class IndexingRepository { Future _runIndexing( Library library, { + required IndexingRunDiagnosticsCollector diagnostics, required int cancellationGeneration, List? books, List changedBooks = const [], @@ -578,6 +607,7 @@ class IndexingRepository { bool includePdfBooks = true, void Function(int processed, int total)? onScanProgress, void Function(int total)? onWorkListReady, + void Function(PdfIndexingProgress? progress)? onPdfProgress, void Function()? onActualIndexingStarted, required void Function(int processed, int total) onProgress, void Function()? onFinalizing, @@ -626,7 +656,10 @@ class IndexingRepository { ); } - await syncBookOrder(library); + await diagnostics.measure( + IndexingStage.preparation, + () => syncBookOrder(library), + ); final libraryBooks = wholeLibrary ? scope : eligible(library.getIndexableBooks()); @@ -760,14 +793,17 @@ class IndexingRepository { book, ]; final metadataChanged = {}; - final detected = await changeDetector.detectChanged( - candidates, - library: library, - isCancelled: () => !_tantivyDataProvider.isIndexing.value, - waitWhilePaused: _waitWhilePaused, - onMetadataOnlyChanged: (book) => - metadataChanged.add(BookIdentity.indexedFilePath(book)), - onProgress: onScanProgress, + final detected = await diagnostics.measure( + IndexingStage.scan, + () => changeDetector.detectChanged( + candidates, + library: library, + isCancelled: () => !_tantivyDataProvider.isIndexing.value, + waitWhilePaused: _waitWhilePaused, + onMetadataOnlyChanged: (book) => + metadataChanged.add(BookIdentity.indexedFilePath(book)), + onProgress: onScanProgress, + ), ); if (detected == null || !_tantivyDataProvider.isIndexing.value) { return IndexingRunResult.cancelled( @@ -818,7 +854,10 @@ class IndexingRepository { } final totalBooks = allBooks.length; final replacing = pending.isNotEmpty; - await prepareIndexingResources(); + await diagnostics.measure( + IndexingStage.preparation, + () => prepareIndexingResources(diagnostics), + ); if (!_tantivyDataProvider.isIndexing.value) { return IndexingRunResult.cancelled( processedBooks: 0, @@ -840,6 +879,7 @@ class IndexingRepository { : null, ); final canary = IndexingCrashCanary.current; + diagnostics.recoveryStarted = canary?.recovering ?? false; if (canary?.recovering ?? false) { // ספר שהוחלף נשאר באינדקס החתום בתוכנו הישן — אינו מעיד שלא קרס. canary!.forgetIndexed( @@ -848,17 +888,24 @@ class IndexingRepository { ); } prefetcher = PdfExtractionPrefetcher( - extract: extractPdfPagesGuarded, - maxInFlight: IndexingCrashCanary.current?.recovering ?? false - ? 0 - : PdfExtractionPrefetcher.defaultMaxInFlight, + extract: (book) => diagnostics.measure( + IndexingStage.pdfExtraction, + () => extractPdfPagesGuarded(book, onProgress: onPdfProgress), + ), + canPrefetch: () => !(canary?.recovering ?? false), + ); + final sourceHashes = await diagnostics.measure( + IndexingStage.preparation, + () => loadSourceHashes(allBooks), + ); + await diagnostics.measure( + IndexingStage.preparation, + () => Future.wait([ + GenerationCache.instance.warmUp(), + ReferenceBooksCache.instance.warmUp(), + BookFacetMetadataCache.instance.warmUp(), + ]), ); - final sourceHashes = await loadSourceHashes(allBooks); - await Future.wait([ - GenerationCache.instance.warmUp(), - ReferenceBooksCache.instance.warmUp(), - BookFacetMetadataCache.instance.warmUp(), - ]); final totalStopwatch = Stopwatch()..start(); final commitStopwatch = Stopwatch(); @@ -882,7 +929,7 @@ class IndexingRepository { cancelled = true; break; } - await _applyResourcePolicy(); + await _applyResourcePolicy(diagnostics); await _waitWhilePaused(); if (!_tantivyDataProvider.isIndexing.value) { cancelled = true; @@ -915,10 +962,12 @@ class IndexingRepository { } try { await _dropReplacedDocs(replaceKeys, [readyBook]); - final droppedPages = await _indexPdfBook( + final pdfResult = await _indexPdfBook( readyBook, + diagnostics: diagnostics, sourceHashes: sourceHashes, preExtracted: ready.extraction, + onPdfProgress: onPdfProgress, onActualIndexingStarted: onFirstActualIndexing, ); if (!_tantivyDataProvider.isIndexing.value) { @@ -928,10 +977,14 @@ class IndexingRepository { cancelled = true; break bookLoop; } - _recordPartialPdfFailure(readyBook, droppedPages, failures); + _recordPartialPdfFailure( + readyBook, + pdfResult.droppedPages, + failures, + ); _markWritten(BookIdentity.indexedFilePath(readyBook)); actuallyIndexed++; - commitPolicy.recordBook(); + commitPolicy.recordBook(docs: pdfResult.docs); } catch (e, stackTrace) { debugPrint('❌ שגיאה באינדוקס מוקדם של ${readyBook.title}: $e'); errors++; @@ -942,6 +995,7 @@ class IndexingRepository { failure, sourceHashes, failures, + diagnostics: diagnostics, replaceKeys: replaceKeys, ); if (handled) { @@ -976,6 +1030,7 @@ class IndexingRepository { allBooks, bookIndex, libraryBatches, + diagnostics: diagnostics, replaceKeys: replaceKeys, sourceHashes: sourceHashes, onActualIndexingStarted: onFirstActualIndexing, @@ -994,6 +1049,7 @@ class IndexingRepository { await _dropReplacedDocs(replaceKeys, [book]); final docs = await _indexTextBook( textBookForIndex, + diagnostics: diagnostics, sourceHashes: sourceHashes, onActualIndexingStarted: onFirstActualIndexing, ); @@ -1029,10 +1085,12 @@ class IndexingRepository { shouldPrefetch: shouldPrefetch, ); await _dropReplacedDocs(replaceKeys, [book]); - final droppedPages = await _indexPdfBook( + final pdfResult = await _indexPdfBook( book, + diagnostics: diagnostics, sourceHashes: sourceHashes, preExtracted: preExtracted, + onPdfProgress: onPdfProgress, onActualIndexingStarted: onFirstActualIndexing, ); if (!_tantivyDataProvider.isIndexing.value) { @@ -1040,10 +1098,10 @@ class IndexingRepository { cancelled = true; break; } - _recordPartialPdfFailure(book, droppedPages, failures); + _recordPartialPdfFailure(book, pdfResult.droppedPages, failures); _markWritten(BookIdentity.indexedFilePath(book)); actuallyIndexed++; - commitPolicy.recordBook(); + commitPolicy.recordBook(docs: pdfResult.docs); bookWasIndexed = true; } else { skipped++; @@ -1055,7 +1113,7 @@ class IndexingRepository { commitStopwatch ..reset() ..start(); - await _commitIndex(); + await _commitIndex(diagnostics); debugPrint( '💾 commit אחרי ${commitPolicy.pendingBooks} ספרים ' '(${commitPolicy.pendingDocs} מסמכים): ' @@ -1092,6 +1150,7 @@ class IndexingRepository { failure, sourceHashes, failures, + diagnostics: diagnostics, replaceKeys: replaceKeys, ); if (handled) { @@ -1125,12 +1184,15 @@ class IndexingRepository { commitStopwatch ..reset() ..start(); - final index = await _commitIndex(); + final index = await _commitIndex(diagnostics); debugPrint('💾 commit סופי: ${commitStopwatch.elapsedMilliseconds}ms'); await savePendingAfterCommit(); if (compact) { final optimizeStopwatch = Stopwatch()..start(); - await optimizeIndexBestEffort(index.optimize); + await diagnostics.measure( + IndexingStage.optimize, + () => optimizeIndexBestEffort(index.optimize), + ); debugPrint( '⚙️ optimize: ${optimizeStopwatch.elapsedMilliseconds}ms', ); @@ -1141,7 +1203,7 @@ class IndexingRepository { writeBufferDiscarded: writeBufferDiscarded, )) { // בלי commit בביטול, כל מה שאונדקס מאז ה-commit האחרון אבד. - await _commitIndex(); + await _commitIndex(diagnostics); debugPrint('💾 commit אחרי ביטול: ${commitPolicy.pendingBooks} ספרים'); await savePendingAfterCommit(); } @@ -1190,6 +1252,7 @@ class IndexingRepository { /// מחזיר את מספר המסמכים שנוספו (0 כשנכתב סמן ספר ריק). Future _indexTextBook( TextBook book, { + required IndexingRunDiagnosticsCollector diagnostics, required BookSourceHashes sourceHashes, void Function()? onActualIndexingStarted, }) async { @@ -1197,7 +1260,10 @@ class IndexingRepository { // גולמיים, בלי פענוח ל-String וקידוד חוזר על הגשר (~180ms/MB). await _beginBook(book); final loadStopwatch = Stopwatch()..start(); - final source = await loadTextBookSource(book); + final source = await diagnostics.measure( + IndexingStage.sourceLoading, + () => loadTextBookSource(book), + ); final bytes = source.bytes; final text = source.text; loadStopwatch.stop(); @@ -1231,17 +1297,26 @@ class IndexingRepository { ? source.dataUriLines : null; // קידוד String על גשר המנוע רץ על ה-UI isolate (337ms לספר של 18M תווים). - final payload = hasBytes ? bytes : await _utf8EncodeOffFrame(text!); - added = await engine.addTextBookBytes( - title: title, - topics: topics, - filePath: filePath, - text: payload, - sourceHash: _dbSourceHash(book, sourceHashes), - extraFacets: extraFacets, - textStorage: textStorage, - storedLines: storedLines, + final payload = hasBytes + ? bytes + : await diagnostics.measure( + IndexingStage.sourceLoading, + () => _utf8EncodeOffFrame(text!), + ); + added = await diagnostics.measure( + IndexingStage.engine, + () => engine.addTextBookBytes( + title: title, + topics: topics, + filePath: filePath, + text: payload, + sourceHash: _dbSourceHash(book, sourceHashes), + extraFacets: extraFacets, + textStorage: textStorage, + storedLines: storedLines, + ), ); + diagnostics.increment(IndexingCounter.documents, added); engineStopwatch.stop(); final size = hasBytes ? '${bytes.length} בייטים' @@ -1259,6 +1334,7 @@ class IndexingRepository { // אין תוכן ⇒ אין טביעת אצבע; במסלול המלא המנוע חותם אותה בעצמו. await _writeEmptyBookMarker( book, + diagnostics: diagnostics, sourceHashes: sourceHashes, ); } @@ -1331,6 +1407,7 @@ class IndexingRepository { List books, int start, _LibraryBatches batches, { + required IndexingRunDiagnosticsCollector diagnostics, required Set replaceKeys, required BookSourceHashes sourceHashes, void Function()? onActualIndexingStarted, @@ -1344,7 +1421,7 @@ class IndexingRepository { await _waitWhilePaused(); await yieldToIndexingForeground(); if (!_tantivyDataProvider.isIndexing.value) break; - await _applyResourcePolicy(); + await _applyResourcePolicy(diagnostics); await _waitWhilePaused(); if (!_tantivyDataProvider.isIndexing.value) break; final canary = IndexingCrashCanary.current; @@ -1417,6 +1494,7 @@ class IndexingRepository { } break; } finally { + diagnostics.addTime(IndexingStage.engine, stopwatch.elapsed); _libraryBatchToken = null; _tantivyDataProvider.isIndexing.removeListener(cancelOnStop); } @@ -1437,6 +1515,7 @@ class IndexingRepository { added.add(result.docs); indexedBooks++; docs += result.docs; + diagnostics.increment(IndexingCounter.documents, result.docs); case LibraryBookStatus.cancelled: cancelledBooks++; case LibraryBookStatus.missing || @@ -1458,14 +1537,29 @@ class IndexingRepository { return added; } - Future _indexPdfBook( + Future<({int docs, int droppedPages})> _indexPdfBook( PdfBook book, { + required IndexingRunDiagnosticsCollector diagnostics, required BookSourceHashes sourceHashes, void Function()? onActualIndexingStarted, Future? preExtracted, + void Function(PdfIndexingProgress? progress)? onPdfProgress, }) async { // חילוץ מוקדם וישיר שומרים שגיאות בתוצאה; חסימת קריסה חלה גם על OCR. - final extracted = await (preExtracted ?? extractPdfPagesGuarded(book)); + final extracted = + await (preExtracted ?? + diagnostics.measure( + IndexingStage.pdfExtraction, + () => extractPdfPagesGuarded(book, onProgress: onPdfProgress), + )); + if (preExtracted != null) { + diagnostics.increment(IndexingCounter.prefetchedPdfBooks); + } + diagnostics.increment(IndexingCounter.pdfPages, extracted.pages.length); + diagnostics.increment( + IndexingCounter.droppedPdfPages, + extracted.droppedPages, + ); final pages = extracted.pages; final outline = extracted.outline; final openError = extracted.error; @@ -1482,7 +1576,7 @@ class IndexingRepository { 'ב-${extracted.extractMs}ms${preExtracted != null ? ' (prefetch)' : ''}', ); if (!_tantivyDataProvider.isIndexing.value) { - return extracted.droppedPages; + return (docs: 0, droppedPages: extracted.droppedPages); } // המנוע מכריע אם ל-PDF יש טקסט שמיש: addPdfBookBytes מנרמל, מסנן זבל @@ -1492,6 +1586,7 @@ class IndexingRepository { added = await _addPdfBookToEngine( book, pages, + diagnostics: diagnostics, sourceHashes: sourceHashes, onActualIndexingStarted: onActualIndexingStarted, ); @@ -1499,11 +1594,15 @@ class IndexingRepository { if (added == 0 && _tantivyDataProvider.isIndexing.value) { // אין שכבת טקסט שמישה (PDF סרוק) או שהפתיחה נכשלה — sidecar OCR. - final sidecarPages = await _loadPdfSidecar(book, outline); + final sidecarPages = await diagnostics.measure( + IndexingStage.sourceLoading, + () => _loadPdfSidecar(book, outline), + ); if (sidecarPages.isNotEmpty) { added = await _addPdfBookToEngine( book, sidecarPages, + diagnostics: diagnostics, sourceHashes: sourceHashes, onActualIndexingStarted: onActualIndexingStarted, ); @@ -1530,10 +1629,11 @@ class IndexingRepository { if (added == 0) { await _writeEmptyBookMarker( book, + diagnostics: diagnostics, sourceHashes: sourceHashes, ); } - return extracted.droppedPages; + return (docs: added == 0 ? 1 : added, droppedPages: extracted.droppedPages); } void _recordPartialPdfFailure( @@ -1557,27 +1657,35 @@ class IndexingRepository { Future _addPdfBookToEngine( PdfBook book, List<({String reference, String text, int pageIndex})> pages, { + required IndexingRunDiagnosticsCollector diagnostics, required BookSourceHashes sourceHashes, void Function()? onActualIndexingStarted, }) async { onActualIndexingStarted?.call(); // FRB מקודד ומפענח את הארגומנטים על ה-UI thread; רשימת עמודים גדולה הקפיאה // אותו (#3443). חוצץ בתים שנארז ב-isolate עובר כהעתקה אחת. - final packed = await _packPdfPagesOffFrame(pages); + final packed = await diagnostics.measure( + IndexingStage.sourceLoading, + () => _packPdfPagesOffFrame(pages), + ); if (!_tantivyDataProvider.isIndexing.value) { return 0; } final engine = await _tantivyDataProvider.engine; final engineStopwatch = Stopwatch()..start(); - final added = await engine.addPdfBookBytes( - title: book.title, - topics: _bookTopics(book), - filePath: BookIdentity.indexedFilePath(book), - extraFacets: _bookExtraFacets(book), - bytes: packed.bytes, - ends: packed.ends, - pageIndexes: packed.pageIndexes, + final added = await diagnostics.measure( + IndexingStage.engine, + () => engine.addPdfBookBytes( + title: book.title, + topics: _bookTopics(book), + filePath: BookIdentity.indexedFilePath(book), + extraFacets: _bookExtraFacets(book), + bytes: packed.bytes, + ends: packed.ends, + pageIndexes: packed.pageIndexes, + ), ); + diagnostics.increment(IndexingCounter.documents, added); engineStopwatch.stop(); debugPrint( '📄 "${book.title}": ${pages.length} עמודים → $added מסמכים | ' @@ -1620,6 +1728,7 @@ class IndexingRepository { /// הפעלה. בלי זה, מצב האינדוקס (שנקרא מהאינדקס) לעולם לא היה שלם. Future _writeEmptyBookMarker( Book book, { + IndexingRunDiagnosticsCollector? diagnostics, required BookSourceHashes sourceHashes, }) async { if (!_tantivyDataProvider.isIndexing.value) { @@ -1628,24 +1737,30 @@ class IndexingRepository { final index = await _tantivyDataProvider.engine; // add (ולא upsert): כל מסלולי הכתיבה מדלגים על ספר שכבר מאונדקס // (isBookIndexed), כך שהספר כאן תמיד חדש ואין מה למחוק. - await index.addDocumentsBatch( - docs: [ - DocumentInput( - ordinal: 0, - title: book.title, - reference: '', - topics: _bookTopics(book), - text: '', - segment: BigInt.zero, - isPdf: book is PdfBook, - filePath: BookIdentity.indexedFilePath(book), - extraFacets: _bookExtraFacets(book), - sourceHash: _dbSourceHash(book, sourceHashes), - // טביעת הטקסט הריק: כך ספר שנשאר ריק נמצא תואם בבדיקה הבאה. - textHash: await contentFingerprint(text: const []), - ), - ], - ); + final stopwatch = Stopwatch()..start(); + try { + await index.addDocumentsBatch( + docs: [ + DocumentInput( + ordinal: 0, + title: book.title, + reference: '', + topics: _bookTopics(book), + text: '', + segment: BigInt.zero, + isPdf: book is PdfBook, + filePath: BookIdentity.indexedFilePath(book), + extraFacets: _bookExtraFacets(book), + sourceHash: _dbSourceHash(book, sourceHashes), + // טביעת הטקסט הריק: כך ספר שנשאר ריק נמצא תואם בבדיקה הבאה. + textHash: await contentFingerprint(text: const []), + ), + ], + ); + diagnostics?.increment(IndexingCounter.documents); + } finally { + diagnostics?.addTime(IndexingStage.engine, stopwatch.elapsed); + } } /// כשל קבוע מקבל סמן ריק באינדקס, אחרת הספר "חסר" לנצח ומפעיל ריצת @@ -1655,6 +1770,7 @@ class IndexingRepository { IndexingFailure failure, BookSourceHashes sourceHashes, List failures, { + IndexingRunDiagnosticsCollector? diagnostics, Set replaceKeys = const {}, }) async { if (failure.isRetryable) return false; @@ -1664,6 +1780,7 @@ class IndexingRepository { await _dropReplacedDocs(replaceKeys, [book]); await _writeEmptyBookMarker( book, + diagnostics: diagnostics, sourceHashes: sourceHashes, ); } catch (error, stackTrace) { @@ -1750,13 +1867,16 @@ class IndexingRepository { /// נשמרת בתוצאה (הקורא מכריע בין sidecar להפצתה), ומשך החילוץ נמדד כאן — /// כך גם חילוץ שרץ מראש (prefetch) מדווח את זמנו האמיתי. @visibleForTesting - Future extractPdfPagesGuarded(PdfBook book) async { + Future extractPdfPagesGuarded( + PdfBook book, { + void Function(PdfIndexingProgress? progress)? onProgress, + }) async { final stopwatch = Stopwatch()..start(); try { await _beginBook(book); // pdfium של האינדוקס ממתין בתור ה-worker לכל עבודה אחרת (הקורא קודם). final extracted = await Pdfrx.runAsBackgroundWork( - () => _extractPdfPages(book), + () => _extractPdfPages(book, onProgress: onProgress), ); return ( pages: extracted.pages, @@ -1775,6 +1895,8 @@ class IndexingRepository { extractMs: stopwatch.elapsedMilliseconds, droppedPages: 0, ); + } finally { + onProgress?.call(null); } } @@ -1787,7 +1909,10 @@ class IndexingRepository { int droppedPages, }) > - _extractPdfPages(PdfBook book) async { + _extractPdfPages( + PdfBook book, { + void Function(PdfIndexingProgress? progress)? onProgress, + }) async { const empty = ( pages: <({String reference, String text, int pageIndex})>[], outline: [], @@ -1816,6 +1941,7 @@ class IndexingRepository { final extracted = await extractPageTextsWithRetry( pageCount: document.pages.length, + onProgress: onProgress, loadPageText: (i) async { final text = await document.pages[i].loadText(); return text?.fullText; @@ -1867,20 +1993,50 @@ class IndexingRepository { required Future Function(int pageIndex) loadPageText, required Future Function() beforeEachPage, Duration pageTimeout = const Duration(seconds: 5), + Duration Function()? progressElapsed, + void Function(PdfIndexingProgress? progress)? onProgress, }) async { + final progressClock = onProgress == null || progressElapsed != null + ? null + : (Stopwatch()..start()); + const progressIntervalMicros = 250 * Duration.microsecondsPerMillisecond; + var lastReportMicros = 0; + var phase = PdfIndexingPhase.extraction; + var phaseTotal = pageCount; + void report(int processed, {bool force = false}) { + if (onProgress == null) return; + final elapsedMicros = + progressElapsed?.call().inMicroseconds ?? + progressClock!.elapsedMicroseconds; + if (force || elapsedMicros - lastReportMicros >= progressIntervalMicros) { + onProgress( + PdfIndexingProgress( + processed: processed, + total: phaseTotal, + phase: phase, + ), + ); + lastReportMicros = elapsedMicros; + } + } + + report(0, force: true); final pending = >{}; + // Future דוחה null ב-timeout גם כשהמשתנה הוא Future. + final deadline = Object(); Future load(int index) async { final future = pending[index] ??= loadPageText(index); - var timedOut = false; - final text = await future.timeout( - pageTimeout, - onTimeout: () { - timedOut = true; - return null; - }, - ); - if (!timedOut) pending.remove(index); - return text; + try { + final text = await future.timeout( + pageTimeout, + onTimeout: () => throw deadline, + ); + pending.remove(index); + return text; + } catch (error) { + if (identical(error, deadline)) return null; + rethrow; + } } final texts = SplayTreeMap(); @@ -1893,9 +2049,17 @@ class IndexingRepository { } else { texts[i] = text; } + if (i + 1 < pageCount) report(i + 1); } + report(pageCount, force: true); var droppedPages = 0; + if (retryPages.isNotEmpty) { + phase = PdfIndexingPhase.retry; + phaseTotal = retryPages.length; + report(0, force: true); + } + var retried = 0; for (final i in retryPages) { if (!await beforeEachPage()) return null; final reusingPending = pending.containsKey(i); @@ -1909,7 +2073,10 @@ class IndexingRepository { } else { texts[i] = text; } + retried++; + if (retried < phaseTotal) report(retried); } + if (retryPages.isNotEmpty) report(retried, force: true); return (texts: texts, droppedPages: droppedPages); } @@ -2308,9 +2475,16 @@ class IndexingRepository { } /// commit לאינדקס ורישום הספרים שנחתמו בקנרית הקריסות. - Future _commitIndex() async { + Future _commitIndex([ + IndexingRunDiagnosticsCollector? diagnostics, + ]) async { final index = await _tantivyDataProvider.engine; - await index.commit(); + final stopwatch = Stopwatch()..start(); + try { + await index.commit(); + } finally { + diagnostics?.addTime(IndexingStage.commit, stopwatch.elapsed); + } IndexingCrashCanary.current?.committed( _tantivyDataProvider.indexedFilePaths, ); diff --git a/lib/indexing/services/indexing_failure_reporter.dart b/lib/indexing/services/indexing_failure_reporter.dart index 57ac81c255..71ad42d84d 100644 --- a/lib/indexing/services/indexing_failure_reporter.dart +++ b/lib/indexing/services/indexing_failure_reporter.dart @@ -5,10 +5,6 @@ import 'package:otzaria/core/startup_timeline.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; /// רושם ל-errors.txt סיכום של ריצת אינדוקס שכשלה בחלקה, או שנמשכה זמן רב. -/// -/// ריצה נקייה וקצרה אינה נרשמת. ריצה נקייה שחרגה מסף העלייה האיטית כן — -/// אינדוקס מלא אחרי עדכון ספרייה מקפיא את התוכנה לדקות ומדווח כ"לא נפתחת" -/// (issue #1192), ובלי הרשומה אין דרך להבדיל בינו לעלייה איטית באמת. class IndexingFailureReporter { const IndexingFailureReporter._(); @@ -74,6 +70,24 @@ class IndexingFailureReporter { ..writeln('Warnings: ${result.warningCount}'); final memoryLine = formatMemoryLine(memory ?? memoryInfo()); if (memoryLine.isNotEmpty) buffer.writeln('Memory: $memoryLine'); + final diagnostics = result.diagnostics; + if (diagnostics != null) { + buffer.writeln('Recovery at start: ${diagnostics.recoveryStarted}'); + buffer.writeln('Work times (overlapping stages; not additive):'); + for (final entry in diagnostics.stageTimes.entries) { + buffer.writeln(' ${entry.key.name}: ${entry.value.inMicroseconds}us'); + } + for (final entry in diagnostics.counters.entries) { + buffer.writeln('${entry.key.name}: ${entry.value}'); + } + for (final decision in diagnostics.resourceDecisions) { + buffer.writeln( + 'Resources: mode=${decision.mode.name} reason=${decision.reason.name} ' + 'cpu=${decision.cpuCount} totalRamMb=${decision.totalRamMb} ' + 'availableRamMb=${decision.availableRamMb}', + ); + } + } for (var i = 0; i < result.failures.length; i++) { final failure = result.failures[i]; diff --git a/lib/indexing/utils/indexing_crash_canary.dart b/lib/indexing/utils/indexing_crash_canary.dart index aba3aec8f8..d1942ad3b7 100644 --- a/lib/indexing/utils/indexing_crash_canary.dart +++ b/lib/indexing/utils/indexing_crash_canary.dart @@ -14,7 +14,9 @@ class IndexingCrashedBefore implements Exception { /// מוני קריסות של ספרים שבאינדוקס וחסימות שטרם נחתמו באינדקס. class IndexingCrashCanary { - IndexingCrashCanary._(this._file) : _attempts = _read(_file); + IndexingCrashCanary._(this._file) : _attempts = _read(_file) { + _recoveryKeys.addAll(_attempts.keys); + } /// הריצה הפעילה; סגירה מסודרת של התוכנה מסיימת אותה ([finish]). static IndexingCrashCanary? current; @@ -31,6 +33,7 @@ class IndexingCrashCanary { final keys = pendingKeys().toSet(); final previousCount = canary._attempts.length; canary._attempts.removeWhere((key, _) => !keys.contains(key)); + canary._recoveryKeys.retainAll(keys); if (canary._attempts.length != previousCount) canary._write(); } if (canary != null && canary.recovering) canary._logCrash(); @@ -43,6 +46,7 @@ class IndexingCrashCanary { final File _file; final Map _attempts; + final Set _recoveryKeys = {}; final Set _inFlight = {}; final Set _skipped = {}; RandomAccessFile? _raf; @@ -50,7 +54,7 @@ class IndexingCrashCanary { bool _dirty = false; /// ריצה קודמת מתה באמצע: מאנדקסים ספר-ספר, כדי שרק האשם ייספר. - bool get recovering => _attempts.isNotEmpty; + bool get recovering => _recoveryKeys.isNotEmpty; static Map _read(File file) { try { @@ -80,7 +84,7 @@ class IndexingCrashCanary { void end(String key) { if (_skipped.contains(key)) return; if (!_inFlight.remove(key)) return; - if (_attempts.remove(key) != null) _write(); + if (_removeAttempt(key)) _write(); } /// מסתיים כשכל השינויים עד עכשיו בדיסק. @@ -91,7 +95,7 @@ class IndexingCrashCanary { if (_skipped.isEmpty) return; final saved = _skipped.where(indexedKeys.contains).toList(); if (saved.isEmpty) return; - saved.forEach(_attempts.remove); + saved.forEach(_removeAttempt); _skipped.removeAll(saved); _write(); } @@ -99,10 +103,16 @@ class IndexingCrashCanary { /// מנקה רק ספרים שה-reader קרא מהאינדקס החתום בדיסק. void forgetIndexed(Iterable committedKeys) { final previousCount = _attempts.length; - committedKeys.forEach(_attempts.remove); + committedKeys.forEach(_removeAttempt); if (_attempts.length != previousCount) _write(); } + bool _removeAttempt(String key) { + if (_attempts.remove(key) == null) return false; + _recoveryKeys.remove(key); + return true; + } + /// הריצה הסתיימה (או התוכנה נסגרה) בלי שהתהליך מת — מה שבטיסה לא הפיל אותו. Future finish() { if (identical(current, this)) current = null; diff --git a/lib/indexing/utils/pdf_extraction_prefetcher.dart b/lib/indexing/utils/pdf_extraction_prefetcher.dart index cd3554ff6e..b864699b32 100644 --- a/lib/indexing/utils/pdf_extraction_prefetcher.dart +++ b/lib/indexing/utils/pdf_extraction_prefetcher.dart @@ -48,6 +48,7 @@ class PdfExtractionPrefetcher { this.maxInFlight = defaultMaxInFlight, this.maxPendingChars = defaultMaxPendingChars, this.maxInFlightBytes = defaultMaxInFlightBytes, + this.canPrefetch, @visibleForTesting Future Function(String path)? fileSizeOf, }) : _fileSizeOf = fileSizeOf ?? _statFileSize; @@ -67,6 +68,7 @@ class PdfExtractionPrefetcher { final int maxInFlight; final int maxPendingChars; final int maxInFlightBytes; + final bool Function()? canPrefetch; final Future Function(String path) _fileSizeOf; final List<_PrefetchSlot> _slots = []; @@ -158,6 +160,7 @@ class PdfExtractionPrefetcher { } bool get _hasCapacity { + if (canPrefetch?.call() == false) return false; if (_slots.length >= maxInFlight) return false; // ספר יחיד החורג מהתקרות מוזנק בכל זאת, אחרת התור נתקע ריק לנצח. if (_slots.isEmpty) return true; diff --git a/lib/navigation/view/main_window_screen.dart b/lib/navigation/view/main_window_screen.dart index 32b7eface6..03d6d06a0b 100644 --- a/lib/navigation/view/main_window_screen.dart +++ b/lib/navigation/view/main_window_screen.dart @@ -3381,7 +3381,7 @@ class MainWindowScreenState extends State listener: (context, state) { final cubit = context.read(); if (state is IndexingInProgress && - (state.isCreatingIndex || state.isScanning)) { + shouldShowIndexingWorkStatus(state)) { final indexingBloc = context.read(); cubit.upsert( indexingWorkStatusItem( diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index 141522656f..b660ac9340 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -2368,6 +2368,7 @@ class _IndexMissingGate extends StatelessWidget { valueListenable: TantivyDataProvider.instance.isInitialized, builder: (context, providerInitialized, _) => BlocBuilder( + buildWhen: IndexingInProgress.bookProgressChanged, builder: (context, state) => isSearchBlockedByMissingIndex( providerInitialized: providerInitialized, diff --git a/lib/settings/tabs/library_settings_tab.dart b/lib/settings/tabs/library_settings_tab.dart index 0fd8f3a401..a83858f615 100644 --- a/lib/settings/tabs/library_settings_tab.dart +++ b/lib/settings/tabs/library_settings_tab.dart @@ -739,6 +739,7 @@ class _LibrarySettingsTabState extends State { context.read().add(UpdateIndexingResourceMode(mode)), ), BlocBuilder( + buildWhen: IndexingInProgress.bookProgressChanged, builder: (context, indexingState) { final processed = indexingState.booksProcessed ?? 0; final total = indexingState.totalBooks ?? 0; diff --git a/lib/widgets/feedback/indexing_warning.dart b/lib/widgets/feedback/indexing_warning.dart index 9354c166aa..63edebf9cc 100644 --- a/lib/widgets/feedback/indexing_warning.dart +++ b/lib/widgets/feedback/indexing_warning.dart @@ -140,6 +140,7 @@ class IndexingWarningContainer extends StatelessWidget { valueListenable: TantivyDataProvider.instance.isIndexingDeferred, builder: (context, indexingDeferred, _) { return BlocBuilder( + buildWhen: IndexingInProgress.bookProgressChanged, builder: (context, state) { final mode = resolveIndexingWarningMode( state: state, diff --git a/test/indexing/bloc/indexing_bloc_test.dart b/test/indexing/bloc/indexing_bloc_test.dart index 987bc56990..9e863656da 100644 --- a/test/indexing/bloc/indexing_bloc_test.dart +++ b/test/indexing/bloc/indexing_bloc_test.dart @@ -1,3 +1,5 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; + import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; @@ -9,6 +11,8 @@ import 'package:otzaria/core/messages/settings_messages.dart'; import 'package:otzaria/indexing/bloc/indexing_bloc.dart'; import 'package:otzaria/indexing/bloc/indexing_event.dart'; import 'package:otzaria/indexing/bloc/indexing_state.dart'; +import 'package:otzaria/indexing/indexing_work_status.dart'; +import 'package:otzaria/work_status/work_status_cubit.dart'; import 'package:otzaria/indexing/models/index_check_scope.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; import 'package:otzaria/indexing/repository/indexing_repository.dart'; @@ -42,6 +46,205 @@ void main() { _FakeIndexingRepository repositoryOf(IndexingBloc bloc) => (bloc as _FakeIndexingBloc).repository; + test('חיווי עמודי PDF נשמר בהשהיה ומתעלם מאירוע אחרי ביטול', () async { + final repository = _FakeIndexingRepository()..pdfGate = Completer(); + final bloc = _FakeIndexingBloc(repository); + final settled = Completer(); + bloc.add(StartIndexing(libraryWithBooks(), onSettled: settled.complete)); + await repository.pdfReady.future; + await pumpEventQueue(); + final status = WorkStatusCubit(); + addTearDown(status.close); + final subscription = bloc.stream.listen((state) { + if (state is IndexingInProgress && shouldShowIndexingWorkStatus(state)) { + status.upsert( + indexingWorkStatusItem( + state, + onTogglePause: () {}, + onToggleEconomy: () {}, + ), + ); + } else { + status.remove(kIndexingWorkStatusId); + } + }); + addTearDown(subscription.cancel); + final report = repository.reportPdfProgress!; + final progress = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.pdfPagesProcessed == 23, + ); + report(const PdfIndexingProgress(processed: 23, total: 120)); + final displayed = await progress as IndexingInProgress; + expect(displayed.pdfTotalPages, 120); + expect(displayed.isCreatingIndex, isFalse); + expect( + status.state.items[kIndexingWorkStatusId]?.detail, + contains('23/120 עמודים'), + ); + final paused = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.isPaused, + ); + bloc.add(PauseIndexing()); + expect((await paused as IndexingInProgress).pdfPagesProcessed, 23); + final retryState = bloc.stream.firstWhere( + (state) => + state is IndexingInProgress && + state.pdfPhase == PdfIndexingPhase.retry, + ); + report( + const PdfIndexingProgress( + processed: 2, + total: 5, + phase: PdfIndexingPhase.retry, + ), + ); + expect((await retryState as IndexingInProgress).pdfPagesProcessed, 2); + expect( + status.state.items[kIndexingWorkStatusId]?.detail, + contains('ניסיון חוזר לחילוץ PDF: 2/5'), + ); + bloc.add( + const UpdatePdfIndexingProgress( + -1, + PdfIndexingProgress( + processed: 4, + total: 5, + phase: PdfIndexingPhase.retry, + ), + ), + ); + await pumpEventQueue(); + expect((bloc.state as IndexingInProgress).pdfPagesProcessed, 2); + + repository.indexingActive = false; + report( + const PdfIndexingProgress( + processed: 5, + total: 5, + phase: PdfIndexingPhase.retry, + ), + ); + await pumpEventQueue(); + expect((bloc.state as IndexingInProgress).pdfPagesProcessed, 2); + + report(null); + await pumpEventQueue(); + expect((bloc.state as IndexingInProgress).pdfTotalPages, isNull); + + final stopped = bloc.stream.firstWhere((state) => state is IndexingStopped); + bloc.add(CancelIndexing()); + await stopped; + expect(status.state.items, isEmpty); + report( + const PdfIndexingProgress( + processed: 99, + total: 120, + phase: PdfIndexingPhase.retry, + ), + ); + await pumpEventQueue(); + expect(bloc.state, isA()); + repository.pdfGate!.complete(); + await settled.future; + await bloc.close(); + }); + + test('דיווח ואיפוס מחילוץ ישן אינם מחליפים חיווי של ריצה חדשה', () async { + final firstGate = Completer(); + final secondGate = Completer(); + final repository = _FakeIndexingRepository()..pdfGate = firstGate; + final bloc = _FakeIndexingBloc(repository); + final stopped = bloc.stream.firstWhere((state) => state is IndexingStopped); + bloc.add(StartIndexing(libraryWithBooks())); + await repository.pdfReady.future; + final oldReport = repository.reportPdfProgress!; + bloc.add(CancelIndexing()); + await stopped; + + repository.pdfGate = secondGate; + final secondStarted = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.totalBooks == 2, + ); + final secondSettled = Completer(); + bloc.add( + StartIndexing(libraryWithBooks(2), onSettled: secondSettled.complete), + ); + firstGate.complete(); + await secondStarted; + final freshProgress = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.pdfPagesProcessed == 1, + ); + repository.reportPdfProgress!( + const PdfIndexingProgress(processed: 1, total: 8), + ); + final beforeLateEvents = await freshProgress; + oldReport(null); + oldReport( + const PdfIndexingProgress( + processed: 5, + total: 5, + phase: PdfIndexingPhase.retry, + ), + ); + await pumpEventQueue(); + expect(bloc.state, beforeLateEvents); + + secondGate.complete(); + await secondSettled.future; + await bloc.close(); + }); + + test('null מנקה חיווי retry ואירוע מאוחר אינו חוזר בשלב האיחוד', () async { + final repository = _FakeIndexingRepository() + ..pdfGate = Completer() + ..finalizeGate = Completer(); + final bloc = _FakeIndexingBloc(repository); + final settled = Completer(); + bloc.add(StartIndexing(libraryWithBooks(), onSettled: settled.complete)); + await repository.pdfReady.future; + await pumpEventQueue(); + final report = repository.reportPdfProgress!; + final retry = bloc.stream.firstWhere( + (state) => + state is IndexingInProgress && + state.pdfPhase == PdfIndexingPhase.retry, + ); + report( + const PdfIndexingProgress( + processed: 1, + total: 3, + phase: PdfIndexingPhase.retry, + ), + ); + await retry; + final cleared = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.pdfTotalPages == null, + ); + report(null); + expect( + (await cleared as IndexingInProgress).pdfPhase, + PdfIndexingPhase.extraction, + ); + final finalizing = bloc.stream.firstWhere( + (state) => state is IndexingInProgress && state.isFinalizing, + ); + repository.pdfGate!.complete(); + final finalizingState = await finalizing; + report( + const PdfIndexingProgress( + processed: 2, + total: 3, + phase: PdfIndexingPhase.retry, + ), + ); + await pumpEventQueue(); + expect(bloc.state, finalizingState); + expect((bloc.state as IndexingInProgress).pdfTotalPages, isNull); + repository.finalizeGate!.complete(); + await settled.future; + await bloc.close(); + }); + group('מקום פנוי בכונן האינדקס', () { const mb = 1024 * 1024; @@ -1341,6 +1544,9 @@ class _FakeIndexingRepository extends IndexingRepository { /// כשהוא מסופק — כל ריצה ממתינה לו לפני שהיא מתחילה. Completer? runGate; + Completer? pdfGate; + final pdfReady = Completer(); + void Function(PdfIndexingProgress? progress)? reportPdfProgress; int dropOrphanedCalls = 0; final compactionRequests = []; int dropHiddenCalls = 0; @@ -1386,6 +1592,7 @@ class _FakeIndexingRepository extends IndexingRepository { bool includePdfBooks = true, void Function(int processed, int total)? onScanProgress, void Function(int total)? onWorkListReady, + void Function(PdfIndexingProgress? progress)? onPdfProgress, void Function()? onActualIndexingStarted, required void Function(int processed, int total) onProgress, void Function()? onFinalizing, @@ -1400,6 +1607,10 @@ class _FakeIndexingRepository extends IndexingRepository { ? 0 : (books ?? library.getIndexableBooks()).length + changedBooks.length; if (total > 0) onWorkListReady?.call(total); + reportPdfProgress = onPdfProgress; + if (!pdfReady.isCompleted) pdfReady.complete(); + final pdfWait = pdfGate; + if (pdfWait != null) await pdfWait.future; final gate = finalizeGate; final IndexingRunResult runResult; if (gate != null) { @@ -1486,8 +1697,10 @@ class _FakeIndexingRepository extends IndexingRepository { library.getIndexableBooks().any((book) => !isBookIndexed(book)); } + bool indexingActive = true; + @override - bool isIndexing() => true; + bool isIndexing() => indexingActive; @override void cancelIndexing() { diff --git a/test/indexing/bloc/indexing_state_test.dart b/test/indexing/bloc/indexing_state_test.dart index 70016db93f..f4d7d93e88 100644 --- a/test/indexing/bloc/indexing_state_test.dart +++ b/test/indexing/bloc/indexing_state_test.dart @@ -4,6 +4,23 @@ import 'package:otzaria/indexing/bloc/indexing_state.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; void main() { + test('התקדמות בתוך PDF משתתפת בשוויון המצב', () { + const before = IndexingInProgress(pdfPagesProcessed: 1, pdfTotalPages: 100); + const after = IndexingInProgress(pdfPagesProcessed: 2, pdfTotalPages: 100); + expect(before, isNot(after)); + final hasBookProgress = IndexingInProgress.bookProgressChanged; + expect(hasBookProgress(before, after), isFalse); + expect(hasBookProgress(after, const IndexingInProgress()), isFalse); + expect( + hasBookProgress(after, const IndexingInProgress(booksProcessed: 1)), + isTrue, + ); + expect( + hasBookProgress(after, const IndexingInProgress(isFinalizing: true)), + isTrue, + ); + expect(hasBookProgress(after, const IndexingComplete()), isTrue); + }); const failure = IndexingFailure( bookTitle: 'ספר', bookPath: 'ext:42', diff --git a/test/indexing/indexing_work_status_test.dart b/test/indexing/indexing_work_status_test.dart index 359409be2d..f7302e14eb 100644 --- a/test/indexing/indexing_work_status_test.dart +++ b/test/indexing/indexing_work_status_test.dart @@ -1,9 +1,39 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/indexing/bloc/indexing_state.dart'; import 'package:otzaria/indexing/indexing_work_status.dart'; void main() { group('indexingWorkStatusItem', () { + test('שלב החזרה מציג מכנה של העמודים הממתינים בלבד', () { + final item = indexingWorkStatusItem( + const IndexingInProgress( + booksProcessed: 7, + totalBooks: 12, + pdfPagesProcessed: 2, + pdfTotalPages: 5, + pdfPhase: PdfIndexingPhase.retry, + ), + onTogglePause: () {}, + onToggleEconomy: () {}, + ); + expect(item.detail, 'התקדמות: 7/12 · ניסיון חוזר לחילוץ PDF: 2/5 עמודים'); + expect(item.progress, closeTo(7 / 12, 0.001)); + }); + test('חיווי PDF מציג עמודים בלי להחליף את התקדמות הספרים', () { + final item = indexingWorkStatusItem( + const IndexingInProgress( + booksProcessed: 7, + totalBooks: 12, + pdfPagesProcessed: 23, + pdfTotalPages: 120, + ), + onTogglePause: () {}, + onToggleEconomy: () {}, + ); + expect(item.detail, 'התקדמות: 7/12 · חילוץ PDF ברקע: 23/120 עמודים'); + expect(item.progress, closeTo(7 / 12, 0.001)); + }); const running = IndexingInProgress( booksProcessed: 25, totalBooks: 100, diff --git a/test/indexing/models/indexing_resource_policy_test.dart b/test/indexing/models/indexing_resource_policy_test.dart index 97d9ee9a44..759063a74a 100644 --- a/test/indexing/models/indexing_resource_policy_test.dart +++ b/test/indexing/models/indexing_resource_policy_test.dart @@ -2,6 +2,68 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; void main() { + test( + 'decision reasons preserve thresholds and explicit preference precedence', + () { + final cases = <(IndexingResourcePolicy, IndexingResourceReason)>[ + ( + const IndexingResourcePolicy(cpuCount: 8, mobile: true), + IndexingResourceReason.mobile, + ), + ( + const IndexingResourcePolicy(cpuCount: 4, mobile: false), + IndexingResourceReason.lowCpu, + ), + ( + const IndexingResourcePolicy(cpuCount: 5, mobile: false), + IndexingResourceReason.unknownRam, + ), + ( + const IndexingResourcePolicy( + cpuCount: 5, + mobile: false, + totalRamMb: 4096, + ), + IndexingResourceReason.lowRam, + ), + ( + const IndexingResourcePolicy( + cpuCount: 5, + mobile: false, + totalRamMb: 4097, + availableRamMb: 1023, + ), + IndexingResourceReason.lowAvailableRam, + ), + ( + const IndexingResourcePolicy( + cpuCount: 5, + mobile: false, + totalRamMb: 4097, + availableRamMb: 1024, + ), + IndexingResourceReason.normal, + ), + ]; + for (final (policy, reason) in cases) { + expect(policy.reason(IndexingResourceMode.automatic), reason); + expect( + policy.useEconomy(IndexingResourceMode.automatic), + reason != IndexingResourceReason.normal, + ); + expect( + policy.reason(IndexingResourceMode.normal), + IndexingResourceReason.explicitNormal, + ); + expect(policy.useEconomy(IndexingResourceMode.normal), isFalse); + expect( + policy.reason(IndexingResourceMode.economy), + IndexingResourceReason.explicitEconomy, + ); + expect(policy.useEconomy(IndexingResourceMode.economy), isTrue); + } + }, + ); test( 'automatic policy considers CPU, RAM, available memory and platform', () { diff --git a/test/indexing/models/indexing_run_diagnostics_test.dart b/test/indexing/models/indexing_run_diagnostics_test.dart new file mode 100644 index 0000000000..a31a8cad5d --- /dev/null +++ b/test/indexing/models/indexing_run_diagnostics_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; +import 'package:otzaria/indexing/models/indexing_run_result.dart'; + +void main() { + const policy = IndexingResourcePolicy( + cpuCount: 8, + mobile: false, + totalRamMb: 16000, + availableRamMb: 6000, + ); + + test('snapshots retain their values when late background work finishes', () { + final collector = IndexingRunDiagnosticsCollector() + ..recoveryStarted = true + ..addTime(IndexingStage.engine, const Duration(microseconds: 1500)) + ..increment(IndexingCounter.documents, 20) + ..recordResources(policy, IndexingResourceMode.automatic); + final first = collector.snapshot(); + collector + ..addTime(IndexingStage.engine, const Duration(microseconds: 500)) + ..increment(IndexingCounter.documents, 3) + ..recordResources(policy, IndexingResourceMode.economy); + final last = collector.snapshot(); + expect(first.stageTimes[IndexingStage.engine]!.inMicroseconds, 1500); + expect(first.counters[IndexingCounter.documents], 20); + expect(first.resourceDecisions, hasLength(1)); + expect(last.stageTimes[IndexingStage.engine]!.inMicroseconds, 2000); + expect(last.counters[IndexingCounter.documents], 23); + expect(last.resourceDecisions, hasLength(2)); + expect(first.recoveryStarted, isTrue); + expect(() => first.counters.clear(), throwsUnsupportedError); + expect(() => first.stageTimes.clear(), throwsUnsupportedError); + expect(() => first.resourceDecisions.clear(), throwsUnsupportedError); + }); + + test( + 'resource decisions suppress repeated samples but retain mode changes', + () { + final collector = IndexingRunDiagnosticsCollector() + ..recordResources(policy, IndexingResourceMode.automatic) + ..recordResources(policy, IndexingResourceMode.automatic) + ..recordResources(policy, IndexingResourceMode.normal) + ..recordResources(policy, IndexingResourceMode.automatic); + expect(collector.snapshot().resourceDecisions, hasLength(3)); + expect(IndexingRunDiagnosticsCollector().snapshot().counters, isEmpty); + }, + ); + + test( + 'a failed measured operation keeps its elapsed work and original error', + () async { + final collector = IndexingRunDiagnosticsCollector(); + final error = StateError('source failure'); + await expectLater( + collector.measure(IndexingStage.sourceLoading, () async { + throw error; + }), + throwsA(same(error)), + ); + expect( + collector.snapshot().stageTimes, + contains(IndexingStage.sourceLoading), + ); + expect(await collector.measure(IndexingStage.engine, () async => 42), 42); + }, + ); + + test( + 'cancelled results preserve diagnostics and include them in equality', + () { + IndexingRunResult result(int docs) => IndexingRunResult.cancelled( + processedBooks: 1, + totalBooks: 3, + indexedBooks: 1, + diagnostics: IndexingRunDiagnostics( + counters: {IndexingCounter.documents: docs}, + ), + ); + expect(result(3), result(3)); + expect(result(3), isNot(result(4))); + expect(result(3).diagnostics!.counters[IndexingCounter.documents], 3); + expect(result(3).completed, isFalse); + }, + ); +} diff --git a/test/indexing/repository/indexing_repository_test.dart b/test/indexing/repository/indexing_repository_test.dart index a178ac5f83..340e29ecc9 100644 --- a/test/indexing/repository/indexing_repository_test.dart +++ b/test/indexing/repository/indexing_repository_test.dart @@ -1,4 +1,6 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; import 'package:otzaria/data/book_identity.dart'; + import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; @@ -23,6 +25,7 @@ import 'package:otzaria/find_ref/repository/find_ref_db_isolate.dart'; import 'package:otzaria/migration/database/daos/database.dart'; import 'package:otzaria/migration/database/repository/seforim_repository.dart'; import 'package:otzaria/settings/engine/settings_repository.dart'; + import '../../test_helpers/memory_cache_provider.dart'; import '../../support/fake_line_source_engine.dart'; @@ -35,6 +38,8 @@ import 'package:otzaria/indexing/models/index_check_scope.dart'; import 'package:otzaria/indexing/models/index_commit_policy.dart'; import 'package:otzaria/indexing/models/index_update_mode.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; +import 'package:otzaria/indexing/repository/index_change_detector.dart'; import 'package:otzaria/indexing/repository/indexing_repository.dart'; import 'package:otzaria/indexing/utils/indexing_crash_canary.dart'; import 'package:otzaria/indexing/utils/pdf_extraction_prefetcher.dart'; @@ -82,6 +87,80 @@ void main() { IndexingCrashCanary.writeLog = ErrorLogFile.appendText; IndexingRepository.contentFingerprint = computeContentFingerprintBytes; }); + group('אבחון ריצות אינדוקס', () { + test('שתי ריצות שומרות תמונות מצב נפרדות ושלבי עבודה', () async { + final provider = _RecordingTantivyDataProvider(_RecordingSearchEngine()); + final repository = _FakeExtractionRepository(provider); + final pdf = PdfBook(title: 'ראשון', path: 'first.pdf'); + final text = TextBook(id: 62187, title: 'שני'); + final library = Library(categories: [])..books.addAll([pdf, text]); + final first = await repository.runIndexing( + library, + books: [pdf], + onProgress: (_, _) {}, + ); + final firstDiagnostics = first.diagnostics!; + expect(firstDiagnostics.counters[IndexingCounter.pdfPages], 1); + expect( + firstDiagnostics.counters[IndexingCounter.documents], + greaterThan(0), + ); + expect( + firstDiagnostics.stageTimes, + contains(IndexingStage.pdfExtraction), + ); + expect(firstDiagnostics.stageTimes, contains(IndexingStage.engine)); + expect(firstDiagnostics.stageTimes, contains(IndexingStage.commit)); + final second = await repository.runIndexing( + library, + books: [text], + onProgress: (_, _) {}, + ); + expect(second.diagnostics!.counters[IndexingCounter.pdfPages], isNull); + expect( + second.diagnostics!.stageTimes, + contains(IndexingStage.sourceLoading), + ); + expect(firstDiagnostics.counters[IndexingCounter.pdfPages], 1); + expect(firstDiagnostics, isNot(same(second.diagnostics))); + }); + + test('ביטול בזמן טעינת ספר שומר אבחון בלי כתיבת מסמכים', () async { + final provider = _RecordingTantivyDataProvider(_RecordingSearchEngine()); + final repository = _CancelDuringLoadRepository(provider); + final book = TextBook(id: 62188, title: 'ביטול'); + final result = await repository.runIndexing( + Library(categories: [])..books.add(book), + books: [book], + onProgress: (_, _) {}, + ); + expect(result.cancelled, isTrue); + expect( + result.diagnostics!.stageTimes, + contains(IndexingStage.sourceLoading), + ); + expect(result.diagnostics!.counters[IndexingCounter.documents], isNull); + }); + + test('סריקה ללא שינוי שומרת זמן בדיקה בלי משאבי כתיבה', () async { + final provider = _RecordingTantivyDataProvider(_RecordingSearchEngine()); + final repository = _FakeExtractionRepository(provider) + ..changeDetector = _EmptyDiagnosticsChangeDetector(); + final book = TextBook(id: 62189, title: 'תואם'); + provider.indexedFilePaths.add(BookIdentity.indexedFilePath(book)); + final result = await repository.runIndexing( + Library(categories: [])..books.add(book), + books: const [], + check: IndexCheckScope.library, + onProgress: (_, _) {}, + ); + expect(result.completed, isTrue); + expect(result.indexedBooks, 0); + expect(result.diagnostics!.stageTimes, contains(IndexingStage.scan)); + expect(result.diagnostics!.counters, isEmpty); + expect(result.diagnostics!.resourceDecisions, isEmpty); + }); + }); group('הסתרות ואינדקס מלא', () { test('סטטוס כולל מהדורה גלויה מחוץ לעץ ומחריג קטגוריה מוסתרת', () async { final library = Library(categories: []); @@ -3084,6 +3163,60 @@ void main() { expect(provider.indexedFilePaths, {r'C:\missing\א.pdf'}); }); + test('PDF נספר בסף המסמכים לשמירת ביניים', () async { + IndexingRepository.newCommitPolicy = () => IndexCommitPolicy(maxDocs: 1); + addTearDown( + () => IndexingRepository.newCommitPolicy = IndexCommitPolicy.new, + ); + final engine = _RecordingSearchEngine(); + final provider = _RecordingTantivyDataProvider(engine); + final books = [ + for (var i = 0; i < 2; i++) PdfBook(title: 'p$i', path: 'C:\\p$i.pdf'), + ]; + final library = Library(categories: [])..books.addAll(books); + final commits = >[]; + engine.onCommit = () => commits.add([...engine.addedPdfTitles]); + final result = await _FakeExtractionRepository(provider) + .indexAllBooks(library, onProgress: (_, _) {}); + expect(result.isClean, isTrue); + expect(commits.first, ['p0']); + expect(commits.last, ['p0', 'p1']); + expect(provider.indexedFilePaths, books.map((b) => b.path).toSet()); + }); + + test('התאוששות PDF מחזירה חפיפה לאחר סיום החשוד', () async { + final temp = await io.Directory.systemTemp.createTemp('pdf_recovery_'); + addTearDown(() => temp.delete(recursive: true)); + final engine = _RecordingSearchEngine(); + final provider = _RecordingTantivyDataProvider(engine) + ..activeIndexPath = '${temp.path}/index'; + final books = [ + for (var i = 0; i < 3; i++) PdfBook(title: 'p$i', path: 'C:\\p$i.pdf'), + ]; + io.File('${provider.activeIndexPath}.in_flight.json') + .writeAsStringSync(jsonEncode({books.first.path: 1})); + final repository = _CanaryExtractionRepository(provider); + final extractedDuringWrite = >{}; + engine.onPdfAdded = (title) => + extractedDuringWrite[title] = [...repository.extractedTitles]; + final result = await repository.indexAllBooks( + Library(categories: [])..books.addAll(books), + onProgress: (_, _) {}, + ); + expect(result.isClean, isTrue); + expect(extractedDuringWrite['p0'], [ + 'p0', + ], reason: 'החשוד מבודד מהספרים הבאים'); + expect(extractedDuringWrite['p1'], [ + 'p0', + 'p1', + 'p2', + ], reason: 'החילוץ הבא כבר הוזנק בזמן כתיבת השני'); + expect(engine.addedPdfTitles, ['p0', 'p1', 'p2']); + expect(repository.extractedTitles, ['p0', 'p1', 'p2']); + expect(provider.indexedFilePaths, books.map((b) => b.path).toSet()); + }); + for (final recoveringCommitted in [false, true]) { test( 'חילוצי PDF מוקדמים ללא כפילות (${recoveringCommitted ? 'אחרי קריסה וסמן חתום' : 'ריצה בריאה'})', @@ -5064,6 +5197,18 @@ class FakeTantivyDataProvider implements TantivyDataProvider { } } +class _EmptyDiagnosticsChangeDetector implements IndexChangeDetector { + @override + Future?> detectChanged( + List candidates, { + required Library library, + required bool Function() isCancelled, + required Future Function() waitWhilePaused, + void Function(Book book)? onMetadataOnlyChanged, + void Function(int processed, int total)? onProgress, + }) async => const []; +} + class _FakeSearchEngine implements SearchEngine { @override dynamic noSuchMethod(Invocation invocation) { @@ -5257,7 +5402,10 @@ class _FakeExtractionRepository extends IndexingRepository { } @override - Future extractPdfPagesGuarded(PdfBook book) async { + Future extractPdfPagesGuarded( + PdfBook book, { + void Function(PdfIndexingProgress? progress)? onProgress, + }) async { extractedTitles.add(book.title); _activeExtractions++; peakConcurrentExtractions = max( @@ -5301,15 +5449,33 @@ class _FakeExtractionRepository extends IndexingRepository { } } +class _CanaryExtractionRepository extends _FakeExtractionRepository { + _CanaryExtractionRepository(super.provider); + + @override + Future extractPdfPagesGuarded( + PdfBook book, { + void Function(PdfIndexingProgress? progress)? onProgress, + }) { + if (IndexingCrashCanary.current?.begin(book.path) == false) { + throw const IndexingCrashedBefore(); + } + return super.extractPdfPagesGuarded(book, onProgress: onProgress); + } +} + class _GatedPdfExtractionRepository extends _FakeExtractionRepository { _GatedPdfExtractionRepository(super.provider, this.extractionGate); final Future extractionGate; @override - Future extractPdfPagesGuarded(PdfBook book) async { + Future extractPdfPagesGuarded( + PdfBook book, { + void Function(PdfIndexingProgress? progress)? onProgress, + }) async { await extractionGate; - return super.extractPdfPagesGuarded(book); + return super.extractPdfPagesGuarded(book, onProgress: onProgress); } } @@ -5569,12 +5735,11 @@ StampChangeDetector _textDetector( }) => StampChangeDetector( repository, loadSourceHashes: (_) async => sourceHashes ?? BookSourceHashes.none, - metadataFingerprint: - ({ - required String title, - required String topics, - List? extraFacets, - }) => metadataOf?.call(title) ?? _metadata, + metadataFingerprint: ({ + required String title, + required String topics, + List? extraFacets, + }) => metadataOf?.call(title) ?? _metadata, textMatchesIndex: fingerprintOf == null || loadText == null ? null : (book, textHash) async { diff --git a/test/indexing/repository/library_batch_indexing_test.dart b/test/indexing/repository/library_batch_indexing_test.dart index b318ae5181..d622c5eb20 100644 --- a/test/indexing/repository/library_batch_indexing_test.dart +++ b/test/indexing/repository/library_batch_indexing_test.dart @@ -8,9 +8,11 @@ import 'package:otzaria/attached_libraries/models/attached_library.dart'; import 'package:otzaria/attached_libraries/repository/attached_library_registry.dart'; import 'package:otzaria/data/data_providers/tantivy_data_provider.dart'; import 'package:otzaria/indexing/models/index_commit_policy.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; import 'package:otzaria/indexing/repository/indexing_repository.dart'; +import 'package:otzaria/indexing/utils/indexing_crash_canary.dart'; import 'package:otzaria/indexing/utils/pending_reindex_store.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/book_source.dart'; @@ -325,8 +327,11 @@ void main() { final previous = AttachedLibraryRegistry.instance; AttachedLibraryRegistry.instance = registry; addTearDown(() => AttachedLibraryRegistry.instance = previous); - AttachedLibraryRegistry.configureEngineSource = - ({required slug, dbPath, required immutable}) async {}; + AttachedLibraryRegistry.configureEngineSource = ({ + required slug, + dbPath, + required immutable, + }) async {}; addTearDown( () => AttachedLibraryRegistry.configureEngineSource = configureAttachedLineSource, @@ -650,6 +655,85 @@ void main() { ]); }); + test( + 'אחרי טיפול בספר החשוד חוזרים לאצווה גדולה ושומרים את כל המסמכים', + () async { + final dir = await Directory.systemTemp.createTemp( + 'batch_recovery_resume', + ); + addTearDown(() => dir.delete(recursive: true)); + provider.activeIndexPath = p.join(dir.path, 'index'); + final canaryFile = File('${provider.activeIndexPath}.in_flight.json'); + await canaryFile.writeAsString(jsonEncode({'id:2': 1})); + final books = officialBooks(20); + + final result = await repository.indexAllBooks( + libraryOf(books), + onProgress: (_, _) {}, + ); + + expect(engine.batches.length, lessThan(20)); + expect(engine.batches[0], ['id:1']); + expect(engine.batches[1], ['id:2']); + expect(engine.batches.skip(2).any((batch) => batch.length > 1), isTrue); + expect(engine.batches.skip(2).expand((batch) => batch), [ + for (var id = 3; id <= 20; id++) 'id:$id', + ]); + final keys = {for (var id = 1; id <= 20; id++) 'id:$id'}; + expect(engine.batches.expand((batch) => batch), hasLength(20)); + expect(provider.indexedFilePaths, keys); + expect(engine.committedFilePaths, keys); + expect(engine.pending, isEmpty); + expect(engine.bytesFilePaths, isEmpty); + expect(result.isClean, isTrue); + expect(result.processedBooks, 20); + expect(result.indexedBooks, 20); + expect(result.diagnostics!.recoveryStarted, isTrue); + expect(result.diagnostics!.counters[IndexingCounter.documents], 60); + expect(jsonDecode(await canaryFile.readAsString()), isEmpty); + }, + ); + + test('ספר בריא בטיסה אינו מצמצם אצוות של ספרי הספרייה', () async { + final dir = await Directory.systemTemp.createTemp( + 'batch_healthy_in_flight', + ); + addTearDown(() => dir.delete(recursive: true)); + provider.activeIndexPath = p.join(dir.path, 'index'); + final books = officialBooks(20); + IndexingCrashCanary? activeCanary; + const healthyKey = 'healthy-pdf-in-flight'; + + final result = await repository.indexAllBooks( + libraryOf(books), + onProgress: (processed, _) { + if (processed == 1 && activeCanary == null) { + activeCanary = IndexingCrashCanary.current!; + // מדמה רישום של PDF בריא שהחל בחילוץ מוקדם ועדיין בטיסה; + // לא מפעיל PDFium ואינו מסמן חשוד מריצה קודמת. + expect(activeCanary!.begin(healthyKey), isTrue); + } + }, + ); + expect(activeCanary, isNotNull); + activeCanary!.end(healthyKey); + await activeCanary!.flush(); + + expect(engine.batches.first.length, greaterThan(1)); + expect(engine.batches, hasLength(2)); + final keys = {for (var id = 1; id <= 20; id++) 'id:$id'}; + expect(engine.batches.expand((batch) => batch), hasLength(20)); + expect(provider.indexedFilePaths, keys); + expect(engine.committedFilePaths, keys); + expect(engine.pending, isEmpty); + expect(engine.bytesFilePaths, isEmpty); + expect(result.isClean, isTrue); + expect(result.processedBooks, 20); + expect(result.indexedBooks, 20); + expect(result.diagnostics!.recoveryStarted, isFalse); + expect(result.diagnostics!.counters[IndexingCounter.documents], 60); + }); + test('ספרי האצווה רשומים בקובץ הקריסות לפני המנוע (issue #3330)', () async { final dir = await Directory.systemTemp.createTemp('batch_canary'); addTearDown(() => dir.delete(recursive: true)); @@ -711,9 +795,12 @@ void main() { }); test('ספר שהמנוע לא מצא נבדק דרך Dart כמו קודם', () async { - IndexingRepository.libraryFingerprint = - ({required source, required bookId, dbTitle, attachedSlug}) async => - null; + IndexingRepository.libraryFingerprint = ({ + required source, + required bookId, + dbTitle, + attachedSlug, + }) async => null; final book = TextBook(id: 7, title: 'ז', categoryId: 1); await repository.textBookContentMatchesIndex(book, BigInt.from(1)); diff --git a/test/indexing/repository/pdf_text_timeout_test.dart b/test/indexing/repository/pdf_text_timeout_test.dart index c65ae6f1e1..10208d3096 100644 --- a/test/indexing/repository/pdf_text_timeout_test.dart +++ b/test/indexing/repository/pdf_text_timeout_test.dart @@ -1,3 +1,5 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; + import 'dart:async'; import 'package:fake_async/fake_async.dart'; @@ -5,6 +7,150 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/indexing/repository/indexing_repository.dart'; void main() { + test('חיווי מפריד בין סריקת עמודים לניסיונות חוזרים ומגביל כל שלב', () { + fakeAsync((clock) { + final reports = []; + final attempts = {}; + ({Map texts, int droppedPages})? result; + IndexingRepository.extractPageTextsWithRetry( + pageCount: 8, + loadPageText: (index) async { + final attempt = attempts.update( + index, + (n) => n + 1, + ifAbsent: () => 1, + ); + await Future.delayed(const Duration(milliseconds: 100)); + return attempt == 1 ? null : 'עמוד $index'; + }, + beforeEachPage: () async => true, + progressElapsed: () => clock.elapsed, + onProgress: (value) => reports.add(value!), + ).then((value) => result = value); + clock.elapse(const Duration(seconds: 2)); + expect(result!.texts.length, 8); + expect(result!.droppedPages, 0); + expect(attempts.values, everyElement(2)); + for (final phase in PdfIndexingPhase.values) { + final series = reports.where((r) => r.phase == phase).toList(); + expect(series.map((r) => r.processed), [0, 3, 6, 8]); + expect(series.map((r) => r.total), everyElement(8)); + } + }); + }); + + test('מאה timeouts מתקדמים בשני שלבים בלי להכפיל חילוץ', () { + fakeAsync((clock) { + final pages = List.generate(100, (_) => Completer()); + final calls = []; + final reports = []; + ({Map texts, int droppedPages})? result; + IndexingRepository.extractPageTextsWithRetry( + pageCount: pages.length, + loadPageText: (index) { + calls.add(index); + return pages[index].future; + }, + beforeEachPage: () async => true, + progressElapsed: () => clock.elapsed, + onProgress: (value) => reports.add(value!), + ).then((value) => result = value); + clock.elapse(const Duration(seconds: 501)); + expect(reports.last.phase, PdfIndexingPhase.retry); + expect(reports.last.processed, 0); + clock.elapse(const Duration(seconds: 500)); + expect(result!.droppedPages, 100); + expect(calls, List.generate(100, (index) => index)); + for (final phase in PdfIndexingPhase.values) { + final series = reports.where((r) => r.phase == phase); + expect(series.map((r) => r.processed), List.generate(101, (i) => i)); + expect(series.map((r) => r.total), everyElement(100)); + } + for (final page in pages) { + page.complete(null); + } + clock.flushMicrotasks(); + }); + }); + + test('retry סופר רק תת קבוצה וסופר null מאוחר פעם אחת', () { + fakeAsync((clock) { + final first = Completer(); + final calls = {}; + final reports = []; + ({Map texts, int droppedPages})? result; + Timer(const Duration(seconds: 6), () => first.complete(null)); + IndexingRepository.extractPageTextsWithRetry( + pageCount: 3, + loadPageText: (index) { + final attempt = calls.update(index, (n) => n + 1, ifAbsent: () => 1); + if (index == 0 && attempt == 1) return first.future; + if (index == 1) { + return Future.delayed(const Duration(seconds: 2), () => 'שני'); + } + return Future.value('עמוד $index'); + }, + beforeEachPage: () async => true, + progressElapsed: () => clock.elapsed, + onProgress: (value) => reports.add(value!), + ).then((value) => result = value); + clock.elapse(const Duration(seconds: 8)); + expect(result!.texts.length, 3); + expect(result!.droppedPages, 0); + expect(calls, {0: 2, 1: 1, 2: 1}); + final retry = reports.where((r) => r.phase == PdfIndexingPhase.retry); + expect(retry.map((r) => r.processed), [0, 1]); + expect(retry.map((r) => r.total), everyElement(1)); + }); + }); + + test('ביטול בתחילת retry אינו מציג השלמה שגויה', () { + fakeAsync((clock) { + var cancelled = false; + final reports = []; + var completed = false; + ({Map texts, int droppedPages})? result; + IndexingRepository.extractPageTextsWithRetry( + pageCount: 3, + loadPageText: (_) async => null, + beforeEachPage: () async => !cancelled, + progressElapsed: () => clock.elapsed, + onProgress: (value) { + reports.add(value!); + if (value.phase == PdfIndexingPhase.retry) cancelled = true; + }, + ).then((value) { + result = value; + completed = true; + }); + clock.flushMicrotasks(); + expect(completed, isTrue); + expect(result, isNull); + expect( + reports.last, + const PdfIndexingProgress( + processed: 0, + total: 3, + phase: PdfIndexingPhase.retry, + ), + ); + }); + }); + + test('חיווי עמודים כולל התחלה וסיום בלי אירוע לכל עמוד', () async { + final progress = <(int, int)>[]; + final result = await IndexingRepository.extractPageTextsWithRetry( + pageCount: 100, + loadPageText: (index) async => 'עמוד $index', + beforeEachPage: () async => true, + onProgress: (value) => progress.add((value!.processed, value.total)), + ); + expect(result!.texts.length, 100); + expect(progress.first, (0, 100)); + expect(progress.last, (100, 100)); + expect(progress.length, lessThan(100)); + }); + test('timeout ממתין לאותה עבודת עמוד ומקבל את התוצאה המאוחרת', () { fakeAsync((clock) { final first = Completer(); diff --git a/test/indexing/services/indexing_failure_reporter_test.dart b/test/indexing/services/indexing_failure_reporter_test.dart index 1cf69f85fd..f0a41f1312 100644 --- a/test/indexing/services/indexing_failure_reporter_test.dart +++ b/test/indexing/services/indexing_failure_reporter_test.dart @@ -3,9 +3,46 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/core/error_log_file.dart'; import 'package:otzaria/indexing/models/indexing_run_result.dart'; +import 'package:otzaria/indexing/models/indexing_run_diagnostics.dart'; +import 'package:otzaria/indexing/models/indexing_resource_policy.dart'; import 'package:otzaria/indexing/services/indexing_failure_reporter.dart'; void main() { + test( + 'cancelled report preserves overlapping stage times and resource reason', + () { + final collector = IndexingRunDiagnosticsCollector() + ..recoveryStarted = true + ..addTime( + IndexingStage.pdfExtraction, + const Duration(microseconds: 1234), + ) + ..addTime(IndexingStage.engine, const Duration(seconds: 2)) + ..increment(IndexingCounter.pdfPages, 7) + ..recordResources( + const IndexingResourcePolicy(cpuCount: 4, mobile: false), + IndexingResourceMode.automatic, + ); + final report = IndexingFailureReporter.formatReport( + IndexingRunResult.cancelled( + processedBooks: 1, + totalBooks: 2, + indexedBooks: 1, + diagnostics: collector.snapshot(), + ), + memory: const {}, + elapsed: const Duration(seconds: 2), + ); + expect(report, contains('Completed: false')); + expect(report, contains('Recovery at start: true')); + expect(report, contains('overlapping stages; not additive')); + expect(report, contains('pdfExtraction: 1234us')); + expect(report, contains('engine: 2000000us')); + expect(report, contains('pdfPages: 7')); + expect(report, contains('mode=automatic reason=lowCpu cpu=4')); + expect(report, contains('totalRamMb=null availableRamMb=null')); + }, + ); const failures = [ IndexingFailure( bookTitle: 'מוגן', diff --git a/test/indexing/utils/indexing_crash_canary_test.dart b/test/indexing/utils/indexing_crash_canary_test.dart index d0a8d5e8d5..12e2acac1e 100644 --- a/test/indexing/utils/indexing_crash_canary_test.dart +++ b/test/indexing/utils/indexing_crash_canary_test.dart @@ -14,6 +14,44 @@ void main() { }); tearDown(() => IndexingCrashCanary.writeLog = ErrorLogFile.appendText); + test('עבודה חדשה אינה מחזירה ריצה בריאה למצב התאוששות', () async { + final temp = await Directory.systemTemp.createTemp('canary_recovery_'); + addTearDown(() => temp.delete(recursive: true)); + final index = p.join(temp.path, 'index'); + File('$index.in_flight.json').writeAsStringSync(jsonEncode({'old': 1})); + IndexingCrashCanary.start(index); + final canary = IndexingCrashCanary.current!; + addTearDown(canary.finish); + expect(canary.recovering, isTrue); + canary.begin('new'); + canary.begin('old'); + canary.end('old'); + expect(canary.recovering, isFalse); + await canary.flush(); + expect(jsonDecode(File('$index.in_flight.json').readAsStringSync()), { + 'new': 1, + }); + expect(canary.begin('old'), isTrue); + expect(canary.recovering, isFalse); + }); + + test('דילוג על חשוד נשאר בהתאוששות עד שנחתם', () async { + final temp = await Directory.systemTemp.createTemp('canary_skipped_'); + addTearDown(() => temp.delete(recursive: true)); + final index = p.join(temp.path, 'index'); + File('$index.in_flight.json').writeAsStringSync(jsonEncode({'old': 2})); + IndexingCrashCanary.start(index); + final canary = IndexingCrashCanary.current!; + addTearDown(canary.finish); + expect(canary.begin('old'), isFalse); + canary.end('old'); + expect(canary.recovering, isTrue); + canary.committed({'other'}); + expect(canary.recovering, isTrue); + canary.committed({'old'}); + expect(canary.recovering, isFalse); + }); + test( 'commit מנקה רק דילוג שנחתם, ומשמר ספר שעדיין מחולץ וספר שלא נבדק', () async { diff --git a/test/indexing/utils/pdf_extraction_prefetcher_test.dart b/test/indexing/utils/pdf_extraction_prefetcher_test.dart index 455f9cad59..f41e328858 100644 --- a/test/indexing/utils/pdf_extraction_prefetcher_test.dart +++ b/test/indexing/utils/pdf_extraction_prefetcher_test.dart @@ -48,6 +48,28 @@ bool _always(PdfBook book) => true; void main() { group('PdfExtractionPrefetcher.fill', () { + test('התאוששות מעכבת סריקה וחידוש אינו מדלג על ספר', () async { + final extractor = _ControlledExtractor(); + var recovering = true; + final prefetcher = PdfExtractionPrefetcher( + extract: extractor.call, + canPrefetch: () => !recovering, + fileSizeOf: (_) async => 0, + ); + addTearDown(prefetcher.dispose); + final books = [_pdf('p0'), _pdf('p1')]; + await prefetcher.fill(books, 0, shouldPrefetch: _always); + expect(extractor.started, isEmpty); + recovering = false; + await prefetcher.fill(books, 0, shouldPrefetch: _always); + expect(extractor.started, ['p0']); + await extractor.finish('p0'); + prefetcher.takeReady(); + await prefetcher.fill(books, 0, shouldPrefetch: _always); + expect(extractor.started, ['p0', 'p1']); + await extractor.finish('p1'); + }); + test('ברירת המחדל משאירה רק חילוץ יחיד בטיסה', () async { final extractor = _ControlledExtractor(); final prefetcher = PdfExtractionPrefetcher( diff --git a/test/support/indexing_progress_capture_test.dart b/test/support/indexing_progress_capture_test.dart new file mode 100644 index 0000000000..67180ab640 --- /dev/null +++ b/test/support/indexing_progress_capture_test.dart @@ -0,0 +1,133 @@ +import 'package:otzaria/indexing/models/pdf_indexing_progress.dart'; + +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/indexing/bloc/indexing_state.dart'; +import 'package:otzaria/indexing/indexing_work_status.dart'; +import 'package:otzaria/theme/app_seed_colors.dart'; +import 'package:otzaria/theme/app_theme_data.dart'; +import 'package:otzaria/work_status/work_status_cubit.dart'; +import 'package:otzaria/work_status/work_status_overlay.dart'; + +import 'golden_fonts.dart'; + +void main() { + final output = Platform.environment['OTZARIA_INDEXING_UI_CAPTURE_OUT']; + for (final compact in [false, true]) { + for (final brightness in Brightness.values) { + testWidgets( + 'indexing progress capture ${compact ? 'compact' : 'desktop'} ${brightness.name}', + (tester) async { + debugDefaultTargetPlatformOverride = goldenPlatform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = Size(compact ? 360 : 900, 360); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + await loadGoldenFonts(); + + final cubit = WorkStatusCubit(); + addTearDown(cubit.close); + final boundaryKey = GlobalKey(); + final scheme = AppThemeData.createColorScheme( + brightness == Brightness.light + ? AppSeedColors.defaultLight + : AppSeedColors.defaultDark, + brightness, + ); + final theme = brightness == Brightness.light + ? AppThemeData.light(scheme, compactMenuMode: compact) + : AppThemeData.dark(scheme, compactMenuMode: compact); + + for (final capture in ['before', 'after', 'retry']) { + final after = capture != 'before'; + final retry = capture == 'retry'; + cubit.upsert( + indexingWorkStatusItem( + IndexingInProgress( + booksProcessed: 7, + totalBooks: 12, + pdfPagesProcessed: retry + ? 2 + : after + ? 23 + : null, + pdfTotalPages: retry + ? 5 + : after + ? 120 + : null, + pdfPhase: retry + ? PdfIndexingPhase.retry + : PdfIndexingPhase.extraction, + ), + onTogglePause: () {}, + onToggleEconomy: () {}, + ), + ); + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: MaterialApp( + debugShowCheckedModeBanner: false, + theme: theme, + locale: const Locale('he', 'IL'), + supportedLocales: const [Locale('he', 'IL')], + localizationsDelegates: GlobalMaterialLocalizations.delegates, + home: RepaintBoundary( + key: boundaryKey, + child: const Scaffold( + body: Stack(children: [WorkStatusOverlay()]), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('אינדוקס ספרים'), findsOneWidget); + expect(find.text('השהה'), findsOneWidget); + expect( + find.textContaining( + retry ? 'ניסיון חוזר לחילוץ PDF' : 'חילוץ PDF ברקע', + ), + after ? findsOneWidget : findsNothing, + ); + expect( + Directionality.of(tester.element(find.byType(WorkStatusOverlay))), + TextDirection.rtl, + ); + final boundary = + boundaryKey.currentContext!.findRenderObject()! + as RenderRepaintBoundary; + final name = + '$capture-${compact ? 'compact' : 'desktop'}-${brightness.name}.png'; + await tester.runAsync(() async { + final image = await boundary.toImage(); + try { + final data = await image.toByteData( + format: ui.ImageByteFormat.png, + ); + final file = File('$output/$name'); + await file.parent.create(recursive: true); + await file.writeAsBytes(data!.buffer.asUint8List()); + } finally { + image.dispose(); + } + }); + } + await tester.pumpWidget(const SizedBox.shrink()); + debugDefaultTargetPlatformOverride = null; + }, + skip: output == null, + ); + } + } +} diff --git a/test/tool/perf_probe/indexing_native_probe_test.dart b/test/tool/perf_probe/indexing_native_probe_test.dart new file mode 100644 index 0000000000..f756222440 --- /dev/null +++ b/test/tool/perf_probe/indexing_native_probe_test.dart @@ -0,0 +1,271 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/data/data_providers/cache_database_holder.dart'; +import 'package:otzaria/data/book_identity.dart'; +import 'package:otzaria/data/data_providers/tantivy_data_provider.dart'; +import 'package:otzaria/indexing/models/index_update_mode.dart'; +import 'package:otzaria/indexing/repository/indexing_repository.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/migration/services/external_book_import.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; +import 'package:otzaria/utils/file/document_format.dart'; +import 'package:otzaria/utils/file/document_converter.dart'; +import 'package:otzaria_search_engine/otzaria_search_engine.dart'; +import 'package:pdfrx/pdfrx.dart'; + +import '../../../integration_test/support/installed_plugin_pdf_fixture.dart'; +import '../../support/search_engine_test_init.dart'; +import '../../test_helpers/memory_cache_provider.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final output = Platform.environment['OTZARIA_INDEXING_PROBE_OUT']; + test( + 'isolated native indexing measurement', + () async { + await runNativeIndexingMeasurement(output!); + }, + skip: output == null + ? 'Set OTZARIA_INDEXING_PROBE_OUT to measure indexing' + : false, + timeout: const Timeout(Duration(minutes: 15)), + ); +} + +/// מריץ מדידה ואימות תוכן מתוך גוף בדיקה פעילה. +Future> runNativeIndexingMeasurement(String output) async { + final pdfPageCount = int.parse( + Platform.environment['OTZARIA_INDEXING_PROBE_PDF_PAGES'] ?? '4', + ); + expect(pdfPageCount, greaterThan(0)); + expect(await tryInitSearchEngine(), true, reason: searchEngineSkipReason); + final loadedEngine = File(searchEngineLoadedLibraryPath!); + final loadedEngineDigest = sha256 + .convert(await loadedEngine.readAsBytes()) + .toString(); + final root = await Directory.systemTemp.createTemp('indexing-probe-'); + final oldModule = Pdfrx.pdfiumModulePath; + final module = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium_dart.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$module', + ).absolute.path; + await pdfrxInitialize(tmpPath: root.path); + AppPaths.debugOverrideDataRootPath(root.path); + addTearDown(() async { + await CacheDatabaseHolder.instance.close(); + AppPaths.debugOverrideDataRootPath(null); + Pdfrx.pdfiumModulePath = oldModule; + await root.delete(recursive: true); + }); + final rows = >[]; + final manifest = {}; + for (final economy in [false, true]) { + for (final kind in ['txt', 'docx', 'pdf', 'pdf-recovery']) { + final directory = await Directory('${root.path}/$kind-$economy').create(); + await Settings.init(cacheProvider: MemoryCacheProvider()); + await Settings.setValue( + SettingsRepository.keyDatabasesPath, + directory.path, + ); + await Settings.setValue( + SettingsRepository.keyLibraryPath, + directory.path, + ); + final index = await Directory('${directory.path}/index').create(); + final engine = await SearchEngine.newInstance(path: index.path); + final provider = TantivyDataProvider.forTesting(Future.value(engine)) + ..activeIndexPath = index.path + ..isInitialized.value = true; + TantivyDataProvider.instance = provider; + final repository = IndexingRepository( + provider, + indexPdfBooks: () => true, + indexUpdateMode: () => IndexUpdateMode.all, + ); + await repository.setEconomyIndexing(economy); + final pdf = kind.startsWith('pdf'); + final extension = pdf ? 'pdf' : kind; + final books = []; + final texts = List.generate( + 1000, + (i) => + 'benchmarktoken שורה מספר $i עם תוכן ארוך מספיק לאינדוקס ומילים נוספות לבדיקת שלמות התוצאות', + ); + final archive = Archive(); + final xml = utf8.encode( + '${texts.map((line) => '$line').join()}', + ); + archive.addFile( + ArchiveFile('word/document.xml', xml.length, xml)..lastModTime = 0, + ); + final bytes = pdf + ? createInstalledPdfFixture(pageCount: pdfPageCount) + : kind == 'docx' + ? ZipEncoder().encode(archive) + : utf8.encode(texts.join('\n')); + manifest[kind] = sha256.convert(bytes).toString(); + for (var i = 0; i < 8; i++) { + final file = await File('${directory.path}/book$i.$extension') + .writeAsBytes(bytes); + books.add( + pdf + ? PdfBook( + title: 'book$i', + path: file.path, + source: BookSource.user, + ) + : kind == 'txt' + ? _FileTextBook(title: 'book$i', path: file.path) + : TextBook( + title: 'book$i', + filePath: file.path, + fileType: kind, + source: BookSource.user, + ), + ); + } + if (kind == 'pdf-recovery') { + await File('${index.path}.in_flight.json').writeAsString( + jsonEncode({ + books.first.filePath ?? (books.first as PdfBook).path: 1, + }), + ); + } + final library = Library(categories: [])..books.addAll(books); + final watch = Stopwatch()..start(); + if (!pdf) { + for (final book in books) { + final file = File(book.filePath!); + await PreparedExternalBook.prepare( + file.path, + await file.stat(), + kind == 'docx' ? DocumentFormat.docx : DocumentFormat.txt, + ); + } + } + final result = await repository.runIndexing( + library, + books: books, + onProgress: (_, _) {}, + ); + watch.stop(); + expect(result.isClean, true, reason: '${result.failures}'); + expect(result.indexedBooks, 8); + final segmentCount = await engine.getSegmentCount(); + expect(segmentCount, greaterThan(0)); + final expected = pdf ? 8 * pdfPageCount : 8000; + final hits = await engine.searchExact( + query: pdf ? installedPdfQuery : 'benchmarktoken', + facets: const [], + limit: expected + 1, + offset: 0, + order: ResultsOrder.catalogue, + matchNikud: false, + matchTaamim: false, + ); + expect(hits, hasLength(expected)); + final keysToTitles = { + for (final book in books) + BookIdentity.indexedFilePath(book): book.title, + }; + final fingerprints = await engine.getBookTextFingerprints(); + expect(fingerprints.keys.toSet(), keysToTitles.keys.toSet()); + final stamps = >[]; + for (final entry in keysToTitles.entries) { + final hash = fingerprints[entry.key]!; + expect(hash, greaterThan(BigInt.zero), reason: entry.value); + stamps.add([entry.value, hash.toString()]); + } + stamps.sort((a, b) => a.first.compareTo(b.first)); + final hitsPerBook = {}; + final canonicalHits = []; + for (final hit in hits) { + expect(keysToTitles[hit.filePath], hit.title); + expect(hit.textStatus, TextStatus.ok); + expect(hit.text, isNotEmpty); + expect(hit.isPdf, pdf); + hitsPerBook.update( + hit.title, + (count) => count + 1, + ifAbsent: () => 1, + ); + canonicalHits.add( + jsonEncode([ + hit.title, + hit.reference, + hit.text, + hit.isPdf, + hit.continuesToNextLine, + ]), + ); + } + expect(hitsPerBook.keys.toSet(), keysToTitles.values.toSet()); + expect(hitsPerBook.values, everyElement(expected ~/ 8)); + canonicalHits.sort(); + rows.add({ + 'case': kind, + 'economy': economy, + 'elapsedUs': watch.elapsedMicroseconds, + 'documentsMatched': hits.length, + 'books': result.indexedBooks, + 'segmentCount': segmentCount, + 'textFingerprints': { + for (final stamp in stamps) stamp.first: stamp.last, + }, + 'textFingerprintSha256': sha256 + .convert(utf8.encode(jsonEncode(stamps))) + .toString(), + 'hitsPerBook': hitsPerBook, + 'hitContentSha256': sha256 + .convert(utf8.encode(jsonEncode(canonicalHits))) + .toString(), + 'rssBytesAfter': ProcessInfo.currentRss, + 'peakRssBytesProcess': ProcessInfo.maxRss, + }); + await engine.closeIndexWriter(); + engine.dispose(); + await CacheDatabaseHolder.instance.close(); + } + } + final report = { + 'schemaVersion': 2, + 'pdfPageCount': pdfPageCount, + 'buildMode': 'flutter-test-debug/native-build-hook', + 'os': Platform.operatingSystem, + 'dartVersion': Platform.version, + 'processors': Platform.numberOfProcessors, + 'cacheState': 'fresh application index/cache; OS cache uncontrolled', + 'scope': 'metadata preparation and repository indexing, not folder scanning or UI responsiveness', + 'manifest': manifest, + 'loadedEnginePath': loadedEngine.absolute.path, + 'loadedEngineSha256': loadedEngineDigest, + 'pdfiumSha256': sha256 + .convert(await File(Pdfrx.pdfiumModulePath!).readAsBytes()) + .toString(), + 'rows': rows, + }; + await File(output).writeAsString(jsonEncode(report)); + return report; +} + +/// הקטלוג אינו חלק מהמדידה; הקובץ נקרא דרך מפענח הטקסט של האפליקציה. +class _FileTextBook extends TextBook { + _FileTextBook({required super.title, required String path}) + : super(filePath: path, fileType: 'txt', source: BookSource.user); + + @override + Future get text async => + (await readFileBackedBookText(File(filePath!), fileType, title))!; +} diff --git a/test/tool/perf_probe/installed_plugin_pdf_fixture_test.dart b/test/tool/perf_probe/installed_plugin_pdf_fixture_test.dart index 2c1bddd7e8..b881d06e19 100644 --- a/test/tool/perf_probe/installed_plugin_pdf_fixture_test.dart +++ b/test/tool/perf_probe/installed_plugin_pdf_fixture_test.dart @@ -46,8 +46,31 @@ void main() { test('fixture bytes are reproducible', () { final first = createInstalledPdfFixture(); expect(first, createInstalledPdfFixture()); + expect(first, createInstalledPdfFixture(pageCount: 4)); + expect(() => createInstalledPdfFixture(pageCount: 0), throwsArgumentError); }); + test( + 'extended fixture cycles page dimensions and preserves page tokens', + () async { + final document = await PdfDocument.openData( + createInstalledPdfFixture(pageCount: 6), + ); + addTearDown(document.dispose); + expect(document.pages, hasLength(6)); + for (var i = 0; i < document.pages.length; i++) { + final page = document.pages[i]; + final size = installedPdfPageSizes[i % installedPdfPageSizes.length]; + expect(page.width, size.width); + expect(page.height, size.height); + expect( + (await page.loadText())!.fullText, + contains(installedPdfPageToken(i + 1)), + ); + } + }, + ); + testWidgets('target readiness waits for the navigated viewport to paint', ( tester, ) async { diff --git a/test_driver/indexing_native_probe.dart b/test_driver/indexing_native_probe.dart new file mode 100644 index 0000000000..b38629cca9 --- /dev/null +++ b/test_driver/indexing_native_probe.dart @@ -0,0 +1,3 @@ +import 'package:integration_test/integration_test_driver.dart'; + +Future main() => integrationDriver(); diff --git a/tool/ci/prepare_native_build_dependencies.py b/tool/ci/prepare_native_build_dependencies.py index 4458b96375..fa42b6a422 100644 --- a/tool/ci/prepare_native_build_dependencies.py +++ b/tool/ci/prepare_native_build_dependencies.py @@ -195,8 +195,19 @@ def write_cmake_cache(build_directory, values): value = directory.as_posix() if any(character in value for character in ("\r", "\n", ";")): raise ValueError("Dependency path cannot contain a CMake list or line separator") - lines = [line for line in lines if not re.match(rf"^{key}:[^=]*=", line)] - lines.append(f"{key}:PATH={value}") + positions = [index for index, line in enumerate(lines) + if re.match(rf"^{re.escape(key)}:[^=]*=", line)] + entry = f"{key}:PATH={value}" + if positions: + lines[positions[0]] = entry + for index in reversed(positions[1:]): + start = index + # CMake requires each help block to be followed by an entry. + while start > 0 and lines[start - 1].startswith("//"): + start -= 1 + del lines[start:index + 1] + else: + lines.append(entry) descriptor, temporary_name = tempfile.mkstemp(prefix="cache-", dir=build_directory) os.close(descriptor) temporary = Path(temporary_name) diff --git a/tool/ci/test_prepare_native_build_dependencies.py b/tool/ci/test_prepare_native_build_dependencies.py index 22f835b2b5..c59ebbcebb 100644 --- a/tool/ci/test_prepare_native_build_dependencies.py +++ b/tool/ci/test_prepare_native_build_dependencies.py @@ -251,6 +251,33 @@ def test_line_and_cmake_list_injection_preserves_cache(self): native.write_cmake_cache(build, {"PRINTING_PDFIUM_DIR": self.root / suffix}) self.assertEqual(cache.read_text(), "KEEP:BOOL=ON\n") + def test_cache_replacement_preserves_help_and_entry_position(self): + build = self.root / "build" + build.mkdir() + cache = build / "CMakeCache.txt" + original = ("// Existing dependency path\n// and its second help line\n" + "PRINTING_PDFIUM_DIR:PATH=old\n\n" + "// Unrelated setting\nKEEP:STRING=hello\n") + cache.write_text(original) + native.write_cmake_cache(build, {"PRINTING_PDFIUM_DIR": self.printing}) + self.assertEqual(cache.read_text(), original.replace( + "PRINTING_PDFIUM_DIR:PATH=old", f"PRINTING_PDFIUM_DIR:PATH={self.printing.as_posix()}")) + + def test_cache_duplicate_entries_remove_their_help_without_orphaning_it(self): + build = self.root / "build" + build.mkdir() + cache = build / "CMakeCache.txt" + cache.write_text("// First help\nPRINTING_PDFIUM_DIR:PATH=first\n\n" + "// Duplicate help\n// second line\nPRINTING_PDFIUM_DIR:PATH=second\n\n" + "// Unrelated help\nKEEP:BOOL=ON\n") + native.write_cmake_cache(build, {"PRINTING_PDFIUM_DIR": self.printing}) + result = cache.read_text() + self.assertTrue(result.startswith(f"// First help\nPRINTING_PDFIUM_DIR:PATH={self.printing.as_posix()}\n")) + self.assertEqual(result.count("PRINTING_PDFIUM_DIR:"), 1) + self.assertNotIn("// Duplicate help", result) + self.assertNotIn("// second line", result) + self.assertIn("// Unrelated help\nKEEP:BOOL=ON\n", result) + @unittest.skipUnless(shutil.which("cmake"), "CMake is required for the real configuration control") def test_real_cmake_consumes_prepared_sources_twice_without_network(self): source = self.root / "cmake project" @@ -279,12 +306,12 @@ def test_real_cmake_consumes_prepared_sources_twice_without_network(self): sentry_source = self.root / "sentry source" sentry_source.mkdir() (sentry_source / "CMakeLists.txt").write_text("add_library(sentry INTERFACE)\n") - native.write_cmake_cache(build, { - "PRINTING_PDFIUM_DIR": self.printing, - "FETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON": json_source, - "FETCHCONTENT_SOURCE_DIR_SN": sentry_source, - }) for _ in range(2): + native.write_cmake_cache(build, { + "PRINTING_PDFIUM_DIR": self.printing, + "FETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON": json_source, + "FETCHCONTENT_SOURCE_DIR_SN": sentry_source, + }) result = subprocess.run(["cmake", "-S", str(source), "-B", str(build)], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) diff --git a/tool/perf_probe/run_indexing_pair.py b/tool/perf_probe/run_indexing_pair.py new file mode 100644 index 0000000000..020daf9ecb --- /dev/null +++ b/tool/perf_probe/run_indexing_pair.py @@ -0,0 +1,317 @@ +"""Compare native indexing through the same Flutter-test harness on one host.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import statistics +import subprocess +import sys +import tempfile + + +HARNESS = "test/tool/perf_probe/indexing_native_probe_test.dart" +PROFILE_TARGET = "integration_test/indexing_native_probe_test.dart" +PROFILE_DRIVER = "test_driver/indexing_native_probe.dart" +PROFILE_WINDOW_SUPPORT = "integration_test/support/webview_probe_window.dart" +PROFILE_BUILD_HELPER = "tool/ci/prepare_native_build_dependencies.py" +PROFILE_BUILD_SUPPORT = [PROFILE_BUILD_HELPER, "tool/release/download_release_asset.sh"] +SUPPORT = [HARNESS, "integration_test/support/installed_plugin_pdf_fixture.dart", + "test/support/search_engine_test_init.dart", + "test/test_helpers/memory_cache_provider.dart"] +CASES = {(kind, economy) for kind in ("txt", "docx", "pdf", "pdf-recovery") + for economy in (False, True)} +BOOK_TITLES = {f"book{index}" for index in range(8)} + + +def profile_build_command(flutter): + return [flutter, 'build', 'windows', '--profile', '--no-pub', + '--target=' + PROFILE_TARGET] + + +def profile_artifact_hashes(executable): + executable = Path(executable) + if executable.suffix.lower() != '.exe' or not executable.is_file(): + raise ValueError('A built Windows profile executable is required') + if not (executable.parent / 'portable.marker').is_file(): + raise ValueError('Profile bundle must have its own portable.marker') + files = {'otzaria.exe': executable, + 'data/app.so': executable.parent / 'data/app.so', + 'flutter_windows.dll': executable.parent / 'flutter_windows.dll'} + for relative, path in files.items(): + if not path.is_file(): + raise ValueError(f'Missing profile application artifact: {relative}') + return {relative: hashlib.sha256(path.read_bytes()).hexdigest() + for relative, path in files.items()} + + +def prepare_profile_application(flutter, checkout, log): + executable = checkout / 'build/windows/x64/runner/Profile/otzaria.exe' + executable.parent.mkdir(parents=True, exist_ok=True) + command([sys.executable, '-B', PROFILE_BUILD_HELPER, '--project-root', str(checkout), + '--platform', 'windows', '--arch', 'x64', '--mode', 'profile', '--with-sentry'], + checkout, log.with_name(log.stem + '-dependencies' + log.suffix)) + command(profile_build_command(flutter), checkout, log) + (executable.parent / 'portable.marker').touch() + return executable, profile_artifact_hashes(executable) + + +def verify_profile_artifacts(executable, expected): + if profile_artifact_hashes(executable) != expected: + raise ValueError('Profile application artifacts changed after their build') + + +def validate_profile_pair(artifacts): + if artifacts['baseline']['flutter_windows.dll'] != artifacts['candidate']['flutter_windows.dll']: + raise ValueError('Profile builds use different Flutter engine binaries') + + +def measurement_command(flutter, mode, application_binary=None): + if mode == 'profile': + if application_binary is None: + raise ValueError('Profile measurements require a prebuilt application') + application_binary = Path(application_binary) + if application_binary.suffix.lower() != '.exe' or not application_binary.is_file(): + raise ValueError('Profile application executable is missing') + return [flutter, 'drive', '--profile', '-d', 'windows', '--no-pub', + '--target=' + PROFILE_TARGET, '--driver=' + PROFILE_DRIVER, + '--use-application-binary=' + str(application_binary)] + if mode != 'debug': + raise ValueError('Unsupported measurement mode') + return [flutter, 'test', '--no-pub', HARNESS, '--concurrency=1'] + + +def command(args, cwd, log=None, env=None): + process = subprocess.run(args, cwd=cwd, env=env, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + encoding="utf-8", errors="replace") + if log: + log.write_text(process.stdout, encoding="utf-8") + if process.returncode: + raise RuntimeError(f"Command failed ({process.returncode}): {args}; log={log}") + return process.stdout.strip() + + +def validate(report): + if report.get("schemaVersion") != 2: + raise ValueError("Unsupported or absent indexing report schema") + pdf_pages = report.get("pdfPageCount") + if type(pdf_pages) is not int or pdf_pages <= 0: + raise ValueError("Missing or invalid PDF page count") + keys = [(row["case"], row["economy"]) for row in report["rows"]] + if len(keys) != len(CASES) or set(keys) != CASES: + raise ValueError("Missing, duplicated or unexpected indexing cases") + for row in report["rows"]: + expected = 8 * pdf_pages if row["case"].startswith("pdf") else 8000 + if row["documentsMatched"] != expected or row["books"] != 8: + raise ValueError("Incomplete indexed corpus") + if row["elapsedUs"] <= 0: + raise ValueError("Invalid duration") + if type(row.get("segmentCount")) is not int or row["segmentCount"] <= 0: + raise ValueError("Missing or invalid committed segment count") + stamps = row.get("textFingerprints", {}) + if set(stamps) != BOOK_TITLES or any( + not re.fullmatch(r"[1-9][0-9]*", value) or int(value) >= 2**64 + for value in stamps.values()): + raise ValueError("Missing, zero or invalid per-book text fingerprints") + digest = hashlib.sha256(json.dumps(sorted(stamps.items()), ensure_ascii=False, + separators=(",", ":")).encode("utf-8")).hexdigest() + if row.get("textFingerprintSha256") != digest: + raise ValueError("Per-book text fingerprint digest disagrees") + per_book = row.get("hitsPerBook", {}) + if set(per_book) != BOOK_TITLES or any(value != expected // 8 for value in per_book.values()): + raise ValueError("Missing or incomplete per-book matches") + if not re.fullmatch(r"[0-9a-f]{64}", row.get("hitContentSha256", "")): + raise ValueError("Missing canonical result content digest") + for key in ("loadedEngineSha256", "pdfiumSha256"): + if not re.fullmatch(r"[0-9a-f]{64}", report.get(key, "")): + raise ValueError(f"Loaded native binary identity missing: {key}") + if not report.get("loadedEnginePath"): + raise ValueError("Loaded engine path missing") + + +def compare(samples): + reference = samples[0]["report"] + for sample in samples: + report = sample["report"] + validate(report) + for key in ("manifest", "buildMode", "pdfPageCount", "os", "dartVersion", "processors", "cacheState", + "loadedEngineSha256", "pdfiumSha256"): + if report[key] != reference[key]: + raise ValueError(f"Non-comparable metadata: {key}") + measured = [sample for sample in samples if not sample["warmup"]] + results = [] + for kind, economy in sorted(CASES): + by_role = {} + iterations_by_role = {} + fingerprints = set() + hit_contents = set() + for role in ("baseline", "candidate"): + iterations = {} + for sample in measured: + if sample['role'] != role: + continue + iteration = sample.get('iteration') + if type(iteration) is not int or iteration < 0: + raise ValueError('Measured samples require a non-negative integer iteration') + if iteration in iterations: + raise ValueError(f'Duplicate measured iteration: {role}, {iteration}') + iterations[iteration] = next(row for row in sample['report']['rows'] + if row['case'] == kind and row['economy'] == economy) + iterations_by_role[role] = iterations + rows = list(iterations.values()) + if len(rows) < 5: + raise ValueError("At least five measured repetitions per source required") + fingerprints.update(row["textFingerprintSha256"] for row in rows) + hit_contents.update(row["hitContentSha256"] for row in rows) + median = statistics.median(row["elapsedUs"] for row in rows) + by_role[role] = {"medianMs": median / 1000, + "documentsPerSecond": rows[0]["documentsMatched"] * 1_000_000 / median, + "rssBytesAfterMedian": statistics.median(row["rssBytesAfter"] for row in rows), + "peakRssBytesProcessMedian": statistics.median(row["peakRssBytesProcess"] for row in rows), + "segmentCountMedian": statistics.median(row["segmentCount"] for row in rows), + "samples": len(rows)} + if len(fingerprints) != 1: + raise ValueError(f"Indexed contents changed: {kind}, economy={economy}") + if len(hit_contents) != 1: + raise ValueError(f"Result contents changed: {kind}, economy={economy}") + if iterations_by_role['baseline'].keys() != iterations_by_role['candidate'].keys(): + raise ValueError('Baseline and candidate measured iterations do not match') + pairs = [] + for iteration in sorted(iterations_by_role['baseline']): + baseline = iterations_by_role['baseline'][iteration]['elapsedUs'] + candidate = iterations_by_role['candidate'][iteration]['elapsedUs'] + pairs.append({'iteration': iteration, 'baselineMs': baseline / 1000, + 'candidateMs': candidate / 1000, + 'durationRatio': candidate / baseline, + 'durationDeltaMs': (candidate - baseline) / 1000}) + results.append({"case": kind, "economy": economy, **by_role, + "durationRatio": by_role["candidate"]["medianMs"] / by_role["baseline"]["medianMs"], + "durationRatioBasis": "ratio of group medians", + "paired": {'medianDurationRatio': statistics.median(pair['durationRatio'] for pair in pairs), + 'medianDurationDeltaMs': statistics.median(pair['durationDeltaMs'] for pair in pairs), + 'candidateSlowerPairs': sum(pair['durationDeltaMs'] > 0 for pair in pairs), + 'pairs': len(pairs), 'rows': pairs}}) + return results + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--candidate", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--repetitions", type=int, default=5) + parser.add_argument("--warmups", type=int, default=1) + parser.add_argument("--mode", choices=['debug', 'profile'], default='debug') + parser.add_argument("--pdf-pages", type=int, default=4) + args = parser.parse_args() + for commit in (args.baseline, args.candidate): + if not re.fullmatch(r"[0-9a-f]{40}", commit): + parser.error("Sources must be full immutable commit SHAs") + if args.repetitions < 5 or args.warmups < 1: + parser.error("Require at least five measured repetitions and one warmup") + if args.pdf_pages <= 0: + parser.error("PDF page count must be positive") + root = Path(command(["git", "rev-parse", "--show-toplevel"], Path.cwd())) + flutter = shutil.which("flutter.bat" if os.name == "nt" else "flutter") + if not flutter: + parser.error("Flutter SDK not found") + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + snapshots = {} + samples = [] + shared_engine = None + profile_applications = {} + profile_artifacts = {} + with tempfile.TemporaryDirectory(prefix="otz-idx-", dir=os.environ.get('RUNNER_TEMP')) as temporary: + scratch = Path(temporary) + try: + for role, commit in (("baseline", args.baseline), ("candidate", args.candidate)): + checkout = scratch / role + command(["git", "worktree", "add", "--detach", str(checkout), commit], root) + snapshots[role] = checkout + support = SUPPORT + ([PROFILE_TARGET, PROFILE_DRIVER, PROFILE_WINDOW_SUPPORT, + *PROFILE_BUILD_SUPPORT] + if args.mode == 'profile' else []) + for relative in support: + target = checkout / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(root / relative, target) + command([flutter, "pub", "get", "--enforce-lockfile"], checkout, output / f"{role}-pub.log") + locks = [hashlib.sha256((path / "pubspec.lock").read_bytes()).hexdigest() + for path in snapshots.values()] + if locks[0] != locks[1]: + raise ValueError("Lockfiles differ; this experiment isolates app-code changes") + if args.mode == 'profile': + for role, checkout in snapshots.items(): + executable, artifacts = prepare_profile_application( + flutter, checkout, output / f'{role}-profile-build.log') + profile_applications[role] = executable + profile_artifacts[role] = artifacts + validate_profile_pair(profile_artifacts) + for iteration in range(args.warmups + args.repetitions): + order = ("baseline", "candidate") if iteration % 2 == 0 else ("candidate", "baseline") + for role in order: + name = f"{iteration:02}-{role}" + raw = output / f"{name}.json" + env = dict(os.environ, OTZARIA_INDEXING_PROBE_OUT=str(raw), + OTZARIA_INDEXING_PROBE_ROOT=str(snapshots[role]), + OTZARIA_INDEXING_PROBE_PDF_PAGES=str(args.pdf_pages)) + if shared_engine: + env.update(OTZARIA_SEARCH_ENGINE_LIBRARY_PATH=shared_engine[0], + OTZARIA_EXPECTED_SEARCH_ENGINE_SHA256=shared_engine[1]) + executable = profile_applications.get(role) + if executable is not None: + verify_profile_artifacts(executable, profile_artifacts[role]) + try: + command(measurement_command(flutter, args.mode, executable), + snapshots[role], output / f"{name}.log", env) + finally: + if executable is not None: + verify_profile_artifacts(executable, profile_artifacts[role]) + report = json.loads(raw.read_text(encoding="utf-8")) + validate(report) + if report['pdfPageCount'] != args.pdf_pages: + raise ValueError('Measured PDF page count differs from requested experiment') + if shared_engine is None: + loaded = Path(report["loadedEnginePath"]) + if not loaded.is_file(): + raise ValueError("Loaded engine disappeared before paired measurement") + shared = scratch / "shared-native" / loaded.name + shared.parent.mkdir() + shutil.copy2(loaded, shared) + shared_engine = (str(shared), report["loadedEngineSha256"]) + samples.append({"role": role, "iteration": iteration, + "warmup": iteration < args.warmups, "report": report, + "applicationArtifactsSha256": profile_artifacts.get(role)}) + (output / "raw.json").write_text(json.dumps(samples, ensure_ascii=False, indent=2), encoding="utf-8") + result = {"baseline": args.baseline, "candidate": args.candidate, + "measurementMode": args.mode, + "pdfPageCount": args.pdf_pages, + "profileApplications": {role: {'executable': str(executable), + 'sha256': profile_artifacts[role]} + for role, executable in profile_applications.items()}, + "profilePreparationSha256": {relative: hashlib.sha256((root / relative).read_bytes()).hexdigest() + for relative in PROFILE_BUILD_SUPPORT} + if args.mode == 'profile' else {}, + "lockSha256": locks[0], + "harnessSha256": hashlib.sha256((root / HARNESS).read_bytes()).hexdigest(), + "limitations": ["Flutter test debug harness; not release app performance" if args.mode == 'debug' + else "Flutter profile AOT in a minimal native window; not the full application UI", + "OS caches uncontrolled; fresh app index/cache per case", + "No UI frame or concurrent-search measurement", + "Peak RSS is cumulative per process, not attributable to one case", + "Metadata preparation and indexing; excludes folder discovery and worker import cache"], + "comparisons": compare(samples)} + (output / "comparison.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps(result, ensure_ascii=False, indent=2)) + finally: + for checkout in snapshots.values(): + command(["git", "worktree", "remove", "--force", str(checkout)], root) + + +if __name__ == "__main__": + main() diff --git a/tool/perf_probe/test_indexing_pair.py b/tool/perf_probe/test_indexing_pair.py new file mode 100644 index 0000000000..b05bf41517 --- /dev/null +++ b/tool/perf_probe/test_indexing_pair.py @@ -0,0 +1,236 @@ +import copy +import hashlib +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +from tool.perf_probe.run_indexing_pair import ( + CASES, PROFILE_BUILD_HELPER, compare, measurement_command, prepare_profile_application, + profile_artifact_hashes, profile_build_command, validate, validate_profile_pair, + verify_profile_artifacts, +) + + +def fixture(pdf_pages=4): + stamps = {f"book{index}": str(index + 1) for index in range(8)} + fingerprint = hashlib.sha256(json.dumps(sorted(stamps.items()), separators=(",", ":")).encode()).hexdigest() + return {"schemaVersion": 2, "manifest": {"txt": "abc"}, "buildMode": "test", + "pdfPageCount": pdf_pages, + "os": "windows", "dartVersion": "test", "processors": 8, + "cacheState": "fresh", "loadedEnginePath": "engine", + "loadedEngineSha256": "c" * 64, "pdfiumSha256": "d" * 64, + "rows": [{"case": kind, "economy": economy, "elapsedUs": 1000, + "documentsMatched": 8 * pdf_pages if kind.startswith("pdf") else 8000, + "books": 8, "segmentCount": 2, "textFingerprints": dict(stamps), + "textFingerprintSha256": fingerprint, + "hitsPerBook": {title: pdf_pages if kind.startswith("pdf") else 1000 for title in stamps}, + "hitContentSha256": "a" * 64, + "rssBytesAfter": 10, "peakRssBytesProcess": 20} + for kind, economy in sorted(CASES)]} + + +class IndexingPairTests(unittest.TestCase): + def test_profile_uses_native_drive_and_debug_uses_test(self): + with tempfile.TemporaryDirectory() as temporary: + executable = Path(temporary) / 'otzaria.exe' + executable.write_bytes(b'launcher') + profile = measurement_command('flutter', 'profile', executable) + self.assertIn('--use-application-binary=' + str(executable), profile) + with self.assertRaises(ValueError): + measurement_command('flutter', 'profile', executable.with_name('missing.exe')) + with self.assertRaises(ValueError): + measurement_command('flutter', 'profile', executable.parent) + debug = measurement_command('flutter', 'debug') + self.assertEqual(profile[:5], ['flutter', 'drive', '--profile', '-d', 'windows']) + self.assertIn('--target=integration_test/indexing_native_probe_test.dart', profile) + self.assertIn('--driver=test_driver/indexing_native_probe.dart', profile) + self.assertEqual(debug[:2], ['flutter', 'test']) + with self.assertRaises(ValueError): + measurement_command('flutter', 'release') + with self.assertRaises(ValueError): + measurement_command('flutter', 'profile') + self.assertEqual(profile_build_command('flutter'), [ + 'flutter', 'build', 'windows', '--profile', '--no-pub', + '--target=integration_test/indexing_native_probe_test.dart']) + + def test_profile_build_creates_portable_bundle_after_build_before_launch(self): + with tempfile.TemporaryDirectory() as temporary: + checkout = Path(temporary) + executable = checkout / 'build/windows/x64/runner/Profile/otzaria.exe' + operations = [] + + def build(args, cwd, log): + self.assertEqual(cwd, checkout) + self.assertFalse((executable.parent / 'portable.marker').exists()) + if not operations: + self.assertEqual(args, [sys.executable, '-B', PROFILE_BUILD_HELPER, + '--project-root', str(checkout), '--platform', 'windows', + '--arch', 'x64', '--mode', 'profile', '--with-sentry']) + operations.append('prepare') + return + self.assertEqual(operations, ['prepare']) + self.assertEqual(args, profile_build_command('flutter')) + operations.append('build') + executable.write_bytes(b'launcher') + (executable.parent / 'data').mkdir() + (executable.parent / 'data/app.so').write_bytes(b'aot') + (executable.parent / 'flutter_windows.dll').write_bytes(b'engine') + + with patch('tool.perf_probe.run_indexing_pair.command', side_effect=build) as mocked: + actual, hashes = prepare_profile_application('flutter', checkout, checkout / 'build.log') + self.assertEqual(mocked.call_count, 2) + self.assertEqual(operations, ['prepare', 'build']) + self.assertEqual(actual, executable) + self.assertTrue((executable.parent / 'portable.marker').is_file()) + self.assertEqual(set(hashes), {'otzaria.exe', 'data/app.so', 'flutter_windows.dll'}) + verify_profile_artifacts(executable, hashes) + for name in hashes: + path = executable.parent / name + original = path.read_bytes() + path.write_bytes(original + b'changed') + with self.assertRaisesRegex(ValueError, 'artifacts changed'): + verify_profile_artifacts(executable, hashes) + path.unlink() + with self.assertRaises(ValueError): + profile_artifact_hashes(executable) + path.write_bytes(original) + (executable.parent / 'portable.marker').unlink() + with self.assertRaisesRegex(ValueError, 'portable.marker'): + profile_artifact_hashes(executable) + + def test_profile_dependency_failure_does_not_start_build(self): + with tempfile.TemporaryDirectory() as temporary: + checkout = Path(temporary) + with patch('tool.perf_probe.run_indexing_pair.command', + side_effect=RuntimeError('Dependency download failed')) as mocked: + with self.assertRaisesRegex(RuntimeError, 'Dependency download failed'): + prepare_profile_application('flutter', checkout, checkout / 'build.log') + mocked.assert_called_once() + self.assertEqual(mocked.call_args.args[0][2], PROFILE_BUILD_HELPER) + + def test_profile_pair_requires_identical_flutter_engine(self): + baseline = {'otzaria.exe': 'a', 'data/app.so': 'b', 'flutter_windows.dll': 'c'} + candidate = {'otzaria.exe': 'd', 'data/app.so': 'e', 'flutter_windows.dll': 'c'} + validate_profile_pair({'baseline': baseline, 'candidate': candidate}) + candidate['flutter_windows.dll'] = 'changed' + with self.assertRaisesRegex(ValueError, 'different Flutter engine'): + validate_profile_pair({'baseline': baseline, 'candidate': candidate}) + + def samples(self, pdf_pages=4): + return [{"role": role, "iteration": iteration, + "warmup": iteration == 0, "report": fixture(pdf_pages)} + for iteration in range(6) for role in ("baseline", "candidate")] + + def test_pdf_page_count_requires_exact_per_book_results(self): + samples = self.samples(pdf_pages=600) + self.assertEqual(len(compare(samples)), 8) + for count in [None, 0, -1, True, 4.5, "600"]: + report = fixture() + report['pdfPageCount'] = count + with self.assertRaises(ValueError): + validate(report) + for field, value in [('documentsMatched', 32), + ('hitsPerBook', {f'book{i}': 4 for i in range(8)})]: + report = fixture(pdf_pages=600) + row = next(row for row in report['rows'] if row['case'] == 'pdf') + row[field] = value + with self.assertRaises(ValueError): + validate(report) + samples[-1]['report'] = fixture(pdf_pages=4) + with self.assertRaisesRegex(ValueError, 'pdfPageCount'): + compare(samples) + + def test_complete_comparison_excludes_warmup(self): + samples = self.samples() + samples[0]["report"]["rows"][0]["elapsedUs"] = 1000000 + result = compare(samples) + self.assertEqual(len(result), 8) + self.assertTrue(all(row["durationRatio"] == 1 for row in result)) + self.assertTrue(all(row["baseline"]["samples"] == 5 for row in result)) + self.assertTrue(all(row['paired']['pairs'] == 5 for row in result)) + self.assertTrue(all(row['paired']['candidateSlowerPairs'] == 0 for row in result)) + + def test_pairing_by_iteration_preserves_majority_when_group_medians_reverse(self): + samples = self.samples() + durations = {'baseline': [10000, 20000, 30000, 100000, 200000], + 'candidate': [40000, 15000, 25000, 90000, 150000]} + for sample in samples: + if sample['warmup']: + continue + for row in sample['report']['rows']: + row['elapsedUs'] = durations[sample['role']][sample['iteration'] - 1] + for result in compare(list(reversed(samples))): + self.assertGreater(result['durationRatio'], 1) + paired = result['paired'] + self.assertAlmostEqual(paired['medianDurationRatio'], 5 / 6) + self.assertEqual(paired['medianDurationDeltaMs'], -5) + self.assertEqual(paired['candidateSlowerPairs'], 1) + self.assertEqual(paired['pairs'], 5) + self.assertEqual([row['iteration'] for row in paired['rows']], [1, 2, 3, 4, 5]) + self.assertEqual(paired['rows'][0], {'iteration': 1, 'baselineMs': 10, + 'candidateMs': 40, 'durationRatio': 4, 'durationDeltaMs': 30}) + + def test_duplicate_missing_or_invalid_pair_iterations_are_rejected(self): + for mutate in [lambda samples: samples.append(copy.deepcopy(samples[-1])), + lambda samples: samples[-1].update(iteration=99), + lambda samples: samples[-1].update(iteration=True), + lambda samples: samples[-1].pop('iteration')]: + samples = self.samples() + mutate(samples) + with self.assertRaises(ValueError): + compare(samples) + + def test_partial_duplicate_or_zero_time_is_rejected(self): + for mutate in [lambda r: r["rows"].pop(), + lambda r: r["rows"].append(copy.deepcopy(r["rows"][0])), + lambda r: r["rows"][0].update(elapsedUs=0), + lambda r: r["rows"][0].update(segmentCount=0), + lambda r: r["rows"][0].update(segmentCount=True), + lambda r: r["rows"][0].update(documentsMatched=0)]: + report = fixture() + mutate(report) + with self.assertRaises(ValueError): + validate(report) + + def test_input_mode_or_fingerprint_changes_are_rejected(self): + for mutate in [lambda r: r.update(buildMode="release"), + lambda r: r.update(manifest={"txt": "changed"}), + lambda r: r.update(loadedEngineSha256="e" * 64), + lambda r: r.update(pdfiumSha256="e" * 64), + lambda r: r["rows"][0].update(hitContentSha256="b" * 64), + lambda r: r["rows"][0].update(textFingerprintSha256="b" * 64)]: + samples = self.samples() + mutate(samples[-1]["report"]) + with self.assertRaises(ValueError): + compare(samples) + + def test_too_few_repetitions_are_rejected(self): + with self.assertRaises(ValueError): + compare(self.samples()[:-2]) + + def test_unverifiable_or_misassigned_book_contents_are_rejected(self): + for mutate in [lambda row: row["textFingerprints"].update(book0="0"), + lambda row: row["textFingerprints"].pop("book0"), + lambda row: row["hitsPerBook"].pop("book0"), + lambda row: row["hitsPerBook"].update(book0=0), + lambda row: row["textFingerprints"].update(book0="999")]: + report = fixture() + mutate(report["rows"][0]) + with self.assertRaises(ValueError): + validate(report) + + def test_changed_text_is_rejected_even_with_self_consistent_digest(self): + samples = self.samples() + row = samples[-1]["report"]["rows"][0] + row["textFingerprints"]["book0"] = "999" + row["textFingerprintSha256"] = hashlib.sha256(json.dumps( + sorted(row["textFingerprints"].items()), separators=(",", ":")).encode()).hexdigest() + with self.assertRaises(ValueError): + compare(samples) + + +if __name__ == "__main__": + unittest.main() diff --git a/tool/perf_probe/verify_indexing_recovery_regression.py b/tool/perf_probe/verify_indexing_recovery_regression.py new file mode 100644 index 0000000000..d19dee6159 --- /dev/null +++ b/tool/perf_probe/verify_indexing_recovery_regression.py @@ -0,0 +1,53 @@ +"""Require the recovery regression to fail on the base and pass on the candidate.""" + +import argparse +import os +from pathlib import Path +import re +import shutil +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if not re.fullmatch(r"[a-f0-9]{40}", args.baseline): + parser.error("An immutable baseline SHA is required") + flutter = shutil.which("flutter.bat" if os.name == "nt" else "flutter") + if not flutter: + parser.error("Flutter SDK not found") + source = Path("lib/indexing/utils/indexing_crash_canary.dart") + test = Path("test/indexing/utils/indexing_crash_canary_test.dart") + name = re.search(r"test\('([^']+)'", test.read_text(encoding="utf-8")).group(1) + cases = [ + ('recovery', test, name, ('Expected: false', 'Actual: ')), + ('healthy-batching', Path('test/indexing/repository/library_batch_indexing_test.dart'), + 'ספר בריא בטיסה אינו מצמצם אצוות של ספרי הספרייה', + ('Expected: a value greater than <1>', 'Actual: <1>')), + ] + baseline = subprocess.check_output(["git", "show", f"{args.baseline}:{source.as_posix()}"]) + candidate = source.read_bytes() + args.output.mkdir(parents=True, exist_ok=True) + try: + for label, content in (("baseline", baseline), ("candidate", candidate)): + source.write_bytes(content) + for case, target, title, failure in cases: + result = subprocess.run( + [flutter, "test", "--no-pub", str(target), "--plain-name", title], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, encoding="utf-8", errors="replace", check=False, + ) + (args.output / f"{case}-{label}.log").write_text(result.stdout, encoding="utf-8") + if label == "baseline": + if result.returncode != 1 or not all(text in result.stdout for text in failure): + raise RuntimeError(f"Baseline did not fail at the intended {case} assertion") + elif result.returncode: + raise RuntimeError(f"Candidate failed the {case} regression") + finally: + source.write_bytes(candidate) + + +if __name__ == "__main__": + main()