Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/scripts/ci-safety.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
73 changes: 73 additions & 0 deletions .github/workflows/perf_probe.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
Binary file added docs/screenshots/issue6187/after-compact-dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/screenshots/issue6187/after-desktop-dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/screenshots/issue6187/retry-desktop-dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
79 changes: 79 additions & 0 deletions integration_test/indexing_native_probe_test.dart
Original file line number Diff line number Diff line change
@@ -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<Map<String, dynamic>>();
expect(rows, hasLength(8));
final cases = <String>{};
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<String, String>();
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)));
}
14 changes: 9 additions & 5 deletions integration_test/support/installed_plugin_pdf_fixture.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <String>[
'<< /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 '
Expand Down
44 changes: 44 additions & 0 deletions lib/indexing/bloc/indexing_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:otzaria/indexing/models/pdf_indexing_progress.dart';

import 'dart:async';

import 'package:bloc_concurrency/bloc_concurrency.dart';
Expand Down Expand Up @@ -29,6 +31,9 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
int? _activeWorkId;
bool _isPaused = false;
bool _isFinalizing = false;
int? _pdfPagesProcessed;
int? _pdfTotalPages;
PdfIndexingPhase _pdfPhase = PdfIndexingPhase.extraction;

// ביטול מנקז את ריצות האינדוקס שכבר בתור: הן נשלחו לפני שהמשתמש עצר.
final _enqueuedAtCancelCount = Expando<int>();
Expand Down Expand Up @@ -66,6 +71,7 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
on<ActualIndexingStarted>(_onActualIndexingStarted);
on<IndexingFinalizing>(_onFinalizing);
on<UpdateIndexingProgress>(_onUpdateProgress);
on<UpdatePdfIndexingProgress>(_onPdfProgress);
}

/// Factory constructor that creates an IndexingBloc with a default repository
Expand Down Expand Up @@ -98,6 +104,9 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
isPaused: _isPaused,
isEconomy: _repository.isEconomyIndexing,
isFinalizing: _isFinalizing,
pdfPagesProcessed: _pdfPagesProcessed,
pdfTotalPages: _pdfTotalPages,
pdfPhase: _pdfPhase,
);

Future<void> _onIndexingWork(
Expand Down Expand Up @@ -268,6 +277,9 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
Emitter<IndexingState> emit,
) async {
final workId = ++_nextWorkId;
_pdfPagesProcessed = null;
_pdfTotalPages = null;
_pdfPhase = PdfIndexingPhase.extraction;
final runClock = Stopwatch()..start();
_activeWorkId = workId;

Expand Down Expand Up @@ -300,6 +312,11 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
},
onActualIndexingStarted: () => add(ActualIndexingStarted(workId)),
onProgress: _progressOf(workId),
onPdfProgress: (progress) {
if (!isClosed && _activeWorkId == workId) {
add(UpdatePdfIndexingProgress(workId, progress));
}
},
onFinalizing: () => add(IndexingFinalizing(workId)),
),
);
Expand Down Expand Up @@ -370,6 +387,9 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
final currentState = state;
if (currentState is! IndexingInProgress) return;
_isFinalizing = true;
_pdfPagesProcessed = null;
_pdfTotalPages = null;
_pdfPhase = PdfIndexingPhase.extraction;
emit(
_inProgress(
booksProcessed: currentState.booksProcessed,
Expand Down Expand Up @@ -459,6 +479,9 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {

void _cancelWork() {
_activeWorkId = null;
_pdfPagesProcessed = null;
_pdfTotalPages = null;
_pdfPhase = PdfIndexingPhase.extraction;
_isPaused = false;
_cancelCount++;
_repository.cancelIndexing();
Expand Down Expand Up @@ -540,4 +563,25 @@ class IndexingBloc extends Bloc<IndexingEvent, IndexingState> {
);
}
}

void _onPdfProgress(
UpdatePdfIndexingProgress event,
Emitter<IndexingState> 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);
}
}
11 changes: 11 additions & 0 deletions lib/indexing/bloc/indexing_event.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<Object?> get props => [workId, progress];
}
Loading
Loading