diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 21e7898..83cc268 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -90,6 +90,9 @@ jobs: - name: Verify installed caller trial-table experiment run: python -m tools.verify_installed_experiment dist/opensmell-0.1.0-py3-none-any.whl --evidence-directory dist/experiment-proof + - name: Verify passive installed trial observation analysis + run: python -m tools.verify_installed_trial_analysis dist/opensmell-0.1.0-py3-none-any.whl --output dist/experiment-proof/analysis + - name: Retain portable caller experiment proof if: always() uses: actions/upload-artifact@v7.0.2 diff --git a/README.md b/README.md index 804d81a..5d01e03 100644 --- a/README.md +++ b/README.md @@ -1646,6 +1646,10 @@ The active direction covers the installed SDK/CLI, interoperable data, reusable adapters and a reproducible ESP32 bench. Local Explorer remains a demo client. See [the deliverables and exit criteria](docs/development-status.md#active-direction--developer-kit-and-concrete-prototype-2026-11-10). +The installed [`analyze-experiment` entry](docs/trial-analysis.md) joins explicit +caller observation IDs to trial receipts and exports loss-preserving JSON/CSV for +external analysis. Execution completion never creates a measurement. + The installed [`run-experiment` entry](docs/run-experiment.md) consumes one verified prepared dossier in caller order, with explicit software transport selection and retained trial IDs/receipts. It also exposes a transport-neutral SDK entry. diff --git a/docs/autonomous-development.md b/docs/autonomous-development.md index 1e875a8..2bf314a 100644 --- a/docs/autonomous-development.md +++ b/docs/autonomous-development.md @@ -78,6 +78,8 @@ this protocol before changing project files. Read-only inspection needs no lease Create a tree containing only `state.json`, then a commit whose parent is the observed control head. Move the branch with an **expected-head-SHA check** and `force=false`. The GitHub `update_ref` tool supports `expected_sha`. + Initialize coordination functions in the current run; fail on missing helpers. + Confirm acquisition from a newly fetched remote state, never the local object. 3. A rejected lease means another session won: stop, rather than retrying with a newer SHA. Re-read state and verify ownership before making project changes. 4. Do not extend the lease. The initial 240-minute maximum supports the increased diff --git a/docs/development-status.md b/docs/development-status.md index b25b070..ef7ae18 100644 --- a/docs/development-status.md +++ b/docs/development-status.md @@ -5,6 +5,23 @@ The broader roadmap remains in the [README](../README.md#roadmap). Operational checkpoints and the short session log live in `state.json` on the `automation/control` branch; follow its pending PR before starting new work. +## Trial observation analysis — 2026-11-25 + +The first installed dossier execution path (#46) is closed. The next concrete +data/SDK slice is [passive trial observation analysis](trial-analysis.md): explicit +caller bindings connect separately supplied observation IDs to retained receipts, +with loss-preserving JSON and CSVs for external analysis. Reuse existing perceptual +projection; never infer a measurement from completion or invent trial observations. + +Exit: installed prepare/run/analyze outside checkout, relocated dossier and removed +originals, distinct trial IDs in caller order, explicit synthetic imported data, +Pandas CSV consumer, exact bytes/provenance/unknown data retained; missing/zero/unit +semantics preserved; uncertain/unrecorded receipts, ambiguous/unmatched bindings, +stale report and collision behaviors demonstrated. Close this first analysis slice +after CI. Next choose an independent integration/data need from the whole kit, +not endless receipt diagnostics or scheduler/retry extensions. Physical board and +independent adoption evidence remain unobserved. + ## Prepared dossier execution — 2026-11-24 evening The reusable sequence core/manual serial slice (#44/#45) is closed. The next diff --git a/docs/trial-analysis.md b/docs/trial-analysis.md new file mode 100644 index 0000000..c79ec6e --- /dev/null +++ b/docs/trial-analysis.md @@ -0,0 +1,111 @@ +# Analyze trial observations (experimental) + +`analyze-experiment` passively joins a selected prepared dossier, its retained +`run-experiment` receipt report and **separately supplied** observation data. +Explicit CSV bindings select `trial_id,observation_id`; neither equal names nor +execution completion infer a measurement. No transport is constructed or opened. + +## Installed entry + +Prepare/run a dossier through [run-experiment](run-experiment.md), then supply a +Generic ResourceGraph0.1 containing your observations and a UTF-8 binding CSV: + +```csv +trial_id,observation_id,caller_note +first,EXPLICIT_OBSERVATION_ID_A,declared association +second,EXPLICIT_OBSERVATION_ID_B,declared association +``` + +Use the **observation resource ID**, not a stimulus, subject or molecule ID. CSV +order does not reorder trials. Additional columns remain opaque caller context. +IDs are explicit nonblank strings up to128 characters. A trial can have several +observations; each observation can bind exactly once. Repeated observation IDs, +including duplicate pairs, are ambiguous: all competing associations are retained +in diagnostics and excluded from joined measurement/category rows. No first/last +winner or averaging is chosen. + +```sh +opensmell analyze-experiment experiment --report execution-report.json \ + --observations supplied-observations.osmell --bindings associations.csv \ + --output-directory new-analysis +``` + +Original preparation inputs need not exist; the dossier can be relocated. The +whole dossier is reverified. The report must retain that exact dossier manifest, +inputs, caller order and per-step plans. A stale/different dossier, altered plan +snapshot or contradictory step/execution state refuses before output creation. +This checks declared consistency, **not authenticity of a receipt**. A report +without sequence receipts is retained as `unrecorded`, never `not_attempted` or +`completed`. Accepted/running/future states and unfinished reports remain partial. + +Outputs in a new exclusive directory: + +| File | Content | +| --- | --- | +| `analysis.json` | Exact input snapshots, complete observation projection/context, explicit bindings, joined numeric/category rows and coverage issues | +| `trials.csv` | Caller order, original record, receipt state/IDs, selected observation IDs and result counts | +| `measurements.csv` | Joined known perceptual0.1 numeric rows with trial, receipt state, source path/digest, scale/unit and binding context | + +Unknown observation contracts, invalid/unmeasured results, unmatched IDs and +ambiguous bindings stay in the original snapshots/context and coverage diagnostics. +They are never guessed, skipped silently or coerced to numeric rows. Recognized +observation categories stay opaque in JSON, separate from numeric CSV. Semantic +annotations are not observation measurements and are not joined by coincident ID. + +`status=joined` means complete coverage **within this projection**; it does not +mean successful scientific design, authenticated data or reproduced odor. Partial +coverage still produces usable tables and complete retained input. Exit0 joined; +3 partial;1 invalid;2 filesystem error/collision. Invalid input creates no output; +a write failure after exclusive creation leaves an incomplete marker. Existing +directories/reports are never overwritten. Analysis never rewrites its inputs. + +Units and scales are not converted. Zero remains zero, absent measurements produce +no row, and absent/null unit fields have distinct `unit_presence` values. Mixed +units are not pooled. Integer values are not converted to floats. CSV exports raw +caller strings (including opaque fields); choose appropriate types and spreadsheet +import settings. For a loss-preserving Pandas consumer: + +```python +import pandas as pd +rows = pd.read_csv("new-analysis/measurements.csv", dtype="string", keep_default_na=False) +# Select explicit property/unit/scale groups before any caller-chosen conversion. +``` + +## SDK + +```python +from opensmell.experimental.trial_analysis import analyze_experiment, write_analysis_directory +result = analyze_experiment("experiment", report_bytes, observation_graph_bytes, binding_csv_bytes) +write_analysis_directory(result, "new-analysis") +``` + +Inputs are bounded at64MiB for the report,8MiB for observations and64KiB/4096rows +for bindings; existing dossier/sequence bounds still apply. Exact report, graph, +bindings, dossier input and plan bytes remain available. Source/provenance/unknown +fields and excluded rows are retained, not reduced to the CSV projection. Files +are local and the dossier check uses disposable compiler temporary files. + +## Evidence and limits + +```sh +python -m build --wheel +python -m tools.verify_installed_trial_analysis dist/opensmell-0.1.0-py3-none-any.whl \ + --output /tmp/new-trial-analysis-proof +``` + +The proof installs a wheel outside the checkout, imports **declared synthetic** +Keller-style rows through the normal entry, prepares/runs a relocated dossier on +the explicitly selected installed software simulator, then analyzes it through +the normal CLI and an optional Pandas consumer. Caller trial order survives reversed +observation graph order. Zero, missing values, categorical context, unknown fields, +exact source bytes, uncertain receipts, duplicate associations, stale reports and +output collisions are checked. Build/Pandas dependencies are inherited; this is +not a new clean offline dependency proof or independent third-party adoption. + +The supplied observations can predate the software run. Binding is a caller claim, +not inferred stimulus equivalence, synchronization, causation or efficacy. An +unknown/not-attempted trial can still have caller-supplied observation rows; these +are retained beside the receipt state, not relabeled as an execution result. +This entry does not generate observations, normalize ratings, estimate statistics, +contact participants, run hardware, validate a device or measure an olfactory +outcome. Human electrical/olfactory validation remains a separate unobserved gate. diff --git a/examples/developer_kit/START_HERE.md b/examples/developer_kit/START_HERE.md index a09bda0..cd6a1e9 100644 --- a/examples/developer_kit/START_HERE.md +++ b/examples/developer_kit/START_HERE.md @@ -201,3 +201,5 @@ recipe never authorizes autonomous physical commands; verification uses owned pseudo-terminals only. Existing software sequence commands remain unchanged. For a whole caller-ordered prepared dossier, see [RUN_EXPERIMENT.md](RUN_EXPERIMENT.md). + +For passive receipt/observation joins and CSV analysis, see [TRIAL_ANALYSIS.md](TRIAL_ANALYSIS.md). diff --git a/src/opensmell/cli.py b/src/opensmell/cli.py index c697440..42293db 100644 --- a/src/opensmell/cli.py +++ b/src/opensmell/cli.py @@ -227,6 +227,27 @@ def _prepare_experiment_command(args): print(json.dumps({"status":"invalid","error":str(error)})); return 1 +def _analyze_experiment_command(args): + from .experimental.trial_analysis import analyze_experiment, write_analysis_directory + from .experimental.trial_analysis import MAX_REPORT_BYTES, MAX_OBSERVATION_BYTES, MAX_BINDING_BYTES + import csv + try: + raws = [] + for path, bound in ((args.report, MAX_REPORT_BYTES), (args.observations, MAX_OBSERVATION_BYTES), (args.bindings, MAX_BINDING_BYTES)): + with Path(path).open("rb") as source: + raws.append(source.read(bound+1)) + result = analyze_experiment(args.directory, *raws) + write_analysis_directory(result, args.output_directory) + print(json.dumps({"status":result["status"], "execution":"not_attempted", "physical_validation":False, + "trial_count":len(result["tables"]["trials"]), "measurement_count":len(result["tables"]["measurements"]), + "issue_count":len(result["coverage"]["issues"])})) + return 3 if result["status"] == "partial" else 0 + except OSError as error: + print(json.dumps({"status":"error", "error":str(error)}), file=sys.stderr); return 2 + except (OpenSmellError, ValueError, TypeError, KeyError, RecursionError, OverflowError, csv.Error) as error: + print(json.dumps({"status":"invalid", "error":str(error)}), file=sys.stderr); return 1 + + def _run_experiment_command(args): from .experimental.experiment_run import run_prepared_experiment from .experimental.process_transport import ProcessTransport @@ -619,6 +640,12 @@ def main(argv: list[str] | None = None) -> int: experiment.add_argument("--graph", required=True, help="Explicit source ResourceGraph") experiment.add_argument("--profile", required=True, help="Explicit mapping/capability profile for every trial") experiment.add_argument("--output-directory", required=True, help="New portable experiment directory; never overwrite") + analysis = commands.add_parser("analyze-experiment", help="Passively join explicit observation IDs to a prepared dossier's execution receipts") + analysis.add_argument("directory", help="Selected prepared-experiment directory") + analysis.add_argument("--report", required=True, help="Retained run-experiment receipt report; max64MiB") + analysis.add_argument("--observations", required=True, help="Separately supplied observation ResourceGraph; max8MiB") + analysis.add_argument("--bindings", required=True, help="Explicit trial_id,observation_id CSV; max64KiB") + analysis.add_argument("--output-directory", required=True, help="New analysis.json/trials.csv/measurements.csv directory; never overwrite") run_experiment = commands.add_parser("run-experiment", help="Verify and run one prepared experiment on explicitly selected trusted software") run_experiment.add_argument("directory", help="Explicit prepared-experiment directory; never selects transport") run_experiment.add_argument("--software-command-json", required=True, help="Trusted executable/argument JSON array; no shell; not sandboxed") @@ -646,6 +673,8 @@ def main(argv: list[str] | None = None) -> int: return _plan_core_command(args) if args.command == "prepare-experiment": return _prepare_experiment_command(args) + if args.command == "analyze-experiment": + return _analyze_experiment_command(args) if args.command == "run-experiment": return _run_experiment_command(args) if args.command == "run-sequence": diff --git a/src/opensmell/experimental/trial_analysis.py b/src/opensmell/experimental/trial_analysis.py new file mode 100644 index 0000000..1aad1c6 --- /dev/null +++ b/src/opensmell/experimental/trial_analysis.py @@ -0,0 +1,177 @@ +"""Passive explicit trial/observation join; never constructs or opens a transport.""" +import csv +from dataclasses import asdict +from collections import Counter +from copy import deepcopy +import io +import json +from pathlib import Path + +from .._json import decode_bytes +from .experiment_run import load_prepared_experiment +from .frame_export import _snapshot +from .observation_table import observation_table +from .transport_sequence import prepare_steps + +MAX_REPORT_BYTES = 64 * 1048576 +MAX_OBSERVATION_BYTES = 8 * 1048576 +MAX_BINDING_BYTES = 65536 +TERMINAL = {'completed', 'stopped', 'rejected', 'unknown', 'not_attempted'} + + +def analyze_experiment(directory, report_raw, observations_raw, bindings_raw): + """Join explicit CSV trial_id,observation_id pairs to known observation rows. + + Exact inputs are retained; unmatched/ambiguous bindings and unfinished receipts + make the result partial, never fabricate zero/missing measurements. Reports are + unauthenticated declarations; consistency is not proof of physical delivery. + """ + for raw, bound in ((report_raw, MAX_REPORT_BYTES), (observations_raw, MAX_OBSERVATION_BYTES), + (bindings_raw, MAX_BINDING_BYTES)): + if not isinstance(raw, bytes) or len(raw) > bound: + raise ValueError('Report/observations/bindings require bytes within 64 MiB/8 MiB/64 KiB') + plans, context = load_prepared_experiment(directory) + report = decode_bytes(report_raw) + if (not isinstance(report, dict) or report.get('format') != 'org.opensmell.experimental.transport-sequence' + or report.get('version') != '0.1' or report.get('physical_validation') is not False): + raise ValueError('Expected experimental transport-sequence0.1 report without physical validation') + retained = report.get('prepared_experiment') + if not isinstance(retained, dict) or any(retained.get(k) != v for k,v in context.items()): + raise ValueError('Report belongs to a different or altered prepared dossier') + projected = observation_table(observations_raw) + issues = [{'scope':'observations', **deepcopy(i)} for i in projected['coverage']['issues']] + def issue(code, **details): + issues.append({'scope':'join', 'code':code, **details}) + sequence = report.get('sequence') + expected_steps = prepare_steps(plans) + steps = [None] * len(plans) + if sequence is None: + issue('no_sequence_receipts') + else: + if (not isinstance(sequence, dict) or sequence.get('format') != 'org.opensmell.experimental.sequence' + or sequence.get('version') != '0.1' or not isinstance(sequence.get('steps'), list) + or len(sequence['steps']) != len(plans)): + raise ValueError('Expected one ordered sequence step per prepared trial') + steps = sequence['steps'] + if sequence.get('physical_validation') is not False: + raise ValueError('Contradictory physical-validation declaration in sequence') + if report.get('status') == 'completed' and (sequence.get('status') != 'completed' + or any(not isinstance(step, dict) or step.get('state') != 'completed' for step in steps)): + raise ValueError('Completed report requires every declared sequence step to be completed') + for step, expected, trial in zip(steps, expected_steps, context['trial_order']): + if (not isinstance(step, dict) or step.get('step_id') != expected.step_id + or step.get('trial_id') != trial['trial_id'] or step.get('plan') != asdict(expected.plan) + or not isinstance(step.get('context'), dict) + or any(step['context'].get(k) != v for k,v in expected.context.items()) + or not isinstance(step.get('state'), str)): + raise ValueError('Sequence step/plan snapshot does not match selected dossier') + execution = step.get('execution') + if ((execution is None and step['state'] != 'not_attempted') + or (execution is not None and (not isinstance(execution, dict) + or execution.get('state') != step['state'] + or execution.get('request_id') != step.get('request_id') + or step['state'] == 'not_attempted'))): + raise ValueError('Inconsistent declared step and execution states') + if step['state'] not in TERMINAL: + issue('unfinished_or_uninterpreted_receipt', trial_id=trial['trial_id'], state=step['state']) + if report.get('phase') != 'finished': + issue('unfinished_report', phase=report.get('phase')) + # A failed live preflight can leave a non-complete report whose steps are all + # not_attempted. Preserve this declaration separately rather than inventing IO. + if report.get('status') != 'completed': + issue('sequence_not_completed', declared_status=report.get('status')) + reader = csv.reader(io.StringIO(bindings_raw.decode('utf-8-sig'), newline=''), strict=True) + try: + header = next(reader) + except StopIteration: + raise ValueError('Bindings CSV header required') from None + if (not {'trial_id','observation_id'}.issubset(header) or len(set(header)) != len(header) + or any(not h.strip() for h in header)): + raise ValueError('Unique nonblank headers including trial_id,observation_id required') + records = [] + for row in reader: + if len(records) >= 4096 or len(row) != len(header): + raise ValueError('At most4096 complete binding rows; no ragged/blank rows') + record = dict(zip(header,row)) + if any(not record[k].strip() or len(record[k]) > 128 for k in ('trial_id','observation_id')): + raise ValueError('Explicit trial/observation IDs of1–128 characters required') + records.append(record) + trial_ids = {t['trial_id'] for t in context['trial_order']} + obs_ids = {o['observation_id'] for o in projected['tables']['observations']} + counts = Counter(r['observation_id'] for r in records) + bindings, selected = [], {} + for index, record in enumerate(records): + trial, obs = record['trial_id'], record['observation_id'] + problems = [] + if trial not in trial_ids: problems.append('unmatched_trial') + if obs not in obs_ids: problems.append('unmatched_observation') + if counts[obs] != 1: problems.append('ambiguous_observation_binding') + for code in problems: issue(code, binding_index=index, trial_id=trial, observation_id=obs) + bindings.append({'binding_index':index, 'record':record, 'status':'unmatched_or_ambiguous' if problems else 'joined'}) + if not problems: + selected[obs] = (trial, index, record) + trials = [] + for trial, step in zip(context['trial_order'], steps): + matched = [o for o,b in selected.items() if b[0] == trial['trial_id']] + if not matched: issue('trial_without_observation', trial_id=trial['trial_id']) + state = step['state'] if step else 'unrecorded' + execution = step.get('execution') if step else None + trials.append({'ordinal':trial['ordinal'], 'trial_id':trial['trial_id'], + 'caller_record':deepcopy(trial['record']), 'receipt_state':state, + 'request_id':step.get('request_id') if step else None, + 'execution_id':execution.get('execution_id') if execution else None, + 'observation_ids':matched}) + for obs in sorted(obs_ids - selected.keys()): issue('observation_without_trial', observation_id=obs) + by_trial = {t['trial_id']:t for t in trials} + def join(rows): + joined = [] + for row in rows: + # Categorical projections include semantic annotations. They are not + # observations and must never be assigned merely by an equal ID. + obs = row.get('observation_id') or (row.get('resource_id') if row.get('kind') == 'observation_categories' else None) + if obs not in selected: continue + trial, index, record = selected[obs] + joined.append({**deepcopy(row), 'trial_id':trial, + 'ordinal':by_trial[trial]['ordinal'], 'receipt_state':by_trial[trial]['receipt_state'], + 'binding_index':index, 'binding_record':deepcopy(record)}) + return sorted(joined, key=lambda row: row["ordinal"]) + measurements = join(projected['tables']['measurements']) + categorical = join(projected['tables']['categorical']) + for trial in trials: + trial['measurement_count'] = sum(r['trial_id'] == trial['trial_id'] for r in measurements) + trial['categorical_count'] = sum(r['trial_id'] == trial['trial_id'] for r in categorical) + for obs in selected: + if not any(r['observation_id'] == obs for r in projected['tables']['measurements']) and not any( + r.get('kind') == 'observation_categories' and r['resource_id'] == obs for r in projected['tables']['categorical']): + issue('observation_without_projected_results', observation_id=obs) + return {'format':'org.opensmell.experimental.trial-analysis', 'version':'0.1', + 'experimental':True, 'status':'partial' if issues else 'joined', + 'execution':'not_attempted', 'physical_validation':False, + 'inputs':{'execution_report':_snapshot(report_raw), 'observations':_snapshot(observations_raw), + 'bindings':_snapshot(bindings_raw), 'prepared_experiment':context}, + 'tables':{'trials':trials, 'measurements':measurements, + 'categorical':categorical, 'bindings':bindings}, + 'observation_projection':projected, 'coverage':{'issues':issues}, + 'limits':['Passive explicit ID join; no transport, retry, normalization, imputation, statistics or efficacy claim.', + 'Each observation may bind once; repeats/ambiguous associations are retained but excluded from joined rows.', + 'Receipt state, source observation and measured odor outcome remain distinct. Reports and observations are unauthenticated.', + 'Units/scales and missing/null unit presence are retained. No measurement is generated for absence.', + 'Joined only denotes complete coverage in this projection, not scientific validity or physical verification.']} + + +def write_analysis_directory(result, directory): + """Exclusive output; incomplete marker remains if writing fails.""" + output = Path(directory); output.mkdir(parents=True, exist_ok=False) + marker = output/'analysis.json'; marker.write_text('{"status":"incomplete","execution":"not_attempted"}\n') + columns = {'trials':['ordinal','trial_id','receipt_state','request_id','execution_id','observation_ids','measurement_count','categorical_count','caller_record'], + 'measurements':['ordinal','trial_id','receipt_state','observation_id','stimulus_id','target_id', + 'property','value','scale_min','scale_max','unit','unit_presence', + 'source_sha256','source_path','result_index','measurement_index','binding_index','binding_record']} + for table, fields in columns.items(): + with (output/(table+'.csv')).open('x', encoding='utf-8', newline='') as target: + writer = csv.DictWriter(target, fieldnames=fields); writer.writeheader() + for row in result['tables'][table]: + writer.writerow({k: json.dumps(row[k], ensure_ascii=True, allow_nan=False) if isinstance(row.get(k),(dict,list)) else row.get(k) for k in fields}) + with (output/'analysis.pending').open('x', encoding='utf-8') as target: + json.dump(result, target, indent=2, allow_nan=False); target.write('\n') + (output/'analysis.pending').replace(marker) diff --git a/tests/test_trial_analysis.py b/tests/test_trial_analysis.py new file mode 100644 index 0000000..c173d43 --- /dev/null +++ b/tests/test_trial_analysis.py @@ -0,0 +1,132 @@ +"""Explicit passive observation joins; no inference from execution completion.""" +import base64 +from copy import deepcopy +import csv +import io +import json +import shutil +import subprocess +import sys + +import pytest +from opensmell.experimental.experiment import prepare_experiment +from opensmell.experimental.experiment_run import run_prepared_experiment +from opensmell.experimental.trial_analysis import analyze_experiment, write_analysis_directory +from test_experiment import TABLE, GRAPH, PROFILE +from test_transport_sequence import Transport, ID + + +def encode(obj):return (json.dumps(obj,ensure_ascii=True)+'\n').encode() + +@pytest.fixture +def inputs(tmp_path): + dossier=tmp_path/'dossier';prepare_experiment(TABLE,GRAPH,PROFILE,dossier) + report=run_prepared_experiment(dossier,lambda:Transport(),expected_device_id=ID) + graph=json.loads(GRAPH);graph['analysis_fixture']='Declared synthetic join example, not a measured device outcome' + obs=next(r for r in graph['resources'] if r['type']=='observation');obs['id']='observation-A' + obs['results']=[{'scheme':{'id':'org.opensmell.perceptual.measurements','version':'0.1'}, + 'data':{'measurements':[{'property':'zero','value':0,'scale':{'min':0,'max':100},'unit':'rating','future':{'keep':2**70}}, + {'property':'missing-unit','value':3,'scale':{'min':0,'max':5}}, + {'property':'null-unit','value':4,'scale':{'min':0,'max':10},'unit':None}]}}] + other=deepcopy(obs);other['id']='observation-B';graph['resources'].append(other) + bindings=b'trial_id,observation_id,note\r\nfirst,observation-A,"quoted, opaque"\r\nsecond,observation-B,caller\r\n' + return dossier,report,graph,bindings + + +def analyze(inputs): + d,r,g,b=inputs;return analyze_experiment(d,encode(r),encode(g),b) + + +def test_join_exact_inputs_order_unknown_units_and_csv(inputs,tmp_path,monkeypatch): + # Analysis must not even construct a transport; report is already supplied. + monkeypatch.setattr(subprocess,'Popen',lambda *a,**k:pytest.fail('Passive analysis launched a process')) + result=analyze(inputs) + assert result['status']=='joined' and result['execution']=='not_attempted' and not result['physical_validation'] + assert [t['trial_id'] for t in result['tables']['trials']]==['first','second'] + rows=result['tables']['measurements'];assert len(rows)==6 + assert [(m['unit_presence'],m['value']) for m in rows[:3]]==[('value',0),('missing',3),('null',4)] + assert rows[0]['binding_record']['note']=='quoted, opaque' + assert base64.b64decode(result['inputs']['observations']['data'])==encode(inputs[2]) + assert base64.b64decode(result['inputs']['execution_report']['data'])==encode(inputs[1]) + assert result['observation_projection']['context']['analysis_fixture']==inputs[2]['analysis_fixture'] + out=tmp_path/'tables';write_analysis_directory(result,out) + csvrows=list(csv.DictReader(io.StringIO((out/'measurements.csv').read_text()))) + assert csvrows[0]['value']=='0' and csvrows[1]['unit_presence']=='missing' and csvrows[2]['unit_presence']=='null' + before=(out/'analysis.json').read_bytes() + with pytest.raises(FileExistsError):write_analysis_directory(result,out) + assert (out/'analysis.json').read_bytes()==before + + +@pytest.mark.parametrize('mode,state',[('lost','unknown'),('refused','rejected')]) +def test_uncertain_refused_receipts_do_not_become_measurements(inputs,mode,state): + d,r,g,b=inputs + r=run_prepared_experiment(d,lambda:Transport(mode),expected_device_id=ID) + result=analyze((d,r,g,b)) + assert result['status']=='partial' + assert [t['receipt_state'] for t in result['tables']['trials']]==['completed',state] + assert len(result['tables']['measurements'])==6 # caller observations retained, not generated/dropped by receipt + assert not result['physical_validation'] + + +def test_no_receipts_and_unfinished_snapshot(inputs): + d,r,g,b=inputs;r['sequence']=None;r['phase']='connect';r['status']='incomplete' + result=analyze((d,r,g,b));assert result['status']=='partial' + assert all(t['receipt_state']=='unrecorded' for t in result['tables']['trials']) + assert {'no_sequence_receipts','unfinished_report'} <= {i['code'] for i in result['coverage']['issues']} + + +@pytest.mark.parametrize('kind',['manifest','plan','trial','state','execution','format','length','aggregate','physical']) +def test_report_cannot_bind_to_another_dossier(inputs,kind): + d,r,g,b=inputs + if kind=='manifest':r['prepared_experiment']['manifest']['sha256']='0'*64 + if kind=='plan':r['sequence']['steps'][1]['context']['input']['data']='' + if kind=='trial':r['sequence']['steps'][1]['trial_id']='first' + if kind=='state':r['sequence']['steps'][0]['state']='unknown' + if kind=='execution':r['sequence']['steps'][0]['execution']=None + if kind=='format':r['format']='future' + if kind=='length':r['sequence']['steps'].pop() + if kind=='aggregate':r['sequence']['status']='unknown' + if kind=='physical':r['sequence']['physical_validation']=True + with pytest.raises(ValueError):analyze((d,r,g,b)) + + +@pytest.mark.parametrize('bindings,codes',[ + (b'trial_id,observation_id\nunknown,observation-A\n',{'unmatched_trial','trial_without_observation'}), + (b'trial_id,observation_id\nfirst,absent\n',{'unmatched_observation'}), + (b'trial_id,observation_id\nfirst,observation-A\nsecond,observation-A\n',{'ambiguous_observation_binding'}), + (b'trial_id,observation_id\nfirst,observation-A\nfirst,observation-A\n',{'ambiguous_observation_binding'}), + (b'trial_id,observation_id\n',{'trial_without_observation','observation_without_trial'})]) +def test_unmatched_ambiguous_bindings_preserved_without_double_count(inputs,bindings,codes): + d,r,g,b=inputs;result=analyze((d,r,g,bindings)) + assert result['status']=='partial' and result['tables']['measurements']==[] + assert codes <= {i['code'] for i in result['coverage']['issues']} + assert base64.b64decode(result['inputs']['bindings']['data'])==bindings + + +@pytest.mark.parametrize('bindings',[b'',b'trial_id,trial_id\nx,y\n',b'trial_id,observation_id\nx\n', + b'trial_id,observation_id\n,observation-A\n',b'trial_id,observation_id\n\n',b'x'*65537]) +def test_invalid_csv_not_silently_skipped(inputs,bindings): + d,r,g,b=inputs + with pytest.raises(ValueError):analyze((d,r,g,bindings)) + + +def test_unknown_scheme_and_no_results_stay_partial(inputs): + d,r,g,b=inputs;obs=next(o for o in g['resources'] if o['id']=='observation-A') + obs['results'][0]['scheme']['version']='future' + result=analyze(inputs) + assert result['status']=='partial' and len(result['tables']['measurements'])==3 + assert any(i['code']=='observation_without_projected_results' for i in result['coverage']['issues']) + assert result['observation_projection']['context']==g + + +def test_normal_cli_moved_dossier_collision_and_stale_report(inputs,tmp_path): + d,r,g,b=inputs;moved=tmp_path/'moved';shutil.move(d,moved) + for name,raw in [('report.json',encode(r)),('observations.osmell',encode(g)),('bindings.csv',b)]: (tmp_path/name).write_bytes(raw) + out=tmp_path/'analysis';cmd=[sys.executable,'-m','opensmell','analyze-experiment',str(moved),'--report',str(tmp_path/'report.json'), + '--observations',str(tmp_path/'observations.osmell'),'--bindings',str(tmp_path/'bindings.csv'),'--output-directory',str(out)] + result=subprocess.run(cmd,capture_output=True);assert result.returncode==0,result.stderr + original=(out/'analysis.json').read_bytes();assert subprocess.run(cmd,capture_output=True).returncode==2 + assert (out/'analysis.json').read_bytes()==original + r['prepared_experiment']['trial_order'].reverse();(tmp_path/'report.json').write_bytes(encode(r)) + cmd[-1]=str(tmp_path/'refused') + assert subprocess.run(cmd,capture_output=True).returncode==1 and not (tmp_path/'refused').exists() diff --git a/tools/build_developer_kit.py b/tools/build_developer_kit.py index 2e6d982..01f4a83 100644 --- a/tools/build_developer_kit.py +++ b/tools/build_developer_kit.py @@ -21,6 +21,7 @@ ROOT = Path(__file__).resolve().parents[1] # Explicit allowlist; external datasets, caches and arbitrary checkout files are excluded. PAYLOADS = { + "TRIAL_ANALYSIS.md": "docs/trial-analysis.md", "RUN_EXPERIMENT.md": "docs/run-experiment.md", "TRANSPORT_SEQUENCES.md": "docs/transport-sequences.md", "WHEEL_STARTER.md": "docs/wheel-starter.md", diff --git a/tools/verify_installed_trial_analysis.py b/tools/verify_installed_trial_analysis.py new file mode 100644 index 0000000..d1d6a96 --- /dev/null +++ b/tools/verify_installed_trial_analysis.py @@ -0,0 +1,123 @@ +"""Installed synthetic trial/observation pipeline; analysis never starts a device.""" +import argparse +import base64 +import csv +from copy import deepcopy +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import venv + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('wheel',type=Path);parser.add_argument('--output',type=Path,required=True) + args=parser.parse_args();wheel=args.wheel.resolve(strict=True);output=args.output.resolve() + output.mkdir(parents=True,exist_ok=False);root=Path(__file__).resolve().parents[1] + proof={'result':'incomplete','source_kind':'synthetic','physical_validation':False} + def save():(output/'result.json').write_text(json.dumps(proof,indent=2)+'\n') + save() + with tempfile.TemporaryDirectory(prefix='opensmell-installed-trial-analysis-') as tmp: + work=Path(tmp);venv.EnvBuilder(with_pip=True,system_site_packages=True).create(work/'venv') + python=work/'venv'/('Scripts/python.exe' if os.name=='nt' else 'bin/python') + env={k:v for k,v in os.environ.items() if k not in {'PYTHONPATH','PYTHONHOME'}} + def run(command,code=0): + r=subprocess.run(list(map(str,command)),cwd=work,env=env,capture_output=True,timeout=60) + assert r.returncode==code,(command,r.returncode,r.stdout[-1000:],r.stderr[-1000:]) + return r.stdout + def cli(*command,code=0):return run([python,'-I','-m','opensmell',*command],code) + run([python,'-m','pip','install','--no-deps','--no-index','--ignore-installed',wheel]) + location=run([python,'-I','-c','import opensmell;print(opensmell.__file__)']).decode().strip() + assert Path(location).is_relative_to(work/'venv') + proof['installed_outside_checkout']=True + proof['dependency_scope']='Installed wheel with inherited build/Pandas dependencies, not clean offline closure' + # Import explicitly synthetic source; do not invent or claim participant data. + source=work/'source.json';source.write_bytes((root/'examples/synthetic_keller_source.json').read_bytes()) + original=work/'observations.csv';original.write_bytes((root/'examples/synthetic_keller.csv').read_bytes()) + parts=[];ids=[] + for index in (1,2,3): + path=work/f'part-{index}.osmell' + cli('import-keller',original,'--source',source,'--row',index,'--output',path) + part=json.loads(path.read_bytes());parts.append(part) + ids.append(next(r['id'] for r in part['resources'] if r['type']=='observation')) + graph=deepcopy(parts[0]);resources={} + for part in parts: + for resource in part['resources']: + if resource['id'] in resources:assert resources[resource['id']]==resource + resources[resource['id']]=resource + graph['resources']=list(reversed(list(resources.values()))) # graph order must not determine trial order + graph['org.example.synthetic-join-proof']={'parts':parts,'unknown':[None,2**70], + 'scope':'Synthetic declared source observations; not outcomes measured from the software run'} + graph_raw=(json.dumps(graph,indent=3)+'\n').encode() + observations=work/'observations.osmell';observations.write_bytes(graph_raw) + planning_source=work/'planning-source.osmell';planning_source.write_bytes(graph_raw) + profile=work/'profile.json';profile.write_bytes((root/'examples/offline_perceptual_profile.json').read_bytes()) + table=work/'trials.csv';table.write_text('trial_id,resource_id,duration,note\n'+''.join( + f'{trial},{rid},{duration},{note}\n' for trial,rid,duration,note in + [('trial-A',ids[0],.1,'caller-A'),('trial-B',ids[1],.2,'caller-B'),('trial-C',ids[0],.1,'caller-C')])) + cli('prepare-experiment',table,'--graph',planning_source,'--profile',profile,'--output-directory',work/'original-dossier') + moved=work/'relocated dossier';shutil.move(work/'original-dossier',moved) + for path in [source,original,profile,table,planning_source,*[work/f'part-{i}.osmell' for i in (1,2,3)]]:path.unlink() + report=output/'completed-report.json' + cli('run-experiment',moved,'--software-command-json',json.dumps([str(python),'-I','-m','opensmell','simulate-device']), + '--expected-device-id','opensmell-local-simulator-001','--action','complete','--output',report) + bindings=work/'bindings.csv';bindings.write_text('trial_id,observation_id,declared_context\n'+''.join( + f'trial-{trial},{oid},explicit-synthetic-association\n' for trial,oid in zip('ABC',ids))) + binding_raw=bindings.read_bytes() + def analysis(name,receipt=report,code=0): + cli('analyze-experiment',moved,'--report',receipt,'--observations',observations,'--bindings',bindings, + '--output-directory',output/name,code=code) + return json.loads((output/name/'analysis.json').read_bytes()) + joined=analysis('joined') + assert joined['status']=='joined' and len(joined['tables']['measurements'])==6 + assert [t['trial_id'] for t in joined['tables']['trials']]==['trial-A','trial-B','trial-C'] + assert [t['measurement_count'] for t in joined['tables']['trials']]==[4,2,0] + assert [r['ordinal'] for r in joined['tables']['measurements']]==[1]*4+[2]*2 + assert base64.b64decode(joined['inputs']['observations']['data'])==graph_raw + assert base64.b64decode(joined['inputs']['bindings']['data'])==binding_raw + assert base64.b64decode(joined['inputs']['execution_report']['data'])==report.read_bytes() + assert not any(m['property']=='pleasantness' for m in joined['tables']['measurements']) + assert next(m for m in joined['tables']['measurements'] if m['property']=='grass')['value']==0 + run([python,'-I','-c',"import pandas as p;d=p.read_csv(r'"+str(output/'joined/measurements.csv')+"',dtype='string',keep_default_na=False);assert list(d.trial_id.unique())==['trial-A','trial-B'];assert d.loc[d.property=='grass','value'].iloc[0]=='0'"]) + before=(output/'joined/analysis.json').read_bytes() + cli('analyze-experiment',moved,'--report',report,'--observations',observations,'--bindings',bindings,'--output-directory',output/'joined',code=2) + assert (output/'joined/analysis.json').read_bytes()==before + # SDK-produced uncertain receipt, not a hand-edited successful report. + consumer=work/'uncertain.py';consumer.write_text('''import json,sys +from opensmell.experimental.experiment_run import run_prepared_experiment +from opensmell.experimental.lifecycle_simulator import SimulatedEndpoint +class Lost: + def __init__(self):self.t=SimulatedEndpoint();self.renders=0 + def exchange(self,line): + req=json.loads(line);reply=self.t.exchange(line) + if req['type']=='render': + self.renders+=1 + if self.renders==2:raise OSError('Verifier injected lost reply after simulator acceptance') + return reply + def close(self):self.t.close() +r=run_prepared_experiment(sys.argv[1],Lost,expected_device_id='opensmell-local-simulator-001') +with open(sys.argv[2],'x') as out:json.dump(r,out) +''') + uncertain=output/'uncertain-report.json';run([python,'-I',consumer,moved,uncertain]) + partial=analysis('uncertain',uncertain,3) + assert [t['receipt_state'] for t in partial['tables']['trials']]==['completed','unknown','not_attempted'] + assert len(partial['tables']['measurements'])==6 and not partial['physical_validation'] + bindings.write_bytes(binding_raw+f'trial-B,{ids[0]},conflicting\n'.encode()) + ambiguous=analysis('ambiguous',code=3) + assert any(i['code']=='ambiguous_observation_binding' for i in ambiguous['coverage']['issues']) + assert all(m['trial_id']!='trial-A' for m in ambiguous['tables']['measurements']) + bindings.write_bytes(binding_raw);bad=json.loads(report.read_bytes());bad['prepared_experiment']['trial_order'].reverse() + stale=work/'stale.json';stale.write_text(json.dumps(bad)) + cli('analyze-experiment',moved,'--report',stale,'--observations',observations,'--bindings',bindings,'--output-directory',output/'stale',code=1) + assert not (output/'stale').exists() + proof.update(result='passed',measurement_counts=[4,2,0],pandas_consumer=True, + ambiguous_without_double_count=True,uncertain_state_preserved=True,stale_before_output=True, + collision_preserved=True,exact_inputs_preserved=True,execution='not_attempted_for_analysis') + save() + print(json.dumps(proof,indent=2)) + +if __name__=='__main__':main()