Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
df6212c
fix(local-feed): distinguish hydration size notifications from edits
Quaternion8192 Nov 25, 2026
7b5db4b
fix(local-feed): retain late sizes at retired ordinary names
Quaternion8192 Nov 25, 2026
2c0ac66
test(local-feed): make delayed hydration delivery deterministic
Quaternion8192 Nov 25, 2026
52bdc03
fix(local-feed): revalidate size identity before journal commit
Quaternion8192 Nov 25, 2026
0d8e8fe
test(local-feed): wait for hydration size processing
Quaternion8192 Nov 25, 2026
449efe9
fix(local-feed): require durable identity for ordinary size observations
Quaternion8192 Nov 25, 2026
4c67e11
fix(local-feed): keep size notices from establishing namespace ownership
Quaternion8192 Nov 25, 2026
16e2413
fix(local-feed): withhold size bindings until post-commit validation
Quaternion8192 Nov 25, 2026
7862276
fix(local-feed): revalidate the placeholder identity of size notices
Quaternion8192 Nov 26, 2026
1b699dd
fix(sqlite): fence staged content recovery with schema 11
Quaternion8192 Nov 26, 2026
f59321f
fix(local-feed): require data evidence for out-of-sync size notices
Quaternion8192 Nov 26, 2026
4b2d8a6
fix(local-feed): accept size notices after revision acknowledgement
Quaternion8192 Nov 26, 2026
2d25973
fix(remote-changes): defer on unvalidated local journal associations
Quaternion8192 Nov 26, 2026
744eb04
fix(local-feed): validate native timestamps for delayed size notices
Quaternion8192 Nov 26, 2026
6216447
fix(local-feed): preserve local writes after a remote resize
Quaternion8192 Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions docs/local-change-feed.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
5 changes: 3 additions & 2 deletions docs/metadata-echo-coordination.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/remote-change-application.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 8 additions & 7 deletions docs/state-store-sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion eng/test-ordinary-user-delete.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions src/CfSharp.Native/Internal/WindowsSecurityChangeSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ internal sealed partial class WindowsSecurityChangeSource : IAsyncDisposable
internal WindowsSecurityChangeSource(string path, int capacity, Action<WindowsSecurityChange> changed,
Action<int, bool> 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;
Expand Down Expand Up @@ -180,7 +180,14 @@ internal static unsafe WindowsSecurityChange[] Decode(ReadOnlySpan<byte> 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<byte, char>(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."); }
Expand Down Expand Up @@ -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; }
}
7 changes: 4 additions & 3 deletions src/CfSharp.Storage.Sqlite/SqliteCloudStateStoreFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SqliteCloudStateTransaction> BeginSchemaTransactionAsync(
Expand Down Expand Up @@ -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(
Expand Down
39 changes: 29 additions & 10 deletions src/CfSharp/FileSystem/CloudFileSystem.RemoteChanges.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -284,6 +284,8 @@ private async ValueTask<CloudRemoteApplyResult> ApplyRemoteChangesCoreAsync(
/// </remarks>
/// <exception cref="KeyNotFoundException">The conflict no longer exists.</exception>
/// <exception cref="InvalidDataException">The durable conflict envelope is corrupt.</exception>
/// <exception cref="IOException">A local observation for the item is still awaiting
/// identity validation. Retry with the same conflict identifier.</exception>
public async ValueTask<CloudRemoteApplyEntryResult> ResolveRemoteConflictAsync(
Guid conflictId,
CloudRemoteConflictResolution resolution,
Expand Down Expand Up @@ -1049,7 +1051,8 @@ private async ValueTask<RemoteEntryContext> ReadRemoteEntryContextAsync(
CloudItemState? localState = byRemoteId ?? byItemId ?? byPreviousPath ?? pathState;
IReadOnlyList<CloudOperationJournalEntry> operations = localState is null
? []
: await transaction.Operations.ListByItemIdAsync(
: await ReadValidatedRemoteLocalOperationsAsync(
transaction,
localState.ItemId,
maximumCount: int.MaxValue,
cancellationToken)
Expand All @@ -1064,6 +1067,24 @@ private async ValueTask<RemoteEntryContext> ReadRemoteEntryContextAsync(
operations);
}

private static async ValueTask<IReadOnlyList<CloudOperationJournalEntry>> ReadValidatedRemoteLocalOperationsAsync(
ICloudStateTransaction transaction, Guid itemId, int maximumCount, CancellationToken cancellationToken)
{
IReadOnlyList<CloudOperationJournalEntry> 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<string>? 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<Guid> RegisterRemoteEchoSuppressionAsync(
CloudRemoteChange change,
Guid itemId,
Expand All @@ -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),
Expand Down Expand Up @@ -1234,8 +1255,8 @@ private async ValueTask<IDisposable> GuardRemotePlaceholderWriteAsync(CloudRemot
{
throw new RemotePlaceholderWriteConflictException(CloudRemoteConflictReason.Metadata);
}
IReadOnlyList<CloudOperationJournalEntry> operations = await transaction.Operations.ListByItemIdAsync(
itemId, maximumCount: 1, cancellationToken).ConfigureAwait(false);
IReadOnlyList<CloudOperationJournalEntry> operations = await ReadValidatedRemoteLocalOperationsAsync(
transaction, itemId, maximumCount: 1, cancellationToken).ConfigureAwait(false);
if (operations.Count != 0)
{
throw new RemotePlaceholderWriteConflictException(change.Kind == CloudRemoteChangeKind.MetadataUpdate
Expand Down Expand Up @@ -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<CloudEchoSuppressionState> 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);
}
Expand Down
Loading
Loading