Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5 ee4f076b68 feat(app): Tools > Database maintenance -- integrity check, backup, the retention sweep on demand, compaction (P4 PR-7)
The sweep is the Agent's, because frame_blobs and sensor_blobs are: the App sends the new
SweepRetention command (no payload) and the Agent's RetentionSweep reads its own
retention.raw_sessions_per_game and runs ISessionRepository.SweepRetentionAllAsync -- the finalize's
per-game rule for every game in one transaction, a removed game's kept sessions included. Unlimited
never reaches the repository, which refuses a keep below 1.

The App's LedgerMaintenance changes no row: PRAGMA integrity_check; a VACUUM INTO backup that refuses
the ledger, its WAL and its shm file as the destination (the save dialog's "replace?" would otherwise
have deleted the live database); and VACUUM + wal_checkpoint(TRUNCATE), refused while a fresh
GetStatus reports a session. LedgerDatabase.MaintainAsync runs these outside a transaction.

A ContentDialog with four cards and a status line; the sweep confirms with a Danger button. The last
NotYetCommand and its strings are gone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 00:49:18 +07:00
36 changed files with 1588 additions and 38 deletions

No files matched your search

+22
View File
@@ -21,6 +21,28 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
### Added
- **P4 PR-7 — Tools ▸ Database maintenance: integrity check, backup, the retention sweep on demand, compaction
(2026-09-15).** `06_DATA_MODEL` §Retention promised the four since P0; the menu item said "not built yet". **The
sweep is the Agent's**, because `frame_blobs` and `sensor_blobs` are (§Writer ownership): the App sends the new
`SweepRetention` command (no payload; `07_IPC` row), and the Agent's `RetentionSweep` reads its own
`retention.raw_sessions_per_game` and runs `ISessionRepository.SweepRetentionAllAsync` — the finalize's per-game
rule for every game in one transaction (`ROW_NUMBER() OVER (PARTITION BY game_id …)`, a removed game's kept sessions
included), answering `SweepRetentionAck { keep, games, sessions }`; unlimited (0) never reaches the repository, which
refuses a keep below 1. The other three run in the App through `LedgerMaintenance` and change no row:
`PRAGMA integrity_check`; a backup through `VACUUM INTO`, which is consistent while the Agent writes and **refuses
the ledger, its WAL and its shared-memory file as a destination** — the save dialog's "replace?" would otherwise have
let "delete the existing file first" delete the live database; and compaction (`VACUUM` + `wal_checkpoint(TRUNCATE)`)
refused while a fresh `GetStatus` reports a session, with SQLite's busy error a status line rather than a crash.
`LedgerDatabase.MaintainAsync` runs a statement outside a transaction, for these only. The dialog
(`DatabaseMaintenanceContent` / `DatabaseMaintenanceViewModel`, `DatabaseMaintenancePrompts`) confirms the sweep with a
Danger button and shows one status line; the menu's last `NotYetCommand` and the `NotYet_*` strings are gone.
Strings en/vi/ja. Tests: `LedgerMaintenanceTests` (healthy, a backup that opens at the same schema with the same rows,
never over a file or onto the ledger in any spelling, compaction that returns the space of ten swept series),
`SqliteSessionRepositoryTests` (every game keeps its own newest N, a sensors-only session counted once, a second
sweep finds nothing, a keep of 0 refused), `RetentionSweepTests`, `AgentCommandHandlerTests` (the composed sweep
answers; none composed is not a command), `DatabaseMaintenanceViewModelTests` (twelve cases, the ledger-as-backup
refusal among them), `PagesLoadTests` (the dialog loads under the real dictionaries). Docs: `07_IPC`,
`06_DATA_MODEL` §Retention and §Writer ownership, `08_UI`, `15_ROADMAP`, HANDOFF §P4.
- **P4 PR-6 — every NuGet package the App and the Agent ship has its licence text, and the gate keeps it true
(2026-09-15).** `tools/license-gather.ps1` reads the two publish roots' restore output (`obj/project.assets.json`,
win-x64, every package with a runtime or native asset that is not a suppressed build-time dependency) and writes
+13 -1
View File
@@ -2,7 +2,7 @@
`%LOCALAPPDATA%\FrameLedger\ledger.db`. Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=5000`. `Microsoft.Data.Sqlite` + Dapper; all writes in explicit transactions.
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms` — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms` — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
## Schema (v2 — hook architecture)
@@ -385,6 +385,18 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
Default: raw blobs for the **last 20 sessions per game** (configurable N or unlimited — `retention.raw_sessions_per_game`, 0 = unlimited, §Settings registry). Aggregates and segments kept forever. Sweep at finalize + on demand (Tools → DB maintenance, which also offers `PRAGMA integrity_check`, `VACUUM`, backup).
> **Built 2026-09-15 (P4 PR-7).** The on-demand sweep is the **Agent's**: the App sends `SweepRetention` (`07_IPC`),
> and the Agent runs `ISessionRepository.SweepRetentionAllAsync` — the finalize's per-game rule for every game in one
> transaction, `ROW_NUMBER() OVER (PARTITION BY game_id ORDER BY started_at DESC, id DESC)`, so the two can never
> disagree about which session is the Nth, and a removed game's kept sessions are swept like any other. A keep of 0
> never reaches it: unlimited is honoured by not sweeping. The other three run in the App through
> `Infrastructure.Persistence.LedgerMaintenance` and change no row: `PRAGMA integrity_check`; a backup through
> `VACUUM INTO` (a complete, consistent copy while the Agent keeps writing; never over an existing file and never onto
> the ledger, its WAL or its shared-memory file — the save dialog's "replace?" would otherwise have deleted the live
> database); and compaction, `VACUUM` + `wal_checkpoint(TRUNCATE)`, refused while a fresh `GetStatus` reports a
> session. `LedgerDatabase.MaintainAsync` is the one way to run a statement outside a transaction, and it is for
> these statements only.
## Migrations
Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied at startup by whichever process opens the DB first, guarded by `schema_migrations` + a named mutex. Never edit an applied script; only append.
+1
View File
@@ -315,6 +315,7 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
| `StopSession` | UI→A | `{ sessionGuid }` — graceful ~~unhook~~ stop + finalize → `StopAck { sessionGuid, accepted, reason? }`. *(Built 2026-09-13, PR-1b: the orchestrator names every session it starts and cancels THAT session's stop token; the loop reads it at its next tick, drains once more, and ends as `SessionEndReason.StoppedByUser` — `exit_status = normal`, the row stored like any other, the target left running. A guid nobody runs is `accepted: false`. Distinct from the host's cancellation, which leaves a `.partial`.)* |
| `UpdateRules` | UI→A | **no payload** — a trigger, not a source. The Agent re-reads only its own `%LOCALAPPDATA%\FrameLedger\rules\` copy → `UpdateRulesAck { outcome }`. *(Built 2026-09-13, PR-1b: the seeder's `EnsureSeededAsync` outcome; a payload naming a path is ignored, and a test sends one to prove it.)* |
| `Shutdown` | UI→A | graceful stop → `ShutdownAck`, then the host stops (sessions finalize inside its grace window). *(Built 2026-09-13, PR-1b: `IAgentLifetime`, the host's under `--serve`, a logged no-op under `--console`.)* |
| `SweepRetention` | UI→A | **no payload** — a trigger, like `UpdateRules`: the Agent applies `06_DATA_MODEL` §Retention to every game with the `retention.raw_sessions_per_game` it reads itself → `SweepRetentionAck { keep, games, sessions }` (`keep` 0 = unlimited, and then nothing was swept). *(Built 2026-09-15, P4 PR-7, for Tools ▸ Database maintenance: `Application.Recording.RetentionSweep` over `ISessionRepository.SweepRetentionAllAsync`, composed into `AgentCommandHandler` under `--serve`. The client names no number because the rows are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the dialog reads as "restart the Agent". Carries no safety fact.)* |
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt }` — **published at the attach**, i.e. when the session becomes Tier 1 and the live card has something to show; a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2) and, when a refusal or error caused that, the event below that names it |
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, vramProcMb?, latencyUs?, fgRefusal?, fgRuntimeCensus? }` — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **Two fields added 2026-09-14, both optional (an older client ignores them, §C):** `fgRefusal` is the row's `fg_refusal` (schema 0003) — present when `fgMode` names a technology and `fgFactor` is absent, so the live card can say "DLSS-G active — factor not counted" rather than N/A; `fgRuntimeCensus` is the raw census so the `fg_runtime_loaded` chip can name the module. **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason` |
+6 -1
View File
@@ -40,7 +40,12 @@ The Menu sits in its own row **below** the TitleBar (never inside the drag regio
> off and shows the Games page; `05_DETECTION` §Platform signatures built note). **Help ▸ Check for updates is PR-5's** (`Update/UpdateService.CheckInteractivelyAsync`, the
> dialogs of `11_UPDATER` §Flow; a downloaded update is the shell's persistent InfoBar with the one button,
> disabled while a session runs — FR-12 — and "update available" is a tray balloon only while the window is off
> screen). Still "later build": Tools ▸ Database maintenance.
> screen). ~~Still "later build": Tools ▸ Database maintenance.~~ **Tools ▸ Database maintenance… is PR-7's (2026-09-15)**:
> a `ContentDialog` (`Dialogs/DatabaseMaintenanceContent`, `ViewModels/DatabaseMaintenanceViewModel`) with four cards —
> Check integrity, Back up…, Sweep raw data…, Compact — and one status line; the sweep confirms in a `MessageBox` with a
> Danger button (§UX rules) and is sent to the Agent, compaction is refused while a session runs, and a backup is never
> written onto the ledger itself (`06_DATA_MODEL` §Retention built note). No menu item says "not built yet" any more:
> `NotYetCommand` and its two strings are gone.
>
> **Built 2026-09-13 (P3 PR-2): the shell, and only the shell.** `FluentWindow`, the TitleBar with the
> Agent pill as trailing content, the Menu row (every item that a later slice builds says so in a 4 s
+1 -1
View File
@@ -317,7 +317,7 @@ Agent: watcher, tier selection, injection orchestration, shm drain, telemetry po
WPF UI shell (`16_WPFUI_SYNTAX`), library, per-game hooking consent flow, Dashboard live card showing *measured* settings, session summary, ScottPlot charts, game detail tabs, Compare with tier guarding, segment ribbon, tri-state chips with override, refusal/degradation/unhook notices as first-class UI. **Plus, moved here from P4 on 2026-09-13 (owner):** the command pipe (`07_IPC` §C — P2's decision D10 put it here), i18n en/vi/ja with `tools/resx-audit` (the consent dialog is the first thing that needs a reviewed `.resx`, so it cannot wait), the Legal Gate (FR-11), Settings (FR-10, the kill switch first), the Logs page, tray + toasts. The owner chose the whole of `08_UI` over a shell-first cut; HANDOFF §P3 carries the slice order and the decisions (D11–D17). *Not started as of 2026-09-13: `FrameLedger.App` is the scaffold, `FrameLedger.Shared` has no IPC type, and no `.resx` exists in the tree.*
## P4 — Detection & product polish (1 week)
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; ~~store auto-import~~ **landed 2026-09-14 (P4 PR-4)**; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ ~~Velopack + updater (with the hooked-session deferral)~~ **landed 2026-09-14 (P4 PR-5 — the deferral is `UpdateService`'s shape, not a flag)**; bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ DB maintenance; accessibility pass; ~~the scheduled task (`--install-task`)~~ (P3 PR-8b) and ~~the Velopack install hooks~~ **(PR-5: the uninstall hook; install registers nothing, by design — `12_BUILD` §The Vulkan layer is not registered at install time)**. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; ~~store auto-import~~ **landed 2026-09-14 (P4 PR-4)**; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ ~~Velopack + updater (with the hooked-session deferral)~~ **landed 2026-09-14 (P4 PR-5 — the deferral is `UpdateService`'s shape, not a flag)**; bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ ~~DB maintenance~~ **landed 2026-09-15 (P4 PR-7: the sweep is the Agent's over `SweepRetention`; integrity, backup and compaction in the App)**; accessibility pass; ~~the scheduled task (`--install-task`)~~ (P3 PR-8b) and ~~the Velopack install hooks~~ **(PR-5: the uninstall hook; install registers nothing, by design — `12_BUILD` §The Vulkan layer is not registered at install time)**. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
## P5 — Ship (3–4 days)
CI/CD with the native build (`release.yml` exists since P4 PR-5, 2026-09-14 — untested by a tag yet); CodeQL (C# + C++); Dependabot; CHANGELOG; README with the P0 accuracy comparison — **which is not a percentage, and this line used to send its author looking for one**. The decision is recorded under item 3 and in `spike-notes.md` §8: the baseline can answer **none** of item 4's four runtime questions, so the defensible claim is *"the baseline cannot answer four of these five questions at all"*, not *"N% more accurate"*. Overhead + tier cross-validation measurements; release smoke on clean VMs; `v0.1.0-beta.1`.
+5
View File
@@ -1244,6 +1244,11 @@ carries it**, the Help menu's
script~~ **LANDED 2026-09-15 (P4 PR-6: `tools/license-gather.ps1` → `legal/licenses/nuget/`, 77 packages, `license-check` §3 both directions; the runtime's notices by `release.yml`)**. Decisions that live only here: D11–D17 below still hold; nothing in P4 may add a third writer to
`ledger.db` or a message that carries a safety fact over the pipe.
`15_ROADMAP` §P4's last two items were not in the list above: ~~DB maintenance~~ **LANDED 2026-09-15 (P4 PR-7:
Tools ▸ Database maintenance — the retention sweep on demand is the Agent's, over a new `SweepRetention` command with
no payload; integrity check, `VACUUM INTO` backup and compaction run in the App and change no row — `06_DATA_MODEL`
§Retention built note)**, and the accessibility pass, which needs `08_UI` §Accessibility written before any code.
## P3 — ~~**START HERE**~~ (2026-09-13, owner-approved plan; **code-complete 2026-09-14** — every row below is struck with its PR)
`15_ROADMAP` §P3 is the UI — and since 2026-09-13 it is **all of `08_UI`**, Settings, Logs, the tray
@@ -168,7 +168,9 @@ internal static class AgentServices
// P3 PR-4 (D14): the reviewed disclosure this Agent stamps against, and its own clock for the stamp.
SafetyDisclosure.Version,
TimeProvider.System,
sp.GetRequiredService<VkLayerReconciler>()));
sp.GetRequiredService<VkLayerReconciler>(),
// P4 PR-7: the on-demand retention sweep, over the Agent's own settings read and its own blob tables.
ct => new RetentionSweep(sp.GetRequiredService<ISessionRepository>(), sp.GetRequiredService<RegisteredSettings>()).RunAsync(ct)));
services.AddSingleton<IIpcRequestHandler>(static sp => new AgentRequestHandler(
AgentIdentityFactory.OfThisProcess(sp.GetRequiredService<AgentPaths>().VkLayerDirectory),
TelemetryDescriptor(),
+3
View File
@@ -284,6 +284,9 @@ public partial class App : System.Windows.Application
AddUpdates(services);
// Tools ▸ Database maintenance (P4 PR-7): the dialog builds its view model over the ledger each time it opens.
services.AddSingleton<IDatabaseMaintenancePrompts, DatabaseMaintenancePrompts>();
// FR-11 (P3 PR-9): the gate over the UI's own table, the documents this build embeds, the window that shows them.
services.AddSingleton<ILegalAcceptanceStore, SqliteLegalAcceptanceStore>();
services.AddSingleton(static sp => new LegalGate(sp.GetRequiredService<ILegalAcceptanceStore>(), LegalDocuments.Load()));
@@ -0,0 +1,66 @@
<UserControl x:Class="FrameLedger.App.Dialogs.DatabaseMaintenanceContent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:res="clr-namespace:FrameLedger.App"
xmlns:vm="clr-namespace:FrameLedger.App.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{d:DesignInstance Type=vm:DatabaseMaintenanceViewModel}"
mc:Ignorable="d"
MinWidth="600">
<!--
Tools ▸ Database maintenance (P4 PR-7, 06_DATA_MODEL §Retention). Four actions, each one card and one button; the
outcome of the last one is the line at the bottom. Two only read (check, back up); compacting is refused while a
session runs; the sweep is the Agent's and asks first. Buttons are disabled while an action runs.
-->
<StackPanel>
<ui:TextBlock MaxWidth="700" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Maintenance_Intro}" TextWrapping="Wrap" />
<ui:CardControl Margin="0,12,0,0" Icon="{ui:SymbolIcon ShieldCheckmark24}">
<ui:CardControl.Header>
<StackPanel>
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Maintenance_Integrity_Label}" />
<ui:TextBlock MaxWidth="440" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Maintenance_Integrity_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:Button MinWidth="120" Command="{Binding CheckIntegrityCommand}" Content="{x:Static res:Strings.Maintenance_Integrity_Button}" />
</ui:CardControl>
<ui:CardControl Margin="0,4,0,0" Icon="{ui:SymbolIcon Save24}">
<ui:CardControl.Header>
<StackPanel>
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Maintenance_Backup_Label}" />
<ui:TextBlock MaxWidth="440" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Maintenance_Backup_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:Button MinWidth="120" Command="{Binding BackUpCommand}" Content="{x:Static res:Strings.Maintenance_Backup_Button}" />
</ui:CardControl>
<ui:CardControl Margin="0,4,0,0" Icon="{ui:SymbolIcon Broom24}">
<ui:CardControl.Header>
<StackPanel>
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Maintenance_Sweep_Label}" />
<ui:TextBlock MaxWidth="440" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Maintenance_Sweep_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:Button MinWidth="120" Command="{Binding SweepCommand}" Content="{x:Static res:Strings.Maintenance_Sweep_Button}" />
</ui:CardControl>
<ui:CardControl Margin="0,4,0,0" Icon="{ui:SymbolIcon ArrowMinimize24}">
<ui:CardControl.Header>
<StackPanel>
<ui:TextBlock FontTypography="BodyStrong" Text="{x:Static res:Strings.Maintenance_Compact_Label}" />
<ui:TextBlock MaxWidth="440" HorizontalAlignment="Left" Appearance="Secondary" Text="{x:Static res:Strings.Maintenance_Compact_Body}" TextWrapping="Wrap" />
</StackPanel>
</ui:CardControl.Header>
<ui:Button MinWidth="120" Command="{Binding CompactCommand}" Content="{x:Static res:Strings.Maintenance_Compact_Button}" />
</ui:CardControl>
<DockPanel Margin="0,12,0,0">
<ui:ProgressRing Width="16" Height="16" Margin="0,0,8,0" DockPanel.Dock="Left" IsIndeterminate="True"
Visibility="{Binding IsBusy, Converter={StaticResource BoolToVis}}" />
<ui:TextBlock MaxWidth="680" HorizontalAlignment="Left" Text="{Binding Status}" TextWrapping="Wrap" />
</DockPanel>
</StackPanel>
</UserControl>
@@ -0,0 +1,17 @@
using System.Windows.Controls;
using FrameLedger.App.ViewModels;
namespace FrameLedger.App.Dialogs;
/// <summary>The body of Tools ▸ Database maintenance's <c>ContentDialog</c> (P4 PR-7).</summary>
public partial class DatabaseMaintenanceContent : UserControl
{
public DatabaseMaintenanceContent(DatabaseMaintenanceViewModel viewModel)
{
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
DataContext = viewModel;
InitializeComponent();
}
public DatabaseMaintenanceViewModel ViewModel { get; }
}
+1 -1
View File
@@ -51,7 +51,7 @@
<MenuItem Header="{x:Static res:Strings.Menu_Tools_UpdateRules}" Command="{Binding ViewModel.UpdateRulesCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_VulkanLayer}" Command="{Binding ViewModel.VulkanLayerCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_OpenDataFolder}" Command="{Binding ViewModel.OpenDataFolderCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_DbMaintenance}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_DbMaintenance}" Command="{Binding ViewModel.DatabaseMaintenanceCommand}" />
</MenuItem>
<MenuItem Header="{x:Static res:Strings.Menu_Help}">
<MenuItem Header="{x:Static res:Strings.Menu_Help_CheckUpdates}" Command="{Binding ViewModel.CheckForUpdatesCommand}" />
@@ -0,0 +1,60 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using FrameLedger.App.Dialogs;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Persistence;
using Wpf.Ui;
using Wpf.Ui.Controls;
namespace FrameLedger.App.Services;
/// <summary>
/// <see cref="IDatabaseMaintenancePrompts"/> in WPF UI: a <c>ContentDialog</c> over a fresh
/// <see cref="DatabaseMaintenanceViewModel"/> each time it opens, and a <c>MessageBox</c> with a Danger button for the sweep.
/// </summary>
public sealed class DatabaseMaintenancePrompts : IDatabaseMaintenancePrompts
{
private readonly IContentDialogService _dialogs;
private readonly LedgerDatabase _db;
private readonly IAgentRequests _agent;
private readonly IFileSaver _files;
private readonly RegisteredSettings _settings;
public DatabaseMaintenancePrompts(IContentDialogService dialogs, LedgerDatabase db, IAgentRequests agent, IFileSaver files, RegisteredSettings settings)
{
_dialogs = dialogs ?? throw new ArgumentNullException(nameof(dialogs));
_db = db ?? throw new ArgumentNullException(nameof(db));
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_files = files ?? throw new ArgumentNullException(nameof(files));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
public async Task ShowAsync(CancellationToken ct = default)
{
var viewModel = new DatabaseMaintenanceViewModel(new LedgerMaintenance(_db), _db.Path, _agent, _files, this, _settings);
var dialog = new ContentDialog
{
Title = Strings.Maintenance_Title,
Content = new DatabaseMaintenanceContent(viewModel),
CloseButtonText = Strings.Common_Close,
DialogMaxWidth = 760,
};
_ = await _dialogs.ShowAsync(dialog, ct).ConfigureAwait(true);
}
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime")]
public async Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default)
{
var box = new MessageBox
{
Title = Strings.Maintenance_Sweep_Confirm_Title,
Content = string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Sweep_Confirm_Body_Format, keep),
PrimaryButtonText = Strings.Maintenance_Sweep_Confirm_Button,
PrimaryButtonAppearance = ControlAppearance.Danger,
CloseButtonText = Strings.Common_Cancel,
};
MessageBoxResult result = await box.ShowDialogAsync(cancellationToken: ct).ConfigureAwait(true);
return result == MessageBoxResult.Primary;
}
}
@@ -0,0 +1,11 @@
namespace FrameLedger.App.Services;
/// <summary>Tools ▸ Database maintenance's two windows (P4 PR-7): the dialog itself, and the one confirmation a destructive action asks (<c>08_UI</c> §UX rules).</summary>
public interface IDatabaseMaintenancePrompts
{
/// <summary>The maintenance dialog, until the user closes it.</summary>
Task ShowAsync(CancellationToken ct = default);
/// <summary>"Remove the raw series of all but the newest <paramref name="keep"/> sessions per game?" — true to go ahead.</summary>
Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default);
}
+96 -6
View File
@@ -295,6 +295,38 @@ public static class Strings
nameof(Logs_Showing_Format),
nameof(Logs_Source_Agent),
nameof(Logs_Source_Ui),
nameof(Maintenance_Backup_Body),
nameof(Maintenance_Backup_Button),
nameof(Maintenance_Backup_Done_Format),
nameof(Maintenance_Backup_Filter),
nameof(Maintenance_Backup_IsLedger),
nameof(Maintenance_Backup_Label),
nameof(Maintenance_Busy),
nameof(Maintenance_Compact_Body),
nameof(Maintenance_Compact_Button),
nameof(Maintenance_Compact_Done_Format),
nameof(Maintenance_Compact_Label),
nameof(Maintenance_Compact_SessionRunning),
nameof(Maintenance_Failed_Format),
nameof(Maintenance_Integrity_Body),
nameof(Maintenance_Integrity_Button),
nameof(Maintenance_Integrity_Label),
nameof(Maintenance_Integrity_Ok),
nameof(Maintenance_Integrity_Problems_Format),
nameof(Maintenance_Intro),
nameof(Maintenance_Status_Ready),
nameof(Maintenance_Status_Working),
nameof(Maintenance_Sweep_AgentTooOld),
nameof(Maintenance_Sweep_Body),
nameof(Maintenance_Sweep_Button),
nameof(Maintenance_Sweep_Confirm_Body_Format),
nameof(Maintenance_Sweep_Confirm_Button),
nameof(Maintenance_Sweep_Confirm_Title),
nameof(Maintenance_Sweep_Done_Format),
nameof(Maintenance_Sweep_Label),
nameof(Maintenance_Sweep_NoAgent),
nameof(Maintenance_Sweep_Unlimited),
nameof(Maintenance_Title),
nameof(Menu_File),
nameof(Menu_File_AddGame),
nameof(Menu_File_Exit),
@@ -326,8 +358,6 @@ public static class Strings
nameof(Notice_Refused_Recording),
nameof(Notice_Refused_Title_Format),
nameof(Notice_Unhooked_Title),
nameof(NotYet_Body),
nameof(NotYet_Title),
nameof(Override_Apply),
nameof(Override_Body),
nameof(Override_Default),
@@ -1079,6 +1109,70 @@ public static class Strings
public static string Logs_Source_Ui => ResourceManager.GetString(nameof(Logs_Source_Ui), Culture) ?? nameof(Logs_Source_Ui);
public static string Maintenance_Backup_Body => ResourceManager.GetString(nameof(Maintenance_Backup_Body), Culture) ?? nameof(Maintenance_Backup_Body);
public static string Maintenance_Backup_Button => ResourceManager.GetString(nameof(Maintenance_Backup_Button), Culture) ?? nameof(Maintenance_Backup_Button);
public static string Maintenance_Backup_Done_Format => ResourceManager.GetString(nameof(Maintenance_Backup_Done_Format), Culture) ?? nameof(Maintenance_Backup_Done_Format);
public static string Maintenance_Backup_Filter => ResourceManager.GetString(nameof(Maintenance_Backup_Filter), Culture) ?? nameof(Maintenance_Backup_Filter);
public static string Maintenance_Backup_IsLedger => ResourceManager.GetString(nameof(Maintenance_Backup_IsLedger), Culture) ?? nameof(Maintenance_Backup_IsLedger);
public static string Maintenance_Backup_Label => ResourceManager.GetString(nameof(Maintenance_Backup_Label), Culture) ?? nameof(Maintenance_Backup_Label);
public static string Maintenance_Busy => ResourceManager.GetString(nameof(Maintenance_Busy), Culture) ?? nameof(Maintenance_Busy);
public static string Maintenance_Compact_Body => ResourceManager.GetString(nameof(Maintenance_Compact_Body), Culture) ?? nameof(Maintenance_Compact_Body);
public static string Maintenance_Compact_Button => ResourceManager.GetString(nameof(Maintenance_Compact_Button), Culture) ?? nameof(Maintenance_Compact_Button);
public static string Maintenance_Compact_Done_Format => ResourceManager.GetString(nameof(Maintenance_Compact_Done_Format), Culture) ?? nameof(Maintenance_Compact_Done_Format);
public static string Maintenance_Compact_Label => ResourceManager.GetString(nameof(Maintenance_Compact_Label), Culture) ?? nameof(Maintenance_Compact_Label);
public static string Maintenance_Compact_SessionRunning => ResourceManager.GetString(nameof(Maintenance_Compact_SessionRunning), Culture) ?? nameof(Maintenance_Compact_SessionRunning);
public static string Maintenance_Failed_Format => ResourceManager.GetString(nameof(Maintenance_Failed_Format), Culture) ?? nameof(Maintenance_Failed_Format);
public static string Maintenance_Integrity_Body => ResourceManager.GetString(nameof(Maintenance_Integrity_Body), Culture) ?? nameof(Maintenance_Integrity_Body);
public static string Maintenance_Integrity_Button => ResourceManager.GetString(nameof(Maintenance_Integrity_Button), Culture) ?? nameof(Maintenance_Integrity_Button);
public static string Maintenance_Integrity_Label => ResourceManager.GetString(nameof(Maintenance_Integrity_Label), Culture) ?? nameof(Maintenance_Integrity_Label);
public static string Maintenance_Integrity_Ok => ResourceManager.GetString(nameof(Maintenance_Integrity_Ok), Culture) ?? nameof(Maintenance_Integrity_Ok);
public static string Maintenance_Integrity_Problems_Format => ResourceManager.GetString(nameof(Maintenance_Integrity_Problems_Format), Culture) ?? nameof(Maintenance_Integrity_Problems_Format);
public static string Maintenance_Intro => ResourceManager.GetString(nameof(Maintenance_Intro), Culture) ?? nameof(Maintenance_Intro);
public static string Maintenance_Status_Ready => ResourceManager.GetString(nameof(Maintenance_Status_Ready), Culture) ?? nameof(Maintenance_Status_Ready);
public static string Maintenance_Status_Working => ResourceManager.GetString(nameof(Maintenance_Status_Working), Culture) ?? nameof(Maintenance_Status_Working);
public static string Maintenance_Sweep_AgentTooOld => ResourceManager.GetString(nameof(Maintenance_Sweep_AgentTooOld), Culture) ?? nameof(Maintenance_Sweep_AgentTooOld);
public static string Maintenance_Sweep_Body => ResourceManager.GetString(nameof(Maintenance_Sweep_Body), Culture) ?? nameof(Maintenance_Sweep_Body);
public static string Maintenance_Sweep_Button => ResourceManager.GetString(nameof(Maintenance_Sweep_Button), Culture) ?? nameof(Maintenance_Sweep_Button);
public static string Maintenance_Sweep_Confirm_Body_Format => ResourceManager.GetString(nameof(Maintenance_Sweep_Confirm_Body_Format), Culture) ?? nameof(Maintenance_Sweep_Confirm_Body_Format);
public static string Maintenance_Sweep_Confirm_Button => ResourceManager.GetString(nameof(Maintenance_Sweep_Confirm_Button), Culture) ?? nameof(Maintenance_Sweep_Confirm_Button);
public static string Maintenance_Sweep_Confirm_Title => ResourceManager.GetString(nameof(Maintenance_Sweep_Confirm_Title), Culture) ?? nameof(Maintenance_Sweep_Confirm_Title);
public static string Maintenance_Sweep_Done_Format => ResourceManager.GetString(nameof(Maintenance_Sweep_Done_Format), Culture) ?? nameof(Maintenance_Sweep_Done_Format);
public static string Maintenance_Sweep_Label => ResourceManager.GetString(nameof(Maintenance_Sweep_Label), Culture) ?? nameof(Maintenance_Sweep_Label);
public static string Maintenance_Sweep_NoAgent => ResourceManager.GetString(nameof(Maintenance_Sweep_NoAgent), Culture) ?? nameof(Maintenance_Sweep_NoAgent);
public static string Maintenance_Sweep_Unlimited => ResourceManager.GetString(nameof(Maintenance_Sweep_Unlimited), Culture) ?? nameof(Maintenance_Sweep_Unlimited);
public static string Maintenance_Title => ResourceManager.GetString(nameof(Maintenance_Title), Culture) ?? nameof(Maintenance_Title);
public static string Menu_File => ResourceManager.GetString(nameof(Menu_File), Culture) ?? nameof(Menu_File);
public static string Menu_File_AddGame => ResourceManager.GetString(nameof(Menu_File_AddGame), Culture) ?? nameof(Menu_File_AddGame);
@@ -1141,10 +1235,6 @@ public static class Strings
public static string Notice_Unhooked_Title => ResourceManager.GetString(nameof(Notice_Unhooked_Title), Culture) ?? nameof(Notice_Unhooked_Title);
public static string NotYet_Body => ResourceManager.GetString(nameof(NotYet_Body), Culture) ?? nameof(NotYet_Body);
public static string NotYet_Title => ResourceManager.GetString(nameof(NotYet_Title), Culture) ?? nameof(NotYet_Title);
public static string Override_Apply => ResourceManager.GetString(nameof(Override_Apply), Culture) ?? nameof(Override_Apply);
public static string Override_Body => ResourceManager.GetString(nameof(Override_Body), Culture) ?? nameof(Override_Body);
+128 -8
View File
@@ -353,14 +353,6 @@
<value>設定</value>
<comment>review</comment>
</data>
<data name="NotYet_Body" xml:space="preserve">
<value>この機能は後のビルドで提供されます。</value>
<comment>review</comment>
</data>
<data name="NotYet_Title" xml:space="preserve">
<value>未実装</value>
<comment>review</comment>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>検出ルール</value>
<comment>review</comment>
@@ -2069,4 +2061,132 @@
<value>データフォルダー(%LOCALAPPDATA%\FrameLedger:ライブラリ、すべてのセッション、ログ、設定)も削除しますか?後でインストールするために残す場合は「いいえ」を選んでください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Title" xml:space="preserve">
<value>データベースのメンテナンス</value>
<comment>review</comment>
</data>
<data name="Maintenance_Intro" xml:space="preserve">
<value>セッションは ledger という 1 つの SQLite ファイルに保存されています。確認とバックアップは読み取りのみです。圧縮は同じ内容でファイルを書き直し、セッションが実行されていないときだけ行います。整理は保持設定に従って生データを削除します。これらの行は Agent のものなので、Agent が実行します。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Integrity_Label" xml:space="preserve">
<value>整合性の確認</value>
<comment>review</comment>
</data>
<data name="Maintenance_Integrity_Body" xml:space="preserve">
<value>ファイル全体に SQLite の整合性チェックを実行します。読み取りのみです。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Integrity_Button" xml:space="preserve">
<value>確認</value>
<comment>review</comment>
</data>
<data name="Maintenance_Integrity_Ok" xml:space="preserve">
<value>問題は見つかりませんでした。SQLite の整合性チェックは "ok" と答えました。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Integrity_Problems_Format" xml:space="preserve">
<value>SQLite が {0} 件の問題を報告しました。最初の問題: {1}。まずファイルをバックアップしてから、バグを報告してください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_Label" xml:space="preserve">
<value>バックアップ</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_Body" xml:space="preserve">
<value>選択したファイルに ledger の整合したコピーを書き込みます。実行中も Agent は記録を続けます。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_Button" xml:space="preserve">
<value>バックアップ…</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_Filter" xml:space="preserve">
<value>SQLite データベース (*.db)|*.db</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_Done_Format" xml:space="preserve">
<value>{0} にバックアップしました ({1} MB)。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Backup_IsLedger" xml:space="preserve">
<value>そのファイルは ledger そのものです。バックアップには別のファイルを選んでください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Label" xml:space="preserve">
<value>生データの整理</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Body" xml:space="preserve">
<value>保持設定に従い、各ゲームの最新のセッションを除くすべてのセッションから、フレームごとのデータとセンサーの系列を削除します。平均値、パーセンタイル、要約の行は残ります。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Button" xml:space="preserve">
<value>整理…</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Unlimited" xml:space="preserve">
<value>保持は無制限に設定されています (設定 ▸ キャプチャ)。整理するものはありません。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_NoAgent" xml:space="preserve">
<value>Agent に接続されていません。生データの削除は Agent が行います。Agent を起動してもう一度お試しください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_AgentTooOld" xml:space="preserve">
<value>実行中の Agent は整理機能より前のバージョンです。FrameLedger を再起動して同梱の Agent を起動してから、もう一度お試しください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Confirm_Title" xml:space="preserve">
<value>生データを削除しますか?</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Confirm_Body_Format" xml:space="preserve">
<value>各ゲームの最新 {0} 件を除くすべてのセッションのフレームごとのデータとセンサーの系列が完全に削除されます。要約は残りますが、それらのセッションのフレームタイムのグラフは表示されなくなります。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Confirm_Button" xml:space="preserve">
<value>削除</value>
<comment>review</comment>
</data>
<data name="Maintenance_Sweep_Done_Format" xml:space="preserve">
<value>{1} 件のゲームにわたる {0} 件のセッションから生データを削除しました。各ゲームの最新 {2} 件は保持されています。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Compact_Label" xml:space="preserve">
<value>圧縮</value>
<comment>review</comment>
</data>
<data name="Maintenance_Compact_Body" xml:space="preserve">
<value>削除されたデータで空いた領域をディスクに返すため、ファイルを書き直します。セッションが実行されていないときだけ行います。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Compact_Button" xml:space="preserve">
<value>圧縮</value>
<comment>review</comment>
</data>
<data name="Maintenance_Compact_SessionRunning" xml:space="preserve">
<value>セッションが実行中です。圧縮はファイル全体を書き直すため、セッションの終了を待ちます。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Compact_Done_Format" xml:space="preserve">
<value>圧縮しました: 前 {0} MB、後 {1} MB。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Busy" xml:space="preserve">
<value>ledger が使用中でした (Agent が書き込み中)。何も変更されていません。しばらくしてからもう一度お試しください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Failed_Format" xml:space="preserve">
<value>完了しませんでした: {0}</value>
<comment>review</comment>
</data>
<data name="Maintenance_Status_Ready" xml:space="preserve">
<value>操作を選んでください。</value>
<comment>review</comment>
</data>
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>実行中…</value>
<comment>review</comment>
</data>
</root>
+96 -6
View File
@@ -270,12 +270,6 @@
<data name="Nav_Settings" xml:space="preserve">
<value>Settings</value>
</data>
<data name="NotYet_Body" xml:space="preserve">
<value>This part of FrameLedger arrives with a later build.</value>
</data>
<data name="NotYet_Title" xml:space="preserve">
<value>Not built yet</value>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>Detection rules</value>
</data>
@@ -1557,4 +1551,100 @@
<data name="Uninstall_DataFolder_Body" xml:space="preserve">
<value>Also delete the data folder (%LOCALAPPDATA%\FrameLedger: your library, every session, logs and settings)? Choose No to keep it for a later install.</value>
</data>
<data name="Maintenance_Title" xml:space="preserve">
<value>Database maintenance</value>
</data>
<data name="Maintenance_Intro" xml:space="preserve">
<value>Your sessions live in one SQLite file, the ledger. Checking and backing up only read it. Compacting rewrites the file with the same contents and waits until no session runs. Sweeping removes raw series by your retention setting; the Agent does it, because those rows are the Agent's.</value>
</data>
<data name="Maintenance_Integrity_Label" xml:space="preserve">
<value>Check integrity</value>
</data>
<data name="Maintenance_Integrity_Body" xml:space="preserve">
<value>Runs SQLite's integrity check over the whole file. Reads only.</value>
</data>
<data name="Maintenance_Integrity_Button" xml:space="preserve">
<value>Check</value>
</data>
<data name="Maintenance_Integrity_Ok" xml:space="preserve">
<value>No problems found: SQLite's integrity check answered "ok".</value>
</data>
<data name="Maintenance_Integrity_Problems_Format" xml:space="preserve">
<value>SQLite reported {0} problem(s). The first: {1}. Back up the file before anything else, then report a bug.</value>
</data>
<data name="Maintenance_Backup_Label" xml:space="preserve">
<value>Back up</value>
</data>
<data name="Maintenance_Backup_Body" xml:space="preserve">
<value>Writes a consistent copy of the ledger to a file you choose. The Agent keeps recording while it runs.</value>
</data>
<data name="Maintenance_Backup_Button" xml:space="preserve">
<value>Back up…</value>
</data>
<data name="Maintenance_Backup_Filter" xml:space="preserve">
<value>SQLite database (*.db)|*.db</value>
</data>
<data name="Maintenance_Backup_Done_Format" xml:space="preserve">
<value>Backed up to {0} ({1} MB).</value>
</data>
<data name="Maintenance_Backup_IsLedger" xml:space="preserve">
<value>That file is the ledger itself. Choose another file for the backup.</value>
</data>
<data name="Maintenance_Sweep_Label" xml:space="preserve">
<value>Sweep raw data</value>
</data>
<data name="Maintenance_Sweep_Body" xml:space="preserve">
<value>Removes the per-frame and sensor series of all but the newest sessions per game, as the retention setting says. Averages, percentiles and charts' summary rows stay.</value>
</data>
<data name="Maintenance_Sweep_Button" xml:space="preserve">
<value>Sweep…</value>
</data>
<data name="Maintenance_Sweep_Unlimited" xml:space="preserve">
<value>Retention is unlimited (Settings ▸ Capture), so there is nothing to sweep.</value>
</data>
<data name="Maintenance_Sweep_NoAgent" xml:space="preserve">
<value>The Agent is not connected. The raw data is the Agent's to remove; start it and try again.</value>
</data>
<data name="Maintenance_Sweep_AgentTooOld" xml:space="preserve">
<value>The running Agent predates the sweep. Restart FrameLedger so the Agent beside it starts, then try again.</value>
</data>
<data name="Maintenance_Sweep_Confirm_Title" xml:space="preserve">
<value>Remove raw data?</value>
</data>
<data name="Maintenance_Sweep_Confirm_Body_Format" xml:space="preserve">
<value>The per-frame and sensor series of every session except the newest {0} per game will be removed for good. Summaries stay; frame-time charts of those sessions will no longer draw.</value>
</data>
<data name="Maintenance_Sweep_Confirm_Button" xml:space="preserve">
<value>Remove</value>
</data>
<data name="Maintenance_Sweep_Done_Format" xml:space="preserve">
<value>Raw series removed from {0} session(s) across {1} game(s); the newest {2} per game are kept.</value>
</data>
<data name="Maintenance_Compact_Label" xml:space="preserve">
<value>Compact</value>
</data>
<data name="Maintenance_Compact_Body" xml:space="preserve">
<value>Rewrites the file to give space freed by removed data back to the disk. Waits until no session runs.</value>
</data>
<data name="Maintenance_Compact_Button" xml:space="preserve">
<value>Compact</value>
</data>
<data name="Maintenance_Compact_SessionRunning" xml:space="preserve">
<value>A session is running. Compacting rewrites the whole file, so it waits until the session ends.</value>
</data>
<data name="Maintenance_Compact_Done_Format" xml:space="preserve">
<value>Compacted: {0} MB before, {1} MB after.</value>
</data>
<data name="Maintenance_Busy" xml:space="preserve">
<value>The ledger was busy (the Agent was writing). Nothing changed; try again in a moment.</value>
</data>
<data name="Maintenance_Failed_Format" xml:space="preserve">
<value>That did not complete: {0}</value>
</data>
<data name="Maintenance_Status_Ready" xml:space="preserve">
<value>Choose an action.</value>
</data>
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>Working…</value>
</data>
</root>
+96 -6
View File
@@ -265,12 +265,6 @@
<data name="Nav_Settings" xml:space="preserve">
<value>Cài đặt</value>
</data>
<data name="NotYet_Body" xml:space="preserve">
<value>Phần này của FrameLedger sẽ có ở bản sau.</value>
</data>
<data name="NotYet_Title" xml:space="preserve">
<value>Chưa xây dựng</value>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>Quy tắc nhận diện</value>
</data>
@@ -1552,4 +1546,100 @@
<data name="Uninstall_DataFolder_Body" xml:space="preserve">
<value>Xoá luôn thư mục dữ liệu (%LOCALAPPDATA%\FrameLedger: thư viện, mọi phiên, log và cài đặt)? Chọn Không để giữ lại cho lần cài sau.</value>
</data>
<data name="Maintenance_Title" xml:space="preserve">
<value>Bảo trì cơ sở dữ liệu</value>
</data>
<data name="Maintenance_Intro" xml:space="preserve">
<value>Các phiên của bạn nằm trong một tệp SQLite gọi là ledger. Kiểm tra và sao lưu chỉ đọc tệp. Thu gọn ghi lại tệp với cùng nội dung và chỉ chạy khi không có phiên nào. Dọn dẹp xoá dữ liệu thô theo cài đặt lưu giữ; việc này do Agent làm vì các dòng đó thuộc về Agent.</value>
</data>
<data name="Maintenance_Integrity_Label" xml:space="preserve">
<value>Kiểm tra toàn vẹn</value>
</data>
<data name="Maintenance_Integrity_Body" xml:space="preserve">
<value>Chạy kiểm tra toàn vẹn của SQLite trên toàn bộ tệp. Chỉ đọc.</value>
</data>
<data name="Maintenance_Integrity_Button" xml:space="preserve">
<value>Kiểm tra</value>
</data>
<data name="Maintenance_Integrity_Ok" xml:space="preserve">
<value>Không phát hiện vấn đề: kiểm tra toàn vẹn của SQLite trả lời "ok".</value>
</data>
<data name="Maintenance_Integrity_Problems_Format" xml:space="preserve">
<value>SQLite báo {0} vấn đề. Vấn đề đầu tiên: {1}. Hãy sao lưu tệp trước tiên, rồi báo lỗi.</value>
</data>
<data name="Maintenance_Backup_Label" xml:space="preserve">
<value>Sao lưu</value>
</data>
<data name="Maintenance_Backup_Body" xml:space="preserve">
<value>Ghi một bản sao nhất quán của ledger vào tệp bạn chọn. Agent vẫn ghi phiên trong lúc sao lưu.</value>
</data>
<data name="Maintenance_Backup_Button" xml:space="preserve">
<value>Sao lưu…</value>
</data>
<data name="Maintenance_Backup_Filter" xml:space="preserve">
<value>Cơ sở dữ liệu SQLite (*.db)|*.db</value>
</data>
<data name="Maintenance_Backup_Done_Format" xml:space="preserve">
<value>Đã sao lưu vào {0} ({1} MB).</value>
</data>
<data name="Maintenance_Backup_IsLedger" xml:space="preserve">
<value>Tệp đó chính là ledger. Hãy chọn tệp khác để sao lưu.</value>
</data>
<data name="Maintenance_Sweep_Label" xml:space="preserve">
<value>Dọn dữ liệu thô</value>
</data>
<data name="Maintenance_Sweep_Body" xml:space="preserve">
<value>Xoá chuỗi dữ liệu từng khung hình và cảm biến của mọi phiên trừ các phiên mới nhất của mỗi game, theo cài đặt lưu giữ. Giá trị trung bình, phân vị và các dòng tóm tắt vẫn được giữ.</value>
</data>
<data name="Maintenance_Sweep_Button" xml:space="preserve">
<value>Dọn dẹp…</value>
</data>
<data name="Maintenance_Sweep_Unlimited" xml:space="preserve">
<value>Lưu giữ đang là không giới hạn (Cài đặt ▸ Ghi), nên không có gì để dọn.</value>
</data>
<data name="Maintenance_Sweep_NoAgent" xml:space="preserve">
<value>Agent chưa kết nối. Dữ liệu thô do Agent xoá; hãy khởi động Agent rồi thử lại.</value>
</data>
<data name="Maintenance_Sweep_AgentTooOld" xml:space="preserve">
<value>Agent đang chạy là phiên bản cũ chưa có chức năng dọn dẹp. Hãy khởi động lại FrameLedger để Agent đi kèm được khởi động, rồi thử lại.</value>
</data>
<data name="Maintenance_Sweep_Confirm_Title" xml:space="preserve">
<value>Xoá dữ liệu thô?</value>
</data>
<data name="Maintenance_Sweep_Confirm_Body_Format" xml:space="preserve">
<value>Chuỗi dữ liệu từng khung hình và cảm biến của mọi phiên, trừ {0} phiên mới nhất của mỗi game, sẽ bị xoá vĩnh viễn. Phần tóm tắt được giữ; biểu đồ thời gian khung hình của các phiên đó sẽ không còn vẽ được.</value>
</data>
<data name="Maintenance_Sweep_Confirm_Button" xml:space="preserve">
<value>Xoá</value>
</data>
<data name="Maintenance_Sweep_Done_Format" xml:space="preserve">
<value>Đã xoá dữ liệu thô của {0} phiên trên {1} game; {2} phiên mới nhất của mỗi game được giữ lại.</value>
</data>
<data name="Maintenance_Compact_Label" xml:space="preserve">
<value>Thu gọn</value>
</data>
<data name="Maintenance_Compact_Body" xml:space="preserve">
<value>Ghi lại tệp để trả lại cho ổ đĩa phần dung lượng đã được giải phóng. Chỉ chạy khi không có phiên nào.</value>
</data>
<data name="Maintenance_Compact_Button" xml:space="preserve">
<value>Thu gọn</value>
</data>
<data name="Maintenance_Compact_SessionRunning" xml:space="preserve">
<value>Đang có phiên chạy. Thu gọn ghi lại toàn bộ tệp nên phải chờ phiên kết thúc.</value>
</data>
<data name="Maintenance_Compact_Done_Format" xml:space="preserve">
<value>Đã thu gọn: trước {0} MB, sau {1} MB.</value>
</data>
<data name="Maintenance_Busy" xml:space="preserve">
<value>Ledger đang bận (Agent đang ghi). Không có gì thay đổi; hãy thử lại sau giây lát.</value>
</data>
<data name="Maintenance_Failed_Format" xml:space="preserve">
<value>Thao tác không hoàn tất: {0}</value>
</data>
<data name="Maintenance_Status_Ready" xml:space="preserve">
<value>Hãy chọn một thao tác.</value>
</data>
<data name="Maintenance_Status_Working" xml:space="preserve">
<value>Đang thực hiện…</value>
</data>
</root>
@@ -0,0 +1,195 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FrameLedger.App.Services;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
using Microsoft.Data.Sqlite;
using Serilog;
namespace FrameLedger.App.ViewModels;
/// <summary>
/// Tools ▸ Database maintenance (P4 PR-7, <c>06_DATA_MODEL</c> §Retention): the integrity check and the backup, which
/// only read; compaction (<c>VACUUM</c>), refused while the Agent reports a session because a session writes; and the
/// retention sweep, which the Agent runs when asked because the raw series are its rows (§Writer ownership). Each
/// action ends in one line in <see cref="Status"/>; a failure is a line too, never an unhandled command.
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed partial class DatabaseMaintenanceViewModel : ObservableObject
{
/// <summary>SQLite's busy result: another connection held the lock past the busy timeout.</summary>
private const int _sqliteBusy = 5;
private readonly LedgerMaintenance _ledger;
private readonly string _ledgerPath;
private readonly IAgentRequests _agent;
private readonly IFileSaver _files;
private readonly IDatabaseMaintenancePrompts _prompts;
private readonly RegisteredSettings _settings;
private readonly TimeProvider _clock;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(CheckIntegrityCommand), nameof(BackUpCommand), nameof(SweepCommand), nameof(CompactCommand))]
private bool _isBusy;
[ObservableProperty]
private string _status = Strings.Maintenance_Status_Ready;
public DatabaseMaintenanceViewModel(LedgerMaintenance ledger, string ledgerPath, IAgentRequests agent, IFileSaver files, IDatabaseMaintenancePrompts prompts,
RegisteredSettings settings, TimeProvider? clock = null)
{
_ledger = ledger ?? throw new ArgumentNullException(nameof(ledger));
ArgumentException.ThrowIfNullOrWhiteSpace(ledgerPath);
_ledgerPath = Path.GetFullPath(ledgerPath);
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_files = files ?? throw new ArgumentNullException(nameof(files));
_prompts = prompts ?? throw new ArgumentNullException(nameof(prompts));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_clock = clock ?? TimeProvider.System;
}
private bool CanRun => !IsBusy;
/// <summary><c>PRAGMA integrity_check</c>: "no problems", or the count and SQLite's first line.</summary>
[RelayCommand(CanExecute = nameof(CanRun))]
private Task CheckIntegrityAsync() => RunAsync(async () =>
{
IReadOnlyList<string> lines = await _ledger.CheckIntegrityAsync().ConfigureAwait(true);
Status = LedgerMaintenance.IsHealthy(lines)
? Strings.Maintenance_Integrity_Ok
: string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Integrity_Problems_Format, lines.Count, lines.Count > 0 ? lines[0] : string.Empty);
});
/// <summary>A consistent copy through <c>VACUUM INTO</c> to a file the user names; never the live ledger itself.</summary>
[RelayCommand(CanExecute = nameof(CanRun))]
private Task BackUpAsync() => RunAsync(async () =>
{
string suggested = string.Format(CultureInfo.InvariantCulture, "FrameLedger-ledger-{0:yyyyMMdd-HHmmss}.db", _clock.GetLocalNow());
string? path = _files.PickSavePath(Strings.Maintenance_Backup_Filter, suggested);
if (path is null)
{
return;
}
string full = Path.GetFullPath(path);
if (IsLedgerFile(full))
{
Status = Strings.Maintenance_Backup_IsLedger;
return;
}
// The save dialog already asked before an existing file is replaced; VACUUM INTO refuses to write over one.
if (File.Exists(full))
{
File.Delete(full);
}
await _ledger.BackupAsync(full).ConfigureAwait(true);
Status = string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Backup_Done_Format, full, Megabytes(new FileInfo(full).Length));
});
/// <summary>
/// The retention sweep, asked of the Agent: nothing to do when retention is unlimited, a confirmation before rows
/// go, and the Agent's own count after.
/// </summary>
[RelayCommand(CanExecute = nameof(CanRun))]
private Task SweepAsync() => RunAsync(async () =>
{
int keep = await _settings.GetIntegerAsync(SettingsRegistry.RetentionRawSessionsPerGame).ConfigureAwait(true);
if (keep == 0)
{
Status = Strings.Maintenance_Sweep_Unlimited;
return;
}
if (!_agent.IsConnected)
{
Status = Strings.Maintenance_Sweep_NoAgent;
return;
}
if (!await _prompts.ConfirmSweepAsync(keep).ConfigureAwait(true))
{
return;
}
try
{
IpcEnvelope envelope = await _agent.RequestAsync(IpcMessageType.SweepRetention, new SweepRetentionRequest()).ConfigureAwait(true);
SweepRetentionAck ack = IpcCodec.Payload<SweepRetentionAck>(envelope) ?? throw new InvalidOperationException("SweepRetention answered without a payload");
Status = string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Sweep_Done_Format, ack.Sessions, ack.Games, ack.Keep);
}
catch (IpcRequestException ex) when (string.Equals(ex.Code, IpcErrorCode.UnknownType, StringComparison.Ordinal))
{
Log.Warning("maintenance: the Agent does not know SweepRetention ({Message})", ex.Message);
Status = Strings.Maintenance_Sweep_AgentTooOld;
}
});
/// <summary><c>VACUUM</c>, only while the Agent says no session runs; "busy" is a line, not a crash.</summary>
[RelayCommand(CanExecute = nameof(CanRun))]
private Task CompactAsync() => RunAsync(async () =>
{
if (await IsSessionRunningAsync().ConfigureAwait(true))
{
Status = Strings.Maintenance_Compact_SessionRunning;
return;
}
LedgerCompaction result = await _ledger.CompactAsync().ConfigureAwait(true);
Status = string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Compact_Done_Format, Megabytes(result.BytesBefore), Megabytes(result.BytesAfter));
});
/// <summary>A fresh <c>GetStatus</c> when connected (the connection's cached one can be a minute old); no Agent, no session.</summary>
private async Task<bool> IsSessionRunningAsync()
{
if (!_agent.IsConnected)
{
return false;
}
IpcEnvelope envelope = await _agent.RequestAsync(IpcMessageType.GetStatus, new GetStatusRequest()).ConfigureAwait(true);
StatusAck? status = IpcCodec.Payload<StatusAck>(envelope);
return status is null || !string.Equals(status.State, "idle", StringComparison.Ordinal) || status.ActiveSessions.Count > 0;
}
private async Task RunAsync(Func<Task> action)
{
IsBusy = true;
Status = Strings.Maintenance_Status_Working;
try
{
await action().ConfigureAwait(true);
}
catch (SqliteException ex) when (ex.SqliteErrorCode == _sqliteBusy)
{
Log.Warning(ex, "maintenance: the ledger was busy");
Status = Strings.Maintenance_Busy;
}
catch (Exception ex) when (ex is SqliteException or IOException or UnauthorizedAccessException or IpcRequestException or TimeoutException or InvalidOperationException)
{
Log.Warning(ex, "maintenance: the action failed");
Status = string.Format(CultureInfo.CurrentCulture, Strings.Maintenance_Failed_Format, ex.Message);
}
finally
{
if (string.Equals(Status, Strings.Maintenance_Status_Working, StringComparison.Ordinal))
{
Status = Strings.Maintenance_Status_Ready;
}
IsBusy = false;
}
}
private bool IsLedgerFile(string full) =>
string.Equals(full, _ledgerPath, StringComparison.OrdinalIgnoreCase)
|| full.StartsWith(_ledgerPath + "-", StringComparison.OrdinalIgnoreCase);
private static string Megabytes(long bytes) => (bytes / (1024.0 * 1024.0)).ToString("0.0", CultureInfo.CurrentCulture);
}
@@ -48,6 +48,7 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
private readonly AddGameFlow _addGame;
private readonly UpdateService _updates;
private readonly IDatabaseMaintenancePrompts _maintenance;
private readonly BugReportFlow _bugReports;
private readonly IUrlOpener _urls;
private readonly SessionSelection _selection;
@@ -57,8 +58,9 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IShellPresence shell, IPageNavigator navigator, AddGameFlow addGame, SafetyNotices notices,
BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries, ImportLibraryFlow import,
UpdateService updates)
UpdateService updates, IDatabaseMaintenancePrompts maintenance)
{
_maintenance = maintenance ?? throw new ArgumentNullException(nameof(maintenance));
Notices = notices ?? throw new ArgumentNullException(nameof(notices));
_updates = updates ?? throw new ArgumentNullException(nameof(updates));
_import = import ?? throw new ArgumentNullException(nameof(import));
@@ -267,8 +269,10 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
private void NoSelection() =>
_snackbar.Show(Strings.Menu_File_Export, Strings.Export_NoSelection_Body, ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4));
/// <summary>Every menu item of <c>08_UI</c> §Menu bar that a later slice builds says so, in a 4 s snackbar, rather than doing nothing.</summary>
/// <summary>
/// Tools ▸ Database maintenance… (P4 PR-7): integrity check, backup, the retention sweep (the Agent's) and compaction.
/// It was the last menu item that said "not built yet"; the placeholder command went with it.
/// </summary>
[RelayCommand]
private void NotYet() =>
_snackbar.Show(Strings.NotYet_Title, Strings.NotYet_Body, ControlAppearance.Secondary, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4));
private Task DatabaseMaintenanceAsync() => _maintenance.ShowAsync();
}
@@ -33,6 +33,7 @@ public sealed class AgentCommandHandler
private readonly string? _disclosureVersion;
private readonly TimeProvider _clock;
private readonly VkLayerReconciler? _layer;
private readonly Func<CancellationToken, ValueTask<SweepRetentionAck>>? _sweepRetention;
/// <summary>
/// <c>disclosureVersion</c> is the version of FR-2.1's reviewed disclosure this Agent carries
@@ -41,8 +42,11 @@ public sealed class AgentCommandHandler
/// </summary>
public AgentCommandHandler(IGameRepository games, IGameConsentStore consent, IAntiCheatGuard guard, IExecutableIdentitySource identity,
CaptureOrchestrator orchestrator, CapturePause pause, IAgentLifetime lifetime, Func<CancellationToken, ValueTask<string>> updateRules,
string? disclosureVersion = null, TimeProvider? clock = null, VkLayerReconciler? layer = null)
string? disclosureVersion = null, TimeProvider? clock = null, VkLayerReconciler? layer = null,
Func<CancellationToken, ValueTask<SweepRetentionAck>>? sweepRetention = null)
{
// P4 PR-7: Tools ▸ Database maintenance's sweep — composed under --serve, absent (UnknownType) where nothing wired it.
_sweepRetention = sweepRetention;
_clock = clock ?? TimeProvider.System;
// P4 PR-2: the layer's registration follows every consent change this handler makes (12_BUILD §The Vulkan
// layer is not registered at install time); null in tests that do not care, and the sweep reconciles anyway.
@@ -75,6 +79,8 @@ public sealed class AgentCommandHandler
IpcMessageType.StopSession => Stop(request),
IpcMessageType.UpdateRules => IpcCodec.Encode(IpcMessageType.UpdateRulesAck, request.Id, new UpdateRulesAck(await _updateRules(ct).ConfigureAwait(false))),
IpcMessageType.Shutdown => Shutdown(request),
IpcMessageType.SweepRetention when _sweepRetention is not null =>
IpcCodec.Encode(IpcMessageType.SweepRetentionAck, request.Id, await _sweepRetention(ct).ConfigureAwait(false)),
_ => null,
};
}
@@ -28,6 +28,14 @@ public interface ISessionRepository
ValueTask<int> SweepRetentionAsync(long gameId, int keep, CancellationToken ct = default);
/// <summary>
/// <c>06_DATA_MODEL</c> §Retention on demand (P4 PR-7): the per-game rule of <see cref="SweepRetentionAsync"/> for
/// every game at once, a removed game whose sessions were kept included, in one transaction. <paramref name="keep"/>
/// must be at least 1 — "unlimited" is the caller's to honour by not sweeping, never a keep of zero that deletes
/// every raw series.
/// </summary>
ValueTask<RetentionSweepResult> SweepRetentionAllAsync(int keep, CancellationToken ct = default);
ValueTask<FrameBlobs?> FindFramesAsync(long sessionId, CancellationToken ct = default);
/// <summary>The session's segments in frame order (the ribbon, <c>08_UI</c> §Session summary).</summary>
@@ -0,0 +1,4 @@
namespace FrameLedger.Application.Persistence;
/// <summary>One on-demand retention sweep across every game: the games that have sessions, and the sessions whose raw series went.</summary>
public sealed record RetentionSweepResult(int Games, int Sessions);
@@ -0,0 +1,36 @@
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.Application.Recording;
/// <summary>
/// <c>06_DATA_MODEL</c> §Retention's "on demand" leg (P4 PR-7, Tools ▸ Database maintenance): the rule every finalize
/// applies to its own game — the raw frame and sensor series of all but the newest
/// <c>retention.raw_sessions_per_game</c> sessions go, aggregates and segments stay — applied to every game at once.
/// The blob tables are the Agent's (§Writer ownership), so this runs in the Agent when the App sends
/// <c>SweepRetention</c>, with the setting the Agent reads itself. A setting of 0 is unlimited and sweeps nothing.
/// </summary>
public sealed class RetentionSweep
{
private readonly ISessionRepository _sessions;
private readonly RegisteredSettings _settings;
public RetentionSweep(ISessionRepository sessions, RegisteredSettings settings)
{
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}
public async ValueTask<SweepRetentionAck> RunAsync(CancellationToken ct = default)
{
int keep = await _settings.GetIntegerAsync(SettingsRegistry.RetentionRawSessionsPerGame, ct).ConfigureAwait(false);
if (keep == 0)
{
return new SweepRetentionAck(0, 0, 0);
}
RetentionSweepResult result = await _sessions.SweepRetentionAllAsync(keep, ct).ConfigureAwait(false);
return new SweepRetentionAck(keep, result.Games, result.Sessions);
}
}
@@ -0,0 +1,4 @@
namespace FrameLedger.Infrastructure.Persistence;
/// <summary>What <see cref="LedgerMaintenance.CompactAsync"/> did to the file: the ledger's bytes (the database and its WAL) before and after.</summary>
public sealed record LedgerCompaction(long BytesBefore, long BytesAfter);
@@ -110,6 +110,26 @@ public sealed class LedgerDatabase : IAsyncDisposable
}
}
/// <summary>
/// Runs <paramref name="work"/> OUTSIDE any transaction, serialised with every other caller (P4 PR-7): for the
/// statements SQLite refuses inside one — <c>VACUUM</c>, <c>VACUUM INTO</c>, <c>wal_checkpoint</c> — and only for
/// maintenance. A domain write goes through <see cref="WriteAsync{T}"/>.
/// </summary>
public async ValueTask<T> MaintainAsync<T>(Func<SqliteConnection, CancellationToken, Task<T>> work, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(work);
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await work(_connection, ct).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Runs <paramref name="work"/> inside one explicit transaction: committed when it returns, rolled back
/// when it throws. <c>06_DATA_MODEL</c>: "all writes in explicit transactions".
@@ -0,0 +1,94 @@
using System.IO;
using Dapper;
namespace FrameLedger.Infrastructure.Persistence;
/// <summary>
/// Tools ▸ Database maintenance's App-side half (P4 PR-7, <c>06_DATA_MODEL</c> §Retention: "which also offers
/// <c>PRAGMA integrity_check</c>, <c>VACUUM</c>, backup"). None of it changes a row: the integrity check and the backup
/// only read, and <c>VACUUM</c> rewrites the file's pages with the same contents. Removing raw series is the Agent's
/// (<c>SweepRetention</c>), because the blob tables are its (§Writer ownership).
/// </summary>
public sealed class LedgerMaintenance
{
private readonly LedgerDatabase _db;
public LedgerMaintenance(LedgerDatabase db) => _db = db ?? throw new ArgumentNullException(nameof(db));
/// <summary><c>PRAGMA integrity_check</c>: the single line <c>ok</c> when the file is sound, otherwise SQLite's own problem lines (at most 100).</summary>
public ValueTask<IReadOnlyList<string>> CheckIntegrityAsync(CancellationToken ct = default) =>
_db.ReadAsync<IReadOnlyList<string>>(async (c, token) =>
{
IEnumerable<string> lines = await c.QueryAsync<string>(new CommandDefinition("PRAGMA integrity_check", cancellationToken: token)).ConfigureAwait(false);
return [.. lines];
}, ct);
/// <summary>True when <see cref="CheckIntegrityAsync"/>'s answer is SQLite's healthy one.</summary>
public static bool IsHealthy(IReadOnlyList<string> lines)
{
ArgumentNullException.ThrowIfNull(lines);
return lines.Count == 1 && string.Equals(lines[0], "ok", StringComparison.Ordinal);
}
/// <summary>
/// A consistent, compacted copy of the ledger at <paramref name="destination"/> through <c>VACUUM INTO</c>: other
/// connections — the Agent's — keep reading and writing while it runs, and the copy is a complete database, not a
/// file copy caught between a write and its WAL. The destination must not exist; the caller asked the user first.
/// </summary>
/// <exception cref="IOException">The destination exists.</exception>
public async ValueTask BackupAsync(string destination, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destination);
string full = Path.GetFullPath(destination);
string ledger = Path.GetFullPath(_db.Path);
if (string.Equals(full, ledger, StringComparison.OrdinalIgnoreCase) || full.StartsWith(ledger + "-", StringComparison.OrdinalIgnoreCase))
{
// The live ledger, its WAL or its shared-memory file: a caller that deleted "the existing file" first would
// have deleted the database, so the destination is refused whatever the caller did before.
throw new IOException($"{full} is the ledger itself; a backup goes to another file");
}
if (File.Exists(full))
{
throw new IOException($"{full} exists; a backup never overwrites a file");
}
await _db.MaintainAsync(async (c, token) =>
{
await c.ExecuteAsync(new CommandDefinition("VACUUM INTO @full", new { full }, cancellationToken: token)).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
}
/// <summary>
/// <c>VACUUM</c>, then <c>wal_checkpoint(TRUNCATE)</c> so the space is returned to the disk rather than parked in
/// the WAL. The caller refuses while a session runs; a writer that arrives anyway makes this fail with SQLite's
/// busy error after the busy timeout, and nothing is lost either way.
/// </summary>
public async ValueTask<LedgerCompaction> CompactAsync(CancellationToken ct = default)
{
long before = FileBytes(_db.Path);
await _db.MaintainAsync(async (c, token) =>
{
await c.ExecuteAsync(new CommandDefinition("VACUUM", cancellationToken: token)).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition("PRAGMA wal_checkpoint(TRUNCATE)", cancellationToken: token)).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
return new LedgerCompaction(before, FileBytes(_db.Path));
}
private static long FileBytes(string database)
{
long bytes = 0;
foreach (string path in new[] { database, database + "-wal" })
{
var info = new FileInfo(path);
if (info.Exists)
{
bytes += info.Length;
}
}
return bytes;
}
}
@@ -52,6 +52,22 @@ public sealed class SqliteSessionRepository : ISessionRepository
"DELETE FROM sensor_blobs WHERE session_id IN ("
+ "SELECT id FROM sessions WHERE game_id = @gameId ORDER BY started_at DESC, id DESC LIMIT -1 OFFSET @keep)";
// P4 PR-7: the same rule as the two statements above, every game at once. ROW_NUMBER per game in the same order
// the per-game sweep uses (newest first, id breaking a tie), so the two can never disagree about which session
// is the Nth; a removed game's kept sessions are in `sessions` and are swept like any other.
private const string _rankedBeyondKeep =
"SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY game_id ORDER BY started_at DESC, id DESC) AS rn FROM sessions) WHERE rn > @keep";
private const string _countSweptSessions =
"SELECT COUNT(*) FROM (" + _rankedBeyondKeep + ") r "
+ "WHERE EXISTS (SELECT 1 FROM frame_blobs f WHERE f.session_id = r.id) OR EXISTS (SELECT 1 FROM sensor_blobs s WHERE s.session_id = r.id)";
private const string _sweepFramesAll = "DELETE FROM frame_blobs WHERE session_id IN (" + _rankedBeyondKeep + ")";
private const string _sweepSensorsAll = "DELETE FROM sensor_blobs WHERE session_id IN (" + _rankedBeyondKeep + ")";
private const string _countGamesWithSessions = "SELECT COUNT(DISTINCT game_id) FROM sessions";
private readonly LedgerDatabase _db;
public SqliteSessionRepository(LedgerDatabase db) => _db = db ?? throw new ArgumentNullException(nameof(db));
@@ -149,6 +165,19 @@ public sealed class SqliteSessionRepository : ISessionRepository
}, ct);
}
public ValueTask<RetentionSweepResult> SweepRetentionAllAsync(int keep, CancellationToken ct = default)
{
ArgumentOutOfRangeException.ThrowIfLessThan(keep, 1);
return _db.WriteAsync(async (c, tx, token) =>
{
long sessions = await c.ExecuteScalarAsync<long>(new CommandDefinition(_countSweptSessions, new { keep }, tx, cancellationToken: token)).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition(_sweepFramesAll, new { keep }, tx, cancellationToken: token)).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition(_sweepSensorsAll, new { keep }, tx, cancellationToken: token)).ConfigureAwait(false);
long games = await c.ExecuteScalarAsync<long>(new CommandDefinition(_countGamesWithSessions, transaction: tx, cancellationToken: token)).ConfigureAwait(false);
return new RetentionSweepResult(checked((int)games), checked((int)sessions));
}, ct);
}
public ValueTask<FrameBlobs?> FindFramesAsync(long sessionId, CancellationToken ct = default) =>
_db.ReadAsync((c, token) => SqliteReaders.ReadOneAsync(
c, new CommandDefinition(_selectFrames, new { sessionId }, cancellationToken: token), ReadFrames), ct);
@@ -46,6 +46,8 @@ namespace FrameLedger.Shared.Ipc;
[JsonSerializable(typeof(UpdateRulesAck))]
[JsonSerializable(typeof(ShutdownRequest))]
[JsonSerializable(typeof(ShutdownAck))]
[JsonSerializable(typeof(SweepRetentionRequest))]
[JsonSerializable(typeof(SweepRetentionAck))]
public sealed partial class IpcJsonContext : JsonSerializerContext
{
}
+18
View File
@@ -44,6 +44,10 @@ public static class IpcMessageType
public const string Shutdown = "Shutdown";
public const string ShutdownAck = "ShutdownAck";
/// <summary>Tools ▸ Database maintenance (P4 PR-7): the on-demand retention sweep, which the Agent runs because the blob tables are its.</summary>
public const string SweepRetention = "SweepRetention";
public const string SweepRetentionAck = "SweepRetentionAck";
public const string SessionStarted = "SessionStarted";
public const string SessionProgress = "SessionProgress";
public const string SessionCompleted = "SessionCompleted";
@@ -269,3 +273,17 @@ public sealed record UpdateRulesAck(string Outcome);
public sealed record ShutdownRequest;
public sealed record ShutdownAck;
/// <summary>
/// <c>SweepRetention</c> (P4 PR-7): a trigger, no payload. The Agent applies <c>06_DATA_MODEL</c> §Retention to every
/// game with the <c>retention.raw_sessions_per_game</c> it reads itself — the client names no number, because the
/// rows it would delete are the Agent's (§Writer ownership).
/// </summary>
public sealed record SweepRetentionRequest;
/// <summary>
/// What the sweep did: <see cref="Keep"/> is the setting it applied (0 = unlimited, and then nothing was swept),
/// <see cref="Games"/> the games that have sessions, <see cref="Sessions"/> the sessions whose raw frame or sensor
/// series were removed. Aggregates and segments are never touched.
/// </summary>
public sealed record SweepRetentionAck(int Keep, int Games, int Sessions);
@@ -0,0 +1,230 @@
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Settings;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
/// <summary>
/// Tools ▸ Database maintenance (P4 PR-7) over a scratch ledger and a fake Agent: the check and the backup read, a
/// backup never lands on the ledger itself, the sweep is the Agent's (asked, confirmed, never with an unlimited
/// setting), compaction waits for sessions to end, and every failure is a status line.
/// </summary>
public sealed class DatabaseMaintenanceViewModelTests
{
private sealed class Saver(string? path) : IFileSaver
{
public int Asked { get; private set; }
public string? PickSavePath(string filter, string suggestedName)
{
Asked++;
return path;
}
}
private sealed class Prompts(bool confirm) : IDatabaseMaintenancePrompts
{
public List<int> Confirmations { get; } = [];
public Task ShowAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default)
{
Confirmations.Add(keep);
return Task.FromResult(confirm);
}
}
private static DatabaseMaintenanceViewModel Vm(ScratchLedger s, FakeAgentLink agent, IFileSaver? saver = null, Prompts? prompts = null, MemorySettings? store = null) =>
new(new LedgerMaintenance(s.Db), s.Db.Path, agent, saver ?? new Saver(null), prompts ?? new Prompts(true), new RegisteredSettings(store ?? new MemorySettings()));
private static string TempFile() => Path.Combine(Path.GetTempPath(), "fl-maint-" + Guid.NewGuid().ToString("N") + ".db");
/// <summary>True when <paramref name="actual"/> is <paramref name="format"/> with any text in its placeholders.</summary>
private static bool MatchesFormat(string format, string actual)
{
string pattern = "^" + Regex.Replace(Regex.Escape(format), @"\\\{\d+\}", ".+", RegexOptions.None, TimeSpan.FromSeconds(1)) + "$";
return Regex.IsMatch(actual, pattern, RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
}
[Fact]
public async Task TheIntegrityCheckOfAHealthyLedgerSaysSo()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
DatabaseMaintenanceViewModel vm = Vm(s, new FakeAgentLink());
await vm.CheckIntegrityCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Integrity_Ok);
vm.IsBusy.Should().BeFalse();
}
[Fact]
public async Task ABackupGoesToTheChosenFile()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string target = TempFile();
try
{
DatabaseMaintenanceViewModel vm = Vm(s, new FakeAgentLink(), new Saver(target));
await vm.BackUpCommand.ExecuteAsync(null);
File.Exists(target).Should().BeTrue();
vm.Status.Should().Contain(target);
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
File.Delete(target);
}
}
[Fact]
public async Task ABackupOntoTheLedgerItselfIsRefusedAndTheLedgerIsUntouched()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
long before = new FileInfo(s.Db.Path).Length;
DatabaseMaintenanceViewModel vm = Vm(s, new FakeAgentLink(), new Saver(s.Db.Path.ToUpperInvariant()));
await vm.BackUpCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Backup_IsLedger);
File.Exists(s.Db.Path).Should().BeTrue("the save dialog's overwrite answer must never delete the live database");
new FileInfo(s.Db.Path).Length.Should().Be(before);
await vm.CheckIntegrityCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Integrity_Ok);
}
[Fact]
public async Task ACancelledSaveDialogDoesNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var saver = new Saver(null);
DatabaseMaintenanceViewModel vm = Vm(s, new FakeAgentLink(), saver);
await vm.BackUpCommand.ExecuteAsync(null);
saver.Asked.Should().Be(1);
vm.Status.Should().Be(Strings.Maintenance_Status_Ready);
}
[Fact]
public async Task AnUnlimitedRetentionSweepsNothingAndAsksNobody()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink();
var prompts = new Prompts(true);
var store = new MemorySettings();
store.Rows[SettingsRegistry.RetentionRawSessionsPerGame.Key] = "0";
DatabaseMaintenanceViewModel vm = Vm(s, agent, prompts: prompts, store: store);
await vm.SweepCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Sweep_Unlimited);
prompts.Confirmations.Should().BeEmpty();
agent.Sent.Should().BeEmpty();
}
[Fact]
public async Task WithNoAgentTheSweepSaysWhoseItIs()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink { IsConnected = false };
var prompts = new Prompts(true);
DatabaseMaintenanceViewModel vm = Vm(s, agent, prompts: prompts);
await vm.SweepCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Sweep_NoAgent);
prompts.Confirmations.Should().BeEmpty("nothing is asked that cannot be done");
}
[Fact]
public async Task ADeclinedSweepSendsNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink();
var prompts = new Prompts(false);
DatabaseMaintenanceViewModel vm = Vm(s, agent, prompts: prompts);
await vm.SweepCommand.ExecuteAsync(null);
prompts.Confirmations.Should().Equal(20);
agent.Sent.Should().BeEmpty();
vm.Status.Should().Be(Strings.Maintenance_Status_Ready);
}
[Fact]
public async Task AConfirmedSweepIsTheAgentsAndItsCountIsShown()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink
{
Answer = static (type, _) => FakeAgentLink.Envelope(IpcMessageType.SweepRetentionAck, new SweepRetentionAck(20, 4, 9)),
};
DatabaseMaintenanceViewModel vm = Vm(s, agent);
await vm.SweepCommand.ExecuteAsync(null);
agent.Sent.Should().ContainSingle().Which.Type.Should().Be(IpcMessageType.SweepRetention);
vm.Status.Should().Be(string.Format(CultureInfo.CurrentCulture, CompositeFormat.Parse(Strings.Maintenance_Sweep_Done_Format), 9, 4, 20));
}
[Fact]
public async Task AnAgentThatPredatesTheSweepIsNamedAsSuch()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink
{
Answer = static (_, _) => throw new IpcRequestException(IpcErrorCode.UnknownType, "unknown message type SweepRetention"),
};
DatabaseMaintenanceViewModel vm = Vm(s, agent);
await vm.SweepCommand.ExecuteAsync(null);
vm.Status.Should().Be(Strings.Maintenance_Sweep_AgentTooOld);
vm.IsBusy.Should().BeFalse();
}
[Fact]
public async Task CompactingWaitsWhileASessionRuns()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var agent = new FakeAgentLink
{
Answer = static (type, _) => FakeAgentLink.Envelope(IpcMessageType.StatusAck, new StatusAck("capturing", null, 1, [])),
};
DatabaseMaintenanceViewModel vm = Vm(s, agent);
await vm.CompactCommand.ExecuteAsync(null);
agent.Sent.Should().ContainSingle().Which.Type.Should().Be(IpcMessageType.GetStatus, "a fresh status, not the connection's cached one");
vm.Status.Should().Be(Strings.Maintenance_Compact_SessionRunning);
}
[Fact]
public async Task CompactingRunsWhenTheAgentIsIdleOrAbsent()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var idle = new FakeAgentLink
{
Answer = static (_, _) => FakeAgentLink.Envelope(IpcMessageType.StatusAck, new StatusAck("idle", null, null, [])),
};
DatabaseMaintenanceViewModel withIdleAgent = Vm(s, idle);
await withIdleAgent.CompactCommand.ExecuteAsync(null);
MatchesFormat(Strings.Maintenance_Compact_Done_Format, withIdleAgent.Status).Should().BeTrue(withIdleAgent.Status);
DatabaseMaintenanceViewModel withoutAgent = Vm(s, new FakeAgentLink { IsConnected = false });
await withoutAgent.CompactCommand.ExecuteAsync(null);
MatchesFormat(Strings.Maintenance_Compact_Done_Format, withoutAgent.Status).Should().BeTrue(withoutAgent.Status);
}
}
@@ -251,6 +251,30 @@ public sealed class PagesLoadTests
/// Content, the library's does not — so this turns red the day upstream renders it, which is the day the
/// override comes out rather than staying by habit.
/// </summary>
/// <summary>Tools ▸ Database maintenance's dialog body (P4 PR-7) under the real dictionaries: its icons, the converter key, every binding.</summary>
[Fact]
public async Task TheDatabaseMaintenanceDialogLoads()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var vm = new DatabaseMaintenanceViewModel(new LedgerMaintenance(s.Db), s.Db.Path, new NoAgent(), new NoSaver(), new NoMaintenancePrompts(), new RegisteredSettings(new SqliteSettingsStore(s.Db)));
double width = await OnStaAsync(() =>
{
var content = new Dialogs.DatabaseMaintenanceContent(vm);
Render(content);
return content.ActualWidth;
});
width.Should().BeGreaterThan(0);
}
private sealed class NoMaintenancePrompts : IDatabaseMaintenancePrompts
{
public Task ShowAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<bool> ConfirmSweepAsync(int keep, CancellationToken ct = default) => Task.FromResult(false);
}
[Fact]
public async Task TheInfoBarTemplateRendersItsContent()
{
@@ -128,7 +128,7 @@ public sealed class AgentCommandHandlerTests : IAsyncDisposable
public int RulesUpdates { get; set; }
}
private async Task<Harness> BuildAsync(bool consented = true, string? disclosureVersion = null)
private async Task<Harness> BuildAsync(bool consented = true, string? disclosureVersion = null, Func<CancellationToken, ValueTask<SweepRetentionAck>>? sweep = null)
{
_db ??= await LedgerDatabase.OpenAsync(Path.Combine(_dir, LedgerPaths.DatabaseFileName), ct: Ct).ConfigureAwait(false);
var consent = new SqliteGameConsentStore(_db);
@@ -153,7 +153,7 @@ public sealed class AgentCommandHandlerTests : IAsyncDisposable
Harness h = null!;
var handler = new AgentCommandHandler(games, consent, guard, identity, orchestrator, pause, lifetime,
_ => { h.RulesUpdates++; return ValueTask.FromResult("AlreadyCurrent"); },
disclosureVersion, new FakeClock());
disclosureVersion, new FakeClock(), sweepRetention: sweep);
h = new Harness
{
Handler = handler,
@@ -168,6 +168,33 @@ public sealed class AgentCommandHandlerTests : IAsyncDisposable
return h;
}
[Fact]
public async Task SweepRetentionRunsTheComposedSweepAndAnswersItsCounts()
{
int runs = 0;
Harness h = await BuildAsync(sweep: _ =>
{
runs++;
return ValueTask.FromResult(new SweepRetentionAck(20, 3, 7));
}).ConfigureAwait(true);
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.SweepRetention, new SweepRetentionRequest()).ConfigureAwait(true);
ack.Type.Should().Be(IpcMessageType.SweepRetentionAck);
IpcCodec.Payload<SweepRetentionAck>(ack).Should().Be(new SweepRetentionAck(20, 3, 7));
runs.Should().Be(1);
}
[Fact]
public async Task WithNoSweepComposedSweepRetentionIsNotACommandThisHalfAnswers()
{
Harness h = await BuildAsync().ConfigureAwait(true);
byte[]? ack = await h.Handler.HandleAsync(IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.SweepRetention, "1", new SweepRetentionRequest())), Ct).ConfigureAwait(true);
ack.Should().BeNull("the request handler then answers UnknownType, which the App reads as an Agent that predates the sweep");
}
private static async Task<IpcEnvelope> AskAsync<T>(AgentCommandHandler handler, string type, T payload)
where T : class
{
@@ -38,6 +38,17 @@ internal sealed class FakeSessionRepository : ISessionRepository
return ValueTask.FromResult(SweptPerCall);
}
/// <summary>Every keep an all-games sweep was asked for (P4 PR-7), and the result it answers.</summary>
public List<int> SweepAlls { get; } = [];
public RetentionSweepResult SweepAllResult { get; set; } = new(0, 0);
public ValueTask<RetentionSweepResult> SweepRetentionAllAsync(int keep, CancellationToken ct = default)
{
SweepAlls.Add(keep);
return ValueTask.FromResult(SweepAllResult);
}
public ValueTask<FrameBlobs?> FindFramesAsync(long sessionId, CancellationToken ct = default) =>
ValueTask.FromResult(sessionId >= 1 && sessionId <= Stored.Count ? Stored[(int)sessionId - 1].Frames : null);
@@ -0,0 +1,54 @@
using FluentAssertions;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Application.Settings;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.Application.Tests.Recording;
/// <summary>The on-demand sweep (P4 PR-7): the Agent's own setting is the keep, unlimited sweeps nothing, and the repository's count is the answer.</summary>
public sealed class RetentionSweepTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class Store : ISettingsStore
{
public Dictionary<string, string> Rows { get; } = new(StringComparer.Ordinal);
public ValueTask<string?> GetAsync(string key, CancellationToken ct = default) => ValueTask.FromResult(Rows.GetValueOrDefault(key));
public ValueTask SetAsync(string key, string value, CancellationToken ct = default)
{
Rows[key] = value;
return ValueTask.CompletedTask;
}
}
[Fact]
public async Task UnlimitedRetentionSweepsNothingAndSaysSo()
{
var sessions = new FakeSessionRepository();
var store = new Store();
store.Rows[SettingsRegistry.RetentionRawSessionsPerGame.Key] = "0";
SweepRetentionAck ack = await new RetentionSweep(sessions, new RegisteredSettings(store)).RunAsync(Ct);
ack.Should().Be(new SweepRetentionAck(0, 0, 0));
sessions.SweepAlls.Should().BeEmpty("0 is unlimited, and a keep of zero must never reach the repository");
}
[Fact]
public async Task TheSettingIsTheKeepAndTheRepositorysCountIsTheAnswer()
{
var sessions = new FakeSessionRepository { SweepAllResult = new RetentionSweepResult(3, 11) };
var store = new Store();
SweepRetentionAck byDefault = await new RetentionSweep(sessions, new RegisteredSettings(store)).RunAsync(Ct);
store.Rows[SettingsRegistry.RetentionRawSessionsPerGame.Key] = "5";
SweepRetentionAck set = await new RetentionSweep(sessions, new RegisteredSettings(store)).RunAsync(Ct);
byDefault.Should().Be(new SweepRetentionAck(20, 3, 11), "the registry's default is 20");
set.Should().Be(new SweepRetentionAck(5, 3, 11));
sessions.SweepAlls.Should().Equal(20, 5);
}
}
@@ -0,0 +1,151 @@
using Dapper;
using FluentAssertions;
using FrameLedger.Application.Persistence;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Blobs;
using FrameLedger.Infrastructure.Persistence;
namespace FrameLedger.Infrastructure.Tests.Persistence;
/// <summary>
/// Tools ▸ Database maintenance's App-side half (P4 PR-7): the integrity check answers SQLite's "ok", a backup is a
/// complete ledger that never overwrites a file and never targets the ledger itself, and compacting gives the space of
/// swept blobs back to the disk.
/// </summary>
public sealed class LedgerMaintenanceTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly ExecutableFingerprint _game = new() { ExePath = @"C:\Games\M\m.exe", SizeBytes = 1, MtimeUnixMs = 2 };
private static string TempFile() => Path.Combine(Path.GetTempPath(), "fl-backup-" + Guid.NewGuid().ToString("N") + ".db");
private static SessionRow Row(long gameId, long snapshotId, DateTimeOffset started) => new()
{
SessionGuid = Guid.NewGuid(),
GameId = gameId,
SnapshotId = snapshotId,
StartedAt = started,
EndedAt = started.AddSeconds(90),
QpcEpoch = 1,
QpcFrequency = 10_000_000,
Tier = CaptureTier.Hooked,
Mode = CaptureMode.Launch,
ExitStatus = ExitStatus.Normal,
FrameCount = 5400,
AppFrameCount = 5400,
DisplayedFrameCount = 5400,
DroppedFrames = 0,
FgMode = "none",
FgSource = "none",
RtFlag = "no",
RtSource = "measured",
NativeFps = 60.0,
};
private static FrameBlobs Frames(int n) => new()
{
Codec = SeriesCodec.Tag,
SampleCount = n,
FrameTimes = SeriesCodec.EncodeFloat32([.. Enumerable.Range(0, n).Select(static i => 16f + (i % 97 / 10f))]),
FrameFlags = SeriesCodec.EncodeBytes([.. Enumerable.Range(0, n).Select(static i => (byte)(i % 7))]),
LatencyUs = SeriesCodec.EncodeUInt32([.. Enumerable.Range(0, n).Select(static i => (uint)(12_000 + (i % 1_009)))]),
};
private static async Task<(long GameId, long SnapshotId)> SeedAsync(LedgerDatabase db)
{
long gameId = (await new SqliteGameRepository(db).EnsureAsync(_game, "M", Ct).ConfigureAwait(false)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(db).EnsureAsync(new HardwareSnapshot { GpuName = "GPU", CpuName = "CPU" }, DateTimeOffset.UnixEpoch, Ct).ConfigureAwait(false);
return (gameId, snapshotId);
}
[Fact]
public async Task AFreshLedgerIsHealthy()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
IReadOnlyList<string> lines = await new LedgerMaintenance(f.Db).CheckIntegrityAsync(Ct);
lines.Should().Equal("ok");
LedgerMaintenance.IsHealthy(lines).Should().BeTrue();
LedgerMaintenance.IsHealthy(["*** in database main ***", "Page 7 is never used"]).Should().BeFalse();
}
[Fact]
public async Task ABackupIsACompleteLedgerWithTheSameRows()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f.Db);
await new SqliteSessionRepository(f.Db).InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, DateTimeOffset.UnixEpoch), Frames = Frames(100) }, Ct);
string backup = TempFile();
try
{
await new LedgerMaintenance(f.Db).BackupAsync(backup, Ct);
LedgerDatabase copy = await LedgerDatabase.OpenAsync(backup, ct: Ct);
await using (copy)
{
copy.SchemaVersion.Should().Be(f.Db.SchemaVersion);
copy.Migration.Should().Be(MigrationOutcome.AlreadyCurrent, "the copy is already at the ledger's schema");
long sessions = await copy.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM sessions", cancellationToken: ct)), Ct);
long frames = await copy.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM frame_blobs", cancellationToken: ct)), Ct);
(sessions, frames).Should().Be((1L, 1L));
LedgerMaintenance.IsHealthy(await new LedgerMaintenance(copy).CheckIntegrityAsync(Ct)).Should().BeTrue();
}
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
File.Delete(backup);
}
}
[Fact]
public async Task ABackupNeverOverwritesAFileAndNeverTargetsTheLedgerItself()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var maintenance = new LedgerMaintenance(f.Db);
string existing = TempFile();
await File.WriteAllTextAsync(existing, "someone's file", Ct);
try
{
Func<Task> overwrite = async () => await maintenance.BackupAsync(existing, Ct).ConfigureAwait(false);
await overwrite.Should().ThrowAsync<IOException>();
(await File.ReadAllTextAsync(existing, Ct)).Should().Be("someone's file");
}
finally
{
File.Delete(existing);
}
foreach (string ledgerFile in new[] { f.Path, f.Path + "-wal", f.Path.ToUpperInvariant() })
{
Func<Task> self = async () => await maintenance.BackupAsync(ledgerFile, Ct).ConfigureAwait(false);
(await self.Should().ThrowAsync<IOException>()).Which.Message.Should().Contain("the ledger itself");
}
LedgerMaintenance.IsHealthy(await maintenance.CheckIntegrityAsync(Ct)).Should().BeTrue("nothing touched the ledger");
}
[Fact]
public async Task CompactingGivesTheSpaceOfSweptBlobsBackToTheDisk()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f.Db);
var sessions = new SqliteSessionRepository(f.Db);
for (int i = 0; i < 12; i++)
{
await sessions.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, DateTimeOffset.UnixEpoch.AddHours(i)), Frames = Frames(40_000) }, Ct);
}
RetentionSweepResult swept = await sessions.SweepRetentionAllAsync(keep: 2, Ct);
swept.Sessions.Should().Be(10);
LedgerCompaction result = await new LedgerMaintenance(f.Db).CompactAsync(Ct);
result.BytesAfter.Should().BeLessThan(result.BytesBefore / 2, "ten of twelve raw series were swept, and VACUUM plus a truncating checkpoint returns their pages");
LedgerMaintenance.IsHealthy(await new LedgerMaintenance(f.Db).CheckIntegrityAsync(Ct)).Should().BeTrue();
(await sessions.ListRecentAsync(20, Ct)).Should().HaveCount(12, "compacting changes no row");
}
}
@@ -198,6 +198,45 @@ public sealed class SqliteSessionRepositoryTests
sensors.Should().Be(2);
}
[Fact]
public async Task SweepingEveryGameKeepsTheNewestNOfEachAndCountsWhatWent()
{
// P4 PR-7: Tools ▸ Database maintenance's sweep, the per-game rule above applied to every game in one statement.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long first, long snapshotId) = await SeedAsync(f);
long second = (await new SqliteGameRepository(f.Db).EnsureAsync(new ExecutableFingerprint { ExePath = @"C:\Games\U\u.exe", SizeBytes = 3, MtimeUnixMs = 4 }, "U", Ct)).Id;
var repo = new SqliteSessionRepository(f.Db);
var firstIds = new List<long>();
for (int i = 0; i < 4; i++)
{
firstIds.Add(await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(first, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(i)), Frames = Frames(10) }, Ct));
}
// The second game's oldest session carries sensors only (a recording nothing measured): swept, and counted once.
await repo.InsertFinalizedAsync(new FinalizedSession
{
Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch),
Sensors = [new SensorBlob { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([1f]) }],
}, Ct);
long secondNew = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(9)), Frames = Frames(10) }, Ct);
await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(10)), Frames = Frames(10) }, Ct);
RetentionSweepResult result = await repo.SweepRetentionAllAsync(keep: 2, Ct);
result.Should().Be(new RetentionSweepResult(Games: 2, Sessions: 3));
(await repo.FindFramesAsync(firstIds[0], Ct)).Should().BeNull();
(await repo.FindFramesAsync(firstIds[1], Ct)).Should().BeNull();
(await repo.FindFramesAsync(firstIds[2], Ct)).Should().NotBeNull("each game keeps its own newest two");
(await repo.FindFramesAsync(secondNew, Ct)).Should().NotBeNull();
long sensors = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM sensor_blobs", cancellationToken: ct)), Ct);
sensors.Should().Be(0);
(await repo.ListRecentAsync(10, Ct)).Should().HaveCount(7, "aggregates and segments are kept forever");
(await repo.SweepRetentionAllAsync(keep: 2, Ct)).Should().Be(new RetentionSweepResult(Games: 2, Sessions: 0), "a second sweep finds nothing left to remove");
Func<Task> zero = async () => await repo.SweepRetentionAllAsync(keep: 0, Ct).ConfigureAwait(false);
await zero.Should().ThrowAsync<ArgumentOutOfRangeException>("a keep of zero would delete every raw series; unlimited is the caller's to honour by not sweeping");
}
[Fact]
public async Task ListRecentIsNewestFirstAndBounded()
{