From df6212c8f0108d9e6c30df2f111f3bfe1520feb8 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:46:01 +0800 Subject: [PATCH 01/15] fix(local-feed): distinguish hydration size notifications from edits --- docs/local-change-feed.md | 14 +- eng/test-ordinary-user-delete.ps1 | 5 +- .../Internal/WindowsSecurityChangeSource.cs | 16 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 71 +++++++ .../LocalChanges/CloudLocalChangeFeed.cs | 35 +++- .../LocalChanges/CloudLocalChangeModels.cs | 7 +- .../LocalChanges/WindowsLocalChangeSource.cs | 49 ++++- .../CloudContentConfirmationTests.cs | 23 ++- .../ReadOnlyHydrationJournalTests.cs | 194 ++++++++++++++++++ .../WindowsSecurityChangeSourceTests.cs | 8 + 10 files changed, 391 insertions(+), 31 deletions(-) create mode 100644 src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs create mode 100644 tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index fafa53c..554f382 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -17,11 +17,19 @@ attribute suppression requires the explicit caller guarantee described in [metadata echo coordination](metadata-echo-coordination.md). Security and data notifications bypass that authorization as well. Windows can report an attribute change during a rename without changing resident bytes. That observation remains metadata; the -independent size, last-write and creation-time subscription still reports conservative content -candidates, including same-length writes before, between or after successive renames. No content -read, timestamp heuristic, in-sync flag or rename window suppresses a data notification. An attribute +independent last-write and creation-time subscription still reports conservative content +candidates, including same-length writes before, between or after successive renames. An attribute record delivered after its path has moved or been replaced remains an unbound metadata observation requiring reconciliation, rather than discovering a new object at the historical path. + +Size notifications have their own subscription because Windows can report a size change when +hydration increases physical allocation and leaves the logical length unchanged. A size notice +for a known file placeholder produces no content row when the native notice and the current +object agree on identity, logical length and in-sync state, and Windows reports only validated +data. If the object was replaced or the captured and current states disagree, the feed retains an +unbound observation and requires reconciliation. Last-write notifications remain independent, so +a same-length local write overlapping hydration can still be read and acknowledged separately. + For newly discovered ordinary files and directories, the feed also retains the native NTFS file reference in the official item row. A later attribute record can bind to that exact object without requiring a placeholder identity. Older ordinary rows without that binding remain unbound until diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index d110065..e7116c8 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -27,6 +27,9 @@ $suiteName = $Suite.ToLowerInvariant() $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversItsOwnReceiptsAcrossOfficialStoreReopen' } elseif ($Suite -eq 'AccessJournal') { @('FullyQualifiedName~AccessOnlyResidentWriteRetainsOriginalJournalAndGenuineLaterEdit', + 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', + 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', + 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', 'FullyQualifiedName~ConfirmedFileTimestampPassthroughDoesNotUnbindLaterContent', @@ -68,7 +71,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 82 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 86 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs b/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs index a2ef9d9..1c44cb3 100644 --- a/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs +++ b/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs @@ -27,7 +27,7 @@ internal sealed partial class WindowsSecurityChangeSource : IAsyncDisposable internal WindowsSecurityChangeSource(string path, int capacity, Action changed, Action error, Action? beforeRearm = null, uint notifyFilter = 0x100) { - if (notifyFilter is not (0x100 or 0x4)) { throw new ArgumentOutOfRangeException(nameof(notifyFilter)); } + if (notifyFilter is not (0x100 or 0x4 or 0x8)) { throw new ArgumentOutOfRangeException(nameof(notifyFilter)); } _changed = changed; _error = error; _beforeRearm = beforeRearm; @@ -180,7 +180,12 @@ internal static unsafe WindowsSecurityChange[] Decode(ReadOnlySpan buffer) int end = checked(header + (int)record.FileNameLength); if (record.Action != 3) { throw new InvalidDataException("Unexpected action in a metadata-only subscription."); } changes.Add(new(new string(MemoryMarshal.Cast(buffer[header..end])), record.FileId, - record.ParentFileId, (record.FileAttributes & 0x10) != 0)); + record.ParentFileId, (record.FileAttributes & 0x10) != 0) + { + FileAttributes = record.FileAttributes, + ReparsePointTag = record.ReparsePointTag, + FileSize = record.FileSize, + }); if (record.NextEntryOffset == 0) { return changes.ToArray(); } if (record.NextEntryOffset < end || record.NextEntryOffset > buffer.Length || (record.NextEntryOffset & 3) != 0) { throw new InvalidDataException("The security notification link is invalid."); } @@ -235,4 +240,9 @@ private static unsafe partial bool ReadDirectoryChangesEx(SafeFileHandle directo private static unsafe partial bool CancelIoEx(SafeFileHandle directory, NativeOverlapped* overlapped); } -internal readonly record struct WindowsSecurityChange(string RelativePath, ulong FileId, ulong ParentFileId, bool IsDirectory); +internal readonly record struct WindowsSecurityChange(string RelativePath, ulong FileId, ulong ParentFileId, bool IsDirectory) +{ + internal uint FileAttributes { get; init; } + internal uint ReparsePointTag { get; init; } + internal long FileSize { get; init; } +} diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs new file mode 100644 index 0000000..efd044a --- /dev/null +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -0,0 +1,71 @@ +using System.ComponentModel; + +using CfSharp.Native; + +using Microsoft.Win32.SafeHandles; + +namespace CfSharp; + +public sealed partial class CloudLocalChangeFeed +{ + private bool IsCleanPlaceholderSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size) + { + LocalSecurityChangeIdentity identity = size.Identity; + CloudItemKind kind = identity.IsDirectory ? CloudItemKind.Directory : CloudItemKind.File; + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); + } + try + { + using SafeFileHandle reference = WindowsFileMetadata.OpenMetadataReference(path.FullPath); + if (!MatchesAttributePath(reference, path)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); + } + LocalCloudItemInspection item = CloudItemInspector.Inspect(reference, path.FullPath, kind, _syncRootPath); + if (NtfsFileId(item.LocalBinding) is not long fileId || unchecked((ulong)fileId) != identity.FileId || + item.LocalBinding?.VolumeSerialNumber != identity.VolumeSerialNumber || + item.LocalBinding.SyncRootFileId != identity.RootFileId || + (owner?.LocalFileId is long recorded && recorded != fileId) || owner?.IsTombstone == true || + !MatchesAttributePath(reference, path)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); + } + + bool capturedPlaceholder = size.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder); + if (capturedPlaceholder != item.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); + } + if (kind != CloudItemKind.File || !capturedPlaceholder) { return false; } + if (owner is not { Kind: CloudItemKind.File } || + !CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || + placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || + placeholder.RemoteRevision != owner.RemoteRevision) + { + throw new CloudNamespaceObservationUncertainException(isDirectory: false); + } + + // On Windows, hydration can change allocation and signal Size while the + // placeholder remains in sync. A logical data modification clears in-sync. + // Keep last-write notifications independent, including overlapping writes. + bool capturedInSync = size.PlaceholderState.HasFlag(CloudPlaceholderState.InSync); + bool inSyncNow = item.SynchronizationState == CloudSynchronizationState.InSync; + if (capturedInSync != inSyncNow || item.Length != size.Length || + (inSyncNow && (item.ModifiedDataSize != 0 || item.OnDiskDataSize != item.ValidatedDataSize))) + { + // This can be a delayed allocation notice delivered after a genuine edit. + // Preserve the original without letting it authorize an upload. + throw new CloudNamespaceObservationUncertainException(isDirectory: false); + } + return inSyncNow; + } + catch (Exception exception) when (exception is not CloudNamespaceObservationUncertainException && + exception is (CloudPathReparsePointException or CloudFilesException or Win32Exception or + UnauthorizedAccessException or InvalidOperationException or IOException)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory, exception); + } + } +} diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index ebb0f15..a956704 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -783,11 +783,13 @@ await PersistChangeAsync( cancellationToken).ConfigureAwait(false); break; case LocalChangeSourceAction.Modified: + case LocalChangeSourceAction.SizeModified: await PersistChangeAsync( CloudLocalChangeKind.ContentUpdate, sourceEvent.RelativePath, previousRelativePath: null, - cancellationToken).ConfigureAwait(false); + cancellationToken, + sizeChange: sourceEvent.SizeChange).ConfigureAwait(false); break; case LocalChangeSourceAction.SecurityModified: case LocalChangeSourceAction.AttributesModified: @@ -816,12 +818,13 @@ private async ValueTask PersistChangeAsync( string relativePath, string? previousRelativePath, CancellationToken cancellationToken, - LocalChangeSourceEvent? securityObservation = null) + LocalChangeSourceEvent? securityObservation = null, + LocalSizeChange? sizeChange = null) { CloudItemPath path; try { - path = securityObservation is null + path = securityObservation is null && sizeChange is null ? CloudItemPathResolver.Resolve(_syncRootPath, relativePath, allowRoot: false) : CloudItemPathResolver.ResolveLexically(_syncRootPath, relativePath, allowRoot: false); } @@ -868,7 +871,7 @@ await TryRetainUnresolvedTimeObservationAsync(relativePath, cancellationToken).C ? await AcquireSecurityOperationAsync(path, securityObservation.Value, cancellationToken).ConfigureAwait(false) : null; await PersistChangeAttemptAsync(kind, path, previousPath, operationId, observedAt, null, - cancellationToken, securityObservation).ConfigureAwait(false); + cancellationToken, securityObservation, sizeChange).ConfigureAwait(false); } catch (CloudNamespaceObservationUncertainException exception) { @@ -878,7 +881,7 @@ await PersistChangeAttemptAsync(kind, path, previousPath, operationId, observedA if (kind == CloudLocalChangeKind.ContentUpdate && exception.IsDirectory) { kind = CloudLocalChangeKind.MetadataUpdate; } await PersistChangeAttemptAsync(kind, path, previousPath, operationId, observedAt, exception.IsDirectory, - cancellationToken, securityObservation).ConfigureAwait(false); + cancellationToken, securityObservation, sizeChange).ConfigureAwait(false); } catch (IOException) when (kind == CloudLocalChangeKind.Move) { @@ -919,7 +922,7 @@ await PersistChangeAttemptAsync(CloudLocalChangeKind.ContentUpdate, path, null, private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, CloudItemPath path, CloudItemPath? previousPath, Guid operationId, DateTimeOffset observedAt, bool? uncertainDirectory, - CancellationToken cancellationToken, LocalChangeSourceEvent? securityObservation = null) + CancellationToken cancellationToken, LocalChangeSourceEvent? securityObservation = null, LocalSizeChange? sizeChange = null) { using IDisposable? publication = await AcquirePublicationAsync(cancellationToken).ConfigureAwait(false); StagedSecurityObservation? staged = null; @@ -928,7 +931,7 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo await using (ICloudStateTransaction transaction = await _stateStore.BeginTransactionAsync(cancellationToken).ConfigureAwait(false)) { staged = await PersistChangeCoreAsync(transaction, kind, path, previousPath, operationId, observedAt, - uncertainDirectory, securityObservation, cancellationToken).ConfigureAwait(false); + uncertainDirectory, securityObservation, sizeChange, cancellationToken).ConfigureAwait(false); } if (staged is not null) @@ -945,7 +948,8 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo private async ValueTask PersistChangeCoreAsync(ICloudStateTransaction transaction, CloudLocalChangeKind kind, CloudItemPath path, CloudItemPath? previousPath, Guid operationId, DateTimeOffset observedAt, - bool? uncertainDirectory, LocalChangeSourceEvent? securityObservation, CancellationToken cancellationToken) + bool? uncertainDirectory, LocalChangeSourceEvent? securityObservation, LocalSizeChange? sizeChange, + CancellationToken cancellationToken) { LocalChangeCheckpoint checkpoint = await ReadCheckpointAsync(transaction, cancellationToken) .ConfigureAwait(false); @@ -971,6 +975,14 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo IReadOnlyList deletes = await transaction.Checkpoints.ListAsync(RemoteDeleteIntent.Prefix, cancellationToken).ConfigureAwait(false); bool pendingDelete = deletes.Select(value => RemoteDeleteIntent.Decode(value.Value)).Any(intent => intent.Contains(path.RelativePath) || (previousPath is not null && intent.Contains(previousPath.Value.RelativePath))); + if (sizeChange is { } size && uncertainDirectory is null) + { + if (pendingCreation || pendingMove || pendingDelete) + { + throw new CloudNamespaceObservationUncertainException(size.Identity.IsDirectory); + } + if (IsCleanPlaceholderSizeObservation(path, current, size)) { return null; } + } bool uncertainFileContent = false; if (kind == CloudLocalChangeKind.ContentUpdate) { @@ -980,13 +992,13 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo cancellationToken).ConfigureAwait(false)).Count != 0; bool historicalDirectory = await transaction.Checkpoints.GetAsync(RemoteMetadataIntent.DirectoryTimeObservationName(path.RelativePath), cancellationToken).ConfigureAwait(false) is not null; - if (!historicalFile && uncertainDirectory is null && Directory.Exists(path.FullPath)) + if (!historicalFile && uncertainDirectory is null && (sizeChange?.Identity.IsDirectory ?? Directory.Exists(path.FullPath))) { kind = CloudLocalChangeKind.MetadataUpdate; } else { - uncertainFileContent = historicalFile || historicalDirectory; + uncertainFileContent = historicalFile || historicalDirectory || (sizeChange is not null && uncertainDirectory is not null); } } bool metadataObservation = kind == CloudLocalChangeKind.MetadataUpdate && @@ -1327,7 +1339,8 @@ await UpsertCheckpointAsync( private async ValueTask PublishAsync(LocalChangeSourceEvent sourceEvent) { - if (sourceEvent.Action is LocalChangeSourceAction.SecuritySubscriptionFailed or LocalChangeSourceAction.AttributeSubscriptionFailed) + if (sourceEvent.Action is LocalChangeSourceAction.SecuritySubscriptionFailed or LocalChangeSourceAction.AttributeSubscriptionFailed or + LocalChangeSourceAction.SizeSubscriptionFailed) { if (Interlocked.Exchange(ref _terminalSourceSignaled, 1) != 0) { return; } // Fail readers out of band, but close the input only after every subscription diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs index 72a25fc..9d7f491 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs @@ -194,16 +194,21 @@ internal enum LocalChangeSourceAction SecuritySubscriptionFailed, AttributesModified, AttributeSubscriptionFailed, + SizeModified, + SizeSubscriptionFailed, } internal readonly record struct LocalChangeSourceEvent( LocalChangeSourceAction Action, string RelativePath, int ErrorCode = 0, - LocalSecurityChangeIdentity? SecurityIdentity = null); + LocalSecurityChangeIdentity? SecurityIdentity = null, + LocalSizeChange? SizeChange = null); internal readonly record struct LocalSecurityChangeIdentity(ulong VolumeSerialNumber, Guid RootFileId, ulong FileId, ulong ParentFileId, bool IsDirectory); +internal readonly record struct LocalSizeChange(LocalSecurityChangeIdentity Identity, long Length, CloudPlaceholderState PlaceholderState); + internal sealed record LocalChangePayload( string RelativePath, string? PreviousRelativePath, diff --git a/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs b/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs index 3291be0..5ce6b2f 100644 --- a/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs +++ b/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs @@ -11,7 +11,7 @@ Task StartAsync( } /// -/// Combines the Windows data/name watcher and identity-bearing attribute and security notifications +/// Combines the Windows name and time watcher with identity-bearing size, attribute and security notifications /// into the immutable local-change source contract. /// internal sealed class WindowsLocalChangeSource : ILocalChangeSource @@ -26,6 +26,7 @@ internal sealed class WindowsLocalChangeSource : ILocalChangeSource private FileSystemWatcher? _watcher; private WindowsSecurityChangeSource? _securityWatcher; private WindowsSecurityChangeSource? _attributeWatcher; + private WindowsSecurityChangeSource? _sizeWatcher; private Func? _eventHandler; private int _disposed; private Task? _disposal; @@ -64,7 +65,6 @@ public async Task StartAsync( IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | - NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime, InternalBufferSize = _bufferCapacity, @@ -85,6 +85,10 @@ public async Task StartAsync( _securityWatcher = new(_rootPath, _bufferCapacity, OnSecurityChanged, OnSecurityError, _beforeSecurityRearm); _beforeAttributeStart?.Invoke(); _attributeWatcher = new(_rootPath, _bufferCapacity, OnAttributesChanged, OnAttributeError, notifyFilter: 0x4); + // Hydration can raise Size without changing the logical file length. + // Keep that observation separate from last-write notices, including + // when both arrive for a real write that races hydration. + _sizeWatcher = new(_rootPath, _bufferCapacity, OnSizeChanged, OnSizeError, notifyFilter: 0x8); } } catch (Exception startupFailure) @@ -116,19 +120,28 @@ private async Task DisposeCoreAsync() FileSystemWatcher? watcher; WindowsSecurityChangeSource? security; WindowsSecurityChangeSource? attributes; + WindowsSecurityChangeSource? size; lock (_gate) { watcher = _watcher; _watcher = null; security = _securityWatcher; attributes = _attributeWatcher; + size = _sizeWatcher; } try { try { - if (attributes is not null) { await attributes.DisposeAsync().ConfigureAwait(false); } + try + { + if (size is not null) { await size.DisposeAsync().ConfigureAwait(false); } + } + finally + { + if (attributes is not null) { await attributes.DisposeAsync().ConfigureAwait(false); } + } } finally { @@ -144,6 +157,7 @@ private async Task DisposeCoreAsync() { _securityWatcher = null; _attributeWatcher = null; + _sizeWatcher = null; _eventHandler = null; } watcher?.Dispose(); @@ -185,7 +199,7 @@ private void OnAttributeError(int error, bool terminal) { if (_attributeWatcher is not null) { - // Loss of either metadata subscription invalidates the feed until rebuilt. + // Loss of a metadata subscription invalidates the feed until rebuilt. PublishCore(new(terminal ? LocalChangeSourceAction.AttributeSubscriptionFailed : error == 1022 ? LocalChangeSourceAction.Overflow : LocalChangeSourceAction.Error, string.Empty, error), fromSecurityPump: true); @@ -193,6 +207,33 @@ private void OnAttributeError(int error, bool terminal) } } + private void OnSizeChanged(WindowsSecurityChange change) + { + lock (_gate) + { + if (_sizeWatcher is null) { return; } + LocalSecurityChangeIdentity identity = new(_sizeWatcher.VolumeSerialNumber, _sizeWatcher.RootFileId, + change.FileId, change.ParentFileId, change.IsDirectory); + CfPlaceholderState state = OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299) + ? CfApi.CfGetPlaceholderStateFromAttributeTag(change.FileAttributes, change.ReparsePointTag) + : CfPlaceholderState.Invalid; + PublishCore(new(LocalChangeSourceAction.SizeModified, change.RelativePath, + SizeChange: new(identity, change.FileSize, state == CfPlaceholderState.Invalid + ? CloudPlaceholderState.None : (CloudPlaceholderState)state)), fromSecurityPump: true); + } + } + + private void OnSizeError(int error, bool terminal) + { + lock (_gate) + { + if (_sizeWatcher is null) { return; } + PublishCore(new(terminal ? LocalChangeSourceAction.SizeSubscriptionFailed : + error == 1022 ? LocalChangeSourceAction.Overflow : LocalChangeSourceAction.Error, string.Empty, error), + fromSecurityPump: true); + } + } + private void OnDeleted(object sender, FileSystemEventArgs args) => Publish(new(LocalChangeSourceAction.Deleted, GetRelativePath(args.FullPath))); diff --git a/tests/CfSharp.IntegrationTests/CloudContentConfirmationTests.cs b/tests/CfSharp.IntegrationTests/CloudContentConfirmationTests.cs index c188b65..e712088 100644 --- a/tests/CfSharp.IntegrationTests/CloudContentConfirmationTests.cs +++ b/tests/CfSharp.IntegrationTests/CloudContentConfirmationTests.cs @@ -167,7 +167,7 @@ private static CloudContentConfirmationRequest Proof(CloudLocalFileBinding bindi private sealed class Fixture : IAsyncDisposable { private readonly string _directory; - private Fixture(string directory, string root, CloudFileSystem system, UnexpectedProvider provider, + private Fixture(string directory, string root, CloudFileSystem system, FixtureContentProvider provider, SyncRootRegistrationOptions registration) { _directory = directory; @@ -181,12 +181,13 @@ private Fixture(string directory, string root, CloudFileSystem system, Unexpecte internal string Root { get; } internal CloudFileSystem System { get; private set; } internal CloudFile File { get; private set; } - internal UnexpectedProvider Provider { get; } + internal FixtureContentProvider Provider { get; } internal SyncRootRegistrationOptions Registration { get; } private ICloudStateStoreFactory? _restartFactory; internal static async Task StartAsync(Func? createStore = null, - CloudInSyncPolicy inSyncPolicy = CloudInSyncPolicy.None, bool allowHardLinks = false) + CloudInSyncPolicy inSyncPolicy = CloudInSyncPolicy.None, bool allowHardLinks = false, byte[]? hydrationContent = null, + CloudHydrationPolicy hydrationPolicy = CloudHydrationPolicy.Progressive) { // This acceptance fixture fails on unavailable Windows capabilities; it never // silently returns success when native confirmation has not actually executed. @@ -194,11 +195,11 @@ internal static async Task StartAsync(Func Volatile.Read(ref _fetches); + public ValueTask OpenReadAsync(CloudFileFetchRequest request, CancellationToken cancellationToken) { - Fetches++; + Interlocked.Increment(ref _fetches); + if (hydrationContent is not null) + { + return ValueTask.FromResult(new MemoryStream(hydrationContent, writable: false)); + } throw new InvalidOperationException("Confirmation must not hydrate missing content."); } diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs new file mode 100644 index 0000000..670a6f3 --- /dev/null +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -0,0 +1,194 @@ +namespace CfSharp.IntegrationTests; + +public sealed partial class CloudContentConfirmationTests +{ + [Trait("Category", "AccessJournal")] + [Theory] + [InlineData(CloudInSyncPolicy.None)] + [InlineData(CloudInSyncPolicy.TrackAll)] + public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite(CloudInSyncPolicy inSyncPolicy) + { + byte[] bytes = new byte[65_537]; + new Random(20261125).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), inSyncPolicy, hydrationContent: bytes); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "read-only-hydration", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(fixture.File.RelativePath, identity, bytes.Length) + .WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + CloudItemSnapshot before = await fixture.File.InspectAsync(token); + Assert.Equal(CloudContentAvailability.OnlineOnly, before.ContentAvailability); + Assert.Equal(0, before.ModifiedDataSize); + string fullPath = fixture.File.FullPath; + + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(); + await feed.StartAsync(token); + Assert.Empty(await AccessRowsAsync(factory!)); + Assert.Equal(bytes, await File.ReadAllBytesAsync(fullPath, token)); + Assert.True(fixture.Provider.Fetches > 0); + CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); + Assert.Equal((before.LocalBinding, identity.ItemId, identity.RemoteRevision), + (hydrated.LocalBinding, hydrated.ItemId, hydrated.RemoteRevision)); + Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); + Assert.Equal(0, hydrated.ModifiedDataSize); + Assert.Equal(before.LastWriteTime, hydrated.LastWriteTime); + await WaitForHydrationJournalFenceAsync(fixture, factory!, "read-finished"); + IReadOnlyList afterRead = await AccessRowsAsync(factory!); + + bytes[0] ^= 0xff; + await using (FileStream writer = new(fullPath, FileMode.Open, FileAccess.Write, FileShare.Read)) + { + writer.WriteByte(bytes[0]); + await writer.FlushAsync(token); + } + await WaitForAccessRowsAsync(factory!, rows => rows.Any(row => row.Kind == CloudStateOperationKind.ContentUpdate && + row.ItemId == identity.ItemId && afterRead.All(previous => previous.OperationId != row.OperationId))); + Assert.DoesNotContain(afterRead, row => row.Kind == CloudStateOperationKind.ContentUpdate && + LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath); + await feed.DisposeAsync(); + IReadOnlyList edits = (await AccessRowsAsync(factory!)).Where(row => + row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId == identity.ItemId).ToArray(); + Assert.NotEmpty(edits); + await fixture.RestartAsync(); + await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(); + await reopened.StartAsync(token); + int fetches = fixture.Provider.Fetches; + Assert.Equal(bytes, await File.ReadAllBytesAsync(fullPath, token)); + Assert.Equal(fetches, fixture.Provider.Fetches); + await WaitForHydrationJournalFenceAsync(fixture, factory!, "dirty-read-finished"); + IReadOnlyList retained = (await AccessRowsAsync(factory!)).Where(row => + row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId == identity.ItemId).ToArray(); + Assert.Equal(edits.Select(row => (row.OperationId, row.Sequence)), retained.Select(row => (row.OperationId, row.Sequence))); + CloudRemoteChange update = new("content", CloudRemoteChangeKind.FileUpsert, identity.RemoteId, "revision-2", + CloudItemKind.File, fixture.File.RelativePath, identity.ItemId, previousRemoteRevision: identity.RemoteRevision, + length: bytes.Length, metadata: CloudPlaceholderMetadata.CreateFileBuilder().Build()); + CloudRemoteApplyEntryResult conflict = Assert.Single((await fixture.System.ApplyRemoteChangesAsync( + new("dirty-hydration-update", Array.Empty(), [update], new byte[] { 1 }), cancellationToken: token)).Entries); + Assert.Equal(CloudRemoteApplyEntryStatus.Conflict, conflict.Status); + Assert.Equal(CloudRemoteConflictReason.Content, conflict.Conflict!.Reason); + CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 100, token); + Assert.False(page.RequiresFullRescan); + foreach (CloudOperationJournalEntry edit in edits) + { + Assert.Contains(page.Changes, change => change.OperationId == edit.OperationId && + change.Sequence == edit.Sequence && change.ItemId == identity.ItemId); + await reopened.AcknowledgeAsync([edit.OperationId], token); + } + Assert.DoesNotContain(await AccessRowsAsync(factory!), row => edits.Any(edit => edit.OperationId == row.OperationId)); + } + + [Trait("Category", "AccessJournal")] + [Fact] + public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent() + { + byte[] bytes = new byte[256 * 1024]; + new Random(20261125).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), hydrationContent: bytes, + hydrationPolicy: CloudHydrationPolicy.Partial); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "partial-read-only-hydration", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(fixture.File.RelativePath, identity, bytes.Length) + .WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + CloudLocalFileBinding? original = (await fixture.File.InspectAsync(token)).LocalBinding; + await using (CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed()) + { + await feed.StartAsync(token); + await fixture.File.HydrateAsync(new(0, Environment.SystemPageSize), token); + CloudItemSnapshot partial = await fixture.File.InspectAsync(token); + Assert.Equal(CloudContentAvailability.PartiallyAvailable, partial.ContentAvailability); + Assert.Equal(CloudSynchronizationState.InSync, partial.SynchronizationState); + await WaitForHydrationJournalFenceAsync(fixture, factory!, "partial-read-finished"); + Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); + } + int firstFetches = fixture.Provider.Fetches; + await fixture.RestartAsync(); + await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(); + await reopened.StartAsync(token); + Assert.Equal(bytes, await File.ReadAllBytesAsync(fixture.File.FullPath, token)); + Assert.True(fixture.Provider.Fetches > firstFetches); + int completedFetches = fixture.Provider.Fetches; + Assert.Equal(bytes, await File.ReadAllBytesAsync(fixture.File.FullPath, token)); + Assert.Equal(completedFetches, fixture.Provider.Fetches); + await WaitForHydrationJournalFenceAsync(fixture, factory!, "complete-read-finished"); + CloudItemSnapshot complete = await fixture.File.InspectAsync(token); + Assert.Equal((original, identity.ItemId, identity.RemoteRevision), (complete.LocalBinding, complete.ItemId, complete.RemoteRevision)); + Assert.Equal(CloudSynchronizationState.InSync, complete.SynchronizationState); + Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); + CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 100, token); + Assert.False(page.RequiresFullRescan); + Assert.DoesNotContain(page.Changes, row => row.Kind == CloudLocalChangeKind.ContentUpdate && + row.RelativePath == fixture.File.RelativePath); + + bool IsHydrationContentRow(CloudOperationJournalEntry row) => row.Kind == CloudStateOperationKind.ContentUpdate && + LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath; + } + + [Trait("Category", "AccessJournal")] + [Fact] + public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds() + { + byte[] bytes = new byte[65_537]; + new Random(20261125).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), hydrationContent: bytes); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + string path = fixture.File.FullPath; + string name = fixture.File.RelativePath; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "delayed-read-only-hydration", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(name, identity, bytes.Length).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + + LocalChangeSourceEvent hydration = await CaptureNativeModificationAsync(fixture.Root, name, async () => + { + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + }, token, LocalChangeSourceAction.SizeModified); + Assert.True(hydration.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => + { + await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); + writer.WriteByte((byte)(bytes[0] ^ 0xff)); + await writer.FlushAsync(token); + }, token); + await source.EmitAsync(hydration); + await source.EmitAsync(write); + await WaitForAccessRowsAsync(factory!, rows => rows.Count == 2); + IReadOnlyList originals = await AccessRowsAsync(factory!); + Assert.Null(originals[0].ItemId); + Assert.Equal(identity.ItemId, originals[1].ItemId); + Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); + await feed.DisposeAsync(); + await fixture.RestartAsync(); + await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(null, new ControlledMetadataSource()); + await reopened.StartAsync(token); + await reopened.AcknowledgeFullRescanAsync(reopened.BeginFullRescan(), token); + CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 10, token); + Assert.Equal(originals.Select(row => (row.OperationId, row.Sequence, row.ItemId)), + page.Changes.Select(row => (row.OperationId, row.Sequence, row.ItemId))); + Assert.All(page.Changes, row => Assert.Equal(CloudLocalChangeKind.ContentUpdate, row.Kind)); + await reopened.AcknowledgeAsync([originals[0].OperationId], token); + Assert.Equal(originals[1].OperationId, Assert.Single(await AccessRowsAsync(factory!)).OperationId); + await reopened.AcknowledgeAsync([originals[1].OperationId], token); + Assert.Empty(await AccessRowsAsync(factory!)); + bytes[0] ^= 0xff; + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + } + + private static async Task WaitForHydrationJournalFenceAsync(Fixture fixture, AccessJournalFactory factory, string name) + { + Directory.CreateDirectory(Path.Combine(fixture.Root, name)); + await WaitForAccessRowsAsync(factory, rows => rows.Any(row => row.Kind == CloudStateOperationKind.Create && + LocalChangePayload.Decode(row.Payload).RelativePath == name)); + } +} diff --git a/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs index aec0498..7b1beec 100644 --- a/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs +++ b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs @@ -43,13 +43,18 @@ public async Task NativeSecuritySubscriptionSurvivesItsStartingThread() public void ExtendedSecurityRecordLayoutAndBoundsMatchTheWindowsContract() { Assert.Equal(88, Marshal.SizeOf()); + Assert.Equal(48, Marshal.OffsetOf("FileSize").ToInt32()); + Assert.Equal(56, Marshal.OffsetOf("FileAttributes").ToInt32()); + Assert.Equal(60, Marshal.OffsetOf("ReparsePointTag").ToInt32()); Assert.Equal(64, Marshal.OffsetOf("FileId").ToInt32()); Assert.Equal(72, Marshal.OffsetOf("ParentFileId").ToInt32()); Assert.Equal(84, Marshal.OffsetOf("FileName").ToInt32()); byte[] name = Encoding.Unicode.GetBytes("before.txt"); byte[] record = new byte[84 + name.Length]; BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(4), 3); + BinaryPrimitives.WriteInt64LittleEndian(record.AsSpan(48), 65537); BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(56), 0x10); + BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(60), 0x9000001a); BinaryPrimitives.WriteUInt64LittleEndian(record.AsSpan(64), 0x1000000000001234); BinaryPrimitives.WriteUInt64LittleEndian(record.AsSpan(72), 0x2000000000005678); BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(80), (uint)name.Length); @@ -59,6 +64,9 @@ public void ExtendedSecurityRecordLayoutAndBoundsMatchTheWindowsContract() Assert.Equal(0x1000000000001234ul, change.FileId); Assert.Equal(0x2000000000005678ul, change.ParentFileId); Assert.True(change.IsDirectory); + Assert.Equal(65537, change.FileSize); + Assert.Equal(0x10u, change.FileAttributes); + Assert.Equal(0x9000001au, change.ReparsePointTag); byte[] unpaired = [.. record.AsSpan(0, 84), 0, 0xd8, 0x61, 0]; BinaryPrimitives.WriteUInt32LittleEndian(unpaired.AsSpan(80), 4); string nativeName = Assert.Single(WindowsSecurityChangeSource.Decode(unpaired)).RelativePath; From 7b5db4b4d562e533930a2bd8f3dfb0b71d65b7ce Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:58:51 +0800 Subject: [PATCH 02/15] fix(local-feed): retain late sizes at retired ordinary names --- docs/local-change-feed.md | 4 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 26 ++++++++++-- .../LocalChanges/CloudLocalChangeFeed.cs | 17 +++++++- .../ReadOnlyHydrationJournalTests.cs | 40 +++++++++++++++++++ 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index 554f382..f76244e 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -27,7 +27,9 @@ hydration increases physical allocation and leaves the logical length unchanged. for a known file placeholder produces no content row when the native notice and the current object agree on identity, logical length and in-sync state, and Windows reports only validated data. If the object was replaced or the captured and current states disagree, the feed retains an -unbound observation and requires reconciliation. Last-write notifications remain independent, so +unbound observation and requires reconciliation. A size notice delayed past the removal of an +ordinary name also stays unbound, while the ordered name subscription tracks the removal or move. +Last-write notifications remain independent, so a same-length local write overlapping hydration can still be read and acknowledged separately. For newly discovered ordinary files and directories, the feed also retains the native NTFS file diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index efd044a..bd9b527 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -8,10 +8,13 @@ namespace CfSharp; public sealed partial class CloudLocalChangeFeed { - private bool IsCleanPlaceholderSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size) + private enum SizeObservationDisposition { Content, CleanPlaceholder, MissingOrdinaryObject } + + private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size) { LocalSecurityChangeIdentity identity = size.Identity; CloudItemKind kind = identity.IsDirectory ? CloudItemKind.Directory : CloudItemKind.File; + bool capturedPlaceholder = size.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder); if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); @@ -33,12 +36,11 @@ private bool IsCleanPlaceholderSizeObservation(CloudItemPath path, CloudItemStat throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } - bool capturedPlaceholder = size.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder); if (capturedPlaceholder != item.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)) { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } - if (kind != CloudItemKind.File || !capturedPlaceholder) { return false; } + if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } if (owner is not { Kind: CloudItemKind.File } || !CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || @@ -59,7 +61,16 @@ private bool IsCleanPlaceholderSizeObservation(CloudItemPath path, CloudItemStat // Preserve the original without letting it authorize an upload. throw new CloudNamespaceObservationUncertainException(isDirectory: false); } - return inSyncNow; + return inSyncNow ? SizeObservationDisposition.CleanPlaceholder : SizeObservationDisposition.Content; + } + catch (Win32Exception exception) when (kind == CloudItemKind.File && !capturedPlaceholder && exception.NativeErrorCode is 2 or 3) + { + return SizeObservationDisposition.MissingOrdinaryObject; + } + catch (CloudNamespaceObservationUncertainException) when (kind == CloudItemKind.File && !capturedPlaceholder && + IsMissingSizeObservationPath(path.FullPath)) + { + return SizeObservationDisposition.MissingOrdinaryObject; } catch (Exception exception) when (exception is not CloudNamespaceObservationUncertainException && exception is (CloudPathReparsePointException or CloudFilesException or Win32Exception or @@ -68,4 +79,11 @@ exception is (CloudPathReparsePointException or CloudFilesException or Win32Exce throw new CloudNamespaceObservationUncertainException(identity.IsDirectory, exception); } } + + private static bool IsMissingSizeObservationPath(string path) + { + try { _ = File.GetAttributes(path); } + catch (Exception exception) when (exception is FileNotFoundException or DirectoryNotFoundException) { return true; } + return false; + } } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index a956704..0ec184b 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -981,7 +981,22 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo { throw new CloudNamespaceObservationUncertainException(size.Identity.IsDirectory); } - if (IsCleanPlaceholderSizeObservation(path, current, size)) { return null; } + SizeObservationDisposition disposition = InspectSizeObservation(path, current, size); + if (disposition == SizeObservationDisposition.CleanPlaceholder) { return null; } + if (disposition == SizeObservationDisposition.MissingOrdinaryObject) + { + // The independent size source can lag the ordered name/time source. + // A missing ordinary name is not proof of watcher loss. Keep the + // historical observation without rediscovering the old name. + LocalChangePayload historical = new(path.RelativePath, null, IsDirectory: false, observedAt); + await transaction.Operations.EnqueueAsync(new(operationId, CloudStateOperationKind.ContentUpdate, null, + historical.Encode(), observedAt), cancellationToken).ConfigureAwait(false); + await UpsertCheckpointAsync(transaction, observation, checkpoint.RequiresFullRescan, observedAt, + cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + SignalAvailable(); + return null; + } } bool uncertainFileContent = false; if (kind == CloudLocalChangeKind.ContentUpdate) diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 670a6f3..ca54fa6 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -191,4 +191,44 @@ private static async Task WaitForHydrationJournalFenceAsync(Fixture fixture, Acc await WaitForAccessRowsAsync(factory, rows => rows.Any(row => row.Kind == CloudStateOperationKind.Create && LocalChangePayload.Decode(row.Payload).RelativePath == name)); } + + [Fact] + public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() + { + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path)); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); + CancellationToken token = deadline.Token; + const string original = "original.bin"; + const string moved = "moved.bin"; + string originalPath = Path.Combine(fixture.Root, original); + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + LocalChangeSourceEvent size = await CaptureNativeModificationAsync(fixture.Root, original, + () => File.WriteAllTextAsync(originalPath, "local content", token), token, LocalChangeSourceAction.SizeModified); + Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); + await source.EmitAsync(new(LocalChangeSourceAction.Created, original)); + await WaitForAccessRowsAsync(factory!, rows => rows.Count == 1); + File.Move(originalPath, Path.Combine(fixture.Root, moved)); + await source.EmitAsync(new(LocalChangeSourceAction.RenamedOldName, original)); + await source.EmitAsync(new(LocalChangeSourceAction.RenamedNewName, moved)); + await source.EmitAsync(size); + await WaitForAccessRowsAsync(factory!, rows => rows.Count == 3); + + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + Assert.False(page.RequiresFullRescan); + Assert.Collection(page.Changes, + change => { Assert.Equal(CloudLocalChangeKind.Create, change.Kind); Assert.NotNull(change.ItemId); }, + change => { Assert.Equal(CloudLocalChangeKind.Move, change.Kind); Assert.Equal(moved, change.RelativePath); }, + change => + { + Assert.Equal(CloudLocalChangeKind.ContentUpdate, change.Kind); + Assert.Equal(original, change.RelativePath); + Assert.Null(change.ItemId); + }); + Assert.Equal(page.Changes[0].ItemId, page.Changes[1].ItemId); + await using ICloudStateTransaction state = await factory!.Store!.BeginTransactionAsync(token); + Assert.Null(await state.Items.GetByRelativePathAsync(original, token)); + } } From 2c0ac6686fff56e795cafd452db754c45a4874fc Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:02:58 +0800 Subject: [PATCH 03/15] test(local-feed): make delayed hydration delivery deterministic --- .../ReadOnlyHydrationJournalTests.cs | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index ca54fa6..29b99c2 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -150,11 +150,17 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); - LocalChangeSourceEvent hydration = await CaptureNativeModificationAsync(fixture.Root, name, async () => - { - Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); - }, token, LocalChangeSourceAction.SizeModified); - Assert.True(hydration.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); + Assert.True(hydrated.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + CloudLocalFileBinding binding = Assert.IsType(hydrated.LocalBinding); + long fileId = Assert.IsType(hydrated.LocalFileId); + // The live-feed tests cover the real size subscription. Freeze the native + // snapshot here so the delayed-delivery test does not depend on whether + // Windows generates a size notice for this particular allocation. + LocalSizeChange size = new(new(binding.VolumeSerialNumber, binding.SyncRootFileId, + unchecked((ulong)fileId), ParentFileId: 0, IsDirectory: false), bytes.Length, hydrated.PlaceholderState); + LocalChangeSourceEvent hydration = new(LocalChangeSourceAction.SizeModified, name, SizeChange: size); LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => { await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); @@ -205,8 +211,14 @@ public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() ControlledMetadataSource source = new(); await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); - LocalChangeSourceEvent size = await CaptureNativeModificationAsync(fixture.Root, original, - () => File.WriteAllTextAsync(originalPath, "local content", token), token, LocalChangeSourceAction.SizeModified); + await File.WriteAllTextAsync(originalPath, "local content", token); + LocalChangeSourceEvent size = await CaptureNativeModificationAsync(fixture.Root, original, () => + { + using FileStream file = new(originalPath, FileMode.Open, FileAccess.Write, FileShare.Read); + file.SetLength(4096); + file.Flush(flushToDisk: true); + return Task.CompletedTask; + }, token, LocalChangeSourceAction.SizeModified); Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); await source.EmitAsync(new(LocalChangeSourceAction.Created, original)); await WaitForAccessRowsAsync(factory!, rows => rows.Count == 1); From 52bdc0311b0a25975f78723a3a1ae534eeb53d70 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:39:53 +0800 Subject: [PATCH 04/15] fix(local-feed): revalidate size identity before journal commit --- docs/local-change-feed.md | 9 +-- eng/test-ordinary-user-delete.ps1 | 3 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 27 +++++++- .../LocalChanges/CloudLocalChangeFeed.cs | 15 +++-- .../ReadOnlyHydrationJournalTests.cs | 66 ++++++++++++++++--- .../RemoteMetadataRecoveryTests.cs | 23 ++++++- 6 files changed, 122 insertions(+), 21 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index f76244e..7bd4b3b 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -27,10 +27,11 @@ hydration increases physical allocation and leaves the logical length unchanged. for a known file placeholder produces no content row when the native notice and the current object agree on identity, logical length and in-sync state, and Windows reports only validated data. If the object was replaced or the captured and current states disagree, the feed retains an -unbound observation and requires reconciliation. A size notice delayed past the removal of an -ordinary name also stays unbound, while the ordered name subscription tracks the removal or move. -Last-write notifications remain independent, so -a same-length local write overlapping hydration can still be read and acknowledged separately. +unbound observation and requires reconciliation. Discovery uses the validated file ID and +rechecks the path binding before committing the item and journal row. A size notice delayed +past the removal of an ordinary name also stays unbound, while the ordered name subscription +tracks the removal or move. Last-write notifications remain independent, so a same-length local +write overlapping hydration can still be read and acknowledged separately. For newly discovered ordinary files and directories, the feed also retains the native NTFS file reference in the official item row. A later attribute record can bind to that exact object without diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index e7116c8..2763847 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -30,6 +30,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', + 'FullyQualifiedName~ReplacedSizeObservationDoesNotDiscoverTheNewOccupant', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', 'FullyQualifiedName~ConfirmedFileTimestampPassthroughDoesNotUnbindLaterContent', @@ -71,7 +72,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 86 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 88 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index bd9b527..355977a 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -10,8 +10,10 @@ public sealed partial class CloudLocalChangeFeed { private enum SizeObservationDisposition { Content, CleanPlaceholder, MissingOrdinaryObject } - private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size) + private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size, + out CloudLocalFileBinding? binding) { + binding = null; LocalSecurityChangeIdentity identity = size.Identity; CloudItemKind kind = identity.IsDirectory ? CloudItemKind.Directory : CloudItemKind.File; bool capturedPlaceholder = size.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder); @@ -40,6 +42,7 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } + binding = item.LocalBinding; if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } if (owner is not { Kind: CloudItemKind.File } || !CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || @@ -80,6 +83,28 @@ exception is (CloudPathReparsePointException or CloudFilesException or Win32Exce } } + private void ValidateSizeObservationBinding(CloudItemPath path, CloudLocalFileBinding binding, bool isDirectory) + { + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) + { + throw new CloudNamespaceObservationUncertainException(isDirectory); + } + try + { + using SafeFileHandle reference = WindowsFileMetadata.OpenMetadataReference(path.FullPath); + if (CloudLocalFileBindingPlatform.TryRead(reference.DangerousGetHandle(), _syncRootPath) == binding && + MatchesAttributePath(reference, path)) + { + return; + } + } + catch (Exception exception) when (exception is CloudPathReparsePointException or Win32Exception or IOException or UnauthorizedAccessException) + { + throw new CloudNamespaceObservationUncertainException(isDirectory, exception); + } + throw new CloudNamespaceObservationUncertainException(isDirectory); + } + private static bool IsMissingSizeObservationPath(string path) { try { _ = File.GetAttributes(path); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index 0ec184b..cb1844e 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -975,13 +975,14 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo IReadOnlyList deletes = await transaction.Checkpoints.ListAsync(RemoteDeleteIntent.Prefix, cancellationToken).ConfigureAwait(false); bool pendingDelete = deletes.Select(value => RemoteDeleteIntent.Decode(value.Value)).Any(intent => intent.Contains(path.RelativePath) || (previousPath is not null && intent.Contains(previousPath.Value.RelativePath))); + CloudLocalFileBinding? sizeBinding = null; if (sizeChange is { } size && uncertainDirectory is null) { if (pendingCreation || pendingMove || pendingDelete) { throw new CloudNamespaceObservationUncertainException(size.Identity.IsDirectory); } - SizeObservationDisposition disposition = InspectSizeObservation(path, current, size); + SizeObservationDisposition disposition = InspectSizeObservation(path, current, size, out sizeBinding); if (disposition == SizeObservationDisposition.CleanPlaceholder) { return null; } if (disposition == SizeObservationDisposition.MissingOrdinaryObject) { @@ -1139,7 +1140,8 @@ await transaction.Checkpoints.UpsertAsync(new CloudStateCheckpoint( ? current : previous ?? current; // A retained uncertain kind must not be reclassified through a rejected namespace. - bool directory = uncertainDirectory ?? (observedState?.Kind == CloudItemKind.Directory || Directory.Exists(path.FullPath)); + bool directory = uncertainDirectory ?? sizeChange?.Identity.IsDirectory ?? + (observedState?.Kind == CloudItemKind.Directory || Directory.Exists(path.FullPath)); using DirectoryFeedProjection? directoryProjection = uncertainDirectory is null && kind == CloudLocalChangeKind.Move && previousPath is not null ? await TryProjectDirectoryAsync().ConfigureAwait(false) : null; if (uncertainDirectory is null && kind == CloudLocalChangeKind.Move && previous is not null && current is not null && @@ -1197,6 +1199,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding, directory); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); SignalAvailable(); @@ -1215,13 +1218,16 @@ await UpsertCheckpointAsync( if (uncertainDirectory is null && directoryProjection is null && discovered) { itemId = Guid.NewGuid(); + bool discoveredDirectory = sizeChange?.Identity.IsDirectory ?? Directory.Exists(path.FullPath); state = new CloudItemState( itemId.Value, "local:" + itemId.Value.ToString("N"), path.RelativePath, - Directory.Exists(path.FullPath) ? CloudItemKind.Directory : CloudItemKind.File, + discoveredDirectory ? CloudItemKind.Directory : CloudItemKind.File, remoteRevision: null, - localFileId: TryReadDiscoveredFileId(path), + // An independent size notice names the object captured by Windows. + // Ordinary discovery cannot substitute the path's current occupant. + localFileId: sizeBinding is not null ? NtfsFileId(sizeBinding) : TryReadDiscoveredFileId(path), isTombstone: false, observedAt); } @@ -1281,6 +1287,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding, directory); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); if (requiresRescan) { diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 29b99c2..53aa10f 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -2,6 +2,8 @@ namespace CfSharp.IntegrationTests; public sealed partial class CloudContentConfirmationTests { + private const string OriginalSizePath = "original.bin"; + [Trait("Category", "AccessJournal")] [Theory] [InlineData(CloudInSyncPolicy.None)] @@ -205,20 +207,14 @@ public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path)); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); CancellationToken token = deadline.Token; - const string original = "original.bin"; + const string original = OriginalSizePath; const string moved = "moved.bin"; string originalPath = Path.Combine(fixture.Root, original); ControlledMetadataSource source = new(); await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); await File.WriteAllTextAsync(originalPath, "local content", token); - LocalChangeSourceEvent size = await CaptureNativeModificationAsync(fixture.Root, original, () => - { - using FileStream file = new(originalPath, FileMode.Open, FileAccess.Write, FileShare.Read); - file.SetLength(4096); - file.Flush(flushToDisk: true); - return Task.CompletedTask; - }, token, LocalChangeSourceAction.SizeModified); + LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, original, originalPath, token); Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); await source.EmitAsync(new(LocalChangeSourceAction.Created, original)); await WaitForAccessRowsAsync(factory!, rows => rows.Count == 1); @@ -243,4 +239,58 @@ public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() await using ICloudStateTransaction state = await factory!.Store!.BeginTransactionAsync(token); Assert.Null(await state.Items.GetByRelativePathAsync(original, token)); } + + private static Task CaptureOrdinarySizeChangeAsync(string root, string relativePath, string fullPath, CancellationToken token) => + CaptureNativeModificationAsync(root, relativePath, () => + { + using FileStream file = new(fullPath, FileMode.Open, FileAccess.Write, FileShare.Read); + file.SetLength(4096); + file.Flush(flushToDisk: true); + return Task.CompletedTask; + }, token, LocalChangeSourceAction.SizeModified); + + [Trait("Category", "AccessJournal")] + [Theory] + [InlineData("size-before-discovery")] + [InlineData("size-before-commit")] + public async Task ReplacedSizeObservationDoesNotDiscoverTheNewOccupant(string boundary) + { + MetadataFaultFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path, boundary)); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); + CancellationToken token = deadline.Token; + string path = Path.Combine(fixture.Root, OriginalSizePath); + string retiredPath = Path.Combine(fixture.Root, "retired.bin"); + await File.WriteAllTextAsync(path, "old", token); + LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, OriginalSizePath, path, token); + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + factory!.Armed = true; + await source.EmitAsync(size); + try + { + await factory.OutcomePaused.Task.WaitAsync(token); + File.Move(path, retiredPath); + await File.WriteAllBytesAsync(path, new byte[4096], token); + } + finally { factory.ResumeOutcome.TrySetResult(); } + + CloudOperationJournalEntry original = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); + Assert.Null(original.ItemId); + Assert.Equal(CloudStateOperationKind.ContentUpdate, original.Kind); + await using (ICloudStateTransaction transaction = await factory.Store!.BeginTransactionAsync(token)) + { + Assert.Null(await transaction.Items.GetByRelativePathAsync(OriginalSizePath, token)); + } + + Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + CloudLocalChange retained = Assert.Single(page.Changes); + Assert.Equal((original.OperationId, original.Sequence, OriginalSizePath), (retained.OperationId, retained.Sequence, retained.RelativePath)); + Assert.Null(retained.ItemId); + Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); + Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); + } } diff --git a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs index 7b7eb77..8165730 100644 --- a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs +++ b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs @@ -1660,14 +1660,21 @@ private sealed class FaultTransaction(ICloudStateTransaction inner, MetadataFaul private bool _writesReconciliation; public ICloudItemStateRepository Items => inner.Items; public ICloudCheckpointRepository Checkpoints => owner.OverlappingWrites || - owner._boundary is "rescan-before-preparation" or "metadata-cancel-preparation" ? this : inner.Checkpoints; + owner._boundary is "rescan-before-preparation" or "metadata-cancel-preparation" or + "size-before-discovery" or "size-before-commit" ? this : inner.Checkpoints; public ICloudOperationJournal Operations => inner.Operations; public ICloudConflictRepository Conflicts => inner.Conflicts; public ICloudRemoteBatchRepository RemoteBatches => owner.OverlappingWrites ? this : inner.RemoteBatches; public ICloudEchoSuppressionRepository EchoSuppressions => inner.EchoSuppressions; - ValueTask ICloudCheckpointRepository.GetAsync(string name, CancellationToken cancellationToken) => - inner.Checkpoints.GetAsync(name, cancellationToken); + async ValueTask ICloudCheckpointRepository.GetAsync(string name, CancellationToken cancellationToken) + { + if (owner._boundary == "size-before-discovery" && name == RemoteMetadataIntent.DirectoryTimeObservationName(OriginalSizePath)) + { + await PauseSizeDiscoveryAsync("size-before-discovery", cancellationToken); + } + return await inner.Checkpoints.GetAsync(name, cancellationToken); + } async ValueTask> ICloudCheckpointRepository.ListAsync(string namePrefix, CancellationToken cancellationToken) { // For a protected write, the first per-item lookup is preflight. The @@ -1692,6 +1699,16 @@ async ValueTask ICloudCheckpointRepository.UpsertAsync(CloudStateCheckpoint chec _writesReconciliation |= checkpoint.Name.StartsWith(RemoteMetadataIntent.Prefix, StringComparison.Ordinal) && RemoteMetadataIntent.Decode(checkpoint).RequiresReconciliation; await inner.Checkpoints.UpsertAsync(checkpoint, cancellationToken); + if (checkpoint.Name == CloudLocalChangeFeed.CheckpointName) + { + await PauseSizeDiscoveryAsync("size-before-commit", cancellationToken); + } + } + private async ValueTask PauseSizeDiscoveryAsync(string boundary, CancellationToken cancellationToken) + { + if (!owner.Armed || owner._boundary != boundary || Interlocked.Exchange(ref owner._failed, 1) != 0) { return; } + owner.OutcomePaused.TrySetResult(); + await owner.ResumeOutcome.Task.WaitAsync(cancellationToken); } ValueTask ICloudCheckpointRepository.RemoveAsync(string name, CancellationToken cancellationToken) { From 0d8e8fe7f3dad6314882dabd8668a887185b0491 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:39:54 +0800 Subject: [PATCH 05/15] test(local-feed): wait for hydration size processing --- .../ReadOnlyHydrationJournalTests.cs | 74 +++++++++++++------ 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 53aa10f..2da8b82 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -26,7 +26,8 @@ public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWr Assert.Equal(0, before.ModifiedDataSize); string fullPath = fixture.File.FullPath; - await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(); + HydrationJournalSource source = new(fixture.Root); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); Assert.Empty(await AccessRowsAsync(factory!)); Assert.Equal(bytes, await File.ReadAllBytesAsync(fullPath, token)); @@ -37,8 +38,10 @@ public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWr Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); Assert.Equal(0, hydrated.ModifiedDataSize); Assert.Equal(before.LastWriteTime, hydrated.LastWriteTime); - await WaitForHydrationJournalFenceAsync(fixture, factory!, "read-finished"); + await source.WaitForFenceAsync(factory!, "read-finished", CaptureHydratedSize(fixture.File.RelativePath, hydrated)); IReadOnlyList afterRead = await AccessRowsAsync(factory!); + Assert.DoesNotContain(afterRead, row => row.Kind == CloudStateOperationKind.ContentUpdate && + LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath); bytes[0] ^= 0xff; await using (FileStream writer = new(fullPath, FileMode.Open, FileAccess.Write, FileShare.Read)) @@ -48,19 +51,18 @@ public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWr } await WaitForAccessRowsAsync(factory!, rows => rows.Any(row => row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId == identity.ItemId && afterRead.All(previous => previous.OperationId != row.OperationId))); - Assert.DoesNotContain(afterRead, row => row.Kind == CloudStateOperationKind.ContentUpdate && - LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath); await feed.DisposeAsync(); IReadOnlyList edits = (await AccessRowsAsync(factory!)).Where(row => row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId == identity.ItemId).ToArray(); Assert.NotEmpty(edits); await fixture.RestartAsync(); - await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(); + HydrationJournalSource restartedSource = new(fixture.Root); + await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(null, restartedSource); await reopened.StartAsync(token); int fetches = fixture.Provider.Fetches; Assert.Equal(bytes, await File.ReadAllBytesAsync(fullPath, token)); Assert.Equal(fetches, fixture.Provider.Fetches); - await WaitForHydrationJournalFenceAsync(fixture, factory!, "dirty-read-finished"); + await restartedSource.WaitForFenceAsync(factory!, "dirty-read-finished"); IReadOnlyList retained = (await AccessRowsAsync(factory!)).Where(row => row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId == identity.ItemId).ToArray(); Assert.Equal(edits.Select(row => (row.OperationId, row.Sequence)), retained.Select(row => (row.OperationId, row.Sequence))); @@ -99,29 +101,31 @@ public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent .WithInSyncState(true).Build(), ], cancellationToken: token)).ThrowIfAnyFailed(); CloudLocalFileBinding? original = (await fixture.File.InspectAsync(token)).LocalBinding; - await using (CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed()) + HydrationJournalSource source = new(fixture.Root); + await using (CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source)) { await feed.StartAsync(token); await fixture.File.HydrateAsync(new(0, Environment.SystemPageSize), token); CloudItemSnapshot partial = await fixture.File.InspectAsync(token); Assert.Equal(CloudContentAvailability.PartiallyAvailable, partial.ContentAvailability); Assert.Equal(CloudSynchronizationState.InSync, partial.SynchronizationState); - await WaitForHydrationJournalFenceAsync(fixture, factory!, "partial-read-finished"); + await source.WaitForFenceAsync(factory!, "partial-read-finished", CaptureHydratedSize(fixture.File.RelativePath, partial)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); } int firstFetches = fixture.Provider.Fetches; await fixture.RestartAsync(); - await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(); + HydrationJournalSource restartedSource = new(fixture.Root); + await using CloudLocalChangeFeed reopened = fixture.System.CreateLocalChangeFeed(null, restartedSource); await reopened.StartAsync(token); Assert.Equal(bytes, await File.ReadAllBytesAsync(fixture.File.FullPath, token)); Assert.True(fixture.Provider.Fetches > firstFetches); int completedFetches = fixture.Provider.Fetches; Assert.Equal(bytes, await File.ReadAllBytesAsync(fixture.File.FullPath, token)); Assert.Equal(completedFetches, fixture.Provider.Fetches); - await WaitForHydrationJournalFenceAsync(fixture, factory!, "complete-read-finished"); CloudItemSnapshot complete = await fixture.File.InspectAsync(token); Assert.Equal((original, identity.ItemId, identity.RemoteRevision), (complete.LocalBinding, complete.ItemId, complete.RemoteRevision)); Assert.Equal(CloudSynchronizationState.InSync, complete.SynchronizationState); + await restartedSource.WaitForFenceAsync(factory!, "complete-read-finished", CaptureHydratedSize(fixture.File.RelativePath, complete)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 100, token); Assert.False(page.RequiresFullRescan); @@ -154,15 +158,7 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); - Assert.True(hydrated.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); - CloudLocalFileBinding binding = Assert.IsType(hydrated.LocalBinding); - long fileId = Assert.IsType(hydrated.LocalFileId); - // The live-feed tests cover the real size subscription. Freeze the native - // snapshot here so the delayed-delivery test does not depend on whether - // Windows generates a size notice for this particular allocation. - LocalSizeChange size = new(new(binding.VolumeSerialNumber, binding.SyncRootFileId, - unchecked((ulong)fileId), ParentFileId: 0, IsDirectory: false), bytes.Length, hydrated.PlaceholderState); - LocalChangeSourceEvent hydration = new(LocalChangeSourceAction.SizeModified, name, SizeChange: size); + LocalChangeSourceEvent hydration = CaptureHydratedSize(name, hydrated); LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => { await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); @@ -193,11 +189,43 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); } - private static async Task WaitForHydrationJournalFenceAsync(Fixture fixture, AccessJournalFactory factory, string name) + private static LocalChangeSourceEvent CaptureHydratedSize(string relativePath, CloudItemSnapshot hydrated) { - Directory.CreateDirectory(Path.Combine(fixture.Root, name)); - await WaitForAccessRowsAsync(factory, rows => rows.Any(row => row.Kind == CloudStateOperationKind.Create && - LocalChangePayload.Decode(row.Payload).RelativePath == name)); + Assert.True(hydrated.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + CloudLocalFileBinding binding = Assert.IsType(hydrated.LocalBinding); + long fileId = Assert.IsType(hydrated.LocalFileId); + LocalSizeChange size = new(new(binding.VolumeSerialNumber, binding.SyncRootFileId, unchecked((ulong)fileId), + ParentFileId: 0, IsDirectory: false), Assert.IsType(hydrated.Length), hydrated.PlaceholderState); + return new(LocalChangeSourceAction.SizeModified, relativePath, SizeChange: size); + } + + private sealed class HydrationJournalSource(string root) : ILocalChangeSource + { + private const string FencePrefix = "journal-fence-"; + private readonly WindowsLocalChangeSource _native = new(root, 4096); + private Func? _deliver; + + public Task StartAsync(Func eventHandler, CancellationToken cancellationToken) + { + _deliver = eventHandler; + return _native.StartAsync(change => change.RelativePath.StartsWith(FencePrefix, StringComparison.Ordinal) + ? ValueTask.CompletedTask : eventHandler(change), cancellationToken); + } + + internal async Task WaitForFenceAsync(AccessJournalFactory factory, string fence, LocalChangeSourceEvent? size = null) + { + string name = FencePrefix + fence; + Directory.CreateDirectory(Path.Combine(root, name)); + // Windows can coalesce away the actual Size notice. Supply one based on + // the hydrated object's native snapshot, followed by a marker in the same + // channel. A notification from another watcher cannot satisfy the fence. + if (size is { } target) { await _deliver!(target); } + await _deliver!(new(LocalChangeSourceAction.Created, name)); + await WaitForAccessRowsAsync(factory, rows => rows.Any(row => row.Kind == CloudStateOperationKind.Create && + LocalChangePayload.Decode(row.Payload).RelativePath == name)); + } + + public ValueTask DisposeAsync() => _native.DisposeAsync(); } [Fact] From 449efe9af66db43929880f2996dac1010ca36a09 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:56:46 +0800 Subject: [PATCH 06/15] fix(local-feed): require durable identity for ordinary size observations --- docs/local-change-feed.md | 10 ++-- eng/test-ordinary-user-delete.ps1 | 3 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 6 +- .../ReadOnlyHydrationJournalTests.cs | 55 +++++++++++++++++++ 4 files changed, 68 insertions(+), 6 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index 7bd4b3b..b3305b2 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -28,10 +28,12 @@ for a known file placeholder produces no content row when the native notice and object agree on identity, logical length and in-sync state, and Windows reports only validated data. If the object was replaced or the captured and current states disagree, the feed retains an unbound observation and requires reconciliation. Discovery uses the validated file ID and -rechecks the path binding before committing the item and journal row. A size notice delayed -past the removal of an ordinary name also stays unbound, while the ordered name subscription -tracks the removal or move. Last-write notifications remain independent, so a same-length local -write overlapping hydration can still be read and acknowledged separately. +rechecks the path binding before committing the item and journal row. A size notice for an +ordinary file can reuse an existing item ID only when its durable native file ID matches the +observed object. A size notice delayed past the removal of an ordinary name also stays unbound, +while the ordered name subscription tracks the removal or move. Last-write notifications remain +independent, so a same-length local write overlapping hydration can still be read and +acknowledged separately. For newly discovered ordinary files and directories, the feed also retains the native NTFS file reference in the official item row. A later attribute record can bind to that exact object without diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 2763847..4208c8e 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -31,6 +31,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', 'FullyQualifiedName~ReplacedSizeObservationDoesNotDiscoverTheNewOccupant', + 'FullyQualifiedName~OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', 'FullyQualifiedName~ConfirmedFileTimestampPassthroughDoesNotUnbindLaterContent', @@ -72,7 +73,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 88 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 89 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 355977a..1d2e63c 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -29,10 +29,14 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } LocalCloudItemInspection item = CloudItemInspector.Inspect(reference, path.FullPath, kind, _syncRootPath); + // The native notice identifies today's object. To reuse an existing row for + // an ordinary object, its recorded FileId must also identify that object. if (NtfsFileId(item.LocalBinding) is not long fileId || unchecked((ulong)fileId) != identity.FileId || item.LocalBinding?.VolumeSerialNumber != identity.VolumeSerialNumber || item.LocalBinding.SyncRootFileId != identity.RootFileId || - (owner?.LocalFileId is long recorded && recorded != fileId) || owner?.IsTombstone == true || + (owner is not null && (owner.IsTombstone || owner.Kind != kind || + (!capturedPlaceholder && owner.LocalFileId is null) || + (owner.LocalFileId is long recorded && recorded != fileId))) || !MatchesAttributePath(reference, path)) { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 2da8b82..22f1bb6 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -321,4 +321,59 @@ public async Task ReplacedSizeObservationDoesNotDiscoverTheNewOccupant(string bo Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); } + + [Trait("Category", "AccessJournal")] + [Fact] + public async Task OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem() + { + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path)); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); + CancellationToken token = deadline.Token; + string relativePath = fixture.File.RelativePath; + string path = fixture.File.FullPath; + string retiredPath = Path.Combine(fixture.Root, "retired.bin"); + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "original-size-placeholder", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(relativePath, identity, 4096).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + CloudItemState original; + await using (ICloudStateTransaction transaction = await factory!.Store!.BeginTransactionAsync(token)) + { + original = Assert.IsType(await transaction.Items.GetByRelativePathAsync(relativePath, token)); + Assert.Equal(identity.ItemId, original.ItemId); + Assert.Null(original.LocalFileId); + } + + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + File.Move(path, retiredPath); + await File.WriteAllTextAsync(path, "replacement", token); + LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, relativePath, path, token); + Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); + // Deliver Size before the name source has projected the replacement. + await source.EmitAsync(size); + + CloudOperationJournalEntry observation = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + Assert.Equal(CloudStateOperationKind.ContentUpdate, observation.Kind); + Assert.Null(observation.ItemId); + await using (ICloudStateTransaction transaction = await factory.Store!.BeginTransactionAsync(token)) + { + CloudItemState retained = Assert.IsType(await transaction.Items.GetByRelativePathAsync(relativePath, token)); + Assert.Equal((original.ItemId, original.RemoteId, original.RemoteRevision, original.LocalFileId, original.UpdatedAt), + (retained.ItemId, retained.RemoteId, retained.RemoteRevision, retained.LocalFileId, retained.UpdatedAt)); + } + + Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + CloudLocalChange change = Assert.Single(page.Changes); + Assert.Equal((observation.OperationId, observation.Sequence, relativePath), (change.OperationId, change.Sequence, change.RelativePath)); + Assert.Null(change.ItemId); + await feed.AcknowledgeAsync([change.OperationId], token); + Assert.Empty(await AccessRowsAsync(factory)); + Assert.Equal("replacement"u8.ToArray(), (await File.ReadAllBytesAsync(path, token))[..11]); + Assert.True(File.Exists(retiredPath)); + } } From 4c67e11987301eba61e6601ac9f8057198086197 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:55:41 +0800 Subject: [PATCH 07/15] fix(local-feed): keep size notices from establishing namespace ownership --- docs/local-change-feed.md | 10 +-- eng/test-ordinary-user-delete.ps1 | 5 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 17 +++-- .../LocalChanges/CloudLocalChangeFeed.cs | 24 +++---- .../ReadOnlyHydrationJournalTests.cs | 62 ++++++++++++++++++- .../RemoteMetadataRecoveryTests.cs | 6 +- 6 files changed, 90 insertions(+), 34 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index b3305b2..e47fc29 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -27,11 +27,11 @@ hydration increases physical allocation and leaves the logical length unchanged. for a known file placeholder produces no content row when the native notice and the current object agree on identity, logical length and in-sync state, and Windows reports only validated data. If the object was replaced or the captured and current states disagree, the feed retains an -unbound observation and requires reconciliation. Discovery uses the validated file ID and -rechecks the path binding before committing the item and journal row. A size notice for an -ordinary file can reuse an existing item ID only when its durable native file ID matches the -observed object. A size notice delayed past the removal of an ordinary name also stays unbound, -while the ordered name subscription tracks the removal or move. Last-write notifications remain +unbound observation and requires reconciliation. A size notice for a path without an item row +stays unbound. The ordered name subscription establishes ownership, including when Size arrives +before a rename or after an ordinary name disappears. A size notice for an ordinary file can +reuse an existing item ID only when its durable native file ID matches the observed object. +The feed rechecks that binding before committing the journal row. Last-write notifications remain independent, so a same-length local write overlapping hydration can still be read and acknowledged separately. diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 4208c8e..6be25a8 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -30,7 +30,8 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', - 'FullyQualifiedName~ReplacedSizeObservationDoesNotDiscoverTheNewOccupant', + 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', + 'FullyQualifiedName~ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit', 'FullyQualifiedName~OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', @@ -73,7 +74,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 89 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 90 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 1d2e63c..7cc3372 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -8,9 +8,9 @@ namespace CfSharp; public sealed partial class CloudLocalChangeFeed { - private enum SizeObservationDisposition { Content, CleanPlaceholder, MissingOrdinaryObject } + private enum SizeObservationDisposition { Content, CleanPlaceholder, Unbound } - private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState? owner, LocalSizeChange size, + private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState owner, LocalSizeChange size, out CloudLocalFileBinding? binding) { binding = null; @@ -34,9 +34,9 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl if (NtfsFileId(item.LocalBinding) is not long fileId || unchecked((ulong)fileId) != identity.FileId || item.LocalBinding?.VolumeSerialNumber != identity.VolumeSerialNumber || item.LocalBinding.SyncRootFileId != identity.RootFileId || - (owner is not null && (owner.IsTombstone || owner.Kind != kind || - (!capturedPlaceholder && owner.LocalFileId is null) || - (owner.LocalFileId is long recorded && recorded != fileId))) || + owner.IsTombstone || owner.Kind != kind || + (!capturedPlaceholder && owner.LocalFileId is null) || + (owner.LocalFileId is long recorded && recorded != fileId) || !MatchesAttributePath(reference, path)) { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); @@ -48,8 +48,7 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl } binding = item.LocalBinding; if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } - if (owner is not { Kind: CloudItemKind.File } || - !CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || + if (!CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || placeholder.RemoteRevision != owner.RemoteRevision) { @@ -72,12 +71,12 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl } catch (Win32Exception exception) when (kind == CloudItemKind.File && !capturedPlaceholder && exception.NativeErrorCode is 2 or 3) { - return SizeObservationDisposition.MissingOrdinaryObject; + return SizeObservationDisposition.Unbound; } catch (CloudNamespaceObservationUncertainException) when (kind == CloudItemKind.File && !capturedPlaceholder && IsMissingSizeObservationPath(path.FullPath)) { - return SizeObservationDisposition.MissingOrdinaryObject; + return SizeObservationDisposition.Unbound; } catch (Exception exception) when (exception is not CloudNamespaceObservationUncertainException && exception is (CloudPathReparsePointException or CloudFilesException or Win32Exception or diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index cb1844e..e520d42 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -982,15 +982,18 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo { throw new CloudNamespaceObservationUncertainException(size.Identity.IsDirectory); } - SizeObservationDisposition disposition = InspectSizeObservation(path, current, size, out sizeBinding); + SizeObservationDisposition disposition = current is null + ? SizeObservationDisposition.Unbound + : InspectSizeObservation(path, current, size, out sizeBinding); if (disposition == SizeObservationDisposition.CleanPlaceholder) { return null; } - if (disposition == SizeObservationDisposition.MissingOrdinaryObject) + if (disposition == SizeObservationDisposition.Unbound) { - // The independent size source can lag the ordered name/time source. - // A missing ordinary name is not proof of watcher loss. Keep the - // historical observation without rediscovering the old name. - LocalChangePayload historical = new(path.RelativePath, null, IsDirectory: false, observedAt); - await transaction.Operations.EnqueueAsync(new(operationId, CloudStateOperationKind.ContentUpdate, null, + // The independent size source can arrive on either side of a rename. + // Only the ordered name/time source can establish namespace ownership. + LocalChangePayload historical = new(path.RelativePath, null, size.Identity.IsDirectory, observedAt); + CloudStateOperationKind operation = size.Identity.IsDirectory + ? CloudStateOperationKind.MetadataUpdate : CloudStateOperationKind.ContentUpdate; + await transaction.Operations.EnqueueAsync(new(operationId, operation, null, historical.Encode(), observedAt), cancellationToken).ConfigureAwait(false); await UpsertCheckpointAsync(transaction, observation, checkpoint.RequiresFullRescan, observedAt, cancellationToken).ConfigureAwait(false); @@ -1218,16 +1221,13 @@ await UpsertCheckpointAsync( if (uncertainDirectory is null && directoryProjection is null && discovered) { itemId = Guid.NewGuid(); - bool discoveredDirectory = sizeChange?.Identity.IsDirectory ?? Directory.Exists(path.FullPath); state = new CloudItemState( itemId.Value, "local:" + itemId.Value.ToString("N"), path.RelativePath, - discoveredDirectory ? CloudItemKind.Directory : CloudItemKind.File, + Directory.Exists(path.FullPath) ? CloudItemKind.Directory : CloudItemKind.File, remoteRevision: null, - // An independent size notice names the object captured by Windows. - // Ordinary discovery cannot substitute the path's current occupant. - localFileId: sizeBinding is not null ? NtfsFileId(sizeBinding) : TryReadDiscoveredFileId(path), + localFileId: TryReadDiscoveredFileId(path), isTombstone: false, observedAt); } diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 22f1bb6..daaac12 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -277,11 +277,63 @@ private static Task CaptureOrdinarySizeChangeAsync(strin return Task.CompletedTask; }, token, LocalChangeSourceAction.SizeModified); + [Trait("Category", "AccessJournal")] + [Fact] + public async Task SizeBeforeRenamePreservesTheOriginalItemId() + { + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path)); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); + CancellationToken token = deadline.Token; + const string renamed = "renamed.bin"; + string originalPath = Path.Combine(fixture.Root, OriginalSizePath); + string renamedPath = Path.Combine(fixture.Root, renamed); + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + await File.WriteAllTextAsync(originalPath, "original", token); + await source.EmitAsync(new(LocalChangeSourceAction.Created, OriginalSizePath)); + CloudOperationJournalEntry created = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + Guid itemId = Assert.IsType(created.ItemId); + await feed.AcknowledgeAsync([created.OperationId], token); + + File.Move(originalPath, renamedPath); + await source.EmitAsync(await CaptureOrdinarySizeChangeAsync(fixture.Root, renamed, renamedPath, token)); + CloudOperationJournalEntry size = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); + Assert.Null(size.ItemId); + await using (ICloudStateTransaction state = await factory.Store!.BeginTransactionAsync(token)) + { + Assert.Null(await state.Items.GetByRelativePathAsync(renamed, token)); + Assert.Equal(itemId, (await state.Items.GetByRelativePathAsync(OriginalSizePath, token))!.ItemId); + } + + await source.EmitAsync(new(LocalChangeSourceAction.RenamedOldName, OriginalSizePath)); + await source.EmitAsync(new(LocalChangeSourceAction.RenamedNewName, renamed)); + await WaitForAccessRowsAsync(factory, rows => rows.Count == 2); + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + Assert.False(page.RequiresFullRescan); + Assert.Collection(page.Changes, + change => + { + Assert.Equal((size.OperationId, size.Sequence, renamed), (change.OperationId, change.Sequence, change.RelativePath)); + Assert.Equal(CloudLocalChangeKind.ContentUpdate, change.Kind); + Assert.Null(change.ItemId); + }, + change => + { + Assert.Equal(CloudLocalChangeKind.Move, change.Kind); + Assert.Equal((itemId, OriginalSizePath, renamed), (change.ItemId, change.PreviousRelativePath, change.RelativePath)); + }); + await using ICloudStateTransaction confirmed = await factory.Store!.BeginTransactionAsync(token); + CloudItemState owner = Assert.Single(await confirmed.Items.ListSubtreeAsync(string.Empty, token)); + Assert.Equal((itemId, renamed), (owner.ItemId, owner.RelativePath)); + } + [Trait("Category", "AccessJournal")] [Theory] - [InlineData("size-before-discovery")] + [InlineData("size-before-append")] [InlineData("size-before-commit")] - public async Task ReplacedSizeObservationDoesNotDiscoverTheNewOccupant(string boundary) + public async Task ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit(string boundary) { MetadataFaultFactory? factory = null; await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path, boundary)); @@ -294,6 +346,9 @@ public async Task ReplacedSizeObservationDoesNotDiscoverTheNewOccupant(string bo ControlledMetadataSource source = new(); await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); + await source.EmitAsync(new(LocalChangeSourceAction.Created, OriginalSizePath)); + CloudOperationJournalEntry created = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + await feed.AcknowledgeAsync([created.OperationId], token); factory!.Armed = true; await source.EmitAsync(size); try @@ -309,7 +364,8 @@ public async Task ReplacedSizeObservationDoesNotDiscoverTheNewOccupant(string bo Assert.Equal(CloudStateOperationKind.ContentUpdate, original.Kind); await using (ICloudStateTransaction transaction = await factory.Store!.BeginTransactionAsync(token)) { - Assert.Null(await transaction.Items.GetByRelativePathAsync(OriginalSizePath, token)); + CloudItemState retainedOwner = Assert.Single(await transaction.Items.ListSubtreeAsync(string.Empty, token)); + Assert.Equal((created.ItemId, OriginalSizePath), (retainedOwner.ItemId, retainedOwner.RelativePath)); } Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); diff --git a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs index 8165730..fa5eb0e 100644 --- a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs +++ b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs @@ -1661,7 +1661,7 @@ private sealed class FaultTransaction(ICloudStateTransaction inner, MetadataFaul public ICloudItemStateRepository Items => inner.Items; public ICloudCheckpointRepository Checkpoints => owner.OverlappingWrites || owner._boundary is "rescan-before-preparation" or "metadata-cancel-preparation" or - "size-before-discovery" or "size-before-commit" ? this : inner.Checkpoints; + "size-before-append" or "size-before-commit" ? this : inner.Checkpoints; public ICloudOperationJournal Operations => inner.Operations; public ICloudConflictRepository Conflicts => inner.Conflicts; public ICloudRemoteBatchRepository RemoteBatches => owner.OverlappingWrites ? this : inner.RemoteBatches; @@ -1669,9 +1669,9 @@ owner._boundary is "rescan-before-preparation" or "metadata-cancel-preparation" async ValueTask ICloudCheckpointRepository.GetAsync(string name, CancellationToken cancellationToken) { - if (owner._boundary == "size-before-discovery" && name == RemoteMetadataIntent.DirectoryTimeObservationName(OriginalSizePath)) + if (owner._boundary == "size-before-append" && name == RemoteMetadataIntent.DirectoryTimeObservationName(OriginalSizePath)) { - await PauseSizeDiscoveryAsync("size-before-discovery", cancellationToken); + await PauseSizeDiscoveryAsync("size-before-append", cancellationToken); } return await inner.Checkpoints.GetAsync(name, cancellationToken); } From 16e2413e0ca61a75af6c4439fa55b51c66bbffa0 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:01:14 +0800 Subject: [PATCH 08/15] fix(local-feed): withhold size bindings until post-commit validation --- docs/local-change-feed.md | 9 ++- eng/test-ordinary-user-delete.ps1 | 4 +- .../CloudLocalChangeFeed.Scans.cs | 2 +- .../CloudLocalChangeFeed.Security.cs | 71 ++++++++++++------- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 12 ++++ .../LocalChanges/CloudLocalChangeFeed.cs | 36 ++++++---- .../ReadOnlyHydrationJournalTests.cs | 50 ++++++++++--- .../RemoteMetadataRecoveryTests.cs | 4 +- ...loudLocalChangeMetadataPublicationTests.cs | 8 ++- 9 files changed, 138 insertions(+), 58 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index e47fc29..bdd5ad4 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -31,9 +31,12 @@ unbound observation and requires reconciliation. A size notice for a path withou stays unbound. The ordered name subscription establishes ownership, including when Size arrives before a rename or after an ordinary name disappears. A size notice for an ordinary file can reuse an existing item ID only when its durable native file ID matches the observed object. -The feed rechecks that binding before committing the journal row. Last-write notifications remain -independent, so a same-length local write overlapping hydration can still be read and -acknowledged separately. +The feed rechecks that binding before and after committing the journal row. A durable validation +receipt withholds the row from reads and acknowledgement until the second check. If the object +changed or the feed stopped during publication, reconciliation exposes the original operation +with the same ID and sequence and no item association. Last-write notifications remain +independent, so a same-length local write overlapping hydration can still be read and acknowledged +separately. For newly discovered ordinary files and directories, the feed also retains the native NTFS file reference in the official item row. A later attribute record can bind to that exact object without diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 6be25a8..9a0236e 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -31,7 +31,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', - 'FullyQualifiedName~ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit', + 'FullyQualifiedName~TrackedSizeObservationPublishesOnlyVerifiedAssociation', 'FullyQualifiedName~OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', @@ -74,7 +74,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 90 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 92 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Scans.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Scans.cs index dd644b8..3fda478 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Scans.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Scans.cs @@ -126,7 +126,7 @@ public async ValueTask ReadPageAsync(CloudLocalChangeScan bool rescan = scan.RequiresFullRescan || HasUnpersistedLoss || ScanIsInvalidated(scan) || await RequiresScanReconciliationAsync(transaction, cancellationToken).ConfigureAwait(false); - int validatedCount = rescan ? 0 : await ValidatedMetadataPrefixLengthAsync(transaction, journalPage.Operations, cancellationToken).ConfigureAwait(false); + int validatedCount = rescan ? 0 : await ValidatedObservationPrefixLengthAsync(transaction, journalPage.Operations, cancellationToken).ConfigureAwait(false); bool pendingValidation = validatedCount < journalPage.Operations.Count; CloudLocalChange[] changes = rescan ? [] : journalPage.Operations.Take(validatedCount).Select(DecodeScannedChange).ToArray(); long lastScanned = pendingValidation diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs index 5d133f1..2f5873a 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs @@ -10,7 +10,7 @@ namespace CfSharp; public sealed partial class CloudLocalChangeFeed { internal const string SecurityValidationPrefix = "cfsharp/security-validation/v1/"; - private long _validatedAttributeSequence; + private long _validatedObservationSequence; private static string SecurityValidationName(Guid operationId) => SecurityValidationPrefix + operationId.ToString("N"); @@ -65,20 +65,23 @@ private async ValueTask PublishValidatedSecurityObservationAsync(CloudOperationJ if (projection.AllowsRename) { projection.Validate(); - // The worker serializes publication, so one monotonic watermark covers all - // successfully validated rows without retaining an unbounded per-operation cache. - Volatile.Write(ref _validatedAttributeSequence, published.Sequence); - SignalAvailable(); - // Eligibility is established above, without another publication commit window. - // A crash before this bookkeeping completes leaves the receipt for safe recovery. - await using ICloudStateTransaction completed = await _stateStore.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); - await completed.Checkpoints.RemoveAsync(receipt, cancellationToken).ConfigureAwait(false); - await completed.CommitAsync(cancellationToken).ConfigureAwait(false); + await CompleteValidatedObservationAsync(published.OperationId, published.Sequence, cancellationToken).ConfigureAwait(false); } else { SignalAvailable(); } } - private async ValueTask ValidatedMetadataPrefixLengthAsync(ICloudStateTransaction transaction, + private async ValueTask CompleteValidatedObservationAsync(Guid operationId, long sequence, CancellationToken cancellationToken) + { + // One worker serializes publication. Advance the watermark only after the + // native binding is checked, then remove the durable recovery receipt. + Volatile.Write(ref _validatedObservationSequence, sequence); + SignalAvailable(); + await using ICloudStateTransaction transaction = await _stateStore.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + await transaction.Checkpoints.RemoveAsync(SecurityValidationName(operationId), cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + private async ValueTask ValidatedObservationPrefixLengthAsync(ICloudStateTransaction transaction, IReadOnlyList operations, CancellationToken cancellationToken) { if (operations.Count == 0) { return 0; } @@ -86,7 +89,7 @@ private async ValueTask ValidatedMetadataPrefixLengthAsync(ICloudStateTrans cancellationToken).ConfigureAwait(false); if (receipts.Count == 0) { return operations.Count; } HashSet pending = new(receipts.Select(receipt => receipt.Name), StringComparer.Ordinal); - long validated = Volatile.Read(ref _validatedAttributeSequence); + long validated = Volatile.Read(ref _validatedObservationSequence); for (int index = 0; index < operations.Count; index++) { CloudOperationJournalEntry operation = operations[index]; @@ -95,19 +98,27 @@ private async ValueTask ValidatedMetadataPrefixLengthAsync(ICloudStateTrans return operations.Count; } - private static async ValueTask RetainUnboundSecurityObservationAsync(ICloudStateTransaction transaction, Guid operationId, - ReadOnlyMemory payload, DateTimeOffset observedAt, CancellationToken cancellationToken) + private static async ValueTask RetainUnboundObservationAsync(ICloudStateTransaction transaction, Guid operationId, + ReadOnlyMemory payload, DateTimeOffset observedAt, CancellationToken cancellationToken, + CloudStateOperationKind? kind = CloudStateOperationKind.MetadataUpdate) { CloudOperationJournalEntry? existing = await transaction.Operations.GetAsync(operationId, cancellationToken).ConfigureAwait(false); + // Size receipts commit with their journal row. A receipt with no row can + // come from the initial staging transaction for a metadata observation. + CloudStateOperationKind operationKind = kind ?? existing?.Kind ?? CloudStateOperationKind.MetadataUpdate; + if (operationKind is not (CloudStateOperationKind.MetadataUpdate or CloudStateOperationKind.ContentUpdate) || + (existing is not null && existing.Kind != operationKind)) + { + throw new InvalidDataException("An observation validation receipt references a different operation kind."); + } if (existing is null) { - await transaction.Operations.EnqueueAsync(new(operationId, CloudStateOperationKind.MetadataUpdate, null, + await transaction.Operations.EnqueueAsync(new(operationId, operationKind, null, payload.Span, observedAt), cancellationToken).ConfigureAwait(false); } else if (existing.ItemId is not null) { RequireJournalAssociationUpdates(transaction); - if (existing.Kind != CloudStateOperationKind.MetadataUpdate) { throw new InvalidDataException("A metadata validation receipt references a different operation kind."); } // The row may already have committed while its validation receipt still withheld // delivery. Clear only its association, preserving ordering and retry metadata. CloudOperationJournalEntry unbound = new(existing.OperationId, existing.Kind, null, @@ -119,17 +130,18 @@ await transaction.Operations.EnqueueAsync(new(operationId, CloudStateOperationKi CloudOperationJournalEntry? retained = await transaction.Operations.GetAsync(operationId, cancellationToken).ConfigureAwait(false); if (retained is null || retained.ItemId is not null) { - throw new NotSupportedException("The custom operation journal must clear an item's association during metadata recovery. The validation receipt remains pending."); + throw new NotSupportedException("The custom operation journal must clear an item's association during observation recovery. The validation receipt remains pending."); } if (retained.OperationId != existing.OperationId || retained.Sequence != existing.Sequence || retained.Kind != existing.Kind || retained.CreatedAt != existing.CreatedAt || retained.AttemptCount != existing.AttemptCount || retained.RetryAfter != existing.RetryAfter || !retained.Payload.Span.SequenceEqual(existing.Payload.Span)) { - throw new InvalidDataException("The custom operation journal changed the original metadata observation during recovery."); + throw new InvalidDataException("The custom operation journal changed the original observation during recovery."); } } await transaction.Checkpoints.RemoveAsync(SecurityValidationName(operationId), cancellationToken).ConfigureAwait(false); + return operationKind; } private static void RequireJournalAssociationUpdates(ICloudStateTransaction transaction) @@ -140,7 +152,7 @@ private static void RequireJournalAssociationUpdates(ICloudStateTransaction tran } } - private static async ValueTask RecoverStagedSecurityObservationsAsync(ICloudStateTransaction transaction, + private static async ValueTask RecoverStagedObservationsAsync(ICloudStateTransaction transaction, CancellationToken cancellationToken) { IReadOnlyList receipts = await transaction.Checkpoints.ListAsync(SecurityValidationPrefix, @@ -149,13 +161,13 @@ private static async ValueTask RecoverStagedSecurityObservationsAsync(IClo { if (!Guid.TryParseExact(receipt.Name.AsSpan(SecurityValidationPrefix.Length), "N", out Guid operationId) || operationId == Guid.Empty) { - throw new InvalidDataException("A staged security observation has an invalid operation identifier."); + throw new InvalidDataException("A staged observation has an invalid operation identifier."); } LocalChangePayload payload = LocalChangePayload.Decode(receipt.Value); - await RetainUnboundSecurityObservationAsync(transaction, operationId, receipt.Value, payload.ObservedAt, - cancellationToken).ConfigureAwait(false); - if (payload.IsDirectory) + CloudStateOperationKind kind = await RetainUnboundObservationAsync(transaction, operationId, receipt.Value, payload.ObservedAt, + cancellationToken, kind: null).ConfigureAwait(false); + if (payload.IsDirectory || kind == CloudStateOperationKind.ContentUpdate) { CloudItemState? owner = await transaction.Items.GetByRelativePathAsync(payload.RelativePath, cancellationToken).ConfigureAwait(false); await RetainMetadataObservationProtectionAsync(transaction.Checkpoints, payload.RelativePath, owner, @@ -168,9 +180,20 @@ await transaction.Checkpoints.UpsertAsync(new(NamespaceObservationsPrefix + "/" return receipts.Count != 0; } + private interface IStagedObservation : IDisposable + { + ValueTask PublishAsync(CloudLocalChangeFeed feed, CancellationToken cancellationToken); + } + private sealed record StagedSecurityObservation(CloudOperationJournalEntry Entry, SecurityFeedProjection Projection, - LocalChangeSourceEvent Observation) : IDisposable + LocalChangeSourceEvent Observation) : IStagedObservation { + public ValueTask PublishAsync(CloudLocalChangeFeed feed, CancellationToken cancellationToken) + { + Projection.Validate(); + return feed.PublishValidatedSecurityObservationAsync(Entry, Projection, Observation, cancellationToken); + } + public void Dispose() => Projection.Dispose(); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 7cc3372..977b26b 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -10,6 +10,18 @@ public sealed partial class CloudLocalChangeFeed { private enum SizeObservationDisposition { Content, CleanPlaceholder, Unbound } + private sealed record StagedSizeObservation(CloudItemPath Path, CloudLocalFileBinding Binding, + bool IsDirectory, CloudOperationJournalEntry Entry) : IStagedObservation + { + public ValueTask PublishAsync(CloudLocalChangeFeed feed, CancellationToken cancellationToken) + { + feed.ValidateSizeObservationBinding(Path, Binding, IsDirectory); + return feed.CompleteValidatedObservationAsync(Entry.OperationId, Entry.Sequence, cancellationToken); + } + + public void Dispose() { } + } + private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState owner, LocalSizeChange size, out CloudLocalFileBinding? binding) { diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index e520d42..95032b4 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -197,7 +197,7 @@ public async ValueTask ReadBatchAsync( await RequiresMetadataReconciliationAsync(transaction, cancellationToken).ConfigureAwait(false); IReadOnlyList operations = await transaction.Operations .ListAsync(_options.BatchSize, cancellationToken).ConfigureAwait(false); - int validatedCount = await ValidatedMetadataPrefixLengthAsync(transaction, operations, cancellationToken).ConfigureAwait(false); + int validatedCount = await ValidatedObservationPrefixLengthAsync(transaction, operations, cancellationToken).ConfigureAwait(false); await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false); ThrowIfFailed(); // Persistence can clear HasUnpersistedLoss after this snapshot was read. Capture @@ -290,9 +290,9 @@ public async ValueTask AcknowledgeAsync( .ConfigureAwait(false); if (operation is not null) { - if (await ValidatedMetadataPrefixLengthAsync(transaction, [operation], cancellationToken).ConfigureAwait(false) == 0) + if (await ValidatedObservationPrefixLengthAsync(transaction, [operation], cancellationToken).ConfigureAwait(false) == 0) { - throw new InvalidOperationException("The local metadata observation has not completed validation."); + throw new InvalidOperationException("The local observation has not completed validation."); } if (acknowledgement.RemoteRevision is not null && operation.ItemId is Guid itemId) { @@ -925,7 +925,7 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo CancellationToken cancellationToken, LocalChangeSourceEvent? securityObservation = null, LocalSizeChange? sizeChange = null) { using IDisposable? publication = await AcquirePublicationAsync(cancellationToken).ConfigureAwait(false); - StagedSecurityObservation? staged = null; + IStagedObservation? staged = null; try { await using (ICloudStateTransaction transaction = await _stateStore.BeginTransactionAsync(cancellationToken).ConfigureAwait(false)) @@ -936,8 +936,7 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo if (staged is not null) { - staged.Projection.Validate(); - await PublishValidatedSecurityObservationAsync(staged.Entry, staged.Projection, staged.Observation, cancellationToken).ConfigureAwait(false); + await staged.PublishAsync(this, cancellationToken).ConfigureAwait(false); } } finally @@ -946,7 +945,7 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo } } - private async ValueTask PersistChangeCoreAsync(ICloudStateTransaction transaction, + private async ValueTask PersistChangeCoreAsync(ICloudStateTransaction transaction, CloudLocalChangeKind kind, CloudItemPath path, CloudItemPath? previousPath, Guid operationId, DateTimeOffset observedAt, bool? uncertainDirectory, LocalChangeSourceEvent? securityObservation, LocalSizeChange? sizeChange, CancellationToken cancellationToken) @@ -1082,12 +1081,12 @@ await UpsertCheckpointAsync(transaction, observation, checkpoint.RequiresFullRes LocalChangePayload uncertain = new(path.RelativePath, previousPath?.RelativePath, directoryObservation, observedAt); if (uncertainFileContent) { - await transaction.Operations.EnqueueAsync(new(operationId, CloudStateOperationKind.ContentUpdate, null, - uncertain.Encode(), observedAt), cancellationToken).ConfigureAwait(false); + await RetainUnboundObservationAsync(transaction, operationId, uncertain.Encode(), observedAt, + cancellationToken, CloudStateOperationKind.ContentUpdate).ConfigureAwait(false); } else if (securityObservation is not null || pendingMetadata) { - await RetainUnboundSecurityObservationAsync(transaction, operationId, uncertain.Encode(), observedAt, + await RetainUnboundObservationAsync(transaction, operationId, uncertain.Encode(), observedAt, cancellationToken).ConfigureAwait(false); } if (uncertainFileContent || ambiguousDirectoryGeneration) @@ -1263,13 +1262,23 @@ await CloudDirectoryProvenance.RefreshProjectionAncestorsAsync(transaction, path observedAt); byte[] encoded = payload.Encode(); CloudOperationJournalEntry entry = new(operationId, operationKind, itemId, encoded, observedAt); + StagedSizeObservation? stagedSize = null; if (securityObservation is not null) { - await RetainUnboundSecurityObservationAsync(transaction, operationId, encoded, observedAt, cancellationToken).ConfigureAwait(false); + await RetainUnboundObservationAsync(transaction, operationId, encoded, observedAt, cancellationToken).ConfigureAwait(false); } else if (await transaction.Operations.GetAsync(operationId, cancellationToken).ConfigureAwait(false) is null) { - await transaction.Operations.EnqueueAsync(entry, cancellationToken).ConfigureAwait(false); + CloudOperationJournalEntry appended = await transaction.Operations.EnqueueAsync(entry, cancellationToken).ConfigureAwait(false); + if (sizeBinding is not null) + { + RequireJournalAssociationUpdates(transaction); + // Commit the row and its validation receipt together. The worker + // rechecks the binding after the store releases the transaction. + await transaction.Checkpoints.UpsertAsync(new(SecurityValidationName(operationId), encoded, observedAt), + cancellationToken).ConfigureAwait(false); + stagedSize = new(path, sizeBinding, directory, appended); + } } bool requiresRescan = uncertainDirectory is not null || directoryProjection?.RequiresRescan == true; @@ -1295,6 +1304,7 @@ await UpsertCheckpointAsync( } directoryProjection?.Validate(); + if (stagedSize is not null) { return stagedSize; } SignalAvailable(); return null; @@ -1419,7 +1429,7 @@ private async ValueTask LoadCheckpointAsync(CancellationToken cancellationToken) await RecoverMetadataIntentsAsync(transaction, cancellationToken).ConfigureAwait(false); (bool retiredTimeMarkers, bool timeMarkersRequireReconciliation) = await RetireTimeObservationsBeforeStartingAsync(transaction.Checkpoints, cancellationToken).ConfigureAwait(false); - bool recoveredObservations = await RecoverStagedSecurityObservationsAsync(transaction, cancellationToken).ConfigureAwait(false); + bool recoveredObservations = await RecoverStagedObservationsAsync(transaction, cancellationToken).ConfigureAwait(false); if (recoveredObservations || metadataRequiresReconciliation || timeMarkersRequireReconciliation) { await UpsertCheckpointAsync(transaction, checkpoint.Observation, true, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false); diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index daaac12..1ca4289 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -331,9 +331,11 @@ public async Task SizeBeforeRenamePreservesTheOriginalItemId() [Trait("Category", "AccessJournal")] [Theory] - [InlineData("size-before-append")] - [InlineData("size-before-commit")] - public async Task ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit(string boundary) + [InlineData("size-before-append", true)] + [InlineData("size-before-commit", true)] + [InlineData("size-publication-committed", true)] + [InlineData("size-publication-committed", false)] + public async Task TrackedSizeObservationPublishesOnlyVerifiedAssociation(string boundary, bool replace) { MetadataFaultFactory? factory = null; await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path, boundary)); @@ -351,16 +353,39 @@ public async Task ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit(strin await feed.AcknowledgeAsync([created.OperationId], token); factory!.Armed = true; await source.EmitAsync(size); + CloudOperationJournalEntry? provisional = null; try { await factory.OutcomePaused.Task.WaitAsync(token); - File.Move(path, retiredPath); - await File.WriteAllBytesAsync(path, new byte[4096], token); + if (replace) + { + File.Move(path, retiredPath); + await File.WriteAllBytesAsync(path, new byte[4096], token); + } + if (boundary == "size-publication-committed") + { + provisional = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); + Assert.Equal(created.ItemId, provisional.ItemId); + CloudLocalChangePage waiting = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + Assert.False(waiting.RequiresFullRescan); + Assert.Empty(waiting.Changes); + Assert.True(waiting.HasMore); + Assert.Equal(0, waiting.LastScannedSequence); + await Assert.ThrowsAsync(() => feed.AcknowledgeAsync([provisional.OperationId], token).AsTask()); + } } finally { factory.ResumeOutcome.TrySetResult(); } + CloudLocalChangeBatch published = await feed.ReadBatchAsync(token); + Assert.Equal(replace, published.RequiresFullRescan); + if (replace) { await WaitForMetadataRescanMarkerAsync(factory.Store!, token); } CloudOperationJournalEntry original = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); - Assert.Null(original.ItemId); + if (provisional is not null) + { + Assert.Equal((provisional.OperationId, provisional.Sequence), (original.OperationId, original.Sequence)); + } + Guid? expectedItemId = replace ? null : created.ItemId; + Assert.Equal(expectedItemId, original.ItemId); Assert.Equal(CloudStateOperationKind.ContentUpdate, original.Kind); await using (ICloudStateTransaction transaction = await factory.Store!.BeginTransactionAsync(token)) { @@ -368,14 +393,17 @@ public async Task ReplacedTrackedSizeObservationRemainsUnboundBeforeCommit(strin Assert.Equal((created.ItemId, OriginalSizePath), (retainedOwner.ItemId, retainedOwner.RelativePath)); } - Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); - await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + if (replace) + { + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); + Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); + } CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); CloudLocalChange retained = Assert.Single(page.Changes); Assert.Equal((original.OperationId, original.Sequence, OriginalSizePath), (retained.OperationId, retained.Sequence, retained.RelativePath)); - Assert.Null(retained.ItemId); - Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); - Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); + Assert.Equal(expectedItemId, retained.ItemId); + await feed.AcknowledgeAsync([retained.OperationId], token); } [Trait("Category", "AccessJournal")] diff --git a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs index fa5eb0e..51b36a8 100644 --- a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs +++ b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs @@ -1749,6 +1749,8 @@ public async ValueTask CommitAsync(CancellationToken cancellationToken = default "conflict-outcome-before" => owner.CancelConflictOutcome is { } configured && await Conflicts.GetAsync(configured.ConflictId, cancellationToken) is null, "staging-after" or "staging-paused-after" => staged is not null, + "size-publication-committed" => (await Operations.ListAsync(2, cancellationToken)) + .Any(row => row.Kind == CloudStateOperationKind.ContentUpdate && row.ItemId.HasValue), "passthrough-confirmation-before" => intents.Any(intent => intent.OutcomeConfirmed), "rescan-awaiting-authorization" => intents.Any(intent => intent.OutcomeConfirmed), "overlapping-outcome" => intents.Any(intent => intent.Completed && !intent.OutcomeConfirmed), @@ -1779,7 +1781,7 @@ await Conflicts.GetAsync(configured.ConflictId, cancellationToken) is null, return; } if (owner._boundary is "preparation-paused-after" or "native-projection-paused-after" or - "rescan-awaiting-authorization" or "staging-paused-after") + "rescan-awaiting-authorization" or "staging-paused-after" or "size-publication-committed") { await inner.CommitAsync(cancellationToken); owner.OutcomePaused.TrySetResult(); diff --git a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs index 24f3b51..7b46973 100644 --- a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs +++ b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs @@ -38,8 +38,10 @@ public async Task UnvalidatedMetadataWithholdsOnlyItsSuffixWithoutAdvancingTheCu Assert.True((await reopened.BeginScanAsync()).RequiresFullRescan); } - [Fact] - public async Task CommittedUnvalidatedMetadataRecoversUnboundWithItsOriginalSequence() + [Theory] + [InlineData(CloudStateOperationKind.MetadataUpdate)] + [InlineData(CloudStateOperationKind.ContentUpdate)] + public async Task CommittedUnvalidatedObservationRecoversUnboundWithItsOriginalSequence(CloudStateOperationKind kind) { await using ICloudStateStore store = await OpenStoreAsync(); Guid operationId = Guid.NewGuid(); @@ -51,7 +53,7 @@ public async Task CommittedUnvalidatedMetadataRecoversUnboundWithItsOriginalSequ { await interrupted.Items.UpsertAsync(new(itemId, "original", "history.bin", CloudItemKind.File, "accepted", null, false, observedAt)); - original = await interrupted.Operations.EnqueueAsync(new(operationId, CloudStateOperationKind.MetadataUpdate, + original = await interrupted.Operations.EnqueueAsync(new(operationId, kind, itemId, payload, observedAt, attemptCount: 2, retryAfter: observedAt.AddMinutes(1))); await interrupted.Checkpoints.UpsertAsync(new(CloudLocalChangeFeed.SecurityValidationPrefix + operationId.ToString("N"), payload, observedAt)); From 786227637737c4dc3b07904d64e9f15c77899554 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:39:00 +0800 Subject: [PATCH 09/15] fix(local-feed): revalidate the placeholder identity of size notices --- docs/local-change-feed.md | 3 +- eng/test-ordinary-user-delete.ps1 | 2 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 40 ++++++--- .../LocalChanges/CloudLocalChangeFeed.cs | 8 +- .../ReadOnlyHydrationJournalTests.cs | 85 ++++++++++++++----- 5 files changed, 97 insertions(+), 41 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index bdd5ad4..8018bd0 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -31,7 +31,8 @@ unbound observation and requires reconciliation. A size notice for a path withou stays unbound. The ordered name subscription establishes ownership, including when Size arrives before a rename or after an ordinary name disappears. A size notice for an ordinary file can reuse an existing item ID only when its durable native file ID matches the observed object. -The feed rechecks that binding before and after committing the journal row. A durable validation +The feed rechecks the native binding and any placeholder's item ID, remote ID and revision +before and after committing the journal row. A durable validation receipt withholds the row from reads and acknowledgement until the second check. If the object changed or the feed stopped during publication, reconciliation exposes the original operation with the same ID and sequence and no item association. Last-write notifications remain diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 9a0236e..6b2145b 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -74,7 +74,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 92 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 94 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 977b26b..d228d5e 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -10,12 +10,15 @@ public sealed partial class CloudLocalChangeFeed { private enum SizeObservationDisposition { Content, CleanPlaceholder, Unbound } - private sealed record StagedSizeObservation(CloudItemPath Path, CloudLocalFileBinding Binding, - bool IsDirectory, CloudOperationJournalEntry Entry) : IStagedObservation + private sealed record SizeObservationBinding(CloudLocalFileBinding Local, CloudItemKind Kind, + CloudPlaceholderIdentity? Placeholder); + + private sealed record StagedSizeObservation(CloudItemPath Path, SizeObservationBinding Binding, + CloudOperationJournalEntry Entry) : IStagedObservation { public ValueTask PublishAsync(CloudLocalChangeFeed feed, CancellationToken cancellationToken) { - feed.ValidateSizeObservationBinding(Path, Binding, IsDirectory); + feed.ValidateSizeObservationBinding(Path, Binding); return feed.CompleteValidatedObservationAsync(Entry.OperationId, Entry.Sequence, cancellationToken); } @@ -23,7 +26,7 @@ public void Dispose() { } } private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState owner, LocalSizeChange size, - out CloudLocalFileBinding? binding) + out SizeObservationBinding? binding) { binding = null; LocalSecurityChangeIdentity identity = size.Identity; @@ -58,14 +61,16 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } - binding = item.LocalBinding; - if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } - if (!CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? placeholder) || - placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || - placeholder.RemoteRevision != owner.RemoteRevision) + CloudPlaceholderIdentity? placeholder = null; + if (capturedPlaceholder && + (!CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out placeholder) || + placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || + placeholder.RemoteRevision != owner.RemoteRevision)) { - throw new CloudNamespaceObservationUncertainException(isDirectory: false); + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } + binding = new(item.LocalBinding, kind, placeholder); + if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } // On Windows, hydration can change allocation and signal Size while the // placeholder remains in sync. A logical data modification clears in-sync. @@ -98,8 +103,9 @@ exception is (CloudPathReparsePointException or CloudFilesException or Win32Exce } } - private void ValidateSizeObservationBinding(CloudItemPath path, CloudLocalFileBinding binding, bool isDirectory) + private void ValidateSizeObservationBinding(CloudItemPath path, SizeObservationBinding binding) { + bool isDirectory = binding.Kind == CloudItemKind.Directory; if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) { throw new CloudNamespaceObservationUncertainException(isDirectory); @@ -107,13 +113,19 @@ private void ValidateSizeObservationBinding(CloudItemPath path, CloudLocalFileBi try { using SafeFileHandle reference = WindowsFileMetadata.OpenMetadataReference(path.FullPath); - if (CloudLocalFileBindingPlatform.TryRead(reference.DangerousGetHandle(), _syncRootPath) == binding && - MatchesAttributePath(reference, path)) + LocalCloudItemInspection item = CloudItemInspector.Inspect(reference, path.FullPath, binding.Kind, _syncRootPath); + // An in-place CFAPI update can change the cloud identity while preserving the NTFS file ID. + bool sameIdentity = binding.Placeholder is null + ? !item.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder) + : CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? current) && + binding.Placeholder.Equals(current); + if (item.LocalBinding == binding.Local && sameIdentity && MatchesAttributePath(reference, path)) { return; } } - catch (Exception exception) when (exception is CloudPathReparsePointException or Win32Exception or IOException or UnauthorizedAccessException) + catch (Exception exception) when (exception is CloudPathReparsePointException or CloudFilesException or + Win32Exception or UnauthorizedAccessException or InvalidOperationException or IOException) { throw new CloudNamespaceObservationUncertainException(isDirectory, exception); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index 95032b4..bfae53f 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -974,7 +974,7 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo IReadOnlyList deletes = await transaction.Checkpoints.ListAsync(RemoteDeleteIntent.Prefix, cancellationToken).ConfigureAwait(false); bool pendingDelete = deletes.Select(value => RemoteDeleteIntent.Decode(value.Value)).Any(intent => intent.Contains(path.RelativePath) || (previousPath is not null && intent.Contains(previousPath.Value.RelativePath))); - CloudLocalFileBinding? sizeBinding = null; + SizeObservationBinding? sizeBinding = null; if (sizeChange is { } size && uncertainDirectory is null) { if (pendingCreation || pendingMove || pendingDelete) @@ -1201,7 +1201,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); - if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding, directory); } + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); SignalAvailable(); @@ -1277,7 +1277,7 @@ await CloudDirectoryProvenance.RefreshProjectionAncestorsAsync(transaction, path // rechecks the binding after the store releases the transaction. await transaction.Checkpoints.UpsertAsync(new(SecurityValidationName(operationId), encoded, observedAt), cancellationToken).ConfigureAwait(false); - stagedSize = new(path, sizeBinding, directory, appended); + stagedSize = new(path, sizeBinding, appended); } } @@ -1296,7 +1296,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); - if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding, directory); } + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); if (requiresRescan) { diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 1ca4289..1719df8 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -242,7 +242,7 @@ public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); await File.WriteAllTextAsync(originalPath, "local content", token); - LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, original, originalPath, token); + LocalChangeSourceEvent size = await CaptureSizeChangeAsync(fixture.Root, original, originalPath, token); Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); await source.EmitAsync(new(LocalChangeSourceAction.Created, original)); await WaitForAccessRowsAsync(factory!, rows => rows.Count == 1); @@ -268,7 +268,7 @@ public async Task DelayedOrdinarySizeNoticeDoesNotInterruptTheOrderedMove() Assert.Null(await state.Items.GetByRelativePathAsync(original, token)); } - private static Task CaptureOrdinarySizeChangeAsync(string root, string relativePath, string fullPath, CancellationToken token) => + private static Task CaptureSizeChangeAsync(string root, string relativePath, string fullPath, CancellationToken token) => CaptureNativeModificationAsync(root, relativePath, () => { using FileStream file = new(fullPath, FileMode.Open, FileAccess.Write, FileShare.Read); @@ -298,7 +298,7 @@ public async Task SizeBeforeRenamePreservesTheOriginalItemId() await feed.AcknowledgeAsync([created.OperationId], token); File.Move(originalPath, renamedPath); - await source.EmitAsync(await CaptureOrdinarySizeChangeAsync(fixture.Root, renamed, renamedPath, token)); + await source.EmitAsync(await CaptureSizeChangeAsync(fixture.Root, renamed, renamedPath, token)); CloudOperationJournalEntry size = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); Assert.Null(size.ItemId); await using (ICloudStateTransaction state = await factory.Store!.BeginTransactionAsync(token)) @@ -331,33 +331,72 @@ public async Task SizeBeforeRenamePreservesTheOriginalItemId() [Trait("Category", "AccessJournal")] [Theory] - [InlineData("size-before-append", true)] - [InlineData("size-before-commit", true)] - [InlineData("size-publication-committed", true)] - [InlineData("size-publication-committed", false)] - public async Task TrackedSizeObservationPublishesOnlyVerifiedAssociation(string boundary, bool replace) + [InlineData("size-before-append", true, false)] + [InlineData("size-before-commit", true, false)] + [InlineData("size-publication-committed", true, false)] + [InlineData("size-publication-committed", false, false)] + [InlineData("size-publication-committed", true, true)] + [InlineData("size-publication-committed", false, true)] + public async Task TrackedSizeObservationPublishesOnlyVerifiedAssociation(string boundary, bool replace, bool placeholder) { MetadataFaultFactory? factory = null; - await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path, boundary)); + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path, boundary), hydrationContent: "old"u8.ToArray()); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(20)); CancellationToken token = deadline.Token; string path = Path.Combine(fixture.Root, OriginalSizePath); string retiredPath = Path.Combine(fixture.Root, "retired.bin"); - await File.WriteAllTextAsync(path, "old", token); - LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, OriginalSizePath, path, token); + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "size-owner", "revision-1"); + if (placeholder) + { + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(OriginalSizePath, identity, 3).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + Assert.Equal("old"u8.ToArray(), await File.ReadAllBytesAsync(path, token)); + // Capture the resize after the placeholder is already out of sync so the + // test pauses publication, independent of the timing of the native flag change. + await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( + CloudPlaceholderPatch.CreateBuilder().WithInSyncState(false).Build(), token); + } + else { await File.WriteAllTextAsync(path, "old", token); } + LocalChangeSourceEvent size = await CaptureSizeChangeAsync(fixture.Root, OriginalSizePath, path, token); + Assert.Equal(placeholder, size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); + if (placeholder) + { + CloudItemSnapshot resized = await fixture.System.GetFile(OriginalSizePath).InspectAsync(token); + Assert.False(size.SizeChange.Value.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + Assert.Equal(CloudSynchronizationState.NotInSync, resized.SynchronizationState); + Assert.Equal(resized.Length, size.SizeChange.Value.Length); + } ControlledMetadataSource source = new(); await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); - await source.EmitAsync(new(LocalChangeSourceAction.Created, OriginalSizePath)); - CloudOperationJournalEntry created = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); - await feed.AcknowledgeAsync([created.OperationId], token); + Guid ownerId = identity.ItemId; + if (!placeholder) + { + await source.EmitAsync(new(LocalChangeSourceAction.Created, OriginalSizePath)); + CloudOperationJournalEntry created = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + ownerId = Assert.IsType(created.ItemId); + await feed.AcknowledgeAsync([created.OperationId], token); + } factory!.Armed = true; await source.EmitAsync(size); CloudOperationJournalEntry? provisional = null; try { await factory.OutcomePaused.Task.WaitAsync(token); - if (replace) + if (replace && placeholder) + { + CloudFile file = fixture.System.GetFile(OriginalSizePath); + CloudItemSnapshot before = await file.InspectAsync(token); + Assert.Equal(identity.Encode(), before.PlaceholderIdentity.ToArray()); + CloudPlaceholderIdentity revised = new(identity.ItemId, identity.RemoteId, "revision-2"); + Assert.Equal(0, ReplaceNativeIdentity(path, revised)); + CloudItemSnapshot after = await file.InspectAsync(token); + Assert.NotNull(before.LocalBinding); + Assert.Equal(before.LocalBinding, after.LocalBinding); + Assert.Equal(revised.Encode(), after.PlaceholderIdentity.ToArray()); + } + else if (replace) { File.Move(path, retiredPath); await File.WriteAllBytesAsync(path, new byte[4096], token); @@ -365,7 +404,7 @@ public async Task TrackedSizeObservationPublishesOnlyVerifiedAssociation(string if (boundary == "size-publication-committed") { provisional = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); - Assert.Equal(created.ItemId, provisional.ItemId); + Assert.Equal(ownerId, provisional.ItemId); CloudLocalChangePage waiting = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); Assert.False(waiting.RequiresFullRescan); Assert.Empty(waiting.Changes); @@ -384,20 +423,24 @@ public async Task TrackedSizeObservationPublishesOnlyVerifiedAssociation(string { Assert.Equal((provisional.OperationId, provisional.Sequence), (original.OperationId, original.Sequence)); } - Guid? expectedItemId = replace ? null : created.ItemId; + Guid? expectedItemId = replace ? null : ownerId; Assert.Equal(expectedItemId, original.ItemId); Assert.Equal(CloudStateOperationKind.ContentUpdate, original.Kind); await using (ICloudStateTransaction transaction = await factory.Store!.BeginTransactionAsync(token)) { CloudItemState retainedOwner = Assert.Single(await transaction.Items.ListSubtreeAsync(string.Empty, token)); - Assert.Equal((created.ItemId, OriginalSizePath), (retainedOwner.ItemId, retainedOwner.RelativePath)); + Assert.Equal((ownerId, OriginalSizePath), (retainedOwner.ItemId, retainedOwner.RelativePath)); + if (placeholder) { Assert.Equal(identity.RemoteRevision, retainedOwner.RemoteRevision); } } if (replace) { await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); - Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); - Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); + if (!placeholder) + { + Assert.Equal(new byte[4096], await File.ReadAllBytesAsync(path, token)); + Assert.Equal((byte)'o', (await File.ReadAllBytesAsync(retiredPath, token))[0]); + } } CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); CloudLocalChange retained = Assert.Single(page.Changes); @@ -434,7 +477,7 @@ public async Task OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem() await feed.StartAsync(token); File.Move(path, retiredPath); await File.WriteAllTextAsync(path, "replacement", token); - LocalChangeSourceEvent size = await CaptureOrdinarySizeChangeAsync(fixture.Root, relativePath, path, token); + LocalChangeSourceEvent size = await CaptureSizeChangeAsync(fixture.Root, relativePath, path, token); Assert.False(size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); // Deliver Size before the name source has projected the replacement. await source.EmitAsync(size); From 1b699ddcfafe2e2b0383b1715943dfc79acad2ef Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:42:40 +0800 Subject: [PATCH 10/15] fix(sqlite): fence staged content recovery with schema 11 --- docs/metadata-echo-coordination.md | 5 ++-- docs/remote-change-application.md | 2 +- docs/state-store-sqlite.md | 15 ++++++------ .../SqliteCloudStateStoreFactory.cs | 7 +++--- .../CloudLocalChangeFeed.Security.cs | 2 ++ .../Persistence/SqliteStateStoreProtocol.cs | 4 ++-- ...loudLocalChangeMetadataPublicationTests.cs | 5 ++-- .../SqliteCloudStateStoreTests.cs | 23 +++++++++++-------- 8 files changed, 36 insertions(+), 27 deletions(-) diff --git a/docs/metadata-echo-coordination.md b/docs/metadata-echo-coordination.md index b01be8f..5f24d86 100644 --- a/docs/metadata-echo-coordination.md +++ b/docs/metadata-echo-coordination.md @@ -149,8 +149,9 @@ outcome commit throws after persisting, replay can report `AlreadyApplied`, whil requires reconciliation for that entry. If only the confirmation write fails, the known apply outcome stays successful and any unconfirmed receipt remains conservative. A legacy passthrough receipt without durable evidence of a successful native write requires reconciliation. -The official SQLite store upgrades to schema 10 before writing remote metadata receipts. Preview.15 -and other older SQLite providers reject the upgraded database before opening it for application work. +The official SQLite store upgrades to schema 11 before opening for application work. This protects +the remote metadata receipts introduced in schema 10 and the staged content observations added in +schema 11. Preview.16 and other older SQLite providers reject the upgraded database. Upgrade `CfSharp` and `CfSharp.Storage.Sqlite` together. File-system startup rejects an older official SQLite factory or store before starting the runtime. Custom stores that adapt SQLite are responsible for using a provider that establishes the same downgrade protection. diff --git a/docs/remote-change-application.md b/docs/remote-change-application.md index 93ecfe6..b11918f 100644 --- a/docs/remote-change-application.md +++ b/docs/remote-change-application.md @@ -176,7 +176,7 @@ to settle a move after later edits instead of clearing or overwriting them. ### Compatibility and limits -The official SQLite provider upgrades schemas 0–9 in place to **schema 10**, retaining existing +The official SQLite provider upgrades schemas 0–10 in place to **schema 11**, retaining existing repositories and enforcing foreign keys. Schema 9 introduced retained generations at the same path. The version check prevents older providers from opening incompatible recovery state. Use matching core and provider packages. diff --git a/docs/state-store-sqlite.md b/docs/state-store-sqlite.md index 54c8c47..5eba41f 100644 --- a/docs/state-store-sqlite.md +++ b/docs/state-store-sqlite.md @@ -151,13 +151,14 @@ from the new creation receipts and preserve processed-conflict receipts. No priv editing or provider generation codec is required. See the remote-change guide for already affected preview.7 states and legacy preparations, which require explicit reconciliation. -### Schema 10: remote metadata reconciliation - -The official SQLite store commits the schema 10 marker before it opens for application work. -The upgrade preserves the existing tables, item rows, checkpoints, and journal entries. The marker -protects durable remote metadata receipts and observations that require reconciliation, even before -the feed starts or a watcher notification arrives. Preview.15 and other older SQLite providers -reject schema 10 with `SqliteCloudStateStoreError.UnsupportedSchema`. +### Schemas 10 and 11: remote metadata reconciliation and staged size observations + +The official SQLite store commits the schema 11 marker before it opens for application work. +The upgrade preserves the existing tables, item rows, checkpoints, and journal entries. Schema 10 +protects durable remote metadata receipts even before the feed starts or a watcher notification +arrives. Schema 11 also protects journaled content observations that await native identity validation. +Preview.16 and other older SQLite providers reject schema 11 with +`SqliteCloudStateStoreError.UnsupportedSchema` before opening the store for application work. Use matching core and SQLite packages. To roll back, restore the database backup taken before the upgrade together with its corresponding sync state. Custom stores must enforce the same protocol diff --git a/src/CfSharp.Storage.Sqlite/SqliteCloudStateStoreFactory.cs b/src/CfSharp.Storage.Sqlite/SqliteCloudStateStoreFactory.cs index 5eef1e9..05402c9 100644 --- a/src/CfSharp.Storage.Sqlite/SqliteCloudStateStoreFactory.cs +++ b/src/CfSharp.Storage.Sqlite/SqliteCloudStateStoreFactory.cs @@ -843,7 +843,7 @@ private struct FileAttributeTagInfo internal static class SqliteSchema { - internal const int CurrentVersion = 10; + internal const int CurrentVersion = 11; internal const string PathCollationName = "CFSHARP_UNICODE_NOCASE"; private static ValueTask BeginSchemaTransactionAsync( @@ -985,8 +985,9 @@ await ValidateCurrentVersionAsync( if (version < CurrentVersion) { - // Remote metadata receipts use existing tables, but a schema-9 reader - // would ignore pending reconciliation. Commit the fence before opening the store. + // Recovery receipts use existing tables. Schema-9 readers ignore remote + // metadata receipts, and schema-10 readers cannot recover staged ContentUpdate + // rows. Commit the version fence before opening the store. await using SqliteCloudStateTransaction transaction = await BeginSchemaTransactionAsync( connection, databasePath, cancellationToken).ConfigureAwait(false); await using SqliteCommand upgrade = transaction.CreateCommand( diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs index 2f5873a..876dcde 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs @@ -9,6 +9,8 @@ namespace CfSharp; public sealed partial class CloudLocalChangeFeed { + // Keep metadata receipts readable across upgrades. SQLite schema 11 fences readers + // that cannot recover the staged ContentUpdate rows also referenced by this prefix. internal const string SecurityValidationPrefix = "cfsharp/security-validation/v1/"; private long _validatedObservationSequence; diff --git a/src/CfSharp/Persistence/SqliteStateStoreProtocol.cs b/src/CfSharp/Persistence/SqliteStateStoreProtocol.cs index adb8665..ceba161 100644 --- a/src/CfSharp/Persistence/SqliteStateStoreProtocol.cs +++ b/src/CfSharp/Persistence/SqliteStateStoreProtocol.cs @@ -9,7 +9,7 @@ internal interface ISqliteStateStoreProtocol internal static class SqliteStateStoreProtocol { - private const int MinimumSchemaVersion = 10; + private const int MinimumSchemaVersion = 11; internal static void EnsureCompatible(object provider) { @@ -17,7 +17,7 @@ internal static void EnsureCompatible(object provider) provider is not ISqliteStateStoreProtocol { SchemaVersion: >= MinimumSchemaVersion }) { throw new NotSupportedException( - "This CfSharp version requires CfSharp.Storage.Sqlite with schema 10 or later. Upgrade both packages together."); + $"This CfSharp version requires CfSharp.Storage.Sqlite with schema {MinimumSchemaVersion} or later. Upgrade both packages together."); } } } diff --git a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs index 7b46973..cddfb6a 100644 --- a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs +++ b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs @@ -43,13 +43,13 @@ public async Task UnvalidatedMetadataWithholdsOnlyItsSuffixWithoutAdvancingTheCu [InlineData(CloudStateOperationKind.ContentUpdate)] public async Task CommittedUnvalidatedObservationRecoversUnboundWithItsOriginalSequence(CloudStateOperationKind kind) { - await using ICloudStateStore store = await OpenStoreAsync(); Guid operationId = Guid.NewGuid(); Guid itemId = Guid.NewGuid(); DateTimeOffset observedAt = DateTimeOffset.UtcNow; byte[] payload = new LocalChangePayload("history.bin", null, false, observedAt).Encode(); CloudOperationJournalEntry original; - await using (ICloudStateTransaction interrupted = await store.BeginTransactionAsync()) + await using (ICloudStateStore previous = await OpenStoreAsync()) + await using (ICloudStateTransaction interrupted = await previous.BeginTransactionAsync()) { await interrupted.Items.UpsertAsync(new(itemId, "original", "history.bin", CloudItemKind.File, "accepted", null, false, observedAt)); @@ -59,6 +59,7 @@ await interrupted.Checkpoints.UpsertAsync(new(CloudLocalChangeFeed.SecurityValid payload, observedAt)); await interrupted.CommitAsync(); } + await using ICloudStateStore store = await OpenStoreAsync(); await using CloudLocalChangeFeed feed = CreateFeed(store, new FakeSource()); await feed.StartAsync(); await using (ICloudStateTransaction read = await store.BeginTransactionAsync()) diff --git a/tests/CfSharp.Storage.Sqlite.Tests/SqliteCloudStateStoreTests.cs b/tests/CfSharp.Storage.Sqlite.Tests/SqliteCloudStateStoreTests.cs index 74065a3..580bfb2 100644 --- a/tests/CfSharp.Storage.Sqlite.Tests/SqliteCloudStateStoreTests.cs +++ b/tests/CfSharp.Storage.Sqlite.Tests/SqliteCloudStateStoreTests.cs @@ -700,7 +700,8 @@ await write.EchoSuppressions.UpsertAsync(new CloudEchoSuppressionState(suppressi [Theory] [InlineData(5)] [InlineData(9)] - public async Task VersionTenFenceSurvivesProcessExitBeforeApplicationCommit(int previousVersion) + [InlineData(10)] + public async Task VersionElevenFenceSurvivesProcessExitBeforeApplicationCommit(int previousVersion) { await using (ICloudStateStore store = await CreateFactory().OpenAsync(CreateContext())) await using (ICloudStateTransaction seed = await store.BeginTransactionAsync()) @@ -713,7 +714,7 @@ public async Task VersionTenFenceSurvivesProcessExitBeforeApplicationCommit(int (int exitCode, _) = await RunCrashHarnessAsync("before-commit", _databasePath, _syncRootPath); Assert.NotEqual(0, exitCode); Assert.True(File.Exists(_databasePath + ".before-commit.started")); - Assert.Equal(10L, await ExecuteScalarInt64Async(_databasePath, + Assert.Equal(11L, await ExecuteScalarInt64Async(_databasePath, "SELECT version FROM cfsharp_schema WHERE singleton = 1;")); await using ICloudStateStore recovered = await CreateFactory().OpenAsync(CreateContext()); await using ICloudStateTransaction verify = await recovered.BeginTransactionAsync(); @@ -721,15 +722,17 @@ public async Task VersionTenFenceSurvivesProcessExitBeforeApplicationCommit(int Assert.Null(await verify.Items.GetByRelativePathAsync("crash-recovery.txt")); } - [Fact] - public async Task VersionNineStoreCannotOpenIfItsSchemaMarkerDoesNotAdvance() + [Theory] + [InlineData(9)] + [InlineData(10)] + public async Task OlderStoreCannotOpenIfItsSchemaMarkerDoesNotAdvance(int previousVersion) { await using (ICloudStateStore store = await CreateFactory().OpenAsync(CreateContext())) { } - await ExecuteSqlAsync(_databasePath, """ - UPDATE cfsharp_schema SET version = 9 WHERE singleton = 1; + await ExecuteSqlAsync(_databasePath, $""" + UPDATE cfsharp_schema SET version = {previousVersion} WHERE singleton = 1; CREATE TRIGGER retain_old_marker BEFORE UPDATE OF version ON cfsharp_schema BEGIN SELECT RAISE(IGNORE); @@ -738,13 +741,13 @@ CREATE TRIGGER retain_old_marker BEFORE UPDATE OF version ON cfsharp_schema SqliteCloudStateStoreException error = await Assert.ThrowsAsync( () => CreateFactory().OpenAsync(CreateContext()).AsTask()); Assert.Equal(SqliteCloudStateStoreError.InvalidSchema, error.Error); - Assert.Equal(9L, await ExecuteScalarInt64Async(_databasePath, "SELECT version FROM cfsharp_schema WHERE singleton = 1;")); + Assert.Equal((long)previousVersion, await ExecuteScalarInt64Async(_databasePath, "SELECT version FROM cfsharp_schema WHERE singleton = 1;")); await ExecuteSqlAsync(_databasePath, "DROP TRIGGER retain_old_marker;"); await using (ICloudStateStore store = await CreateFactory().OpenAsync(CreateContext())) { } - Assert.Equal(10L, await ExecuteScalarInt64Async(_databasePath, "SELECT version FROM cfsharp_schema WHERE singleton = 1;")); + Assert.Equal(11L, await ExecuteScalarInt64Async(_databasePath, "SELECT version FROM cfsharp_schema WHERE singleton = 1;")); } [Fact] @@ -752,12 +755,12 @@ public async Task NewerSchemaVersionIsRejected() { await ExecuteSqlAsync( _databasePath, - """ + $""" CREATE TABLE cfsharp_schema ( singleton INTEGER NOT NULL PRIMARY KEY CHECK (singleton = 1), version INTEGER NOT NULL ); - INSERT INTO cfsharp_schema(singleton, version) VALUES(1, 11); + INSERT INTO cfsharp_schema(singleton, version) VALUES(1, {SqliteSchema.CurrentVersion + 1}); """); SqliteCloudStateStoreException exception = await Assert.ThrowsAsync< From f59321fb4e7a131b5613926b8e60acf24b97ea44 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:16:13 +0800 Subject: [PATCH 11/15] fix(local-feed): require data evidence for out-of-sync size notices --- docs/local-change-feed.md | 8 +- eng/test-ordinary-user-delete.ps1 | 3 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 12 +-- .../ReadOnlyHydrationJournalTests.cs | 86 ++++++++++++++++--- 4 files changed, 90 insertions(+), 19 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index 8018bd0..3311aee 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -26,9 +26,11 @@ Size notifications have their own subscription because Windows can report a size hydration increases physical allocation and leaves the logical length unchanged. A size notice for a known file placeholder produces no content row when the native notice and the current object agree on identity, logical length and in-sync state, and Windows reports only validated -data. If the object was replaced or the captured and current states disagree, the feed retains an -unbound observation and requires reconciliation. A size notice for a path without an item row -stays unbound. The ordered name subscription establishes ownership, including when Size arrives +data. A placeholder can become out of sync from an attribute edit. The feed associates an +out-of-sync size notice with a file only when Windows reports modified data. If the object was +replaced, the captured and current states disagree, or modified data cannot be confirmed, the +feed retains an unbound observation and requires reconciliation. A size notice for a path +without an item row stays unbound. The ordered name subscription establishes ownership, including when Size arrives before a rename or after an ordinary name disappears. A size notice for an ordinary file can reuse an existing item ID only when its durable native file ID matches the observed object. The feed rechecks the native binding and any placeholder's item ID, remote ID and revision diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 6b2145b..0d3738c 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -28,6 +28,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'AccessJournal') { @('FullyQualifiedName~AccessOnlyResidentWriteRetainsOriginalJournalAndGenuineLaterEdit', 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', + 'FullyQualifiedName~ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation', 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', @@ -74,7 +75,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 94 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 95 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index d228d5e..400b447 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -72,16 +72,18 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl binding = new(item.LocalBinding, kind, placeholder); if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } - // On Windows, hydration can change allocation and signal Size while the - // placeholder remains in sync. A logical data modification clears in-sync. + // Hydration can signal Size when allocation grows. Metadata changes can + // already have cleared in-sync, so that flag alone cannot prove a data edit. // Keep last-write notifications independent, including overlapping writes. bool capturedInSync = size.PlaceholderState.HasFlag(CloudPlaceholderState.InSync); bool inSyncNow = item.SynchronizationState == CloudSynchronizationState.InSync; if (capturedInSync != inSyncNow || item.Length != size.Length || - (inSyncNow && (item.ModifiedDataSize != 0 || item.OnDiskDataSize != item.ValidatedDataSize))) + (inSyncNow + ? item.ModifiedDataSize != 0 || item.OnDiskDataSize != item.ValidatedDataSize + : item.ModifiedDataSize is not > 0)) { - // This can be a delayed allocation notice delivered after a genuine edit. - // Preserve the original without letting it authorize an upload. + // A Size notice has no previous logical length. Without evidence of + // modified data, retain it for reconciliation, including length-only edits. throw new CloudNamespaceObservationUncertainException(isDirectory: false); } return inSyncNow ? SizeObservationDisposition.CleanPlaceholder : SizeObservationDisposition.Content; diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 1719df8..933f218 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -38,7 +38,7 @@ public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWr Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); Assert.Equal(0, hydrated.ModifiedDataSize); Assert.Equal(before.LastWriteTime, hydrated.LastWriteTime); - await source.WaitForFenceAsync(factory!, "read-finished", CaptureHydratedSize(fixture.File.RelativePath, hydrated)); + await source.WaitForFenceAsync(factory!, "read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, hydrated)); IReadOnlyList afterRead = await AccessRowsAsync(factory!); Assert.DoesNotContain(afterRead, row => row.Kind == CloudStateOperationKind.ContentUpdate && LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath); @@ -109,7 +109,7 @@ public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent CloudItemSnapshot partial = await fixture.File.InspectAsync(token); Assert.Equal(CloudContentAvailability.PartiallyAvailable, partial.ContentAvailability); Assert.Equal(CloudSynchronizationState.InSync, partial.SynchronizationState); - await source.WaitForFenceAsync(factory!, "partial-read-finished", CaptureHydratedSize(fixture.File.RelativePath, partial)); + await source.WaitForFenceAsync(factory!, "partial-read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, partial)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); } int firstFetches = fixture.Provider.Fetches; @@ -125,7 +125,7 @@ public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent CloudItemSnapshot complete = await fixture.File.InspectAsync(token); Assert.Equal((original, identity.ItemId, identity.RemoteRevision), (complete.LocalBinding, complete.ItemId, complete.RemoteRevision)); Assert.Equal(CloudSynchronizationState.InSync, complete.SynchronizationState); - await restartedSource.WaitForFenceAsync(factory!, "complete-read-finished", CaptureHydratedSize(fixture.File.RelativePath, complete)); + await restartedSource.WaitForFenceAsync(factory!, "complete-read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, complete)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 100, token); Assert.False(page.RequiresFullRescan); @@ -158,7 +158,8 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); - LocalChangeSourceEvent hydration = CaptureHydratedSize(name, hydrated); + Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); + LocalChangeSourceEvent hydration = SizeFromPlaceholderSnapshot(name, hydrated); LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => { await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); @@ -189,13 +190,65 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); } - private static LocalChangeSourceEvent CaptureHydratedSize(string relativePath, CloudItemSnapshot hydrated) + [Trait("Category", "AccessJournal")] + [Fact] + public async Task ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation() { - Assert.True(hydrated.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); - CloudLocalFileBinding binding = Assert.IsType(hydrated.LocalBinding); - long fileId = Assert.IsType(hydrated.LocalFileId); + byte[] bytes = new byte[65_537]; + new Random(20261125).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), + CloudInSyncPolicy.TrackAll, hydrationContent: bytes); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + string name = fixture.File.RelativePath; + string path = fixture.File.FullPath; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "metadata-only-hydration", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(name, identity, bytes.Length).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + CloudItemSnapshot before = await fixture.File.InspectAsync(token); + Assert.Equal(CloudSynchronizationState.InSync, before.SynchronizationState); + Assert.Equal(CloudContentAvailability.OnlineOnly, before.ContentAvailability); + + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); + CloudItemSnapshot metadataOnly = await fixture.File.InspectAsync(token); + Assert.Equal(CloudSynchronizationState.NotInSync, metadataOnly.SynchronizationState); + Assert.Equal(CloudContentAvailability.OnlineOnly, metadataOnly.ContentAvailability); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + Assert.True(fixture.Provider.Fetches > 0); + CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); + Assert.Equal(CloudSynchronizationState.NotInSync, hydrated.SynchronizationState); + Assert.False(hydrated.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); + Assert.Equal(0, hydrated.ModifiedDataSize); + Assert.True(hydrated.OnDiskDataSize > metadataOnly.OnDiskDataSize); + Assert.Equal((before.LocalBinding, before.Length, before.LastWriteTime), + (hydrated.LocalBinding, hydrated.Length, hydrated.LastWriteTime)); + + // Allocation notifications can be coalesced. Deliver the Size record from + // the actual post-hydration snapshot through the controlled source. + await source.EmitAsync(SizeFromPlaceholderSnapshot(name, hydrated)); + CloudOperationJournalEntry observation = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + Assert.Equal(CloudStateOperationKind.ContentUpdate, observation.Kind); + Assert.Null(observation.ItemId); + Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + CloudLocalChange change = Assert.Single(page.Changes); + Assert.Equal((observation.OperationId, observation.Sequence, name, (Guid?)null), + (change.OperationId, change.Sequence, change.RelativePath, change.ItemId)); + await feed.AcknowledgeAsync([change.OperationId], token); + } + + private static LocalChangeSourceEvent SizeFromPlaceholderSnapshot(string relativePath, CloudItemSnapshot snapshot) + { + CloudLocalFileBinding binding = Assert.IsType(snapshot.LocalBinding); + long fileId = Assert.IsType(snapshot.LocalFileId); LocalSizeChange size = new(new(binding.VolumeSerialNumber, binding.SyncRootFileId, unchecked((ulong)fileId), - ParentFileId: 0, IsDirectory: false), Assert.IsType(hydrated.Length), hydrated.PlaceholderState); + ParentFileId: 0, IsDirectory: false), Assert.IsType(snapshot.Length), snapshot.PlaceholderState); return new(LocalChangeSourceAction.SizeModified, relativePath, SizeChange: size); } @@ -277,6 +330,16 @@ private static Task CaptureSizeChangeAsync(string root, return Task.CompletedTask; }, token, LocalChangeSourceAction.SizeModified); + private static Task CaptureContentGrowthAsync(string root, string relativePath, string fullPath, + byte value, CancellationToken token) => + CaptureNativeModificationAsync(root, relativePath, () => + { + using FileStream file = new(fullPath, FileMode.Append, FileAccess.Write, FileShare.Read); + file.WriteByte(value); + file.Flush(flushToDisk: true); + return Task.CompletedTask; + }, token, LocalChangeSourceAction.SizeModified); + [Trait("Category", "AccessJournal")] [Fact] public async Task SizeBeforeRenamePreservesTheOriginalItemId() @@ -358,7 +421,9 @@ await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( CloudPlaceholderPatch.CreateBuilder().WithInSyncState(false).Build(), token); } else { await File.WriteAllTextAsync(path, "old", token); } - LocalChangeSourceEvent size = await CaptureSizeChangeAsync(fixture.Root, OriginalSizePath, path, token); + LocalChangeSourceEvent size = placeholder + ? await CaptureContentGrowthAsync(fixture.Root, OriginalSizePath, path, 42, token) + : await CaptureSizeChangeAsync(fixture.Root, OriginalSizePath, path, token); Assert.Equal(placeholder, size.SizeChange!.Value.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)); if (placeholder) { @@ -366,6 +431,7 @@ await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( Assert.False(size.SizeChange.Value.PlaceholderState.HasFlag(CloudPlaceholderState.InSync)); Assert.Equal(CloudSynchronizationState.NotInSync, resized.SynchronizationState); Assert.Equal(resized.Length, size.SizeChange.Value.Length); + Assert.True(resized.ModifiedDataSize > 0); } ControlledMetadataSource source = new(); await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); From 4b2d8a6a9b54aa84b264ca3724c9a836ea525ba8 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:19:01 +0800 Subject: [PATCH 12/15] fix(local-feed): accept size notices after revision acknowledgement --- docs/local-change-feed.md | 12 +++-- eng/test-ordinary-user-delete.ps1 | 3 +- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 5 +- .../ReadOnlyHydrationJournalTests.cs | 53 +++++++++++++++++++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index 3311aee..d7e66f8 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -30,11 +30,13 @@ data. A placeholder can become out of sync from an attribute edit. The feed asso out-of-sync size notice with a file only when Windows reports modified data. If the object was replaced, the captured and current states disagree, or modified data cannot be confirmed, the feed retains an unbound observation and requires reconciliation. A size notice for a path -without an item row stays unbound. The ordered name subscription establishes ownership, including when Size arrives -before a rename or after an ordinary name disappears. A size notice for an ordinary file can -reuse an existing item ID only when its durable native file ID matches the observed object. -The feed rechecks the native binding and any placeholder's item ID, remote ID and revision -before and after committing the journal row. A durable validation +without an item row stays unbound. The ordered name subscription establishes ownership, including +when Size arrives before a rename or after an ordinary name disappears. A size notice for an +ordinary file can reuse an existing item ID only when its durable native file ID matches the +observed object. An acknowledgement can advance the stored remote revision independently of the +placeholder. The feed matches the placeholder's item ID and remote ID against the stored item, +then rechecks the native binding and complete native identity, including its revision, before +and after committing the journal row. A durable validation receipt withholds the row from reads and acknowledgement until the second check. If the object changed or the feed stopped during publication, reconciliation exposes the original operation with the same ID and sequence and no item association. Last-write notifications remain diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 0d3738c..87aa3ac 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -32,6 +32,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', + 'FullyQualifiedName~SizeAfterRevisionAcknowledgementRemainsBoundToTheSamePlaceholder', 'FullyQualifiedName~TrackedSizeObservationPublishesOnlyVerifiedAssociation', 'FullyQualifiedName~OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', @@ -75,7 +76,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 95 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 96 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 400b447..011081f 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -62,10 +62,11 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } CloudPlaceholderIdentity? placeholder = null; + // A revision ACK can advance the official row without rewriting the native + // revision. Capture the actual native value for both publication checks. if (capturedPlaceholder && (!CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out placeholder) || - placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId || - placeholder.RemoteRevision != owner.RemoteRevision)) + placeholder.ItemId != owner.ItemId || placeholder.RemoteId != owner.RemoteId)) { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 933f218..c255055 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -340,6 +340,59 @@ private static Task CaptureContentGrowthAsync(string roo return Task.CompletedTask; }, token, LocalChangeSourceAction.SizeModified); + [Trait("Category", "AccessJournal")] + [Fact] + public async Task SizeAfterRevisionAcknowledgementRemainsBoundToTheSamePlaceholder() + { + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), hydrationContent: "seed"u8.ToArray()); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + string name = fixture.File.RelativePath; + string path = fixture.File.FullPath; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "acked-size-owner", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(name, identity, 4).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + Assert.Equal("seed"u8.ToArray(), await File.ReadAllBytesAsync(path, token)); + CloudItemSnapshot original = await fixture.File.InspectAsync(token); + await fixture.File.UpdatePlaceholderAsync(CloudPlaceholderPatch.CreateBuilder().WithInSyncState(false).Build(), token); + + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + await source.EmitAsync(await CaptureContentGrowthAsync(fixture.Root, name, path, (byte)'1', token)); + CloudLocalChangeBatch firstBatch = await feed.ReadBatchAsync(token); + Assert.False(firstBatch.RequiresFullRescan); + CloudLocalChange first = Assert.Single(firstBatch.Changes); + Assert.Equal((CloudLocalChangeKind.ContentUpdate, identity.ItemId, name), (first.Kind, first.ItemId, first.RelativePath)); + await feed.AcknowledgeAsync([new CloudLocalChangeAcknowledgement(first.OperationId, "revision-2")], token); + await using (ICloudStateTransaction transaction = await factory!.Store!.BeginTransactionAsync(token)) + { + CloudItemState owner = Assert.IsType(await transaction.Items.GetByItemIdAsync(identity.ItemId, token)); + Assert.Equal("revision-2", owner.RemoteRevision); + Assert.Null(await transaction.Operations.GetAsync(first.OperationId, token)); + } + Assert.Equal(identity.Encode(), (await fixture.File.InspectAsync(token)).PlaceholderIdentity.ToArray()); + + LocalChangeSourceEvent secondNotice = await CaptureContentGrowthAsync(fixture.Root, name, path, (byte)'2', token); + CloudItemSnapshot resized = await fixture.File.InspectAsync(token); + Assert.Equal(6L, secondNotice.SizeChange!.Value.Length); + Assert.Equal((original.LocalBinding, 6L), (resized.LocalBinding, resized.Length)); + Assert.True(resized.ModifiedDataSize > 0); + Assert.Equal(identity.Encode(), resized.PlaceholderIdentity.ToArray()); + await source.EmitAsync(secondNotice); + CloudLocalChangeBatch secondBatch = await feed.ReadBatchAsync(token); + Assert.False(secondBatch.RequiresFullRescan); + CloudLocalChange second = Assert.Single(secondBatch.Changes); + Assert.Equal((first.Kind, first.ItemId, first.RelativePath), (second.Kind, second.ItemId, second.RelativePath)); + Assert.NotEqual(first.OperationId, second.OperationId); + Assert.True(second.Sequence > first.Sequence); + await feed.AcknowledgeAsync([second.OperationId], token); + Assert.Empty(await AccessRowsAsync(factory!)); + Assert.Equal("seed12"u8.ToArray(), await File.ReadAllBytesAsync(path, token)); + } + [Trait("Category", "AccessJournal")] [Fact] public async Task SizeBeforeRenamePreservesTheOriginalItemId() From 2d259734386dae200ad1249eb44a2f9231fe9782 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:48:12 +0800 Subject: [PATCH 13/15] fix(remote-changes): defer on unvalidated local journal associations --- docs/local-change-feed.md | 4 +- .../CloudFileSystem.RemoteChanges.cs | 29 ++++++++++-- .../CloudFileSystem.RemoteCreation.cs | 6 +-- .../CloudFileSystem.RemoteDeletes.cs | 4 +- .../FileSystem/CloudFileSystem.RemoteMoves.cs | 6 +-- .../CloudLocalChangeFeed.Security.cs | 16 +++++-- .../ReadOnlyHydrationJournalTests.cs | 46 +++++++++++++++++++ 7 files changed, 94 insertions(+), 17 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index d7e66f8..ce8af40 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -39,7 +39,9 @@ then rechecks the native binding and complete native identity, including its rev and after committing the journal row. A durable validation receipt withholds the row from reads and acknowledgement until the second check. If the object changed or the feed stopped during publication, reconciliation exposes the original operation -with the same ID and sequence and no item association. Last-write notifications remain +with the same ID and sequence and no item association. Remote application encountering such a +pending association returns a retryable entry and leaves its safe cursor at the previous durable +entry. Last-write notifications remain independent, so a same-length local write overlapping hydration can still be read and acknowledged separately. diff --git a/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs index 9660b5c..b0adb2a 100644 --- a/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs +++ b/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs @@ -69,6 +69,8 @@ public sealed partial class CloudFileSystem /// caller; replay rereads durable state, including when a commit completed before throwing. /// A metadata update whose native object changes before outcome publication retains its /// recovery evidence and the prior safe cursor. + /// An entry that encounters a local journal association awaiting identity validation + /// fails with a retryable outcome and retains the prior safe cursor. /// Cancellation after native success finishes item projection without cancellation and may /// leave outcome publication for replay. This protocol covers file moves submitted through /// this method; it cannot authenticate historical file moves without original evidence or @@ -284,6 +286,8 @@ private async ValueTask ApplyRemoteChangesCoreAsync( /// /// The conflict no longer exists. /// The durable conflict envelope is corrupt. + /// A local observation for the item is still awaiting + /// identity validation. Retry with the same conflict identifier. public async ValueTask ResolveRemoteConflictAsync( Guid conflictId, CloudRemoteConflictResolution resolution, @@ -1049,7 +1053,8 @@ private async ValueTask ReadRemoteEntryContextAsync( CloudItemState? localState = byRemoteId ?? byItemId ?? byPreviousPath ?? pathState; IReadOnlyList operations = localState is null ? [] - : await transaction.Operations.ListByItemIdAsync( + : await ReadValidatedRemoteLocalOperationsAsync( + transaction, localState.ItemId, maximumCount: int.MaxValue, cancellationToken) @@ -1064,6 +1069,24 @@ private async ValueTask ReadRemoteEntryContextAsync( operations); } + private static async ValueTask> ReadValidatedRemoteLocalOperationsAsync( + ICloudStateTransaction transaction, Guid itemId, int maximumCount, CancellationToken cancellationToken) + { + IReadOnlyList operations = await transaction.Operations.ListByItemIdAsync( + itemId, maximumCount, cancellationToken).ConfigureAwait(false); + if (operations.Count == 0) { return operations; } + + // Inspect the receipt in the same transaction as the journal row. Waiting + // while holding that transaction could block the worker that clears it. + HashSet? pending = await CloudLocalChangeFeed.ReadPendingObservationValidationsAsync( + transaction, cancellationToken).ConfigureAwait(false); + if (pending is not null && operations.Any(operation => pending.Contains(CloudLocalChangeFeed.SecurityValidationName(operation.OperationId)))) + { + throw new IOException($"A local journal observation for item '{itemId}' is awaiting identity validation. Retry the original remote change."); + } + return operations; + } + private async ValueTask RegisterRemoteEchoSuppressionAsync( CloudRemoteChange change, Guid itemId, @@ -1234,8 +1257,8 @@ private async ValueTask GuardRemotePlaceholderWriteAsync(CloudRemot { throw new RemotePlaceholderWriteConflictException(CloudRemoteConflictReason.Metadata); } - IReadOnlyList operations = await transaction.Operations.ListByItemIdAsync( - itemId, maximumCount: 1, cancellationToken).ConfigureAwait(false); + IReadOnlyList operations = await ReadValidatedRemoteLocalOperationsAsync( + transaction, itemId, maximumCount: 1, cancellationToken).ConfigureAwait(false); if (operations.Count != 0) { throw new RemotePlaceholderWriteConflictException(change.Kind == CloudRemoteChangeKind.MetadataUpdate diff --git a/src/CfSharp/FileSystem/CloudFileSystem.RemoteCreation.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteCreation.cs index 72c931e..d3f9ab1 100644 --- a/src/CfSharp/FileSystem/CloudFileSystem.RemoteCreation.cs +++ b/src/CfSharp/FileSystem/CloudFileSystem.RemoteCreation.cs @@ -66,7 +66,7 @@ private async ValueTask CreateRemotePlaceholderCoordinatedAs await CloudDirectoryMoveEvidence.GetScopeAsync(preparation, true, cancellationToken).ConfigureAwait(false), SyncRootPath, parents.Parents, PreserveContent: options.PreserveUnsynchronizedLocalContent, Resolution: resolution, LocalOperationsFingerprint: RemoteNamespaceEvidence.FingerprintOperations( - await preparation.Operations.ListByItemIdAsync(itemId, int.MaxValue, cancellationToken).ConfigureAwait(false))); + await ReadValidatedRemoteLocalOperationsAsync(preparation, itemId, int.MaxValue, cancellationToken).ConfigureAwait(false))); await preparation.Checkpoints.UpsertAsync(new(name, intent.Encode(), DateTimeOffset.UtcNow), cancellationToken).ConfigureAwait(false); await preparation.CommitAsync(cancellationToken).ConfigureAwait(false); } @@ -181,8 +181,8 @@ private static async ValueTask HasRemoteCreationCollisionAsync(ICloudState CloudItemState? byPath = await transaction.Items.GetByRelativePathAsync(change.RelativePath, cancellationToken).ConfigureAwait(false); CloudItemState? byId = await transaction.Items.GetByItemIdAsync(intent.Identity.ItemId, cancellationToken).ConfigureAwait(false); CloudItemState? byRemote = await transaction.Items.GetByRemoteIdAsync(change.RemoteId, cancellationToken).ConfigureAwait(false); - IReadOnlyList operations = await transaction.Operations.ListByItemIdAsync( - intent.Identity.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); + IReadOnlyList operations = await ReadValidatedRemoteLocalOperationsAsync( + transaction, intent.Identity.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); return (byPath is { IsTombstone: false } && byPath.ItemId != intent.Identity.ItemId) || (byRemote is not null && byRemote.ItemId != intent.Identity.ItemId) || (byId is not null && (byId.RemoteId != change.RemoteId || byId.Kind != change.ItemKind || diff --git a/src/CfSharp/FileSystem/CloudFileSystem.RemoteDeletes.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteDeletes.cs index bdffc9b..e11316e 100644 --- a/src/CfSharp/FileSystem/CloudFileSystem.RemoteDeletes.cs +++ b/src/CfSharp/FileSystem/CloudFileSystem.RemoteDeletes.cs @@ -165,7 +165,7 @@ private async ValueTask PrepareRemoteDeleteAsync(CloudItemSt } IReadOnlyList operations = state is null ? [] : - await transaction.Operations.ListByItemIdAsync(state.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); + await ReadValidatedRemoteLocalOperationsAsync(transaction, state.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); if (effectiveOptions.PreserveUnsynchronizedLocalContent && (state is null || operations.Count != 0)) { throw DeleteUnresolved(request, "local work changed during preparation"); @@ -365,7 +365,7 @@ private static async ValueTask ValidateRemoteDeleteStateAsync(ICloudStateTransac } IReadOnlyList operations = expected is null ? [] : - await transaction.Operations.ListByItemIdAsync(expected.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); + await ReadValidatedRemoteLocalOperationsAsync(transaction, expected.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); if (!member.OperationsFingerprint.AsSpan().SequenceEqual(RemoteNamespaceEvidence.FingerprintOperations(operations))) { throw DeleteUnresolved(request, "changed original local operations"); diff --git a/src/CfSharp/FileSystem/CloudFileSystem.RemoteMoves.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteMoves.cs index 04802de..bec732d 100644 --- a/src/CfSharp/FileSystem/CloudFileSystem.RemoteMoves.cs +++ b/src/CfSharp/FileSystem/CloudFileSystem.RemoteMoves.cs @@ -84,8 +84,8 @@ private async ValueTask PrepareRemoteFileMoveAsync(CloudRemote } CloudRemoteApplyOptions policy = request.Options; - IReadOnlyList localOperations = await transaction.Operations.ListByItemIdAsync( - original.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); + IReadOnlyList localOperations = await ReadValidatedRemoteLocalOperationsAsync( + transaction, original.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false); if (effectiveOptions.PreserveUnsynchronizedLocalContent && localOperations.Count != 0) { throw new IOException("Local operations changed during remote move preparation."); @@ -154,7 +154,7 @@ private async ValueTask CompleteRemoteFileMoveAsync(CloudRem : intent.Original; CloudItemState? occupant = await transaction.Items.GetByRelativePathAsync(change.RelativePath, cancellationToken).ConfigureAwait(false); if (!SameRemoteItemState(current, expected) || (occupant is not null && occupant.ItemId != expected.ItemId) || - !RemoteNamespaceEvidence.FingerprintOperations(await transaction.Operations.ListByItemIdAsync(expected.ItemId, int.MaxValue, + !RemoteNamespaceEvidence.FingerprintOperations(await ReadValidatedRemoteLocalOperationsAsync(transaction, expected.ItemId, int.MaxValue, cancellationToken).ConfigureAwait(false)).AsSpan().SequenceEqual(intent.LocalOperationsFingerprint)) { throw RemoteMoveUnresolved(intent, "durable projection validation"); diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs index 876dcde..b0f62c0 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs @@ -14,7 +14,7 @@ public sealed partial class CloudLocalChangeFeed internal const string SecurityValidationPrefix = "cfsharp/security-validation/v1/"; private long _validatedObservationSequence; - private static string SecurityValidationName(Guid operationId) => SecurityValidationPrefix + operationId.ToString("N"); + internal static string SecurityValidationName(Guid operationId) => SecurityValidationPrefix + operationId.ToString("N"); private static async ValueTask StageMetadataObservationAsync(ICloudStateTransaction transaction, SecurityFeedProjection projection, CloudItemState owner, CloudItemPath path, LocalChangeSourceEvent sourceEvent, @@ -87,10 +87,8 @@ private async ValueTask ValidatedObservationPrefixLengthAsync(ICloudStateTr IReadOnlyList operations, CancellationToken cancellationToken) { if (operations.Count == 0) { return 0; } - IReadOnlyList receipts = await transaction.Checkpoints.ListAsync(SecurityValidationPrefix, - cancellationToken).ConfigureAwait(false); - if (receipts.Count == 0) { return operations.Count; } - HashSet pending = new(receipts.Select(receipt => receipt.Name), StringComparer.Ordinal); + HashSet? pending = await ReadPendingObservationValidationsAsync(transaction, cancellationToken).ConfigureAwait(false); + if (pending is null) { return operations.Count; } long validated = Volatile.Read(ref _validatedObservationSequence); for (int index = 0; index < operations.Count; index++) { @@ -100,6 +98,14 @@ private async ValueTask ValidatedObservationPrefixLengthAsync(ICloudStateTr return operations.Count; } + internal static async ValueTask?> ReadPendingObservationValidationsAsync(ICloudStateTransaction transaction, + CancellationToken cancellationToken) + { + IReadOnlyList receipts = await transaction.Checkpoints.ListAsync(SecurityValidationPrefix, + cancellationToken).ConfigureAwait(false); + return receipts.Count == 0 ? null : new(receipts.Select(receipt => receipt.Name), StringComparer.Ordinal); + } + private static async ValueTask RetainUnboundObservationAsync(ICloudStateTransaction transaction, Guid operationId, ReadOnlyMemory payload, DateTimeOffset observedAt, CancellationToken cancellationToken, CloudStateOperationKind? kind = CloudStateOperationKind.MetadataUpdate) diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index c255055..fb28e82 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -500,6 +500,7 @@ await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( factory!.Armed = true; await source.EmitAsync(size); CloudOperationJournalEntry? provisional = null; + CloudRemoteChangeBatch? remoteBatch = null; try { await factory.OutcomePaused.Task.WaitAsync(token); @@ -530,6 +531,27 @@ await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( Assert.True(waiting.HasMore); Assert.Equal(0, waiting.LastScannedSequence); await Assert.ThrowsAsync(() => feed.AcknowledgeAsync([provisional.OperationId], token).AsTask()); + + if (placeholder) + { + CloudRemoteChange remote = new("remote-size", CloudRemoteChangeKind.FileUpsert, identity.RemoteId, "revision-3", + CloudItemKind.File, OriginalSizePath, ownerId, previousRemoteRevision: identity.RemoteRevision, + length: 4, metadata: CloudPlaceholderMetadata.CreateFileBuilder().Build()); + remoteBatch = new("size-awaiting-validation", new byte[] { 7 }, [remote], new byte[] { 8 }); + CloudRemoteApplyResult waitingRemote = await fixture.System.ApplyRemoteChangesAsync(remoteBatch, cancellationToken: token); + Assert.True(waitingRemote.RequiresRetry); + Assert.Equal(new byte[] { 7 }, waitingRemote.SafeCursor.ToArray()); + CloudRemoteApplyEntryResult deferred = Assert.Single(waitingRemote.Entries); + Assert.Equal(CloudRemoteApplyEntryStatus.Failed, deferred.Status); + Assert.IsType(deferred.Error); + Assert.Empty(waitingRemote.ConflictIds); + await using ICloudStateTransaction read = await factory.Store!.BeginTransactionAsync(token); + Assert.Empty(await read.Conflicts.ListAsync(cancellationToken: token)); + CloudRemoteBatchState progress = Assert.IsType( + await read.RemoteBatches.GetAsync(remoteBatch.BatchId, token)); + Assert.Equal(0, progress.AppliedEntryCount); + Assert.Equal(new byte[] { 7 }, progress.Cursor.ToArray()); + } } } finally { factory.ResumeOutcome.TrySetResult(); } @@ -550,6 +572,30 @@ await fixture.System.GetFile(OriginalSizePath).UpdatePlaceholderAsync( CloudItemState retainedOwner = Assert.Single(await transaction.Items.ListSubtreeAsync(string.Empty, token)); Assert.Equal((ownerId, OriginalSizePath), (retainedOwner.ItemId, retainedOwner.RelativePath)); if (placeholder) { Assert.Equal(identity.RemoteRevision, retainedOwner.RemoteRevision); } + Assert.Empty(await transaction.Conflicts.ListAsync(cancellationToken: token)); + } + + if (remoteBatch is not null && !replace) + { + // The same batch can now use the validated observation as evidence of real local work. + while (true) + { + await using (ICloudStateTransaction read = await factory.Store!.BeginTransactionAsync(token)) + { + if (await read.Checkpoints.GetAsync(CloudLocalChangeFeed.SecurityValidationName(original.OperationId), token) is null) + { + break; + } + } + await Task.Delay(20, token); + } + CloudRemoteApplyResult replay = await fixture.System.ApplyRemoteChangesAsync(remoteBatch, cancellationToken: token); + Assert.False(replay.RequiresRetry); + Assert.Equal(new byte[] { 8 }, replay.SafeCursor.ToArray()); + CloudRemoteApplyEntryResult conflict = Assert.Single(replay.Entries); + Assert.Equal(CloudRemoteApplyEntryStatus.Conflict, conflict.Status); + Assert.Equal(CloudRemoteConflictReason.Content, conflict.Conflict!.Reason); + Assert.Single(replay.ConflictIds); } if (replace) From 744eb043ef3327f2d010b49d2c1b88aee0ea01e5 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:05:11 +0800 Subject: [PATCH 14/15] fix(local-feed): validate native timestamps for delayed size notices --- docs/local-change-feed.md | 10 +- eng/test-ordinary-user-delete.ps1 | 3 +- .../Internal/WindowsSecurityChangeSource.cs | 4 + src/CfSharp/Items/CloudItemInspector.cs | 3 + .../LocalChanges/CloudLocalChangeFeed.Size.cs | 33 ++++-- .../LocalChanges/CloudLocalChangeModels.cs | 3 +- .../LocalChanges/WindowsLocalChangeSource.cs | 2 +- .../ReadOnlyHydrationJournalTests.cs | 105 ++++++++++++++++-- .../WindowsSecurityChangeSourceTests.cs | 4 + 9 files changed, 138 insertions(+), 29 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index ce8af40..39e4879 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -26,10 +26,12 @@ Size notifications have their own subscription because Windows can report a size hydration increases physical allocation and leaves the logical length unchanged. A size notice for a known file placeholder produces no content row when the native notice and the current object agree on identity, logical length and in-sync state, and Windows reports only validated -data. A placeholder can become out of sync from an attribute edit. The feed associates an -out-of-sync size notice with a file only when Windows reports modified data. If the object was -replaced, the captured and current states disagree, or modified data cannot be confirmed, the -feed retains an unbound observation and requires reconciliation. A size notice for a path +data. A placeholder can become out of sync from an attribute edit, and a later write can change +the modified-data count before an older size notice is processed. An out-of-sync size notice +can bind only when the native record's last-write and change times still match the file and +Windows reports modified data. The feed checks those times again around the journal commit. +If the object was replaced, the captured and current states disagree, or modified data cannot be +confirmed, the feed retains an unbound observation and requires reconciliation. A size notice for a path without an item row stays unbound. The ordered name subscription establishes ownership, including when Size arrives before a rename or after an ordinary name disappears. A size notice for an ordinary file can reuse an existing item ID only when its durable native file ID matches the diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 87aa3ac..7281997 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -31,6 +31,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI 'FullyQualifiedName~ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation', 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', + 'FullyQualifiedName~DelayedHydrationSizeNoticeStaysUnboundAfterAcknowledgingTheWrite', 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', 'FullyQualifiedName~SizeAfterRevisionAcknowledgementRemainsBoundToTheSamePlaceholder', 'FullyQualifiedName~TrackedSizeObservationPublishesOnlyVerifiedAssociation', @@ -76,7 +77,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 96 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 99 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs b/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs index 1c44cb3..3c1cf2e 100644 --- a/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs +++ b/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs @@ -185,6 +185,8 @@ internal static unsafe WindowsSecurityChange[] Decode(ReadOnlySpan buffer) FileAttributes = record.FileAttributes, ReparsePointTag = record.ReparsePointTag, FileSize = record.FileSize, + LastWriteTime = record.LastModificationTime, + ChangeTime = record.LastChangeTime, }); if (record.NextEntryOffset == 0) { return changes.ToArray(); } if (record.NextEntryOffset < end || record.NextEntryOffset > buffer.Length || (record.NextEntryOffset & 3) != 0) @@ -245,4 +247,6 @@ internal readonly record struct WindowsSecurityChange(string RelativePath, ulong internal uint FileAttributes { get; init; } internal uint ReparsePointTag { get; init; } internal long FileSize { get; init; } + internal long LastWriteTime { get; init; } + internal long ChangeTime { get; init; } } diff --git a/src/CfSharp/Items/CloudItemInspector.cs b/src/CfSharp/Items/CloudItemInspector.cs index 2385a3e..ab11557 100644 --- a/src/CfSharp/Items/CloudItemInspector.cs +++ b/src/CfSharp/Items/CloudItemInspector.cs @@ -21,6 +21,8 @@ internal sealed class LocalCloudItemInspection internal DateTimeOffset? LastWriteTime { get; init; } + internal long ChangeTime { get; init; } + internal DateTimeOffset? LastAccessTime { get; init; } internal CloudPlaceholderState PlaceholderState { get; init; } @@ -161,6 +163,7 @@ internal static unsafe LocalCloudItemInspection Inspect( Length = length, CreationTime = ToDateTimeOffset(DateTime.FromFileTimeUtc(basic.CreationTime)), LastWriteTime = ToDateTimeOffset(DateTime.FromFileTimeUtc(basic.LastWriteTime)), + ChangeTime = basic.ChangeTime, LastAccessTime = ToDateTimeOffset(DateTime.FromFileTimeUtc(basic.LastAccessTime)), PlaceholderState = placeholderState, ContentAvailability = GetContentAvailability( diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index 011081f..da2ce87 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -11,7 +11,7 @@ public sealed partial class CloudLocalChangeFeed private enum SizeObservationDisposition { Content, CleanPlaceholder, Unbound } private sealed record SizeObservationBinding(CloudLocalFileBinding Local, CloudItemKind Kind, - CloudPlaceholderIdentity? Placeholder); + CloudPlaceholderIdentity? Placeholder, LocalSizeChange? ContentObservation = null); private sealed record StagedSizeObservation(CloudItemPath Path, SizeObservationBinding Binding, CloudOperationJournalEntry Entry) : IStagedObservation @@ -44,8 +44,8 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } LocalCloudItemInspection item = CloudItemInspector.Inspect(reference, path.FullPath, kind, _syncRootPath); - // The native notice identifies today's object. To reuse an existing row for - // an ordinary object, its recorded FileId must also identify that object. + // Match the notice to the current object. Reusing an ordinary item's + // existing row also requires its recorded FileId to identify that object. if (NtfsFileId(item.LocalBinding) is not long fileId || unchecked((ulong)fileId) != identity.FileId || item.LocalBinding?.VolumeSerialNumber != identity.VolumeSerialNumber || item.LocalBinding.SyncRootFileId != identity.RootFileId || @@ -70,8 +70,11 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl { throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); } - binding = new(item.LocalBinding, kind, placeholder); - if (kind != CloudItemKind.File || !capturedPlaceholder) { return SizeObservationDisposition.Content; } + if (kind != CloudItemKind.File || !capturedPlaceholder) + { + binding = new(item.LocalBinding, kind, placeholder); + return SizeObservationDisposition.Content; + } // Hydration can signal Size when allocation grows. Metadata changes can // already have cleared in-sync, so that flag alone cannot prove a data edit. @@ -81,13 +84,16 @@ private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, Cl if (capturedInSync != inSyncNow || item.Length != size.Length || (inSyncNow ? item.ModifiedDataSize != 0 || item.OnDiskDataSize != item.ValidatedDataSize - : item.ModifiedDataSize is not > 0)) + : !MatchesSizeContentObservation(item, size))) { - // A Size notice has no previous logical length. Without evidence of - // modified data, retain it for reconciliation, including length-only edits. + // The current dirty ranges may belong to a later write. Preserve the + // original for reconciliation if its native timestamps disagree. throw new CloudNamespaceObservationUncertainException(isDirectory: false); } - return inSyncNow ? SizeObservationDisposition.CleanPlaceholder : SizeObservationDisposition.Content; + if (inSyncNow) { return SizeObservationDisposition.CleanPlaceholder; } + + binding = new(item.LocalBinding, kind, placeholder, size); + return SizeObservationDisposition.Content; } catch (Win32Exception exception) when (kind == CloudItemKind.File && !capturedPlaceholder && exception.NativeErrorCode is 2 or 3) { @@ -122,7 +128,8 @@ private void ValidateSizeObservationBinding(CloudItemPath path, SizeObservationB ? !item.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder) : CloudPlaceholderIdentity.TryDecode(item.PlaceholderIdentity, out CloudPlaceholderIdentity? current) && binding.Placeholder.Equals(current); - if (item.LocalBinding == binding.Local && sameIdentity && MatchesAttributePath(reference, path)) + if (item.LocalBinding == binding.Local && sameIdentity && MatchesAttributePath(reference, path) && + (binding.ContentObservation is not { } observation || MatchesSizeContentObservation(item, observation))) { return; } @@ -135,6 +142,12 @@ private void ValidateSizeObservationBinding(CloudItemPath path, SizeObservationB throw new CloudNamespaceObservationUncertainException(isDirectory); } + private static bool MatchesSizeContentObservation(LocalCloudItemInspection item, LocalSizeChange size) => + item.SynchronizationState == CloudSynchronizationState.NotInSync && + item.Length == size.Length && item.ModifiedDataSize is > 0 && + size.LastWriteTime > 0 && item.LastWriteTime?.ToFileTime() == size.LastWriteTime && + size.ChangeTime > 0 && item.ChangeTime == size.ChangeTime; + private static bool IsMissingSizeObservationPath(string path) { try { _ = File.GetAttributes(path); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs index 9d7f491..c5878a0 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs @@ -207,7 +207,8 @@ internal readonly record struct LocalChangeSourceEvent( internal readonly record struct LocalSecurityChangeIdentity(ulong VolumeSerialNumber, Guid RootFileId, ulong FileId, ulong ParentFileId, bool IsDirectory); -internal readonly record struct LocalSizeChange(LocalSecurityChangeIdentity Identity, long Length, CloudPlaceholderState PlaceholderState); +internal readonly record struct LocalSizeChange(LocalSecurityChangeIdentity Identity, long Length, + CloudPlaceholderState PlaceholderState, long LastWriteTime, long ChangeTime); internal sealed record LocalChangePayload( string RelativePath, diff --git a/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs b/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs index 5ce6b2f..0aa6038 100644 --- a/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs +++ b/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs @@ -219,7 +219,7 @@ private void OnSizeChanged(WindowsSecurityChange change) : CfPlaceholderState.Invalid; PublishCore(new(LocalChangeSourceAction.SizeModified, change.RelativePath, SizeChange: new(identity, change.FileSize, state == CfPlaceholderState.Invalid - ? CloudPlaceholderState.None : (CloudPlaceholderState)state)), fromSecurityPump: true); + ? CloudPlaceholderState.None : (CloudPlaceholderState)state, change.LastWriteTime, change.ChangeTime)), fromSecurityPump: true); } } diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index fb28e82..7f62036 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -38,7 +38,7 @@ public async Task ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWr Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); Assert.Equal(0, hydrated.ModifiedDataSize); Assert.Equal(before.LastWriteTime, hydrated.LastWriteTime); - await source.WaitForFenceAsync(factory!, "read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, hydrated)); + await source.WaitForFenceAsync(factory!, "read-finished", SizeFromPlaceholderSnapshot(fixture.File, hydrated)); IReadOnlyList afterRead = await AccessRowsAsync(factory!); Assert.DoesNotContain(afterRead, row => row.Kind == CloudStateOperationKind.ContentUpdate && LocalChangePayload.Decode(row.Payload).RelativePath == fixture.File.RelativePath); @@ -109,7 +109,7 @@ public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent CloudItemSnapshot partial = await fixture.File.InspectAsync(token); Assert.Equal(CloudContentAvailability.PartiallyAvailable, partial.ContentAvailability); Assert.Equal(CloudSynchronizationState.InSync, partial.SynchronizationState); - await source.WaitForFenceAsync(factory!, "partial-read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, partial)); + await source.WaitForFenceAsync(factory!, "partial-read-finished", SizeFromPlaceholderSnapshot(fixture.File, partial)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); } int firstFetches = fixture.Provider.Fetches; @@ -125,7 +125,7 @@ public async Task PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent CloudItemSnapshot complete = await fixture.File.InspectAsync(token); Assert.Equal((original, identity.ItemId, identity.RemoteRevision), (complete.LocalBinding, complete.ItemId, complete.RemoteRevision)); Assert.Equal(CloudSynchronizationState.InSync, complete.SynchronizationState); - await restartedSource.WaitForFenceAsync(factory!, "complete-read-finished", SizeFromPlaceholderSnapshot(fixture.File.RelativePath, complete)); + await restartedSource.WaitForFenceAsync(factory!, "complete-read-finished", SizeFromPlaceholderSnapshot(fixture.File, complete)); Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); CloudLocalChangePage page = await reopened.ReadPageAsync(await reopened.BeginScanAsync(token), 0, 100, token); Assert.False(page.RequiresFullRescan); @@ -137,13 +137,17 @@ bool IsHydrationContentRow(CloudOperationJournalEntry row) => row.Kind == CloudS } [Trait("Category", "AccessJournal")] - [Fact] - public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds(bool metadataEdit) { byte[] bytes = new byte[65_537]; new Random(20261125).NextBytes(bytes); AccessJournalFactory? factory = null; - await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), hydrationContent: bytes); + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), + metadataEdit ? CloudInSyncPolicy.TrackAll : CloudInSyncPolicy.None, + hydrationContent: bytes); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); CancellationToken token = deadline.Token; string path = fixture.File.FullPath; @@ -156,10 +160,12 @@ public async Task DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalId await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); await feed.StartAsync(token); + if (metadataEdit) { File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); } Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); - Assert.Equal(CloudSynchronizationState.InSync, hydrated.SynchronizationState); - LocalChangeSourceEvent hydration = SizeFromPlaceholderSnapshot(name, hydrated); + Assert.Equal(metadataEdit ? CloudSynchronizationState.NotInSync : CloudSynchronizationState.InSync, hydrated.SynchronizationState); + Assert.Equal(0, hydrated.ModifiedDataSize); + LocalChangeSourceEvent hydration = SizeFromPlaceholderSnapshot(fixture.File, hydrated); LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => { await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); @@ -230,7 +236,7 @@ public async Task ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservati // Allocation notifications can be coalesced. Deliver the Size record from // the actual post-hydration snapshot through the controlled source. - await source.EmitAsync(SizeFromPlaceholderSnapshot(name, hydrated)); + await source.EmitAsync(SizeFromPlaceholderSnapshot(fixture.File, hydrated)); CloudOperationJournalEntry observation = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); Assert.Equal(CloudStateOperationKind.ContentUpdate, observation.Kind); Assert.Null(observation.ItemId); @@ -243,13 +249,88 @@ public async Task ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservati await feed.AcknowledgeAsync([change.OperationId], token); } - private static LocalChangeSourceEvent SizeFromPlaceholderSnapshot(string relativePath, CloudItemSnapshot snapshot) + [Trait("Category", "AccessJournal")] + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DelayedHydrationSizeNoticeStaysUnboundAfterAcknowledgingTheWrite(bool restoreLastWrite) + { + byte[] bytes = new byte[65_537]; + new Random(20261125).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), CloudInSyncPolicy.TrackAll, + hydrationContent: bytes); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + string name = fixture.File.RelativePath; + string path = fixture.File.FullPath; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "acked-hydration-size", "revision-1"); + DateTimeOffset originalWrite = new(2025, 1, 1, 0, 0, 0, TimeSpan.Zero); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(name, identity, bytes.Length) + .WithMetadata(CloudPlaceholderMetadata.CreateFileBuilder().WithLastWriteTime(originalWrite).Build()) + .WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + + File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); + Assert.Equal(CloudContentAvailability.OnlineOnly, (await fixture.File.InspectAsync(token)).ContentAvailability); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + CloudItemSnapshot hydrated = await fixture.File.InspectAsync(token); + Assert.Equal(CloudSynchronizationState.NotInSync, hydrated.SynchronizationState); + Assert.Equal(0, hydrated.ModifiedDataSize); + LocalChangeSourceEvent hydration = SizeFromPlaceholderSnapshot(fixture.File, hydrated); + + bytes[0] ^= 0xff; + LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => + { + await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); + writer.WriteByte(bytes[0]); + await writer.FlushAsync(token); + }, token); + if (restoreLastWrite) { File.SetLastWriteTimeUtc(path, originalWrite.UtcDateTime); } + CloudItemSnapshot edited = await fixture.File.InspectAsync(token); + Assert.Equal((hydrated.Length, hydrated.LocalBinding, hydrated.SynchronizationState), + (edited.Length, edited.LocalBinding, edited.SynchronizationState)); + Assert.True(edited.ModifiedDataSize > 0); + Assert.Equal(restoreLastWrite, hydrated.LastWriteTime == edited.LastWriteTime); + Assert.NotEqual(hydration.SizeChange!.Value.ChangeTime, + SizeFromPlaceholderSnapshot(fixture.File, edited).SizeChange!.Value.ChangeTime); + + await source.EmitAsync(write); + CloudLocalChangeBatch writeBatch = await feed.ReadBatchAsync(token); + Assert.False(writeBatch.RequiresFullRescan); + CloudLocalChange content = Assert.Single(writeBatch.Changes); + Assert.Equal((CloudLocalChangeKind.ContentUpdate, identity.ItemId), (content.Kind, content.ItemId)); + await feed.AcknowledgeAsync([new CloudLocalChangeAcknowledgement(content.OperationId, "revision-2")], token); + Assert.Empty(await AccessRowsAsync(factory!)); + + await source.EmitAsync(hydration); + CloudOperationJournalEntry retained = await WaitForSingleMetadataJournalEntryAsync(factory!.Store!, token); + Assert.Null(retained.ItemId); + Assert.NotEqual(content.OperationId, retained.OperationId); + Assert.True(retained.Sequence > content.Sequence); + Assert.True((await feed.BeginScanAsync(token)).RequiresFullRescan); + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + CloudLocalChange observation = Assert.Single(page.Changes); + Assert.Equal((retained.OperationId, retained.Sequence, name, (Guid?)null), + (observation.OperationId, observation.Sequence, observation.RelativePath, observation.ItemId)); + await feed.AcknowledgeAsync([observation.OperationId], token); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + } + + private static LocalChangeSourceEvent SizeFromPlaceholderSnapshot(CloudFile file, CloudItemSnapshot snapshot) { CloudLocalFileBinding binding = Assert.IsType(snapshot.LocalBinding); long fileId = Assert.IsType(snapshot.LocalFileId); + LocalCloudItemInspection local = CloudItemInspector.Inspect(file.FullPath, CloudItemKind.File); LocalSizeChange size = new(new(binding.VolumeSerialNumber, binding.SyncRootFileId, unchecked((ulong)fileId), - ParentFileId: 0, IsDirectory: false), Assert.IsType(snapshot.Length), snapshot.PlaceholderState); - return new(LocalChangeSourceAction.SizeModified, relativePath, SizeChange: size); + ParentFileId: 0, IsDirectory: false), Assert.IsType(snapshot.Length), snapshot.PlaceholderState, + Assert.IsType(local.LastWriteTime).ToFileTime(), local.ChangeTime); + return new(LocalChangeSourceAction.SizeModified, file.RelativePath, SizeChange: size); } private sealed class HydrationJournalSource(string root) : ILocalChangeSource diff --git a/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs index 7b1beec..3ed7527 100644 --- a/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs +++ b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs @@ -52,6 +52,8 @@ public void ExtendedSecurityRecordLayoutAndBoundsMatchTheWindowsContract() byte[] name = Encoding.Unicode.GetBytes("before.txt"); byte[] record = new byte[84 + name.Length]; BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(4), 3); + BinaryPrimitives.WriteInt64LittleEndian(record.AsSpan(16), 134022528000000000); + BinaryPrimitives.WriteInt64LittleEndian(record.AsSpan(24), 134022528000000002); BinaryPrimitives.WriteInt64LittleEndian(record.AsSpan(48), 65537); BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(56), 0x10); BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(60), 0x9000001a); @@ -65,6 +67,8 @@ public void ExtendedSecurityRecordLayoutAndBoundsMatchTheWindowsContract() Assert.Equal(0x2000000000005678ul, change.ParentFileId); Assert.True(change.IsDirectory); Assert.Equal(65537, change.FileSize); + Assert.Equal(134022528000000000, change.LastWriteTime); + Assert.Equal(134022528000000002, change.ChangeTime); Assert.Equal(0x10u, change.FileAttributes); Assert.Equal(0x9000001au, change.ReparsePointTag); byte[] unpaired = [.. record.AsSpan(0, 84), 0, 0xd8, 0x61, 0]; From 6216447e0c744bf40b379cd8b2b2d9d7a82fd5c0 Mon Sep 17 00:00:00 2001 From: Quaternion8192 <70364461+Quaternion8192@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:43:16 +0800 Subject: [PATCH 15/15] fix(local-feed): preserve local writes after a remote resize --- docs/local-change-feed.md | 4 + eng/test-ordinary-user-delete.ps1 | 3 +- .../CloudFileSystem.RemoteChanges.cs | 10 +-- .../LocalChanges/CloudLocalChangeFeed.Size.cs | 20 +++++ .../LocalChanges/CloudLocalChangeFeed.cs | 25 +++++- src/CfSharp/Persistence/CloudStateModels.cs | 5 ++ .../ReadOnlyHydrationJournalTests.cs | 88 +++++++++++++++++++ 7 files changed, 144 insertions(+), 11 deletions(-) diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index 39e4879..21ae72a 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -321,6 +321,10 @@ Provider-originated writes can be wrapped by `SuppressProviderEchoAsync` so they uploads. Hydration, pinning, and availability transitions are not local upload operations by themselves. +An automatic file upsert ticket can consume a content notification only while the matching +placeholder is in sync and Windows reports no modified data. A clean Size notification may +leave a ticket active. A subsequent local write with modified data still enters the journal. + ### Acknowledging uploaded snapshots Each observed change has its own durable operation identifier, including repeated notifications for the same path. Acknowledge only the identifiers whose snapshots have completed uploading. An acknowledgement does not cover subsequent observations. Consumers must tolerate redundant uploads rather than assume pending events are coalesced. diff --git a/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index 7281997..ccbc7b6 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -27,6 +27,7 @@ $suiteName = $Suite.ToLowerInvariant() $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversItsOwnReceiptsAcrossOfficialStoreReopen' } elseif ($Suite -eq 'AccessJournal') { @('FullyQualifiedName~AccessOnlyResidentWriteRetainsOriginalJournalAndGenuineLaterEdit', + 'FullyQualifiedName~RemoteResizeSizeNoticeCannotHideASubsequentSameLengthWrite', 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', 'FullyQualifiedName~ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation', 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', @@ -77,7 +78,7 @@ $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversI elseif ($Suite -eq 'CreationBinding') { 'FullyQualifiedName~OfficialCreationBindingSurvivesOnlyCommittedProjection' } else { 'FullyQualifiedName~ExplicitSuccessorAtRetiredPathPreservesBothGenerationsAcrossReopen' } $expectedCount = if ($Suite -eq 'Delete') { 14 } elseif ($Suite -eq 'CreationBinding') { 6 } - elseif ($Suite -eq 'AccessJournal') { 99 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } + elseif ($Suite -eq 'AccessJournal') { 100 } elseif ($Suite -eq 'DeleteReconciliation') { 4 } else { 2 } $evidence = Join-Path $repository ('artifacts/ordinary-user-' + $suiteName) New-Item -ItemType Directory -Path $executionRoot, $evidence -Force | Out-Null $account = $null diff --git a/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs index b0adb2a..31f2310 100644 --- a/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs +++ b/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs @@ -12,8 +12,6 @@ namespace CfSharp; public sealed partial class CloudFileSystem { private const int RemoteConflictEnvelopeVersion = 1; - private const string RemoteEchoPayloadPrefix = "remote-change/v1|"; - private static readonly byte[] s_remoteEchoPayloadPrefix = Encoding.UTF8.GetBytes(RemoteEchoPayloadPrefix); private readonly SemaphoreSlim _remoteApplyGate = new(1, 1); private readonly CloudMetadataEchoAuthority _metadataEchoAuthority = new(); private CloudMetadataEchoAuthority.Call? _metadataEchoCall; @@ -1104,7 +1102,7 @@ await transaction.EchoSuppressions.UpsertAsync( itemId, kind, change.RelativePath, - Encoding.UTF8.GetBytes(RemoteEchoPayloadPrefix + change.ChangeId), + Encoding.UTF8.GetBytes(CloudEchoSuppressionState.RemoteChangePayloadPrefix + change.ChangeId), DateTimeOffset.UtcNow + options.EchoSuppressionLifetime, change.PreviousRelativePath, options.EchoSuppressionObservationCount), @@ -1331,16 +1329,14 @@ await preparation.Checkpoints.UpsertAsync(new(intent.ProvisionalFileTimeObservat cancellationToken).ConfigureAwait(false); } - // These provider-issued upsert tickets can match file Modified events - // without a native identity check. Revoke them in the same transaction + // Revoke earlier provider-issued upsert tickets in the same transaction // that switches policy, before the native write can queue a notification. // A queued observation can carry a time earlier than this switch. IReadOnlyList tickets = await preparation.EchoSuppressions .ListActiveAsync(DateTimeOffset.MinValue, cancellationToken).ConfigureAwait(false); foreach (CloudEchoSuppressionState ticket in tickets) { - if (ticket.ItemId == itemId && ticket.Kind == CloudStateOperationKind.ContentUpdate && - ticket.Payload.Span.StartsWith(s_remoteEchoPayloadPrefix)) + if (ticket.ItemId == itemId && ticket.IsRemoteUpsertContentEcho) { await preparation.EchoSuppressions.RemoveAsync(ticket.SuppressionId, cancellationToken).ConfigureAwait(false); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs index da2ce87..c4aed9d 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -148,6 +148,26 @@ private static bool MatchesSizeContentObservation(LocalCloudItemInspection item, size.LastWriteTime > 0 && item.LastWriteTime?.ToFileTime() == size.LastWriteTime && size.ChangeTime > 0 && item.ChangeTime == size.ChangeTime; + private static bool IsCleanRemoteUpsertFile(CloudItemPath path, CloudItemState owner) + { + if (owner.IsTombstone || !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) { return false; } + try + { + using SafeFileHandle reference = WindowsFileMetadata.OpenMetadataReference(path.FullPath); + LocalCloudItemInspection current = CloudItemInspector.Inspect(reference, path.FullPath, CloudItemKind.File); + return current.SynchronizationState == CloudSynchronizationState.InSync && current.ModifiedDataSize == 0 && + CloudPlaceholderIdentity.TryDecode(current.PlaceholderIdentity, out CloudPlaceholderIdentity? identity) && + identity.ItemId == owner.ItemId && identity.RemoteId == owner.RemoteId && + (owner.LocalFileId is null || owner.LocalFileId == current.LocalFileId) && MatchesAttributePath(reference, path); + } + catch (Exception exception) when (exception is CloudPathReparsePointException or CloudFilesException or + Win32Exception or UnauthorizedAccessException or InvalidOperationException or IOException) + { + // Without a clean native match, leave the observation in the journal path. + return false; + } + } + private static bool IsMissingSizeObservationPath(string path) { try { _ = File.GetAttributes(path); } diff --git a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs index bfae53f..74d3979 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.cs @@ -1173,9 +1173,28 @@ await transaction.Checkpoints.UpsertAsync(new CloudStateCheckpoint( CloudDirectoryStateProjection.SamePath(candidate.RelativePath, path.RelativePath)) && (await ReadMetadataIntentsAsync(transaction, cancellationToken, observedState.ItemId).ConfigureAwait(false)) .Any(intent => intent.Passthrough && !intent.Superseded && intent.Covers(path.RelativePath)); - suppression = suppressions.FirstOrDefault(candidate => candidate.Kind != CloudStateOperationKind.MetadataUpdate && (RemoteCreationIntent.IsCreationEcho(candidate) - ? !bypassCreationContentEcho && MatchesRemoteCreationEcho(candidate, operationKind, path, observedState) - : candidate.Matches(operationKind, path.RelativePath, previousPath?.RelativePath, observedState?.ItemId))); + bool? cleanUpsertTarget = null; + suppression = suppressions.FirstOrDefault(MatchesSuppression); + + bool MatchesSuppression(CloudEchoSuppressionState candidate) + { + if (candidate.Kind == CloudStateOperationKind.MetadataUpdate) { return false; } + if (RemoteCreationIntent.IsCreationEcho(candidate)) + { + return !bypassCreationContentEcho && MatchesRemoteCreationEcho(candidate, operationKind, path, observedState); + } + if (!candidate.Matches(operationKind, path.RelativePath, previousPath?.RelativePath, observedState?.ItemId)) + { + return false; + } + if (observedState is { Kind: CloudItemKind.File } && candidate.IsRemoteUpsertContentEcho) + { + // A clean Size notice can be the provider's only notification. A + // remaining upsert ticket must not consume a later local write. + return cleanUpsertTarget ??= IsCleanRemoteUpsertFile(path, observedState); + } + return true; + } } if (suppression is not null) diff --git a/src/CfSharp/Persistence/CloudStateModels.cs b/src/CfSharp/Persistence/CloudStateModels.cs index 9790279..57b8357 100644 --- a/src/CfSharp/Persistence/CloudStateModels.cs +++ b/src/CfSharp/Persistence/CloudStateModels.cs @@ -359,6 +359,8 @@ public CloudRemoteBatchState( /// Represents a durable provider-originated local-change suppression record. public sealed class CloudEchoSuppressionState { + internal const string RemoteChangePayloadPrefix = "remote-change/v1|"; + private static readonly byte[] s_remoteChangePayloadPrefix = System.Text.Encoding.UTF8.GetBytes(RemoteChangePayloadPrefix); private readonly byte[] _payload; /// Initializes a suppression record and copies its CfSharp-defined payload. @@ -428,6 +430,9 @@ public CloudEchoSuppressionState( /// Gets the number of matching local observations that may still be consumed. public int RemainingObservations { get; } + internal bool IsRemoteUpsertContentEcho => + Kind == CloudStateOperationKind.ContentUpdate && _payload.AsSpan().StartsWith(s_remoteChangePayloadPrefix); + internal bool Matches( CloudStateOperationKind observedKind, string relativePath, diff --git a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs index 7f62036..89adf9a 100644 --- a/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -4,6 +4,94 @@ public sealed partial class CloudContentConfirmationTests { private const string OriginalSizePath = "original.bin"; + [Trait("Category", "AccessJournal")] + [Fact] + public async Task RemoteResizeSizeNoticeCannotHideASubsequentSameLengthWrite() + { + byte[] bytes = new byte[4096]; + new Random(20261127).NextBytes(bytes); + AccessJournalFactory? factory = null; + await using Fixture fixture = await Fixture.StartAsync(path => factory = new(path), hydrationContent: bytes); + using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(25)); + CancellationToken token = deadline.Token; + string name = fixture.File.RelativePath; + string path = fixture.File.FullPath; + CloudPlaceholderIdentity identity = new(Guid.NewGuid(), "remote-resize-echo", "revision-1"); + (await fixture.System.Root.CreatePlaceholdersAsync([ + CloudFilePlaceholderSpec.CreateBuilder(name, identity, 0).WithInSyncState(true).Build(), + ], cancellationToken: token)).ThrowIfAnyFailed(); + + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(token); + CloudRemoteChange resize = new("resize", CloudRemoteChangeKind.FileUpsert, identity.RemoteId, "revision-2", + CloudItemKind.File, name, identity.ItemId, previousRemoteRevision: identity.RemoteRevision, length: bytes.Length, + metadata: CloudPlaceholderMetadata.CreateFileBuilder().Build()); + LocalChangeSourceEvent size = await CaptureNativeModificationAsync(fixture.Root, name, async () => + { + CloudRemoteApplyResult result = await fixture.System.ApplyRemoteChangesAsync( + new("remote-resize-echo", Array.Empty(), [resize], new byte[] { 1 }), cancellationToken: token); + Assert.Equal(CloudRemoteApplyEntryStatus.Applied, Assert.Single(result.Entries).Status); + }, token, LocalChangeSourceAction.SizeModified); + CloudItemSnapshot resized = await fixture.File.InspectAsync(token); + Assert.Equal((bytes.LongLength, CloudSynchronizationState.InSync, 0L), + (resized.Length, resized.SynchronizationState, resized.ModifiedDataSize)); + Assert.Equal(bytes.LongLength, size.SizeChange!.Value.Length); + + await source.EmitAsync(size); + await DrainThroughMarkerAsync("resize-drained"); + Assert.Empty(await AccessRowsAsync(factory!)); + CloudEchoSuppressionState originalTicket; + await using (ICloudStateTransaction read = await factory!.Store!.BeginTransactionAsync(token)) + { + originalTicket = Assert.Single(await read.EchoSuppressions.ListActiveAsync(DateTimeOffset.UtcNow, token)); + Assert.Equal((CloudStateOperationKind.ContentUpdate, identity.ItemId), (originalTicket.Kind, originalTicket.ItemId)); + } + + // A remote resize can emit only Size, leaving its ContentUpdate ticket available + // for the genuine LastWrite that follows the first read of the new revision. + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + bytes[0] ^= 0xff; + LocalChangeSourceEvent write = await CaptureNativeModificationAsync(fixture.Root, name, async () => + { + await using FileStream writer = new(path, FileMode.Open, FileAccess.Write, FileShare.Read); + writer.WriteByte(bytes[0]); + await writer.FlushAsync(token); + }, token); + CloudItemSnapshot edited = await fixture.File.InspectAsync(token); + Assert.Equal(resized.Length, edited.Length); + Assert.True(edited.ModifiedDataSize > 0); + await source.EmitAsync(write); + await DrainThroughMarkerAsync("write-drained"); + + CloudOperationJournalEntry original = Assert.Single(await AccessRowsAsync(factory!)); + Assert.Equal((CloudStateOperationKind.ContentUpdate, identity.ItemId), (original.Kind, original.ItemId)); + await using (ICloudStateTransaction read = await factory!.Store!.BeginTransactionAsync(token)) + { + CloudEchoSuppressionState unused = Assert.IsType( + await read.EchoSuppressions.GetAsync(originalTicket.SuppressionId, token)); + Assert.Equal(originalTicket.RemainingObservations, unused.RemainingObservations); + } + CloudLocalChangePage page = await feed.ReadPageAsync(await feed.BeginScanAsync(token), 0, 10, token); + Assert.False(page.RequiresFullRescan); + CloudLocalChange local = Assert.Single(page.Changes); + Assert.Equal((original.OperationId, original.Sequence, identity.ItemId, name), + (local.OperationId, local.Sequence, local.ItemId, local.RelativePath)); + await feed.AcknowledgeAsync([local.OperationId], token); + Assert.Empty(await AccessRowsAsync(factory!)); + Assert.Equal(bytes, await File.ReadAllBytesAsync(path, token)); + + async Task DrainThroughMarkerAsync(string marker) + { + Directory.CreateDirectory(Path.Combine(fixture.Root, marker)); + await source.EmitAsync(new(LocalChangeSourceAction.Created, marker)); + await WaitForAccessRowsAsync(factory!, rows => rows.Any(row => LocalChangePayload.Decode(row.Payload).RelativePath == marker)); + CloudOperationJournalEntry fence = Assert.Single(await AccessRowsAsync(factory!), + row => LocalChangePayload.Decode(row.Payload).RelativePath == marker); + await feed.AcknowledgeAsync([fence.OperationId], token); + } + } + [Trait("Category", "AccessJournal")] [Theory] [InlineData(CloudInSyncPolicy.None)]