Skip to content

fix: reject unsafe duet alignment previews - #15

Merged
cchacs merged 4 commits into
mainfrom
codex/duet-alignment-safety
Sep 29, 2026
Merged

cchacs merged 4 commits into
mainfrom
codex/duet-alignment-safety

Conversation

@cchacs

@cchacs cchacs commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes get-flashbacks/feedBack#98.

Summary

  • checks word/syllable alignment timestamps for non-monotonic data and >8-second gaps within a caller lyric line
  • rejects segment spans that are non-numeric, non-finite, or reversed (end before start) — /save writes d = end - start with no d <= 0 filter
  • per-segment and monotonicity checks apply at every granularity; the within-line gap rule stays word/syllable-only because it needs the server's new_line markers
  • rejects suspect previews with HTTP 422 before they can reach the separate save flow, preserving existing lyrics
  • the align error panel now renders the details the 422 already carried, so a rejected preview names the offending segments
  • allows long pauses at explicit line boundaries
  • adds a duet-shaped regression case (How / can / you at 0.031, 0.11, 14.49 seconds)

Validation

  • python3 -m pytest -q — 33 passed
  • node --check screen.js

Pullfrog  | View workflow run | via Pullfrog | Using Big Pickle (free) | 𝕏

@codacy-production

codacy-production Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 high

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
ErrorProne 1 high

View in Codacy

🟢 Metrics -328 complexity · 0 duplication

Metric Results
Complexity -328
Duplication 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@pullfrog pullfrog 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.

ℹ️ No critical issues — minor suggestions inline.

Reviewed changes

This run reviewed PR #15: "fix: reject unsafe duet alignment previews". The PR adds a plausibility guard in routes.py that rejects word/syllable alignment previews with non-monotonic timestamps or >8s gaps within a lyric line (resetting the line window when new_line is true), returning HTTP 422 with a short error list. It also adds two regression tests in tests/test_helpers.py covering the duet example and a boundary case where the gap occurs across a line break.

  • Guard implementation: _alignment_plausibility_errors checks for empty/non-list/shape errors, enforces monotonic start times (returns immediately on violation), and for word/syllable granularity flags a gap > 8.0s between consecutive segments within the same line (line window reset on new_line). Called only from ls_align when the alignment server returns a 200 response.
  • Test coverage: Two new tests covering (a) the reported duet case (gap > 8s within line) and (b) a legitimate large pause across a new_line boundary.
  • Integration: The 422 is surfaced only on the read-only /align preview path; the UI's lsAlign() shows the error message but discards data.details (the guard already computes details: plausibility_errors, but the frontend never renders them). The write paths /save and /save-lyrics remain independent shape validators.

Notes on efficacy (from specialist investigation)

The new guard does reject all three signatures from the linked issue (the reported How/can/you at 14.49s gap, the second singer line with ~16s gap, and the combined 68-line case). However, the heuristic has several inherent edge cases worth acknowledging:

  • The 8.0s threshold is arbitrary; same defect passes if the stray word is < 8.0s away or if consecutive pairs stay under threshold even across a very long "line" (window never reset except by new_line).
  • The guard trusts the server's new_line markers to delimit lines; if the server mis-flags a stray word as new_line, the check resets and the gap goes undetected. Conversely, if a legitimate multi-line stanza lacks new_line markers (server omits them), the guard treats the whole thing as one line and can flag a large intentional pause as implausible.
  • The guard only evaluates start (monotonicity and gap); it does not inspect end, so end < start (negative duration) or end == start (zero duration) pass the guard but produce d < 0 or d == 0 when converted. The /save route writes d = seg.end - seg.start with no d <= 0 filter (unlike /save-lyrics which drops d <= 0), while the host loader (per docstring) tolerates non-positive durations. The guard is also bypassed entirely for granularity == "line" (returns empty errors by design at L279-280) — non-monotonic or malformed starts at line granularity pass through unflagged by this helper.
  • Defense-in-depth: the guard runs only in ls_align (preview). Hand-crafted POSTs to /save or /save-lyrics bypass it entirely (both already have their own shape validation; only /save-lyrics normalizes/sorts). The shipped UI cannot reach an ungated alignment-derived save because _lsAlignmentResult is only populated from a successful gated /align response, so the practical risk is API surface, not the UI flow.

Recommended follow-ups (non-blocking)

  1. Surface the computed details array in the UI when a 422 occurs (screen.js:200-206 currently only shows data.error). Exposing which specific segment/gap triggered rejection would help users understand and recover (e.g. try line granularity).
  2. Consider extending the guard to also sanity-check end (e.g. end >= start and finite) and/or add a soft per-line span cap in addition to the consecutive-pair gap, or document the 8.0s assumption. At minimum, add tests for the edge cases (new_line reset, sub-8s gap, granularity='line' bypass, end < start).
  3. Either also gate /save with the same plausibility check (defense-in-depth for direct API calls) or explicitly document that /align is the only plausibility-gated path. Given /save already validates shape/finite values and the UI flow is gated, this is a design choice rather than a correctness bug for the shipped path.

ℹ️ Nitpicks

  • routes.py:297-301 — consider extracting the 8.0s constant (e.g. MAX_GAP_WITHIN_LINE_SECONDS = 8.0) to make it configurable/testable and self-documenting.
  • tests/test_helpers.py:21-29 — consider adding a quick assertion on the exact error string format to prevent accidental regression of the message, or add cases for the reset/bypass behaviors noted above.
  • The frontend drops diagnostics: screen.js:204 uses only esc(data.error). If you keep the 422 shape, render data.details?.join('\n') (escaped) in the error panel so users see which segment triggered the rejection.

Pullfrog  | Fix it ➔ | View workflow run | Using Big Pickle (free) | 𝕏

@pullfrog

pullfrog Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Addressed the findings in review 5345922682 (body-only — it has no inline threads, so there was nothing to reply to or resolve individually). Pushed as 5484926.

Applied

  • Frontend drops diagnostics (screen.js:200): the 422 already computed details, but the error panel only rendered data.error. It now renders the list escaped, so a rejected preview names the offending segment instead of just "Alignment failed".
  • end was never checked: /save writes d = end - start with no d <= 0 filter (unlike /save-lyrics), so a reversed span reached lyrics.json and core's loader keeps it. The guard now rejects non-numeric, non-finite, and end < start — float() silently accepts "NaN"/"Infinity", so math.isfinite is needed here as it is on start.
  • line granularity bypassed the whole helper: the early return [] meant non-monotonic or malformed line previews were unflagged. The per-segment and monotonicity checks now run at every granularity; only the within-line gap rule stays word/syllable-only, since it depends on the server's new_line markers (which line responses don't carry) and a long gap between two lines is not a duet defect.
  • Extracted MAX_GAP_WITHIN_LINE_SECONDS with the 8.0s assumption documented inline.
  • Tests (30 → 33 passing, plus node --check screen.js): sub-threshold gap still accepted, all three unusable-end cases, the line-granularity split, and the exact before segment 3 message — that string is now user-facing in the error panel, so it's worth pinning.

Deliberately not changed

  • Gating /save with the plausibility check: agreed this is a design choice, not a bug. The shipped UI can only reach an ungated alignment-derived save if _lsAlignmentResult is populated outside a successful /align, which it isn't — both /save and /save-lyrics keep their own shape validation. Happy to add it as defense-in-depth if you want the API surface closed too.
  • A per-line span cap: a second arbitrary threshold on top of the gap rule would reject legitimate long lines, so the documented constant is the better trade. The stray-word-passes-if-under-threshold limitation is inherent to a consecutive-pair heuristic.

Pullfrog  | View workflow run | via Pullfrog | Using Big Pickle (free) | 𝕏

pullfrog Bot and others added 2 commits September 29, 2026 01:30
Follow-up to the plausibility guard: the 422 already carried a
`details` list that the UI dropped, and the per-segment checks
skipped `end` and skipped `line` granularity entirely.

- render `data.details` (escaped) in the align error panel so a
  rejected preview names the offending segments
- reject non-numeric, non-finite, or reversed `end` values — /save
  writes `d = end - start` with no `d <= 0` filter
- keep the within-line gap rule word/syllable-only (it needs the
  server's `new_line` markers) but apply the per-segment and
  monotonicity checks at every granularity
- extract MAX_GAP_WITHIN_LINE_SECONDS and document the assumption
- cover sub-threshold gaps, unusable end times, and the line-granularity
  split with tests
CodeFactor flagged this function as a Complex Method (routes.py#L283-330).
Extract span parsing (_parse_segment_span) and the within-line gap check
(_within_line_gap_error) into their own helpers so the main function reads
as a sequence of checks. Pure refactor - same error strings, same
behavior, verified against the existing test_helpers.py cases.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2BDXmZrLF1kq7RE823NHw
@get-flashbacks get-flashbacks deleted a comment from coderabbitai Bot Sep 29, 2026

@pullfrog pullfrog 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.

ℹ️ No critical issues — one consistency nit inline. The refactor is behaviour-preserving and the prior follow-ups are all addressed.

Reviewed changes

This run reviewed the two commits pushed since the previous pullfrog review of #15 (5486526, 7551137).

  • Surface the rejection details: screen.js now renders the 422 details list as an escaped <ul> inside the existing error panel, so a rejected preview names the offending segments instead of just saying "unsafe to save".
  • Validate segment end times: _parse_segment_span rejects non-numeric and non-finite end as well as end < start, and these checks now run at every granularity rather than being short-circuited by the old granularity not in {"word", "syllable"} early return. The within-line gap rule stays word/syllable-only, which is right — it is the one rule that needs the server's new_line markers.
  • Split the guard for readability: _parse_segment_span and _within_line_gap_error extracted as module-level helpers with MAX_GAP_WITHIN_LINE_SECONDS promoted to a named constant. I checked the extraction against the previous inline logic: gap <= 8.0 is the exact complement of the old gap > 8.0 for the finite start values already guaranteed by the isfinite check, and end == start, overlapping word spans, and equal consecutive start values all still pass as before.
  • Test coverage: four new assertions — the segment number pinned in the duet case, a 7.5s sub-threshold gap allowed, the three end failure modes with exact message substrings, and line granularity allowing a 20s inter-line gap while still rejecting out-of-order lines. Each one can fail against a plausible regression. python3 -m pytest -q → 33 passed.

The one thing worth a decision from you is below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Big Pickle (free) | 𝕏

Comment thread routes.py Resolved
@cchacs
cchacs merged commit aa72ed1 into main Sep 29, 2026
5 of 6 checks passed
@cchacs
cchacs deleted the codex/duet-alignment-safety branch September 29, 2026 04:33
@pullfrog

pullfrog Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Addressed the one open thread from this review.

The finding was correct. _parse_segment_span tolerated a missing end key but rejected an explicit end: null, and the tolerated shape is precisely the one /save (routes.py:638-644) and the editor (screen.js:530) cannot write — so a preview could render clean and then 400 on save.

Fix (commit 99c3418, pushed to codex/duet-alignment-safety): end is now required unconditionally, read in the same try as start so a missing key and an explicit null produce the identical alignment segment N has no numeric end time. The return type narrows to tuple[float, float] | str, and the docstring no longer promises a None case. This is the smaller of the two options the review offered and matches the shape ls_align's own docstring declares.

Tests: the three within-line-gap tests were written without end at all and now carry it; a new test pins both JSON spellings of a missing end to the same verdict. python3 -m pytest -q → 34 passed (was 33), node --check screen.js clean.

A re-read of the review before finishing turned up no new threads.

Task list (5/5 completed)
  • Read routes.py plausibility guard + /save handler to verify the finding
  • Decide on the single end contract and implement it
  • Add/adjust tests for the agreed contract
  • Run pytest + node --check, review diff, commit
  • Push, reply to thread, resolve if warranted, report progress

Pullfrog  | View workflow run | via Pullfrog | Using Big Pickle (free) | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: lyrics-sync accepts implausible word timings for duet vocals

1 participant