Check a Synthetic 100,000-Point DHO804-Style Record Offline

Two synthetic exports can show about twenty cycles of the same sine wave. One can contain 100,000 voltage readings and the other just 1,000. If the curves look alike, how do you tell which one covers the requested memory record?

Make the decision from the saved settings, numbered read requests and replies. Start with the downloadable Python exercise. It generates four synthetic records, including a convincing screen trace. Once you have identified the two records that meet the specification, remove one window (a numbered range of points) and see which evidence exposes the gap.

Download the offline reader, example, drawings and worksheet. The software exercise runs without instruments. The physical comparison below is a procedure awaiting qualification on an actual instrument connection.

Predict which records will qualify

An oscilloscope samples voltage at successive instants. An acquisition is one collection of those readings. Memory depth is the selected number of points in the acquisition record. The readout mode selects what the instrument sends when asked for a waveform. On the RIGOL DHO804, NORMal readout provides screen data, up to 1,000 points. RAW reads the stopped acquisition memory. The separate Normal acquisition setting stays the same throughout this experiment.

Suppose a subsequent calculation calls for a RAW record of exactly 100,000 reported points, with at most 10 microseconds (ยตs) between neighbors and 0.12 to 0.50 seconds from first point to last, endpoints included. These are the exercise requirements. Give each export a prediction before opening its report.

One readout change, followed by two memory-depth controls
Record Acquisition What you request
A_SCREEN A ยท 100,000 selected Read the displayed points while stopped.
A_RAW Same stopped A Read the full acquisition memory.
B_RAW New B ยท 1,000 selected Read every point in a deliberately shallow memory.
C_RAW New C ยท 100,000 restored Repeat the full-memory read after restoring Aโ€™s settings.

Run the offline experiment

Extract the archive into a new local directory. Open a terminal in the extracted reader directory containing check_records.py. Use Python 3.9 or later on a supported Unix-like host with local hard-link support. The checker creates a new output file each time. Choose a fresh directory and report name for another run. The commands below use a POSIX (Portable Operating System Interface) shell such as the one on macOS.

The archive includes a ready-to-read examples/synthetic-228/manifest.json. A manifest is an index connecting each request to its original reply file. To make your own equivalent set from scratch and check it, run these two commands. The first creates a new directory named my-synthetic-lab.

PYTHONPATH=tests python3 -c 'from pathlib import Path; from full_shape_fixture import build_lab; build_lab(Path("my-synthetic-lab"))'
python3 check_records.py my-synthetic-lab/manifest.json --output my-report.json

You should see PASS (synthetic, non-bench). Open my-report.json, a JavaScript Object Notation (JSON) text file. Find records. Each row below describes a separate result you can check there.

Expected results for the generated voltages and settings
Record Protocol Digital contract Fixture sanity
A_SCREEN PASS FAIL ยท screen mode, count and step PASS
A_RAW PASS PASS PASS
B_RAW PASS FAIL ยท count and step PASS
C_RAW PASS PASS PASS

Protocol checks whether the files and readbacks support a complete, interpretable record. Digital contract applies the chosen mode, count and time-grid criteria. Fixture sanity asks whether the returned voltages resemble the intended test signal. Operator scope identifies whether the required observations were reported. In the example even the operator statements are generated. The overall comparison passes when both positive cases qualify, both deliberate controls fail for their required reasons, and the other checks agree.

Count the intervals yourself

The preamble is the instrumentโ€™s description of the data that follows. Its points field gives the number of points, N. Its xincrement gives the time step ฮ”t in seconds. Keep the other fields too. The separate count field describes averaging. Use points for the length. For one-based point number k, its time since the first reported point is (k โˆ’ 1) ร— ฮ”t. Two points span one interval, so the first-to-last span of N points is (N โˆ’ 1) ร— ฮ”t.

  • A_RAW and C_RAW. The synthetic preamble gives 100,000 points and 0.000002 s per step. Span = 99,999 ร— 2 ยตs = 0.199998 s. A synthetic rate of 500,000 samples per second agrees with that step. At the chosen 100 hertz (Hz), one cycle lasts 0.010 s and occupies 5,000 steps.
  • B_RAW. Its 1,000 points have a step of 200 ยตs and span 999 ร— 200 ยตs = 0.1998 s. A complete read of B covers about the same duration as A, yet it has only 50 steps per cycle. It passes the span limit while failing the count and step limits.
  • A_SCREEN. This synthetic screen read also has 1,000 points at 200 ยตs. Aโ€™s acquisition still reports 100,000 selected points and 500,000 samples per second. Reading the display changed the grid of the returned data. Compare that modeโ€™s own preamble with its returned count.

C starts a quarter-cycle later in the generated sine. Its reported rate, step, timebase, depth, instrument identity and panel observations return to Aโ€™s settings. Matching every voltage byte between A and C would incorrectly reject a valid repeat with another starting phase.

Prove that the windows join

A window is one requested range of point numbers. A 1-based inclusive request from i to j must return exactly j โˆ’ i + 1 finite voltages. A 100,000-point transfer can use ten windows of 10,000. The first covers 1โ€“10,000, the second 10,001โ€“20,000, and the last 90,001โ€“100,000. In the saved array order each start must equal the preceding stop plus one.

Ten adjacent 10,000-point windows with indices 10,000 and 10,001 on opposite sides of the first boundary.
Requested index geometry. The first sample in the second window is one time step after the last sample in the first. Editable drawing (editable SVG inside reader ZIP) ยท Full size

Find records.A_RAW.chunks in the manifest. For its first entry, compare requested_start and requested_stop with the files named in before.start, before.stop, after.start and after.stop. Look at reply.file to find the comma-separated voltages. The points readback remains the full record count. Every data reply has an expected byte length and a Secure Hash Algorithm 256-bit (SHA-256) digest, a fingerprint of its exact bytes. Each synthetic A_RAW window contains two copies of a 5,000-value pattern. Its first and last samples are 9,999 steps apart, so their elapsed span is 9,999 ร— 2 ยตs = 19.998 ms. Successive window starts are 10,000 steps apart, or 20 ms (two full periods). Two windows can therefore have identical bytes and digests. The readbacks and point ranges locate them.

A physical comparison for a qualified instrument link

The following setup uses a Tektronix AFG1022 signal generator and a RIGOL DHO804 oscilloscope. No bench measurements accompany this exercise. A physical comparison requires a documented control link and a terminal that saves complete replies. Earth the scope as described below before attaching any signal or control connection. The link needs a dated qualification for the actual model and firmware (the software running in the instrument), framing (which bytes make one reply) and transfer-end behavior (how the link signals completion). The packaged checkerโ€™s only supported profile is synthetic. Actual input remains UNSUPPORTED_ACTUAL_TRANSPORT. Preserve its actual origin when storing it.

Generator channel 1 center and shell connect to scope channel 1 by short coax. Generator mains earth and scope rear earth lead are separate connections.
External connections for the proposed comparison. The scope uses its supplied adapter and rear earth lead. Switch generator output off for hookup and disconnection. Editable schematic (editable SVG inside reader ZIP) ยท Full size
  1. Earth and power. Connect the DHO804 rear Ground Terminal to earth with its supplied ground cable before connecting any input or output terminal. This includes both the signal cable and the control link. Use its supplied 15 V, 3 A power adapter. Keep protective earth (PE), the safety conductor in the AFG1022 mains cord, connected to a grounded outlet. The scope requires its separate earth lead even with the coax shield connected.
  2. Wire the signal with the generator output off. Use one short 50 ohm (ฮฉ) coaxial cable with Bayonet Neillโ€“Concelman (BNC) connectors. Join channel 1 (CH1) output to scope CH1 input. Center conductor carries the signal. The surrounding shield connects the two shells as the return. The scope presents 1 megohm (Mฮฉ). Leave out external termination and probes. The cableโ€™s 50 ฮฉ characteristic impedance describes wave propagation along it. It does not add a 50 ฮฉ load across the scope input.
  3. Set the signal and display. Select High Z, the generatorโ€™s high-impedance load display setting. Its output still has about 50 ฮฉ source impedance. Choose a continuous 100 Hz sine, 2.00 volts peak-to-peak (Vpp, maximum minus minimum), zero offset. Leave generator CH2 off. Enable only scope CH1, select direct-current (DC) coupling to preserve the mean level and use a 1ร— display ratio for the direct cable. Start at 0.5 V per vertical division and 20 milliseconds per horizontal division on the main timebase. The nominal 2 Vpp trace should span about four vertical divisions. These are initial settings.
  4. Enable generator CH1. Verify the sine is visible and that the scope triggers steadily from CH1 before using Single, which arms the scope for one acquisition and then stops it. A trigger defines the event used to align the capture. Record actual settings and observations. Investigate missing or clipped signals with the settings and cable, keeping output off for any reconnection.
  5. Capture A, B and C. Set Normal acquisition and Single trigger sweep. At 100,000 selected points arm Single once and wait for STOP. Read A_SCREEN, then A_RAW during the same stopped A. Select 1,000 points and take a new manual Single for B_RAW. Restore 100,000 and take a third manual Single for C_RAW. Wait for STOP on each. Keep output on, the same fixture and generator settings, and the same trigger settings throughout. During each read allow only the readout selector changes. Record before/after panel observations and exclude concurrent operation. After Cโ€™s final observations, turn generator CH1 off before disconnecting.

Copy the blank observation worksheet before use. Leave unknown readings and any unmeasured optional meter values empty. Its fields cover the fixture, each acquisition and each read boundary. Full manual sequence and query map

What a saved reply needs to establish

Standard Commands for Programmable Instruments (SCPI) let a terminal request the instrument settings and data. A command ending in a question mark requests a reply. A setting command records your intent. Save the subsequent query reply to establish what the instrument reported. The checker reads files offline. It sends no instrument commands.

  1. Capture boundaries. Before and after each acquisitionโ€™s read sequence, retain the identity query *IDN?, trigger status and sweep, acquisition type, selected memory depth, sample rate and main timebase scale. Record the operatorโ€™s observations separately. Each full record boundary also saves these seven acquisition replies.
  2. Full read boundaries. Select CH1, the roleโ€™s NORMal or RAW readout and American Standard Code for Information Interchange (ASCII), which represents voltage readings as text. Set the full points and inclusive range. Save the seven waveform readbacks for source, mode, format, points, start, stop and the ten-field preamble. A full snapshot therefore holds fourteen replies. Require full endpoints 1 and N and agreement between the full points and preamble at both boundaries. For RAW the queried depth must agree too. ASCII already returns volts.
  3. Window boundaries. For each forward window set the new stop before advancing the start. Save source, mode, format, full points and the start/stop readbacks immediately before and after its :WAVeform:DATA? reply. Record both requested endpoints. Each window must contribute its own complete data frame, the original bytes for that response. A partial-window preamble may be recorded if queried. The two full preambles supply the count authority. Restore the full range before taking the full after snapshot. :WAVeform:STOP selects the last read index. :TRIGger:STATus? separately reports whether acquisition is stopped.
  4. Preserve transfer evidence. Save the complete original frame, relative file path, byte count, digest, exact query, profile and its reported transfer observations. An end-of-message (EOM) event is evidence from the connection that a response ended. Reaching the end of a saved file only establishes its stored length. Configure and retain a finite deadline on the qualified terminal, including any timeout and partial bytes. The offline checker can report these observations but cannot impose an instrument deadline.

The programming guide documents a 100,000-point stopped RAW ASCII example. It describes an ASCII end identifier without establishing the literal bytes for a particular connection. No actual connection framing or firmware profile is supplied. Both RIGOL guides cite software baseline 00.01.03. Read the actual firmware identity separately. The programming guide also gives two different cues for the RAW step. Figure 3.13 labels it TimeScale/100, while ยง3.28.6 gives 1/SampleRate for RAW and TimeScale/100 for Normal readout. Retain and compare the actual preamble, reported rate, mode and timebase. Only the synthetic profile here requires the exact RAW rate ร— step product to equal one.

Operator labels A, B and C express who associated the reads. Two STOP observations, unchanged settings and a matching digest cannot prove that no intervening acquisition occurred or that every read came from one indivisible capture. The result concerns the reported digital record. Physical voltage accuracy, calibrated time, aliasing (different signals producing indistinguishable samples), the waveform between samples and numerical integration remain unverified.

Read a failure without hiding it

The fixture check requires peak-to-peak voltage from 1.0 through 3.0 V, and absolute mean voltage at most 0.20 V. The crossing detector arms on a sample at or below โˆ’0.05 V. It registers a rise when a subsequent sample reaches +0.05 V, then waits to arm again. The two thresholds keep small variations around zero from counting as extra cycles. It requires at least eleven rising crossings and every adjacent crossing interval from 1/110 to 1/90 second inclusive. A flat trace, a large offset or a wrong period can fail fixture sanity even when every index arrived. These are broad teaching checks rather than calibration tolerances.

  • 0 ยท PASS means the expected comparison occurred, including the two deliberate digital failures. Open the individual roles to see which records qualify.
  • 1 ยท FAIL means an interpretable comparison missed a required condition. Inspect reasons and issues for the affected record, fixture or restoration setting.
  • 3 ยท UNSUPPORTED identifies unqualified input such as an actual transport or incompatible metadata. 3 ยท PHYSICAL_CONTROL_PENDING identifies incomplete required observations. Preserve unknowns and original bytes.
  • 2 ยท MALFORMED covers damaged input such as a missing range, altered file or extra empty voltage cell. Command usage and output creation errors also return 2. Use a new report path on a supported local filesystem.

Malformed input takes precedence over unsupported or pending evidence, which in turn takes precedence over a failed comparison. The software limits each window to 10,000 values, each record to 100,000 values and 100 windows, and each data frame to one mebibyte (1 MiB = 1,048,576 bytes). See the full format, field definitions and limits (record-format.md inside reader ZIP) for the remaining bounds.

Challenge: remove the middle of a convincing record

Predict what happens if window 6 disappears from A_RAW but the full before and after metadata still report 100,000 points. Keep the original example intact. After the first exercise, run this in the same extracted reader directory, using a fresh destination name.

python3 - <<'PY'
import json
from pathlib import Path
from shutil import copytree

root = Path("my-gap-copy")
copytree("my-synthetic-lab", root)
path = root / "manifest.json"
manifest = json.loads(path.read_text())
del manifest["records"]["A_RAW"]["chunks"][5]
path.write_text(json.dumps(manifest, separators=(",", ":")) + "\n")
PY
python3 check_records.py my-gap-copy/manifest.json --output my-gap-report.json
Answer and a check on your reasoning

Window 5 ends at 50,000. With window 6 absent, the next start is 60,001. The manifest leaves indices 50,001โ€“60,000 uncovered, even though the unused data file still exists on disk. The reader follows the declared sequence. It returns MALFORMED (synthetic, non-bench), exit 2, and A_RAW retains MALFORMED_COVERAGE. Its digital and fixture verdicts are NOT_EVALUATED. The other three roles retain their own results. Interpolating 10,000 voltages would create new values without supplying evidence of a read. Restore the original window reference or obtain a new complete capture under the qualified procedure.

Source code and further reading

Each listing is complete and matches the corresponding file in the reader. Expand a listing to search its text. The archive also includes the format, fixed synthetic profile, manual sequence, worksheet and host tests.

Load original replies and check their saved evidence ยท reply_io.py
"""Bounded offline loader for the reviewed candidate 228 saved-reply format.

Snapshot keys map to Reply objects. Full snapshots also carry an acquisition
map. Reply.reference retains the saved reference and transport reports,
Reply.frame is the exact verified file content, and Reply.value is decoded
only when supported. An unqueried window preamble is represented by None.
Record.values concatenates complete decoded chunks in manifest order, or is
None if any chunk is unavailable. The windows still require coverage review.
Record.issues retains issues from its own record and capture locations.

Lab.issues is a tuple of Issue(code, location, category). Dot-separated
locations begin with a manifest field, with zero-based chunk indexes.
MalformedError carries the issues gathered across independent slots and
roles. A returned Lab may have unsupported, pending or known setup issues.
"""

from contextlib import ExitStack, contextmanager
from dataclasses import dataclass, replace
from decimal import Decimal
from fractions import Fraction
from hashlib import sha256
import json
import os
from pathlib import Path
import re
import stat
from typing import Optional


_KIB = 1024
_MIB = _KIB * _KIB
_MANIFEST_LIMIT = 512 * _KIB
_SCALAR_LIMIT = 4 * _KIB
_MAX_POINTS = 100_000
_MAX_WINDOW = 10_000
_REGISTRY_SHA256 = "50bf572e76497bdf4af13de91f22f4eed6b75ac945fd65e34aa8bf0e4bde80cd"
_ROLES = {"A_SCREEN": "A", "A_RAW": "A", "B_RAW": "B", "C_RAW": "C"}
_ACQUISITION = {
    "idn": "*IDN?",
    "trigger_status": ":TRIGger:STATus?",
    "trigger_sweep": ":TRIGger:SWEep?",
    "acquisition_type": ":ACQuire:TYPE?",
    "memory_depth": ":ACQuire:MDEPth?",
    "sample_rate": ":ACQuire:SRATe?",
    "main_timebase_scale": ":TIMebase:MAIN:SCALe?",
}
_WAVEFORM = {
    "source": ":WAVeform:SOURce?",
    "mode": ":WAVeform:MODE?",
    "format": ":WAVeform:FORMat?",
    "points": ":WAVeform:POINts?",
    "start": ":WAVeform:STARt?",
    "stop": ":WAVeform:STOP?",
    "preamble": ":WAVeform:PREamble?",
}
_COMMANDS = {**_ACQUISITION, **_WAVEFORM, "data": ":WAVeform:DATA?"}
_ENUMS = {
    "trigger_status": ("TD", "WAIT", "RUN", "AUTO", "STOP"),
    "trigger_sweep": ("AUTO", "NORM", "SING"),
    "acquisition_type": ("NORM", "PEAK", "AVER", "ULTR"),
    "source": ("CHAN1", "CHAN2", "CHAN3", "CHAN4"),
    "mode": ("NORM", "MAX", "RAW"),
    "format": ("BYTE", "WORD", "ASC"),
}
_EXPECTED_ACQUISITION = {"trigger_status": "STOP", "trigger_sweep": "SING", "acquisition_type": "NORM"}
_PREAMBLE_CELLS = (
    "format", "type", "points", "count", "xincrement", "xorigin", "xreference",
    "yincrement", "yorigin", "yreference",
)
_OPERATOR_CONTROLS = (
    "single_capture_performed", "no_concurrent_operation",
    "no_acquisition_setting_change_during_reads", "same_fixture_and_generator_between_controls",
)
_PANEL_CONTROLS = {
    "ch1_enabled": True, "other_channels_disabled": True, "coupling": "DC",
    "scale_V_per_div": None, "offset_V": None, "probe_ratio": Decimal(1),
    "timebase_mode": "MAIN",
}
_FILE_KEYS = {"file", "bytes", "sha256"}
_EOM_KEYS = {"eom_status", "eom_basis", "telemetry_ref", "timeout_reported"}
_NUMERIC = re.compile(rb"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[Ee]([+-]?[0-9]+))?")
_RELATIVE_PATH = re.compile(r"[ -~]{1,240}")
_URI_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:")


@dataclass(frozen=True)
class Issue:
    code: str
    location: str
    category: str


class MalformedError(ValueError):
    """Invalid saved input. See issues for precise locations and all collected reasons."""

    def __init__(self, issues):
        self.issues = tuple(issues)
        first_bad = next(issue for issue in self.issues if issue.category == "MALFORMED")
        super().__init__(f"{first_bad.code} at {first_bad.location}")


@dataclass(frozen=True)
class Reply:
    reference: dict
    frame: bytes
    value: object


@dataclass(frozen=True)
class Chunk:
    requested_start: int
    requested_stop: int
    before: dict
    after: dict
    reply: Reply


@dataclass(frozen=True)
class Capture:
    label: str
    operator: dict
    panel: dict
    before: dict
    after: dict


@dataclass(frozen=True)
class Record:
    role: str
    capture: str
    before: dict
    after: dict
    chunks: tuple[Chunk, ...]
    values: Optional[tuple[Decimal, ...]]
    issues: tuple[Issue, ...] = ()


@dataclass(frozen=True)
class Lab:
    synthetic: bool
    captures: dict[str, Capture]
    records: dict[str, Record]
    issues: tuple[Issue, ...] = ()


def _bad(code, location):
    raise MalformedError((Issue(code, location, "MALFORMED"),))


def _object(value, required, location, *, optional=()):
    if not isinstance(value, dict) or required - value.keys() or value.keys() - required - set(optional):
        _bad("MALFORMED_SCHEMA", location)
    return value


def _observations(value, allowed, location):
    return {} if value is None else _object(value, set(), location, optional=allowed)


def _string(value, location, *, max_length=4096):
    if not isinstance(value, str) or not 1 <= len(value) <= max_length:
        _bad("MALFORMED_SCHEMA", location)
    return value


def _identity(info):
    return info.st_dev, info.st_ino


@contextmanager
def _directories(start_fd, parts, location):
    """Anchor each component to its open parent directory without following a link."""
    with ExitStack() as stack:
        directory_fd = start_fd
        links = []
        try:
            for part in parts:
                child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
                                   dir_fd=directory_fd)
                stack.callback(os.close, child_fd)
                links.append((directory_fd, part, _identity(os.fstat(child_fd))))
                directory_fd = child_fd
            yield directory_fd, links
        except OSError:
            _bad("MALFORMED_PATH", location)


def _check_links(links, location):
    for parent_fd, name, identity in links:
        current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
        if _identity(current) != identity:
            _bad("MALFORMED_PATH", location)


def _read_regular(start_fd, parts, parent_links, limit, location, *, length=None):
    with _directories(start_fd, parts[:-1], location) as (parent_fd, directory_links):
        name = parts[-1]
        initial = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
        if not stat.S_ISREG(initial.st_mode):
            _bad("MALFORMED_PATH", location)
        if initial.st_size > limit:
            _bad("MALFORMED_SIZE_LIMIT", location)
        if length is not None and initial.st_size != length:
            _bad("MALFORMED_FILE_LENGTH", location)
        file_fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent_fd)
        with os.fdopen(file_fd, "rb") as handle:
            opened = os.fstat(handle.fileno())
            file_identity = _identity(opened)
            if not stat.S_ISREG(opened.st_mode) or file_identity != _identity(initial):
                _bad("MALFORMED_PATH", location)
            links = [*parent_links, *directory_links, (parent_fd, name, file_identity)]
            _check_links(links, location)
            read_limit = limit if length is None else length
            data = handle.read(read_limit + 1)
            final = os.fstat(handle.fileno())
            _check_links(links, location)
            if len(data) > limit or final.st_size > limit:
                _bad("MALFORMED_SIZE_LIMIT", location)
            if (len(data) != opened.st_size or len(data) != final.st_size
                    or (length is not None and len(data) != length)
                    or opened.st_mtime_ns != final.st_mtime_ns):
                _bad("MALFORMED_FILE_LENGTH", location)
        return data, file_identity


def _json_manifest(raw):
    # Bound nesting before giving the untrusted text to the recursive JSON parser.
    depth = 0
    quoted = False
    escaped = False
    for byte in raw:
        if quoted:
            if escaped:
                escaped = False
            elif byte == 92:
                escaped = True
            elif byte == 34:
                quoted = False
        elif byte == 34:
            quoted = True
        elif byte in (91, 123):
            depth += 1
            if depth > 16:
                _bad("MALFORMED_SIZE_LIMIT", "manifest")
        elif byte in (93, 125):
            depth -= 1
            if depth < 0:
                _bad("MALFORMED_SCHEMA", "manifest")

    def object_pairs(pairs):
        result = {}
        for key, item in pairs:
            if key in result:
                _bad("MALFORMED_DUPLICATE_KEY", "manifest")
            result[key] = item
        return result

    def reject_real(_):
        _bad("MALFORMED_SCHEMA", "manifest")

    def parse_int(token):
        # Avoid CPython's platform-dependent limit on decimal string-to-int.
        return int(token) if len(token) < 64 else int(Decimal(token))

    try:
        manifest = json.loads(raw.decode("utf-8"), object_pairs_hook=object_pairs,
                              parse_float=reject_real, parse_constant=reject_real, parse_int=parse_int)
        pending = [manifest]
        while pending:
            value = pending.pop()
            if isinstance(value, dict):
                pending.extend(value)
                pending.extend(value.values())
            elif isinstance(value, list):
                pending.extend(value)
            elif isinstance(value, str) and len(value.encode("utf-8")) > 4096:
                _bad("MALFORMED_SIZE_LIMIT", "manifest")
        return manifest
    except (UnicodeError, json.JSONDecodeError):
        _bad("MALFORMED_SCHEMA", "manifest")


def _profile():
    # Bind the decoder to the exact reviewed package, never to caller files.
    path = Path(__file__).with_name("transport-profiles.json")
    try:
        with path.open("rb") as handle:
            raw = handle.read(_SCALAR_LIMIT + 1)
    except OSError as error:
        raise RuntimeError("Reviewed packaged transport registry is unavailable") from error
    if sha256(raw).hexdigest() != _REGISTRY_SHA256:
        raise RuntimeError("Packaged transport registry differs from the reviewed registry")
    return json.loads(raw)["profiles"][0]


def _number(cell, location, invalid_code):
    if len(cell) > 64:
        _bad("MALFORMED_NUMERIC_BOUND", location)
    token = cell.strip(b" \t")
    match = _NUMERIC.fullmatch(token)
    if match is None:
        _bad(invalid_code, location)
    if match[1] is not None and abs(int(match[1])) > 10_000:
        _bad("MALFORMED_NUMERIC_BOUND", location)
    return Decimal(token.decode("ascii"))


def _integer(value, location, invalid_code, *, positive=True, maximum=None):
    if (value != value.to_integral_value() or (positive and value <= 0)
            or (maximum is not None and value > maximum)):
        _bad(invalid_code, location)
    return int(value)


def _value(snapshot, key):
    reply = snapshot.get(key) if snapshot is not None else None
    return None if reply is None else reply.value


def _disagrees(first, second):
    return first is not None and second is not None and first != second


class _Loader:
    def __init__(self, directory_fd, links, synthetic, manifest_size):
        self.directory_fd = directory_fd
        self.links = links
        self.synthetic = synthetic
        self.profile = _profile()
        self.total_bytes = manifest_size
        self.scope_bytes = {}
        self.files = set()
        self.issues = []

    def note(self, category, code, location):
        self.issues.append(Issue(code, location, category))

    def unsupported(self, code, location):
        self.note("UNSUPPORTED", code, location)

    def pending(self, location):
        self.note("PHYSICAL_CONTROL_PENDING", "PHYSICAL_CONTROL_PENDING", location)

    def setup_fail(self, code, location):
        self.note("CONTRACT_FAIL", code, location)

    def attempt(self, read, *args):
        try:
            return read(*args)
        except MalformedError as error:
            self.issues.extend(error.issues)
            return None

    def file(self, reference, location, frame_limit):
        relative = reference["file"]
        if (not isinstance(relative, str) or not _RELATIVE_PATH.fullmatch(relative)
                or "\\" in relative or _URI_SCHEME.match(relative)):
            _bad("MALFORMED_PATH", location)
        parts = relative.split("/")
        if any(part in ("", ".", "..") for part in parts):
            _bad("MALFORMED_PATH", location)
        size, digest = reference["bytes"], reference["sha256"]
        if type(size) is not int or size <= 0:
            _bad("MALFORMED_FILE_LENGTH", location)
        if not isinstance(digest, str) or re.fullmatch(r"[0-9a-f]{64}", digest) is None:
            _bad("MALFORMED_SCHEMA", location)
        fields = location.split(".", 2)
        scope = "captures" if fields[0] == "captures" else fields[1]
        scope_limit = _MIB if scope == "captures" else 16 * _MIB
        if (size > frame_limit or self.scope_bytes.get(scope, 0) + size > scope_limit
                or self.total_bytes + size > 65 * _MIB):
            _bad("MALFORMED_SIZE_LIMIT", location)
        self.scope_bytes[scope] = self.scope_bytes.get(scope, 0) + size
        self.total_bytes += size
        frame, identity = _read_regular(self.directory_fd, parts, self.links, frame_limit,
                                        location, length=size)
        self.files.add(identity)
        if len(self.files) > 1024:
            _bad("MALFORMED_SIZE_LIMIT", location)
        if sha256(frame).hexdigest() != digest:
            _bad("MALFORMED_DIGEST", location)
        return frame

    def evidence(self, reference, location):
        if reference is not None:
            self.file(_object(reference, _FILE_KEYS, location), location, _MIB)

    def transport(self, ref, location):
        path = f"{location}.transport"
        transport = _object(ref.get("transport", {}), set(), path, optional=_EOM_KEYS)
        self.evidence(transport.get("telemetry_ref"), f"{path}.telemetry_ref")
        status = transport.get("eom_status")
        if status not in (None, "observed", "not_observed", "unknown"):
            _bad("MALFORMED_SCHEMA", f"{path}.eom_status")
        if status != self.profile["eom"]["accepted_status"]:
            self.pending(f"{path}.eom_status")
        basis = transport.get("eom_basis")
        if basis not in (None, "synthetic_event", "backend_event", "operator_assertion"):
            _bad("MALFORMED_SCHEMA", f"{path}.eom_basis")
        if basis is None:
            self.pending(f"{path}.eom_basis")
        elif ((self.synthetic and basis != self.profile["eom"]["accepted_basis"])
                or (not self.synthetic and basis == self.profile["eom"]["accepted_basis"])):
            self.unsupported("UNSUPPORTED_TRANSPORT_EVIDENCE", f"{path}.eom_basis")
        timeout = transport.get("timeout_reported")
        if timeout is not None and type(timeout) is not bool:
            _bad("MALFORMED_SCHEMA", f"{path}.timeout_reported")
        if timeout is not False:
            self.pending(f"{path}.timeout_reported")

    def read_reply(self, ref, slot, location, data_limit=None):
        _object(ref, _FILE_KEYS | {"command", "profile_id", "framing_evidence"},
                location, optional=("transport",))
        frame = self.file(ref, location, _MIB if slot == "data" else _SCALAR_LIMIT)
        framing = _object(ref["framing_evidence"], {"kind", "evidence_ref"}, f"{location}.framing_evidence")
        self.evidence(framing["evidence_ref"], f"{location}.framing_evidence.evidence_ref")
        self.transport(ref, location)
        command = _string(ref["command"], f"{location}.command")
        if ";" in command or any(ord(character) < 32 or ord(character) == 127 for character in command):
            _bad("MALFORMED_COMMAND_BINDING", location)
        bound_command = command == _COMMANDS[slot]
        if not bound_command:
            if command in _COMMANDS.values():
                _bad("MALFORMED_COMMAND_BINDING", location)
            self.unsupported("UNSUPPORTED_COMMAND", location)
        profile_id = _string(ref["profile_id"], f"{location}.profile_id")
        known_profile = profile_id == self.profile["id"]
        if not known_profile:
            self.unsupported("UNSUPPORTED_TRANSPORT_PROFILE", location)
        kind = framing["kind"]
        if kind not in ("synthetic_contract", "qualified_backend", "unknown"):
            _bad("MALFORMED_SCHEMA", f"{location}.framing_evidence.kind")
        known_framing = kind == self.profile["framing_evidence_kind"]
        if kind == "unknown" or (self.synthetic and not known_framing):
            self.unsupported("UNSUPPORTED_FRAMING", location)
        if not (self.synthetic and known_profile and known_framing and bound_command):
            return Reply(ref, frame, None)
        if slot == "data" and data_limit is None:
            return Reply(ref, frame, None)

        # The pinned profile has zero prefix/offset and an empty suffix.
        value = self.decode(frame, slot, location, data_limit)
        return Reply(ref, frame, value)

    def decode(self, frame, slot, location, data_limit):
        if not frame or not frame.isascii() or b"\r" in frame or b"\n" in frame:
            _bad("MALFORMED_ASCII", location)
        if slot == "data":
            if frame.count(b",") + 1 > data_limit:
                _bad("MALFORMED_SIZE_LIMIT", location)
            return tuple(_number(cell, location, "MALFORMED_ASCII") for cell in frame.split(b","))
        if slot == "preamble":
            return self.preamble(frame, location)
        if slot == "idn":
            identity = tuple(frame.decode("ascii").split(","))
            if len(identity) != 4 or any(not field or not field.isprintable() for field in identity):
                _bad("MALFORMED_IDN", location)
            if identity[1] != "DHO804":
                self.setup_fail("CONTRACT_FAIL_MODEL", location)
            return identity
        if slot in _ENUMS:
            token = frame.decode("ascii")
            if token not in _ENUMS[slot]:
                self.unsupported("UNSUPPORTED_SOURCE" if slot == "source" else "UNSUPPORTED_REPLY", location)
                return None
            if slot == "format" and token != "ASC":
                self.unsupported("UNSUPPORTED_FORMAT", location)
            if slot == "source" and token != "CHAN1":
                self.setup_fail("CONTRACT_FAIL_SOURCE", location)
            if slot in _EXPECTED_ACQUISITION and token != _EXPECTED_ACQUISITION[slot]:
                self.setup_fail(f"CONTRACT_FAIL_{slot.upper()}", location)
            return token
        if slot == "memory_depth" and frame.strip(b" \t") == b"AUTO":
            self.unsupported("UNSUPPORTED_DEPTH_REPLY", location)
            return None
        number = _number(frame, location, "MALFORMED_ASCII")
        if slot in ("memory_depth", "points", "start", "stop"):
            cap = None if slot == "memory_depth" else _MAX_POINTS
            return _integer(number, location, "MALFORMED_NUMERIC", maximum=cap)
        if number <= 0:
            _bad("MALFORMED_NUMERIC", location)
        return number

    def preamble(self, frame, location):
        if frame.count(b",") != 9:
            _bad("MALFORMED_PREAMBLE", location)
        parsed = {key: _number(cell, f"{location}.{key}", "MALFORMED_PREAMBLE")
                  for key, cell in zip(_PREAMBLE_CELLS, frame.split(b","))}
        for field, members in (("format", _ENUMS["format"]), ("type", _ENUMS["mode"])):
            key_path = f"{location}.{field}"
            index = _integer(parsed[field], key_path, "MALFORMED_PREAMBLE", positive=False)
            if 0 <= index < len(members):
                parsed[field] = members[index]
            else:
                self.unsupported("UNSUPPORTED_PREAMBLE_ENUM", key_path)
                parsed[field] = None
        for field in ("points", "count"):
            cap = _MAX_POINTS if field == "points" else None
            parsed[field] = _integer(parsed[field], f"{location}.{field}",
                                     "MALFORMED_PREAMBLE", maximum=cap)
        for field in ("xincrement", "yincrement"):
            if parsed[field] <= 0:
                _bad("MALFORMED_PREAMBLE", f"{location}.{field}")
        return parsed

    def acquisition(self, snapshot, location):
        _object(snapshot, _ACQUISITION.keys(), location)
        return {slot: self.attempt(self.read_reply, snapshot[slot], slot, f"{location}.{slot}")
                for slot in _ACQUISITION}

    def waveform(self, snapshot, location, full):
        required = _WAVEFORM.keys() | ({"acquisition"} if full else set())
        _object(snapshot, required, location)
        result = {}
        for slot in _WAVEFORM:
            if not full and slot == "preamble" and snapshot[slot] is None:
                result[slot] = None
            else:
                result[slot] = self.attempt(self.read_reply, snapshot[slot], slot, f"{location}.{slot}")
        if full:
            result["acquisition"] = self.attempt(self.acquisition, snapshot["acquisition"],
                                                 f"{location}.acquisition")
        return result

    def operator(self, data, location):
        limits = {"operator_label": 128, "report": 2048}
        data = _observations(data, set(_OPERATOR_CONTROLS) | limits.keys(), location)
        result = {}
        for field in _OPERATOR_CONTROLS:
            value = data.get(field)
            key_path = f"{location}.{field}"
            if value is None:
                self.pending(key_path)
            elif type(value) is not bool:
                _bad("MALFORMED_SCHEMA", key_path)
            elif not value:
                self.setup_fail("CONTRACT_FAIL_OPERATOR", key_path)
            result[field] = value
        for field, limit in limits.items():
            value = data.get(field)
            result[field] = None if value is None else _string(value, f"{location}.{field}",
                                                               max_length=limit)
        return result

    def panel(self, data, location):
        data = _observations(data, _PANEL_CONTROLS.keys(), location)
        result = {}
        for field, expected in _PANEL_CONTROLS.items():
            value = data.get(field)
            key_path = f"{location}.{field}"
            if value is None:
                self.pending(key_path)
            elif field in ("scale_V_per_div", "offset_V", "probe_ratio"):
                text = _string(value, key_path)
                if not text.isascii():
                    _bad("MALFORMED_NUMERIC", key_path)
                value = _number(text.encode("ascii"), key_path, "MALFORMED_NUMERIC")
                if (field == "scale_V_per_div" and value <= 0) or (expected is not None and value != expected):
                    self.setup_fail("CONTRACT_FAIL_PANEL", key_path)
            else:
                if type(value) is not type(expected) or value == "":
                    _bad("MALFORMED_SCHEMA", key_path)
                if value != expected:
                    self.setup_fail("CONTRACT_FAIL_PANEL", key_path)
            result[field] = value
        return result

    def compare_snapshots(self, first, second, keys, location):
        for key in keys:
            if _disagrees(_value(first, key), _value(second, key)):
                self.unsupported("UNSUPPORTED_METADATA_CHANGED", f"{location}.{key}")

    def capture(self, label, data):
        location = f"captures.{label}"
        _object(data, {"label", "before", "after"}, location, optional=("operator", "panel"))
        if data["label"] != label:
            _bad("MALFORMED_CAPTURE_BINDING", location)
        operator = self.attempt(self.operator, data.get("operator"), f"{location}.operator")
        observations = self.attempt(_observations, data.get("panel"), {"before", "after"},
                                    f"{location}.panel")
        panel = {}
        if observations is not None:
            for bound in ("before", "after"):
                panel[bound] = self.attempt(self.panel, observations.get(bound), f"{location}.panel.{bound}")
            if panel["before"] is not None and panel["after"] is not None:
                for key in _PANEL_CONTROLS:
                    if _disagrees(panel["before"][key], panel["after"][key]):
                        key_path = f"{location}.panel.{key}"
                        self.unsupported("UNSUPPORTED_METADATA_CHANGED", key_path)
                        if key in ("scale_V_per_div", "offset_V"):
                            self.setup_fail("CONTRACT_FAIL_PANEL", key_path)
        before = self.attempt(self.acquisition, data["before"], f"{location}.before")
        after = self.attempt(self.acquisition, data["after"], f"{location}.after")
        self.compare_snapshots(before, after, _ACQUISITION, f"{location}.after")
        return Capture(label, operator, panel, before, after)

    def full_checks(self, full, capture, role, bound, location):
        if full is None:
            return
        acquisition = full["acquisition"]
        mode, points, preamble = (_value(full, key) for key in ("mode", "points", "preamble"))
        expected_mode = "NORM" if role == "A_SCREEN" else "RAW"
        if mode is not None and mode != expected_mode:
            self.setup_fail("CONTRACT_FAIL_MODE", f"{location}.mode")
        for key, want in (("start", 1), ("stop", points)):
            if _disagrees(_value(full, key), want):
                self.unsupported("UNSUPPORTED_METADATA", f"{location}.{key}")
        if mode == "NORM" and points is not None and points > 1000:
            self.unsupported("UNSUPPORTED_METADATA_FULL_COUNT", location)

        capture_snapshot = getattr(capture, bound) if capture is not None else None
        counts = {points, preamble["points"] if preamble is not None else None}
        if mode == "RAW":
            counts.add(_value(acquisition, "memory_depth"))
            counts.add(_value(capture_snapshot, "memory_depth"))
        counts.discard(None)
        if len(counts) > 1:
            self.unsupported("UNSUPPORTED_METADATA_FULL_COUNT", location)

        if preamble is not None:
            for key, query in (("format", "format"), ("type", "mode")):
                if _disagrees(preamble[key], _value(full, query)):
                    self.unsupported("UNSUPPORTED_METADATA", f"{location}.preamble.{key}")
            if _value(acquisition, "acquisition_type") == "NORM" and preamble["count"] != 1:
                self.unsupported("UNSUPPORTED_METADATA", f"{location}.preamble.count")
            sample_rate = _value(acquisition, "sample_rate")
            if mode == "RAW" and preamble["type"] == "RAW" and sample_rate is not None:
                if Fraction(preamble["xincrement"]) * Fraction(sample_rate) != 1:
                    self.unsupported("UNSUPPORTED_METADATA_RATE_STEP", f"{location}.preamble.xincrement")
        self.compare_snapshots(capture_snapshot, acquisition, _ACQUISITION, f"{location}.acquisition")

    def window_checks(self, window, full, start, stop, location):
        if window is None:
            return
        self.compare_snapshots(full, window, ("source", "mode", "format", "points"), location)
        for key, requested in (("start", start), ("stop", stop)):
            if _disagrees(_value(window, key), requested):
                self.unsupported("UNSUPPORTED_METADATA", f"{location}.{key}")
        preamble = _value(window, "preamble")
        if _disagrees(preamble, _value(full, "preamble")):
            self.unsupported("UNSUPPORTED_METADATA_WINDOW_PREAMBLE", f"{location}.preamble")
        if preamble is not None:
            for key, query in (("format", "format"), ("type", "mode")):
                if _disagrees(preamble[key], _value(window, query)):
                    self.unsupported("UNSUPPORTED_METADATA_WINDOW_PREAMBLE", f"{location}.preamble")

    def chunk(self, data, full_before, full_after, location, remaining_values):
        _object(data, {"requested_start", "requested_stop", "before", "after", "reply"}, location)
        start, stop = data["requested_start"], data["requested_stop"]
        if (type(start) is not int or type(stop) is not int
                or not 1 <= start <= stop <= _MAX_POINTS or stop - start + 1 > _MAX_WINDOW):
            _bad("MALFORMED_WINDOW", location)
        before = self.attempt(self.waveform, data["before"], f"{location}.before", False)
        after = self.attempt(self.waveform, data["after"], f"{location}.after", False)
        self.window_checks(before, full_before, start, stop, f"{location}.before")
        self.window_checks(after, full_after, start, stop, f"{location}.after")
        self.compare_snapshots(before, after, ("source", "mode", "format", "points"), f"{location}.after")
        snapshots = (before, after, full_before, full_after)
        formats = {_value(snapshot, "format") for snapshot in snapshots}
        formats.discard(None)
        preambles = (_value(snapshot, "preamble") for snapshot in snapshots)
        conflicting_preamble = any(
            preamble is not None and preamble["format"] in ("BYTE", "WORD")
            for preamble in preambles
        )
        # Decode under known ASC query evidence only when no available
        # format query or preamble contradicts it.
        data_limit = None
        if formats == {"ASC"} and not conflicting_preamble:
            data_limit = min(_MAX_WINDOW, remaining_values)
        reply = self.read_reply(data["reply"], "data", f"{location}.reply", data_limit)
        if reply.value is not None and len(reply.value) != stop - start + 1:
            _bad("MALFORMED_WINDOW_PAYLOAD_COUNT", f"{location}.reply")
        return Chunk(start, stop, before, after, reply)

    def record(self, role, data, capture):
        location = f"records.{role}"
        _object(data, {"role", "capture", "before", "after", "chunks"}, location)
        if data["role"] != role or data["capture"] != _ROLES[role]:
            _bad("MALFORMED_ROLE_BINDING", location)
        before = self.attempt(self.waveform, data["before"], f"{location}.before", True)
        after = self.attempt(self.waveform, data["after"], f"{location}.after", True)
        for bound, snapshot in (("before", before), ("after", after)):
            self.full_checks(snapshot, capture, role, bound, f"{location}.{bound}")
        self.compare_snapshots(before, after, _WAVEFORM, f"{location}.after")
        if _disagrees(_value(before, "points"), _value(after, "points")):
            self.unsupported("UNSUPPORTED_METADATA_FULL_COUNT", f"{location}.after")
        if before is not None and after is not None:
            self.compare_snapshots(before["acquisition"], after["acquisition"], _ACQUISITION,
                                   f"{location}.after.acquisition")
        chunks = data["chunks"]
        if not isinstance(chunks, list) or not chunks:
            _bad("MALFORMED_SCHEMA", f"{location}.chunks")
        if len(chunks) > 100:
            _bad("MALFORMED_SIZE_LIMIT", f"{location}.chunks")
        parsed = []
        remaining_values = _MAX_POINTS
        for index, item in enumerate(chunks):
            chunk = self.attempt(self.chunk, item, before, after, f"{location}.chunks.{index}",
                                 remaining_values)
            if chunk is not None:
                parsed.append(chunk)
                if chunk.reply.value is not None:
                    remaining_values -= len(chunk.reply.value)
        values = None
        if len(parsed) == len(chunks) and all(chunk.reply.value is not None for chunk in parsed):
            values = tuple(value for chunk in parsed for value in chunk.reply.value)
        return Record(role, _ROLES[role], before, after, tuple(parsed), values)

    def lab(self, captures_data, records_data):
        if not self.synthetic:
            self.unsupported("UNSUPPORTED_ACTUAL_TRANSPORT", "synthetic")
        captures = {label: self.attempt(self.capture, label, captures_data[label]) for label in "ABC"}
        records = {role: self.attempt(self.record, role, records_data[role], captures[label])
                   for role, label in _ROLES.items()}
        # A's screen and RAW reads share one capture. Compare the available
        # acquisition replies even when one shared boundary cannot be decoded.
        if records["A_SCREEN"] is not None and records["A_RAW"] is not None:
            for bound in ("before", "after"):
                screen = getattr(records["A_SCREEN"], bound)
                raw = getattr(records["A_RAW"], bound)
                if screen is not None and raw is not None:
                    self.compare_snapshots(screen["acquisition"], raw["acquisition"], _ACQUISITION,
                                           f"records.A_RAW.{bound}.acquisition")
        if any(issue.category == "MALFORMED" for issue in self.issues):
            raise MalformedError(self.issues)
        issues = tuple(self.issues)
        records = {
            role: replace(record, issues=tuple(
                issue for issue in issues
                if issue.location.startswith((f"records.{role}.", f"captures.{record.capture}."))
            ))
            for role, record in records.items()
        }
        return Lab(self.synthetic, captures, records, issues)


def load_lab(path: Path) -> Lab:
    """Load and validate a local saved lab without instrument or network access.

    The host must support descriptor-relative open and stat, no-follow
    traversal, and directory-only opens. An unavailable host capability
    raises RuntimeError. Invalid saved input raises MalformedError.
    """
    if not (hasattr(os, "O_NOFOLLOW") and hasattr(os, "O_DIRECTORY")
            and os.open in os.supports_dir_fd and os.stat in os.supports_dir_fd
            and os.stat in os.supports_follow_symlinks):
        raise RuntimeError("This host does not support safe descriptor-relative file traversal")
    path = Path(path).absolute()
    if ".." in path.parts or len(path.parts) < 2 or "\x00" in str(path):
        _bad("MALFORMED_PATH", "manifest")
    anchor_fd = os.open(path.anchor, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        with _directories(anchor_fd, path.parts[1:-1], "manifest") as (directory_fd, links):
            raw, _ = _read_regular(directory_fd, (path.name,), links, _MANIFEST_LIMIT, "manifest")
            data = _object(_json_manifest(raw), {"schema_version", "synthetic", "captures", "records"}, "manifest")
            if type(data["schema_version"]) is not int or type(data["synthetic"]) is not bool:
                _bad("MALFORMED_SCHEMA", "manifest")
            if data["schema_version"] != 1:
                return Lab(data["synthetic"], {}, {},
                           (Issue("UNSUPPORTED_SCHEMA", "schema_version", "UNSUPPORTED"),))
            captures = _object(data["captures"], set("ABC"), "captures")
            records = _object(data["records"], _ROLES.keys(), "records")
            return _Loader(directory_fd, links, data["synthetic"], len(raw)).lab(captures, records)
    finally:
        os.close(anchor_fd)
Check coverage, time grid, fixture and A/B/C results ยท record_check.py
"""Qualify decoded saved records and compare the synthetic controls."""

from dataclasses import dataclass, replace
from decimal import Context, Decimal, Inexact, localcontext
from fractions import Fraction
from math import ceil, floor
from typing import Optional

from reply_io import Issue, Lab, Record


_POINTS = 100_000
_MAX_STEP = Fraction(1, 100_000)
_MIN_SPAN = Fraction(12, 100)
_MAX_SPAN = Fraction(1, 2)


@dataclass(frozen=True)
class Verdict:
    protocol: str
    digital_contract: str
    fixture_sanity: str
    reasons: tuple[str, ...]
    operator_scope: str = "COMPLETE_REPORTED"


def _full_count(record: Record, reasons: set[str]) -> Optional[int]:
    """Use only agreement at the two full boundaries to establish coverage."""
    if "UNSUPPORTED_METADATA_FULL_COUNT" in reasons:
        return None

    snapshots = (record.before, record.after)
    mode = record.before["mode"].value
    points = record.before["points"].value
    if mode is None or points is None:
        return None

    for snapshot in snapshots:
        preamble = snapshot["preamble"].value
        if (preamble is None or preamble["points"] != points
                or snapshot["points"].value != points or snapshot["mode"].value != mode
                or snapshot["start"].value != 1 or snapshot["stop"].value != points):
            return None
        if mode == "RAW" and snapshot["acquisition"]["memory_depth"].value != points:
            return None

    if mode == "RAW" and any(
        issue.category == "UNSUPPORTED"
        and issue.location.startswith(f"captures.{record.capture}.")
        and issue.location.endswith(".memory_depth")
        for issue in record.issues
    ):
        return None
    return points


def _coverage_failures(record: Record, count: Optional[int]) -> set[str]:
    """Check requested coverage even when a separate reply is unsupported."""
    failures = set()
    next_start = 1
    for chunk in record.chunks:
        start, stop = chunk.requested_start, chunk.requested_stop
        if start != next_start or stop < start or (count is not None and stop > count):
            failures.add("MALFORMED_COVERAGE")
        values = chunk.reply.value
        if values is not None and len(values) != stop - start + 1:
            failures.add("MALFORMED_WINDOW_PAYLOAD_COUNT")
        next_start = stop + 1

    if not record.chunks or (count is not None and (
        next_start != count + 1 or (record.values is not None and len(record.values) != count)
    )):
        failures.add("MALFORMED_COVERAGE")
    return failures


def qualify(record: Record) -> Verdict:
    """Qualify one decoded record from the saved-reply loader."""
    reasons = {issue.code for issue in record.issues}
    categories = {issue.category for issue in record.issues}
    operator_scope = "COMPLETE_REPORTED"
    if "PHYSICAL_CONTROL_PENDING" in categories:
        operator_scope = "PHYSICAL_CONTROL_PENDING"
    elif reasons.intersection(("CONTRACT_FAIL_OPERATOR", "CONTRACT_FAIL_PANEL")):
        operator_scope = "CONTRACT_FAIL"

    count = _full_count(record, reasons)
    coverage_failures = _coverage_failures(record, count)
    reasons.update(coverage_failures)
    preamble = record.before["preamble"].value
    step = None if preamble is None else preamble["xincrement"]
    if step is not None and (not step.is_finite() or step <= 0):
        reasons.add("MALFORMED_PREAMBLE")
        categories.add("MALFORMED")

    digital = "NOT_EVALUATED"
    if coverage_failures or "MALFORMED" in categories:
        protocol = "MALFORMED"
    elif "UNSUPPORTED" in categories:
        protocol = "UNSUPPORTED"
    elif count is None or step is None or record.values is None:
        protocol = "UNSUPPORTED"
        reasons.add("UNSUPPORTED_RECORD_EVIDENCE")
    else:
        protocol = "PASS"
        exact_step = Fraction(step)
        span = (count - 1) * exact_step
        numerical_failures = {
            reason for failed, reason in (
                (record.before["mode"].value != "RAW", "DIGITAL_CONTRACT_MODE"),
                (count != _POINTS, "DIGITAL_CONTRACT_COUNT"),
                (exact_step > _MAX_STEP, "DIGITAL_CONTRACT_STEP"),
                (not _MIN_SPAN <= span <= _MAX_SPAN, "DIGITAL_CONTRACT_SPAN"),
            ) if failed
        }
        reasons.update(numerical_failures)
        digital = "FAIL" if numerical_failures or "CONTRACT_FAIL" in categories else "PASS"

    return Verdict(protocol, digital, "NOT_EVALUATED", tuple(sorted(reasons)), operator_scope)


_EXPECTED_ROLES = {
    "A_SCREEN": ("NORM", 1, 1000, "DIGITAL_CONTRACT_MODE"),
    "A_RAW": ("RAW", _POINTS, _POINTS, None),
    "B_RAW": ("RAW", 1000, 1000, "DIGITAL_CONTRACT_COUNT"),
    "C_RAW": ("RAW", _POINTS, _POINTS, None),
}
_ARM_VOLTAGE = Decimal("-0.05")
_RISE_VOLTAGE = Decimal("0.05")
_MIN_PERIOD = Fraction(1, 110)
_MAX_PERIOD = Fraction(1, 90)


@dataclass(frozen=True)
class LabVerdict:
    overall: str
    records: dict[str, Verdict]
    operator_scope: str
    limitations: tuple[str, ...]
    reasons: tuple[str, ...] = ()
    issues: tuple[Issue, ...] = ()


def _sum_exact(values, maximum_magnitude):
    # At the finest stored exponent, each operand is an integer with at
    # most this many digits. The sample-count digits cover all partial sums.
    finest_exponent = min(value.as_tuple().exponent for value in values)
    precision = maximum_magnitude.adjusted() - finest_exponent + len(str(len(values))) + 1
    # The loader bounds keep the largest exact partial sum within this range.
    context = Context(prec=precision, Emin=-100_000, Emax=100_000)
    context.traps[Inexact] = True
    with localcontext(context):
        return sum(values, Decimal(0))


def _fixture_failures(values, exact_step):
    failures = set()
    minimum, maximum = min(values), max(values)
    if not 1 <= Fraction(maximum) - Fraction(minimum) <= 3:
        failures.add("FIXTURE_PTP")
    maximum_magnitude = max(minimum.copy_abs(), maximum.copy_abs())
    if Fraction(_sum_exact(values, maximum_magnitude).copy_abs()) > Fraction(len(values), 5):
        failures.add("FIXTURE_MEAN")

    # Exactly allowable integer sample gaps, derived from the rational limits.
    shortest_gap = ceil(_MIN_PERIOD / exact_step)
    longest_gap = floor(_MAX_PERIOD / exact_step)
    armed = False
    crossings = 0
    previous = None
    for index, value in enumerate(values):
        if value <= _ARM_VOLTAGE:
            armed = True
        elif armed and value >= _RISE_VOLTAGE:
            if previous is not None and not shortest_gap <= index - previous <= longest_gap:
                failures.add("FIXTURE_PERIOD")
            previous = index
            crossings += 1
            armed = False
    if crossings < 11:
        failures.add("FIXTURE_CROSSINGS")
    return failures


def _qualify_fixture(record: Record) -> Verdict:
    verdict = qualify(record)
    if verdict.protocol != "PASS":
        return verdict
    step = Fraction(record.before["preamble"].value["xincrement"])
    failures = _fixture_failures(record.values, step)
    return replace(verdict, fixture_sanity="FAIL" if failures else "PASS",
                   reasons=tuple(sorted(set(verdict.reasons) | failures)))


def _acquisition_snapshots(lab, label):
    capture = lab.captures[label]
    yield capture.before
    yield capture.after
    for record in lab.records.values():
        if record.capture == label:
            yield record.before["acquisition"]
            yield record.after["acquisition"]


def _expectation_issues(lab, verdicts):
    for role, record in lab.records.items():
        mode, min_points, max_points, required_failure = _EXPECTED_ROLES[role]
        location = f"records.{role}"
        for boundary in (record.before, record.after):
            reported_mode = boundary["mode"].value
            points = boundary["points"].value
            if reported_mode is not None and reported_mode != mode:
                yield Issue("EXPECTED_RECORD_MODE", location, "CONTRACT_FAIL")
            if points is not None and not min_points <= points <= max_points:
                yield Issue("EXPECTED_RECORD_COUNT", location, "CONTRACT_FAIL")

        verdict = verdicts[role]
        if verdict.protocol == "PASS":
            if required_failure is None:
                matches = verdict.digital_contract == "PASS"
            else:
                matches = verdict.digital_contract == "FAIL" and required_failure in verdict.reasons
            if not matches:
                yield Issue("EXPECTED_DIGITAL_VERDICT", location, "CONTRACT_FAIL")

    for label, depth in (("A", _POINTS), ("B", 1000), ("C", _POINTS)):
        depths = (snapshot["memory_depth"].value for snapshot in _acquisition_snapshots(lab, label))
        if any(value is not None and value != depth for value in depths):
            yield Issue("EXPECTED_CAPTURE_DEPTH", f"captures.{label}", "CONTRACT_FAIL")


def _known_disagreement(left, right):
    left = {value for value in left if value is not None}
    right = {value for value in right if value is not None}
    return bool(left and right and len(left | right) > 1)


def _restoration_issues(lab):
    a = tuple(_acquisition_snapshots(lab, "A"))
    c = tuple(_acquisition_snapshots(lab, "C"))
    for slot in ("idn", "sample_rate", "main_timebase_scale"):
        if _known_disagreement((snapshot[slot].value for snapshot in a),
                               (snapshot[slot].value for snapshot in c)):
            code = "A_C_IDENTITY_MISMATCH" if slot == "idn" else "A_C_RESTORED_GRID_MISMATCH"
            yield Issue(code, f"A_C.{slot}", "CONTRACT_FAIL")

    a_panel = lab.captures["A"].panel
    c_panel = lab.captures["C"].panel
    for field in a_panel["before"]:
        if _known_disagreement((panel[field] for panel in a_panel.values()),
                               (panel[field] for panel in c_panel.values())):
            yield Issue("A_C_PANEL_MISMATCH", f"A_C.panel.{field}", "CONTRACT_FAIL")

    def steps(role):
        record = lab.records[role]
        for boundary in (record.before, record.after):
            preamble = boundary["preamble"].value
            if preamble is not None:
                yield preamble["xincrement"]

    if _known_disagreement(steps("A_RAW"), steps("C_RAW")):
        yield Issue("A_C_RESTORED_GRID_MISMATCH", "A_C.xincrement", "CONTRACT_FAIL")


def compare_lab(lab: Lab) -> LabVerdict:
    """Compare controls from load_lab, preserving record verdicts and issue locations."""
    records = {role: _qualify_fixture(record) for role, record in lab.records.items()}
    issues = list(lab.issues)
    for record in lab.records.values():
        issues.extend(record.issues)
    if records:
        issues.extend(_expectation_issues(lab, records))
        issues.extend(_restoration_issues(lab))

    categories = {issue.category for issue in issues}
    protocols = {verdict.protocol for verdict in records.values()}
    scopes = {verdict.operator_scope for verdict in records.values()}
    panel_mismatch = any(issue.code == "A_C_PANEL_MISMATCH" for issue in issues)
    if "PHYSICAL_CONTROL_PENDING" in categories | scopes:
        operator_scope = "PHYSICAL_CONTROL_PENDING"
    elif "CONTRACT_FAIL" in scopes or panel_mismatch:
        operator_scope = "CONTRACT_FAIL"
    else:
        operator_scope = "COMPLETE_REPORTED" if records else "NOT_EVALUATED"

    if "MALFORMED" in categories | protocols:
        overall = "MALFORMED"
    elif "UNSUPPORTED" in categories | protocols:
        overall = "UNSUPPORTED"
    elif operator_scope == "PHYSICAL_CONTROL_PENDING":
        overall = "PHYSICAL_CONTROL_PENDING"
    elif "CONTRACT_FAIL" in categories or any(v.fixture_sanity != "PASS" for v in records.values()):
        overall = "FAIL"
    else:
        overall = "PASS"

    limitations = (
        "synthetic_non_bench" if lab.synthetic else "actual_transport_unverified",
        "acquisition_freshness_unverified",
        "atomic_capture_unverified",
        "analog_accuracy_unverified",
        "calibrated_time_unverified",
        "aliasing_unverified",
        "continuous_waveform_unverified",
        "integration_not_evaluated",
    )
    reasons = {issue.code for issue in issues}
    for verdict in records.values():
        reasons.update(verdict.reasons)
    return LabVerdict(overall, records, operator_scope, limitations,
                      tuple(sorted(reasons)), tuple(dict.fromkeys(issues)))
Run the checker and write a new report ยท check_records.py
"""Check saved waveform records offline and create a new JSON report."""

import argparse
from dataclasses import asdict
import json
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from typing import Optional, Sequence

from record_check import LabVerdict, compare_lab
from reply_io import Issue, Lab, MalformedError, Reply, load_lab


_EXIT_CODES = {
    "MALFORMED": 2,
    "UNSUPPORTED": 3,
    "PHYSICAL_CONTROL_PENDING": 3,
    "FAIL": 1,
    "PASS": 0,
}
_TRANSPORT_FIELDS = ("eom_status", "eom_basis", "timeout_reported", "telemetry_ref")


def _snapshot_replies(snapshot, location):
    for name, value in snapshot.items():
        path = f"{location}.{name}"
        if isinstance(value, Reply):
            yield path, value
        elif isinstance(value, dict):
            yield from _snapshot_replies(value, path)


def _saved_replies(lab: Lab):
    for group, owners in (("captures", lab.captures), ("records", lab.records)):
        for label, owner in owners.items():
            location = f"{group}.{label}"
            yield from _snapshot_replies(owner.before, f"{location}.before")
            yield from _snapshot_replies(owner.after, f"{location}.after")
    for role, record in lab.records.items():
        for index, chunk in enumerate(record.chunks):
            location = f"records.{role}.chunks.{index}"
            yield from _snapshot_replies(chunk.before, f"{location}.before")
            yield from _snapshot_replies(chunk.after, f"{location}.after")
            yield f"{location}.reply", chunk.reply


def _reported_transport(lab: Lab):
    observations = {}
    for location, reply in _saved_replies(lab):
        transport = reply.reference.get("transport", {})
        observations[location] = {field: transport.get(field) for field in _TRANSPORT_FIELDS}
    return observations


def _malformed(issues):
    return LabVerdict("MALFORMED", {}, "NOT_EVALUATED", (),
                      tuple(sorted({issue.code for issue in issues})), issues)


def _write_report(path: Path, report: dict) -> None:
    content = json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n"
    # Complete and close the staged file before publishing it. The final
    # link is exclusive even when another writer or a symlink gets there first.
    with TemporaryDirectory(prefix=".record-report-", dir=path.parent) as directory:
        staged = Path(directory) / "report.json"
        staged.write_text(content, encoding="utf-8")
        os.link(staged, path)


def main(argv: Optional[Sequence[str]] = None) -> int:
    """Run the offline check, returning the comparison or usage exit code."""
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("manifest", type=Path, help="saved lab manifest")
    parser.add_argument("--output", type=Path, required=True, help="new JSON report path")
    try:
        args = parser.parse_args(argv)
    except SystemExit as error:
        return error.code

    lab = None
    try:
        lab = load_lab(args.manifest)
    except MalformedError as error:
        verdict = _malformed(error.issues)
    except OSError:
        verdict = _malformed((Issue("MALFORMED_PATH", "manifest", "MALFORMED"),))
    except RuntimeError as error:
        print(f"{parser.prog}: {error}", file=sys.stderr)
        return 2
    else:
        verdict = compare_lab(lab)

    report = asdict(verdict)
    report["limitations"] += ("instrument_io_deadlines_not_enforced",)
    report["synthetic"] = None if lab is None else lab.synthetic
    report["transport_observations"] = {} if lab is None else _reported_transport(lab)
    try:
        _write_report(args.output, report)
    except (OSError, ValueError) as error:
        print(f"{parser.prog}: cannot create output {str(args.output)!r}: {error}", file=sys.stderr)
        return 2

    if report["synthetic"]:
        print(f"{verdict.overall} (synthetic, non-bench)")
    else:
        print(verdict.overall)
    return _EXIT_CODES[verdict.overall]


if __name__ == "__main__":
    sys.exit(main())
Generate the four synthetic records ยท tests/full_shape_fixture.py
"""Build the representative full-size synthetic manifest for loader tests."""

from hashlib import sha256
import json
import math
from pathlib import Path


ACQUISITION_COMMANDS = {
    "idn": "*IDN?",
    "trigger_status": ":TRIGger:STATus?",
    "trigger_sweep": ":TRIGger:SWEep?",
    "acquisition_type": ":ACQuire:TYPE?",
    "memory_depth": ":ACQuire:MDEPth?",
    "sample_rate": ":ACQuire:SRATe?",
    "main_timebase_scale": ":TIMebase:MAIN:SCALe?",
}
WAVEFORM_COMMANDS = {
    "source": ":WAVeform:SOURce?",
    "mode": ":WAVeform:MODE?",
    "format": ":WAVeform:FORMat?",
    "points": ":WAVeform:POINts?",
    "start": ":WAVeform:STARt?",
    "stop": ":WAVeform:STOP?",
    "preamble": ":WAVeform:PREamble?",
    "data": ":WAVeform:DATA?",
}
COMMANDS = {**ACQUISITION_COMMANDS, **WAVEFORM_COMMANDS}
ROLES = {
    "A_SCREEN": ("A", "NORM", 1000, "0.0002", 50, 0),
    "A_RAW": ("A", "RAW", 100000, "0.000002", 5000, 0),
    "B_RAW": ("B", "RAW", 1000, "0.0002", 50, 0),
    "C_RAW": ("C", "RAW", 100000, "0.000002", 5000, 1250),
}
PANEL = {
    "ch1_enabled": True,
    "other_channels_disabled": True,
    "coupling": "DC",
    "scale_V_per_div": "0.5",
    "offset_V": "0",
    "probe_ratio": "1",
    "timebase_mode": "MAIN",
}
OPERATOR = {
    "operator_label": "Synthetic fixture",
    "report": "Simulated controls for the manifest size check.",
    "single_capture_performed": True,
    "no_concurrent_operation": True,
    "no_acquisition_setting_change_during_reads": True,
    "same_fixture_and_generator_between_controls": True,
}


def _sine_tokens(period, phase):
    tokens = []
    for index in range(period):
        angle = math.tau * ((index + phase) % period) / period
        millionths = round(math.sin(angle) * 1_000_000)
        sign = "-" if millionths < 0 else ""
        whole, fraction = divmod(abs(millionths), 1_000_000)
        tokens.append(f"{sign}{whole}.{fraction:06d}")
    return tokens


def build_lab(directory: Path) -> Path:
    """Create a complete synthetic lab with distinct, descriptively named frames."""
    directory.mkdir()

    def reply(prefix, slot, text):
        name = f"frames/{prefix}/{slot}.txt"
        path = directory / name
        path.parent.mkdir(parents=True, exist_ok=True)
        payload = text.encode("ascii")
        with path.open("xb") as handle:
            handle.write(payload)
        return {
            "file": name,
            "bytes": len(payload),
            "sha256": sha256(payload).hexdigest(),
            "command": COMMANDS[slot],
            "profile_id": "synthetic-payload-v1",
            "framing_evidence": {"kind": "synthetic_contract", "evidence_ref": None},
            "transport": {
                "eom_status": "observed",
                "eom_basis": "synthetic_event",
                "telemetry_ref": None,
                "timeout_reported": False,
            },
        }

    def acquisition(label, prefix):
        values = {
            "idn": "RIGOL,DHO804,SYNTHETIC-228,synthetic-fw",
            "trigger_status": "STOP",
            "trigger_sweep": "SING",
            "acquisition_type": "NORM",
            "memory_depth": "1000" if label == "B" else "100000",
            "sample_rate": "5000" if label == "B" else "500000",
            "main_timebase_scale": "0.02",
        }
        return {slot: reply(prefix, slot, text) for slot, text in values.items()}

    def waveform(prefix, mode, points, start, stop):
        values = {
            "source": "CHAN1", "mode": mode, "format": "ASC",
            "points": str(points), "start": str(start), "stop": str(stop),
        }
        return {slot: reply(prefix, slot, text) for slot, text in values.items()}

    def full(role, label, bound, mode, points, step):
        prefix = f"records/{role}/{bound}"
        waveform_type = 2 if mode == "RAW" else 0
        return {
            "acquisition": acquisition(label, f"{prefix}/acquisition"),
            **waveform(prefix, mode, points, 1, points),
            "preamble": reply(prefix, "preamble", f"2,{waveform_type},{points},1,{step},0,0,1,0,0"),
        }

    captures = {
        label: {
            "label": label,
            "operator": OPERATOR.copy(),
            "panel": {"before": PANEL.copy(), "after": PANEL.copy()},
            "before": acquisition(label, f"captures/{label}/before"),
            "after": acquisition(label, f"captures/{label}/after"),
        }
        for label in "ABC"
    }

    records = {}
    for role, (label, mode, points, step, period, phase) in ROLES.items():
        tokens = _sine_tokens(period, phase)
        chunks = []
        for index, start in enumerate(range(1, points + 1, 10_000), 1):
            stop = min(points, start + 9_999)
            prefix = f"records/{role}/chunks/{index:02d}"
            payload = ",".join(tokens[cell % period] for cell in range(start - 1, stop))
            chunks.append({
                "requested_start": start,
                "requested_stop": stop,
                "before": {**waveform(f"{prefix}/before", mode, points, start, stop), "preamble": None},
                "after": {**waveform(f"{prefix}/after", mode, points, start, stop), "preamble": None},
                "reply": reply(prefix, "data", payload),
            })
        records[role] = {
            "role": role,
            "capture": label,
            "before": full(role, label, "before", mode, points, step),
            "after": full(role, label, "after", mode, points, step),
            "chunks": chunks,
        }
    manifest = directory / "manifest.json"
    data = {"schema_version": 1, "synthetic": True, "captures": captures, "records": records}
    with manifest.open("x", encoding="ascii") as handle:
        handle.write(json.dumps(data, separators=(",", ":")) + "\n")
    return manifest

The load setting and trigger alignment have separate experiments. Why a 50 ฮฉ Generator Can Read Twice as High on Your Scope ยท Use Trigger Holdoff to Align Repeating Sine Bursts

  • RIGOL, DHO800/DHO900 Programming Guide PGA39106-1110, ยงยง3.3, 3.27, 3.28 and 4.3. Printed pages 403โ€“414 cover waveform queries, and page 418 gives the stopped-memory ASCII example. Programming guide
  • RIGOL, DHO800 User Guide UGA36105-1110, safety, rear panel and vertical system. The DHO800 data sheet specifies the scope input. User guide ยท Data sheet
  • Tektronix, AFG1022 Quick Start User Manual 077-1097-00, channel output and load setup, printed pages 21 and 48. See the AFG1022 column for model-specific output limits. Quick start manual ยท AFG1000 series data sheet
๐Ÿ“กBroadcast the signal โ€” amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.

Supplier product photo

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu