Skip to content

#600 stage A: analyze_beats task (numpy/scipy beat tracking + anchor calibration) #625

Closed

Description

@dkackman

Stage A of #600, from plan v2, section Stages → A — analyze_beats (with Design → Surfaces → New task analyze_beats). The plan comment is authoritative; this restates it.

Filed by the feature lead, claude-opus-5-5 via anthropic.

Builds

  • Onset envelope, autocorrelation tempo and DP beat tracking in dw/dsp.py, numpy/scipy only, no librosa (Q1, decided).
  • RMS-peak fallback when the onset envelope is too flat to track.
  • Anchor calibration: two or more anchors warp detected beats piecewise-linearly through them; one anchor plus tempo_bpm builds an even grid.
  • The analyze_beats task in a new dw/tasks/beats.py (dw/tasks/task.py is near its line cap), registered with returns="json" and no assessment flag; domain rows.
  • Arguments: audio, sample_rate?, tempo_bpm?, anchors? (list of {beat_index, seconds} or of seconds), min_bpm, max_bpm.
  • Returns {bpm, beats:[s], downbeat_phase?, method: "onset"|"rms_peaks"|"grid", calibration: {offset_s, drift, anchors_used}, warnings}.

Owes

  • Tests: synthetic click tracks at 90 and 128 BPM (beats within ±20 ms); a swung track; silence; a fallback case; anchors (one anchor + BPM gives an exact grid; two anchors remove a known drift); test_task_discovery.
  • Docs: a TASKS.md section; one line in the minimax-music3 skill.

Deploy path

Server deploy (engine code: restart dw.serve so the worker picks it up).

Passes when

Its own repro works:

  • list_tasks shows analyze_beats;
  • on a Music 3 output in a one-step workflow it returns bpm and an ascending beats list spanning the song, method: "onset";
  • silence returns an empty or rms_peaks result with a warning, never a crash;
  • one anchor plus tempo_bpm returns an exact even grid from the anchor (method: "grid");
  • two anchors move the nearest beats onto them;
  • min_bpm >= max_bpm, or an anchor past the song's end, is refused by validate_workflow (or at run start where the static pass can't see it);

and every pending: #<this issue> case the tester writes passes.

Activity

  1. added
    featureWork bigger than a fix: designed with Don, built in stages (harnest R11)
    owner:leadFeature lead's turn (harnest R11)
    stageA child issue: one stage of a feature
    on Oct 5, 2026
  2. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Progress (claude-opus-5-5 via anthropic): branch feat/600-a-analyze-beats pushed with the engine side - dw/dsp.py beat functions, dw/tasks/beats.py (analyze_beats, registered via a new dw/tasks/registry.py), domains and static checks in dw/task_domains.py. Remaining: unit tests, TASKS.md / skill / ARCHITECTURE docs, merge, deploy, hand-off.

  3. added 2 commits that reference this issue on Oct 6, 2026
  4. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Stage A built (claude-opus-5-5 via anthropic).

    Shipped: develop @ 3c97709 (merge of feat/600-a-analyze-beats). Deploy: [deploy 02:06:02] deployed develop @ 3c977092, healthy, mcp=true.

    Plan items covered

    • dw/dsp.py (numpy/scipy only, no librosa): onset_envelope (spectral flux, 10 ms hop), estimate_tempo (autocorrelation under a log-normal prior; tempo_bpm narrows the prior when not laying a grid), track_beats (Ellis DP, head and tail beats trimmed), rms_peaks (fallback), downbeat_phase, warp_times.
    • analyze_beats in new dw/tasks/beats.py, registered returns="json" with no assessment flag. Arguments: audio, sample_rate?, tempo_bpm?, anchors?, min_bpm=60, max_bpm=200.
    • Returns {bpm, beats, downbeat_phase, method: onset|rms_peaks|grid, calibration: {offset_s, drift, anchors_used}, warnings}. Each warning also goes through emit_warning.
    • Anchors work three ways:
      • two or more warp the beats piecewise-linearly through them;
      • one alone shifts every beat;
      • one plus tempo_bpm lays an exact grid with no detection.
    • Domain rows: sample_rate, tempo_bpm, min_bpm and max_bpm must be positive.
    • validate_workflow refuses:
      • min_bpm >= max_bpm;
      • malformed anchors: mixed kinds, out of order, or a negative or non-whole beat_index.
    • At run start it refuses:
      • an anchor past the song's end;
      • a beat_index past the number of detected beats;
      • a grid whose beat 0 falls before 0 s.
    • Silence returns beats: [], bpm: null, method: "rms_peaks" and a warning. A track with no clear onsets returns rms_peaks and a warning.
    • Tests: tests/test_analyze_beats.py and tests/test_task_discovery.py.
      • Click tracks at 90 and 128 BPM land within ±20 ms; swing; silence; the fallback.
      • Anchors: the grid, drift removal with bare and indexed anchors, a one-anchor shift.
      • Static refusals, a real .wav run, and the registered handler.
    • Docs: a docs/TASKS.md section, one line in the minimax-music3 skill, and the docs/ARCHITECTURE.md rows.

    Deviations from the plan

    • register_command and the registry tables moved to a new dw/tasks/registry.py. dw/tasks/task.py re-exports them, so imports are unchanged. Reason: task.py was over the 1100-line ceiling, so beats.py registers its own handler. task.py is now 1031 lines.
    • The result has one extra key, duration_seconds, so you can check that the beats span the song.
    • A bare-seconds anchor snaps to the nearest detected beat, so it corrects drift of under half a beat. {beat_index, seconds} anchors name the beat explicitly.
    • If two bare anchors snap to the same beat, the later one is dropped with a warning.
    • downbeat_phase is null for grid and rms_peaks.

    No existing MCP shape changed.

  5. added and removed
    owner:leadFeature lead's turn (harnest R11)
    on Oct 6, 2026
  6. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Architecture review queued by the loop driver: this hand-off changed dw/ or dw_mcp/ on develop (85471b4fa2..3c97709249: dw/dsp.py dw/task_domains.py dw/tasks/beats.py dw/tasks/registry.py dw/tasks/task.py). The reviewer checks it against docs/ARCHITECTURE.md before the tester verifies.

  7. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Architecture review: pass (claude-opus-5-5 via anthropic).

    Read 85471b4f..3c977092 under dw/ (the two #625 commits: dw/dsp.py, dw/task_domains.py, dw/tasks/beats.py, dw/tasks/registry.py, dw/tasks/task.py) against docs/ARCHITECTURE.md and stage C item 3.

    • Second owner: none. analyze_beats decodes through audio_utils.waveform_and_rate, coerces through coerce_number, and checks domains through task_domains.check_arguments. Its cross-argument rules live in task_domains.beats_problems, which the static pass and the run both call. The measurement is in dw/dsp.py, which still imports nothing from dw (Signal processing row). Warnings go out through events.emit_warning. The only checks the run makes itself are the ones that need the decoded song: an anchor past the end, a beat_index past the detected beats, and a grid that starts before 0 s.
    • Build vs. buy: none. librosa isn't in pyproject.toml (Q1 decided against it). The pieces scipy already provides come from scipy: signal.stft, correlate, find_peaks and argrelmax. The autocorrelation tempo prior and the Ellis DP aren't provided by any declared dependency.
    • The map: the Adding a task row now points to dw/tasks/registry.py and names beats.py as a self-registering task module. The Task argument domains row names beats_problems and beats_errors. The beat functions fall under the existing Signal processing row (dw/dsp.py), which needs no change.
    • Context: rationale is in the docstrings of beats.py, registry.py and dsp.py. No CLAUDE.md changed.

    Not a finding, just for the record: the downmix pattern now in dsp.mono_float64 predates this change in dw/tasks/loop_bed.py:430, and that line could call the new helper at the next consolidation.

    Not checked here because it's the hook's and CI's job: this change adds two modules (beats.py and registry.py), and docs/stabilization/baseline.json (modules: 175) wasn't touched in this range.

  8. 36 remaining items

  9. added and removed
    status:verifiedTester confirmed the fix via a real MCP call
    on Oct 6, 2026
  10. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Reopened: bounce-2's fix (cb04ee98) regressed a real song. Refixed. Shipped: cbf614a6, merged to develop as e8beed84. Deploy: [deploy 05:55:51] deployed develop @ e8beed84 (healthy after 5s, mcp=true).

    Lead: claude-fable-5-1 via anthropic, at Don's request after he asked how to judge cb04ee98.

    What was wrong

    cb04ee98 (detrend the tempo envelope, keep tracked beats only when periodicity >= 0.3 or salience >= 3) was written against C-F208 arm 2 as it then stood, and the triage after it found that case was a real pulse. Nobody had checked the commit on real songs. I ran the parent (1c5f3d04) and b96fe24c on 8 Music 3 songs from Don's workspaces and 7 controls:

    • noise-bed.wav (the rewritten arm 2) is rms_peaks on both builds. The commit was never needed for the corrected case.
    • acorn-wars (acorn-wars/assets/score.mp3, caption: 88 BPM half-time orchestral build) lost its beats: parent onset 100 BPM / 125 beats / interval CV 2.4%; b96fe24c rms_peaks. Its strongest period is 50 BPM (detrended autocorrelation 0.65); its in-range octaves at 100 and 200 sit level with the song's other repeats (0.18 vs 0.23), the detrended search picked the 200 BPM range edge, and the gate threw the beats away.
    • shedding-skin (caption 76-84 BPM a cappella, rubato) moved 139.5 -> 69.8 BPM, the caption's octave. It passed the gate by salience alone (periodicity 0.297 < 0.3).
    • Two ambient controls (parhelion score, inner-space world bed) went onset -> rms_peaks: the detrend doing its job.
    • Five songs unchanged.

    The fix

    1. estimate_tempo always holds the range's best against the pulse found over 30-300 BPM and takes the pulse's octave when it is the more periodic. The fallback already did this, but only once the range's best fell under 0.2; acorn-wars's sat at 0.23.
    2. The confidence gate no longer falls back to rms_peaks. A tracked pulse that is faint keeps its beats and warns ("the pulse is faint (periodicity …) - … pass anchors or tempo_bpm if they are off"). A wrong grid can be checked against the song; a missing one cannot. The detrend stays.

    Tests: tests/test_analyze_beats.py gains TestRange::test_a_weak_tempo_in_the_range_yields_to_a_strong_pulse_outside_it (a 50 BPM click track with a soft 190 BPM train at periodicity ~0.22: the old code returned 95.2, the pulse's double period; now 100) and TestFaintPulse (method stays onset, one warning naming anchors). 68 pass in the file; the suite is 8650 passed, 1 failed - tests/test_api_contract.py::test_the_committed_document_is_current, which fails identically on pristine a3522de0, so it is develop's, not this change's (the OpenAPI document is stale around the realized/note fields; whoever owns #626's plan_cuts API additions should run scripts/dump_openapi.py + npm run gen:api). Docs: TASKS.md analyze_beats paragraph.

    Verified on lem @ e8beed84 (CPU, outputs deleted)

    • acorn-wars asset:score.mp3: onset, 100.0 BPM, 125 beats, no warnings (job 7fe1b7faf5a2).
    • shedding-skin asset:shedding-skin-quartet/take1-raw.mp3: onset, 69.77 BPM, 190 beats, no warnings (job e74eb094706f).
    • All 15 files on this tree match b96fe24c except acorn-wars, which matches the parent.

    For the tester

    Re-run C-F205 to C-F211 as written. C-F208 arms 1-3 hold on this tree (arm 2 rms_peaks + "no reliable beat", arm 3 onset at 80). Nothing in plan_cuts (#626) reads the beats result's method or warnings, only beats and duration_seconds, so B is unaffected.

    For Don (not blocking this)

    • Stage A's tests pin only synthetic clicks. A couple of short real Music 3 excerpts as fixtures would have caught cb04ee98 before it merged; worth a follow-up issue.
    • The dw-agent checkout's uncommitted edits on feat/600-A-analyze-beats-quiet-average (the thing blocking #600 stage B: plan_cuts task (line/stanza/beat segmentation) + music-video-cuts template #626's hand-off) are a third attempt at the old C-F208: an average-level gate at -45 dBFS. The case it targeted was wrong and the gate would silence quiet real songs. My recommendation is git checkout -- . there; nothing in them is in this fix.
  11. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Correction to the note above: the stale OpenAPI document was from #647's get_job_workflow note field (1760a48b), not #626. Regenerated in 2e8fced0 on develop under the pinned fastapi/pydantic; test_api_contract.py is 72 passed, so the suite is clean again for the tester.

  12. dkackman commented on Oct 6, 2026

    @dkackman
    OwnerAuthor

    Verified by tester (claude-opus-5-5 via anthropic) against lem on develop @ 95fc37f. C-F205 to C-F211 were re-run as written. All pass.

    • C-F205
      • list_tasks lists analyze_beats, and it is not in assessment.
      • get_task shows audio, sample_rate, tempo_bpm, anchors (seconds or {beat_index, seconds}), min_bpm 60 and max_bpm 200.
      • get_guide("tasks", section="analyze_beats") names bpm, beats, downbeat_phase (null when none stands out), method onset/rms_peaks/grid, calibration {offset_s, drift, anchors_used} and warnings.
      • The dw:minimax-music3 skill (Run and judge, step 5) points at analyze_beats, and at tempo_bpm plus one anchor for a grid.
    • C-F206
      • Job 2f89d9291b29: 120.0 BPM, 40 beats from 0.0 to 19.5 at a 0.5 s step, onset, no warnings.
      • Job 7cd2b64e6866: 100.0 BPM, 34 beats at a 0.6 s step, onset, no warnings.
    • C-F207
      • Job ef5259510e24: onset, 85.71 BPM, beats 0.19 to 29.77, no warnings.
      • Job f93e5587e0e3 (60-90): 85.71.
      • Job 1305a58025fa (140-200): 171.43, folded, with the faint-pulse warning (periodicity 0.23). The case allows this.
    • C-F208 (the refix target)
      • Silence, job 8ab9b67ddb8a: bpm null, beats [], rms_peaks, "the track is silent" warning.
      • noise-bed, job 181863db19e0: rms_peaks, 157.89, "no reliable beat was found" warning.
      • room-bed, job 35a0c2aa1ade: onset, 80.0 BPM, beats at a 0.75 s step, no warnings.
    • C-F209
      • Job b469ae4f86c9 (anchors [1.25]): grid, 120, beats 0.25, 0.75, 1.25 … 29.75.
      • Job f9a555b91afc ({beat_index 0, seconds 1.25}): grid, beats 1.25 … 29.75.
      • Job 2d7969aa7fa7 (96 BPM, {beat_index 4, seconds 3.0}): 0.5, 1.125, 1.75, 2.375, 3.0 ….
    • C-F210
      • Jobs 451cf0ba4492 and 5013302c9f5f: 120 BPM, onset, beats 0.1, 0.6 … 19.6, with 2.1 and 15.1 landing on the anchors.
      • Both returned offset_s 0.1, drift -0.0, anchors_used 2.
    • C-F211
      • validate_workflow refuses min_bpm 120 against max_bpm 120, and 150 against 90, at steps[0].task.arguments.min_bpm.
      • Anchors past the end fail at run start:
        • job 82ff924dbfa6: "anchors[0] (45 s) is past the song's end (30.023 s)";
        • job 8390ed2135dc: the same for 31 s.
      • The boundary cases succeed:
        • job cfe937f7e2b8: anchors [29.9];
        • job 806cb2b06026: 119-120, with a warning that no octave of the 85.8 BPM pulse fits and the beats keep to 119.0.

    Every job's output was deleted with delete_output. The pending: #625 markers were already dropped in harnest commit c93b812, so no suite edit was needed.

  13. added
    status:verifiedTester confirmed the fix via a real MCP call
    and removed on Oct 6, 2026
  14. added 3 commits that reference this issue on Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureWork bigger than a fix: designed with Don, built in stages (harnest R11)owner:testerTester's turn to actstageA child issue: one stage of a featurestatus:verifiedTester confirmed the fix via a real MCP call

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions