Saving a PPTX Should Feel Like a Database Transaction
go-pptx Tech Blog · Part 3: OPC Container, Transactional Editing, and Atomic Save
Series: go-pptx Tech Blog (10 parts)
Baseline: v2.4.4
Keywords: OPC, ZIP lazy indexing, resource budget, ChangeSet, SavePlan, revision, atomic flush to disk
1. A PPTX is Essentially an OPC Package
A PPTX file is not "an XML file" but a collection of Parts inside a ZIP container (OPC, Open Packaging Conventions):
presentation.pptx
├── [Content_Types].xml # content type for each extension/Part
├── _rels/.rels # package-level relationships: officeDocument → ppt/presentation.xml
├── ppt/
│ ├── presentation.xml # slide list
│ ├── _rels/presentation.xml.rels
│ ├── slides/slide1.xml # spTree for each slide
│ ├── slideLayouts/...
│ ├── slideMasters/...
│ ├── theme/theme1.xml
│ ├── media/image1.png
│ ├── charts/chart1.xml
│ └── embeddings/...
└── docProps/
├── core.xml
├── app.xml
└── custom.xml
A single "change a word" operation actually has to handle:
- byte patches to the target XML Part;
- possibly newly added media Parts (images/audio/video);
- content types for new Parts (
[Content_Types].xml); - newly added/modified relationships (
_rels/*.rels); - deleting relationships when a Part is removed;
- finally producing a new ZIP.
If these steps are not atomic, you end up with broken packages such as "a relationship points to a nonexistent Part", "a content type is missing", or "duplicate ZIP entries". go-pptx solves this with a three-layer mechanism: lazy indexing + resource budget, ChangeSet/SavePlan, and transactions + atomic flush to disk.
2. Open: Lazy Indexing and a Budget for Untrusted Input
2.1 Only the Central Directory and a Lightweight Index
When internal/opc opens a file, it does not immediately decompress every Part:
- it parses the ZIP central directory and builds an entry index;
- it parses
[Content_Types].xmland the relationship streams; - media bytes are read lazily on demand;
- an XML Part is parsed into
xmlstore.XMLDocumentonly when accessed, and cached by revision.
This matters for large files: a 100-slide presentation with 20 large images should not load every image into memory on open.
2.2 Budget: Setting Limits on Untrusted Input
type Budget struct {
MaxEntries int // total number of ZIP entries
MaxXMLBytes int64 // decompressed limit for a single XML Part (default 32 MiB)
MaxMediaBytes int64 // limit for a single media Part (default 512 MiB)
MaxTotalBytes int64 // limit on declared size and actual cumulative bytes read (default 1 GiB)
}
Default values (DefaultBudget()):
| Field | Default |
|---|---|
MaxEntries |
10,000 |
MaxXMLBytes |
32 MiB |
MaxMediaBytes |
512 MiB |
MaxTotalBytes |
1 GiB |
A few design details:
- 0 does not mean unlimited: unconfigured fields fall back to defaults; to tighten, explicitly give a positive value.
-
Actual bytes read are also constrained: since v2.4.4,
MaxTotalBytesconstrains both the ZIP declared size and the actual cumulative decompressed bytes read; exceeding it returnsErrLimitExceededrather than waiting for an OOM. - Depth limits are not in Budget: XML nesting depth is handled by the parsing side (xmlstore defaults to 256 levels), avoiding a fake knob that "is set but has no effect".
-
Malicious packages do not panic: the three entry points
Open/OpenReader/Newall return explicit errors.
3. Editing: ChangeSet and SavePlan
3.1 ChangeSet: The Set of Changes for One Save
type ChangeSet struct {
Patched map[PartName][]byte
Added map[PartName]AddedPart
Deleted map[PartName]bool
}
It only describes "what the output should become relative to the current package"; it does not care how the ZIP is written. Key rules:
- a Part in
Patchedmust already exist; - a Part in
Addedmust not exist, and must have a determinable content type; - a Part in
Deletedmust already exist; - the same Part cannot appear in mutually exclusive sets at the same time;
- deleting a Part automatically removes its relationship stream as well (relationships are meaningless once detached from their source Part).
3.2 SavePlan: A Determined List of Output Entries
BuildSavePlan turns a ChangeSet into []PlannedEntry, where each entry has one of four actions:
| Action | Meaning | Byte source |
|---|---|---|
CopyOriginal |
Unmodified | Decompressed content of the original ZIP entry, copied as-is (B1) |
EmitPatched |
Modified | New bytes provided by the change set |
EmitNew |
Newly created | New bytes provided by the change set |
Omit |
Deleted | Does not appear in the output |
Output entries are sorted by Part name, guaranteeing determinism. The package structure generated from the same change set is stable, which helps comparison and reproduction.
A SavePlan also carries two kinds of diagnostics:
- Blocking errors: invalid Part names, patching/deleting a nonexistent Part, creating an already-existing Part, undeterminable content type;
-
Non-blocking diagnostics: for example, dangling relationships, recorded in
Diagnostics, with the caller deciding whether to accept them.
3.3 Content Types and Relationships Generated from a Single Source
A common source of broken packages is "a Part was added but its content type was forgotten". SavePlan's strategy is:
- a newly added Part must provide a
ContentType, or its extension must already be covered by aDefault; - otherwise the plan fails outright (
ErrPlanInvalid); producing an untyped Part is not allowed; - relationship streams are generated from the same source as the change set, and relationships are handled together when a Part is deleted.
This is not "one extra step" but rather blocking "broken packages" before the save happens.
4. Transactions: SinglePartPatch and MultiPartPlan
4.1 Single-Part Editing
plan := editplan.NewSinglePartPatch(partName, newBytes)
err := plan.Apply(store) // StagePatch + Commit
Suitable for operations that change only one XML Part, such as text replacement or shape property modification.
4.2 Multi-Part Editing
plan := editplan.NewMultiPartPlan(
editplan.Patch(slidePart, newSlideXML),
editplan.Add(mediaPart, imageBytes, "image/png"),
editplan.Patch(contentTypesPart, newCT),
editplan.Patch(relsPart, newRels),
)
err := applyMultiPartPlan(pres, plan)
A multi-Part operation must be a single transaction:
- if any
Stage*fails, the whole plan fails; - on failure,
pendingis restored, leaving no half-committed state; - on success, a single
Commithappens, and revision is incremented only once.
This solves the intermediate-state problem of "the image was added halfway, the relationship was added, but the content type was not".
4.3 revision: Detecting Concurrent Modification
Presentation maintains a monotonically increasing revision:
- +1 on every successful commit;
- parse caches and media hash caches are invalidated wholesale with the revision;
- the save plan is based on a snapshot of a certain revision;
- if the document is modified again after the plan is generated,
p.rev != revand the save returnsErrConcurrentModification.
This makes a race between "read snapshot → build plan → save" detectable, instead of silently saving a mixed state.
5. Saving: Atomic Flush to Disk, Not "Delete Old and Write New"
The Save flow:
target check
→ temporary file in the same directory
→ write ZIP
→ (optional) fsync the file
→ Close
→ output validation (ZIP opens, entry set matches the plan)
→ atomic replace of the target
→ (optional) fsync the directory
5.1 Overwrite Denied by Default
- target exists and overwrite is not explicitly allowed →
ErrOutputExists; - overwriting must be explicitly enabled with
WithSaveOverwrite(true); - overwriting still uses atomic replace and does not degrade into "delete the old file first, then write the new file".
5.2 Saving In Place Over the Source File Is Rejected
The current version does not support in-place saving:
if p.sameSourceEntity(path) {
return ErrInvalidArgument // please choose a new output path
}
The reason is that the source file is still being read lazily; safe in-place replacement would require handling source handle lifetimes, temporary packages, and rollback semantics. This limitation is an explicit rejection, not "silently writing something broken".
5.3 Durability: Durability Levels
| Level | Behavior |
|---|---|
DurabilityDefault |
Guarantees error handling and atomic visibility, but does not promise power-loss durability |
DurabilityFull |
Additionally performs file fsync and (on supported platforms) directory fsync |
5.4 Failure Recovery
- any failure before commit: the temporary file is deleted, and the old target remains unchanged;
- cleanup failure: the error is attached with
errors.Joinso the primary error is not masked; - atomic replace unavailable: returns
ErrAtomicReplaceUnavailable, and the old target is preserved; - output validation failure: the target is not replaced, avoiding a broken package.
This set of semantics is much like a database transaction: you either see the old version or the complete new version, never half a package.
6. Deterministic Saving and raw Pass-Through
6.1 Deterministic Output
SaveOptions.Deterministic can pin metadata such as timestamps, so that the same input produces the same output. This is useful for CI golden files, content addressing, and caching.
6.2 raw Pass-Through
Unmodified media Parts can use raw pass-through: copy the compressed bytes directly from the original ZIP instead of decompressing and recompressing. Since v2.4.4, entries with a data descriptor (Flags bit3) are supported: CRC/size is taken from the central directory, and the actual compressed byte count is re-checked after copying.
Exclusions:
- encrypted frames;
- exotic compression methods;
- XML / rels (these need to be readable and modifiable).
If the actual compressed byte count does not match after copying, the entire save fails rather than silently producing a broken package.
6.3 Save Statistics
SaveReport provides the write distribution:
type SaveReport struct {
RawParts int // raw pass-through
StreamedParts int // streamed copy
PatchedParts int // patch write
NewParts int // newly added
// ...
}
This lets callers observe "how much this save actually changed", and also helps with performance tuning.
7. A Complete Edit-Save Example
p, err := pptx.Open("template.pptx",
pptx.WithBudget(pptx.Budget{
MaxEntries: 5000,
MaxTotalBytes: 256 << 20,
}),
)
if err != nil {
return err
}
defer p.Close()
slides, _ := p.Slides()
shapes, _ := slides[0].Shapes()
tf, _ := shapes[0].TextFrame()
if err := tf.ReplaceText("{{title}}", "Q4 Business Review"); err != nil {
return err
}
report, err := p.Save(context.Background(), "out.pptx",
pptx.WithSaveOverwrite(true),
pptx.WithSaveDurability(pptx.DurabilityFull),
)
if err != nil {
// ErrOutputExists / ErrConcurrentModification / ErrLimitExceeded ...
return err
}
fmt.Printf("revision=%d patched=%d new=%d raw=%d\n",
report.Revision, report.PatchedParts, report.NewParts, report.RawParts)
What actually happens behind this code:
- on open, only the index is built; not all media is read;
-
ReplaceTextgenerates a minimal SpanPatch via xmlstore; - one transaction is committed, revision +1;
-
Savebuilds a SavePlan based on the current revision; - unmodified Parts go through
CopyOriginal, modified Parts go throughEmitPatched; - the temporary file is written, validated, and atomically replaced.
8. Boundaries and Trade-offs
| Item | Current choice | Reason |
|---|---|---|
| In-place save | Rejected | Source file is read lazily; safe replacement and rollback are not yet fully closed |
| Overwrite by default | Rejected | Prevents accidental overwrite; explicit WithSaveOverwrite
|
| Large media | Lazy read + raw pass-through | Avoids full decompression; unmodified media is not decompressed |
| Resource limits | Configurable via Budget | Server-side processing of untrusted files must be controllable |
| Save failure | Old target preserved | No half-finished product |
| Missing content type | Fails at plan time | Producing an untyped Part is not allowed |
| Dangling relationships | Diagnostic (non-blocking) | Some real samples have historical leftovers; report first, then decide |
9. Summary
The core of the OPC layer is not "being able to read and write ZIP" but turning package-level consistency into verifiable constraints:
- open: lazy indexing + budget, so malicious input cannot bring down the service;
- edit: ChangeSet describes intent, SavePlan generates deterministic output;
- transaction: single/multi-Part plans, zero residue on failure;
- concurrency: revision snapshots, detecting modifications during planning;
- save: temporary file + validation + atomic replace, so the old target is never harmed.
The next part moves into the object model layer: how handles become stale, how cross-Run text is replaced faithfully, and why shape IDs must be monotonically increasing.
Series navigation: ← Part 2: Byte-Level Fidelity · Part 4: Object Model, Cross-Run Text, and Handle Lifecycle →
Top comments (0)