Registry Mirror
Skip to content

[Bug] VacuumAsync(VacuumMode.Full) throws ObjectDisposedException under .NET 10 Trimming / Native AOT #343

Closed

Description

@saltus7

Describe the bug
VacuumAsync(VacuumMode.Full) crashes with an unhandled ObjectDisposedException when the application is published with .NET 10 trimming enabled (PublishTrimmed=true).

To Reproduce
Steps to reproduce the behavior:

  1. Create a project referencing SharpCoreDB v1.9.7.
  2. Configure the project for AOT/Trimming:
    <PublishSingleFile>true</PublishSingleFile>
    <PublishTrimmed>true</PublishTrimmed>
  3. Publish and run: dotnet publish -c Release -r win-x64 --self-contained true
  4. Execute: await db.VacuumAsync(VacuumMode.Full, CancellationToken.None);
  5. See error:
    [FATAL] ObjectDisposedException: Cannot access a closed file.
       at System.IO.FileStream.get_Length()
       at SharpCoreDB.Storage.SingleFileStorageProvider.VacuumAsync(...) at SingleFileStorageProvider.cs:line 1258
    

Expected behavior
The vacuum operation should complete successfully, rewriting the file compactly and swapping the underlying file stream without crashing.

Root Cause Analysis
VacuumFullAsync closes the current _fileStream and attempts to swap in a newly opened stream using Reflection:

_fileStream.Close();
// ... file moves ...
var newFileStream = new FileStream(...);

var fsField = typeof(SingleFileStorageProvider).GetField("_fileStream", 
    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
fsField.SetValue(this, newFileStream);

Under .NET 10 Trimming / Native AOT, metadata for private fields is aggressively trimmed. GetField("_fileStream", ...) returns null, causing fsField.SetValue(...) to throw a NullReferenceException.

This triggers a cascading failure:

  1. The NullReferenceException is caught by the catch block in VacuumFullAsync.
  2. The catch block attempts to read _fileStream.Length to build the VacuumResult.
  3. Because the old stream was closed just prior to the reflection call, this throws ObjectDisposedException.
  4. This exception propagates to the catch block in VacuumAsync, which also attempts to read _fileStream.Length (line 1258), throwing the ObjectDisposedException that ultimately crashes the application.

Desktop (please complete the following information):

  • OS: Windows NT 10.0.26200.0
  • Runtime: .NET 10.0.11
  • Library Version: v1.9.7

Additional context
Proposed fixes:

  1. Avoid Reflection: The reliance on GetField for internal state mutation is fundamentally incompatible with AOT/Trimming. Consider exposing an internal ReplaceFileStream(FileStream newStream) method, or refactoring VacuumFull to operate without closing and swapping the underlying stream mid-operation.
  2. Safe Error Handling: The catch blocks in both VacuumAsync and VacuumFullAsync should not blindly access _fileStream.Length if the stream may have been closed. Use a safe fallback (e.g., FileSizeAfter = -1 or 0) in the error path.

Activity

  1. added
    priority:p1
    on Aug 29, 2026
  2. added
    bug
    on Aug 29, 2026
  3. MPCoreDeveloper commented on Aug 29, 2026

    @MPCoreDeveloper
    Owner

    Thanks for the detailed report — this is exactly the kind of root-cause analysis that makes a fix fast. ✔️

    Fixed in v1.9.8 (and carried into the upcoming v2.0)

    Your diagnosis was accurate on all counts. The fix follows your ReplaceFileStream proposal:

    1. Reflection-free stream swap — VacuumFullAsync now swaps _fileStream / _memoryMappedFile via direct assignment in an internal SwapFileStream helper (the fields are no longer readonly). No more GetField(...)/SetValue(...).
    2. Safe error paths — the catch blocks in both VacuumAsync and VacuumFullAsync now read the file size through GetFileSizeSafely() with a -1 fallback instead of touching a possibly-closed stream, so the cascade you described (ObjectDisposedException) can no longer happen.
    3. Bonus bug the new regression test exposed — the temp file was created as <file>.vacuum.tmp.scdb (the provider appends the .scdb extension) but later moved as <file>.vacuum.tmp → FileNotFoundException. The temp-file name is now consistent.
    4. Single-file mode is now fully Native AOT-safe — while validating the fix we found two more reflection-based paths that broke under trimming: the row-cache JSON serialization (now a source-generated JsonSerializerContext + polymorphic converter, byte-identical output so existing .scdb files stay readable) and the batch-flush GetField(...) + dynamic calls (now internal TableDirectoryManager/BlockRegistry accessors).

    Verified by publishing SharpCoreDB.AotSmoke with PublishAot=true — it runs exit 0 including the single-file full-VACUUM path. Regression test: SingleFileDatabase_VacuumFull_Works_And_SurvivesReopen (100 rows, full vacuum, reopen + read-back).

    About the v2.0 release

    We will publish a v2.0 preview shortly after this — the performance-first release (point reads beat SQLite on the default engine, batch INSERTs beat SQLite on the PageBased engine, every CRUD operation beats LiteDB), and it carries the same AOT fix set, so VacuumAsync(Full) + single-file mode will be AOT-safe there too.

    Full credit added to CONTRIBUTORS.md — thanks again! 🙏

  4. saltus7 commented on Aug 29, 2026

    @saltus7
    CollaboratorAuthor

    @MPCoreDeveloper Verified the fix in v1.9.8 under .NET 10 trimming. VacuumMode.Full now completes successfully with no ObjectDisposedException, and data integrity is perfectly maintained. I also noted the v2.0 roadmap for block-registry encryption to address the metadata leakage — excellent long-term planning. Thanks for the rapid turnaround!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

buginvesttigationpriority:p1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions