From 66db17ce400c0447a911d76b40ba716ab81dfc0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Sat, 10 Oct 2026 12:06:55 +0300 Subject: [PATCH 1/3] Preserve fallback tags after failed xattr writes Co-Authored-By: GPT-6.1-sol (OpenAI Codex) Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Data/Items/ListedItem.FileTags.cs | 4 + .../Utils/FileTags/FileTagsHelper.Linux.cs | 27 +++- .../Tags/FileTagsHelperTests.cs | 133 ++++++++++++++++-- 3 files changed, 153 insertions(+), 11 deletions(-) diff --git a/src/Files.App/Data/Items/ListedItem.FileTags.cs b/src/Files.App/Data/Items/ListedItem.FileTags.cs index 24f106c3228b..a25e9836004a 100644 --- a/src/Files.App/Data/Items/ListedItem.FileTags.cs +++ b/src/Files.App/Data/Items/ListedItem.FileTags.cs @@ -64,6 +64,10 @@ public void SetLoadedFileTags(string[] tags, long? expectedRevision = null) #if WINDOWS FileTags = tags; #else + // A deferred snapshot may predate an edit made through another item for this path. + if (FileTagsHelper.TryReadDatabaseFallback(this.GetRequiredPath(), out var fallbackTags)) + tags = fallbackTags; + if (fileTags is not null && fileTags.SequenceEqual(tags, StringComparer.Ordinal)) return; diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs index 8901d41e6c8b..62d535888fca 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs @@ -5,6 +5,7 @@ using Files.Platform.Abstractions.Tags; using Microsoft.Extensions.Logging; using System; +using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -15,11 +16,31 @@ namespace Files.App.Utils.FileTags // Files stores tag UIDs internally, so names are translated through the tag list; xattr tags with an unknown name are ignored. public static partial class FileTagsHelper { + private static readonly ConcurrentDictionary failedXattrWrites = new(StringComparer.Ordinal); + + internal static bool TryReadDatabaseFallback(string filePath, out string[] tags) + { + if (failedXattrWrites.ContainsKey(filePath)) + { + tags = GetDbInstance().GetTags(filePath, null); + return true; + } + tags = []; + return false; + } + public static string[] ReadFileTag(string filePath) { + if (TryReadDatabaseFallback(filePath, out var tags)) + return tags; + var store = Ioc.Default.GetService(); var names = store?.ReadTags(filePath); + // A write may have failed while the attribute was being read. + if (TryReadDatabaseFallback(filePath, out tags)) + return tags; + if (names is { Count: > 0 }) { var settings = Ioc.Default.GetRequiredService(); @@ -109,7 +130,11 @@ private static bool WriteTags(string filePath, string[] tags, string[] names, IF try { GetDbInstance().SetTags(filePath, null, tags); - if (store is not null && !store.WriteTags(filePath, names)) + // Keep the DB authoritative even when a readable attribute could not be updated or removed. + failedXattrWrites[filePath] = 0; + if (store is not null && store.WriteTags(filePath, names)) + failedXattrWrites.TryRemove(filePath, out _); + else App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath)); return true; } diff --git a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs index 40a47d66645a..c2684ac462b2 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs @@ -4,6 +4,7 @@ using Files.App.Utils; using Files.App.Utils.FileTags; using Files.Platform.Abstractions.Tags; +using Files.Platform.Linux.Tags; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; @@ -90,14 +91,17 @@ public async Task BulkDeletion_SerializesPropertyLoadingReadAndDatabaseUpdate(bo } [TestMethod] - [DataRow(true, false)] - [DataRow(false, false)] - [DataRow(true, true)] - [DataRow(false, true)] - public async Task EditsAcrossItems_MergeInsideQueueWithoutDroppingPendingTags(bool supportsXattrs, bool secondItemLoaded) + [DataRow(true, true, false)] + [DataRow(false, false, false)] + [DataRow(true, false, false)] + [DataRow(true, true, true)] + [DataRow(false, false, true)] + [DataRow(true, false, true)] + public async Task EditsAcrossItems_MergeInsideQueueWithoutDroppingPendingTags(bool supportsXattrs, bool writesSucceed, bool secondItemLoaded) { using var fixture = new TagFixture(); fixture.Store.SupportsXattrs = supportsXattrs; + fixture.Store.WritesSucceed = writesSucceed; fixture.Store.Tags["/preset"] = ["A"]; FileTagsHelper.GetDbInstance().SetTags("/preset", null, ["a"]); _ = FileTagsHelper.WriteFileTagAsync("/blocked", ["a"]); @@ -117,7 +121,7 @@ public async Task EditsAcrossItems_MergeInsideQueueWithoutDroppingPendingTags(bo await Task.WhenAll(firstEdit, secondEdit).WaitAsync(TimeSpan.FromSeconds(10)); CollectionAssert.AreEqual(new[] { "a", "b", "c" }, secondItem.FileTags); CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags("/preset", null)); - if (supportsXattrs) + if (supportsXattrs && writesSucceed) CollectionAssert.AreEqual(new[] { "A", "B", "C" }, fixture.Store.Tags["/preset"]); } @@ -204,6 +208,105 @@ public async Task EditOfUntaggedItem_ReachesXattrAndSurvivesRelaunch() CollectionAssert.AreEqual(new[] { "b" }, FileTagsHelper.ReadFileTag("/fresh")); } + [TestMethod] + public async Task FailedXattrWrite_LoadsAndEditsUseDatabaseUntilSyncSucceeds() + { + using var fixture = new TagFixture(); + const string path = "/read-only"; + fixture.Store.Tags[path] = ["A"]; + fixture.Store.WritesSucceed = false; + CollectionAssert.AreEqual(new[] { "a" }, FileTagsHelper.ReadFileTag(path)); + + Assert.IsTrue(await FileTagsHelper.WriteFileTagAsync(path, ["a", "b"])); + CollectionAssert.AreEqual(new[] { "A" }, fixture.Store.ReadTags(path).ToArray()); + CollectionAssert.AreEqual(new[] { "a", "b" }, FileTagsHelper.ReadFileTag(path)); + CollectionAssert.AreEqual(new[] { "a", "b" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, + await FileTagsHelper.EditFileTagsAsync(path, tags => [.. tags, "c"])); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null)); + + fixture.Store.WritesSucceed = true; + CollectionAssert.AreEqual(new[] { "b", "c" }, + await FileTagsHelper.EditFileTagsAsync(path, tags => tags.Where(uid => uid != "a").ToArray())); + CollectionAssert.AreEqual(new[] { "B", "C" }, fixture.Store.Tags[path]); + fixture.Store.Tags[path] = ["A"]; + CollectionAssert.AreEqual(new[] { "a" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + } + + [TestMethod] + public async Task FailedXattrRemoval_EmptyDatabaseRemainsAuthoritative() + { + using var fixture = new TagFixture(); + const string path = "/read-only-removal"; + fixture.Store.Tags[path] = ["A"]; + FileTagsHelper.GetDbInstance().SetTags(path, null, ["a"]); + fixture.Store.WritesSucceed = false; + + Assert.IsTrue(await FileTagsHelper.UntagAllFilesAsync("a")); + Assert.AreEqual(0, (await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)).Length); + Assert.AreEqual(0, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null).Length); + CollectionAssert.AreEqual(new[] { "b" }, await FileTagsHelper.EditFileTagsAsync(path, tags => [.. tags, "b"])); + CollectionAssert.AreEqual(new[] { "A" }, fixture.Store.Tags[path]); + } + + [TestMethod] + public async Task FailedXattrWrite_DeferredSnapshotOnAnotherItemUsesDatabase() + { + using var fixture = new TagFixture(); + const string path = "/read-only-deferred"; + fixture.Store.Tags[path] = ["A"]; + fixture.Store.WritesSucceed = false; + var loadingItem = new ListedItem { ItemPath = path }; + var editingItem = new ListedItem { ItemPath = path }; + var revision = loadingItem.FileTagsRevision; + var snapshot = await FileTagsHelper.ReadAndUpdateFileTagsAsync(path); + + await editingItem.EditFileTagsAsync(tags => [.. tags, "b"]); + loadingItem.SetLoadedFileTags(snapshot, revision); + CollectionAssert.AreEqual(new[] { "a", "b" }, loadingItem.FileTags); + await loadingItem.EditFileTagsAsync(tags => [.. tags, "c"]); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, loadingItem.FileTags); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null)); + } + + [TestMethod] + public async Task ReadOnlyFile_ReadableXattrCannotOverwriteDatabaseFallback() + { + if (!OperatingSystem.IsLinux()) + { + Assert.Inconclusive("Requires Linux file permissions and extended attributes."); + return; + } + + var store = new XattrFileTagsStore(); + using var fixture = new TagFixture(store); + var path = Path.Combine(Path.GetDirectoryName(fixture.DatabasePath)!, "read-only.txt"); + File.WriteAllText(path, "tags"); + if (!store.WriteTags(path, ["A"])) + Assert.Inconclusive("The test file system has no user xattr support."); + + File.SetUnixFileMode(path, UnixFileMode.UserRead); + try + { + if (store.WriteTags(path, ["B"])) + Assert.Inconclusive("The current user can bypass read-only file permissions."); + CollectionAssert.AreEqual(new[] { "A" }, store.ReadTags(path).ToArray()); + + var item = new ListedItem { ItemPath = path }; + await item.EditFileTagsAsync(tags => [.. tags, "b"]); + CollectionAssert.AreEqual(new[] { "a", "b" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + await item.EditFileTagsAsync(tags => [.. tags, "c"]); + + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, item.FileTags); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null)); + CollectionAssert.AreEqual(new[] { "A" }, store.ReadTags(path).ToArray()); + } + finally + { + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + private sealed class TagFixture : IDisposable { private readonly string root = Path.Combine(Path.GetTempPath(), "files-tags-queue-" + Guid.NewGuid().ToString("N")); @@ -212,11 +315,11 @@ private sealed class TagFixture : IDisposable public BlockingTagStore Store { get; } = new(); public TagSettings Settings { get; } = new(); - public TagFixture() + public TagFixture(IFileTagsStore? store = null) { Directory.CreateDirectory(root); FileTagsHelper.Database = new FileTagsDatabase(DatabasePath); - services = new ServiceCollection().AddSingleton(Store) + services = new ServiceCollection().AddSingleton(store ?? Store) .AddSingleton(Settings).BuildServiceProvider(); Ioc.Default.Services = services; } @@ -240,6 +343,7 @@ private sealed class BlockingTagStore : IFileTagsStore public ManualResetEventSlim Release { get; } = new(); public Dictionary Tags { get; } = new(); public bool SupportsXattrs { get; set; } = true; + public bool WritesSucceed { get; set; } = true; public bool BlockReads { get; set; } public TaskCompletionSource ReadEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ManualResetEventSlim ReadRelease { get; } = new(); @@ -259,7 +363,7 @@ public bool WriteTags(string path, IReadOnlyList tags) Entered.SetResult(); if (!Release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } - if (!SupportsXattrs) return false; + if (!SupportsXattrs || !WritesSucceed) return false; Tags[path] = tags.ToArray(); return true; } @@ -278,7 +382,16 @@ namespace Files.App.Utils.FileTags { public static partial class FileTagsHelper { - internal static FileTagsDatabase Database { get; set; } = null!; + private static FileTagsDatabase database = null!; + internal static FileTagsDatabase Database + { + get => database; + set + { + failedXattrWrites.Clear(); + database = value; + } + } public static FileTagsDatabase GetDbInstance() => Database; } From d7ac30d9b2956bb1ecfad4160ab68d0fd05368d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Sat, 10 Oct 2026 15:53:26 +0300 Subject: [PATCH 2/3] Persist stale-xattr marker so the tags DB stays authoritative after restart Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Utils/FileTags/FileTagsDatabase.Linux.cs | 33 +++++--- .../Utils/FileTags/FileTagsHelper.Linux.cs | 28 ++++--- src/Files.App/Utils/FileTags/TaggedFile.cs | 2 + .../Tags/FileTagsHelperTests.cs | 75 ++++++++++++++++++- 4 files changed, 117 insertions(+), 21 deletions(-) diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs index 84d1680ce46e..56fb7a1df098 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs @@ -30,23 +30,38 @@ public FileTagsDatabase() { } private string DatabasePath => _databasePath ?? Path.Combine(Ioc.Default.GetRequiredService().DataDirectory, "filetags.json"); - public void SetTags(string filePath, ulong? frn, string[] tags) + public void SetTags(string filePath, ulong? frn, string[] tags) => SetTags(filePath, frn, tags, xattrStale: false); + + /// + /// Stores the tags of a file. persists that the file's extended attribute could not be updated, + /// so the entry (even an empty one) stays authoritative over the attribute after a restart. + /// + public void SetTags(string filePath, ulong? frn, string[] tags, bool xattrStale) { lock (_gate) { var entries = Load(); - var changed = tags.Length == 0 + var keep = tags.Length > 0 || xattrStale; + var changed = !keep ? entries.Remove(filePath) - : !entries.TryGetValue(filePath, out var current) || !current.Tags.SequenceEqual(tags, StringComparer.Ordinal); + : !entries.TryGetValue(filePath, out var current) + || current.XattrStale != xattrStale + || !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() }; + if (keep && changed) + entries[filePath] = new TaggedFile { FilePath = filePath, Tags = (string[])tags.Clone(), XattrStale = xattrStale }; Save(entries); } } + public bool IsXattrStale(string filePath) + { + lock (_gate) + return Load().TryGetValue(filePath, out var tagged) && tagged.XattrStale; + } + public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath) { if (newFilePath is null || string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal)) @@ -81,14 +96,14 @@ public string[] GetTags(string? filePath, ulong? frn) public IEnumerable GetAll() { lock (_gate) - return Load().Values.ToList(); + return Load().Values.Where(x => x.Tags.Length > 0).ToList(); } public IEnumerable GetAllUnderPath(string folderPath) { var prefix = folderPath.TrimEnd('/') + "/"; lock (_gate) - return Load().Values.Where(x => x.FilePath.StartsWith(prefix, StringComparison.Ordinal)).ToList(); + return Load().Values.Where(x => x.Tags.Length > 0 && x.FilePath.StartsWith(prefix, StringComparison.Ordinal)).ToList(); } public void Import(string json) @@ -117,7 +132,7 @@ public void Import(string json) public string Export() { lock (_gate) - return JsonSerializer.Serialize(Load().Values.ToList(), AppJsonSerializerContext.Default.ListTaggedFile); + return JsonSerializer.Serialize(Load().Values.Where(x => x.Tags.Length > 0).ToList(), AppJsonSerializerContext.Default.ListTaggedFile); } private Dictionary Load() @@ -134,7 +149,7 @@ private Dictionary Load() var list = JsonSerializer.Deserialize(File.ReadAllText(path), AppJsonSerializerContext.Default.TaggedFileArray); foreach (var tag in list ?? []) { - if (!string.IsNullOrEmpty(tag.FilePath) && tag.Tags.Length > 0) + if (!string.IsNullOrEmpty(tag.FilePath) && (tag.Tags.Length > 0 || tag.XattrStale)) entries[tag.FilePath] = tag; } } diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs index 62d535888fca..5241acaba143 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs @@ -5,7 +5,6 @@ using Files.Platform.Abstractions.Tags; using Microsoft.Extensions.Logging; using System; -using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,11 +15,10 @@ namespace Files.App.Utils.FileTags // Files stores tag UIDs internally, so names are translated through the tag list; xattr tags with an unknown name are ignored. public static partial class FileTagsHelper { - private static readonly ConcurrentDictionary failedXattrWrites = new(StringComparer.Ordinal); - internal static bool TryReadDatabaseFallback(string filePath, out string[] tags) { - if (failedXattrWrites.ContainsKey(filePath)) + // Persisted marker: survives restarts, so a stale readable attribute never overwrites newer database tags. + if (GetDbInstance().IsXattrStale(filePath)) { tags = GetDbInstance().GetTags(filePath, null); return true; @@ -64,7 +62,8 @@ public static Task ReadAndUpdateFileTagsAsync(string filePath) return EnqueueWrite(() => { var tags = ReadFileTag(filePath); - GetDbInstance().SetTags(filePath, null, tags); + if (!GetDbInstance().IsXattrStale(filePath)) + GetDbInstance().SetTags(filePath, null, tags); return tags; }, Array.Empty()); } @@ -129,12 +128,19 @@ private static bool WriteTags(string filePath, string[] tags, string[] names, IF { try { - GetDbInstance().SetTags(filePath, null, tags); - // Keep the DB authoritative even when a readable attribute could not be updated or removed. - failedXattrWrites[filePath] = 0; - if (store is not null && store.WriteTags(filePath, names)) - failedXattrWrites.TryRemove(filePath, out _); - else + var written = false; + try + { + written = store is not null && store.WriteTags(filePath, names); + } + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException)) + { + App.Logger?.LogDebug(ex, "Could not write extended attributes."); + } + + // Keep the DB authoritative (persistently) when a readable attribute could not be updated or removed. + GetDbInstance().SetTags(filePath, null, tags, xattrStale: !written); + if (!written) App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath)); return true; } diff --git a/src/Files.App/Utils/FileTags/TaggedFile.cs b/src/Files.App/Utils/FileTags/TaggedFile.cs index 6e062192caf7..b15adb8f2584 100644 --- a/src/Files.App/Utils/FileTags/TaggedFile.cs +++ b/src/Files.App/Utils/FileTags/TaggedFile.cs @@ -9,5 +9,7 @@ public sealed class TaggedFile public ulong? Frn { get; set; } public string FilePath { get; set; } = string.Empty; public string[] Tags { get; set; } = []; + /// Linux: the database is newer than the file's extended attribute, which could not be updated. + public bool XattrStale { get; set; } } } diff --git a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs index c2684ac462b2..4767a7eaad7a 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs @@ -307,6 +307,80 @@ public async Task ReadOnlyFile_ReadableXattrCannotOverwriteDatabaseFallback() } } + [TestMethod] + public async Task FailedXattrWrite_DatabaseStaysAuthoritativeAfterRestart() + { + using var fixture = new TagFixture(); + const string path = "/read-only-restart"; + fixture.Store.Tags[path] = ["A"]; + fixture.Store.WritesSucceed = false; + await FileTagsHelper.EditFileTagsAsync(path, tags => [.. tags, "b"]); + await FileTagsHelper.EditFileTagsAsync(path, tags => [.. tags, "c"]); + + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null)); + + fixture.Store.WritesSucceed = true; + await FileTagsHelper.EditFileTagsAsync(path, tags => tags.Where(uid => uid != "a").ToArray()); + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + Assert.IsFalse(FileTagsHelper.GetDbInstance().IsXattrStale(path)); + CollectionAssert.AreEqual(new[] { "B", "C" }, fixture.Store.Tags[path]); + fixture.Store.Tags[path] = ["A"]; + CollectionAssert.AreEqual(new[] { "a" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + } + + [TestMethod] + public async Task FailedXattrRemoval_EmptyDatabaseStaysAuthoritativeAfterRestart() + { + using var fixture = new TagFixture(); + const string path = "/read-only-removal-restart"; + fixture.Store.Tags[path] = ["A"]; + fixture.Store.WritesSucceed = false; + await FileTagsHelper.EditFileTagsAsync(path, _ => []); + + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + Assert.AreEqual(0, (await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)).Length); + Assert.AreEqual(0, FileTagsHelper.GetDbInstance().GetAll().Count()); + } + + [TestMethod] + public async Task ReadOnlyFile_StaleXattrDoesNotOverwriteDatabaseAfterRestart() + { + if (!OperatingSystem.IsLinux()) + { + Assert.Inconclusive("Requires Linux file permissions and extended attributes."); + return; + } + + var store = new XattrFileTagsStore(); + using var fixture = new TagFixture(store); + var path = Path.Combine(Path.GetDirectoryName(fixture.DatabasePath)!, "read-only-restart.txt"); + File.WriteAllText(path, "tags"); + if (!store.WriteTags(path, ["A"])) + Assert.Inconclusive("The test file system has no user xattr support."); + + File.SetUnixFileMode(path, UnixFileMode.UserRead); + try + { + if (store.WriteTags(path, ["B"])) + Assert.Inconclusive("The current user can bypass read-only file permissions."); + + var item = new ListedItem { ItemPath = path }; + await item.EditFileTagsAsync(tags => [.. tags, "b"]); + await item.EditFileTagsAsync(tags => [.. tags, "c"]); + + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, await FileTagsHelper.ReadAndUpdateFileTagsAsync(path)); + CollectionAssert.AreEqual(new[] { "a", "b", "c" }, new FileTagsDatabase(fixture.DatabasePath).GetTags(path, null)); + CollectionAssert.AreEqual(new[] { "A" }, store.ReadTags(path).ToArray()); + } + finally + { + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + private sealed class TagFixture : IDisposable { private readonly string root = Path.Combine(Path.GetTempPath(), "files-tags-queue-" + Guid.NewGuid().ToString("N")); @@ -388,7 +462,6 @@ internal static FileTagsDatabase Database get => database; set { - failedXattrWrites.Clear(); database = value; } } From 7c4ea055a5ad3345f8718a0a097826237988f901 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Sat, 10 Oct 2026 16:07:55 +0300 Subject: [PATCH 3/3] Preserve stale tag markers through export and import Co-Authored-By: GPT-6.1-sol (OpenAI Codex) Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Utils/FileTags/FileTagsDatabase.Linux.cs | 6 +-- .../Tags/FileTagsDatabaseTests.cs | 51 +++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs index 56fb7a1df098..21e7a87b7a35 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs @@ -115,14 +115,14 @@ public void Import(string json) var entries = new Dictionary(StringComparer.Ordinal); foreach (var tag in tags ?? []) { - if (!string.IsNullOrEmpty(tag.FilePath) && tag.Tags.Length > 0) + if (!string.IsNullOrEmpty(tag.FilePath) && (tag.Tags.Length > 0 || tag.XattrStale)) 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))) + existing.XattrStale == pair.Value.XattrStale && existing.Tags.SequenceEqual(pair.Value.Tags, StringComparer.Ordinal))) return; Save(entries); @@ -132,7 +132,7 @@ public void Import(string json) public string Export() { lock (_gate) - return JsonSerializer.Serialize(Load().Values.Where(x => x.Tags.Length > 0).ToList(), AppJsonSerializerContext.Default.ListTaggedFile); + return JsonSerializer.Serialize(Load().Values.Where(x => x.Tags.Length > 0 || x.XattrStale).ToList(), AppJsonSerializerContext.Default.ListTaggedFile); } private Dictionary Load() diff --git a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs index da541740a8a1..13b6b2f0cfa5 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs @@ -47,6 +47,57 @@ public void Save_SkipsEmptyAndEqualTagsAndKeepsInputAndOutputIsolated() finally { Directory.Delete(root, true); } } + [TestMethod] + public void ExportImport_EmptyStaleEntry_RemainsAuthoritativeAndHidden() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var source = new FileTagsDatabase(Path.Combine(root, "source.json")); + source.SetTags("/folder/file", null, ["a"]); + source.SetTags("/folder/file", null, [], xattrStale: true); + Assert.AreEqual(0, source.GetAll().Count()); + + var path = Path.Combine(root, "imported.json"); + var imported = new FileTagsDatabase(path); + imported.Import(source.Export()); + foreach (var db in new[] { imported, new FileTagsDatabase(path) }) + { + Assert.IsTrue(db.IsXattrStale("/folder/file")); + Assert.AreEqual(0, db.GetTags("/folder/file", null).Length); + Assert.AreEqual(0, db.GetAll().Count()); + Assert.AreEqual(0, db.GetAllUnderPath("/folder").Count()); + } + } + finally { Directory.Delete(root, true); } + } + + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void Import_IdenticalTagsWithDifferentXattrStale_PersistsFlag(bool xattrStale) + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var source = new FileTagsDatabase(Path.Combine(root, "source.json")); + source.SetTags("/file", null, ["a"], xattrStale); + var path = Path.Combine(root, "imported.json"); + var imported = new FileTagsDatabase(path); + imported.SetTags("/file", null, ["a"], !xattrStale); + + imported.Import(source.Export()); + foreach (var db in new[] { imported, new FileTagsDatabase(path) }) + { + Assert.AreEqual(xattrStale, db.IsXattrStale("/file")); + CollectionAssert.AreEqual(new[] { "a" }, db.GetTags("/file", null)); + } + } + finally { Directory.Delete(root, true); } + } + [TestMethod] public void Save_RetriesFailedPersistenceEvenWhenTagsAreEqual() {