XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
"""Fail-closed comparison of matched physical captures; software probes cannot pass.

Input format: platform, context, width/height/refreshMilliHz, physicalScanout,
rawEvidence (relative Path/Sha256), and workloads mapping IDs to five run objects.
Each run supplies activeSeconds, displayIntervalsMs, changedFrames, and, as
required, inputToDisplayMs or readyMs. These must be extracted from the hashed
raw captures, never copied from the CPU RenderProbe or from a configured target.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path

STANDARD_PATH = Path(__file__).with_name('Standard.json')


def percentile(values, p):
    values = sorted(values)
    if not values or any(not isinstance(x, (float, int)) or not math.isfinite(x) or x <= 0 for x in values):
        raise ValueError('Missing, zero or invalid measurement samples')
    return values[min(len(values)-1, math.ceil(len(values)*p)-1)]


def verify_raw(evidence, root):
    root = root.resolve()
    refs = evidence.get('rawEvidence')
    if not refs:
        raise ValueError('Hashed raw capture evidence is required')
    canonical = None
    for item in refs:
        path = (root / item['Path']).resolve()
        if not path.is_relative_to(root) or not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != item['Sha256']:
            raise ValueError('Raw capture missing, outside its directory or changed')
        if path.suffix.lower() == '.json':
            capture = json.loads(path.read_text(encoding='utf-8-sig'))
            if capture.get('Kind') == 'XfeCanonicalPhysicalWorkloads':
                if canonical is not None:
                    raise ValueError('Ambiguous canonical workload captures')
                canonical = capture.get('workloads')
    if canonical is None or canonical != evidence.get('workloads'):
        raise ValueError('Measured workload samples must equal the hashed canonical capture')


def compare(windows, candidate, standard=None):
    standard = standard or json.loads(STANDARD_PATH.read_text(encoding='utf-8-sig'))
    failures = []
    def check(ok, reason):
        if not ok: failures.append(reason)
    for name, evidence in (('Windows', windows), ('XFESystem', candidate)):
        check(evidence.get('platform') == name, name + ': platform is absent or wrong')
        check(evidence.get('physicalScanout') is True, name + ': actual physical display evidence is absent')
        check(evidence.get('measurementLayer') == 'PhysicalDisplay', name + ': configured/rendered frame counts cannot replace display evidence')
        check(evidence.get('width') == standard['TargetWidth'] and evidence.get('height') == standard['TargetHeight'], name + ': wrong native resolution')
        refresh = evidence.get('refreshMilliHz')
        check(isinstance(refresh, (int, float)) and math.isfinite(refresh) and abs(refresh-standard['TargetRefreshMilliHz']) <= standard['RefreshToleranceMilliHz'], name + ': wrong or unknown physical refresh')
        check(evidence.get('rawEvidenceVerified') is True, name + ': raw capture hashes have not been verified')
    context = windows.get('context')
    check(isinstance(context, dict) and all(context.get(key) for key in
          ('machine', 'monitor', 'cable', 'scaling', 'inputRateHz', 'powerPolicy', 'loadProfile')) and context == candidate.get('context'), 'Physical test conditions are missing or differ')
    frame_period = 1000000 / standard['TargetRefreshMilliHz']
    for workload in standard['Workloads']:
        identifier = workload['Id']
        before = windows.get('workloads', {}).get(identifier, [])
        after = candidate.get('workloads', {}).get(identifier, [])
        if len(before) != standard['RunsPerWorkload'] or len(after) != standard['RunsPerWorkload']:
            failures.append(identifier + ': missing matched workload runs'); continue
        for index, (left, right) in enumerate(zip(before, after)):
            label = f'{identifier}/{index+1}'
            try:
                check(bool(left.get('contentSha256')) and left.get('contentSha256') == right.get('contentSha256') and
                      bool(left.get('actionsSha256')) and left.get('actionsSha256') == right.get('actionsSha256'), label + ': workload content/actions differ')
                for run in (left, right):
                    check(run.get('activeSeconds', 0) >= standard['ActiveSecondsPerRun'], label + ': insufficient actual active time')
                    check(run.get('warmupSeconds', 0) >= standard['WarmupSeconds'], label + ': insufficient warmup')
                    check(run.get('errors', 1) == 0 and run.get('lostInputs', 1) == 0 and run.get('tearing') is False, label + ': rendering/input/scanout checks missing or failed')
                if workload.get('ContinuousMotion'):
                    for run in (left, right):
                        check(run.get('changedFrames', 0) >= standard['MinimumMatchedMotionSamplesPerRun'] and
                              len(run.get('displayIntervalsMs', [])) >= standard['MinimumMatchedMotionSamplesPerRun']-1, label + ': too few distinct movement frames')
                        intervals = run.get('displayIntervalsMs', [])
                        check(run.get('changedFrames') == len(intervals)+1 and abs(sum(intervals)-run['activeSeconds']*1000) <= frame_period*2,
                              label + ': movement frames do not cover the measured active interval')
                    for p in (.95, .99):
                        a, b = percentile(left['displayIntervalsMs'], p), percentile(right['displayIntervalsMs'], p)
                        check(b <= a + max(a*(standard['MaximumFrameIntervalRatioToWindows']-1), standard['FrameIntervalMeasurementToleranceMs']), label + ': frame-time tail exceeds Windows')
                    a = left['changedFrames'] / left['activeSeconds']; b = right['changedFrames'] / right['activeSeconds']
                    check(b >= a*standard['MinimumDistinctMotionRateRatioToWindows'], label + ': distinct movement rate below Windows')
                    stall_a = sum(x > standard['MaximumLongStallMs'] for x in left['displayIntervalsMs']) / len(left['displayIntervalsMs'])
                    stall_b = sum(x > standard['MaximumLongStallMs'] for x in right['displayIntervalsMs']) / len(right['displayIntervalsMs'])
                    check(stall_b <= stall_a + standard['MaximumLongStallRateAboveWindows'], label + ': excess long stalls')
                if workload.get('InputLatency'):
                    for run in (left, right):
                        check(len(run.get('inputToDisplayMs', [])) >= standard['MinimumInputLatencySamplesPerRun'], label + ': input-to-display measurement missing')
                    for p in (.95, .99):
                        check(percentile(right['inputToDisplayMs'], p) <= percentile(left['inputToDisplayMs'], p) + frame_period*standard['MaximumInputLatencyExtraRefreshPeriods'], label + ': input latency exceeds Windows')
                if workload.get('ReadyTime'):
                    a, b = left['readyMs'], right['readyMs']
                    percentile([a, b], 1)
                    check(b <= a + max(a*(standard['MaximumReadyTimeRatioToWindows']-1), standard['ReadyTimeMeasurementToleranceMs']), label + ': full editor readiness slower than Windows')
            except (KeyError, TypeError, ValueError, ZeroDivisionError) as error:
                failures.append(label + ': incomplete/invalid samples: ' + str(error))
    physical_refresh = all(item.get('physicalScanout') is True and item.get('measurementLayer') == 'PhysicalDisplay' and
                           item.get('rawEvidenceVerified') is True and isinstance(item.get('refreshMilliHz'), (int, float)) and
                           math.isfinite(item['refreshMilliHz']) and abs(item['refreshMilliHz']-standard['TargetRefreshMilliHz']) <= standard['RefreshToleranceMilliHz']
                           for item in (windows, candidate))
    return {'Kind': 'XfeWindowsFluidityAcceptance', 'WindowsFluidityParityPassed': not failures,
            'Physical240HzVerified': physical_refresh,
            'Failures': failures, 'StandardSha256': hashlib.sha256(STANDARD_PATH.read_bytes()).hexdigest()}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('windows', type=Path); parser.add_argument('candidate', type=Path); parser.add_argument('output', type=Path)
    args = parser.parse_args()
    evidence = []
    for path in (args.windows, args.candidate):
        item = json.loads(path.read_text(encoding='utf-8-sig'))
        item['rawEvidenceVerified'] = False
        verify_raw(item, path.resolve().parent)
        item['rawEvidenceVerified'] = True
        evidence.append(item)
    result = compare(*evidence)
    with args.output.open('x', encoding='utf-8') as output:
        json.dump(result, output, indent=2, ensure_ascii=False)
    return 0 if result['WindowsFluidityParityPassed'] else 1


if __name__ == '__main__':
    raise SystemExit(main())