Skip to content

Commit 96b04b8

Browse files
author
Naohito Yoshikawa
committed
šŸ› fix(pptx-animations-transitions-roundtrip): accept only the two roundings of a half
Approval review by ShotaroKataoka, 2026-11-18, against `0983d1b7`. Three new Low findings; the first is a real defect and it contradicts what I wrote in the reply. **The half slack accepted a value neither writer produces.** I argued that a blanket ±1 would let a changed delay through, and then allowed exactly that on a half: `abs(written - expected) <= 1`. `_scaled` rounds a half up, so `expected` is already the upper rounding and the only other value a writer can emit is `expected - 1`. The two legitimate values are not symmetric around `expected`, and `expected + 1` passed. Reproduced on all three cases the review names: `entrance.bounce` at 300 ms with `@delay` hand-edited from 98 to 99 (650 Ɨ 300/2000 = 97.5) imported as `entrance.bounce` at 300 ms with no raw sidecar, and the next build wrote 98 back over the edit. Same for `entrance.drop@875` and `exit.boomerang@201`. The comparison now lists the values a writer can produce — `(expected - 1, expected)` on a half, `(expected,)` otherwise — and the refusal message names both. The lower rounding still imports, which is the case the slack exists for: PowerPoint's float precision splits an exact half both ways. Two tests. The three named cases, as the review asked. And a sweep of every exact half the catalogue produces — 64 locations across 97 presets at three durations, of which 27 imported semantically before this commit. Which timing lands on a half depends on the ratio, so these cannot be enumerated by hand; that is the same reason the duration sweep covers the whole catalogue, and it is why the three named cases alone would have been the weaker test. **The "Related guides" heading was gone.** My `### When a target is checked` section replaced `## Related guides` rather than going above it, so the four `read_guides([...])` bullets read as part of the validation subsection. Restored. **The invalid-include error named the resolved path.** Caching the read moved the message into the cached function, where only the absolute path is in scope — and on the Remote server that is a materialised tmpdir, which tells the agent reading the error nothing. Raised at the call site again, naming the deck-relative `src`. A test pins that the resolved path does not appear, and another pins that a read error is still not cached, so fixing the file and rebuilding works without a restart. On the cache's one real limit, which the review asked to have known rather than worked around: a rewrite that keeps the same size within the filesystem's timestamp granularity is the same key and returns the old content until the process restarts. That needs one-second timestamps — HFS+, FAT, some network filesystems — while APFS and ext4 store nanoseconds. Recorded in the docstring.
1 parent 0983d1b commit 96b04b8

5 files changed

Lines changed: 202 additions & 13 deletions

File tree

ā€Žsdpm/references/guides/animations.mdā€Ž

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,6 +994,8 @@ The build resolves both and checks the resolved slide, so a misspelled target is
994994
refused; it is refused at build rather than at save. If you want the earlier signal on an
995995
`override` slide, build it.
996996

997+
## Related guides
998+
997999
- `read_guides(["animation-craft"])` — whether to animate at all, how long an effect should
9981000
run, how to stagger a group, and what the published guidance on motion says. This guide
9991001
covers what is possible; that one covers what is worth doing.

ā€Žsdpm/sdpm/engine/builder/__init__.pyā€Ž

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -665,11 +665,19 @@ def _include_elements(path: str, _stamp: tuple[int, int]) -> tuple:
665665
``_stamp`` is the file's modification time and size, so an edited file is a
666666
different key rather than a stale hit. It is positional because
667667
:func:`functools.lru_cache` keys on the arguments it is given.
668+
669+
One limit worth knowing rather than working around: a rewrite that keeps
670+
the same size, within the filesystem's timestamp granularity, is the same
671+
key and returns the old content until the process restarts. That needs
672+
one-second timestamps — HFS+, FAT, some network filesystems — while APFS
673+
and ext4 store nanoseconds.
674+
675+
A read error is raised rather than cached, and :func:`expand_includes`
676+
turns it into a message naming the deck-relative ``src``: on the Remote
677+
server the resolved path is a materialised tmpdir, which tells the agent
678+
reading the error nothing.
668679
"""
669-
try:
670-
data = read_json(Path(path))
671-
except (json.JSONDecodeError, ValueError) as error:
672-
raise ValueError(f"Invalid JSON in include file {path}: {error}")
680+
data = read_json(Path(path))
673681
elements = data if isinstance(data, list) else data.get("elements", [])
674682
return tuple(elements)
675683

@@ -700,7 +708,14 @@ def expand_includes(elements, base_dir: Path) -> list:
700708
stat = include_path.stat()
701709
except OSError:
702710
continue
703-
included = _include_elements(str(include_path), (stat.st_mtime_ns, stat.st_size))
711+
try:
712+
included = _include_elements(
713+
str(include_path), (stat.st_mtime_ns, stat.st_size)
714+
)
715+
except (json.JSONDecodeError, ValueError) as error:
716+
# Named by `src`, the way the deck refers to it. The resolved path
717+
# is a materialised tmpdir on the Remote server.
718+
raise ValueError(f"Invalid JSON in include file {src}: {error}")
704719
# Copied, because the caller may edit what it gets back and the cache
705720
# hands the same objects to the next reader.
706721
expanded.extend(copy.deepcopy(element) for element in included)

ā€Žsdpm/sdpm/engine/timing/reader.pyā€Ž

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2272,10 +2272,16 @@ def _check_measured_timings(
22722272
eight of the gallery presets at some durations — sending decks sdpm
22732273
itself had just written to the raw fallback.
22742274
2275-
A millisecond of slack is allowed, and only where ``_scaled``'s own
2276-
docstring records that PowerPoint and this writer may legitimately
2277-
differ: an exact half, which PowerPoint's float precision splits both
2278-
ways. Anywhere else the match is exact.
2275+
The comparison accepts the values a writer can produce, and nothing
2276+
else. On an exact half ``_scaled``'s own docstring records that
2277+
PowerPoint and this writer may legitimately differ — PowerPoint's float
2278+
precision splits those both ways — so there are two. They are *not*
2279+
symmetric around the expected value: ``_scaled`` rounds a half up, so
2280+
the expected value is already the upper rounding and PowerPoint's
2281+
alternative is the lower one. Allowing ``abs(written - expected) <= 1``
2282+
instead also accepted the value one above, which neither writer emits:
2283+
`entrance.bounce` at 300 ms took a hand-edited ``@delay`` of 99 for the
2284+
98 it had written (650 Ɨ 300/2000 = 97.5) and wrote 98 back over it.
22792285
"""
22802286
from sdpm.engine.timing.writer import _scaled
22812287

@@ -2288,14 +2294,18 @@ def _check_measured_timings(
22882294
expected = source if attribute == "dur" else (
22892295
max(duration - 1, 0) if source > 0 else source
22902296
)
2291-
slack = 0
2297+
accepted = (expected,)
22922298
else:
22932299
expected = _scaled(source, ratio)
2294-
slack = 1 if (Fraction(source) * ratio).denominator == 2 else 0
2295-
if abs(written - expected) > slack:
2300+
accepted = (
2301+
(expected - 1, expected)
2302+
if (Fraction(source) * ratio).denominator == 2
2303+
else (expected,)
2304+
)
2305+
if written not in accepted:
22962306
raise _Unsupported(
22972307
f"{sequence} behavior {tag} @{attribute} {written} is not the measured "
2298-
f"{source} at this effect duration ({expected})"
2308+
f"{source} at this effect duration ({' or '.join(map(str, accepted))})"
22992309
)
23002310

23012311
def _check_bounce_mirror(

ā€Žtests/test_animation_import.pyā€Ž

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from __future__ import annotations
1414

1515
import json
16+
from fractions import Fraction
1617
from pathlib import Path
1718

1819
import pytest
@@ -1106,6 +1107,128 @@ def test_every_measured_preset_round_trips_at_this_duration(self, tmp_path, dura
11061107
)
11071108

11081109

1110+
class TestOnlyTheTwoRoundingsOfAHalfAreAccepted:
1111+
"""A scaled half has two legitimate values, and they are not symmetric.
1112+
1113+
`_scaled` rounds a half up, so the value it writes is the *upper* rounding
1114+
and PowerPoint's alternative is the lower one. Allowing
1115+
`abs(written - expected) <= 1` also accepted the value one above, which
1116+
neither writer emits — so a hand-edited `@delay` of 99 was taken for the 98
1117+
sdpm had written, and the next build put 98 back over it.
1118+
1119+
The three cases are the ones the review measured. Each `source Ɨ ratio` is
1120+
an exact half, which is the only place any slack applies at all.
1121+
"""
1122+
1123+
#: category, effect, duration, the value sdpm writes, element, attribute.
1124+
HALVES = [
1125+
("entrance", "bounce", 300, 98, "animScale", "delay"),
1126+
("entrance", "drop", 875, 137, "anim", "dur"),
1127+
("exit", "boomerang", 201, 101, "anim", "delay"),
1128+
]
1129+
1130+
def _retime(self, element, attribute, before, after):
1131+
def mutate(slide):
1132+
changed = 0
1133+
for node in slide.iter(f"{{{NS['p']}}}{element}"):
1134+
ctn = node.find(f"{{{NS['p']}}}cBhvr").find(f"{{{NS['p']}}}cTn")
1135+
if attribute == "dur":
1136+
target = ctn
1137+
else:
1138+
conditions = ctn.find(f"{{{NS['p']}}}stCondLst")
1139+
target = (
1140+
None if conditions is None
1141+
else conditions.find(f"{{{NS['p']}}}cond")
1142+
)
1143+
if target is None or target.get(attribute) != str(before):
1144+
continue
1145+
target.set(attribute, str(after))
1146+
changed += 1
1147+
assert changed, (
1148+
f"the fixture must carry p:{element}/@{attribute}={before}"
1149+
)
1150+
return mutate
1151+
1152+
def _read_at(self, tmp_path, case, offset):
1153+
category, effect, duration, written, element, attribute = case
1154+
package = _package(tmp_path, _slide(animations={
1155+
"mainSequence": [_effect(
1156+
preset={"category": category, "effect": effect},
1157+
timing={"durationMs": duration},
1158+
)],
1159+
"interactiveSequences": [],
1160+
}), name=f"{category}-{effect}-{written + offset}.pptx")
1161+
mutate = (
1162+
(lambda _slide: None) if offset == 0
1163+
else self._retime(element, attribute, written, written + offset)
1164+
)
1165+
return _read(_mutate(package, mutate))
1166+
1167+
@pytest.mark.parametrize("case", HALVES, ids=lambda c: f"{c[0]}.{c[1]}@{c[2]}")
1168+
def test_the_value_above_the_upper_rounding_is_refused(self, tmp_path, case):
1169+
motion = self._read_at(tmp_path, case, +1)
1170+
assert motion.animations is None, (
1171+
f"{case[3] + 1} is neither rounding of the product, so taking it for "
1172+
f"{case[3]} would write {case[3]} back over a hand edit"
1173+
)
1174+
assert motion.raw_timing is not None
1175+
1176+
@pytest.mark.parametrize("case", HALVES, ids=lambda c: f"{c[0]}.{c[1]}@{c[2]}")
1177+
def test_both_roundings_of_the_half_still_import(self, tmp_path, case):
1178+
"""The refusal must not cost the case the slack exists for.
1179+
1180+
PowerPoint's float precision splits an exact half both ways, so the
1181+
lower rounding is a file PowerPoint really writes.
1182+
"""
1183+
for offset in (-1, 0):
1184+
motion = self._read_at(tmp_path, case, offset)
1185+
assert motion.animations is not None, (
1186+
f"{case[3] + offset} is a rounding of the product: "
1187+
f"{motion.raw_timing.reasons[0] if motion.raw_timing else ''}"
1188+
)
1189+
1190+
def test_no_half_anywhere_in_the_catalogue_accepts_the_value_above(self, tmp_path):
1191+
"""The three cases above are named; this is every one of them.
1192+
1193+
Which timing lands on an exact half depends on the ratio, so the cases
1194+
cannot be enumerated by hand — the same reason the duration sweep
1195+
covers the whole catalogue. 64 locations across 97 presets at three
1196+
durations; 27 of them imported semantically before the fix.
1197+
"""
1198+
from sdpm.engine.timing.writer import _is_visibility_set, _scaled
1199+
1200+
leaked, checked = [], 0
1201+
for key in SCALABLE_MEASURED:
1202+
preset, measured = _measured_preset(key)
1203+
entry = next(item for item in CATALOG["guiItems"] if item["key"] == key)
1204+
for duration in (300, 875, 1234):
1205+
if duration == measured:
1206+
continue
1207+
ratio = Fraction(duration, measured)
1208+
for behavior in entry["ooxml"]["behaviors"]:
1209+
if _is_visibility_set(behavior):
1210+
continue
1211+
element = str(behavior.get("element", ""))[len("p:"):]
1212+
for attribute, field in (("dur", "durMs"), ("delay", "delayMs")):
1213+
source = behavior.get(field)
1214+
if source is None:
1215+
continue
1216+
if (Fraction(int(source)) * ratio).denominator != 2:
1217+
continue
1218+
checked += 1
1219+
written = _scaled(int(source), ratio)
1220+
case = (preset["category"], preset["effect"], duration,
1221+
written, element, attribute)
1222+
if self._read_at(tmp_path, case, +1).animations is not None:
1223+
leaked.append(f"{key}@{duration} p:{element}/@{attribute} "
1224+
f"{written} -> {written + 1}")
1225+
assert checked, "the catalogue must produce some exact halves to check"
1226+
assert not leaked, (
1227+
f"{len(leaked)} of {checked} half timings accepted a value neither "
1228+
f"writer produces: {leaked[:10]}"
1229+
)
1230+
1231+
11091232
class TestAMeasuredTimingMustBeAnInteger:
11101233
"""A recorded timing that is absent or non-numeric is a change, not a gap.
11111234

ā€Žtests/test_checks_includes.pyā€Ž

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,42 @@ def test_the_caller_may_edit_what_it_gets_back(self, tmp_path):
132132
first = expand_includes(elements, tmp_path)
133133
first[0]["id"] = "mutated"
134134
assert [e["id"] for e in expand_includes(elements, tmp_path)] == ["panel"]
135+
136+
def test_an_unreadable_file_is_named_the_way_the_deck_names_it(self, tmp_path):
137+
"""By `src`, not by the resolved path.
138+
139+
On the Remote server the resolved path is a materialised tmpdir, which
140+
tells the agent reading the error nothing. Caching the read moved the
141+
message into the cached function, where only the absolute path is in
142+
scope, so it is raised at the call site instead.
143+
"""
144+
import pytest
145+
146+
from sdpm.engine.builder import expand_includes
147+
148+
deck = tmp_path / "deck"
149+
(deck / "includes").mkdir(parents=True)
150+
(deck / "includes" / "panel.json").write_text("{not json", encoding="utf-8")
151+
152+
with pytest.raises(ValueError) as caught:
153+
expand_includes([{"type": "include", "src": "includes/panel.json"}], deck)
154+
message = str(caught.value)
155+
assert "includes/panel.json" in message, message
156+
assert str(deck) not in message, (
157+
f"the resolved path is a tmpdir on Remote: {message}"
158+
)
159+
160+
def test_a_read_error_is_not_cached(self, tmp_path):
161+
"""So fixing the file and rebuilding works without a restart."""
162+
import pytest
163+
164+
from sdpm.engine.builder import expand_includes
165+
166+
inc = tmp_path / "panel.json"
167+
inc.write_text("{not json", encoding="utf-8")
168+
elements = [{"type": "include", "src": "panel.json"}]
169+
with pytest.raises(ValueError):
170+
expand_includes(elements, tmp_path)
171+
172+
inc.write_text(json.dumps([{"id": "panel", "type": "shape"}]), encoding="utf-8")
173+
assert [e["id"] for e in expand_includes(elements, tmp_path)] == ["panel"]

0 commit comments

Comments
Ā (0)