Improved reading and writing large Office files without copying them into memory (#1243)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-28 23:03:30 +01:00
1 parent 918572c158
commit dbe609a9a7
37 files changed
+1161 -471

No files matched your search

@@ -52,14 +52,16 @@ the repository root and to `app/AGENTS.md`, which apply here as well.
The format refuses a larger text before reading it (`DocumentTooLargeException`), and `SelectDocument` when the
form is checked, before a run starts. A new format measures its own factor with a dense document.
- **Write only into the file the user chose, and never the whole file through memory.** A document with videos
takes hundreds of megabytes, and the SDK saves a package in the update mode of ZipArchive, which loads every entry
behind the first changed one. So `OpenXmlSegmentFormat` opens the source for reading only, the writer changes the
DOM, and `PackageRewrite` from `app/MindWork AI Studio/Tools/OpenXml/` writes a new archive in which every other
entry streams through as it is, a stored one stays stored. The new document comes about in a `StagedDocument`
below the data directory, not in the temporary folder, which lives in memory on many Linux systems, and
`TargetFile` streams it into the file the user chose. A writer therefore changes only the XML of existing parts and
never adds or removes parts or relationships. A new Office format brings only its reader, its writer, and the
element of each paragraph (`ElementOf`).
takes hundreds of megabytes. The SDK copies a document it opens for reading only into the temporary folder, as a
whole, and the temporary folder lives in memory on many Linux systems; it saves a package in the update mode of
ZipArchive, which loads every entry behind the first changed one. So `OpenXmlSegmentFormat` never opens the source
with the SDK: it reads and writes through a `PackageSkeleton` from `app/MindWork AI Studio/Tools/OpenXml/`, which
holds only the XML of the source. The writer changes the DOM of the skeleton, opened for reading only, and the
skeleton writes a new archive with the changed parts, in which every other entry streams through as it is, a stored
one stays stored. Skeleton and new document come about in `StagedDocument`s below the data directory, not in the
temporary folder, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
only the XML of existing parts and never adds or removes parts or relationships. A new Office format brings only its
reader, its writer, and the element of each paragraph (`ElementOf`).
## Markdown files and other text
@@ -41,16 +41,17 @@ public interface IDocumentSegmentFormat
/// Reads the segments of a document, in the order of the document.
/// </summary>
/// <param name="path">The document.</param>
/// <param name="logger">Where the format reports what goes wrong on the way, e.g., a temporary file which cannot be removed.</param>
/// <param name="token">Cancels the reading.</param>
/// <returns>The segments, including those without letters.</returns>
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token);
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token);
/// <summary>
/// Writes a copy of a document with the new texts of its segments.
/// </summary>
/// <remarks>
/// The format reads the source again and writes nothing when the results do not cover one of its
/// segments. It writes only into the target, which the user chose, and leaves the source as it is.
/// segments, or when the source changes while the format writes. It writes only into the target, which the user chose, and leaves the source as it is.
/// </remarks>
/// <param name="sourcePath">The document the segments were read from.</param>
/// <param name="targetPath">The new document, which the user chose.</param>
@@ -1,3 +1,4 @@
using System.Collections.ObjectModel;
using System.IO.Compression;
using AIStudio.Tools.OpenXml;
@@ -13,10 +14,12 @@ namespace AIStudio.Tools.DocumentSegments;
/// </summary>
/// <remarks>
/// The source is read again, for reading only, and nothing is written when the results miss one of its paragraphs.
/// The writer changes the DOM of the paragraphs, and PackageRewrite writes a new document with the parts whose
/// paragraphs got new words, streaming every other entry through: the pictures and videos of a document never come
/// into memory. The new document comes about in a StagedDocument and goes into the file the user chose once it is
/// complete, see TargetFile. A paragraph whose text stays as it was keeps everything, its runs included.
/// Reading and writing both go through a PackageSkeleton, which holds only the XML of the source: the writer changes the
/// DOM of the paragraphs in the skeleton, and the skeleton writes a new document with the parts whose paragraphs got new
/// words, streaming the pictures and videos through from the source. They never come into memory, nor into the
/// temporary folder, where the SDK copies whatever it opens for reading. The new document comes about in a
/// StagedDocument and goes into the file the user chose once it is complete, see TargetFile. A paragraph whose text
/// stays as it was keeps everything, its runs included.
/// </remarks>
/// <typeparam name="TDocument">The kind of Office document, e.g., WordprocessingDocument.</typeparam>
/// <typeparam name="TParagraph">A paragraph as the reader of the format returns it, with all its writer needs.</typeparam>
@@ -45,23 +48,23 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// <inheritdoc />
/// <remarks>
/// The entries of XML and of relationships count with their unpacked size, which the directory of the archive
/// holds, so nothing is unpacked; pictures, videos, and other binary entries never come into memory.
/// The entries of XML and of relationships, which a PackageSkeleton keeps, count with their unpacked size, which the
/// directory of the archive holds, so nothing is unpacked; pictures, videos, and other binary entries never come into
/// memory.
/// </remarks>
public long TextSizeOf(string path)
{
using var file = TemplateFile.OpenRead(path);
using var archive = new ZipArchive(file, ZipArchiveMode.Read);
return archive.Entries
.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
.Sum(entry => entry.Length);
return archive.Entries.Where(PackageSkeleton.HoldsXml).Sum(entry => entry.Length);
}
/// <inheritdoc />
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
{
this.RefuseTooLargeText(path);
using var file = TemplateFile.OpenRead(path);
using var skeleton = PackageSkeleton.Create(path, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
return this.ReadParagraphs(document).Select(this.SegmentOf).ToList();
}, token);
@@ -70,7 +73,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
public async Task<SegmentWriteResult> WriteAsync(string sourcePath, string targetPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
using var stagedDocument = StagedDocument.Create(this.FileExtension, logger);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, token), token);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, logger, token), token);
if (result.Outcome is SegmentWriteOutcome.WRITTEN)
await stagedDocument.WriteIntoAsync(targetPath, token);
@@ -80,7 +83,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
#endregion
/// <summary>
/// The extension of the documents, with its dot, e.g., ".docx", for the new document in the StagedDocument.
/// The extension of the documents, with its dot, e.g., ".docx", for the skeleton and the new document in the staging folder.
/// </summary>
protected abstract string FileExtension { get; }
@@ -122,13 +125,14 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// Writes the new words into the DOM of the source read again, and the new document into the given file.
/// </summary>
/// <remarks>
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which
/// PackageRewrite does instead.
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which the
/// skeleton does instead.
/// </remarks>
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, CancellationToken token)
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
this.RefuseTooLargeText(sourcePath);
using var file = TemplateFile.OpenRead(sourcePath);
using var skeleton = PackageSkeleton.Create(sourcePath, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
var paragraphs = this.ReadParagraphs(document);
if (paragraphs.Any(paragraph => !results.Covers(this.SegmentOf(paragraph))))
@@ -151,8 +155,10 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
simplifiedCount++;
}
PackageRewrite.Write(sourcePath, changedParts, documentPath, token);
return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount);
// False when the source changed since its skeleton was written, e.g., because Word saved it meanwhile:
return skeleton.TryWriteDocument(changedParts, ReadOnlyDictionary<string, string>.Empty, documentPath, token)
? new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount)
: SegmentWriteResult.SOURCE_CHANGED;
}
/// <summary>
@@ -11,7 +11,8 @@ public enum SegmentWriteOutcome
WRITTEN,
/// <summary>
/// The source holds segments the results do not know, i.e., it changed since it was read, so nothing is written.
/// The source changed since it was read, e.g., it holds segments the results do not know, or it changed while the
/// format wrote, so nothing is written.
/// </summary>
SOURCE_CHANGED,
}
@@ -33,7 +33,7 @@ public abstract class TextSegmentFormat : IDocumentSegmentFormat
public long TextSizeOf(string path) => new FileInfo(path).Length;
/// <inheritdoc />
public async Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token)
public async Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token)
{
var file = await this.ReadFileAsync(path, token);
return this.ReadSegments(file.Text).OrderBy(segment => segment.Start).Select(segment => segment.Segment).ToList();