Trail map comparing the 2 m and 6 m marker positions when measured from the registered trailhead and from the opposite end.

Can You Trust the Direction of a Merged Route in Shapely?

Fri, Dec 4, 2026

A nine-metre trail can be geometrically valid, continuous and exactly the expected length and still put both published distance markers in the wrong place.

Take a synthetic trail from A through B and C to D. The approved trailhead is A. A marker at station 2 m should be at (2, 0), and station 6 m should be at (3, 3). Reverse the whole assembled line, however, and its length remains 9 m. It is still a perfectly usable LineString as geometry. Yet station 2 becomes (3, 4) and station 6 becomes (3, 0).

That is the distinction this release test is designed to protect.

For this article, a station is an absolute distance measured along one declared route direction from a separately registered station zero. It is linear referencing in a deliberately narrow sense: local two-dimensional projected metre coordinates, one open trail, no M values, no station equations and no survey calibration.

The publishing decision therefore has two independent questions. First, does the assembled geometry represent one continuous registered trail? Second, if it does, do distances increase from the approved origin toward the approved terminus?

Shapely can help answer the first question and expose some direction conflicts, but its merge operation does not consult an organisation's route register. The Shapely 2.1.2 line merge documentation explains that the ordinary merge may choose direction according to the majority direction of constituent lines, while directed=True refuses joins that require changing point order and requires GEOS 3.11.0 or later. The missing control is organisational: a separately maintained A-to-D registration against which the assembled line and its station coordinates can be tested.

Define the route contract and independent station-zero evidence

The route should be defined before a MultiLineString reaches line_merge. A useful release record for this fixture contains at least:

Field

Fixture value

Route ID

TRAIL-AD

Route revision

route-r1

Fixture revision

trail-A-D-r1

Origin

A

Terminus

D

Coordinate model

local Cartesian plane

Linear unit

metre

Approved part IDs

seg-AB, seg-BC, seg-CD

Legal station domain

[0, 9] m

Interior controls

2 m → (2,0); 6 m → (3,3)

Route-register owner

named trail-data owner

Publishing steward

named station-table publisher

The station table should carry enough lineage to reconstruct the decision: route_id, route_revision, station_revision, station distance, x, y, fixture or source revision, disposition and the release approval identifier. A coordinate without the route revision that generated it is insufficient evidence when an assembly is later quarantined.

Station zero comes from the route register, not from incidental geometry ordering. The smallest coordinate is not authoritative. The first feature returned by a data source is not authoritative. Neither is lexicographically sorted WKT, a feature ID, a shapefile row number or the first component returned by a merge.

For this fixture the independently authored route register says:

route_id: TRAIL-AD
route_revision: route-r1
origin_id: A
terminus_id: D
direction: A -> D
length_control_m: 9

That declaration is deliberately outside the geometry-building function. If the register is absent, contradictory or awaiting steward approval, the correct release disposition is hold, even if a merge returns one attractive-looking LineString. Geometry processing cannot manufacture authority over the trailhead.

The same distinction matters in larger pipelines: validity describes whether a representation satisfies a geometry model; route authority describes whether that representation corresponds to the approved business object. The two contracts overlap but are not interchangeable.

This demonstration also assumes the coordinates have already been accepted as local projected metres. CRS assignment and coordinate transformation are upstream responsibilities; see the separate guide on coordinate provenance before a geometry operation. Its concern is whether coordinates mean what their CRS metadata says they mean, whereas this article begins after that question has been resolved.

No roadway M values, geographic distances, geodesics, station equations, shortest paths or CRS conversions enter the test.

Freeze the source manifest, runtime and hand-calculated controls

The source evidence needs to survive every experiment. Do not “fix” the only copy of a segment and then ask later what was originally digitised.

Our immutable fixture is:

A = (0, 0)
B = (3, 0)
C = (3, 4)
D = (3, 6)
E = (6, 0)   # branch case only
G = (3, 1)   # gap case only

The baseline source manifest preserves original direction:

seg-AB: A -> B
seg-BC: B -> C
seg-CD: C -> D

The reference lengths are independent arithmetic, not measurements copied back from Shapely:

AB = sqrt((3-0)^2 + (0-0)^2) = 3 m
BC = sqrt((3-3)^2 + (4-0)^2) = 4 m
CD = sqrt((3-3)^2 + (6-4)^2) = 2 m

total = 3 + 4 + 2 = 9 m

Station 2 is two metres along AB from A, so its expected coordinate is (2, 0). Station 6 consists of all 3 m of AB plus another 3 m up the 4 m BC segment, so its expected coordinate is (3, 3). Terminal controls are station 0 = A = (0, 0) and station 9 = D = (3, 6).

Those values form an oracle independent of the operation under test. Using line_interpolate_point to produce both the “expected” value and the observation would only confirm that the function agrees with itself.

The asymmetry of the interior controls is useful. Reverse the completed route to D→A and the same absolute distances produce:

Station

Accepted A→D coordinate

Reversed D→A coordinate

2 m

(2, 0)

(3, 4)

6 m

(3, 3)

(3, 0)

The reversed 2 m point is C because CD is exactly 2 m long. The reversed 6 m point reaches B after 2 m of DC and 4 m of CB. Length alone therefore cannot discriminate between the accepted and globally inverted lines.

The runtime is also evidence. Shapely 2.1.2 states that directed merging requires GEOS 3.11.0 or later. The GEOS LineMerger development reference describes the underlying endpoint-oriented model: it sews fully noded linework, stops at nodes of degree 1 or degree 3 or more, and expects linework intersections to occur at endpoints; its displayed documentation is currently for a development tree, not evidence of the runtime loaded by Python.

A local execution performed for this article reported:

python=3.13.5
shapely=2.1.2
geos=3.13.1
geos_capi=3.13.1-CAPI-1.19.2

Those are observations from this particular run, not version requirements beyond the documented GEOS minimum. The separate C API check used the same versions (GEOS 3.13.1 and CAPI 1.19.2).

Create a disposable environment and reproduce the test as follows:

mkdir route-orientation-lab
cd route-orientation-lab

python -m venv .venv
source .venv/bin/activate        # Windows PowerShell: .venv\Scripts\Activate.ps1

python -m pip install --upgrade pip
python -m pip install "shapely==2.1.2"

python route_orientation_lab.py

Always print the actual runtime rather than inferring which GEOS library a particular installation must contain.

Run the baseline, a single reversal and the global inversion

Shapely's binding contract is precise about what directed mode adds. By default, merged line direction follows the majority direction of the constituent lines from which it is formed. With directed=True, the operation does not change point order within input lines and therefore merges only where that can be done without reversing a component. PostGIS documents corresponding GEOS-backed ST_LineMerge behavior (two-way endpoint joining, no merging across degree-three-or-higher intersections, preservation of point order under its directed option and the same GEOS 3.11 minimum), which is useful corroboration for mixed Python/database teams without implying byte-for-byte cross-engine output equivalence.

The complete local driver below creates fresh geometries for each case, preserves source IDs, records output family and component count, refuses to treat enumeration order of multipart output as route order, and restricts station interpolation to deliberately admitted single lines.

from future import annotations

from collections import Counter, defaultdict, deque
from dataclasses import dataclass
from math import isfinite
import platform

import shapely
from shapely import LineString, MultiLineString
from shapely import line_interpolate_point, line_merge, reverse

ROUTE_ID = "TRAIL-AD"
ROUTE_REV = "route-r1"
FIXTURE_REV = "trail-A-D-r1"

POINTS = {
    "A": (0.0, 0.0),
    "B": (3.0, 0.0),
    "C": (3.0, 4.0),
    "D": (3.0, 6.0),
    "E": (6.0, 0.0),
    "G": (3.0, 1.0),
}

ORIGIN_ID = "A"
TERMINUS_ID = "D"
EXPECTED_LENGTH = 9.0
EXPECTED_STATIONS = {
    2.0: (2.0, 0.0),
    6.0: (3.0, 3.0),
}


@dataclass(frozen=True)
class Part:
    part_id: str
    start_id: str
    end_id: str
    start: tuple[float, float]
    end: tuple[float, float]

    def geometry(self) -> LineString:
        # New geometry: the source record remains unchanged.
        return LineString((self.start, self.end))


def part(part_id: str, a: str, b: str) -> Part:
    return Part(part_id, a, b, POINTS[a], POINTS[b])


# Immutable baseline source manifest.
SOURCE_MANIFEST = (
    part("seg-AB", "A", "B"),
    part("seg-BC", "B", "C"),
    part("seg-CD", "C", "D"),
)


def geometry_parts(g):
    if g.geom_type == "LineString":
        return [g]
    if g.geom_type == "MultiLineString":
        return list(g.geoms)
    return []


def ordered_endpoints(g):
    if g.geom_type != "LineString" or g.is_empty:
        return None
    coords = list(g.coords)
    return tuple(coords[0]), tuple(coords[-1])


def ordered_part_coordinates(g):
    # Enumeration order is evidence only; it is not route semantics.
    return [
        tuple(tuple(xy) for xy in ls.coords)
        for ls in geometry_parts(g)
    ]


def endpoint_stats(parts):
    degree = Counter()
    adjacency = defaultdict(set)

    for p in parts:
        a, b = p.start, p.end
        degree[a] += 1
        degree[b] += 1
        adjacency[a].add(b)
        adjacency[b].add(a)

    seen = set()
    components = 0

    for start in adjacency:
        if start in seen:
            continue
        components += 1
        queue = deque([start])
        seen.add(start)

        while queue:
            node = queue.popleft()
            for neighbor in adjacency[node]:
                if neighbor not in seen:
                    seen.add(neighbor)
                    queue.append(neighbor)

    return dict(degree), components


def observe_case(case_id, parts):
    source = MultiLineString([p.geometry() for p in parts])

    observations = {}
    for label, directed in (
        ("default", False),
        ("directed", True),
    ):
        merged = line_merge(source, directed=directed)

        row = {
            "family": merged.geom_type,
            "part_count": len(geometry_parts(merged)),
            "length": float(merged.length),
            "endpoints": ordered_endpoints(merged),
            "ordered_parts": ordered_part_coordinates(merged),
            "stations": None,
        }

        if merged.geom_type == "LineString" and not merged.is_empty:
            row["stations"] = {
                d: tuple(line_interpolate_point(merged, d).coords[0])
                for d in EXPECTED_STATIONS
            }

        observations[label] = row

    degrees, components = endpoint_stats(parts)

    return {
        "case_id": case_id,
        "source_parts": parts,
        "degrees": degrees,
        "components": components,
        "merge": observations,
    }


def station_request_is_admissible(route, distance):
    if route.geom_type != "LineString" or route.is_empty:
        return False, "route_not_single_nonempty_linestring"

    if not isfinite(distance):
        return False, "station_not_finite"

    if distance < 0.0 or distance > EXPECTED_LENGTH:
        return False, "station_out_of_domain"

    return True, "accepted"


def print_case(result):
    print(f"CASE {result['case_id']}")
    for mode in ("default", "directed"):
        row = result["merge"][mode]
        print(
            mode,
            "family=", row["family"],
            "parts=", row["part_count"],
            "length=", row["length"],
            "endpoints=", row["endpoints"],
            "stations=", row["stations"],
        )
        print("ordered_parts=", row["ordered_parts"])

    print("degrees=", result["degrees"])
    print("components=", result["components"])
    print()


def main():
    print("RUNTIME")
    print("python=", platform.python_version())
    print("shapely=", shapely.__version__)
    print("geos=", shapely.geos_version_string)
    print("geos_capi=", shapely.geos_capi_version_string)
    print("fixture_revision=", FIXTURE_REV)

    if shapely.geos_version < (3, 11, 0):
        raise RuntimeError(
            "directed line_merge requires GEOS >= 3.11.0"
        )

    cases = {
        "baseline": (
            part("seg-AB", "A", "B"),
            part("seg-BC", "B", "C"),
            part("seg-CD", "C", "D"),
        ),
        "reversed_middle": (
            part("seg-AB", "A", "B"),
            part("seg-BC", "C", "B"),
            part("seg-CD", "C", "D"),
        ),
        "all_reversed": (
            part("seg-AB", "B", "A"),
            part("seg-BC", "C", "B"),
            part("seg-CD", "D", "C"),
        ),
        "branch": (
            part("seg-AB", "A", "B"),
            part("seg-BC", "B", "C"),
            part("seg-CD", "C", "D"),
            part("seg-BE", "B", "E"),
        ),
        "gap": (
            part("seg-AB", "A", "B"),
            Part(
                "seg-BC",
                "G",
                "C",
                POINTS["G"],
                POINTS["C"],
            ),
            part("seg-CD", "C", "D"),
        ),
    }

    # Approved correction test:
    # the original C->B record survives unchanged.
    original_bc = part("seg-BC", "C", "B")
    corrected_geometry = reverse(original_bc.geometry())

    corrected_bc = Part(
        "seg-BC",
        "B",
        "C",
        tuple(corrected_geometry.coords[0]),
        tuple(corrected_geometry.coords[-1]),
    )

    cases["approved_repair"] = (
        part("seg-AB", "A", "B"),
        corrected_bc,
        part("seg-CD", "C", "D"),
    )

    results = {
        case_id: observe_case(case_id, parts)
        for case_id, parts in cases.items()
    }

    for result in results.values():
        print_case(result)

    # Independent release controls.
    baseline = results["baseline"]["merge"]["directed"]

    assert baseline["family"] == "LineString"
    assert baseline["part_count"] == 1
    assert baseline["length"] == EXPECTED_LENGTH
    assert baseline["endpoints"] == (
        POINTS[ORIGIN_ID],
        POINTS[TERMINUS_ID],
    )
    assert baseline["stations"] == EXPECTED_STATIONS

    reversed_middle = results["reversed_middle"]
    assert reversed_middle["merge"]["default"]["part_count"] == 1
    assert reversed_middle["merge"]["directed"]["part_count"] == 3

    inverted = results["all_reversed"]["merge"]["directed"]
    assert inverted["endpoints"] == (
        POINTS["D"],
        POINTS["A"],
    )
    assert inverted["stations"] == {
        2.0: POINTS["C"],
        6.0: POINTS["B"],
    }

    branch = results["branch"]
    assert branch["merge"]["default"]["part_count"] == 3
    assert branch["merge"]["directed"]["part_count"] == 3
    assert branch["components"] == 1
    assert branch["degrees"][POINTS["B"]] == 3

    gap = results["gap"]
    assert gap["merge"]["default"]["part_count"] == 2
    assert gap["merge"]["directed"]["part_count"] == 2
    assert gap["components"] == 2

    repair = results["approved_repair"]["merge"]["directed"]
    assert repair["endpoints"] == (
        POINTS["A"],
        POINTS["D"],
    )
    assert repair["stations"] == EXPECTED_STATIONS

    accepted_route = line_merge(
        MultiLineString(
            [p.geometry() for p in cases["baseline"]]
        ),
        directed=True,
    )

    for request in (
        -1.0,
        0.0,
        2.0,
        6.0,
        9.0,
        10.0,
        float("nan"),
    ):
        admitted, reason = station_request_is_admissible(
            accepted_route,
            request,
        )

        print(
            "STATION_REQUEST",
            request,
            "accepted=", admitted,
            "reason=", reason,
        )

        if admitted:
            point = line_interpolate_point(
                accepted_route,
                request,
            )
            print("point=", tuple(point.coords[0]))


if name == "__main__":
    main()

The baseline run produced one 9 m LineString under both merge modes with ordered endpoints A→D. Station 2 was (2,0) and station 6 was (3,3), matching the hand-derived controls.

That is the first publishable case: continuity, source direction, route-register direction, total length and asymmetric interior controls agree.

A single reversed source segment changes the interpretation dramatically. For A→B, C→B, C→D, the default merge in this run still returned one A→D LineString, length 9, whose two station observations matched the expected coordinates. The default operation was permitted to reorient linework while sewing it, exactly the behavior Shapely documents. A check that asks only “did merge produce one row?” therefore hides the bad source record.

Directed mode returned three LineString components instead. That is evidence of incompatible digitising direction in the delivered parts, not authorization to reverse one.

The observed directed components were equivalent to these ordered coordinate sequences:

A -> B
C -> D
C -> B

Do not depend on their enumeration order. Multipart ordering is not being published here as a Shapely guarantee. For regression comparison, treat the collection as a set or multiset of parts when enumeration is immaterial, while retaining the exact point order inside each part.

This is also where ordinary output-family testing is useful but insufficient. A downstream pipeline should certainly require the single LineString family before station release; the broader principle is discussed in output-type checks for Shapely geometries. But a correct family still does not prove route orientation.

Now reverse all three source arrows: B→A, C→B, D→C. Both default and directed modes returned one continuous 9 m LineString in this run. Its orientation was D→A.

That case defeats a rule that treats a successful directed merge as proof of correct stationing. All parts are mutually compatible; they are simply compatible in the wrong global direction.

The observed diagnostic interpolation was:

station 2 -> (3, 4)
station 6 -> (3, 0)

Both are wrong for the registered A→D route, even though the geometry type and length pass.

Directed merge is consequently a source-consistency experiment, not an origin oracle. It can expose a direction disagreement among component records. It cannot determine whether an internally consistent collection is globally aligned with the registered trailhead.

Distinguish branch, gap and source-inventory failures before stationing

The endpoint topology tests answer a different question from orientation, and keeping the failure categories separate makes recovery safer.

Add a fourth part B→E, where E=(6,0), to the correctly directed baseline. Endpoint B now has degree three:

A: degree 1
B: degree 3
C: degree 2
D: degree 1
E: degree 1

There is still one connected component, but B is a branch. GEOS describes LineMerger as stopping at degree-1 and degree-3-or-more nodes, while Shapely says lines are not joined when three or more lines meet at an endpoint. In the executed fixture, both default and directed modes returned three parts. The separate GEOS C API check likewise reported 3/3.

A branch is not a request for the software to choose an edge. The steward needs authoritative path membership: is seg-BE part of this route revision, another route, or an erroneously included source record?

The gap case is different. Keep AB; replace the BC start with G=(3,1) so the part runs G→C; retain C→D.

The endpoint counts become:

A: degree 1
B: degree 1
G: degree 1
C: degree 2
D: degree 1

Now there are two connected components. Both merge modes returned two parts in the local run, matching the GEOS C API count of 2/2.

The total delivered length is also only 8 m because the altered G→C segment is 3 m rather than 4 m. That helps diagnosis in this fixture, but it should not be generalized into “wrong length means gap.” A different defect could preserve total length.

Case

Endpoint signal

Components

Interpretation

Baseline

A/D degree 1; B/C degree 2

1

candidate open path

Reversed middle

same as baseline

1

topology alone misses directional contradiction

All reversed

same as baseline

1

topology alone misses global inversion

Branch

B degree 3

1

path membership unresolved

Gap

four degree-1 endpoints

2

missing connection/source mismatch

These endpoint rules are intentionally limited to this endpoint-only miniature fixture. GEOS itself warns that line merging assumes correctly noded linework whose edges meet at their endpoints. Arbitrary production GIS data may contain interior crossings, near misses or topology requiring a validated approach beyond these counters.

Do not repair either failure automatically. The branch case does not justify picking the “straightest” edge, shortest edge or first edge. The gap does not justify inserting (3,0)→(3,1), applying an arbitrary snapping tolerance or silently shifting coordinates.

The source manifest also needs an explicit inventory reconciliation. For this fixture, the approved baseline is:

seg-AB: (0,0) -> (3,0)
seg-BC: (3,0) -> (3,4)
seg-CD: (3,4) -> (3,6)

Two comparisons are useful.

The undirected edge inventory tells you whether the same footprint edges are present irrespective of direction:

def undirected_key(a, b):
    return frozenset((a, b))

The directed inventory preserves the ordered pair:

def directed_key(a, b):
    return (a, b)

If seg-BC changes from B→C to C→B, its undirected edge still matches, while its directed key does not. That distinction is exactly what a geometric-footprint comparison can miss.

Hold conditions should include a missing approved part, a duplicate part ID, an extra unauthorised part, an unexpected endpoint pair or an orientation inconsistent with the approved manifest. “Same number of points,” “same total length,” “same undirected footprint” and “topologically equal” are not substitutes for an orientation check because none independently establishes which endpoint is station zero.

Admit interpolation only after the route passes, then record approved reversals separately

line_interpolate_point has useful behavior that is dangerous if mistaken for station-domain validation. Shapely 2.1.2 documents absolute distance by default, optional normalized distance, negative values measured from the end, and clipping of distances beyond the line to an endpoint. It also documents that, for multipart inputs, the first geometry is used and the rest ignored.

Those semantics are why interpolation belongs late in the release gate.

For this station register, an admissible production request must satisfy all of the following:

1.     The candidate is nonempty and is exactly one LineString.

2.     Its ordered start/end agree with registered A→D.

3.     Its accepted length is 9 m for this fixture.

4.     Its source-part inventory has passed.

5.     The station request is finite.

6.     The request is an absolute distance in the closed interval [0,9].

7.     The route revision supplying that domain is the same revision referenced by the output station record.

Station zero remains legal. Requests -1 and 10 are held before interpolation.

That is policy layered on top of API behavior. If you called Shapely directly, -1 would mean one metre from the end and 10 would clip to the terminal point. Neither interpretation belongs in this organisation's station register.

The distinction resembles scalar interpolation pipelines where endpoint behavior can return a finite value for a query that should have been rejected by the application's domain contract; see a scalar interpolation example with endpoint clipping. The governing point is the same: library behavior does not replace application admission.

The globally reversed case is the one controlled exception. We deliberately interpolate it as a diagnostic replay because showing (3,4) and (3,0) makes the orientation defect visible. Those points never enter the production station table. The audit record should mark them as test evidence attached to a quarantined case.

Corrections also require a separate decision.

Shapely's reverse operation returns a copy of a geometry with coordinate order reversed. That is an appropriate mechanism only after an authorized decision has said that a specific source record should be represented in the opposite order.

Suppose seg-BC arrives as C→B, and the responsible data owner approves change CHG-BC-017 to use B→C for route revision route-r2. The evidence should retain:

part_id: seg-BC
source_order: C -> B
corrected_order: B -> C
change_id: CHG-BC-017
authority: <owner identifier>
source_geometry_retained: yes
operation: shapely.reverse(copy)
rerun_case: approved_repair

The source geometry remains untouched; the corrected geometry is a distinct object.

For a global inversion, do not simply reverse the finished merged route because the control failed. First determine whether the route register is wrong, whether all source segments were digitised backwards intentionally, or whether an upstream export changed orientation. The correction needs to be made at the layer whose provenance is actually wrong.

The repair test should prove that only the authorized source record changed. In this fixture:

assert original_ab == corrected_ab
assert original_cd == corrected_cd

assert original_bc_start == C
assert original_bc_end == B

assert corrected_bc_start == B
assert corrected_bc_end == C

Then rerun the complete gate rather than assuming one reversal solved everything:

part IDs: exactly AB, BC, CD
directed merge: one LineString
ordered endpoints: A -> D
length: 9
station 2: (2,0)
station 6: (3,3)

The local approved-repair case passed all those controls under both merge modes. That result supports release of a new route/station revision, not retroactive alteration of an already published edition.

Turn observations into a release matrix and an auditable recovery process

The release matrix should keep engine observations distinct from organisational disposition.

The local Shapely 2.1.2 / GEOS 3.13.1 run produced the following. The separate GEOS 3.13.1 C API check reported default/directed counts 1/1, 1/3, 1/1, 3/3, 2/2 for baseline, reversed-middle, all-reversed, branch and gap respectively; that is useful engine-side corroboration, but it is not substituted for the Shapely observations below.

Case

Default parts

Directed parts

Candidate direction

Station control

Disposition

Required owner

Baseline

1

1

A→D

2 m and 6 m pass

Publish

publisher

Middle reversal

1

3

default A→D; directed multipart

not evaluated on directed result

Quarantine source assembly

GIS steward / source owner

Global inversion

1

1

D→A

diagnostic gives wrong controls

Quarantine station edition

route-register owner + GIS steward

Branch

3

3

undefined as one route

not evaluated

Hold pending path membership

route-register owner

Gap

2

2

undefined as one route

not evaluated

Hold pending source review

GIS steward

Approved BC repair

1

1

A→D

both pass

Publish new revision

approving owner + publisher

The “not evaluated” cells matter. Interpolating every multipart result and then deciding which point looks plausible would mix diagnosis with admission. Shapely explicitly documents special multipart behavior for line_interpolate_point, so the production gate should prevent that call rather than rely on it.

A compact audit record can be JSON-compatible:

{
  "route_id": "TRAIL-AD",
  "route_revision": "route-r2",
  "fixture_revision": "trail-A-D-r1",
  "case_id": "approved_repair",
  "source_parts": [
    ["seg-AB", "A", "B", [0, 0], [3, 0]],
    ["seg-BC", "C", "B", [3, 4], [3, 0]],
    ["seg-CD", "C", "D", [3, 4], [3, 6]]
  ],
  "approved_changes": [
    {
      "change_id": "CHG-BC-017",
      "part_id": "seg-BC",
      "old_order": ["C", "B"],
      "new_order": ["B", "C"]
    }
  ],
  "merge_mode": "directed",
  "python_version": "3.13.5",
  "shapely_version": "2.1.2",
  "geos_version": "3.13.1",
  "geos_capi_version": "3.13.1-CAPI-1.19.2",
  "geometry_family": "LineString",
  "part_count": 1,
  "ordered_endpoints": ["A", "D"],
  "length_m": 9.0,
  "controls": {
    "station_2": [2, 0],
    "station_6": [3, 3]
  },
  "disposition": "publish_new_revision"
}

In a real release system, the authority identity and approval record should be added from the organisation's workflow rather than invented by the script.

Recovery begins with lineage. If station-table revision stations-r7 points to a route assembly later shown to be globally inverted, mark stations-r7 held or superseded according to the organisation's publication policy. Do not overwrite its coordinates in place if that would destroy traceability.

Determine confirmed impact by following recorded dependencies:

station-table revision
    -> route revision
        -> assembly case / source manifest
            -> source segment revisions
                -> correction approval

Products explicitly referencing the defective station-table revision are confirmed candidates for rerun. Products for which that lineage is unavailable have unknown impact, not zero impact. That distinction belongs in the incident record.

After an approved source correction, the steward reruns the route gate and stores the new evidence. Only then does the publisher generate replacement station rows linked to the corrected route revision. Downstream products are regenerated from the replacement table according to their retained dependency records.

This is also why exact WKT should not become the contractual regression oracle. WKT is useful evidence, but the stable assertions here are source IDs, ordered coordinate pairs, component counts where meaningful, registered endpoints, length controls and station controls. Multipart enumeration order is deliberately not promoted into a general guarantee.

Know what the fixture proves and where it stops

The miniature test establishes a narrow but operationally valuable result.

A directed line merge can reveal a local conflict in the original orientation of components because it refuses joins that require changing input point order. A successful directed merge cannot, by itself, establish the route's global business direction. Shapely's own contract says what directed=True preserves; it does not say that the resulting start coordinate is an approved trailhead.

The fully reversed case is the proof. It passes directed merging, single-LineString output and the 9 m length control. Only comparison with the independent A→D route register and asymmetric station controls catches the defect.

The fixture also demonstrates that branch and gap failures should be distinguished. A branch can remain one connected component while creating a degree-three junction where merging stops. A gap creates multiple connected components. GEOS documents these endpoint/noding assumptions as engine behavior; production topology outside that model needs additional validation.

Do not extend the miniature test casually to closed loops. GEOS notes a special isolated-loop case in which a start node is selected because every node has degree two. That is precisely the sort of situation in which an external linear-reference origin needs a different validated design.

Likewise, this article has intentionally excluded self-intersections, interior crossings, alternate paths, network routing, snapping, real survey calibration, geographic distance and CRS conversion. Production tolerances also need their own acceptance rationale: exact tuple equality is appropriate for the deliberately exact fixture, not automatically for measured field data.

Once a station has been validly produced, downstream ownership is a separate contract. For example, assigning the marker to an administrative or reporting polygon may require rules for points on shared boundaries; that concern is covered in a downstream point-to-zone ownership check. Route orientation should not be inferred from that later overlay, and polygon ownership should not be inferred from route stationing.

The release rule can therefore remain compact:

Publish only when:

•       the approved part inventory is reconciled;

•       directed merge yields one nonempty LineString;

•       the ordered endpoints equal registered origin → terminus;

•       the independent length control passes;

•       independent station controls pass; and

•       every requested production station is finite and in domain.

No single one of those conditions is advertised as a universal guarantee. Together they form a reproducible admission policy for this declared fixture and its stated assumptions.

Hand the evidence from steward to publisher

A mature route workflow should make orientation evidence an ordinary release artifact rather than an inference hidden inside a geoprocessing script.

The GIS steward supplies the versioned route register, immutable source manifest, any separately authorized reversal decisions, topology observations, runtime versions and the control results. The publisher releases only station records tied to the route revision that passed. That division is more useful than asking downstream users to inspect line coordinates and guess which end was intended to be zero.

For analysts developing this kind of role, how GIS analysts use spatial validation at work provides broader context around GIS data-management and decision-support responsibilities. Refonte Learning's GIS Analyst Program lists vector analysis, Python geoprocessing, data quality, topology, metadata and spatial databases among its competencies; its page currently states a three-month, 10–12-hour-per-week format and describes hands-on labs and project work.

The operational lesson is narrower than any course syllabus: retain the arrows you received, distinguish a documented correction from silent reversal, and never equate “merged successfully” with “station zero is correct.” A route becomes publishable when its geometry, source inventory, registered direction and independent station controls tell the same versioned story.