Edit One Run, Leave the Other 99% Untouched
go-pptx Tech Blog · Part 2: Byte-level Fidelity — xmlstore and the SpanPatch Engine
Series: go-pptx Tech Blog (10 parts)
Baseline: v2.4.4
Keywords: XML scanner, namespace scope, node index, SpanPatch, B1 invariant
1. The Problem: Why "Read Out and Write Back" Damages Documents
The edit path of most PPTX libraries is:
Parse XML → modify the object tree → re-serialize the entire Part → write back to ZIP This path is fine for "generating from scratch," but dangerous for "processing existing documents":
- Unknown extensions are dropped: OOXML allows vendor extensions (
p14:,p15:,mc:AlternateContent, WPS private nodes). The object tree doesn't recognize them, and they easily vanish on re-serialization. - Lexical details are rewritten: attribute order, namespace prefixes, self-closing form, whitespace, and entity spelling may all change. Semantically the same, but byte-wise different, affecting downstream signatures, comparisons, and audits.
- Unrelated regions are dragged in: changing only one Run re-lays-out the entire page's XML, expanding the difference from a few bytes to the whole page.
- Concurrent modifications are hard to detect: you read first, then construct a new document, then write everything back; you don't know if the source document was modified in between.
go-pptx's choice is: treat raw bytes as the invariant and patch only the target region. The foundation of this mechanism is internal/xmlstore.
2. The Four Components of xmlstore
internal/xmlstore is not a general-purpose XML editor, but "a minimal XML storage layer serving fidelity editing." It does four things:
2.1 Namespace-aware Lexical Scanner
The scanner outputs tokens with raw byte spans, covering:
- Start tags / end tags / text / comments / CDATA / PI / DOCTYPE;
- Attribute names, attribute values, in-quote ranges;
- Namespace declarations
xmlns/xmlns:p; - Close validation, mismatch detection;
- Direct refusal of non-UTF-8 (
ErrEncoding), because a reliable byte mapping cannot be established.
Key point: do not use regex to locate XML, and do not Unmarshal the entire Part into a struct then Marshal it. For unknown elements, build nodes as usual and preserve the raw bytes.
2.2 Namespace Scope
Each element node holds an immutable NamespaceScope, which stores the xmlns bindings it declares and chains to the parent scope:
type NamespaceScope struct { parent *NamespaceScope decls map[string]string // "" means the default namespace } When identifying elements, use URI + local name, never guess semantics from the prefix. Because prefixes can be bound arbitrarily, only the URI is a stable identity. Upper layers can ask:
- What URI does this prefix resolve to in the current scope?
- Does the target URI already have a usable prefix at the insertion point?
- What is the context of
mc:Ignorable/mc:AlternateContent?
2.3 Node Index Tree
XMLDocument builds every element into a NodeRecord:
type NodeRecord struct { ID NodeID Parent NodeID QName QName Namespace string Source ByteRange // the whole element [Start, End) OpenEnd int // end of the open tag, start of content CloseStart int // offset of the closing tag '<'; -1 for self-closing Attrs []AttributeRecord Children []NodeID scope *NamespaceScope } These spans let upper layers answer precisely:
- In which interval of the raw bytes is the
<a:t>content of this Run? - Where does the complete
<a:p>of this paragraph start and end? - When deleting this shape, which byte segment should be deleted?
- During text replacement, which bytes must be preserved?
Non-element content (text, comments, CDATA, PI, DOCTYPE) does not get its own node, but the raw bytes are always fully preserved in XMLDocument.original; layers needing text location (such as textmap) work on spans.
2.4 Controlled Structure Insertion
Besides replacement, xmlstore also provides InsertBefore / InsertAfter / AppendChild. The constraints are clear:
- The inserted fragment must be a well-formed single-root fragment;
- Prefixes explicitly used in the fragment must be self-contained, or resolvable in the scope at the insertion point;
- Otherwise return
ErrFragmentNamespaceinstead of producing a package that "might not open."
This constraint looks conservative, but it actually protects client compatibility: PowerPoint has very low tolerance for unbound prefixes, multiple root nodes, and incorrect nesting.
3. SpanPatch: Atomic Application of One Change Set
3.1 Data Structure
type SpanPatch struct { Start int // raw-byte half-open interval [Start, End) End int Replacement []byte Expect []byte // optional anchor: require data[Start:End] == Expect before applying Desc string // for diagnostics only } Expect is "baseline drift protection": after a patch is constructed and before it is applied, if the target interval has already been changed by another path, the anchor check fails and returns ErrPatchAnchor, rather than overwriting with wrong content.
3.2 Application Contract
ApplyPatches guarantees four things:
- An empty set returns the original data (no copy);
- Validate everything first, then apply all at once: out-of-range,
Start > End, overlapping intervals, or anchor mismatch—any failure fails the whole thing, with no partial application; - Rebuild into a new buffer in ascending Start order: the new buffer is immune to offset drift, equivalent to "in-place replacement in descending order," but the caller does not need to handle offsets themselves;
- Replacement content must be explicitly escaped by the caller:
EscapeText/EscapeAttrValuedo not happen implicitly insideApplyPatches, avoiding double-escaping semantic ambiguity.
Illustration:
patches := []xmlstore.SpanPatch{ {Start: 120, End: 135, Replacement: []byte("Q4"), Expect: []byte("Q3 revenue")}, {Start: 400, End: 412, Replacement: []byte("new note")}, } out, err := xmlstore.ApplyPatches(original, patches) if err != nil { // ErrPatchOverlap / ErrPatchRange / ErrPatchAnchor / ErrEscapeInvalidRune } 3.3 Escaping Is Explicit, Invalid Characters Are Refused
EscapeText handles & < >; EscapeAttrValue additionally handles quotes. Both check the character range allowed by XML 1.0:
- Allowed:
#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] - Refused: most C0 control characters,
U+FFFE,U+FFFF, invalid UTF-8
Invalid characters return ErrEscapeInvalidRune, and the caller decides whether to sanitize or refuse. No silent replacement—otherwise "lexical fidelity" would be empty talk.
4. Why "Change One Run, Leave the Rest of the Bytes Unchanged" Is Possible
Take a simplified XML snippet as an example:
<a:p> <a:r> <a:rPr lang="zh-CN" sz="1800"/> <a:t>Q3 revenue</a:t> </a:r> <a:r> <a:rPr lang="zh-CN" sz="1800" b="1"/> <a:t>up 12% year over year</a:t> </a:r> </a:p> To change "Q3" to "Q4":
- The scanner builds the node tree and locates the first
<a:t>; - The text layer computes the rune interval and confirms the match does not cross a grapheme-cluster boundary;
- It constructs a
SpanPatchcovering only the two bytes ofQ3; -
ApplyPatchesvalidates and rebuilds, and only these two bytes change; - All remaining tags, attribute order, whitespace, and the second Run's bytes are preserved as-is.
If the target string spans Runs—say "Q3 revenue" is split across two Runs—the text layer plans multiple patches: delete/replace the target portion in the first Run, clear the target portion in the middle Run, and replace the target portion in the last Run. Each patch still covers only the necessary interval, and the formatting and bytes of other Runs are not rewritten.
This is the underlying logic of "cross-Run fidelity replacement," which Part 4 expands on.
5. Unknown Extensions and Namespace Safety
A common "pitfall" in OOXML:
<p:sp> <p:nvSpPr>...</p:nvSpPr> <p:spPr> <a:xfrm>...</a:xfrm> <a:prstGeom prst="rect">...</a:prstGeom> <p14:shadowObscured xmlns:p14="..."/> </p:spPr> <p:txBody>...</p:txBody> </p:sp> p14:shadowObscured is an unknown extension. xmlstore handles it by:
- Building a node as usual, recording the URI/local name and byte span;
- The upper layer does not interpret it, but does not delete it either;
- When editing other child elements of
p:spPr, the patch covers only the target child element, and thep14:node's raw bytes are preserved; - If a new element must be created, the insertion point checks whether the prefix is resolvable in the current scope, avoiding unbound prefixes.
This is safer than "dropping unknown nodes" or "forcing schema-ization." The cost: xmlstore does not provide "full schema validation"; it only guarantees structurally parseable + byte-locatable + namespace-resolvable. Completeness validation is handled by Validate and higher-layer business rules.
6. The B1 Invariant: Verifiable, Not a Slogan
In the project, "unmodified Part bytes are identical" is called B1. It is constrained by at least three pieces of evidence:
- Saving an empty change set:
BuildSavePlanproduces a fullCopyOriginalfor an emptyChangeSet, and the decompressed content matches the input bytes (TestSavePlanUnchangedIsB1). - Single-Run replacement: on the real sample
ext-0024(WPS, with animations and unknown extensions), replacing only one Run converges the difference span to 1 byte. - Public golden sample replay: the "before-change/after-change" golden samples of
s001-text/s002-table/s003-image/s004-audioare replayed in CI with byte-level comparison.
The meaning of B1 is not "pursuing zero difference," but limiting the difference to the declared scope: wherever you changed something, the difference appears only there; wherever you did not change anything, the tool has no right to touch it.
7. Design Trade-offs and Boundaries
| Trade-off | Choice | Reason |
|---|---|---|
| XML parsing method | Self-developed lexical scan + node index | Preserve byte spans and namespaces; avoid encoding/xml synchronization deviations on certain self-closing combinations |
| Write method | SpanPatch interval replacement | Untouched regions preserve bytes; difference scope is controllable |
| Unknown nodes | Build tree as-is, preserve as-is | Do not drop vendor extensions; do not guess semantics |
| schema usage | Read-only projection (internal/ooxml/schema) | Generated types do not enter the write path, avoiding re-serialization damage to fidelity |
| Invalid characters | Explicit refusal | No silent sanitization, avoiding "looks successful but semantics changed" |
| Nesting depth | Default 256-level budget | Prevent deep recursion from untrusted input |
Limitations to be clear about:
- xmlstore is not a general-purpose XML DOM and does not provide XPath, XSLT, or full schema validation.
- It assumes the input is UTF-8; non-UTF-8 is refused directly rather than transcoded and then claimed to be faithful.
- It guarantees "structure locatable + patch applicable," not "business semantics definitely correct"; business validation lives at a higher layer.
- The write path does not use generated schema types; generated types are only used for read-only projection (a hard constraint of ADR-030).
8. Summary
xmlstore solves the lowest-level and most easily overlooked problem: how to precisely change a small piece of XML without damaging the document.
Its answer consists of four parts:
- Namespace-aware scanning that preserves raw byte spans;
- A node index tree that supports locating by element;
- The SpanPatch engine that validates everything first, then applies all at once;
- Controlled insertion and explicit escaping that refuse to produce invalid XML.
The next post moves up a layer: how these patches enter the OPC package, how saving is planned together with relationships/content types, and how transactions and atomic persistence are guaranteed.
Series navigation: ← Part 1: Overview · Part 3: OPC Container, Transactional Editing, and Atomic Save →