From d4157a3e37f945f8b1570cc9b2eef9278c1ae086 Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Wed, 4 Nov 2026 11:53:27 +1030 Subject: [PATCH 01/96] docs(spec): add plan and S1 tasks for 005-coordinate-frame-correctness --- .../005-coordinate-frame-correctness/plan.md | 641 ++++++++++++++++++ .../005-coordinate-frame-correctness/tasks.md | 391 +++++++++++ specs/README.md | 4 +- 3 files changed, 1034 insertions(+), 2 deletions(-) create mode 100644 specs/005-coordinate-frame-correctness/plan.md create mode 100644 specs/005-coordinate-frame-correctness/tasks.md diff --git a/specs/005-coordinate-frame-correctness/plan.md b/specs/005-coordinate-frame-correctness/plan.md new file mode 100644 index 000000000..9871ca062 --- /dev/null +++ b/specs/005-coordinate-frame-correctness/plan.md @@ -0,0 +1,641 @@ +# Implementation plan: Coordinate and fault-frame correctness + +**Feature**: `005-coordinate-frame-correctness` | **Date**: 2026-11-04 | **Spec**: [spec.md](spec.md) + + + +## Open points + +- **OP1**: This plan gives the exact design only for stage S1 (shared + transform, reference-constraint boundary and fault frame). The spec-planner + limit is 10 code files, and the maintainer selected a staged plan on + 2026-11-04. Stages S2 to S6 have a stage map, a file list from a grep + survey and a requirement allocation, but no exact signatures. Owner: the + spec-planner skill, one run for each stage, after S1 merges. Blocks: the + tasks of S2 to S6. The spec-tasks skill must make tasks for S1 only. +- **OP2**: Run time of the mandatory R2 and R5 matrices. R2 needs 4 anchors x + 3 rotations x 2 centre modes x 2 engines = 48 solves (FDI with 20000 + requested cells). R5 needs 3 buffers x 3 rotations x 2 centre modes x 2 + engines = 36 support builds. SC-018 forbids skips of mandatory cells. Owner: + the maintainer. Decision needed: run the full matrix in the default + `pytest` run, or put it behind a pytest marker that a named CI job runs. + Default until an answer: the full matrix runs in the default `pytest` run. + The S1 test task measures the time and records it in `verification.md`. Blocks: + nothing in S1 design; it can change the test layout only. + +## Answers + + + +## Summary + +Observations, fault geometry, masks and public queries stay in world +coordinates. Local assembly and supports use the computational frame of the +target interpolator (`interpolator.bounding_box`). Each boundary converts +points once and directions once (rotation only). + +S1 repairs the shared boundary and the fault frame: + +1. A rigid-rotation check and a corner-enclosure helper in common geometry. +2. Support resize that keeps the node and cell counts consistent. +3. Public world/local conversion methods on `GeologicalInterpolator`. +4. Reference sampling (orthogonality, equality, feature inequality, restored + support expansion) at world locations, with directions converted into the + target basis. +5. A fault factory that does not project an explicit centre, keeps the + requested buffer and forced geometry, infers a 3D centre, and adds one + extent-direction row at the centre. + +S2 to S6 repair fold paths, persistence and lifecycle, display consumers, +grid and diagnostics, and the auxiliary utilities and validation matrix +(see "Stages and rollback"). + +## Technical context + +- **Packages changed**: `LoopStructural` (modelling builders and the feature + factory), `packages/loop_common` (geometry), `packages/loop_interpolation` + (base and discrete interpolators). S1 does not change + `packages/loop_interpolation_core`. +- **Languages and versions**: Python only. Ruff target py39. New modules use + `from __future__ import annotations` for `X | None` hints. +- **New dependencies**: none. +- **Public API and import changes**: additive only in S1. New public names: + `loop_common.geometry.validate_rigid_rotation`, + `BoundingBox.local_enclosure`, + `GeologicalInterpolator.world_to_local_points`, + `GeologicalInterpolator.local_to_world_points`, + `GeologicalInterpolator.world_to_local_vectors`, + `GeologicalInterpolator.local_to_world_vectors`, + `GeologicalFeatureBuilder.excluded_rows`. The signatures of + `GeologicalModel.create_and_add_fault`, `FaultBuilder` and + `set_interpolation_geometry` do not change. Behaviour changes with known + coordinate meaning (FR-028): an explicit `fault_center` is used as a world + point; `fault_buffer` and `force_mesh_geometry` keep their effect; an + inferred centre keeps its elevation; `BoundingBox.set_local_transform` and + `rotation_xy` reject a non-rigid matrix. +- **Saved-data format changes**: none in S1. S3 adds a format version (FR-016). +- **Coordinate contract**: + + | Boundary | Input space | Output space | Function | + |---|---|---|---| + | Public evaluation | world points | world values, world directions | `GeologicalInterpolator.evaluate_value`, `evaluate_gradient` (unchanged) | + | Data to interpolator | world constraint arrays | local stored arrays | `GeologicalInterpolator.set_*_constraints` (unchanged) | + | Support samples to reference feature | local support points | world points | `GeologicalInterpolator.local_to_world_points` | + | Reference direction to assembly | world direction | target-local direction | `GeologicalInterpolator.world_to_local_vectors` | + | Region and mask callbacks | world points | boolean | caller callbacks (documented contract) | + | `DiscreteInterpolator.add_gradient_orthogonal_constraints` | local points, local unit vectors | rows | internal local contract, now documented | + | `DiscreteInterpolator.add_inequality_feature` feature callback | world points | values | documented feature-facing contract | + | Support geometry request | world box | local enclosure | `BoundingBox.local_enclosure` | + | Fault restoration for support expansion | world points | world points | `FaultSegment.apply_to_points` (unchanged) | + + The geological-frame values (fault coordinates 0, 1, 2) are scalars. No + translation applies to them. +- **Performance target**: none specified. OP2 records the test run time. +- **Platforms and backends**: S1 covers Python FDI and PLI/P1. P2, fold, + constant-norm, native and Surfe cells belong to S2 and S6. The native + adapter rejects rotated supports (`_native.py:170`); S1 does not change it. + +## Constitution check + +| Project rule | Result | How the plan agrees | +|---|---|---| +| Work stays within the existing library and package responsibilities | Pass | Changes stay in `loop_common` geometry, `loop_interpolation` base classes and `LoopStructural` builders. One new private module `_rigid.py` in `loop_common.geometry`. No new package. | +| Development commands come from .dev-tools/project.json and the constitution | Pass | Gates use `pytest` and `ruff check LoopStructural packages`, and `black .` for format. | +| Both pytest and ruff check LoopStructural packages must pass before merge | Pass | Each stage row in "Stages and rollback" names both gates. | +| Python changes use numpy-style docstrings and type hints; Ruff targets py39 | Pass | Each new function has a numpy docstring and hints; `from __future__ import annotations` keeps py39 syntax. | +| Black uses line length 100 and preserves string quoting | Pass | Run `black .`; no string normalisation. | +| ROADMAP.md owns architecture stages and decisions; update it when either changes | Pass | S1 adds no ROADMAP stage. S3 records the FR-019 legacy-load decision in ROADMAP.md. The final stage adds a "005 complete" line. | +| Stages can be tested and reversed independently | Pass | Six stages, each with an acceptance check and a rollback target. | +| The public GeologicalModel API stays compatible; a break needs a ROADMAP.md decision and a major-version note | Pass | No signature or return-shape change. Corrected behaviour of known-meaning inputs gets a `COMPAT.md` "Migration notices" entry. S3 handles the FR-019 exception. | +| The QGIS plugin stays in its separate repository | Pass | No plugin file changes. | +| Feature documents stay under specs/NNN-name/ | Pass | `plan.md` and `verification.md` are in `specs/005-coordinate-frame-correctness/`. | +| Releases use release-please with per-package paths | Pass | Conventional commits per package path; no release config change. | +| A constitution amendment requires a pull request and maintainer acceptance | Not applicable | No amendment. | + +## Design + +S1 has the exact design below. S2 to S6 have scope only (OP1). + +### Types and data + +1. **`FaultBuilder` state** (`LoopStructural/modelling/features/builders/_fault_builder.py`). + New private fields, set in `__init__`: + - `self._fault_buffer: float = 0.2` — last requested support buffer, as a + fraction of the longest box side. + - `self._force_mesh_geometry: bool = False` — last forced-geometry request. + + `create_data_from_geometry` writes both fields from its arguments before + any other work. `_on_geometry_change` reads them when its arguments are + `None`. + +2. **`GeologicalFeatureBuilder.excluded_rows`** + (`LoopStructural/modelling/features/builders/_geological_feature_builder.py`). + Type `dict[str, dict[str, int]]`. Key 1: constraint name + (`f"{feature.name}_orthogonal"` or `f"{feature.name}_equality"`). Key 2: + reason. Value: number of rows not installed. Reasons: + - `"invalid_reference_value"` — the reference value is not finite. + - `"invalid_reference_direction"` — the reference gradient is not finite + or has zero length. + - `"evaluation_error"` — the reference evaluation raised an exception; the + count is the number of selected rows. + + The builder resets the dictionary at the start of + `install_gradient_constraint` (orthogonal keys) and + `install_equality_constraints` (equality keys). S5 connects it to the + diagnostics report. + +3. **Generated fault rows** (data frame columns `X, Y, Z, feature_name, nx, + ny, nz, val, coord, w`, world coordinates). S1 adds one row when + `major_axis` is not `None`: + + | X, Y, Z | nx, ny, nz | val | coord | w | + |---|---|---|---|---| + | fault centre (world) | `strike_unit / major_axis` | NaN | 2 | `w` | + + `strike_unit = cross(n, s_perp) / |cross(n, s_perp)|`, where `n` is the + unit normal and `s_perp` is the unit slip direction after the normal + component is removed. For R2, `n=(1,0,0)`, `s=(0,0,-1)`, so + `strike_unit=(0,1,0)` and the row is `(0, 1/20, 0)`. This is the only + automatic direction row (R4, SC-013). Existing tip rows (`val=+-0.5`, + `coord=2`) do not change. + +### Functions and public API + +All names below were checked with `git grep -n -w ` on 2026-11-04 in +`LoopStructural`, `packages` and `tests`: 0 matches for each new name. + +**`packages/loop_common/src/loop_common/geometry/_rigid.py`** (new) + +```python +def validate_rigid_rotation( + matrix: np.ndarray, dimensions: int, atol: float = 1e-10 +) -> np.ndarray: + """Return a float copy of ``matrix`` if it is a proper rigid rotation. + + Raises RigidRotationError (a ValueError subclass in this module) when: + shape != (dimensions, dimensions); any entry is not finite; + max|R^T R - I| > atol; |det(R) - 1| > atol. + The message names the failed condition and the action: + "supply a proper rotation (orthonormal, det +1); scale and shear are + not supported". + """ +``` + +`RigidRotationError(ValueError)` is defined in the same module. It is a +`ValueError` subclass, so existing `except ValueError` callers still work. +Export both names from `loop_common.geometry.__init__`. The module imports +only `numpy`, so it causes no import cycle. + +**`BoundingBox`** (`packages/loop_common/src/loop_common/geometry/_bounding_box.py`) + +- `set_local_transform(local_origin=None, rotation_matrix=None)`: call + `validate_rigid_rotation(rotation_matrix, self.dimensions)` before any field + changes. Also reject a non-finite `local_origin` with `LoopValueError`. + On error the old transform stays (SC-012). +- New method: + + ```python + def local_enclosure( + self, + origin: np.ndarray | None = None, + maximum: np.ndarray | None = None, + ) -> tuple[np.ndarray, np.ndarray]: + """Return (local_min, local_max) that enclose the projection of all + 2**dimensions corners of the world box [origin, maximum]. + Defaults: self.origin and self.maximum. Raises LoopValueError if + either bound is None or not finite, or if origin > maximum on any axis. + """ + ``` + + Implementation: build the corners with `itertools.product` over the two + bounds per axis, call `self.project(corners)`, return `min` and `max` on + axis 0. + +**`StructuredGrid3DGeometry`** (`packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py`) + +- `rotation_xy` setter: after the existing float/int conversion, call + `validate_rigid_rotation(rotation_xy, 3)`. `None` keeps the current value. +- New private method used by both setters: + + ```python + def _cells_for_length(self, length: np.ndarray) -> np.ndarray: + """Number of cells per axis that cover ``length`` with the current step. + + cells = ceil(length / step_vector - 1e-9). An axis with 0 cells gets 2 + cells (the existing degenerate rule of 3 nodes). Raises ValueError + (existing message "Cannot resize the grid.") if any cell count < 0. + """ + ``` + +- `origin` setter: `self._nsteps = self._cells_for_length(self.maximum - origin) + 1`. + Compute `self.maximum` before the origin changes. +- `maximum` setter: + `self._nsteps = self._cells_for_length(maximum - self.origin) + 1`. + + This repairs the 1-cell loss (node count was set to the cell count). + Reapplying unchanged bounds keeps origin, maximum, step and counts + (SC-011, first part). + +**`GeologicalInterpolator`** (`packages/loop_interpolation/src/loop_interpolation/_geological_interpolator.py`) + +New public methods. Each is a documented wrapper of the existing private +method. The private methods stay for compatibility. + +```python +def world_to_local_points(self, points: np.ndarray) -> np.ndarray: ... +def local_to_world_points(self, points: np.ndarray) -> np.ndarray: ... +def world_to_local_vectors(self, vectors: np.ndarray) -> np.ndarray: ... +def local_to_world_vectors(self, vectors: np.ndarray) -> np.ndarray: ... +``` + +Input shape `(N, d)` or `(d,)`; output has the same shape. Vectors use +rotation only. With `bounding_box is None` each method returns its input +(existing behaviour). + +**`DiscreteInterpolator`** (`packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py`) + +- `add_gradient_orthogonal_constraints` (abstract): docstring states the + internal contract — `points` are target-local, `vectors` are target-local + unit directions. No signature change. +- `add_inequality_feature(feature, lower=True, mask=None)`: call + `feature(self.local_to_world_points(self.support.nodes))`. Docstring: + `feature` receives world points and returns one value for each node. No + signature change. + +**`GeologicalFeatureBuilder`** (`LoopStructural/modelling/features/builders/_geological_feature_builder.py`) + +- `install_gradient_constraint()`: + 1. `local_pts` = barycentres or quadrature points (existing code). + 2. `world_pts = self.interpolator.local_to_world_points(local_pts)`. + 3. `vector = feature.evaluate_gradient(world_pts, ignore_regions=True)`. + 4. `valid = all(isfinite(vector), axis=1) & (norm > 0)`. + Record `(~valid).sum()` under `"invalid_reference_direction"`. + 5. Normalise `vector[valid]`, then + `local_vec = self.interpolator.world_to_local_vectors(vector[valid])`. + 6. Call `add_gradient_orthogonal_constraints(local_pts[valid], local_vec, + w=weight[valid] if weight is an array else weight, b=B, name=...)`. + 7. If `valid.sum() == 0`, install no rows and log a warning with the count. +- `install_equality_constraints()`: + 1. `world_nodes = self.interpolator.local_to_world_points(support.nodes)`. + 2. `selected = np.asarray(region(world_nodes), dtype=bool)`; + `idc = np.flatnonzero(selected)`. + 3. `val = feature.evaluate_value(world_nodes[idc])`; `valid = isfinite(val)`. + 4. Record `(~valid).sum()` under `"invalid_reference_value"`. + 5. `self.interpolator.add_equality_constraints(idc[valid], + val[valid] * scalefactor, name=f"{feature.name}_equality")`. + 6. The existing `except` clause stays. It also records `idc.size` (or the + node count if `idc` is not set) under `"evaluation_error"`. +- `set_interpolation_geometry(origin, maximum, rotation=None)`: replace the + two-point projection with + `origin, maximum = self.interpolator.bounding_box.local_enclosure(origin, maximum)` + when `bounding_box` is not `None`. The NaN checks and the `dof < 100` loop + do not change. +- `check_interpolation_geometry(data, buffer=0.3)`: + 1. `pts = self.model.bounding_box.with_buffer(buffer).regular_grid(local=False)` + (world). + 2. For each fault: `pts = f.apply_to_points(pts)` (world in, world out). + 3. `local = self.interpolator.world_to_local_points(pts)`. + 4. `origin = np.minimum(support.origin.copy(), local.min(axis=0))`; + `maximum = np.maximum(support.maximum.copy(), local.max(axis=0))`. + 5. Assign `support.origin = origin`, then `support.maximum = maximum`. + The copies stop the in-place change of the support arrays. + +**`FaultBuilder`** (`LoopStructural/modelling/features/builders/_fault_builder.py`) + +- `create_data_from_geometry(...)`: no signature change. + - Store `self._fault_buffer = fault_buffer` and + `self._force_mesh_geometry = force_mesh_geometry` first. + - Inferred centre (`fault_center is None`): use the rows with `coord == 0` + and `val == 0`, columns `X, Y, Z`; `fault_center = np.nanmean(pts, axis=0)`. + If a component is not finite, set it to `0.0` and log a warning that names + the axis. This keeps the elevation (FR-010). + - Slip direction: after normalisation, `s_perp = s - (s @ n) * n`. If + `|s_perp| < 1e-12`, raise `ValueError("fault slip vector is parallel to + the fault normal; supply a slip direction in the fault plane")`. Use + `s_perp / |s_perp|` for `self.fault_slip_vector`, for the strike vector, + and for the depth rows. + - Add the extent-direction row (see "Types and data", item 3). + - Early-return branch (no fault trace): call + `self.set_mesh_geometry(fault_buffer, None)` before `return`. This keeps + the support that the factory previously set. +- `_on_geometry_change(force_mesh_geometry=None, fault_buffer=None, ...)`: + the default of `force_mesh_geometry` changes from `False` to `None`. `None` + means "use the stored value". This is a private method. + +**`create_and_add_fault`** (`LoopStructural/modelling/core/_model_feature_factory.py`) + +- Delete the call `fault_center = model.scale(fault_center, inplace=False)`. + An explicit centre stays a world point (FR-010, U1.1). +- Delete the block + `if "force_mesh_geometry" not in kwargs: fault_frame_builder.set_mesh_geometry(kwargs.get("fault_buffer", 0.2), 0)`. + `create_data_from_geometry` already applies the named `fault_buffer` and + `force_mesh_geometry` (FR-012, U1.4, U1.5). + +### Messages and saved data + +None in S1. S3 owns the saved-format change (FR-016 to FR-019). + +### Behaviour + +Call sequence for a fault through the public API after S1: + +1. `GeologicalModel.create_and_add_fault(...)` calls the factory with world + data and an optional world `fault_center`. +2. The factory makes `FaultBuilder` with `model.bounding_box` and calls + `create_data_from_geometry` with the unchanged centre. +3. The builder makes the world rows, sets `origin`/`maximum` (forced or from + rows), and calls `set_mesh_geometry(self._fault_buffer, None)`. +4. `set_mesh_geometry` calls `set_interpolation_geometry` on the three + coordinate builders. Each builder projects the world box with + `local_enclosure` and resizes its support with the repaired setters. +5. `build` sends world rows to `set_*_constraints`. The interpolator converts + them once into local arrays (existing code). +6. `install_gradient_constraint` samples the reference coordinate at world + points, converts the directions into the target basis, and installs rows + at local points. +7. Evaluation and displacement take world points and return world values and + directions (existing code). + +Errors: an invalid rotation raises `RigidRotationError` before any state +change. A slip parallel to the normal raises `ValueError` before the data +frame is added to the builder. + +Cache invalidation: S1 changes no cache. S3 owns transform changes after +population (FR-020). + +### Stages and rollback + +| Stage | Files and behaviour | Acceptance check | Rollback target and compatibility check | +|---|---|---|---| +| S1 | Shared transform boundary, reference relationships for FDI and PLI, fault frame, buffer and forced geometry, rotation check, resize stability (this design) | New S1 tests pass for FDI and PLI; `pytest`; `ruff check LoopStructural packages`; `pytest packages/loop_common/tests packages/loop_interpolation/tests` | Revert the S1 commits to master `ebc7c699`. Check: the existing `tests/unit/modelling/test__fault_builder.py` and `packages/loop_common/tests/test_bounding_box.py` pass on the reverted tree. No saved format changed. | +| S2 | Fold geometry, directional regularisation, quadrature, masks, sign alignment for FDI-fold, PLI discrete fold, P2 and P2-fold; constant-norm variants (FR-008; R3 for P2; R4) | SC-007, SC-008, SC-013 for every mandatory fold and P2 cell | Revert to the S1 merge. Check: S1 tests still pass. | +| S3 | Persistence format version, transform and coordinate-space metadata; no second projection at load; copies keep the frame; legacy load requires a transform or identity declaration; transform change policy and restored-point cache invalidation (FR-016 to FR-020); ROADMAP.md decision for FR-019; `COMPAT.md` migration note | SC-006, SC-012, SC-016, SC-017 | Revert to the S2 merge. Check: old-format R1 files load through their documented path; a new-format file fails with 1 actionable error and 0 state changes on the old reader (SC-017). | +| S4 | Display, export of observation geometry, fault-centre geometry and intrusion classification use stored world locations (FR-022) | World-location comparison within `Tp` (U3.4, U3.5) | Revert to the S3 merge. Check: viewer import paths unchanged. | +| S5 | Cell-centre sampling, remaining resize paths, non-mutating diagnostics, residual and exclusion report (FR-014 remainder, FR-015, FR-023, FR-024) | SC-009, SC-011 | Revert to the S4 merge. Check: diagnostics report fields unchanged for callers. | +| S6 | Auxiliary point transformations and duplicate entry points (FR-025); displacement validation R2 (FR-026, FR-027); backend matrix incl. native and Surfe (FR-030); golden review (FR-029); 005 completion line in ROADMAP.md | SC-004, SC-010, SC-014, SC-015, SC-018 | Revert to the S5 merge. Check: `LoopStructural.utils` and `loop_common.math` import paths unchanged. | + +## Test strategy + +Shared rule for every stage (FR-031): write each regression test first, run +it on the unfixed tree, and record the failure (test id, observed value) in +`specs/005-coordinate-frame-correctness/verification.md`. Then fix and record +the pass. A finding of the 1.7.0 investigation that does not reproduce on the +current tree is recorded as "not reproduced"; its test stays as a guard. + +- **Unit and regression tests (S1)**: + - `packages/loop_common/tests/test_rigid_transform_contract.py`: + `validate_rigid_rotation` accepts rotations of 0, 30 and 90 degrees about + z; rejects scale, shear, singular, reflection (det -1), NaN/inf and wrong + shape (2D and 3D). SC-001 point round trips (`Tp`) and direction round + trips (`1e-12`) for 1 point and arrays, for all 4 anchors. `local_enclosure` + contains all 8 projected corners for each rotation. Invalid rotation: + `set_local_transform` and `rotation_xy` leave the prior state unchanged + (SC-012, rotation part). Reapply unchanged support bounds 10 times: 0 + changes to origin, maximum, step and counts (SC-011, resize part). + - `tests/unit/modelling/test_reference_constraint_frames.py`: R3 for FDI + and PLI, 4 anchors x 3 rotations. Equality region `x' > 4` selects 168 of + 336 nodes unrotated; for rotations the expected set comes from the world + nodes. 0 missing or duplicate nodes, local index paired with the world + value (SC-007). Orthogonality rows with `f=y'`, direction `(1,0,0)`, + target 0, and direction `(0,1,0)`, target 1: residual at most `1e-10` + (SC-008, FDI and PLI; barycentre, `"centroid"` and `"gauss4"`). Feature + inequality bounds equal `h` at each node's world location. Restricted + reference support: `excluded_rows` count equals the analytic count of + samples outside the closed restricted box. Support expansion through a + restoring fault: restored world samples project inside the support + (FR-009, U2.7). + - `tests/unit/modelling/test_fault_frame_analytic.py`: R2 through + `GeologicalModel.create_and_add_fault` for FDI and PLI, explicit and + inferred centre, 4 anchors x 3 rotations. SC-003 on the 6859 probes with + CG `rtol=1e-10`, `atol=1e-12`, `maxiter=20000`. U1.1: generated rows use + the centre with no projection. Inferred centre equals `O` in all 3 + components. R4: the extent-direction row equals the analytic extent + gradient at the centre within `1e-10` per component; the analytic extent + directions at `O+(0,-6,0)` and `O+(0,6,0)` differ by at least 15 degrees; + a constant centre direction at those probes fails the check (SC-013). + Non-orthogonal slip input: `fault_slip_vector` is orthogonal to the + normal; a parallel slip raises `ValueError`. + - `tests/unit/modelling/test_fault_buffer_bounds.py`: R5 for FDI and PLI, + buffers 0, 0.2, 0.5, 3 rotations, explicit and inferred centre, forced + geometry. Each local face is outward of the expected enclosure by at most + 1 cell plus `Tp`. The 3 buffers give distinct bounds. All generated rows + are inside the support (SC-005). A property change after creation + (`fault_builder.fault_normal_vector = ...`) keeps the buffer and the + forced geometry (U1.5). + - `tests/fixtures/coordinate_frames.py` (new helpers, no tests): anchors, + `rot_z(deg) -> np.ndarray`, `tp(L, W) -> float`, R1 to R5 data frames, + the R2 analytic frame, the R3 field `h`, and the R4 curved fields. Tests + import only this module, not an external investigation workspace. +- **Integration and compatibility tests**: `tests/unit/test_public_api_contract.py` + and `tests/unit/test_stable_api_surface.py` must pass unchanged. If + `tests/fixtures/api_surface_snapshot.json` lists public methods of + `GeologicalInterpolator` or `BoundingBox`, add the new names to it (additive). +- **Round-trip tests**: S1 covers point and direction round trips (SC-001). + Persistence round trips are S3. +- **Backend coverage**: S1 covers Python FDI and PLI/P1 cells for R2, R3 and + R5. S2 and S6 cover the other cells (OP1). +- **Cross-language fixtures**: Not applicable in S1. +- **Grid and display checks**: S1 checks support enclosure and resize. Cell + centres and display are S4 and S5. +- **Performance check**: none required. Record the S1 test time (OP2). +- **Merge gates**: `pytest` and `ruff check LoopStructural packages`. Also run + `pytest packages/loop_common/tests packages/loop_interpolation/tests`, + because the root `testpaths` is `tests` only. + +## Project structure + +### Common geometry (`packages/loop_common`) + +**Responsibility**: rigid-rotation meaning, transformed box enclosure, stable +support resize. + +**Files**: + +- `packages/loop_common/src/loop_common/geometry/_rigid.py` - Create; + `RigidRotationError`, `validate_rigid_rotation`. +- `packages/loop_common/src/loop_common/geometry/__init__.py` - Change; export + `RigidRotationError` and `validate_rigid_rotation`. +- `packages/loop_common/src/loop_common/geometry/_bounding_box.py` - Change; + validation in `set_local_transform`; new `local_enclosure`. +- `packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py` - + Change; `rotation_xy` validation; `_cells_for_length`; `origin` and + `maximum` setters. +- `packages/loop_common/tests/test_rigid_transform_contract.py` - Create; + SC-001, SC-011 (resize part), SC-012 (rotation part), enclosure. + +### Interpolation (`packages/loop_interpolation`) + +**Responsibility**: public world/local conversion; documented local and world +callback contracts. + +**Files**: + +- `packages/loop_interpolation/src/loop_interpolation/_geological_interpolator.py` + - Change; four public conversion methods. +- `packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py` + - Change; `add_inequality_feature` samples world nodes; contract docstring + of `add_gradient_orthogonal_constraints`. + +### Geological modelling (`LoopStructural`) + +**Responsibility**: world fault geometry, reference sampling, support +requests. + +**Files**: + +- `LoopStructural/modelling/features/builders/_geological_feature_builder.py` + - Change; `excluded_rows`; `install_gradient_constraint`; + `install_equality_constraints`; `set_interpolation_geometry`; + `check_interpolation_geometry`. +- `LoopStructural/modelling/features/builders/_fault_builder.py` - Change; + stored buffer and forced geometry; 3D inferred centre; slip + orthogonalisation; extent-direction row; early-return mesh geometry. +- `LoopStructural/modelling/core/_model_feature_factory.py` - Change; remove + the centre projection and the buffer override in `create_and_add_fault`. +- `tests/fixtures/coordinate_frames.py` - Create; shared R1 to R5 fixtures. +- `tests/unit/modelling/test_reference_constraint_frames.py` - Create; R3, + FR-004 to FR-007, FR-009. +- `tests/unit/modelling/test_fault_frame_analytic.py` - Create; R2, R4, + FR-010, FR-011, SC-003, SC-013. +- `tests/unit/modelling/test_fault_buffer_bounds.py` - Create; R5, FR-012, + FR-013, SC-005. +- `tests/unit/modelling/test__fault_builder.py` - Change only if an assertion + encodes a defect fixed by S1 (for example an inferred centre with `z=0`). + Record each change in `verification.md` under C-004. + +### Documents + +**Responsibility**: evidence, golden review, migration notes. + +**Files**: + +- `specs/005-coordinate-frame-correctness/verification.md` - Create; + sections "Pre-fix failures", "Post-fix results", "Golden review (C-004)", + "Backend matrix", "Rollback checks", "Test run time (OP2)". +- `COMPAT.md` - Change; one entry under "Migration notices": explicit + `fault_center` is a world point; `fault_buffer` and `force_mesh_geometry` + now keep their effect; an inferred centre keeps its elevation; non-rigid + rotations are rejected; extra observations added as a workaround are no + longer necessary. + +### Later stages (file survey only, OP1) + +The next planner runs read and confirm these files. The lists come from a +grep survey on 2026-11-04 and are not final. + +- **S2**: `packages/loop_interpolation/src/loop_interpolation/_fd_fold_interpolator.py`, + `_discrete_fold_interpolator.py`, `_p2_fold_interpolator.py`, + `_p2interpolator.py`, `_fold_setup.py`, `_fold_norm_alignment.py`, + `_quadrature.py`, `_regularisation.py`, `_constant_norm.py`, + `_finite_difference_interpolator.py`, `_p1interpolator.py`; + `LoopStructural/modelling/features/builders/_folded_feature_builder.py`. +- **S3**: `_geological_interpolator.py` (`to_dict`, `from_dict`), + `_interpolator_factory.py`, `_finite_difference_interpolator.py` (`copy`), + `_p2interpolator.py` (`copy`), `_p2_fold_interpolator.py` (`copy`), + `packages/loop_common/src/loop_common/supports/_support_factory.py`, + `LoopStructural/modelling/features/fault/_fault_segment.py` (restoration + cache), `ROADMAP.md`, `COMPAT.md`. +- **S4**: `packages/loopstructural_visualisation/src/loopstructuralvisualisation/_3d_viewer.py`, + `LoopStructural/modelling/intrusions/intrusion_builder.py`, + `LoopStructural/modelling/intrusions/intrusion_frame_builder.py`, + `LoopStructural/modelling/features/fault/_fault_segment.py`, + `LoopStructural/export/exporters.py`. +- **S5**: `packages/loop_common/src/loop_common/geometry/_bounding_box.py` + (`cell_centres`), `_structured_grid.py`, `_structured_grid_2d.py`, + `packages/loop_common/src/loop_common/supports/_3d_structured_grid.py`, + `_3d_rectilinear_grid.py`, + `packages/loop_interpolation/src/loop_interpolation/_diagnostics.py`. +- **S6**: `packages/loop_common/src/loop_common/math/_transformation.py`, + `LoopStructural/utils/_transformation.py`, + `packages/loop_interpolation/src/loop_interpolation/_native.py`, + `_surfe_wrapper.py`, `LoopStructural/modelling/features/fault/_fault_function.py`, + `ROADMAP.md`. + +## Requirement coverage + +| Requirement | Design and files | Verification | Gap | +|---|---|---|---| +| FR-001 | Existing public evaluation; S1 keeps it; fault path in `_model_feature_factory.py` | `test_fault_frame_analytic.py` (gradients in world after rotation) | None for S1 paths; other paths OP1 | +| FR-002 | Factory keeps explicit centre in world; builder rows in world | `test_fault_frame_analytic.py` U1.1 | None | +| FR-003 | Public conversion methods; builder uses each once | `test_rigid_transform_contract.py`; `test_reference_constraint_frames.py` | Load path (U3.2) is S3, OP1 | +| FR-004 | `install_gradient_constraint`, `install_equality_constraints`, `add_inequality_feature`; documented callbacks | `test_reference_constraint_frames.py` | None | +| FR-005 | `world_to_local_vectors` in `install_gradient_constraint` | SC-007, SC-008 tests | P2 is S2, OP1 | +| FR-006 | `install_equality_constraints` | 168-node check, rotated sets | None | +| FR-007 | `add_inequality_feature` | Bounds equal `h` at world nodes | None | +| FR-008 | S2 | S2 | OP1 | +| FR-009 | `check_interpolation_geometry` | U2.7 test | None | +| FR-010 | Factory (no `model.scale`); 3D inferred centre | SC-003 explicit and inferred | None | +| FR-011 | Slip orthogonalisation; extent-direction row | SC-003, SC-013 | None | +| FR-012 | Stored `_fault_buffer`, `_force_mesh_geometry`; factory override removed | SC-005; U1.5 test | None | +| FR-013 | `local_enclosure`; `set_interpolation_geometry` | SC-005; enclosure unit test | None | +| FR-014 | `_cells_for_length`; setters | Resize-10-times test | Other supports S5, OP1 | +| FR-015 | S5 | S5 | OP1 | +| FR-016 | S3 | S3 | OP1 | +| FR-017 | S3 | S3 | OP1 | +| FR-018 | S3 | S3 | OP1 | +| FR-019 | S3 | S3 | OP1 | +| FR-020 | S3 | S3 | OP1 | +| FR-021 | `validate_rigid_rotation` in `set_local_transform` and `rotation_xy` | `test_rigid_transform_contract.py` | Saved-metadata part S3, OP1 | +| FR-022 | S4 | S4 | OP1 | +| FR-023 | S5 | S5 | OP1 | +| FR-024 | `excluded_rows` (S1 part) | Restricted-support exclusion count | Report integration S5, OP1 | +| FR-025 | S6 | S6 | OP1 | +| FR-026 | S1: values, gradients, residuals (SC-003, SC-008); displacement S6 | `test_fault_frame_analytic.py` | Displacement OP1 | +| FR-027 | S6 | S6 | OP1 | +| FR-028 | No signature change; `COMPAT.md` note | API contract tests | FR-019 exception S3, OP1 | +| FR-029 | `verification.md` golden review section | Review record per changed result | None | +| FR-030 | S1 FDI and PLI cells | S1 tests | Other cells S2, S6, OP1 | +| FR-031 | Pre-fix rule in "Test strategy" | `verification.md` | None | +| FR-032 | "Stages and rollback" | Rollback checks in `verification.md` | None | +| SC-001 | `_rigid.py`, `BoundingBox` | `test_rigid_transform_contract.py` | None | +| SC-002 | R1 evaluation | S2/S3 (R1 lifecycle and fits) | OP1 | +| SC-003 | Fault design | `test_fault_frame_analytic.py` | Run time OP2 | +| SC-004 | S6 | S6 | OP1 | +| SC-005 | Fault and enclosure design | `test_fault_buffer_bounds.py` | Run time OP2 | +| SC-006 | S3 | S3 | OP1 | +| SC-007 | Reference sampling | `test_reference_constraint_frames.py` | Fold and P2 S2, OP1 | +| SC-008 | Reference sampling | `test_reference_constraint_frames.py` (FDI, PLI) | P2 S2, OP1 | +| SC-009 | S5 | S5 | OP1 | +| SC-010 | S6 | S6 | OP1 | +| SC-011 | `_cells_for_length` (resize part) | Resize test | Cell centres S5, OP1 | +| SC-012 | Rotation part in S1 | `test_rigid_transform_contract.py` | Metadata and legacy part S3, OP1 | +| SC-013 | Extent-direction row | `test_fault_frame_analytic.py` | Fold R4 geometry S2, OP1 | +| SC-014 | Merge gates in every stage | `pytest`, ruff, package tests | None | +| SC-015 | `verification.md` golden review | Review record; 0 tolerance changes | None | +| SC-016 | S3 | S3 | OP1 | +| SC-017 | Rollback column; format part S3 | `verification.md` | OP1 | +| SC-018 | S1 cells; matrix S6 | `verification.md` backend matrix | OP1 | +| SC-019 | Gate checked on 2026-11-04: 003 spec (C-006, main and native worktree copies identical) and 004 spec (2026-11-03 source-005 entries) contain the amendments | Document check | None | + +## Handover + +- **Coordinate conversion (owner: `loop_interpolation`)**: + `GeologicalInterpolator.world_to_local_points`, `local_to_world_points`, + `world_to_local_vectors`, `local_to_world_vectors`. Spec 004 uses + `world_to_local_vectors` to convert sampled world directions once into the + computational basis before the low-level core. Spec 001 keeps its contract: + the core gets local, unrotated grid inputs. +- **Rotation check (owner: `loop_common`)**: + `loop_common.geometry.validate_rigid_rotation(matrix, dimensions, atol=1e-10)` + and `RigidRotationError(ValueError)`. S3 uses them for saved metadata. +- **Box enclosure (owner: `loop_common`)**: + `BoundingBox.local_enclosure(origin=None, maximum=None) -> (local_min, local_max)`. +- **Callback contracts**: feature-facing reference callbacks and region + callbacks receive world points. `add_gradient_orthogonal_constraints` + receives target-local points and target-local unit vectors. +- **Exclusion record**: `GeologicalFeatureBuilder.excluded_rows: + dict[str, dict[str, int]]`. S5 connects it to the diagnostics report. +- **Fault geometry**: an explicit `fault_center` is a world point; the + generated centre extent row is `coord=2` with `strike_unit / major_axis`. + Spec 003 golden fault models can change only under C-006/C-004 with a + record in `verification.md`. Spec 003 cache invalidation for transform + changes is S3. +- **Shared files**: `_geological_interpolator.py`, `_discrete_interpolator.py` + and `_fault_builder.py` are also in the scope of specs 003 and 004. + Coordinate the merge order with the active 003 worktree + (`LoopStructural-native`). + +## Complexity tracking + +None. diff --git a/specs/005-coordinate-frame-correctness/tasks.md b/specs/005-coordinate-frame-correctness/tasks.md new file mode 100644 index 000000000..30cdbe7c3 --- /dev/null +++ b/specs/005-coordinate-frame-correctness/tasks.md @@ -0,0 +1,391 @@ +# Tasks: Coordinate and fault-frame correctness (stage S1) + +**Feature**: `005-coordinate-frame-correctness` | **Plan**: [plan.md](plan.md) + + + +## Orchestrator notes + +- Run this file with the spec-orchestrator skill. It has the rules for the + worktree, the sub agents, the checks and the commits. +- Waves: 7. Tiers: [S] = simple model, [M] = standard model. +- Do not start a task with "Blocked by". + +## Phase 1: Setup + +- [ ] T001 [P] [Setup] [S] Create the S1 verification record skeleton. + - Files: `specs/005-coordinate-frame-correctness/verification.md` + - Needs: none + - Wave: 1 + - Done when: the file exists with the 6 headings below, each followed by + the line "No entries yet." + - Context: Title `# Verification: 005-coordinate-frame-correctness`. + Headings, in this order: `## Pre-fix failures`, `## Post-fix results`, + `## Golden review (C-004)`, `## Backend matrix`, `## Rollback checks`, + `## Test run time (OP2)`. Under the title, add one sentence: "This file + records the evidence for FR-029, FR-031 and FR-032 of spec 005." + Write in ASD-STE100 Simplified Technical English. + +- [ ] T002 [P] [Setup] [M] Create the shared analytic fixtures R1 to R5. + - Files: `tests/fixtures/coordinate_frames.py` + - Needs: none + - Wave: 1 + - Done when: `pytest tests/fixtures/coordinate_frames.py` collects 0 + tests with no import error, and `ruff check LoopStructural packages` + passes. + - Context: Helper module, no tests. numpy docstrings and type hints; Black + line length 100. Names: `ANCHORS` = arrays (0,0,0), (100,200,300), + (-100,-200,-300), (500000,6500000,100); `ROTATIONS_DEG = (0.0, 30.0, 90.0)`; + `rot_z(deg: float) -> np.ndarray` = [[c,-s,0],[s,c,0],[0,0,1]]; + `tp(L: float, W: float) -> float` = `1e-10*L + 32*np.finfo(float).eps*max(W, L)`; + `model_with_frame(origin, maximum, rotation_deg) -> GeologicalModel` makes + `GeologicalModel(origin, maximum)` then calls + `model.bounding_box.set_local_transform(local_origin=origin, rotation_matrix=rot_z(rotation_deg))`. + `r2_fault_data(anchor)`: DataFrame, columns X,Y,Z,val,coord,feature_name + ("fault"),w; 25 rows at x'=0, y',z' in {-8,-4,0,4,8}, val 0, coord 0, w 1. + `r5_fault_data(anchor)`: same, y',z' in {-4,-2,0,2,4}. + `r2_probes(anchor)`: 6859 points `anchor + {-9..9}^3`. + `r2_frame(points, anchor) -> (values (N,3), gradients (N,3,3))`: + gx=x'/20, gy=-z'/20, gz=y'/20. `r3_value`/`r3_gradient`: h=x'+0.05*y'^2+z', + grad (1,0.1*y',1). `r4_frame(points, anchor)`: R=40, X=R+x', + r=sqrt(X^2+y'^2); surface (r-R)/20, slip -z'/20, extent R*atan2(y',X)/20, + with the analytic gradients of spec.md R4. `class AnalyticReference` with + `__init__(value_fn, gradient_fn, name, support_box=None)`, + `evaluate_value(points)`, `evaluate_gradient(points, ignore_regions=True)`, + `__call__ = evaluate_value`; NaN outside the closed `support_box`. + +## Phase 2: Foundation (blocks all user stories) + +- [ ] T003 [P] [Found] [M] Test: rigid rotation, round trips, enclosure and resize stability. + - Files: `packages/loop_common/tests/test_rigid_transform_contract.py` + - Needs: none + - Wave: 1 + - Done when: `pytest packages/loop_common/tests/test_rigid_transform_contract.py` + fails before T004 (import error), then passes after T005 and T006. + - Context: Self-contained (do not import `tests/fixtures`). Tests: + `test_validate_rigid_rotation_accepts_proper_rotations` (0, 30, 90 deg + about z; 2D and 3D); `test_validate_rigid_rotation_rejects_invalid` + (scale, shear, singular, reflection det -1, NaN, inf, wrong shape) expects + `RigidRotationError`, a `ValueError` subclass; + `test_point_and_direction_round_trips` (SC-001: `BoundingBox.project` then + `reproject` within `Tp = 1e-10*L + 32*eps*max(W,L)`; `project_vectors` then + `reproject_vectors` within 1e-12; 1 point and arrays; anchors (0,0,0), + (100,200,300), (-100,-200,-300), (500000,6500000,100)); + `test_local_enclosure_contains_projected_corners` (all 8 projected corners + inside `BoundingBox.local_enclosure()` within Tp, for each rotation); + `test_invalid_rotation_keeps_prior_state` (`set_local_transform` and + `StructuredGrid3DGeometry.rotation_xy` keep the old matrix after the error); + `test_reapply_unchanged_bounds_is_stable` (set `origin` and `maximum` of a + `StructuredGrid3DGeometry` to their own values 10 times: 0 changes to + origin, maximum, step_vector, nsteps). Import from `loop_common.geometry`. + +- [ ] T004 [Found] [S] Add `validate_rigid_rotation` and `RigidRotationError`. + - Files: `packages/loop_common/src/loop_common/geometry/_rigid.py`, + `packages/loop_common/src/loop_common/geometry/__init__.py` + - Needs: T003 + - Wave: 2 + - Done when: `pytest packages/loop_common/tests/test_rigid_transform_contract.py -k validate_rigid_rotation` + passes. + - Context: New module, imports numpy only. `class RigidRotationError(ValueError)`. + `def validate_rigid_rotation(matrix: np.ndarray, dimensions: int, atol: float = 1e-10) -> np.ndarray`: + return `np.array(matrix, dtype=float)` (a copy). Raise + `RigidRotationError` when shape != (dimensions, dimensions), any entry is + not finite, `max|R.T @ R - I| > atol`, or `|det(R) - 1| > atol`. Message + names the failed condition and ends with "supply a proper rotation + (orthonormal, det +1); scale and shear are not supported". In + `__init__.py` add `from ._rigid import RigidRotationError, validate_rigid_rotation` + as the first import line. numpy docstrings, type hints, py39 (use + `from __future__ import annotations`). + +- [ ] T005 [P] [Found] [M] Validate the local transform and add `BoundingBox.local_enclosure`. + - Files: `packages/loop_common/src/loop_common/geometry/_bounding_box.py` + - Needs: T004 + - Wave: 3 + - Done when: `pytest packages/loop_common/tests/test_rigid_transform_contract.py -k "round_trips or local_enclosure or prior_state"` + and `pytest packages/loop_common/tests` pass. + - Context: In `set_local_transform(local_origin=None, rotation_matrix=None)` + call `validate_rigid_rotation(rotation_matrix, self.dimensions)` (import + from `._rigid`) and reject a non-finite `local_origin` with + `LoopValueError`, both before any field changes. New method + `def local_enclosure(self, origin: np.ndarray | None = None, maximum: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]`: + defaults `self.origin`, `self.maximum`; raise `LoopValueError` if a bound + is None, not finite, or origin > maximum on an axis; build the + `2**dimensions` corners with `itertools.product`; return + `(min, max)` over axis 0 of `self.project(corners)`. numpy docstring. + Existing tests in `packages/loop_common/tests/test_bounding_box.py` use + proper rotations and must still pass. + +- [ ] T006 [P] [Found] [M] Repair support resize and validate `rotation_xy`. + - Files: `packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py` + - Needs: T004 + - Wave: 3 + - Done when: `pytest packages/loop_common/tests/test_rigid_transform_contract.py -k "prior_state or unchanged_bounds"` + and `pytest packages/loop_common/tests` pass. + - Context: `_nsteps` is a NODE count; `nsteps_cells = nsteps - 1`; + `maximum = origin + nsteps_cells * step_vector`. Defect: the `origin` and + `maximum` setters set `_nsteps = ceil(length/step)` (a cell count), so the + support loses 1 cell. Add + `def _cells_for_length(self, length: np.ndarray) -> np.ndarray`: + `cells = np.ceil(length / self.step_vector - 1e-9).astype(np.int64)`; + axes with 0 cells get 2 cells; raise `ValueError("Cannot resize the grid.")` + if a count < 0. `origin` setter: compute `self.maximum` first, then + `self._nsteps = self._cells_for_length(maximum - origin) + 1`. + `maximum` setter: `self._nsteps = self._cells_for_length(maximum - self.origin) + 1`. + Keep `_on_geometry_change()` calls. `rotation_xy` setter: after the + float/int conversion call `validate_rigid_rotation(rotation_xy, 3)` + (import from `._rigid`); `None` keeps the current value. + +## Phase 3: User story 2 - Constrain features at the intended physical points (P1) + +**Goal**: reference relationships sample at world points and install rows in +the target-local basis. +**Independent test**: `pytest tests/unit/modelling/test_reference_constraint_frames.py`. + +- [ ] T007 [P] [US2] [M] Test: R3 reference relationships for FDI and PLI. + - Files: `tests/unit/modelling/test_reference_constraint_frames.py` + - Needs: T002 + - Wave: 2 + - Done when: `pytest tests/unit/modelling/test_reference_constraint_frames.py` + fails before T008 to T010, then passes after them. Record the failing + test ids in the task report. + - Context: Use `tests/fixtures/coordinate_frames.py` (ANCHORS, + ROTATIONS_DEG, model_with_frame, AnalyticReference, r3_value, r3_gradient, + tp). Box `O` to `O+(8,10,12)`; support 5x6x7 cells (336 nodes); engines + "FDI" and "PLI". Tests: `test_world_local_conversion_methods` + (`interpolator.world_to_local_points` etc. invert each other within Tp); + `test_equality_region_selects_world_nodes` (region `x' > 4`: 168 of 336 + unrotated; for rotations compute the expected set from world nodes; 0 + missing or duplicate; value = h at the world node); + `test_orthogonal_rows_affine_residual` (field f=y', direction (1,0,0) + target 0, direction (0,1,0) target 1; rows `f"{name}_orthogonal"`; + residual `A @ c_exact - b` at most 1e-10 for sample_rule None, + "centroid", "gauss4"); + `test_inequality_feature_bounds_world` (bounds = h at world nodes); + `test_restricted_reference_exclusion_counts` (box O+(2.1,2.1,2.1) to + O+(5.9,7.9,9.9); `builder.excluded_rows` count equals the analytic count); + `test_support_expansion_contains_restored_points` (FR-009); + `test_set_interpolation_geometry_encloses_rotated_box`. + +- [ ] T008 [US2] [S] Add the public world/local conversion methods. + - Files: `packages/loop_interpolation/src/loop_interpolation/_geological_interpolator.py` + - Needs: T007 + - Wave: 3 + - Done when: `pytest tests/unit/modelling/test_reference_constraint_frames.py -k conversion` + passes. + - Context: Add four public methods after `_project_constraint_array`: + `world_to_local_points(self, points: np.ndarray) -> np.ndarray` returns + `self._project_points(points)`; `local_to_world_points` returns + `self._reproject_points(points)`; `world_to_local_vectors` returns + `self._project_vectors(vectors)`; `local_to_world_vectors` returns + `self._reproject_vectors(vectors)`. Keep the private methods. Docstrings + (numpy style): input `(N, d)` or `(d,)`, same output shape; vectors use + rotation only; with `bounding_box is None` the input is returned. + +- [ ] T009 [P] [US2] [S] Sample `add_inequality_feature` at world nodes. + - Files: `packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py` + - Needs: T008 + - Wave: 4 + - Done when: `pytest tests/unit/modelling/test_reference_constraint_frames.py -k inequality` + passes. + - Context: In `add_inequality_feature(self, feature, lower=True, mask=None)` + replace `value = feature(self.support.nodes)` with + `value = feature(self.local_to_world_points(self.support.nodes))`. Add to + its docstring: "`feature` receives world points and returns one value for + each support node." In the docstring of the abstract + `add_gradient_orthogonal_constraints(self, points, vectors, w=1.0)` state: + "`points` are target-local support points; `vectors` are target-local + unit directions." No signature changes. + +- [ ] T010 [P] [US2] [M] Sample reference features at world points in the feature builder. + - Files: `LoopStructural/modelling/features/builders/_geological_feature_builder.py` + - Needs: T005, T008 + - Wave: 4 + - Done when: `pytest tests/unit/modelling/test_reference_constraint_frames.py -k "not inequality"` + and `pytest tests/unit/modelling` pass. + - Context: Add `self.excluded_rows: dict[str, dict[str, int]] = {}` in + `__init__`. Reasons: "invalid_reference_value", + "invalid_reference_direction", "evaluation_error". + `install_gradient_constraint`: local points (existing) -> `world = + self.interpolator.local_to_world_points(pts)`; `vector = + feature.evaluate_gradient(world, ignore_regions=True)`; `valid` = finite + and norm > 0; record `(~valid).sum()`; normalise; `world_to_local_vectors`; + pass `pts[valid]`, local vectors, `weight[valid]` if array. 0 valid -> no + rows, warning. `install_equality_constraints`: world nodes, `idc = + np.flatnonzero(region(world_nodes))`, `val = + feature.evaluate_value(world_nodes[idc])`, finite mask, name + `f"{feature.name}_equality"`; the `except` records "evaluation_error". + `set_interpolation_geometry`: use + `self.interpolator.bounding_box.local_enclosure(origin, maximum)`. + `check_interpolation_geometry`: `regular_grid(local=False)`, restore in + world, `world_to_local_points`, min/max on copies of support arrays. + +## Phase 4: User story 1 - Build a fault frame at its supplied location (P1) + +**Goal**: the public fault API makes the analytic planar frame at the supplied +world location, with the requested buffer. +**Independent test**: `pytest tests/unit/modelling/test_fault_frame_analytic.py tests/unit/modelling/test_fault_buffer_bounds.py`. + +- [ ] T011 [P] [US1] [M] Test: R2 planar frame, centre handling and R4 extent row. + - Files: `tests/unit/modelling/test_fault_frame_analytic.py` + - Needs: T002 + - Wave: 2 + - Done when: `pytest tests/unit/modelling/test_fault_frame_analytic.py` + fails before T012 and T013, then passes after them. + - Context: Build through `model.create_and_add_fault("fault", 0, data=..., + interpolatortype=..., fault_center=O or None, fault_normal_vector=(1,0,0), + fault_slip_vector=(0,0,-1), major_axis=20, minor_axis=10, + intermediate_axis=20, fault_buffer=0.2, nelements=20000 (FDI) or 1000 + (PLI), fault_trace_anisotropy=0, fault_dip_anisotropy=0)`. Solve: CG rtol + 1e-10, atol 1e-12, maxiter 20000; orthogonality weight 1, step 10. + Tests: `test_explicit_centre_rows_not_projected` (generated rows use O); + `test_inferred_centre_keeps_elevation` (inferred centre == O, all 3 + components); `test_slip_vector_made_orthogonal` and + `test_parallel_slip_raises` (ValueError); + `test_extent_direction_row_at_centre` (one coord-2 row at O with + n = (0,1/20,0); equals the R4 analytic extent gradient at O within 1e-10; + R4 extent directions at O+(0,-6,0), O+(0,6,0) differ >= 15 degrees); + `test_planar_fault_frame_matches_analytic` (SC-003 on `r2_probes`: scalar + error <= 1e-6, relative gradient magnitude <= 1e-4, direction <= 0.01 deg; + 4 anchors x 3 rotations x 2 centre modes x FDI, PLI). + +- [ ] T012 [US1] [M] Repair centre, slip, extent row and buffer state in `FaultBuilder`. + - Files: `LoopStructural/modelling/features/builders/_fault_builder.py` + - Needs: T011, T014 + - Wave: 3 + - Done when: `pytest tests/unit/modelling/test_fault_frame_analytic.py -k "inferred_centre or slip or extent_direction"` + passes. + - Context: `__init__`: `self._fault_buffer: float = 0.2`, + `self._force_mesh_geometry: bool = False`. `create_data_from_geometry` + stores both from its arguments first. `_on_geometry_change`: default + `force_mesh_geometry=None`; `None` args use the stored values. Inferred + centre: rows `coord == 0` and `val == 0`, columns X,Y,Z, `np.nanmean`; + a non-finite component -> 0.0 plus a warning naming the axis. Slip: + `s_perp = s - (s @ n) * n`; if `|s_perp| < 1e-12` raise + `ValueError("fault slip vector is parallel to the fault normal; supply a slip direction in the fault plane")`; + use the unit `s_perp` for `fault_slip_vector`, strike and depth rows. + `strike_unit = cross(n, s_perp)/|...|`. When `major_axis` is not None add + one row: X,Y,Z = centre, nx,ny,nz = `strike_unit / major_axis`, val NaN, + coord 2, w. Early return (no trace): call + `self.set_mesh_geometry(fault_buffer, None)` before `return`. + +- [ ] T013 [US1] [S] Stop the centre projection and the buffer override in the fault factory. + - Files: `LoopStructural/modelling/core/_model_feature_factory.py` + - Needs: T006, T010, T012 + - Wave: 5 + - Done when: `pytest tests/unit/modelling/test_fault_frame_analytic.py tests/unit/modelling/test_fault_buffer_bounds.py` + passes. + - Context: In `create_and_add_fault`, delete the two lines + `if fault_center is not None and ~np.isnan(fault_center).any():` / + `fault_center = model.scale(fault_center, inplace=False)`. Delete the two + lines `if "force_mesh_geometry" not in kwargs:` / + `fault_frame_builder.set_mesh_geometry(kwargs.get("fault_buffer", 0.2), 0)`. + `create_data_from_geometry` already applies `fault_buffer` and + `force_mesh_geometry`. No signature change. An explicit `fault_center` + is a world point (FR-010). + +- [ ] T014 [P] [US1] [M] Test: R5 buffer and forced-geometry bounds. + - Files: `tests/unit/modelling/test_fault_buffer_bounds.py` + - Needs: T002 + - Wave: 2 + - Done when: `pytest tests/unit/modelling/test_fault_buffer_bounds.py` + fails before T012 and T013, then passes after them. + - Context: Use `r5_fault_data`, `model_with_frame`, `rot_z`, `tp`. Box + O-(10,10,10) to O+(10,10,10); normal (1,0,0), slip (0,0,-1); axes major 12, + minor 4, intermediate 12; `force_mesh_geometry=True`; buffers b = 0, 0.2, + 0.5 through `create_and_add_fault`; FDI nelements 20000, PLI 1000; + explicit and inferred centre; rotations 0, 30, 90 deg. Requested world + box `O +/- (10+20*b)`; expected local box = enclosure of its 8 projected + corners. Tests: `test_buffer_bounds_match_request` (each support face is + outward of the expected bound by 0 to 1 cell (actual local spacing) plus + Tp; all generated rows inside the support); + `test_buffers_give_distinct_bounds`; + `test_property_change_keeps_buffer_and_forced_geometry` (set + `builder.fault_normal_vector = (1,0,0)` after creation; bounds unchanged). + +- [ ] T015 [US1] [M] Align `test__fault_builder.py` with the corrected behaviour. + - Files: `tests/unit/modelling/test__fault_builder.py`, + `specs/005-coordinate-frame-correctness/verification.md` + - Needs: T001, T013 + - Wave: 6 + - Done when: `pytest tests/unit/modelling/test__fault_builder.py` passes. + - Context: Change an assertion only if it encodes a defect that S1 fixed + (for example an inferred centre with z = 0, a projected explicit centre, + or a default buffer that replaced the requested one). For each change add + one entry under `## Golden review (C-004)` in `verification.md`: test id, + old value, new value, defect, expected physical effect. Do not relax a + tolerance (SC-015). If no change is needed, write "No golden change in + S1." under that heading. + +## Phase 5: Finish + +- [ ] T016 [P] [Finish] [S] Add the S1 migration notice to `COMPAT.md`. + - Files: `COMPAT.md` + - Needs: T013 + - Wave: 6 + - Done when: the "Migration notices" table in `COMPAT.md` has the new row + with date 2026-11-04. + - Context: Add one row at the end of the table under + `## Migration notices (not breaking, no shim needed)`. Columns: Old | + New | Since. Old: "`create_and_add_fault(fault_center=...)` projected the + centre into local coordinates; `fault_buffer`/`force_mesh_geometry` were + replaced by a default 0.2 buffer; an inferred centre had z = 0; any 3x3 + matrix was accepted as a rotation". New: "`fault_center` is a world point; + the requested buffer and forced geometry are kept; an inferred centre keeps + its elevation; `set_local_transform` and `rotation_xy` raise + `RigidRotationError` for a non-rigid matrix. Extra observations added to + work around these defects are no longer necessary (spec 005)". Since: + 2026-11-04. + +- [ ] T017 [Finish] [M] Record pre-fix evidence, gates, run time and rollback. + - Files: `specs/005-coordinate-frame-correctness/verification.md` + - Needs: T003, T004, T005, T006, T007, T008, T009, T010, T011, T012, T013, T014, T015, T016 + - Wave: 7 + - Done when: `ruff check LoopStructural packages && pytest` and + `pytest packages/loop_common/tests packages/loop_interpolation/tests` + pass, and each heading of `verification.md` has an entry. + - Context: Pre-fix evidence (FR-031): make a throw-away worktree at commit + `ebc7c699` (`git worktree add ebc7c699`), copy the 4 new test files + and `tests/fixtures/coordinate_frames.py` into it, run them with + `PYTHONPATH=;/packages/loop_common/src;/packages/loop_interpolation/src` + (the repo `.venv` is editable on the main checkout), record each failing + test id and value under `## Pre-fix failures`, then + `git worktree remove `. A finding that does not fail is "not + reproduced". Record pass results, the backend cells covered (Python FDI, + PLI/P1), the S1 test time (OP2), and the rollback check: on the + worktree at `ebc7c699`, `tests/unit/modelling/test__fault_builder.py` and + `packages/loop_common/tests/test_bounding_box.py` pass. + +## Wave table + +| Wave | Tasks | Tier [S] | Tier [M] | +|---|---|---|---| +| 1 | T001, T002, T003 | 1 | 2 | +| 2 | T004, T007, T011, T014 | 1 | 3 | +| 3 | T005, T006, T008, T012 | 1 | 3 | +| 4 | T009, T010 | 1 | 1 | +| 5 | T013 | 1 | 0 | +| 6 | T015, T016 | 1 | 1 | +| 7 | T017 | 0 | 1 | + +## Critical path + +T003 -> T004 -> T005 -> T010 -> T013 -> T015 -> T017 + +## Dependencies + +- Setup (T001, T002) and the foundation test T003 start at once. +- Foundation: T003 -> T004 -> T005, T006. +- US2: T007 -> T008 -> T009, T010 (T010 also needs T005). +- US1: T011, T014 -> T012 -> T013 (T013 also needs T006 and T010, because + the fault frame uses the repaired reference sampling and resize). +- Finish: T015 and T016 after T013; T017 last. +- Stages S2 to S6 have no tasks yet (OP1 in plan.md). diff --git a/specs/README.md b/specs/README.md index 0288aeb37..ebd99cc42 100644 --- a/specs/README.md +++ b/specs/README.md @@ -1,6 +1,6 @@ # Specification index -Updated: 2026-11-03. This index records document and workflow state. It does +Updated: 2026-11-04. This index records document and workflow state. It does not certify that an implementation or a numerical acceptance gate passed. | Spec | State | Next step or existing open point | @@ -9,7 +9,7 @@ not certify that an implementation or a numerical acceptance gate passed. | [002-rbf-interpolator](002-rbf-interpolator/spec.md) | Draft, not reviewed | Continue its existing review and clarification workflow. This cascade did not change it. | | [003-fault-evaluation-performance](003-fault-evaluation-performance/spec.md) | Implementation in progress; 005 contract cascade applied | Its active plan and tasks remain in the existing LoopStructural-native worktree. OP3 and OP4 remain open; completed tasks, including concurrent T043, and measured failures are preserved. | | [004-matrix-free-directional-constraints](004-matrix-free-directional-constraints/spec.md) | Draft; 005 contract cascade applied; task graph checked | Review the updated plan and tasks. OP1 still requires the quadrature measurements before a default is chosen. | -| [005-coordinate-frame-correctness](005-coordinate-frame-correctness/spec.md) | Cross-spec documentation prerequisite reconciled | Continue the 005 planning workflow after confirming SC-019. Its source header still records the earlier cascade block; this cascade leaves the source spec unchanged. | +| [005-coordinate-frame-correctness](005-coordinate-frame-correctness/spec.md) | Staged plan and S1 tasks written 2026-11-04 ([plan.md](005-coordinate-frame-correctness/plan.md), [tasks.md](005-coordinate-frame-correctness/tasks.md): 17 tasks, 7 waves); SC-019 confirmed | Run spec-orchestrator for S1. OP1: plan S2 to S6 in later planner runs. OP2: decide where the R2/R5 matrix runs. | ## Cascade of 005 From 4ed44583f45bd5073ed61bd04d164b6d538b915c Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Fri, 6 Nov 2026 14:34:59 +1030 Subject: [PATCH 02/96] docs(spec): add spec, plan and tasks for 006-loop-link --- specs/006-loop-link/plan.md | 783 +++++++++++++++++++++++++++++ specs/006-loop-link/run-state.json | 10 + specs/006-loop-link/spec.md | 436 ++++++++++++++++ specs/006-loop-link/tasks.md | 323 ++++++++++++ 4 files changed, 1552 insertions(+) create mode 100644 specs/006-loop-link/plan.md create mode 100644 specs/006-loop-link/run-state.json create mode 100644 specs/006-loop-link/spec.md create mode 100644 specs/006-loop-link/tasks.md diff --git a/specs/006-loop-link/plan.md b/specs/006-loop-link/plan.md new file mode 100644 index 000000000..846d063c0 --- /dev/null +++ b/specs/006-loop-link/plan.md @@ -0,0 +1,783 @@ +# Implementation plan: loop_link, a Python link to geoviewer + +**Feature**: `006-loop-link` | **Date**: 2026-11-06 | **Spec**: [spec.md](spec.md) + + + +## Open points + +Each point has a default. A point that has no owner is for the maintainer. + +- **OP1**: The `[NEEDS CLARIFICATION]` mark of story 7, scenario 7 (FR-021). + The protocol 1.14 data array can carry `colour_map` (`name`, `range`, `clip`, + `scale`). So the map, the range and the scale can go in the send message. The + property that colours the object (active array) and the plain colour of the + object have no field in `scene.upsert`. The `style` field has no schema. Default + for S4: send the map, range and scale in `colour_map`, and send the active + array and the plain colour as follow-up commands (`colour.set_active`, + `object.set_colour`) on the tool connection, inside the same call. The S4 + task reads how the viewer applies `style` first. It blocks S4 only. S1 to S3 + do not use it. +- **OP2**: The default `crs` of `hello`. `Hello.crs` is a required string in the + viewer. The viewer may refuse an empty text. Default: `Viewer(crs="")`, and the + library keeps the CRS that the viewer answers in `Viewer.scene_crs`. Task T-S1 + for `viewer.py` reads `crates/geoviewer/src` hello handling in the geoviewer + repository first. If the viewer refuses `""`, the library raises + `InvalidInputError` that says "give crs=..." for an empty scene. +- **OP3**: FR-010 says that pyvista input works for all seven types. A pyvista + mesh cannot hold a collar, a survey and intervals. Default: `from_pyvista` + raises `InvalidInputError` for a Drillhole, and the message names `Drillhole` + and the pandas adapter. The coverage table shows this gap until the spec owner + answers. Blocks S2 only for this one combination. +- **OP4**: FR-017 sets Python 3.10 for this package. The QGIS plugin runs on the + Python of QGIS, which can be 3.9 on some systems. Owner: plugin repository. + Default: keep 3.10. This blocks no task here. +- **OP5**: The root `pyproject.toml` has `requires-python = '>=3.9'` and the uv + workspace takes all `packages/*`. A member with `>=3.10` can make `uv lock` + refuse the workspace, or can raise the floor of the lock. Default: add the + member, and run `uv lock`. If uv refuses, or if the lock drops 3.9 for the other + members, add `packages/loop_link` to `[tool.uv.workspace] exclude` (as + `packages/loop_interpolation_core` is) and make the CI job install it with + `pip install -e packages/loop_link[tests]`. +- **OP6**: Stories 6 and 7 (filter and colour, FR-018 to FR-021, SC-007) need the + tool connection. Default: plan them in a later planner run as stage S4. The + names of the commands are in "Handover". +- **OP7**: Stories 2, 3 and 4 (select, read selection, fetch) wait for geoviewer + spec 066. Default: plan them in a later planner run as stage S5, after 066 + lands. The plan of 066 uses protocol 1.15 and may change names (its OP4). +- **OP8**: SC-004 needs the folder `fixtures/protocol/python` of the geoviewer + repository. CI of this repository cannot see it. Default: the tests read the + folder from the environment variable `LOOP_LINK_GEOVIEWER_FIXTURES`. When it + is not set, they skip, with the reason in the skip text. A copy of the frames + is not stored here (one source). The maintainer runs the tests with the + variable before a release. +- **OP9**: The structured grid of the spec is the viewer `BlockModel` (a regular + axis-aligned grid). Default: a non-regular pyvista `StructuredGrid` or a + `RectilinearGrid` with uneven spacing gives `InvalidInputError`. The viewer has + no type for them. + +## Answers + +(empty) + +## Summary + +`packages/loop_link` is a new Python package. It has its own codec for protocol +1.14 (numpy and the standard library only), a stdlib WebSocket client (ported from +the plugin), discovery of the viewer and the token, the seven object types as +dataclasses, one `Viewer` class that holds the one data connection (with a +keepalive thread), optional adapters (pyvista, LoopStructural, pandas), a plugin +push API with no Qt, and a fake viewer in `loop_link.testing`. The package +registers in `ROADMAP.md`, the release-please files, the CI matrix and the Ruff +config. + +The work has three stages in this plan: S1 (send, story 1), S2 (adapters, +FR-010), S3 (plugin API, story 5). The stages S4 and S5 are for later runs. + +## Technical context + +- **Packages changed**: new `packages/loop_link`. Root files: `pyproject.toml`, + `uv.lock`, `ROADMAP.md`, `.release-please-config.json`, + `.release-please-manifest.json`, `.github/workflows/packages.yml`. No change + in `LoopStructural/`, `loop_common`, or `packages/loop_interpolation_core`. +- **Languages and versions**: Python `>=3.10` for the package (FR-017). Root + Ruff and Black target py39. So the package has its own `ruff.toml` with + `target-version = "py310"` (see "Project structure"). Every module starts with + `from __future__ import annotations` (Ruff rule `FA`). The code uses no + `match` statement and no parenthesised `with`, because `black .` from the root + parses with target py39. +- **New dependencies**: required: `numpy`. Extras: `pyvista` (`pyvista`), + `loopstructural` (`loop-common`), `pandas` (`pandas`), `tests` (`pytest`). + There is no WebSocket package. The plugin client uses the standard library + because QGIS does not ship a WebSocket package for each platform. The spec says + "a WebSocket client", and a stdlib client meets this with no dependency + (principle VII of the geoviewer constitution has the same intent). +- **Public API and import changes**: new import path `loop_link`. No existing + import changes. The public names are in "Functions and public API". +- **Saved-data format changes**: none. The package writes no file. It reads + `link.json` and `instances/.json` of the viewer. +- **Coordinate contract**: the library sends the coordinates that the caller + gives, as world coordinates (spec 005: public data is in world coordinates). It + subtracts the origin of the scene (from the `hello` answer of the viewer) in + `f64`, then writes `f32`, or `f64` when a value is more than 4000 from the + origin. No local frame or geological frame crosses the boundary. The LoopStructural + adapter reads the public attributes `origin`, `step_vector`, `nsteps`, + `vertices` (world coordinates) and applies no other transform. +- **Performance target**: SC-001 (1,000,000 cells, one float property, under 5 s + to the inventory) and SC-007 (S4). Measure SC-001 with the fake viewer and + with the real viewer by hand (manual check M1). +- **Platforms and backends**: Windows, Linux, macOS; Python 3.10 to 3.12. The CI + matrix variable `PYTHON_VERSIONS` can have 3.9. The package job skips 3.9. The + optional extras may be missing. A missing extra gives `MissingExtraError` when + the adapter runs, and never at `import loop_link`. + +## Constitution check + +| Project rule | Result | How the plan agrees | +|---|---|---| +| Work stays within the existing library and package responsibilities | Pass | The new package is a client of the geoviewer protocol only. It does not change `LoopStructural/` or another package. The extra `loopstructural` reads the public classes of `loop_common.geometry`. | +| Development commands come from .dev-tools/project.json and the constitution | Pass | The commands are `pytest`, `ruff check LoopStructural packages` and `black .`. The package tests run with `uv run --package loop-link pytest packages/loop_link/tests` (the form of `packages.yml`). | +| Both pytest and ruff check LoopStructural packages must pass before merge | Pass | Each stage lists both commands. The new package is under `packages`, so Ruff checks it. | +| Python changes use numpy-style docstrings and type hints; Ruff targets py39 | Pass, with one deliberate difference | New files get no `D`/`ANN` exemption in `src`. Tests get the same exemption as the other package tests. The package target is py310 by `packages/loop_link/ruff.toml` (FR-017 asks the plan to set it). The repository default stays py39. | +| Black uses line length 100 and preserves string quoting | Pass | The package uses the root Black config. The code avoids syntax that py39 cannot parse. | +| ROADMAP.md owns architecture stages and decisions; update it when either changes | Pass | S1 adds the package to `ROADMAP.md` (FR-016, SC-006). | +| Stages can be tested and reversed independently | Pass | See "Stages and rollback". The new package only adds files. Rollback of each stage is a revert of that stage. | +| The public GeologicalModel API stays compatible; a break needs a ROADMAP.md decision and a major-version note | Not applicable | No change in `GeologicalModel` or `LoopStructural/`. | +| The QGIS plugin stays in its separate repository | Pass | The plugin change and the removal of the old client stay in the plugin repository (spec, "Out of scope"). S3 only gives the API. | +| Feature documents stay under specs/NNN-name/ | Pass | This file is `specs/006-loop-link/plan.md`. | +| Releases use release-please with per-package paths | Pass | S1 adds `packages/loop_link` to the config and manifest, and adds it to `exclude-paths` of the root entry. | +| A constitution amendment requires a pull request and maintainer acceptance | Not applicable | The plan does not change the constitution. | + +## Design + +### Types and data + +All modules are in `packages/loop_link/src/loop_link/`. Names are checked free +(`git grep -n -w` on 2026-11-06 found no use of `loop_link`, `LinkError`, +`ViewerConnection` or `FakeViewer` outside `specs/`). + +**Errors** (`errors.py`). Each type has its own class and a text that says what +to do (FR-008). + +```python +class LoopLinkError(Exception): ... +class NoViewerError(LoopLinkError): ... # no instance file, no listener +class TokenError(LoopLinkError): ... # no token, or the viewer refused it +class BusyError(LoopLinkError): ... # another program holds the data connection +class MissingFeatureError(LoopLinkError): # viewer too old + feature: str +class InvalidInputError(LoopLinkError): ... +class ObjectTooLargeError(LoopLinkError): + object_id: str; size: int; limit: int +class ViewerClosedError(LoopLinkError): ... # the viewer closed in the middle of a call +class ViewerRefusedError(LoopLinkError): + refusals: list[Refusal] +class MissingExtraError(LoopLinkError): # an optional extra is not installed + extra: str +@dataclass(frozen=True) +class Refusal: object_id: str; code: str; message: str # code as in protocol "error" +``` + +**Codec** (`protocol.py`, no Qt, no pyvista): + +```python +PROTOCOL_VERSION = {"major": 1, "minor": 14} +MAX_FRAME_BYTES = 256 * 1024 * 1024 +MAX_HEADER_BYTES = 1024 * 1024 +MAX_OBJECT_BYTES = 2 * 1024 ** 3 +F32_LIMIT = 4000.0 +@dataclass(frozen=True) +class Frame: + header: dict[str, Any] + buffers: dict[str, np.ndarray] # by name, shape as in the header, little-endian +def encode_frame(header: dict, buffers: Sequence[tuple[str, np.ndarray]] = ()) -> bytes +def decode_frame(data: bytes) -> Frame +def decode_header(data: bytes) -> dict +class ProtocolError(LoopLinkError): ... +``` + +`encode_frame` adds `version` and `buffers`, writes `json.dumps(..., +separators=(",", ":"), allow_nan=False)`, and refuses a header over +`MAX_HEADER_BYTES` or a frame over `MAX_FRAME_BYTES` (`ObjectTooLargeError` is +raised by the caller, which knows the id). The dtype names are `f32`, `f64`, +`u32`, `i32`, `u8`. `decode_frame` checks that `4 + header_len + sum(buffer +sizes) == len(data)`, and gives `ProtocolError` otherwise. + +**Objects** (`objects.py`). All are frozen dataclasses. The arrays are numpy +arrays after `__post_init__` (`np.asarray`, no copy when possible). A shape error +gives `InvalidInputError` with the field name. `properties` has one value per +vertex (or per node for a `BlockModel`). `cell_properties` has one value per cell. +A value is a 1-D numpy array, or `Categorical`. + +```python +ArrayLike = Union[np.ndarray, Sequence[float]] +@dataclass(frozen=True) +class Categorical: # protocol data type "referenced" + codes: np.ndarray # (n,) integers >= 0, below 2**32 + names: Sequence[str] # name of value i is names[i] + colours: Optional[Sequence[Sequence[int]]] = None # RGBA per name; default DEFAULT_CATEGORY_COLOURS cycle +DEFAULT_CATEGORY_COLOURS: tuple[tuple[int, int, int, int], ...] # 10 colours of the tab10 set + +@dataclass(frozen=True) +class Points: + vertices: ArrayLike # (n, 3) world coordinates + properties: Mapping[str, Property] = field(default_factory=dict) +@dataclass(frozen=True) +class Vectors: # a Points object with a property group + vertices: ArrayLike # (n, 3) + orientation: Optional[tuple[ArrayLike, ArrayLike]] = None # (dip_direction, dip) degrees, each (n,) + lineation: Optional[tuple[ArrayLike, ArrayLike]] = None # (trend, plunge) degrees, each (n,) + properties: Mapping[str, Property] = field(default_factory=dict) + @classmethod + def from_directions(cls, vertices, directions, *, kind: str, properties=None) -> "Vectors" + # kind: "normal" (plane normal -> orientation) or "lineation" (line direction) +@dataclass(frozen=True) +class Lines: + vertices: ArrayLike # (n, 3) + segments: ArrayLike # (m, 2) vertex indices + properties: ...; cell_properties: ... # cell = segment +@dataclass(frozen=True) +class Surface: + vertices: ArrayLike; triangles: ArrayLike # (n, 3), (m, 3) + properties: ...; cell_properties: ... +@dataclass(frozen=True) +class BlockModel: # the "structured grid" + origin: ArrayLike # (3,) world coordinates of the lowest corner + cell_sizes: ArrayLike # (3,) > 0 + cells: ArrayLike # (3,) integers >= 1: nx, ny, nz + properties: ... # nodes, (nx+1)(ny+1)(nz+1), x fastest + cell_properties: ... # cells, nx*ny*nz, x fastest +@dataclass(frozen=True) +class TetraMesh: + vertices: ArrayLike; tetrahedra: ArrayLike # (n, 3), (m, 4) + properties: ...; cell_properties: ... +@dataclass(frozen=True) +class Drillhole: + collar: ArrayLike # (3,) world coordinates + survey: ArrayLike # (k, 3): depth, azimuth degrees, dip degrees (positive down) + intervals: ArrayLike # (j, 2): from, to + end_of_hole: Optional[float] = None + properties: ... # one value per survey station (association "vertex") + interval_properties: ... # one value per interval (association "interval") +SceneObject = Union[Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole] +``` + +Validity rules (all checked in `__post_init__`, so a bad object never reaches the +codec): the vertex array has finite values; index arrays are integers with +`0 <= i < n`; an array property has the length of its association; a 2-D property +is refused; `cells` and `cell_sizes` are positive; a `Points` or `Vectors` object +has no `cell_properties`. + +**Property to protocol data type** (`encode.py`, function `_data_array`): + +| Python value | `data_type` | Buffer | +|---|---|---| +| `float32` | `float` | `f32` | +| other float dtype | `float` | `f64` | +| `bool` | `boolean` | `u8` | +| integer dtype, all values in the `i32` range | `integer` | `i32` | +| integer dtype with a value outside `i32` | refused | `InvalidInputError` | +| numpy string dtype (`U`, `S`) | `text` | `u8` bytes plus `u32` offsets | +| `Categorical` | `referenced` | `u32`, with `value_map` (`id`, `name`, `colour`) | +| `object` dtype, other | refused | `InvalidInputError` that names the accepted dtypes | + +The data array `id` and `name` are the property name. The buffer name is +`data/`, and the offsets buffer name is `data//offsets`. A name that +is not unique after this rule gives `InvalidInputError`. + +**Vector conversion** (`orientation.py`). The directions use x east, y north, z up. +The result is in degrees. + +```python +def normals_to_orientation(normals: ArrayLike) -> tuple[np.ndarray, np.ndarray] + # n = normalise(normal); if n_z < 0: n = -n + # dip = degrees(arccos(clip(n_z, -1, 1))); dip_direction = degrees(arctan2(n_x, n_y)) % 360 + # n_x = n_y = 0: dip_direction = 0.0 +def directions_to_lineation(directions: ArrayLike) -> tuple[np.ndarray, np.ndarray] + # d = normalise(direction); if d_z > 0: d = -d (a lineation is an axis) + # plunge = degrees(arcsin(clip(-d_z, -1, 1))); trend = degrees(arctan2(d_x, d_y)) % 360 + # d_x = d_y = 0: trend = 0.0 +def orientation_to_normals(dip_direction, dip) -> np.ndarray # helper for S5 (fetch); inverse of the first +def lineation_to_directions(trend, plunge) -> np.ndarray # inverse of the second +``` + +A vector of length 0 or with a NaN gives `InvalidInputError`. The upward normal +of a plane that dips to azimuth `a` with dip `d` is +`(sin d sin a, sin d cos a, cos d)`. The unit tests use this as the independent +expected result. `Vectors.from_directions(kind="normal")` uses the first function. +`kind="lineation"` uses the second. Another `kind` gives `InvalidInputError`. + +**Property groups of `Vectors`**: group id and name `orientation` (role +`orientation`, members `dip_direction` and `dip`) or `lineation` (role `lineation`, +members `trend` and `plunge`). The data arrays are `float` `f64`, association +`vertex`, ids `orientation/dip_direction`, `orientation/dip`, +`lineation/trend`, `lineation/plunge`. A `Vectors` object with both groups has both. + +**Connection state** (`viewer.py`): + +```python +@dataclass(frozen=True) +class InventoryEntry: id: str; object_type: str; revision: int +``` + +### Functions and public API + +`loop_link/__init__.py` exports: `Viewer`, `PushResult`, `push_objects`, +`Points`, `Vectors`, `Lines`, `Surface`, `BlockModel`, `TetraMesh`, `Drillhole`, +`Categorical`, `InventoryEntry`, `Refusal`, all error classes, and `__version__`. +`import loop_link` imports numpy and the standard library only (SC-005). A test +checks that `sys.modules` has no key that starts with `PyQt`, `PySide`, `qgis`, +`pyvista`, `pandas`, `loop_common` or `LoopStructural` after the import. + +```python +# viewer.py +class Viewer: + def __init__(self, *, port: Optional[int] = None, token: Optional[str] = None, + host: str = "127.0.0.1", crs: str = "", origin: Sequence[float] = (0.0, 0.0, 0.0), + settings_dir: Optional[Path] = None, timeout: float = 5.0, + heartbeat_interval: float = 5.0) -> None + def connect(self) -> "Viewer" + def send(self, obj: Any, *, id: str, name: Optional[str] = None, + parent: Optional[str] = None) -> int + def send_group(self, id: str, name: str, parent: Optional[str] = None) -> int + def remove(self, id: str) -> None + def clear(self) -> None + def inventory(self) -> list[InventoryEntry] + def flush(self, settle: float = 0.5, *, raise_on_refusal: bool = True) -> list[Refusal] + def release_data(self) -> None + def close(self) -> None + @property + def revisions(self) -> Mapping[str, int] # read-only copy + @property + def scene_origin(self) -> tuple[float, float, float] + @property + def scene_crs(self) -> str + @property + def connected(self) -> bool + def __enter__(self) -> "Viewer"; def __exit__(self, *exc) -> None +``` + +Behaviour of each method: + +- `send` connects when it is not connected (`connect`). `obj` is a `SceneObject`, + or an object that an adapter accepts (see S2). `id` is required. `name` defaults + to `id`. It returns the new revision. The revision of an id is `previous + 1`, + where `previous` is the larger of the revision that this `Viewer` sent and the + revision in the inventory of the last `hello` answer; for a new id it is 1 + (FR-003, scenario 2). It raises `InvalidInputError` for an unaccepted input + (the text names the accepted inputs of FR-010), `ObjectTooLargeError` before any + byte goes out, and `ViewerClosedError` when the socket closes. + After each frame the method drains the socket without a wait and adds each + `error` frame that has an `object` to an internal list of `Refusal`. +- `flush` waits up to `settle` seconds for late `error` frames, returns the list + (and clears it), and raises `ViewerRefusedError` when the list is not empty and + `raise_on_refusal` is true. +- `release_data` closes the data connection and stops the keepalive thread. It + keeps `revisions`. A later `send` opens a new data connection (FR-014). If the + viewer answers `busy`, `send` and `connect` raise `BusyError` ("Another program + holds the data connection of the viewer. It can call `release_data()`."). The + objects of the other program do not change, because the viewer closes only the + second connection. +- `close` calls `release_data`. `Viewer` is not thread safe. One thread uses it at + a time. A lock inside protects the socket against the keepalive thread only. +- `clear` sends `scene.clear`, `remove` sends `scene.remove`; both drop the + revisions of the removed ids. `inventory` returns the entries of the last + inventory. It does not poll the viewer (the viewer sends the inventory after + `hello` only). + +```python +# discovery.py +@dataclass(frozen=True) +class ViewerAddress: host: str; port: int; token: str +DEFAULT_PORT = 47615 +def settings_dir() -> Path # %APPDATA%\geoviewer on Windows, else ~/.geoviewer +def find_viewer(*, port: Optional[int] = None, token: Optional[str] = None, + host: str = "127.0.0.1", settings: Optional[Path] = None, + timeout: float = 0.5) -> ViewerAddress +``` + +`find_viewer` order for the token: the argument, the environment variable +`GEOVIEWER_TOKEN` (empty is not a token), the field `token` of `link.json` in the +settings folder. No token gives `TokenError` ("Set GEOVIEWER_TOKEN, or save a +token in the link popup of the viewer."). Order for the port: the argument; else +the instance files `instances/.json` (fields `version`, `pid`, `port`, +`kind`, `started`, `focused`): drop the files whose port does not accept a TCP +connection within `timeout`, prefer `kind == "window"` over `"headless"`, then +the largest `focused`; damaged files are ignored; else `DEFAULT_PORT` if it +accepts a connection; else `NoViewerError`. The library never starts a viewer +(scenario 3). A wrong token gives HTTP 401 at the handshake, and the transport +maps it to `TokenError`. + +```python +# _websocket.py (port of loopstructural/main/geoviewer/websocket_client.py in the plugin) +class WebSocketClient: + @classmethod + def connect(cls, host: str, port: int, *, token: str = "", timeout: float = 5.0, + path: str = "/") -> "WebSocketClient" + def send_binary(self, data: bytes) -> None + def receive(self, timeout: float) -> Optional[bytes] + def close(self) -> None +class WebSocketError(LoopLinkError); class WebSocketClosed(WebSocketError) +MAX_INCOMING_BYTES = MAX_FRAME_BYTES + MAX_HEADER_BYTES # the plugin limit of 16 MiB is too small for S5 +``` + +The port changes three things: the base class of the errors, the incoming limit +(above), and `connect` maps an HTTP 401 to `TokenError` and a refused connection to +`NoViewerError`. The handshake header is `Authorization: Bearer `. Data +clients use the path `/`. The path `/tool` is for S4. + +```python +# encode.py +def encode_object(obj: SceneObject, *, id: str, name: str, parent: Optional[str], + revision: int, origin: Sequence[float]) -> bytes +def hello_frame(crs: str, origin: Sequence[float], version: str) -> bytes +def heartbeat_frame(seq: int) -> bytes +def remove_frame(id: str) -> bytes +def clear_frame() -> bytes +def group_frame(id: str, name: str, parent: Optional[str], revision: int) -> bytes +``` + +`encode_object` gives the `scene.upsert` header with these fields: `type`, `id`, +`object_type`, `name`, `parent`, `revision`, `edit` (`[]`), `replaces` (`null`), +`geometry`, `params`, `data`, `property_groups`, `drape` (`null`), `style` (`{}`). +Mapping of the types: + +| Class | `object_type` | `geometry` roles and buffers | `params` | +|---|---|---|---| +| `Points`, `Vectors` | `Points` | `vertices` | none | +| `Lines` | `Curve` | `vertices`, `segments` (`u32`) | none | +| `Surface` | `Surface` | `vertices`, `triangles` (`u32`) | none | +| `TetraMesh` | `TetraMesh` | `vertices`, `tetrahedra` (`u32`) | none | +| `BlockModel` | `BlockModel` | none | `origin` (3, minus scene origin), `cell_sizes` (3), `cells` (3) as JSON lists | +| `Drillhole` | `Drillhole` | `collar` (3, minus origin), `survey` `f64` (k, 3), `intervals` `f64` (j, 2) | `end_of_hole` as `[value]` when set | + +Coordinate buffers (`vertices`, `collar`) are `f32` when the largest absolute +value after the origin shift is at most `F32_LIMIT`, and `f64` otherwise. Before +the frame goes out, `encode_object` sums the declared bytes of all buffers (and +`entries * 8 + name bytes` for each `value_map`). A sum over `MAX_OBJECT_BYTES` +or a frame over `MAX_FRAME_BYTES` raises `ObjectTooLargeError` (edge case, FR-008). + +### Messages and saved data + +No new message and no saved data. The library writes: `hello` (`application` +`{"name": "loop_link", "version": __version__}`, `crs`, `origin`), `heartbeat` +(`seq`), `scene.upsert`, `scene.remove`, `scene.clear`. It reads: `hello`, +`scene.inventory`, `error`, `heartbeat`. Example `hello` header: + +```json +{"type":"hello","application":{"name":"loop_link","version":"0.1.0"}, + "crs":"EPSG:28350","origin":[500000.0,7000000.0,0.0], + "version":{"major":1,"minor":14},"buffers":[]} +``` + +A reply with an unknown type is ignored. An `error` with the code +`unsupported_version` raises `MissingFeatureError("protocol 1.x")` with the +`supported` field in the text. + +### Behaviour + +**Connect** (`Viewer.connect`): `find_viewer`; `WebSocketClient.connect`; send +`hello`; read until both `hello` and `scene.inventory` arrived (timeout `timeout`, +then `ViewerClosedError`). An `error` frame with the code `busy` raises +`BusyError` and closes the socket. Another `error` frame raises `ViewerRefusedError` +with a `Refusal` that has an empty `object_id`. The scene origin is the `origin` +of the viewer `hello`; when it is `null` the origin that the caller proposed +applies. The library keeps both `scene_origin` and `scene_crs`. When the scene +origin differs from the proposed origin, all frames use the scene origin +(the viewer rule; the client converts). The revisions of the inventory fill +the internal table `max(local, inventory)`. + +**Keepalive**: the viewer closes a data connection that sends no frame for 15 s +(spec 003 of geoviewer). After `connect`, a daemon thread `loop-link-heartbeat` +tries every `heartbeat_interval` seconds (default 5.0) to take the socket lock +without a wait. When it gets the lock and the last send was more than +`heartbeat_interval` ago, it sends `heartbeat_frame(seq)`. When the lock is not +free, a send is running, which counts as traffic. A socket error stops the thread +and marks the connection closed. `release_data` and `close` stop the thread +(`threading.Event`) and join it with a timeout of `2 * heartbeat_interval`. + +**Plugin API** (S3, `push.py`): + +```python +@dataclass +class PushResult: + sent: int = 0 + removed: int = 0 + refused: list[Refusal] = field(default_factory=list) + skipped: list[tuple[str, str]] = field(default_factory=list) # (id, reason) + cancelled: bool = False + def summary(self) -> str +def push_objects(viewer: Viewer, objects: Iterable[tuple[str, Any]], *, + replace_prefix: Optional[str] = None, + progress: Optional[Callable[[str], None]] = None, + cancel: Optional[threading.Event] = None) -> PushResult +``` + +`objects` yields `(id, object)` pairs. The function connects the viewer when it +is not connected. For each pair it checks `cancel` (stop with `cancelled=True`), +calls `progress("Sending ...")`, and calls `viewer.send(obj, id=id)`. An +`InvalidInputError` or `ObjectTooLargeError` for one object goes to `skipped` and +the push goes on (the plugin rule). A `ViewerClosedError` or `BusyError` stops the +push and goes up. After the loop, when `replace_prefix` is set, it sends +`viewer.remove(id)` for each id of the inventory that starts with the prefix and +was not sent in this call. Then it calls `viewer.flush(raise_on_refusal=False)` and +puts the refusals in `refused`. The function uses no Qt and no module state. It +calls `progress` on the thread that calls it. The plugin runs it on a worker thread. + +### Stages and rollback + +| Stage | Files and behaviour | Acceptance check | Rollback target and compatibility check | +|---|---|---|---| +| S1 | New package: codec, errors, WebSocket, discovery, objects, orientation, encode, `Viewer`, fake viewer; repository registration (ROADMAP, release-please, CI, Ruff, uv). Inputs: the dataclasses and numpy arrays only. | `uv run --package loop-link pytest packages/loop_link/tests`; `ruff check LoopStructural packages`; root `pytest`; SC-001, SC-004 (with the variable), SC-005, SC-006; manual check M1 | Revert the stage: the files are new, and the root files change by added lines only. The root `pytest` result is the same as before. | +| S2 | `adapters/` for pyvista, LoopStructural, pandas; `Viewer.send` calls `adapters.convert`. | The same commands. Adapter tests (pyvista, LoopStructural, pandas extras installed in the test environment). | Revert S2. S1 still sends the dataclasses. | +| S3 | `push.py` and its tests; frame comparison with the plugin frames; the slow-viewer and cancel tests. | The same commands; SC-004 frames of the plugin. | Revert S3. S1 and S2 stay. | +| S4, S5 | Not planned here (OP6, OP7). | | | + +## Test strategy + +- **Unit and regression tests** (`packages/loop_link/tests/`): + - `test_protocol.py`: `encode_frame` then `decode_frame` for every dtype; a frame + with a wrong size, a header over 1 MiB, a frame over 256 MiB each give + `ProtocolError`/`ObjectTooLargeError`. Expected values come from the frames + in `fixtures/protocol/expected/*.json` of the geoviewer repository when + `LOOP_LINK_GEOVIEWER_FIXTURES` is set (OP8), else from literal bytes in the test. + - `test_orientation.py`: a table of planes (`dip_direction`, `dip`) turned into + normals by the formula `(sin d sin a, sin d cos a, cos d)` written in the test, + then converted back with the library; the same for lineations; the edge cases + (vertical plane, horizontal plane, vertical line, zero vector, NaN). + Tolerance `1e-9` degrees. + - `test_objects.py`: each validity rule, each of the seven types, the property + type table (all rows), the refusal of an `object` array and of a 2-D property. + - `test_encode.py`: header fields and buffers of the seven types; `f32` below + 4000 from the origin and `f64` above; the origin shift in `f64`; + `ObjectTooLargeError` for 2 GiB + 1 declared bytes (a test that builds the + header sizes with `numpy.broadcast_to`, with no real allocation). + - `test_discovery.py`: token order (argument, environment, `link.json`), a + damaged `link.json`, instance files (window before headless, focus order, dead + port dropped, damaged file ignored), no viewer, default port. + - `test_viewer.py` (with `FakeViewer`): story 1 scenarios 1 to 7 (the two-program + scenario uses two `Viewer` objects on one fake viewer), revision rules, `busy` + with the first program unchanged, `release_data` then send from the second + program, the keepalive (the fake closes after `heartbeat_timeout=0.6`, the + viewer sends with `heartbeat_interval=0.1` and stays up for 2 s), the viewer + that closes in the middle of a send gives `ViewerClosedError`, the wrong token + gives `TokenError`, the `unsupported_version` error. + - `test_import.py`: SC-005 (`sys.modules` check in a subprocess run with + `python -I -c`). +- **Integration and compatibility tests**: `test_fixtures.py` reads every + `*.bin` in `LOOP_LINK_GEOVIEWER_FIXTURES/` (`fixtures/protocol/python` of the + geoviewer repository) with `FakeViewer.accept_frame`, and fails for a frame + that the fake refuses (SC-004). It also encodes the plugin test objects and + compares header and buffers to the `.bin` frames. It skips with a reason when + the variable is missing (OP8). No public API of `GeologicalModel` is touched. +- **Round-trip tests**: not applicable in this plan (fetch is S5). The fake viewer + keeps the received frames, so `test_viewer.py` compares the stored arrays with + the input. +- **Backend coverage**: the library has one backend (stdlib sockets). S2 tests need + pyvista, `loop_common` and pandas; each test file uses `pytest.importorskip`, + and the CI `tests` extra installs them (`tests = ["pytest", "pyvista", + "loop-common", "pandas"]`), so they do not skip in CI. +- **Cross-language fixtures**: the frames of `fixtures/protocol/python` and + `expected` (OP8). The Rust side is in the geoviewer repository. +- **Grid and display checks**: `BlockModel` node and cell counts and order. The + test builds an analytic property `f = x + 10 y + 100 z` on the nodes of a + 3 x 4 x 5 grid in x-fastest order, sends it, and reads the stored buffer from + the fake viewer. The LoopStructural adapter test repeats this with a + `loop_common.geometry.StructuredGrid` (x varies fastest in this class, so no + reorder is made; the test proves it). +- **Performance check**: SC-001. `tests/test_performance.py` is marked + `@pytest.mark.slow` (the marker is registered in `packages/loop_link/pyproject.toml`; + the default run does not exclude it). It sends a + `BlockModel` of 100 x 100 x 100 cells with one `float32` cell property to the + fake viewer, and asserts that the inventory has the object in under 5 s. Manual + check M1 repeats it with the real headless viewer + (`geoviewer-headless --port 0`) and records the time. +- **Merge gates**: `pytest` and `ruff check LoopStructural packages` must pass. The + package gate is `uv run --package loop-link pytest packages/loop_link/tests` + (the line of `.github/workflows/packages.yml`, which S1 extends). The root + `pytest` does not run the package tests. Black: `black --check packages/loop_link`. + +## Project structure + +### New package `packages/loop_link` + +**Responsibility**: the Python client of the geoviewer protocol: codec, transport, +discovery, object model, `Viewer`, adapters, plugin push API, fake viewer. + +**Files** (S1 unless the text says S2 or S3): + +- `packages/loop_link/pyproject.toml` - Create. Name `loop-link`, version `0.1.0`, + `requires-python = ">=3.10"`, `dependencies = ["numpy"]`, extras `pyvista`, + `loopstructural = ["loop-common"]`, `pandas`, `tests`, setuptools + `where = ["src"]`, `include = ["loop_link", "loop_link.*"]`, pytest marker + `slow`. +- `packages/loop_link/README.md` - Create. Install, the token, a 10-line example. +- `packages/loop_link/LICENSE` - Create. Copy of `packages/loop_common/LICENSE`. +- `packages/loop_link/ruff.toml` - Create. `extend = "../../pyproject.toml"` and + `target-version = "py310"`. +- `packages/loop_link/src/loop_link/__init__.py` - Create. Exports (see "Functions + and public API"). +- `packages/loop_link/src/loop_link/errors.py` - Create. The error classes and `Refusal`. +- `packages/loop_link/src/loop_link/protocol.py` - Create. The codec. +- `packages/loop_link/src/loop_link/_websocket.py` - Create. Port of the plugin client. +- `packages/loop_link/src/loop_link/discovery.py` - Create. `find_viewer`, `settings_dir`. +- `packages/loop_link/src/loop_link/objects.py` - Create. The dataclasses and `Categorical`. +- `packages/loop_link/src/loop_link/orientation.py` - Create. The four conversion functions. +- `packages/loop_link/src/loop_link/encode.py` - Create. `encode_object` and the frame builders. +- `packages/loop_link/src/loop_link/viewer.py` - Create. `Viewer`, `InventoryEntry`, keepalive thread. +- `packages/loop_link/src/loop_link/testing/__init__.py` - Create. Exports `FakeViewer`. +- `packages/loop_link/src/loop_link/testing/fake_viewer.py` - Create (FR-015). + `FakeViewer(token="secret", crs="EPSG:28350", origin=(0.0, 0.0, 0.0), kind="window", + heartbeat_timeout=15.0, reply_errors=None, read_delay=0.0)` with `.port`, + `.objects` (id to `StoredObject(header, buffers)`), `.received` (list of + `Frame`), `.inventory()`, `.write_instance_file(settings: Path) -> Path`, + `.accept_frame(data: bytes) -> list[Frame]` (apply one frame, return the + replies), `.close()`, and the context manager. It listens on `127.0.0.1` port 0 + in a thread; it accepts any number of connections; it checks the bearer token + (HTTP 401 if wrong); it answers `hello` with `hello` and `scene.inventory`; it + gives `busy` to a second data connection and closes it; it closes a data + connection that sends no frame for `heartbeat_timeout` seconds; it applies the + protocol rules of `scene.upsert` (roles, index range, array length, finite + coordinates, object size limit) and answers `invalid_object` with `object` when + a rule fails; `reply_errors` maps an id to a forced error text. It accepts the + path `/tool` and answers every tool message with `unknown_message` in S1. +- `packages/loop_link/src/loop_link/adapters/__init__.py` - Create (S2). + `convert(obj, **hints) -> SceneObject`: return `obj` when it is a `SceneObject`; + else choose the adapter by `type(obj).__module__` prefix (`pyvista`, + `loop_common`), without an import of the extra; else `InvalidInputError` with + the text "Accepted inputs: loop_link objects; pyvista meshes and grids; + numpy arrays in a loop_link object; LoopStructural Surface and StructuredGrid; + pandas tables for drillholes (use loop_link.adapters.drillholes_from_pandas)". +- `packages/loop_link/src/loop_link/adapters/pyvista.py` - Create (S2). + `from_pyvista(mesh, *, kind: Optional[str] = None, vectors: Optional[str] = None, vectors_kind: str = "normal") -> SceneObject`. + Rules: `PolyData` with only vertex cells gives `Points` (`Vectors` when `vectors` + names a point array of shape (n, 3), converted by `Vectors.from_directions`); + `PolyData` with `lines` gives `Lines`; `PolyData` with faces gives `Surface` + (`triangulate()` first when a face is not a triangle); + `ImageData` or a `RectilinearGrid` with equal spacing on each axis gives + `BlockModel`; `UnstructuredGrid` whose cells are all type `VTK_TETRA` (10) gives + `TetraMesh`; any other mesh, and `kind="Drillhole"`, give `InvalidInputError` + (OP3, OP9). `point_data` goes to `properties`, `cell_data` to `cell_properties`; + a 2-D array is refused. `kind` overrides the rule for `Points` versus `Vectors` + only. +- `packages/loop_link/src/loop_link/adapters/loopstructural.py` - Create (S2). + `from_loopstructural(obj) -> SceneObject`: `loop_common.geometry.Surface` gives + `Surface(vertices, triangles, properties=obj.properties or {}, cell_properties=obj.cell_properties or {})`; + `loop_common.geometry.StructuredGrid` gives `BlockModel(origin=obj.origin, + cell_sizes=obj.step_vector, cells=obj.nsteps_cells, properties=obj.properties, + cell_properties=obj.cell_properties)`. The adapter finds the class with + `sys.modules.get("loop_common.geometry")`, so it never imports the module when the + caller has no LoopStructural object. +- `packages/loop_link/src/loop_link/adapters/pandas.py` - Create (S2). + `drillholes_from_pandas(collar, survey, logs=None, *, hole_id="hole_id", x="x", y="y", z="z", depth="depth", azimuth="azimuth", dip="dip", from_="from", to="to", dip_positive_down=True) -> dict[str, Drillhole]`. + It groups each table by `hole_id`; the result maps a hole id to a `Drillhole`; + extra columns of `logs` become `interval_properties` (a text column of strings + becomes a numpy `U` array; any other `object` column gives `InvalidInputError`); + `dip_positive_down=False` changes the sign of `dip` (the `geoh5` convention). A + hole in `survey` or `logs` that is not in `collar` gives `InvalidInputError`. + `Viewer.send` accepts one `Drillhole`. The user sends the dict with a loop of + `viewer.send(hole, id=hole_id)`. +- `packages/loop_link/src/loop_link/push.py` - Create (S3). `PushResult`, `push_objects`. +- `packages/loop_link/tests/conftest.py` - Create. Fixture `fake_viewer` (starts + `FakeViewer`, writes `GEOVIEWER_TOKEN` with `monkeypatch`, sets `settings_dir` to + `tmp_path`), and the helper `geoviewer_fixtures()` (OP8). +- `packages/loop_link/tests/test_protocol.py`, `test_orientation.py`, `test_objects.py`, + `test_encode.py`, `test_discovery.py`, `test_viewer.py`, `test_import.py`, + `test_performance.py`, `test_fixtures.py` - Create (S1). +- `packages/loop_link/tests/test_adapter_pyvista.py`, + `test_adapter_loopstructural.py`, `test_adapter_pandas.py` - Create (S2). +- `packages/loop_link/tests/test_push.py` - Create (S3). Scenarios of story 5: + `push_objects` frames equal `Viewer.send` frames; `replace_prefix` removes old + ids; one bad object goes to `skipped`; `cancel` stops after the current object; + a `FakeViewer(read_delay=0.05)` push in a worker thread leaves the main thread + free (the main thread counts to 20 ticks of 0.01 s while the push runs). +- `packages/loop_link/tests/manual_checks.md` - Create (S1). M1: performance with the + real headless viewer; M2: a send of the seven types, then a visual check in the + window viewer. + +### Repository registration (S1) + +**Responsibility**: FR-016, SC-006, and the repository settings for the new package. + +**Files**: + +- `ROADMAP.md` - Change. Add a stage entry for `packages/loop_link` after the + last entry of "Stage sequence" (the task reads the end of the list first and + uses the next stage number), and add one status log entry. Both entries name + `loop_link` (SC-006, first entry). +- `.release-please-config.json` - Change. Add `"packages/loop_link": {"release-type": + "python", "component": "loop-link"}` and add `"packages/loop_link"` to `exclude-paths` of + the root entry (SC-006, second entry; the fix of 2026-09-27 keeps sub-package + commits out of the root bump). +- `.release-please-manifest.json` - Change. Add `"packages/loop_link": "0.1.0"`. +- `pyproject.toml` - Change. Add `loop-link = { workspace = true }` to + `[tool.uv.sources]` (or the `exclude` entry of OP5); add + `"packages/loop_link/tests/*" = ["D", "ANN"]` to the Ruff `per-file-ignores`. No + entry for `packages/loop_link/src`. +- `uv.lock` - Change. Run `uv lock` (OP5). +- `.github/workflows/packages.yml` - Change. Add `{ name: loop-link, dir: loop_link }` + to the matrix, and add the condition `if: ${{ !(matrix.package.name == 'loop-link' && + startsWith(matrix.python-version, '3.9')) }}` to the two steps that install and test. + The paths filter `packages/**` already covers the new folder. + +## Requirement coverage + +| Requirement | Design and files | Verification | Gap | +|---|---|---|---| +| FR-001 | "Functions and public API", `discovery.py` | `test_discovery.py`; story 1 scenario 1 in `test_viewer.py` | None | +| FR-002 | `objects.py`, `encode.py` (type table) | `test_encode.py`, `test_viewer.py` (seven types) | None | +| FR-003 | `Viewer.send` revision rule | `test_viewer.py` scenario 2 | None | +| FR-004 | Select by id and index | none in this plan | OP7 (S5) | +| FR-005 | Read selection and poll | none in this plan | OP7 (S5) | +| FR-006 | Fetch | none in this plan | OP7 (S5) | +| FR-007 | `import loop_link` has no Qt; `push.py` has no Qt | `test_import.py` | None | +| FR-008 | `errors.py`; each edge case maps to one class (token: `TokenError`; no viewer: `NoViewerError`; too large: `ObjectTooLargeError`; closed: `ViewerClosedError`; bad property: `InvalidInputError`; busy: `BusyError`; older viewer: `MissingFeatureError`; origin differs: handled by conversion, not an error) | `test_viewer.py`, `test_encode.py`, `test_discovery.py` | None for S1 to S3. The older-viewer case for select and read is S5 (OP7). | +| FR-009 | `push.py` (`push_objects`, `PushResult`) | `test_push.py` | None. The plugin change is in the plugin repository. | +| FR-010 | `adapters/` | `test_adapter_*.py` | OP3 (pyvista to Drillhole); OP9 (non-regular grids) | +| FR-011 | `orientation.py`, `Vectors` | `test_orientation.py`; story 1 scenario 6 | None | +| FR-012 | One codec in `protocol.py` and `encode.py`; core imports numpy and the standard library only; adapters are extras | `test_import.py`; `test_protocol.py` | None | +| FR-013 | Missing feature detect for 066 | none in this plan | OP7 (S5) | +| FR-014 | `Viewer.release_data`, `BusyError`, keepalive thread. The tool connection part (select, read, fetch, filter, colour while busy) is S4 and S5. | `test_viewer.py` scenario 7 (send part) | OP6, OP7 for the tool connection part | +| FR-015 | `testing/fake_viewer.py` | `test_viewer.py`, `test_fixtures.py` | None | +| FR-016 | "Repository registration" | `git grep -n loop_link ROADMAP.md .release-please-config.json` gives 2 entries or more | None | +| FR-017 | `pyproject.toml` (`>=3.10`), `ruff.toml` (py310) | `ruff check` and CI on 3.10 to 3.12 | OP4 (QGIS Python), OP5 (uv) | +| FR-018 | Filter | none in this plan | OP6 (S4) | +| FR-019 | Filter wait and cancel | none in this plan | OP6 (S4) | +| FR-020 | Colour | none in this plan | OP6 (S4) | +| FR-021 | Colour in send | none in this plan | OP1, OP6 (S4) | +| SC-001 | `test_performance.py`; M1 | assert under 5 s | None | +| SC-002 | Round trip | none in this plan | OP7 (S5) | +| SC-003 | Selection in one message | none in this plan | OP7 (S5) | +| SC-004 | `test_fixtures.py` | frames of `fixtures/protocol/python`; the geoviewer tests read the frames of the library in the geoviewer repository | OP8 | +| SC-005 | `test_import.py`; CI matrix | `sys.modules` check | None | +| SC-006 | "Repository registration" | `git grep` of two files | None | +| SC-007 | Reply time of colour and filter | none in this plan | OP6 (S4) | +| Story 1 scenarios 1 to 8 | `Viewer`, `discovery.py`, `test_viewer.py`, `test_import.py` | as above | None | +| Story 5 scenarios 1 and 2 | `push.py`, `test_push.py` | frame comparison with plugin frames (OP8); worker thread test | OP8 | + +## Handover + +Other specs and repositories use these contracts. + +- **Python API**: the names in "Functions and public API", `loop_link.objects`, + `loop_link.errors`, and `loop_link.testing.FakeViewer`. The `0.x` version means + a breaking change can come in a minor version, and release-please records it. +- **Plugin repository**: `push_objects(viewer, objects, replace_prefix=, progress=, + cancel=)` replaces `GeoViewerLink.push`. `PushResult.summary()` keeps the text of + the old `PushResult.summary()`. The plugin builds `objects` as `(id, SceneObject)` + pairs and runs the call on its worker thread. The plugin owns the change and the + removal of the old client (FR-009). +- **S4** (filter and colour) uses: `WebSocketClient.connect(..., path="/tool")`; + the tool messages `commands.list`, `command.run`, `command.result`, + `request.error`, `command.cancel`, `command.progress`; the commands + `filter.edit` (input `{"object": id, "edit": {"kind": "set_range", "array": + name, "min": text, "max": text, "keep_nan": bool}}`; kinds `add`, `set_range`, + `set_values` with `values: list[u32]`, `set_on`, `set_exclude`, `remove`, + `cancel`), `colour.set_active` (`id`, `array`), `colour.set_map` (`id`, `name`), + `colour.set_range` (`id`, `min` text, `max` text), `colour.clear_range` (`id`), + `colour.set_scale` (`object`, `scale` `linear` or `log`), `object.set_colour` + (`id`, `colour` RGB or `null`). The viewer answers `{"status":"done"}` or + `{"status":"refused","text":...}`; the result has no count of passing elements, so + the "count of elements that pass" of story 6 needs a check in the S4 plan. +- **S5** (select, read selection, fetch) uses the 066 messages `selection.set`, + `selection.get`, `selection.result`, `object.fetch`, `object.header`, + `object.part`, `object.end` of protocol 1.15. `MAX_INCOMING_BYTES` already + allows the 64 MiB parts. The helpers `orientation_to_normals` and + `lineation_to_directions` are for the fetch of vectors. +- **geoviewer repository**: the frames that `encode_object` writes must pass the + geoviewer protocol tests. The coordinator copies the frames to + `fixtures/protocol/python` by hand when the fixtures change (OP8). +- **Shared files**: `ROADMAP.md`, `pyproject.toml`, `uv.lock`, + `.release-please-config.json`, `.release-please-manifest.json`, + `.github/workflows/packages.yml`. Specs 003 and 005 also work in these + repository areas. S1 changes only the lines named above. A merge conflict in + `uv.lock` is solved by `uv lock` again. + +## Complexity tracking + +None. Every applicable constitution check passes. The py310 target of the package +is a decision that FR-017 asks of this plan, and it does not break a project rule +(the repository target py39 stays for all other code). diff --git a/specs/006-loop-link/run-state.json b/specs/006-loop-link/run-state.json new file mode 100644 index 000000000..61b4c0e54 --- /dev/null +++ b/specs/006-loop-link/run-state.json @@ -0,0 +1,10 @@ +{ + "spec": "006-loop-link", + "worktree": "C:/Users/lachl/dev/LoopStructural-006", + "branch": "feat/006-loop-link", + "review_mode": "wave", + "start_commit": "d4157a3e37f945f8b1570cc9b2eef9278c1ae086", + "waves": [], + "runs": {}, + "findings": { "found": 0, "rejected": 0, "dropped": 0, "fixed": 0, "open_minor": [] } +} diff --git a/specs/006-loop-link/spec.md b/specs/006-loop-link/spec.md new file mode 100644 index 000000000..d90f16273 --- /dev/null +++ b/specs/006-loop-link/spec.md @@ -0,0 +1,436 @@ +# Feature spec: loop_link, a Python link to geoviewer + +**Feature**: `006-loop-link` | **Created**: 2026-11-05 | **Status**: Draft + +**Input**: A Python library, `packages/loop_link`, that sends 3D objects with +their properties to geoviewer, receives them back, and shares the selection +(the highlight) between Python and the viewer. The LoopStructural QGIS plugin +uses the same library. + + + +## User scenarios and tests + +### User story 1: Send objects to the viewer (priority: P1) + +A Python user sends points, vectors, lines, surfaces, structured grids, tetra +meshes and drillholes to a running viewer. Each object keeps its properties. +The user sees the objects in the viewer. + +**Why this priority**: All other stories need objects in the viewer. + +**Independent test**: Start the fake viewer (FR-015). Send one object of each +type with one property. Read the inventory of the fake viewer and check the +ids and types. A manual check with the real headless viewer repeats the test +(CI cannot run it). + +**Acceptance scenarios**: + +1. **Given** a running viewer and a saved token, **when** the user sends an + object, **then** the library finds the viewer with no port or token entry + and the object is in the viewer scene. +2. **Given** an object that was sent, **when** the user sends the same id + again, **then** the viewer replaces the object and the revision increases. +3. **Given** no running viewer, **when** the user sends an object, **then** the + library gives a clear error and does not start a viewer. +4. **Given** an object with properties on its points or cells, **when** it is + sent, **then** the viewer shows the same property names and values. +5. **Given** one object of each of the seven types, **when** the user sends + them, **then** the viewer holds seven objects with the correct types. +6. **Given** an x, y, z direction vector, **when** it is sent, **then** the + viewer holds the equal orientation or lineation. +7. **Given** one Python program that holds the data connection of a viewer, + **when** a second program tries to send, **then** the second program gets + the library error `busy` and the objects of the first program do not + change. The second program can still select, read, fetch, filter and + colour on the tool connection. + **Given** the first program releases the data connection, **when** the + second program sends, **then** the viewer accepts it and keeps the objects + of the first program. +8. **Given** an install of the core only, **when** the library is imported, + **then** it needs neither Qt nor the optional extras. + +### User story 2: Select a cell from Python (priority: P1) + +The user sends an object id and one or more cell indices. The viewer selects +them. The selection is the same selection that a user makes in the viewer. + +**Why this priority**: It is the main way to link a result in Python to the +picture. + +**Independent test**: Send a structured grid. Select cell 12 from Python. +Read the selection of the viewer and check that it holds cell 12. + +**Acceptance scenarios**: + +1. **Given** an object in the viewer, **when** Python selects cell indices, + **then** the viewer outlines those cells. +2. **Given** an index that is outside the object, **when** Python selects it, + **then** the library gets an error and the selection does not change. +3. **Given** an object that was replaced after Python read its indices, + **when** Python selects with the old revision, **then** the viewer refuses + the selection. +4. **Given** a viewer without the selection messages, **when** Python selects, + **then** the library gives an error that names the missing feature. + +### User story 3: Read the selection in Python (priority: P1) + +The user selects objects or cells in the viewer. Python reads the selection on +request. The library can also poll the selection and call a function when it +changes. The viewer does not push a selection change. + +**Why this priority**: It closes the loop from the picture to Python. + +**Independent test**: A second client selects a cell in the viewer. Python +reads the selection and gets the object id and the cell index. + +**Acceptance scenarios**: + +1. **Given** a selection in the viewer, **when** Python asks for it, **then** + Python gets each selected object id, the kind of location (cell, vertex) + and the indices. +2. **Given** a polling callback in Python with a set interval, **when** the user + changes the selection in the viewer, **then** Python calls the callback + once for the change, at the next poll. +3. **Given** a selection of more than 100,000 cells, **when** Python asks for + it, **then** the answer arrives as an array and not as text. + +### User story 4: Receive objects from the viewer (priority: P2) + +Python gets an object from the viewer as the same kind of object that it can +send: geometry and properties. The objects include those that the viewer made +by an import, for example a drillhole import or a file. + +**Why this priority**: It makes the link two-way. It needs a new viewer +feature, so it comes after send and select. + +**Independent test**: Send an object, fetch it back, and compare geometry and +properties with the original. + +**Acceptance scenarios**: + +1. **Given** an object in the viewer, **when** Python fetches it, **then** + Python gets the geometry and all properties with the same values. +2. **Given** an object type, **when** Python sends it and fetches it back, + **then** the result equals the original (a round trip). +3. **Given** a request for an id that does not exist, **when** Python fetches + it, **then** the library gives a clear error. + +### User story 5: The QGIS plugin uses the library (priority: P2) + +The plugin sends model objects and reads the selection through this library. +The library does not need Qt. The plugin runs it on a worker thread. + +**Why this priority**: It removes the second copy of the client code. + +**Independent test**: Push the same model with the library and with the old +client to the fake viewer, and compare the messages that the fake viewer +receives. + +**Acceptance scenarios**: + +1. **Given** the plugin, **when** it pushes a model, **then** it calls only the + library and the objects in the viewer are the same as with the old client. +2. **Given** a slow viewer, **when** the plugin sends, **then** the QGIS user + interface does not block. + +### User story 6: Filter objects from Python (priority: P2) + +The user sets a data filter on an object in the viewer from Python. The filter +is the filter of the viewer (spec 023 of geoviewer): a range filter on a number +property, or a value filter on a category property. The viewer shows only the +elements that pass. + +**Why this priority**: The user finds a part of a model, for example the cells +with a grade above 0.5, without a manual step in the viewer. + +**Independent test**: Send a grid with a number property. Set a range filter. +Check that the viewer reports the filter as on, with the count of elements +that pass. Use the fake viewer in CI. + +**Acceptance scenarios**: + +1. **Given** an object with a number property, **when** the user sets a range + (minimum, maximum, and keep or drop NaN), **then** the viewer shows only the + elements in the range. +2. **Given** an object with a category property, **when** the user sets the + values to show, with or without the exclude switch, **then** the viewer + shows only the matching elements. +3. **Given** a filter, **when** the user turns it off or removes it, **then** + the viewer shows all elements again. The data does not change. +4. **Given** a property that does not exist, or a property of a type that has + no filter (text, or one value for the whole object), **when** the user sets a + filter, **then** the library gives a clear error. +5. **Given** a filter that takes time to build, **when** the user sets it, + **then** the call can wait for the end, or return at once, and the user can + cancel the build. +6. **Given** a new revision of an object, **when** the user sends it, **then** + the filters of the object stay and apply to the new data. + +### User story 7: Set the colouring of an object from Python (priority: P2) + +The user chooses which property colours an object, and sets the colour map, +the range and the scale. The user can also set the plain colour of an object. +These are the colour settings of the viewer (geoviewer specs 018 and 047). + +**Why this priority**: A script can show a result at once with a useful colour, +for example a grade with a log scale, with no manual step in the viewer. + +**Independent test**: Send a grid with a number property. Set the property as +the colouring, the map `coolwarm`, a range and the log scale. Check the +settings with the fake viewer. + +**Acceptance scenarios**: + +1. **Given** an object with properties, **when** the user chooses a property + to colour by, **then** the viewer colours the object by that property. The + user can also choose no property. +2. **Given** a number property, **when** the user sets a colour map by name, + **then** the viewer uses that map. The names are those of the viewer. +3. **Given** a number property, **when** the user sets a range, or clears it, + **then** the viewer uses that range, or the range of the data. +4. **Given** a number property, **when** the user chooses the linear or the log + scale, **then** the viewer uses that scale. +5. **Given** a property that is a category or a boolean, **when** the user sets + a map, a range or a scale, **then** the library gives a clear error, + because these properties have none. +6. **Given** a map name that the viewer does not know, **when** the user sets + it, **then** the library gives a clear error that lists the names. +7. **Given** the user sends an object with the colour settings, **when** the + viewer receives it, **then** the settings apply to the object. The + settings go in the send, or in a follow-up call that the library sends at + once [NEEDS CLARIFICATION: the plan checks if the send message can carry + the settings; the user-visible result is the same]. + +### Edge cases + +- The token is missing or wrong. The library says how to set the token. +- The viewer is an older version without the selection messages. Sending works. + Select and read give a clear error that names the missing feature. +- An object is larger than one frame (256 MiB) or larger than the object limit + (2 GiB). The library refuses it with an error before it sends. +- The origin of the viewer is different from the origin of the client. +- The viewer closes in the middle of a send. +- The user has a property that the protocol cannot hold (for example an + object array). +- Two Python programs connect to the same viewer. Only one holds the data + connection (story 1, scenario 7). +- A filter or a colour command changes only how the viewer shows an object. + It is not an edit, and it has no owner check or undo step. + +## Requirements + +### Functional requirements + +- **FR-001**: The library must find a running viewer and its token with no + manual entry. +- **FR-002**: The library must send these object types with their properties: + points, vectors, lines, surfaces, structured grids, tetra meshes and + drillholes. +- **FR-003**: The library must keep the revision of each object it sent. It + must replace an object that has the same id, and the revision must + increase. +- **FR-004**: The library must select objects and cells in the viewer by + object id and index. +- **FR-005**: The library must read the selection of the viewer on request, + and must offer a poll that calls a function when the selection changes. The + user sets the poll interval (default 0.5 s). The poll runs only when the + user starts it. +- **FR-006**: The library must fetch any object of the scene from the viewer, + also an object that another client or an import made, and return the + geometry and the properties. A fetch does not change the scene. Coordinates + are returned as world coordinates. Each array keeps the data type that the + viewer holds. +- **FR-014**: The library must hold at most one data connection for each + program. When the viewer refuses a second data client with `busy`, the + library must give the error `busy` and must not change the objects of the + first program. A program without the data connection can still select, read + the selection, fetch, filter and colour. The library must let a program + release the data connection and keep the tool connection, so that another + program can send. The viewer keeps the objects that the first program sent. +- **FR-007**: The library must not need Qt. A plugin adapter handles threads. +- **FR-008**: The library must give a library error for each failure in the + edge cases. Each failure has its own error type, with a text that says what + to do. +- **FR-009**: The library must keep an API that the plugin can use in place of + its own client. The plugin change, and the removal of the old client, are + done in the plugin repository after the library ships. +- **FR-010**: The library must accept these inputs: pyvista meshes and grids + and plain numpy arrays with a dict of properties, for all seven object + types; LoopStructural objects for structured grids and surfaces; pandas + tables (collar, survey, logs) for drillholes only. Any other combination + gives a clear error that names the accepted inputs. +- **FR-011**: The library must accept a vector as an orientation (dip + direction and dip), a lineation (trend and plunge) or an x, y, z direction. + It converts an x, y, z direction before it sends. + +- **FR-012**: The library must own the only Python codec of the protocol. The + core needs numpy and a WebSocket client only. The adapters for pyvista, + LoopStructural and pandas are optional extras. +- **FR-016**: The change must add the package to `ROADMAP.md` and to the + per-package release configuration. +- **FR-017**: The package must support Python 3.10 and later. This is the + minimum of the package. It is higher than the lint target of the repo + (py39), so the plan must set the target for this package. +- **FR-018**: The library must set, turn on or off, and remove a range filter + and a value filter (with the exclude switch) on an object in the viewer, by + the name of a property. The library uses the existing filter command of the + viewer. This needs no change in the viewer. +- **FR-019**: The library must let the user wait for a filter build to end, or + continue at once, and must cancel a filter build on request. +- **FR-020**: The library must set the property that colours an object, the + colour map by name, the range (and clear it), and the linear or log scale. + It must also set the plain colour of an object. The library uses the + existing colour commands of the viewer. It must get the list of map names from + the viewer (the command list of the viewer), not from a fixed list in the + library. This needs a small change in the viewer (geoviewer spec 066, FR-009). +- **FR-021**: The library must let the user give the colour settings in the + call that sends an object. The library applies them with the send or with a + follow-up call, so that the user needs one call. +- **FR-015**: The package must include a fake viewer: a test server that + speaks the protocol. CI uses it, because CI cannot run the real viewer. +- **FR-013**: Stories 2 to 4 need geoviewer spec 066 in the viewer. The + library must detect a viewer without it, and must give a library error that + names the missing feature for these calls. + +### Protocol and data + +- **Messages**: uses the messages of protocol 1.14 for send, and the existing + commands for filter and colour. Uses the selection messages and the fetch + message of geoviewer spec 066: set the selection, read the selection, and + fetch an object. The exact names and the protocol version come from that + spec. The viewer sends no selection change message. +- **Objects and data**: object types and data types of the viewer. A "vector" + is a Points object with an orientation or lineation property group. An + x, y, z direction is converted to dip direction and dip, or to trend and + plunge, before it is sent. A fetch returns the angles that the viewer + stores, and a helper converts them to x, y, z (assumption, 2026-11-05: the + viewer keeps the angles, so the round trip of an x, y, z input is equal + only up to the conversion). + +### Key entities + +- **Object**: one item in the viewer scene, with an id, a type, geometry and + properties. +- **Property**: a named array of values on the points, cells or the whole + object. +- **Viewer connection**: the link from Python to one viewer. It has a tool + connection and, when the program sends objects, the one data connection. It + holds the revision of each object it sent. +- **Library error**: an error type of the library with a text. The types + include no viewer, wrong token, `busy`, missing feature, invalid input and + object too large. +- **Selection**: a list of object ids, and for each object a location kind and + an array of indices. + +## Success criteria + +- **SC-001**: A grid of 1,000,000 cells with one float property is sent and + appears in the viewer inventory in less than 5 s on the same computer. +- **SC-002**: A send followed by a fetch gives geometry and properties that + are equal for all seven object types, within a relative tolerance of 1e-6 + (the precision of `f32`). +- **SC-003**: A selection of 100,000 cells goes from Python to the viewer in + one message. +- **SC-004**: The fake viewer reads all 100% of the frames in the geoviewer + folder `fixtures/protocol/python`, and the library writes frames that the + geoviewer tests accept. +- **SC-005**: The package installs and imports on Python 3.10 and later, with + 0 imports of Qt in the core. +- **SC-006**: `ROADMAP.md` and the release configuration list `loop_link` + (2 entries). +- **SC-007**: A colour command, or a filter command, gets its reply from the + fake viewer in less than 250 ms for an object with 1,000,000 cells. The time + of a filter build is not counted. + +## Out of scope + +- The geoviewer changes (geoviewer spec 066). They are a separate spec. +- Several programs that send objects at the same time. The viewer allows one + data client. +- A separate highlight that is not the user selection. +- Starting or installing the viewer. +- Removing the old client from the plugin repository. +- A push message for selection changes. +- A custom colour map (own colours or stops). Only the named maps of the + viewer. +- Reading the colour settings back from the viewer. +- Reading the filters back from the viewer. The viewer has no command for it. +- Filters on drillhole log sets (the filter of geoviewer spec 049). +- Editing an object that another client owns. +- A link to the browser (wasm) build of the viewer. The browser cannot run + the server that the library connects to. A later spec can add a notebook + widget or a Python-side server. + +## Clarifications + +- 2026-11-05: Q: Where does the library live? A: `packages/loop_link`. +- 2026-11-05: Q: Highlight and selection: same or separate? A: Same. The + highlight is the user selection. +- 2026-11-05: Q: Which object types? A: Points, vectors, lines, surfaces, + structured grids, tetra meshes and drillholes, all with properties. Send and + receive. +- 2026-11-05: Q: Name of the spec? A: `006-loop-link`. +- 2026-11-05: Q: What is a vector? A: Both: orientation or lineation, and an + x, y, z direction (converted before sending). +- 2026-11-05: Q: Which Python inputs? A: pyvista meshes and grids, + LoopStructural objects, plain numpy arrays, pandas drillhole tables. +- 2026-11-05: Q: Who owns the Python protocol codec? A: `loop_link` alone. It + is tested against the geoviewer frames in `fixtures/protocol/python`. The + plugin drops its copy. +- 2026-11-05: Q: How are the adapters packaged? A: Optional extras (pyvista, + LoopStructural, pandas). The core needs numpy and a WebSocket client only. +- 2026-11-05: Q: Viewer side of stories 2 to 4? A: A new geoviewer spec for + protocol 1.15. Stories 2 to 4 wait for it. Stories 1 and 5 work with 1.14. +- 2026-11-05: Q: Speed of a send? A: Under 5 s for 1,000,000 cells. +- 2026-11-05: Q: Which objects can be fetched? A: Any object of the scene. +- 2026-11-05: Q: Selection events? A: Polling only. The viewer pushes no + selection message; the library polls. This lowers the viewer work to + `selection.set` and `selection.get`. +- 2026-11-05: Q: Many clients? A: Each client owns its ids. The selection is + shared. (Replaced in the second review: the viewer allows one data client.) +- 2026-11-05 (second review): Q: Can two programs send at once? A: No. The + viewer gives `busy` to a second data client (geoviewer spec 003). The second + program can use the tool connection. +- 2026-11-06: Q: Should the viewer allow several data clients? A: No. Keep one + data client. The library lets a program release the data connection so that + another program can send (FR-014). +- 2026-11-05 (review): Q: Tolerance of a round trip? A: Relative 1e-6. +- 2026-11-05 (review): Q: Data type of a fetch? A: The type the viewer holds; + coordinates are world coordinates. +- 2026-11-05 (review): Q: Which inputs for which types? A: pyvista and numpy + for all seven; LoopStructural for grids and surfaces; pandas for drillholes. +- 2026-11-05 (review): Q: Poll interval? A: Set by the user, default 0.5 s. +- 2026-11-05 (review): Q: Minimum Python? A: 3.10 and later (FR-017). +- 2026-11-05 (review): Q: ROADMAP and release entries? A: Required in this + spec (FR-016). +- 2026-11-05 (review): Q: Geoviewer spec not yet written? A: Keep the + dependency as text. The plan covers stories 1 and 5 first. Fill in the + number when the geoviewer spec exists. +- 2026-11-05: Q: Can Python also send filters? A: Yes. The viewer already has + the command `filter.edit` on the tool connection (range, values, exclude, + on or off, remove, cancel). Story 6, FR-018 and FR-019. No viewer change. +- 2026-11-05: Q: Can Python change the colour map? A: Yes. The viewer has the + commands `colour.set_active`, `colour.set_map`, `colour.set_range`, + `colour.clear_range`, `colour.set_scale` and `object.set_colour`. See story 7 + and the requirements for colour. The viewer has three named maps (`viridis`, `grey`, + `coolwarm`). A custom map is not in scope. +- 2026-11-05: Q: Where do the colour map names come from? A: From the viewer. + Today the input `name` of `colour.set_map` is free text and the command list + does not give the names, so spec 066 adds the names to the schema. +- 2026-11-05: Q: Old plugin client? A: Removed in the plugin repository after + the library ships, not in this spec. diff --git a/specs/006-loop-link/tasks.md b/specs/006-loop-link/tasks.md new file mode 100644 index 000000000..c38cb8cbc --- /dev/null +++ b/specs/006-loop-link/tasks.md @@ -0,0 +1,323 @@ +# Tasks: loop_link, a Python link to geoviewer + +**Feature**: `006-loop-link` | **Plan**: [plan.md](plan.md) + + + +## Orchestrator notes + +- Run this file with the spec-orchestrator skill. It has the rules for the + worktree, the sub agents, the checks and the commits. +- Waves: 13. Tiers: [S] = simple model, [M] = standard model. +- Do not start a task with "Blocked by". + +## Phase 1: Setup + +- [ ] T001 [Setup] [M] Create the package skeleton `packages/loop_link`. + - Files: `packages/loop_link/pyproject.toml`, `packages/loop_link/README.md`, `packages/loop_link/LICENSE`, `packages/loop_link/ruff.toml`, `packages/loop_link/src/loop_link/__init__.py` + - Needs: none + - Wave: 1 + - Done when: `python -c "import tomllib,pathlib;tomllib.loads(pathlib.Path('packages/loop_link/pyproject.toml').read_text())"` passes and `ruff check packages/loop_link` passes. + - Context: Model on `packages/loop_common/pyproject.toml` (setuptools, `where = ["src"]`). `[project]` name `loop-link`, version `0.1.0`, `requires-python = ">=3.10"`, `dependencies = ["numpy"]`. Extras: `pyvista = ["pyvista"]`, `loopstructural = ["loop-common"]`, `pandas = ["pandas"]`, `tests = ["pytest", "pyvista", "loop-common", "pandas"]`. Setuptools `include = ["loop_link", "loop_link.*"]`. Register the pytest marker `slow` under `[tool.pytest.ini_options]`. `ruff.toml` has exactly `extend = "../../pyproject.toml"` and `target-version = "py310"`. `LICENSE` is a copy of `packages/loop_common/LICENSE`. `README.md`: install, the token (`GEOVIEWER_TOKEN` or the saved token of the viewer), a 10-line example with `Viewer`, `Points`. `__init__.py` holds a docstring and `__version__ = "0.1.0"` only (T023 adds the exports). + +- [ ] T002 [P] [Setup] [S] Register `loop_link` for release-please. + - Files: `.release-please-config.json`, `.release-please-manifest.json` + - Needs: none + - Wave: 1 + - Done when: `python -c "import json;c=json.load(open('.release-please-config.json'));m=json.load(open('.release-please-manifest.json'));assert 'packages/loop_link' in c['packages'] and 'packages/loop_link' in c['packages']['.']['exclude-paths'] and m['packages/loop_link']=='0.1.0'"` passes. + - Context: In the config, add the key `"packages/loop_link"` under `packages` with the value `{"release-type": "python", "component": "loop-link"}`. Also append `"packages/loop_link"` to the `exclude-paths` list of the `"."` entry (keep the list sorted by path as it is). In the manifest, add `"packages/loop_link": "0.1.0"`. Keep the 2-space JSON indent. + +- [ ] T003 [Setup] [M] Add `loop-link` to the uv workspace and to the Ruff config (OP5). + - Files: `pyproject.toml`, `uv.lock` + - Needs: T001 + - Wave: 2 + - Done when: `uv lock --check` passes and `ruff check LoopStructural packages` passes. + - Context: In root `pyproject.toml` add `loop-link = { workspace = true }` to `[tool.uv.sources]`. Add `"packages/loop_link/tests/*" = ["D", "ANN"]` to `[tool.ruff.lint.per-file-ignores]` next to the other `packages/*/tests/*` lines. Do NOT add an entry for `packages/loop_link/src`. Run `uv lock`. OP5 fallback: if uv refuses the workspace, or the lock drops Python 3.9 for the other members, remove the source line, add `"packages/loop_link"` to `[tool.uv.workspace] exclude`, run `uv lock` again, and write one line in the commit message that says the fallback was used. Do not change another dependency in `uv.lock`. + +- [ ] T004 [P] [Setup] [S] Add `loop-link` to the package CI matrix. + - Files: `.github/workflows/packages.yml` + - Needs: none + - Wave: 1 + - Done when: `python -c "import yaml;yaml.safe_load(open('.github/workflows/packages.yml'))"` passes and `git grep -n "loop-link" .github/workflows/packages.yml` shows 3 lines. + - Context: In `jobs.packages-test.strategy.matrix.package` add the line `- { name: loop-link, dir: loop_link }`. Add this line to the two steps that install and test (`Install package with test extras` and `pytest`): `if: ${{ !(matrix.package.name == 'loop-link' && startsWith(matrix.python-version, '3.9')) }}`. The package needs Python 3.10 or later. Do not change another step. + +- [ ] T005 [P] [Setup] [M] Add `loop_link` to `ROADMAP.md`. + - Files: `ROADMAP.md` + - Needs: none + - Wave: 1 + - Done when: `git grep -n -c loop_link ROADMAP.md` gives 2 or more. + - Context: Read the end of the section "Stage sequence" and the end of "Status log" first. Add one unchecked stage entry for `packages/loop_link` (spec `specs/006-loop-link`) with the next free stage number: the Python link to geoviewer (send, adapters, plugin push API; select, fetch, filter and colour wait for geoviewer spec 066). Add one status log entry dated 2026-11-06 that says the spec and plan exist and the package is new. Use the style of the neighbouring entries. Principle: `ROADMAP.md` owns the stages (constitution). + +## Phase 2: Foundation (blocks all user stories) + +- [ ] T006 [Found] [S] Errors module with its test. + - Files: `packages/loop_link/src/loop_link/errors.py`, `packages/loop_link/tests/test_errors.py` + - Needs: T001 + - Wave: 2 + - Done when: write the test first and see it fail; then `uv run --package loop-link pytest packages/loop_link/tests/test_errors.py` passes. + - Context: Classes, all subclasses of `LoopLinkError(Exception)`: `NoViewerError`, `TokenError`, `BusyError`, `InvalidInputError`, `ViewerClosedError`, plus `MissingFeatureError(feature: str)` (attribute `feature`; text names the feature), `ObjectTooLargeError(object_id: str, size: int, limit: int)` (attributes with the same names; text has all three), `ViewerRefusedError(refusals: list[Refusal])` (attribute `refusals`), `MissingExtraError(extra: str)` (attribute `extra`; text says `pip install loop-link[]`). `@dataclass(frozen=True) class Refusal: object_id: str; code: str; message: str`. Each default text says what to do (FR-008). Test: each class is a `LoopLinkError`; the attributes are kept; `str(error)` is not empty; `Refusal` is hashable. + +- [ ] T007 [P] [Found] [M] Test: the codec in `test_protocol.py`. + - Files: `packages/loop_link/tests/test_protocol.py` + - Needs: T006 + - Wave: 3 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_protocol.py` fails with ImportError of `loop_link.protocol`, then passes after T008. + - Context: API under test: `encode_frame(header: dict, buffers: Sequence[tuple[str, np.ndarray]] = ()) -> bytes`, `decode_frame(data: bytes) -> Frame` (`Frame(header: dict, buffers: dict[str, np.ndarray])`), `decode_header(data: bytes) -> dict`, `ProtocolError`, constants `MAX_FRAME_BYTES=256*1024*1024`, `MAX_HEADER_BYTES=1024*1024`, `PROTOCOL_VERSION={"major":1,"minor":14}`. Frame layout: `[u32 LE header_len][JSON header][buffers]`, little-endian. `encode_frame` adds `version` and `buffers` (`[{"name","dtype","shape"}]`). dtype names `f32 f64 u32 i32 u8`. Tests: a round trip for each of the 5 dtypes with shape (2,3); a zero-element array is valid; a frame whose length differs from `4+header_len+sum(sizes)` gives `ProtocolError`; a header over 1 MiB gives `ProtocolError` on encode; a frame under 4 bytes gives `ProtocolError`; NaN in the header gives an error (`allow_nan=False`); an unsupported dtype (`complex128`) gives `ProtocolError`. A byte-literal test: `encode_frame({"type":"heartbeat","seq":1})` starts with `struct.pack(' (dip_direction, dip)`, `directions_to_lineation(directions) -> (trend, plunge)`, `orientation_to_normals(dip_direction, dip) -> (n,3)`, `lineation_to_directions(trend, plunge) -> (n,3)`. Degrees. x east, y north, z up. Independent expected value in the test: a plane that dips to azimuth `a` with dip `d` has the upward normal `(sin d sin a, sin d cos a, cos d)` (write this formula in the test, not by calling the library). Tests: 12 planes (`a` in 0, 45, 90, 135, 180, 270, 359; `d` in 10, 45, 80) convert to `(a, d)` within 1e-9 degrees; a downward normal gives the same result as its upward twin; a vertical plane (n_z=0) gives dip 90; a horizontal plane gives dip 0 and dip direction 0.0; lineations: `(trend, plunge)` to direction `(cos p sin t, cos p cos t, -sin p)` and back; a direction with z>0 flips (axis); vertical line gives trend 0.0 and plunge 90; the inverse functions round trip; a zero vector and a NaN vector each raise `InvalidInputError`. Dip direction and trend are in [0, 360). + +- [ ] T010 [Found] [M] Implement `orientation.py`. + - Files: `packages/loop_link/src/loop_link/orientation.py` + - Needs: T009 + - Wave: 4 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_orientation.py` passes. + - Context: Signatures take array-like (n,3) or (3,) input and return numpy arrays: `normals_to_orientation(normals) -> tuple[np.ndarray, np.ndarray]`; `directions_to_lineation(directions) -> tuple[np.ndarray, np.ndarray]`; `orientation_to_normals(dip_direction, dip) -> np.ndarray`; `lineation_to_directions(trend, plunge) -> np.ndarray`. Rules: `n = v/|v|`; for normals, if `n_z < 0` use `-n`; `dip = degrees(arccos(clip(n_z,-1,1)))`; `dip_direction = degrees(arctan2(n_x, n_y)) % 360`; if `n_x == n_y == 0` the dip direction is 0.0. For lineations, if `d_z > 0` use `-d`; `plunge = degrees(arcsin(clip(-d_z,-1,1)))`; `trend = degrees(arctan2(d_x, d_y)) % 360`; if `d_x == d_y == 0` the trend is 0.0. Inverse of normals: `(sin d sin a, sin d cos a, cos d)`. Inverse of lineations: `(cos p sin t, cos p cos t, -sin p)`. A zero-length or non-finite vector raises `InvalidInputError` (from `loop_link.errors`). + +- [ ] T011 [P] [Found] [M] Test: the object model in `test_objects.py`. + - Files: `packages/loop_link/tests/test_objects.py` + - Needs: T006 + - Wave: 3 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_objects.py` fails with ImportError of `loop_link.objects`, then passes after T012. + - Context: Frozen dataclasses in `loop_link.objects`: `Points(vertices, properties={})`; `Vectors(vertices, orientation=None, lineation=None, properties={})` with `Vectors.from_directions(vertices, directions, *, kind, properties=None)` (`kind` is `"normal"` or `"lineation"`, else `InvalidInputError`); `Lines(vertices, segments, properties, cell_properties)`; `Surface(vertices, triangles, properties, cell_properties)`; `BlockModel(origin, cell_sizes, cells, properties, cell_properties)`; `TetraMesh(vertices, tetrahedra, properties, cell_properties)`; `Drillhole(collar, survey, intervals, end_of_hole=None, properties, interval_properties)`; `Categorical(codes, names, colours=None)`; `DEFAULT_CATEGORY_COLOURS` (10 RGBA tuples). Rules to test (each raises `InvalidInputError` that names the field): vertices not (n,3) or not finite; an index array with a negative value or a value >= n; a property of the wrong length (vertex: n; cell: m; `BlockModel` nodes: (nx+1)(ny+1)(nz+1), cells: nx*ny*nz, x fastest; Drillhole `properties`: k stations, `interval_properties`: j rows); a 2-D property; `cell_sizes` <= 0 or `cells` < 1 or non-integer; `Points` or `Vectors` with `cell_properties` (they have no such field, so the test checks `TypeError`); `Categorical` with a code >= `len(names)`. Valid input of all 7 types is accepted and arrays become numpy arrays. + +- [ ] T012 [Found] [M] Implement `objects.py`. + - Files: `packages/loop_link/src/loop_link/objects.py` + - Needs: T011, T010 + - Wave: 5 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_objects.py` passes. + - Context: Implement the dataclasses that T011 names, with the same fields and defaults (`field(default_factory=dict)` for the mappings). Each class does its checks in `__post_init__` and converts arrays with `object.__setattr__(self, name, np.asarray(...))` (frozen). Vertex and index arrays: `float64` and integer. `Vectors.from_directions(..., kind="normal")` calls `normals_to_orientation` and `kind="lineation"` calls `directions_to_lineation` (both in `loop_link.orientation`) and stores the pair in `orientation` or `lineation`. `Vectors` accepts both `orientation` and `lineation`. Add `SceneObject = Union[Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole]`, `Property = Union[np.ndarray, Sequence, Categorical]` and `ArrayLike`. `DEFAULT_CATEGORY_COLOURS` = the 10 tab10 colours as RGBA with alpha 255: (31,119,180), (255,127,14), (44,160,44), (214,39,40), (148,103,189), (140,86,75), (227,119,194), (127,127,127), (188,189,34), (23,190,207). A category without a given colour uses the colour at index `i % 10`. Do not import pyvista, pandas or Qt. + +- [ ] T013 [Found] [M] Test: object encoding in `test_encode.py`. + - Files: `packages/loop_link/tests/test_encode.py` + - Needs: T012, T008 + - Wave: 6 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_encode.py` fails with ImportError of `loop_link.encode`, then passes after T014. + - Context: Under test: `encode_object(obj, *, id, name, parent, revision, origin) -> bytes` (decode with `decode_frame`), `hello_frame(crs, origin, version)`, `heartbeat_frame(seq)`, `remove_frame(id)`, `clear_frame()`, `group_frame(id, name, parent, revision)`. Header fields of `scene.upsert`: `type id object_type name parent revision edit([]) replaces(null) geometry params data property_groups drape(null) style({})`. Type map: Points and Vectors -> `Points` (geometry `vertices`); Lines -> `Curve` (`vertices`, `segments` u32); Surface -> `Surface` (`vertices`, `triangles` u32); TetraMesh -> `TetraMesh` (`vertices`, `tetrahedra` u32); BlockModel -> `BlockModel` (no geometry; `params` `origin`, `cell_sizes`, `cells` as JSON lists, origin minus scene origin); Drillhole -> `Drillhole` (`collar` minus origin, `survey` f64 (k,3), `intervals` f64 (j,2); `params.end_of_hole=[v]` only when set). Vertices are f32 when max abs after the shift <= 4000, else f64; the shift is done in f64 (test with origin 500000, 7000000, 0 and vertices near it: f32 buffer, values equal to input minus origin within 1e-3). Data types: float32 -> `float`/f32; float64 -> `float`/f64; bool -> `boolean`/u8; int64 inside i32 -> `integer`/i32; int64 outside i32 -> `InvalidInputError`; `U` strings -> `text` (u8 bytes + u32 offsets named `data//offsets`, header field `offsets`); `Categorical` -> `referenced`/u32 with `value_map` entries `{"id","name","colour"}`; `object` dtype -> `InvalidInputError`; two properties that give the same buffer name -> `InvalidInputError`. Data array: `id`=`name`=property name, `buffer`=`data/`, `association` `vertex` or `cell` (Drillhole `interval_properties`: `interval`). Vectors: `property_groups` `[{"id":"orientation","name":"orientation","role":"orientation","members":[{"role":"dip_direction","data":"orientation/dip_direction"},{"role":"dip","data":"orientation/dip"}]}]` and the f64 vertex arrays; lineation uses `lineation`, `trend`, `plunge`. Too large: build an object whose declared size exceeds 2 GiB with `np.broadcast_to` views (no real allocation) and expect `ObjectTooLargeError` with the id, size and limit. + +- [ ] T014 [Found] [M] Implement `encode.py`. + - Files: `packages/loop_link/src/loop_link/encode.py` + - Needs: T013 + - Wave: 7 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_encode.py` passes. + - Context: Public: `encode_object`, `hello_frame(crs: str, origin: Sequence[float], version: str) -> bytes` (header `type hello`, `application {"name":"loop_link","version":version}`, `crs`, `origin` as floats), `heartbeat_frame(seq: int)`, `remove_frame(id)` (`scene.remove`), `clear_frame()` (`scene.clear`), `group_frame(id, name, parent, revision)` (a `scene.upsert` of `object_type` `Group`). Private `_data_array(name, value, association) -> (desc: dict, buffers: list[tuple[str, np.ndarray]])` follows the type table in the test of T013. Use `loop_link.protocol.encode_frame`. Before building the frame, sum the declared bytes of all buffers plus `entries*8+name bytes` of each `value_map`; if the sum is over `MAX_OBJECT_BYTES`, or the frame is over `MAX_FRAME_BYTES` (catch `ProtocolError` from `encode_frame`), raise `ObjectTooLargeError(id, size, limit)`. Use broadcast views without copying when computing sizes (read `array.size * itemsize`, not `tobytes`). Coordinates: reject NaN and infinity with `InvalidInputError` (objects already check this). Principle IV: subtract the origin in float64 before any cast to f32. + +- [ ] T015 [Found] [M] Port the stdlib WebSocket client to `_websocket.py`. + - Files: `packages/loop_link/src/loop_link/_websocket.py` + - Needs: T008 + - Wave: 5 + - Done when: `ruff check packages/loop_link` passes and `uv run --package loop-link python -c "import loop_link._websocket"` passes. Behaviour is tested through `test_viewer.py` (T020). + - Context: Read and port `C:\Users\lachl\dev\plugin_loopstructural-geoviewer\loopstructural\main\geoviewer\websocket_client.py` (245 lines, standard library only). Keep the class `WebSocketClient` with `connect(cls, host, port, *, token="", timeout=5.0, path="/")`, `send_binary(data: bytes)`, `receive(timeout: float) -> Optional[bytes]`, `close()`. Changes: (1) `WebSocketError(LoopLinkError)` and `WebSocketClosed(WebSocketError)`; (2) `MAX_INCOMING_BYTES = MAX_FRAME_BYTES + MAX_HEADER_BYTES` (import from `loop_link.protocol`; the old limit was 16 MiB); (3) in `connect`, an HTTP 401 answer raises `TokenError`, and a refused or timed-out TCP connection raises `NoViewerError` (both from `loop_link.errors`); (4) add numpy-style docstrings and type hints to every public method (Ruff `D` and `ANN` apply to new files); (5) the handshake header stays `Authorization: Bearer `. Keep the thread rule: not thread safe. + +- [ ] T016 [P] [Found] [M] Test: discovery in `test_discovery.py`. + - Files: `packages/loop_link/tests/test_discovery.py` + - Needs: T006 + - Wave: 3 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_discovery.py` fails with ImportError, then passes after T017. + - Context: Under test: `find_viewer(*, port=None, token=None, host="127.0.0.1", settings=None, timeout=0.5) -> ViewerAddress` (frozen dataclass `host, port, token`), `settings_dir() -> Path` (`%APPDATA%\geoviewer` on Windows, else `~/.geoviewer`), `DEFAULT_PORT = 47615`. Use `tmp_path` as `settings` and `monkeypatch` for `GEOVIEWER_TOKEN`. Token order: the argument; then `GEOVIEWER_TOKEN` (an empty value is not a token); then the field `token` of `settings/link.json`; none gives `TokenError`; a damaged `link.json` (not JSON) gives `TokenError`. Instance files: `settings/instances/.json` with fields `version (1), pid, port, kind ("window" or "headless"), started, focused` (ms). To make a live port, open a `socket` listener on port 0 in the test. Rules: a file whose port has no listener is dropped; `window` before `headless`; then the largest `focused`; a damaged file is ignored; an explicit `port` skips the files; no file and no listener on the default port gives `NoViewerError`. The function never starts a program. `settings_dir()` test: monkeypatch `sys.platform`, `APPDATA` and `HOME`. + +- [ ] T017 [Found] [M] Implement `discovery.py`. + - Files: `packages/loop_link/src/loop_link/discovery.py` + - Needs: T016 + - Wave: 4 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_discovery.py` passes. + - Context: Public: `DEFAULT_PORT = 47615`, `ViewerAddress`, `settings_dir()`, `find_viewer(...)`. Token text on failure: "Set GEOVIEWER_TOKEN, or save a token in the link popup of the viewer." (`TokenError`). Alive check: `socket.create_connection((host, port), timeout)` then close. Sort key of live instances: `(kind != "window", -focused)`. Read JSON with `json.loads`; catch `OSError` and `ValueError` per file. The `NoViewerError` text says: "No viewer found. Start geoviewer and turn the link on. This library never starts a viewer." Use only the standard library. + +- [ ] T019 [Found] [M] Implement the fake viewer. + - Files: `packages/loop_link/src/loop_link/testing/__init__.py`, `packages/loop_link/src/loop_link/testing/fake_viewer.py` + - Needs: T008, T006 + - Wave: 5 + - Done when: `ruff check packages/loop_link` passes and `uv run --package loop-link python -c "from loop_link.testing import FakeViewer"` passes. Behaviour is tested by T020 and T025. + - Context: Base: `C:\Users\lachl\dev\plugin_loopstructural-geoviewer\tests\unit\geoviewer_fake_server.py` (179 lines, read it). New class `FakeViewer(token="secret", crs="EPSG:28350", origin=(0.0, 0.0, 0.0), kind="window", heartbeat_timeout=15.0, reply_errors=None, read_delay=0.0)`. Members: `.port`, `.objects: dict[str, StoredObject]` (`StoredObject(header: dict, buffers: dict[str, np.ndarray])`), `.received: list[Frame]`, `.inventory() -> list[dict]` (`id`, `object_type`, `revision`), `.write_instance_file(settings: Path) -> Path` (writes `instances/.json` and `link.json` is not written), `.accept_frame(data: bytes) -> list[Frame]` (apply one data-client frame and return the reply frames), `.close()`, context manager. Rules: listen on `127.0.0.1` port 0 in a thread; many connections; bearer token check (HTTP 401 when wrong); answer `hello` with `hello` (`application {"name":"fake-viewer"}`, `crs`, `origin`) then `scene.inventory` (`entries`); the second data connection (path not `/tool`) gets an `error` frame code `busy` then is closed; close a data connection with no frame for `heartbeat_timeout` seconds; the path `/tool` is accepted and every message gets `error` code `unknown_message`; `scene.upsert` rules (geometry roles present for the type, index < vertex count, data array length from association, finite coordinates, buffer sizes match, object size <= 2 GiB) else `error` code `invalid_object` with field `object`; `reply_errors` maps id to a forced error text; `scene.remove` and `scene.clear` change `objects`; `read_delay` waits that many seconds after each frame. The object keeps the data until a `scene.remove`. Frames use `loop_link.protocol`. Add docstrings and type hints. + +- [ ] T018 [Found] [M] Test support: `conftest.py`. + - Files: `packages/loop_link/tests/conftest.py` + - Needs: T019, T017 + - Wave: 6 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests --collect-only -q` passes. + - Context: Fixture `fake_viewer` (function scope): start `FakeViewer()`, write its instance file into `tmp_path / "geoviewer"`, `monkeypatch.setenv("GEOVIEWER_TOKEN", "secret")`, yield an object with `.viewer` (the `FakeViewer`) and `.settings` (the settings `Path`), and close at the end. Fixture `viewer_factory`: returns a function that makes `Viewer(settings_dir=, heartbeat_interval=0.1)` objects and closes all of them at teardown. Helper `geoviewer_fixtures() -> Optional[Path]`: the path in `LOOP_LINK_GEOVIEWER_FIXTURES` when it is a folder, else `None`. No test code in this file. + +- [ ] T020 [Found] [M] Test: `Viewer` in `test_viewer.py` (story 1). + - Files: `packages/loop_link/tests/test_viewer.py` + - Needs: T018, T012 + - Wave: 7 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_viewer.py` fails with ImportError of `loop_link.viewer`, then passes after T021. + - Context: Use fixtures `fake_viewer` and `viewer_factory` of `conftest.py`. API: `Viewer(*, port=None, token=None, host="127.0.0.1", crs="", origin=(0,0,0), settings_dir=None, timeout=5.0, heartbeat_interval=5.0)`; `connect()`, `send(obj, *, id, name=None, parent=None) -> int`, `send_group`, `remove`, `clear`, `inventory() -> list[InventoryEntry]`, `flush(settle=0.5, *, raise_on_refusal=True) -> list[Refusal]`, `release_data()`, `close()`, properties `revisions`, `scene_origin`, `scene_crs`, `connected`. Tests (one per scenario of story 1): 1 discovery with no port or token argument and the object in `fake_viewer.viewer.objects`; 2 same id twice gives revisions 1 then 2 and the stored header has revision 2; 3 no viewer gives `NoViewerError` and no process starts; 4 properties are the same names and values in the stored buffers; 5 one object of each of the 7 types gives 7 objects with the right `object_type`; 6 a `Vectors.from_directions` object gives stored `dip_direction` and `dip` equal to the expected values; 7 a second `Viewer` gets `BusyError` and the objects of the first do not change, then after `release_data()` of the first the second sends and the objects of the first stay. Also: a wrong token gives `TokenError`; `reply_errors` makes `flush()` raise `ViewerRefusedError` with a `Refusal` that has the id; the scene origin of the viewer differs from the proposed origin: coordinates use the scene origin; a viewer that closes in the middle of a send (`FakeViewer.close()` in a thread) gives `ViewerClosedError`; keepalive: `FakeViewer(heartbeat_timeout=0.6)` with `heartbeat_interval=0.1` stays connected for 2 s and a later `send` works; an `error` code `unsupported_version` gives `MissingFeatureError`. + +- [ ] T021 [Found] [M] Implement `Viewer` in `viewer.py`. + - Files: `packages/loop_link/src/loop_link/viewer.py` + - Needs: T020, T014, T015, T017 + - Wave: 8 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_viewer.py` passes. + - Context: Class and method signatures as in T020 (also `@dataclass(frozen=True) class InventoryEntry: id: str; object_type: str; revision: int`). `connect()`: `find_viewer(...)`, `WebSocketClient.connect(host, port, token=token, timeout=timeout, path="/")`, send `hello_frame(crs, origin, __version__)`, read until both `hello` and `scene.inventory` arrive (else `ViewerClosedError`); an `error` frame with code `busy` raises `BusyError` and closes the socket; `unsupported_version` raises `MissingFeatureError`; other `error` raises `ViewerRefusedError`. Scene origin: the viewer `hello` origin when not null, else the proposed origin; keep `scene_crs` from the viewer `hello`. All frames use the scene origin. Revision of an id: `max(local, inventory) + 1`, 1 for a new id. `send(obj, ...)` calls `adapters.convert` only when `obj` is not a `SceneObject` (T027 adds the hook; before that, a non-`SceneObject` raises `InvalidInputError` that names the accepted inputs). After each frame, drain the socket with a 1 ms wait and keep each `error` frame that has an `object` as a `Refusal`. `flush` waits up to `settle` for late frames. Keepalive: daemon thread `loop-link-heartbeat`; every `heartbeat_interval` it tries a non-blocking `lock.acquire`; if the last send was older than the interval, it sends `heartbeat_frame(seq)`; an `OSError` stops the thread and marks the connection closed. `release_data` and `close` set a `threading.Event`, join with timeout `2*heartbeat_interval`, close the socket, and keep `revisions`. OP2: default `crs=""`; first read the hello handling of the geoviewer repository (`C:\Users\lachl\dev\geoviewer\crates`, search `Hello`) and, if the viewer refuses an empty CRS, raise `InvalidInputError("give crs=...")` for an empty scene. Convert `OSError` and `WebSocketClosed` on send to `ViewerClosedError`. + +- [ ] T023 [US1] [S] Export the public names in `__init__.py`. + - Files: `packages/loop_link/src/loop_link/__init__.py` + - Needs: T021 + - Wave: 9 + - Done when: `uv run --package loop-link python -c "import loop_link as l; [getattr(l, n) for n in l.__all__]"` passes and `ruff check packages/loop_link` passes. + - Context: Keep `__version__ = "0.1.0"`. Import and list in `__all__`: from `.viewer`: `Viewer`, `InventoryEntry`; from `.objects`: `Points`, `Vectors`, `Lines`, `Surface`, `BlockModel`, `TetraMesh`, `Drillhole`, `Categorical`; from `.errors`: `LoopLinkError`, `NoViewerError`, `TokenError`, `BusyError`, `MissingFeatureError`, `InvalidInputError`, `ObjectTooLargeError`, `ViewerClosedError`, `ViewerRefusedError`, `MissingExtraError`, `Refusal`. Do not export `PushResult` or `push_objects` yet (T036). Do not import pyvista, pandas, Qt or LoopStructural here. + +- [ ] T024 [P] [US1] [S] Test: SC-001 speed in `test_performance.py`. + - Files: `packages/loop_link/tests/test_performance.py` + - Needs: T021 + - Wave: 9 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_performance.py` passes. + - Context: Mark the test `@pytest.mark.slow`. Use fixtures `fake_viewer` and `viewer_factory`. Build `BlockModel(origin=(0,0,0), cell_sizes=(1,1,1), cells=(100,100,100), cell_properties={"grade": np.random.default_rng(0).random(1_000_000, dtype=np.float32)})`. Time with `time.perf_counter()` from the start of `viewer.send(obj, id="grid")` to the moment that `fake_viewer.viewer.inventory()` has an entry with `id == "grid"` (poll every 10 ms, give up after 10 s). Assert the time is below 5.0 s (SC-001). The stored buffer must equal the input (`np.array_equal`). + +- [ ] T025 [P] [US1] [M] Test: frames of the geoviewer repository (SC-004). + - Files: `packages/loop_link/tests/test_fixtures.py` + - Needs: T021 + - Wave: 9 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_fixtures.py -rs` passes, or skips with the reason "set LOOP_LINK_GEOVIEWER_FIXTURES"; with the variable set to `C:\Users\lachl\dev\geoviewer\fixtures\protocol\python` it passes with no skip. + - Context: Use the helper `geoviewer_fixtures()` of `conftest.py` (OP8). `pytest.skip("set LOOP_LINK_GEOVIEWER_FIXTURES to the folder fixtures/protocol/python of the geoviewer repository")` when it is `None`. Test 1: for each `*.bin` file in the folder, `FakeViewer.accept_frame(bytes)` returns no `error` reply (use a fresh `FakeViewer` and send a `hello_frame` first). Test 2: for the file `scene_upsert_drillhole_end_of_hole.bin`, decode it with `decode_frame`, rebuild the same object with `Drillhole` and `encode_object` (read the header for `id`, `name`, collar, survey, intervals, `end_of_hole`), decode the result, and assert that the headers are equal except `version`, and the buffers are equal with `np.array_equal`. Other plugin frames: compare the header keys `type`, `object_type`, `geometry` only. + +- [ ] T027 [US1] [M] Add the adapter dispatch `adapters/__init__.py` and hook it into `Viewer.send`. + - Files: `packages/loop_link/src/loop_link/adapters/__init__.py`, `packages/loop_link/src/loop_link/viewer.py` + - Needs: T021 + - Wave: 9 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_viewer.py packages/loop_link/tests/test_import.py` passes (no regression) and `ruff check packages/loop_link` passes. + - Context: `adapters/__init__.py`: `convert(obj: Any, **hints: Any) -> SceneObject`. Return `obj` when it is a `SceneObject`. Else choose by the first part of `type(obj).__module__`: `pyvista` -> `adapters.pyvista.from_pyvista(obj, **hints)`; `loop_common` -> `adapters.loopstructural.from_loopstructural(obj)`; import the adapter module lazily inside the branch. Any other type raises `InvalidInputError("Accepted inputs: loop_link objects (Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole); pyvista meshes and grids; LoopStructural Surface and StructuredGrid; pandas tables for drillholes (use loop_link.adapters.pandas.drillholes_from_pandas).")`. The adapter modules are created by T029 and T031; `convert` imports them lazily, so a missing module raises `ImportError` only when used. Do not create stubs for them. In `viewer.py`, `Viewer.send` calls `convert(obj)` first. Add `**hints` to `Viewer.send` (`send(obj, *, id, name=None, parent=None, **hints)`) and pass them on. + +- [ ] T034 [P] [US5] [M] Test: plugin push API in `test_push.py` (story 5). + - Files: `packages/loop_link/tests/test_push.py` + - Needs: T021 + - Wave: 9 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_push.py` fails with ImportError of `loop_link.push`, then passes after T035. + - Context: Under test: `push_objects(viewer, objects, *, replace_prefix=None, progress=None, cancel=None) -> PushResult` and `PushResult(sent=0, removed=0, refused=[], skipped=[], cancelled=False)` with `summary() -> str`. `objects` is an iterable of `(id, object)`. Use `fake_viewer` and `viewer_factory`. Tests: (1) frames equal: push 3 objects and send the same 3 with `Viewer.send` to a second `FakeViewer`; the stored headers (without `version`) and buffers are equal (story 5, scenario 1); (2) `replace_prefix="model/"`: the fake starts with ids `model/old` and `other/keep` (send them first); after the push of `model/new` the ids `model/old` is removed, `other/keep` stays, `removed == 1`; (3) an object that raises `InvalidInputError` (for example an unsupported type `42`) goes to `skipped` as `(id, reason)` and the push goes on; (4) `cancel` set after the first object: `cancelled is True`, `sent == 1`; (5) `progress` gets the text `Sending ...` before each object, on the calling thread; (6) a slow viewer: `FakeViewer(read_delay=0.05)`; run `push_objects` in a `threading.Thread` for 5 objects; in the main thread count 20 ticks of 0.01 s with `time.sleep`; all 20 ticks finish while the push still runs or within 0.5 s of its start (the main thread is not blocked; story 5, scenario 2); (7) `summary()` text: "3 objects sent to GeoViewer", plus ", 1 old objects removed" and ", 1 objects skipped" when set, and ". The viewer refused N messages" when `refused` is not empty, ending with ".". + +- [ ] T037 [P] [Finish] [S] Manual checks document. + - Files: `packages/loop_link/tests/manual_checks.md` + - Needs: T021 + - Wave: 9 + - Done when: `git grep -n -c "^## M" packages/loop_link/tests/manual_checks.md` gives 2. + - Context: Two sections. `## M1: speed with the real headless viewer (SC-001)`: start `geoviewer-headless --port 0` with `GEOVIEWER_TOKEN=secret` (it prints the port); run a script that sends a `BlockModel` of 100 x 100 x 100 cells with one `float32` cell property to it and prints the time until the object is in `Viewer.inventory()` after a reconnect; pass if under 5 s; record the time. `## M2: seven types in the window viewer`: start the viewer with a window, turn the link on, save a token, send one object of each of the 7 types with one property each, check by eye that 7 objects with the right types show, and that the property names show in the property table. Keep each section to 8 steps or fewer, in ASD-STE100 English. + +## Phase 3: Stage S2 adapters (FR-010) + +- [ ] T028 [P] [US1] [M] Test: the pyvista adapter. + - Files: `packages/loop_link/tests/test_adapter_pyvista.py` + - Needs: T027 + - Wave: 10 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_pyvista.py` fails with ImportError of `loop_link.adapters.pyvista`, then passes after T029. + - Context: `pv = pytest.importorskip("pyvista")`. Under test: `from_pyvista(mesh, *, kind=None, vectors=None, vectors_kind="normal") -> SceneObject` and `Viewer.send(mesh, id=...)`. Cases: `pv.PolyData(points)` with only vertices -> `Points`, `point_data` -> `properties`; with a point array `"n"` of shape (n,3) and `vectors="n"` -> `Vectors` (check `dip` against the formula arccos(n_z) for upward normals); `pv.lines_from_points` PolyData -> `Lines` with segments (m,2); `pv.Sphere().triangulate()` -> `Surface` (vertices, triangles (m,3), cell data -> `cell_properties`); a quad `pv.Plane()` face set is triangulated -> `Surface`; `pv.ImageData(dimensions=(4,5,6), spacing=(1,2,3), origin=(10,20,30))` -> `BlockModel(origin=(10,20,30), cell_sizes=(1,2,3), cells=(3,4,5))` with point data on nodes and cell data on cells; `pv.RectilinearGrid` with uneven spacing -> `InvalidInputError` (OP9); `pv.StructuredGrid` -> `InvalidInputError`; an `UnstructuredGrid` of all tetra cells (`pv.UnstructuredGrid(cells, [pv.CellType.TETRA], points)`) -> `TetraMesh` with tetrahedra (m,4); a mixed-cell `UnstructuredGrid` -> `InvalidInputError`; `kind="Drillhole"` -> `InvalidInputError` whose text names `Drillhole` and `drillholes_from_pandas` (OP3); a 2-D array in `point_data` of shape (n,2) -> `InvalidInputError`. Analytic grid test: `f = x + 10 y + 100 z` on the nodes of the ImageData grid; send it and read the stored buffer from the `FakeViewer`; it equals `f` at the node order x fastest. + +- [ ] T029 [US1] [M] Implement the pyvista adapter. + - Files: `packages/loop_link/src/loop_link/adapters/pyvista.py` + - Needs: T028 + - Wave: 11 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_pyvista.py` passes. + - Context: `from_pyvista(mesh, *, kind: Optional[str] = None, vectors: Optional[str] = None, vectors_kind: str = "normal") -> SceneObject`. Import `pyvista` inside the module; if it is missing raise `MissingExtraError("pyvista")` at the first call of `from_pyvista`, not at `import loop_link`. Rules: `PolyData` with `n_lines > 0` -> `Lines` (segments from the line cell array: each line of k points gives k-1 segments); `PolyData` with faces -> `Surface` (call `mesh.triangulate()` when `not mesh.is_all_triangles`; triangles `faces.reshape(-1, 4)[:, 1:]`); `PolyData` of vertices only -> `Points`, or `Vectors.from_directions(points, mesh.point_data[vectors], kind=vectors_kind)` when `vectors` is set; `ImageData` -> `BlockModel(origin=mesh.origin, cell_sizes=mesh.spacing, cells=np.array(mesh.dimensions) - 1)`; `RectilinearGrid` with equal spacing on each axis (`np.allclose(np.diff(axis), step)`) -> `BlockModel`, else `InvalidInputError` (OP9); `UnstructuredGrid` with all cells `pyvista.CellType.TETRA` -> `TetraMesh` (`cells_dict[pyvista.CellType.TETRA]`); any other type or `kind="Drillhole"` -> `InvalidInputError` that names the accepted inputs (OP3 text: "A pyvista mesh cannot hold a drillhole. Use loop_link.Drillhole or loop_link.adapters.pandas.drillholes_from_pandas."). `point_data` -> `properties`, `cell_data` -> `cell_properties`, as numpy arrays; a 2-D array raises `InvalidInputError` that names the array. Order of pyvista image data is x fastest: no reorder. Add docstrings and type hints. + +- [ ] T030 [P] [US1] [M] Test: the LoopStructural adapter. + - Files: `packages/loop_link/tests/test_adapter_loopstructural.py` + - Needs: T027 + - Wave: 10 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_loopstructural.py` fails with ImportError of `loop_link.adapters.loopstructural`, then passes after T031. + - Context: `geometry = pytest.importorskip("loop_common.geometry")`. Classes: `loop_common.geometry.Surface` (fields `vertices`, `triangles`, `properties: dict|None`, `cell_properties: dict|None`, `name`) and `loop_common.geometry.StructuredGrid` (fields `origin`, `step_vector`, `nsteps` (node counts), `properties` (per node, x fastest), `cell_properties` (per cell, x fastest), property `nsteps_cells`). Under test: `from_loopstructural(obj)` and `Viewer.send(obj, id=...)`. Cases: `Surface` with 4 vertices, 2 triangles, `properties={"a": ...}`, `cell_properties={"b": ...}` -> `Surface` with the same arrays; `properties=None` -> empty mapping; `StructuredGrid(origin=[1,2,3], step_vector=[1,2,3], nsteps=[4,5,6])` -> `BlockModel(origin=(1,2,3), cell_sizes=(1,2,3), cells=(3,4,5))`; analytic check: set `properties["f"]` to `grid.nodes @ [1, 10, 100]` and send it; the stored buffer from the `FakeViewer` equals it (so no reorder is needed); any other class from `loop_common.geometry` (for example `ValuePoints`) -> `InvalidInputError` that names the accepted inputs. + +- [ ] T031 [US1] [M] Implement the LoopStructural adapter. + - Files: `packages/loop_link/src/loop_link/adapters/loopstructural.py` + - Needs: T030 + - Wave: 11 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_loopstructural.py` passes. + - Context: `from_loopstructural(obj: Any) -> SceneObject`. Do not import `loop_common` at module level. Find the classes with `module = sys.modules.get("loop_common.geometry")`; if `module is None` or `obj` is not an instance of `module.Surface` or `module.StructuredGrid`, raise `InvalidInputError` that names the accepted inputs. If `loop_common` cannot be imported when the extra is needed, raise `MissingExtraError("loopstructural")`. `Surface` -> `Surface(vertices=obj.vertices, triangles=obj.triangles, properties=obj.properties or {}, cell_properties=obj.cell_properties or {})`. `StructuredGrid` -> `BlockModel(origin=obj.origin, cell_sizes=obj.step_vector, cells=obj.nsteps_cells, properties=obj.properties, cell_properties=obj.cell_properties)`. Coordinates are the public attributes (world coordinates, spec 005). No other transform. Add docstrings and type hints. + +- [ ] T032 [P] [US1] [M] Test: the pandas adapter. + - Files: `packages/loop_link/tests/test_adapter_pandas.py` + - Needs: T027 + - Wave: 10 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_pandas.py` fails with ImportError of `loop_link.adapters.pandas`, then passes after T033. + - Context: `pd = pytest.importorskip("pandas")`. Under test: `drillholes_from_pandas(collar, survey, logs=None, *, hole_id="hole_id", x="x", y="y", z="z", depth="depth", azimuth="azimuth", dip="dip", from_="from", to="to", dip_positive_down=True) -> dict[str, Drillhole]`. Data: collar `hole_id,x,y,z` for `DH1`, `DH2`; survey `hole_id,depth,azimuth,dip` (2 rows each); logs `hole_id,from,to,grade,lith` (grade float, lith strings). Cases: result keys `DH1`, `DH2`; `Drillhole.collar` equals the row; `survey` shape (2,3) in the order depth, azimuth, dip; `intervals` shape (j,2); `interval_properties["grade"]` float array and `["lith"]` a numpy `U` array; `dip_positive_down=False` changes the sign of `dip`; a custom column name through `x="east"` works; a hole in `survey` that is not in `collar` -> `InvalidInputError`; an `object` column with a non-string value in `logs` -> `InvalidInputError`; `logs=None` gives holes with 0 intervals (`intervals` shape (0,2)); the result sends with `Viewer.send(hole, id=hole_id)` to the `FakeViewer` and the stored `object_type` is `Drillhole`. + +- [ ] T033 [US1] [M] Implement the pandas adapter. + - Files: `packages/loop_link/src/loop_link/adapters/pandas.py` + - Needs: T032 + - Wave: 11 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_adapter_pandas.py` passes. + - Context: Signature as in T032. Import `pandas` inside the function body of the first use; if it is missing raise `MissingExtraError("pandas")`. Group the three tables by `hole_id` (`groupby`, `sort=False`); sort the survey rows by `depth`; `Drillhole(collar=[x,y,z], survey=array of [depth, azimuth, dip], intervals=array of [from, to], properties={}, interval_properties={extra columns of logs})`. `dip_positive_down=False` multiplies `dip` by -1 (the `geoh5` sign is the opposite of the viewer, which has positive down). A column of strings (all `str`) becomes `np.asarray(values, dtype="U")`; a numeric or bool column keeps its dtype; any other `object` column raises `InvalidInputError` that names the column. A hole id in `survey` or `logs` that is not in `collar` raises `InvalidInputError` that names the id. Return a `dict` that keeps the order of `collar`. Add docstrings and type hints. + +## Phase 4: Stage S3 plugin API (story 5) + +- [ ] T035 [US5] [M] Implement `push.py`. + - Files: `packages/loop_link/src/loop_link/push.py` + - Needs: T034 + - Wave: 10 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_push.py` passes. + - Context: `@dataclass class PushResult: sent: int = 0; removed: int = 0; refused: list[Refusal] = field(default_factory=list); skipped: list[tuple[str, str]] = field(default_factory=list); cancelled: bool = False` and `summary(self) -> str` (text as in the test of T034: " objects sent to GeoViewer", ", old objects removed", ", objects skipped", ". The viewer refused messages", final "."). `push_objects(viewer: Viewer, objects: Iterable[tuple[str, Any]], *, replace_prefix: Optional[str] = None, progress: Optional[Callable[[str], None]] = None, cancel: Optional[threading.Event] = None) -> PushResult`. Steps: `viewer.connect()` if `not viewer.connected`; for each `(id, obj)`: if `cancel` is set, set `cancelled=True` and stop; call `progress(f"Sending {id}...")`; `viewer.send(obj, id=id)` and `sent += 1`; `InvalidInputError` or `ObjectTooLargeError` -> `skipped.append((id, str(error)))` and go on; `ViewerClosedError` and `BusyError` are not caught. After the loop, if `replace_prefix`, for each id in `viewer.inventory()` that starts with the prefix and was not sent in this call: `viewer.remove(id)` and `removed += 1`. Then `refused = viewer.flush(raise_on_refusal=False)`. No Qt, no module state; `progress` runs on the calling thread. Docstrings and type hints. + +- [ ] T036 [US5] [S] Export `PushResult` and `push_objects`. + - Files: `packages/loop_link/src/loop_link/__init__.py` + - Needs: T035, T023 + - Wave: 11 + - Done when: `uv run --package loop-link python -c "from loop_link import PushResult, push_objects"` passes and `ruff check packages/loop_link` passes. + - Context: Add `from .push import PushResult, push_objects` to `__init__.py` and add both names to `__all__`. Keep all other lines. + +- [ ] T022 [Finish] [S] Test: the core import needs no Qt or optional extras (SC-005). + - Files: `packages/loop_link/tests/test_import.py` + - Needs: T036 + - Wave: 12 + - Done when: `uv run --package loop-link pytest packages/loop_link/tests/test_import.py` passes. + - Context: Run in a subprocess: `subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True)` where `code` imports `loop_link`, then prints `sorted(m for m in sys.modules if m.split(".")[0] in {"PyQt5","PyQt6","PySide2","PySide6","qgis","pyvista","pandas","loop_common","LoopStructural"})`. The test asserts the printed list is `[]` and the return code is 0. Add a second test: `loop_link.__all__` names all exist (`getattr`). + +## Phase 5: Finish + +- [ ] T038 [Finish] [M] Run the merge gates and fix the findings. + - Files: `packages/loop_link/` + - Needs: T002, T003, T004, T005, T022, T024, T025, T029, T031, T033, T037 + - Wave: 13 + - Done when: `ruff check LoopStructural packages && pytest` passes, `uv run --package loop-link pytest packages/loop_link/tests` passes, and `black --check packages/loop_link` passes. + - Context: Constitution merge gate: `pytest` and `ruff check LoopStructural packages` must both pass. The root `pytest` does not run the package tests, so run the package command too. Run `black packages/loop_link` to fix format (line length 100, quotes kept). Fix only problems in `packages/loop_link/`. Do not change a gate or add a Ruff ignore for `packages/loop_link/src`. Run `git grep -n loop_link ROADMAP.md .release-please-config.json .release-please-manifest.json` and check 2 files or more show the name (SC-006). Report the result of each command in the commit message. + +## Wave table + +| Wave | Tasks | Tier [S] | Tier [M] | +|---|---|---|---| +| 1 | T001, T002, T004, T005 | 2 | 2 | +| 2 | T003, T006 | 1 | 1 | +| 3 | T007, T009, T011, T016 | 0 | 4 | +| 4 | T008, T010, T017 | 0 | 3 | +| 5 | T012, T015, T019 | 0 | 3 | +| 6 | T013, T018 | 0 | 2 | +| 7 | T014, T020 | 0 | 2 | +| 8 | T021 | 0 | 1 | +| 9 | T023, T024, T025, T027, T034, T037 | 3 | 3 | +| 10 | T028, T030, T032, T035 | 0 | 4 | +| 11 | T029, T031, T033, T036 | 1 | 3 | +| 12 | T022 | 1 | 0 | +| 13 | T038 | 0 | 1 | + +## Critical path + +T001 -> T006 -> T009 -> T010 -> T012 -> T013 -> T014 -> T021 -> T034 -> T035 -> T036 -> T022 -> T038 + +## Dependencies + +Setup (T001 to T005) first. T006 (errors) opens the foundation. Then three chains in parallel: +codec (T007, T008), vector math (T009, T010), objects (T011, T012; needs T010), and discovery +(T016, T017). The chain objects, then encode (T013, T014), joins the WebSocket port (T015) and +discovery in `Viewer` (T020, T021; needs the fake viewer T019 and `conftest.py` T018). After T021: +exports (T023), speed (T024), fixtures (T025), adapter dispatch (T027), push tests (T034) and +manual checks (T037) run in parallel. S2 adapters follow T027 as test-then-code pairs +(T028 to T033). S3 is T034, T035, T036. T022 and T038 close the work. From 5a8b9f4b0108473ed887d73dae990698d19f600c Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Fri, 6 Nov 2026 14:36:28 +1030 Subject: [PATCH 03/96] feat(loop-link): add package skeleton and register it (wave 1) --- .github/workflows/packages.yml | 3 ++ .release-please-config.json | 5 +++ .release-please-manifest.json | 3 +- ROADMAP.md | 8 ++++ packages/loop_link/LICENSE | 21 +++++++++ packages/loop_link/README.md | 30 +++++++++++++ packages/loop_link/pyproject.toml | 38 ++++++++++++++++ packages/loop_link/ruff.toml | 2 + packages/loop_link/src/loop_link/__init__.py | 3 ++ specs/006-loop-link/run-state.json | 47 ++++++++++++++++++-- specs/006-loop-link/tasks.md | 8 ++-- 11 files changed, 159 insertions(+), 9 deletions(-) create mode 100644 packages/loop_link/LICENSE create mode 100644 packages/loop_link/README.md create mode 100644 packages/loop_link/pyproject.toml create mode 100644 packages/loop_link/ruff.toml create mode 100644 packages/loop_link/src/loop_link/__init__.py diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 7c9a7b003..ba36700a7 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -48,6 +48,7 @@ jobs: - { name: loop_common, dir: loop_common } - { name: loop_interpolation, dir: loop_interpolation } - { name: loopstructuralvisualisation, dir: loopstructural_visualisation } + - { name: loop-link, dir: loop_link } os: ${{ fromJSON(vars.BUILD_OS)}} python-version: ${{ fromJSON(vars.PYTHON_VERSIONS)}} steps: @@ -62,10 +63,12 @@ jobs: run: uv python install ${{ matrix.python-version }} - name: Install package with test extras + if: ${{ !(matrix.package.name == 'loop-link' && startsWith(matrix.python-version, '3.9')) }} run: | uv sync --package ${{ matrix.package.name }} --extra tests --python ${{ matrix.python-version }} - name: pytest + if: ${{ !(matrix.package.name == 'loop-link' && startsWith(matrix.python-version, '3.9')) }} run: | uv run --package ${{ matrix.package.name }} pytest packages/${{ matrix.package.dir }}/tests diff --git a/.release-please-config.json b/.release-please-config.json index 1f1853d88..ba601927a 100644 --- a/.release-please-config.json +++ b/.release-please-config.json @@ -11,6 +11,7 @@ "packages/loop_interpolation", "packages/loop_interpolation_core", "packages/map2loop", + "packages/loop_link", "packages/loopstructural_visualisation" ] }, @@ -40,6 +41,10 @@ "packages/loopstructural_visualisation": { "release-type": "python", "component": "loopstructuralvisualisation" + }, + "packages/loop_link": { + "release-type": "python", + "component": "loop-link" } } } diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d1b350183..f6ca71892 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -4,5 +4,6 @@ "packages/loop_interpolation": "0.2.0", "packages/loop_interpolation_core": "0.1.0", "packages/map2loop": "3.5.1", - "packages/loopstructural_visualisation": "0.2.2" + "packages/loopstructural_visualisation": "0.2.2", + "packages/loop_link": "0.1.0" } diff --git a/ROADMAP.md b/ROADMAP.md index 814e3c47c..ac447ac03 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -549,6 +549,11 @@ just at release time. Phase A-C status notes. Phase D remains the open item for the dedicated discussion. +- [ ] **Stage 7 — `loop_link`: Python link to geoviewer.** New package + `packages/loop_link` (spec `specs/006-loop-link`). It gives Python a way to + send data to geoviewer: send, adapters and the plugin push API. Select, + fetch, filter and colour wait for geoviewer spec 066. + ## Status log - **2026-07-24:** Stage 0 done in worktree `~/dev/LoopStructural-roadmap` @@ -831,3 +836,6 @@ just at release time. `loopstructuralvisualisation`, none warranted in `map2loop`), and the release-please/PyPI/ruff wiring. `tests/unit`: 695 passed/4 skipped, zero regressions. + +- **2026-11-06:** Stage 7 started. The spec and the plan for + `packages/loop_link` exist (`specs/006-loop-link`). The package is new. diff --git a/packages/loop_link/LICENSE b/packages/loop_link/LICENSE new file mode 100644 index 000000000..3a62ff6af --- /dev/null +++ b/packages/loop_link/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Lachlan Grose + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/loop_link/README.md b/packages/loop_link/README.md new file mode 100644 index 000000000..0650c8519 --- /dev/null +++ b/packages/loop_link/README.md @@ -0,0 +1,30 @@ +# loop-link + +Send geoscience data from Python to the LoopConnect viewer. + +## Install + +``` +pip install loop-link +``` + +Optional extras: `pyvista`, `loopstructural`, `pandas`. + +## Token + +The package needs a token. It reads the `GEOVIEWER_TOKEN` environment +variable. If this variable is not set, it uses the token that the viewer +saved. + +## Example + +```python +import numpy as np +from loop_link import Viewer, Points + +viewer = Viewer() +xyz = np.random.rand(100, 3) +viewer.connect() +viewer.send(Points(xyz), id="random-points", name="random points") +viewer.close() +``` diff --git a/packages/loop_link/pyproject.toml b/packages/loop_link/pyproject.toml new file mode 100644 index 000000000..75fe8f1ae --- /dev/null +++ b/packages/loop_link/pyproject.toml @@ -0,0 +1,38 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "loop-link" +description = "Send geoscience data to the LoopConnect viewer" +version = "0.1.0" +requires-python = ">=3.10" +authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }] +readme = "README.md" +license = { text = "MIT" } +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering :: Information Analysis", + "License :: OSI Approved :: MIT License", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Operating System :: MacOS", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] +dependencies = ["numpy"] + +[project.optional-dependencies] +pyvista = ["pyvista"] +loopstructural = ["loop-common"] +pandas = ["pandas"] +tests = ["pytest", "pyvista", "loop-common", "pandas"] + +[tool.setuptools.packages.find] +where = ["src"] +include = ["loop_link", "loop_link.*"] + +[tool.pytest.ini_options] +markers = ["slow: tests that take a long time to run"] diff --git a/packages/loop_link/ruff.toml b/packages/loop_link/ruff.toml new file mode 100644 index 000000000..456965361 --- /dev/null +++ b/packages/loop_link/ruff.toml @@ -0,0 +1,2 @@ +extend = "../../pyproject.toml" +target-version = "py310" diff --git a/packages/loop_link/src/loop_link/__init__.py b/packages/loop_link/src/loop_link/__init__.py new file mode 100644 index 000000000..e3d9577a6 --- /dev/null +++ b/packages/loop_link/src/loop_link/__init__.py @@ -0,0 +1,3 @@ +"""loop-link: send geoscience data to the LoopConnect viewer.""" + +__version__ = "0.1.0" diff --git a/specs/006-loop-link/run-state.json b/specs/006-loop-link/run-state.json index 61b4c0e54..a0794504b 100644 --- a/specs/006-loop-link/run-state.json +++ b/specs/006-loop-link/run-state.json @@ -4,7 +4,46 @@ "branch": "feat/006-loop-link", "review_mode": "wave", "start_commit": "d4157a3e37f945f8b1570cc9b2eef9278c1ae086", - "waves": [], - "runs": {}, - "findings": { "found": 0, "rejected": 0, "dropped": 0, "fixed": 0, "open_minor": [] } -} + "waves": [ + { + "wave": 1, + "base": "4ed44583f45bd5073ed61bd04d164b6d538b915c", + "commit": null, + "review": "pending" + } + ], + "runs": { + "T001": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T002": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T004": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T005": [ + { + "model": "sonnet", + "result": "pass" + } + ] + }, + "findings": { + "found": 0, + "rejected": 0, + "dropped": 0, + "fixed": 0, + "open_minor": [] + }, + "note": "Baseline: 'ruff check LoopStructural packages' fails on master (475 errors, ruff 0.16.0 pinned); scoped 'ruff check packages/loop_link' passes." +} \ No newline at end of file diff --git a/specs/006-loop-link/tasks.md b/specs/006-loop-link/tasks.md index c38cb8cbc..c53dc1e0d 100644 --- a/specs/006-loop-link/tasks.md +++ b/specs/006-loop-link/tasks.md @@ -23,14 +23,14 @@ length 100; keep string quotes as written (Black `skip-string-normalization`). ## Phase 1: Setup -- [ ] T001 [Setup] [M] Create the package skeleton `packages/loop_link`. +- [x] T001 [Setup] [M] Create the package skeleton `packages/loop_link`. - Files: `packages/loop_link/pyproject.toml`, `packages/loop_link/README.md`, `packages/loop_link/LICENSE`, `packages/loop_link/ruff.toml`, `packages/loop_link/src/loop_link/__init__.py` - Needs: none - Wave: 1 - Done when: `python -c "import tomllib,pathlib;tomllib.loads(pathlib.Path('packages/loop_link/pyproject.toml').read_text())"` passes and `ruff check packages/loop_link` passes. - Context: Model on `packages/loop_common/pyproject.toml` (setuptools, `where = ["src"]`). `[project]` name `loop-link`, version `0.1.0`, `requires-python = ">=3.10"`, `dependencies = ["numpy"]`. Extras: `pyvista = ["pyvista"]`, `loopstructural = ["loop-common"]`, `pandas = ["pandas"]`, `tests = ["pytest", "pyvista", "loop-common", "pandas"]`. Setuptools `include = ["loop_link", "loop_link.*"]`. Register the pytest marker `slow` under `[tool.pytest.ini_options]`. `ruff.toml` has exactly `extend = "../../pyproject.toml"` and `target-version = "py310"`. `LICENSE` is a copy of `packages/loop_common/LICENSE`. `README.md`: install, the token (`GEOVIEWER_TOKEN` or the saved token of the viewer), a 10-line example with `Viewer`, `Points`. `__init__.py` holds a docstring and `__version__ = "0.1.0"` only (T023 adds the exports). -- [ ] T002 [P] [Setup] [S] Register `loop_link` for release-please. +- [x] T002 [P] [Setup] [S] Register `loop_link` for release-please. - Files: `.release-please-config.json`, `.release-please-manifest.json` - Needs: none - Wave: 1 @@ -44,14 +44,14 @@ length 100; keep string quotes as written (Black `skip-string-normalization`). - Done when: `uv lock --check` passes and `ruff check LoopStructural packages` passes. - Context: In root `pyproject.toml` add `loop-link = { workspace = true }` to `[tool.uv.sources]`. Add `"packages/loop_link/tests/*" = ["D", "ANN"]` to `[tool.ruff.lint.per-file-ignores]` next to the other `packages/*/tests/*` lines. Do NOT add an entry for `packages/loop_link/src`. Run `uv lock`. OP5 fallback: if uv refuses the workspace, or the lock drops Python 3.9 for the other members, remove the source line, add `"packages/loop_link"` to `[tool.uv.workspace] exclude`, run `uv lock` again, and write one line in the commit message that says the fallback was used. Do not change another dependency in `uv.lock`. -- [ ] T004 [P] [Setup] [S] Add `loop-link` to the package CI matrix. +- [x] T004 [P] [Setup] [S] Add `loop-link` to the package CI matrix. - Files: `.github/workflows/packages.yml` - Needs: none - Wave: 1 - Done when: `python -c "import yaml;yaml.safe_load(open('.github/workflows/packages.yml'))"` passes and `git grep -n "loop-link" .github/workflows/packages.yml` shows 3 lines. - Context: In `jobs.packages-test.strategy.matrix.package` add the line `- { name: loop-link, dir: loop_link }`. Add this line to the two steps that install and test (`Install package with test extras` and `pytest`): `if: ${{ !(matrix.package.name == 'loop-link' && startsWith(matrix.python-version, '3.9')) }}`. The package needs Python 3.10 or later. Do not change another step. -- [ ] T005 [P] [Setup] [M] Add `loop_link` to `ROADMAP.md`. +- [x] T005 [P] [Setup] [M] Add `loop_link` to `ROADMAP.md`. - Files: `ROADMAP.md` - Needs: none - Wave: 1 From ece3030f98abc65ee2f61f9c9738d0933bda0bc9 Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Fri, 6 Nov 2026 15:25:28 +1030 Subject: [PATCH 04/96] chore(spec): record wave 1 in run state --- specs/006-loop-link/run-state.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specs/006-loop-link/run-state.json b/specs/006-loop-link/run-state.json index a0794504b..5e051baca 100644 --- a/specs/006-loop-link/run-state.json +++ b/specs/006-loop-link/run-state.json @@ -8,7 +8,7 @@ { "wave": 1, "base": "4ed44583f45bd5073ed61bd04d164b6d538b915c", - "commit": null, + "commit": "5a8b9f4b0108473ed887d73dae990698d19f600c", "review": "pending" } ], @@ -45,5 +45,5 @@ "fixed": 0, "open_minor": [] }, - "note": "Baseline: 'ruff check LoopStructural packages' fails on master (475 errors, ruff 0.16.0 pinned); scoped 'ruff check packages/loop_link' passes." + "merged_origin_master": "7497982b (ruff baseline fixed upstream by #395)" } \ No newline at end of file From 0e969185e7026700323902cc536fb5e933a08753 Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Fri, 6 Nov 2026 15:28:20 +1030 Subject: [PATCH 05/96] feat(loop-link): errors module and workspace config (wave 2) OP5 fallback used: packages/loop_link is in the uv workspace exclude list; uv.lock is unchanged. --- packages/loop_link/src/loop_link/errors.py | 212 +++++++++++++++++++++ packages/loop_link/tests/test_errors.py | 92 +++++++++ pyproject.toml | 3 +- specs/006-loop-link/run-state.json | 24 ++- specs/006-loop-link/tasks.md | 72 +++---- 5 files changed, 366 insertions(+), 37 deletions(-) create mode 100644 packages/loop_link/src/loop_link/errors.py create mode 100644 packages/loop_link/tests/test_errors.py diff --git a/packages/loop_link/src/loop_link/errors.py b/packages/loop_link/src/loop_link/errors.py new file mode 100644 index 000000000..484f69938 --- /dev/null +++ b/packages/loop_link/src/loop_link/errors.py @@ -0,0 +1,212 @@ +"""Error types that loop_link raises. + +All errors derive from :class:`LoopLinkError`, so a caller can catch every +loop_link error with one ``except`` clause. +""" + +from __future__ import annotations + +from dataclasses import dataclass + + +class LoopLinkError(Exception): + """Base class for all loop_link errors.""" + + +class NoViewerError(LoopLinkError): + """No viewer is available. + + Parameters + ---------- + message : str + The error text. The default text tells the user how to start a viewer. + """ + + def __init__( + self, + message: str = "No viewer is running. Start a viewer before you send objects.", + ) -> None: + super().__init__(message) + + +class TokenError(LoopLinkError): + """The access token is missing, wrong or expired. + + Parameters + ---------- + message : str + The error text. The default text tells the user how to get a new token. + """ + + def __init__( + self, + message: str = "The access token is not valid. Create a new token and try again.", + ) -> None: + super().__init__(message) + + +class BusyError(LoopLinkError): + """The viewer is busy with another request. + + Parameters + ---------- + message : str + The error text. The default text tells the user to wait and retry. + """ + + def __init__( + self, + message: str = "The viewer is busy. Wait a moment and try again.", + ) -> None: + super().__init__(message) + + +class InvalidInputError(LoopLinkError): + """An input value is not valid. + + Parameters + ---------- + message : str + The error text. The default text tells the user to check the input. + """ + + def __init__( + self, + message: str = "An input value is not valid. Check the input and try again.", + ) -> None: + super().__init__(message) + + +class ViewerClosedError(LoopLinkError): + """The viewer was closed. + + Parameters + ---------- + message : str + The error text. The default text tells the user to open the viewer again. + """ + + def __init__( + self, + message: str = "The viewer was closed. Open the viewer again and retry.", + ) -> None: + super().__init__(message) + + +class MissingFeatureError(LoopLinkError): + """A required feature is not available. + + Parameters + ---------- + feature : str + The name of the missing feature. + + Attributes + ---------- + feature : str + The name of the missing feature. + """ + + def __init__(self, feature: str) -> None: + self.feature = feature + super().__init__( + f"The feature '{feature}' is not available in this installation. " + f"Check that the '{feature}' feature is installed and enabled, then retry." + ) + + +class ObjectTooLargeError(LoopLinkError): + """An object is larger than the allowed limit. + + Parameters + ---------- + object_id : str + The identifier of the object. + size : int + The size of the object. + limit : int + The largest size that is allowed. + + Attributes + ---------- + object_id : str + The identifier of the object. + size : int + The size of the object. + limit : int + The largest size that is allowed. + """ + + def __init__(self, object_id: str, size: int, limit: int) -> None: + self.object_id = object_id + self.size = size + self.limit = limit + super().__init__( + f"Object '{object_id}' is {size} units, which is larger than the limit of " + f"{limit} units. Reduce the size of the object or split it into smaller " + "objects, then try again." + ) + + +@dataclass(frozen=True) +class Refusal: + """A reason why the viewer refused one object. + + Parameters + ---------- + object_id : str + The identifier of the refused object. + code : str + A short code that names the reason. + message : str + A message that explains the reason. + """ + + object_id: str + code: str + message: str + + +class ViewerRefusedError(LoopLinkError): + """The viewer refused one or more objects. + + Parameters + ---------- + refusals : list of Refusal + The refusals, one for each refused object. + + Attributes + ---------- + refusals : list of Refusal + The refusals, one for each refused object. + """ + + def __init__(self, refusals: list[Refusal]) -> None: + self.refusals = refusals + count = len(refusals) + super().__init__( + f"The viewer refused {count} object(s). Read the code and message of each " + "refusal, fix those objects, and try again." + ) + + +class MissingExtraError(LoopLinkError): + """An optional extra package is not installed. + + Parameters + ---------- + extra : str + The name of the extra. + + Attributes + ---------- + extra : str + The name of the extra. + """ + + def __init__(self, extra: str) -> None: + self.extra = extra + super().__init__( + f"The optional '{extra}' part of loop-link is not installed. " + f"Run: pip install loop-link[{extra}]" + ) diff --git a/packages/loop_link/tests/test_errors.py b/packages/loop_link/tests/test_errors.py new file mode 100644 index 000000000..875bf5879 --- /dev/null +++ b/packages/loop_link/tests/test_errors.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import dataclasses + +import pytest + +from loop_link.errors import ( + BusyError, + InvalidInputError, + LoopLinkError, + MissingExtraError, + MissingFeatureError, + NoViewerError, + ObjectTooLargeError, + Refusal, + TokenError, + ViewerClosedError, + ViewerRefusedError, +) + +SIMPLE_ERRORS = [ + NoViewerError, + TokenError, + BusyError, + InvalidInputError, + ViewerClosedError, +] + + +@pytest.mark.parametrize("error_class", SIMPLE_ERRORS) +def test_simple_error_is_loop_link_error(error_class: type[LoopLinkError]) -> None: + assert issubclass(error_class, LoopLinkError) + assert issubclass(LoopLinkError, Exception) + + +@pytest.mark.parametrize("error_class", SIMPLE_ERRORS) +def test_simple_error_default_text_is_not_empty(error_class: type[LoopLinkError]) -> None: + assert str(error_class()) != "" + + +@pytest.mark.parametrize("error_class", SIMPLE_ERRORS) +def test_simple_error_keeps_custom_text(error_class: type[LoopLinkError]) -> None: + assert str(error_class("custom text")) == "custom text" + + +def test_missing_feature_error_keeps_feature_and_names_it() -> None: + error = MissingFeatureError("viewer") + + assert isinstance(error, LoopLinkError) + assert error.feature == "viewer" + assert "viewer" in str(error) + + +def test_object_too_large_error_keeps_attributes_and_text() -> None: + error = ObjectTooLargeError("mesh-1", 2048, 1024) + + assert isinstance(error, LoopLinkError) + assert error.object_id == "mesh-1" + assert error.size == 2048 + assert error.limit == 1024 + text = str(error) + assert "mesh-1" in text + assert "2048" in text + assert "1024" in text + + +def test_viewer_refused_error_keeps_refusals() -> None: + refusals = [Refusal(object_id="mesh-1", code="too_big", message="Object is too large.")] + error = ViewerRefusedError(refusals) + + assert isinstance(error, LoopLinkError) + assert error.refusals == refusals + assert str(error) != "" + + +def test_missing_extra_error_keeps_extra_and_gives_install_command() -> None: + error = MissingExtraError("viewer") + + assert isinstance(error, LoopLinkError) + assert error.extra == "viewer" + assert "pip install loop-link[viewer]" in str(error) + + +def test_refusal_is_hashable_and_frozen() -> None: + refusal = Refusal(object_id="mesh-1", code="too_big", message="Object is too large.") + + assert hash(refusal) == hash( + Refusal(object_id="mesh-1", code="too_big", message="Object is too large.") + ) + assert {refusal} + with pytest.raises(dataclasses.FrozenInstanceError): + refusal.code = "other" # type: ignore[misc] diff --git a/pyproject.toml b/pyproject.toml index e5bade632..512034a34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,7 +91,7 @@ LoopStructural = [ [tool.uv.workspace] members = ["packages/*"] -exclude = ["packages/loop_interpolation_core"] +exclude = ["packages/loop_interpolation_core", "packages/loop_link"] [tool.uv.sources] loop-common = { workspace = true } @@ -325,6 +325,7 @@ allow-dict-calls-with-keyword-arguments = true "docs/*" = ["D", "ANN"] "setup.py" = ["D", "ANN"] "packages/loop_common/tests/*" = ["D", "ANN"] +"packages/loop_link/tests/*" = ["D", "ANN"] "packages/loop_interpolation/tests/*" = ["D", "ANN"] "packages/map2loop/tests/*" = ["D", "ANN"] "packages/loopstructural_visualisation/tests/*" = ["D", "ANN"] diff --git a/specs/006-loop-link/run-state.json b/specs/006-loop-link/run-state.json index 5e051baca..59b227b64 100644 --- a/specs/006-loop-link/run-state.json +++ b/specs/006-loop-link/run-state.json @@ -9,6 +9,12 @@ "wave": 1, "base": "4ed44583f45bd5073ed61bd04d164b6d538b915c", "commit": "5a8b9f4b0108473ed887d73dae990698d19f600c", + "review": "pass" + }, + { + "wave": 2, + "base": "ece3030f98abc65ee2f61f9c9738d0933bda0bc9", + "commit": null, "review": "pending" } ], @@ -36,14 +42,28 @@ "model": "sonnet", "result": "pass" } + ], + "T003": [ + { + "model": "sonnet", + "result": "pass (OP5 fallback)" + } + ], + "T006": [ + { + "model": "haiku", + "result": "pass" + } ] }, "findings": { - "found": 0, + "found": 1, "rejected": 0, "dropped": 0, "fixed": 0, - "open_minor": [] + "open_minor": [ + "W1 T004: loop-link CI job fails between wave 1 and wave 2 (fixed by T003/T006); do not merge wave 1 alone" + ] }, "merged_origin_master": "7497982b (ruff baseline fixed upstream by #395)" } \ No newline at end of file diff --git a/specs/006-loop-link/tasks.md b/specs/006-loop-link/tasks.md index c53dc1e0d..b1c5d70da 100644 --- a/specs/006-loop-link/tasks.md +++ b/specs/006-loop-link/tasks.md @@ -5,8 +5,12 @@ +Scope of this plan: stories 1 and 5 (stages S1 to S3, built), and stories 2 to 4 +(stage S5, planned 2026-11-07, see "Design of stage S5"). Stories 6 and 7 (S4) get +their own planner run (OP6). --> ## Open points @@ -45,9 +45,12 @@ Each point has a default. A point that has no owner is for the maintainer. - **OP6**: Stories 6 and 7 (filter and colour, FR-018 to FR-021, SC-007) need the tool connection. Default: plan them in a later planner run as stage S4. The names of the commands are in "Handover". -- **OP7**: Stories 2, 3 and 4 (select, read selection, fetch) wait for geoviewer - spec 066. Default: plan them in a later planner run as stage S5, after 066 - lands. The plan of 066 uses protocol 1.15 and may change names (its OP4). +- **OP7**: Stories 2, 3 and 4 (select, read selection, fetch) are planned in stage S5 + (see "Design of stage S5"). They use geoviewer spec 067-selection-and-fetch + (protocol 1.18), merged in the geoviewer repository. The text of this spec and of + the earlier parts of this plan calls it "066"; read "067". The spec owner should + change the number in `spec.md`. The names of the messages are final (they are in + `docs/protocol.md` of the geoviewer repository). - **OP8**: SC-004 needs the folder `fixtures/protocol/python` of the geoviewer repository. CI of this repository cannot see it. Default: the tests read the folder from the environment variable `LOOP_LINK_GEOVIEWER_FIXTURES`. When it @@ -59,6 +62,30 @@ Each point has a default. A point that has no owner is for the maintainer. `RectilinearGrid` with uneven spacing gives `InvalidInputError`. The viewer has no type for them. +- **OP10**: A fetch of a Drillhole that the viewer made by an import can have log + sets, sample sets and per-hole values that the `Drillhole` dataclass cannot hold + (it has one set of intervals). Default: `fetch` keeps the first interval set and + the survey values, and drops the rest with a `UserWarning` that names each dropped + property. The other choice is an error, which would make most imported holes + impossible to fetch. Owner: spec owner. Blocks no task. +- **OP11**: The tool fixtures of geoviewer are in `fixtures/protocol/tool`, next to + `fixtures/protocol/python`. Default: the tests read them from + `/../tool` and skip when the folder is missing (OP8 + rule). No new variable. +- **OP12**: Which object types have a selection table is a viewer fact that the + protocol text does not list. Default for the fake viewer: `Points` has nodes only; + `Curve`, `Surface`, `BlockModel` and `TetraMesh` have nodes and cells; `Drillhole` + and `Group` have no table. Manual check M3 repeats this with the real viewer. If the + real viewer differs, change the fake viewer (one task). +- **OP13**: The spec entity "Selection" is a list of object ids. Spec 067 gives one + object for each selection (one table). Default: `Selection` has one `object_id` + (or `None`). The spec owner should change the entity text. +- **OP14**: The plan of geoviewer spec 067 says that a part has an `offset` and that + the parts follow the order of `arrays`. It does not say that the parts of one array + arrive in order with no gap. Default: the assembler requires this and gives an error + otherwise. M3 checks it with the real viewer. If the real viewer sends the parts in + another order, relax the rule to "each byte is filled one time" (one task). + ## Answers - 2026-11-06 (orchestrator, wave 10 review): pyvista adapter. The adapter skips the arrays that @@ -76,6 +103,15 @@ Each point has a default. A point that has no owner is for the maintainer. from the hello frame, updated by `send` (add or update the entry), `remove` (drop it) and `clear` (drop all). `push_objects` with `replace_prefix` keeps the ids of the objects that were sent or skipped in this call, and does no removal when the push was cancelled. +- 2026-11-07 (orchestrator, manual check M2 with the real window viewer; this replaces the + 2026-11-06 entry about `cell`): a Drillhole `interval_properties` array goes out with the + association `interval`, the field `log_set` = `"intervals"` in its description, and the header + field `log_sets` = `[{"name": "intervals", "kind": "interval"}]`. The viewer offers + drillhole interval values for colour only from such arrays; with `cell` it accepted the object + but showed no property. A Drillhole with no interval properties has no `log_sets`. A tetra + mesh has no Data button in the viewer; its properties are used by the isosurface and filter. +- 2026-11-07 (maintainer): the geoviewer spec for stories 2 to 4 is 067-selection-and-fetch + (the text calls it 066). ## Summary @@ -88,8 +124,10 @@ push API with no Qt, and a fake viewer in `loop_link.testing`. The package registers in `ROADMAP.md`, the release-please files, the CI matrix and the Ruff config. -The work has three stages in this plan: S1 (send, story 1), S2 (adapters, -FR-010), S3 (plugin API, story 5). The stages S4 and S5 are for later runs. +The work has three built stages: S1 (send, story 1), S2 (adapters, FR-010), S3 +(plugin API, story 5). Stage S5 (planned 2026-11-07) adds the tool connection, the +selection calls and the fetch (stories 2 to 4). Stage S4 (filter and colour) is for +a later run. ## Technical context @@ -528,7 +566,492 @@ calls `progress` on the thread that calls it. The plugin runs it on a worker thr | S1 | New package: codec, errors, WebSocket, discovery, objects, orientation, encode, `Viewer`, fake viewer; repository registration (ROADMAP, release-please, CI, Ruff, uv). Inputs: the dataclasses and numpy arrays only. | `uv run --package loop-link pytest packages/loop_link/tests`; `ruff check LoopStructural packages`; root `pytest`; SC-001, SC-004 (with the variable), SC-005, SC-006; manual check M1 | Revert the stage: the files are new, and the root files change by added lines only. The root `pytest` result is the same as before. | | S2 | `adapters/` for pyvista, LoopStructural, pandas; `Viewer.send` calls `adapters.convert`. | The same commands. Adapter tests (pyvista, LoopStructural, pandas extras installed in the test environment). | Revert S2. S1 still sends the dataclasses. | | S3 | `push.py` and its tests; frame comparison with the plugin frames; the slow-viewer and cancel tests. | The same commands; SC-004 frames of the plugin. | Revert S3. S1 and S2 stay. | -| S4, S5 | Not planned here (OP6, OP7). | | | +| S4 | Not planned here (OP6). | | | +| S5 | Planned in "Design of stage S5": S5a (tool connection and selection), S5b (fetch), S5c (real codec checks, manual check M3, docs). | See "Stages and rollback of S5". | See "Stages and rollback of S5". | + +## Design of stage S5 (stories 2 to 4) + +Planned 2026-11-07, after S1 to S3 were built (PR 406) and geoviewer spec 067 merged +(protocol 1.18). S5 adds the tool connection, the selection calls and the fetch. S4 +(filter and colour) is not in S5, but S4 reuses the tool connection of S5. + +### Facts that S5 uses (geoviewer spec 067, `docs/protocol.md` version 1.18) + +- A tool connects to the same server on the path `/tool`, with the same bearer token. + It sends no `hello`. The viewer accepts 8 tool connections at the same time. A tool + connection does not take the one data slot, so it works while another program holds + the data connection (FR-014). +- Each tool message has the field `request` (a number that the tool chooses). Replies + have the same number. The new messages: `selection.set`, `selection.get`, + `selection.result`, `object.fetch`, `object.header`, `object.part`, `object.end`. + Fixtures of these messages are in `fixtures/protocol/tool/` of the geoviewer + repository. They use the version `{"major":1,"minor":18}`. `command.cancel` and + `command.progress` come from spec 035 (the fixture of `command.cancel` has minor 11). +- `selection.set`: fields `object`, optional `revision`, `entries` (list of + `{"kind": "cells" | "nodes", "indices": }`), one `u32` buffer for each + entry. An empty `entries` list clears the selection of the object. A kind that is + not in the list is cleared. The viewer counts a repeated index one time. The reply + is `selection.result` with `object`, `revision` and `entries` that have `kind` and + `count` only. +- `selection.get`: no fields. The reply is `selection.result` with one entry for each + kind that has a selection, and a `u32` buffer for each entry (`indices` gives its + name). The selection is the selection of the table that the user (or a tool) + changed last, so it holds one object. With no table the reply has no `object`, no + `revision` and `"entries": []`. +- `object.fetch`: field `id`. Replies, in this order: `object.header` (fields + `origin`, `crs`, `object` = the `scene.upsert` fields of the object with no buffers, + and `arrays` = the list of `{name, dtype, shape}` that the parts fill), then + `object.part` messages (fields `array`, `offset`, `bytes`; one `u8` buffer named + `part`; at most 64 MiB; `offset` is a multiple of 8), then `object.end` (field + `parts`). Between parts the viewer sends `command.progress` with the same + `request`. A tool cancels with `command.cancel` (field `request`); the reply is + `request.error` with the code `cancelled`. A fetch needs no window. +- All coordinates of a fetch are relative to `origin` (f32 or f64 as stored). +- `request.error` has `error` = `{code, message, field}`. The codes that S5 meets: + `invalid_input` (`field` is `object`, `id`, `kind`, `indices` or `revision`), + `needs_window`, `cancelled`, `busy`, `failed`, `too_large`. +- A viewer older than 1.18 answers a tool message that it does not know with an + `error` frame that has the code `unknown_message`. The tool connection has no + `hello`, so this reply is the only way to detect an old viewer (FR-013). + +### Names and errors + +All new names below are free (checked with `git grep -n -w` on 2026-11-07). + +New errors in `errors.py` (all derive from `LoopLinkError`): + +```python +class StaleRevisionError(LoopLinkError): + # attributes: object_id: str, revision: Optional[int] + def __init__(self, object_id: str, revision: Optional[int] = None) -> None + # text: "The object '' is not at that revision in the viewer. Read the + # selection or fetch the object again, then try again." +class CancelledError(LoopLinkError): + def __init__(self, message: str = "The request was cancelled.") -> None +class UnsupportedObjectError(LoopLinkError): + # attributes: object_id: str, object_type: str + def __init__(self, object_id: str, object_type: str) -> None + # text: "The object '' has the type ''. loop_link can fetch Points, Curve, + # Surface, BlockModel, TetraMesh and Drillhole objects only." +``` + +`loop_link/__init__.py` exports them, and `Selection`, `SelectionWatcher`, +`FetchResult`. + +Mapping of a tool failure to a library error (function `raise_for_request_error(error: +Mapping[str, Any], *, object_id: Optional[str]) -> NoReturn` in `tool.py`): + +| Tool reply | Library error | +|---|---| +| `request.error`, code `invalid_input`, field `revision` | `StaleRevisionError(object_id)` | +| `request.error`, code `invalid_input`, other field | `InvalidInputError("The viewer refused the request: ")` | +| `request.error`, code `needs_window` | `MissingFeatureError("a viewer window (this viewer has no window)")` | +| `request.error`, code `cancelled` | `CancelledError()` | +| `request.error`, code `busy` | `BusyError()` | +| `request.error`, any other code | `ViewerRefusedError([Refusal(object_id or "", code, message)])` | +| `error` frame, code `unknown_message` | `MissingFeatureError(feature)`, where `feature` is the argument of `request` (for S5: `"selection and fetch (geoviewer protocol 1.18)"`) | +| `error` frame, code `unsupported_version` | `MissingFeatureError("protocol " + str(supported))` | +| other `error` frame | `ViewerRefusedError([Refusal("", code, message)])` | +| HTTP 401 at connect | `TokenError()` (the client already does this) | +| socket closed, or no frame in time | `ViewerClosedError` | + +### Protocol changes (`protocol.py`, `encode.py`) + +```python +TOOL_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 18} +CANCEL_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 11} +def encode_frame(header, buffers=(), *, version: Optional[dict[str, int]] = None) -> bytes + # version=None keeps PROTOCOL_VERSION (1.14). Else the header gets this version. +``` + +New frame builders in `encode.py` (each returns the bytes of one frame): + +```python +def selection_set_frame(request: int, object_id: str, cells: Optional[np.ndarray], + vertices: Optional[np.ndarray], revision: Optional[int]) -> bytes +def selection_get_frame(request: int) -> bytes +def fetch_frame(request: int, id: str) -> bytes +def cancel_frame(request: int) -> bytes # command.cancel, version CANCEL_PROTOCOL_VERSION +``` + +`selection_set_frame`: the header is `{"type": "selection.set", "request": n, "object": +id, ["revision": r,] "entries": [...]}`. An entry is added for `cells` (kind `cells`, +buffer name `cells`) and for `vertices` (kind `nodes`, buffer name `nodes`) only when +the array is not empty. Each buffer is `u32` with shape `[k]`. With no entry, there is +no buffer. The `revision` key is left out when `revision` is `None`. The version is +`TOOL_PROTOCOL_VERSION`. `selection_get_frame` and `fetch_frame` use the same version. + +### Tool connection (`tool.py`) + +```python +class ToolConnection: + def __init__(self, *, port: Optional[int] = None, token: Optional[str] = None, + host: str = "127.0.0.1", settings_dir: Optional[Path] = None, + timeout: float = 5.0) -> None + @property + def connected(self) -> bool + def connect(self) -> ToolConnection # no hello; path "/tool" + def request(self, build: Callable[[int], bytes], *, until: Sequence[str], + feature: str, object_id: Optional[str] = None, + on_frame: Optional[Callable[[Frame], None]] = None, + progress: Optional[Callable[[float], None]] = None, + cancel: Optional[threading.Event] = None, + timeout: Optional[float] = None) -> Frame + def close(self) -> None +``` + +Behaviour of `request`: + +1. It takes the lock `self._lock` (one request at a time on one connection). It + connects when there is no socket (`discovery.find_viewer`, then + `WebSocketClient.connect(host, port, token=..., timeout=..., path="/tool")`). It + sends no `hello`. +2. It makes the number `n` (starts at 1, increases by 1 for each request of this + connection), sends `build(n)`, and notes the time. +3. It reads frames with `client.receive(0.1)` in a loop. It decodes each with + `protocol.decode_frame`. A `ProtocolError` closes the connection and raises + `ViewerClosedError("The viewer sent a frame that is not valid. ...")`. +4. A frame with `type == "error"` goes to `raise_for_request_error` (the `error` rows + of the table). A frame with another `request` number is dropped (a late frame of an + older request). For a frame with the number `n`: `request.error` goes to + `raise_for_request_error`; `command.progress` calls `progress(fraction)` when + `fraction` is a number and `progress` is not `None`; a frame whose type is in + `until` ends the loop and is returned (before that, `on_frame` has seen it too); + any other frame goes to `on_frame` when it is not `None`, else it is dropped. + `on_frame` sees every frame of the request except `command.progress` and + `request.error`. +5. The wait time restarts at each frame of the request. When `timeout` seconds (default + `self._timeout`) pass with no frame, the function closes the connection and raises + `ViewerClosedError("The viewer did not answer in time. ...")`. +6. When `cancel` is set, the function sends `cancel_frame(n)` one time and goes on + reading until the `cancelled` error arrives (then `CancelledError` goes up), or the + `until` frame arrives (the request ended first, so it is returned), or the time + runs out. +7. A socket error sets the socket to `None` and raises `ViewerClosedError`. The next + call of `request` connects again. + +`connect` raises `NoViewerError` and `TokenError`. A tool connection has no keepalive +thread (the viewer sets no idle time for it). + +### Selection (`selection.py`) + +```python +@dataclass(frozen=True, eq=False) +class Selection: + object_id: Optional[str] # None when nothing is selected + revision: Optional[int] + cells: np.ndarray # uint32, 1-D, empty when none + vertices: np.ndarray # uint32, 1-D, empty when none + @property + def empty(self) -> bool # no cells and no vertices + def same_as(self, other: Selection) -> bool + # same object_id, and the sorted cells and the sorted vertices are equal. + # The revision is not compared. + +def parse_selection_result(frame: Frame) -> Selection + # kind "cells" gives cells, kind "nodes" gives vertices. The array is + # frame.buffers[entry["indices"]]. An entry with a count but no buffer, a buffer + # that is not uint32, or a length that differs from count gives ProtocolError. + +class SelectionWatcher: + @property + def running(self) -> bool + @property + def error(self) -> Optional[BaseException] # the error that stopped the thread + def stop(self) -> None # stop, then join (timeout 2 * interval + 1 s) + def __enter__(self) -> SelectionWatcher + def __exit__(self, *exc) -> None +``` + +Only `Viewer.watch_selection` makes a `SelectionWatcher`. It has a daemon thread +`loop-link-selection-poll`. The thread holds a `weakref` to the `Viewer`, so a dropped +`Viewer` ends it. Loop of the thread: wait `interval` seconds on a `threading.Event` +(so `stop` is fast), call `viewer.selection()`, and when the result is not `same_as` +the last one, call `callback(selection)` one time and keep it as the last one. An +exception of the poll or of the callback goes to `error`, and the thread ends. No +thread runs before `watch_selection` is called (FR-005). + +### Fetch (`fetch.py`) + +```python +@dataclass(frozen=True, eq=False) +class FetchResult: + id: str + object: SceneObject # Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole + object_type: str # the viewer type name, for example "Curve" + revision: int + name: Optional[str] + parent: Optional[str] + origin: Optional[tuple[float, float, float]] + crs: Optional[str] + +def fetch_object(tool: ToolConnection, id: str, *, + progress: Optional[Callable[[float], None]] = None, + cancel: Optional[threading.Event] = None, + timeout: float = 30.0) -> FetchResult + +def decode_object(header: Mapping[str, Any], arrays: Mapping[str, np.ndarray], + origin: Optional[Sequence[float]]) -> SceneObject +``` + +`fetch_object` calls `tool.request(lambda n: encode.fetch_frame(n, id), until=("object.end",), +feature="selection and fetch (geoviewer protocol 1.18)", object_id=id, +on_frame=assembler.feed, progress=progress, cancel=cancel, timeout=timeout)`. The +private class `_Assembler` keeps the state and the rules: + +1. The first frame must be `object.header`. Any other first frame gives `ProtocolError`. +2. Header checks. Each entry of `arrays` has a unique `name`, a `dtype` in `f32 f64 u32 + i32 u8`, and a `shape` of non-negative integers. The sum of the bytes of all arrays + must be at most `protocol.MAX_OBJECT_BYTES`, else `ObjectTooLargeError(id, size, + limit)`. Each buffer name in `object.geometry`, in `object.data[*].buffer`, and in the + `offsets` fields must be in `arrays`, else `ProtocolError`. Then the assembler makes + one `numpy.empty(nbytes, dtype=numpy.uint8)` for each array. +3. `object.part`: the array must be in `arrays`; `offset % 8 == 0`; the buffer `part` must + be `u8` with `bytes` entries; `offset` must equal the bytes already filled in that + array (parts of one array arrive in order, with no gap and no overlap); `offset + + bytes` must be at most the size of the array. A break gives `ProtocolError`. The + assembler copies the part into the array. +4. `object.end`: `parts` must equal the number of parts received, and each array must be + full. A break gives `ProtocolError`. +5. The assembler views each array with its dtype and shape (`numpy.ndarray.view`, + `reshape`) and calls `decode_object(header["object"], arrays, header["origin"])`. The + `revision` of the result is `header["object"]["revision"]`. + +`ProtocolError` is the existing `loop_link.protocol.ProtocolError`. `fetch_object` +catches it, closes the tool connection (the stream is out of step), and raises +`ViewerClosedError("The viewer sent an object that is not valid: ")`. +`CancelledError` and the other library errors go up unchanged. + +Rules of `decode_object` (world coordinates, no other change of values): + +| `object_type` | Result | +|---|---| +| `Points` | `Vectors` when `property_groups` has an entry with the role `orientation` or `lineation`; else `Points`. | +| `Curve` | `Lines(vertices, segments, ...)` | +| `Surface` | `Surface(vertices, triangles, ...)` | +| `BlockModel` | `BlockModel(origin = params["origin"] + origin, cell_sizes = params["cell_sizes"], cells = params["cells"], ...)` | +| `TetraMesh` | `TetraMesh(vertices, tetrahedra, ...)` | +| `Drillhole` | `Drillhole(collar + origin, survey, intervals, end_of_hole = params["end_of_hole"][0] when present, ...)` | +| any other (`Grid2D`, `GeoImage`, `Group`) | `UnsupportedObjectError(id, object_type)` | + +- `origin` is `None` or three numbers; `None` means `(0, 0, 0)`. The `vertices` and + `collar` are computed in float64: `array.astype(float64) + origin`. The result is + float64. This is the only dtype change: the viewer holds f32 relative to the origin, + and the sum in f64 is the world coordinate. +- Property rules, for each entry of `object["data"]` (the name is `name`; the values are + the array of `buffer`): + - Association `vertex` goes to `properties`. Association `cell` goes to + `cell_properties`, except for a Drillhole, where `cell` and `interval` (with no + `log_set`, or with the first interval log set) go to `interval_properties`. For + `Points` or `Vectors`, an association `cell` gives `UnsupportedObjectError`. + - A property of another log set of a Drillhole, a property with the association `sample` + or `object`, and any other association are dropped. The function calls + `warnings.warn("loop_link dropped the property '' of object '': ", + UserWarning, stacklevel=2)` one time for each (OP10). + - Types: `data_type` `float` keeps the stored dtype (f32 stays f32, f64 stays f64); + `integer` gives int32; `boolean` gives `numpy.bool_` (`values != 0`); `text` gives a + numpy `U` array (decode each item as UTF-8 from the data and the `offsets` arrays); + `referenced` gives `Categorical(codes, names, colours)`: `names` are the `name` fields + of `value_map` ordered by `id`; the codes are renumbered with a lookup when the ids + are not `0..n-1`; a code that is not in `value_map` gives `InvalidInputError`; + `colours` are the `colour` lists as 4-tuples (alpha 255 when a list has 3 values). + - Vectors: for each entry of `property_groups` with the role `orientation` (members + `dip_direction`, `dip`) or `lineation` (members `trend`, `plunge`), the member arrays + (as float64) form the tuple `orientation` or `lineation`. The member arrays are not + in `properties`. + +### Viewer (`viewer.py`) + +New members (the code of the data connection does not change): + +```python +class Viewer: + @property + def tool_connected(self) -> bool + def select(self, object_id: str, *, cells: Optional[ArrayLike] = None, + vertices: Optional[ArrayLike] = None, + revision: Optional[int] = None) -> dict[str, int] + def selection(self) -> Selection + def watch_selection(self, callback: Callable[[Selection], None], *, + interval: float = 0.5, initial: bool = False) -> SelectionWatcher + def fetch(self, id: str, *, progress: Optional[Callable[[float], None]] = None, + cancel: Optional[threading.Event] = None) -> FetchResult +``` + +- The `Viewer` makes its `ToolConnection` at the first call of `select`, `selection`, + `watch_selection` or `fetch`, with the same `port`, `token`, `host`, `settings_dir` and + `timeout`. These calls do not open the data connection. So a program that gets + `BusyError` from `connect` or `send` can still select, read and fetch (FR-014). + `release_data` does not close the tool connection. `close` stops all watchers, closes + the tool connection and marks the viewer closed. A later tool call raises + `ViewerClosedError`, as `send` does. +- `select(object_id, cells, vertices, revision)`: `object_id` must be a non-empty `str`. + At least one of `cells`, `vertices` must not be `None`, else `InvalidInputError("Give + cells or vertices. Use an empty list to clear the selection.")`. Each given array must + be a 1-D sequence of integers from 0 to 2**32 - 1 (no float, no bool, no negative + value), else `InvalidInputError` that names the argument. The call sends one + `selection.set` frame (all indices in one message, SC-003). It returns + `{"cell": n, "vertex": m}` with the counts of the reply (only the kinds that the reply + has). Empty lists clear the selection. When the viewer refuses the call, the selection + does not change. +- `selection()` sends `selection.get` and returns a `Selection`. +- `watch_selection(callback, interval, initial)`: `interval` must be more than 0, else + `InvalidInputError`. The call first reads the selection in the calling thread, so + `MissingFeatureError` and `ViewerClosedError` go to the caller. When `initial` is true + and this first selection is not empty, the callback is called once with it. Then the + call starts the `SelectionWatcher` thread. The `Viewer` keeps a list of its watchers. +- `fetch(id, progress, cancel)` calls `fetch.fetch_object(...)` on the tool connection. + `progress` gets a float from 0 to 1. `cancel` is a `threading.Event`; when it is set, + the fetch stops and raises `CancelledError`. An unknown id gives `InvalidInputError` + (the viewer reply `invalid_input`, field `id`). + +### Fake viewer changes (`testing/fake_viewer.py`) + +The tool endpoint answers the 1.18 messages. New constructor arguments (all have +defaults, so no S1 to S3 test changes): `protocol_minor: int = 18` (a value below 18 +makes each selection or fetch message get an `error` frame with the code +`unknown_message`), `part_bytes: int = 64 * 1024 * 1024` (the largest part; it must be a +multiple of 8), `fetch_delay: float = 0.0` (the pause after each part; it makes a cancel +test possible). `kind="headless"` (it exists) makes `selection.set` and `selection.get` +answer `request.error` with `needs_window`. New members: + +- `.selection` (property): the current selection as `{"object": str, "revision": int, + "cells": list[int], "nodes": list[int]}`, or `None`. +- `.set_user_selection(object_id: str, *, cells=None, nodes=None) -> None`: it simulates a + selection that the user made in the window. It uses the checks of `selection.set`. +- `.tool_requests` (list of `Frame`): each tool frame that arrived, for tests. + +Rules of the fake tool endpoint (they follow spec 067; the real viewer is the +authority, and manual check M3 repeats them): + +- `selection.set`: an unknown object gives `invalid_input` (field `object`). A `revision` + that is not the current revision gives `invalid_input` (field `revision`). An object + with no table (the types `Drillhole` and `Group`, see OP12), or a kind that the object + lacks (`Points` has `nodes` only), gives `invalid_input` (field `kind`). An index at or + above the element count gives `invalid_input` (field `indices`). A buffer that is not + `u32`, or is not in the frame, gives `invalid_input` (field `indices`). Counts: nodes + are the vertex count (a BlockModel has `(nx+1)(ny+1)(nz+1)`); cells are the segments, + triangles, tetrahedra, or `nx*ny*nz`. A repeated index counts one time. The new + selection replaces the old one, also when the old one is on another object. An empty + `entries` list clears it. The reply has `object`, `revision`, and `entries` with `kind` + and `count`. +- `selection.get`: the reply has `object`, `revision`, and one entry for each kind that + has indices, with a `u32` buffer named `cells` or `nodes`. With no selection the reply + has `"entries": []`. +- `object.fetch`: an unknown id gives `invalid_input` (field `id`). Else the fake sends + `object.header` (`origin` and `crs` of the fake, the stored header of the object with + `buffers: []`, and `arrays` = the stored buffers), then `object.part` frames of at + most `part_bytes` for each array in order, then `object.end`. When there is more than + one part, a `command.progress` frame (`fraction`, `text`) follows each part. After + each part the fake reads for at most 0.001 s. When it finds a `command.cancel` with the + same `request`, it sends `request.error` with the code `cancelled` and stops. A fetch + does not change the selection or the objects. + +### Files (S5) + +- `packages/loop_link/src/loop_link/errors.py` - Change. The three new errors. +- `packages/loop_link/src/loop_link/protocol.py` - Change. `TOOL_PROTOCOL_VERSION`, + `CANCEL_PROTOCOL_VERSION`, `encode_frame(..., version=None)`. +- `packages/loop_link/src/loop_link/encode.py` - Change. The four frame builders. +- `packages/loop_link/src/loop_link/tool.py` - Create. `ToolConnection`, + `raise_for_request_error`. +- `packages/loop_link/src/loop_link/selection.py` - Create. `Selection`, + `parse_selection_result`, `SelectionWatcher`. +- `packages/loop_link/src/loop_link/fetch.py` - Create. `FetchResult`, `fetch_object`, + `decode_object`, `_Assembler`. +- `packages/loop_link/src/loop_link/viewer.py` - Change. The new members. +- `packages/loop_link/src/loop_link/__init__.py` - Change. The new exports. +- `packages/loop_link/src/loop_link/testing/fake_viewer.py` - Change. The tool endpoint. +- `packages/loop_link/tests/test_tool.py` - Create. `ToolConnection` and each row of the + error table; request numbers; a late frame of an older request is dropped; progress; + cancel; the connection closes in the middle of a request; reconnect at the next + request; wrong token; no viewer; `unknown_message` with `protocol_minor=14`. +- `packages/loop_link/tests/test_selection.py` - Create. Story 2 scenarios 1 to 4; story 3 + scenarios 1 to 3; the clear rule and the duplicate rule; `cells` and `vertices` + together; `StaleRevisionError`; `needs_window` for `kind="headless"`; a selection of + 100,000 cells is one frame (SC-003: `fake.tool_requests` has one `selection.set` frame + with a `u32` buffer of shape `[100000]`); a selection that the user made + (`set_user_selection`); `watch_selection` (the callback runs once for a change and not + for no change, `initial`, `stop`, no thread before the call, the error of a callback + is in `.error`, a dropped `Viewer` ends the thread); FR-014 (program A holds the data + connection; program B gets `BusyError` from `send` but selects, reads and fetches; after + A calls `release_data`, B sends and the objects of A stay). +- `packages/loop_link/tests/test_fetch.py` - Create. `decode_object` for each row of the + table, each property rule, and each drop with its warning. The cases are built by hand + as a viewer writes them: an orientation group, a value map with ids that are not + `0..n-1`, text, boolean, a Drillhole with two log sets and a sample set, a non-zero + origin, `UnsupportedObjectError` for a `Group`. `_Assembler` with hostile frames: the + first frame is not a header; an array too large for the 2 GiB limit (a header only); + a part for an array that the header does not list; an offset that is not a multiple of + 8; a part past the end; a gap; an overlap; a missing part; a wrong `parts` count; a + `part` buffer that is not `u8`. A fetch of several parts (`part_bytes=64`) with + `progress` calls that rise. A cancel with `fetch_delay=0.05` gives `CancelledError` + and the scene stays the same. An unknown id gives `InvalidInputError`. A headless fake + still fetches. The revision is in the result. +- `packages/loop_link/tests/test_roundtrip.py` - Create. SC-002 and story 4 scenario 2: + for each of the seven types (and a `Vectors` made with `from_directions`), `send` then + `fetch`; compare with `numpy.testing.assert_allclose(rtol=1e-6)` for floats and + `array_equal` for integers, booleans, text, `Categorical` (codes, names, colours) and + index arrays; the dtype of each property stays; the coordinates are float64 world + coordinates for a scene with a non-zero origin and for a point 10 km from it. +- `packages/loop_link/tests/test_codec_real.py` - Change. Add the cases `selection.set` + (cells and nodes, with and without `revision`, with no entry), `selection.get`, + `object.fetch` and `command.cancel`, written by the new builders, and check that the + real codec accepts them (the helper and the negative control stay). +- `packages/loop_link/tests/test_fixtures.py` - Change. When `LOOP_LINK_GEOVIEWER_FIXTURES` + is set, read `/../tool/{selection.set,selection.get,object.fetch,command.cancel}.json` + (OP11). For each, build the frame with the `request`, `object` or `id`, `revision` and + indices of the fixture, and assert that the header equals the fixture (including + `version` and `buffers`). Skip with a reason when the variable or the folder is missing. +- `packages/loop_link/tests/test_fake_viewer.py` - Change. Add the rules of the fake tool + endpoint (one test for each row of the list above). +- `packages/loop_link/tests/manual_checks.md` - Change. Add M3 (see "Test strategy of S5"). +- `packages/loop_link/README.md` - Change. A short section "Select and fetch" with an + example of about 10 lines. +- `ROADMAP.md` - Change (last task of S5). Update the Stage 7 entry: S5 done. + +### Stages and rollback of S5 + +| Stage | Files and behaviour | Acceptance check | Rollback target and compatibility check | +|---|---|---|---| +| S5a | `errors.py`, `protocol.py`, `encode.py`, `tool.py`, `selection.py`, `viewer.py` (select, selection, watch_selection), `__init__.py`, fake viewer (selection part), `test_tool.py`, `test_selection.py`, `test_fake_viewer.py` | `packages/loop_link/.venv/Scripts/python.exe -m pytest packages/loop_link/tests`; `ruff check LoopStructural packages`; `black --check packages/loop_link`; FR-004, FR-005, FR-013 (selection part), FR-014 (tool part), SC-003 | Revert S5a. S1 to S3 do not use the new files. The new argument of `encode_frame` has a default that keeps the old frames. | +| S5b | `fetch.py`, `viewer.py` (fetch), fake viewer (fetch part), `test_fetch.py`, `test_roundtrip.py` | The same commands; FR-006, FR-013 (fetch part), SC-002 | Revert S5b. S5a stays. | +| S5c | `test_codec_real.py`, `test_fixtures.py`, `manual_checks.md` (M3), `README.md`, `ROADMAP.md` | The same commands with `LOOP_LINK_GEOVIEWER_REPO` and `LOOP_LINK_GEOVIEWER_FIXTURES` set; M3 by hand with the 067 viewer build | Revert S5c. | + +### Test strategy of S5 + +- Unit and regression tests: the files above. The fake viewer applies the rules of spec + 067, as the S1 fake applies the rules of the codec. +- Integration and compatibility: the real geoviewer codec checks the frames that the + library writes (`test_codec_real.py`, needs `LOOP_LINK_GEOVIEWER_REPO`). The fixtures + of `fixtures/protocol/tool` check the headers (`test_fixtures.py`). +- Manual check M3 (real window viewer built from geoviewer spec 067): + 1. Send a `BlockModel` of 10 x 10 x 10 cells. Select cells 12, 13 and 14 with + `Viewer.select`. Check that the viewer outlines three cells and that + `Viewer.selection()` returns them. + 2. Select cells in the window with the mouse. Read them with `Viewer.selection()`. + 3. `select` with an index of 5000 gives `InvalidInputError`, and the selection stays. + 4. Send, replace, then `select` with the old revision. It gives `StaleRevisionError`. + 5. Fetch each of the seven types back and compare with the original (the script of M2 + plus `fetch`). + 6. Fetch a drillhole that the viewer imported. Check the warning for the log sets that + the library drops. + 7. Start `watch_selection`. Change the selection in the window. Check that the callback + runs once. + 8. Start a second program that sends. Check that it gets `BusyError` while the first + program still selects and fetches. + M3 checks the points that the fake viewer assumes (OP12, OP13), and the order of the + parts of a fetch (OP14). Record the time of a fetch of 1,000,000 cells (no limit). +- Backend coverage and cross-language fixtures: as in the main "Test strategy". +- Performance: SC-002 has no time limit. +- Merge gates: as in the main "Test strategy". + +### Constitution check for S5 + +All rows of the table above hold for S5. The differences: the new files are under +`packages/loop_link` only; docstrings and type hints follow the same rules (`D` and +`ANN` apply to `src`); the ROADMAP entry is updated in the last task; each stage is a +separate revert. ## Test strategy @@ -567,9 +1090,8 @@ calls `progress` on the thread that calls it. The plugin runs it on a worker thr that the fake refuses (SC-004). It also encodes the plugin test objects and compares header and buffers to the `.bin` frames. It skips with a reason when the variable is missing (OP8). No public API of `GeologicalModel` is touched. -- **Round-trip tests**: not applicable in this plan (fetch is S5). The fake viewer - keeps the received frames, so `test_viewer.py` compares the stored arrays with - the input. +- **Round-trip tests**: S1 to S3 compare the arrays that the fake viewer stored with + the input (`test_viewer.py`). S5 adds `test_roundtrip.py` (send, then fetch). - **Backend coverage**: the library has one backend (stdlib sockets). S2 tests need pyvista, `loop_common` and pandas; each test file uses `pytest.importorskip`, and the CI `tests` extra installs them (`tests = ["pytest", "pyvista", @@ -724,17 +1246,17 @@ discovery, object model, `Viewer`, adapters, plugin push API, fake viewer. | FR-001 | "Functions and public API", `discovery.py` | `test_discovery.py`; story 1 scenario 1 in `test_viewer.py` | None | | FR-002 | `objects.py`, `encode.py` (type table) | `test_encode.py`, `test_viewer.py` (seven types) | None | | FR-003 | `Viewer.send` revision rule | `test_viewer.py` scenario 2 | None | -| FR-004 | Select by id and index | none in this plan | OP7 (S5) | -| FR-005 | Read selection and poll | none in this plan | OP7 (S5) | -| FR-006 | Fetch | none in this plan | OP7 (S5) | +| FR-004 | `Viewer.select`, `encode.selection_set_frame` (S5a) | `test_selection.py`, `test_codec_real.py`, `test_fixtures.py` | None (OP12, OP13 are viewer facts that M3 checks) | +| FR-005 | `Viewer.selection`, `Viewer.watch_selection`, `SelectionWatcher` (S5a) | `test_selection.py` (poll once for a change, interval, no thread before the call) | None | +| FR-006 | `Viewer.fetch`, `fetch.py` (S5b) | `test_fetch.py`, `test_roundtrip.py` | OP10 (a drillhole with several log sets loses the extra sets, with a warning), OP14 | | FR-007 | `import loop_link` has no Qt; `push.py` has no Qt | `test_import.py` | None | | FR-008 | `errors.py`; each edge case maps to one class (token: `TokenError`; no viewer: `NoViewerError`; too large: `ObjectTooLargeError`; closed: `ViewerClosedError`; bad property: `InvalidInputError`; busy: `BusyError`; older viewer: `MissingFeatureError`; origin differs: handled by conversion, not an error) | `test_viewer.py`, `test_encode.py`, `test_discovery.py` | None for S1 to S3. The older-viewer case for select and read is S5 (OP7). | | FR-009 | `push.py` (`push_objects`, `PushResult`) | `test_push.py` | None. The plugin change is in the plugin repository. | | FR-010 | `adapters/` | `test_adapter_*.py` | OP3 (pyvista to Drillhole); OP9 (non-regular grids) | | FR-011 | `orientation.py`, `Vectors` | `test_orientation.py`; story 1 scenario 6 | None | | FR-012 | One codec in `protocol.py` and `encode.py`; core imports numpy and the standard library only; adapters are extras | `test_import.py`; `test_protocol.py` | None | -| FR-013 | Missing feature detect for 066 | none in this plan | OP7 (S5) | -| FR-014 | `Viewer.release_data`, `BusyError`, keepalive thread. The tool connection part (select, read, fetch, filter, colour while busy) is S4 and S5. | `test_viewer.py` scenario 7 (send part) | OP6, OP7 for the tool connection part | +| FR-013 | `unknown_message` of the tool connection gives `MissingFeatureError` (`raise_for_request_error`) | `test_tool.py`, `test_selection.py` (`protocol_minor=14`) | None | +| FR-014 | `Viewer.release_data`, `BusyError`, keepalive thread; the tool connection (S5) for select, read and fetch while another program holds the data connection. Filter and colour use the same tool connection (S4). | `test_viewer.py` scenario 7 (send part); `test_selection.py` (tool part) | OP6 for filter and colour | | FR-015 | `testing/fake_viewer.py` | `test_viewer.py`, `test_fixtures.py` | None | | FR-016 | "Repository registration" | `git grep -n loop_link ROADMAP.md .release-please-config.json` gives 2 entries or more | None | | FR-017 | `pyproject.toml` (`>=3.10`), `ruff.toml` (py310) | `ruff check` and CI on 3.10 to 3.12 | OP4 (QGIS Python), OP5 (uv) | @@ -743,13 +1265,16 @@ discovery, object model, `Viewer`, adapters, plugin push API, fake viewer. | FR-020 | Colour | none in this plan | OP6 (S4) | | FR-021 | Colour in send | none in this plan | OP1, OP6 (S4) | | SC-001 | `test_performance.py`; M1 | assert under 5 s | None | -| SC-002 | Round trip | none in this plan | OP7 (S5) | -| SC-003 | Selection in one message | none in this plan | OP7 (S5) | +| SC-002 | `fetch.py`, `Viewer.fetch` | `test_roundtrip.py` (rtol 1e-6, seven types) | None | +| SC-003 | `encode.selection_set_frame` (one frame, one `u32` buffer) | `test_selection.py` (100,000 cells in one frame) | None | | SC-004 | `test_fixtures.py` | frames of `fixtures/protocol/python`; the geoviewer tests read the frames of the library in the geoviewer repository | OP8 | | SC-005 | `test_import.py`; CI matrix | `sys.modules` check | None | | SC-006 | "Repository registration" | `git grep` of two files | None | | SC-007 | Reply time of colour and filter | none in this plan | OP6 (S4) | | Story 1 scenarios 1 to 8 | `Viewer`, `discovery.py`, `test_viewer.py`, `test_import.py` | as above | None | +| Story 2 scenarios 1 to 4 | `Viewer.select`, errors table | `test_selection.py` | None | +| Story 3 scenarios 1 to 3 | `Viewer.selection`, `watch_selection`, `parse_selection_result` | `test_selection.py` | None | +| Story 4 scenarios 1 to 3 | `Viewer.fetch`, `decode_object` | `test_fetch.py`, `test_roundtrip.py` | None | | Story 5 scenarios 1 and 2 | `push.py`, `test_push.py` | frame comparison with plugin frames (OP8); worker thread test | OP8 | ## Handover @@ -776,11 +1301,16 @@ Other specs and repositories use these contracts. (`id`, `colour` RGB or `null`). The viewer answers `{"status":"done"}` or `{"status":"refused","text":...}`; the result has no count of passing elements, so the "count of elements that pass" of story 6 needs a check in the S4 plan. -- **S5** (select, read selection, fetch) uses the 066 messages `selection.set`, - `selection.get`, `selection.result`, `object.fetch`, `object.header`, - `object.part`, `object.end` of protocol 1.15. `MAX_INCOMING_BYTES` already - allows the 64 MiB parts. The helpers `orientation_to_normals` and - `lineation_to_directions` are for the fetch of vectors. +- **S5** (select, read selection, fetch) gives: `Viewer.select`, `Viewer.selection`, + `Viewer.watch_selection`, `Viewer.fetch`, `Selection`, `SelectionWatcher`, + `FetchResult`, the errors `StaleRevisionError`, `CancelledError` and + `UnsupportedObjectError`, and the fake viewer members `selection`, + `set_user_selection`, `tool_requests`. S4 (filter and colour) reuses + `loop_link.tool.ToolConnection`: `request(build, until=("command.result",), + feature=..., object_id=...)` with a frame builder for `command.run`, and + `raise_for_request_error` for the failures. The plugin can use `select`, + `selection` and `watch_selection` on a worker thread (the tool connection takes + one request at a time). - **geoviewer repository**: the frames that `encode_object` writes must pass the geoviewer protocol tests. The coordinator copies the frames to `fixtures/protocol/python` by hand when the fixtures change (OP8). diff --git a/specs/006-loop-link/tasks.md b/specs/006-loop-link/tasks.md index 5702d68e5..a3839bddc 100644 --- a/specs/006-loop-link/tasks.md +++ b/specs/006-loop-link/tasks.md @@ -3,8 +3,8 @@ **Feature**: `006-loop-link` | **Plan**: [plan.md](plan.md) +(stage S5, planned 2026-11-07, see "Design of stage S5"), and stories 6 and 7 (stage S4, +planned 2026-11-08, see "Design of stage S4"). --> ## Open points Each point has a default. A point that has no owner is for the maintainer. -- **OP1**: The `[NEEDS CLARIFICATION]` mark of story 7, scenario 7 (FR-021). - The protocol 1.14 data array can carry `colour_map` (`name`, `range`, `clip`, - `scale`). So the map, the range and the scale can go in the send message. The - property that colours the object (active array) and the plain colour of the - object have no field in `scene.upsert`. The `style` field has no schema. Default - for S4: send the map, range and scale in `colour_map`, and send the active - array and the plain colour as follow-up commands (`colour.set_active`, - `object.set_colour`) on the tool connection, inside the same call. The S4 - task reads how the viewer applies `style` first. It blocks S4 only. S1 to S3 - do not use it. +- **OP1**: The `[NEEDS CLARIFICATION]` mark of story 7, scenario 7 (FR-021). Answered + 2026-11-08 (see "Answers"): all colour settings go as follow-up commands on the tool + connection, in the same call. The `scene.upsert` data array can carry `colour_map` + (`name`, `range`, `clip`, `scale`), but it has no field for the property that colours + the object or for the plain colour, so the follow-up commands are needed anyway. One + path is simpler than two. The user sees one call. - **OP2**: The default `crs` of `hello`. `Hello.crs` is a required string in the viewer. The viewer may refuse an empty text. Default: `Viewer(crs="")`, and the library keeps the CRS that the viewer answers in `Viewer.scene_crs`. Task T-S1 @@ -42,9 +38,8 @@ Each point has a default. A point that has no owner is for the maintainer. members, add `packages/loop_link` to `[tool.uv.workspace] exclude` (as `packages/loop_interpolation_core` is) and make the CI job install it with `pip install -e packages/loop_link[tests]`. -- **OP6**: Stories 6 and 7 (filter and colour, FR-018 to FR-021, SC-007) need the - tool connection. Default: plan them in a later planner run as stage S4. The - names of the commands are in "Handover". +- **OP6**: Stories 6 and 7 (filter and colour, FR-018 to FR-021, SC-007) are planned in + stage S4 (see "Design of stage S4"). They use the tool connection of S5. - **OP7**: Stories 2, 3 and 4 (select, read selection, fetch) are planned in stage S5 (see "Design of stage S5"). They use geoviewer spec 067-selection-and-fetch (protocol 1.18), merged in the geoviewer repository. The text of this spec and of @@ -86,6 +81,37 @@ Each point has a default. A point that has no owner is for the maintainer. otherwise. M3 checks it with the real viewer. If the real viewer sends the parts in another order, relax the rule to "each byte is filled one time" (one task). +- **OP15**: FR-019 asks the call to wait for the end of a filter build. The viewer gives + no signal for it: `filter.edit` is not a long command, it sends no `command.progress`, + and it answers when the edit is accepted. Default (stage S4d): `wait=True` sends the + edits, then sends the same `set_on` edit again until the viewer takes it without `busy`. + A command that waits when busy waits for the end of the build, so this works only if the + scene is busy while the filter builds and a repeated `set_on` does not start a new build. + Both are unverified. M4 step 7 checks them. If a point fails, the fallback is to leave + `wait` out and to ask the geoviewer maintainer for a long `filter.edit` with progress. The + cancel part of FR-019 (`cancel_filter`) does not depend on this. Owner: spec owner. + Blocks S4d only. +- **OP16**: The viewer does not say if `add` for an array that has a filter is an error, or + if a new filter is on after `add` and `set_range`. Default: the library sends `add`, + goes on if it is refused, and sends `set_on` true at the end. M4 step 9 checks it. +- **OP17**: A value filter takes the `u32` ids of the value map. Story 6 scenario 2 says "the + values to show" and does not say if the user gives names. Default: S4 takes ids + (integers). The library keeps no value map of the objects it sent. A later stage can add + `names=`. Owner: spec owner. Blocks no task. +- **OP18**: The type rules (a filter on a text property, a map on a category) are assumed to + give `refused` with a text. If the real viewer accepts them without a change, scenario 4 + of story 6 and scenario 5 of story 7 fail against the real viewer. M4 steps 4 and 6 check + it. The fix would then be a type check in the library, which needs the types of the + properties (a fetch), or a viewer change. +- **OP19**: `send(..., colour=...)` waits 0.5 s (`flush`) before the colour commands. A + large object can take longer to enter the scene, and the first colour command then gets + an error for an unknown object. M4 step 8 checks it. If it fails, replace the fixed wait + by a retry for a time that the user sets. Owner: maintainer. Blocks no task. +- **OP20**: Story 6 says "the viewer reports the filter as on, with the count of elements + that pass". The viewer result has no count. S4 checks "filter on" with the fake + (`FakeViewer.filters`) and gives no count. The spec owner should change the sentence, or + ask for a count in the geoviewer result. Blocks no task. + ## Answers - 2026-11-06 (orchestrator, wave 10 review): pyvista adapter. The adapter skips the arrays that @@ -115,6 +141,11 @@ Each point has a default. A point that has no owner is for the maintainer. - 2026-11-07 (orchestrator, wave 11): `Viewer.select` always returns both keys, `{"cell": n, "vertex": m}`. A kind that the reply does not list has the count 0. This replaces "only the kinds that the reply has" in the text of "Viewer (`viewer.py`)" of stage S5. The tests of T048 check this shape. +- 2026-11-08 (planner, S4): OP1 is answered. `send(..., colour=ColourSettings(...))` sends the + object, waits with `flush()`, and then sends the colour commands (`colour.set_active`, + `colour.set_map`, `colour.set_range`, `colour.set_scale`, `object.set_colour`) on the tool + connection. The `colour_map` field of the data array is not used. The commands use the + protocol version 1.11 of the fixtures. ## Summary @@ -569,7 +600,7 @@ calls `progress` on the thread that calls it. The plugin runs it on a worker thr | S1 | New package: codec, errors, WebSocket, discovery, objects, orientation, encode, `Viewer`, fake viewer; repository registration (ROADMAP, release-please, CI, Ruff, uv). Inputs: the dataclasses and numpy arrays only. | `uv run --package loop-link pytest packages/loop_link/tests`; `ruff check LoopStructural packages`; root `pytest`; SC-001, SC-004 (with the variable), SC-005, SC-006; manual check M1 | Revert the stage: the files are new, and the root files change by added lines only. The root `pytest` result is the same as before. | | S2 | `adapters/` for pyvista, LoopStructural, pandas; `Viewer.send` calls `adapters.convert`. | The same commands. Adapter tests (pyvista, LoopStructural, pandas extras installed in the test environment). | Revert S2. S1 still sends the dataclasses. | | S3 | `push.py` and its tests; frame comparison with the plugin frames; the slow-viewer and cancel tests. | The same commands; SC-004 frames of the plugin. | Revert S3. S1 and S2 stay. | -| S4 | Not planned here (OP6). | | | +| S4 | Planned in "Design of stage S4": S4a (frames, commands module, fake commands), S4b (filter and colour members), S4c (colour in send), S4d (filter wait), S4e (real codec checks, manual check M4, docs). | See "Stages and rollback of S4". | See "Stages and rollback of S4". | | S5 | Planned in "Design of stage S5": S5a (tool connection and selection), S5b (fetch), S5c (real codec checks, manual check M3, docs). | See "Stages and rollback of S5". | See "Stages and rollback of S5". | ## Design of stage S5 (stories 2 to 4) @@ -1056,6 +1087,342 @@ All rows of the table above hold for S5. The differences: the new files are unde `ANN` apply to `src`); the ROADMAP entry is updated in the last task; each stage is a separate revert. +## Design of stage S4 (stories 6 and 7) + +Planned 2026-11-08, after S5 was built. S4 adds the filter calls and the colour calls. It +reuses the tool connection of S5 (`tool.py`). It needs no viewer change, except that the +list of colour map names (FR-020) needs a viewer of protocol 1.18 (geoviewer spec 067 gives +the names in the schema of `colour.set_map`; the text of this spec calls it "066"). + +### Facts that S4 uses (geoviewer `ui-fixes` build, read 2026-11-08) + +The facts come from `crates/geoviewer/src/tool/input_colour.rs`, `tool/result.rs`, +`tool/host.rs`, `tool/input_object.rs`, `fixtures/protocol/tool/` and `docs/protocol.md` +of the geoviewer repository. The real viewer is the authority. Manual check M4 repeats the +points marked "assumed". + +- A command goes on the tool connection (path `/tool`) in a `command.run` message: + `{"type": "command.run", "version": {"major": 1, "minor": 11}, "request": n, + "command": name, "input": {...}, "buffers": []}`. The fixtures use minor 11 for it. The + reply is `command.result` with `"result": {"status": ...}`, or `request.error`. +- `commands.list` (field `request` only) has the reply `commands`: `{"type": "commands", + "request": n, "viewer": "window" | "headless", "commands": [{"name", "description", + "needs_window", "tool_available", "unavailable_reason", "input_schema", + "result_schema"}]}`. +- The seven commands that S4 uses, with their input. Each input rejects an unknown field. + +| Command | Input | Note | +|---|---|---| +| `filter.edit` | `{"object": id, "edit": {"kind": ..., ...}}` | The kinds are in the next list. | +| `colour.set_active` | `{"id": id, "array": name}`; leave `array` out for no array | | +| `colour.set_map` | `{"id": id, "name": text}` | In a viewer of protocol 1.18 the schema of `name` is `{"type": "string", "enum": [...]}`. The names are `viridis`, `grey` and `coolwarm`. | +| `colour.set_range` | `{"id": id, "min": text, "max": text}` | The numbers are texts. | +| `colour.clear_range` | `{"id": id}` | | +| `colour.set_scale` | `{"object": id, "scale": "linear" or "log"}` | The key is `object`, not `id`. It needs a window. It does not wait when the scene is busy (the reply is `busy` at once). | +| `object.set_colour` | `{"id": id, "colour": [r, g, b] or null}` | `null` removes the plain colour. | + +- The edits of `filter.edit` (field `kind`): `add` (`array`), `set_range` (`array`, `min` + text, `max` text, `keep_nan` bool), `set_values` (`array`, `values`: list of `u32`, the + `id` values of the `value_map` of the array), `set_on` (`array`, `on` bool), + `set_exclude` (`array`, `exclude` bool), `remove` (`array`), `cancel` (no other field; + it cancels the running job). +- The result of each of these commands is `{"status": "done"}` or `{"status": + "refused", "text": ...}`. A filter edit that fails (for example an array that does not + exist) gives `refused` with a text. The result has no count of elements that pass. +- A command that "waits when busy" waits at most 5 s for a scene that is not busy, then + gets `request.error` with the code `busy`. All commands of the list above wait, except + `colour.set_scale`. +- `filter.edit` is not a long command: it sends no `command.progress`, and it answers when the + edit is accepted. The viewer builds the filter after that. No message tells the end of + the build (OP15). +- Assumed (M4 checks): a filter on a text property, a filter on a property that does not + exist, and a map, a range or a scale on a category or boolean property are `refused` + with a text. A new revision of an object keeps its filters and its colour settings. A + command for an unknown object gives `request.error` `invalid_input` or `refused`. +- The data array in `scene.upsert` can carry `colour_map` (`name`, `range`, `clip`, + `scale`). It has no field for the array that colours the object or for the plain + colour. See the answer of OP1 for the S4 decision. + +### Names and errors + +All new names below are free (checked with `git grep -n -w` on 2026-11-08). + +No new error class. S4 uses the errors of S5 and S1: + +| Reply | Library error | +|---|---| +| `command.result`, status `done` | none | +| `command.result`, status `refused`, with `text` | `InvalidInputError("The viewer refused the command '': ")` | +| `command.result`, any other status | `ProtocolError("The viewer sent an unknown result status ''.")` | +| `request.error` and `error` frames | `raise_for_request_error` (the table of S5). `needs_window` gives `MissingFeatureError`. `busy` gives `BusyError`. `invalid_input` gives `InvalidInputError`. | +| `error` frame, code `unknown_message` for `commands.list` or `command.run` | `MissingFeatureError("filter and colour commands (geoviewer protocol 1.11)")` | +| A map name that is not in the list of the viewer | `InvalidInputError("The viewer has no colour map ''. The names are: .")`, before any frame goes out | + +### Protocol changes (`protocol.py`, `encode.py`) + +```python +COMMAND_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 11} # protocol.py +def commands_list_frame(request: int) -> bytes # encode.py +def command_frame(request: int, command: str, input: Mapping[str, Any]) -> bytes +``` + +`commands_list_frame` writes `{"type": "commands.list", "request": n, "buffers": []}`. +`command_frame` writes `{"type": "command.run", "request": n, "command": command, +"input": dict(input), "buffers": []}`. Both use the version `COMMAND_PROTOCOL_VERSION`, so +a viewer of protocol 1.11 to 1.17 accepts them (FR-018: no viewer change). The header must +equal `fixtures/protocol/tool/commands.list.json` and `command.run.json` when the +arguments are the same. + +### Commands module (`commands.py`) + +```python +@dataclass(frozen=True) +class ColourSettings: + array: Optional[str] = None # property that colours the object + colour_map: Optional[str] = None # name of a map of the viewer + range: Optional[tuple[float, float]] = None # (minimum, maximum) + scale: Optional[str] = None # "linear" or "log" + plain: Optional[tuple[int, int, int]] = None # plain colour of the object + # A field that is None is not sent. __post_init__ calls the check functions below. + +def run_command(tool: ToolConnection, command: str, input: Mapping[str, Any], *, + object_id: Optional[str] = None, timeout: Optional[float] = None, + cancel: Optional[threading.Event] = None) -> Mapping[str, Any] +def list_colour_map_names(tool: ToolConnection) -> Optional[tuple[str, ...]] +def parse_colour_map_names(frame: Frame) -> Optional[tuple[str, ...]] +def raise_for_command_result(result: Mapping[str, Any], *, command: str) -> None +def format_number(value: float) -> str +def check_number(value: object, name: str) -> float +def check_text(value: object, name: str) -> str +def check_rgb(value: object, name: str) -> tuple[int, int, int] +def check_codes(values: object, name: str) -> list[int] +``` + +- `run_command` calls `tool.request(lambda n: encode.command_frame(n, command, input), + until=("command.result",), feature="filter and colour commands (geoviewer protocol 1.11)", + object_id=object_id, ...)`. It reads `frame.header["result"]`, calls + `raise_for_command_result`, and returns the result mapping. A result that is not a + mapping with a `status` text gives `ProtocolError`. +- `list_colour_map_names` calls `commands_list_frame` with `until=("commands",)` and returns + `parse_colour_map_names(frame)`. +- `parse_colour_map_names` finds the entry with `name == "colour.set_map"`. It reads + `input_schema["properties"]["name"]["enum"]`. It returns the tuple of names. It returns + `None` when the entry, the property or the `enum` is missing (a viewer older than 1.18). A + malformed field (the `enum` is not a list of text) gives `ProtocolError`. +- `format_number(value)` returns `repr(float(value))` (for example `"0.5"` or `"1e-05"`). +- `check_number` accepts `int` and `float` (and numpy numbers) that are not `bool` and not + NaN or infinite, and returns `float`. Other input gives `InvalidInputError` that names + `name`. `check_text` accepts a non-empty `str`. `check_rgb` accepts three integers from 0 + to 255 (not `bool`). `check_codes` accepts a sequence or array of integers from 0 to + 2**32 - 1 (not `bool`, not float) and returns a `list[int]`. + +### Viewer (`viewer.py`) + +New members. They use the tool connection of S5 (`self._tool()`), so they work while another +program holds the data connection (FR-014). They do not open the data connection. Each one +raises `InvalidInputError` for a wrong argument before any frame goes out. + +```python +class Viewer: + def filter_range(self, object_id: str, array: str, minimum: float, maximum: float, *, + keep_nan: bool = False, wait: bool = True, + cancel: Optional[threading.Event] = None, timeout: float = 60.0) -> None + def filter_values(self, object_id: str, array: str, values: ArrayLike, *, + exclude: bool = False, wait: bool = True, + cancel: Optional[threading.Event] = None, timeout: float = 60.0) -> None + def filter_enable(self, object_id: str, array: str, on: bool = True) -> None + def filter_remove(self, object_id: str, array: str) -> None + def cancel_filter(self, object_id: str) -> None + def colour_map_names(self) -> tuple[str, ...] + def set_colour_property(self, object_id: str, array: Optional[str]) -> None + def set_colour_map(self, object_id: str, name: str) -> None + def set_colour_range(self, object_id: str, minimum: float, maximum: float) -> None + def clear_colour_range(self, object_id: str) -> None + def set_colour_scale(self, object_id: str, scale: str) -> None + def set_object_colour(self, object_id: str, colour: Optional[tuple[int, int, int]]) -> None + def apply_colour(self, object_id: str, settings: ColourSettings) -> None + # send() gets one new keyword-only argument, before **hints: + # colour: Optional[ColourSettings] = None +``` + +Filter rules (each call sends the edits in the order shown, with `run_command`; the first +refusal stops the call and raises): + +- `filter_range`: `add`, `set_range` (`min` and `max` are `format_number` texts, `keep_nan`), + `set_on` with `on` true. `minimum` must not be more than `maximum`, else + `InvalidInputError`. If `add` is refused, the call goes on with `set_range` (OP16: the + filter can exist already). If `set_range` is refused, its text goes up. +- `filter_values`: `add` (the same refusal rule), `set_values` (the codes from + `check_codes`), `set_exclude` (`exclude`), `set_on` true. The codes are the `id` values of + the `value_map` of the property. A `Categorical` that the library sent has the ids + `0..n-1` in the order of its names (OP17: names as input are a later stage). +- `filter_enable`: one `set_on` edit. `filter_remove`: one `remove` edit. `cancel_filter`: + one `cancel` edit. +- `wait` is true by default and is stage S4d. In S4a to S4c the argument exists, and a + true value is accepted and does nothing more than return when the viewer accepted the + edits. S4d adds the wait (OP15). `cancel` and `timeout` are used only by the wait. + +Colour rules: + +- `colour_map_names()` returns the names from `list_colour_map_names`. It keeps the tuple + for the life of the tool connection. If the result is `None`, it raises + `MissingFeatureError("colour map names (geoviewer protocol 1.18)")`. +- `set_colour_map(object_id, name)`: `name` must be a non-empty `str`. The method reads the + names. When the viewer gives names and `name` is not one of them, it raises the error of + the table above. When the viewer gives no names (older viewer), it sends the name and + the viewer decides. It sends `colour.set_map` `{"id", "name"}`. +- `set_colour_property`: `colour.set_active` `{"id", "array"}`. With `array=None` the key + `array` is left out (no property). +- `set_colour_range`: `colour.set_range` `{"id", "min", "max"}` with `format_number` texts. + `minimum` must be less than `maximum`. `clear_colour_range`: `colour.clear_range`. +- `set_colour_scale`: `scale` must be `"linear"` or `"log"`, else `InvalidInputError`. + It sends `colour.set_scale` `{"object", "scale"}`. +- `set_object_colour`: it sends `object.set_colour` `{"id", "colour"}` with the list + `[r, g, b]` (from `check_rgb`) or `null`. +- `apply_colour(object_id, settings)`: it sends, in this order, `colour.set_active`, + `colour.set_map`, `colour.set_range`, `colour.set_scale`, `object.set_colour`, each one + only when its field is not `None`. It checks all fields before it sends any frame. +- `send(..., colour=settings)`: the call sends the object as before. When `colour` is not + `None`, it then calls `self.flush()` (this waits 0.5 s for a late refusal of the object + and raises it), and then `self.apply_colour(id, settings)`. If a colour command fails, + the object is already in the viewer, and the error goes up. The user can call the + `set_colour_*` methods later. The send returns the revision as before. + +### Fake viewer changes (`testing/fake_viewer.py`) + +New constructor arguments, all with defaults, so no earlier test changes: +`filter_delay: float = 0.0` (the seconds that the scene stays busy after a `filter.edit` +that changes a filter) and `busy_wait: float = 5.0` (the seconds that a waiting command +waits before `busy`; tests set it to 0.05). New members: `.filters` (property): a +`dict[str, dict[str, dict]]`, by object id and array name, with the keys `kind` (`"range"` +or `"values"`), `on`, `minimum`, `maximum`, `keep_nan`, `values`, `exclude`; `.colouring` +(property): a `dict[str, dict]` by object id with the keys `array`, `colour_map`, +`range`, `scale`, `plain`. Both return copies. + +Rules of the fake tool endpoint (they follow the facts above; the real viewer is the +authority and M4 repeats them): + +- `commands.list` answers `commands` with `viewer` = `self.kind` and one entry for each + command of the table (and no other). `needs_window` is true only for `colour.set_scale`. + `input_schema` of `colour.set_map` has `properties.name.enum` = `["viridis", "grey", + "coolwarm"]` when `protocol_minor >= 18`, and `properties.name.type` = `"string"` only + below 18. With `protocol_minor < 11` the endpoint answers `unknown_message`. +- `command.run` of an unknown command: `request.error` `invalid_input`, field `command`. + An input with an unknown or a missing field, or a field of a wrong type (the key and type + rules of the table above), gives `request.error` `invalid_input` with that field. An + object that does not exist gives `request.error` `invalid_input`, field `id` (or + `object` for the two commands that use that key). `kind="headless"` gives `needs_window` + for `colour.set_scale` only. +- A command that waits: while the scene is busy (the time `filter_delay` after a filter + edit), each command except `colour.set_scale` waits up to `busy_wait` seconds. Then it + runs, or it gets `request.error` `busy` when the scene is still busy. `colour.set_scale` + gets `busy` at once. `filter.edit` with `cancel` ends the busy time. +- Property rules, from the header of the stored object (`data` entries: `name`, + `data_type`, `association`): a filter on an array that does not exist, or on a `text` + array or an `object` association array, is `refused` with a text that names the array. A + range edit on a `referenced` or `boolean` array, and a values edit on a number array, + are `refused`. `colour.set_active` with an unknown array is `refused`. `colour.set_map`, + `colour.set_range` and `colour.set_scale` on an object whose active array is `referenced` + or `boolean` are `refused`. These rules are assumed from the spec (OP18). +- Effects: `add` creates an off filter. `set_range`, `set_values`, `set_exclude` and + `set_on` change it (a missing filter is `refused`). `remove` deletes it. A + `scene.upsert` of an object that already exists keeps its `filters` and `colouring` + (story 6, scenario 6). When the new revision has no array of that name, the fake drops + the filter of that array. +- The reply is `command.result` `{"status": "done"}` or `{"status": "refused", "text": + ...}`, with the same `request` number. + +### Files (S4) + +- `packages/loop_link/src/loop_link/protocol.py` - Change. `COMMAND_PROTOCOL_VERSION`. +- `packages/loop_link/src/loop_link/encode.py` - Change. `commands_list_frame`, `command_frame`. +- `packages/loop_link/src/loop_link/commands.py` - Create. The names of "Commands module". +- `packages/loop_link/src/loop_link/viewer.py` - Change. The new members and the `colour` + argument of `send`. +- `packages/loop_link/src/loop_link/__init__.py` - Change. Export `ColourSettings`. +- `packages/loop_link/src/loop_link/testing/fake_viewer.py` - Change. The commands endpoint. +- `packages/loop_link/tests/test_commands.py` - Create. The frame builders (header + equal to the two fixtures when the arguments are the same), `check_*` functions, + `raise_for_command_result` for each row of the table, `parse_colour_map_names` (with + names, without names, malformed), `ColourSettings`. +- `packages/loop_link/tests/test_filter.py` - Create. Story 6 scenarios 1 to 4 and 6: + range, values with exclude, off, on and remove (data does not change: the stored object + stays the same), a missing array, a text array, `minimum > maximum`, a new revision keeps + the filters, `add` refused and the call goes on, `cancel_filter`; the viewer without + window; an old viewer (`protocol_minor=10`) gives `MissingFeatureError`; the tool part of + FR-014 (program A holds the data connection; program B filters and colours). S4d adds the + tests of the wait. +- `packages/loop_link/tests/test_colour.py` - Create. Story 7 scenarios 1 to 7: property, + no property, map, range, clear, scale, plain colour, a category and a boolean property + (`InvalidInputError` with the viewer text), an unknown map name (the error lists the + names, and the fake received no `colour.set_map`), an older viewer without names, + `colour_map_names`, `send(..., colour=...)` (the object is in the fake before the + commands, the commands arrive in the order of `apply_colour`, a failed command leaves the + object in the viewer), the headless viewer for `set_colour_scale`. SC-007: with an object + of 1,000,000 cells, each of the commands of the table gets its reply in less than 250 ms. +- `packages/loop_link/tests/test_fake_viewer.py` - Change. One test for each rule of the + fake commands endpoint. +- `packages/loop_link/tests/test_codec_real.py` - Change. Add `commands.list` and + `command.run` for `filter.edit` (each kind) and each colour command; the real codec + accepts them. +- `packages/loop_link/tests/test_fixtures.py` - Change. When `LOOP_LINK_GEOVIEWER_FIXTURES` + is set, read `/../tool/{commands.list,command.run}.json` (OP11). Build the + frames with the `request`, `command` and `input` of the fixtures, and assert that the + headers are equal. Skip with a reason when the folder is missing. +- `packages/loop_link/tests/manual_checks.md` - Change. Add M4 (see "Test strategy of S4"). +- `packages/loop_link/README.md` - Change. A section "Filter and colour", about 10 lines. +- `ROADMAP.md` - Change (last task of S4). Update the Stage 7 entry: S4 done. + +### Stages and rollback of S4 + +| Stage | Files and behaviour | Acceptance check | Rollback target and compatibility check | +|---|---|---|---| +| S4a | `protocol.py`, `encode.py`, `commands.py`, fake viewer (commands endpoint), `test_commands.py`, `test_fake_viewer.py` | `packages/loop_link/.venv/Scripts/python.exe -m pytest packages/loop_link/tests`; `ruff check LoopStructural packages`; `black --check packages/loop_link` | Revert S4a. Nothing else uses the new names. | +| S4b | `viewer.py` (filter and colour members, no wait, no `send` argument), `__init__.py`, `test_filter.py`, `test_colour.py` | The same commands; FR-018, FR-020, FR-014 (tool part), SC-007 | Revert S4b. S4a stays. | +| S4c | `viewer.py` (`colour` argument of `send`, `apply_colour` use), tests in `test_colour.py` | The same commands; FR-021 | Revert S4c. The default `colour=None` keeps the old `send`. | +| S4d | `viewer.py` (the wait of `filter_range`, `filter_values`), tests in `test_filter.py` | The same commands; FR-019. Blocked by OP15 and by step 7 of M4 | Revert S4d. `wait=True` goes back to "return when accepted". | +| S4e | `test_codec_real.py`, `test_fixtures.py`, `manual_checks.md` (M4), `README.md`, `ROADMAP.md` | The same commands with `LOOP_LINK_GEOVIEWER_REPO` and `LOOP_LINK_GEOVIEWER_FIXTURES` set; M4 by hand | Revert S4e. | + +### Test strategy of S4 + +- Unit and regression tests: the files above. The fake viewer applies the rules above, as the + S5 fake applies the rules of spec 067. +- Integration and compatibility: the real geoviewer codec checks the frames + (`test_codec_real.py`, needs `LOOP_LINK_GEOVIEWER_REPO`). The fixtures check the two + headers that exist (`test_fixtures.py`). +- Manual check M4 (real window viewer of protocol 1.18). Use a fresh scene (`Viewer.clear`) + and place test objects near the origin of the scene (M3 found that far objects give wrong + pictures): + 1. Send a `BlockModel` with a number property `grade`. Call `filter_range` for `grade` + from 0.5 to 1.0. Check that the viewer shows only the cells in the range. + 2. Send an object with a category property. Call `filter_values` with two codes, then with + `exclude=True`. Check the picture each time. + 3. Call `filter_enable(False)` and then `filter_remove`. Check that all cells show again. + 4. Call `filter_range` for a text property and for a property that does not exist. Check + the `InvalidInputError` and its text. + 5. Call `set_colour_property`, `set_colour_map` (`coolwarm`), `set_colour_range`, + `set_colour_scale("log")` and `set_object_colour`. Check the picture after each call. + 6. Call the colour map, range and scale methods for a category property. Check the error. + Call `colour_map_names()` and check that it gives the names of the viewer. + 7. Send the same id again (a new revision). Check that the filter and the colours stay. + Start a filter that takes time (an object with 1,000,000 cells), call `filter_range` + with `wait=False`, and check what a second command does while the viewer builds + (OP15). Call `cancel_filter` during the build. + 8. Send an object of 1,000,000 cells with `colour=ColourSettings(...)`. Check that the + colour settings apply (OP19: the 0.5 s of `flush` can be too short). + 9. Check the questions "assumed" in the facts: does `add` for an existing filter get + `refused` (OP16), and is a new filter on after `add` and `set_range`. + M4 records the time of one `set_range` command on the object of 1,000,000 cells. +- Backend coverage and cross-language fixtures: as in the main "Test strategy". +- Performance: SC-007 is a test with the fake viewer (a limit of 250 ms per command). +- Merge gates: as in the main "Test strategy". + +### Constitution check for S4 + +All rows of the table above hold for S4. The differences: the new files are under +`packages/loop_link` only; docstrings and type hints follow the same rules; the ROADMAP +entry is updated in the last task; each stage is a separate revert. + ## Test strategy - **Unit and regression tests** (`packages/loop_link/tests/`): @@ -1259,25 +1626,27 @@ discovery, object model, `Viewer`, adapters, plugin push API, fake viewer. | FR-011 | `orientation.py`, `Vectors` | `test_orientation.py`; story 1 scenario 6 | None | | FR-012 | One codec in `protocol.py` and `encode.py`; core imports numpy and the standard library only; adapters are extras | `test_import.py`; `test_protocol.py` | None | | FR-013 | `unknown_message` of the tool connection gives `MissingFeatureError` (`raise_for_request_error`) | `test_tool.py`, `test_selection.py` (`protocol_minor=14`) | None | -| FR-014 | `Viewer.release_data`, `BusyError`, keepalive thread; the tool connection (S5) for select, read and fetch while another program holds the data connection. Filter and colour use the same tool connection (S4). | `test_viewer.py` scenario 7 (send part); `test_selection.py` (tool part) | OP6 for filter and colour | +| FR-014 | `Viewer.release_data`, `BusyError`, keepalive thread; the tool connection (S5) for select, read and fetch while another program holds the data connection. Filter and colour use the same tool connection (S4b). | `test_viewer.py` scenario 7 (send part); `test_selection.py` (tool part); `test_filter.py` (filter and colour while another program holds the data connection) | None | | FR-015 | `testing/fake_viewer.py` | `test_viewer.py`, `test_fixtures.py` | None | | FR-016 | "Repository registration" | `git grep -n loop_link ROADMAP.md .release-please-config.json` gives 2 entries or more | None | | FR-017 | `pyproject.toml` (`>=3.10`), `ruff.toml` (py310) | `ruff check` and CI on 3.10 to 3.12 | OP4 (QGIS Python), OP5 (uv) | -| FR-018 | Filter | none in this plan | OP6 (S4) | -| FR-019 | Filter wait and cancel | none in this plan | OP6 (S4) | -| FR-020 | Colour | none in this plan | OP6 (S4) | -| FR-021 | Colour in send | none in this plan | OP1, OP6 (S4) | +| FR-018 | `Viewer.filter_range`, `filter_values`, `filter_enable`, `filter_remove`, `commands.run_command` (S4b) | `test_filter.py`, `test_codec_real.py`, `test_fixtures.py`; M4 steps 1 to 4 | OP16, OP17, OP18, OP20 | +| FR-019 | `Viewer.cancel_filter` (S4b); the `wait` argument (S4d) | `test_filter.py`; M4 step 7 | OP15 (the viewer gives no end signal) | +| FR-020 | `Viewer.set_colour_property`, `set_colour_map`, `set_colour_range`, `clear_colour_range`, `set_colour_scale`, `set_object_colour`, `colour_map_names` (S4b) | `test_colour.py`, `test_commands.py`; M4 steps 5 and 6 | OP18 | +| FR-021 | `ColourSettings`, `Viewer.apply_colour`, the `colour` argument of `Viewer.send` (S4c) | `test_colour.py`; M4 step 8 | OP19 | | SC-001 | `test_performance.py`; M1 | assert under 5 s | None | | SC-002 | `fetch.py`, `Viewer.fetch` | `test_roundtrip.py` (rtol 1e-6, seven types) | None | | SC-003 | `encode.selection_set_frame` (one frame, one `u32` buffer) | `test_selection.py` (100,000 cells in one frame) | None | | SC-004 | `test_fixtures.py` | frames of `fixtures/protocol/python`; the geoviewer tests read the frames of the library in the geoviewer repository | OP8 | | SC-005 | `test_import.py`; CI matrix | `sys.modules` check | None | | SC-006 | "Repository registration" | `git grep` of two files | None | -| SC-007 | Reply time of colour and filter | none in this plan | OP6 (S4) | +| SC-007 | `run_command` on the tool connection (S4b) | `test_colour.py` (each command under 250 ms with an object of 1,000,000 cells in the fake) | None | | Story 1 scenarios 1 to 8 | `Viewer`, `discovery.py`, `test_viewer.py`, `test_import.py` | as above | None | | Story 2 scenarios 1 to 4 | `Viewer.select`, errors table | `test_selection.py` | None | | Story 3 scenarios 1 to 3 | `Viewer.selection`, `watch_selection`, `parse_selection_result` | `test_selection.py` | None | | Story 4 scenarios 1 to 3 | `Viewer.fetch`, `decode_object` | `test_fetch.py`, `test_roundtrip.py` | None | +| Story 6 scenarios 1 to 6 | `Viewer.filter_*`, `cancel_filter`, the fake `filters` | `test_filter.py` (scenario 5 in S4d); M4 | OP15, OP16, OP17, OP18, OP20 | +| Story 7 scenarios 1 to 7 | `Viewer.set_colour_*`, `apply_colour`, `send(colour=)` | `test_colour.py`; M4 | OP18, OP19 | | Story 5 scenarios 1 and 2 | `push.py`, `test_push.py` | frame comparison with plugin frames (OP8); worker thread test | OP8 | ## Handover @@ -1292,18 +1661,14 @@ Other specs and repositories use these contracts. the old `PushResult.summary()`. The plugin builds `objects` as `(id, SceneObject)` pairs and runs the call on its worker thread. The plugin owns the change and the removal of the old client (FR-009). -- **S4** (filter and colour) uses: `WebSocketClient.connect(..., path="/tool")`; - the tool messages `commands.list`, `command.run`, `command.result`, - `request.error`, `command.cancel`, `command.progress`; the commands - `filter.edit` (input `{"object": id, "edit": {"kind": "set_range", "array": - name, "min": text, "max": text, "keep_nan": bool}}`; kinds `add`, `set_range`, - `set_values` with `values: list[u32]`, `set_on`, `set_exclude`, `remove`, - `cancel`), `colour.set_active` (`id`, `array`), `colour.set_map` (`id`, `name`), - `colour.set_range` (`id`, `min` text, `max` text), `colour.clear_range` (`id`), - `colour.set_scale` (`object`, `scale` `linear` or `log`), `object.set_colour` - (`id`, `colour` RGB or `null`). The viewer answers `{"status":"done"}` or - `{"status":"refused","text":...}`; the result has no count of passing elements, so - the "count of elements that pass" of story 6 needs a check in the S4 plan. +- **S4** (filter and colour) gives: `Viewer.filter_range`, `filter_values`, `filter_enable`, + `filter_remove`, `cancel_filter`, `colour_map_names`, `set_colour_property`, + `set_colour_map`, `set_colour_range`, `clear_colour_range`, `set_colour_scale`, + `set_object_colour`, `apply_colour`, the `colour` argument of `Viewer.send`, + `loop_link.commands.ColourSettings`, and the fake viewer members `filters` and + `colouring`. It uses the tool messages `commands.list`, `command.run`, `command.result` + and the commands of "Facts that S4 uses". The viewer result has no count of elements + that pass (OP20). - **S5** (select, read selection, fetch) gives: `Viewer.select`, `Viewer.selection`, `Viewer.watch_selection`, `Viewer.fetch`, `Selection`, `SelectionWatcher`, `FetchResult`, the errors `StaleRevisionError`, `CancelledError` and From 88ca4475236f4686ba510472b5fbca6a3be38603 Mon Sep 17 00:00:00 2001 From: lachlangrose Date: Sun, 8 Nov 2026 18:59:35 +1030 Subject: [PATCH 66/96] docs(spec): add S4 tasks T064 to T087 for 006-loop-link --- specs/006-loop-link/tasks.md | 250 +++++++++++++++++++++++++++++++---- specs/README.md | 2 +- 2 files changed, 222 insertions(+), 30 deletions(-) diff --git a/specs/006-loop-link/tasks.md b/specs/006-loop-link/tasks.md index 8b4dc6faa..c5757ee8d 100644 --- a/specs/006-loop-link/tasks.md +++ b/specs/006-loop-link/tasks.md @@ -3,8 +3,8 @@ **Feature**: `006-loop-link` | **Plan**: [plan.md](plan.md)