Files
ssw-mvp/nax/tests/test_mock.py
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

493 lines
20 KiB
Python

"""双阶段执行:dry_run 模式、PlainVault 明文快路、Dataset mock 数据。"""
import numpy as np
import pandas as pd
import pytest
import nax
from nax.device.plain import PlainVault
from nax.ml import FedAvg, VerticalLogisticRegression, metrics
from helpers import rand
# --------------------------------------------------------------------------- #
def _both(fn, sites=("alice", "bob")):
"""同一段计算分别跑真实 MPC 与明文快路,返回 ``(real, mock)``。"""
real = fn(nax.vault(list(sites), seed=5))
with nax.dry_run():
mock = fn(nax.vault(list(sites), seed=5))
return real, mock
@pytest.fixture
def two_party_debug():
"""放宽守卫的本地两方集群,仅供需要取回明文(试跑 mock / 真实)数据的单测。
试跑数据刻意仍打 ``PLAIN`` 标签,但单测要核对它「不像真实数据」必须能
把它读出来。这里打开 ``allow_plain_fetch`` 相当于「本地调试」开关
(见 guard 文档),不影响守卫在正式测试里的有效性——守卫相关用例仍用
默认的 ``two_party`` 夹具,明文取回依旧被拦。
"""
c = nax.init(["alice", "bob"], backend="local", seed=42, allow_plain_fetch=True)
yield c
nax.shutdown()
class TestModeSwitch:
def test_default_is_real(self, two_party):
assert nax.is_dry_run() is False
assert type(nax.vault(["alice", "bob"])).__name__ == "Vault"
def test_dry_run_swaps_vault(self, two_party):
with nax.dry_run():
assert nax.is_dry_run() is True
box = nax.vault(["alice", "bob"])
assert isinstance(box, PlainVault)
assert box.is_mock is True
assert nax.is_dry_run() is False
def test_direct_construction_also_swaps(self, two_party):
"""``Vault(...)`` 也要被拦住,否则试跑会漏回真实 MPC。"""
with nax.dry_run():
assert isinstance(nax.Vault(["alice", "bob"]), PlainVault)
def test_nesting_restores(self, two_party):
with nax.dry_run():
with nax.real_run():
assert nax.is_dry_run() is False
assert type(nax.vault(["alice", "bob"])).__name__ == "Vault"
assert nax.is_dry_run() is True
def test_exception_restores_mode(self, two_party):
with pytest.raises(RuntimeError):
with nax.dry_run():
raise RuntimeError("boom")
assert nax.is_dry_run() is False
def test_custom_host(self, two_party):
with nax.dry_run(host="bob"):
assert nax.vault(["alice", "bob"]).host == "bob"
def test_unknown_host_rejected(self, two_party):
with nax.dry_run(host="nobody"):
with pytest.raises(nax.UnknownSite):
nax.vault(["alice", "bob"])
class TestSafetyValve:
def test_plain_vault_refused_outside_dry_run(self, two_party):
"""明文设备不得在正式路径上被造出来——这是整套机制的底线。"""
with pytest.raises(nax.PrivacyViolation, match="dry_run"):
PlainVault(["alice", "bob"])
def test_mock_marker_present(self, two_party):
with nax.dry_run():
assert nax.vault(["alice", "bob"]).is_mock is True
assert "MOCK" in repr(nax.vault(["alice", "bob"]))
def test_cross_vault_operands_rejected(self, two_party):
with nax.dry_run():
a, b = nax.vault(["alice", "bob"]), nax.vault(["alice", "bob"])
x, y = a.share(np.ones(3), owner="alice"), b.share(np.ones(3), owner="alice")
with pytest.raises(nax.ProtocolError):
_ = x + y
class TestNumericAgreement:
"""明文快路必须与真实密文在定点精度内一致。"""
TOL = 1e-4
@pytest.mark.parametrize(
"op",
[
lambda a, b: a + b,
lambda a, b: a - b,
lambda a, b: a * b,
lambda a, b: -a,
lambda a, b: a @ b,
lambda a, b: a.sum(),
lambda a, b: a.sum(axis=0),
lambda a, b: a.mean(axis=1),
lambda a, b: a.T,
lambda a, b: a.square(),
lambda a, b: a.reshape(9),
lambda a, b: a * 2.5,
lambda a, b: a + 1.0,
],
)
def test_arithmetic(self, two_party, op):
x, y = rand((3, 3), seed=1, scale=2.0), rand((3, 3), seed=2, scale=2.0)
def run(box):
a = box.share(x, owner="alice")
b = box.share(y, owner="bob")
return op(a, b).reveal(to="alice").fetch()
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
@pytest.mark.parametrize("op", ["lt", "le", "gt", "ge", "eq", "ne"])
def test_comparison(self, two_party, op):
x = np.array([-1.0, 0.0, 1.0, 2.0])
y = np.array([1.0, 0.0, -1.0, 2.0])
def run(box):
a, b = box.share(x, owner="alice"), box.share(y, owner="bob")
return getattr(a, op)(b).reveal(to="alice").fetch()
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
def test_sigmoid_matches_including_approximation(self, two_party):
"""明文快路要复用同一套多项式逼近,而不是偷偷用真 sigmoid。"""
x = np.linspace(-5.0, 5.0, 11)
def run(box):
return box.share(x, owner="alice").sigmoid().reveal(to="alice").fetch()
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
# 与真 sigmoid 存在可观测的逼近误差,证明走的确实是多项式
true_sig = 1.0 / (1.0 + np.exp(-x))
assert np.abs(mock - true_sig).max() > 1e-3
def test_select_and_minmax(self, two_party):
x, y = rand((6,), seed=3, scale=2.0), rand((6,), seed=4, scale=2.0)
def run(box):
a, b = box.share(x, owner="alice"), box.share(y, owner="bob")
return np.concatenate([
a.max(b).reveal(to="alice").fetch(),
a.min(b).reveal(to="alice").fetch(),
a.lt(b).select(a, b).reveal(to="alice").fetch(),
])
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
def test_argmax_returns_same_index(self, two_party):
x = rand((5, 3), seed=8, scale=3.0)
def run(box):
val, idx = box.share(x, owner="alice").argmax(axis=0)
return np.concatenate([val.reveal(to="alice").fetch().ravel(),
np.asarray(idx, dtype=np.float64).ravel()])
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
def test_concat(self, two_party):
x, y = rand((4, 2), seed=5), rand((4, 3), seed=6)
def run(box):
a, b = box.share(x, owner="alice"), box.share(y, owner="bob")
return box.concat([a, b], axis=1).reveal(to="alice").fetch()
real, mock = _both(run)
assert np.allclose(real, mock, atol=self.TOL)
assert mock.shape == (4, 5)
class TestFixedPointEmulation:
def test_quantization_is_emulated_by_default(self, two_party):
"""默认模拟定点,所以结果不是干净的 float64。"""
v = 1.0 / 3.0
with nax.dry_run():
box = nax.vault(["alice", "bob"])
got = float((box.share(np.array([v]), owner="alice") * 1.0)
.reveal(to="alice").fetch()[0])
assert got != v # 被量化过
assert abs(got - v) < 2 ** -17 # 但误差在 fxp 精度内
def test_can_be_disabled(self, two_party):
v = 1.0 / 3.0
with nax.dry_run(emulate_fixed_point=False):
box = nax.vault(["alice", "bob"])
got = float((box.share(np.array([v]), owner="alice") * 1.0)
.reveal(to="alice").fetch()[0])
assert got == v # 纯 float64,没有量化
def test_overflow_is_reported(self, two_party):
"""真实路径会静默回绕,试跑要当场报错。"""
big = np.array([2.0 ** 40])
with nax.dry_run():
box = nax.vault(["alice", "bob"])
a = box.share(big, owner="alice")
with pytest.raises(OverflowError, match="试跑发现定点溢出"):
_ = (a * a).reveal(to="alice").fetch()
class TestHealthChecks:
"""明文能看见数值,因此可以断言密文断言不了的东西。"""
def test_rsqrt_divergence_is_caught(self, two_party):
# 真实密文对 x=9 会静默返回约 2.2e8;试跑必须拦下来
with nax.dry_run():
box = nax.vault(["alice", "bob"])
a = box.share(np.array([9.0]), owner="alice")
with pytest.raises(ValueError, match="收敛域"):
box.rsqrt(a)
def test_rsqrt_sign_flip_is_caught(self, two_party):
"""x=4 时真实密文返回 −0.5(符号翻转),比发散更难发现。"""
real_box = nax.vault(["alice", "bob"])
got = float(real_box.rsqrt(real_box.share(np.array([4.0]), owner="alice"))
.reveal(to="alice").fetch()[0])
assert got < 0 # 真实路径确实悄悄给了负数
with nax.dry_run():
box = nax.vault(["alice", "bob"])
with pytest.raises(ValueError, match="收敛域"):
box.rsqrt(box.share(np.array([4.0]), owner="alice"))
def test_sigmoid_out_of_range_is_caught(self, two_party):
with nax.dry_run():
box = nax.vault(["alice", "bob"])
a = box.share(np.array([20.0]), owner="alice") # 远超 ±6 拟合区间
with pytest.raises(ValueError, match="sigmoid"):
a.sigmoid()
def test_strict_can_be_turned_off(self, two_party):
with nax.dry_run():
box = nax.device.plain_vault(["alice", "bob"], strict=False)
out = box.rsqrt(box.share(np.array([9.0]), owner="alice"))
assert out.shape == (1,) # 不再拦截,行为与密文一致地跑偏
def test_healthy_input_passes(self, two_party):
with nax.dry_run():
box = nax.vault(["alice", "bob"])
got = box.sqrt(box.share(np.array([0.25, 1.0, 2.0]), owner="alice"))
out = got.reveal(to="alice").fetch()
assert np.allclose(out, np.sqrt([0.25, 1.0, 2.0]), atol=1e-3)
class TestDataset:
@pytest.fixture
def real_df(self):
rng = np.random.default_rng(0)
return pd.DataFrame({
"uid": [f"u{i}" for i in range(40)],
"age": rng.integers(20, 70, 40),
"score": rng.normal(600.0, 50.0, 40),
"tag": ["x"] * 20 + ["y"] * 20,
})
def test_mock_does_not_leak_real_values(self, two_party_debug, real_df):
ds = nax.dataset("alice", real=real_df, keys=["uid"], seed=1)
real = ds.load_real().fetch()
mock = ds.load_mock().fetch()
assert list(mock.columns) == list(real.columns)
assert len(mock) == len(real)
# schema 档只保留列名与 dtype,数值必须无关
assert not np.array_equal(real["age"].to_numpy(), mock["age"].to_numpy())
assert set(real["uid"]).isdisjoint(set(mock["uid"]))
def test_load_follows_mode(self, two_party, real_df):
ds = nax.dataset("alice", real=real_df, keys=["uid"], seed=1)
assert ds.load() is ds.load_real()
with nax.dry_run():
assert ds.load() is ds.load_mock()
def test_mock_keys_intersect_across_sites(self, two_party_debug, real_df):
"""各方 mock 的主键必须对得上,否则试跑的 PSI 会得到空表。"""
a = nax.dataset("alice", real=real_df, keys=["uid"], seed=1, overlap=0.8)
b = nax.dataset("bob", real=real_df, keys=["uid"], seed=2, overlap=0.8)
ka = set(a.load_mock().fetch()["uid"])
kb = set(b.load_mock().fetch()["uid"])
assert len(ka & kb) == len(ka) # 同 overlap、同行数 ⇒ 完全重合
assert all(k.startswith("mock_id_") for k in ka)
def test_overlap_controls_intersection(self, two_party_debug, real_df):
a = nax.dataset("alice", real=real_df, keys=["uid"], overlap=1.0)
b = nax.dataset("bob", real=real_df, keys=["uid"], overlap=0.5)
ka = set(a.load_mock().fetch()["uid"])
kb = set(b.load_mock().fetch()["uid"])
assert 0 < len(ka & kb) < len(ka)
def test_psi_works_on_mock(self, two_party, real_df):
a = nax.dataset("alice", real=real_df, keys=["uid"], seed=1)
b = nax.dataset("bob", real=real_df, keys=["uid"], seed=2)
with nax.dry_run():
vf = nax.data.VFrame.from_datasets({"alice": a, "bob": b})
aligned = vf.psi_align("uid")
assert aligned.count() == 40
def test_rows_override(self, two_party_debug, real_df):
ds = nax.dataset("alice", real=real_df, keys=["uid"], rows=7)
assert len(ds.load_mock().fetch()) == 7
def test_user_supplied_mock(self, two_party_debug, real_df):
fake = pd.DataFrame({"uid": ["a", "b"], "age": [1, 2],
"score": [3.0, 4.0], "tag": ["x", "y"]})
ds = nax.dataset("alice", real=real_df, mock=fake)
got = ds.load_mock().fetch()
assert got["age"].tolist() == [1, 2]
def test_callable_source(self, two_party_debug, real_df):
ds = nax.dataset("alice", real=lambda: real_df, keys=["uid"])
assert len(ds.load_real().fetch()) == 40
def test_stats_mode_needs_bounds(self, two_party, real_df):
with pytest.raises(nax.ProtocolError, match="bounds"):
nax.dataset("alice", real=real_df, mock="stats")
def test_stats_mode_applies_dp(self, two_party_debug, real_df):
ds = nax.dataset(
"alice", real=real_df, mock="stats", keys=["uid"],
bounds={"age": (18, 80), "score": (300, 900)}, epsilon=2.0, seed=3,
)
mock = ds.load_mock().fetch()
# 分布量级贴近,但不是原值
assert 18 <= mock["age"].min() and mock["age"].max() <= 80
assert abs(mock["score"].mean() - real_df["score"].mean()) < 60
assert not np.array_equal(mock["score"].to_numpy(), real_df["score"].to_numpy())
def test_stats_bounds_must_exist(self, two_party, real_df):
ds = nax.dataset("alice", real=real_df, mock="stats",
bounds={"nope": (0, 1)})
with pytest.raises(nax.ProtocolError, match="不存在"):
ds.load_mock()
def test_bad_overlap_rejected(self, two_party, real_df):
with pytest.raises(nax.ProtocolError, match="overlap"):
nax.dataset("alice", real=real_df, overlap=1.5)
def test_frame_rejects_non_dataset(self, two_party, real_df):
with pytest.raises(nax.ProtocolError, match="Dataset"):
nax.data.VFrame.from_datasets({"alice": real_df})
def test_frame_rejects_site_mismatch(self, two_party, real_df):
ds = nax.dataset("alice", real=real_df)
with pytest.raises(nax.ProtocolError, match="不一致"):
nax.data.VFrame.from_datasets({"bob": ds})
class TestGuardStillApplies:
"""试跑不是安全后门——守卫与审计必须照常工作。"""
def test_mock_data_is_still_plain_labelled(self, two_party):
df = pd.DataFrame({"a": [1.0, 2.0]})
ds = nax.dataset("alice", real=df)
with nax.dry_run():
ref = ds.load()
assert ref.handle.label == nax.Label.PLAIN
with pytest.raises(nax.PrivacyViolation):
ref.fetch() # 明文照样不许出域
def test_cross_site_plain_still_blocked(self, two_party):
df = pd.DataFrame({"a": [1.0, 2.0]})
ds = nax.dataset("alice", real=df)
with nax.dry_run():
with pytest.raises(nax.PrivacyViolation):
ds.load().to("bob")
def test_reveal_is_audited(self, two_party):
with nax.dry_run():
box = nax.vault(["alice", "bob"])
box.share(np.ones(2), owner="alice").reveal(to="alice")
events = nax.audit().filter(kind="reveal")
assert len(events) == 1
assert events[0].get("mock") is True # 审计里能看出这是试跑
class TestSecureAggregatorMock:
def test_mask_mode_degrades(self, cluster):
from nax.ml.aggregate import SecureAggregator
vals = {s: nax.site(s).put(np.array([float(i + 1)] * 3))
for i, s in enumerate(["alice", "bob", "carol"])}
with nax.dry_run():
agg = SecureAggregator(["alice", "bob", "carol"], "alice")
assert agg.mock is True
got = agg.sum(vals).fetch()
assert np.allclose(got, [6.0, 6.0, 6.0])
def test_paillier_skips_keygen(self, cluster):
from nax.ml.aggregate import SecureAggregator
with nax.dry_run():
agg = SecureAggregator(["alice", "bob", "carol"], "alice",
mode="paillier", key_site="bob")
assert not hasattr(agg, "_priv") # 1024 位密钥根本没生成
def test_paillier_config_error_still_raised(self, cluster):
"""配置错误必须在试跑阶段就暴露,而不是等上生产。"""
from nax.ml.aggregate import SecureAggregator
with nax.dry_run():
with pytest.raises(nax.ProtocolError, match="密钥方"):
SecureAggregator(["alice", "bob"], "alice",
mode="paillier", key_site="alice")
def test_labels_match_real_path(self, cluster):
"""标签轨迹要与真实一致,否则守卫就被绕过了。"""
from nax.ml.aggregate import SecureAggregator
vals = {s: nax.site(s).put(np.ones(2)) for s in ["alice", "bob", "carol"]}
with nax.dry_run():
SecureAggregator(["alice", "bob", "carol"], "alice").sum(vals)
ops = [e.get("op", "") for e in nax.audit().events]
assert any("secure_sum/mask#mock" in o for o in ops)
class TestEndToEnd:
def test_vertical_lr_matches(self, two_party):
rng = np.random.default_rng(7)
x = rng.normal(size=(120, 4))
x = (x - x.mean(0)) / x.std(0)
y = (rng.random(120) < 1 / (1 + np.exp(-(x @ rng.normal(size=4))))).astype(float)
def run(box):
xs = box.concat([
box.share(nax.site("alice").put(x[:, :2])),
box.share(nax.site("bob").put(x[:, 2:])),
], axis=1)
ys = box.share(nax.site("bob").put(y.reshape(-1, 1)))
m = VerticalLogisticRegression(box, lr=0.5, epochs=8).fit(xs, ys)
return m.weights(to="bob").fetch().reshape(-1)
real, mock = _both(run)
assert np.abs(real - mock).max() < 1e-3
def test_fedavg_matches(self, cluster):
rng = np.random.default_rng(0)
xs, ys = {}, {}
for s in ["alice", "bob", "carol"]:
xi = rng.normal(size=(60, 3))
yi = (xi @ np.array([1.0, -0.5, 0.3]) > 0).astype(float)
xs[s], ys[s] = nax.site(s).put(xi), nax.site(s).put(yi)
def run():
m = FedAvg(clients=["alice", "bob", "carol"], aggregator="alice")
return m.fit(xs, ys, n_features=3, rounds=3, lr=0.3).history
real = run()
with nax.dry_run():
mock = run()
assert abs(real.loss[-1] - mock.loss[-1]) < 1e-6
def test_binning_matches(self, two_party):
rng = np.random.default_rng(3)
n = 200
feat = pd.DataFrame({"uid": [f"u{i}" for i in range(n)],
"age": rng.integers(20, 70, n).astype(float)})
lab = pd.DataFrame({"uid": [f"u{i}" for i in range(n)],
"y": (rng.random(n) < 0.4).astype(float)})
def run():
from nax.ml import hetero_binning
box = nax.vault(["alice", "bob"])
parts = {"alice": nax.site("alice").put(feat),
"bob": nax.site("bob").put(lab)}
vf = nax.data.VFrame(parts)
rep = hetero_binning(box, vf, feature_site="alice", label_site="bob",
label="y", features=["age"], bins=4)
return rep.iv["age"]
real = run()
with nax.dry_run():
mock = run()
assert abs(real - mock) < 1e-6