Skip to content

Add ShapeService and move TripPattern geometries out of the transit model - #8149

Merged
VillePihlava merged 36 commits into
opentripplanner:dev-2.xfrom
HSLdevcom:add-shape-module
Dec 4, 2026
Merged

VillePihlava merged 36 commits into
opentripplanner:dev-2.xfrom
HSLdevcom:add-shape-module

Conversation

@VillePihlava

Copy link
Copy Markdown
Contributor

Summary

Adds a shape module (service/shape) that extracts TripPattern geometries out of TripPattern into a dedicated repository/service, and resolves geometries for real-time patterns via RealTimeShapeResolver. CompactLineString* were moved into the new module. The new PackedLineStringCodec stays in the street module.

This is the first phase of adding real-time shape capability to OTP by extracting a shape module. This PR aims to not change existing functionality.

Functional changes

Mostly a refactoring, but there are some behavior changes:

  • A pattern with fewer than two stops now returns an empty geometry instead of null in the GTFS
    (geometry, patternGeometry) and Transmodel (pointsOnLink) APIs.
  • Real-time pattern geometries are created when the update is applied (RealTimeShapeResolver)
    instead of when the TripPattern is built, using the same algorithm.
  • Real-time geometries are no longer garbage collected with the pattern (see above).
  • With --build --serve shapes are empty, same as the timetable data.

Review focus

  • RealTimeShapeResolver: derives a real-time pattern's geometry from the original pattern's. It
    runs last in TripUpdateApplier.apply, so no shape is written for an update that failed. If the
    resolver itself throws, the timetable update is already applied and the exception is caught by
    the caller, so the pattern is committed without a geometry.
  • Real-time shapes are never evicted: DefaultShapeRepository only adds real-time geometries, and
    every commit copies the whole map. SIRI creates a new pattern id for each added/extra-call
    update, so the map grows with uptime. Previously the geometry was garbage collected together
    with the pattern.
  • Contracts enforced by new exceptions:
    • RealTimeShapeResolver:60 IllegalStateException: hop count must equal max(stops - 1, 0).
      Previously TripPatternBuilder.buildHopGeometries enforced this when the pattern was built;
      geometry creation is now separate from the pattern, so the resolver checks it (real-time only).
    • RealTimeShapeResolver:83 IllegalStateException: the replaced original pattern must have a
      geometry. New: the geometry used to be on the original TripPattern itself.
    • DefaultShapeService:27 IllegalStateException: every committed pattern must have a geometry.
      New: a TripPattern used to always carry its geometry.
    • ShapeDataImport:63 IllegalStateException: no setTripPatternGeometry after
      toScheduledShapeData(). New: mirrors TimetableDataImport.
    • CompactLineStringSequence:47/55/61 IllegalArgumentException: cumulative distances must have
      geometries + 1 entries, start at 0 and be non-decreasing. Moved unchanged from
      CompactLineStringSequence.
  • ScheduledTransitLegReference.getLeg: shape lookup moved here.
  • Leg geometries stay
  • Geometry methods removed from TripPattern.
  • Is the naming ok?

Issue

Ref #7939

Unit tests

  • ScheduledShapeDataTest, ShapeDataImportTest, DefaultShapeRepositoryTest,
    DefaultShapeServiceTest, ShapeRepositoryLifecycleTest
  • TripGeometryFactoryTest, CompactLineStringTest, CompactLineStringSequenceTest,
    PackedLineStringCodecTest
  • RealTimeShapeResolverTest, TripUpdateApplierTest
  • ScheduledTransitLegReferenceTest, GraphSerializationTest
  • Existing tests updated for the new service wiring.

Documentation

  • Javadoc added for the new public types and methods.
  • New service/shape/package.md describing the design, data flow and a glossary.
  • No new configuration options.

@VillePihlava
VillePihlava requested a review from a team as a code owner October 29, 2026 11:55
@VillePihlava VillePihlava added !Improvement A functional improvement or micro feature +Bump Serialization Id Add this label if you want the serialization id automatically bumped after merging the PR labels Oct 29, 2026
@VillePihlava VillePihlava added this to the 2.11 (next release) milestone Oct 29, 2026
@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.77690% with 58 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.16%. Comparing base (b22fbcd) to head (012e167).
⚠️ Report is 1 commits behind head on dev-2.x.

Files with missing lines Patch % Lines
...ner/standalone/configure/ConstructApplication.java 0.00% 8 Missing ⚠️
...s/transmodel/model/network/JourneyPatternType.java 14.28% 6 Missing ⚠️
...pentripplanner/apis/gtfs/datafetchers/LegImpl.java 20.00% 4 Missing ⚠️
...pplanner/apis/gtfs/datafetchers/QueryTypeImpl.java 0.00% 4 Missing ⚠️
...entripplanner/apis/gtfs/datafetchers/TripImpl.java 0.00% 4 Missing ⚠️
...ripplanner/apis/gtfs/datafetchers/PatternImpl.java 25.00% 3 Missing ⚠️
...planner/street/geometry/PackedLineStringCodec.java 92.30% 1 Missing and 2 partials ⚠️
...ripplanner/apis/transmodel/model/plan/LegType.java 0.00% 2 Missing ⚠️
...transmodel/model/timetable/ServiceJourneyType.java 0.00% 2 Missing ⚠️
...algorithm/mapping/RaptorPathToItineraryMapper.java 50.00% 2 Missing ⚠️
... and 18 more
Additional details and impacted files
@@              Coverage Diff              @@
##             dev-2.x    #8149      +/-   ##
=============================================
+ Coverage      76.14%   76.16%   +0.01%     
- Complexity     24836    24896      +60     
=============================================
  Files           2658     2671      +13     
  Lines          93078    93270     +192     
  Branches        9288     9293       +5     
=============================================
+ Hits           70878    71042     +164     
- Misses         19058    19086      +28     
  Partials        3142     3142              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@optionsome
optionsome requested a review from vpaturet October 29, 2026 14:59
@optionsome optionsome self-assigned this Oct 29, 2026
@optionsome
optionsome self-requested a review October 29, 2026 14:59

@optionsome optionsome left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partial review

"No geometry created for trip pattern " + tripPattern.getId()
);
}
int expectedHops = Math.max(tripPattern.numberOfStops() - 1, 0);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the number of stops be negative?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While working on the code there were references to the possibility of tripPatterns without stops, which is weird. This is an old check from TripPatternBuilder

}
int expectedHops = Math.max(tripPattern.numberOfStops() - 1, 0);
if (tripPatternGeometry.size() != expectedHops) {
throw new IllegalStateException(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't remember what was the exception handling in the data builder, but does the build crash when you throw this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of these IllegalStateExceptions are caused by states that should never be reachable. I think we should discuss how the contract between shapes and tripPatterns is handled and if/where to put these checks.

If this happens during the data build, the build should crash (I haven't verified). However, what if a similar thing happens in a realtime updater?

*/
private transient boolean frozen = false;

public ShapeDataImport() {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if we have these empty public constructors defined or not. This looked a bit odd so we probably don't usually do it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TimetableDataImport does the same thing

}
return new CompactLineStringSequence(packed, cumulativeDistanceMeters);
return new CompactLineStringSequence(
geometries.toArray(new CompactLineString[0]),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I asked AI why the CompactLineString size isn't allocated properly here and it claimed that this 0 approach is as fast or faster. It's some standard java idiom that I just wasn't aware of but I'm not sure if everyone else is or is it worth a comment here why it's done like this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would just leave it as is without comment


private static final ScheduledShapeData EMPTY = new ScheduledShapeData(Map.of());

private final Map<FeedScopedId, CompactLineStringSequence> geometriesByTripPattern;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't yet support different shapes for a pattern, but I guess we can do that change as a follow up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, this PR is aiming for not making functional changes, per-trip shapes will come in later phases

@vpaturet

vpaturet commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

could you fix the conflicts?

@vpaturet

vpaturet commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

there are some conflicts again.

Comment on lines +80 to +85
var originalTripPatternGeometry = repository.getTripPatternGeometry(original.getId());
if (originalTripPatternGeometry == null) {
throw new IllegalStateException(
"No geometry found for the original trip pattern " + original.getId()
);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we clear the shapes for a FULL_DATASET update? In that case, can the fact that the trip pattern cache does not clear trip patterns cause problems? For example, a trip pattern from a realtime update is based on a cleared trip pattern.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One option would be to not clear them at all. In dev-2.x the trip pattern cache is never cleared, which means that a realtime generated geometry stored on a trip pattern is also stored forever. However, for example SIRI extra journeys skip the cache and are garbage collected once cleared on dev-2.x. If the geometries are not cleared in the ShapeRepository, this would be a behaviour change for SIRI extra journeys since their geometries would now be stored forever.

@vpaturet vpaturet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some general comments:

  1. Have you considered TripPatternGeometry instead of Shape?

  2. The existing invariant "A TripPattern has always a geometry" should be preserved.
    I would suggest keeping the checks on the "impossible cases" with IllegalStateException to prove the invariant.
    In the current state of the PR there is no code path that leads to a TripPattern without geometry, but you could secure this with:

  • inverting the order of insertion (shape first, then trip pattern) so that a failure in saving the shape prevents the creation of the pattern (you may end up with an orphan entry in the shape repository, but this is a minor issue)
  • ensuring that there is always a fallback to a straight-line geometry.
  1. The growth of the repository is unbounded, this may be problematic for SIRI-Lite which uses the FULL_DATASET mode. I would suggest adding logic to track the removal of patterns and propagate it to the shape repository.
    Ideally this would be implemented using events. Could be worth a follow-up.

@VillePihlava

Copy link
Copy Markdown
Contributor Author

Some general comments:

  1. Have you considered TripPatternGeometry instead of Shape?
  2. The existing invariant "A TripPattern has always a geometry" should be preserved.
    I would suggest keeping the checks on the "impossible cases" with IllegalStateException to prove the invariant.
    In the current state of the PR there is no code path that leads to a TripPattern without geometry, but you could secure this with:
  • inverting the order of insertion (shape first, then trip pattern) so that a failure in saving the shape prevents the creation of the pattern (you may end up with an orphan entry in the shape repository, but this is a minor issue)
  • ensuring that there is always a fallback to a straight-line geometry.
  1. The growth of the repository is unbounded, this may be problematic for SIRI-Lite which uses the FULL_DATASET mode. I would suggest adding logic to track the removal of patterns and propagate it to the shape repository.
    Ideally this would be implemented using events. Could be worth a follow-up.

Thanks, I think 1. and 2. are pretty straightforward, but I think we need to discuss how to handle the removal of patterns. Right now I can think of 3 options:

  • Copying the existing clear logic from TimetableRepository and adapting it to trip geometries
  • No removal - not good :)
  • Event-based - this requires some work/discussion, since its not clear to me at the moment when a trip pattern is considered "removed". For example as mentioned earlier, the trip pattern cache is not cleared.

@VillePihlava

Copy link
Copy Markdown
Contributor Author
  1. TripShape instead of Shape, maybe HopShape for hops
  2. Keep IllegalStateException for contract, atm no code path that breaks the contract - however future-proof so future changes don't break. Invert the way elements are inserted. Insert shapes first and then the trip pattern.

As long as a shape is always provided, order does not matter.

RealTimeShapeResolver should just return a shape. The storing should be separate. And where the contract should live will be decided after refactoring.

  1. Lets go with clear logic for now. The event-based approach would be nice for a follow-up.

@VillePihlava
VillePihlava dismissed stale reviews from vpaturet and optionsome via bd15a0e November 30, 2026 15:13
@VillePihlava
VillePihlava marked this pull request as ready for review November 30, 2026 15:13
Comment on lines +34 to +41
public CompactLineStringSequence getTripPatternShape(TripPattern tripPattern) {
var tripPatternShape = shapes.getTripPatternShape(tripPattern.getId());
if (tripPatternShape == null) {
LOG.warn("No shape found for trip pattern {}. Using straight lines.", tripPattern.getId());
return TripShapeFactory.straightLines(tripPattern.getStopPattern(), DeduplicatorService.NOOP);
}
return tripPatternShape;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would feel better if the shape service didn't interact with patterns but just with feedscopedids. It does feel tempting for DRYness reasons to put the fallback code here though. So before you change anything, it would be nice to hear someone else's opinion on this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed in the dev meeting: This is not ideal but this is still the best compromise. In this case using feed ids would make the logic more complicated and redundant.

vpaturet
vpaturet previously approved these changes Dec 4, 2026
optionsome
optionsome previously approved these changes Dec 4, 2026
@VillePihlava
VillePihlava dismissed stale reviews from optionsome and vpaturet via 012e167 December 4, 2026 09:46
@VillePihlava

Copy link
Copy Markdown
Contributor Author

Some last minute merge conflicts

@VillePihlava
VillePihlava added this pull request to the merge queue Dec 4, 2026
Merged via the queue into opentripplanner:dev-2.x with commit 0d8fcb2 Dec 4, 2026
7 checks passed
@VillePihlava
VillePihlava deleted the add-shape-module branch December 4, 2026 10:26
t2gran pushed a commit that referenced this pull request Dec 4, 2026
t2gran pushed a commit that referenced this pull request Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

+Bump Serialization Id Add this label if you want the serialization id automatically bumped after merging the PR !Improvement A functional improvement or micro feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants