Skip to content

fix(observations): right-align a stream's data against its own expected series - #302

Merged
seabbs merged 11 commits into
mainfrom
fix/285-split-lead-in
Aug 28, 2026
Merged

seabbs merged 11 commits into
mainfrom
fix/285-split-lead-in

Conversation

@seabbs-bot

@seabbs-bot seabbs-bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #285.
Closes #306.

What is actually going on

The issue reads as Split being the odd one out. It is not: the
observation-error loop right-aligns in one direction only, and every model
shares that loop.

diff_t = length(y_t) - length(Y_t)
@assert diff_t >= 0 "The observation vector must be at least as long as the expected observation vector"
for i in eachindex(Y_t)
    y_t[i + diff_t] ~ dist(i)
end

More observations than expected values is fine, and the head of y_t goes
unscored (the chain's lead-in, #266). More expected values than observations is
rejected. A single stream never has to hit the second case, because the caller
picks n and can always make the expected series come out at length(y). A
Split runs its streams in parallel off one expected series, so one n has to
serve every stream, and a stream whose chain consumes a shorter lead-in is left
with more expected values than the caller has observations. There is no n that
satisfies both, hence the manual pad.

The change

Score the overlap of the two series rather than requiring one of them to be at
least as long as the other. The two series end at the same time point, so
right-aligning is the whole rule:

  • a longer y_t keeps its unscored head — the chain's lead-in, unchanged;
  • a longer Y_t keeps an unobserved head — run-in the data does not cover.

No observation is ever dropped by the new direction, so nothing that used to be
scored stops being scored. What used to be an assertion is now a model that runs
longer than its data, which is a legitimate setup in its own right. A Split
needs no per-stream arithmetic: each stream right-aligns its own data against
its own expected series, and the caller passes each stream the observations it
has.

BinomialError's number-of-trials vector is aligned the same way. It used to be
required to match the expected series exactly, which would have forced a
BinomialError branch of a Split to pad N even though its successes no
longer need padding. N is now right-aligned against the expected series like
the observations are, so it can be given with one entry per observation or one
per expected value; both put the same trials on the same time points and only
the unused head differs. A scalar N still broadcasts. An N too short to
cover every scored step is rejected with a message saying how many entries are
needed.

Tests

  • Two parallel streams with lead-ins 2 and 7 on a 20-point expected series,
    given 13 observations each with no padding. The stream with the shorter
    lead-in produces 18 expected values, and the log-joint is checked against
    the sum of logpdf over the last 13 of them, so an alignment off by the
    lead-in difference fails.
  • The same shape end to end through IDModel on a renewal process: moving the
    earliest observation of the shorter-lead-in stream moves the log-joint, so
    nothing is dropped from its head.
  • The single-stream contract in the new direction, for a plain vector and for
    a MissingObservations carrier.
  • BinomialError trials given at data length and at expected-series length
    produce the same log-joint, a scalar N still broadcasts, and an N too
    short to cover the scored window is rejected.
  • Aggregate's alignment in all three directions — expected series longer
    than the data, equal, and data longer — with a log-joint check, so windows
    taken off the head of the expected series would fail. This one is a
    characterisation test, not a fix: the behaviour is already correct,
    because fix(Aggregate): right-align a delay nested inside an aggregation #307's window offset generalises to a negative value on its own.
    Nothing exercised the negative direction, and scoring the overlap is what
    makes that direction reachable, so it is pinned here rather than left to a
    future change to break silently.

Relationship to the other open observation PRs

Checked against every one of them; none is a replacement for this.

CI

One red check, ad / Enzyme forward, and it is CANCELLED rather than failed —
the 60-minute job cap that backend hits across the repo. Everything else is
green on cba182f.

Relationship to #276

Independent. observation_lead_in on fix/266-observation-lead-in reports what
a chain consumes; the branch was read but not touched. An alternative fix was to
have Split trim each stream's incoming expected series by that stream's
lead-in, which needs the walk that PR adds. That is strictly more machinery for
the same result, so this takes the alignment route instead and the two do not
conflict. observation_coverage there assumes the surplus is always on the
observation side; once both land it is worth reporting the run-in direction too.

Interaction with the work merged since this branch was cut

main moved by ten PRs while this sat open, two of which touch the same
alignment machinery. Both were checked directly.

main also renamed _at to at. That sits in a different part of the
observation-error loop and merged cleanly; _at remains as an alias.

Known limitations

The two this PR originally recorded are both closed. The BinomialError trials
gap (#306) is fixed here, and the Aggregate left-alignment (#301) was resolved
by #307 on main.

One component still assumes the two series are the same length. ReportTriangle
asserts size(observed, 1) == length(Y_t) and indexes the expected series at the
data's reference day, so it cannot sit under a Split whose branches have
unequal lead-ins. It fails loudly rather than misaligning, so nothing is silently
wrong, and the window walk is untouched here. Filed as #316.

Verification

main was merged into this branch (cba182f). The only conflict was an
append/append in test/unit/observation_models/observations.jl, where both
sides had added a testitem at the end; both are kept. main's NEWS.md
deletion is byte-identical to this branch's, so it merged with no change.
pre-commit and the runic formatting check pass on the merge.

Before the merge this PR was CONFLICTING, which meant GitHub could not compute
refs/pull/302/merge and no pull_request workflow ran at all. The previous
head commit carried zero checks. The merge is what restores CI, and the full
matrix now runs on cba182f.

Reproductions run directly against the merged tree:

Suite run on the merge commit in this worktree:

  • julia --project=test test/runtests.jl skip_quality — 1422 passed, 0
    failed, 16m14.4s.

The quality and AD suites were not run locally; CI covers both on cba182f.
The counts quoted in earlier revisions of this description were pre-merge and no
longer apply.

Attribution

d8039bc carries my commit message over another agent's implementation. Two of
us were working in the same worktree; I committed their uncommitted working tree
with git add -A under a message of my own before they could commit it
themselves. The code in that commit, and the test in 5dbf8e0 under it, are
theirs. Recorded here rather than by rewriting a pushed commit.

This was opened by a bot. Please ping @seabbs for any questions.

Two parallel streams whose chains consume different lead-ins are given
observations of equal length, as the caller has them. The branch with
the shorter lead-in produces more expected values than there are
observations and the error model rejects the data.
The observation-error loop right-aligned the data against the expected
series only when there were more observations than expected values, and
rejected the other direction. Split streams run in parallel off one
expected series, so a stream whose chain consumes a shorter lead-in is
left with more expected values than the caller has observations, and one
series length cannot satisfy every stream at once.

Score the overlap of the two series instead: a longer observation vector
keeps its unscored lead-in, and a longer expected series is unobserved
run-in. Callers pass each stream the observations they have rather than
padding the shorter-lead-in stream with leading missings.
@github-actions

Copy link
Copy Markdown
Contributor

Try this Pull Request!

Option 1: Julia Package Manager

Open Julia and type:

import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="fix/285-split-lead-in")
using ComposableTuringIDModels

Option 2: Local Checkout

If you have the repo locally:

git checkout fix/285-split-lead-in
julia --project=. -e "using Pkg; Pkg.instantiate()"

@codecov

codecov Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
ad-enzyme-reverse 66.44% <93.75%> (+0.55%) ⬆️
ad-forwarddiff 66.98% <93.75%> (+0.53%) ⬆️
ad-mooncake-forward 66.98% <93.75%> (+0.53%) ⬆️
ad-mooncake-reverse 66.98% <93.75%> (+0.06%) ⬆️
ad-reversediff 67.14% <93.75%> (+0.52%) ⬆️
ad-reversediff-compiled 67.14% <93.75%> (+0.06%) ⬆️
unit 93.79% <100.00%> (+0.21%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/base/base.jl 25.00% <ø> (ø)
...ion_models/ObservationErrorModels/BinomialError.jl 96.29% <100.00%> (+13.68%) ⬆️
...servation_models/ObservationErrorModels/methods.jl 100.00% <100.00%> (ø)
src/observation_models/Split.jl 96.77% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark comparison vs base

Minimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:

Group 🟢 <50% 🟢 50–75% 🟢 75–95% ⚪ 95–105% 🔴 105–125% 🔴 125–150% 🔴 >150%
Evaluation · · 3 6 · · ·
ForwardDiff · · 1 1 · · ·
ReverseDiff (tape) · · 1 · · · 1
Mooncake reverse · · · 2 · · ·
Enzyme reverse · · · · 1 · ·
Evaluation — 9 benchmarks (by time change)
Benchmark base PR time memory
Model evaluation / RandomWalk latent / rand 460.0 ns 431.0 ns 🟢 0.94× ⚪ 1.0×
Model evaluation / AR latent / rand 641.0 ns 601.0 ns 🟢 0.94× ⚪ 1.0×
Model evaluation / DirectInfections+Poisson / rand 681.0 ns 641.0 ns 🟢 0.94× ⚪ 1.0×
Model evaluation / DirectInfections+Poisson / forward 1.13 μs 1.1 μs ⚪ 0.97× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / rand 2.22 μs 2.17 μs ⚪ 0.98× ⚪ 1.0×
Model evaluation / RandomWalk latent / forward 421.0 ns 430.0 ns ⚪ 1.02× ⚪ 1.0×
Sampling / NUTS (DirectInfections+Poisson, 50 draws) 111.08 ms 113.36 ms ⚪ 1.02× ⚪ 1.0×
Model evaluation / AR latent / forward 531.0 ns 540.0 ns ⚪ 1.02× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / forward 4.72 μs 4.66 μs ⚪ 0.99× ⚪ 1.0×
AD gradients — 7 benchmarks (by time change)
Benchmark base PR time memory
AD gradients / AR latent logjoint / ReverseDiff (tape) 45.34 μs 161.98 μs 🔴 3.57× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / ForwardDiff 16.94 μs 14.83 μs 🟢 0.88× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / Enzyme reverse 3.43 μs 3.71 μs 🔴 1.08× ⚪ 1.01×
AD gradients / DirectInfections+Poisson posterior / ReverseDiff (tape) 106.03 μs 98.78 μs 🟢 0.93× ⚪ 1.0×
AD gradients / AR latent logjoint / Mooncake reverse 6.14 μs 6.35 μs ⚪ 1.03× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / Mooncake reverse 9.95 μs 9.62 μs ⚪ 0.97× ⚪ 1.0×
AD gradients / AR latent logjoint / ForwardDiff 8.84 μs 8.61 μs ⚪ 0.97× ⚪ 1.0×

Release notes live on the GitHub release, built on TagBot's merged-PR list,
so a changelog file in the repo is not kept. The substance of these entries
belongs in the pull request title and body, which is what the release notes
are assembled from.
The trials vector is indexed at the expected-series step, so a per-time-point
`N` given at the length of the data trips the length assertion whenever the
expected series is longer. Cover both alignment directions and the partially
observed carrier.
…data

Scoring the overlap of the observed and expected series left the
number-of-trials vector behind: it was required to match the expected
series and indexed at the expected step, so a per-time-point N of data
length tripped an assertion. It is now resolved against the data, and a
vector of either length is accepted.
Both sides appended a new testitem to the end of
test/unit/observation_models/observations.jl, so the conflict is a plain
append/append and both blocks are kept. main's NEWS.md deletion is
identical to this branch's, so it merges with no change.

main's `_at` to `at` rename and this branch's `_scored_steps` touch
different parts of the observation-error loop and merge cleanly.
This is a characterisation test, not a fix. The behaviour is already correct:
the window offset generalises to a negative value on its own, so windows come
off the tail of the expected series in both directions. Nothing exercised the
negative direction, which scoring the overlap of the observed and expected
series is what makes reachable.

Cover all three cases — expected longer, equal, data longer — with a log-joint
check, so windows taken off the head of the expected series would fail.
@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation preview is ready!

View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR302/

This preview will be updated automatically when you push new commits.

@seabbs-review-bot seabbs-review-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The PR generalises observation scoring so the observed and expected series can be right-aligned regardless of which is longer, replacing the old diff_t >= 0 invariant with a shared _scored_steps helper, and extends BinomialError's trials vector to the same alignment via a new _TrialDist.n_diff. The core alignment arithmetic checks out against the new tests (Aggregate, Split, BinomialError all trace correctly by hand), but CI's ad / Enzyme forward check is red, and the only Enzyme-forward scenario that exercises the touched BinomialError code path is not in the AD fixture registry's known-broken list, so this looks like an unresolved regression rather than a pre-existing flake.

Automated first pass by seabbs-review-bot (Claude sonnet), triggered by: first pass. Not a human review. Comment @seabbs-review-bot to ask for another pass: @seabbs any time, the author's agent once it has pushed changes. Add the no-review label to opt this PR out. Ping @seabbs with any questions.

@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

Merge hazard with the other one of this pair — #325

Verified by actually merging this branch with the other and running the result, rather than reasoning about it.

#302 and #319 both rewrite the two scoring loops in ObservationErrorModels/methods.jl, neither contains the other, and they conflict in exactly the place that matters. The obvious resolution — take the newer branch's side — is a latent BoundsError:

diff_t          = -24            # #302's new direction
_scored_steps   = 25:144         # idx = i + diff_t -> 1:120, in bounds
eachindex(Y_t)  = 1:144          # idx = i + diff_t -> -23:120, OUT OF BOUNDS

Resolve by keeping #319's marginalisation body and #302's _scored_steps bound. With that, the same model evaluates and reports 0 y_t latents on a 120-day series with 33 measurements — #319 doing what it is for, on a shape only #302 makes reachable.

_TrialDist also diverges (n_diff vs main's bare index). Git resolves it in #302's favour on its own, but only because #319 does not touch the line.

Neither branch can carry a regression test for this today, because on each branch alone the combination is unreachable. Whichever merges second should add one. Details and the full reproduction are in #325.

seabbs-bot added a commit that referenced this pull request Aug 26, 2026
#302 and #319 both rewrite the two scoring loops in methods.jl and
neither contained the other, so they conflicted in the place that
matters. Issue #325 records why the obvious resolution is wrong.

Resolved by keeping #319's marginalisation body and #302's _scored_steps
bound. eachindex(Y_t) is only safe while diff_t >= 0, and #302 exists to
make diff_t < 0 reachable, so taking #319's side alone indexes
y.present at i + diff_t <= 0. Ported #302's other changes to the file
explicitly rather than by conflict resolution: the two-way alignment
docstring, both dropped @Assert diff_t >= 0, and _TrialDist's n_diff.

Added the regression test neither branch could carry alone. A carrier
with gaps against a longer expected series: that it evaluates, that no
y_t reaches the chain, that the log-joint equals the observed entries
against their own right-aligned expected values, and that moving the
earliest observation moves it.

Corrected one test inherited from #302. "BinomialError right-aligns its
trials with the data" asserted 0 <= y_t[2] <= N for a gap, which is the
pre-#319 behaviour where a gap is drawn. A gap is now marginalised and
comes back missing. The replacement asserts that and pins the alignment
with a log-joint against each observed entry's own day's trials, which
the old bounds check did not do.

observations.jl 96/96 locally.
seabbs
seabbs previously approved these changes Aug 28, 2026
Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
Closes #299
seabbs
seabbs previously approved these changes Aug 28, 2026
@seabbs
seabbs merged commit bc44d0c into main Aug 28, 2026
1 of 24 checks passed
seabbs-bot added a commit that referenced this pull request Aug 28, 2026
…ling

Keep main's #272/#302 observation-error and forecast files (which superseded
the branch's older right-alignment), keep the branch's new feature file
requirements.jl, and consolidate the observation tests.

Also fixes two pre-existing main defects exposed by the rebase's test run:
- observations.jl had a missing 'end' between two @testItems, so the second
  never ran as its own testitem (main's own CI was failing on this).
- the stale #272 NamedTuple test asserted gaps were sampled as latents; they
  are marginalised out, matching the implementation and the newer gap tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm-reviewed Reviewed by seabbs-review-bot

Projects

None yet

2 participants