Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions docs/plans/primary_segmentation_diagnostics_checkpoint_20260929.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# Primary-segmentation diagnostics (#214)

Implementation owner: Singer. Base audited: `a0263e82a1b3296f34f8c5cdd50ffae5c33ef7dd`.
Worktree: `/home/ts/wt/openhcs-primary-segmentation-diagnostics-20260929`.
Issue: https://github.com/OpenHCSDev/openhcs/issues/214.
Draft implementation: https://github.com/OpenHCSDev/openhcs/pull/215.

## Contract and ownership

The final mask alone cannot locate a loss in threshold support, peak suppression,
watershed or filtering. IPO now captures the actual threshold support before
hole filling and connected components before declumping. It returns exact
maxima-response, maxima and marker arrays from the existing execution, followed
by image projections of the canonical unedited/small-removed label variants.
There is no second segmentation, fixture-capture dependency or biological verdict.

`PrimaryObjectDiagnosticPlanes` owns stage names, order and slot types. The
module's existing cooperative `finalize_artifact_contract_outputs` hook appends
image `QA_CHECKPOINT` sidecars with source-stack and exact object-output relations.
Their names are `<object>__qa_checkpoint__<field>`. Source address, group/plane
coordinates and compiled producer remain owned by the existing artifact path.
The first three ordinary return values are preserved, including ordinary
ArrayBridge main-output dtype handling; seven typed image values follow them.
Direct tuple-unpacking tests are migrated, not supported by an old-return alias.

These are not new object sets, do not alter measurement subjects, do not enter
main flow and use `ON_DEMAND` viewer streaming. Normal runtime artifact persistence
still applies by default. Declumping-disabled and no-foreground executions have
wholly invalid response/seed masks and NaN response pixels: absent evidence is
not represented as a measured zero. Pipeline settings and threshold support
distinguish disabled from empty execution. Diagnostic intensity metadata describes
the stage's pixels, not the acquisition's uint16 scale.

Evidence is bounded to seven planes per IPO plane. Only threshold support and
initial components are snapshotted to protect their pre-transform stage identity.
Executed response/seed arrays and payload variant arrays are referenced, not
rerun or cloned. Source validity is decoded once and shared across stages;
unexecuted stages share one invalid mask and use float32 NaN response pixels,
halving the absent response allocation compared with NumPy's default float64.
No input or private benchmark was read.

## Actual focused checks

Nine lightweight tests passed in 1.76 seconds, using the prescribed project
Python 3.12 environment, this worktree and all eight recorded submodule source
directories on `PYTHONPATH`, with `OPENHCS_CPU_ONLY=true`, thread limits of one,
`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` and:

```
python -B -m pytest -q --confcutdir=tests/unit tests/unit/test_primary_object_diagnostics.py
```

Two unrelated pytest async-config warnings remain because plugins are disabled.
Verified import paths are under this worktree and its recorded submodules,
including all eight dependency modules. This explicit source authority matters:
the shared environment's default imports now resolve to the clean installed
harness, not this feature tree. Latest remote main
`283b21275553c54261cf9aeedb7374c113d07f2b` was merged normally into this branch
as `e6b2addc8c9e626d045742ef7d2f18c8b29e2b4a`; its installed package/skill remains
frozen and unchanged.
The first test iterations exposed incorrect fixture assumptions about source
spatial-domain construction and the payload's count owner; those fixtures now
use `SourceSpatialDomain` and `objects.domain.declared_object_count` directly.

This is a focused source/AST audit, not a complete NRA scan:

- IMPL-1/2/3/7: actual new diagnostic source has no string/type/kind dispatcher;
executed and unexecuted evidence own their behavior under an ABC.
- MEMB-1/3: artifact projection reads the typed record's `_fields`; no parallel
stage roster or handler registry. ABI slot types derive from the same annotations.
- BOUND-1/2/7: no string-key raw record reads, duck-typed fallback access or bypass
of `ObjectLabelPayload` variant ownership in the new source. One source decode
precedes all stage projections.
- IDEN-5/6: exact input-source and object-output relations are exercised; projections
retain coordinates and share the authoritative arrays rather than reconstructing
filtering evidence or inventing a competing object identity.
- Actual AST comparison against the pinned baseline confirms the segmentation
body is unchanged except evidence captures and the augmented return.
- The real image-output contextualizer preserves absent-stage masks and numeric
pixels, provenance and stage intensity semantics.
- The existing PURE_2D auxiliary aggregator preserves stage pixels, independent
masks and two-plane source provenance. A small pickle boundary roundtrip
preserves typed planes; this is not persisted MCP/result-review acceptance.
- New-case experiment: one added nominal record field is picked up by the actual
artifact projection without a catalog/dispatcher edit. A real new computed
stage requires its field plus its same-execution producer argument (two sites);
output names, slot annotation and consumers derive without extra maintenance.

## Remaining acceptance and scheduling

The new worktree cannot yet import IPO because main's newly required native
`_granularity_reconstruct` extension is not built here. No native build, algorithm,
MCP, JVM or GUI has been started. Build the extension only in this worktree
(`python setup.py build_ext --inplace --parallel 1`) after explicit slot handoff.
Do not install or change the running baseline.

`tests/integration/test_primary_segmentation_diagnostics_journey.py` is prepared
but NOT run. It covers real registered IPO on a small synthetic close-pair/faint
field (empty, unclumping disabled, watershed disabled, intensity and shape
declumping), then source-document
roundtrip, normal compiled execution, secondary binding and persisted review
through the existing runtime/filemanager. Native parity, these real journeys,
fresh MCP discovery, persisted MCP result review and isolated-display same-coordinate
raw/intermediate/final viewer inspection remain required. Passing metadata tests
does not prove them or biological QA.

Parent's #151/#212 acceptance is merged and installed. Confucius owns the current
heavy slot using that frozen harness. Wait for the parent's explicit handoff,
then acquire `/home/ts/wt/openhcs-issue-batch-20260929/validation.lock`
nonblocking, run the resource guard and retain at least 8 GiB RAM. Use a single
worker and owned disposable test output under
`/home/ts/.cache/agent-scratch/openhcs-primary-diagnostics-20260929`, retain receipts,
then clean disposable output. Do not poll the lock or start a GUI without display
allocation.

Core artifact/runtime/adapter implementation files owned by Zeno are unchanged.
The IPO-specific fixture in `tests/unit/test_cellprofiler_runtime_adapter.py`
previously declared only the old measurement/object slots. PR #205 and Zeno's
worktree had no conflicting edits to that file at the scope check. The fixture
now derives appended diagnostic specs from `PrimaryObjectDiagnosticPlanes`,
preserving its original main/label/persistence assertions and adapter bindings.
This fixture migration is source-only; its native test has NOT run. Normal
compiled contracts already use the module hook. Any future shared implementation
change still requires direct coordination with Zeno; no comms route is required
for independent source work.

Independent draft PR #207 / issue #138 now includes the independent MI discovery
correction at `bd164a94f0a42b90b45d7f8e43d09314d5fcaccf`, with 53 provider-free
tests and actual Python3.9 standalone diamond-command/stage evidence. Its prior
existing-environment lifecycle receipts do not certify that current revision.
Authorized bounded fresh bootstrap creation/native validation is
still pending the explicit serialized slot. It is not abandoned or closed.
197 changes: 197 additions & 0 deletions docs/validation/primary_diagnostics_current_main_20260930.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
Primary object diagnostics current-main checkpoint
=================================================

Parent integration owns existing PR215. Reviewed featurec4b7dc02 merged
normally with mainc42d9bf5 into3048eda2. Original author source is untouched;
no rebase, force push, second diagnostic registry or competing implementation.
This sparse persistent worktree is not the installed editable source.

The seven stages are declared by PrimaryObjectDiagnosticPlanes. Artifact names,
order and callable return-slot types derive from that same declaration. Executed
and unexecuted declumping evidence own their different plane projections; no
consumer dispatch decides their semantics. Object variants remain owned by
ObjectLabelPayload. QA planes use existing image-sidecar/output contextualizing
and PURE_2D aggregation mechanisms, not another segmentation algorithm.

Executed source validation
--------------------------

First pytest collection failed: local _tabular_native had not been built in
the new source checkout. Original XML is preserved in the parent ledger as
primary-diagnostics-current-main-unit-original-20260930.xml. Zero cases ran.

Standard setup.py build_ext --inplace --parallel1 built both existing declared
native extensions in3.60s, exit0, peak146620KiB. No binary copied from another
checkout, package installation, dependency download or source-path shim.
Compiler scratch is tracked in the parent integration ledger.

Subsequent actual source test command used existing Python3.12.3, this checkout
as PYTHONPATH, native threads1, pytest plugin autoload disabled and timeout60:

.. code-block:: text

python -m pytest tests/unit/test_primary_object_diagnostics.py -q

Nine cases PASS1.26s, process1.68s, peak89020KiB. Two async config warnings
come from disabled plugin autoload. XML is preserved as
primary-diagnostics-current-main-unit-after-build-20260930.xml in parent ledger.
Checks exercise source/coordinate and canonical variant identity, wholly-invalid
unexecuted stages, existing real output contextualization and plane aggregation,
typed pickle boundary, declaration extension without catalog changes, focused
new-source antipattern guards, and original algorithm AST preservation apart
from same-run capture. They are not full-package NRA or scientific acceptance.

Required structural screen also ran using the existing packaged agent-comms
ratchet, authenticated byte-identical to pinned3b03785 by SHA256e323c94d49c2b72d9524a5169f123e64b4a6e46a41035ca9fb4497e49b6ca562.
Basec42d9bf5 to published1bc80d6e: PASS5114 metrics, zero nonzero or positive
deltas,12.84s/86528KiB/exit0. Two changed production paths are the diagnostics
owner and primary_objects. Complete JSON lives in the parent persistent ledger
as primary-diagnostics-packaged-ratchet-20260930.json. This screen does not
replace complete NRA/R1, module parity or live acceptance.

Continuous native acceptance
----------------------------

Following the scientific worker's verified terminal cleanup, the parent used
the released validation lock for the real synthetic primary/secondary journey.
No biological inputs, held-out data, extra environment or Fiji download.

The originally unexecuted fixture had three API/semantic mistakes: row_count
is a method; memory records belong to RuntimeValueStore, not an unrelated
FileManager; source-binding identities are virtual addresses, not necessarily
physical input filenames. Readback now compares ordinary persisted TIFFs with
the existing writer's declared runtime-plane projection. Source identity and
pixel contributors are checked through their nominal authorities; a sidecar's
own runtime alias is not incorrectly required to equal the DNA alias.

Native execution exposed a product defect: all seven diagnostic stages used
the same source-derived filename. The diagnostic declaration now requests the
existing artifact-name TIFF materialization, preserving each stage separately.
No second writer, routing registry or serialization fallback was introduced.
The first explicit declaration lacked its required .tif suffix; that failed
attempt is retained rather than hidden by an inferred serialization format.

Final command, with one CPU and native threads1, existing Python3.12 and this
source checkout as PYTHONPATH:

.. code-block:: text

python -m pytest tests/unit/test_primary_object_diagnostics.py \
tests/integration/test_primary_segmentation_diagnostics_journey.py -q

Actual result:15PASS7.05s; process10.55s, peak463732KiB, exit0. The five real
registered IPO modes include empty, declumping-disabled, watershed-disabled,
intensity and shape. The continuous PipelineDocument roundtrip -> compile ->
execute -> persist journey checks all seven distinct stage TIFFs pixel-exactly,
source address and contributors, canonical unedited/small-removed label
variants, primary-to-secondary label identity and containment of each own seed.
All earlier failures and the final XML are retained in the parent ledger as
primary-diagnostics-native-{first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,final}-20260930.xml.

Installed reopening defect and ownership cutover
------------------------------------------------

Ordinary editable imports at candidate97195 passed15 cases7.09s with PYTHONPATH
unset. Actual fresh installed MCP then opened and streamed the raw synthetic
image on isolated:91/5992. Reopening its persisted threshold-support TIFF
failed StorageResolutionError. The viewer was closed explicitly through MCP,
the shell exited1 after the failed command, and the ports and lock were freed.
The original terminal transcript and failed fixture remain in the parent ledger.

Correction to the initial diagnosis: the second step did not overwrite early
diagnostic metadata. The first step's main-flow backend was memory and its
checkpoint was absent. Both manually enumerated metadata targets were absent,
although the independent artifact materialization target saved all stage TIFFs.
AtomicMetadataWriter already retains those projections across later steps.

The existing OutputTarget now owns an AutoRegisterMeta declaration family.
Primary images and explicit checkpoints compose their shared produced-image
capability by MI. RuntimeArtifactMetadataTarget resolves the independently
compiled artifact destination and publishes its typed projections, including
when main flow is memory. Shared serialization and AtomicMetadataWriter remain
the only writer. The old primary/materialized constructors, repeated consumer
rosters and is_main-based target dispatch are deleted, not retained as aliases.
is_main is now a declaration fact consumed only by the external metadata format.

MEMB-2, IMPL-4/5 and IDEN-1 witnesses: the old two-member tuples in write and
finalize omitted artifact persistence; produced_projection_metadata dispatched
through is_main. The new-case guard declares an additional target and proves
automatic discovery for execution and reconciliation without changing either
consumer. The native journey checks seven persistent stage source entries and
both Nuclei/Cells label entries after secondary execution and reconciliation.
Source identities after persistence are compared through the canonical JSON
codec, which normalizes nested mapping keys; this is separate from the existing
native sidecar/source identity and pixel-contributor equality checks.

First combined run:72PASS/2FAIL9.57s. One real table-only publication regression
was repaired by the primary declaration's execution admission hook; the other
assertion incorrectly compared in-memory mapping keys with serialized JSON
identities. Original XML retained. Second combined run:74PASS9.89s. The final
family-discovery guard passed in the final75PASS8.64s run. Installed reopening
still requires execution.
These are focused source/native proofs, not complete NRA or biological QA.

The parent owns this same PR215 and issue214, with no competing implementation.
Complete the affected installed path before merge; do not wait for optional CI.
The frozen scientific abstention, held-out boundary and full ZIP scope remain
unchanged. Owner clarification:20GiB is a warning margin, not a hard disk limit.

Result inventory continuation
----------------------------

Installed candidatecba1c90df with the75-case metadata fix still failed diagnostic
reopening. The exact native viewer rejection was ``No component metadata
available for path``. Its full log and terminal transcript are retained at
primary-diagnostics-viewer-reopen-20260930; viewer/MCP were explicitly closed,
the shell exited1, and ports5992/6792/6992 and validation.lock were freed.
An attempted capture_scope=canvas was rejected at the boundary, so no bitmap
inspection is claimed for that attempt.

The result-directory owner now carries its existing typed source authority
from OpenHCSMetadataHandler through PlateResultFileRecord to PlateFileRecord.
The canonical projection/ref and acquisition components survive selecting a
native TIFF as a result, not just as an image. Ordered inventory merging keeps
the handler declaration ahead of path-only duplicate discoveries. There is no
new JSON reader, filename-derived source identity or reconstructed source
receipt. Generic external result directories still have genuinely optional
source bindings; absence is handled by their nominal directory owner.

The compiled plan owns artifact output plate-root resolution beside its two
existing artifact directory properties. This removes the newly introduced
foreign absence probe flagged by the original packaged ratchet. Its original
exit1 JSON remains preserved; no baseline or guard was weakened.

Four focused target/compiled-root cases PASS1.40s. Expanded inventory/native
run97PASS/1FAIL20.84s: the new fixture used address.items instead of the declared
component_values().items accessor. The original failed XML is retained. Final
expanded run:98PASS18.82s. Directory existence/type admission is now owned by
AnalysisResultDirectory, rather than growing OpenHCSMetadataHandler. Its focused
guard and corrected installed viewer acceptance remain pending.

Installed live result
---------------------

Directory owner suite7PASS2.86s and explicit absent/file/directory guard3PASS1.92s.
Original packaged ratchet againstmain616 at2ae8f0b95:PASS5154 metrics, no positive
deltas, OpenHCSMetadataHandler excess reduced8. Original failed screen retained.

Actual installed MCP at2ae8f0b95, ordinary editable imports with PYTHONPATH unset,
successfully reopened raw, threshold-support TIFF selected as result, and the
primary ROI archive on isolated:91/5992. Parent personally opened raw-only,
result-only, combined and diagnostic-only PNGs. All have nativecanvas953x470,
XY orientation, point[0,0,0,0,0,15,19]; camera center[0,15.5,19.5],zoom11.1625,
unit native scale and zero translation. Raw contrast approximately[0,.862224],
gamma1, stage[0,1]. Two ROI polygons align with bright/dim synthetic support;
the binary diagnostic shows their two foreground components. Technical
reopening/visibility/alignment PASS, not biological segmentation acceptance.
Full terminal inputs/responses, exact PNG hashes and evidence are retained in
the parent ledger's primary-diagnostics-viewer-binding-20260930/ACCEPTANCE.rst.
Explicit MCP close succeeded and the shell terminated normallyexit0.

New main7b169084 SaveImages binding fix is normally integrated atd556afb8 in
the isolated source tree. No dependency gitlink changes or competing patch.
Latest-main combined suite171PASS22.22s, including the real compiled persistence
journey, inventory/streaming/metadata families and the updated function artifact
binding suite. Original packaged ratchet against7b169084:PASS5155 metrics, zero
positive deltas. Installed activation of this integrated source remains next;
the live result above specifically identifies2ae8, not unexecuted later code.
Loading
Loading