This is an automated email from the ASF dual-hosted git repository.

jimjag pushed a commit to branch odf-devel
in repository https://gitbox.apache.org/repos/asf/openoffice.git

commit c8cf4e5c049c7961c323ab623e21d22e00877acf
Author: Jim Jagielski <[email protected]>
AuthorDate: Mon Oct 26 13:15:10 2026 -0400

    test/odf-validate: add the corpus regression gate
---
 test/odf-validate/README.md         |  35 ++++
 test/odf-validate/cmp7.py           | 228 ++++++++++++++++++++
 test/odf-validate/diff7.py          |  28 +++
 test/odf-validate/drive.sh          |   4 +-
 test/odf-validate/dump7.py          | 260 +++++++++++++++++++++++
 test/odf-validate/gate-fixtures.tsv |  82 ++++++++
 test/odf-validate/gate-volatile.tsv |  14 ++
 test/odf-validate/gate.py           | 404 ++++++++++++++++++++++++++++++++++++
 test/odf-validate/selftest.py       |  28 +++
 9 files changed, 1081 insertions(+), 2 deletions(-)

diff --git a/test/odf-validate/README.md b/test/odf-validate/README.md
index 2c6e06161d..525670510a 100644
--- a/test/odf-validate/README.md
+++ b/test/odf-validate/README.md
@@ -101,6 +101,41 @@ The steps:
   checks `xml:id` syntax and uniqueness per stream (ODF 1.2 Part 1 ยง2.2.1
   D.1, D.2). `jing -i` does not check ID uniqueness.
 
+## The regression gate
+
+    python3 -I gate.py <tag> --prev runs/gate-<earlier tag>      # everything
+    python3 -I gate.py <tag> --build xmloff,sw --prev ...        # rebuild 
first
+    python3 -I gate.py smoke --limit 8 --prev ... --stages 
corpus,validate,dump,diff
+
+`gate.py` runs the stages below in `runs/gate-<tag>/`, records `results.json`,
+skips stages already done (`--force` reruns) and exits 0 only if everything
+that ran passed.
+
+| stage | does | passes if |
+|---|---|---|
+| `build` | `build.pl` and `deliver.pl` for the `--build` modules (environment 
script: `ODFV_BUILD_ENV`) | exit codes 0 |
+| `refresh` | copies `--libs` from the solver into `app/` (`refresh-app.sh`) | 
copies identical |
+| `corpus` | saves the job list in `ext` and `strict` mode | no crash, every 
job accounted for, OK/FAIL counts equal `--prev` |
+| `validate` | `validate.py`, `report.py` and the four checkers per mode | 
kinds not worse than `baseline/<mode>.kinds.json` or than `--prev` (checked 
both ways) |
+| `dump` | reloads every saved package with `dump7.py` | no office failure; 
hangs and crashes are listed |
+| `diff` | `diff7.py` on the dumps and `cmp7.py` on the packages against 
`--prev` | every difference is a document in `gate-volatile.tsv` |
+| `fixtures` | `gate-fixtures.tsv`: saves in `v00 v10 v11 ext strict`, runs 
the reload checks, validates | saved, checked, and unchanged against `--prev` |
+
+- Inputs are frozen: without `--jobs` the list of `--prev` is reused (outputs
+  are rewritten), so the same documents are saved when files under `main/`
+  change. A later run's `--prev` may be any earlier gate directory or a
+  directory with the same layout (`<mode>/out`, `<mode>/dump`).
+- The dump stage kills the office only when the dump makes no progress for
+  `--stall` seconds (default 300), then writes a `HANG` marker for that
+  document alone. A long batch that keeps progressing is never killed.
+- `gate-volatile.tsv` names the documents whose dumps differ between runs
+  without an export change (volatile Calc formulas, redline timestamps, the
+  `0238` loader order, the intermittent Basic library loss of `0048`). A new
+  entry needs a reason.
+- The first fixtures run has nothing to compare with: its mismatch pattern is
+  only recorded. By design, strict, ODF 1.0 and ODF 1.1 mode fail the 14
+  reload rows that need gradient or transparency fills.
+
 ## Checking a change
 
     python3 -I compare.py baseline/strict.kinds.json runs/new/strict.kinds.json
diff --git a/test/odf-validate/cmp7.py b/test/odf-validate/cmp7.py
new file mode 100644
index 0000000000..bc0d16a843
--- /dev/null
+++ b/test/odf-validate/cmp7.py
@@ -0,0 +1,228 @@
+# usage: cmp7.py <old_run> <new_run> <mode:strict|ext> <out.json> [-v]
+# Masked structural comparison of two corpus output sets (<run>/out/*).
+# Layer 1: environment/noise masks only (RAND values, dates, ids, printer 
config, relative-href depth, auto-style numbering).
+# Layer 2: additionally applies the INTENDED edits of the fixes under test to 
both sides, so the remaining diff = unexplained.
+# Counts, per package, how often each fix's marker is present on the old side 
and on the new side (exercise map input).
+import zipfile, sys, re, os, hashlib, difflib, json, collections
+import xml.etree.ElementTree as ET
+old, new, mode, outjson = sys.argv[1:5]
+verbose = "-v" in sys.argv
+NS = dict(style="urn:oasis:names:tc:opendocument:xmlns:style:1.0", 
office="urn:oasis:names:tc:opendocument:xmlns:office:1.0",
+          text="urn:oasis:names:tc:opendocument:xmlns:text:1.0", 
draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
+          table="urn:oasis:names:tc:opendocument:xmlns:table:1.0", 
form="urn:oasis:names:tc:opendocument:xmlns:form:1.0",
+          chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0", 
meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
+          fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0", 
svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
+          xlink="http://www.w3.org/1999/xlink";, 
config="urn:oasis:names:tc:opendocument:xmlns:config:1.0",
+          dc="http://purl.org/dc/elements/1.1/";)
+def q(p, l): return "{%s}%s" % (NS[p], l)
+STYLE_NAME = q("style", "name")
+
+def mask_text(d):
+    d = re.sub(rb'Pictures/[0-9A-F]{24,40}', b'Pictures/H', d)
+    d = re.sub(rb'text:change-id="ct[0-9]+"', b'text:change-id="CT"', d)
+    d = re.sub(rb'<text:(time|date)\b([^>]*)>[^<]*</text:\1>', 
rb'<text:\1\2>T</text:\1>', d)
+    d = re.sub(rb'office:value="[-0-9.eE+]+"', b'office:value="#"', d)
+    d = re.sub(rb'<text:p>[0-9.]+</text:p>', b'<text:p>#</text:p>', d)
+    d = 
re.sub(rb'(text:time-value|text:date-value|text:time|text:date)="[^"]*"', 
rb'\1="T"', d)
+    d = re.sub(rb'<meta:(creation-date|editing-duration)>[^<]*</meta:\1>', 
rb'<meta:\1>T</meta:\1>', d)
+    d = re.sub(rb'<dc:date>[^<]*</dc:date>', b'<dc:date>T</dc:date>', d)
+    d = re.sub(rb'(xml:id|text:id|form:id|text:continue-list)="[^"]*"', 
rb'\1="ID"', d)
+    # environment: default printer of the host, relative links depend on the 
output directory depth
+    d = re.sub(rb'(<config:config-item 
config:name="(?:PrinterName|PrinterSetup)"[^>]*>)[^<]*', rb'\1PRN', d)
+    d = re.sub(rb'(xlink:href|form:image-data)="(?:\.\./)+', rb'\1="../*/', d)
+    # host calendar date moved from 2026-10-22 (baseline run) to 2026-10-23 
(TODAY()-style cells)
+    d = re.sub(rb'2026-10-2[23]', b'DATE', d)
+    d = re.sub(rb'10/2[23]/26', b'DATE', d)
+    # fields.odt: weekday name length (Donnerstag vs Freitag) changes the 
document character count
+    d = re.sub(rb'(character-count[^>]*?>|meta:character-count=")\d+', 
rb'\1N', d)
+    return d
+def isref(k):
+    return k.endswith("style-name") or k.endswith("page-layout-name") or 
k.endswith("master-page-name") or k.endswith("class-names") or 
k.endswith("style-names")
+def ser(e, m, defn=False, out=None):
+    out = [] if out is None else out
+    attrs = sorted((k, m.get(v, v) if isref(k) and not (defn and k == 
STYLE_NAME) else v) for k, v in e.attrib.items() if not (defn and k == 
STYLE_NAME))
+    out.append("<" + e.tag + " " + " ".join(f'{k}="{v}"' for k, v in attrs) + 
">" + (e.text or "").strip())
+    for c in e: ser(c, m, False, out); out.append((c.tail or "").strip())
+    out.append("</>")
+    return "".join(out)
+
+def canon(root, dedupe):
+    autos = [c for ac in root.iter(q("office", "automatic-styles")) for c in 
ac if STYLE_NAME in c.attrib]
+    m = {}
+    for _ in range(4):
+        nm = {}
+        for c in autos: nm[c.get(STYLE_NAME)] = "S" + hashlib.md5(ser(c, m, 
True).encode()).hexdigest()[:10]
+        if nm == m: break
+        m = nm
+    lines = []
+    def walk(e, depth):
+        if e.tag == q("office", "automatic-styles"):
+            lines.append("<automatic-styles>")
+            ss = sorted(ser(c, m, True) for c in e)
+            if dedupe: ss = sorted(set(ss))
+            for s in ss: lines.append("  " + s)
+            lines.append("</automatic-styles>")
+            return
+        attrs = sorted((k, m.get(v, v) if isref(k) else v) for k, v in 
e.attrib.items())
+        lines.append(" " * depth + "<" + e.tag + " " + " ".join(f'{k}="{v}"' 
for k, v in attrs) + ">" + ((e.text or "").strip()))
+        for c in e: walk(c, depth + 1)
+    walk(root, 0)
+    return lines
+
+def pct(v):
+    m = re.fullmatch(r'(-?[0-9.]+)%', v); return float(m.group(1)) if m else 
None
+def length_pos(v):
+    m = re.fullmatch(r'(-?[0-9.]+)([a-z%]*)', v); return float(m.group(1)) > 0 
if m else True
+
+def normalise(root, cnt, strict, is_old):
+    """Apply the intended edits of the fixes (both sides). cnt[key] counts how 
often an edit was needed on this side."""
+    parent = {c: p for p in root.iter() for c in p}
+    def bump(k): cnt[k] += 1
+    def drop_attr(e, name): del e.attrib[name]
+    for e in list(root.iter()):
+        t = e.tag; a = e.attrib
+        if t == q("draw", "connector") and q("svg", "viewBox") in a: 
drop_attr(e, q("svg", "viewBox")); bump("cc5a09edf8 viewBox")
+        if t in (q("text", "a"), q("text", "section-source"), q("meta", 
"auto-reload")):
+            k = {q("text", "a"): "4b1c1a1375 text:a xlink:type", q("text", 
"section-source"): "dd43dd10dc section-source xlink:type", q("meta", 
"auto-reload"): "60942d1a9c auto-reload xlink:type"}[t]
+            if q("xlink", "type") in a: drop_attr(e, q("xlink", "type")); 
bump(k)
+            elif q("xlink", "href") in a or t != q("text", "section-source"): 
bump(k + " MISSING")
+        if t in (q("office", "document-content"), q("office", 
"document-styles")) and q("office", "version") in a:
+            drop_attr(e, q("office", "version")); bump("c7615ea10d 
office:version present")
+        elif t in (q("office", "document-content"), q("office", 
"document-styles")): bump("c7615ea10d office:version MISSING")
+        if t == q("meta", "print-date"):
+            if not re.match(r'\d{4,}-\d\d-\d\dT', (e.text or "")): 
parent[e].remove(e); bump("150358e458 print-date bogus")
+        if t == q("form", "property") and q("office", "value") in a:
+            if a[q("office", "value")] == "": bump("e64781e76d form 
office:value empty")
+            a[q("office", "value")] = "#"
+        for atn in (q("draw", "opacity"), q("draw", "image-opacity")):
+            if atn in a:
+                p = pct(a[atn])
+                if p is not None and (p > 100 or p < 0): bump("d47ac291e9 
opacity out of range"); a[atn] = "%g%%" % max(0, min(100, p))
+        if q("fo", "font-size") in a and not length_pos(a[q("fo", 
"font-size")]): drop_attr(e, q("fo", "font-size")); bump("efbe32fc4d 
font-size<=0")
+        for hn in ("hyphenation-push-char-count", 
"hyphenation-remain-char-count"):
+            if q("fo", hn) in a and a[q("fo", hn)] == "0": drop_attr(e, 
q("fo", hn)); bump("fe667bb0b4 hyphenation 0")
+        if q("office", "boolean-value") in a and a[q("office", 
"boolean-value")] not in ("true", "false"):
+            del a[q("office", "boolean-value")]; a[q("office", "value-type")] 
= "float"; a[q("office", "value")] = "#"; bump("4250607123 boolean non-0/1")
+        if q("table", "number-columns-spanned") in a and a[q("table", 
"number-columns-spanned")] == "0": drop_attr(e, q("table", 
"number-columns-spanned")); bump("895d935e38 colspan 0")
+        if q("text", "anchor-page-number") in a and a[q("text", 
"anchor-page-number")] == "0": drop_attr(e, q("text", "anchor-page-number")); 
bump("b070ffe226 anchor-page 0")
+        if t == q("text", "note-ref") and a.get(q("text", "reference-format")) 
in ("category-and-value", "caption", "value"):
+            a[q("text", "reference-format")] = "text"; bump("9eca93128d 
note-ref format")
+        if t == q("table", "dde-link"):
+            tabs = [c for c in e if c.tag == q("table", "table")]
+            if not tabs: bump("f8ad6c41e5 dde-link without table")
+            else:
+                tb = tabs[0]
+                kids = [c.tag for c in tb]
+                if kids == [q("table", "table-columns"), q("table", 
"table-rows")] and len(list(tb.iter(q("table", "table-cell")))) == 1 and not 
tb.attrib.get(q("table", "name")) is None and False: pass
+                if kids == [q("table", "table-columns"), q("table", 
"table-rows")] and len(list(tb.iter(q("table", "table-cell")))) == 1 and not 
"".join(tb.itertext()).strip() and len(list(tb.iter())) == 6 and not 
any(x.attrib for x in tb.iter(q("table", "table-cell"))):
+                    e.remove(tb); bump("f8ad6c41e5 dde-link wrapper table"); 
+        if t == q("chart", "symbol-image") and q("xlink", "href") not in a: 
parent[e].remove(e); bump("d6bd426c78 empty symbol-image")
+        if t in (q("table", "table-columns"), q("table", "table-rows")) and 
len(e) == 0 and parent.get(e) is not None and parent[e].tag == q("table", 
"table") and root.tag.endswith("document-content"):
+            # chart internal data (empty wrappers)
+            parent[e].remove(e); bump("26a3e0ceb0 empty chart table wrapper")
+    if strict:
+        norm_strict(root, cnt, parent)
+
+PARA_FAM = {"paragraph", "text"}
+def norm_strict(root, cnt, parent):
+    chart_shapes_dropped = False
+    for e in list(root.iter()):
+        t = e.tag; a = e.attrib
+        if t == q("style", "style") and a.get(q("style", "family")) == 
"paragraph":
+            for c in list(e):
+                if c.tag == q("style", "graphic-properties") and 
any(k.startswith("{%s}fill" % NS["draw"]) or k == q("draw", "opacity") or 
k.startswith("{%s}fill-" % NS["draw"]) for k in c.attrib):
+                    e.remove(c); cnt["ef0a8aeea9 para draw:fill"] += 1
+        if t in (q("style", "page-layout-properties"), q("style", 
"header-footer-properties")):
+            for k in list(a):
+                if k.startswith("{%s}fill" % NS["draw"]) or k == q("draw", 
"opacity") or k.startswith("{%s}opacity" % NS["draw"]):
+                    del a[k]; cnt["e86e06dbff page/hf draw:fill"] += 1
+        if t == q("style", "header-footer-properties"):
+            for c in list(e):
+                if c.tag == q("style", "background-image"):
+                    if not c.attrib and len(c) == 0: e.remove(c); 
cnt["83b30299d0 hf background-image empty"] += 1
+                    else: e.remove(c); cnt["83b30299d0 hf background-image 
with content"] += 1
+        if q("style", "layout-grid-snap-to-characters") in a:
+            a[q("style", "layout-grid-snap-to")] = a.pop(q("style", 
"layout-grid-snap-to-characters")); cnt["be94c9a190 grid-snap rename"] += 1
+        if t == q("style", "table-row-properties") and q("style", 
"keep-together") in a: del a[q("style", "keep-together")]; cnt["58c72c10be row 
keep-together"] += 1
+        if t in (q("draw", "object"), q("draw", "object-ole")):
+            for c in list(e):
+                if c.tag == q("text", "p"):
+                    cnt["57b28c93a4 draw:object text:p " + ("with text" if 
"".join(c.itertext()).strip() else "empty")] += 1; e.remove(c)
+        if t == q("form", "combobox") and q("form", "xforms-list-source") in 
a: del a[q("form", "xforms-list-source")]; cnt["1028eb24a1 combobox 
xforms-list-source"] += 1
+        if t == q("chart", "chart"):
+            for c in list(e):
+                if c.tag.startswith("{%s}" % NS["draw"]): e.remove(c); 
cnt["edc67281bb chart additional shape " + c.tag.split("}")[1]] += 1; 
chart_shapes_dropped = True
+        if t.startswith("{%s}" % NS["style"]) and t.endswith("-properties") 
and q("text", "enable-numbering") in a:
+            del a[q("text", "enable-numbering")]; cnt["e9b28885e5 alien 
text:enable-numbering"] += 1
+        if t == q("text", "changed-region"):
+            for c in list(e):
+                if c.tag in (q("text", "insertion"),) and e.find(q("text", 
"insertion")) is not c: pass
+    # P3: successor change = an text:insertion/deletion nested in a 
changed-region that already carries a change; nested `office:change-info` with 
attribute form
+    for e in list(root.iter(q("office", "change-info"))):
+        if q("office", "chg-author") in e.attrib or q("office", 
"chg-date-time") in e.attrib:
+            p = parent.get(e)
+            if p is not None and p.tag in (q("text", "insertion"), q("text", 
"deletion"), q("text", "format-change")) and parent.get(p) is not None and 
len(p) == 1:
+                parent[p].remove(p); cnt["c8b13970b2 redline successor 
change-info"] += 1
+            elif p is not None: p.remove(e); cnt["c8b13970b2 redline successor 
change-info (other)"] += 1
+    # empty property elements left behind by dropped alien attributes
+    for e in list(root.iter()):
+        for c in list(e):
+            if c.tag.startswith("{%s}" % NS["style"]) and 
c.tag.endswith("-properties") and not c.attrib and len(c) == 0 and not (c.text 
or "").strip():
+                e.remove(c); cnt["empty style:*-properties dropped"] += 1
+    if chart_shapes_dropped:
+        for _ in range(3):
+            used = {v for e in root.iter() for k, v in e.attrib.items() if 
isref(k)}
+            for ac in root.iter(q("office", "automatic-styles")):
+                for st in list(ac):
+                    if st.get(STYLE_NAME) is not None and st.get(STYLE_NAME) 
not in used and st.tag == q("style", "style") and st.get(q("style", "family")) 
in ("graphic", "paragraph"):
+                        ac.remove(st); cnt["orphan auto style after chart 
shapes dropped"] += 1
+    # drop empty paragraph auto styles and the references to them (merge / 
omission effect of row 1)
+    empty = set()
+    for ac in root.iter(q("office", "automatic-styles")):
+        for s in list(ac):
+            if s.tag == q("style", "style") and len(s) == 0 and set(s.attrib) 
<= {STYLE_NAME, q("style", "family"), q("style", "parent-style-name")} and 
q("style", "parent-style-name") not in s.attrib and s.get(q("style", "family")) 
in ("paragraph", "text", "graphic", "presentation"):
+                empty.add(s.get(STYLE_NAME)); ac.remove(s)
+    if empty:
+        for e in root.iter():
+            for k in list(e.attrib):
+                if isref(k) and e.attrib[k] in empty and not (e.tag == 
q("style", "style")): del e.attrib[k]
+
+def load(path, name, strict, dedupe, cnt, is_old, raw):
+    z = zipfile.ZipFile(path); data = z.read(name)
+    d = mask_text(data)
+    try: root = ET.fromstring(d)
+    except ET.ParseError: return [d.decode("utf8", "replace")], 
[d.decode("utf8", "replace")]
+    raw_lines = canon(ET.fromstring(d), False)
+    if raw: return raw_lines, None
+    normalise(root, cnt, strict, is_old)
+    return raw_lines, canon(root, dedupe)
+
+strict = mode == "strict"
+res = {}
+tot = collections.Counter()
+for f in sorted(os.listdir(old + "/out")):
+    r = {"raw_diff_streams": [], "norm_diff_streams": [], "old": 
collections.Counter(), "new": collections.Counter()}
+    if not os.path.exists(new + "/out/" + f): res[f] = {"missing_in_new": 
True}; continue
+    pa, pb = old + "/out/" + f, new + "/out/" + f
+    za, zb = zipfile.ZipFile(pa), zipfile.ZipFile(pb)
+    nn = lambda z: sorted(re.sub(r'Pictures/[0-9A-F]{24,40}', 'Pictures/H', n) 
for n in z.namelist())
+    if nn(za) != nn(zb): r["names_diff"] = sorted(set(nn(za)) ^ set(nn(zb)))
+    for n in sorted(za.namelist()):
+        if n.endswith("/") or not n.endswith(".xml") or n not in 
zb.namelist(): continue
+        ca, cb = collections.Counter(), collections.Counter()
+        ra, xa = load(pa, n, strict, strict, ca, True, False)
+        rb, xb = load(pb, n, strict, strict, cb, False, False)
+        r["old"].update(ca); r["new"].update(cb)
+        if ra != rb: r["raw_diff_streams"].append(n)
+        if xa != xb:
+            r["norm_diff_streams"].append(n)
+            diffl = [l[:300] for l in difflib.unified_diff(xa, xb, 
lineterm="", n=0) if not l.startswith(("---", "+++", "@@"))]
+            r.setdefault("diff_lines", {})[n] = diffl[:40]
+            if verbose:
+                print("UNEXPLAINED", f, n)
+                for l in diffl[:20]: print("    ", l)
+    r["old"] = dict(r["old"]); r["new"] = dict(r["new"])
+    res[f] = r
+json.dump(res, open(outjson, "w"), indent=1)
+nr = sum(1 for v in res.values() if v.get("raw_diff_streams")); nn_ = sum(1 
for v in res.values() if v.get("norm_diff_streams") or v.get("names_diff") or 
v.get("missing_in_new"))
+print(f"packages {len(res)}; differing after env masks: {nr}; differing after 
intended-edit normalisation: {nn_}")
diff --git a/test/odf-validate/diff7.py b/test/odf-validate/diff7.py
new file mode 100644
index 0000000000..563a846eb1
--- /dev/null
+++ b/test/odf-validate/diff7.py
@@ -0,0 +1,28 @@
+# usage: diff7.py <old_dump_dir> <new_dump_dir> <out.json>
+# Flattens the per-document reload dumps and lists every differing path with 
old/new value.
+import sys, os, json, collections
+old, new, out = sys.argv[1:4]
+IGN = ("props.creation_date", "props.gen", "props.edit_cycles")   # none 
expected to differ; creation_date is kept from the input
+def flat(x, p=""):
+    if isinstance(x, dict):
+        for k in sorted(x): yield from flat(x[k], p + "." + k if p else k)
+    elif isinstance(x, list):
+        if len(x) > 40 and all(not isinstance(i, (dict, list)) for i in x): 
yield p, x
+        else:
+            for i, e in enumerate(x): yield from flat(e, f"{p}[{i}]")
+    else: yield p, x
+res = {}
+names = sorted(f for f in os.listdir(old) if f.endswith(".json"))
+for f in names:
+    a = json.load(open(os.path.join(old, f)))
+    b = json.load(open(os.path.join(new, f))) if 
os.path.exists(os.path.join(new, f)) else {"error": "MISSING"}
+    fa, fb = dict(flat(a)), dict(flat(b))
+    d = [(k, fa.get(k, "<absent>"), fb.get(k, "<absent>")) for k in 
sorted(set(fa) | set(fb)) if fa.get(k, "<absent>") != fb.get(k, "<absent>")]
+    res[f[:-5]] = {"type": a.get("type") or b.get("type") or ("error" if 
"error" in a else "?"), "errors": [a.get("error"), b.get("error"), 
a.get("body_error"), b.get("body_error")], "ndiff": len(d), "diffs": d, 
"nprops": len(fa)}
+json.dump(res, open(out, "w"), indent=0, default=str)
+c = collections.Counter(); ident = collections.Counter(); diff = 
collections.Counter()
+for k, v in res.items():
+    c[v["type"]] += 1
+    (diff if v["ndiff"] else ident)[v["type"]] += 1
+for t in sorted(c): print(f"{t:8s} docs={c[t]:3d} identical={ident[t]:3d} 
different={diff[t]:3d}")
+print("total", len(res), "identical", sum(ident.values()), "different", 
sum(diff.values()))
diff --git a/test/odf-validate/drive.sh b/test/odf-validate/drive.sh
index 02a277782a..1e0d3a5bc6 100755
--- a/test/odf-validate/drive.sh
+++ b/test/odf-validate/drive.sh
@@ -19,14 +19,14 @@
 #  under the License.
 #
 #**************************************************************
-# usage: drive.sh <ext|strict> <port> <jobs.tsv> <done.tsv>
+# usage: drive.sh <ext|strict|v00|v10|v11> <port> <jobs.tsv> <done.tsv>   
(DefaultVersion 3, 4, 0 UNKNOWN, 1 = ODF 1.0, 2 = ODF 1.1)
 # Converts jobs in batches of 20. Stops on the first soffice crash; kills and 
resumes on a hang.
 source ${0:A:h}/env.sh
 mode=$1; port=$2; jobs=$3; done_=$4; log=${done_:r}.log
 prof=$mode
 if [[ ! -e $D/runs/profile_$prof/user/registrymodifications.xcu ]]; then
   mkdir -p $D/runs/profile_$prof/user
-  v=3; [[ $mode == strict ]] && v=4
+  case $mode in v00) v=0;; v10) v=1;; v11) v=2;; ext) v=3;; strict) v=4;; *) 
echo "drive.sh: unknown mode $mode" >&2; exit 2;; esac
   cat > $D/runs/profile_$prof/user/registrymodifications.xcu <<XCU
 <?xml version="1.0" encoding="UTF-8"?>
 <oor:items xmlns:oor="http://openoffice.org/2001/registry"; 
xmlns:xs="http://www.w3.org/2001/XMLSchema"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";>
diff --git a/test/odf-validate/dump7.py b/test/odf-validate/dump7.py
new file mode 100644
index 0000000000..fcc3306e86
--- /dev/null
+++ b/test/odf-validate/dump7.py
@@ -0,0 +1,260 @@
+# usage: runpy.sh dump7.py <port> <outdir> <file>...
+# Loads each ODF package read-only over UNO and writes a JSON dump of a fixed 
property set (Task 7, Review Focus 2).
+import sys, os, json, hashlib, uno
+from unohelp import connect, desktop, load
+
+port, outdir, files = int(sys.argv[1]), sys.argv[2], sys.argv[3:]
+LIM = 400
+
+def v(x, depth=0):
+    if isinstance(x, uno.Enum): return x.value
+    if x is None or isinstance(x, (bool, int, float, str)): return x
+    if isinstance(x, (tuple, list)): return [v(i, depth + 1) for i in x][:200]
+    if hasattr(x, "typeName"):
+        if depth > 3: return "<deep>"
+        try: return {k: v(getattr(x, k), depth + 1) for k in dir(x) if not 
k.startswith("_") and k not in ("typeName", "value")}
+        except Exception: return "<struct>"
+    return "<obj>"
+def g(o, n):
+    try: return v(o.getPropertyValue(n))
+    except Exception: return "n/a"
+def gs(o, names): return [g(o, n) for n in names]
+def h(s): return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()[:16]
+def tryf(f, d="n/a"):
+    try: return f()
+    except Exception as e: return d if d != "ERR" else repr(e)[:80]
+def has(doc, s): return tryf(lambda: doc.supportsService(s), False)
+
+SHAPE_PROPS = ["FillStyle", "FillColor", "FillTransparence", 
"FillGradientName", "FillHatchName", "FillBitmapName", "LineStyle", 
"LineColor", "LineWidth", "CharHeight", "ParaAdjust"]
+def shape(s, depth=0):
+    d = {"t": tryf(lambda: s.ShapeType), "name": tryf(lambda: s.Name), "pos": 
v(tryf(lambda: s.Position)), "size": v(tryf(lambda: s.Size)),
+         "text": tryf(lambda: s.String[:80]), "p": gs(s, SHAPE_PROPS)}
+    t = d["t"] if isinstance(d["t"], str) else ""
+    if "Connector" in t:
+        d["conn"] = {"kind": g(s, "EdgeKind"), "start": g(s, "StartPosition"), 
"end": g(s, "EndPosition"), "bez": g(s, "PolyPolygonBezier")}
+    if "OLE2" in t:
+        d["ole"] = {"cls": g(s, "CLSID"), "internal": g(s, "IsInternal"), 
"model": embedded(tryf(lambda: s.Model, None))}
+    if "GraphicObject" in t: d["gr"] = gs(s, ["GraphicURL", 
"Transparency"])[1:]
+    if tryf(lambda: s.supportsService("com.sun.star.drawing.GroupShape"), 
False) and depth < 4:
+        d["kids"] = [shape(s.getByIndex(i), depth + 1) for i in 
range(min(s.Count, 100))]
+    return d
+def forms_of(page):
+    out = []
+    try: forms = page.Forms
+    except Exception: return out
+    def walk(c):
+        for i in range(min(c.Count, 300)):
+            e = c.getByIndex(i)
+            if tryf(lambda: 
e.supportsService("com.sun.star.form.FormComponents"), False) or tryf(lambda: 
e.supportsService("com.sun.star.form.component.Form"), False):
+                out.append(["FORM", tryf(lambda: e.Name)]); walk(e)
+            else:
+                names = tryf(lambda: [p.Name for p in 
e.getPropertySetInfo().getProperties()], [])
+                out.append([tryf(lambda: e.Name), tryf(lambda: 
e.ImplementationName), g(e, "ObjIDinMSO") if "ObjIDinMSO" in names else "-",
+                            tryf(lambda: e.getValueBinding() is not None, 
"-"), tryf(lambda: (e.getListEntrySource() is not None), "-"), len(names)])
+    walk(forms)
+    return out
+def chart_info(m):
+    if m is None: return None
+    try:
+        r = {"title": tryf(lambda: m.Title.String if m.HasMainTitle else ""), 
"diagram": tryf(lambda: m.Diagram.ServiceName if hasattr(m.Diagram, 
"ServiceName") else m.getDiagram().getDiagramType()),
+             "addshapes": tryf(lambda: [m.DrawPage.Count, 
sorted(m.DrawPage.getByIndex(i).ShapeType.split(".")[-1] for i in 
range(m.DrawPage.Count))]), "intdata": tryf(lambda: 
m.hasInternalDataProvider())}
+        return r
+    except Exception: return "n/a"
+def embedded(m, depth=0):
+    """Dump an embedded model: drawing and spreadsheet documents fully, charts 
by title/type/additional shapes."""
+    if m is None: return None
+    if depth > 1: return "<deep>"
+    try:
+        if has(m, "com.sun.star.drawing.DrawingDocument") or has(m, 
"com.sun.star.presentation.PresentationDocument"): return {"draw": draw(m)}
+        if has(m, "com.sun.star.sheet.SpreadsheetDocument"): return {"calc": 
calc(m)}
+        if has(m, "com.sun.star.chart2.ChartDocument") or has(m, 
"com.sun.star.chart.ChartDocument"): return chart_info(m)
+        return {"other": tryf(lambda: list(m.SupportedServiceNames)[:3])}
+    except Exception as e: return "ERR " + repr(e)[:80]
+def docprops(doc):
+    p = doc.DocumentProperties
+    ud = tryf(lambda: [[n, v(p.UserDefinedProperties.getPropertyValue(n))] for 
n in sorted(i.Name for i in 
p.UserDefinedProperties.getPropertySetInfo().getProperties())], [])
+    return {"title": p.Title, "subject": p.Subject, "author": p.Author, 
"keywords": list(p.Keywords), "desc": p.Description, "gen": p.Generator[:20] if 
p.Generator else "",
+            "print_date": v(p.PrintDate), "printed_by": p.PrintedBy, 
"creation_date": v(p.CreationDate), "template": p.TemplateName, "edit_cycles": 
p.EditingCycles,
+            "autoload": [p.AutoloadURL, p.AutoloadSecs], "defaulttarget": 
p.DefaultTarget, "userdef": ud}
+def basic(doc):
+    out = {}
+    for k in ("BasicLibraries", "DialogLibraries"):
+        out[k] = tryf(lambda: sorted(getattr(doc, k).ElementNames), "n/a")
+    return out
+
+def writer(doc):
+    o = {}
+    txt = doc.Text.String
+    o["text_hash"] = h(txt); o["chars"] = len(txt)
+    paras = []; ncell = 0
+    e = doc.Text.createEnumeration(); tbl = 0; port_hash = []
+    while e.hasMoreElements() and len(paras) < LIM:
+        p = e.nextElement()
+        if p.supportsService("com.sun.star.text.Paragraph"):
+            paras.append([len(p.String), g(p, "ParaStyleName"), g(p, 
"ParaBackColor"), g(p, "ParaBackTransparent"), g(p, "FillStyle"), g(p, 
"FillColor"), g(p, "FillTransparence"),
+                          g(p, "CharHeight"), g(p, "ParaAdjust"), g(p, 
"ParaHyphenationMaxLeadingChars"), g(p, "ParaHyphenationMaxTrailingChars"), 
g(p, "ParaHyphenationMaxHyphens")])
+            try:
+                pe = p.createEnumeration(); sig = []
+                while pe.hasMoreElements():
+                    t = pe.nextElement(); ty = t.TextPortionType; 
sig.append(ty)
+                    if ty == "TextField": sig.append(tryf(lambda: 
t.TextField.ServiceName if hasattr(t.TextField, "ServiceName") else 
",".join(t.TextField.SupportedServiceNames)))
+                    u = g(t, "HyperLinkURL")
+                    if u: sig.append("URL:" + str(u))
+                port_hash.append(h("|".join(map(str, sig))))
+            except Exception: port_hash.append("n/a")
+        else: tbl += 1
+    o["paras"] = paras; o["nparas"] = len(paras); o["port_hash"] = 
h("".join(port_hash)); o["top_tables"] = tbl
+    ps = doc.StyleFamilies.getByName("PageStyles")
+    pk = ["Width", "Height", "BackColor", "BackTransparent", "FillStyle", 
"FillColor", "FillTransparence", "HeaderIsOn", "HeaderBackColor", 
"HeaderBackTransparent", "HeaderFillStyle",
+          "HeaderFillColor", "HeaderFillTransparence", "FooterIsOn", 
"FooterBackColor", "FooterBackTransparent", "FooterFillStyle", 
"FooterFillColor", "FooterFillTransparence",
+          "GridMode", "GridBaseWidth", "GridBaseHeight", "GridLines", 
"GridSnapToChars", "StandardPageMode", "GridRubyHeight", "GridDisplay", 
"GridPrint", "IsLandscape", "PageStyleLayout"]
+    o["pagestyles"] = {n: gs(ps.getByName(n), pk) + [bool(g(ps.getByName(n), 
"BackGraphicURL")), bool(g(ps.getByName(n), "HeaderBackGraphicURL")), 
bool(g(ps.getByName(n), "FooterBackGraphicURL"))] for n in ps.ElementNames}
+    pa = doc.StyleFamilies.getByName("ParagraphStyles")
+    ak = ["ParaBackColor", "ParaBackTransparent", "FillStyle", "FillColor", 
"FillTransparence", "CharHeight", "ParaHyphenationMaxLeadingChars", 
"ParaHyphenationMaxTrailingChars", "ParaKeepTogether", "ParaAdjust"]
+    o["parastyles"] = {n: gs(pa.getByName(n), ak) for n in pa.ElementNames}
+    cs = doc.StyleFamilies.getByName("CharacterStyles")
+    o["charstyles"] = {n: gs(cs.getByName(n), ["CharHeight", "CharWeight", 
"CharColor"]) for n in cs.ElementNames}
+    fs = doc.StyleFamilies.getByName("FrameStyles")
+    o["framestyles"] = {n: gs(fs.getByName(n), ["BackColor", "FillStyle", 
"FillTransparence", "FillColor", "Width", "Height"]) for n in fs.ElementNames}
+    tabs = []
+    for i in range(min(doc.TextTables.Count, 100)):
+        t = doc.TextTables.getByIndex(i)
+        cn = list(t.CellNames)
+        tabs.append({"name": t.Name, "rows": t.Rows.Count, "cols": 
t.Columns.Count, "cells": len(cn), "cellhash": h("|".join(cn) + 
"".join(tryf(lambda: t.getCellByName(c).String, "") for c in cn[:300])),
+                     "split": [tryf(lambda: 
t.Rows.getByIndex(r).IsSplitAllowed) for r in range(min(t.Rows.Count, 50))], 
"bg": g(t, "BackColor"), "kt": g(t, "Split")})
+    o["tables"] = tabs
+    fld = []
+    en = doc.TextFields.createEnumeration()
+    while en.hasMoreElements() and len(fld) < LIM:
+        f = en.nextElement()
+        sn = tryf(lambda: ",".join(f.SupportedServiceNames))
+        r = [sn.replace("com.sun.star.text.", "")[:120]]
+        if "GetReference" in sn: r += gs(f, ["ReferenceFieldPart", 
"ReferenceFieldSource", "SourceName", "SequenceNumber"])
+        if "URL" in sn: r += gs(f, ["URL", "Representation"])
+        fld.append(r)
+    o["fields"] = fld
+    o["footnotes"] = [doc.Footnotes.Count, [tryf(lambda: 
doc.Footnotes.getByIndex(i).String[:30], "") for i in 
range(min(doc.Footnotes.Count, 30))]]
+    o["endnotes"] = [doc.Endnotes.Count, [tryf(lambda: 
doc.Endnotes.getByIndex(i).String[:30], "") for i in 
range(min(doc.Endnotes.Count, 30))]]
+    fr = []
+    for coll, name in ((doc.TextFrames, "frame"), (doc.GraphicObjects, 
"graphic"), (doc.EmbeddedObjects, "embedded")):
+        for n in coll.ElementNames[:100]:
+            f = coll.getByName(n)
+            fr.append([name, n, g(f, "AnchorType"), g(f, "AnchorPageNo"), g(f, 
"Width"), g(f, "Height"), g(f, "BackColor"), g(f, "FillTransparence"), g(f, 
"Transparency"), g(f, "FillStyle"), g(f, "HoriOrientPosition"), g(f, 
"VertOrientPosition")])
+            if name == "embedded": fr[-1].append(embedded(tryf(lambda: 
f.Model, None)))
+    o["frames"] = fr
+    sec = []
+    for n in doc.TextSections.ElementNames[:100]:
+        s = doc.TextSections.getByName(n); sec.append([n, g(s, "FileLink"), 
g(s, "LinkRegion"), g(s, "IsProtected"), g(s, "IsVisible")])
+    o["sections"] = sec
+    rl = []
+    try:
+        en = doc.Redlines.createEnumeration()
+        while en.hasMoreElements() and len(rl) < 100:
+            r = en.nextElement(); rl.append([g(r, "RedlineType"), g(r, 
"RedlineAuthor"), g(r, "RedlineDateTime"), g(r, "RedlineComment"), g(r, 
"RedlineSuccessorData") != "n/a" and bool(g(r, "RedlineSuccessorData"))])
+    except Exception: rl = "n/a"
+    o["redlines"] = rl
+    o["bookmarks"] = tryf(lambda: sorted(doc.Bookmarks.ElementNames))
+    o["refmarks"] = tryf(lambda: sorted(doc.ReferenceMarks.ElementNames))
+    o["indexes"] = tryf(lambda: doc.DocumentIndexes.Count)
+    o["shapes"] = [shape(doc.DrawPage.getByIndex(i)) for i in 
range(min(doc.DrawPage.Count, 150))]
+    o["forms"] = forms_of(doc.DrawPage)
+    o["nstyles"] = {k: len(doc.StyleFamilies.getByName(k).ElementNames) for k 
in doc.StyleFamilies.ElementNames}
+    return o
+
+def calc(doc):
+    o = {"sheets": []}
+    nfs = doc.NumberFormats; ftype = {}
+    def ft(k):
+        if k not in ftype: ftype[k] = tryf(lambda: nfs.getByKey(k).Type)
+        return ftype[k]
+    for i in range(doc.Sheets.Count):
+        sh = doc.Sheets.getByIndex(i)
+        cur = sh.createCursor(); cur.gotoEndOfUsedArea(False)
+        rng = sh.getCellRangeByPosition(0, 0, cur.RangeAddress.EndColumn, 
cur.RangeAddress.EndRow)
+        if cur.RangeAddress.EndColumn > 300 or cur.RangeAddress.EndRow > 3000:
+            rng = sh.getCellRangeByPosition(0, 0, 
min(cur.RangeAddress.EndColumn, 300), min(cur.RangeAddress.EndRow, 3000))
+        da = rng.DataArray; fa = rng.FormulaArray
+        so = {"name": sh.Name, "end": [cur.RangeAddress.EndColumn, 
cur.RangeAddress.EndRow], "data_hash": h(repr(da)), "formula_hash": h(repr(fa)),
+              "nformulas": sum(1 for r in fa for c in r if isinstance(c, str) 
and c.startswith("="))}
+        cells = []
+        nrow = min(len(da), 400)
+        for r in range(nrow):
+            for c in range(min(len(da[r]), 60)):
+                if da[r][c] != "" and da[r][c] is not None:
+                    cell = rng.getCellByPosition(c, r)
+                    cells.append([r, c, ft(cell.NumberFormat), 
cell.getError(), cell.Type.value])
+        so["cells_hash"] = h(repr(cells)); so["ncells"] = len(cells)
+        so["errors"] = sum(1 for x in cells if x[3])
+        so["annotations"] = [sh.Annotations.Count, h("".join(tryf(lambda: 
sh.Annotations.getByIndex(k).String, "") for k in 
range(min(sh.Annotations.Count, 100))))]
+        so["charts"] = {n: chart_info(tryf(lambda: 
sh.Charts.getByName(n).EmbeddedObject, None)) for n in 
sh.Charts.ElementNames[:30]}
+        urls = []
+        for r in range(nrow):
+            for c in range(min(len(da[r]), 40)):
+                if isinstance(fa[r][c], str) and fa[r][c] and not 
fa[r][c].startswith("="):
+                    cell = rng.getCellByPosition(c, r)
+                    try:
+                        en = cell.Text.createEnumeration()
+                        while en.hasMoreElements():
+                            pe = en.nextElement().createEnumeration()
+                            while pe.hasMoreElements():
+                                pt = pe.nextElement()
+                                if pt.TextPortionType == "TextField": 
urls.append([r, c, tryf(lambda: pt.TextField.URL), tryf(lambda: 
pt.TextField.Representation)])
+                    except Exception: pass
+                    if len(urls) > 100: break
+        so["urls"] = urls
+        so["shapes"] = [shape(sh.DrawPage.getByIndex(k)) for k in 
range(min(sh.DrawPage.Count, 100))]
+        so["forms"] = forms_of(sh.DrawPage)
+        so["pagestyle"] = sh.PageStyle
+        so["flags"] = gs(sh, ["IsVisible", "IsProtected"])
+        o["sheets"].append(so)
+    o["dde"] = tryf(lambda: [[n, doc.DDELinks.getByName(n).Application, 
doc.DDELinks.getByName(n).Topic, doc.DDELinks.getByName(n).Item] for n in 
doc.DDELinks.ElementNames])
+    o["names"] = tryf(lambda: sorted(doc.NamedRanges.ElementNames))
+    ps = doc.StyleFamilies.getByName("PageStyles")
+    o["pagestyles"] = {n: gs(ps.getByName(n), ["BackColor", "BackTransparent", 
"FillStyle", "HeaderIsOn", "FooterIsOn", "IsLandscape", "Width", "Height", 
"ScaleToPagesX"]) for n in ps.ElementNames}
+    cs = doc.StyleFamilies.getByName("CellStyles")
+    o["cellstyles"] = {n: gs(cs.getByName(n), ["CellBackColor", 
"IsCellBackgroundTransparent", "CharHeight", "NumberFormat"]) for n in 
cs.ElementNames}
+    return o
+
+def draw(doc):
+    o = {"pages": []}
+    pages = doc.DrawPages
+    for i in range(pages.Count):
+        pg = pages.getByIndex(i)
+        po = {"name": tryf(lambda: pg.Name), "shapes": 
[shape(pg.getByIndex(k)) for k in range(min(pg.Count, 300))], "forms": 
forms_of(pg),
+              "layout": g(pg, "Layout"), "bg": tryf(lambda: gs(pg.Background, 
["FillStyle", "FillColor", "FillTransparence", "FillGradientName"])), "master": 
tryf(lambda: pg.MasterPage.Name)}
+        if has(doc, "com.sun.star.presentation.PresentationDocument"):
+            po["notes"] = tryf(lambda: [pg.NotesPage.getByIndex(k).String[:40] 
for k in range(min(pg.NotesPage.Count, 20)) if 
hasattr(pg.NotesPage.getByIndex(k), "String")], "n/a")
+        o["pages"].append(po)
+    masters = doc.MasterPages
+    o["masters"] = [[tryf(lambda: masters.getByIndex(i).Name), 
len(shape_list(masters.getByIndex(i)))] for i in range(masters.Count)]
+    for fam in ("graphics", "Default"):
+        pass
+    try:
+        gf = doc.StyleFamilies.getByName("graphics")
+        o["graphicstyles"] = {n: gs(gf.getByName(n), ["FillStyle", 
"FillColor", "FillTransparence", "CharHeight", "LineStyle", "LineColor", 
"TextWritingMode"]) for n in gf.ElementNames}
+    except Exception: pass
+    return o
+def shape_list(pg): return [shape(pg.getByIndex(k)) for k in 
range(min(pg.Count, 300))]
+
+DESK = desktop(connect(port))
+os.makedirs(outdir, exist_ok=True)
+for f in files:
+    dest = os.path.join(outdir, os.path.basename(f) + ".json")
+    if os.path.exists(dest): continue
+    open(os.path.join(outdir, ".current"), "w").write(f)
+    out = {}
+    try:
+        doc = load(DESK, f)
+        out["type"] = ("writer" if has(doc, "com.sun.star.text.TextDocument") 
else "calc" if has(doc, "com.sun.star.sheet.SpreadsheetDocument")
+                       else "impress" if has(doc, 
"com.sun.star.presentation.PresentationDocument") else "draw" if has(doc, 
"com.sun.star.drawing.DrawingDocument") else "other")
+        out["props"] = tryf(lambda: docprops(doc), "ERR")
+        out["basic"] = basic(doc)
+        try:
+            out["body"] = {"writer": writer, "calc": calc, "impress": draw, 
"draw": draw}.get(out["type"], lambda d: {})(doc)
+        except Exception as e:
+            out["body_error"] = repr(e)[:200]
+        doc.close(True)
+    except Exception as e:
+        out["error"] = repr(e)[:200]
+    json.dump(out, open(dest, "w"), sort_keys=True, indent=0, default=str)
+print("done", len(files))
diff --git a/test/odf-validate/gate-fixtures.tsv 
b/test/odf-validate/gate-fixtures.tsv
new file mode 100644
index 0000000000..fcb94f124b
--- /dev/null
+++ b/test/odf-validate/gate-fixtures.tsv
@@ -0,0 +1,82 @@
+# Documents the gate saves in every ODF version mode, and the reload checks 
run on the saved copies.
+# source<TAB>checks. A source is relative to fixtures/, or EXT:<path under 
main/>.
+# checks "-" saves the document only; otherwise the file (relative to 
fixtures/) is run with roundtrip.py on the saved copy.
+grid-snap/grid-snap.odt        -
+row-split/row-split.odt        -
+table-colspan/MergedTable_3_3.docx     -
+print-date/burger_factory.odt  -
+page-fill/page-fill.odt        -
+para-fill/para-fill.odt        -
+fill-others/others-writer.odt  -
+fill-others/others-calc.ods    -
+fill-others/others-draw.odg    -
+fill-others/others-impress.odp -
+EXT:writerfilter/qa/documents/fields.doc       -
+ole-text/ole-text.odg  -
+ole-text-edge/ole-text-edge.odg        -
+chart-shapes/chart-shapes.ods  -
+xforms-list/xforms-list.odt    -
+alien-attrs/alien-writer.odt   -
+alien-attrs/alien-draw.odg     -
+alien-attrs/alien-calc.ods     -
+connector-viewbox/conn.odg     -
+connector-viewbox/conn.odp     -
+redline-stack/test-review-stack.docx   -
+control/good.odt       -
+normal-values5b/normal5b.ods   -
+chart-empty/AddInChart.ods     -
+para-fill-foreign/aoo-form.odt -
+para-fill-foreign/foreign-v8.odt       -
+para-fill-foreign/foreign-v3.odt       -
+para-fill-foreign/foreign-v11.odt      -
+para-fill-foreign/edge-unknown-name.odt        -
+para-fill-foreign/edge-empty.odt       -
+para-fill-foreign/edge-nonparagraph.odt        -
+para-fill-foreign/edge-duplicate-nested.odt    -
+para-fill-foreign/edge-both-forms.odt  -
+para-fill-foreign/edge-unknown-attr.odt        -
+page-fill-1_3/aoo-src.odt      -
+page-fill-1_3/foreign-v10.odt  -
+page-fill-1_3/foreign-v11.odt  -
+page-fill-1_3/foreign-v12.odt  -
+page-fill-1_3/foreign-v3.odt   -
+page-fill-1_3/foreign-v8.odt   -
+page-fill-1_3/edge-unknown-name.odt    -
+page-fill-1_3/edge-empty.odt   -
+page-fill-1_3/edge-undefined.odt       -
+page-fill-1_3/edge-none.odt    -
+page-fill-1_3/edge-common.odt  -
+page-fill-1_3/edge-both.odt    -
+page-fill-1_3/edge-shared-layout.odt   -
+page-fill-1_3/calc-src.ods     -
+page-fill-1_3/calc-drawing-page.ods    -
+EXT:forms/workben/xforms/xforms-ubl.odt        -
+EXT:framework/qa/complex/loadAllDocuments/testdocuments/imp1.sxi       -
+EXT:qadevOOo/testdocs/TwoShapes.sxi    -
+EXT:vcl/qa/complex/memCheck/testdocuments/ImpressDoc.sxi       -
+EXT:xmlsecurity/doc/XMLSecurityFramework.sxw   -
+EXT:svx/doc/drawing_layer_UNO_objects.odg      -
+EXT:qadevOOo/testdocs/TransparencyCalcChart.sxc        -
+EXT:scripting/workben/data/ExampleSpreadSheetLatest.sxc        -
+EXT:xmerge/source/palmtests/qa-wrapper/results/baseline/xml-base/c_textimage.sxc
       -
+page-fill-1_3/aoo-src.odt      page-fill-1_3/checks.json
+page-fill-1_3/foreign-v11.odt  page-fill-1_3/checks-foreign.json
+page-fill-1_3/foreign-v3.odt   page-fill-1_3/checks-foreign.json
+page-fill-1_3/foreign-v8.odt   page-fill-1_3/checks-foreign.json
+page-fill-1_3/foreign-v10.odt  page-fill-1_3/checks-foreign-strict.json
+page-fill-1_3/foreign-v12.odt  page-fill-1_3/checks-foreign-strict.json
+page-fill-1_3/edge-unknown-name.odt    
page-fill-1_3/checks-edge-unknown-name.json
+page-fill-1_3/edge-empty.odt   page-fill-1_3/checks-edge-empty.json
+page-fill-1_3/edge-undefined.odt       page-fill-1_3/checks-edge-undefined.json
+page-fill-1_3/edge-none.odt    page-fill-1_3/checks-foreign-strict.json
+page-fill-1_3/edge-common.odt  page-fill-1_3/checks-foreign-strict.json
+page-fill-1_3/edge-both.odt    page-fill-1_3/checks-edge-both.json
+page-fill-1_3/edge-shared-layout.odt   
page-fill-1_3/checks-edge-shared-layout.json
+page-fill-1_3/calc-src.ods     page-fill-1_3/checks-calc.json
+page-fill-1_3/calc-drawing-page.ods    page-fill-1_3/checks-calc.json
+page-fill/page-fill.odt        page-fill/checks.json
+page-fill/page-fill.odt        page-fill/bitmap.json
+fill-others/others-writer.odt  fill-others/writer.json
+fill-others/others-calc.ods    fill-others/calc.json
+fill-others/others-draw.odg    fill-others/draw.json
+fill-others/others-impress.odp fill-others/impress.json
diff --git a/test/odf-validate/gate-volatile.tsv 
b/test/odf-validate/gate-volatile.tsv
new file mode 100644
index 0000000000..146ef00618
--- /dev/null
+++ b/test/odf-validate/gate-volatile.tsv
@@ -0,0 +1,14 @@
+# Output documents whose reload dump may differ between runs without a change 
in the export.
+# name<TAB>reason. Read by gate.py's diff stage; anything else that differs is 
unexplained.
+0048__OOoDocAnalysisExcelDriver.ods    strict: the saved file intermittently 
lacks the Basic library (KNOWN-BUGS.md)
+0067_AddInChart.ods    volatile Calc formula (NOW, TODAY or RAND)
+0082_ToDo.ods  volatile Calc formula (NOW, TODAY or RAND)
+0126_datevalue.ods     volatile Calc formula (NOW, TODAY or RAND)
+0161_datevalue.ods     volatile Calc formula (NOW, TODAY or RAND)
+0206_CurrentTime.ods   volatile Calc formula (NOW, TODAY or RAND)
+0248_fields.odt        date fields differ between sessions
+0230_test-review-brk.odt       redline import stamps Unknown Author changes 
with the load time
+0231_test-review-para.odt      redline import stamps Unknown Author changes 
with the load time
+0232_test-review-stack.odt     redline import stamps Unknown Author changes 
with the load time
+0266_RedlineTest.odt   redline import stamps Unknown Author changes with the 
load time
+0238_parentinvguid.odt the loader gives different shape and frame order in 
fresh sessions (the export is identical)
diff --git a/test/odf-validate/gate.py b/test/odf-validate/gate.py
new file mode 100644
index 0000000000..c71bddec7d
--- /dev/null
+++ b/test/odf-validate/gate.py
@@ -0,0 +1,404 @@
+#**************************************************************
+#
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing,
+#  software distributed under the License is distributed on an
+#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#  KIND, either express or implied.  See the License for the
+#  specific language governing permissions and limitations
+#  under the License.
+#
+#**************************************************************
+
+# usage: gate.py <tag> [--stages s,...] [--modes ext,strict] [--prev DIR] 
[--jobs FILE] [--limit N] [--port P]
+#                [--build mod,...] [--libs lib.dylib,...] [--stall SECONDS] 
[--force] [--crosscheck]
+# The corpus regression gate as one resumable run in runs/gate-<tag>/. Stages, 
in order:
+#   build     rebuild the modules (--build) and deliver them to the solver
+#   refresh   copy the rebuilt libraries (--libs) from the solver into the app 
copy and verify them
+#   corpus    save the job list in ODF 1.2 Extended (ext) and strict (strict) 
mode with the app copy
+#   validate  validate.py and the checkers on the saved packages; kinds 
compared with baseline/ and --prev
+#   dump      reload every saved package and dump a fixed property set 
(dump7.py), with a stall watchdog
+#   diff      dumps (diff7.py) and packages (cmp7.py) against --prev; 
differences not in gate-volatile.tsv are unexplained
+#   fixtures  gate-fixtures.tsv saved in five version modes, reload checks, 
validation; results against --prev
+# --jobs freezes the inputs (source<TAB>output lines; outputs are rewritten); 
default: --prev's list, else make-jobs.sh.
+# Exit status 0 only if every stage that ran passed.
+import argparse, collections, json, os, re, shutil, socket, subprocess, sys, 
threading, time
+
+D = os.path.dirname(os.path.abspath(__file__))
+PY = [sys.executable, "-I"]
+STAGES = ["build", "refresh", "corpus", "validate", "dump", "diff", "fixtures"]
+FIX_MODES = ["v00", "v10", "v11", "ext", "strict"]
+DEFAULT_LIBS = "libxo.dylib,libsw.dylib,libsc.dylib,libsd.dylib,libsfx.dylib"
+
+
+def listening(port):
+    with socket.socket() as s:
+        s.settimeout(0.5)
+        return s.connect_ex(("localhost", port)) == 0
+
+
+def kill_office(profile):
+    subprocess.run(["pkill", "-f", "profile_" + profile], capture_output=True)
+    time.sleep(2)
+
+
+def run(cmd, log=None, timeout=None, cwd=None, env=None):
+    """Runs cmd, appending its output to log; returns the exit code (124 on 
timeout)."""
+    out = open(log, "a") if log else subprocess.DEVNULL
+    try:
+        return subprocess.run(cmd, stdout=out, stderr=subprocess.STDOUT, 
timeout=timeout, cwd=cwd, env=env).returncode
+    except subprocess.TimeoutExpired:
+        return 124
+    finally:
+        if log:
+            out.close()
+
+
+def read_jobs(path):
+    return [tuple(l.rstrip("\n").split("\t")) for l in open(path) if l.strip()]
+
+
+def rewrite_jobs(jobs, outdir):
+    """Same sources, outputs moved into outdir."""
+    return [(src, os.path.join(outdir, os.path.basename(out))) for src, out in 
jobs]
+
+
+def read_volatile(path=os.path.join(D, "gate-volatile.tsv")):
+    return {l.split("\t")[0]: l.rstrip("\n").split("\t")[1] for l in 
open(path) if l.strip() and not l.startswith("#")}
+
+
+def classify(diff, volatile):
+    """diff: diff7.py's result; returns (identical, volatile differing, 
unexplained differing)."""
+    differing = sorted(k for k, v in diff.items() if v["ndiff"])
+    vol = [k for k in differing if k in volatile]
+    return len(diff) - len(differing), vol, [k for k in differing if k not in 
volatile]
+
+
+def run_with_stall(cmd, progress, stall, poll=2.0, log=None):
+    """Runs cmd until it exits or progress() has not changed for `stall` 
seconds (then kills it).
+    Returns ('exit', returncode) or ('stalled', None)."""
+    out = open(log, "a") if log else subprocess.DEVNULL
+    p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.STDOUT)
+    last, since = progress(), time.time()
+    try:
+        while p.poll() is None:
+            time.sleep(poll)
+            now = progress()
+            if now != last:
+                last, since = now, time.time()
+            elif time.time() - since > stall:
+                p.kill(); p.wait()
+                return "stalled", None
+        return "exit", p.returncode
+    finally:
+        if log:
+            out.close()
+
+
+def dump_dir(src, dest, profile, port, stall, log, tool=None, poll=2.0):
+    """Reloads every package in src into dest/*.json. A document that stalls 
the office or kills it gets an error
+    marker only after `stall` seconds without progress, never because the 
whole batch took long.
+    tool(port, dest, files) -> argv replaces dump7.py under the office (for 
tests); then no office is started."""
+    os.makedirs(dest, exist_ok=True)
+    files = sorted(os.path.join(src, f) for f in os.listdir(src) if not 
f.startswith("."))
+    count = lambda: len([f for f in os.listdir(dest) if f.endswith(".json")])
+    stalls = 0
+    while count() < len(files):
+        if tool is None and not listening(port):
+            if run([os.path.join(D, "start.sh"), profile, str(port)], log) != 
0:
+                return {"error": "office did not start", "stalls": stalls}
+        before = count()
+        marker = os.path.join(dest, ".current")
+        argv = tool(port, dest, files) if tool else [os.path.join(D, 
"runpy.sh"), os.path.join(D, "dump7.py"), str(port), dest] + files
+        how, rc = run_with_stall(argv, lambda: (count(), 
os.path.getmtime(marker) if os.path.exists(marker) else 0), stall, poll, 
log=log)
+        if how == "stalled" or rc != 0:
+            cur = open(marker).read().strip() if os.path.exists(marker) else ""
+            if cur and not os.path.exists(os.path.join(dest, 
os.path.basename(cur) + ".json")):
+                reason = ("HANG: no progress for %ds" % stall) if how == 
"stalled" else "CRASH: rc=%s" % rc
+                json.dump({"error": reason}, open(os.path.join(dest, 
os.path.basename(cur) + ".json"), "w"))
+                stalls += 1
+            if tool is None:
+                kill_office(profile)
+        elif count() == before:
+            return {"error": "dump7.py made no progress", "stalls": stalls}
+    if tool is None:
+        kill_office(profile)
+    return {"documents": count(), "stalls": stalls}
+
+
+def count_done(done):
+    ok = fail = 0
+    if os.path.exists(done):
+        for l in open(done):
+            ok += l.rstrip("\n").endswith("\tOK")
+            fail += "\tFAIL" in l
+    return ok, fail
+
+
+class Gate:
+    def __init__(self, a):
+        self.a = a
+        self.run = os.path.join(D, "runs", "gate-" + a.tag)
+        os.makedirs(self.run, exist_ok=True)
+        self.res_path = os.path.join(self.run, "results.json")
+        self.res = json.load(open(self.res_path)) if 
os.path.exists(self.res_path) else {}
+        self.modes = a.modes.split(",")
+        self.prev = os.path.abspath(a.prev) if a.prev else None
+
+    def save(self):
+        json.dump(self.res, open(self.res_path, "w"), indent=1)
+
+    def log(self, name):
+        return os.path.join(self.run, name + ".log")
+
+    def prev_path(self, *candidates):
+        for c in candidates:
+            p = os.path.join(self.prev, c) if self.prev else None
+            if p and os.path.exists(p):
+                return p
+        return None
+
+    # ---- stages
+    def build(self):
+        mods = [m for m in self.a.build.split(",") if m]
+        if not mods:
+            return {"skipped": "no --build modules"}
+        env = os.environ.get("ODFV_BUILD_ENV") or 
sorted(__import__("glob").glob(os.path.join(D, "..", "..", "main", 
"*Env.Set.sh")))[-1]
+        res = {}
+        for m in mods:
+            cmd = "cd %s/../../main && source %s && cd %s && perl 
$SOLARENV/bin/build.pl && perl $SOLARENV/bin/deliver.pl" % (D, env, m)
+            res[m] = run(["/bin/zsh", "-c", cmd], self.log("build_" + m))
+        return {"ok": all(v == 0 for v in res.values()), "rc": res}
+
+    def refresh(self):
+        libs = [l for l in self.a.libs.split(",") if l]
+        out = subprocess.run([os.path.join(D, "refresh-app.sh")] + libs, 
capture_output=True, text=True)
+        return {"ok": out.returncode == 0, "output": 
out.stdout.strip().splitlines()}
+
+    def jobs(self):
+        if self.a.jobs:
+            return read_jobs(self.a.jobs)
+        pj = self.prev_path("jobs.tsv", "ext/jobs.tsv")
+        if pj:
+            return read_jobs(pj)
+        out = subprocess.run([os.path.join(D, "make-jobs.sh"), "OUT"], 
capture_output=True, text=True, check=True).stdout
+        return [tuple(l.split("\t")) for l in out.splitlines()]
+
+    def corpus(self):
+        jobs = self.jobs()
+        if self.a.limit:
+            jobs = jobs[:self.a.limit]
+        with open(os.path.join(self.run, "jobs.tsv"), "w") as f:
+            f.writelines("%s\t%s\n" % j for j in jobs)
+        procs, res = {}, {}
+        for i, mode in enumerate(self.modes):
+            md = os.path.join(self.run, mode)
+            os.makedirs(os.path.join(md, "out"), exist_ok=True)
+            with open(os.path.join(md, "jobs.tsv"), "w") as f:
+                f.writelines("%s\t%s\n" % j for j in rewrite_jobs(jobs, 
os.path.join(md, "out")))
+            open(os.path.join(md, "done.tsv"), "a").close()
+            procs[mode] = subprocess.Popen([os.path.join(D, "drive.sh"), mode, 
str(self.a.port + i), os.path.join(md, "jobs.tsv"), os.path.join(md, 
"done.tsv")])
+        for mode, p in procs.items():
+            p.wait()
+            md = os.path.join(self.run, mode)
+            ok, fail = count_done(os.path.join(md, "done.tsv"))
+            res[mode] = {"rc": p.returncode, "ok": ok, "fail": fail, "jobs": 
len(jobs), "packages": len(os.listdir(os.path.join(md, "out")))}
+            pd = self.prev_path(mode + "/done.tsv")
+            if pd and not self.a.limit:
+                res[mode]["prev_ok_fail"] = count_done(pd)
+        res["ok"] = all(r["rc"] == 0 and r["ok"] + r["fail"] == r["jobs"] and 
r["ok"] > 0 for r in res.values() if isinstance(r, dict))
+        if not self.a.limit:
+            res["ok"] = res["ok"] and all(tuple(r["prev_ok_fail"]) == 
(r["ok"], r["fail"]) for r in res.values() if isinstance(r, dict) and 
"prev_ok_fail" in r)
+        return res
+
+    def validate_dir(self, md, out, kinds_base, label):
+        """validate.py + report.py + the checkers on out/; returns a result 
dict."""
+        r = {}
+        log = os.path.join(md, "validate.log")
+        run(PY + [os.path.join(D, "validate.py"), out, os.path.join(md, 
"val.json")], log)
+        val = json.load(open(os.path.join(md, "val.json")))
+        r["errors"] = {v: len(e) for v, e in val["errors"].items()}
+        r["packages"] = len(val["packages"])
+        for v in ("12", "14", "12x"):
+            kp = os.path.join(md, "kinds%s.json" % ("" if v == "12" else v))
+            run(PY + [os.path.join(D, "report.py"), os.path.join(md, 
"val.json"), kp, v], os.path.join(md, "report%s.log" % v))
+            r["kinds" + v] = len(json.load(open(kp)))
+        for name, script, pat in (("ids", "idcheck.py", r"(\d+) errors"), 
("pkg", "pkgcheck.py", r"(\d+) shall"),
+                                  ("doctype", "doctypecheck.py", r"(\d+) 
shall"), ("formulas", "formulacheck.py", r"(\d+) shall")):
+            o = subprocess.run(PY + [os.path.join(D, script), out, 
os.path.join(md, name + ".json")], capture_output=True, text=True)
+            m = re.search(pat, o.stdout)
+            r["shall_" + name] = int(m.group(1)) if m else None
+        base = kinds_base
+        if base and os.path.exists(base):
+            r["vs_baseline"] = run(PY + [os.path.join(D, "compare.py"), base, 
os.path.join(md, "kinds.json")], os.path.join(md, "compare_base.log"))
+        return r
+
+    def validate(self):
+        res = {}
+        for mode in self.modes:
+            md = os.path.join(self.run, mode)
+            r = self.validate_dir(md, os.path.join(md, "out"), os.path.join(D, 
"baseline", mode + ".kinds.json"), mode)
+            pk = self.prev_path(mode + "/kinds.json")
+            if pk and not self.a.limit:
+                r["vs_prev"] = run(PY + [os.path.join(D, "compare.py"), pk, 
os.path.join(md, "kinds.json")], os.path.join(md, "compare_prev.log"))
+                r["vs_prev_reverse"] = run(PY + [os.path.join(D, 
"compare.py"), os.path.join(md, "kinds.json"), pk], os.path.join(md, 
"compare_prev_rev.log"))
+            res[mode] = r
+        res["ok"] = all(r.get("vs_baseline", 0) == 0 and r.get("vs_prev", 0) 
== 0 and r.get("vs_prev_reverse", 0) == 0 for r in res.values())
+        return res
+
+    def dump(self):
+        res, threads = {}, []
+        for i, mode in enumerate(self.modes):
+            def one(mode=mode, i=i):
+                md = os.path.join(self.run, mode)
+                res[mode] = dump_dir(os.path.join(md, "out"), os.path.join(md, 
"dump"), "gate_dump_%s_%s" % (self.a.tag, mode),
+                                     self.a.port + 10 + i, self.a.stall, 
self.log("dump_" + mode))
+            t = threading.Thread(target=one); t.start(); threads.append(t)
+        for t in threads:
+            t.join()
+        res["ok"] = all("error" not in r for r in res.values())
+        for mode in self.modes:
+            md = os.path.join(self.run, mode, "dump")
+            res[mode]["hang_markers"] = sorted(f for f in os.listdir(md) if 
f.endswith(".json") and "error" in json.load(open(os.path.join(md, f))) and
+                                               
str(json.load(open(os.path.join(md, f)))["error"]).startswith(("HANG", 
"CRASH")))
+        return res
+
+    def diff(self):
+        if not self.prev:
+            return {"skipped": "no --prev"}
+        volatile, res = read_volatile(), {}
+        for mode in self.modes:
+            md = os.path.join(self.run, mode)
+            old = self.prev_path(mode + "/dump", "dump_" + mode)
+            oldrun = self.prev_path(mode + "/out")
+            r = {}
+            if old:
+                # compare only the documents this run saved (a --limit run 
saves fewer)
+                sub = os.path.join(md, "prev-dump")
+                shutil.rmtree(sub, ignore_errors=True); os.makedirs(sub)
+                for f in os.listdir(os.path.join(md, "dump")):
+                    if f.endswith(".json") and 
os.path.exists(os.path.join(old, f)):
+                        os.symlink(os.path.join(old, f), os.path.join(sub, f))
+                dj = os.path.join(md, "diff_dump.json")
+                run(PY + [os.path.join(D, "diff7.py"), sub, os.path.join(md, 
"dump"), dj], os.path.join(md, "diff_dump.log"))
+                same, vol, unexplained = classify(json.load(open(dj)), 
volatile)
+                r["dump"] = {"compared": len(os.listdir(sub)), "identical": 
same, "volatile": vol, "unexplained": unexplained}
+            if oldrun:
+                stage = os.path.join(self.run, "cmp-" + mode)
+                shutil.rmtree(stage, ignore_errors=True); 
os.makedirs(os.path.join(stage, "out"))
+                for f in os.listdir(os.path.join(md, "out")):
+                    if os.path.exists(os.path.join(oldrun, f)):
+                        os.symlink(os.path.join(oldrun, f), 
os.path.join(stage, "out", f))
+                # cmp7 reads <run>/out for both sides: the old side is the 
subset linked above, the new side this run
+                cj = os.path.join(md, "cmp7.json")
+                cp = subprocess.run(PY + [os.path.join(D, "cmp7.py"), stage, 
md, mode, cj], capture_output=True, text=True)
+                open(os.path.join(md, "cmp7.log"), "w").write(cp.stdout + 
cp.stderr)
+                m = re.search(r"differing after env masks: (\d+); differing 
after intended-edit normalisation: (\d+)", cp.stdout)
+                if m:
+                    cmp = json.load(open(cj))
+                    differing = sorted(k for k, v in cmp.items() if 
v.get("norm_diff_streams") or v.get("names_diff") or v.get("missing_in_new"))
+                    r["packages"] = {"after_masks": int(m.group(1)), 
"volatile": [k for k in differing if k in volatile],
+                                     "unexplained": [k for k in differing if k 
not in volatile]}
+                else:
+                    r["packages"] = {"error": (cp.stderr or cp.stdout)[-200:], 
"unexplained": ["cmp7.py failed"]}
+            res[mode] = r
+        res["ok"] = all(("dump" not in r or not r["dump"]["unexplained"]) and 
("packages" not in r or not r["packages"]["unexplained"]) for r in res.values())
+        return res
+
+    def fixtures(self):
+        entries = [l.rstrip("\n").split("\t") for l in open(os.path.join(D, 
"gate-fixtures.tsv")) if l.strip() and not l.startswith("#")]
+        def src_path(s):
+            return os.path.join(D, "..", "..", "main", s[4:]) if 
s.startswith("EXT:") else os.path.join(D, "fixtures", s)
+        def out_name(s):
+            b = os.path.splitext(os.path.basename(s))[0]
+            ext = {"doc": "odt", "docx": "odt", "odt": "odt", "sxw": "odt", 
"ods": "ods", "sxc": "ods", "odg": "odg", "sxd": "odg", "odp": "odp", "sxi": 
"odp"}[s.rsplit(".", 1)[1]]
+            return ("pf13-" if s.startswith("page-fill-1_3/") else "") + b + 
"." + ext
+        sources = sorted({e[0] for e in entries})
+        res, threads = {}, []
+        for i, mode in enumerate(FIX_MODES):
+            def one(mode=mode, i=i):
+                md = os.path.join(self.run, "fixtures", mode)
+                out = os.path.join(md, "out")
+                os.makedirs(out, exist_ok=True)
+                missing = [s for s in sources if not 
os.path.isfile(src_path(s))]
+                with open(os.path.join(md, "jobs.tsv"), "w") as f:
+                    f.writelines("%s\t%s\n" % (os.path.abspath(src_path(s)), 
os.path.join(out, out_name(s))) for s in sources if s not in missing)
+                open(os.path.join(md, "done.tsv"), "a").close()
+                rc = run([os.path.join(D, "drive.sh"), mode, str(self.a.port + 
20 + i), os.path.join(md, "jobs.tsv"), os.path.join(md, "done.tsv")])
+                ok, fail = count_done(os.path.join(md, "done.tsv"))
+                r = {"drive_rc": rc, "saved": ok, "failed": fail, "missing": 
missing, "checks": {}}
+                prof, port = "gate_rt_%s_%s" % (self.a.tag, mode), self.a.port 
+ 30 + i
+                run([os.path.join(D, "start.sh"), prof, str(port)], 
os.path.join(md, "rt.log"))
+                for s, ck in (e for e in entries if e[1] != "-"):
+                    doc = os.path.join(out, out_name(s))
+                    key = "%s|%s" % (os.path.basename(s), ck)
+                    if not os.path.isfile(doc):
+                        r["checks"][key] = {"error": "no saved copy"}; continue
+                    p = subprocess.run([os.path.join(D, "runpy.sh"), 
os.path.join(D, "roundtrip.py"), str(port), doc, os.path.join(D, "fixtures", 
ck)], capture_output=True, text=True, timeout=600)
+                    m = re.search(r"roundtrip: (\d+)/(\d+) match", p.stdout)
+                    r["checks"][key] = {"mismatches": 
sorted(re.findall(r"^MISMATCH (\S+?):", p.stdout, re.M)), "match": 
int(m.group(1)) if m else None, "total": int(m.group(2)) if m else None}
+                kill_office(prof)
+                r["validate"] = self.validate_dir(md, out, None, mode)
+                res[mode] = r
+            t = threading.Thread(target=one); t.start(); threads.append(t)
+        for t in threads:
+            t.join()
+        pf = self.prev_path("results.json")
+        changed = []
+        if pf:
+            prev = json.load(open(pf)).get("fixtures", {})
+            for mode in FIX_MODES:
+                for k, c in res.get(mode, {}).get("checks", {}).items():
+                    pc = prev.get(mode, {}).get("checks", {}).get(k)
+                    if pc is not None and pc != c:
+                        changed.append("%s %s" % (mode, k))
+        res["changed_vs_prev"] = changed if pf else "no previous fixtures 
results"
+        res["ok"] = all(res[m]["drive_rc"] == 0 and res[m]["failed"] == 0 and 
not res[m]["missing"] and
+                        all("error" not in c and c["total"] for c in 
res[m]["checks"].values()) for m in FIX_MODES) and not changed
+        return res
+
+
+def main():
+    ap = argparse.ArgumentParser()
+    ap.add_argument("tag")
+    ap.add_argument("--stages", 
default="refresh,corpus,validate,dump,diff,fixtures")
+    ap.add_argument("--modes", default="ext,strict")
+    ap.add_argument("--prev")
+    ap.add_argument("--jobs")
+    ap.add_argument("--limit", type=int, default=0)
+    ap.add_argument("--port", type=int, default=2013)
+    ap.add_argument("--build", default="")
+    ap.add_argument("--libs", default=DEFAULT_LIBS)
+    ap.add_argument("--stall", type=int, default=300)
+    ap.add_argument("--force", action="store_true")
+    a = ap.parse_args()
+    g = Gate(a)
+    stages = [s for s in STAGES if s in a.stages.split(",") or (s == "build" 
and a.build)]
+    failed = []
+    for s in stages:
+        if s in g.res and not a.force:
+            print("%-9s already done (--force to rerun)" % s)
+        else:
+            t0 = time.time()
+            g.res[s] = getattr(g, s)()
+            g.res[s]["seconds"] = int(time.time() - t0)
+            g.save()
+        ok = g.res[s].get("ok", True)
+        print("%-9s %s  %s" % (s, "PASS" if ok else "FAIL", json.dumps({k: v 
for k, v in g.res[s].items() if k != "ok"})[:300]))
+        if not ok:
+            failed.append(s)
+    print("gate %s: %s" % (a.tag, "PASS" if not failed else "FAIL in " + ", 
".join(failed)))
+    sys.exit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/test/odf-validate/selftest.py b/test/odf-validate/selftest.py
index 7f3bdf92ba..36d4773202 100644
--- a/test/odf-validate/selftest.py
+++ b/test/odf-validate/selftest.py
@@ -137,6 +137,34 @@ if os.path.isfile(ODFV_JAR):
     })
 else:
     print("SKIP crosscheck controls: odfvalidator not installed 
(fetch-odfvalidator.sh)")
+import tempfile, time
+gspec = importlib.util.spec_from_file_location("gate", os.path.join(D, 
"gate.py"))
+gt = importlib.util.module_from_spec(gspec)
+gspec.loader.exec_module(gt)
+vol = gt.read_volatile()
+checks["gate: gate-volatile.tsv lists the 12 documents with a reason"] = 
len(vol) == 12 and all(len(r) > 10 for r in vol.values())
+checks["gate: rewrite_jobs keeps sources and moves outputs"] = 
gt.rewrite_jobs([("/a/b.odt", "/x/0001_b.odt")], "/new") == [("/a/b.odt", 
"/new/0001_b.odt")]
+fake = {"0067_AddInChart.ods": {"ndiff": 1}, "0001_x.odt": {"ndiff": 0}, 
"0002_y.odt": {"ndiff": 3}}
+checks["gate: classify separates volatile from unexplained differences"] = 
gt.classify(fake, vol) == (1, ["0067_AddInChart.ods"], ["0002_y.odt"])
+gtmp = tempfile.mkdtemp()
+stub = os.path.join(gtmp, "stub.py")
+open(stub, "w").write("import sys,os,time,json\ndest=sys.argv[1]\nfor f in 
sys.argv[2:]:\n    d=os.path.join(dest,os.path.basename(f)+'.json')\n"
+                      "    if os.path.exists(d): continue\n    
open(os.path.join(dest,'.current'),'w').write(f)\n    time.sleep(600 if 'hang' 
in f else 0.6)\n    json.dump({'type':'x'},open(d,'w'))\n")
+gsrc = os.path.join(gtmp, "src")
+os.makedirs(gsrc)
+for n in ("a", "b", "hang", "c"):
+    open(os.path.join(gsrc, n), "w").write("x")
+mk = lambda port, dest, files: [sys.executable, stub, dest] + files
+r1 = gt.dump_dir(gsrc, os.path.join(gtmp, "d1"), "p", 0, 2, os.path.join(gtmp, 
"l1"), tool=mk, poll=0.3)
+hang = json.load(open(os.path.join(gtmp, "d1", "hang.json")))
+checks["gate: a stalled document gets one HANG marker, the others are dumped"] 
= r1 == {"documents": 4, "stalls": 1} and hang["error"].startswith("HANG") \
+    and all("error" not in json.load(open(os.path.join(gtmp, "d1", n + 
".json"))) for n in ("a", "b", "c"))
+os.remove(os.path.join(gsrc, "hang"))
+for n in ("d", "e", "f"):
+    open(os.path.join(gsrc, n), "w").write("x")
+t0 = time.time()
+r2 = gt.dump_dir(gsrc, os.path.join(gtmp, "d2"), "p", 0, 2, os.path.join(gtmp, 
"l2"), tool=mk, poll=0.3)
+checks["gate: a batch longer than the stall limit that keeps progressing is 
not killed"] = r2 == {"documents": 6, "stalls": 0} and time.time() - t0 > 2
 for k, ok in checks.items():
     print(("PASS " if ok else "FAIL ") + k)
 sys.exit(0 if all(checks.values()) else 1)

Reply via email to