Files
orisys-app/apps/studio/tests/test_scene3d_protected_package.py
T
ykcheungab ef487098c9 feat(studio-3d): 限速、真实耗时统计、无位移复用资产几何,以及保护包密钥注入(阶段 9 上半)
- What:
  1. **显示限速真的生效**(R5):`ThreeDCoordinator.tick()` 用注入的单调时钟与
     `display_period_s() = 1/max_fps` 限制**合成启动**频率(窗口定时器仍是 16 ms,但"显示帧率"是给操作者的
     承诺,不是定时器的描述);声明边界(activate/begin_session/show_rest/隐藏)把预算清零,所以按下开始后的
     第一帧立刻合成。生产者侧改为**按需**跳过:`Scene3DView.submit_packet()` 在
     `coordinator.has_pending_frame()`(mailbox 里已有一帧等待)时不再构造快照——那是 O(H×W) 的拷贝,
     而 mailbox 只保留最新一帧,两次拷贝里必然丢一个;被跳过的数量计入新的 `skipped_producer`,
     与"显示跳帧"分开。**不丢任何本该显示的帧**(等待中的那一帧仍在)。
  2. **真实统计**:`RenderFrame.compose_ms`(composer 在构造帧之前测量并写入,不再读会被下一任务改写的
     `last_stats`);`GLRenderer` 的绘制计数改名为 `paint_calls`,`RenderStats.displayed_frames` 由
     **widget 按帧身份**统计(相机旋转/色标改动只是重画,不再是"多显示了一帧");`render_totals()` 增
     `compose_ms`/`latency_ms`(合成开始→被接受的单调耗时)/`paint_calls`/`skipped_producer`,并且
     `shown`/`compose_ms` 改从 widget 读(无 GL 的机器也能报告,之前只有画过才有数)。
  3. **无位移时复用资产几何**(R5 建议):`SceneComposer` 缓存 `asset_hash → (positions, normals)`;
     变形时照旧从形变后的位置重算法线,不变形时直接用资产自己的(只读、零拷贝)数组。20k 顶点实测:
     compose p50 **6.15 ms → 1.03 ms**(法线段 4.9 ms → 0.0001 ms,剩余是采样 1.01 ms);
     真实发布包(1032 顶点)compose p50 **0.50 ms → 0.17 ms**。
  4. **保护包密钥注入**(R4):新增 `scene3d/keys.py`——从 preference 读取
     `scene3d_verify_key`(验签公钥 PEM)/`scene3d_content_key_file` + `scene3d_content_key_id`
     (内容密钥,经 `protect.load_key_file`)/`scene3d_require_signature`(发布模式,拒绝无签名包),
     组装成 `SceneKeys` 交给 `SceneAssetLoader` → `load_package` → `PackagedAssetLoader.load(keys=…,
     verify_key_pem=…)`;`AppWindow._sync_3d_source()` 解析它并 `Mesh3dPanel.set_keys()`。
     缺失/不可读的密钥是**状态而不是崩溃**(`describe()` 里带原因),密钥材料永不进日志;
     `Mesh3dPanel.describe()` 的 scene 块记录 `keys`(布尔 + 路径)。
- Why: 审查报告 R5(`max_fps` 只被存储与显示、`draw()` 硬编码 `compose_ms=0.0`、`_displayed_frames` 把
  重画也算新帧、`SceneComposer.last_stats` 被显示链路完全未读)与 R4(底层支持签名/加密包,Studio 加载
  入口却从不传验签公钥与 KeyProvider,合法保护包打不开,只能发明文包或关掉校验)。R5 的另一半是
  "当前只有曲面着色、没有 displacement 时,composer 仍每帧重算法线并重新打包位置"——缓存后 20k 顶点
  降低到六分之一。
- Verification:
  · `test_scene3d_coordinator.py` +6:15 fps 的假时钟下 1.32 s 内只启动约 20 次合成(60 fps 对照 ≥55 次)、
  `display_period_s()` 跟随设置、结果延迟是真实单调差值、`has_pending_frame()` 随 mailbox 变化;
  `test_scene3d_live.py` +3:无位移时发布帧直接**就是**资产自己的(只读)数组、force_deform 但仍无位移时
  给出 `field_unavailable` 诊断、有标定位移时仍重算、`compose_ms` 属于该帧且不被下一次合成改写;
  `test_scene3d_view.py` +2:等待中的帧让生产者跳过第二个快照且取出后立即恢复、`render_totals()` 的
  compose 成本与延迟是真实值;新增 `test_scene3d_protected_package.py` 7 项:Studio 入口打开签名包、
  用 preference 里的内容密钥打开加密包、缺验签公钥 → `asset_auth_failed`、密钥文件缺失/无 key id →
  状态而非崩溃、发布模式拒绝无签名包而开发模式接受、`SceneAssetLoader` 把密钥交给 worker、面板携带密钥。
  · 全量:shared+apps 同一次运行 **588 项 0 失败 15 跳过**;真 GL 冒烟(`QT_QPA_PLATFORM=windows`)
  **14 项 0 失败**;ui_check 587 项 0 失败;locale_check 0 缺失。
  · 顺带修掉两个**既有的顺序依赖**真 GL 用例(不是本次引入:在上一提交上单跑同样失败):
  `test_the_producer_side_never_waits_for_the_gpu` 的收尾没有排空 mailbox(留下的一帧会被下一个测试
  上传),`test_an_automatic_colour_scale_follows_the_frame` 在渲染之前就断言"范围来自本帧",
  且用"不同颜色数"当自动量程的代理(对可见面积敏感)。现在前者排空并断言排空完成,后者先渲染再断言,
  判据改为**平均亮度**(固定 0..1000 把 3..7 压进 LUT 最暗的一小段,自动量程铺满整条色带)。
  · 性能报告(`.repro/perf-cpu-*-after-9.json`,`bench_scene.py --cpu-only`):合成 p50
  合成 poc 0.016 ms / 20k 顶点 1.03 ms / 真实包 0.17 ms;对比已提交的 `perf-report-windows-dev.json`
  (20k 6.15 ms、真实包 0.50 ms)。
- Not in this change: **画布布局第二批**(2D/3D 页签容器、参数抽屉、窄窗口回退、诊断抽屉)与曲线量程开关
  仍未做;阶段 9 的门禁部分(`soak_scene.py --minutes 120` GUI 模式、Jetson Orin Nano 与 QCS6490 上的
  `probe_gl/bench_scene/soak_scene` 报告)需要长时间运行与板卡,本轮未跑,结论不写"通过";
  签名私钥仍只在构建机(本提交只引入"读"的一半)。
2026-09-14 21:52:02 +08:00

229 lines
8.8 KiB
Python

"""Stage 9 acceptance: a protected scene package, opened from the application.
The container could always read a signed or sealed package, but the application never
passed a verification key or a content-key provider, so a legitimate protected release
was refused with "this package is signed; a verification key is required" — and the only
ways to run it were to ship a plain package or to disable the check. These tests are
about the *wiring*: preferences → ``SceneKeys`` → the loader the pane actually uses.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from orisys_app_shared.scene3d import protect, synthetic
from orisys_app_shared.scene3d.contracts import ExpectedGeometry, ThreeDError
from orisys_app_shared.scene3d.package import write_package
from orisys_studio.scene3d.asset_source import SceneSource, load_package
from orisys_studio.scene3d.keys import (
PREF_CONTENT_KEY_FILE,
PREF_CONTENT_KEY_ID,
PREF_REQUIRE_SIGNATURE,
PREF_VERIFY_KEY,
resolve_scene_keys,
)
KEY_ID = "finger-display"
CONTENT_KEY_HEX = "11" * 32
def _expected(scene) -> ExpectedGeometry:
return ExpectedGeometry(
"finger", "", scene.geometry_id, scene.field_domain_id, scene.shape_hw
)
def _keys_and_paths(tmp_path: Path):
"""A signing key pair and a content key file, as a release build would have."""
private = protect.generate_signing_key()
public = protect.public_key_pem(private)
verify_path = tmp_path / "verify.pem"
verify_path.write_bytes(public)
key_path = tmp_path / "content.key"
key_path.write_text(CONTENT_KEY_HEX + "\n", encoding="utf-8")
provider = protect.MappingKeyProvider({KEY_ID: CONTENT_KEY_HEX})
return private, public, verify_path, key_path, provider
def _write_signed(tmp_path: Path, scene, *, sealed: bool):
private, public, verify_path, key_path, provider = _keys_and_paths(tmp_path)
from orisys_app_shared.scene3d.contracts import Sealing
target = tmp_path / ("sealed.oryscene" if sealed else "signed.oryscene")
write_package(
scene,
target,
sealing=Sealing(
key_id=KEY_ID if sealed else "",
provider=provider if sealed else None,
signing_key_pem=private,
signing_key_reference="stage-9",
verify_key_pem=public,
),
)
return target, verify_path, key_path
def _source(path: Path) -> SceneSource:
return SceneSource(path=path, kind="package", directory=path.parent)
def test_a_signed_package_opens_from_the_application(tmp_path):
"""The review's R4: the library could read it; the application could not.
With the verification key resolved from the preferences, the pane's own
``load_package`` accepts the package and the scene comes out intact.
"""
scene = synthetic.poc_scene()
package, verify_path, _key_path = _write_signed(tmp_path, scene, sealed=False)
keys = resolve_scene_keys({PREF_VERIFY_KEY: str(verify_path)})
assert keys.verify_key_pem is not None
assert keys.describe()["verify_key"] is True
assets = load_package(_source(package), _expected(scene), keys)
assert assets.geometry_id == scene.geometry_id
# The manifest's own hash, recomputed when the package was written: the synthetic
# scene's ``asset_hash`` is a placeholder until it goes through ``write_package``.
assert len(assets.asset_hash) == 64
def test_a_sealed_package_opens_with_the_content_key_from_the_preferences(tmp_path):
scene = synthetic.poc_scene()
package, verify_path, key_path = _write_signed(tmp_path, scene, sealed=True)
keys = resolve_scene_keys(
{
PREF_VERIFY_KEY: str(verify_path),
PREF_CONTENT_KEY_FILE: str(key_path),
PREF_CONTENT_KEY_ID: KEY_ID,
}
)
assert keys.provider is not None
described = keys.describe()
assert described["content_key"] is True
assert described["content_key_id"] == KEY_ID
# The description carries paths and ids, never key material.
assert CONTENT_KEY_HEX not in json.dumps(described)
assert keys.verify_key_pem is not None
assert CONTENT_KEY_HEX.encode() not in keys.verify_key_pem
assets = load_package(_source(package), _expected(scene), keys)
assert assets.geometry_id == scene.geometry_id
def test_without_the_verification_key_a_signed_package_is_refused(tmp_path):
"""Not a silent fallback to plain: the refusal names what is missing."""
scene = synthetic.poc_scene()
package, _verify_path, _key_path = _write_signed(tmp_path, scene, sealed=False)
keys = resolve_scene_keys({})
with pytest.raises(ThreeDError) as excinfo:
load_package(_source(package), _expected(scene), keys)
assert excinfo.value.diagnostic.code == "asset_auth_failed"
assert "verification key" in excinfo.value.diagnostic.message
def test_a_missing_or_unreadable_key_file_is_a_state_not_a_crash(tmp_path):
"""The 2D application must start whatever the key configuration looks like."""
keys = resolve_scene_keys(
{
PREF_VERIFY_KEY: str(tmp_path / "gone.pem"),
PREF_CONTENT_KEY_FILE: str(tmp_path / "gone.key"),
PREF_CONTENT_KEY_ID: KEY_ID,
}
)
assert keys.verify_key_pem is None and keys.provider is None
described = keys.describe()
assert described["verify_key_error"] == "missing"
assert described["content_key_error"] == "missing"
# A key file without a key id is not usable either, and says which half is absent.
key_path = tmp_path / "content.key"
key_path.write_text(CONTENT_KEY_HEX, encoding="utf-8")
keys = resolve_scene_keys({PREF_CONTENT_KEY_FILE: str(key_path)})
assert keys.provider is None
assert keys.describe()["content_key_error"] == "no key id configured"
def test_release_mode_refuses_an_unsigned_package(tmp_path):
"""The gate that replaces "ask the engineer to sign it"."""
scene = synthetic.poc_scene()
plain = tmp_path / "plain.oryscene"
write_package(scene, plain)
release = resolve_scene_keys({PREF_REQUIRE_SIGNATURE: True})
assert release.require_signature is True
with pytest.raises(ThreeDError) as excinfo:
load_package(_source(plain), _expected(scene), release)
assert excinfo.value.diagnostic.code == "asset_auth_failed"
assert "requires signed scene packages" in excinfo.value.diagnostic.message
# The same package is fine in a development build (and the shipped engineering
# package is exactly this case).
dev = resolve_scene_keys({})
assert load_package(_source(plain), _expected(scene), dev).geometry_id == scene.geometry_id
class _InlineExecutor:
"""Runs submitted work immediately: the loader's path without a thread."""
def submit(self, function, *args, **kwargs):
from concurrent.futures import Future
future: Future = Future()
try:
future.set_result(function(*args, **kwargs))
except BaseException as exc: # noqa: BLE001 - mirrored into the future
future.set_exception(exc)
return future
def shutdown(self, wait: bool = True) -> None: # noqa: ARG002 - executor contract
return None
def test_the_scene_loader_passes_the_keys_to_its_worker(qt_app, tmp_path):
"""The pane's loader is where the wiring has to happen, not just ``load_package``."""
from orisys_studio.scene3d.asset_source import SceneAssetLoader
scene = synthetic.poc_scene()
package, verify_path, _key_path = _write_signed(tmp_path, scene, sealed=False)
keys = resolve_scene_keys({PREF_VERIFY_KEY: str(verify_path)})
loader = SceneAssetLoader()
loader._executor = _InlineExecutor()
loaded: list = []
failures: list = []
loader.loaded.connect(
lambda assets, description, request_id, device: loaded.append(assets)
)
loader.failed.connect(lambda item, request_id: failures.append(item))
try:
loader.load(_source(package), _expected(scene), keys=keys)
assert not failures, [item.message for item in failures]
assert loaded and loaded[0].geometry_id == scene.geometry_id
finally:
loader.close()
# Without them the same file is refused, and the loader reports it rather than
# raising into the GUI thread.
loader = SceneAssetLoader()
loader._executor = _InlineExecutor()
failures = []
loader.failed.connect(lambda item, request_id: failures.append(item))
try:
loader.load(_source(package), _expected(scene), keys=resolve_scene_keys({}))
assert failures and failures[0].code == "asset_auth_failed"
finally:
loader.close()
def test_the_pane_carries_the_keys_into_its_loader(qt_app):
from orisys_studio.ui.mesh3d_panel import Mesh3dPanel
panel = Mesh3dPanel()
keys = resolve_scene_keys({})
assert panel.keys() is None
panel.set_keys(keys)
assert panel.keys() is keys