diff --git a/docs/local-change-feed.md b/docs/local-change-feed.md index fafa53c..21ae72a 100644 --- a/docs/local-change-feed.md +++ b/docs/local-change-feed.md @@ -17,11 +17,36 @@ 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. 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 +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. 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. + 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 @@ -296,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/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/eng/test-ordinary-user-delete.ps1 b/eng/test-ordinary-user-delete.ps1 index d110065..ccbc7b6 100644 --- a/eng/test-ordinary-user-delete.ps1 +++ b/eng/test-ordinary-user-delete.ps1 @@ -27,6 +27,16 @@ $suiteName = $Suite.ToLowerInvariant() $filter = if ($Suite -eq 'Delete') { 'FullyQualifiedName~OriginalDeleteRecoversItsOwnReceiptsAcrossOfficialStoreReopen' } elseif ($Suite -eq 'AccessJournal') { @('FullyQualifiedName~AccessOnlyResidentWriteRetainsOriginalJournalAndGenuineLaterEdit', + 'FullyQualifiedName~RemoteResizeSizeNoticeCannotHideASubsequentSameLengthWrite', + 'FullyQualifiedName~ReadOnlyHydrationLeavesNoContentUpdateAndPreservesAnOrdinaryWrite', + 'FullyQualifiedName~ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation', + 'FullyQualifiedName~PartialReadOnlyHydrationAndReconnectPreserveTheAcceptedContent', + 'FullyQualifiedName~DelayedHydrationSizeNoticeAndGenuineWriteKeepSeparateJournalIds', + 'FullyQualifiedName~DelayedHydrationSizeNoticeStaysUnboundAfterAcknowledgingTheWrite', + 'FullyQualifiedName~SizeBeforeRenamePreservesTheOriginalItemId', + 'FullyQualifiedName~SizeAfterRevisionAcknowledgementRemainsBoundToTheSamePlaceholder', + 'FullyQualifiedName~TrackedSizeObservationPublishesOnlyVerifiedAssociation', + 'FullyQualifiedName~OrdinarySizeObservationDoesNotReuseAnUnboundPlaceholderItem', 'FullyQualifiedName~NativeFileTimestampAndSameLengthDataWriteRetainTheirOriginalObservations', 'FullyQualifiedName~UnconfirmedFileTimestampPassthroughRetainsItsDelayedNotification', 'FullyQualifiedName~ConfirmedFileTimestampPassthroughDoesNotUnbindLaterContent', @@ -68,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') { 82 } 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.Native/Internal/WindowsSecurityChangeSource.cs b/src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs index a2ef9d9..3c1cf2e 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,14 @@ 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, + 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) { throw new InvalidDataException("The security notification link is invalid."); } @@ -235,4 +242,11 @@ 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; } + internal long LastWriteTime { get; init; } + internal long ChangeTime { get; init; } +} 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/FileSystem/CloudFileSystem.RemoteChanges.cs b/src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs index 9660b5c..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; @@ -69,6 +67,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 +284,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 +1051,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 +1067,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, @@ -1081,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), @@ -1234,8 +1255,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 @@ -1308,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/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/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.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..b0f62c0 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Security.cs @@ -9,10 +9,12 @@ 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 _validatedAttributeSequence; + 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, @@ -65,28 +67,29 @@ 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; } - 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); - long validated = Volatile.Read(ref _validatedAttributeSequence); + 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++) { CloudOperationJournalEntry operation = operations[index]; @@ -95,19 +98,35 @@ private async ValueTask ValidatedMetadataPrefixLengthAsync(ICloudStateTrans return operations.Count; } - private static async ValueTask RetainUnboundSecurityObservationAsync(ICloudStateTransaction transaction, Guid operationId, - ReadOnlyMemory payload, DateTimeOffset observedAt, CancellationToken cancellationToken) + 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) { 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 +138,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 +160,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 +169,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 +188,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 new file mode 100644 index 0000000..c4aed9d --- /dev/null +++ b/src/CfSharp/LocalChanges/CloudLocalChangeFeed.Size.cs @@ -0,0 +1,177 @@ +using System.ComponentModel; + +using CfSharp.Native; + +using Microsoft.Win32.SafeHandles; + +namespace CfSharp; + +public sealed partial class CloudLocalChangeFeed +{ + private enum SizeObservationDisposition { Content, CleanPlaceholder, Unbound } + + private sealed record SizeObservationBinding(CloudLocalFileBinding Local, CloudItemKind Kind, + CloudPlaceholderIdentity? Placeholder, LocalSizeChange? ContentObservation = null); + + private sealed record StagedSizeObservation(CloudItemPath Path, SizeObservationBinding Binding, + CloudOperationJournalEntry Entry) : IStagedObservation + { + public ValueTask PublishAsync(CloudLocalChangeFeed feed, CancellationToken cancellationToken) + { + feed.ValidateSizeObservationBinding(Path, Binding); + return feed.CompleteValidatedObservationAsync(Entry.OperationId, Entry.Sequence, cancellationToken); + } + + public void Dispose() { } + } + + private SizeObservationDisposition InspectSizeObservation(CloudItemPath path, CloudItemState owner, LocalSizeChange size, + out SizeObservationBinding? binding) + { + binding = null; + 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); + } + 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); + // 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 || + 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); + } + + if (capturedPlaceholder != item.PlaceholderState.HasFlag(CloudPlaceholderState.Placeholder)) + { + 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)) + { + throw new CloudNamespaceObservationUncertainException(identity.IsDirectory); + } + 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. + // 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 + : !MatchesSizeContentObservation(item, size))) + { + // 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); + } + 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) + { + return SizeObservationDisposition.Unbound; + } + catch (CloudNamespaceObservationUncertainException) when (kind == CloudItemKind.File && !capturedPlaceholder && + IsMissingSizeObservationPath(path.FullPath)) + { + return SizeObservationDisposition.Unbound; + } + 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); + } + } + + private void ValidateSizeObservationBinding(CloudItemPath path, SizeObservationBinding binding) + { + bool isDirectory = binding.Kind == CloudItemKind.Directory; + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 16299)) + { + throw new CloudNamespaceObservationUncertainException(isDirectory); + } + try + { + using SafeFileHandle reference = WindowsFileMetadata.OpenMetadataReference(path.FullPath); + 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) && + (binding.ContentObservation is not { } observation || MatchesSizeContentObservation(item, observation))) + { + return; + } + } + catch (Exception exception) when (exception is CloudPathReparsePointException or CloudFilesException or + Win32Exception or UnauthorizedAccessException or InvalidOperationException or IOException) + { + throw new CloudNamespaceObservationUncertainException(isDirectory, exception); + } + 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 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); } + 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 ebb0f15..74d3979 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) { @@ -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,22 +922,21 @@ 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; + IStagedObservation? staged = null; try { 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) { - staged.Projection.Validate(); - await PublishValidatedSecurityObservationAsync(staged.Entry, staged.Projection, staged.Observation, cancellationToken).ConfigureAwait(false); + await staged.PublishAsync(this, cancellationToken).ConfigureAwait(false); } } finally @@ -943,9 +945,10 @@ 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, CancellationToken cancellationToken) + bool? uncertainDirectory, LocalChangeSourceEvent? securityObservation, LocalSizeChange? sizeChange, + CancellationToken cancellationToken) { LocalChangeCheckpoint checkpoint = await ReadCheckpointAsync(transaction, cancellationToken) .ConfigureAwait(false); @@ -971,6 +974,33 @@ 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))); + SizeObservationBinding? sizeBinding = null; + if (sizeChange is { } size && uncertainDirectory is null) + { + if (pendingCreation || pendingMove || pendingDelete) + { + throw new CloudNamespaceObservationUncertainException(size.Identity.IsDirectory); + } + SizeObservationDisposition disposition = current is null + ? SizeObservationDisposition.Unbound + : InspectSizeObservation(path, current, size, out sizeBinding); + if (disposition == SizeObservationDisposition.CleanPlaceholder) { return null; } + if (disposition == SizeObservationDisposition.Unbound) + { + // 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); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + SignalAvailable(); + return null; + } + } bool uncertainFileContent = false; if (kind == CloudLocalChangeKind.ContentUpdate) { @@ -980,13 +1010,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 && @@ -1051,12 +1081,12 @@ private async ValueTask PersistChangeAttemptAsync(CloudLocalChangeKind kind, Clo 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) @@ -1112,7 +1142,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 && @@ -1142,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) @@ -1170,6 +1220,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); SignalAvailable(); @@ -1230,13 +1281,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, appended); + } } bool requiresRescan = uncertainDirectory is not null || directoryProjection?.RequiresRescan == true; @@ -1254,6 +1315,7 @@ await UpsertCheckpointAsync( observedAt, cancellationToken).ConfigureAwait(false); directoryProjection?.Validate(); + if (sizeBinding is not null) { ValidateSizeObservationBinding(path, sizeBinding); } await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); if (requiresRescan) { @@ -1261,6 +1323,7 @@ await UpsertCheckpointAsync( } directoryProjection?.Validate(); + if (stagedSize is not null) { return stagedSize; } SignalAvailable(); return null; @@ -1327,7 +1390,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 @@ -1384,7 +1448,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/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs index 72a25fc..c5878a0 100644 --- a/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs +++ b/src/CfSharp/LocalChanges/CloudLocalChangeModels.cs @@ -194,16 +194,22 @@ 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, long LastWriteTime, long ChangeTime); + internal sealed record LocalChangePayload( string RelativePath, string? PreviousRelativePath, diff --git a/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs b/src/CfSharp/LocalChanges/WindowsLocalChangeSource.cs index 3291be0..0aa6038 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, change.LastWriteTime, change.ChangeTime)), 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/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/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.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..89adf9a --- /dev/null +++ b/tests/CfSharp.IntegrationTests/ReadOnlyHydrationJournalTests.cs @@ -0,0 +1,840 @@ +namespace CfSharp.IntegrationTests; + +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)] + [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; + + 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)); + 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 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); + + 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))); + 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(); + 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 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))); + 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; + 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 source.WaitForFenceAsync(factory!, "partial-read-finished", SizeFromPlaceholderSnapshot(fixture.File, partial)); + Assert.DoesNotContain(await AccessRowsAsync(factory!), IsHydrationContentRow); + } + int firstFetches = fixture.Provider.Fetches; + await fixture.RestartAsync(); + 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); + 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, complete)); + 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")] + [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), + metadataEdit ? CloudInSyncPolicy.TrackAll : CloudInSyncPolicy.None, + 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); + + 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(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); + 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)); + } + + [Trait("Category", "AccessJournal")] + [Fact] + public async Task ReadOnlyHydrationAfterAttributeEditRetainsUnboundSizeObservation() + { + 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(fixture.File, 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); + } + + [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, + Assert.IsType(local.LastWriteTime).ToFileTime(), local.ChangeTime); + return new(LocalChangeSourceAction.SizeModified, file.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] + 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 = 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 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); + 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)); + } + + 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); + file.SetLength(4096); + file.Flush(flushToDisk: true); + 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 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() + { + 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 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)) + { + 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-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), 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"); + 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 = 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) + { + 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); + Assert.True(resized.ModifiedDataSize > 0); + } + ControlledMetadataSource source = new(); + await using CloudLocalChangeFeed feed = fixture.System.CreateLocalChangeFeed(null, source); + await feed.StartAsync(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; + CloudRemoteChangeBatch? remoteBatch = null; + try + { + await factory.OutcomePaused.Task.WaitAsync(token); + 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); + } + if (boundary == "size-publication-committed") + { + provisional = await WaitForSingleMetadataJournalEntryAsync(factory.Store!, token); + 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); + 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(); } + + 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); + if (provisional is not null) + { + Assert.Equal((provisional.OperationId, provisional.Sequence), (original.OperationId, original.Sequence)); + } + 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((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) + { + await feed.AcknowledgeFullRescanAsync(feed.BeginFullRescan(), token); + 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); + Assert.Equal((original.OperationId, original.Sequence, OriginalSizePath), (retained.OperationId, retained.Sequence, retained.RelativePath)); + Assert.Equal(expectedItemId, retained.ItemId); + await feed.AcknowledgeAsync([retained.OperationId], token); + } + + [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 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); + + 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)); + } +} diff --git a/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs b/tests/CfSharp.IntegrationTests/RemoteMetadataRecoveryTests.cs index 7b7eb77..51b36a8 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-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; 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-append" && name == RemoteMetadataIntent.DirectoryTimeObservationName(OriginalSizePath)) + { + await PauseSizeDiscoveryAsync("size-before-append", 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) { @@ -1732,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), @@ -1762,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.Native.Tests/WindowsSecurityChangeSourceTests.cs b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs index aec0498..3ed7527 100644 --- a/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs +++ b/tests/CfSharp.Native.Tests/WindowsSecurityChangeSourceTests.cs @@ -43,13 +43,20 @@ 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(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); BinaryPrimitives.WriteUInt64LittleEndian(record.AsSpan(64), 0x1000000000001234); BinaryPrimitives.WriteUInt64LittleEndian(record.AsSpan(72), 0x2000000000005678); BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(80), (uint)name.Length); @@ -59,6 +66,11 @@ public void ExtendedSecurityRecordLayoutAndBoundsMatchTheWindowsContract() Assert.Equal(0x1000000000001234ul, change.FileId); 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]; BinaryPrimitives.WriteUInt32LittleEndian(unpaired.AsSpan(80), 4); string nativeName = Assert.Single(WindowsSecurityChangeSource.Decode(unpaired)).RelativePath; diff --git a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs index 24f3b51..cddfb6a 100644 --- a/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs +++ b/tests/CfSharp.Storage.Sqlite.Tests/CloudLocalChangeMetadataPublicationTests.cs @@ -38,25 +38,28 @@ 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(); 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)); - 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)); 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<