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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions docs/linux-port/performance-tracing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Slow-action tracing (issue #131)

Set `FILES_TRACE=1` before starting Files. Other values leave tracing disabled. The flag is read once per process;
disabled scopes do not allocate, read clocks, or queue records. Enabled tracing buffers at most 1,024 records,
drops records when full, and writes `[files-trace]` lines to stderr on a worker. Slow stderr must not stall the UI.
Buffered records can be lost at shutdown; this is diagnostic output, not an audit log.

For an authorised headless verification run, from the repository root:

```bash
FILES_TRACE=1 FILES_SANDBOX_DRIVES=scripts/linux/showcase-drives.txt \
nice -n 19 scripts/linux/headless-run.sh -s 40 -o /tmp/files-perf-actions -a /tmp/perf-actions.txt
```

Use only the private Xvfb harness and its throwaway HOME/session bus. Never use the real display, real home,
real desktop settings, or host inotify-limit changes. The harness captures stderr in `app.log` and cleans up
its processes. Default dry-run launches do not measure real process spawning; use a disposable fixture program
in the sandbox if actual spawn measurements are needed.

Each record carries `id`, `parent`, `operation`, elapsed `ms` (monotonic clock), completion `thread`, optional
`ui` flag, and `outcome`. Parent IDs follow async execution context. A thread ID identifies the completion
thread, not a thread occupied throughout an await. No paths, arguments, selected names, bus addresses,
message bodies, credentials, or process output are included.

| Operation | Measured boundary |
| --- | --- |
| `context-menu-build` | Item/background flyout opening through model building and awaited extension loading; excludes visible-frame latency and deferred submenu loading. |
| `open-with-load` | MIME lookup, application query and default lookup on a worker; excludes UI icon decoding/population. |
| `open-with-query` | Registry worker query, including candidate resolution. |
| `parsed-file-cache` | File identity check plus parsing on a miss; outcomes `hit`, `miss`, `missing-or-unreadable`. |
| `service-menu-scan` | Directory scan, cached parsing and selection filtering; MIME lookup precedes this scope. |
| `tag-db-save` | Actual atomic database save attempt; unchanged tags/empty missing entries produce no save record. |
| `dbus-connect` | Session/system connection attempt, including its timeout. |
| `dbus.*` | Outbound call to reply/fault, grouped by platform feature. Caller timeouts can occur before this record; a call that never completes has no completion record. |
| `process-spawn` | `Process.Start` only, across platform runners. |
| `process-wrapper-exit` | Detached-launch wrapper wait, not external application readiness. |
| `folder-enumeration` | Batch enumerator lifetime, including consumer time between batches. |
| `folder-enumeration-batch` | Directory entries/metadata read on a worker, excluding consumer/UI rendering time. |

`completed-or-unwound` means the scope ended, including exception/cancellation paths; it does not claim success.
D-Bus records explicitly report `reply`/`fault`. Correlate caller logs to distinguish cancellations/timeouts.

Application, association and MIME mapping caches check device/inode/mode/size/nanosecond mtime on every use.
Atomic replacements, edits, removals and user overrides are visible on the next query without watcher resources
or an invalidation delay. Directory scans still discover newly installed entries, including nested application
entries. Caches are instance/culture specific and bounded to 4,096 parsed files each. KDE menu parsing uses
no-follow identities; launch-time strict parsing and identity checks remain independent of this display cache.
Open With populates on pointer entry or keyboard focus, with a localized loading placeholder, and queries run
off the UI thread. Tag edits use one ordered background write queue; failed database saves stay dirty for retry.

Watcher degradation is logged once per watcher, including the polling interval and exception type (or forced
polling), without a folder path. Existing post-operation refresh hooks also refresh polling-backed listings,
so app create/rename/paste/trash/restore actions need not wait for the normal two-second external-change poll.

## Pending private Xvfb checks

1. Repeat file and background right-clicks cold/warm, including mouse and keyboard Open With activation.
Confirm the loading placeholder resolves, cancellation on closing/navigation is safe, applications/default
labels remain correct, and registry work reports `ui=False`. Compare menu/query/scan timings (median/p95).
2. Seed sandbox application associations and KDE service menus; add, edit, atomically replace and remove them
between queries. Confirm overrides, Hidden/NoDisplay, removal lists, localization, selection filtering and
fresh execution-time validation still behave correctly.
3. Browse a large tagged/untagged fixture directory repeatedly. Confirm warm reads do not emit tag saves;
edit/remove tags rapidly and reopen Files to check the final database/xattr values and write ordering.
4. Inject a test watcher factory using `FolderWatcherOptions.ForcePolling` (do not alter host limits). Verify
one fallback log, prompt create/rename/copy/move/trash/restore updates after our operations, stable selection,
no duplicate rows when the next poll arrives, and ordinary polling of external fixture edits. Check native
watcher behaviour separately. The production app has no force-polling environment switch.
5. Use only private mock D-Bus services and a harmless disposable process fixture to confirm trace output for
delayed replies, faults, spawns and wrapper exit. Compare tracing off/on responsiveness; verify off produces
no trace records. Navigation should emit enumeration and batch timings; no record should expose fixture paths.

These checks were not run by the implementation agent. Xvfb software rendering does not establish real KDE
compositor/GPU performance or production D-Bus daemon latency.
1 change: 1 addition & 0 deletions src/Files.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public App()
AppDomain.CurrentDomain.ProcessExit += static (_, _) =>
SafetyExtensions.IgnoreExceptions(() => Ioc.Default.GetService<FileLoggerProvider>()?.TryCompleteAndFlush(TimeSpan.FromSeconds(2)));
#if !WINDOWS
AppDomain.CurrentDomain.ProcessExit += static (_, _) => FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult();
AppDomain.CurrentDomain.ProcessExit += static (_, _) => SafetyExtensions.IgnoreExceptions(ArchiveOpenTempStore.CleanupCurrentProcess);
_ = Task.Run(ArchiveOpenTempStore.CleanupStale);
#endif
Expand Down
11 changes: 8 additions & 3 deletions src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,14 @@ private static async Task LoadOpenWithItemsAsync(ContextMenuFlyoutItemViewModel
var registry = Ioc.Default.GetRequiredService<IApplicationRegistry>();
var launcher = Ioc.Default.GetRequiredService<ILauncherService>();

var mime = await mimeTypes.GetMimeTypeAsync(path, cancellationToken);
var apps = await registry.GetApplicationsForMimeTypeAsync(mime, cancellationToken);
var defaultApp = await registry.GetDefaultApplicationAsync(mime, cancellationToken);
var (apps, defaultApp) = await Task.Run(async () =>
{
using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("open-with-load", false);
var mime = await mimeTypes.GetMimeTypeAsync(path, cancellationToken).ConfigureAwait(false);
var applications = await registry.GetApplicationsForMimeTypeAsync(mime, cancellationToken).ConfigureAwait(false);
var preferred = await registry.GetDefaultApplicationAsync(mime, cancellationToken).ConfigureAwait(false);
return (applications, preferred);
}, cancellationToken);
var items = model.Items ??= [];

foreach (var app in apps)
Expand Down
6 changes: 6 additions & 0 deletions src/Files.App/Data/Items/ListedItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ public string[]? FileTags
get => fileTags;
set
{
#if !WINDOWS
if (fileTags is not null && fileTags.SequenceEqual(value, StringComparer.Ordinal))
return;
#endif
// fileTags is null when the item is first created
var fileTagsInitialized = fileTags is not null;
if (SetProperty(ref fileTags, value))
Expand All @@ -124,8 +128,10 @@ public string[]? FileTags
if (fileTagsInitialized)
{
var path = this.GetRequiredPath();
#if WINDOWS
var dbInstance = FileTagsHelper.GetDbInstance();
dbInstance.SetTags(path, FileFRN, value);
#endif
_ = FileTagsHelper.WriteFileTagAsync(path, value);
}

Expand Down
9 changes: 8 additions & 1 deletion src/Files.App/Platforms/Desktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,14 @@ public static int Main(string[] args)
}))
.Build();

host.Run();
try
{
host.Run();
}
finally
{
FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult();
}

SingleInstance?.DisposeAsync().AsTask().GetAwaiter().GetResult();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ namespace Files.App.ViewModels
public sealed partial class ShellViewModel
{
private Files.Platform.Abstractions.Watching.IFolderWatcher? _linuxWatcher;
public bool IsLinuxWatcherPolling => _linuxWatcher?.IsPolling == true;
private CancellationTokenSource? _linuxRefreshDebounce;
private readonly List<Files.Platform.Abstractions.Watching.IFolderWatcher> _linuxRepositoryWatchers = [];
private Action? _linuxTrashUnsubscribe;
Expand Down
4 changes: 4 additions & 0 deletions src/Files.App/Services/Settings/FileTagsSettingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,9 @@ private int GetTagIndex(string uid)

private void UntagAllFiles(string uid)
{
#if !WINDOWS
_ = FileTagsHelper.UntagAllFilesAsync(uid);
#else
var tagDoDelete = new string[] { uid };

foreach (var item in FileTagsHelper.GetDbInstance().GetAll())
Expand All @@ -198,6 +201,7 @@ private void UntagAllFiles(string uid)
item.Tags.Except(tagDoDelete).ToArray());
}
}
#endif
}

private IJsonSettingsSerializer GetJsonSettingsSerializer()
Expand Down
37 changes: 29 additions & 8 deletions src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

#if !WINDOWS
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using JsonSerializer = System.Text.Json.JsonSerializer;

Expand All @@ -17,27 +20,36 @@ public sealed partial class FileTagsDatabase
{
private readonly object _gate = new();
private Dictionary<string, TaggedFile>? _entries;
private bool _dirty;
private readonly string? _databasePath;

private static string DatabasePath
=> Path.Combine(Ioc.Default.GetRequiredService<Files.Platform.Abstractions.IAppDataPaths>().DataDirectory, "filetags.json");
public FileTagsDatabase() { }

internal FileTagsDatabase(string databasePath) => _databasePath = databasePath;

private string DatabasePath
=> _databasePath ?? Path.Combine(Ioc.Default.GetRequiredService<Files.Platform.Abstractions.IAppDataPaths>().DataDirectory, "filetags.json");

public void SetTags(string filePath, ulong? frn, string[] tags)
{
lock (_gate)
{
var entries = Load();
if (tags is [])
entries.Remove(filePath);
else
entries[filePath] = new TaggedFile { FilePath = filePath, Tags = tags };
var changed = tags.Length == 0
? entries.Remove(filePath)
: !entries.TryGetValue(filePath, out var current) || !current.Tags.SequenceEqual(tags, StringComparer.Ordinal);
if (!changed && !_dirty)
return;
if (tags.Length > 0 && changed)
entries[filePath] = new TaggedFile { FilePath = filePath, Tags = (string[])tags.Clone() };

Save(entries);
}
}

public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath)
{
if (newFilePath is null)
if (newFilePath is null || string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal))
return;

lock (_gate)
Expand All @@ -63,7 +75,7 @@ public string[] GetTags(string? filePath, ulong? frn)
return [];

lock (_gate)
return Load().TryGetValue(filePath, out var tagged) ? tagged.Tags : [];
return Load().TryGetValue(filePath, out var tagged) ? (string[])tagged.Tags.Clone() : [];
}

public IEnumerable<TaggedFile> GetAll()
Expand Down Expand Up @@ -92,6 +104,12 @@ public void Import(string json)
entries[tag.FilePath] = tag;
}

var current = Load();
if (!_dirty && current.Count == entries.Count && entries.All(pair =>
current.TryGetValue(pair.Key, out var existing) && existing.Frn == pair.Value.Frn &&
existing.Tags.SequenceEqual(pair.Value.Tags, StringComparer.Ordinal)))
return;

Save(entries);
}
}
Expand Down Expand Up @@ -131,7 +149,9 @@ private Dictionary<string, TaggedFile> Load()

private void Save(Dictionary<string, TaggedFile> entries)
{
using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("tag-db-save");
_entries = entries;
_dirty = true;

string? temp = null;
try
Expand All @@ -142,6 +162,7 @@ private void Save(Dictionary<string, TaggedFile> entries)
File.WriteAllText(temp, JsonSerializer.Serialize(entries.Values.ToList(), AppJsonSerializerContext.Default.ListTaggedFile));
File.Move(temp, path, overwrite: true);
temp = null;
_dirty = false;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Expand Down
100 changes: 85 additions & 15 deletions src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
#if !WINDOWS
using Files.Platform.Abstractions.Tags;
using Microsoft.Extensions.Logging;
using Windows.Storage;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Files.App.Utils.FileTags
{
Expand Down Expand Up @@ -35,29 +38,96 @@ public static string[] ReadFileTag(string filePath)
return GetDbInstance().GetTags(filePath, null);
}

public static Task<bool> WriteFileTagAsync(string filePath, string[] tag, CancellationToken cancellationToken = default)
public static Task<string[]> ReadAndUpdateFileTagsAsync(string filePath)
{
try
return EnqueueWrite(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var tags = ReadFileTag(filePath);
GetDbInstance().SetTags(filePath, null, tags);
return tags;
}, Array.Empty<string>());
}

GetDbInstance().SetTags(filePath, null, tag);
private static readonly object writeGate = new();
private static Task pendingWrite = Task.CompletedTask;

// Best effort: the database already holds the tags, so a file system without xattr support is not an error
var store = Ioc.Default.GetService<IFileTagsStore>();
if (store is not null)
public static Task<bool> WriteFileTagAsync(string filePath, string[] tag, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested) return Task.FromResult(false);
var tags = (string[])tag.Clone();
var store = Ioc.Default.GetService<IFileTagsStore>();
var settings = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
var names = settings.GetTagsByIds(tags)?.Select(x => x.Name).ToArray() ?? [];
return EnqueueWrite(() => !cancellationToken.IsCancellationRequested && WriteTags(filePath, tags, names, store), false);
}

public static Task<bool> UntagAllFilesAsync(string uid)
{
var store = Ioc.Default.GetService<IFileTagsStore>();
var settings = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
var namesById = settings.FileTagList.ToDictionary(tag => tag.Uid, tag => tag.Name);
return EnqueueWrite(() =>
{
var succeeded = true;
foreach (var item in GetDbInstance().GetAll())
{
var settings = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
var names = settings.GetTagsByIds(tag)?.Select(x => x.Name).ToArray() ?? [];
if (!store.WriteTags(filePath, names))
App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath));
if (!item.Tags.Contains(uid)) continue;
var tags = item.Tags.Where(tag => tag != uid).ToArray();
var names = tags.Where(namesById.ContainsKey).Select(tag => namesById[tag]).ToArray();
succeeded &= WriteTags(item.FilePath, tags, names, store);
}
return succeeded;
}, false);
}

public static async Task DrainPendingWritesAsync()
{
while (true)
{
Task write;
lock (writeGate) write = pendingWrite;
await write.ConfigureAwait(false);
lock (writeGate)
if (ReferenceEquals(write, pendingWrite)) return;
}
}

return Task.FromResult(true);
private static bool WriteTags(string filePath, string[] tags, string[] names, IFileTagsStore? store)
{
try
{
GetDbInstance().SetTags(filePath, null, tags);
if (store is not null && !store.WriteTags(filePath, names))
App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath));
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException))
{
return Task.FromResult(false);
App.Logger?.LogWarning(ex, "Could not write file tags.");
return false;
}
}

private static Task<T> EnqueueWrite<T>(Func<T> action, T failureResult)
{
lock (writeGate)
{
var previous = pendingWrite;
var write = Task.Run(async () =>
{
await previous.ConfigureAwait(false);
try
{
return action();
}
catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException))
{
App.Logger?.LogWarning(ex, "Could not write file tags.");
return failureResult;
}
});
pendingWrite = write;
return write;
}
}

Expand Down
Loading
Loading