跳转至

ADR-011:Python 真实性证明与 Mock 消除

状态

提议(紧急)

日期

2026-02-28

背景

可信度问题

WiFi-DensePose Python 代码库包含真实且数学上可靠的信号处理(FFT、相位解卷绕、多普勒提取、相关特征),同时也存在会严重损害可信度的 mock/占位代码。外部审查者如果在默认执行流程中遇到任何 mock 路径,都会认为整个系统是合成的。这不是技术问题——它是一个具有技术根源的认知问题。

具体 Mock/占位代码清单

以下代码路径会在默认配置下生成虚假数据,或者容易被误认为表示虚假功能:

严重级别(在默认路径上生成虚假输出)

文件 行号 问题 影响
archive/v1/src/core/csi_processor.py 390 doppler_shift = np.random.rand(10) # Placeholder 真实特征提取器返回随机多普勒——摧毁整个特征流水线的可信度
archive/v1/src/hardware/csi_extractor.py 83-84 CSI 提取回退路径中的 amplitude = np.random.rand(...) 解析失败时静默替换为随机数据
archive/v1/src/hardware/csi_extractor.py 129-135 _parse_atheros() 返回 np.random.rand(),注释为 “placeholder implementation” 名称看似解析真实数据,实际是随机数据
archive/v1/src/hardware/router_interface.py 211-212 回退路径中的 np.random.rand(3, 56) 静默随机回退
archive/v1/src/services/pose_service.py 431 生产代码路径中的 mock_csi = np.random.randn(64, 56, 3) # Mock CSI data 生产代码路径中的 Mock CSI
archive/v1/src/services/pose_service.py 293-356 整个 _generate_mock_poses() 中遍布 random.randint 服务层中存在完整的 mock 姿态生成器
archive/v1/src/services/pose_service.py 489-607 占用率和历史数据中使用多个 random.randint API 响应中看似真实的虚假统计数据
archive/v1/src/api/dependencies.py 82, 408 “return a mock user for development” 默认路径中的认证绕过

中等严重程度(mock 由标志控制但令人困惑)

文件 行号 问题
archive/v1/src/config/settings.py 144-145 mock_hardware=False、mock_pose_data=False 默认值——正确,但存在 mock 基础设施
archive/v1/src/core/router_interface.py 27-300 生产代码中存在 270 多行 mock 数据生成基础设施
archive/v1/src/services/pose_service.py 84-88 静默条件:if not self.settings.mock_pose_data,未记录真实模式日志
archive/v1/src/services/hardware_service.py 72-375 mock/真实路径交错分布

低严重程度(占位符/TODO)

文件 行号 问题
archive/v1/src/core/router_interface.py 198 “Collect real CSI data from router (placeholder implementation)”
archive/v1/src/api/routers/health.py 170-171 uptime_seconds = 0.0 # TODO
archive/v1/src/services/pose_service.py 739 "uptime_seconds": 0.0 # TODO

根本原因分析

  1. mock 与真实代码未分离:Mock 生成器与真实处理器位于同一模块中。审查者阅读 csi_processor.py 时,会在第 390 行遇到 np.random.rand(10),从而不再信任其上方 400 行真实信号处理代码。

  2. 静默回退:当真实硬件不可用时,系统不会显式失败,而是静默回退到随机数据。这意味着默认 docker compose up 会生成看似合理但完全虚假的结果。

  3. 没有证明工件:没有随附的 CSI 捕获文件,没有预期输出哈希,也没有办法让审查者验证流水线能从真实输入产生确定性结果。

  4. 构建环境脆弱:Dockerfile 引用了 requirements.txt,但它并不作为独立文件存在。setup.py 硬编码了 87 个依赖项。ONNX Runtime 和 BLAS 不在容器中。docker build 可能成功也可能失败,取决于机器。

  5. 没有 CI 验证:没有 GitHub Actions 工作流使用真实或确定性输入运行流水线并验证输出。

决策

我们将通过五项具体变更消除可信度差距:

1. 消除所有静默 Mock 回退(硬性失败)

所有当前返回 np.random.rand() 的路径都将被替换为真实计算,或抛出显式错误。

# BEFORE (csi_processor.py:390)
doppler_shift = np.random.rand(10)  # Placeholder

# AFTER
def _extract_doppler_features(self, csi_data: CSIData) -> tuple:
    """Extract Doppler and frequency domain features from CSI temporal history."""
    if len(self.csi_history) < 2:
        # Not enough history for temporal analysis - return zeros, not random
        doppler_shift = np.zeros(self.window_size)
        psd = np.abs(scipy.fft.fft(csi_data.amplitude.flatten(), n=128))**2
        return doppler_shift, psd

    # Real Doppler extraction from temporal CSI differences
    history_array = np.array([h.amplitude for h in self.get_recent_history(self.window_size)])
    # Compute phase differences over time (proportional to Doppler shift)
    temporal_phase_diff = np.diff(np.angle(history_array + 1j * np.zeros_like(history_array)), axis=0)
    # Average across antennas, FFT across time for Doppler spectrum
    doppler_spectrum = np.abs(scipy.fft.fft(temporal_phase_diff.mean(axis=1), axis=0))
    doppler_shift = doppler_spectrum.mean(axis=1)

    psd = np.abs(scipy.fft.fft(csi_data.amplitude.flatten(), n=128))**2
    return doppler_shift, psd
# BEFORE (csi_extractor.py:129-135)
def _parse_atheros(self, raw_data):
    """Parse Atheros CSI format (placeholder implementation)."""
    # For now, return mock data for testing
    return CSIData(amplitude=np.random.rand(3, 56), ...)

# AFTER
def _parse_atheros(self, raw_data: bytes) -> CSIData:
    """Parse Atheros CSI Tool format.

    Format: https://dhalperi.github.io/linux-80211n-csitool/
    """
    if len(raw_data) < 25:  # Minimum Atheros CSI header
        raise CSIExtractionError(
            f"Atheros CSI data too short ({len(raw_data)} bytes). "
            "Expected real CSI capture from Atheros-based NIC. "
            "See docs/hardware-setup.md for capture instructions."
        )
    # Parse actual Atheros binary format
    # ... real parsing implementation ...

2. 通过显式标志和横幅隔离模拟基础设施

所有模拟代码都移至专用模块。默认执行绝不会触及模拟路径。

archive/v1/src/
├── core/
│   ├── csi_processor.py        # Real processing only
│   └── router_interface.py     # Real hardware interface only
├── testing/                    # NEW: isolated mock module
│   ├── __init__.py
│   ├── mock_csi_generator.py   # Mock CSI generation (moved from router_interface)
│   ├── mock_pose_generator.py  # Mock poses (moved from pose_service)
│   └── fixtures/               # Test fixtures, not production paths
│       ├── sample_csi_capture.bin  # Real captured CSI data (tiny sample)
│       └── expected_output.json    # Expected pipeline output for sample

运行时强制:

import os
import sys

MOCK_MODE = os.environ.get("WIFI_DENSEPOSE_MOCK", "").lower() == "true"

if MOCK_MODE:
    # Print banner on EVERY log line
    _original_log = logging.Logger._log
    def _mock_banner_log(self, level, msg, args, **kwargs):
        _original_log(self, level, f"[MOCK MODE] {msg}", args, **kwargs)
    logging.Logger._log = _mock_banner_log

    print("=" * 72, file=sys.stderr)
    print("  WARNING: RUNNING IN MOCK MODE - ALL DATA IS SYNTHETIC", file=sys.stderr)
    print("  Set WIFI_DENSEPOSE_MOCK=false for real operation", file=sys.stderr)
    print("=" * 72, file=sys.stderr)

3. 交付可复现的证明包

一个小型真实 CSI 捕获文件 + 一条命令验证流水线:

archive/v1/data/proof/
├── README.md                      # How to verify
├── sample_csi_capture.bin         # Real CSI data (1 second, ~50 KB)
├── sample_csi_capture_meta.json   # Capture metadata (hardware, env)
├── expected_features.json         # Expected feature extraction output
├── expected_features.sha256       # SHA-256 hash of expected output
└── verify.py                      # One-command verification script

verify.py:

#!/usr/bin/env python3
"""Verify WiFi-DensePose pipeline produces deterministic output from real CSI data.

Usage:
    python archive/v1/data/proof/verify.py

Expected output:
    PASS: Pipeline output matches expected hash
    SHA256: <hash>

If this passes, the signal processing pipeline is producing real,
deterministic results from real captured CSI data.
"""
import hashlib
import json
import sys
import os

# Ensure reproducibility
os.environ["PYTHONHASHSEED"] = "42"
import numpy as np
np.random.seed(42)  # Only affects any remaining random elements

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))

from src.core.csi_processor import CSIProcessor
from src.hardware.csi_extractor import CSIExtractor

def main():
    # Load real captured CSI data
    capture_path = os.path.join(os.path.dirname(__file__), "sample_csi_capture.bin")
    meta_path = os.path.join(os.path.dirname(__file__), "sample_csi_capture_meta.json")
    expected_hash_path = os.path.join(os.path.dirname(__file__), "expected_features.sha256")

    with open(meta_path) as f:
        meta = json.load(f)

    # Extract CSI from binary capture
    extractor = CSIExtractor(format=meta["format"])
    csi_data = extractor.extract_from_file(capture_path)

    # Process through feature pipeline
    config = {
        "sampling_rate": meta["sampling_rate"],
        "window_size": meta["window_size"],
        "overlap": meta["overlap"],
        "noise_threshold": meta["noise_threshold"],
    }
    processor = CSIProcessor(config)
    features = processor.extract_features(csi_data)

    # Serialize features deterministically
    output = {
        "amplitude_mean": features.amplitude_mean.tolist(),
        "amplitude_variance": features.amplitude_variance.tolist(),
        "phase_difference": features.phase_difference.tolist(),
        "doppler_shift": features.doppler_shift.tolist(),
        "psd_first_16": features.power_spectral_density[:16].tolist(),
    }
    output_json = json.dumps(output, sort_keys=True, separators=(",", ":"))
    output_hash = hashlib.sha256(output_json.encode()).hexdigest()

    # Verify against expected hash
    with open(expected_hash_path) as f:
        expected_hash = f.read().strip()

    if output_hash == expected_hash:
        print(f"PASS: Pipeline output matches expected hash")
        print(f"SHA256: {output_hash}")
        print(f"Features: {len(output['amplitude_mean'])} subcarriers processed")
        return 0
    else:
        print(f"FAIL: Hash mismatch")
        print(f"Expected: {expected_hash}")
        print(f"Got:      {output_hash}")
        return 1

if __name__ == "__main__":
    sys.exit(main())

4. 固定构建环境

选项 A(推荐):可在全新机器上运行的确定性 Dockerfile

FROM python:3.11-slim

# System deps that actually matter
RUN apt-get update && apt-get install -y --no-install-recommends \
    libopenblas-dev \
    libfftw3-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Pinned requirements (not a reference to missing file)
COPY archive/v1/requirements-lock.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

COPY archive/v1/ ./v1/

# Proof of reality: verify pipeline on build
RUN cd archive/v1 && python data/proof/verify.py

EXPOSE 8000
# Default: REAL mode (mock requires explicit opt-in)
ENV WIFI_DENSEPOSE_MOCK=false
CMD ["uvicorn", "v1.src.api.main:app", "--host", "0.0.0.0", "--port", "8000"]

关键变更:在构建期间执行 RUN python data/proof/verify.py 意味着,除非流水线能从真实 CSI 数据产生正确输出,否则无法创建 Docker 镜像。

需求锁定文件(archive/v1/requirements-lock.txt):

# Core (required)
fastapi==0.115.6
uvicorn[standard]==0.34.0
pydantic==2.10.4
pydantic-settings==2.7.1
numpy==1.26.4
scipy==1.14.1

# Signal processing (required)
# No ONNX required for basic pipeline verification

# Optional (install separately for full features)
# torch>=2.1.0
# onnxruntime>=1.17.0

5. 证明真实性的 CI 流水线

# .github/workflows/verify-pipeline.yml
name: Verify Signal Pipeline

on:
  push:
    paths: ['archive/v1/src/**', 'archive/v1/data/proof/**']
  pull_request:
    paths: ['archive/v1/src/**']

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - name: Install minimal deps
        run: pip install numpy scipy pydantic pydantic-settings
      - name: Verify pipeline determinism
        run: python archive/v1/data/proof/verify.py
      - name: Verify no random in production paths
        run: |
          # Fail if np.random appears in production code (not in testing/)
          ! grep -r "np\.random\.\(rand\|randn\|randint\)" archive/v1/src/ \
            --include="*.py" \
            --exclude-dir=testing \
            || (echo "FAIL: np.random found in production code" && exit 1)

所需的具体文件更改

文件 操作 描述
archive/v1/src/core/csi_processor.py:390 替换 从时间 CSI 历史中提取真实多普勒
archive/v1/src/hardware/csi_extractor.py:83-84 替换 解析失败时抛出带描述性消息的硬错误
archive/v1/src/hardware/csi_extractor.py:129-135 替换 真实 Atheros CSI 解析器,或带硬件说明的硬错误
archive/v1/src/hardware/router_interface.py:198-212 替换 对未实现硬件抛出硬错误,或真实 iwconfig + CSI 工具集成
archive/v1/src/services/pose_service.py:293-356 移动 将 _generate_mock_poses() 移动到 archive/v1/src/testing/mock_pose_generator.py
archive/v1/src/services/pose_service.py:430-431 删除 从生产路径中移除 mock CSI 生成
archive/v1/src/services/pose_service.py:489-607 替换 来自数据库的真实统计,或显式的“无数据”响应
archive/v1/src/core/router_interface.py:60-300 移动 将 mock 生成器移动到 archive/v1/src/testing/mock_csi_generator.py
archive/v1/src/api/dependencies.py:82,408 替换 真实身份验证检查,或带日志记录的显式开发模式绕过
archive/v1/data/proof/ 创建 证明包(样本捕获 + 预期哈希 + 验证脚本)
archive/v1/requirements-lock.txt 创建 固定版本的最小依赖
.github/workflows/verify-pipeline.yml 创建 CI 验证

硬件文档

archive/v1/docs/hardware-setup.md (to be created)

# Supported Hardware Matrix

| Chipset | Tool | OS | Capture Command |
|---------|------|----|-----------------|
| Intel 5300 | Linux 802.11n CSI Tool | Ubuntu 18.04 | `sudo ./log_to_file csi.dat` |
| Atheros AR9580 | Atheros CSI Tool | Ubuntu 14.04 | `sudo ./recv_csi csi.dat` |
| Broadcom BCM4339 | Nexmon CSI | Android/Nexus 5 | `nexutil -m1 -k1 ...` |
| ESP32 | ESP32-CSI | ESP-IDF | `csi_recv --format binary` |

# Calibration
1. Place router and receiver 2m apart, line of sight
2. Capture 10 seconds of empty-room baseline
3. Have one person walk through at normal pace
4. Capture 10 seconds during walk-through
5. Run calibration: `python archive/v1/scripts/calibrate.py --baseline empty.dat --activity walk.dat`

后果

积极影响

  • 一条命令完成“克隆、构建、验证”:docker build . && docker run --rm wifi-densepose python archive/v1/data/proof/verify.py 产生确定性的 PASS
  • 无静默伪造:随机数据绝不会出现在生产输出中
  • CI 强制检查:在生产路径中引入 np.random 的 PR 会自动失败
  • 可信锚点:来自真实 CSI 捕获的 SHA-256 已验证输出是不可辩驳的证明
  • 清晰的 mock 边界:Mock 代码仅存在于 archive/v1/src/testing/,生产模块永不导入它

负面影响

  • 需要真实 CSI 捕获:必须有人捕获并提交一个真实 CSI 样本(一次性工作)
  • 没有硬件时构建可能失败:没有 mock 回退时,没有 WiFi 硬件的系统无法演示——必须改用证明包
  • 迁移工作量:将 mock 代码移到独立模块需要更新测试文件中的导入
  • 更严格的开发流程:开发者必须显式选择启用 mock 模式

验收标准

一个陌生人可以: 1. git clone 该仓库 2. 运行一条命令(docker build . 或 python archive/v1/data/proof/verify.py) 3. 看到 PASS: Pipeline output matches expected hash 以及具体的 SHA-256 4. 通过 CI 徽章确认任何非测试文件中都没有 np.random

如果这在干净机器上连续 5 次运行 100% 成功,“伪造”的说法就会终结。

回答两个关键问题

Q1:先 Docker 还是 Nix? 建议:先 Docker。Dockerfile 已经存在,只需要修复。Nix 质量更高但受众更小。Docker 提供最广的“克隆并验证”覆盖范围。

Q2:外部 crate 是否公开且带版本? Python 依赖项都是公开的 PyPI 包。Rust ruvector-core 和 ruvector-data-framework crate 目前在 Cargo.toml 中被注释掉(第 83-84 行:# ruvector-core = "0.1"),尚未发布到 crates.io。它们是 ruvnet 内部使用的。这是 Rust 路径的阻塞项,但不影响本 ADR 中 Python 真实性证明工作。

参考资料

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView