diff options
| author | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
|---|---|---|
| committer | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
| commit | c25cbdf6fb6d946175f4335fab77bfea601b56db (patch) | |
| tree | 6f7a94b7b81f999e434f61b73d47e337dfd26bf2 /test | |
| parent | 71f5689252c9f13e70e1c24856904475b2307809 (diff) | |
| parent | 0685fcada9f95fe90f70b387cd7d757da8209624 (diff) | |
Merge tag 'debian/3.2.0_rc1+dfsg-2' into debian/trixie-backportsdebian/trixie-backports
tagging wsjtx 3.2.0~rc1+dfsg-2
Diffstat (limited to 'test')
39 files changed, 5380 insertions, 0 deletions
diff --git a/test/apply_routing_test.f90 b/test/apply_routing_test.f90 new file mode 100644 index 00000000..ac675cc4 --- /dev/null +++ b/test/apply_routing_test.f90 @@ -0,0 +1,630 @@ +! Apply-routing unit driver. Asserts that +! apply_configure_fields (extracted from streaming_io.f90's former nested-internal +! apply_configure_) routes each configure_fields member to its CORRECT params_block +! slot — the coverage gap the fixture gates cannot close (most Phase 4/5 fields are +! inert on the FT8/JT9 fixtures, so a mis-route like his_call->hisgrid passes every +! fixture byte-identical, as proven empirically). +! +! This drives the APPLY side (configure_fields -> params_block), complementing the +! parse-unit drivers (phase4/phase5_parse_test.f90) which drive the PARSE side +! (JSON -> configure_fields). It also exercises the order-sensitive logic that was +! previously review-only: the rxfreq/tx_audio_offset decouple, emedelay-before- +! per-mode-policy (D1), nfa/nfb baseline restore, and the ntol per-mode cap/restore. +! +! Bool swap-blindness (known, bounded): the Phase 6 bool asserts alternate T/F in +! source order, so an ADJACENT apply-line transposition (the realistic copy-paste +! swap) flips a value and IS caught; a swap of two NON-adjacent bools that share an +! asserted value is not (bools are binary). The parse-unit's per-key anchored +! NAME match is the primary swap guard (a swap there requires editing a literal +! key string, not transposing lines). Ints use distinct values, so int-swaps are +! always caught. +! +! params_block is re-exported from streaming_apply (it owns the include); the +! baseline is a realistic params built via jt9_params_init's init routines. +! Compiled + run by test/run-apply-routing-unit.sh against lib/streaming_control.f90 +! + lib/jt9_params_init.f90 + lib/streaming_apply.f90, in an ISOLATED module dir. +program apply_routing_test + use streaming_control, only: configure_fields + use jt9_params_init, only: cli_args_t, init_default_params, & + init_streaming_extra_fields + use streaming_apply, only: apply_configure_fields, params_block + implicit none + integer :: nfail + integer, parameter :: BNFA = 111, BNFB = 222 ! baseline nfa/nfb + nfail = 0 + + call frame_flat() + call frame_npts_c0_guard() + call frame_rxfreq() + call frame_decouple() + call frame_emedelay_survive() + call frame_emedelay_ft8() + call frame_emedelay_q65() + call frame_nfa_nfb_restore() + call frame_ntol_policy() + call frame_mode_trperiod() + call frame_multithreaded_guard() + call frame_qso_guard() + call frame_utc_precedence() + call frame_phase9_pack() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL APPLY-ROUTING CHECKS PASSED' + else + write(*,'(a,i0,a)') 'APPLY-ROUTING: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Build a realistic, fully-defined baseline params (mode 8 / 15 s). + subroutine fresh(p) + type(params_block), intent(out) :: p + type(cli_args_t) :: args + call init_default_params(p, 8, 15.d0, args) + call init_streaming_extra_fields(p, args) + end subroutine fresh + + subroutine frame_npts_c0_guard() + type(configure_fields) :: cfg + type(params_block) :: p + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame npts_c0_array domain guard' + call fresh(p) + md = 9; tr = 60.d0 + p%npts8 = 74736 + cfg%npts_c0_array_set = .true. + cfg%npts_c0_array = -1 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('negative npts_c0_array not applied', p%npts8 .eq. 74736) + cfg%npts_c0_array = 0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('zero npts_c0_array not applied', p%npts8 .eq. 74736) + cfg%npts_c0_array = 81649 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('oversize npts_c0_array not applied', p%npts8 .eq. 74736) + cfg%npts_c0_array = 81648 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('max npts_c0_array applied', p%npts8 .eq. 81648) + end subroutine frame_npts_c0_guard + + ! Read back a c_char(N) params field as a fixed-length string (inverse of the + ! transfer() the apply does). + function s12(arr) result(s) + character(len=12) :: s + character, intent(in) :: arr(12) + s = transfer(arr, s) + end function s12 + + function s6(arr) result(s) + character(len=6) :: s + character, intent(in) :: arr(6) + s = transfer(arr, s) + end function s6 + + ! =================================================================== + ! Frame FLAT: every flat field, distinct value, NO mode/trperiod (so the + ! per-mode-policy block does NOT fire — emedelay survives, ntol/nfa/nfb keep + ! the explicit value). This is the core routing assertion: each value must + ! land in its OWN slot. The mis-route killers are the same-shaped pairs + ! (his_call/hisgrid, tx_audio_offset/nfsplit, min_width/min_sync, + ! dt_tolerance/emedelay). + subroutine frame_flat() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame FLAT: every flat field -> its own slot (no mode/trperiod)' + call fresh(p) + ! Defeat baseline-collision vacuity: lmycallstd/lhiscallstd + ! default .true. (init_streaming_extra_fields), and mybcall/hisbcall are + ! undefined after init. Plant sentinels OPPOSITE to each asserted value, so a + ! dropped/mis-routed apply leaves the sentinel and the assert fails. + p%lmycallstd = .false. ! asserted .true. + p%lhiscallstd = .true. ! asserted .false. + p%mybcall = transfer('zzzzzzzzzzzz', p%mybcall) + p%hisbcall = transfer('zzzzzzzzzzzz', p%hisbcall) + ! Phase 6 sentinels: plant each param OPPOSITE its asserted value (an + ! assert whose expected value == the init default is vacuous). Bools + ! alternate T/F asserted so a swap between adjacent keys flips a value and is + ! caught; ints get a distinct 99 sentinel so a mis-route leaves 99 != asserted. + ! multithreaded_ft8 is NOT set here (it is apply-ignored; see frame_multithreaded_guard). + p%lft8lowth = .false. ! asserted .true. + p%lft8subpass = .true. ! asserted .false. + p%lft8apon = .true. ! asserted .false. + p%lapcqonly = .false. ! asserted .true. + p%lapmyc = .true. ! asserted .false. + p%ljt65apon = .false. ! asserted .true. + p%lhideft8dupes = .true. ! asserted .false. + p%lcommonft8b = .false. ! asserted .true. + p%lenabledxcsearch = .true. ! asserted .false. + p%lwidedxcsearch = .false. ! asserted .true. + p%b_superfox = .true. ! asserted .false. + p%b_even_seq = .false. ! asserted .true. + p%lhound = .true. ! asserted .false. + p%lmultinst = .false. ! asserted .true. + p%lskiptx1 = .true. ! asserted .false. + p%nagainfil = .false. ! asserted .true. + p%nstophint = .true. ! asserted .false. + p%nhint = .false. ! asserted .true. + p%nft8cycles = 99 + p%nft8rxfsens = 99 + p%nmt = 99 + p%ndecoderstart = 99 + p%napwid = 99 + ! Phase 7 sentinels (plant OPPOSITE the asserted value). bools: + ! ltxing asserted .true. -> plant .false.; lmodechanged asserted .false. -> + ! plant .true. (the SENTINEL is load-bearing here since the init default is + ! also .false., matching the asserted value). ints get a distinct 99. + p%ltxing = .false. ! asserted .true. + p%lmodechanged = .true. ! asserted .false. + p%nlasttx = 99 + p%nQSOProgress = 99 + p%nsecbandchanged = 99 + p%ndelay = 99 + ! Phase 8 sentinels (plant OPPOSITE the asserted value; the + ! asserted values are ALSO non-default so neither the sentinel nor the default + ! can mask a dropped apply). nranera default is 6 / ncandthin default 100, so + ! the asserted 8 / 150 differ from both the planted 99 and the init default. + ! utc is NOT exercised here (it shares the nutc slot — see frame_utc_precedence). + p%yymmdd = 99 + p%nranera = 99 + p%ncandthin = 99 + p%ndtcenter = 99 + md = 8; tr = 15.d0 + cfg%depth_set = .true.; cfg%depth = 7 + cfg%submode_set = .true.; cfg%submode = 2 + cfg%mycall_set = .true.; cfg%mycall = 'K5TST' + cfg%mygrid_set = .true.; cfg%mygrid = 'EM10' + cfg%his_call_set = .true.; cfg%his_call = 'DX1ABC' + cfg%his_grid_set = .true.; cfg%his_grid = 'FN31' + cfg%my_b_call_set = .true.; cfg%my_b_call = 'K5TST/B' + cfg%his_b_call_set = .true.; cfg%his_b_call = 'DX1/B' + cfg%my_call_standard_set = .true.; cfg%my_call_standard = .true. + cfg%his_call_standard_set = .true.; cfg%his_call_standard = .false. + cfg%tx_audio_offset_hz_set = .true.; cfg%tx_audio_offset_hz = 1234 + cfg%jt65_jt9_split_hz_set = .true.; cfg%jt65_jt9_split_hz = 2345 + cfg%max_drift_hz_set = .true.; cfg%max_drift_hz = 55 + cfg%dt_tolerance_seconds_set = .true.; cfg%dt_tolerance_seconds = 0.7d0 + cfg%eme_delay_seconds_set = .true.; cfg%eme_delay_seconds = 1.3d0 + cfg%kin_samples_set = .true.; cfg%kin_samples = 99000 + cfg%nzhsym_per_period_set = .true.; cfg%nzhsym_per_period = 42 + cfg%npts_c0_array_set = .true.; cfg%npts_c0_array = 60000 + cfg%min_width_set = .true.; cfg%min_width = 3 + cfg%min_sync_set = .true.; cfg%min_sync = 4 + cfg%n_2pass_set = .true.; cfg%n_2pass = 1 + cfg%robust_mode_set = .true.; cfg%robust_mode = .true. + cfg%nagain_flag_set = .true.; cfg%nagain_flag = .true. + cfg%tx_mode_set = .true.; cfg%tx_mode = 9 + cfg%clear_average_set = .true.; cfg%clear_average = .true. + cfg%nutc_set = .true.; cfg%nutc = 133430 + cfg%ntol_set = .true.; cfg%ntol = 250 + cfg%nfa_set = .true.; cfg%nfa = 180 + cfg%nfb_set = .true.; cfg%nfb = 3900 + ! Phase 6 (23 keys; multithreaded_ft8 excluded — apply-ignored). Bools + ! alternate T/F (asserted); ints distinct (2/4/3/1/150). + cfg%ft8_low_threshold_set = .true.; cfg%ft8_low_threshold = .true. + cfg%ft8_subpass_set = .true.; cfg%ft8_subpass = .false. + cfg%ft8_ap_on_set = .true.; cfg%ft8_ap_on = .false. + cfg%ap_cq_only_set = .true.; cfg%ap_cq_only = .true. + cfg%ap_my_call_set = .true.; cfg%ap_my_call = .false. + cfg%jt65_ap_on_set = .true.; cfg%jt65_ap_on = .true. + cfg%hide_ft8_duplicates_set = .true.; cfg%hide_ft8_duplicates = .false. + cfg%common_ft8b_set = .true.; cfg%common_ft8b = .true. + cfg%enable_dxc_search_set = .true.; cfg%enable_dxc_search = .false. + cfg%wide_dxc_search_set = .true.; cfg%wide_dxc_search = .true. + cfg%superfox_mode_set = .true.; cfg%superfox_mode = .false. + cfg%even_sequence_set = .true.; cfg%even_sequence = .true. + cfg%hound_mode_set = .true.; cfg%hound_mode = .false. + cfg%multi_instance_set = .true.; cfg%multi_instance = .true. + cfg%skip_tx1_set = .true.; cfg%skip_tx1 = .false. + cfg%nagain_filter_set = .true.; cfg%nagain_filter = .true. + cfg%stop_hint_set = .true.; cfg%stop_hint = .false. + cfg%hint_mode_set = .true.; cfg%hint_mode = .true. + cfg%ft8_cycles_set = .true.; cfg%ft8_cycles = 2 + cfg%ft8_rxf_sensitivity_set = .true.; cfg%ft8_rxf_sensitivity = 4 + cfg%ft8_threads_set = .true.; cfg%ft8_threads = 3 + cfg%ft8_decoder_start_set = .true.; cfg%ft8_decoder_start = 1 + cfg%ap_width_hz_set = .true.; cfg%ap_width_hz = 150 + ! Phase 7 (6 keys; all flat pass-throughs). bools alternate T/F (asserted); + ! ints distinct (4/5/7/6) and != the planted 99 sentinel. + cfg%last_tx_seconds_ago_set = .true.; cfg%last_tx_seconds_ago = 4 + cfg%currently_txing_set = .true.; cfg%currently_txing = .true. + cfg%mode_changed_set = .true.; cfg%mode_changed = .false. + cfg%qso_progress_state_set = .true.; cfg%qso_progress_state = 5 + cfg%sec_band_changed_set = .true.; cfg%sec_band_changed = 7 + cfg%delay_units_set = .true.; cfg%delay_units = 6 + ! Phase 8 (4 keys; utc tested in frame_utc_precedence). The cfg members hold + ! the DERIVED legacy ints (utc_nutc/date_yymmdd/n_trials_nranera computed at + ! parse) — here we set them directly. candthin_threshold/dt_center_seconds are + ! reals scaled nint(x*100) at apply: 1.5 -> 150, 0.2 -> 20. + cfg%date_set = .true.; cfg%date_yymmdd = 210703 + cfg%n_trials_set = .true.; cfg%n_trials_nranera = 8 + cfg%candthin_threshold_set = .true.; cfg%candthin_threshold = 1.5d0 + cfg%dt_center_seconds_set = .true.; cfg%dt_center_seconds = 0.2d0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('depth -> ndepth = 7', p%ndepth .eq. 7) + call ok('submode -> nsubmode = 2', p%nsubmode .eq. 2) + call ok('mycall -> mycall = K5TST', trim(s12(p%mycall)) .eq. 'K5TST') + call ok('mygrid -> mygrid = EM10', trim(s6(p%mygrid)) .eq. 'EM10') + call ok('his_call -> hiscall = DX1ABC', trim(s12(p%hiscall)) .eq. 'DX1ABC') + call ok('his_grid -> hisgrid = FN31', trim(s6(p%hisgrid)) .eq. 'FN31') + call ok('my_b_call -> mybcall = K5TST/B', trim(s12(p%mybcall)) .eq. 'K5TST/B') + call ok('his_b_call -> hisbcall = DX1/B', trim(s12(p%hisbcall)) .eq. 'DX1/B') + call ok('my_call_standard -> lmycallstd true', logical(p%lmycallstd)) + call ok('his_call_standard -> lhiscallstd false', .not. logical(p%lhiscallstd)) + call ok('tx_audio_offset_hz -> nftx = 1234 (not nfsplit)', p%nftx .eq. 1234) + call ok('jt65_jt9_split_hz -> nfsplit = 2345 (not nftx)', p%nfsplit .eq. 2345) + call ok('max_drift_hz -> max_drift = 55', p%max_drift .eq. 55) + call ok('dt_tolerance_seconds -> dttol = 0.7', abs(p%dttol - 0.7) .lt. 1.0e-6) + call ok('eme_delay_seconds -> emedelay = 1.3 (survives)', abs(p%emedelay - 1.3) .lt. 1.0e-6) + call ok('kin_samples -> kin = 99000', p%kin .eq. 99000) + call ok('nzhsym_per_period -> nzhsym = 42', p%nzhsym .eq. 42) + call ok('npts_c0_array -> npts8 = 60000', p%npts8 .eq. 60000) + call ok('min_width -> minw = 3 (not minsync)', p%minw .eq. 3) + call ok('min_sync -> minsync = 4 (not minw)', p%minsync .eq. 4) + call ok('n_2pass -> n2pass = 1', p%n2pass .eq. 1) + call ok('robust_mode -> nrobust true', logical(p%nrobust)) + call ok('nagain_flag -> nagain true', logical(p%nagain)) + call ok('tx_mode -> ntxmode = 9', p%ntxmode .eq. 9) + call ok('clear_average -> nclearave true', logical(p%nclearave)) + call ok('nutc -> nutc = 133430', p%nutc .eq. 133430) + call ok('ntol -> ntol = 250 (no policy)', p%ntol .eq. 250) + call ok('nfa -> nfa = 180', p%nfa .eq. 180) + call ok('nfb -> nfb = 3900', p%nfb .eq. 3900) + ! Phase 6 routing (23 keys). Each asserted value is opposite its planted + ! sentinel, so a dropped/mis-routed apply leaves the sentinel and fails. + call ok('ft8_low_threshold -> lft8lowth true', logical(p%lft8lowth)) + call ok('ft8_subpass -> lft8subpass false', .not. logical(p%lft8subpass)) + call ok('ft8_ap_on -> lft8apon false', .not. logical(p%lft8apon)) + call ok('ap_cq_only -> lapcqonly true', logical(p%lapcqonly)) + call ok('ap_my_call -> lapmyc false', .not. logical(p%lapmyc)) + call ok('jt65_ap_on -> ljt65apon true', logical(p%ljt65apon)) + call ok('hide_ft8_duplicates -> lhideft8dupes false', .not. logical(p%lhideft8dupes)) + call ok('common_ft8b -> lcommonft8b true', logical(p%lcommonft8b)) + call ok('enable_dxc_search -> lenabledxcsearch false', .not. logical(p%lenabledxcsearch)) + call ok('wide_dxc_search -> lwidedxcsearch true', logical(p%lwidedxcsearch)) + call ok('superfox_mode -> b_superfox false', .not. logical(p%b_superfox)) + call ok('even_sequence -> b_even_seq true', logical(p%b_even_seq)) + call ok('hound_mode -> lhound false', .not. logical(p%lhound)) + call ok('multi_instance -> lmultinst true', logical(p%lmultinst)) + call ok('skip_tx1 -> lskiptx1 false', .not. logical(p%lskiptx1)) + call ok('nagain_filter -> nagainfil true', logical(p%nagainfil)) + call ok('stop_hint -> nstophint false', .not. logical(p%nstophint)) + call ok('hint_mode -> nhint true', logical(p%nhint)) + call ok('ft8_cycles -> nft8cycles = 2', p%nft8cycles .eq. 2) + call ok('ft8_rxf_sensitivity -> nft8rxfsens = 4', p%nft8rxfsens .eq. 4) + call ok('ft8_threads -> nmt = 3', p%nmt .eq. 3) + call ok('ft8_decoder_start -> ndecoderstart = 1', p%ndecoderstart .eq. 1) + call ok('ap_width_hz -> napwid = 150 (RAW, not halved)', p%napwid .eq. 150) + ! Phase 7 routing (6 keys). Each asserted value is opposite its planted + ! sentinel, so a dropped/mis-routed apply leaves the sentinel and fails. + call ok('last_tx_seconds_ago -> nlasttx = 4', p%nlasttx .eq. 4) + call ok('currently_txing -> ltxing true', logical(p%ltxing)) + call ok('mode_changed -> lmodechanged false', .not. logical(p%lmodechanged)) + call ok('qso_progress_state -> nQSOProgress = 5', p%nQSOProgress .eq. 5) + call ok('sec_band_changed -> nsecbandchanged = 7', p%nsecbandchanged .eq. 7) + call ok('delay_units -> ndelay = 6', p%ndelay .eq. 6) + ! Phase 8 routing (4 keys; utc in frame_utc_precedence). Each asserted value is + ! opposite its planted sentinel (99) AND non-default, so a dropped/mis-routed + ! apply leaves the sentinel and fails. candthin/dtcenter prove the /100 scaling. + call ok('date -> yymmdd = 210703', p%yymmdd .eq. 210703) + call ok('n_trials -> nranera = 8', p%nranera .eq. 8) + call ok('candthin_threshold 1.5 -> ncandthin = 150', p%ncandthin .eq. 150) + call ok('dt_center_seconds 0.2 -> ndtcenter = 20', p%ndtcenter .eq. 20) + end subroutine frame_flat + + ! Frame RXFREQ: rxfreq sets BOTH nfqso and nftx. + subroutine frame_rxfreq() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame RXFREQ: rxfreq -> nfqso AND nftx' + call fresh(p) + md = 8; tr = 15.d0 + cfg%rxfreq_set = .true.; cfg%rxfreq = 1600 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('rxfreq -> nfqso = 1600', p%nfqso .eq. 1600) + call ok('rxfreq -> nftx = 1600', p%nftx .eq. 1600) + end subroutine frame_rxfreq + + ! Frame DECOUPLE: rxfreq sets both, then tx_audio_offset_hz overrides nftx only. + subroutine frame_decouple() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame DECOUPLE: rxfreq + tx_audio_offset_hz -> nfqso=rx, nftx=offset' + call fresh(p) + md = 8; tr = 15.d0 + cfg%rxfreq_set = .true.; cfg%rxfreq = 1600 + cfg%tx_audio_offset_hz_set = .true.; cfg%tx_audio_offset_hz = 1700 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('nfqso = 1600 (rxfreq)', p%nfqso .eq. 1600) + call ok('nftx = 1700 (offset overrides)', p%nftx .eq. 1700) + end subroutine frame_decouple + + ! Frame EMEDELAY (D1a): eme_delay survives when NO mode/trperiod is set. + subroutine frame_emedelay_survive() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame EMEDELAY-survive: eme_delay, no mode/trperiod -> survives' + call fresh(p) + md = 8; tr = 15.d0 + cfg%eme_delay_seconds_set = .true.; cfg%eme_delay_seconds = 1.9d0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('emedelay = 1.9 (no policy)', abs(p%emedelay - 1.9) .lt. 1.0e-6) + end subroutine frame_emedelay_survive + + ! Frame EMEDELAY (D1b): eme_delay + mode=8 -> per-mode policy clobbers to 0.0 + ! (emedelay is applied BEFORE the policy call, which overwrites it). + subroutine frame_emedelay_ft8() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame EMEDELAY-ft8: eme_delay + mode=8 -> policy clobbers to 0.0' + call fresh(p) + md = 8; tr = 15.d0 + cfg%eme_delay_seconds_set = .true.; cfg%eme_delay_seconds = 1.9d0 + cfg%mode_set = .true.; cfg%mode = 8 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('emedelay = 0.0 (FT8 policy)', abs(p%emedelay - 0.0) .lt. 1.0e-6) + end subroutine frame_emedelay_ft8 + + ! Frame EMEDELAY (D1c): eme_delay + mode=66 (Q65) + trperiod=60 -> policy = 2.5. + subroutine frame_emedelay_q65() + type(params_block) :: p + type(configure_fields) :: cfg + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame EMEDELAY-q65: eme_delay + Q65 60s -> policy = 2.5' + call fresh(p) + md = 8; tr = 15.d0 + cfg%eme_delay_seconds_set = .true.; cfg%eme_delay_seconds = 1.9d0 + cfg%mode_set = .true.; cfg%mode = 66 + cfg%trperiod_set = .true.; cfg%trperiod = 60.d0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('emedelay = 2.5 (Q65 60s policy)', abs(p%emedelay - 2.5) .lt. 1.0e-6) + end subroutine frame_emedelay_q65 + + ! Frame NFA/NFB restore: on a mode change with NO explicit nfa/nfb, the + ! session baseline is restored; an explicit nfa is honored instead. + subroutine frame_nfa_nfb_restore() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame NFA/NFB: mode change restores baseline unless explicit' + ! (a) no explicit nfa/nfb -> baseline restored + call fresh(p) + md = 8; tr = 15.d0 + cfg = blank + cfg%mode_set = .true.; cfg%mode = 8 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('no nfa/nfb + mode change -> nfa = baseline 111', p%nfa .eq. BNFA) + call ok('no nfa/nfb + mode change -> nfb = baseline 222', p%nfb .eq. BNFB) + ! (b) explicit nfa wins over baseline + call fresh(p) + md = 8; tr = 15.d0 + cfg = blank + cfg%mode_set = .true.; cfg%mode = 8 + cfg%nfa_set = .true.; cfg%nfa = 900 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('explicit nfa=900 + mode change -> nfa = 900 (not baseline)', p%nfa .eq. 900) + end subroutine frame_nfa_nfb_restore + + ! Frame NTOL policy: per-mode cap (consumer set) vs restore (consumer unset), + ! on a mode/trperiod change. + subroutine frame_ntol_policy() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame NTOL: per-mode cap/restore on mode change' + ! FT8, consumer unset -> restore default 1000. Sentinel 7777 first (review + ! HIGH: the mode-8 baseline is already 1000, so without a sentinel a deleted + ! restore line would pass vacuously). + call fresh(p); md = 8; tr = 15.d0; cfg = blank + p%ntol = 7777 + cfg%mode_set = .true.; cfg%mode = 8 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('FT8 + no ntol -> ntol = 1000 (restored from 7777)', p%ntol .eq. 1000) + ! FT8, consumer 5000 -> min(5000,1000) = 1000 + call fresh(p); md = 8; tr = 15.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 8 + cfg%ntol_set = .true.; cfg%ntol = 5000 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('FT8 + ntol 5000 -> ntol = 1000 (capped)', p%ntol .eq. 1000) + ! FT8, consumer 200 -> 200 (under cap) + call fresh(p); md = 8; tr = 15.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 8 + cfg%ntol_set = .true.; cfg%ntol = 200 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('FT8 + ntol 200 -> ntol = 200', p%ntol .eq. 200) + ! Q65, consumer 999 -> hard 10 + call fresh(p); md = 8; tr = 60.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 66 + cfg%trperiod_set = .true.; cfg%trperiod = 60.d0 + cfg%ntol_set = .true.; cfg%ntol = 999 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('Q65 + ntol 999 -> ntol = 10 (hard)', p%ntol .eq. 10) + ! JT65+JT9 (mode 74), consumer unset -> hard 20 + call fresh(p); md = 8; tr = 60.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 65 + 9 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('JT65+JT9 + no ntol -> ntol = 20 (hard)', p%ntol .eq. 20) + ! FST4 (241), consumer 50 -> min(50,100) = 50 + call fresh(p); md = 8; tr = 60.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 241 + cfg%ntol_set = .true.; cfg%ntol = 50 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('FST4 + ntol 50 -> ntol = 50 (under cap)', p%ntol .eq. 50) + end subroutine frame_ntol_policy + + ! Frame MODE/TRPERIOD: mode routes to io_mode + nmode; default TRperiod is + ! derived when no explicit trperiod follows; explicit trperiod -> ntr. + subroutine frame_mode_trperiod() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame MODE/TRPERIOD: mode -> io_mode/nmode + TRperiod default' + ! mode=5 (FT4), no explicit trperiod -> io_mode=5, nmode=5, TRperiod=7.5, ntr=7 + call fresh(p); md = 8; tr = 15.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 5 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('mode=5 -> io_mode = 5', md .eq. 5) + call ok('mode=5 -> nmode = 5', p%nmode .eq. 5) + call ok('mode=5 -> TRperiod = 7.5', abs(tr - 7.5d0) .lt. 1.0e-9) + call ok('mode=5 -> ntr = 7', p%ntr .eq. 7) + ! explicit trperiod=30 -> ntr=30 + call fresh(p); md = 8; tr = 15.d0; cfg = blank + cfg%mode_set = .true.; cfg%mode = 144 + cfg%trperiod_set = .true.; cfg%trperiod = 30.d0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('trperiod=30 -> ntr = 30', p%ntr .eq. 30) + end subroutine frame_mode_trperiod + + ! Frame MULTITHREADED-GUARD: multithreaded_ft8 is apply-IGNORED when non-false + ! (a true would re-enable the broken multithread branch + ! decoder.f90:192 -> 0 FT8 decodes). (a) a cfg true must NOT set + ! lmultift8 true (a straight pass-through regression would, and this catches it); + ! (b) a cfg false IS honored. + subroutine frame_multithreaded_guard() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame MULTITHREADED-GUARD: multithreaded_ft8 ignore-non-false' + ! (a) true is IGNORED: plant lmultift8=.false., apply true, assert STILL false. + ! (A pass-through regression would set it true and fail this.) + call fresh(p); md = 8; tr = 15.d0; cfg = blank + p%lmultift8 = .false. + cfg%multithreaded_ft8_set = .true.; cfg%multithreaded_ft8 = .true. + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('multithreaded_ft8=true IGNORED -> lmultift8 stays false', .not. logical(p%lmultift8)) + ! (b) false is HONORED: plant lmultift8=.true. (sentinel), apply false -> false. + call fresh(p); md = 8; tr = 15.d0; cfg = blank + p%lmultift8 = .true. + cfg%multithreaded_ft8_set = .true.; cfg%multithreaded_ft8 = .false. + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('multithreaded_ft8=false honored -> lmultift8 false', .not. logical(p%lmultift8)) + end subroutine frame_multithreaded_guard + + ! Frame QSO-GUARD: qso_progress_state apply guard. nQSOProgress + ! reaches the single-pass FT8 decoder where ft8b.f90:274/299 index + ! nappasses(0:5)/naptypes(0:5,4) -> an out-of-range value crashes the decoder + ! (verified: qso_progress_state=99 crashes jt9 --stream). The apply IGNORES an + ! out-of-range value (valid [0,5] pass through unchanged) -- like the + ! multithreaded_ft8 guard. Negative-controlled: plant a sentinel (2) != asserted, + ! so a straight pass-through regression (which would write 99 / -1) fails the + ! ignore asserts, and a dropped apply fails the in-range asserts. + subroutine frame_qso_guard() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame QSO-GUARD: qso_progress_state in-range applied / out-of-range ignored' + md = 8; tr = 15.d0 + ! out-of-range HIGH (99) IGNORED: plant 2, apply 99, assert STILL 2. + call fresh(p); cfg = blank; p%nQSOProgress = 2 + cfg%qso_progress_state_set = .true.; cfg%qso_progress_state = 99 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('qso_progress_state=99 (>5) IGNORED -> nQSOProgress stays 2', p%nQSOProgress .eq. 2) + ! out-of-range LOW (-1) IGNORED: plant 2, apply -1, assert STILL 2. + call fresh(p); cfg = blank; p%nQSOProgress = 2 + cfg%qso_progress_state_set = .true.; cfg%qso_progress_state = -1 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('qso_progress_state=-1 (<0) IGNORED -> nQSOProgress stays 2', p%nQSOProgress .eq. 2) + ! in-range boundary 5 APPLIED (overwrites sentinel 2). + call fresh(p); cfg = blank; p%nQSOProgress = 2 + cfg%qso_progress_state_set = .true.; cfg%qso_progress_state = 5 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('qso_progress_state=5 (in range) APPLIED -> nQSOProgress = 5', p%nQSOProgress .eq. 5) + ! in-range boundary 0 APPLIED (overwrites sentinel 2 -> proves it is applied, + ! not merely left at a default that happens to equal 0). + call fresh(p); cfg = blank; p%nQSOProgress = 2 + cfg%qso_progress_state_set = .true.; cfg%qso_progress_state = 0 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('qso_progress_state=0 (in range) APPLIED -> nQSOProgress = 0', p%nQSOProgress .eq. 0) + end subroutine frame_qso_guard + + ! Frame UTC-PRECEDENCE (Phase 8): utc (ISO) is a SECOND route to + ! nutc alongside the legacy int nutc. apply_configure_fields applies nutc THEN + ! utc, so utc WINS when a frame carries both. Three cases, each sentinel-planted + ! (nutc=999999, != every asserted value) so a dropped apply fails: + ! (a) utc alone -> nutc = utc_nutc (133430) + ! (b) legacy nutc alone -> nutc = nutc (120000) + ! (c) BOTH -> utc wins (133430, NOT 120000) + ! Case (c) is the precedence killer: a swap of the two apply lines (utc before + ! nutc) would leave 120000 and fail it. + subroutine frame_utc_precedence() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame UTC-PRECEDENCE: utc routes to nutc and wins over a co-present nutc' + md = 8; tr = 15.d0 + ! (a) utc alone -> nutc = utc_nutc. + call fresh(p); cfg = blank; p%nutc = 999999 + cfg%utc_set = .true.; cfg%utc_nutc = 133430 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('utc alone -> nutc = 133430', p%nutc .eq. 133430) + ! (b) legacy nutc alone -> nutc = nutc. + call fresh(p); cfg = blank; p%nutc = 999999 + cfg%nutc_set = .true.; cfg%nutc = 120000 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('nutc alone -> nutc = 120000', p%nutc .eq. 120000) + ! (c) BOTH -> utc wins (120000 overwritten by 133430). + call fresh(p); cfg = blank; p%nutc = 999999 + cfg%nutc_set = .true.; cfg%nutc = 120000 + cfg%utc_set = .true.; cfg%utc_nutc = 133430 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('nutc+utc -> utc WINS (nutc = 133430, not 120000)', p%nutc .eq. 133430) + end subroutine frame_utc_precedence + + ! Frame PHASE9-PACK (Phase 9): the two derived packed ints route + ! FLAT to params%ndepth / params%nexp_decode. The bit-PACKING itself (each wire + ! key -> its bit, the contest collapse, the masking/clamp) is asserted by the + ! parse-unit (run-phase9-parse-unit.sh); this guards the cfg -> params ROUTING. + ! ndepth_packed and the legacy depth are mutually exclusive on an accepted frame + ! (co-present is declined at parse), so they are tested separately: frame_flat + ! covers depth -> ndepth, this covers ndepth_packed -> ndepth. Sentinel-opposite: + ! plant ndepth/nexp_decode = 99 (!= the asserted values) so a + ! dropped or mis-routed apply leaves the sentinel and fails. The asserted values + ! are realistic packs: ndepth 178 = 2|0x10|0x20|0x80; nexp_decode 1382 = + ! 6|0x20|0x40|(5<<8). + subroutine frame_phase9_pack() + type(params_block) :: p + type(configure_fields) :: cfg, blank + integer :: md + real(8) :: tr + write(*,'(a)') 'Frame PHASE9-PACK: ndepth_packed/nexp_decode_packed -> their slots' + call fresh(p); md = 8; tr = 15.d0; cfg = blank + p%ndepth = 99 ! sentinel != 178 + p%nexp_decode = 99 ! sentinel != 1382 + cfg%ndepth_packed_set = .true.; cfg%ndepth_packed = 178 + cfg%nexp_decode_packed_set = .true.; cfg%nexp_decode_packed = 1382 + call apply_configure_fields(cfg, md, tr, p, BNFA, BNFB) + call ok('ndepth_packed -> ndepth = 178 (not sentinel 99)', p%ndepth .eq. 178) + call ok('nexp_decode_packed -> nexp_decode = 1382 (not sentinel 99)', p%nexp_decode .eq. 1382) + end subroutine frame_phase9_pack + +end program apply_routing_test diff --git a/test/fixtures/README.md b/test/fixtures/README.md new file mode 100644 index 00000000..f511c352 --- /dev/null +++ b/test/fixtures/README.md @@ -0,0 +1,47 @@ +# Golden fixtures + +Known-good decoder outputs captured at SHA `3b354122` (a commit with zero decoder changes relative to its parent). + +These fixtures are the regression baseline: any change that alters `jt9`'s or `wsprd`'s stdout byte-for-byte fails the harness in CI. The harness protects decoder behavior through the streaming I/O, NDJSON output, control frames, and wsprd streaming paths. + +## Current fixtures + +| Fixture | Input | Mode | Decodes | Captured from | +|---|---|---|---|---| +| `ft8_210703_133430.expected.txt` | `samples/FT8/210703_133430.wav` | FT8 (`-8`) | 14 signals | `3b354122` | +| `jt9_130418_1742.expected.txt` | `samples/JT9/130418_1742.wav` | JT9 (`-9`) | 6 signals | `3b354122` | +| `q65_30a_201203_024000.expected.txt` | `samples/Q65/30A_Ionoscatter_6m/201203_024000.wav` | Q65-30A (`--q65 -p 30 -f 1000 -d 3`) | 1 signal | K1JT, 2026-08-01 | +| `q65_300a_201210_0505.expected.txt` | `samples/Q65/300A_Optical_Scatter/201210_0505.wav` | Q65-300A (`--q65 -p 300 -f 1000 -d 3`) | 1 signal | K1JT, 2026-08-02 | +| `q65_60d_201212_1838.expected.txt` | `samples/Q65/60D_EME_10GHz/201212_1838.wav` | Q65-60D (`--q65 -b D -p 60 -f 1000 -d 3`) | 1 signal | K1JT, 2026-08-02 | +| `msk144_181211_120800.expected.txt` | `samples/MSK144/181211_120800.wav` | MSK144 (`--msk144 -p 15 -f 1500 -F 50 -d 3`) | 2 signals | K1JT, 2026-08-02 | +| `fst4_210115_0058.expected.txt` | `samples/FST4+FST4W/210115_0058.wav` | FST4 (`--fst4 -p 60 -f 1331 -L 1000 -H 1400 -d 3`) | 3 signals | K1JT, 2026-08-02 | +| `fst4w_201230_0300.expected.txt` | `samples/FST4+FST4W/201230_0300.wav` | FST4W (`--fst4w -p 1800 -f 1433 -F 100 -d 3`) | 1 signal | K1JT, 2026-08-02 | +| `ft4_000000_000002.expected.txt` | `samples/FT4/000000_000002.wav` | FT4 (`--ft4 -d 3`) | 19 signals | K1JT, 2026-08-02 | +| `jt65_000000_0004.expected.txt` | `samples/JT65/JT65B/000000_0004.wav` | JT65 (`--jt65 -b B -f 1700 -d 3`) | 1 signal | K1JT, 2026-08-02 | +| `jt4_OK1KIR_141105_175700.expected.txt` | `samples/JT4/JT4F/OK1KIR_141105_175700.WAV` | JT4-F (`--jt4 -b F -f 1200 -d 3`) | 1 signal | K1JT, 2026-08-02 | +| `wspr_150426_0918.expected.txt` | `samples/WSPR/150426_0918.wav` | WSPR (`wsprd`, no flags) | 9 signals | K1JT, 2026-08-02 | + +## Running + +Two independent ways to run these: + +- **Standalone script** (manual/local use, not itself CI-invoked): + ``` + cmake --build build --target jt9 wsprd + test/run-golden-fixtures.sh + ``` + Exits 0 on pass, 1 on regression. +- **ctest** (this is what CI actually runs): each fixture above is also registered as a `test_jt9_golden_*`/`test_wsprd_golden_*` test via `wsjt_add_jt9_golden_test`/`wsjt_add_wsprd_golden_test` in the top-level `CMakeLists.txt`, using `tests/integration/{jt9,wsprd}/compare_*_output.cmake` for an isolated, byte-exact comparison. These are gated to Linux x86-64 only (`ctest -R test_jt9_golden` / `test_wsprd_golden` to run just these) -- decoder output can drift in small ways across compilers/architectures, so the byte-exact check is pinned to one canonical platform; the other four CI legs still run everything else in `ctest`. + +## Adding a fixture + +1. Put the input `.wav` under `samples/<MODE>/` (already there for standard modes). +2. Run `./build/jt9 <flags> samples/<MODE>/<file>.wav > test/fixtures/<name>.expected.txt 2>&1` (or `./build/wsprd <flags> <file>.wav > ...` for WSPR). +3. Add a `run_fixture` call in `test/run-golden-fixtures.sh`, **and** a `wsjt_add_jt9_golden_test`/`wsjt_add_wsprd_golden_test` call in the top-level `CMakeLists.txt` -- the shell script alone does not run in CI. +4. Commit the expected file + both script/CMake changes together. + +## Coverage + +- FT8 + JT9 + Q65-30A + Q65-300A + Q65-60D + MSK144 + FST4 + FST4W + FT4 + JT65 + JT4 + WSPR fixtures above cover basic decoder regression. +- The streaming harnesses extend coverage to FST4 (`-7`), Q65 (`-3`), MSK144 (`-5`), and wsprd streaming. +- Streaming I/O parity: `test/run-stream-wav-parity.sh` validates that `jt9 --stream` decodes **contain** these expected decodes. The check is **containment, not identity**: streaming legitimately finds *more* signals (the early `nzhsym` passes pick up low-SNR signals) and the `snr`/`dt`/`freq` fields drift between the WAV and stream decode paths for the same signal (≈ ±2 dB / ±0.05 s / ±3 Hz — different fine estimates), so the decoded **message text** is the parity identity. FT8/JT9 only (FST4W has no good fixture; EME/JT65 I/Q paths are pass-on-absence). diff --git a/test/fixtures/fst4_210115_0058.expected.txt b/test/fixtures/fst4_210115_0058.expected.txt new file mode 100644 index 00000000..87c3c703 --- /dev/null +++ b/test/fixtures/fst4_210115_0058.expected.txt @@ -0,0 +1,4 @@ +0058 17 0.4 1331 ` CQ K9KFR EN71 +0058 -8 0.3 1101 ` CQ N5TM EL29 +0058 -29 0.4 1135 ` CQ N3HSK FM28 ? a1 +<DecodeFinished> 0 3 0 diff --git a/test/fixtures/fst4w_201230_0300.expected.txt b/test/fixtures/fst4w_201230_0300.expected.txt new file mode 100644 index 00000000..5565f4e9 --- /dev/null +++ b/test/fixtures/fst4w_201230_0300.expected.txt @@ -0,0 +1,2 @@ +0300 -44 0.3 1433 ` DL0HOT JO60 30 +<DecodeFinished> 0 1 0 diff --git a/test/fixtures/ft4_000000_000002.expected.txt b/test/fixtures/ft4_000000_000002.expected.txt new file mode 100644 index 00000000..647422bc --- /dev/null +++ b/test/fixtures/ft4_000000_000002.expected.txt @@ -0,0 +1,20 @@ +000002 -10 -0.2 296 + N1TRK N4FKH 569 VA +000002 -9 -0.4 422 + N1TRK KB7RUQ RR73 +000002 -7 -0.1 560 + CQ RU AB5XS EM12 +000002 -12 0.1 727 + NZ7P WA7JAY 589 CA +000002 16 0.3 1149 + KB0VHA KA1YQC R 539 MA +000002 -3 -0.2 1640 + CQ RU N9OY EN43 +000002 -11 0.2 1910 + K1JT WB4HXE 559 GA +000002 5 0.3 2067 + VE3LON K7RL R 549 WA +000002 -1 0.2 2310 + WD9IGY KX1X 73 +000002 -17 -0.4 2413 + W7BOB KJ7G RR73 +000002 -7 -0.3 2566 + NI6G W7DRW 569 AZ +000002 2 -0.3 2725 + K4SQC VE3RX RR73 +000002 -6 -0.4 2813 + CQ RU W1QA FN32 +000002 0 0.0 2995 + CQ RU WS4WW FM17 +000002 13 0.2 3159 + HB9BUN KG4W R 549 VA +000002 -8 0.4 3337 + W9TO KN3ILZ 529 PA +000002 -10 -0.3 520 + W9JA PY2APK RRR +000002 -15 0.2 2299 + AC6BW KR9A R 559 WI +000002 -13 -0.3 2560 + CQ RU W0FRC DM79 +<DecodeFinished> 0 19 0 diff --git a/test/fixtures/ft8_210703_133430.expected.txt b/test/fixtures/ft8_210703_133430.expected.txt new file mode 100644 index 00000000..03b27568 --- /dev/null +++ b/test/fixtures/ft8_210703_133430.expected.txt @@ -0,0 +1,15 @@ +133430 15 0.3 2571 ~ W1FC F5BZB -08 +133430 -2 -0.8 1197 ~ CQ F5RXL IN94 +133430 13 -0.1 2157 ~ WM3PEN EA6VQ -09 +133430 -13 0.3 590 ~ K1JT HA0DU KN07 +133430 -7 0.1 723 ~ A92EE F5PSR -14 +133430 -3 -0.1 2695 ~ K1BZM EA3GP -09 +133430 -13 0.3 641 ~ N1JFU EA6EE R-07 +133430 -3 0.2 466 ~ N1PJT HB9CQK -10 +133430 -7 0.4 2734 ~ W1DIG SV9CVY -14 +133430 -16 0.1 1649 ~ K1JT EA3AGB -15 +133430 -16 0.3 400 ~ W0RSJ EA3BMU RR73 +133430 -11 0.2 2855 ~ XE2X HA2NP RR73 +133430 -6 0.4 472 ~ KD2UGC F6GCP R-23 +133430 -7 0.2 2522 ~ K1BZM EA3CJ JN01 +<DecodeFinished> 0 14 0 diff --git a/test/fixtures/ft8_210703_133430_mtd.expected.txt b/test/fixtures/ft8_210703_133430_mtd.expected.txt new file mode 100644 index 00000000..78a17b08 --- /dev/null +++ b/test/fixtures/ft8_210703_133430_mtd.expected.txt @@ -0,0 +1,21 @@ +# Message identities are compared as a set; numeric metadata and order are informational. +133430 -9 0.1 723 ~ A92EE F5PSR -14 +133430 -7 -0.8 1196 ~ CQ F5RXL IN94 +133430 0 -0.1 2157 ~ WM3PEN EA6VQ -09 +133430 0 0.3 2571 ~ W1FC F5BZB -08 +133430 -14 0.3 641 ~ N1JFU EA6EE R-07 +133430 -13 0.3 2239 ~ N1API HA6FQ -23 +133430 -13 0.3 590 ~ K1JT HA0DU KN07 +133430 -12 0.3 465 ~ N1PJT HB9CQK -10 +133430 -11 -0.1 2695 ~ K1BZM EA3GP -09 +133430 -15 0.1 2279 ~ CQ EA2BFM IN83 +133430 -15 0.3 399 ~ W0RSJ EA3BMU RR73 +133430 -9 0.4 2734 ~ W1DIG SV9CVY -14 +133430 -15 0.1 1648 ~ K1JT EA3AGB -15 +133430 -18 0.7 1513 ~ N1API F2VX 73 +133430 -10 0.4 472 ~ KD2UGC F6GCP R-23 +133430 -14 0.2 2854 ~ XE2X HA2NP RR73 +133430 -18 0.1 2039 ~ K1JT HA5WA 73 +133430 -19 0.5 244 ~ K1BZM DK8NE -10 +133430 -12 0.2 2522 ~ K1BZM EA3CJ JN01 +133430 -15 -0.1 2546 ~ WA2FZW DL5AXX RR73 diff --git a/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt new file mode 100644 index 00000000..5add3711 --- /dev/null +++ b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt @@ -0,0 +1,2 @@ +**** -14 1.8 1199 $# G3WDG OK1KIR RRR f +<DecodeFinished> 0 1 0 diff --git a/test/fixtures/jt65_000000_0004.expected.txt b/test/fixtures/jt65_000000_0004.expected.txt new file mode 100644 index 00000000..6a230c84 --- /dev/null +++ b/test/fixtures/jt65_000000_0004.expected.txt @@ -0,0 +1,2 @@ +0004 -26 2.5 1700 # K1ABC G4XYZ IO91 +<DecodeFinished> 0 1 0 diff --git a/test/fixtures/jt9_130418_1742.expected.txt b/test/fixtures/jt9_130418_1742.expected.txt new file mode 100644 index 00000000..147b44de --- /dev/null +++ b/test/fixtures/jt9_130418_1742.expected.txt @@ -0,0 +1,7 @@ +1742 -5 1.2 1505 @ JA1KAU PD0JAC -23 +1742 -25 0.0 1119 @ CQ GM7GAX IO75 +1742 -17 -0.0 1186 @ TF3G N7MQ CN84 +1742 -18 0.0 1224 @ K1JT KF4RWA 73 +1742 -22 0.1 1290 @ CQ M0WAY IO82 +1742 -13 0.0 1461 @ G7CNF N4HFA EL89 +<DecodeFinished> 0 6 0 diff --git a/test/fixtures/msk144_181211_120800.expected.txt b/test/fixtures/msk144_181211_120800.expected.txt new file mode 100644 index 00000000..484bae80 --- /dev/null +++ b/test/fixtures/msk144_181211_120800.expected.txt @@ -0,0 +1,3 @@ +120800 5 4.6 1458 & CQ W4IMD EM84 +120800 7 12.2 1496 & CQ KD9VV EN71 +<DecodeFinished> 0 0 0 diff --git a/test/fixtures/q65_300a_201210_0505.expected.txt b/test/fixtures/q65_300a_201210_0505.expected.txt new file mode 100644 index 00000000..b921120b --- /dev/null +++ b/test/fixtures/q65_300a_201210_0505.expected.txt @@ -0,0 +1,2 @@ +0505 -34 -0.6 1002 : VK7MO VK7PD QE38 q0 +<DecodeFinished> 0 1 1 diff --git a/test/fixtures/q65_30a_201203_024000.expected.txt b/test/fixtures/q65_30a_201203_024000.expected.txt new file mode 100644 index 00000000..d511c993 --- /dev/null +++ b/test/fixtures/q65_30a_201203_024000.expected.txt @@ -0,0 +1,2 @@ +024000 -18 0.3 1008 : K1JT K9AN R-16 q0 +<DecodeFinished> 0 1 1000 diff --git a/test/fixtures/q65_60d_201212_1838.expected.txt b/test/fixtures/q65_60d_201212_1838.expected.txt new file mode 100644 index 00000000..46216a00 --- /dev/null +++ b/test/fixtures/q65_60d_201212_1838.expected.txt @@ -0,0 +1,2 @@ +1838 -15 2.8 998 : VK7MO K6QPV DM12 q0 +<DecodeFinished> 0 1 1000 diff --git a/test/fixtures/wspr_150426_0918.expected.txt b/test/fixtures/wspr_150426_0918.expected.txt new file mode 100644 index 00000000..42ab2b7f --- /dev/null +++ b/test/fixtures/wspr_150426_0918.expected.txt @@ -0,0 +1,10 @@ +0918 -9 1.1 0.001446 0 ND6P DM04 30 +0918 -15 0.1 0.001460 0 W5BIT EL09 17 +0918 -23 2.2 0.001465 0 G8VDQ IO91 37 +0918 -6 0.6 0.001489 0 WD4LHT EL89 30 +0918 -1 -0.8 0.001503 0 NM7J DM26 30 +0918 -21 0.5 0.001517 0 KI7CI DM09 37 +0918 -18 -1.9 0.001530 0 DJ6OL JO52 37 +0918 -11 0.8 0.001587 0 W3HH EL89 30 +0918 -25 0.7 0.001594 0 W3BI FN20 30 +<DecodeFinished> diff --git a/test/phase4_parse_test.f90 b/test/phase4_parse_test.f90 new file mode 100644 index 00000000..116bca60 --- /dev/null +++ b/test/phase4_parse_test.f90 @@ -0,0 +1,206 @@ +! Phase 4 parse-unit regression driver ("unit parse->pack assert"). +! Exercises parse_control_frame for the 9 Phase 4 +! keys + the tricky cases: bool true/false, his_call vs his_call_standard +! substring non-collision (both orderings), wrong-type detection (bool/string/ +! int), and value-vs-key aliasing (a string value equal to a key token must NOT +! be mistaken for that key). Compiled + run by +! test/run-phase4-parse-unit.sh against lib/streaming_control.f90. +! +! SCOPE: this guards the JSON -> configure_fields PARSE (the module-public entry +! point). The configure_fields -> params APPLY routing now lives in the module- +! public streaming_apply::apply_configure_fields (extracted from the +! former nested-internal apply_configure_) and is asserted by +! test/run-apply-routing-unit.sh — so the 9 inert Phase 4 fields' apply routing +! IS now unit-guarded, not just code-review + no-regression. +program p4_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + call frame_H() + call frame_I() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 4 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 4 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: all 9 keys, bools true. + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","mode":"FT8","his_call":"DX1ABC","his_grid":"FN20",' // & + '"my_b_call":"KJ5HST/P","his_b_call":"DX1ABC/P","my_call_standard":true,' //& + '"his_call_standard":true,"tx_audio_offset_hz":1234,' // & + '"jt65_jt9_split_hz":2500,"max_drift_hz":8}' + write(*,'(a)') 'Frame A: all 9 keys present, bools true' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + call ok('his_call == DX1ABC', cfg%his_call_set .and. trim(cfg%his_call) .eq. 'DX1ABC') + call ok('his_grid == FN20', cfg%his_grid_set .and. trim(cfg%his_grid) .eq. 'FN20') + call ok('my_b_call == KJ5HST/P', cfg%my_b_call_set .and. trim(cfg%my_b_call) .eq. 'KJ5HST/P') + call ok('his_b_call == DX1ABC/P', cfg%his_b_call_set.and. trim(cfg%his_b_call).eq. 'DX1ABC/P') + call ok('my_call_standard == true', cfg%my_call_standard_set .and. cfg%my_call_standard) + call ok('his_call_standard == true', cfg%his_call_standard_set .and. cfg%his_call_standard) + call ok('tx_audio_offset_hz == 1234',cfg%tx_audio_offset_hz_set .and. cfg%tx_audio_offset_hz .eq. 1234) + call ok('jt65_jt9_split_hz == 2500', cfg%jt65_jt9_split_hz_set .and. cfg%jt65_jt9_split_hz .eq. 2500) + call ok('max_drift_hz == 8', cfg%max_drift_hz_set .and. cfg%max_drift_hz .eq. 8) + end subroutine frame_A + + ! Frame B: bools false (distinguish "set to false" from "absent"). + subroutine frame_B() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","my_call_standard":false,"his_call_standard":false}' + write(*,'(a)') 'Frame B: bools explicitly false' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('my_call_standard set, value false', cfg%my_call_standard_set .and. (.not. cfg%my_call_standard)) + call ok('his_call_standard set, value false', cfg%his_call_standard_set .and. (.not. cfg%his_call_standard)) + end subroutine frame_B + + ! Frame C: his_call AND his_call_standard both present, BOTH orderings. + ! "his_call" is a substring of "his_call_standard" — the closing quote in the + ! key token must prevent the shorter key from matching the longer one. + subroutine frame_C() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = & + '{"t":"configure","his_call":"W1AW","his_call_standard":true}' + character(len=*), parameter :: b2 = & + '{"t":"configure","his_call_standard":true,"his_call":"W1AW"}' + write(*,'(a)') 'Frame C: his_call vs his_call_standard substring non-collision' + call parse_control_frame(b1, action, cfg, terr) + call ok('order1: terr not present', .not. terr%present) + call ok('order1: his_call == W1AW', cfg%his_call_set .and. trim(cfg%his_call) .eq. 'W1AW') + call ok('order1: his_call_standard == true', cfg%his_call_standard_set .and. cfg%his_call_standard) + call parse_control_frame(b2, action, cfg, terr) + call ok('order2: terr not present', .not. terr%present) + call ok('order2: his_call == W1AW', cfg%his_call_set .and. trim(cfg%his_call) .eq. 'W1AW') + call ok('order2: his_call_standard == true', cfg%his_call_standard_set .and. cfg%his_call_standard) + end subroutine frame_C + + ! Frame D: bool key carrying a number -> configure_type_error. + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","my_call_standard":5}' + write(*,'(a)') 'Frame D: my_call_standard:5 (number) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == my_call_standard',trim(terr%key) .eq. 'my_call_standard') + call ok('expected == bool', trim(terr%expected) .eq. 'bool') + call ok('got == number', trim(terr%got) .eq. 'number') + end subroutine frame_D + + ! Frame E: bool key carrying a string -> configure_type_error. + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","his_call_standard":"true"}' + write(*,'(a)') 'Frame E: his_call_standard:"true" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == his_call_standard',trim(terr%key) .eq. 'his_call_standard') + call ok('expected == bool', trim(terr%expected) .eq. 'bool') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_E + + ! Frame F: string key carrying a number -> configure_type_error. + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","his_call":123}' + write(*,'(a)') 'Frame F: his_call:123 (number) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == his_call', trim(terr%key) .eq. 'his_call') + call ok('expected == string',trim(terr%expected) .eq. 'string') + call ok('got == number', trim(terr%got) .eq. 'number') + end subroutine frame_F + + ! Frame G: int key carrying a string -> configure_type_error. + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","max_drift_hz":"abc"}' + write(*,'(a)') 'Frame G: max_drift_hz:"abc" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == max_drift_hz', trim(terr%key) .eq. 'max_drift_hz') + call ok('expected == int', trim(terr%expected) .eq. 'int') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_G + + ! Frame H: value-vs-key aliasing — his_call VALUE equals the "max_drift_hz" + ! token, with no real max_drift_hz key. The value must NOT be mistaken for the + ! key: max_drift_hz stays unset (benign extraction miss) and NO false type + ! error is raised (anchored find_key_ ignores the value). Aliasing guard. + subroutine frame_H() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","his_call":"max_drift_hz"}' + write(*,'(a)') 'Frame H: his_call value == "max_drift_hz" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('his_call == max_drift_hz', cfg%his_call_set .and. trim(cfg%his_call) .eq. 'max_drift_hz') + call ok('max_drift_hz stays UNSET', .not. cfg%max_drift_hz_set) + end subroutine frame_H + + ! Frame I: Phase 4 keys absent -> all unset, no error (keys are optional). + subroutine frame_I() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8"}' + write(*,'(a)') 'Frame I: Phase 4 keys absent -> unset' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('his_call unset', .not. cfg%his_call_set) + call ok('his_grid unset', .not. cfg%his_grid_set) + call ok('my_b_call unset', .not. cfg%my_b_call_set) + call ok('his_b_call unset', .not. cfg%his_b_call_set) + call ok('my_call_standard unset', .not. cfg%my_call_standard_set) + call ok('his_call_standard unset', .not. cfg%his_call_standard_set) + call ok('tx_audio_offset_hz unset', .not. cfg%tx_audio_offset_hz_set) + call ok('jt65_jt9_split_hz unset', .not. cfg%jt65_jt9_split_hz_set) + call ok('max_drift_hz unset', .not. cfg%max_drift_hz_set) + end subroutine frame_I + +end program p4_parse_test diff --git a/test/phase5_parse_test.f90 b/test/phase5_parse_test.f90 new file mode 100644 index 00000000..e635484f --- /dev/null +++ b/test/phase5_parse_test.f90 @@ -0,0 +1,246 @@ +! Phase 5 parse-unit regression driver ("unit parse->pack assert"). +! Exercises parse_control_frame for the 12 Phase 5 +! decoder-tuning keys + the tricky cases: real(8) keys (dt_tolerance_seconds / +! eme_delay_seconds), the tx_mode enum (string JT9/JT65 -> 9/65 and raw int), +! bool true/false (robust_mode / nagain_flag / clear_average), wrong-type +! detection (real/int/bool), the "mode" vs "tx_mode" + "min_width" vs "min_sync" +! substring non-collision, and value-vs-key aliasing (a string value equal to a +! Phase-5 key token must NOT be mistaken for that key). +! Compiled + run by test/run-phase5-parse-unit.sh against lib/streaming_control.f90. +! +! SCOPE: this guards the JSON -> configure_fields PARSE (the module-public entry +! point). The configure_fields -> params APPLY routing now lives in the module- +! public streaming_apply::apply_configure_fields (extracted from the +! former nested-internal apply_configure_) and is asserted by +! test/run-apply-routing-unit.sh. For Phase 5, 10 of 12 fields are observably +! inert on the FT8/JT9 fixtures; the two observable keys (nagain_flag -> FT8, +! npts_c0_array -> JT9) ALSO get a decode-effect gate in run-schema-v1-fixtures.sh +! (Gates 11/12), which proves they reach the decoder (apply routed them to a +! decode-affecting param). +program p5_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + call frame_H() + call frame_I() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 5 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 5 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: all 12 keys, bools true, tx_mode as the "JT65" enum string. + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","dt_tolerance_seconds":0.1,"eme_delay_seconds":1.5,' // & + '"kin_samples":64800,"nzhsym_per_period":50,"npts_c0_array":74736,' // & + '"min_width":1,"min_sync":2,"n_2pass":1,"robust_mode":true,' // & + '"nagain_flag":true,"tx_mode":"JT65","clear_average":true}' + write(*,'(a)') 'Frame A: all 12 keys present, bools true, tx_mode="JT65"' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + ! 0.1 is NOT exactly representable in real(4); the tight 1e-10 tolerance also + ! proves the configure_fields member is real(8) (a real(4) member would hold + ! ~0.10000000149 and fail). The narrowing to real(c_float) happens at APPLY. + call ok('dt_tolerance_seconds == 0.1 (real8)', cfg%dt_tolerance_seconds_set .and. & + abs(cfg%dt_tolerance_seconds - 0.1d0) .lt. 1.d-10) + call ok('eme_delay_seconds == 1.5', cfg%eme_delay_seconds_set .and. & + abs(cfg%eme_delay_seconds - 1.5d0) .lt. 1.d-9) + call ok('kin_samples == 64800', cfg%kin_samples_set .and. cfg%kin_samples .eq. 64800) + call ok('nzhsym_per_period == 50', cfg%nzhsym_per_period_set .and. cfg%nzhsym_per_period .eq. 50) + call ok('npts_c0_array == 74736', cfg%npts_c0_array_set .and. cfg%npts_c0_array .eq. 74736) + call ok('min_width == 1', cfg%min_width_set .and. cfg%min_width .eq. 1) + call ok('min_sync == 2', cfg%min_sync_set .and. cfg%min_sync .eq. 2) + call ok('n_2pass == 1', cfg%n_2pass_set .and. cfg%n_2pass .eq. 1) + call ok('robust_mode == true', cfg%robust_mode_set .and. cfg%robust_mode) + call ok('nagain_flag == true', cfg%nagain_flag_set .and. cfg%nagain_flag) + call ok('tx_mode == 65 (JT65)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 65) + call ok('clear_average == true', cfg%clear_average_set .and. cfg%clear_average) + end subroutine frame_A + + ! Frame B: bools false (distinguish "set to false" from "absent"); + ! tx_mode as a raw int (9); a negative real. + subroutine frame_B() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","robust_mode":false,"nagain_flag":false,' // & + '"clear_average":false,"tx_mode":9,"dt_tolerance_seconds":-0.5}' + write(*,'(a)') 'Frame B: bools false, tx_mode=9 (int), negative real' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('robust_mode set, value false', cfg%robust_mode_set .and. (.not. cfg%robust_mode)) + call ok('nagain_flag set, value false', cfg%nagain_flag_set .and. (.not. cfg%nagain_flag)) + call ok('clear_average set, value false', cfg%clear_average_set .and. (.not. cfg%clear_average)) + call ok('tx_mode == 9 (int)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('dt_tolerance_seconds == -0.5', cfg%dt_tolerance_seconds_set .and. & + abs(cfg%dt_tolerance_seconds + 0.5d0) .lt. 1.d-9) + end subroutine frame_B + + ! Frame C: substring non-collision. "mode" is a substring of "tx_mode" and + ! "min_width"/"min_sync" share the "min_" prefix — the structural key locator + ! (closing quote in the token + anchor) must keep them distinct, both orderings. + subroutine frame_C() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = & + '{"t":"configure","mode":"FT8","tx_mode":"JT9","min_width":3,"min_sync":4}' + character(len=*), parameter :: b2 = & + '{"t":"configure","tx_mode":"JT9","mode":"FT8","min_sync":4,"min_width":3}' + write(*,'(a)') 'Frame C: mode vs tx_mode + min_width vs min_sync non-collision' + call parse_control_frame(b1, action, cfg, terr) + call ok('order1: terr not present', .not. terr%present) + call ok('order1: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order1: tx_mode == 9 (JT9)',cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order1: min_width == 3', cfg%min_width_set .and. cfg%min_width .eq. 3) + call ok('order1: min_sync == 4', cfg%min_sync_set .and. cfg%min_sync .eq. 4) + call parse_control_frame(b2, action, cfg, terr) + call ok('order2: terr not present', .not. terr%present) + call ok('order2: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order2: tx_mode == 9 (JT9)',cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order2: min_width == 3', cfg%min_width_set .and. cfg%min_width .eq. 3) + call ok('order2: min_sync == 4', cfg%min_sync_set .and. cfg%min_sync .eq. 4) + end subroutine frame_C + + ! Frame D: real key carrying a string -> configure_type_error. + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","dt_tolerance_seconds":"abc"}' + write(*,'(a)') 'Frame D: dt_tolerance_seconds:"abc" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == dt_tolerance_seconds', trim(terr%key) .eq. 'dt_tolerance_seconds') + call ok('expected == real', trim(terr%expected) .eq. 'real') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_D + + ! Frame E: int key carrying a string -> configure_type_error. + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","npts_c0_array":"big"}' + write(*,'(a)') 'Frame E: npts_c0_array:"big" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == npts_c0_array', trim(terr%key) .eq. 'npts_c0_array') + call ok('expected == int', trim(terr%expected) .eq. 'int') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_E + + ! Frame F: bool key carrying a number -> configure_type_error. + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","robust_mode":5}' + write(*,'(a)') 'Frame F: robust_mode:5 (number) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == robust_mode', trim(terr%key) .eq. 'robust_mode') + call ok('expected == bool', trim(terr%expected) .eq. 'bool') + call ok('got == number', trim(terr%got) .eq. 'number') + end subroutine frame_F + + ! Frame G: value-vs-key aliasing — the mycall VALUE is the literal "n_2pass" + ! token, with no real n_2pass key. The anchored locator must NOT mistake the + ! value for the key: n_2pass stays unset (benign extraction miss) and NO false + ! type error is raised. (Documents the benign aliasing + ! behavior for an int key whose token appears as a string value.) NOTE: the + ! primary anchoring-REGRESSION teeth live in Frame C — a value's closing quote + ! is always followed by a structural char ('}'/','), so a hypothetical raw- + ! index regression would classify this value as 'absent' and also not decline; + ! Frame C (mode-inside-tx_mode, order2) is what actually fails on a raw-index + ! regression. This frame documents the benign no-false-decline contract. + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mycall":"n_2pass"}' + write(*,'(a)') 'Frame G: mycall value == "n_2pass" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('mycall == n_2pass', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'n_2pass') + call ok('n_2pass stays UNSET', .not. cfg%n_2pass_set) + end subroutine frame_G + + ! Frame H: Phase 5 keys absent -> all unset, no error (keys are optional). + subroutine frame_H() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8"}' + write(*,'(a)') 'Frame H: Phase 5 keys absent -> unset' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('dt_tolerance_seconds unset', .not. cfg%dt_tolerance_seconds_set) + call ok('eme_delay_seconds unset', .not. cfg%eme_delay_seconds_set) + call ok('kin_samples unset', .not. cfg%kin_samples_set) + call ok('nzhsym_per_period unset', .not. cfg%nzhsym_per_period_set) + call ok('npts_c0_array unset', .not. cfg%npts_c0_array_set) + call ok('min_width unset', .not. cfg%min_width_set) + call ok('min_sync unset', .not. cfg%min_sync_set) + call ok('n_2pass unset', .not. cfg%n_2pass_set) + call ok('robust_mode unset', .not. cfg%robust_mode_set) + call ok('nagain_flag unset', .not. cfg%nagain_flag_set) + call ok('tx_mode unset', .not. cfg%tx_mode_set) + call ok('clear_average unset', .not. cfg%clear_average_set) + end subroutine frame_H + + ! Frame I: npts_c0_array feeds JT9 npts8. Values outside the downsam9 + ! FFT input domain are ignored rather than routed to the decoder. + subroutine frame_I() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = '{"t":"configure","npts_c0_array":-1}' + character(len=*), parameter :: b2 = '{"t":"configure","npts_c0_array":0}' + character(len=*), parameter :: b3 = '{"t":"configure","npts_c0_array":81649}' + character(len=*), parameter :: b4 = '{"t":"configure","npts_c0_array":81648}' + write(*,'(a)') 'Frame I: npts_c0_array domain guard' + call parse_control_frame(b1, action, cfg, terr) + call ok('negative npts_c0_array ignored', .not. terr%present .and. .not. cfg%npts_c0_array_set) + call parse_control_frame(b2, action, cfg, terr) + call ok('zero npts_c0_array ignored', .not. terr%present .and. .not. cfg%npts_c0_array_set) + call parse_control_frame(b3, action, cfg, terr) + call ok('oversize npts_c0_array ignored', .not. terr%present .and. .not. cfg%npts_c0_array_set) + call parse_control_frame(b4, action, cfg, terr) + call ok('max npts_c0_array accepted', .not. terr%present .and. cfg%npts_c0_array_set .and. & + cfg%npts_c0_array .eq. 81648) + end subroutine frame_I + +end program p5_parse_test diff --git a/test/phase6_parse_test.f90 b/test/phase6_parse_test.f90 new file mode 100644 index 00000000..14249aa2 --- /dev/null +++ b/test/phase6_parse_test.f90 @@ -0,0 +1,216 @@ +! Phase 6 parse-unit regression driver. Exercises parse_control_frame for the 24 +! Phase 6 FT8/FT4-specifics keys (19 bools + 5 ints) + the tricky cases: bool +! true/false (distinguishing "set false" from "absent"), int parse, wrong-type +! detection (bool-as-number, int-as-string), the "mode" substring non-collisions +! introduced by hint_mode / hound_mode / superfox_mode (all contain "mode"), and +! value-vs-key aliasing. Compiled + run by +! test/run-phase6-parse-unit.sh against lib/streaming_control.f90. +! +! SCOPE: this guards the JSON -> configure_fields PARSE (the module-public entry +! point). The configure_fields -> params APPLY routing lives in the module-public +! streaming_apply::apply_configure_fields and is asserted by +! test/run-apply-routing-unit.sh (which includes the 24 Phase 6 slot asserts + +! the multithreaded_ft8 ignore-non-false guard). All 24 Phase 6 keys are inert on +! the FT8/JT9 fixtures (multithreaded_ft8 is destructive and +! apply-guarded, the rest read only on multithread/JT65/superfox/WAV paths or have +! no AP-only decodes on the fixture), so no decode-output gate can assert their +! values; this parse-unit + the apply-routing unit are their coverage. +program p6_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 6 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 6 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: all 24 keys present — 19 bools true, 5 ints at distinct values. + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","multithreaded_ft8":true,"ft8_cycles":2,' // & + '"ft8_rxf_sensitivity":4,"ft8_threads":3,"ft8_decoder_start":1,' // & + '"ft8_low_threshold":true,"ft8_subpass":true,"ft8_ap_on":true,' // & + '"ap_cq_only":true,"ap_my_call":true,"jt65_ap_on":true,' // & + '"ap_width_hz":150,"hide_ft8_duplicates":true,"common_ft8b":true,' // & + '"enable_dxc_search":true,"wide_dxc_search":true,"superfox_mode":true,' // & + '"even_sequence":true,"hound_mode":true,"multi_instance":true,' // & + '"skip_tx1":true,"nagain_filter":true,"stop_hint":true,"hint_mode":true}' + write(*,'(a)') 'Frame A: all 24 keys present (19 bools true, 5 ints distinct)' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + ! ints + call ok('ft8_cycles == 2', cfg%ft8_cycles_set .and. cfg%ft8_cycles .eq. 2) + call ok('ft8_rxf_sensitivity == 4', cfg%ft8_rxf_sensitivity_set .and. cfg%ft8_rxf_sensitivity .eq. 4) + call ok('ft8_threads == 3', cfg%ft8_threads_set .and. cfg%ft8_threads .eq. 3) + call ok('ft8_decoder_start == 1', cfg%ft8_decoder_start_set .and. cfg%ft8_decoder_start .eq. 1) + call ok('ap_width_hz == 150 (RAW)', cfg%ap_width_hz_set .and. cfg%ap_width_hz .eq. 150) + ! bools (true) + call ok('multithreaded_ft8 true', cfg%multithreaded_ft8_set .and. cfg%multithreaded_ft8) + call ok('ft8_low_threshold true', cfg%ft8_low_threshold_set .and. cfg%ft8_low_threshold) + call ok('ft8_subpass true', cfg%ft8_subpass_set .and. cfg%ft8_subpass) + call ok('ft8_ap_on true', cfg%ft8_ap_on_set .and. cfg%ft8_ap_on) + call ok('ap_cq_only true', cfg%ap_cq_only_set .and. cfg%ap_cq_only) + call ok('ap_my_call true', cfg%ap_my_call_set .and. cfg%ap_my_call) + call ok('jt65_ap_on true', cfg%jt65_ap_on_set .and. cfg%jt65_ap_on) + call ok('hide_ft8_duplicates true', cfg%hide_ft8_duplicates_set .and. cfg%hide_ft8_duplicates) + call ok('common_ft8b true', cfg%common_ft8b_set .and. cfg%common_ft8b) + call ok('enable_dxc_search true', cfg%enable_dxc_search_set .and. cfg%enable_dxc_search) + call ok('wide_dxc_search true', cfg%wide_dxc_search_set .and. cfg%wide_dxc_search) + call ok('superfox_mode true', cfg%superfox_mode_set .and. cfg%superfox_mode) + call ok('even_sequence true', cfg%even_sequence_set .and. cfg%even_sequence) + call ok('hound_mode true', cfg%hound_mode_set .and. cfg%hound_mode) + call ok('multi_instance true', cfg%multi_instance_set .and. cfg%multi_instance) + call ok('skip_tx1 true', cfg%skip_tx1_set .and. cfg%skip_tx1) + call ok('nagain_filter true', cfg%nagain_filter_set .and. cfg%nagain_filter) + call ok('stop_hint true', cfg%stop_hint_set .and. cfg%stop_hint) + call ok('hint_mode true', cfg%hint_mode_set .and. cfg%hint_mode) + end subroutine frame_A + + ! Frame B: bools false (distinguish "set false" from "absent"); ap_width_hz=0. + subroutine frame_B() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","ft8_ap_on":false,"ap_cq_only":false,' // & + '"superfox_mode":false,"hint_mode":false,"stop_hint":false,' // & + '"multithreaded_ft8":false,"ap_width_hz":0}' + write(*,'(a)') 'Frame B: bools false (set, not absent); ap_width_hz=0' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('ft8_ap_on set, value false', cfg%ft8_ap_on_set .and. (.not. cfg%ft8_ap_on)) + call ok('ap_cq_only set, value false', cfg%ap_cq_only_set .and. (.not. cfg%ap_cq_only)) + call ok('superfox_mode set, value false', cfg%superfox_mode_set .and. (.not. cfg%superfox_mode)) + call ok('hint_mode set, value false', cfg%hint_mode_set .and. (.not. cfg%hint_mode)) + call ok('stop_hint set, value false', cfg%stop_hint_set .and. (.not. cfg%stop_hint)) + call ok('multithreaded_ft8 set, false', cfg%multithreaded_ft8_set .and. (.not. cfg%multithreaded_ft8)) + call ok('ap_width_hz set, value 0', cfg%ap_width_hz_set .and. cfg%ap_width_hz .eq. 0) + end subroutine frame_B + + ! Frame C: "mode" substring non-collision. "mode" is a substring of hint_mode / + ! hound_mode / superfox_mode / tx_mode / submode — the structural key locator + ! (closing quote in the quoted token + anchor) must keep them distinct. Both + ! orderings. A raw-index regression would mis-classify these. + subroutine frame_C() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = & + '{"t":"configure","mode":"FT8","tx_mode":"JT9","superfox_mode":true,' // & + '"hound_mode":false,"hint_mode":true}' + character(len=*), parameter :: b2 = & + '{"t":"configure","hint_mode":true,"hound_mode":false,' // & + '"superfox_mode":true,"tx_mode":"JT9","mode":"FT8"}' + write(*,'(a)') 'Frame C: mode vs tx_mode/superfox_mode/hound_mode/hint_mode' + call parse_control_frame(b1, action, cfg, terr) + call ok('order1: terr not present', .not. terr%present) + call ok('order1: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order1: tx_mode == 9 (JT9)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order1: superfox_mode true', cfg%superfox_mode_set .and. cfg%superfox_mode) + call ok('order1: hound_mode false', cfg%hound_mode_set .and. (.not. cfg%hound_mode)) + call ok('order1: hint_mode true', cfg%hint_mode_set .and. cfg%hint_mode) + call parse_control_frame(b2, action, cfg, terr) + call ok('order2: terr not present', .not. terr%present) + call ok('order2: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order2: tx_mode == 9 (JT9)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order2: superfox_mode true', cfg%superfox_mode_set .and. cfg%superfox_mode) + call ok('order2: hound_mode false', cfg%hound_mode_set .and. (.not. cfg%hound_mode)) + call ok('order2: hint_mode true', cfg%hint_mode_set .and. cfg%hint_mode) + end subroutine frame_C + + ! Frame D: int key carrying a string -> configure_type_error. + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","ap_width_hz":"wide"}' + write(*,'(a)') 'Frame D: ap_width_hz:"wide" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == ap_width_hz', trim(terr%key) .eq. 'ap_width_hz') + call ok('expected == int', trim(terr%expected) .eq. 'int') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_D + + ! Frame E: bool key carrying a number -> configure_type_error (mirrors the + ! Gate 14 fixture, ft8_ap_on:5). + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","ft8_ap_on":5}' + write(*,'(a)') 'Frame E: ft8_ap_on:5 (number) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == ft8_ap_on', trim(terr%key) .eq. 'ft8_ap_on') + call ok('expected == bool', trim(terr%expected) .eq. 'bool') + call ok('got == number', trim(terr%got) .eq. 'number') + end subroutine frame_E + + ! Frame F: value-vs-key aliasing — the mycall VALUE is the literal "ft8_ap_on" + ! token, with no real ft8_ap_on key. The anchored locator must NOT mistake the + ! string value for the key: ft8_ap_on stays unset and NO false type error fires + ! (the benign no-false-decline contract for a Phase 6 key). + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mycall":"ft8_ap_on"}' + write(*,'(a)') 'Frame F: mycall value == "ft8_ap_on" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('mycall == ft8_ap_on', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'ft8_ap_on') + call ok('ft8_ap_on stays UNSET', .not. cfg%ft8_ap_on_set) + end subroutine frame_F + + ! Frame G: Phase 6 keys absent -> all unset, no error (keys are optional). + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8"}' + write(*,'(a)') 'Frame G: Phase 6 keys absent -> unset' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('multithreaded_ft8 unset', .not. cfg%multithreaded_ft8_set) + call ok('ft8_cycles unset', .not. cfg%ft8_cycles_set) + call ok('ft8_ap_on unset', .not. cfg%ft8_ap_on_set) + call ok('ap_width_hz unset', .not. cfg%ap_width_hz_set) + call ok('superfox_mode unset', .not. cfg%superfox_mode_set) + call ok('hint_mode unset', .not. cfg%hint_mode_set) + call ok('stop_hint unset', .not. cfg%stop_hint_set) + call ok('nagain_filter unset', .not. cfg%nagain_filter_set) + end subroutine frame_G + +end program p6_parse_test diff --git a/test/phase7_parse_test.f90 b/test/phase7_parse_test.f90 new file mode 100644 index 00000000..6cde831e --- /dev/null +++ b/test/phase7_parse_test.f90 @@ -0,0 +1,182 @@ +! Phase 7 parse-unit regression driver. Exercises parse_control_frame for the 6 +! Phase 7 diagnostic / sequencing keys (4 ints + 2 bools) + the tricky cases: bool +! true/false (distinguishing "set false" from "absent"), int parse, wrong-type +! detection (int-as-string, bool-as-number), the "mode" substring non-collision +! introduced by mode_changed (it contains "mode", which is also a key and a +! substring of tx_mode), and value-vs-key aliasing. +! Compiled + run by test/run-phase7-parse-unit.sh against lib/streaming_control.f90. +! +! SCOPE: this guards the JSON -> configure_fields PARSE (the module-public entry +! point). The configure_fields -> params APPLY routing lives in the module-public +! streaming_apply::apply_configure_fields and is asserted by +! test/run-apply-routing-unit.sh (which includes the 6 Phase 7 slot asserts). All +! 6 Phase 7 keys are inert on the FT8/JT9 fixtures (five read only +! inside the multithreaded-FT8 block decoder.f90:192..1148 which streaming forces +! off; qso_progress_state reaches the single-pass FT8 decoder but only steers AP +! passes and the fixture has no AP-only decodes), so no decode-output gate can +! assert their values; this parse-unit + the apply-routing unit are their coverage. +program p7_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 7 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 7 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: all 6 keys present — 4 ints at distinct values, 2 bools true. + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","last_tx_seconds_ago":4,"currently_txing":true,' // & + '"mode_changed":true,"qso_progress_state":5,"sec_band_changed":7,' // & + '"delay_units":6}' + write(*,'(a)') 'Frame A: all 6 keys present (4 ints distinct, 2 bools true)' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + ! ints + call ok('last_tx_seconds_ago == 4', cfg%last_tx_seconds_ago_set .and. cfg%last_tx_seconds_ago .eq. 4) + call ok('qso_progress_state == 5', cfg%qso_progress_state_set .and. cfg%qso_progress_state .eq. 5) + call ok('sec_band_changed == 7', cfg%sec_band_changed_set .and. cfg%sec_band_changed .eq. 7) + call ok('delay_units == 6', cfg%delay_units_set .and. cfg%delay_units .eq. 6) + ! bools (true) + call ok('currently_txing true', cfg%currently_txing_set .and. cfg%currently_txing) + call ok('mode_changed true', cfg%mode_changed_set .and. cfg%mode_changed) + end subroutine frame_A + + ! Frame B: bools false (distinguish "set false" from "absent"); ints at 0. + subroutine frame_B() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","currently_txing":false,"mode_changed":false,' // & + '"last_tx_seconds_ago":0,"delay_units":0}' + write(*,'(a)') 'Frame B: bools false (set, not absent); ints 0' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('currently_txing set, value false', cfg%currently_txing_set .and. (.not. cfg%currently_txing)) + call ok('mode_changed set, value false', cfg%mode_changed_set .and. (.not. cfg%mode_changed)) + call ok('last_tx_seconds_ago set, value 0', cfg%last_tx_seconds_ago_set .and. cfg%last_tx_seconds_ago .eq. 0) + call ok('delay_units set, value 0', cfg%delay_units_set .and. cfg%delay_units .eq. 0) + end subroutine frame_B + + ! Frame C: "mode" substring non-collision. "mode" is itself a key AND a + ! substring of tx_mode / mode_changed — the structural key locator (quoted token + ! + anchor) must keep them distinct in BOTH orderings. A raw-index regression + ! would mis-classify mode_changed as mode (or vice-versa). + subroutine frame_C() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = & + '{"t":"configure","mode":"FT8","tx_mode":"JT9","mode_changed":true}' + character(len=*), parameter :: b2 = & + '{"t":"configure","mode_changed":true,"tx_mode":"JT9","mode":"FT8"}' + write(*,'(a)') 'Frame C: mode vs tx_mode vs mode_changed (substring non-collision)' + call parse_control_frame(b1, action, cfg, terr) + call ok('order1: terr not present', .not. terr%present) + call ok('order1: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order1: tx_mode == 9 (JT9)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order1: mode_changed true', cfg%mode_changed_set .and. cfg%mode_changed) + call parse_control_frame(b2, action, cfg, terr) + call ok('order2: terr not present', .not. terr%present) + call ok('order2: mode == 8 (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + call ok('order2: tx_mode == 9 (JT9)', cfg%tx_mode_set .and. cfg%tx_mode .eq. 9) + call ok('order2: mode_changed true', cfg%mode_changed_set .and. cfg%mode_changed) + end subroutine frame_C + + ! Frame D: int key carrying a string -> configure_type_error (mirrors the + ! Gate 17 fixture, last_tx_seconds_ago:"soon"). + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","last_tx_seconds_ago":"soon"}' + write(*,'(a)') 'Frame D: last_tx_seconds_ago:"soon" (string) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == last_tx_seconds_ago', trim(terr%key) .eq. 'last_tx_seconds_ago') + call ok('expected == int', trim(terr%expected) .eq. 'int') + call ok('got == string', trim(terr%got) .eq. 'string') + end subroutine frame_D + + ! Frame E: bool key carrying a number -> configure_type_error. + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","currently_txing":5}' + write(*,'(a)') 'Frame E: currently_txing:5 (number) -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == currently_txing', trim(terr%key) .eq. 'currently_txing') + call ok('expected == bool', trim(terr%expected) .eq. 'bool') + call ok('got == number', trim(terr%got) .eq. 'number') + end subroutine frame_E + + ! Frame F: value-vs-key aliasing — the mycall VALUE is the literal + ! "delay_units" token (a Phase 7 key name; 11 chars, fits mycall's len=12), with + ! no real delay_units key. The anchored locator must NOT mistake the string + ! value for the key: delay_units stays unset and NO false type error fires + ! (the benign no-false-decline contract for a Phase 7 key). + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mycall":"delay_units"}' + write(*,'(a)') 'Frame F: mycall value == "delay_units" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('mycall == delay_units', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'delay_units') + call ok('delay_units stays UNSET', .not. cfg%delay_units_set) + end subroutine frame_F + + ! Frame G: Phase 7 keys absent -> all unset, no error (keys are optional). + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8"}' + write(*,'(a)') 'Frame G: Phase 7 keys absent -> unset' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('last_tx_seconds_ago unset', .not. cfg%last_tx_seconds_ago_set) + call ok('currently_txing unset', .not. cfg%currently_txing_set) + call ok('mode_changed unset', .not. cfg%mode_changed_set) + call ok('qso_progress_state unset', .not. cfg%qso_progress_state_set) + call ok('sec_band_changed unset', .not. cfg%sec_band_changed_set) + call ok('delay_units unset', .not. cfg%delay_units_set) + end subroutine frame_G + +end program p7_parse_test diff --git a/test/phase8_parse_test.f90 b/test/phase8_parse_test.f90 new file mode 100644 index 00000000..e36e3900 --- /dev/null +++ b/test/phase8_parse_test.f90 @@ -0,0 +1,299 @@ +! Phase 8 parse-unit regression driver. Exercises parse_control_frame for the 5 +! Phase 8 string & scaled / derived keys (utc/date/n_trials/candthin_threshold/ +! dt_center_seconds), which are MORE than flat value-extract: utc/date are ISO +! strings tokenized into the legacy int (utc->nutc HHMMSS, date->yymmdd), n_trials +! is ENCODED to nranera, and two keys carry a PARSE-TIME VALUE check that emits +! configure_type_error (n_trials not in {10^N,3*10^N}; date year>=2100). This +! driver asserts the derivations, the encoding table (incl. the n_trials=1 -> +! nranera=0 edge), the two value errors, the wrong-TYPE detection, malformed +! ISO silent-skip, that nutc AND utc are BOTH kept at parse (precedence is resolved +! at apply — see run-apply-routing-unit.sh frame_utc_precedence), and value-vs-key +! aliasing. Compiled + run by run-phase8-parse-unit.sh. +! +! SCOPE: this guards the JSON -> configure_fields PARSE. The configure_fields -> +! params APPLY routing (incl. the utc-wins precedence, the /100 scaling, and the +! flat date/n_trials pass-throughs) lives in streaming_apply::apply_configure_fields +! and is asserted by run-apply-routing-unit.sh. Four of the five keys +! are inert on the FT8/JT9 fixtures (date superfox-only, n_trials JT65-only, +! candthin/dtcenter multithread-variant-only), so this parse-unit + +! the apply-routing unit are their coverage; utc is decode-observable (Gates 19/20). +program p8_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE, CTRL_PARSE_ERR + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + call frame_H() + call frame_H2() + call frame_I() + call frame_J() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 8 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 8 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: all 5 keys present, distinct values, ALL valid. Asserts each + ! derivation: utc "13:34:30" -> nutc 133430; date "2021-07-03" -> yymmdd 210703 + ! ((2021-2000)*10000+7*100+3); n_trials 1000 -> nranera 6; the two reals stored. + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","utc":"13:34:30","date":"2021-07-03",' // & + '"n_trials":1000,"candthin_threshold":1.5,"dt_center_seconds":0.2}' + write(*,'(a)') 'Frame A: all 5 keys valid (utc/date/n_trials/candthin/dtcenter)' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + call ok('utc "13:34:30" -> utc_nutc = 133430', cfg%utc_set .and. cfg%utc_nutc .eq. 133430) + call ok('date "2021-07-03" -> date_yymmdd = 210703', cfg%date_set .and. cfg%date_yymmdd .eq. 210703) + call ok('n_trials 1000 -> nranera = 6', cfg%n_trials_set .and. cfg%n_trials_nranera .eq. 6) + call ok('candthin_threshold == 1.5', cfg%candthin_threshold_set .and. & + abs(cfg%candthin_threshold - 1.5d0) .lt. 1.0d-10) + call ok('dt_center_seconds == 0.2', cfg%dt_center_seconds_set .and. & + abs(cfg%dt_center_seconds - 0.2d0) .lt. 1.0d-10) + end subroutine frame_A + + ! Frame B: the n_trials -> nranera encoding TABLE. Each value is parsed in + ! its own frame so an encoder bug surfaces per-value. Covers both legs (10^N and + ! 3*10^N) and the n_trials=1 -> nranera=0 edge (the legacy quirk). + subroutine frame_B() + write(*,'(a)') 'Frame B: n_trials -> nranera encoding table' + call enc_ok('n_trials 1 -> nranera 0', 1, .true., 0) ! edge case (decoder reads 0 trials) + call enc_ok('n_trials 3 -> nranera 1', 3, .true., 1) + call enc_ok('n_trials 10 -> nranera 2', 10, .true., 2) + call enc_ok('n_trials 30 -> nranera 3', 30, .true., 3) + call enc_ok('n_trials 100 -> nranera 4', 100, .true., 4) + call enc_ok('n_trials 300 -> nranera 5', 300, .true., 5) + call enc_ok('n_trials 1000 -> nranera 6', 1000, .true., 6) + call enc_ok('n_trials 3000 -> nranera 7', 3000, .true., 7) + call enc_ok('n_trials 10000 -> nranera 8', 10000, .true., 8) + end subroutine frame_B + + ! Helper: parse {"t":"configure","n_trials":<n>} and assert set-state + nranera. + subroutine enc_ok(label, n, want_set, want_nranera) + character(len=*), intent(in) :: label + integer, intent(in) :: n, want_nranera + logical, intent(in) :: want_set + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=16) :: ns + character(len=64) :: b + write(ns, '(i0)') n + b = '{"t":"configure","n_trials":' // trim(ns) // '}' + call parse_control_frame(trim(b), action, cfg, terr) + if (want_set) then + call ok(label, (.not. terr%present) .and. cfg%n_trials_set .and. & + cfg%n_trials_nranera .eq. want_nranera) + else + call ok(label, terr%present .and. (.not. cfg%n_trials_set)) + end if + end subroutine enc_ok + + ! Frame C: n_trials VALUE-invalid (not 10^N/3*10^N) -> configure_type_error. The + ! JSON type is correct (a number), so this is the schema's first VALUE error (the + ! envelope reused). Tests 500 (the Gate-21 value), 0, and a negative. + subroutine frame_C() + write(*,'(a)') 'Frame C: n_trials value-invalid -> type error' + call inval_ok('n_trials 500 -> value error', 500) + call inval_ok('n_trials 0 -> value error', 0) + call inval_ok('n_trials 50 -> value error', 50) + call inval_ok('n_trials 7 -> value error', 7) + end subroutine frame_C + + subroutine inval_ok(label, n) + character(len=*), intent(in) :: label + integer, intent(in) :: n + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=16) :: ns + character(len=64) :: b + write(ns, '(i0)') n + b = '{"t":"configure","n_trials":' // trim(ns) // '}' + call parse_control_frame(trim(b), action, cfg, terr) + ! Assert the FULL envelope incl. expected, so the 'int 10^N|3*10^N' constraint + ! string is guarded at the parse-unit level (not only by Gate 21's cross-file + ! grep — a brittle coupling). + call ok(label, terr%present .and. (.not. cfg%n_trials_set) .and. & + trim(terr%key) .eq. 'n_trials' .and. & + trim(terr%expected) .eq. 'int 10^N|3*10^N' .and. & + trim(terr%got) .eq. 'number') + end subroutine inval_ok + + ! Frame D: date year >= 2100 -> configure_type_error (the YYMMDD encoding + ! caps at 2099). The parse succeeds (well-formed ISO) but the value is rejected. + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","date":"2200-01-01"}' + write(*,'(a)') 'Frame D: date year>=2100 -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == date', trim(terr%key) .eq. 'date') + call ok('expected == year<2100', trim(terr%expected) .eq. 'year<2100') + call ok('got == string', trim(terr%got) .eq. 'string') + call ok('date stays UNSET', .not. cfg%date_set) + end subroutine frame_D + + ! Frame E: wrong-TYPE detection (distinct from the value checks above). n_trials + ! as a string and candthin_threshold as a string -> check_type_ rejects (int / + ! real expected, got string). + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = '{"t":"configure","n_trials":"abc"}' + character(len=*), parameter :: b2 = '{"t":"configure","candthin_threshold":"x"}' + write(*,'(a)') 'Frame E: wrong-type keys (n_trials/candthin as string) -> type error' + call parse_control_frame(b1, action, cfg, terr) + call ok('n_trials string: terr present', terr%present) + call ok('n_trials string: key == n_trials', trim(terr%key) .eq. 'n_trials') + call ok('n_trials string: expected == int', trim(terr%expected) .eq. 'int') + call ok('n_trials string: got == string', trim(terr%got) .eq. 'string') + call parse_control_frame(b2, action, cfg, terr) + call ok('candthin string: terr present', terr%present) + call ok('candthin string: key == candthin_threshold', trim(terr%key) .eq. 'candthin_threshold') + call ok('candthin string: expected == real', trim(terr%expected) .eq. 'real') + call ok('candthin string: got == string', trim(terr%got) .eq. 'string') + end subroutine frame_E + + ! Frame F: malformed ISO strings -> value-domain SILENT SKIP (key left unset, NO + ! type error — these are well-typed strings, just not parseable HH:MM:SS / + ! YYYY-MM-DD). Mirrors the bad-mode-name silent skip. + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","utc":"13:34","date":"2021-07","mode":"FT8"}' + write(*,'(a)') 'Frame F: malformed ISO (utc "13:34" / date "2021-07") -> silent skip' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('utc "13:34" (no seconds) -> utc UNSET', .not. cfg%utc_set) + call ok('date "2021-07" (no day) -> date UNSET', .not. cfg%date_set) + call ok('mode still parsed (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + end subroutine frame_F + + ! Frame G: nutc AND utc both present -> parse keeps BOTH (the legacy int nutc and + ! the derived utc_nutc). Precedence (utc wins) is resolved at APPLY, not parse — + ! the parse-unit only proves both legs are captured (see frame_utc_precedence in + ! run-apply-routing-unit.sh for the apply-side utc-wins assertion). + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","nutc":120000,"utc":"13:34:30"}' + write(*,'(a)') 'Frame G: nutc + utc both kept at parse (precedence is apply-side)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('legacy nutc kept (120000)', cfg%nutc_set .and. cfg%nutc .eq. 120000) + call ok('utc derived kept (utc_nutc 133430)', cfg%utc_set .and. cfg%utc_nutc .eq. 133430) + end subroutine frame_G + + ! Frame H: value-vs-key aliasing — the mycall VALUE is the literal "n_trials" + ! token (8 chars, fits mycall len=12) with no real n_trials key. The anchored + ! locator must NOT mistake the string value for the key: n_trials stays unset and + ! NO false type error fires. + subroutine frame_H() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mycall":"n_trials"}' + write(*,'(a)') 'Frame H: mycall value == "n_trials" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('mycall == n_trials', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'n_trials') + call ok('n_trials stays UNSET', .not. cfg%n_trials_set) + end subroutine frame_H + + subroutine frame_H2() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","mycall":"n_trials","n_trials":1000}' + write(*,'(a)') 'Frame H2: value token before real n_trials key' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('mycall == n_trials', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'n_trials') + call ok('n_trials parsed', cfg%n_trials_set .and. cfg%n_trials_nranera .eq. 6) + end subroutine frame_H2 + + ! Frame I: Phase 8 keys absent -> all unset, no error (keys are optional). + subroutine frame_I() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8"}' + write(*,'(a)') 'Frame I: Phase 8 keys absent -> unset' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('utc unset', .not. cfg%utc_set) + call ok('date unset', .not. cfg%date_set) + call ok('n_trials unset', .not. cfg%n_trials_set) + call ok('candthin_threshold unset', .not. cfg%candthin_threshold_set) + call ok('dt_center_seconds unset', .not. cfg%dt_center_seconds_set) + end subroutine frame_I + + ! Frame J: truncated values exercise every scalar getter at end-of-buffer. + subroutine frame_J() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + write(*,'(a)') 'Frame J: truncated key values at end of frame' + + call parse_control_frame('{"t":', action, cfg, terr) + call ok('truncated required t -> parse error', action .eq. CTRL_PARSE_ERR) + + call parse_control_frame('{"t":"configure","mode":', action, cfg, terr) + call ok('truncated string key: action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('truncated string key: terr not present', .not. terr%present) + call ok('truncated string key: mode unset', .not. cfg%mode_set) + + call parse_control_frame('{"t":"configure","depth":', action, cfg, terr) + call ok('truncated int key: action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('truncated int key: terr not present', .not. terr%present) + call ok('truncated int key: depth unset', .not. cfg%depth_set) + + call parse_control_frame('{"t":"configure","trperiod": ', action, cfg, terr) + call ok('space-only real key: action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('space-only real key: terr not present', .not. terr%present) + call ok('space-only real key: trperiod unset', .not. cfg%trperiod_set) + + call parse_control_frame('{"t":"configure","my_call_standard":', action, cfg, terr) + call ok('truncated bool key: action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('truncated bool key: terr not present', .not. terr%present) + call ok('truncated bool key: my_call_standard unset', .not. cfg%my_call_standard_set) + end subroutine frame_J + +end program p8_parse_test diff --git a/test/phase9_parse_test.f90 b/test/phase9_parse_test.f90 new file mode 100644 index 00000000..7290ef4a --- /dev/null +++ b/test/phase9_parse_test.f90 @@ -0,0 +1,355 @@ +! Phase 9 parse-unit regression driver. Phase 9 unpacks two bit-packed legacy ints +! into 9 wire keys; parse_control_frame folds them BACK into the derived members +! cfg%ndepth_packed / cfg%nexp_decode_packed (the post-pass pack_phase9_), so this +! driver is the authoritative guard for the PACKING (each key -> its bit), the +! contest_type -> ncontest table (incl. the SpecOp 5/8/9 -> 1 collapse), the two +! atomic-decline errors (legacy depth co-present with any unpacked ndepth key; a +! depth_level vs q65_maxiters_level inconsistency), the bit-width MASKING of +! depth_level/q65_maxiters_level, and the noise_blanker -3 offset + [0,255] clamp. +! +! WHY a Fortran unit driver (not only fixtures through jt9): only depth_level is +! decode-observable on FT8/JT9 (Gate 24); the other 8 keys are inert (Q65/JT65/ +! FST4/JT4 or contest-branch only), and the bit-PACKING of even +! depth_level is invisible to a decode-count gate (ndepth=3 and ndepth=3|16 both +! decode 21 on FT8). This driver + run-apply-routing-unit.sh (the packed-int APPLY +! routing) + no-regression are the coverage for the 8 inert keys, exactly like the +! Phase 4/6/7 inert fields. Compiled + run by run-phase9-parse-unit.sh. +program p9_parse_test + use streaming_control, only: parse_control_frame, configure_fields, & + control_type_error, CTRL_CONFIGURE + implicit none + integer :: nfail + nfail = 0 + + call frame_A() + call frame_B() + call frame_C() + call frame_D() + call frame_E() + call frame_F() + call frame_G() + call frame_H() + call frame_I() + call frame_J() + call frame_K() + call frame_L() + call frame_M() + + write(*,'(a)') '------------------------------------------------------------' + if (nfail .eq. 0) then + write(*,'(a)') 'ALL PHASE 9 PARSE-UNIT CHECKS PASSED' + else + write(*,'(a,i0,a)') 'PHASE 9 PARSE-UNIT: ', nfail, ' CHECK(S) FAILED' + call exit(1) + end if + +contains + + subroutine ok(label, cond) + character(len=*), intent(in) :: label + logical, intent(in) :: cond + if (cond) then + write(*,'(a,a)') ' PASS ', label + else + write(*,'(a,a)') ' FAIL ', label + nfail = nfail + 1 + end if + end subroutine ok + + ! Frame A: ndepth bit-pack. depth_level=2 (bits0-2), use_averaging (0x10), + ! deep_ap_search (0x20), q65_auto_clear_average (0x80) -> ndepth = 2|16|32|128 = + ! 178. Asserts each bit lands (a dropped/mis-shifted bit changes the total). + subroutine frame_A() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","depth_level":2,"use_averaging":true,' // & + '"deep_ap_search":true,"q65_auto_clear_average":true}' + write(*,'(a)') 'Frame A: ndepth bit-pack (2 | 0x10 | 0x20 | 0x80 = 178)' + call parse_control_frame(b, action, cfg, terr) + call ok('action == CTRL_CONFIGURE', action .eq. CTRL_CONFIGURE) + call ok('terr not present', .not. terr%present) + call ok('ndepth_packed set', cfg%ndepth_packed_set) + call ok('ndepth_packed == 178', cfg%ndepth_packed .eq. 178) + ! Individual bits, so a single dropped key surfaces: + call ok('bit 0-2 (depth_level=2)', iand(cfg%ndepth_packed, 7) .eq. 2) + call ok('bit 4 (use_averaging)', iand(cfg%ndepth_packed, 16) .eq. 16) + call ok('bit 5 (deep_ap_search)', iand(cfg%ndepth_packed, 32) .eq. 32) + call ok('bit 7 (q65_auto_clear_avg)', iand(cfg%ndepth_packed, 128).eq. 128) + call ok('bit 3 unused (clear)', iand(cfg%ndepth_packed, 8) .eq. 0) + call ok('bit 6 unused (clear)', iand(cfg%ndepth_packed, 64) .eq. 0) + call ok('nexp_decode NOT packed (no nexp key)', .not. cfg%nexp_decode_packed_set) + end subroutine frame_A + + ! Frame B: contest_type -> ncontest table (incl. SpecOp/collapse). + ! Each string parsed in its own frame. The 5/8/9 -> 1 collapse is the key risk. + subroutine frame_B() + write(*,'(a)') 'Frame B: contest_type -> ncontest table (incl. SpecOp 5/8/9 collapse)' + call con_ok('none -> 0', 'none', 0) + call con_ok('na_vhf -> 1', 'na_vhf', 1) + call con_ok('eu_vhf -> 2', 'eu_vhf', 2) + call con_ok('field_day -> 3', 'field_day', 3) + call con_ok('rtty -> 4', 'rtty', 4) + call con_ok('ww_digi -> 1 (SpecOp 5 collapsed)', 'ww_digi', 1) + call con_ok('fox -> 6', 'fox', 6) + call con_ok('hound -> 7', 'hound', 7) + call con_ok('arrl_digi -> 1 (SpecOp 8 collapsed)', 'arrl_digi', 1) + call con_ok('q65_pileup -> 1 (SpecOp 9 collapsed)', 'q65_pileup', 1) + end subroutine frame_B + + ! Helper: parse {"t":"configure","contest_type":"<s>"} and assert the collapsed + ! ncontest lands in nexp_decode_packed bits 0-2 (and contest_type member). + subroutine con_ok(label, s, want) + character(len=*), intent(in) :: label, s + integer, intent(in) :: want + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=80) :: b + b = '{"t":"configure","contest_type":"' // trim(s) // '"}' + call parse_control_frame(trim(b), action, cfg, terr) + call ok(label, (.not. terr%present) .and. cfg%contest_type_set .and. & + cfg%contest_type .eq. want .and. cfg%nexp_decode_packed_set .and. & + iand(cfg%nexp_decode_packed, 7) .eq. want) + end subroutine con_ok + + ! Frame C: nexp_decode full pack. contest_type=fox (6) | single_decode (0x20) | + ! vhf_features (0x40) | noise_blanker_level=2 ((2+3)<<8 = 1280) -> 6+32+64+1280 = + ! 1382. Asserts each sub-field lands in its slot. + subroutine frame_C() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","contest_type":"fox","single_decode":true,' // & + '"vhf_features":true,"noise_blanker_level":2}' + write(*,'(a)') 'Frame C: nexp_decode full pack (6 | 0x20 | 0x40 | (2+3)<<8 = 1382)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('nexp_decode_packed == 1382', cfg%nexp_decode_packed .eq. 1382) + call ok('bits 0-2 (ncontest fox=6)', iand(cfg%nexp_decode_packed, 7) .eq. 6) + call ok('bit 5 (single_decode)', iand(cfg%nexp_decode_packed, 32) .eq. 32) + call ok('bit 6 (vhf_features)', iand(cfg%nexp_decode_packed, 64) .eq. 64) + call ok('upper byte (nb+3 = 5)', cfg%nexp_decode_packed / 256 .eq. 5) + call ok('ndepth NOT packed (no ndepth key)', .not. cfg%ndepth_packed_set) + end subroutine frame_C + + ! Frame D: depth_level vs q65_maxiters_level consistency (bits 0-1 + ! overlap). (a) consistent pair (depth_level=6 low2=2, q65_maxiters=2) -> OK, + ! ndepth bits0-2 = 6. (b) inconsistent pair -> configure_type_error. + subroutine frame_D() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: ba = & + '{"t":"configure","depth_level":6,"q65_maxiters_level":2}' + character(len=*), parameter :: bb = & + '{"t":"configure","depth_level":6,"q65_maxiters_level":1}' + write(*,'(a)') 'Frame D: depth_level/q65_maxiters_level consistency (bits 0-1 overlap)' + call parse_control_frame(ba, action, cfg, terr) + call ok('(a) consistent (6 low2 == 2): no error', .not. terr%present) + call ok('(a) ndepth_packed == 6', cfg%ndepth_packed .eq. 6) + call parse_control_frame(bb, action, cfg, terr) + call ok('(b) inconsistent (6 low2=2 != 1): terr present', terr%present) + call ok('(b) key == q65_maxiters_level', trim(terr%key) .eq. 'q65_maxiters_level') + call ok('(b) expected == match depth_lvl', trim(terr%expected) .eq. 'match depth_lvl') + call ok('(b) got == conflict', trim(terr%got) .eq. 'conflict') + call ok('(b) ndepth NOT packed (declined)', .not. cfg%ndepth_packed_set) + end subroutine frame_D + + ! Frame E: legacy depth co-present with an unpacked ndepth key -> conflict + ! configure_type_error (the two encodings are mutually exclusive). + subroutine frame_E() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","depth":3,"depth_level":1}' + write(*,'(a)') 'Frame E: depth + depth_level conflict -> type error' + call parse_control_frame(b, action, cfg, terr) + call ok('terr present', terr%present) + call ok('key == ndepth', trim(terr%key) .eq. 'ndepth') + call ok('expected == depth|unpacked', trim(terr%expected) .eq. 'depth|unpacked') + call ok('got == conflict', trim(terr%got) .eq. 'conflict') + call ok('ndepth NOT packed (declined)', .not. cfg%ndepth_packed_set) + end subroutine frame_E + + ! Frame F: bit-width MASKING. An out-of-range depth_level=99 (0x63) must mask to + ! its 3 bits (99 & 7 = 3) so it cannot corrupt sibling bits (4/5/7). Likewise a + ! lone q65_maxiters_level=99 masks to 2 bits (99 & 3 = 3). No crash. + subroutine frame_F() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: ba = '{"t":"configure","depth_level":99}' + character(len=*), parameter :: bb = '{"t":"configure","q65_maxiters_level":99}' + write(*,'(a)') 'Frame F: out-of-range depth_level/q65_maxiters masked to bit width' + call parse_control_frame(ba, action, cfg, terr) + call ok('(a) depth_level=99 -> ndepth = 3 (99 & 7)', cfg%ndepth_packed .eq. 3) + call ok('(a) no sibling bits set', iand(cfg%ndepth_packed, 240) .eq. 0) + call ok('(a) no type error', .not. terr%present) + call parse_control_frame(bb, action, cfg, terr) + call ok('(b) q65_maxiters=99 -> ndepth = 3 (99 & 3)', cfg%ndepth_packed .eq. 3) + end subroutine frame_F + + ! Frame G: q65_maxiters_level alone (no depth_level) -> derive depth_level's + ! bits 0-1 from it (receiver-side derivation). q65_maxiters=3 -> ndepth=3. + subroutine frame_G() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","q65_maxiters_level":3,"use_averaging":true}' + write(*,'(a)') 'Frame G: q65_maxiters_level alone -> ndepth bits 0-1 derived' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('ndepth_packed == 3|16 = 19', cfg%ndepth_packed .eq. 19) + call ok('bits 0-1 = q65_maxiters 3', iand(cfg%ndepth_packed, 3) .eq. 3) + end subroutine frame_G + + ! Frame H: noise_blanker_level -3 offset + [0,255] clamp (upper byte). + ! nb=0 -> (0+3)<<8 = 768; nb=-3 -> 0; nb=300 -> clamp 255 -> 255<<8 = 65280. + ! Each still sets nexp_decode_packed_set (the key was present). + subroutine frame_H() + write(*,'(a)') 'Frame H: noise_blanker_level offset + clamp' + call nb_ok('nb=0 -> upper byte 3 (768)', 0, 768) + call nb_ok('nb=2 -> upper byte 5 (1280)', 2, 1280) + call nb_ok('nb=-3 -> upper byte 0 (clamp)', -3, 0) + call nb_ok('nb=300 -> upper byte 255 (clamp)', 300, 65280) + end subroutine frame_H + + subroutine nb_ok(label, nb, want) + character(len=*), intent(in) :: label + integer, intent(in) :: nb, want + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=16) :: ns + character(len=64) :: b + write(ns, '(i0)') nb + b = '{"t":"configure","noise_blanker_level":' // trim(ns) // '}' + call parse_control_frame(trim(b), action, cfg, terr) + call ok(label, (.not. terr%present) .and. cfg%nexp_decode_packed_set .and. & + cfg%nexp_decode_packed .eq. want) + end subroutine nb_ok + + ! Frame I: wrong-TYPE detection. depth_level as a string (int expected) and + ! contest_type as a number (string expected) -> check_type_ rejects. + subroutine frame_I() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b1 = '{"t":"configure","depth_level":"deep"}' + character(len=*), parameter :: b2 = '{"t":"configure","contest_type":5}' + character(len=*), parameter :: b3 = '{"t":"configure","use_averaging":7}' + write(*,'(a)') 'Frame I: wrong-type Phase 9 keys -> type error' + call parse_control_frame(b1, action, cfg, terr) + call ok('depth_level string: terr present', terr%present) + call ok('depth_level string: key', trim(terr%key) .eq. 'depth_level') + call ok('depth_level string: expected', trim(terr%expected) .eq. 'int') + call ok('depth_level string: got', trim(terr%got) .eq. 'string') + call ok('depth_level string: ndepth NOT packed', .not. cfg%ndepth_packed_set) + call parse_control_frame(b2, action, cfg, terr) + call ok('contest_type number: terr present', terr%present) + call ok('contest_type number: key', trim(terr%key) .eq. 'contest_type') + call ok('contest_type number: expected', trim(terr%expected) .eq. 'string') + call parse_control_frame(b3, action, cfg, terr) + call ok('use_averaging number: terr present', terr%present) + call ok('use_averaging number: expected bool', trim(terr%expected) .eq. 'bool') + end subroutine frame_I + + ! Frame J: unknown contest_type string -> value-domain SILENT SKIP (left unset, + ! NO type error — mirrors the unknown-mode-name skip). nexp not packed. + subroutine frame_J() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = & + '{"t":"configure","contest_type":"sweepstakes","mode":"FT8"}' + write(*,'(a)') 'Frame J: unknown contest_type -> silent skip (no false decline)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('contest_type stays UNSET', .not. cfg%contest_type_set) + call ok('nexp NOT packed', .not. cfg%nexp_decode_packed_set) + call ok('mode still parsed (FT8)', cfg%mode_set .and. cfg%mode .eq. 8) + end subroutine frame_J + + ! Frame K: value-vs-key aliasing. The mycall VALUE is the literal + ! token "depth_level" (11 chars, fits mycall len=12) with no real depth_level + ! key. The anchored locator must NOT mistake the value for the key. + subroutine frame_K() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mycall":"depth_level"}' + write(*,'(a)') 'Frame K: mycall value == "depth_level" token (aliasing guard)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present (no false decline)', .not. terr%present) + call ok('mycall == depth_level', cfg%mycall_set .and. trim(cfg%mycall) .eq. 'depth_level') + call ok('depth_level stays UNSET', .not. cfg%depth_level_set) + call ok('ndepth NOT packed', .not. cfg%ndepth_packed_set) + end subroutine frame_K + + ! Frame L: Phase 9 keys absent -> all unset, no error, no packing (keys optional). + subroutine frame_L() + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=*), parameter :: b = '{"t":"configure","mode":"FT8","depth":3}' + write(*,'(a)') 'Frame L: Phase 9 keys absent -> unset (legacy depth alone OK)' + call parse_control_frame(b, action, cfg, terr) + call ok('terr not present', .not. terr%present) + call ok('depth (legacy) still set', cfg%depth_set .and. cfg%depth .eq. 3) + call ok('depth_level unset', .not. cfg%depth_level_set) + call ok('contest_type unset', .not. cfg%contest_type_set) + call ok('ndepth NOT packed', .not. cfg%ndepth_packed_set) + call ok('nexp_decode NOT packed', .not. cfg%nexp_decode_packed_set) + end subroutine frame_L + + ! Frame M: per-bool SINGLE-BIT isolation (closes the swap-blindness where + ! two bool keys that only ever appear together-all-true can be + ! swapped invisibly: Frame A sets all 3 ndepth bools true, Frame C both nexp + ! bools true, so a deep_ap_search<->q65_auto_clear_average (0x20<->0x80) or a + ! single_decode<->vhf_features (0x20<->0x40) swap leaves the total unchanged). + ! Each bool set ALONE asserts EXACTLY its bit, so every bool->bit assignment is + ! now independently load-bearing. (use_averaging is also disambiguated by Frame G, + ! but assert it here too for symmetry.) + subroutine frame_M() + write(*,'(a)') 'Frame M: per-bool single-bit isolation (swap-blindness guard)' + call bit_ok_ndepth('use_averaging alone -> ndepth 0x10', 'use_averaging', 16) + call bit_ok_ndepth('deep_ap_search alone -> ndepth 0x20', 'deep_ap_search', 32) + call bit_ok_ndepth('q65_auto_clear_average alone -> ndepth 0x80', 'q65_auto_clear_average', 128) + call bit_ok_nexp('single_decode alone -> nexp 0x20', 'single_decode', 32) + call bit_ok_nexp('vhf_features alone -> nexp 0x40', 'vhf_features', 64) + end subroutine frame_M + + ! Helper: parse {"t":"configure","<key>":true} and assert ndepth_packed == want + ! EXACTLY (so the bit isolated is the only one set; a mis-shift fails the equality). + subroutine bit_ok_ndepth(label, key, want) + character(len=*), intent(in) :: label, key + integer, intent(in) :: want + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=80) :: b + b = '{"t":"configure","' // trim(key) // '":true}' + call parse_control_frame(trim(b), action, cfg, terr) + call ok(label, (.not. terr%present) .and. cfg%ndepth_packed_set .and. & + cfg%ndepth_packed .eq. want) + end subroutine bit_ok_ndepth + + subroutine bit_ok_nexp(label, key, want) + character(len=*), intent(in) :: label, key + integer, intent(in) :: want + type(configure_fields) :: cfg + type(control_type_error) :: terr + integer :: action + character(len=80) :: b + b = '{"t":"configure","' // trim(key) // '":true}' + call parse_control_frame(trim(b), action, cfg, terr) + call ok(label, (.not. terr%present) .and. cfg%nexp_decode_packed_set .and. & + cfg%nexp_decode_packed .eq. want) + end subroutine bit_ok_nexp + +end program p9_parse_test diff --git a/test/run-apply-routing-unit.sh b/test/run-apply-routing-unit.sh new file mode 100755 index 00000000..83c11037 --- /dev/null +++ b/test/run-apply-routing-unit.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# apply-routing unit regression. Compiles +# lib/streaming_control.f90 + lib/jt9_params_init.f90 + lib/streaming_apply.f90 +# and the driver test/apply_routing_test.f90 into an ISOLATED module dir and runs +# it. Guards the APPLY side: each configure_fields member -> its CORRECT +# params_block slot, plus the order-sensitive logic (rxfreq/tx_audio_offset +# decouple, emedelay-before-per-mode-policy, nfa/nfb baseline restore, ntol +# per-mode cap/restore). +# +# WHY a Fortran unit driver: the cfg->params apply routing used to live in a +# nested INTERNAL subroutine (streaming_io.f90 apply_configure_), unreachable from +# a unit driver, AND most Phase 4/5 fields are inert on the FT8/JT9 fixtures, so a +# mis-route (e.g. his_call -> hisgrid) passed every fixture gate byte-identical. +# The mapping was extracted to the module-public +# streaming_apply::apply_configure_fields so this driver can assert it directly. +# This is the structural close of the apply-routing gap. +# +# Usage: +# test/run-apply-routing-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-apply-routing-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC_CTRL="$REPO_ROOT/lib/streaming_control.f90" +SRC_INIT="$REPO_ROOT/lib/jt9_params_init.f90" +SRC_APPLY="$REPO_ROOT/lib/streaming_apply.f90" +DRV="$REPO_ROOT/test/apply_routing_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC_CTRL" "$SRC_INIT" "$SRC_APPLY" "$DRV" \ + "$REPO_ROOT/lib/jt9com.f90" "$REPO_ROOT/lib/constants.f90"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the fresh +# compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "apply-routing unit regression" +echo " FC: $FC" +echo " driver: $DRV" +echo "" + +# Copy the textual includes (jt9com.f90 -> constants.f90) into the work dir so the +# INCLUDE chain resolves with cwd=$WORK and lib/ never lands on the search path. +cp "$REPO_ROOT/lib/jt9com.f90" "$REPO_ROOT/lib/constants.f90" "$WORK/" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files (and INCLUDE files) first, so a stray repo-root *.mod / jt9com.f90 +# would otherwise shadow the fresh compile. -J/-I alone +# do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC_CTRL" -J"$WORK" -I"$WORK" -o "$WORK/streaming_control.o" +"$FC" -c "$SRC_INIT" -J"$WORK" -I"$WORK" -o "$WORK/jt9_params_init.o" +"$FC" -c "$SRC_APPLY" -J"$WORK" -I"$WORK" -o "$WORK/streaming_apply.o" +"$FC" "$DRV" "$WORK/streaming_control.o" "$WORK/jt9_params_init.o" \ + "$WORK/streaming_apply.o" -I"$WORK" -o "$WORK/apply_drv" +"$WORK/apply_drv" diff --git a/test/run-golden-fixtures.sh b/test/run-golden-fixtures.sh new file mode 100755 index 00000000..467baf98 --- /dev/null +++ b/test/run-golden-fixtures.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# golden-fixture regression harness. +# +# Compares decoder stdout against known-good captures, for both `jt9` +# (FT8/JT9/Q65/MSK144/FST4/FST4W/FT4/JT65/JT4) and the standalone `wsprd` +# (WSPR) binary. Any regression that changes decoder stdout byte-for-byte +# fails here. +# +# Usage: +# test/run-golden-fixtures.sh [build-dir] +# +# Where build-dir defaults to ./build and must contain built jt9 and wsprd +# binaries. + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +WSPRD="$REPO_ROOT/$BUILD_DIR/wsprd" +SAMPLES="$REPO_ROOT/samples" +FIXTURES="$REPO_ROOT/test/fixtures" + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found at $JT9" >&2 + echo " Build it first: cmake --build $BUILD_DIR --target jt9" >&2 + exit 2 +fi + +if [[ ! -x "$WSPRD" ]]; then + echo "ERROR: wsprd binary not found at $WSPRD" >&2 + echo " Build it first: cmake --build $BUILD_DIR --target wsprd" >&2 + exit 2 +fi + +FAIL=0 +pass() { echo " PASS: $1"; } +fail() { echo " FAIL: $1"; FAIL=1; } + +run_fixture() { + local binary="$1"; shift + local name="$1"; shift + local sample="$1"; shift + local expected="$1"; shift + # Remaining args are flags for $binary (e.g., -8, -9, --q65 -p 30 ..., etc.) + + local actual_file + actual_file="$(mktemp -t "wsjtl-golden-$name.XXXXXX")" + + if ! "$binary" "$@" "$sample" > "$actual_file" 2>&1; then + fail "$name: $(basename "$binary") exited non-zero" + rm -f "$actual_file" + return + fi + + if diff -u "$expected" "$actual_file" > /dev/null 2>&1; then + pass "$name" + else + fail "$name: output differs from golden (see diff below)" + diff -u "$expected" "$actual_file" | head -30 | sed 's/^/ /' + fi + rm -f "$actual_file" +} + +echo "golden-fixture regression" +echo " jt9: $JT9" +echo " wsprd: $WSPRD" +echo " fixtures: $FIXTURES" +echo "" + +run_fixture "$JT9" "ft8_210703_133430" \ + "$SAMPLES/FT8/210703_133430.wav" \ + "$FIXTURES/ft8_210703_133430.expected.txt" \ + -8 + +run_fixture "$JT9" "jt9_130418_1742" \ + "$SAMPLES/JT9/130418_1742.wav" \ + "$FIXTURES/jt9_130418_1742.expected.txt" \ + -9 + +run_fixture "$JT9" "q65_30a_201203_024000" \ + "$SAMPLES/Q65/30A_Ionoscatter_6m/201203_024000.wav" \ + "$FIXTURES/q65_30a_201203_024000.expected.txt" \ + --q65 -p 30 -f 1000 -d 3 + +run_fixture "$JT9" "q65_300a_201210_0505" \ + "$SAMPLES/Q65/300A_Optical_Scatter/201210_0505.wav" \ + "$FIXTURES/q65_300a_201210_0505.expected.txt" \ + --q65 -p 300 -f 1000 -d 3 + +run_fixture "$JT9" "q65_60d_201212_1838" \ + "$SAMPLES/Q65/60D_EME_10GHz/201212_1838.wav" \ + "$FIXTURES/q65_60d_201212_1838.expected.txt" \ + --q65 -b D -p 60 -f 1000 -d 3 + +run_fixture "$JT9" "msk144_181211_120800" \ + "$SAMPLES/MSK144/181211_120800.wav" \ + "$FIXTURES/msk144_181211_120800.expected.txt" \ + --msk144 -p 15 -f 1500 -F 50 -d 3 + +run_fixture "$JT9" "fst4_210115_0058" \ + "$SAMPLES/FST4+FST4W/210115_0058.wav" \ + "$FIXTURES/fst4_210115_0058.expected.txt" \ + --fst4 -p 60 -f 1331 -L 1000 -H 1400 -d 3 + +run_fixture "$JT9" "fst4w_201230_0300" \ + "$SAMPLES/FST4+FST4W/201230_0300.wav" \ + "$FIXTURES/fst4w_201230_0300.expected.txt" \ + --fst4w -p 1800 -f 1433 -F 100 -d 3 + +run_fixture "$JT9" "ft4_000000_000002" \ + "$SAMPLES/FT4/000000_000002.wav" \ + "$FIXTURES/ft4_000000_000002.expected.txt" \ + --ft4 -d 3 + +run_fixture "$JT9" "jt65_000000_0004" \ + "$SAMPLES/JT65/JT65B/000000_0004.wav" \ + "$FIXTURES/jt65_000000_0004.expected.txt" \ + --jt65 -b B -f 1700 -d 3 + +run_fixture "$JT9" "jt4_OK1KIR_141105_175700" \ + "$SAMPLES/JT4/JT4F/OK1KIR_141105_175700.WAV" \ + "$FIXTURES/jt4_OK1KIR_141105_175700.expected.txt" \ + --jt4 -b F -f 1200 -d 3 + +run_fixture "$WSPRD" "wspr_150426_0918" \ + "$SAMPLES/WSPR/150426_0918.wav" \ + "$FIXTURES/wspr_150426_0918.expected.txt" + +echo "" +if [[ $FAIL -eq 0 ]]; then + echo "All golden fixtures passed." + exit 0 +else + echo "One or more golden fixtures regressed." + exit 1 +fi diff --git a/test/run-phase4-parse-unit.sh b/test/run-phase4-parse-unit.sh new file mode 100755 index 00000000..0d30a5e2 --- /dev/null +++ b/test/run-phase4-parse-unit.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Phase 4 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase4_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE side of the 9 Phase 4 keys: each key -> correct configure_fields member + +# value, bool true/false, his_call vs his_call_standard substring non-collision, +# wrong-type detection (bool/string/int), and the value-vs-key aliasing guard. +# +# WHY a Fortran unit driver (not a fixture through jt9): the 9 Phase 4 fields are +# observably INERT on the FT8/JT9 fixtures (tx/Q65/JT65-split only — an +# all-9-keys configure yields a byte-identical 21-message FT8 decode set), so no +# decode-output gate can assert a Phase 4 value landed. This unit driver is the +# parse->pack assert for inert fields. +# +# SCOPE: this guards JSON -> configure_fields PARSE only (the module-public entry +# point). The configure_fields -> params APPLY routing now lives in the module- +# public streaming_apply::apply_configure_fields and is asserted by +# test/run-apply-routing-unit.sh — so the 9 inert Phase 4 fields' apply routing +# IS now unit-guarded, not just code-review + no-regression. +# +# Usage: +# test/run-phase4-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase4-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase4_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 4 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile (the -J/-I flags alone do NOT remove cwd from the +# search order; the cd does). +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p4drv" +"$WORK/p4drv" diff --git a/test/run-phase5-parse-unit.sh b/test/run-phase5-parse-unit.sh new file mode 100755 index 00000000..2c3a9aeb --- /dev/null +++ b/test/run-phase5-parse-unit.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Phase 5 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase5_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE side of the 12 Phase 5 decoder-tuning keys: each key -> correct +# configure_fields member + value, real(8) keys, the tx_mode enum (JT9/JT65 -> 9/ +# 65 and raw int), bool true/false, wrong-type detection (real/int/bool), the +# "mode" vs "tx_mode" + "min_width" vs "min_sync" substring non-collision, and +# the value-vs-key aliasing guard. +# +# WHY a Fortran unit driver (not only a fixture through jt9): 10 of the 12 Phase 5 +# fields are observably INERT on the FT8/JT9 fixtures (kin/nzhsym +# are recomputed per period; dttol/minw/minsync/n2pass/nrobust/nclearave are +# JT4/JT65/Q65-only; emedelay is forced to 0 on a mode-setting frame; ntxmode is +# read only in mode 65+9), so no decode-output gate can assert those values +# landed. This unit driver is the parse->pack assert for them. +# The two observable keys (nagain_flag -> FT8, npts_c0_array -> JT9) ALSO get a +# decode-effect gate in run-schema-v1-fixtures.sh (Gates 11/12). +# +# SCOPE: this guards JSON -> configure_fields PARSE only (the module-public entry +# point). The configure_fields -> params APPLY routing now lives in the module- +# public streaming_apply::apply_configure_fields and is asserted by +# test/run-apply-routing-unit.sh — so the 10 inert keys' apply routing IS now +# unit-guarded, not just code-review + no-regression. +# +# Usage: +# test/run-phase5-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase5-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase5_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 5 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile. +# -J/-I alone do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p5drv" +"$WORK/p5drv" diff --git a/test/run-phase6-parse-unit.sh b/test/run-phase6-parse-unit.sh new file mode 100755 index 00000000..bbdeb629 --- /dev/null +++ b/test/run-phase6-parse-unit.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Phase 6 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase6_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE side of the 24 Phase 6 FT8/FT4-specifics keys (19 bools + 5 ints): each +# key -> correct configure_fields member + value, bool true/false, int parse, +# wrong-type detection (bool-as-number, int-as-string), the NEW "mode" substring +# non-collisions (hint_mode / hound_mode / superfox_mode all contain "mode"), and +# the value-vs-key aliasing guard. +# +# WHY a Fortran unit driver (not only a fixture through jt9): all 24 Phase 6 keys +# are INERT on the FT8/JT9 fixtures (multithreaded_ft8 is +# destructive and apply-guarded to ignore non-false; the other 23 are read only on +# the multithread-FT8 / JT65 / superfox-Q65 / WAV-disk paths or are AP keys for +# which the fixture has no AP-only decodes), so no decode-output gate can assert +# those values landed. This unit driver is the parse->pack assert +# for the PARSE side; the configure_fields -> params APPLY routing is asserted by +# test/run-apply-routing-unit.sh (the 24 Phase 6 slot asserts + the +# multithreaded_ft8 ignore-non-false guard). +# +# Usage: +# test/run-phase6-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase6-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase6_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 6 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile. +# -J/-I alone do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p6drv" +"$WORK/p6drv" diff --git a/test/run-phase7-parse-unit.sh b/test/run-phase7-parse-unit.sh new file mode 100755 index 00000000..19c4cb33 --- /dev/null +++ b/test/run-phase7-parse-unit.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Phase 7 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase7_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE side of the 6 Phase 7 diagnostic / sequencing keys (4 ints + 2 bools): +# each key -> correct configure_fields member + value, bool true/false, int +# parse, wrong-type detection (int-as-string, bool-as-number), the "mode" +# substring non-collision (mode_changed contains "mode"), and the value-vs-key +# aliasing guard. +# +# WHY a Fortran unit driver (not only a fixture through jt9): all 6 Phase 7 keys +# are INERT on the FT8/JT9 fixtures (five are read only inside +# the multithreaded-FT8 block decoder.f90:192..1148 which streaming forces off; +# qso_progress_state reaches the single-pass FT8 decoder but only steers AP +# decoding passes and the fixture has no AP-only decodes), so no decode-output +# gate can assert those values landed. This unit driver is the +# parse->pack assert for the PARSE side; the configure_fields -> params APPLY +# routing is asserted by test/run-apply-routing-unit.sh (the 6 Phase 7 slot +# asserts). +# +# Usage: +# test/run-phase7-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase7-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase7_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 7 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile. +# -J/-I alone do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p7drv" +"$WORK/p7drv" diff --git a/test/run-phase8-parse-unit.sh b/test/run-phase8-parse-unit.sh new file mode 100755 index 00000000..10848cac --- /dev/null +++ b/test/run-phase8-parse-unit.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Phase 8 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase8_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE side of the 5 Phase 8 string & scaled / derived keys +# (utc/date/n_trials/candthin_threshold/dt_center_seconds): the ISO derivations +# (utc->nutc HHMMSS, date->yymmdd), the n_trials->nranera encoding table (incl. the +# n_trials=1 -> nranera=0 spec edge), the two PARSE-TIME VALUE errors (n_trials not +# in {10^N,3*10^N}; date year>=2100), wrong-TYPE detection, malformed-ISO silent +# skip, nutc+utc both captured, and the value-vs-key aliasing guard. +# +# WHY a Fortran unit driver (not only a fixture through jt9): four of the five +# Phase 8 keys are INERT on the FT8/JT9 fixtures (date superfox-only; n_trials +# JT65-deep-search-only; candthin_threshold/dt_center_seconds multithread-FT8- +# variant-only), so no decode-output gate can assert those +# derivations landed. (utc IS decode-observable — Gates 19/20.) This driver is the +# parse->pack assert for the PARSE side; the configure_fields -> +# params APPLY routing (incl. the utc-wins precedence + the /100 scaling) is +# asserted by test/run-apply-routing-unit.sh. +# +# Usage: +# test/run-phase8-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase8-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase8_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 8 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile. +# -J/-I alone do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p8drv" +"$WORK/p8drv" diff --git a/test/run-phase9-parse-unit.sh b/test/run-phase9-parse-unit.sh new file mode 100755 index 00000000..738116fb --- /dev/null +++ b/test/run-phase9-parse-unit.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Phase 9 parse-unit regression (streaming-schema unit parse->pack assert). +# Compiles lib/streaming_control.f90 and the driver +# test/phase9_parse_test.f90 into an ISOLATED module dir and runs it. Guards the +# PARSE + PACK side of the 9 bit-packed keys (depth_level/q65_maxiters_level/ +# use_averaging/deep_ap_search/q65_auto_clear_average -> ndepth; +# contest_type/single_decode/vhf_features/noise_blanker_level -> nexp_decode): the +# per-bit packing, the contest_type -> ncontest table (incl. the SpecOp 5/8/9 -> 1 +# collapse), the two atomic-decline errors (legacy depth co-present with an unpacked +# ndepth key; depth_level vs q65_maxiters_level inconsistency), the bit-width masking +# of depth_level/q65_maxiters, the noise_blanker -3 offset + [0,255] clamp, +# wrong-type detection, the unknown-contest silent skip, and value-vs-key aliasing. +# +# WHY a Fortran unit driver (not only fixtures through jt9): only depth_level is +# decode-observable on FT8/JT9 (Gate 24); the other 8 keys are INERT (Q65/JT65/ +# FST4/JT4 or contest-branch only), and even depth_level's bit +# PACKING is invisible to a decode-count gate (ndepth=3 and ndepth=3|16 both decode +# 21 on FT8). This driver is the parse->pack assert; the +# configure_fields -> params APPLY routing (the packed ints -> ndepth/nexp_decode) +# is asserted by test/run-apply-routing-unit.sh. +# +# Usage: +# test/run-phase9-parse-unit.sh (no build dir; compiles from source) +# FC=gfortran-13 test/run-phase9-parse-unit.sh (override the compiler) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FC="${FC:-gfortran}" +SRC="$REPO_ROOT/lib/streaming_control.f90" +DRV="$REPO_ROOT/test/phase9_parse_test.f90" + +if ! command -v "$FC" >/dev/null 2>&1; then + echo "ERROR: Fortran compiler '$FC' not found (set \$FC to override)" >&2 + exit 2 +fi +for f in "$SRC" "$DRV"; do + if [[ ! -f "$f" ]]; then + echo "ERROR: missing source: $f" >&2 + exit 2 + fi +done + +# Compile into a throwaway dir so a stray repo-root *.mod cannot shadow the +# fresh compile, and so we leave no artifacts behind. +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +echo "Phase 9 parse-unit regression" +echo " FC: $FC" +echo " source: $SRC" +echo " driver: $DRV" +echo "" + +# Compile FROM the work dir as cwd: gfortran searches the current directory for +# .mod files first, so a stray repo-root streaming_control.mod would otherwise +# shadow the fresh compile. +# -J/-I alone do NOT remove cwd from the search order; the cd does. +cd "$WORK" +"$FC" -c "$SRC" -J"$WORK" -o "$WORK/streaming_control.o" +"$FC" "$DRV" "$WORK/streaming_control.o" -I"$WORK" -o "$WORK/p9drv" +"$WORK/p9drv" diff --git a/test/run-pr3-fixtures.sh b/test/run-pr3-fixtures.sh new file mode 100755 index 00000000..f0ba2117 --- /dev/null +++ b/test/run-pr3-fixtures.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Configure-protocol regression harness — nutc thread-through, nfa/nfb +# mode-change restore, and ntol widening transition. +# +# Three gates: +# 1. nutc thread-through: verify NDJSON time field reflects sent nutc. +# 2. Mode-change ntol restore: prepend Q65 configure (auto-sets ntol=10), +# then FT8 configure with no explicit ntol. Buggy behavior: FT8 decodes +# with ntol=10 → ±10 Hz window → near-zero decodes. Fixed behavior: ntol +# restores to 1000 → full FT8 decode count. +# 3. Mode-change nfa/nfb restore: prepend Q65 configure with explicit +# narrow nfa/nfb (1400/1600) AND ntol=10, then FT8 configure with no +# explicit nfa/nfb/ntol. Buggy behavior: FT8 inherits the narrow window +# → near-zero decodes. Fixed behavior: both ntol AND nfa/nfb restore. +# +# Usage: +# test/run-pr3-fixtures.sh [build-dir] + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +HARNESS="$REPO_ROOT/test/wav_to_stream_harness.py" + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found or not executable: $JT9" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "Configure-protocol regression (nutc + nfa/nfb + ntol)" +echo " jt9: $JT9" +echo " harness: $HARNESS" + +fail=0 + +# --- Gate 1: nutc thread-through ---------------------------------- +echo "" +echo "Gate 1 — nutc thread-through" +nutc_count=$(python3 "$HARNESS" "$JT9" "$REPO_ROOT/samples/FT8/210703_133430.wav" \ + --mode FT8 --nutc 133430 --quiet 2>/dev/null \ + | grep -c '"time":"133430"' || true) +if [[ "$nutc_count" -ge 14 ]]; then + echo " PASS: nutc=133430 reflected in $nutc_count decode records" +else + echo " FAIL: nutc=133430 only reflected in $nutc_count decode records (expected >= 14)" + fail=1 +fi + +# --- Gate 2: mode-change ntol restore ----------------------------- +echo "" +echo "Gate 2 — mode-change ntol restore" +ntol_count=$(python3 "$HARNESS" "$JT9" "$REPO_ROOT/samples/FT8/210703_133430.wav" \ + --mode FT8 --prepend-mode Q65 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +if [[ "$ntol_count" -ge 14 ]]; then + echo " PASS: Q65→FT8 (no explicit ntol): $ntol_count decodes >= 14" + echo " ntol restored from Q65's hard-10 to FT8's default 1000" +else + echo " FAIL: Q65→FT8 (no explicit ntol): $ntol_count decodes < 14 expected" + echo " ntol likely stayed at Q65's 10, narrowing FT8 window" + fail=1 +fi + +# --- Gate 3: mode-change nfa/nfb restore -------------------------- +echo "" +echo "Gate 3 — mode-change nfa/nfb restore" +nfa_count=$(python3 "$HARNESS" "$JT9" "$REPO_ROOT/samples/FT8/210703_133430.wav" \ + --mode FT8 --prepend-mode Q65 --prepend-with-explicit-narrowing \ + --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +if [[ "$nfa_count" -ge 14 ]]; then + echo " PASS: Q65 (narrow nfa=1400 nfb=1600 ntol=10) → FT8 (no override):" + echo " $nfa_count decodes >= 14" + echo " Both nfa/nfb (session baseline) AND ntol (per-mode default) restored" +else + echo " FAIL: Q65 (narrow) → FT8: $nfa_count decodes < 14 expected" + echo " Either nfa/nfb stayed narrow or ntol stayed at Q65's 10" + fail=1 +fi + +echo "" +if [[ "$fail" -eq 0 ]]; then + echo "All configure-protocol fixtures passed." +else + echo "One or more configure-protocol fixtures regressed." + exit 1 +fi diff --git a/test/run-schema-v1-fixtures.sh b/test/run-schema-v1-fixtures.sh new file mode 100755 index 00000000..072794f4 --- /dev/null +++ b/test/run-schema-v1-fixtures.sh @@ -0,0 +1,698 @@ +#!/usr/bin/env bash +# Streaming schema-v1 regression — Phases 1 + 2 + 4 + 5 + 6 + 7 + 8 + 9 +# (schema versioning, structured error envelope, per-key type validation + atomic +# decline, the Phase 4 operator-identity / frequency-window field group, the +# Phase 5 decoder-tuning field group, the Phase 6 FT8/FT4 specifics cluster, the +# Phase 7 diagnostic / sequencing field group, the Phase 8 string / scaled / +# derived field group, and the Phase 9 bit-packed ndepth / nexp_decode fields). +# +# Twenty-six gates: +# 1. Unknown schema version: a configure with version=2 is declined with +# exactly one {"t":"error","code":"unknown_schema_version","got":2}. +# 2. Explicit version=1 accepted: configure applies normally; FT8 decodes +# >= floor and NO unknown_schema_version is emitted. +# 3. Malformed control frame (missing "t"): emits +# {"t":"error","code":"configure_parse_error",...} AND the stream +# continues (the following valid configure applies, FT8 decodes >= floor). +# 4. (Phase 2) Per-key TYPE error + whole-frame decline: a configure with a +# wrong-typed key (depth as a string) AND a co-present good key (mode=JT65) +# emits exactly one {"code":"configure_type_error","key":"depth", +# "expected":"int","got":"string"} and the good key does NOT apply — the +# FT8 audio still decodes under the FT8 init default (>= floor), proving the +# ENTIRE frame was declined (no partial application). +# 5. (Phase 2) Recovery: a wrong-typed frame is declined with +# configure_type_error, then the following VALID configure applies normally. +# Proven by an APPLIED side-effect of the recovered frame (its nutc=133430 +# appears in the decode "time" fields) — a count floor alone cannot tell a +# recovered frame (21 decodes) from a silently-dropped one (14, init +# default), but the nutc reflection can (dropped -> time 000000). +# 6. (Phase 2) Value-vs-key aliasing guard: a configure whose mycall VALUE is +# the literal token "mygrid" (with no real mygrid key) must be ACCEPTED, not +# falsely declined (type validation must anchor keys to structural +# positions, not match a quoted value). +# 7. (Phase 4) All 9 operator-identity / frequency-window keys present with +# correct types (his_call/his_grid/my_b_call/his_b_call strings, +# my_call_standard/his_call_standard bools, tx_audio_offset_hz/ +# jt65_jt9_split_hz/max_drift_hz ints) are ACCEPTED end-to-end: ZERO +# configure_type_error and FT8 still decodes >= floor (parse + apply run +# without corrupting params). These fields are no-ops on the FT8 fixture +# (tx/Q65/split-only), so this gate proves the path, not a decode effect. +# 8. (Phase 4) A wrong-typed Phase 4 key (my_call_standard as a NUMBER) on a +# frame that also sets mode=JT65 emits exactly one {"code": +# "configure_type_error","key":"my_call_standard","expected":"bool", +# "got":"number"} and the whole frame is declined — mode JT65 does NOT +# apply, so the FT8 audio still decodes under the FT8 init default +# (>= floor). Proves Phase 4 type checks are wired into atomic-decline. +# 9. (Phase 5) All 12 decoder-tuning keys (dt_tolerance_seconds/ +# eme_delay_seconds reals, kin_samples/nzhsym_per_period/npts_c0_array/ +# min_width/min_sync/n_2pass ints, robust_mode/nagain_flag/clear_average +# bools, tx_mode enum) present with correct types are ACCEPTED end-to-end: +# ZERO configure_type_error and FT8 still decodes >= floor (parse + apply +# run without corrupting params). 10 of 12 are inert on FT8 (per-period +# recompute / JT65-Q65-only); this gate proves the PATH, not per-key routing +# (that is the parse-unit driver + Gates 11/12). +# 10. (Phase 5) A wrong-typed Phase 5 key (dt_tolerance_seconds as a STRING) on +# a frame that also sets mode=JT65 emits exactly one {"code": +# "configure_type_error","key":"dt_tolerance_seconds","expected":"real", +# "got":"string"} and the whole frame is declined (mode JT65 not applied, +# FT8 >= floor). Proves Phase 5 type checks are wired into atomic-decline. +# 11. (Phase 5 — APPLY ROUTING) nagain_flag=true changes the FT8 decode +# message-set vs the no-key baseline (empirically 21 -> 16). nagain is +# the ONLY Phase 5 key that reaches the FT8 decoder, so an observable change +# proves nagain_flag was applied to an FT8-affecting param — a partial +# apply-routing guard the inert Phase 4 fields could not have. +# 12. (Phase 5 — APPLY ROUTING) npts_c0_array=60000 changes the JT9 decode +# message-set vs the no-key baseline (empirically 7 -> 6). npts8 is +# the Phase 5 key that reaches the JT9 decoder, so an observable change +# proves npts_c0_array was applied to a JT9-affecting param. +# 13. (Phase 6) All 24 FT8/FT4-specifics keys present with correct types are +# ACCEPTED end-to-end: ZERO configure_type_error and FT8 still decodes +# >= floor. 23 of 24 are inert on the FT8 fixture (read only in the +# multithread-FT8 block / JT65 / superfox-Q65 / WAV path; or AP keys that +# this fixture has no AP-only decodes for); the 24th, +# multithreaded_ft8, is sent TRUE here and only stays >= floor BECAUSE the +# apply ignores the non-false value (Gate 15). So this proves the parse->apply +# PATH; per-key routing is guarded by the parse-unit + apply-routing units. +# 14. (Phase 6) A wrong-typed Phase 6 key (ft8_ap_on as a NUMBER) on a frame that +# also sets mode=JT65 emits exactly one {"code":"configure_type_error", +# "key":"ft8_ap_on","expected":"bool","got":"number"} and the whole frame is +# declined (mode JT65 not applied, FT8 >= floor). Wires Phase 6 type checks +# into atomic-decline. +# 15. (Phase 6 — CORRECTNESS GUARD) multithreaded_ft8=true must STILL decode FT8 +# >= floor. Setting lmultift8=.true. would take the decoder.f90:192 multithread +# branch, which yields 0 FT8 decodes on the stream path; the apply IGNORES +# the non-false value (the receiver ignores a non-false value). A regression +# to a straight pass-through would collapse FT8 to 0 and fail here. +# 16. (Phase 7) All 6 diagnostic / sequencing keys (last_tx_seconds_ago/ +# qso_progress_state/sec_band_changed/delay_units ints, currently_txing/ +# mode_changed bools) present with correct types are ACCEPTED end-to-end: +# ZERO configure_type_error and FT8 still decodes >= floor (parse + apply run +# without corrupting params). All 6 are inert on the FT8 fixture (read only +# in the multithread-FT8 block / AP passes with no AP-only decodes), +# so this gate proves the PATH, not a decode effect; per-key routing is +# guarded by run-phase7-parse-unit.sh + run-apply-routing-unit.sh. +# 17. (Phase 7) A wrong-typed Phase 7 key (last_tx_seconds_ago as a STRING) on a +# frame that also sets mode=JT65 emits exactly one {"code": +# "configure_type_error","key":"last_tx_seconds_ago","expected":"int", +# "got":"string"} and the whole frame is declined (mode JT65 not applied, +# FT8 >= floor). Wires Phase 7 type checks into atomic-decline. +# 18. (Phase 7 — CORRECTNESS GUARD) qso_progress_state OUT OF RANGE must STILL +# decode FT8 >= floor. nQSOProgress reaches the single-pass FT8 decoder +# (decoder.f90:1141), where ft8b.f90:274/299 use it as a raw index into +# nappasses(0:5)/naptypes(0:5,4); an out-of-range value (here 99) faults the +# decoder under -fbounds-check (0 decodes). The apply IGNORES +# an out-of-range value (valid [0,5] only), so FT8 must STILL decode >= floor. +# A regression to a straight pass-through would crash and fail here. +# 19. (Phase 8 — APPLY ROUTING) All 5 string/scaled/derived keys (utc/date/ +# n_trials/candthin_threshold/dt_center_seconds) accepted with 0 type errors, +# AND utc:"13:34:30" -> nutc 133430 is reflected in EVERY decode's "time" +# field (utc is decode-observable; the other 4 are inert — superfox / JT65 / +# multithread-variant only). A real apply-routing guard for utc. +# 20. (Phase 8 — PRECEDENCE) A frame with BOTH nutc:120000 and utc:"13:34:30" +# applies utc (time 133430), not nutc (120000) — apply order is nutc then utc +# (utc wins). Asserts 133430 present AND 120000 absent. +# 21. (Phase 8 — VALUE VALIDATION) n_trials=500 (a number, but not 10^N or 3*10^N) +# emits one configure_type_error key:"n_trials" and declines the whole frame +# (co-present mode=JT65 does not apply; FT8 decodes under its default). +# A non-conforming value would integer-divide into a wrong ntrials. +# 22. (Phase 8 — VALUE VALIDATION) date=2200-01-01 (year >= 2100) emits one +# configure_type_error key:"date" and declines the whole frame. +# The 2000+offset YYMMDD encoding caps at 2099. +# 23. (Phase 9 — ACCEPTED) All 9 unpacked ndepth/nexp_decode keys accepted with 0 +# type errors and FT8 >= floor (depth_level=3/q65_maxiters_level=3 keep ndepth=3 +# so the count is unperturbed; the other 7 are inert on FT8 — Q65/JT65/FST4/JT4 +# or contest-branch only). Proves the parse->pack->apply path runs clean. +# 24. (Phase 9 — APPLY ROUTING) depth_level is decode-observable: the FT8 fixture +# runs at depth=3 -> ndepth=3 (21 decodes); depth_level=1 -> ndepth=1 changes +# the FT8 pass structure (ft8_decode.f90:178/182) -> 14 decodes. Assertion: +# baseline >= floor AND with-key >= floor AND with-key != baseline (both-sides- +# healthy differs guard — a crash/empty with-key also "differs", so guard it). +# A real apply-routing guard for the one FT8-observable Phase-9 key. +# 25. (Phase 9 — CONFLICT DECLINE) A frame carrying BOTH the legacy depth and the +# unpacked depth_level emits one configure_type_error key:"ndepth" +# expected:"depth|unpacked" got:"conflict" and declines the whole frame +# (co-present mode=JT65 does not apply; FT8 decodes under its default). The +# conflicting-encodings rule, via the parse post-pass pack_phase9_. +# 26. (Phase 9 — TYPE DECLINE) A wrong-typed Phase 9 key (depth_level as a string) +# emits one configure_type_error key:"depth_level" expected:"int" got:"string" +# and declines the whole frame (mode=JT65 not applied; FT8 >= floor). Wires +# Phase 9 type checks into atomic-decline. +# +# Usage: +# test/run-schema-v1-fixtures.sh [build-dir] + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +HARNESS="$REPO_ROOT/test/wav_to_stream_harness.py" +WAV="$REPO_ROOT/samples/FT8/210703_133430.wav" +JT9_WAV="$REPO_ROOT/samples/JT9/130418_1742.wav" +FT8_FLOOR=14 +JT9_FLOOR=6 + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found or not executable: $JT9" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "Streaming schema-v1 regression (Phase 1: versioning + structured errors)" +echo " jt9: $JT9" +echo " harness: $HARNESS" + +fail=0 + +# --- Gate 1: unknown schema version declined -------------------------------- +echo "" +echo "Gate 1 — unknown schema version (version=2 declined)" +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --schema-version 2 --quiet 2>/dev/null || true) +uv_count=$(printf '%s\n' "$out" | grep -c '"code":"unknown_schema_version"' || true) +got_count=$(printf '%s\n' "$out" | grep -c '"got":2' || true) +if [[ "$uv_count" -eq 1 && "$got_count" -ge 1 ]]; then + echo " PASS: version=2 declined with exactly one unknown_schema_version (got:2)" +else + echo " FAIL: expected exactly 1 unknown_schema_version with got:2 (saw code=$uv_count got=$got_count)" + fail=1 +fi + +# --- Gate 2: explicit version=1 accepted ------------------------------------ +echo "" +echo "Gate 2 — explicit version=1 accepted (normal decode)" +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --schema-version 1 --quiet 2>/dev/null || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +uv=$(printf '%s\n' "$out" | grep -c '"code":"unknown_schema_version"' || true) +if [[ "$dec" -ge "$FT8_FLOOR" && "$uv" -eq 0 ]]; then + echo " PASS: version=1 accepted; $dec decodes >= $FT8_FLOOR, no version error" +else + echo " FAIL: version=1 — $dec decodes (expected >= $FT8_FLOOR), $uv version errors (expected 0)" + fail=1 +fi + +# --- Gate 3: malformed control frame -> configure_parse_error --------------- +echo "" +echo "Gate 3 — malformed control frame (configure_parse_error + graceful continue)" +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --bad-control --quiet 2>/dev/null || true) +pe=$(printf '%s\n' "$out" | grep -c '"code":"configure_parse_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$pe" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: configure_parse_error emitted ($pe) and stream continued ($dec decodes >= $FT8_FLOOR)" +else + echo " FAIL: parse-error=$pe (expected >= 1), decodes=$dec (expected >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 4: per-key type error + atomic decline (no partial application) --- +echo "" +echo "Gate 4 — configure_type_error + whole-frame decline (no partial application)" +# MAIN configure is wrong-typed (depth as a JSON string) AND sets mode JT65. +# Atomic decline: the entire frame -> mode JT65 must NOT apply, so the FT8 +# audio decodes under the FT8 init default (>= floor). Partial application +# (mode=JT65) would collapse FT8 decodes to ~0. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-type --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"depth","expected":"int","got":"string"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (depth/int/string); whole frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 5: type error then recovery (recovered frame's effect must apply) -- +echo "" +echo "Gate 5 — type error then recovery (recovered frame's nutc must be applied)" +# Declined bad-type preamble, then a VALID main configure carrying nutc=133430. +# Recovery is proven by the APPLIED side-effect (decode time == 133430), not by +# the decode count: a silently-dropped recovered frame would still yield ~14 +# init-default decodes (>= FT8_FLOOR) but with time 000000, which this gate +# rejects. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --bad-type-preamble --nutc 133430 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +rec=$(printf '%s\n' "$out" | grep '"t":"decode"' | grep -c '"time":"133430"' || true) +if [[ "$te" -ge 1 && "$dec" -ge "$FT8_FLOOR" && "$rec" -ge 1 ]]; then + echo " PASS: configure_type_error emitted ($te); recovered frame APPLIED ($rec/$dec decodes carry nutc 133430)" +else + echo " FAIL: type_err=$te (want >=1), decodes=$dec (want >= $FT8_FLOOR), nutc-reflected=$rec (want >=1)" + fail=1 +fi + +# --- Gate 6: value-vs-key aliasing must NOT falsely decline (regression) ----- +echo "" +echo "Gate 6 — value-vs-key aliasing accepted (mycall value == \"mygrid\" token)" +# {"t":"configure","mode":"FT8","depth":3,"mycall":"mygrid"} (no real mygrid key). +# A well-typed string value that equals another key's token must NOT be mistaken +# for that key and falsely declined. Expect ZERO configure_type_error and a +# normal decode. (wire-parity regression guard) +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --mycall mygrid --omit-mygrid --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: aliasing frame accepted (0 type errors); $dec decodes >= $FT8_FLOOR" +else + echo " FAIL: type_err=$te (want 0 — false decline = regression), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 7: Phase 4 — all 9 keys accepted (parse + apply run clean) --------- +echo "" +echo "Gate 7 — Phase 4 fields accepted (his_call/his_grid/my_b_call/his_b_call/" +echo " my_call_standard/his_call_standard/tx_audio_offset_hz/" +echo " jt65_jt9_split_hz/max_drift_hz)" +# All 9 keys present with correct types and benign values. They are no-ops on +# the FT8 fixture (tx/Q65/split-only — an all-9-keys configure yields a +# byte-identical 21-message FT8 decode set), so the assertion is: ZERO type +# errors (every key accepted) AND FT8 still decodes >= floor (apply ran without +# corrupting params). This proves the parse->apply PATH executes cleanly; it +# does NOT prove each value lands in its CORRECT params slot (the fields are +# inert here, so a mis-route would still pass) — that routing is guarded by the +# parse-unit driver (test/run-phase4-parse-unit.sh, parse side) + code review. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --his-call DX1ABC --his-grid FN20 --my-b-call KJ5HST/P --his-b-call DX1ABC/P \ + --my-call-standard --his-call-standard \ + --tx-audio-offset-hz 1234 --jt65-jt9-split-hz 2500 --max-drift-hz 8 \ + --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: all 9 Phase 4 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR (apply clean)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 8: Phase 4 — wrong-typed key -> type error + atomic decline -------- +echo "" +echo "Gate 8 — Phase 4 wrong-typed key (my_call_standard as number) declines frame" +# MAIN configure carries my_call_standard:5 (number, wrong type for a bool) AND +# sets mode=JT65. Atomic decline: the entire frame -> mode JT65 must NOT +# apply, so the FT8 audio decodes under the FT8 init default (>= floor). The +# error must name the Phase 4 key with expected:"bool" got:"number". +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-phase4 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"my_call_standard","expected":"bool","got":"number"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (my_call_standard/bool/number); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 9: Phase 5 — all 12 keys accepted (parse + apply run clean) -------- +echo "" +echo "Gate 9 — Phase 5 fields accepted (dt_tolerance_seconds/eme_delay_seconds/" +echo " kin_samples/nzhsym_per_period/npts_c0_array/min_width/min_sync/" +echo " n_2pass/robust_mode/nagain_flag/tx_mode/clear_average)" +# All 12 keys present with correct types and benign values. 10 are inert on FT8 +# (per-period recompute or JT65/Q65-only); nagain_flag=true does affect FT8 +# (21->16, still >= floor) and npts_c0_array is set to its streaming default +# (74736, a no-op). Assertion: ZERO type errors (every key accepted) AND FT8 still +# decodes >= floor (apply ran without corrupting params). Proves the parse->apply +# PATH; per-key routing is guarded by run-phase5-parse-unit.sh + Gates 11/12. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --dt-tolerance-seconds 2.0 --eme-delay-seconds 0.0 --kin-samples 64800 \ + --nzhsym-per-period 50 --npts-c0-array 74736 --min-width 1 --min-sync 1 \ + --n-2pass 1 --robust-mode --nagain-flag --tx-mode JT9 --clear-average \ + --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: all 12 Phase 5 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR (apply clean)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 10: Phase 5 — wrong-typed key -> type error + atomic decline -------- +echo "" +echo "Gate 10 — Phase 5 wrong-typed key (dt_tolerance_seconds as string) declines frame" +# MAIN configure carries dt_tolerance_seconds:"abc" (string, wrong type for a +# real) AND sets mode=JT65. Atomic decline: the entire frame -> mode JT65 must +# NOT apply, so FT8 decodes under the FT8 init default (>= floor). The error must +# name the Phase 5 key with expected:"real" got:"string". +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-phase5 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"dt_tolerance_seconds","expected":"real","got":"string"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (dt_tolerance_seconds/real/string); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 11: Phase 5 APPLY ROUTING — nagain_flag observably changes FT8 ------ +echo "" +echo "Gate 11 — nagain_flag=true changes the FT8 decode set (apply-routing proof)" +# nagain is the only Phase 5 key reaching the FT8 decoder (ft8_decode.f90 final +# pass). Baseline (no key) vs --nagain-flag must DIFFER, proving apply routed +# nagain_flag to an FT8-affecting param. Baseline computed fresh (robust to +# count drift); guard against a vacuous pass by requiring a non-empty baseline. +base=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --quiet 2>/dev/null \ + | grep '"t":"decode"' | grep -oE '"message":"[^"]*"' | sort || true) +withk=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --nagain-flag --quiet 2>/dev/null \ + | grep '"t":"decode"' | grep -oE '"message":"[^"]*"' | sort || true) +nbase=$(printf '%s\n' "$base" | grep -c '"message"' || true) +nwith=$(printf '%s\n' "$withk" | grep -c '"message"' || true) +# Guard BOTH sides: a crash / shmem-collision that emits nothing yields withk="" +# which "differs" from a healthy baseline and would FALSELY pass. Require the +# with-key run to be a healthy decode (>= 1 msg) too — only then does "differs" +# prove the key reached the decoder (not that one side died). (guards a vacuous pass) +if [[ -n "$base" && "$nbase" -ge "$FT8_FLOOR" && "$nwith" -ge 1 && "$base" != "$withk" ]]; then + echo " PASS: nagain_flag observably changed FT8 decode set (baseline $nbase msgs != with-key $nwith msgs)" +else + echo " FAIL: nagain_flag effect unproven (baseline=$nbase >= $FT8_FLOOR?, with-key=$nwith >= 1?, sets differ=$([[ "$base" != "$withk" ]] && echo yes || echo no))" + fail=1 +fi + +# --- Gate 12: Phase 5 APPLY ROUTING — npts_c0_array observably changes JT9 ---- +echo "" +echo "Gate 12 — npts_c0_array changes the JT9 decode set (apply-routing proof)" +# npts8 reaches the JT9 decoder (decoder.f90:1349). Baseline (no key) vs +# --npts-c0-array 60000 (off the 74736 default) must DIFFER, proving apply routed +# npts_c0_array to a JT9-affecting param. Uses the JT9 fixture; baseline fresh. +if [[ -f "$JT9_WAV" ]]; then + base=$(python3 "$HARNESS" "$JT9" "$JT9_WAV" --mode JT9 --quiet 2>/dev/null \ + | grep '"t":"decode"' | grep -oE '"message":"[^"]*"' | sort || true) + withk=$(python3 "$HARNESS" "$JT9" "$JT9_WAV" --mode JT9 --npts-c0-array 60000 --quiet 2>/dev/null \ + | grep '"t":"decode"' | grep -oE '"message":"[^"]*"' | sort || true) + nbase=$(printf '%s\n' "$base" | grep -c '"message"' || true) + nwith=$(printf '%s\n' "$withk" | grep -c '"message"' || true) + # Same both-sides guard as Gate 11 (crash / shmem-collision -> empty withk + # must NOT pass as a spurious "difference"). + if [[ -n "$base" && "$nbase" -ge "$JT9_FLOOR" && "$nwith" -ge 1 && "$base" != "$withk" ]]; then + echo " PASS: npts_c0_array observably changed JT9 decode set (baseline $nbase msgs != with-key $nwith msgs)" + else + echo " FAIL: npts_c0_array effect unproven (baseline=$nbase >= $JT9_FLOOR?, with-key=$nwith >= 1?, sets differ=$([[ "$base" != "$withk" ]] && echo yes || echo no))" + fail=1 + fi +else + echo " SKIP: JT9 fixture not found ($JT9_WAV)" +fi + +# --- Gate 13: Phase 6 — all 24 keys accepted (parse + apply run clean) -------- +echo "" +echo "Gate 13 — Phase 6 FT8/FT4-specifics keys accepted (24 keys: 19 bools + 5 ints)" +# All 24 keys present with correct types and benign values. 23 are inert on the +# FT8 fixture (multithread-block / JT65 / superfox / WAV-path / AP-no-effect). +# multithreaded_ft8 is sent TRUE and only stays >= floor because +# the apply ignores the non-false value (Gate 15). Assertion: ZERO type errors +# (every key accepted) AND FT8 still decodes >= floor (apply ran without +# corrupting params). Per-key routing is guarded by run-phase6-parse-unit.sh + +# run-apply-routing-unit.sh (no Phase 6 key is decode-observable in a healthy way). +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --multithreaded-ft8 --ft8-cycles 3 --ft8-rxf-sensitivity 3 --ft8-threads 0 \ + --ft8-decoder-start 3 --ft8-low-threshold --ft8-subpass --ft8-ap-on \ + --ap-cq-only --ap-my-call --jt65-ap-on --ap-width-hz 150 \ + --hide-ft8-duplicates --common-ft8b --enable-dxc-search --wide-dxc-search \ + --superfox-mode --even-sequence --hound-mode --multi-instance --skip-tx1 \ + --nagain-filter --stop-hint --hint-mode \ + --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: all 24 Phase 6 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR (apply clean)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 14: Phase 6 — wrong-typed key -> type error + atomic decline -------- +echo "" +echo "Gate 14 — Phase 6 wrong-typed key (ft8_ap_on as number) declines frame" +# MAIN configure carries ft8_ap_on:5 (number, wrong type for a bool) AND sets +# mode=JT65. Atomic decline: the entire frame -> mode JT65 must NOT apply, so the +# FT8 audio decodes under the FT8 init default (>= floor). The error must name the +# Phase 6 key with expected:"bool" got:"number". +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-phase6 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"ft8_ap_on","expected":"bool","got":"number"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (ft8_ap_on/bool/number); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 15: Phase 6 CORRECTNESS GUARD — multithreaded_ft8 ignore-non-false --- +echo "" +echo "Gate 15 — multithreaded_ft8=true still decodes (apply ignores non-false)" +# lmultift8=.true. takes the decoder.f90:192 multithread branch, which yields 0 +# FT8 decodes on the stream path. The apply IGNORES a non-false +# multithreaded_ft8, so FT8 must STILL decode >= floor. A straight +# pass-through regression would collapse FT8 to 0 and fail here. Compare against a +# fresh baseline to keep the assertion meaningful (both runs healthy). +base=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +mt=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --multithreaded-ft8 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +if [[ "$base" -ge "$FT8_FLOOR" && "$mt" -ge "$FT8_FLOOR" ]]; then + echo " PASS: multithreaded_ft8=true ignored; FT8 still decodes ($mt >= $FT8_FLOOR, baseline $base)" +else + echo " FAIL: guard broken — multithreaded_ft8=true collapsed FT8 (with-key=$mt, baseline=$base, floor=$FT8_FLOOR)" + fail=1 +fi + +# --- Gate 16: Phase 7 — all 6 keys accepted (parse + apply run clean) --------- +echo "" +echo "Gate 16 — Phase 7 diagnostic/sequencing keys accepted (6 keys: 4 ints + 2 bools)" +# All 6 keys present with correct types and benign values. All are inert on the +# FT8 fixture (multithread-block-only / AP passes with no AP-only decodes). +# qso_progress_state=5 reaches the single-pass FT8 decoder but +# only steers AP passes (no AP-only decodes on this fixture). Assertion: ZERO +# type errors (every key accepted) AND FT8 still decodes >= floor (apply ran +# without corrupting params). Per-key routing is guarded by +# run-phase7-parse-unit.sh + run-apply-routing-unit.sh. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --last-tx-seconds-ago 3 --currently-txing --mode-changed \ + --qso-progress-state 5 --sec-band-changed 7 --delay-units 6 \ + --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: all 6 Phase 7 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR (apply clean)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 17: Phase 7 — wrong-typed key -> type error + atomic decline -------- +echo "" +echo "Gate 17 — Phase 7 wrong-typed key (last_tx_seconds_ago as string) declines frame" +# MAIN configure carries last_tx_seconds_ago:"soon" (string, wrong type for an +# int) AND sets mode=JT65. Atomic decline: the entire frame -> mode JT65 must +# NOT apply, so the FT8 audio decodes under the FT8 init default (>= floor). The +# error must name the Phase 7 key with expected:"int" got:"string". +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-phase7 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"last_tx_seconds_ago","expected":"int","got":"string"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (last_tx_seconds_ago/int/string); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 18: Phase 7 CORRECTNESS GUARD — qso_progress_state out-of-range ------ +echo "" +echo "Gate 18 — qso_progress_state=99 (out of range) still decodes (apply ignores it)" +# nQSOProgress reaches the single-pass FT8 decoder (decoder.f90:1141), where +# ft8b.f90:274/299 use it as a raw index into nappasses(0:5)/naptypes(0:5,4) on the +# default lft8apon=.true. path. An out-of-range value faults the decoder under +# -fbounds-check (qso_progress_state=99 crashes jt9 --stream). The +# apply IGNORES an out-of-range value (valid [0,5] only), so FT8 must STILL decode +# >= floor. A straight-pass-through regression would crash and collapse FT8 to 0. +# Both-sides-healthy: baseline >= floor AND with-key >= floor. +base=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +oor=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --qso-progress-state 99 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +if [[ "$base" -ge "$FT8_FLOOR" && "$oor" -ge "$FT8_FLOOR" ]]; then + echo " PASS: qso_progress_state=99 ignored; FT8 still decodes ($oor >= $FT8_FLOOR, baseline $base)" +else + echo " FAIL: guard broken — out-of-range qso_progress_state collapsed FT8 (with-key=$oor, baseline=$base, floor=$FT8_FLOOR)" + fail=1 +fi + +# --- Gate 19: Phase 8 — all 5 keys accepted + utc DECODE-OBSERVABLE ----------- +echo "" +echo "Gate 19 — Phase 8 string/scaled/derived keys accepted; utc reflected in time" +# All 5 keys present with benign values. utc:"13:34:30" -> nutc 133430 is +# DECODE-OBSERVABLE in the decode "time" field (unlike Phases 4/6/7's inert +# fields, this is a real apply-routing guard, like the Gate 5 nutc pattern). +# date/n_trials/candthin_threshold/dt_center_seconds are inert on FT8 (superfox / +# JT65 / multithread-variant only), and the n_trials/candthin/ +# dtcenter values equal the init defaults (nranera=6 / ncandthin=100 / ndtcenter=0) +# so they cannot perturb the count. Assertion: ZERO type errors, FT8 >= floor, AND +# every decode carries time 133430 (proves utc parsed -> nutc -> emitted). +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --utc "13:34:30" --date "2021-07-03" --n-trials 1000 \ + --candthin-threshold 1.0 --dt-center-seconds 0.0 \ + --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +rec=$(printf '%s\n' "$out" | grep '"t":"decode"' | grep -c '"time":"133430"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" && "$rec" -ge 1 && "$rec" -eq "$dec" ]]; then + echo " PASS: all 5 Phase 8 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR; utc reflected ($rec/$dec carry time 133430)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR), utc-reflected=$rec (want == $dec, >=1)" + fail=1 +fi + +# --- Gate 20: Phase 8 — utc WINS over the legacy int nutc (precedence) -------- +echo "" +echo "Gate 20 — utc precedence: utc beats a co-present nutc" +# A frame carrying BOTH nutc:120000 (legacy int) AND utc:"13:34:30" (ISO) must +# apply utc (133430), not nutc (120000). apply_configure_fields applies nutc then +# utc, so utc wins. Assertion: time 133430 present AND time 120000 ABSENT. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --nutc 120000 --utc "13:34:30" \ + --quiet 2>/dev/null || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +win=$(printf '%s\n' "$out" | grep '"t":"decode"' | grep -c '"time":"133430"' || true) +lose=$(printf '%s\n' "$out" | grep '"t":"decode"' | grep -c '"time":"120000"' || true) +if [[ "$dec" -ge "$FT8_FLOOR" && "$win" -ge 1 && "$lose" -eq 0 ]]; then + echo " PASS: utc wins ($win/$dec carry time 133430; 0 carry the nutc 120000)" +else + echo " FAIL: decodes=$dec (want >= $FT8_FLOOR), utc-wins=$win (want >=1), nutc-leak=$lose (want 0)" + fail=1 +fi + +# --- Gate 21: Phase 8 — n_trials out of {10^N,3*10^N} -> type error + decline - +echo "" +echo "Gate 21 — n_trials=500 (invalid value) declines the frame" +# n_trials is type-correct (a number) but VALUE-invalid (not 10^N or 3*10^N), so the +# receiver emits configure_type_error (a bad nranera would silently corrupt ntrials, +# decoder.f90:143-145). The frame also sets mode=JT65; atomic decline of the WHOLE +# frame -> JT65 must NOT apply, so the FT8 audio decodes under the FT8 init default. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --n-trials 500 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -F '"key":"n_trials","expected":"int 10^N|3*10^N","got":"number"' | grep -c . || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (n_trials value-invalid); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), n_trials triple=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 22: Phase 8 — date year >= 2100 -> type error + decline ------------- +echo "" +echo "Gate 22 — date=2200-01-01 (year >= 2100) declines the frame" +# The 2000+offset YYMMDD encoding caps at 2099; a year >= 2100 is a +# configure_type_error. The frame also sets mode=JT65, which must NOT apply +# (whole-frame decline) -> FT8 decodes under its init default. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --date "2200-01-01" --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -F '"key":"date","expected":"year<2100","got":"string"' | grep -c . || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (date year>=2100); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), date triple=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 23: Phase 9 — all 9 unpacked keys accepted (parse + pack + apply clean) +echo "" +echo "Gate 23 — Phase 9 bit-packed keys accepted (9 keys: ndepth group + nexp_decode group)" +# All 9 unpacked keys present. depth_level=3 / q65_maxiters_level=3 keep ndepth=3 +# (== the harness default depth=3), so the count is unperturbed; q65_maxiters agrees +# with depth_level's low 2 bits (consistency OK). use_averaging/deep_ap_search/ +# q65_auto_clear_average (ndepth bits 4/5/7) + single_decode/vhf_features/ +# noise_blanker (nexp_decode) are all inert on FT8 (Q65/JT65/FST4/JT4 only). +# contest_type=na_vhf -> ncontest=1 reaches FT8 ft8apset but the +# fixture has no contest/AP-only decodes. Assertion: ZERO type errors AND FT8 still +# decodes >= floor (parse->pack->apply ran clean). Per-key bit-packing is guarded by +# run-phase9-parse-unit.sh; per-key routing by run-apply-routing-unit.sh. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 \ + --depth-level 3 --q65-maxiters-level 3 --use-averaging --deep-ap-search \ + --q65-auto-clear-average --contest-type na_vhf --single-decode \ + --vhf-features --noise-blanker-level 2 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 0 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: all 9 Phase 9 keys accepted (0 type errors); $dec decodes >= $FT8_FLOOR (pack+apply clean)" +else + echo " FAIL: type_err=$te (want 0), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 24: Phase 9 APPLY ROUTING — depth_level is decode-observable --------- +echo "" +echo "Gate 24 — depth_level=1 changes the FT8 decode set (real apply-routing guard)" +# The FT8 fixture default runs at depth=3 -> ndepth=3 (21 decodes). Sending +# depth_level=1 (which auto-drops the legacy depth key) -> ndepth=1 takes the FT8 +# fast-decode path (ft8_decode.f90:178 npass=2, :182 syncmin) -> FEWER decodes +# (14). A mis-route to an inert param would leave the count at 21. Assertion: +# baseline healthy (>= floor) AND with-key non-empty (>= 1, NOT a crash/shmem-0 — +# the both-sides-healthy guard: a 0 with-key also "differs" from a healthy +# baseline) AND with-key STRICTLY FEWER than baseline (the fast path +# decodes less). NB: the with-key bound is >= 1, NOT >= FT8_FLOOR, so the gate is +# robust to a future decode-core nudge in the fast-path count (which happens to be +# 14 == FT8_FLOOR today; coupling them would false-fail on a benign drift to 13). +# "< baseline" + ">= 1" still catches a mis-route (== baseline) +# and a crash (0). +base=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +dl=$(python3 "$HARNESS" "$JT9" "$WAV" --mode FT8 --depth-level 1 --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) +if [[ "$base" -ge "$FT8_FLOOR" && "$dl" -ge 1 && "$dl" -lt "$base" ]]; then + echo " PASS: depth_level=1 routed to ndepth (fewer decodes: $dl < baseline $base, both healthy)" +else + echo " FAIL: baseline=$base (want >= $FT8_FLOOR), depth_level=1=$dl (want >= 1 AND < $base)" + fail=1 +fi + +# --- Gate 25: Phase 9 — depth + depth_level conflict -> type error + decline --- +echo "" +echo "Gate 25 — depth + depth_level co-present (conflict) declines the frame" +# A frame carrying BOTH the legacy depth (full int) and the unpacked depth_level is +# a conflicting-encodings error (the two are mutually exclusive). The +# parse post-pass pack_phase9_ emits configure_type_error key:"ndepth" +# expected:"depth|unpacked" got:"conflict". The frame also sets mode=JT65, which must +# NOT apply (whole-frame decline) -> FT8 decodes under its init default. +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --phase9-conflict --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -F '"key":"ndepth","expected":"depth|unpacked","got":"conflict"' | grep -c . || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (ndepth conflict); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), ndepth conflict triple=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +# --- Gate 26: Phase 9 — wrong-typed key -> type error + atomic decline --------- +echo "" +echo "Gate 26 — Phase 9 wrong-typed key (depth_level as string) declines frame" +# MAIN configure carries depth_level:"deep" (string, wrong type for an int) AND sets +# mode=JT65. Atomic decline: the entire frame -> mode JT65 must NOT apply, so the +# FT8 audio decodes under the FT8 init default (>= floor). The error must name the +# Phase 9 key with expected:"int" got:"string". +out=$(python3 "$HARNESS" "$JT9" "$WAV" --mode JT65 --bad-phase9 --quiet 2>/dev/null || true) +te=$(printf '%s\n' "$out" | grep -c '"code":"configure_type_error"' || true) +triple=$(printf '%s\n' "$out" | grep -c '"key":"depth_level","expected":"int","got":"string"' || true) +dec=$(printf '%s\n' "$out" | grep -c '"t":"decode"' || true) +if [[ "$te" -eq 1 && "$triple" -ge 1 && "$dec" -ge "$FT8_FLOOR" ]]; then + echo " PASS: one configure_type_error (depth_level/int/string); frame declined, mode JT65 not applied ($dec FT8 decodes >= $FT8_FLOOR)" +else + echo " FAIL: type_err=$te (want 1), key/expected/got match=$triple (want >=1), decodes=$dec (want >= $FT8_FLOOR)" + fail=1 +fi + +echo "" +if [[ "$fail" -eq 0 ]]; then + echo "All schema-v1 fixtures passed." +else + echo "Some schema-v1 fixtures FAILED." + exit 1 +fi diff --git a/test/run-stream-wav-parity.sh b/test/run-stream-wav-parity.sh new file mode 100755 index 00000000..67c66e43 --- /dev/null +++ b/test/run-stream-wav-parity.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Stream-vs-WAV decode-parity harness. +# +# Asserts CONTAINMENT: every signal in a committed WAV-mode golden +# (test/fixtures/*.expected.txt) is also decoded by `jt9 --stream`. Streaming +# legitimately finds MORE (the early nzhsym passes pick up low-SNR signals; see +# run-streaming-fixtures.sh) so the relation is "WAV goldens are a subset of +# stream decodes", NOT equality. This is the rigorous regression guard the +# decode-affecting later phases (8, 9) depend on. +# +# Identity is the decoded MESSAGE text. Empirically snr/dt/freq drift between +# the WAV and stream decode paths for the SAME signal (snr ±2 dB, dt ±0.05 s, +# freq ±3 Hz on these fixtures — the streaming early passes compute slightly +# different fine estimates), so the harness shows them as diagnostics but the +# pass/fail hinges only on message-set containment. +# +# Scope: FT8 and JT9 ONLY (stated, not silently capped). FST4W has no +# known-good decoder fixture and the EME/JT65 I/Q paths are +# pass-on-absence, so neither can anchor a parity golden. +# +# A NEGATIVE CONTROL gate proves the harness can fail: a golden carrying one +# synthetic impossible signal MUST be reported as a parity failure. Without it, +# a green run cannot distinguish "containment held" from "harness never fails". +# +# Usage: +# test/run-stream-wav-parity.sh [build-dir] +# +# Where build-dir defaults to ./build and must contain a built jt9 binary. + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +HARNESS="$REPO_ROOT/test/wav_to_stream_harness.py" + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found or not executable: $JT9" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "Stream-vs-WAV decode-parity (containment; FT8/JT9 only)" +echo " jt9: $JT9" +echo " harness: $HARNESS" + +fail=0 + +# Format: <wav-path> <jt9-mode-name> <golden-path> +fixtures=( + "samples/FT8/210703_133430.wav FT8 test/fixtures/ft8_210703_133430.expected.txt" + "samples/JT9/130418_1742.wav JT9 test/fixtures/jt9_130418_1742.expected.txt" +) + +for entry in "${fixtures[@]}"; do + read -r wav mode golden <<< "$entry" + wav_path="$REPO_ROOT/$wav" + golden_path="$REPO_ROOT/$golden" + echo "" + if [[ ! -f "$wav_path" ]]; then + echo " SKIP: $wav (sample not present)" + continue + fi + if [[ ! -f "$golden_path" ]]; then + echo " SKIP: $golden (golden not present)" + continue + fi + if python3 "$HARNESS" "$JT9" "$wav_path" --mode "$mode" --parity "$golden_path"; then + echo " PASS: $mode parity (WAV goldens are a subset of stream decodes)" + else + echo " FAIL: $mode parity — a WAV-confirmed signal was dropped" + fail=1 + fi +done + +# --- Negative control: prove the harness can FAIL --------------------------- +echo "" +echo "Negative control — a golden with one impossible signal MUST fail parity" +ng_wav="$REPO_ROOT/samples/FT8/210703_133430.wav" +ng_src="$REPO_ROOT/test/fixtures/ft8_210703_133430.expected.txt" +if [[ -f "$ng_wav" && -f "$ng_src" ]]; then + tmp="$(mktemp)" + trap 'rm -f "$tmp"' EXIT + cat "$ng_src" > "$tmp" + # A syntactically valid WSJT-X decode line whose message this audio can + # never produce. The parser must report it as a dropped (MISSING) signal. + printf '133430 -5 0.0 1500 ~ ZZ9ZZZ NOTREAL XX99\n' >> "$tmp" + if python3 "$HARNESS" "$JT9" "$ng_wav" --mode FT8 --parity "$tmp" >/dev/null 2>&1; then + echo " FAIL: harness reported parity OK on a golden with an impossible signal (cannot discriminate)" + fail=1 + else + echo " PASS: harness correctly flagged the impossible signal as dropped" + fi + rm -f "$tmp" + trap - EXIT + + # An empty/truncated golden must NOT pass vacuously (0 signals ⊆ anything is + # trivially true). The harness must fail it loudly so a corrupt baseline is + # caught rather than masking future regressions. + echo "" + echo "Negative control 2 — an EMPTY golden MUST fail parity (no vacuous pass)" + empty="$(mktemp)" + trap 'rm -f "$empty"' EXIT + : > "$empty" # zero-byte golden + if python3 "$HARNESS" "$JT9" "$ng_wav" --mode FT8 --parity "$empty" >/dev/null 2>&1; then + echo " FAIL: harness reported parity OK on an empty golden (vacuous pass)" + fail=1 + else + echo " PASS: harness correctly rejected the empty golden" + fi + rm -f "$empty" + trap - EXIT +else + echo " SKIP: FT8 sample/golden not present for the negative control" +fi + +echo "" +if [[ "$fail" -eq 0 ]]; then + echo "All stream-vs-WAV parity checks passed." +else + echo "One or more stream-vs-WAV parity checks FAILED." + exit 1 +fi diff --git a/test/run-streaming-fixtures-no-configure.sh b/test/run-streaming-fixtures-no-configure.sh new file mode 100755 index 00000000..318d8131 --- /dev/null +++ b/test/run-streaming-fixtures-no-configure.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Streaming-fixture regression harness — no-configure-frame variant. +# +# Exercises the CLI-arg threading path through init_default_params. +# Sends WSJT header + audio frames + halt to jt9 --stream +# WITHOUT a configure frame; jt9 reads its decode parameters from the +# CLI flags supplied to the binary directly. +# +# Earlier, streaming_io.f90's bulk init silently overrode CLI-supplied +# values like -F (ntol), -f (rxfreq), -L (flow), -H (fhigh), -d (ndepth) +# with FT8-baseline hardcoded defaults. A jt9 invocation without a +# configure frame produced 0 decodes for any non-default CLI args — the +# CLI args were lost. This harness locks in the fix. +# +# Usage: +# test/run-streaming-fixtures-no-configure.sh [build-dir] + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +HARNESS="$REPO_ROOT/test/wav_to_stream_no_configure.py" + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found or not executable: $JT9" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "Streaming-fixture regression (no-configure-frame variant)" +echo " jt9: $JT9" +echo " harness: $HARNESS" + +fail=0 + +# Format: <wav-path> <mode-flag> <minimum-decode-count> +# CLI flags supplied: -F 1000 (ntol), -f 1500 (rxfreq), -L 200 (flow), +# -H 3000 (fhigh), -d 1 (ndepth) — values that would otherwise come from +# a configure frame. Targets the same FT8/JT9 fixtures used by the +# configure-frame harness so the two suites' decode-count expectations +# can be compared directly. +fixtures=( + "samples/FT8/210703_133430.wav -8 14" + "samples/JT9/130418_1742.wav -9 6" +) + +for entry in "${fixtures[@]}"; do + read -r wav mode_flag min_count <<< "$entry" + wav_path="$REPO_ROOT/$wav" + if [[ ! -f "$wav_path" ]]; then + echo " SKIP: $wav (sample not present)" + continue + fi + + count=$(python3 "$HARNESS" "$JT9" "$wav_path" \ + --mode-flag "$mode_flag" \ + --ntol 1000 --nrxfreq 1500 --flow 200 --fhigh 3000 --ndepth 1 \ + --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) + if [[ "$count" -ge "$min_count" ]]; then + echo " PASS: $wav ($mode_flag, $count decodes >= $min_count)" + else + echo " FAIL: $wav ($mode_flag, $count decodes < $min_count expected)" + fail=1 + fi +done + +if [[ "$fail" -eq 0 ]]; then + echo "All no-configure streaming fixtures passed." +else + echo "One or more no-configure streaming fixtures regressed." + exit 1 +fi diff --git a/test/run-streaming-fixtures.sh b/test/run-streaming-fixtures.sh new file mode 100755 index 00000000..bd60987f --- /dev/null +++ b/test/run-streaming-fixtures.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Streaming-fixture regression harness (cross-mode validation). +# +# Pipes the same WAV fixtures used by run-golden-fixtures.sh through +# `jt9 --stream` via test/wav_to_stream_harness.py and asserts that the +# streaming-mode decode count meets or exceeds the WAV-mode ground truth. +# +# Streaming may produce MORE decodes than WAV mode (the early-pass +# nzhsym=41/47 calls can find low-SNR signals; not a regression). What we +# guard against is the "zero decodes" regression: any combination of +# params/protocol bugs that silences the FT8 decoder under --stream. +# +# Usage: +# test/run-streaming-fixtures.sh [build-dir] +# +# Where build-dir defaults to ./build and must contain a built jt9 binary. + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +JT9="$REPO_ROOT/$BUILD_DIR/jt9" +HARNESS="$REPO_ROOT/test/wav_to_stream_harness.py" + +if [[ ! -x "$JT9" ]]; then + echo "ERROR: jt9 binary not found or not executable: $JT9" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "Streaming-fixture regression" +echo " jt9: $JT9" +echo " harness: $HARNESS" + +fail=0 + +# Format: <wav-path> <jt9-mode-name> <minimum-decode-count> +# +# Floors are set conservatively below WAV-mode ground truth to absorb +# small streaming/WAV variance (per file header). FT8 fixture: 14 +# (streaming finds 21+; WAV finds 14). JT9: 6 (matches WAV). FT4: +# 14 (WAV=16, streaming=16). MSK144: +# 1 (WAV=1, streaming=1; the sample contains exactly one ping. The +# 181211_120800 sibling is a fallback if 181211_120500 ever produces 0). +# FST4: 2 (WAV=2, streaming=2; the 60s sample at +# 210115_0058 contains 'CQ K9KFR EN71' + 'CQ N5TM EL29'). +# JT65 deliberately omitted — the JT65B capture +# samples/JT65/JT65B/000000_0001.wav decodes a -25 dB signal at JT65's +# ~-24 dB sensitivity floor. It is one of the upstream cad95e65c "test +# files for JT65 averaging, AP, and DS decodes" -- a weak-signal +# sequence. A probe of all 8 JT65B samples through this harness +# found ONLY 0001 decodes at all (others 0/6), and 0001 only on a +# quiescent box; the one non-averaging sample (DL7UAE) is 8-bit/11025 Hz +# which --stream hard-rejects (needs 16-bit/12 kHz), so no margin-clearing +# JT65 sample is available to swap in. On the single-pass streaming +# path (no WAV multi-pass threshold relaxation, jt65_decode.f90:122-145) +# the candidate sits on KVASD's dual accept gate (extract.f90:176), so a +# floor=1 HARD assertion is nondeterministic: ~50/50 quiescent, 0 under +# concurrent build/workflow churn. It turned CI RED on its first +# Linux-CI exposure: ubuntu-22.04 sampled 0, macos-14 sampled 1. +# Upstream itself gates NO JT65 decode (its tests/ are C++/Qt unit tests; +# the JT65B WAVs ship for manual GUI use only). nmode=65 dispatch/parse/ +# apply coverage is retained via run-schema-v1-fixtures.sh (--mode JT65), +# the Phase-5 parse-unit, and the apply-routing unit; map65d JT65 wiring +# via run-eme-jt65-fixtures.sh. Same posture as FST4W below; replace-with- +# margin-sample and soft-gate were the rejected alternatives. +# Q65: 1 floor (streaming=4). 60s Q65-A sample; EME-sourced but +# decoded through the TERRESTRIAL jt9 --stream nmode=66 path (NOT map65d) — +# exactly the path an external streaming producer exercises. Closes the +# residual per-mode gap (FT4/MSK144/FST4 were closed earlier). +# +# FST4W deliberately omitted — the only available FST4W sample +# (samples/FST4+FST4W/201230_0300.wav, "FST4W-1800" per commit 97dce3aa7) +# does not decode under jt9 -W with any standard period (120/300/900/ +# 1800s) on this build. Streaming-dispatch wiring still verified via +# the FST4W mode_string_to_int mapping (lib/streaming_control.f90:209) +# and TRperiod auto-default (streaming_io.f90:370 case default 60s); +# what's missing is a known-good FST4W decoder fixture. +fixtures=( + "samples/FT8/210703_133430.wav FT8 14" + "samples/JT9/130418_1742.wav JT9 6" + "samples/FT4/000000_000002.wav FT4 14" + "samples/MSK144/181211_120500.wav MSK144 1" + "samples/FST4+FST4W/210115_0058.wav FST4 2" + "samples/Q65/60A_EME_6m/210106_1621.wav Q65 1" +) + +for entry in "${fixtures[@]}"; do + read -r wav mode min_count <<< "$entry" + wav_path="$REPO_ROOT/$wav" + if [[ ! -f "$wav_path" ]]; then + echo " SKIP: $wav (sample not present)" + continue + fi + + count=$(python3 "$HARNESS" "$JT9" "$wav_path" --mode "$mode" --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) + if [[ "$count" -ge "$min_count" ]]; then + echo " PASS: $wav ($mode, $count decodes >= $min_count)" + else + echo " FAIL: $wav ($mode, $count decodes < $min_count expected)" + fail=1 + fi +done + +if [[ "$fail" -eq 0 ]]; then + echo "All streaming fixtures passed." +else + echo "One or more streaming fixtures regressed." + exit 1 +fi diff --git a/test/run-wsjtx-startup-macos.sh b/test/run-wsjtx-startup-macos.sh new file mode 100755 index 00000000..3263efcb --- /dev/null +++ b/test/run-wsjtx-startup-macos.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +set -u + +readonly DEFAULT_TIMEOUT_SECS=15 +readonly SAMPLE_DURATION_SECS=3 +readonly SAMPLE_INTERVAL_MSECS=10 + +diagnostics_dir="${1:?usage: run-wsjtx-startup-macos.sh <diagnostics-dir> <executable> [args...]}" +shift +executable="${1:?usage: run-wsjtx-startup-macos.sh <diagnostics-dir> <executable> [args...]}" +timeout_secs="${WSJTX_STARTUP_SMOKE_TIMEOUT_SECS:-$DEFAULT_TIMEOUT_SECS}" + +case "$timeout_secs" in + ''|*[!0-9]*) + echo "startup smoke: timeout must be a positive integer: $timeout_secs" + exit 2 + ;; +esac +if [ "$timeout_secs" -eq 0 ]; then + echo "startup smoke: timeout must be greater than zero" + exit 2 +fi +if [ ! -x "$executable" ]; then + echo "startup smoke: executable not found or not executable: $executable" + exit 2 +fi + +if ! mkdir -p "$diagnostics_dir"; then + echo "startup smoke: unable to create diagnostics directory: $diagnostics_dir" + exit 2 +fi +output_log="$diagnostics_dir/startup-smoke.log" +summary="$diagnostics_dir/diagnostic-summary.txt" +sample_log="$diagnostics_dir/hang-sample.txt" +sample_command_log="$diagnostics_dir/sample-command.log" +launch_marker="$diagnostics_dir/launch-start.marker" +: >"$output_log" +: >"$launch_marker" + +copy_new_crash_reports () +{ + if [ -z "${HOME:-}" ]; then + return + fi + report_dir="$HOME/Library/Logs/DiagnosticReports" + if [ ! -d "$report_dir" ]; then + return + fi + for report in \ + "$report_dir"/wsjtx*.ips \ + "$report_dir"/wsjtx*.crash \ + "$report_dir"/WSJT-X*.ips \ + "$report_dir"/WSJT-X*.crash + do + if [ -e "$report" ] && [ "$report" -nt "$launch_marker" ]; then + cp "$report" "$diagnostics_dir/" + fi + done +} + +print_failure_diagnostics () +{ + echo "----- diagnostic summary -----" + cat "$summary" 2>/dev/null || true + echo "----- startup smoke output -----" + cat "$output_log" 2>/dev/null || true + if [ -s "$sample_command_log" ]; then + echo "----- sample command output -----" + cat "$sample_command_log" + fi +} + +echo "startup smoke: $executable ${*:2}" +"$@" >"$output_log" 2>&1 & +test_pid=$! +start_time=$SECONDS +timed_out=false + +while kill -0 "$test_pid" 2>/dev/null; do + if [ $((SECONDS - start_time)) -ge "$timeout_secs" ]; then + timed_out=true + break + fi + sleep 0.25 +done + +if [ "$timed_out" = true ]; then + { + echo "result=timeout" + echo "pid=$test_pid" + echo "timeout_seconds=$timeout_secs" + echo "executable=$executable" + } >"$summary" + /usr/bin/sample "$test_pid" "$SAMPLE_DURATION_SECS" "$SAMPLE_INTERVAL_MSECS" \ + -mayDie -file "$sample_log" >"$sample_command_log" 2>&1 || true + kill -TERM "$test_pid" 2>/dev/null || true + terminate_attempts=0 + while [ "$terminate_attempts" -lt 8 ]; do + if ! kill -0 "$test_pid" 2>/dev/null; then + break + fi + sleep 0.25 + terminate_attempts=$((terminate_attempts + 1)) + done + if kill -0 "$test_pid" 2>/dev/null; then + kill -KILL "$test_pid" 2>/dev/null || true + fi + wait "$test_pid" 2>/dev/null || true + copy_new_crash_reports + print_failure_diagnostics + exit 124 +fi + +wait "$test_pid" +status=$? +if [ "$status" -ne 0 ]; then + sleep 2 + copy_new_crash_reports + { + echo "result=exit" + echo "pid=$test_pid" + echo "exit_status=$status" + echo "executable=$executable" + } >"$summary" + print_failure_diagnostics + exit "$status" +fi + +cat "$output_log" +rm -f "$output_log" "$launch_marker" +exit 0 diff --git a/test/run-wsprd-streaming-fixtures.sh b/test/run-wsprd-streaming-fixtures.sh new file mode 100755 index 00000000..6b96d3c3 --- /dev/null +++ b/test/run-wsprd-streaming-fixtures.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# wsprd streaming-fixture regression harness. +# +# Pipes the same WSPR fixture used by file-mode through `wsprd -0` +# (streaming mode) via test/wav_to_wsprd_stream_harness.py and asserts +# that the streaming-mode decode count meets or exceeds the file-mode +# ground truth. +# +# Usage: +# test/run-wsprd-streaming-fixtures.sh [build-dir] + +set -euo pipefail + +BUILD_DIR="${1:-build}" +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +WSPRD="$REPO_ROOT/$BUILD_DIR/wsprd" +HARNESS="$REPO_ROOT/test/wav_to_wsprd_stream_harness.py" + +if [[ ! -x "$WSPRD" ]]; then + echo "ERROR: wsprd binary not found or not executable: $WSPRD" >&2 + exit 2 +fi +if [[ ! -f "$HARNESS" ]]; then + echo "ERROR: harness not found: $HARNESS" >&2 + exit 2 +fi + +echo "wsprd streaming-fixture regression" +echo " wsprd: $WSPRD" +echo " harness: $HARNESS" + +fail=0 + +# Format: <wav-path> <dialfreq-MHz> <wspr-type> <minimum-decode-count> +fixtures=( + "samples/WSPR/150426_0918.wav 14.0956 2 9" +) + +for entry in "${fixtures[@]}"; do + read -r wav dialfreq wspr_type min_count <<< "$entry" + wav_path="$REPO_ROOT/$wav" + if [[ ! -f "$wav_path" ]]; then + echo " SKIP: $wav (sample not present)" + continue + fi + + count=$(python3 "$HARNESS" "$WSPRD" "$wav_path" \ + --dialfreq "$dialfreq" --wspr-type "$wspr_type" \ + --quiet 2>/dev/null \ + | grep -c '"t":"decode"' || true) + if [[ "$count" -ge "$min_count" ]]; then + echo " PASS: $wav (WSPR-$wspr_type, $count decodes >= $min_count)" + else + echo " FAIL: $wav (WSPR-$wspr_type, $count decodes < $min_count expected)" + fail=1 + fi +done + +if [[ "$fail" -eq 0 ]]; then + echo "All wsprd streaming fixtures passed." +else + echo "One or more wsprd streaming fixtures regressed." + exit 1 +fi diff --git a/test/wav_to_stream_harness.py b/test/wav_to_stream_harness.py new file mode 100755 index 00000000..99cc0f28 --- /dev/null +++ b/test/wav_to_stream_harness.py @@ -0,0 +1,966 @@ +#!/usr/bin/env python3 +""" +wav-to-stream validation harness. + +Pipes a 12 kHz mono int16 WAV file through `jt9 --stream` using the +streaming protocol, then prints the resulting NDJSON decodes. +Used to verify that streaming-mode decode results match the WAV-mode +ground truth (cross-mode validation). + +Usage: + test/wav_to_stream_harness.py <jt9-binary> <wav-file> [--mode FT8] + +Exit code is jt9's exit code. NDJSON lines are written to stdout, one +per `{"v":1,"t":"...",...}` event from jt9. Diagnostic stderr from jt9 +is merged into stdout (consumers MUST drain stderr; this harness uses +redirect_error_stream=true). +""" +from __future__ import annotations + +import argparse +import json +import struct +import subprocess +import sys +import wave +from pathlib import Path + +# Frame-type bytes (matching streaming_io.f90). +FRAME_AUDIO = 0x01 +FRAME_CONTROL = 0x02 + +# Audio chunk size in 12 kHz samples per frame. ~1 s per frame keeps the +# protocol's audio-doesn't-span-period gotcha trivially satisfied. +CHUNK_SAMPLES = 12000 + + +def wsjt_session_header(rate_khz: int = 12) -> bytes: + """8-byte WSJT session header: magic + fmt + channels + rate_kHz LE u16.""" + return b"WSJT" + bytes([0, 1]) + struct.pack("<H", rate_khz) + + +def frame(type_byte: int, body: bytes) -> bytes: + """[type:1][len:4 LE][body:len]""" + return bytes([type_byte]) + struct.pack("<I", len(body)) + body + + +def configure_json( + mode: str = "FT8", + depth: int = 3, + ntol: int | None = 1000, + nfa: int | None = 200, + nfb: int | None = 3000, + mycall: str = "KJ5HST", + mygrid: str = "EM18", + nutc: int | None = None, + version: int | None = None, + bad_depth: bool = False, + omit_mygrid: bool = False, + # Phase 4: operator identity + frequency-window keys. None => + # omit the key from the frame (so they default to no-op on the fixtures). + his_call: str | None = None, + his_grid: str | None = None, + my_b_call: str | None = None, + his_b_call: str | None = None, + my_call_standard: bool | None = None, + his_call_standard: bool | None = None, + tx_audio_offset_hz: int | None = None, + jt65_jt9_split_hz: int | None = None, + max_drift_hz: int | None = None, + bad_phase4: bool = False, + # Phase 5: decoder-tuning basic fields. None => omit (no-op). + dt_tolerance_seconds: float | None = None, + eme_delay_seconds: float | None = None, + kin_samples: int | None = None, + nzhsym_per_period: int | None = None, + npts_c0_array: int | None = None, + min_width: int | None = None, + min_sync: int | None = None, + n_2pass: int | None = None, + robust_mode: bool | None = None, + nagain_flag: bool | None = None, + tx_mode: str | None = None, + clear_average: bool | None = None, + bad_phase5: bool = False, + # Phase 6: FT8/FT4 specifics cluster. None => omit (no-op). + multithreaded_ft8: bool | None = None, + ft8_cycles: int | None = None, + ft8_rxf_sensitivity: int | None = None, + ft8_threads: int | None = None, + ft8_decoder_start: int | None = None, + ft8_low_threshold: bool | None = None, + ft8_subpass: bool | None = None, + ft8_ap_on: bool | None = None, + ap_cq_only: bool | None = None, + ap_my_call: bool | None = None, + jt65_ap_on: bool | None = None, + ap_width_hz: int | None = None, + hide_ft8_duplicates: bool | None = None, + common_ft8b: bool | None = None, + enable_dxc_search: bool | None = None, + wide_dxc_search: bool | None = None, + superfox_mode: bool | None = None, + even_sequence: bool | None = None, + hound_mode: bool | None = None, + multi_instance: bool | None = None, + skip_tx1: bool | None = None, + nagain_filter: bool | None = None, + stop_hint: bool | None = None, + hint_mode: bool | None = None, + bad_phase6: bool = False, + # Phase 7: diagnostic / sequencing fields. None => omit (no-op). + last_tx_seconds_ago: int | None = None, + currently_txing: bool | None = None, + mode_changed: bool | None = None, + qso_progress_state: int | None = None, + sec_band_changed: int | None = None, + delay_units: int | None = None, + bad_phase7: bool = False, + # Phase 8: string & scaled / derived fields. None => omit. + utc: str | None = None, + date: str | None = None, + n_trials: int | None = None, + candthin_threshold: float | None = None, + dt_center_seconds: float | None = None, + # Phase 9: bit-packed fields. None => omit. + # Sending ANY ndepth-unpacked key auto-drops the legacy `depth` key + # (precedence — a frame carrying both is a configure_type_error conflict). + depth_level: int | None = None, + q65_maxiters_level: int | None = None, + use_averaging: bool | None = None, + deep_ap_search: bool | None = None, + q65_auto_clear_average: bool | None = None, + contest_type: str | None = None, + single_decode: bool | None = None, + vhf_features: bool | None = None, + noise_blanker_level: int | None = None, + bad_phase9: bool = False, + phase9_conflict: bool = False, +) -> bytes: + payload: dict = { + "t": "configure", + "mode": mode, + "depth": depth, + "mycall": mycall, + "mygrid": mygrid, + } + if omit_mygrid: + # Drop mygrid so a mycall value equal to the literal token "mygrid" has + # no real mygrid key to anchor to — exercises the value-vs-key aliasing + # regression guard. + payload.pop("mygrid", None) + if bad_depth: + # Wrong JSON type for an int key: depth as a string. Exercises the + # configure_type_error / atomic-decline path. + payload["depth"] = "abc" + if version is not None: + payload["version"] = version + if ntol is not None: + payload["ntol"] = ntol + if nfa is not None: + payload["nfa"] = nfa + if nfb is not None: + payload["nfb"] = nfb + if nutc is not None: + payload["nutc"] = nutc + # Phase 4 keys (omitted when None so they don't perturb the default frame). + if his_call is not None: + payload["his_call"] = his_call + if his_grid is not None: + payload["his_grid"] = his_grid + if my_b_call is not None: + payload["my_b_call"] = my_b_call + if his_b_call is not None: + payload["his_b_call"] = his_b_call + if my_call_standard is not None: + payload["my_call_standard"] = my_call_standard + if his_call_standard is not None: + payload["his_call_standard"] = his_call_standard + if tx_audio_offset_hz is not None: + payload["tx_audio_offset_hz"] = tx_audio_offset_hz + if jt65_jt9_split_hz is not None: + payload["jt65_jt9_split_hz"] = jt65_jt9_split_hz + if max_drift_hz is not None: + payload["max_drift_hz"] = max_drift_hz + if bad_phase4: + # Wrong JSON type for a Phase 4 BOOLEAN key: my_call_standard as a + # number. Exercises the configure_type_error / atomic-decline path for + # a Phase 4 key (mirrors --bad-type's depth-as-string for an int key). + # Placed last so it overrides any my_call_standard set above. + payload["my_call_standard"] = 5 + # Phase 5 keys (omitted when None so they don't perturb the default frame). + if dt_tolerance_seconds is not None: + payload["dt_tolerance_seconds"] = dt_tolerance_seconds + if eme_delay_seconds is not None: + payload["eme_delay_seconds"] = eme_delay_seconds + if kin_samples is not None: + payload["kin_samples"] = kin_samples + if nzhsym_per_period is not None: + payload["nzhsym_per_period"] = nzhsym_per_period + if npts_c0_array is not None: + payload["npts_c0_array"] = npts_c0_array + if min_width is not None: + payload["min_width"] = min_width + if min_sync is not None: + payload["min_sync"] = min_sync + if n_2pass is not None: + payload["n_2pass"] = n_2pass + if robust_mode is not None: + payload["robust_mode"] = robust_mode + if nagain_flag is not None: + payload["nagain_flag"] = nagain_flag + if tx_mode is not None: + payload["tx_mode"] = tx_mode + if clear_average is not None: + payload["clear_average"] = clear_average + if bad_phase5: + # Wrong JSON type for a Phase 5 REAL key: dt_tolerance_seconds as a + # string. Exercises the configure_type_error / atomic-decline path for a + # Phase 5 key. Placed last so it overrides any value set above. + payload["dt_tolerance_seconds"] = "abc" + # Phase 6 keys (omitted when None so they don't perturb the default frame). + if multithreaded_ft8 is not None: + payload["multithreaded_ft8"] = multithreaded_ft8 + if ft8_cycles is not None: + payload["ft8_cycles"] = ft8_cycles + if ft8_rxf_sensitivity is not None: + payload["ft8_rxf_sensitivity"] = ft8_rxf_sensitivity + if ft8_threads is not None: + payload["ft8_threads"] = ft8_threads + if ft8_decoder_start is not None: + payload["ft8_decoder_start"] = ft8_decoder_start + if ft8_low_threshold is not None: + payload["ft8_low_threshold"] = ft8_low_threshold + if ft8_subpass is not None: + payload["ft8_subpass"] = ft8_subpass + if ft8_ap_on is not None: + payload["ft8_ap_on"] = ft8_ap_on + if ap_cq_only is not None: + payload["ap_cq_only"] = ap_cq_only + if ap_my_call is not None: + payload["ap_my_call"] = ap_my_call + if jt65_ap_on is not None: + payload["jt65_ap_on"] = jt65_ap_on + if ap_width_hz is not None: + payload["ap_width_hz"] = ap_width_hz + if hide_ft8_duplicates is not None: + payload["hide_ft8_duplicates"] = hide_ft8_duplicates + if common_ft8b is not None: + payload["common_ft8b"] = common_ft8b + if enable_dxc_search is not None: + payload["enable_dxc_search"] = enable_dxc_search + if wide_dxc_search is not None: + payload["wide_dxc_search"] = wide_dxc_search + if superfox_mode is not None: + payload["superfox_mode"] = superfox_mode + if even_sequence is not None: + payload["even_sequence"] = even_sequence + if hound_mode is not None: + payload["hound_mode"] = hound_mode + if multi_instance is not None: + payload["multi_instance"] = multi_instance + if skip_tx1 is not None: + payload["skip_tx1"] = skip_tx1 + if nagain_filter is not None: + payload["nagain_filter"] = nagain_filter + if stop_hint is not None: + payload["stop_hint"] = stop_hint + if hint_mode is not None: + payload["hint_mode"] = hint_mode + if bad_phase6: + # Wrong JSON type for a Phase 6 BOOLEAN key: ft8_ap_on as a number. + # Exercises the configure_type_error / atomic-decline path for a Phase 6 + # key. Placed last so it overrides any ft8_ap_on set above. + payload["ft8_ap_on"] = 5 + # Phase 7 keys (omitted when None so they don't perturb the default frame). + if last_tx_seconds_ago is not None: + payload["last_tx_seconds_ago"] = last_tx_seconds_ago + if currently_txing is not None: + payload["currently_txing"] = currently_txing + if mode_changed is not None: + payload["mode_changed"] = mode_changed + if qso_progress_state is not None: + payload["qso_progress_state"] = qso_progress_state + if sec_band_changed is not None: + payload["sec_band_changed"] = sec_band_changed + if delay_units is not None: + payload["delay_units"] = delay_units + if bad_phase7: + # Wrong JSON type for a Phase 7 INT key: last_tx_seconds_ago as a string. + # Exercises the configure_type_error / atomic-decline path for a Phase 7 + # key (expected:"int" got:"string"). Placed last so it overrides any + # last_tx_seconds_ago set above. + payload["last_tx_seconds_ago"] = "soon" + # Phase 8 keys (omitted when None so they don't perturb the default frame). + # utc/date are ISO strings; n_trials is a plain int the receiver encodes to + # nranera; candthin_threshold/dt_center_seconds are floats scaled /100. + if utc is not None: + payload["utc"] = utc + if date is not None: + payload["date"] = date + if n_trials is not None: + payload["n_trials"] = n_trials + if candthin_threshold is not None: + payload["candthin_threshold"] = candthin_threshold + if dt_center_seconds is not None: + payload["dt_center_seconds"] = dt_center_seconds + # Phase 9 keys (omitted when None so they don't perturb the default frame). + # ndepth group: sending any of these drops the legacy `depth` key (the receiver + # declines a frame carrying BOTH the full-int depth and an unpacked ndepth key — + # conflicting encodings). This mirrors a real producer sending one encoding form. + ndepth_keys = { + "depth_level": depth_level, + "q65_maxiters_level": q65_maxiters_level, + "use_averaging": use_averaging, + "deep_ap_search": deep_ap_search, + "q65_auto_clear_average": q65_auto_clear_average, + } + if any(v is not None for v in ndepth_keys.values()): + payload.pop("depth", None) + for k, v in ndepth_keys.items(): + if v is not None: + payload[k] = v + # nexp_decode group (contest_type / single_decode / vhf_features / noise_blanker). + if contest_type is not None: + payload["contest_type"] = contest_type + if single_decode is not None: + payload["single_decode"] = single_decode + if vhf_features is not None: + payload["vhf_features"] = vhf_features + if noise_blanker_level is not None: + payload["noise_blanker_level"] = noise_blanker_level + if bad_phase9: + # Wrong JSON type for a Phase 9 INT key: depth_level as a string. Drop the + # legacy depth so the only error is the depth_level type mismatch (exercises + # the configure_type_error / atomic-decline path for a Phase 9 key). + payload.pop("depth", None) + payload["depth_level"] = "deep" + if phase9_conflict: + # Co-present legacy depth (full int) + unpacked depth_level -> the receiver + # declines the frame (conflicting encodings). Force BOTH present + # (the unpacked block above would otherwise have dropped depth). + payload["depth"] = depth + payload["depth_level"] = 1 + return json.dumps(payload, separators=(",", ":")).encode("utf-8") + + +def halt_json() -> bytes: + return b'{"t":"halt"}' + + +# --- Stream-vs-WAV parity --------------------------------------------------- +# +# Identity is the decoded MESSAGE text. Empirically the snr/dt/freq fields +# drift between the WAV and stream decode paths for the SAME signal (snr +# ±2 dB, dt ±0.05 s, freq ±3 Hz on the FT8/JT9 fixtures) because the early +# nzhsym streaming passes compute slightly different fine estimates than the +# full-period WAV decode. So they are reported as diagnostics, never asserted; +# the message text is the only exactly-stable field and is the parity identity. + +# WSJT-X decode-line sync indicators (column 5), stripped before the message. +_SYNC_MARKERS = {"~", "@", "&", "+", "*", "#", "$", "`"} + + +def _norm_msg(s: str) -> str: + """Collapse runs of whitespace to single spaces and strip ends, so a + right-padded WAV text message and a trimmed NDJSON message compare equal.""" + return " ".join(s.split()) + + +def parse_wav_golden(path: Path) -> list[dict]: + """Parse a WSJT-X jt9 text decode file (test/fixtures/*.expected.txt). + + Line format: HHMMSS SNR DT FREQ <sync> MESSAGE + The <DecodeFinished ...> trailer and blank lines are skipped. Returns a + list of {"snr": int, "dt": float, "freq": int, "message": str}. + """ + out: list[dict] = [] + for raw in path.read_text().splitlines(): + if not raw.strip(): + continue + if raw.lstrip().startswith("<"): # <DecodeFinished ...> trailer + continue + tok = raw.split() + if len(tok) < 5: + continue + try: + snr = int(tok[1]) + dt = float(tok[2]) + freq = int(tok[3]) + except ValueError: + # Not a decode row (e.g. an unexpected header) — skip defensively. + continue + rest = tok[4:] + if rest and rest[0] in _SYNC_MARKERS: + rest = rest[1:] + out.append({ + "snr": snr, + "dt": dt, + "freq": freq, + "message": _norm_msg(" ".join(rest)), + }) + return out + + +def parse_stream_decodes(lines: list[str]) -> list[dict]: + """Pull the decode payload (snr/dt/freq/message) from each + {"t":"decode",...} NDJSON line, ignoring all other events and any + non-JSON diagnostic lines merged from stderr.""" + out: list[dict] = [] + for line in lines: + s = line.strip() + if not s.startswith("{"): + continue + try: + obj = json.loads(s) + except json.JSONDecodeError: + continue + if obj.get("t") != "decode": + continue + out.append({ + "snr": obj.get("snr"), + "dt": obj.get("dt"), + "freq": obj.get("freq"), + # `or ""` (not a get-default): an explicit "message":null sets the + # key, so get("message","") would return None and crash _norm_msg. + "message": _norm_msg(obj.get("message") or ""), + }) + return out + + +def run_parity(golden_path: Path, stream_lines: list[str], jt9_rc: int, + label: str) -> int: + """Assert WAV-golden signals ⊆ stream decodes (by message). Print a + per-signal diagnostic table; return 0 if all present, 1 if any dropped.""" + golden = parse_wav_golden(golden_path) + stream = parse_stream_decodes(stream_lines) + + if not golden: + # A golden that parses to zero signals cannot anchor a containment + # check — "WAV signals ⊆ stream" is vacuously true. Fail loudly so a + # truncated / corrupt / empty baseline is caught, not silently passed. + print(f"stream-vs-WAV parity: {label}") + print(f" golden: {golden_path} (0 WAV-confirmed signals)") + print(f" stream: {len(stream)} decodes (jt9 rc={jt9_rc})") + print(" PARITY FAIL: golden has 0 signals — cannot verify containment " + "(empty / truncated / corrupt baseline).") + return 1 + + by_msg: dict[str, list[dict]] = {} + for d in stream: + by_msg.setdefault(d["message"], []).append(d) + + print(f"stream-vs-WAV parity: {label}") + print(f" golden: {golden_path} ({len(golden)} WAV-confirmed signals)") + print(f" stream: {len(stream)} decodes (jt9 rc={jt9_rc})") + print(" identity = message text (containment); dFreq/dSNR/dDT are drift " + "diagnostics, not asserted") + print(f" {'status':<8}{'message':<24}{'dFreq':>7}{'dSNR':>6}{'dDT':>7}") + + missing: list[dict] = [] + for g in golden: + cands = by_msg.get(g["message"]) + if not cands: + missing.append(g) + print(f" {'MISSING':<8}{g['message']:<24}{'-':>7}{'-':>6}{'-':>7}") + continue + # If a message somehow appears more than once, diagnose against the + # nearest-frequency stream decode. + best = min(cands, key=lambda d: abs((d["freq"] or 0) - g["freq"])) + d_freq = (best["freq"] or 0) - g["freq"] + d_snr = (best["snr"] if best["snr"] is not None else 0) - g["snr"] + d_dt = (best["dt"] if best["dt"] is not None else 0.0) - g["dt"] + # int() casts guard the :d format codes against a spec-drift float + # freq/snr in the NDJSON (jt9 emits both as integers today). + print(f" {'OK':<8}{g['message']:<24}" + f"{int(d_freq):>7d}{int(d_snr):>6d}{d_dt:>+7.2f}") + + present = len(golden) - len(missing) + print(f" result: {present}/{len(golden)} WAV signals present; " + f"{len(stream)} stream decodes " + f"({len(stream) - present} extra — streaming may legitimately find more)") + if missing: + print(f" PARITY FAIL: {len(missing)} WAV-confirmed signal(s) dropped " + f"by the stream:") + for g in missing: + print(f" - {g['message']!r} (WAV freq {g['freq']} Hz, snr {g['snr']})") + return 1 + print(" PARITY OK: every WAV-confirmed signal is present in the stream.") + return 0 + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("jt9", type=Path) + p.add_argument("wav", type=Path) + p.add_argument("--mode", default="FT8") + p.add_argument("--mycall", default="KJ5HST", + help="Callsign for the main configure frame. Set to a key " + "token (e.g. 'mygrid') with --omit-mygrid to exercise " + "the value-vs-key aliasing guard.") + p.add_argument("--omit-mygrid", action="store_true", + help="Omit the mygrid key from the main configure frame.") + p.add_argument("--ntol", type=int, default=1000) + p.add_argument("--nfa", type=int, default=200) + p.add_argument("--nfb", type=int, default=3000) + p.add_argument("--nutc", type=int, default=None, + help="UTC HHMMSS for the configure frame.") + p.add_argument("--schema-version", type=int, default=None, + help="Body schema version on the configure frame. " + "A version != 1 must be declined with unknown_schema_version.") + p.add_argument("--bad-control", action="store_true", + help="Also send a malformed control frame (missing the required " + "\"t\" field) to exercise the configure_parse_error path.") + p.add_argument("--bad-type", action="store_true", + help="Make the MAIN configure frame carry a wrong-typed key " + "(depth as a JSON string) to exercise the " + "configure_type_error / atomic-decline path. " + "Combine with --mode to verify a co-present good key " + "(e.g. mode) is NOT applied when the frame is declined.") + p.add_argument("--bad-type-preamble", action="store_true", + help="Send a wrong-typed configure frame BEFORE the valid main " + "configure to verify recovery: the bad frame is " + "declined with configure_type_error and the following valid " + "frame applies normally.") + # --- Phase 4: operator identity + frequency-window keys ------------------- + p.add_argument("--his-call", dest="his_call", default=None, + help="Phase 4: his_call (-> hiscall, char12).") + p.add_argument("--his-grid", dest="his_grid", default=None, + help="Phase 4: his_grid (-> hisgrid, char6).") + p.add_argument("--my-b-call", dest="my_b_call", default=None, + help="Phase 4: my_b_call (-> mybcall, char12).") + p.add_argument("--his-b-call", dest="his_b_call", default=None, + help="Phase 4: his_b_call (-> hisbcall, char12).") + p.add_argument("--my-call-standard", dest="my_call_standard", + action="store_true", default=None, + help="Phase 4: my_call_standard=true (-> lmycallstd).") + p.add_argument("--his-call-standard", dest="his_call_standard", + action="store_true", default=None, + help="Phase 4: his_call_standard=true (-> lhiscallstd).") + p.add_argument("--tx-audio-offset-hz", dest="tx_audio_offset_hz", type=int, + default=None, + help="Phase 4: tx_audio_offset_hz (-> nftx; decouples tx " + "from rxfreq, which sets both nfqso+nftx).") + p.add_argument("--jt65-jt9-split-hz", dest="jt65_jt9_split_hz", type=int, + default=None, help="Phase 4: jt65_jt9_split_hz (-> nfsplit).") + p.add_argument("--max-drift-hz", dest="max_drift_hz", type=int, default=None, + help="Phase 4: max_drift_hz (-> max_drift, Q65 drift search).") + p.add_argument("--bad-phase4", action="store_true", + help="Make the MAIN configure carry a wrong-typed Phase 4 key " + "(my_call_standard as a number) to exercise " + "configure_type_error / atomic-decline for a Phase 4 key.") + # Phase 5: decoder-tuning basic fields. None => omit the key. + p.add_argument("--dt-tolerance-seconds", dest="dt_tolerance_seconds", + type=float, default=None, + help="Phase 5: dt tolerance seconds (-> real(c_float) dttol).") + p.add_argument("--eme-delay-seconds", dest="eme_delay_seconds", + type=float, default=None, + help="Phase 5: EME delay seconds (-> real(c_float) emedelay; " + "D1 — overwritten by per-mode policy on a mode/tr frame).") + p.add_argument("--kin-samples", dest="kin_samples", type=int, default=None, + help="Phase 5: kin sample count (-> kin; recomputed per period).") + p.add_argument("--nzhsym-per-period", dest="nzhsym_per_period", type=int, + default=None, + help="Phase 5: nzhsym per period (-> nzhsym; recomputed per period).") + p.add_argument("--npts-c0-array", dest="npts_c0_array", type=int, default=None, + help="Phase 5: npts for the c0() array (-> npts8; JT9 decode).") + p.add_argument("--min-width", dest="min_width", type=int, default=None, + help="Phase 5: min width (-> minw).") + p.add_argument("--min-sync", dest="min_sync", type=int, default=None, + help="Phase 5: min sync (-> minsync).") + p.add_argument("--n-2pass", dest="n_2pass", type=int, default=None, + help="Phase 5: 2-pass count (-> n2pass).") + p.add_argument("--robust-mode", dest="robust_mode", action="store_true", + default=None, help="Phase 5: robust mode flag (-> nrobust).") + p.add_argument("--nagain-flag", dest="nagain_flag", action="store_true", + default=None, help="Phase 5: decode-again flag (-> nagain).") + p.add_argument("--tx-mode", dest="tx_mode", default=None, + help="Phase 5: tx mode enum JT9/JT65 or int 9/65 (-> ntxmode).") + p.add_argument("--clear-average", dest="clear_average", action="store_true", + default=None, help="Phase 5: clear-average flag (-> nclearave).") + p.add_argument("--bad-phase5", action="store_true", + help="Make the MAIN configure carry a wrong-typed Phase 5 key " + "(dt_tolerance_seconds as a string) to exercise " + "configure_type_error / atomic-decline for a Phase 5 key.") + # Phase 6: FT8/FT4 specifics cluster. None => omit the key. The + # bool flags are store_true/default=None (presence => true); --no-* variants + # send an explicit false where a gate needs it (ft8_ap_on defaults true). + p.add_argument("--multithreaded-ft8", dest="multithreaded_ft8", + action="store_true", default=None, + help="Phase 6: multithreaded_ft8=true (-> lmultift8; " + "receiver-ignored on the single-pass stream path).") + p.add_argument("--ft8-cycles", dest="ft8_cycles", type=int, default=None, + help="Phase 6: ft8_cycles (-> nft8cycles).") + p.add_argument("--ft8-rxf-sensitivity", dest="ft8_rxf_sensitivity", type=int, + default=None, help="Phase 6: ft8_rxf_sensitivity (-> nft8rxfsens).") + p.add_argument("--ft8-threads", dest="ft8_threads", type=int, default=None, + help="Phase 6: ft8_threads (-> nmt).") + p.add_argument("--ft8-decoder-start", dest="ft8_decoder_start", type=int, + default=None, help="Phase 6: ft8_decoder_start (-> ndecoderstart).") + p.add_argument("--ft8-low-threshold", dest="ft8_low_threshold", + action="store_true", default=None, + help="Phase 6: ft8_low_threshold=true (-> lft8lowth).") + p.add_argument("--ft8-subpass", dest="ft8_subpass", action="store_true", + default=None, help="Phase 6: ft8_subpass=true (-> lft8subpass).") + p.add_argument("--ft8-ap-on", dest="ft8_ap_on", action="store_true", + default=None, help="Phase 6: ft8_ap_on=true (-> lft8apon, AP on).") + p.add_argument("--no-ft8-ap-on", dest="ft8_ap_on", action="store_false", + help="Phase 6: ft8_ap_on=false (-> lft8apon; AP off — observable, " + "reduces FT8 decodes vs the default-true).") + p.add_argument("--ap-cq-only", dest="ap_cq_only", action="store_true", + default=None, help="Phase 6: ap_cq_only=true (-> lapcqonly).") + p.add_argument("--ap-my-call", dest="ap_my_call", action="store_true", + default=None, help="Phase 6: ap_my_call=true (-> lapmyc).") + p.add_argument("--jt65-ap-on", dest="jt65_ap_on", action="store_true", + default=None, help="Phase 6: jt65_ap_on=true (-> ljt65apon).") + p.add_argument("--ap-width-hz", dest="ap_width_hz", type=int, default=None, + help="Phase 6: ap_width_hz (-> napwid, RAW; decoder halves it).") + p.add_argument("--hide-ft8-duplicates", dest="hide_ft8_duplicates", + action="store_true", default=None, + help="Phase 6: hide_ft8_duplicates=true (-> lhideft8dupes).") + p.add_argument("--common-ft8b", dest="common_ft8b", action="store_true", + default=None, help="Phase 6: common_ft8b=true (-> lcommonft8b).") + p.add_argument("--enable-dxc-search", dest="enable_dxc_search", + action="store_true", default=None, + help="Phase 6: enable_dxc_search=true (-> lenabledxcsearch).") + p.add_argument("--wide-dxc-search", dest="wide_dxc_search", + action="store_true", default=None, + help="Phase 6: wide_dxc_search=true (-> lwidedxcsearch).") + p.add_argument("--superfox-mode", dest="superfox_mode", action="store_true", + default=None, help="Phase 6: superfox_mode=true (-> b_superfox).") + p.add_argument("--even-sequence", dest="even_sequence", action="store_true", + default=None, help="Phase 6: even_sequence=true (-> b_even_seq).") + p.add_argument("--hound-mode", dest="hound_mode", action="store_true", + default=None, help="Phase 6: hound_mode=true (-> lhound).") + p.add_argument("--multi-instance", dest="multi_instance", action="store_true", + default=None, help="Phase 6: multi_instance=true (-> lmultinst).") + p.add_argument("--skip-tx1", dest="skip_tx1", action="store_true", + default=None, help="Phase 6: skip_tx1=true (-> lskiptx1).") + p.add_argument("--nagain-filter", dest="nagain_filter", action="store_true", + default=None, help="Phase 6: nagain_filter=true (-> nagainfil).") + p.add_argument("--stop-hint", dest="stop_hint", action="store_true", + default=None, help="Phase 6: stop_hint=true (-> nstophint).") + p.add_argument("--hint-mode", dest="hint_mode", action="store_true", + default=None, help="Phase 6: hint_mode=true (-> nhint).") + p.add_argument("--bad-phase6", action="store_true", + help="Make the MAIN configure carry a wrong-typed Phase 6 key " + "(ft8_ap_on as a number) to exercise " + "configure_type_error / atomic-decline for a Phase 6 key.") + # Phase 7: diagnostic / sequencing fields. None => omit the key. + # All 6 are inert on the FT8/JT9 stream fixtures (multithread-block-only / + # AP-only) — see lib/streaming_control.f90 Phase 7 comment. + p.add_argument("--last-tx-seconds-ago", dest="last_tx_seconds_ago", + type=int, default=None, + help="Phase 7: last_tx_seconds_ago (-> nlasttx).") + p.add_argument("--currently-txing", dest="currently_txing", + action="store_true", default=None, + help="Phase 7: currently_txing=true (-> ltxing).") + p.add_argument("--mode-changed", dest="mode_changed", + action="store_true", default=None, + help="Phase 7: mode_changed=true (-> lmodechanged).") + p.add_argument("--qso-progress-state", dest="qso_progress_state", + type=int, default=None, + help="Phase 7: qso_progress_state (-> nQSOProgress; steers AP " + "decode passes, inert without AP-only decodes). Apply " + "GUARDS the valid GUI range [0,5]; an out-of-range value is " + "ignored (it would crash the FT8 decoder's AP-array index).") + p.add_argument("--sec-band-changed", dest="sec_band_changed", + type=int, default=None, + help="Phase 7: sec_band_changed (-> nsecbandchanged; D3 inert, " + "multithread-block-only).") + p.add_argument("--delay-units", dest="delay_units", + type=int, default=None, + help="Phase 7: delay_units (-> ndelay; D3 inert, " + "multithread-block-only).") + p.add_argument("--bad-phase7", action="store_true", + help="Make the MAIN configure carry a wrong-typed Phase 7 key " + "(last_tx_seconds_ago as a string) to exercise " + "configure_type_error / atomic-decline for a Phase 7 key.") + # Phase 8: string & scaled / derived fields. None => omit. + p.add_argument("--utc", dest="utc", default=None, + help="Phase 8: utc ISO \"HH:MM:SS\" (-> nutc, full HHMMSS; " + "decode-observable in the time field; WINS over --nutc).") + p.add_argument("--date", dest="date", default=None, + help="Phase 8: date ISO \"YYYY-MM-DD\" (-> yymmdd; superfox-only, " + "inert on FT8/JT9). year>=2100 -> configure_type_error.") + p.add_argument("--n-trials", dest="n_trials", type=int, default=None, + help="Phase 8: n_trials (-> encoded nranera; JT65-only, inert on " + "FT8/JT9). Must be 10^N or 3*10^N else configure_type_error.") + p.add_argument("--candthin-threshold", dest="candthin_threshold", + type=float, default=None, + help="Phase 8: candthin_threshold (-> ncandthin = round(x*100)).") + p.add_argument("--dt-center-seconds", dest="dt_center_seconds", + type=float, default=None, + help="Phase 8: dt_center_seconds (-> ndtcenter = round(x*100)).") + # Phase 9: bit-packed fields. ndepth-group flags + # auto-drop the legacy --depth (precedence; co-present is a conflict error). + p.add_argument("--depth-level", dest="depth_level", type=int, default=None, + help="Phase 9: depth_level (ndepth bits 0-2). The one Phase-9 key " + "decode-observable on FT8/JT9 (depth_level=1 -> ndepth=1 " + "changes the FT8 pass structure). Drops the legacy depth key.") + p.add_argument("--q65-maxiters-level", dest="q65_maxiters_level", type=int, + default=None, + help="Phase 9: q65_maxiters_level (ndepth bits 0-1; Q65-only). " + "Must agree with depth_level's low 2 bits if both are set.") + p.add_argument("--use-averaging", dest="use_averaging", action="store_true", + default=None, + help="Phase 9: use_averaging (ndepth bit 4; Q65/JT65/JT4, inert FT8/JT9).") + p.add_argument("--deep-ap-search", dest="deep_ap_search", action="store_true", + default=None, + help="Phase 9: deep_ap_search (ndepth bit 5; JT4/JT65, inert FT8/JT9).") + p.add_argument("--q65-auto-clear-average", dest="q65_auto_clear_average", + action="store_true", default=None, + help="Phase 9: q65_auto_clear_average (ndepth bit 7; Q65, inert FT8/JT9).") + p.add_argument("--contest-type", dest="contest_type", default=None, + help="Phase 9: contest_type enum string -> ncontest (nexp_decode " + "bits 0-2; SpecOp 5/8/9 collapse to 1). Unknown -> silent skip.") + p.add_argument("--single-decode", dest="single_decode", action="store_true", + default=None, + help="Phase 9: single_decode (nexp_decode bit 5; FST4/JT65, not " + "the single-pass FT8 decoder).") + p.add_argument("--vhf-features", dest="vhf_features", action="store_true", + default=None, + help="Phase 9: vhf_features (nexp_decode bit 6; Q65/JT65, inert FT8/JT9).") + p.add_argument("--noise-blanker-level", dest="noise_blanker_level", type=int, + default=None, + help="Phase 9: noise_blanker_level (nexp_decode upper byte, +3 " + "offset; FST4-only, inert FT8/JT9).") + p.add_argument("--bad-phase9", action="store_true", + help="Make the MAIN configure carry a wrong-typed Phase 9 key " + "(depth_level as a string) to exercise the " + "configure_type_error / atomic-decline for a Phase 9 key.") + p.add_argument("--phase9-conflict", action="store_true", + help="Make the MAIN configure carry BOTH the legacy depth and the " + "unpacked depth_level (conflict) to exercise the " + "configure_type_error / atomic-decline on conflicting encodings.") + p.add_argument("--prepend-mode", default=None, + help="Send a configure with this mode FIRST (no audio), then " + "the main configure + audio. Used to test mode-change " + "semantics.") + p.add_argument("--prepend-with-explicit-narrowing", action="store_true", + help="When --prepend-mode is set, the prepended configure " + "also sets ntol/nfa/nfb to narrow values. Tests that " + "the subsequent main configure restores defaults.") + p.add_argument( + "--quiet", + action="store_true", + help="Suppress non-JSON stderr lines (e.g., TRACE, header-ok).", + ) + p.add_argument( + "--parity", + type=Path, + default=None, + help="Stream-vs-WAV decode-parity mode. Instead of " + "printing NDJSON, decode the WAV via --stream, parse the WSJT-X " + "text golden at this path, and assert CONTAINMENT: every " + "WAV-confirmed signal (by message text) is present in the stream. " + "Exit 0 if all present, 1 if any is dropped. snr/dt/freq are shown " + "as drift diagnostics only (they legitimately differ between the " + "WAV and stream decode paths); message text is the identity.", + ) + args = p.parse_args() + + if not args.jt9.is_file(): + print(f"ERROR: jt9 binary not found: {args.jt9}", file=sys.stderr) + return 2 + if not args.wav.is_file(): + print(f"ERROR: WAV file not found: {args.wav}", file=sys.stderr) + return 2 + if args.parity is not None and not args.parity.is_file(): + print(f"ERROR: parity golden not found: {args.parity}", file=sys.stderr) + return 2 + + with wave.open(str(args.wav)) as w: + if w.getnchannels() != 1: + print( + f"ERROR: WAV must be mono (got {w.getnchannels()} channels)", + file=sys.stderr, + ) + return 2 + if w.getsampwidth() != 2: + print( + f"ERROR: WAV must be 16-bit (got {w.getsampwidth()} byte samples)", + file=sys.stderr, + ) + return 2 + if w.getframerate() != 12000: + print( + f"ERROR: WAV must be 12 kHz (got {w.getframerate()} Hz)", + file=sys.stderr, + ) + return 2 + audio = w.readframes(w.getnframes()) + + proc = subprocess.Popen( + [str(args.jt9), "--stream"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, # mandatory: consumers must drain stderr + ) + + try: + proc.stdin.write(wsjt_session_header()) + + # Malformed control frame (missing "t") -> configure_parse_error. + # Sent before the normal configure; the stream must continue and decode. + if args.bad_control: + proc.stdin.write(frame(FRAME_CONTROL, b'{"mode":"FT8"}')) + + # Wrong-typed preamble frame -> configure_type_error, declined. + # Sent before the valid main configure; the stream must recover and the + # following valid frame must apply normally. + if args.bad_type_preamble: + proc.stdin.write(frame(FRAME_CONTROL, configure_json( + mode=args.mode, bad_depth=True, + ))) + + # Optional mode-change preamble (tests mode-change semantics). + if args.prepend_mode: + if args.prepend_with_explicit_narrowing: + proc.stdin.write(frame(FRAME_CONTROL, configure_json( + mode=args.prepend_mode, ntol=10, nfa=1400, nfb=1600, + ))) + else: + proc.stdin.write(frame(FRAME_CONTROL, configure_json( + mode=args.prepend_mode, + ntol=None, nfa=None, nfb=None, # rely on per-mode defaults + ))) + + # Main configure. When testing mode-change semantics, the bug being + # gated is "after a prior mode's state, the main configure with no + # ntol/nfa/nfb should reset to per-mode/baseline defaults." So pass + # None (omit fields) when prepending, to exercise the restore path. + # Phase 4 keys ride on the MAIN configure only (not the preambles). + phase4 = dict( + his_call=args.his_call, his_grid=args.his_grid, + my_b_call=args.my_b_call, his_b_call=args.his_b_call, + my_call_standard=args.my_call_standard, + his_call_standard=args.his_call_standard, + tx_audio_offset_hz=args.tx_audio_offset_hz, + jt65_jt9_split_hz=args.jt65_jt9_split_hz, + max_drift_hz=args.max_drift_hz, + bad_phase4=args.bad_phase4, + ) + # Phase 5 keys also ride on the MAIN configure only. + phase5 = dict( + dt_tolerance_seconds=args.dt_tolerance_seconds, + eme_delay_seconds=args.eme_delay_seconds, + kin_samples=args.kin_samples, + nzhsym_per_period=args.nzhsym_per_period, + npts_c0_array=args.npts_c0_array, + min_width=args.min_width, + min_sync=args.min_sync, + n_2pass=args.n_2pass, + robust_mode=args.robust_mode, + nagain_flag=args.nagain_flag, + tx_mode=args.tx_mode, + clear_average=args.clear_average, + bad_phase5=args.bad_phase5, + ) + # Phase 6 keys also ride on the MAIN configure only. + phase6 = dict( + multithreaded_ft8=args.multithreaded_ft8, + ft8_cycles=args.ft8_cycles, + ft8_rxf_sensitivity=args.ft8_rxf_sensitivity, + ft8_threads=args.ft8_threads, + ft8_decoder_start=args.ft8_decoder_start, + ft8_low_threshold=args.ft8_low_threshold, + ft8_subpass=args.ft8_subpass, + ft8_ap_on=args.ft8_ap_on, + ap_cq_only=args.ap_cq_only, + ap_my_call=args.ap_my_call, + jt65_ap_on=args.jt65_ap_on, + ap_width_hz=args.ap_width_hz, + hide_ft8_duplicates=args.hide_ft8_duplicates, + common_ft8b=args.common_ft8b, + enable_dxc_search=args.enable_dxc_search, + wide_dxc_search=args.wide_dxc_search, + superfox_mode=args.superfox_mode, + even_sequence=args.even_sequence, + hound_mode=args.hound_mode, + multi_instance=args.multi_instance, + skip_tx1=args.skip_tx1, + nagain_filter=args.nagain_filter, + stop_hint=args.stop_hint, + hint_mode=args.hint_mode, + bad_phase6=args.bad_phase6, + ) + # Phase 7 keys also ride on the MAIN configure only. + phase7 = dict( + last_tx_seconds_ago=args.last_tx_seconds_ago, + currently_txing=args.currently_txing, + mode_changed=args.mode_changed, + qso_progress_state=args.qso_progress_state, + sec_band_changed=args.sec_band_changed, + delay_units=args.delay_units, + bad_phase7=args.bad_phase7, + ) + # Phase 8 keys also ride on the MAIN configure only. + phase8 = dict( + utc=args.utc, + date=args.date, + n_trials=args.n_trials, + candthin_threshold=args.candthin_threshold, + dt_center_seconds=args.dt_center_seconds, + ) + # Phase 9 keys also ride on the MAIN configure only. + phase9 = dict( + depth_level=args.depth_level, + q65_maxiters_level=args.q65_maxiters_level, + use_averaging=args.use_averaging, + deep_ap_search=args.deep_ap_search, + q65_auto_clear_average=args.q65_auto_clear_average, + contest_type=args.contest_type, + single_decode=args.single_decode, + vhf_features=args.vhf_features, + noise_blanker_level=args.noise_blanker_level, + bad_phase9=args.bad_phase9, + phase9_conflict=args.phase9_conflict, + ) + if args.prepend_mode: + proc.stdin.write(frame(FRAME_CONTROL, configure_json( + mode=args.mode, ntol=None, nfa=None, nfb=None, + nutc=args.nutc, version=args.schema_version, + bad_depth=args.bad_type, mycall=args.mycall, + omit_mygrid=args.omit_mygrid, + **phase4, **phase5, **phase6, **phase7, **phase8, **phase9, + ))) + else: + proc.stdin.write(frame(FRAME_CONTROL, configure_json( + mode=args.mode, ntol=args.ntol, nfa=args.nfa, nfb=args.nfb, + nutc=args.nutc, version=args.schema_version, + bad_depth=args.bad_type, mycall=args.mycall, + omit_mygrid=args.omit_mygrid, + **phase4, **phase5, **phase6, **phase7, **phase8, **phase9, + ))) + + # Audio frames: CHUNK_SAMPLES * 2 bytes per chunk. + bytes_per_chunk = CHUNK_SAMPLES * 2 + for off in range(0, len(audio), bytes_per_chunk): + proc.stdin.write(frame(FRAME_AUDIO, audio[off : off + bytes_per_chunk])) + proc.stdin.write(frame(FRAME_CONTROL, halt_json())) + proc.stdin.flush() + proc.stdin.close() + except BrokenPipeError: + pass + + out_bytes = proc.stdout.read() + proc.wait(timeout=60) + out = out_bytes.decode("utf-8", errors="replace") + out_lines = out.splitlines() + + if args.parity is not None: + return run_parity( + args.parity, out_lines, proc.returncode, + f"{args.mode} {args.wav.name}", + ) + + for line in out_lines: + if args.quiet and not line.startswith("{"): + continue + print(line) + return proc.returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/wav_to_stream_no_configure.py b/test/wav_to_stream_no_configure.py new file mode 100755 index 00000000..4611a974 --- /dev/null +++ b/test/wav_to_stream_no_configure.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +""" +wav-to-stream validation harness — no-configure-frame variant. + +Pipes a 12 kHz mono int16 WAV file through `jt9 --stream` using the +streaming protocol, but does NOT send a configure frame. +Decode parameters come from jt9's CLI args (-F/-f/-L/-H/-d) instead. + +This exercises the CLI-arg threading path through init_default_params. +Earlier, streaming_io.f90 silently overrode the CLI +args with FT8-baseline hardcoded defaults — so a no-configure invocation +produced 0 decodes regardless of what the user passed on the CLI. + +Usage: + test/wav_to_stream_no_configure.py <jt9-binary> <wav-file> + [--mode-flag MODE_FLAG] [--ntol NTOL] [--nrxfreq HZ] + [--flow HZ] [--fhigh HZ] [--ndepth N] + +NDJSON lines and stderr are printed to stdout (consumers MUST drain +stderr). Exit code is jt9's exit code. +""" +from __future__ import annotations + +import argparse +import struct +import subprocess +import sys +import wave +from pathlib import Path + +FRAME_AUDIO = 0x01 +FRAME_CONTROL = 0x02 +CHUNK_SAMPLES = 12000 + + +def wsjt_session_header(rate_khz: int = 12) -> bytes: + return b"WSJT" + bytes([0, 1]) + struct.pack("<H", rate_khz) + + +def frame(type_byte: int, body: bytes) -> bytes: + return bytes([type_byte]) + struct.pack("<I", len(body)) + body + + +def halt_json() -> bytes: + return b'{"t":"halt"}' + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("jt9", type=Path) + p.add_argument("wav", type=Path) + p.add_argument("--mode-flag", default="-8", + help="jt9 mode flag (-8 FT8, -9 JT9, etc.)") + p.add_argument("--ntol", type=int, default=1000) + p.add_argument("--nrxfreq", type=int, default=1500) + p.add_argument("--flow", type=int, default=200) + p.add_argument("--fhigh", type=int, default=3000) + p.add_argument("--ndepth", type=int, default=1) + p.add_argument("--quiet", action="store_true", + help="Suppress non-JSON stderr lines.") + args = p.parse_args() + + if not args.jt9.is_file(): + print(f"ERROR: jt9 binary not found: {args.jt9}", file=sys.stderr) + return 2 + if not args.wav.is_file(): + print(f"ERROR: WAV file not found: {args.wav}", file=sys.stderr) + return 2 + + with wave.open(str(args.wav)) as w: + if w.getnchannels() != 1 or w.getsampwidth() != 2 or w.getframerate() != 12000: + print("ERROR: WAV must be 12 kHz mono 16-bit", file=sys.stderr) + return 2 + audio = w.readframes(w.getnframes()) + + cmd = [ + str(args.jt9), "--stream", args.mode_flag, + "-F", str(args.ntol), "-f", str(args.nrxfreq), + "-L", str(args.flow), "-H", str(args.fhigh), + "-d", str(args.ndepth), + ] + + proc = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + + try: + proc.stdin.write(wsjt_session_header()) + # NOTE: NO configure frame here — that is the whole point of this + # harness. CLI args from -F/-f/-L/-H/-d above must be honored by + # init_default_params with no help from a runtime configure. + bytes_per_chunk = CHUNK_SAMPLES * 2 + for off in range(0, len(audio), bytes_per_chunk): + proc.stdin.write(frame(FRAME_AUDIO, audio[off : off + bytes_per_chunk])) + proc.stdin.write(frame(FRAME_CONTROL, halt_json())) + proc.stdin.flush() + proc.stdin.close() + except BrokenPipeError: + pass + + out_bytes = proc.stdout.read() + proc.wait(timeout=60) + out = out_bytes.decode("utf-8", errors="replace") + for line in out.splitlines(): + if args.quiet and not line.startswith("{"): + continue + print(line) + return proc.returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/wav_to_wsprd_stream_harness.py b/test/wav_to_wsprd_stream_harness.py new file mode 100755 index 00000000..3d81f08c --- /dev/null +++ b/test/wav_to_wsprd_stream_harness.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +""" +wav-to-wsprd-stream validation harness. + +Pipes a 12 kHz mono int16 WAV file through `wsprd --stream` using the +streaming protocol, then prints the resulting NDJSON +decodes. Used to verify that streaming-mode decode results match the +file-mode ground truth. + +Usage: + test/wav_to_wsprd_stream_harness.py <wsprd-binary> <wav-file> + [--dialfreq MHZ] [--wspr-type 2|15] + [--mycall CALL] [--mygrid GRID] + +Filename convention: YYMMDD_HHMM.wav (matches existing wsprd file-mode +behavior). Date/time get extracted from the filename and sent in the +configure frame. + +NDJSON lines are written to stdout. stderr is merged into stdout +(consumers MUST drain stderr). +""" +from __future__ import annotations + +import argparse +import json +import re +import struct +import subprocess +import sys +import wave +from pathlib import Path + +FRAME_AUDIO = 0x01 +FRAME_CONTROL = 0x02 + +# Audio chunk size in 12 kHz samples per frame. ~1 s per frame. +CHUNK_SAMPLES = 12000 + + +def wsjt_session_header(rate_khz: int = 12) -> bytes: + return b"WSJT" + bytes([0, 1]) + struct.pack("<H", rate_khz) + + +def frame(type_byte: int, body: bytes) -> bytes: + return bytes([type_byte]) + struct.pack("<I", len(body)) + body + + +def configure_json( + date: str, uttime: str, dialfreq: float, wspr_type: int, + mycall: str = "KJ5HST", mygrid: str = "EM18", +) -> bytes: + payload = { + "t": "configure", + "date": date, + "time": uttime, + "dialfreq": dialfreq, + "wspr_type": wspr_type, + "mycall": mycall, + "mygrid": mygrid, + } + return json.dumps(payload, separators=(",", ":")).encode("utf-8") + + +def halt_json() -> bytes: + return b'{"t":"halt"}' + + +def parse_filename_timestamp(wav_path: Path) -> tuple[str, str]: + """Extract YYMMDD and HHMM from a YYMMDD_HHMM.wav filename.""" + m = re.match(r"^(\d{6})_(\d{4})\.wav$", wav_path.name) + if not m: + raise ValueError(f"WAV filename must match YYMMDD_HHMM.wav: {wav_path.name}") + return m.group(1), m.group(2) + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("wsprd", type=Path) + p.add_argument("wav", type=Path) + p.add_argument("--dialfreq", type=float, default=14.0956) + p.add_argument("--wspr-type", type=int, default=2, choices=[2, 15]) + p.add_argument("--mycall", default="KJ5HST") + p.add_argument("--mygrid", default="EM18") + p.add_argument( + "--quiet", action="store_true", + help="Suppress non-JSON stderr lines (e.g., header-ok).", + ) + args = p.parse_args() + + if not args.wsprd.is_file(): + print(f"ERROR: wsprd binary not found: {args.wsprd}", file=sys.stderr) + return 2 + if not args.wav.is_file(): + print(f"ERROR: WAV file not found: {args.wav}", file=sys.stderr) + return 2 + + date, uttime = parse_filename_timestamp(args.wav) + + with wave.open(str(args.wav)) as w: + if w.getnchannels() != 1: + print(f"ERROR: WAV must be mono (got {w.getnchannels()} channels)", + file=sys.stderr) + return 2 + if w.getsampwidth() != 2: + print(f"ERROR: WAV must be 16-bit (got {w.getsampwidth()} byte samples)", + file=sys.stderr) + return 2 + if w.getframerate() != 12000: + print(f"ERROR: WAV must be 12 kHz (got {w.getframerate()} Hz)", + file=sys.stderr) + return 2 + audio = w.readframes(w.getnframes()) + + proc = subprocess.Popen( + [str(args.wsprd), "-0"], # -0 == streaming mode (wsprd uses getopt single-char only) + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + + try: + proc.stdin.write(wsjt_session_header()) + proc.stdin.write(frame( + FRAME_CONTROL, + configure_json(date, uttime, args.dialfreq, args.wspr_type, + args.mycall, args.mygrid), + )) + bytes_per_chunk = CHUNK_SAMPLES * 2 + for off in range(0, len(audio), bytes_per_chunk): + proc.stdin.write(frame(FRAME_AUDIO, audio[off : off + bytes_per_chunk])) + proc.stdin.write(frame(FRAME_CONTROL, halt_json())) + proc.stdin.flush() + proc.stdin.close() + except BrokenPipeError: + pass + + out_bytes = proc.stdout.read() + proc.wait(timeout=120) + out = out_bytes.decode("utf-8", errors="replace") + for line in out.splitlines(): + if args.quiet and not line.startswith("{"): + continue + print(line) + return proc.returncode + + +if __name__ == "__main__": + sys.exit(main()) |
