# Inspect and run Optimum™ with structured JSON receipts

Use the native C API from a complete Python client, distinguish readiness from execution and handle owned study results and verified artifacts without parsing console summaries.

## Compatibility

JoSIM®-Pro 2.9.0 release target; frozen current-source Windows evidence

Published guidance with release-applicability limits. Confirm package applicability before following this guide.

**KB-OPTIMUM-001 · verified workaround**: Use a fresh complete writable ASCII-path teaching copy for the checked Windows typed study. This avoids the reproduced Unicode-path boundary without changing locale or renaming production sources.

[Download Complete Optimum™ resistor studies and native receipt client (ZIP)](/_functions/kbExample?name=optimum-resistor-studies.zip)

Includes: resistor.cir, resistor.sp, verify.toml, margin.toml, yield.toml, rolloff.toml, optimize.toml, optimum_receipt.py, README.txt.

## Use an owned receipt instead of scraping console text

The complete ZIP includes optimum_receipt.py, a standard-library Python client for the matching Windows x64 C API. It calls the native Optimum™ operation and copies its owned optimum-operation/1 JSON receipt. The native study owns verification, sampling and guarded artifact publication; the client does not reimplement those calculations.

Use a current matching 2.9 core, Optimum™ library and C API wrapper. Earlier installed review components with the same version number may lack the typed Optimum™ exports; the client fails with a missing-export diagnostic rather than using a substitute implementation. The checked interpreter is Windows x64 CPython 3.13.

The native API exposes configuration inspection, Verify and RunStudy separately. Inspection can return ready with planned outputs and effective settings without completing a study or publishing calculation artifacts. That is useful for an agent deciding what to run; it is not execution evidence.

## Inspect, then execute the complete example

1. Extract every ZIP member into a new writable ASCII directory. Keep the matching native bin directory available and set $bin below to its actual path if the installation is elsewhere.
2. Run the supplied inspection command. Read schema, status, exit_code, effective_settings, execution, selected parameters, planned artifacts and study_complete. For inspection the expected status is ready and study_complete is false.
3. Run the Yield command to a new receipt filename. Expect passed, study_complete true and 400 individual sample records. The sample assignments, verdicts, effective seed and execution resources are available in the complete receipt.
4. For the other modes, use action verify with verify.toml, or action run with margin.toml, rolloff.toml or optimize.toml, keeping every receipt filename new. The native configuration still controls calculation output paths and their overwrite policy.

```text
# Use a matching current 2.9 SDK; its C API must include typed Optimum operations.
$bin = "$env:ProgramFiles\SUN Magnetics\JoSIM-Pro\bin"
python -B optimum_receipt.py inspect yield.toml inspect.json --bin "$bin" --seed 1234
if ($LASTEXITCODE -ne 0) { throw "Inspection failed; read its receipt or diagnostic" }
python -B optimum_receipt.py run yield.toml yield_receipt.json --bin "$bin" --seed 1234
if ($LASTEXITCODE -ne 0) { throw "Study failed; read the native status and exit_code" }
```

## Make decisions from status and artifact identity

The C ABI call result and the native operation result are separate. The client checks the C return value, retrieves an owned result, reads its JSON and native exit code, then releases the result and Runtime exactly once. Domain/configuration failures can still have a valid JSON snapshot.

The client uses the NUL-inclusive two-call string contract, a process-local DLL directory and an explicit seed override mask. It copies JSON up to its own 64 MiB teaching-client limit, refuses an existing receipt and preserves native exit codes. A host write failure can leave a partial JSON file, so validate schema and status as well as process exit and file existence.

Complete receipts contain actual input paths, hashes and configuration text. Keep them with the calculation record and review them before sharing; the teaching download contains no real user receipts or mailbox information.

| Signal | Agent action |
| --- | --- |
| ready / study_complete false | Treat as admitted inspection only; do not report a solved or completed study. |
| passed / study_complete true | Read the mode-specific counts, margins or optimisation outcome; completion alone is not improvement. |
| specification_failed / native exit 2 | The operation returned an owned domain result. Read the failed requirement and preserve the receipt. |
| invalid_configuration / native exit 1 | Correct the named selection, control, input or destination; do not reuse an old result. |
| Client argument exit 64 | The teaching client refused its own argument/receipt setup before running. This is not a native specification verdict. |
| artifact status committed and verified true | For an optimised circuit, compare the saved identity and candidate verification before adoption. A planned path is insufficient. |

## Use the recorded resources and reproducibility contract

The checked default study executes serially with effective_threads = 1. A copied Yield configuration with [execution] threads = 2 reports two effective threads and produces exactly the same 400 assignments and verdicts. Setting an unrelated OpenMP environment value is not evidence of the effective native study policy.

The receipt states its sampling policy and standard-library dependency. Preserve exact inputs, selected parameter order, effective seed and component identities when replay matters. Do not infer cross-platform distribution identity from same-runtime equality.

This synchronous client does not implement callbacks or cancellation. The matching API permits only Runtime_RequestAbort to overlap the operation; general concurrent mutation or callback reentry is not qualified by this example.

## Recover the checked Windows path failure

KB-OPTIMUM-001 remains open on the checked Windows source candidate. With identical files under a directory containing Ω, native inspection returns invalid_configuration and “No mapping for the Unicode character exists in the target multi-byte code page.” The receipt still preserves the UTF-8 configuration path. A space-only directory works.

The checked recovery copies the complete teaching project into a new writable ASCII directory and repeats inspection successfully. Preserve the original files. This establishes that bounded recovery; it does not repair or qualify every Unicode filename/API route, and no Windows locale change is needed for this procedure.

## Complete optimum_receipt.py

```text
"""Inspect or run an Optimum operation through the matching Windows C API."""
import argparse
import ctypes as c
import json
import os
from pathlib import Path
import sys


class Parser(argparse.ArgumentParser):
    def error(self,message):
        self.exit(64,self.prog+': '+message+'\n')


def main():
    # Keep diagnostics usable in a legacy Windows console; receipts remain UTF-8.
    sys.stdout.reconfigure(errors='backslashreplace')
    sys.stderr.reconfigure(errors='backslashreplace')
    parser=Parser(description=__doc__)
    parser.add_argument('action',choices=('inspect','verify','run'))
    parser.add_argument('configuration',type=Path)
    parser.add_argument('receipt',type=Path,help='New JSON filename; existing files are refused')
    parser.add_argument('--bin',type=Path,default=Path(os.environ.get('ProgramFiles',r'C:\Program Files'))/'SUN Magnetics/JoSIM-Pro/bin')
    parser.add_argument('--seed',type=int,help='Unsigned 64-bit explicit runtime seed override')
    args=parser.parse_args()
    if os.name!='nt' or c.sizeof(c.c_void_p)!=8:
        parser.error('This checked client targets Windows x64.')
    if args.seed is not None and not 0<=args.seed<2**64:
        parser.error('--seed must be an unsigned 64-bit integer')
    config=args.configuration.resolve();destination=args.receipt.resolve();binary=args.bin.resolve()
    if destination.exists():parser.error('Receipt exists. Choose a new filename before running the study.')
    if not destination.parent.is_dir():parser.error('Receipt parent directory does not exist.')
    try:text=config.read_text(encoding='utf-8-sig').encode('utf-8')
    except OSError as error:parser.error(str(error))
    path=str(config).encode('utf-8')
    # Keep this process-local DLL directory alive throughout native calls/cleanup.
    directory=os.add_dll_directory(str(binary));runtime=c.c_int(0);result=c.c_int(0);exit_code=1;api=None
    try:
        api=c.WinDLL(str(binary/'josim-pro_CAPI_AMD64.dll'))
        signatures={
            'JPRO_Runtime_Create':([c.POINTER(c.c_int)],c.c_int),
            'JPRO_Runtime_Destroy':([c.c_int],c.c_int),
            'JPRO_Runtime_SetSeed':([c.c_int,c.c_uint64],c.c_int),
            'JPRO_Runtime_GetOverrideMask':([c.c_int,c.POINTER(c.c_uint32)],c.c_int),
            'JPRO_Runtime_SetOverrideMask':([c.c_int,c.c_uint32],c.c_int),
            'JPRO_Optimum_InspectA':([c.c_char_p,c.c_char_p,c.c_int,c.POINTER(c.c_int)],c.c_int),
            'JPRO_Optimum_VerifyA':([c.c_char_p,c.c_char_p,c.c_int,c.POINTER(c.c_int)],c.c_int),
            'JPRO_Optimum_RunStudyA':([c.c_char_p,c.c_char_p,c.c_int,c.POINTER(c.c_int)],c.c_int),
            'JPRO_Optimum_GetExitCode':([c.c_int,c.POINTER(c.c_int)],c.c_int),
            'JPRO_Optimum_GetText':([c.c_int,c.POINTER(c.c_int),c.c_void_p,c.c_int],c.c_int),
            'JPRO_Optimum_Destroy':([c.c_int],c.c_int),
            'JPRO_GetLastError':([],c.c_char_p),
        }
        for name,(arguments,returns) in signatures.items():
            function=getattr(api,name);function.argtypes=arguments;function.restype=returns
        def check(name,*arguments):
            code=getattr(api,name)(*arguments)
            if code!=0:
                message=api.JPRO_GetLastError()
                raise RuntimeError(name+' failed ('+str(code)+'): '+(message.decode('utf-8',errors='replace') if message else ''))
        check('JPRO_Runtime_Create',c.byref(runtime))
        if args.seed is not None:
            check('JPRO_Runtime_SetSeed',runtime,args.seed)
            mask=c.c_uint32();check('JPRO_Runtime_GetOverrideMask',runtime,c.byref(mask))
            # JPRO_OVERRIDE_SEED = 16 in the matching supplied C API header.
            check('JPRO_Runtime_SetOverrideMask',runtime,mask.value|16)
        operation={'inspect':'JPRO_Optimum_InspectA','verify':'JPRO_Optimum_VerifyA','run':'JPRO_Optimum_RunStudyA'}[args.action]
        check(operation,text,path,runtime,c.byref(result))
        if result.value==0:raise RuntimeError('Native operation returned no owned result.')
        needed=c.c_int()
        code=api.JPRO_Optimum_GetText(result,c.byref(needed),None,0)
        # The two-call size includes NUL. This small teaching client caps its copy.
        if code!=-2 or not 1<=needed.value<=64*1024*1024:
            raise RuntimeError('Unexpected receipt size query or receipt above the client 64 MiB limit.')
        buffer=c.create_string_buffer(needed.value)
        check('JPRO_Optimum_GetText',result,c.byref(needed),buffer,len(buffer))
        receipt=json.loads(buffer.value.decode('utf-8'))
        native_exit=c.c_int();check('JPRO_Optimum_GetExitCode',result,c.byref(native_exit))
        if receipt.get('schema')!='optimum-operation/1' or receipt.get('exit_code')!=native_exit.value:
            raise RuntimeError('Native receipt schema or exit-code contract differs from this client.')
        # Save owned JSON even for a native configuration/specification failure.
        # Exclusive creation prevents overwrite; a write failure may leave a partial file.
        with destination.open('x',encoding='utf-8',newline='\n') as stream:
            stream.write(json.dumps(receipt,indent=2,ensure_ascii=False)+'\n')
        print('status='+str(receipt['status'])+' native_exit_code='+str(native_exit.value))
        exit_code=native_exit.value
    except (OSError,ValueError,RuntimeError,AttributeError) as error:
        print(str(error),file=sys.stderr);exit_code=1
    finally:
        # Release each successfully created owned handle exactly once.
        for handle,name in ((result,'JPRO_Optimum_Destroy'),(runtime,'JPRO_Runtime_Destroy')):
            if api is not None and handle.value:
                code=getattr(api,name)(handle)
                if code!=0:
                    message=api.JPRO_GetLastError()
                    print(name+' failed ('+str(code)+'): '+(message.decode('utf-8',errors='replace') if message else ''),file=sys.stderr)
                    exit_code=1
        directory.close()
    return exit_code


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

```

## Sources and verification details

Recorded inputs/builds only. Complete walkthrough and final-package acceptance remain separate.

- VAL-030: JoSIM/Optimum 2.9.0 frozen maintained source, native Windows x64 Clang/OpenMP build, 3 November 2026. Fresh hash-frozen Windows 2.9 source build: complete SP resistor Margin/Yield/roll-off/COG Optimize, analytic bounds and statistics, saved-candidate re-verification, native typed JSON receipts, per-sample seeded identity at one/two threads and guarded failures Sixty-two checks qualify this linear SP fixture and the recorded Windows source candidate. The current Unicode configuration-path issue remains KB-OPTIMUM-001, with ASCII-path recovery checked. GUI run/cancel/adoption screenshots, EVENT/CSV/Josephson/process-distribution validation, other platforms, broad concurrency/callback/cancellation contracts and final distributed packages remain open. Earlier installed review binaries behaved differently and are retained separately.


- josim-pro:docs/manual_source/sections/optimum.tex: Current reviewed Optimum reference; applicable mode/configuration and bounded SP fixture claims
- validation:optimum-current-windows-20261103: VAL-030; fresh native CLI/API execution and recovery
- reviewed:optimum-capi-2.9-20261103T203125: Exact typed operation declarations, owned JSON results, runtime seed override and two-call strings

- Sixty-two checks qualify this linear SP fixture and the recorded Windows source candidate. The current Unicode configuration-path issue remains KB-OPTIMUM-001, with ASCII-path recovery checked. GUI run/cancel/adoption screenshots, EVENT/CSV/Josephson/process-distribution validation, other platforms, broad concurrency/callback/cancellation contracts and final distributed packages remain open. Earlier installed review binaries behaved differently and are retained separately.
- The source reference was reviewed and re-pinned individually after its maintained content changed. Older installed-review observations remain separate; no final package or GUI walkthrough is accepted.

## Related guides

- [Start Optimum™ with a verified nominal circuit](/knowledge-base/optimum-first-verification)
- [Configure and interpret an Optimum™ margin study](/knowledge-base/optimum-margin-workflow)
- [Configure and interpret an Optimum™ yield study](/knowledge-base/optimum-yield-workflow)
- [Run Optimum™ optimisation and verify the saved candidate](/knowledge-base/optimum-optimize-workflow)
- [SP, CSV and EVENT verification give different margins](/knowledge-base/optimum-margin-criteria)
- [Write and run a complete JoSIM circuit netlist](/knowledge-base/josim-netlist-basics)
