Skip to content
Closed
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
251 changes: 251 additions & 0 deletions .github/workflows/indexing-ui-profile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
name: Indexing UI profile comparison

on:
pull_request:
paths:
- '.github/workflows/indexing-ui-profile.yml'

permissions:
contents: read

concurrency:
group: indexing-ui-profile-${{ github.event.pull_request.number }}
cancel-in-progress: true

jobs:
paired-profile:
name: Baseline and candidate on one Windows runner
runs-on: windows-2025
timeout-minutes: 100
defaults:
run:
shell: pwsh
env:
BASELINE_SHA: b9a29933a7e1adaca3976370d4a5f8f0b5be3853
CANDIDATE_SHA: 02a82c14a0d7e88421995f19589f395083fa1424
PAIR_HARDWARE_ID: github-hosted-${{ github.run_id }}-${{ github.run_attempt }}
steps:
- name: Validate the fixed source revisions
run: |
foreach ($revision in @($env:BASELINE_SHA, $env:CANDIDATE_SHA)) {
if ($revision -notmatch '^[0-9a-f]{40}$') {
throw 'Both source revisions must be full commit SHAs.'
}
}
git config --global core.longpaths true
if ($LASTEXITCODE -ne 0) {
throw 'Could not enable Git long paths.'
}
git config --global core.autocrlf false
if ($LASTEXITCODE -ne 0) {
throw 'Could not preserve LF source checkouts.'
}
$pairRoot = Join-Path $env:RUNNER_TEMP 'indexing-ui-profile'
"PAIR_ROOT=$pairRoot" | Add-Content -LiteralPath $env:GITHUB_ENV
New-Item -ItemType Directory -Path $pairRoot | Out-Null

- name: Check out the baseline
uses: actions/checkout@v7.0.1
with:
repository: Otzaria/otzaria
ref: ${{ env.BASELINE_SHA }}
path: baseline
persist-credentials: false

- name: Check out the candidate
uses: actions/checkout@v7.0.1
with:
repository: Otzaria/otzaria
ref: ${{ env.CANDIDATE_SHA }}
path: candidate
persist-credentials: false

- name: Set up Flutter
uses: subosito/flutter-action@v2
with:
channel: stable
flutter-version: 3.47.7
cache: true

- name: Install Rust for native source builds
uses: dtolnay/rust-toolchain@stable

- name: Validate fixture controls before measuring
timeout-minutes: 25
working-directory: candidate
run: |
$validationRoot = Join-Path $env:PAIR_ROOT 'validation'
New-Item -ItemType Directory -Path $validationRoot | Out-Null
& flutter pub get --enforce-lockfile
if ($LASTEXITCODE -ne 0) { throw 'Pinned dependency resolution failed.' }
& dart format --output=none --set-exit-if-changed integration_test/perf_resource_probe_test.dart integration_test/support/perf_fixture.dart integration_test/support/perf_reader_scroll.dart test/tool/perf_probe/perf_fixture_test.dart test/tool/perf_probe/perf_reader_scroll_test.dart
if ($LASTEXITCODE -ne 0) { throw 'Probe formatting is not canonical.' }
& flutter analyze --no-pub 2>&1 | Tee-Object -FilePath (Join-Path $validationRoot 'analyze.log')
if ($LASTEXITCODE -ne 0) { throw 'Probe candidate analysis failed.' }

$fixturePath = Join-Path $PWD 'integration_test/support/perf_fixture.dart'
$original = [IO.File]::ReadAllText($fixturePath)
$originalHash = (Get-FileHash -LiteralPath $fixturePath -Algorithm SHA256).Hash
$marker = "(?m)^[ \t]*'settings_initialized': true,\r?\n"
if ([regex]::Matches($original, $marker).Count -ne 1) {
throw 'Expected exactly one fixture initialization marker.'
}
$negativeLog = Join-Path $validationRoot 'fixture-negative.jsonl'
try {
[IO.File]::WriteAllText($fixturePath, [regex]::Replace($original, $marker, ''), [Text.UTF8Encoding]::new($false))
& flutter test --no-pub --reporter json --plain-name 'application settings loading preserves the prepared fixture' test/tool/perf_probe/perf_fixture_test.dart 2>&1 | Tee-Object -FilePath $negativeLog
$negativeExitCode = $LASTEXITCODE
} finally {
[IO.File]::WriteAllText($fixturePath, $original, [Text.UTF8Encoding]::new($false))
}
if ((Get-FileHash -LiteralPath $fixturePath -Algorithm SHA256).Hash -ne $originalHash) {
throw 'The original fixture bytes were not restored.'
}
$events = @(
foreach ($line in [IO.File]::ReadLines($negativeLog)) {
if (-not $line.TrimStart().StartsWith('{')) { continue }
try { $line | ConvertFrom-Json -ErrorAction Stop } catch { continue }
}
)
$errors = @($events | Where-Object { $_.type -eq 'error' })
$expected = @($errors | Where-Object {
$_.error -like '*Prepared fixture font was overwritten by first-run defaults.*' -and
$_.error -like '*NotoSerifHebrew*' -and $_.error -like '*FrankRuhlCLM*'
})
$done = @($events | Where-Object { $_.type -eq 'done' -and $_.success -eq $false })
if ($negativeExitCode -eq 0 -or $errors.Count -ne 1 -or $expected.Count -ne 1 -or $done.Count -ne 1) {
throw 'The negative control did not complete with the expected font assertion.'
}
& flutter test --no-pub --reporter expanded test/tool/perf_probe/perf_fixture_test.dart test/tool/perf_probe/perf_reader_scroll_test.dart 2>&1 | Tee-Object -FilePath (Join-Path $validationRoot 'fixture-positive.log')
if ($LASTEXITCODE -ne 0) { throw 'Corrected probe controls failed.' }
$sourceStatus = (& git status --porcelain=v1 --untracked-files=all | Out-String)
if ($LASTEXITCODE -ne 0 -or -not [string]::IsNullOrWhiteSpace($sourceStatus)) {
throw "Validation left an unverified source tree: $sourceStatus"
}

- name: Measure the baseline
timeout-minutes: 35
working-directory: baseline
run: |
./tool/perf_probe/run_perf_probe.ps1 -Mode profile -CacheState cold `
-Warmup 1 -Repetitions 3 -Launches 2 -TimeoutSeconds 300 `
-HardwareId $env:PAIR_HARDWARE_ID `
-OutputDirectory (Join-Path $env:PAIR_ROOT 'baseline')
exit $LASTEXITCODE

- name: Record baseline binaries and free completed build artifacts
run: |
$sourceRoot = Join-Path $env:PAIR_ROOT 'source'
New-Item -ItemType Directory -Path $sourceRoot -Force | Out-Null
$buildRoot = Join-Path $env:GITHUB_WORKSPACE 'baseline/build/windows/x64/runner/Profile'
$binaries = @(Get-ChildItem -LiteralPath $buildRoot -Recurse -File | Where-Object {
$_.Name -match 'search_engine.*\.dll$|^app\.so$|^otzaria\.exe$|^native_assets\.json$'
} | ForEach-Object {
[ordered]@{ path = [IO.Path]::GetRelativePath($buildRoot, $_.FullName); bytes = $_.Length; sha256 = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() }
})
ConvertTo-Json -InputObject $binaries -Depth 5 | Set-Content -LiteralPath (Join-Path $sourceRoot 'baseline-binaries.json')
foreach ($relative in @('baseline/build', 'baseline/.dart_tool/hooks_runner/shared')) {
$ownedPath = Join-Path $env:GITHUB_WORKSPACE $relative
if (Test-Path -LiteralPath $ownedPath) {
Remove-Item -LiteralPath $ownedPath -Recurse -Force
}
}

- name: Measure and compare the candidate
timeout-minutes: 35
working-directory: candidate
run: |
./tool/perf_probe/run_perf_probe.ps1 -Mode profile -CacheState cold `
-Warmup 1 -Repetitions 3 -Launches 2 -TimeoutSeconds 300 `
-HardwareId $env:PAIR_HARDWARE_ID `
-OutputDirectory (Join-Path $env:PAIR_ROOT 'candidate') `
-Baseline (Join-Path $env:PAIR_ROOT 'baseline')
exit $LASTEXITCODE

- name: Preserve source and native identity evidence
if: always()
run: |
$sourceRoot = Join-Path $env:PAIR_ROOT 'source'
New-Item -ItemType Directory -Path $sourceRoot -Force | Out-Null
foreach ($side in @('baseline', 'candidate')) {
$checkoutPath = Join-Path $env:GITHUB_WORKSPACE $side
if (-not (Test-Path -LiteralPath (Join-Path $checkoutPath '.git'))) { continue }
& git -C $checkoutPath rev-parse HEAD | Set-Content -LiteralPath (Join-Path $sourceRoot "$side-head.txt")
$sourceStatus = (& git -C $checkoutPath status --porcelain=v1 --untracked-files=all | Out-String)
Set-Content -LiteralPath (Join-Path $sourceRoot "$side-status.txt") -Value $sourceStatus
& git -C $checkoutPath diff --no-ext-diff | Set-Content -LiteralPath (Join-Path $sourceRoot "$side-diff.patch")
& git -C $checkoutPath config --show-origin --get-regexp 'core\.(autocrlf|eol|filemode)' | Set-Content -LiteralPath (Join-Path $sourceRoot "$side-git-config.txt")
$buildRoot = Join-Path $checkoutPath 'build/windows/x64/runner/Profile'
if (Test-Path -LiteralPath $buildRoot) {
$binaries = @(Get-ChildItem -LiteralPath $buildRoot -Recurse -File | Where-Object {
$_.Name -match 'search_engine.*\.dll$|^app\.so$|^otzaria\.exe$|^native_assets\.json$'
} | ForEach-Object {
[ordered]@{ path = [IO.Path]::GetRelativePath($buildRoot, $_.FullName); bytes = $_.Length; sha256 = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() }
})
ConvertTo-Json -InputObject $binaries -Depth 5 | Set-Content -LiteralPath (Join-Path $sourceRoot "$side-binaries.json")
}
}
exit 0

- name: Summarize measurement coverage
if: always()
run: |
$comparisonFailure = $false
$summary = @(
'## Indexing UI profile observations',
'',
'Each side requests 2 launches with 3 measured repetitions and 1 warmup per launch.',
'A completed search without confirmed indexing overlap remains skipped.',
'',
'| Side | Search status | Measured | Skipped | Frames | Truncated iterations |',
'|---|---|---:|---:|---:|---:|'
)
foreach ($side in @('baseline', 'candidate')) {
$reportPath = Join-Path $env:PAIR_ROOT "$side/report.json"
if (-not (Test-Path -LiteralPath $reportPath)) {
$summary += "| $side | report unavailable | — | — | — | — |"
Write-Warning "$side report is unavailable; inspect the partial logs."
continue
}
$report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json
$search = $report.scenarios | Where-Object { $_.name -eq 'search.while_indexing' } | Select-Object -First 1
if ($null -eq $search) {
$summary += "| $side | search scenario unavailable | — | — | — | — |"
Write-Warning "$side has no search.while_indexing observation."
continue
}
$summary += "| $side | $($search.status) | $($search.measured) | $($search.skipped) | $($search.frames.count) | $($search.frames.truncatedIterations) |"
if ($search.measured -lt 6 -or $search.frames.count -eq 0 -or $search.frames.truncatedIterations -gt 0) {
Write-Warning "$side has incomplete search/frame coverage; no observations are fabricated or retried."
}
if ($side -eq 'candidate' -and $null -ne $report.comparison) {
$comparison = $report.comparison
if (-not $comparison.comparable) { $comparisonFailure = $true }
$row = $comparison.scenarios | Where-Object { $_.name -eq 'search.while_indexing' } | Select-Object -First 1
$summary += "`nReport comparison eligible: $($comparison.comparable). Search comparison: $($row.status)."
if ($comparison.reasons.Count -gt 0) {
$summary += "Reasons: $($comparison.reasons -join '; ')."
}
}
}
$summary += @(
'',
'Skipped reasons and raw frame observations are retained in phases.jsonl.',
'The existing analyzer omits frame percentiles when collection is truncated.',
'No timing thresholds are applied. With at most 6 latency samples, p95/p99 are not stable tail estimates.',
'This scenario does not measure scrolling during indexing, internal queue bytes, or engine/DB worker counts.',
'Cold means fresh application data; operating-system caches are not cleared.'
)
$summary -join "`n" | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY
if ($comparisonFailure) { throw 'The completed reports do not qualify for comparison.' }

- name: Upload reports and partial observations
if: always()
uses: actions/upload-artifact@v7.0.2
with:
name: indexing-ui-profile-${{ github.run_id }}-${{ github.run_attempt }}
retention-days: 14
if-no-files-found: warn
path: |
${{ runner.temp }}/indexing-ui-profile/**
!${{ runner.temp }}/indexing-ui-profile/*/data/**
26 changes: 8 additions & 18 deletions integration_test/perf_resource_probe_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import 'package:otzaria/work_status/work_status_item.dart';
import 'package:path/path.dart' as p;

import 'support/perf_fixture.dart';
import 'support/perf_reader_scroll.dart';
import 'support/perf_recorder.dart';

void main() {
Expand Down Expand Up @@ -375,6 +376,7 @@ class _Scenario {
.where((item) => item.kind == WorkStatusKind.running)
.length,
'indexingActive': TantivyDataProvider.instance.isIndexing.value ? 1 : 0,
'economyIndexing': TantivyDataProvider.instance.isEconomyIndexing,
'schedulerCallbacks': tester.binding.transientCallbackCount,
'flutterViews': PlatformDispatcher.instance.views.length,
'queueDepth': null,
Expand Down Expand Up @@ -404,24 +406,9 @@ class _Scenario {
});
final tab = tabs.state.currentTab as TextBookTab;
await phase('book.$kind.scroll', () async {
final scrollable = find.descendant(
of: find.byType(App),
matching: find.byType(Scrollable),
final position = perfReaderScrollPosition(
tab.lines.itemController.scrollController,
);
final candidates = tester
.stateList<ScrollableState>(scrollable)
.where(
(state) =>
state.position.axis == Axis.vertical &&
state.position.maxScrollExtent > 500,
)
.toList();
if (candidates.length != 1) {
throw StateError(
'Expected exactly one vertical reader scrollable, found ${candidates.length}.',
);
}
final position = candidates.single.position;
for (var step = 0; step < 60; step++) {
position.jumpTo(
(position.pixels + 30).clamp(
Expand Down Expand Up @@ -663,7 +650,10 @@ class _Scenario {
await phase('notes.caret', () async {
for (var i = 0; i < 12; i++) {
final before = controller.selection;
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(
LogicalKeyboardKey.arrowRight,
physicalKey: PhysicalKeyboardKey.arrowRight,
);
await tester.pump();
if (controller.selection == before) {
throw StateError('The caret did not move.');
Expand Down
3 changes: 2 additions & 1 deletion integration_test/support/perf_fixture.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import 'package:sqlite3/sqlite3.dart';

import '../../test/helpers/seforim_fixture_db.dart';

const perfFixtureVersion = 'synthetic-v1';
const perfFixtureVersion = 'synthetic-v2';
const perfBooks = <String, int>{
'מדידה קצרה': 128,
'מדידה בינונית': 4096,
Expand Down Expand Up @@ -164,6 +164,7 @@ class PerfFixture {
);
try {
await settings.putAll({
'settings_initialized': true,
SettingsRepository.keyLibraryPath: libraryPath,
SettingsRepository.keyLibraryFolderName: '',
SettingsRepository.keyIndexPath: p.join(root.path, 'index'),
Expand Down
18 changes: 18 additions & 0 deletions integration_test/support/perf_reader_scroll.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'package:flutter/widgets.dart';

ScrollPosition perfReaderScrollPosition(ScrollController? controller) {
if (controller == null || controller.positions.length != 1) {
throw StateError(
'The current reader must have one attached scroll position.',
);
}
final position = controller.position;
if (position.axis != Axis.vertical ||
!position.hasContentDimensions ||
position.maxScrollExtent <= 500) {
throw StateError(
'The current reader must be ready for vertical scrolling.',
);
}
return position;
}
3 changes: 2 additions & 1 deletion lib/data/data_providers/db_read_worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,8 @@ class DbReadWorker {
_receivePort.close();
_errorPort.close();
_exitPort.close();
_isolate?.kill(priority: Isolate.immediate);
// ניתוק ה-finalizer של SQLite חייב להסתיים לפני עצירת ה-isolate.
_isolate?.kill(priority: Isolate.beforeNextEvent);
if (identical(_slot.instance, this)) _slot.instance = null;
}
}
Expand Down
3 changes: 2 additions & 1 deletion lib/find_ref/repository/attached_find_ref_worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ class AttachedFindRefWorker {
if (isolate == null) return _closing;
final exited = ReceivePort();
isolate.addOnExitListener(exited.sendPort);
isolate.kill(priority: Isolate.immediate);
// SQLite משחרר handle לפני ניתוק ה-finalizer; מאפשרים לאירוע להסתיים.
isolate.kill(priority: Isolate.beforeNextEvent);
final previousClosing = _closing;
return _closing = Future.wait([
previousClosing,
Expand Down
6 changes: 3 additions & 3 deletions lib/find_ref/repository/find_ref_db_isolate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -539,8 +539,7 @@ class FindRefDbIsolate {
);
return false;
} catch (e) {
// kill של isolate אינו מריץ finalizers, ולכן ה-handle הנייטיבי עשוי
// לשרוד את נפילת ה-worker עד סוף התהליך.
// ללא אישור מה-worker אין ודאות שה-handle כבר שוחרר.
debugPrint(
'[FindRef isolate] suspend failed ($e) — DB handle may still be open',
);
Expand Down Expand Up @@ -699,7 +698,8 @@ class FindRefDbIsolate {
_receivePort.close();
_errorPort.close();
_exitPort.close();
_isolate?.kill(priority: Isolate.immediate);
// ניתוק ה-finalizer של SQLite חייב להסתיים לפני עצירת ה-isolate.
_isolate?.kill(priority: Isolate.beforeNextEvent);
if (identical(_instance, this)) _instance = null;
}

Expand Down
Loading
Loading