Reset a train's turn point on a new playback epoch

- A clock correction starts a new epoch, and playback may first draw its
  second report. The turn point now resets on a new epoch as well as on a
  break, so a standing train no longer turns around after a correction.
- recallDirection and earlierFixes are gone: comparing each earlier report
  with the newest turned a standing train on GPS jitter. A train bound when
  its line arrives late shows no direction until it has moved 15 m.
- Tests share reportDirections, iconOf and the playback helper.
- Comments and CURRENT-STATE match the code.
This commit is contained in:
German Khokhlov committed 2026-11-19 00:26:57 +04:00
1 parent 58afb169d1
commit e8ef4d1293
8 files changed
+108 -131

No files matched your search

-22
View File
@@ -202,28 +202,6 @@ test('a standing train keeps its operator’s bearing through reports that leave
assert.deepEqual(seen, Array(6).fill(-1));
});
test('a train bound standing, its line late, runs the way its earlier reports went', async (t) => {
t.mock.method(console, 'warn', () => {});
const paths = { 'mbta-rail': 503 };
const app = harness(t, { paths, at: BOSTON });
let eastM = 1600;
app.feeds.set('mbta-rail', () => [train('T1', LAT, LON0 + eastM / KX)]);
await app.enable();
// No line yet: it runs 300 m west, with no bearing, and stands.
for (const next of [1500, 1400, 1300, 1300, 1300, 1300, 1300, 1300]) {
eastM = next;
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.equal(app.entry(T1).path, null, 'not bound yet');
paths['mbta-rail'] = PACK;
const slot = app.state()._pathPacks.get('mbta-rail');
app.run(Math.max(0, slot.retryAt - Date.now()));
await app.poll();
app.parts().selection.selectTrain(T1);
assert.equal(app.layer.getSelectedTrain().path.direction, -1);
});
test('a snapshot read again while nothing changed is the one read before', async (t) => {
let list = stopList('Alpha', 'Bravo', 'Charlie');
const app = await onTheLine(t, {
+1 -26
View File
@@ -23,12 +23,7 @@ import {
railTrainKey,
trainReportTimeMs,
} from './policy.js';
import {
bindTrainPath,
followFix,
rebindTrainPath,
recallDirection,
} from './pathBinding.js';
import { bindTrainPath, followFix, rebindTrainPath } from './pathBinding.js';
import { scheduleRetryDelayMs } from './schedules.js';
import { createDuplicateFilter } from './dedupe.js';
@@ -225,23 +220,6 @@ export function createIngestion({ state, services, parts, source }) {
entry.path = rebindTrainPath(pack, ids, entry.path, fix);
}
/**
* A track's reports before `newest`, newest first, back to the start of
* its run of playback (a new epoch or a break).
*/
function earlierFixes(track, newest) {
const fixes = [];
let later = newest;
for (let i = track.count - 2; i >= 0; i--) {
if (later.flags & FIX_FLAGS.BREAK) break;
const fix = readFix(track, i);
if (fix.epoch !== later.epoch) break;
fixes.push(fix);
later = fix;
}
return fixes;
}
/** Bind the trains a feed already shows once its pack arrives. */
function bindFeedTrains(feedId) {
const newest = {};
@@ -250,9 +228,6 @@ export function createIngestion({ state, services, parts, source }) {
if (!entry.track?.count) continue;
readFix(entry.track, entry.track.count - 1, newest);
followPath(entry, entry.record, newest);
// It may have run, and stopped, before its line came.
if (entry.path)
recallDirection(entry.path, earlierFixes(entry.track, newest));
parts.rendering.schedulePlayback(entry);
}
governorRequestRender('rail-paths');
+8 -31
View File
@@ -74,8 +74,8 @@ function createBinding(shapeIndex, path, via, s, fix) {
via,
/**
* Which way the drawn train runs along the shape: +1 along it, -1
* against it, 0 until it has moved DIRECTION_MIN_M (steer, or
* recallDirection). Kept until a rebind, and while the train stands.
* against it, 0 until it has moved DIRECTION_MIN_M (steer). Kept until
* a rebind, and while the train stands.
* Once a playback segment has told it (`directionPlayed`), only playback
* changes it: the newest reports run ahead of the drawn train, so a
* reversal they show turns it when playback reaches it.
@@ -84,7 +84,7 @@ function createBinding(shapeIndex, path, via, s, fix) {
directionPlayed: false,
/** steer() turn points: one for the reports, one for the played segments. */
reportTurn: { s },
playTurn: { s: NaN },
playTurn: { s: NaN, epoch: NaN },
/** The newest operator bearing its reports gave (deg), NaN before one. */
bearingDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN,
/** Arc and time of the newest report. */
@@ -205,32 +205,6 @@ export function rebindTrainPath(pack, { routeId } = {}, binding, fix) {
: null;
}
/**
* Which way a train just bound standing ran before: the newest of its
* earlier reports (newest first) DIRECTION_MIN_M or more along the line
* from its newest one tells. Stops at the first report off the line.
* @param {object} binding Just made, from the newest report.
* @param {Array<{t: number, lat: number, lon: number}>} earlier
*/
export function recallDirection(binding, earlier) {
if (!binding || binding.direction) return;
for (const fix of earlier) {
const hit = projectOnPath(
binding.path,
fix.lat,
fix.lon,
binding.fixS,
pathWindowM(binding.fixT - fix.t),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return;
const step = binding.fixS - hit.s;
if (Math.abs(step) >= DIRECTION_MIN_M) {
binding.direction = Math.sign(step);
return;
}
}
}
/** Project one playback report, near the last drawn arc when that is useful. */
function projectReport(binding, fix, hintS, hintT) {
const path = binding.path;
@@ -296,8 +270,11 @@ export function placeOnPath(binding, sample, segment, out) {
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok) {
const turn = binding.playTurn;
// A break is a corrected position, not a move: steer on from there.
if (from.flags & FIX_FLAGS.BREAK) turn.s = sFrom;
// A break or a new epoch is a corrected position, not a move: steer
// on from there.
if (from.flags & FIX_FLAGS.BREAK || from.epoch !== turn.epoch)
turn.s = sFrom;
turn.epoch = from.epoch;
binding.direction = steer(binding.direction, turn, sFrom);
binding.direction = steer(binding.direction, turn, sTo);
if (binding.direction) binding.directionPlayed = true;
+72 -28
View File
@@ -1,6 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FIX_FLAGS } from '../../data/contactPlayback.js';
import {
FIX_FLAGS,
advance,
createSample,
createTrack,
insertFix,
readFix,
} from '../../data/contactPlayback.js';
import { createRailPathPack } from '../../data/railPaths.js';
import {
PATH_OFF_TRACK_M,
@@ -271,13 +278,10 @@ test('a jump to a corrected position in a new playback epoch is no reversal', ()
{ tripId: 'full', routeId: 'main' },
fix(0, 1000, 0),
);
const play = (seq, from, to) =>
placeOnPath(
binding,
{ fromSeq: seq, toSeq: seq + 1, fraction: 0.5 },
{ from: { seq, ...from }, to: { seq: seq + 1, ...to } },
{},
);
const play = (seq, from, to) => {
const { sample, segment } = playback(seq, seq + 1, from, to, 0.5);
return placeOnPath(binding, sample, segment, {});
};
assert.ok(play(0, fix(0, 1000, 0), fix(60_000, 1600, 0)));
assert.equal(binding.direction, 1);
// The source puts it back at 1400 m: a new epoch whose first report is a
@@ -302,6 +306,42 @@ test('a jump to a corrected position in a new playback epoch is no reversal', ()
assert.equal(binding.direction, -1);
});
test('a clock correction played from past its break is no reversal', () => {
const binding = bindTrainPath(
pack(),
{ tripId: 'full', routeId: 'main' },
fix(0, 600, 0),
);
const track = createTrack();
const sample = createSample();
const segment = { from: {}, to: {} };
let now = 0;
/** One report at `t`, then 15 s of frames; the direction after each. */
const report = (t, eastM) => {
insertFix(track, fix(t, eastM, 0), { receivedAt: now, wallNowMs: now });
return [1, 2, 3].map(() => {
now += 5000;
advance(track, { wallNowMs: now, monoNowMs: now }, sample);
if (sample.fromSeq >= 0) {
readFix(track, sample.fromSeq - track.baseSeq, segment.from);
readFix(track, sample.toSeq - track.baseSeq, segment.to);
placeOnPath(binding, sample, segment, {});
}
return binding.direction;
});
};
for (const eastM of [600, 750, 900, 1050, 1200, 1200, 1200, 1200])
report(now, eastM);
assert.equal(binding.direction, 1);
assert.ok(binding.directionPlayed);
// Its source's clock falls 120 s behind and puts it at 1000 m. The third
// such report starts a new epoch, and playback starts at the newest one,
// past the break.
const seen = [0, 1, 2].flatMap(() => report(now - 120_000, 1000));
assert.equal(track.resetReason, 'out-of-order');
assert.deepEqual(seen, Array(9).fill(1));
});
/** The direction after each played segment, `[fromM, toM]` 15 s apart. */
function playDirections(binding, steps) {
return steps.map(([fromM, toM], seq) => {
@@ -317,15 +357,22 @@ function playDirections(binding, steps) {
});
}
/** The direction after each report, `eastMs` 15 s apart. */
function reportDirections(binding, eastMs) {
return eastMs.map((eastM, i) => {
assert.ok(followFix(binding, fix((i + 1) * 15_000, eastM, 0)));
return binding.direction;
});
}
test('a train that moves under 15 m a report still tells its direction', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
// It sets off slowly, runs east, then backs out 10 m a report.
const reports = bindTrainPath(p, ids, fix(0, 1000, 0));
const learnt = [1010, 1020, 1600, 1590, 1580, 1570].map((eastM, i) => {
assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0)));
return reports.direction;
});
const learnt = reportDirections(
bindTrainPath(p, ids, fix(0, 1000, 0)),
[1010, 1020, 1600, 1590, 1580, 1570],
);
assert.deepEqual(learnt, [0, 1, 1, 1, -1, -1], 'from the newest reports');
const played = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.deepEqual(
@@ -347,11 +394,10 @@ test('a train turns 15 m back from where it ran to, not 14.9 m', () => {
[1100, -1, '15 m back'],
[1100.1, 1, '14.9 m back'],
]) {
const reports = bindTrainPath(p, ids, fix(0, 1000, 0));
const learnt = [1115, backM].map((eastM, i) => {
assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0)));
return reports.direction;
});
const learnt = reportDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [
1115,
backM,
]);
assert.deepEqual(learnt, [1, want], `${label}, from the newest reports`);
assert.deepEqual(
playDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [
@@ -367,11 +413,10 @@ test('a train turns 15 m back from where it ran to, not 14.9 m', () => {
test('GPS jitter of up to 14 m at a standing train keeps its direction', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const reports = bindTrainPath(p, ids, fix(0, 1000, 0));
const learnt = [1600, 1588, 1600, 1586, 1599, 1587].map((eastM, i) => {
assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0)));
return reports.direction;
});
const learnt = reportDirections(
bindTrainPath(p, ids, fix(0, 1000, 0)),
[1600, 1588, 1600, 1586, 1599, 1587],
);
assert.deepEqual(learnt, [1, 1, 1, 1, 1, 1], 'from the newest reports');
const played = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.deepEqual(
@@ -387,12 +432,11 @@ test('GPS jitter of up to 14 m at a standing train keeps its direction', () => {
);
// On both sides of where it stopped: 8 m either way, 16 m from end to end.
const both = bindTrainPath(p, ids, fix(0, 600, 0));
assert.deepEqual(
[1000, 1008, 1000, 992, 1000, 1008].map((eastM, i) => {
assert.ok(followFix(both, fix((i + 1) * 15_000, eastM, 0)));
return both.direction;
}),
reportDirections(
bindTrainPath(p, ids, fix(0, 600, 0)),
[1000, 1008, 1000, 992, 1000, 1008],
),
[1, 1, 1, 1, 1, 1],
'both sides, from the newest reports',
);
+2 -1
View File
@@ -188,7 +188,8 @@ export function createTransitCockpitSubject({ state, parts, services }) {
/**
* A vehicle let go of is out of play until a sweep finds it in view. It
* played on while held, so that sweep keeps its clock (rendering.js).
* played on while held, so the next sweep keeps its clock if it finds it in
* view (rendering.js).
*/
function release(entry) {
if (!entry) return;
+13 -11
View File
@@ -958,8 +958,8 @@ test('disable aborts in-flight work and a response that lands late is ignored',
});
/**
* Serves one bus at `place.lat` (read on every poll), enables the layer and
* polls once; returns its entry.
* Serves one bus at `place.lat` (read on every poll), enables the layer, polls
* once and settles; returns its entry.
*/
async function oneBus(app, place = { lat: 42.36 }) {
app.serve('mbta', () => ({
@@ -4930,6 +4930,11 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes',
assert.equal(app.layer.getCockpitSubject(), null);
});
/** A vehicle's icon in the set that draws it, still or moving. */
function iconOf(app, key) {
return app.markers('still').get(key) ?? app.markers('moving').get(key);
}
test('turning Transit off ends a hold; on again, the vehicle shows, a click selects it and Escape deselects it', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
@@ -4950,8 +4955,7 @@ test('turning Transit off ends a hold; on again, the vehicle shows, a click sele
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held');
const icon = app.markers('still').get(key) ?? app.markers('moving').get(key);
assert.equal(icon?.show, true, 'and so is its icon in the set');
assert.equal(iconOf(app, key)?.show, true, 'and so is its icon in the set');
app.viewer.scene.pick = () => app.pickOf(entry);
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, key, 'a click selects it');
@@ -4984,11 +4988,9 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy
}
const key = 'mbta:bus-1';
const [entry] = app.vehicles();
const icon = () =>
app.markers('still').get(key) ?? app.markers('moving').get(key);
assert.equal(icon()?.show, true, 'drawn before the hold');
assert.equal(iconOf(app, key)?.show, true, 'drawn before the hold');
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(icon()?.show ?? false, false, 'hidden at once');
assert.equal(iconOf(app, key)?.show ?? false, false, 'hidden at once');
// The view rides it for a while: frames, a sweep, a poll.
app.run(2_000, 16);
app.settle();
@@ -4997,7 +4999,7 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy
app.settle();
assert.equal(entry.marker.show, false, 'its marker is hidden');
assert.equal(
icon()?.show ?? false,
iconOf(app, key)?.show ?? false,
false,
'and so is the icon the set draws',
);
@@ -5005,7 +5007,7 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy
assert.equal(app.layer.setCockpitSubject(null), true);
app.advance(250);
app.settle();
assert.equal(icon()?.show, true, 'let go: drawn again');
assert.equal(iconOf(app, key)?.show, true, 'let go: drawn again');
});
test('a hold moved to another vehicle lets the first go out of view', async (t) => {
@@ -5069,7 +5071,7 @@ test('a vehicle in view let go of a hold goes on from its own clock', async (t)
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
// One late poll: the lag the feed earns grows.
// One late poll raises the feed's target lag.
app.run(TRANSIT_POLL_MS + 10_000);
fixAt += TRANSIT_POLL_MS;
north += 0.001;
+2 -1
View File
@@ -1134,7 +1134,8 @@ export function createRendering({ state, services, parts }) {
visibility.noSample = noSample;
const wasShown = entry.marker.show;
const wasVisible = state._visible.has(entry);
// Let go of a hold, it played on (cockpitSubject.js): its clock stands.
// Just let go of a hold (cockpitSubject.js): it played on, so keep
// its clock.
const playedOn = entry.releasedFromHold === true;
entry.releasedFromHold = false;
if (visible) state._visible.add(entry);