From fc785d29a248eb032ada201f98b5f17d32c6089d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 10:59:59 -0500 Subject: [PATCH 01/17] Tests(fix[waits]): Bound event waits why: Eleven macOS-15 CI runs from 09-26 to 10-04 failed on unrelated commits with a wait that gave up at 0.5 or 1.0 seconds: "tmux fixture exceeded event deadline", "attached client did not draw its terminal", "installed MCP did not return a frame" and a DeadlineExceeded inside MCPEnrollmentTest. Each wait already returns on an event (pipe readable, wait-for signal, thread join); only its bound was sized for a fast machine, and a tmux spawn or Ruby start on the hosted macOS runner can exceed it. The same tests pass on Linux at the same shas. what: - Add HANG_GUARD_SECONDS to test/test_helper.rb and use it for event waits in integration tests and TmuxFixture, which now reads it for its command and readiness deadline and for reap waits - Advance the transport clock by the guard in the two tests that expire a request deadline by clock offset, so they still expire it - Raise the same bounds in the shipped examples and their copies in docs/recipes.md and the libtmux-async README - Leave tests that prove a deadline elapsed (0.02 s transport limits, OperationBudgetTest's offset clock, a never-signalled wait-for) --- examples/cancel.rb | 4 +- examples/mcp_protocol.rb | 8 +- examples/support.rb | 2 +- test/integration/async_test.rb | 42 ++++----- test/integration/capture_semantics_test.rb | 10 +-- test/integration/control_test.rb | 90 ++++++++++---------- test/integration/creation_test.rb | 8 +- test/integration/fixture_test.rb | 18 ++-- test/integration/group_test.rb | 4 +- test/integration/identity_test.rb | 10 +-- test/integration/mcp_capture_test.rb | 4 +- test/integration/mcp_cli_test.rb | 18 ++-- test/integration/mcp_cursor_identity_test.rb | 4 +- test/integration/mcp_enrollment_test.rb | 74 ++++++++-------- test/integration/mcp_mutation_test.rb | 14 +-- test/integration/mcp_transport_test.rb | 32 +++---- test/integration/mcp_wait_test.rb | 28 +++--- test/integration/operations_test.rb | 30 +++---- test/integration/pane_io_test.rb | 18 ++-- test/integration/server_control_test.rb | 8 +- test/integration/server_test.rb | 22 ++--- test/integration/session_guard_test.rb | 4 +- test/integration/snapshot_test.rb | 6 +- test/integration/startup_test.rb | 12 +-- test/integration/terminal_test.rb | 18 ++-- test/integration/workspace_cli_test.rb | 2 +- test/integration/workspace_test.rb | 2 +- test/support/control_assertions.rb | 14 +-- test/support/controlling_terminal.rb | 8 +- test/support/process_cursor_support.rb | 2 +- test/support/tmux_fixture.rb | 9 +- test/test_helper.rb | 3 + 32 files changed, 266 insertions(+), 262 deletions(-) diff --git a/examples/cancel.rb b/examples/cancel.rb index eb073131..08ce1018 100644 --- a/examples/cancel.rb +++ b/examples/cancel.rb @@ -11,11 +11,11 @@ begin waiting = Thread.new do server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 0.5, cancel: cancellation) + timeout: 5, cancel: cancellation) rescue LibTmux::Cancelled => error error end - server.wait_for("ready", timeout: 0.5) + server.wait_for("ready", timeout: 5) cancellation.cancel failure = waiting.value Example.check(failure.is_a?(LibTmux::Cancelled), "cancellation lost") diff --git a/examples/mcp_protocol.rb b/examples/mcp_protocol.rb index 2ce4c9be..f28045a7 100644 --- a/examples/mcp_protocol.rb +++ b/examples/mcp_protocol.rb @@ -40,24 +40,24 @@ Example.check(application.call("tmux_close", {}).structured_content.dig("error", "code") == "policy_denied", "default policy permits mutation") cancellations = Queue.new sdk.define_custom_method(method_name: "example/wait") do |_, server_context:| - scope.server.run(["wait-for", "-S", "protocol-ready", ";", "wait-for", "protocol-held"], timeout: 0.5) + scope.server.run(["wait-for", "-S", "protocol-ready", ";", "wait-for", "protocol-held"], timeout: 5) {finished: true} rescue LibTmux::Cancelled => failure cancellations << failure {cancelled: true} end send_request.call(4, "example/wait", {_meta: envelope}) - scope.server.wait_for("protocol-ready", timeout: 0.5) + scope.server.wait_for("protocol-ready", timeout: 5) client_input.write(JSON.generate({jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 4}}) + "\n") send_request.call(5, "tools/call", {name: "tmux_capabilities", arguments: {}, _meta: envelope}) Example.check(receive.call("tmux_capabilities after cancellation").fetch("id") == 5, "cancelled request blocked protocol reader") - failure = parent.with_timeout(0.5) { cancellations.pop } + failure = parent.with_timeout(Example::MCP_RESPONSE_TIMEOUT) { cancellations.pop } Example.check(failure.delivery == :possibly_sent, "cancellation claimed no dispatch") Example.raises(Errno::ECHILD) { Process.waitpid(failure.pid, Process::WNOHANG) } ensure failure = $! cleanup = [-> { client_input&.close unless client_input&.closed? }, - -> { runner&.wait(timeout: 0.5) }, -> { transport&.close }, -> { application&.close }] + -> { runner&.wait(timeout: 5) }, -> { transport&.close }, -> { application&.close }] cleanup.concat([input, output, client_output].compact.map { |io| -> { io.close unless io.closed? } }) cleanup.each do |action| action.call diff --git a/examples/support.rb b/examples/support.rb index 812b7a85..714cb205 100644 --- a/examples/support.rb +++ b/examples/support.rb @@ -6,7 +6,7 @@ module Example MCP_STARTUP_TIMEOUT = 10 MCP_RESPONSE_TIMEOUT = 5 - MCP_SHUTDOWN_TIMEOUT = 2 + MCP_SHUTDOWN_TIMEOUT = 5 class FrameReader MAX_BYTES = 1 << 20 diff --git a/test/integration/async_test.rb b/test/integration/async_test.rb index 087800d3..4725a831 100644 --- a/test/integration/async_test.rb +++ b/test/integration/async_test.rb @@ -66,7 +66,7 @@ def test_process_facade_yields_to_the_client_that_releases_a_wait LibTmux::Server.open(socket_path: fixture.socket_path) do |source| ref = source.list_panes.first.ref Async do |parent| - parent.with_timeout(0.5) do + parent.with_timeout(HANG_GUARD_SECONDS) do LibTmux::Async.open(parent: parent, server: source) do |scope| assert_equal ref, scope.server.pane(ref).ref waiting = parent.async do @@ -119,7 +119,7 @@ def test_binary_pipe_flood_and_partial_input_stay_on_the_scheduler_thread exit(data == "\\0\\xFF".b * 131072 ? 17 : 99) RUBY trace.enable - result = scope.__send__(:execute, ruby(code), input: input, timeout: 0.5) + result = scope.__send__(:execute, ruby(code), input: input, timeout: HANG_GUARD_SECONDS) trace.disable assert_equal 17, result.status.exitstatus assert_equal "\xFF".b * 131_072, result.stdout @@ -264,7 +264,7 @@ def test_repeated_caller_cancellation_reaps_a_child_ignoring_term ensure trace&.disable release << true if release - observer&.join(0.5) + observer&.join(HANG_GUARD_SECONDS) reaping&.close notify&.close peer&.close @@ -355,7 +355,7 @@ def test_map_failure_survives_repeated_cancellation_while_siblings_retire ensure trace&.disable release << true if release - observer&.join(0.5) + observer&.join(HANG_GUARD_SECONDS) reaping&.close notify&.close peer&.close @@ -428,7 +428,7 @@ def test_observed_exit_wins_token_cancellation_before_reaping ensure trace&.disable released << true if released - observer&.join(0.5) + observer&.join(HANG_GUARD_SECONDS) cancel&.close end end @@ -552,17 +552,17 @@ def test_control_pipeline_preserves_reply_ownership_and_cancel_delivery result end first = parent.async do - control.exchange("wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first", timeout: 0.5, cancel: token) + control.exchange("wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first", timeout: HANG_GUARD_SECONDS, cancel: token) rescue LibTmux::Error => error error end assert scope.server.run(["wait-for", "pipeline-ready"]).success? second = parent.async do - control.exchange("display-message -p pipeline-second", timeout: 0.5) + control.exchange("display-message -p pipeline-second", timeout: HANG_GUARD_SECONDS) rescue LibTmux::Error => error error end - assert Fiber.scheduler.io_wait(reader, IO::READABLE, 0.2), "second request bytes waited for the first reply" + assert Fiber.scheduler.io_wait(reader, IO::READABLE, HANG_GUARD_SECONDS), "second request bytes waited for the first reply" refute first.finished? refute second.finished? assert_respond_to control, :diagnostics @@ -609,12 +609,12 @@ def test_control_overflow_and_tail_gaps_do_not_block_replies assert reliable.diagnostics.fetch(:overflowed) assert tail.diagnostics.fetch(:gap_pending) assert_equal 3, control.diagnostics.fetch(:subscription_count) - assert_instance_of LibTmux::ControlEvent, reliable.next(timeout: 0.5) - assert_raises(LibTmux::SubscriptionOverflow) { reliable.next(timeout: 0.5) } - gap = tail.next(timeout: 0.5) + assert_instance_of LibTmux::ControlEvent, reliable.next(timeout: HANG_GUARD_SECONDS) + assert_raises(LibTmux::SubscriptionOverflow) { reliable.next(timeout: HANG_GUARD_SECONDS) } + gap = tail.next(timeout: HANG_GUARD_SECONDS) assert_equal :gap, gap.kind assert_operator gap.dropped_bytes, :>, 0 - assert_instance_of LibTmux::ControlEvent, tail.next(timeout: 0.5) + assert_instance_of LibTmux::ControlEvent, tail.next(timeout: HANG_GUARD_SECONDS) failure = Thread.new { control.exchange("display-message -p wrong") rescue $! }.value assert_instance_of LibTmux::ClosedError, failure assert_instance_of LibTmux::ClosedError, Thread.new { control.diagnostics rescue $! }.value @@ -787,20 +787,20 @@ def test_control_flow_and_explicit_reconnect_report_loss_on_the_owning_scope observer = scope.server.open_control(session: session) stream = control.subscribe(pane_id: "%0") witness = observer.subscribe(pane_id: "%0") - observer.exchange("display-message -p observer-ready", timeout: 0.5) - assert_instance_of LibTmux::GuardedReply, control.pause_output(pane_id: "%0", timeout: 0.5) - pause = stream.next(timeout: 0.5) + observer.exchange("display-message -p observer-ready", timeout: HANG_GUARD_SECONDS) + assert_instance_of LibTmux::GuardedReply, control.pause_output(pane_id: "%0", timeout: HANG_GUARD_SECONDS) + pause = stream.next(timeout: HANG_GUARD_SECONDS) assert_includes [:pause, :pause_requested], pause.reason assert_nil pause.dropped_bytes scope.server.run(["send-keys", "-t", "%0", "-l", "async-missed\n"]) - loop { break if witness.next(timeout: 0.5).data&.include?("async-missed") } - control.resume_output(pane_id: "%0", timeout: 0.5) - resume = stream.next(timeout: 0.5) + loop { break if witness.next(timeout: HANG_GUARD_SECONDS).data&.include?("async-missed") } + control.resume_output(pane_id: "%0", timeout: HANG_GUARD_SECONDS) + resume = stream.next(timeout: HANG_GUARD_SECONDS) assert_includes [:resume, :resume_requested], resume.reason scope.server.run(["send-keys", "-t", "%0", "-l", "async-resumed\n"]) observed = +"".b loop do - event = stream.next(timeout: 0.5) + event = stream.next(timeout: HANG_GUARD_SECONDS) assert_equal :output, event.kind observed << event.data break if observed.include?("async-resumed") @@ -808,13 +808,13 @@ def test_control_flow_and_explicit_reconnect_report_loss_on_the_owning_scope refute_includes observed, "async-missed" control.close fresh = scope.server.open_control(session: session, reconnect: control) - gap = fresh.events.next(timeout: 0.5) + gap = fresh.events.next(timeout: HANG_GUARD_SECONDS) assert_equal :reconnect, gap.reason assert_equal control.generation, gap.previous_generation refute_equal control.generation, gap.generation assert_equal fresh.generation, fresh.events.generation assert_nil gap.dropped_bytes - fresh.exchange("display-message -p renewed", timeout: 0.5) + fresh.exchange("display-message -p renewed", timeout: HANG_GUARD_SECONDS) fresh.close observer.close [control, fresh, observer].each do |connection| diff --git a/test/integration/capture_semantics_test.rb b/test/integration/capture_semantics_test.rb index 241ec08e..28b4a5e3 100644 --- a/test/integration/capture_semantics_test.rb +++ b/test/integration/capture_semantics_test.rb @@ -39,7 +39,7 @@ def test_capture_preserves_requested_screen_content_and_distinguishes_mode_and_a assert_equal "20:8\n", pane.display('#{pane_width}:#{pane_height}').text usage = server.run(["list-commands", "-F", '#{command_list_usage}', "capture-pane"]).text flags = usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.join - assert IO.select([listener], nil, nil, 0.5), "screen program did not connect" + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "screen program did not connect" channel = listener.accept render(channel, "zero\r\n\e[31mRED\e[0m \r\nabcdefghijklmnopqrstUV\r\ntail\r\n") assert_equal "zero\nRED\nabcdefghijklmnopqrst\nUV\ntail\n", pane.capture(start: 0, finish: 4).stdout @@ -81,12 +81,12 @@ def test_capture_preserves_requested_screen_content_and_distinguishes_mode_and_a pending = "\e[31" if control_supported?(server) server.open_control(session: session.ref) do |control| - control.exchange("display-message -p ready", timeout: 0.5) + control.exchange("display-message -p ready", timeout: HANG_GUARD_SECONDS) events = control.subscribe(pane_id: pane.id) channel.write([pending.bytesize | 0x80000000].pack("N") + pending) output = +"".b until output.include?(pending) - event = events.next(timeout: 0.5) + event = events.next(timeout: HANG_GUARD_SECONDS) output << event.data if event.kind == :output end end @@ -136,7 +136,7 @@ def test_copy_source_scroll_selection_exit_and_mouse_context_have_observable_eff source = session.list_panes.first target = session.new_window(name: "copy-target", command: ["/bin/cat"]).list_panes.first server.run(["set-option", "-w", "-t", target.id, "mode-keys", "vi"]) - assert IO.select([listener], nil, nil, 0.5), "copy source did not connect" + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "copy source did not connect" channel = listener.accept render(channel, (0...24).map { |index| "line%02d\r\n" % index }.join) target.copy_mode(source: source.ref, scroll_up: true) @@ -197,7 +197,7 @@ def screen_program(path) def render(channel, content) channel.write([content.bytesize].pack("N") + content) - assert IO.select([channel], nil, nil, 0.5), "tmux did not acknowledge the rendered screen" + assert IO.select([channel], nil, nil, HANG_GUARD_SECONDS), "tmux did not acknowledge the rendered screen" assert_equal "R", channel.read(1) end end diff --git a/test/integration/control_test.rb b/test/integration/control_test.rb index ffb64b10..e4619289 100644 --- a/test/integration/control_test.rb +++ b/test/integration/control_test.rb @@ -30,7 +30,7 @@ def test_boundaries_preserve_groups_aliases_hooks_and_protocol_looking_payload with_control do |fixture, _, control| fixture.tmux("set-option", "-s", "command-alias[99]", "probe=display-message -p alias") fixture.tmux("set-hook", "-g", "command-error", "display-message -p error-hook") - reply = control.exchange("probe ; kill-session -t does-not-exist ; display-message -p never", timeout: 0.5) + reply = control.exchange("probe ; kill-session -t does-not-exist ; display-message -p never", timeout: HANG_GUARD_SECONDS) assert_instance_of LibTmux::GuardedReply, reply assert_equal :boundary_window, reply.attribution refute_respond_to reply, :success? @@ -38,9 +38,9 @@ def test_boundaries_preserve_groups_aliases_hooks_and_protocol_looking_payload assert_includes body, "alias\n" refute_includes body, "never\n" assert reply.blocks.any? { |block| block.terminator == :error } - fake = control.exchange("display-message -p 'parse error: unknown command: libtmux_boundary_guess'", timeout: 0.5) + fake = control.exchange("display-message -p 'parse error: unknown command: libtmux_boundary_guess'", timeout: HANG_GUARD_SECONDS) assert_includes fake.blocks.map(&:body).join, "libtmux_boundary_guess" - assert_equal "ok\n", control.exchange("display-message -p ok", timeout: 0.5).blocks.last.body + assert_equal "ok\n", control.exchange("display-message -p ok", timeout: HANG_GUARD_SECONDS).blocks.last.body end end @@ -49,14 +49,14 @@ def test_native_pause_and_resume_preserve_prefix_and_report_unknown_loss LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0") do |observer| stream = control.subscribe(pane_id: "%0") witness = observer.subscribe(pane_id: "%0") - observer.exchange("display-message -p observer-ready", timeout: 0.5) + observer.exchange("display-message -p observer-ready", timeout: HANG_GUARD_SECONDS) fixture.tmux("send-keys", "-t", "%0", "-l", "prefix-marker\n") - loop { break if witness.next(timeout: 0.5).data&.include?("prefix-marker") } + loop { break if witness.next(timeout: HANG_GUARD_SECONDS).data&.include?("prefix-marker") } - assert_instance_of LibTmux::GuardedReply, control.pause_output(pane_id: "%0", timeout: 0.5) + assert_instance_of LibTmux::GuardedReply, control.pause_output(pane_id: "%0", timeout: HANG_GUARD_SECONDS) prefix = [] loop do - event = stream.next(timeout: 0.5) + event = stream.next(timeout: HANG_GUARD_SECONDS) prefix << event break if event.kind == :gap end @@ -65,17 +65,17 @@ def test_native_pause_and_resume_preserve_prefix_and_report_unknown_loss assert_nil prefix.last.dropped_bytes fixture.tmux("send-keys", "-t", "%0", "-l", "missed-marker\n") - loop { break if witness.next(timeout: 0.5).data&.include?("missed-marker") } - reply = control.resume_output(pane_id: "%0", timeout: 0.5) + loop { break if witness.next(timeout: HANG_GUARD_SECONDS).data&.include?("missed-marker") } + reply = control.resume_output(pane_id: "%0", timeout: HANG_GUARD_SECONDS) refute_respond_to reply, :success? - resumed = stream.next(timeout: 0.5) + resumed = stream.next(timeout: HANG_GUARD_SECONDS) assert_includes [:resume, :resume_requested], resumed.reason assert_equal "%0", resumed.pane_id assert_nil resumed.dropped_bytes fixture.tmux("send-keys", "-t", "%0", "-l", "resumed-marker\n") output = +"".b loop do - event = stream.next(timeout: 0.5) + event = stream.next(timeout: HANG_GUARD_SECONDS) assert_equal :output, event.kind output << event.data break if output.include?("resumed-marker") @@ -95,7 +95,7 @@ def test_explicit_reconnect_has_a_new_generation_and_gap_without_replay assert_raises(ArgumentError) do LibTmux::ControlConnection.__send__(:new, binding: pin, session_id: "$0", reconnect: control) end - control.exchange("new-window -d -n once", timeout: 0.5) + control.exchange("new-window -d -n once", timeout: HANG_GUARD_SECONDS) old_generation, old_pid = control.generation, control.pid control.close assert_raises(Errno::ECHILD) { Process.waitpid(old_pid, Process::WNOHANG) } @@ -103,7 +103,7 @@ def test_explicit_reconnect_has_a_new_generation_and_gap_without_replay refute_equal old_generation, fresh.generation assert_equal old_generation, fresh.previous_generation [fresh.events, fresh.subscribe(pane_id: "%0")].each do |stream| - gap = stream.next(timeout: 0.5) + gap = stream.next(timeout: HANG_GUARD_SECONDS) assert_equal :gap, gap.kind assert_equal :reconnect, gap.reason assert_equal old_generation, gap.previous_generation @@ -112,7 +112,7 @@ def test_explicit_reconnect_has_a_new_generation_and_gap_without_replay assert_nil gap.dropped_bytes assert_nil gap.lost_sequences end - reply = fresh.exchange(%q{list-windows -F '#{window_name}'}, timeout: 0.5) + reply = fresh.exchange(%q{list-windows -F '#{window_name}'}, timeout: HANG_GUARD_SECONDS) assert_equal 1, reply.blocks.flat_map { |block| block.body.lines }.count("once\n") end other = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) @@ -137,20 +137,20 @@ def test_cancelled_flow_request_reports_uncertain_loss_only_after_dispatch fixture.tmux("set-option", "-s", "command-alias[99]", "refresh-client=wait-for -S flow-started ; wait-for flow-held ; refresh") task = Thread.new do - control.pause_output(pane_id: "%0", cancel: token, timeout: 0.5) + control.pause_output(pane_id: "%0", cancel: token, timeout: HANG_GUARD_SECONDS) rescue LibTmux::Cancelled => failure failure end fixture.tmux("wait-for", "flow-started") token.cancel assert_equal :possibly_sent, task.value.delivery - gap = stream.next(timeout: 0.5) + gap = stream.next(timeout: HANG_GUARD_SECONDS) assert_equal :pause_requested, gap.reason assert_nil gap.dropped_bytes control.close assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } ensure - task&.join(0.5) + task&.join(HANG_GUARD_SECONDS) token&.close stream&.close end @@ -159,14 +159,14 @@ def test_cancelled_flow_request_reports_uncertain_loss_only_after_dispatch def test_wait_holds_boundary_until_an_independent_client_releases_it with_control do |fixture, _, control| thread = Thread.new do - control.exchange("wait-for -S control-started ; wait-for control-release ; display-message -p released", timeout: 0.5) + control.exchange("wait-for -S control-started ; wait-for control-release ; display-message -p released", timeout: HANG_GUARD_SECONDS) end fixture.tmux("wait-for", "control-started") assert thread.alive?, "WAIT must keep the request boundary pending after its successful guard" fixture.tmux("wait-for", "-S", "control-release") assert_includes thread.value.blocks.map(&:body).join, "released\n" ensure - thread&.join(0.5) + thread&.join(HANG_GUARD_SECONDS) end end @@ -174,7 +174,7 @@ def test_control_retains_server_binding_and_close_reaps_only_owned_client with_control do |fixture, pin, control| pid = control.pid pin.close - assert_equal "retained\n", control.exchange("display-message -p retained", timeout: 0.5).blocks.last.body + assert_equal "retained\n", control.exchange("display-message -p retained", timeout: HANG_GUARD_SECONDS).blocks.last.body control.close assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } assert fixture.tmux("has-session", "-t", "fixture").last.success? @@ -199,11 +199,11 @@ def test_pipeline_writes_complete_requests_before_prior_replies result end first = Thread.new do - control.exchange("pipeline-probe", timeout: 0.5) + control.exchange("pipeline-probe", timeout: HANG_GUARD_SECONDS) end fixture.tmux("wait-for", "pipeline-ready") - second = Thread.new { control.exchange("display-message -p pipeline-second", timeout: 0.5) } - assert IO.select([reader], nil, nil, 0.2), "second request bytes waited for the first reply" + second = Thread.new { control.exchange("display-message -p pipeline-second", timeout: HANG_GUARD_SECONDS) } + assert IO.select([reader], nil, nil, HANG_GUARD_SECONDS), "second request bytes waited for the first reply" assert first.alive?, "the first reply must remain pending at the wire witness" assert second.alive?, "tmux must retain the second request behind WAIT" assert_respond_to control, :diagnostics @@ -225,7 +225,7 @@ def test_pipeline_writes_complete_requests_before_prior_replies assert_empty control.instance_variable_get(:@requests) ensure fixture.tmux("wait-for", "-S", "pipeline-held") if first&.alive? - [first, second].compact.each { |thread| thread.join(0.5) } + [first, second].compact.each { |thread| thread.join(HANG_GUARD_SECONDS) } input&.singleton_class&.remove_method(:write_nonblock) [reader, writer].compact.each(&:close) end @@ -235,9 +235,9 @@ def test_slow_subscriber_overflows_without_blocking_replies with_control do |fixture, _, control| events = control.subscribe(max_events: 1, max_bytes: 1024) 3.times { |index| fixture.tmux("rename-window", "-t", "@0", "window#{index}") } - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body - assert_instance_of LibTmux::ControlEvent, events.next(timeout: 0.5) - assert_raises(LibTmux::SubscriptionOverflow) { events.next(timeout: 0.5) } + assert_equal "alive\n", control.exchange("display-message -p alive", timeout: HANG_GUARD_SECONDS).blocks.last.body + assert_instance_of LibTmux::ControlEvent, events.next(timeout: HANG_GUARD_SECONDS) + assert_raises(LibTmux::SubscriptionOverflow) { events.next(timeout: HANG_GUARD_SECONDS) } end end @@ -255,7 +255,7 @@ def test_dispatched_cancellation_closes_connection_and_preserves_server end) token = LibTmux::Internal::Cancellation.new thread = Thread.new do - control.exchange("display-message -p cancelled-prefix ; wait-for -S cancellation-started ; wait-for blocked", timeout: 0.5, cancel: token) + control.exchange("display-message -p cancelled-prefix ; wait-for -S cancellation-started ; wait-for blocked", timeout: HANG_GUARD_SECONDS, cancel: token) rescue LibTmux::Cancelled => error error end @@ -278,7 +278,7 @@ def test_dispatched_cancellation_closes_connection_and_preserves_server ensure release << true token&.close - thread&.join(0.5) + thread&.join(HANG_GUARD_SECONDS) end end @@ -295,16 +295,16 @@ def test_pending_admission_is_bounded_and_cancellation_before_admission_is_not_s error = assert_raises(LibTmux::Cancelled) { control.exchange("display-message -p never", cancel: token) } assert_equal :not_sent, error.delivery thread = Thread.new do - control.exchange("wait-for -S capacity-started ; wait-for capacity-release", timeout: 0.5) + control.exchange("wait-for -S capacity-started ; wait-for capacity-release", timeout: HANG_GUARD_SECONDS) end fixture.tmux("wait-for", "capacity-started") assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess") } fixture.tmux("wait-for", "-S", "capacity-release") assert_instance_of LibTmux::GuardedReply, thread.value - assert_equal "still-open\n", control.exchange("display-message -p still-open", timeout: 0.5).blocks.last.body + assert_equal "still-open\n", control.exchange("display-message -p still-open", timeout: HANG_GUARD_SECONDS).blocks.last.body ensure token&.close - thread&.join(0.5) + thread&.join(HANG_GUARD_SECONDS) end end @@ -322,7 +322,7 @@ def test_repeated_thread_cancellation_preserves_first_failure_during_retirement end) first = Interrupt.new("first cancellation") thread = Thread.new do - control.exchange("wait-for -S interrupt-started ; wait-for interrupt-blocked", timeout: 0.5) + control.exchange("wait-for -S interrupt-started ; wait-for interrupt-blocked", timeout: HANG_GUARD_SECONDS) rescue Exception => failure failure end @@ -336,15 +336,15 @@ def test_repeated_thread_cancellation_preserves_first_failure_during_retirement assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } ensure cleanup_release << true - thread&.join(0.5) + thread&.join(HANG_GUARD_SECONDS) end end def test_detach_closes_pending_request_without_waiting_for_deadline with_control do |_, _, control| - control.exchange("detach-client", timeout: 0.5) - loop { break if control.events.next(timeout: 0.5).raw.start_with?("%exit") } - assert_raises(LibTmux::ClosedError) { control.exchange("display-message -p detached", timeout: 0.5) } + control.exchange("detach-client", timeout: HANG_GUARD_SECONDS) + loop { break if control.events.next(timeout: HANG_GUARD_SECONDS).raw.start_with?("%exit") } + assert_raises(LibTmux::ClosedError) { control.exchange("display-message -p detached", timeout: HANG_GUARD_SECONDS) } control.close assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } end @@ -387,10 +387,10 @@ def test_forked_child_rejects_inherited_streams_and_detaches_all_local_pipes exit! 0 end writer.close - assert IO.select([reader], nil, nil, 0.5), "fork check must report through its pipe" + assert IO.select([reader], nil, nil, HANG_GUARD_SECONDS), "fork check must report through its pipe" assert_equal "closed", reader.read Process.wait(child) - assert_equal "parent\n", control.exchange("display-message -p parent", timeout: 0.5).blocks.last.body + assert_equal "parent\n", control.exchange("display-message -p parent", timeout: HANG_GUARD_SECONDS).blocks.last.body ensure [reader, writer].compact.each { |io| io.close unless io.closed? } Process.wait(child) rescue Errno::ECHILD @@ -435,7 +435,7 @@ def check_failed_observation(late: false) end control = LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0") wait_class.define_singleton_method(:new, original_new) - assert_equal "ready\n", control.events.next(timeout: 0.5).raw + assert_equal "ready\n", control.events.next(timeout: HANG_GUARD_SECONDS).raw ENV["RUBYOPT"] = original_rubyopt if late observer = control.instance_variable_get(:@child) @@ -457,7 +457,7 @@ def check_failed_observation(late: false) gate << true if gate if control control.send(:signal, "KILL") - control.instance_variable_get(:@worker)&.join(0.5) + control.instance_variable_get(:@worker)&.join(HANG_GUARD_SECONDS) end pin&.close end @@ -475,22 +475,22 @@ def test_completed_unconsumed_requests_still_count_against_admission super(request, type, message) end end) - thread = Thread.new { control.exchange("display-message -p completed", timeout: 0.5) } + thread = Thread.new { control.exchange("display-message -p completed", timeout: HANG_GUARD_SECONDS) } cleanup_entered.pop assert_respond_to control, :diagnostics retained = control.diagnostics assert_equal [1, 0, 0], retained.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) assert_operator retained.fetch(:retained_reply_bytes), :>=, "completed\n".bytesize - assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess", timeout: 0.5) } + assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess", timeout: HANG_GUARD_SECONDS) } cleanup_release << true reply = thread.value assert_equal "completed\n", reply.blocks.last.body assert_equal reply.blocks.sum(&:bytesize), retained.fetch(:retained_reply_bytes) assert_equal [0, 0], control.diagnostics.values_at(:reserved_wire_bytes, :retained_reply_bytes) - assert_equal "next\n", control.exchange("display-message -p next", timeout: 0.5).blocks.last.body + assert_equal "next\n", control.exchange("display-message -p next", timeout: HANG_GUARD_SECONDS).blocks.last.body ensure cleanup_release << true - thread&.join(0.5) + thread&.join(HANG_GUARD_SECONDS) end end end diff --git a/test/integration/creation_test.rb b/test/integration/creation_test.rb index 3d6c59b1..5a488c70 100644 --- a/test/integration/creation_test.rb +++ b/test/integration/creation_test.rb @@ -73,14 +73,14 @@ def test_respawn_keeps_entity_identity_and_replaces_process_directory_and_enviro assert_raises(LibTmux::CommandError) { sibling.respawn(command: ["/bin/cat"]) } assert_equal old_pid, sibling.display('#{pane_pid}').text sibling.respawn(command: child_command(listener.path), kill: true, cwd: child_directory, - environment: {"ROOT" => "pane"}, timeout: 0.5) + environment: {"ROOT" => "pane"}, timeout: HANG_GUARD_SECONDS) assert_equal [File.realpath(child_directory), "pane", nil, nil], receive(listener) refute_equal old_pid, sibling.display('#{pane_pid}').text assert_equal [original.id, sibling.id], window.list_panes.map(&:id) old_pid = original.display('#{pane_pid}').text window.respawn(command: child_command(listener.path), kill: true, cwd: directory, - environment: {"ROOT" => "window"}, timeout: 0.5) + environment: {"ROOT" => "window"}, timeout: HANG_GUARD_SECONDS) assert_equal [File.realpath(directory), "window", nil, nil], receive(listener) assert_equal [original.id], window.list_panes.map(&:id) refute_equal old_pid, original.display('#{pane_pid}').text @@ -129,10 +129,10 @@ def child_command(path) end def receive(listener) - assert IO.select([listener], nil, nil, 0.5), "created pane did not report its environment" + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "created pane did not report its environment" client = listener.accept begin - assert IO.select([client], nil, nil, 0.5), "created pane receipt was empty" + assert IO.select([client], nil, nil, HANG_GUARD_SECONDS), "created pane receipt was empty" Marshal.load(client.read) ensure client.close diff --git a/test/integration/fixture_test.rb b/test/integration/fixture_test.rb index 962b18b4..1675fda1 100644 --- a/test/integration/fixture_test.rb +++ b/test/integration/fixture_test.rb @@ -44,7 +44,7 @@ def test_failed_observer_still_retires_its_real_child child = fixture.send(:spawn_owned, Gem.ruby, "--disable=rubyopt,gems", "-e", 'trap("TERM") {}; STDOUT.write("ready\n"); STDOUT.flush; input, output = IO.pipe; input.read(1)') fixture.instance_variable_get(:@clients)[child.last.pid] = child - assert IO.select([child[1]], nil, nil, 0.5), "owned helper did not start" + assert IO.select([child[1]], nil, nil, HANG_GUARD_SECONDS), "owned helper did not start" assert_equal "ready\n", child[1].gets release << true trace.disable @@ -78,7 +78,7 @@ def test_exit_observation_keeps_the_server_pid_owned_until_cleanup server = fixture.instance_variable_get(:@server).last pid = server.pid assert fixture.tmux("kill-server").last.success? - assert server.join(0.5), "server exit was not observed" + assert server.join(HANG_GUARD_SECONDS), "server exit was not observed" LibTmux::Internal::ProcessWait.new.observe(pid) end @@ -128,7 +128,7 @@ def test_preserves_block_exception_and_reaps_owned_server LibTmuxTest::TmuxFixture.open do |fixture| directory = File.dirname(fixture.socket_path) pid = server_pid(fixture) - identity = LibTmux::Internal::ProcessExecutor.new.run(["ps", "-o", "ppid=", "-p", pid.to_s], timeout: 0.5) + identity = LibTmux::Internal::ProcessExecutor.new.run(["ps", "-o", "ppid=", "-p", pid.to_s], timeout: HANG_GUARD_SECONDS) assert identity.success? parent = Integer(identity.text.strip, 10) assert_equal Process.pid, parent, "fixture server must remain an owned child" @@ -165,7 +165,7 @@ def test_cancellation_retires_a_dispatched_client_and_its_server end assert_equal 1, clients.length, "expected one dispatched child client" worker.raise(Interrupt, "cancel fixture") - assert_raises(Interrupt) { worker.join(0.5) } + assert_raises(Interrupt) { worker.join(HANG_GUARD_SECONDS) } refute worker.alive?, "cancellation did not finish owned cleanup" refute File.exist?(File.dirname(fixture.socket_path)) [pid, *clients].each do |owned_pid| @@ -175,7 +175,7 @@ def test_cancellation_retires_a_dispatched_client_and_its_server ensure if worker&.alive? worker.kill - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) end end @@ -278,19 +278,19 @@ def test_repeated_interruption_during_cleanup_preserves_first_failure error end end - fixture = ready.pop(timeout: 0.5) + fixture = ready.pop(timeout: HANG_GUARD_SECONDS) assert fixture, "fixture did not reach its interruption barrier" worker.raise(failure) - assert cleaning.pop(timeout: 0.5), "fixture did not begin owned cleanup" + assert cleaning.pop(timeout: HANG_GUARD_SECONDS), "fixture did not begin owned cleanup" worker.raise(Interrupt, "second cancellation") release << true - assert worker.join(0.5), "repeated interruption prevented fixture cleanup" + assert worker.join(HANG_GUARD_SECONDS), "repeated interruption prevented fixture cleanup" assert_same failure, worker.value refute File.exist?(File.dirname(fixture.socket_path)) ensure release << true if release worker&.kill if worker&.alive? - worker&.join(0.5) + worker&.join(HANG_GUARD_SECONDS) end private diff --git a/test/integration/group_test.rb b/test/integration/group_test.rb index 4e6c7695..f63eb158 100644 --- a/test/integration/group_test.rb +++ b/test/integration/group_test.rb @@ -69,7 +69,7 @@ def test_cancellation_retires_the_client_without_undoing_observed_earlier_effect begin assert fixture.tmux("wait-for", "group-ready").last.success? token.cancel - assert worker.join(0.5), "cancelled group client did not retire" + assert worker.join(HANG_GUARD_SECONDS), "cancelled group client did not retire" failure = worker.value assert_instance_of LibTmux::Cancelled, failure assert_equal :possibly_sent, failure.delivery @@ -78,7 +78,7 @@ def test_cancellation_retires_the_client_without_undoing_observed_earlier_effect ensure token.cancel fixture.tmux("wait-for", "-S", "group-held") - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) token.close end end diff --git a/test/integration/identity_test.rb b/test/integration/identity_test.rb index 69bae905..9a4ab3bc 100644 --- a/test/integration/identity_test.rb +++ b/test/integration/identity_test.rb @@ -30,18 +30,18 @@ def test_repeated_constructor_cancellation_preserves_the_first_failure rescue Exception => error error end - assert ready.pop(timeout: 0.5), "binding did not reach its cancellation barrier" + assert ready.pop(timeout: HANG_GUARD_SECONDS), "binding did not reach its cancellation barrier" worker.raise(first) - assert cleanup_ready.pop(timeout: 0.5), "binding did not start cleanup" + assert cleanup_ready.pop(timeout: HANG_GUARD_SECONDS), "binding did not start cleanup" worker.raise(later) release << true - assert worker.join(0.5), "binding cleanup did not finish" + assert worker.join(HANG_GUARD_SECONDS), "binding cleanup did not finish" assert_same first, worker.value refute Dir.exist?(directory) ensure release << true if release worker&.kill if worker&.alive? - worker&.join(0.5) + worker&.join(HANG_GUARD_SECONDS) File.unlink(File.join(directory, "socket")) if directory && File.socket?(File.join(directory, "socket")) Dir.rmdir(directory) if directory && Dir.exist?(directory) end @@ -65,7 +65,7 @@ def test_a_fork_cannot_use_or_retire_the_parent_binding exit! 0 end writer.close - assert IO.select([reader], nil, nil, 0.5), "forked binding did not settle" + assert IO.select([reader], nil, nil, HANG_GUARD_SECONDS), "forked binding did not settle" assert_equal "ok", reader.read(2) status = Process.wait2(child).last child = nil diff --git a/test/integration/mcp_capture_test.rb b/test/integration/mcp_capture_test.rb index d16915c6..46b86369 100644 --- a/test/integration/mcp_capture_test.rb +++ b/test/integration/mcp_capture_test.rb @@ -152,10 +152,10 @@ def with_output(scope, pane, session: scope.server.list_sessions.first, expected end scope.server.open_control(session: session.ref) do |control| events = control.subscribe(pane_id: pane.id) - control.exchange("display-message -p ready", timeout: 0.5) + control.exchange("display-message -p ready", timeout: HANG_GUARD_SECONDS) yield received = +"".b - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + HANG_GUARD_SECONDS loop do event = events.next(timeout: deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)) next unless event.kind == :output diff --git a/test/integration/mcp_cli_test.rb b/test/integration/mcp_cli_test.rb index d9a1d5e4..81a0fa02 100644 --- a/test/integration/mcp_cli_test.rb +++ b/test/integration/mcp_cli_test.rb @@ -80,7 +80,7 @@ def test_explicit_enrollment_file_serves_protocol_and_retires_pending_accept_on_ assert File.file?(words[1]) assert File.socket?(words[2]) input.close - assert worker.join(0.5), "pending shell enrollment prevented EOF retirement" + assert worker.join(HANG_GUARD_SECONDS), "pending shell enrollment prevented EOF retirement" assert_equal 0, worker.value, errors.string refute File.exist?(setup) refute File.exist?(words[2]) @@ -89,9 +89,9 @@ def test_explicit_enrollment_file_serves_protocol_and_retires_pending_accept_on_ ensure trace.disable input.close unless input.closed? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) worker.raise(Interrupt) if worker.alive? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) [reader, output, writer].each { |io| io.close unless io.closed? } end end @@ -131,7 +131,7 @@ def test_cli_serves_real_protocol_and_eof_preserves_the_borrowed_daemon assert_equal "test", result.fetch("data").fetch("endpoint") trace.enable input.close - assert worker.join(0.5), "MCP CLI did not retire after EOF" + assert worker.join(HANG_GUARD_SECONDS), "MCP CLI did not retire after EOF" assert_equal 0, worker.value assert_equal 1, application_closes.length refute_nil application_closes.first @@ -140,9 +140,9 @@ def test_cli_serves_real_protocol_and_eof_preserves_the_borrowed_daemon ensure trace.disable input.close unless input.closed? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) worker.raise(Interrupt) if worker.alive? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) [reader, output, writer].each { |io| io.close unless io.closed? } end end @@ -291,7 +291,7 @@ def test_explicitly_sourced_cli_setup_runs_a_script_through_the_protocol assert_equal "ready", repeated.fetch("data").fetch("stdout").fetch("data") refute_equal result.fetch("authorization").fetch("run_id"), repeated.fetch("data").fetch("authorization").fetch("run_id") input.close - assert worker.join(0.5), "enrolled CLI did not retire after EOF" + assert worker.join(HANG_GUARD_SECONDS), "enrolled CLI did not retire after EOF" assert_equal 0, worker.value, errors.string assert_empty errors.string refute File.exist?(setup) @@ -300,9 +300,9 @@ def test_explicitly_sourced_cli_setup_runs_a_script_through_the_protocol assert_empty server.list_clients ensure input.close unless input.closed? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) worker.raise(Interrupt) if worker.alive? - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) [reader, input, output, writer, channel].compact.each { |io| io.close unless io.closed? } end end diff --git a/test/integration/mcp_cursor_identity_test.rb b/test/integration/mcp_cursor_identity_test.rb index 27990cc8..bdc20ca1 100644 --- a/test/integration/mcp_cursor_identity_test.rb +++ b/test/integration/mcp_cursor_identity_test.rb @@ -109,14 +109,14 @@ def test_process_death_remains_readable_after_owned_child_is_reaped scope.__send__(:execute, [Gem.ruby, "--disable=rubyopt,gems", "-e", code, listener.path]) end connection = pid = nil - ::Async::Task.current.with_timeout(0.5) do + ::Async::Task.current.with_timeout(HANG_GUARD_SECONDS) do connection = listener.accept pid = Integer(connection.gets, 10) end snapshot = scope.server.snapshot identity = LibTmux::MCP.const_get(:ProcessIdentity).acquire(scope.server, server_pid: snapshot.server_info.fetch(:pid), pane_pid: pid, - budget: scope.server.__send__(:operation_budget, 0.5, nil)) + budget: scope.server.__send__(:operation_budget, HANG_GUARD_SECONDS, nil)) klass = LibTmux::MCP.const_get(:ProcessIdentity) native = klass.method(:native) faults = [:interrupted] diff --git a/test/integration/mcp_enrollment_test.rb b/test/integration/mcp_enrollment_test.rb index 0c21fe8c..fea94889 100644 --- a/test/integration/mcp_enrollment_test.rb +++ b/test/integration/mcp_enrollment_test.rb @@ -19,10 +19,10 @@ def test_enrolled_borrowed_shell_prepares_without_executing_and_observes_one_use assert LibTmux::MCP.const_defined?(:EnrollmentRegistry, false), 'explicit shell enrollment is not implemented' with_shell do |registry, pane, channel, scope, source| digest = Digest::SHA256.hexdigest('exit 7') - prepared = registry.prepare(pane.ref, script_digest: digest, timeout: 0.5) + prepared = registry.prepare(pane.ref, script_digest: digest, timeout: HANG_GUARD_SECONDS) refute prepared.authorized? assert_equal pane.id, prepared.reference.id - grant = prepared.authorize(timeout: 0.5) + grant = prepared.authorize(timeout: HANG_GUARD_SECONDS) assert_equal 'authorized', grant.fetch('state') assert_equal digest, grant.fetch('script_digest') assert_equal pane.ref.binding_key, grant.fetch('server_generation') @@ -32,7 +32,7 @@ def test_enrolled_borrowed_shell_prepares_without_executing_and_observes_one_use nonce = prepared.instance_variable_get(:@authorization) assert_raises(LibTmux::DeadlineExceeded) { scope.server.run(['wait-for', nonce], timeout: 0.03) } scope.server.run(['wait-for', '-S', nonce]) - assert_raises(LibTmux::ClosedError) { prepared.authorize(timeout: 0.5) } + assert_raises(LibTmux::ClosedError) { prepared.authorize(timeout: HANG_GUARD_SECONDS) } prepared.close registry.close assert source.run(['has-session', '-t', 'enrolled']).success? @@ -44,15 +44,15 @@ def test_partial_editor_refuses_without_changing_input_and_pregrant_cancel_has_n with_shell do |registry, pane, _channel, _scope, _source| pane.send_text('unfinished-input') failure = assert_raises(LibTmux::UnsupportedFeatureError) do - registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) end assert_equal :not_sent, failure.delivery assert_includes pane.capture.text, 'unfinished-input' pane.send_keys('C-u') - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) token = LibTmux::Internal::Cancellation.new token.cancel - failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } + failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: HANG_GUARD_SECONDS, cancel: token) } assert_equal :not_sent, failure.delivery refute prepared.authorized? prepared.close @@ -63,16 +63,16 @@ def test_partial_editor_refuses_without_changing_input_and_pregrant_cancel_has_n def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original_recipient with_shell do |registry, pane, _channel, scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) pane.respawn(command: ['cat'], kill: true) - failure = assert_raises(LibTmux::TargetNotFoundError) { prepared.authorize(timeout: 0.5) } + failure = assert_raises(LibTmux::TargetNotFoundError) { prepared.authorize(timeout: HANG_GUARD_SECONDS) } assert_equal :not_sent, failure.delivery refute prepared.authorized? prepared.close assert scope.server.snapshot.panes.find { |record| record.id == pane.id } end with_shell do |registry, pane, _channel, scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) old_pid = scope.server.snapshot.panes.find { |record| record.id == pane.id }.pid original = registry.method(:guard) registry.define_singleton_method(:guard) do |reference, identity, budget, nonce = nil| @@ -80,7 +80,7 @@ def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original pane.respawn(command: ['cat'], kill: true) if nonce result end - receipt = prepared.authorize(timeout: 0.5) + receipt = prepared.authorize(timeout: HANG_GUARD_SECONDS) replacement = scope.server.snapshot.panes.find { |record| record.id == pane.id } refute_equal old_pid, replacement.pid assert_equal prepared.process_generation, receipt.fetch('process_generation') @@ -92,7 +92,7 @@ def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original def test_cancellation_after_the_committed_grant_keeps_its_exact_effect_receipt with_shell do |registry, pane, _channel, _scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) token = LibTmux::Internal::Cancellation.new original = registry.method(:guard) registry.define_singleton_method(:guard) do |reference, identity, budget, nonce = nil| @@ -100,7 +100,7 @@ def test_cancellation_after_the_committed_grant_keeps_its_exact_effect_receipt token.cancel if nonce result end - failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } + failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: HANG_GUARD_SECONDS, cancel: token) } assert_equal :possibly_sent, failure.delivery assert_equal 'authorized', prepared.receipt.fetch('state') assert_equal prepared.process_generation, prepared.receipt.fetch('process_generation') @@ -122,14 +122,14 @@ def test_close_cancels_a_busy_shell_preparation_and_prevents_delayed_authorizati original.call(listener, budget) end pending = Async::Task.current.async do - registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: HANG_GUARD_SECONDS) rescue Exception => error error end - Async::Task.current.with_timeout(0.5) { started.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { started.dequeue } registry.close assert pending.finished?, 'registry close must retire its active preparation' - assert_instance_of LibTmux::Cancelled, pending.wait(timeout: 0.5) + assert_instance_of LibTmux::Cancelled, pending.wait(timeout: HANG_GUARD_SECONDS) pane.send_keys('Enter') assert_equal 'busy-ended', read_line(channel) assert_equal 'ready', read_line(channel) @@ -154,7 +154,7 @@ def test_failed_enrollment_transfer_keeps_the_accepted_channel_and_identity_owne end original_close.call end - assert_raises(IOError) { registry.accept(invitation, timeout: 0.5) } + assert_raises(IOError) { registry.accept(invitation, timeout: HANG_GUARD_SECONDS) } registry.close assert accepted.closed?, 'accepted protocol channel must remain owned when invitation retirement fails' assert identity.io.closed?, 'the transferred native identity lease must remain owned' @@ -168,8 +168,8 @@ def test_failed_enrollment_transfer_keeps_the_accepted_channel_and_identity_owne def test_pending_enrollment_rejects_duplicate_reference_before_capture acceptor = lambda do |registry, invitation| - assert_raises(LibTmux::CapacityError) { registry.invite(invitation.reference, timeout: 0.5) } - registry.accept(invitation, timeout: 0.5) + assert_raises(LibTmux::CapacityError) { registry.invite(invitation.reference, timeout: HANG_GUARD_SECONDS) } + registry.accept(invitation, timeout: HANG_GUARD_SECONDS) end with_shell(acceptor: acceptor) { } end @@ -178,7 +178,7 @@ def test_authored_script_preserves_context_separates_binary_output_and_reports_n with_shell(space_paths: true) do |registry, pane, _channel, _scope, _source, directory| assert_respond_to registry, :run, 'authored execution has not been implemented' script = %(printf '%s\n' "$PWD" "$LIBTMUX_RUN_TEST_VALUE" "$TMUX_PANE"; printf 'AUTHORIZED fake marker\n'; printf '\\000\\377\\n' >&2; exit 7) - result = registry.run(pane.ref, script: script, timeout: 0.5, stdout_limit: 8192, stderr_limit: 8192) + result = registry.run(pane.ref, script: script, timeout: HANG_GUARD_SECONDS, stdout_limit: 8192, stderr_limit: 8192) assert_equal "#{directory}\nliteral-value\n#{pane.id}\nAUTHORIZED fake marker\n".b, result.stdout assert_equal "\x00\xff\n".b, result.stderr assert_equal 7, result.exit_status @@ -191,7 +191,7 @@ def test_authored_script_preserves_context_separates_binary_output_and_reports_n def test_authored_output_overflow_and_cancel_do_not_invent_completion_or_allow_parallel_runs with_shell do |registry, pane, _channel, _scope, _source, directory| failure = assert_raises(LibTmux::CapacityError) do - registry.run(pane.ref, script: "printf 123456789", timeout: 0.5, stdout_limit: 8) + registry.run(pane.ref, script: "printf 123456789", timeout: HANG_GUARD_SECONDS, stdout_limit: 8) end assert_equal :possibly_sent, failure.delivery assert_equal 'authorized', failure.run_receipt.fetch('state') @@ -202,14 +202,14 @@ def test_authored_output_overflow_and_cancel_do_not_invent_completion_or_allow_p script = "exec #{[Gem.ruby, '--disable=rubyopt,gems', '-rsocket', '-e', code, path].map { |value| "'#{value.gsub("'", %q('\''))}'" }.join(' ')}" token = LibTmux::Internal::Cancellation.new pending = Async::Task.current.async do - registry.run(pane.ref, script: script, timeout: 0.5, cancel: token) + registry.run(pane.ref, script: script, timeout: HANG_GUARD_SECONDS, cancel: token) rescue Exception => error error end child = fixture_handoff('authored script connection') { listener.accept } pid = Integer(read_line(child, stage: 'authored script PID')) failure = assert_raises(LibTmux::CapacityError) do - registry.run(pane.ref, script: 'exit 0', timeout: 0.5) + registry.run(pane.ref, script: 'exit 0', timeout: HANG_GUARD_SECONDS) end assert_equal :not_sent, failure.delivery token.cancel @@ -250,11 +250,11 @@ def test_registry_close_keeps_a_runs_final_helper_retirement_owned prepared end pending = Async::Task.current.async do - registry.run(pane.ref, script: 'exit 0', timeout: 0.5) + registry.run(pane.ref, script: 'exit 0', timeout: HANG_GUARD_SECONDS) rescue Exception => error error end - Async::Task.current.with_timeout(0.5) { entered.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { entered.dequeue } changed = registry.instance_variable_get(:@changed) original_wait = changed.method(:wait) changed.define_singleton_method(:wait) do @@ -266,24 +266,24 @@ def test_registry_close_keeps_a_runs_final_helper_retirement_owned rescue Exception => error error end - Async::Task.current.with_timeout(0.5) { waiting.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { waiting.dequeue } assert_equal 1, closes, 'registry close must not race the active run cleanup' refute closing.finished?, 'registry close must await the run cleanup owner' 2.times do closing.cancel - Async::Task.current.with_timeout(0.5) { waiting.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { waiting.dequeue } end refute closing.finished?, 'repeated cancellation must not abandon admitted cleanup' release.enqueue(true) - assert_instance_of Async::Cancel, pending.wait(timeout: 0.5) - assert_instance_of Async::Cancel, closing.wait(timeout: 0.5) + assert_instance_of Async::Cancel, pending.wait(timeout: HANG_GUARD_SECONDS) + assert_instance_of Async::Cancel, closing.wait(timeout: HANG_GUARD_SECONDS) assert_empty registry.instance_variable_get(:@runs) assert_empty registry.instance_variable_get(:@prepared) registry.close ensure release&.enqueue(true) - pending&.wait(timeout: 0.5) - closing&.wait(timeout: 0.5) + pending&.wait(timeout: HANG_GUARD_SECONDS) + closing&.wait(timeout: HANG_GUARD_SECONDS) end end @@ -307,7 +307,7 @@ def test_public_enrollment_and_sdk_run_require_opt_in_and_preserve_completion_ev require 'libtmux/mcp' with_shell(app_tools: ['tmux_run']) do |application, pane, _channel, scope, _source| readonly = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'readonly') - assert_raises(LibTmux::UnsupportedFeatureError) { readonly.invite_shell(pane.ref, timeout: 0.5) } + assert_raises(LibTmux::UnsupportedFeatureError) { readonly.invite_shell(pane.ref, timeout: HANG_GUARD_SECONDS) } denied = readonly.call('tmux_run', {}).structured_content assert_equal 'policy_denied', denied.fetch('error').fetch('code') sdk = application.sdk_server @@ -458,10 +458,10 @@ def test_failed_protocol_constructors_keep_native_references_and_socket_paths_ow private def fixture_handoff(stage) - Async::Task.current.with_timeout(2, FixtureHandoffExpired) { yield } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS, FixtureHandoffExpired) { yield } rescue FixtureHandoffExpired => error stacks = Thread.list.map { |thread| [thread.inspect, *thread.backtrace].join("\n") } - flunk "#{stage} did not complete within 2 seconds\n#{(error.backtrace + stacks).join("\n")}" + flunk "#{stage} did not complete within #{HANG_GUARD_SECONDS} seconds\n#{(error.backtrace + stacks).join("\n")}" end def read_line(io, stage: 'shell control frame') @@ -518,7 +518,7 @@ def with_shell(acceptor: nil, space_paths: false, app_tools: nil) begin ENV['TMPDIR'] = directory if space_paths registry = if app_tools - LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'enrolled', enabled_tools: app_tools, request_timeout: 0.5) + LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'enrolled', enabled_tools: app_tools, request_timeout: HANG_GUARD_SECONDS) else LibTmux::MCP.const_get(:EnrollmentRegistry).new(server: scope.server, parent: task) end @@ -528,12 +528,12 @@ def with_shell(acceptor: nil, space_paths: false, app_tools: nil) pane = scope.server.new_session(name: 'enrolled', command: ['/usr/bin/env', "ZDOTDIR=#{directory}", '/bin/zsh', '-d', '-i']).list_panes.first channel = fixture_handoff('enrollment shell connection') { listener.accept } assert_equal 'initializing', read_line(channel, stage: 'enrollment shell initialization') - invitation = app_tools ? registry.invite_shell(pane.ref, timeout: 0.5) : registry.invite(pane.ref, timeout: 0.5) + invitation = app_tools ? registry.invite_shell(pane.ref, timeout: HANG_GUARD_SECONDS) : registry.invite(pane.ref, timeout: HANG_GUARD_SECONDS) fixture_handoff('enrollment shell invitation') { channel.puts invitation.shell_arguments } enrollment = if app_tools - registry.accept_shell(invitation, timeout: 0.5) + registry.accept_shell(invitation, timeout: HANG_GUARD_SECONDS) else - acceptor ? acceptor.call(registry, invitation) : registry.accept(invitation, timeout: 0.5) + acceptor ? acceptor.call(registry, invitation) : registry.accept(invitation, timeout: HANG_GUARD_SECONDS) end assert_equal pane.id, (app_tools ? enrollment : enrollment.reference).id if enrollment assert_equal(enrollment ? 'ready' : 'refused', read_line(channel, stage: 'enrollment shell acknowledgement')) diff --git a/test/integration/mcp_mutation_test.rb b/test/integration/mcp_mutation_test.rb index f3ad88e9..d56a998d 100644 --- a/test/integration/mcp_mutation_test.rb +++ b/test/integration/mcp_mutation_test.rb @@ -31,7 +31,7 @@ def test_opt_in_sdk_mutations_create_exact_entities_and_separate_text_from_keys assert_equal "dispatch_only", sent.fetch("data").fetch("completion") refute File.exist?(result_file) assert invoke(sdk, "tmux_send", target: pane, input: {type: "keys", keys: ["Enter"]}).fetch("ok") - scope.server.wait_for("mcp-received", timeout: 0.5) + scope.server.wait_for("mcp-received", timeout: HANG_GUARD_SECONDS) assert_equal [text + "\n", File.realpath(File.dirname(fixture.socket_path)), "env;literal", "argv;literal"], Marshal.load(File.binread(result_file)) split = invoke(sdk, "tmux_create", kind: "pane", parent: pane, direction: "vertical", size: "25%", argv: ["cat"]) @@ -155,8 +155,8 @@ def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effe source.hooks.set("after-new-window", command: "wait-for -S mcp-created ; wait-for mcp-create-held", index: 93) begin pending = parent.async { invoke(sdk, "tmux_create", kind: "window", parent: session, name: "partial-effect", argv: ["cat"]) } - diagnose.call("create readiness") { scope.server.wait_for("mcp-created", timeout: 0.5) } - failure = diagnose.call("create pending result") { pending.wait(timeout: 0.5) } + diagnose.call("create readiness") { scope.server.wait_for("mcp-created", timeout: HANG_GUARD_SECONDS) } + failure = diagnose.call("create pending result") { pending.wait(timeout: HANG_GUARD_SECONDS) } assert_equal "deadline", failure.dig("error", "code") assert_equal "possibly_sent", failure.dig("error", "delivery") assert_equal({"state" => "unknown", "created" => []}, failure.dig("error", "effects")) @@ -164,7 +164,7 @@ def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effe assert_same seen.fetch(0).fetch(2), seen.fetch(1).fetch(2) assert diagnose.call("created-window readback") { scope.server.run(["list-windows", "-a", "-F", '#{window_name}']) }.text.lines.any? { |line| line.chomp == "partial-effect" } ensure - diagnose.call("create-release cleanup") { scope.server.wait_for("mcp-create-held", action: :signal, timeout: 0.5) } + diagnose.call("create-release cleanup") { scope.server.wait_for("mcp-create-held", action: :signal, timeout: HANG_GUARD_SECONDS) } source.hooks.unset("after-new-window", index: 93) end @@ -172,13 +172,13 @@ def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effe source.options.set("command-alias", "run-shel=wait-for -S mcp-acquire-ready ; wait-for mcp-acquire-held ; run-shell", index: 93) begin pending = parent.async { invoke(sdk, "tmux_create", kind: "window", parent: session, name: "never-dispatched", argv: ["cat"]) } - diagnose.call("acquisition readiness") { scope.server.wait_for("mcp-acquire-ready", timeout: 0.5) } - failure = diagnose.call("acquisition pending result") { pending.wait(timeout: 0.5) } + diagnose.call("acquisition readiness") { scope.server.wait_for("mcp-acquire-ready", timeout: HANG_GUARD_SECONDS) } + failure = diagnose.call("acquisition pending result") { pending.wait(timeout: HANG_GUARD_SECONDS) } assert_equal "deadline", failure.dig("error", "code") assert_equal "not_sent", failure.dig("error", "delivery") assert_equal({"state" => "none", "created" => []}, failure.dig("error", "effects")) ensure - diagnose.call("acquisition-release cleanup") { scope.server.wait_for("mcp-acquire-held", action: :signal, timeout: 0.5) } + diagnose.call("acquisition-release cleanup") { scope.server.wait_for("mcp-acquire-held", action: :signal, timeout: HANG_GUARD_SECONDS) } source.options.unset("command-alias", index: 93) end refute diagnose.call("final readback") { scope.server.run(["list-windows", "-a", "-F", '#{window_name}']) }.text.lines.any? { |line| line.chomp == "never-dispatched" } diff --git a/test/integration/mcp_transport_test.rb b/test/integration/mcp_transport_test.rb index a2f8b972..4c49e87a 100644 --- a/test/integration/mcp_transport_test.rb +++ b/test/integration/mcp_transport_test.rb @@ -49,7 +49,7 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne sdk = sdk_server sdk.define_custom_method(method_name: "custom/wait") do |params, server_context:| entered << [Thread.current, server_context.cancellation] - scope.server.run(["wait-for", "-S", "mcp-ready", ";", "wait-for", "mcp-held"], timeout: 0.5) + scope.server.run(["wait-for", "-S", "mcp-ready", ";", "wait-for", "mcp-held"], timeout: HANG_GUARD_SECONDS) {finished: true} rescue LibTmux::Cancelled => error cancelled << error @@ -60,7 +60,7 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne send_frame(input, request(1, "server/discover")) read_frame(parent, output) send_frame(input, request(2, "custom/wait", **modern_params)) - scope.server.wait_for("mcp-ready", timeout: 0.5) + scope.server.wait_for("mcp-ready", timeout: HANG_GUARD_SECONDS) send_frame(input, request(3, "custom/echo", **modern_params(value: "concurrent reader"))) assert_equal "concurrent reader", read_frame(parent, output).dig("result", "value") refute entered.first.last.cancelled? @@ -72,7 +72,7 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne assert_equal Thread.current, entered.first.first assert entered.first.last.cancelled? send_frame(input, request(5, "custom/wait", **modern_params)) - scope.server.wait_for("mcp-ready", timeout: 0.5) + scope.server.wait_for("mcp-ready", timeout: HANG_GUARD_SECONDS) input.close end assert source.run(["has-session", "-t", "fixture"]).success? @@ -117,7 +117,7 @@ def test_first_success_locks_the_era_and_modern_context_is_request_local first[:_meta]["io.modelcontextprotocol/clientInfo"] = {name: "first", version: "1"} first[:_meta]["io.modelcontextprotocol/clientCapabilities"] = {first: {}} send_frame(input, request(2, "custom/context", **first)) - parent.with_timeout(0.5) { ready.wait } + parent.with_timeout(HANG_GUARD_SECONDS) { ready.wait } send_frame(input, request(3, "custom/context", **modern_params)) replies = 2.times.map { read_frame(parent, output) }.to_h { |entry| [entry.fetch("id"), entry.fetch("result")] } assert_equal "first", replies.fetch(2).fetch("client") @@ -168,7 +168,7 @@ def test_request_deadline_releases_dispatch_capacity assert_equal "after deadline", read_frame(parent, output).dig("result", "value") end elapsed = 0 - sdk.define_custom_method(method_name: "custom/clock") { |_| elapsed += 1; {expired: true} } + sdk.define_custom_method(method_name: "custom/clock") { |_| elapsed += HANG_GUARD_SECONDS; {expired: true} } with_transport(parent, server: sdk) do |transport, input, output| transport.define_singleton_method(:clock) { super() + elapsed } send_frame(input, request(1, "custom/clock")) @@ -177,7 +177,7 @@ def test_request_deadline_releases_dispatch_capacity with_transport(parent) do |transport, input, output| transport.define_singleton_method(:clock) { super() + elapsed } transport.define_singleton_method(:encode) do |message| - super(message).tap { elapsed += 1 } + super(message).tap { elapsed += HANG_GUARD_SECONDS } end send_frame(input, request(1, "custom/echo", value: "encoding crossed deadline")) assert_equal(-32000, read_frame(parent, output).dig("error", "code")) @@ -304,12 +304,12 @@ def test_repeated_cancellation_completes_retirement_before_restoring_sdk_transpo send_frame(client_input, request(1, "custom/echo", value: "started")) assert_equal "started", read_frame(parent, client_output).dig("result", "value") runner.cancel - parent.with_timeout(0.5) { entered.wait until retiring } + parent.with_timeout(HANG_GUARD_SECONDS) { entered.wait until retiring } runner.cancel parent.yield assert_same transport, sdk.transport release.signal - result = runner.wait(timeout: 0.5) + result = runner.wait(timeout: HANG_GUARD_SECONDS) assert_kind_of ::Async::Cancel, result assert transport.closed? assert_same previous, sdk.transport @@ -366,7 +366,7 @@ def test_partial_task_startup_failure_retires_the_already_started_writer end trace.enable do send_frame(client, request(1, "custom/echo", value: "never dispatched")) - error = runner.wait(timeout: 0.5) + error = runner.wait(timeout: HANG_GUARD_SECONDS) raise error if error.is_a?(Exception) end end @@ -401,17 +401,17 @@ def test_failed_retirement_retains_ownership_until_close_can_retry observed = assert_raises(RuntimeError) do with_transport(parent, server: sdk, cleanup_timeout: 0.02) do |transport, input, _, runner| send_frame(input, request(1, "custom/cleanup")) - parent.with_timeout(0.5) { ready.wait until handler } + parent.with_timeout(HANG_GUARD_SECONDS) { ready.wait until handler } input.close transport.instance_variable_set(:@failure, primary) - error = runner.wait(timeout: 0.5) + error = runner.wait(timeout: HANG_GUARD_SECONDS) assert_same primary, error refute_empty error.mcp_cleanup_errors assert error.mcp_cleanup_errors.frozen? refute transport.closed? assert_same transport, sdk.transport release.signal - handler.wait(timeout: 0.5) + handler.wait(timeout: HANG_GUARD_SECONDS) transport.close assert transport.closed? assert_same previous, sdk.transport @@ -437,7 +437,7 @@ def with_transport(parent, server: sdk_server, **limits) input, client_input = IO.pipe client_output, output = IO.pipe transport = LibTmux::MCP::StdioTransport.new(server: server, parent: parent, input: input, output: output, - **{request_timeout: 0.5}.merge(limits)) + **{request_timeout: HANG_GUARD_SECONDS}.merge(limits)) runner = parent.async do transport.run rescue Exception => error @@ -451,7 +451,7 @@ def with_transport(parent, server: sdk_server, **limits) ensure client_input.close unless client_input.closed? begin - result = runner.wait(timeout: 0.75) + result = runner.wait(timeout: HANG_GUARD_SECONDS) failure ||= result if result.is_a?(Exception) rescue Exception => error failure ||= error @@ -468,7 +468,7 @@ def await_handoff(parent, handoffs, stage) flunk "Test observer timed out waiting for MCP #{stage}" end - def observe_transport(runner, timeout: 2) + def observe_transport(runner, timeout: HANG_GUARD_SECONDS) runner.wait(timeout: timeout) rescue Async::TimeoutError flunk "Test observer timed out waiting for MCP transport retirement after #{timeout}s" @@ -487,7 +487,7 @@ def send_frame(input, frame) end def read_frame(parent, output) - line = parent.with_timeout(0.5) { output.gets } + line = parent.with_timeout(HANG_GUARD_SECONDS) { output.gets } JSON.parse(line) end end diff --git a/test/integration/mcp_wait_test.rb b/test/integration/mcp_wait_test.rb index 17632918..1622fc0f 100644 --- a/test/integration/mcp_wait_test.rb +++ b/test/integration/mcp_wait_test.rb @@ -22,7 +22,7 @@ def test_wait_observes_screen_events_and_initial_process_exit await_ready(ready, pending) refute pending.finished? pane.send_text("event-visible") - result = pending.wait(timeout: 0.5) + result = pending.wait(timeout: HANG_GUARD_SECONDS) assert result.fetch("ok"), "#{result.inspect}; #{@observation_failure.inspect}" assert result.dig("data", "capture", "rows").join.include?("event-visible") assert_empty scope.server.list_clients @@ -35,7 +35,7 @@ def test_wait_observes_screen_events_and_initial_process_exit pending = Async::Task.current.async { call(app, wire_ref(child.ref), {type: "process_exit"}) } await_ready(ready, pending) child.send_keys("Enter") - result = pending.wait(timeout: 0.5) + result = pending.wait(timeout: HANG_GUARD_SECONDS) assert result.fetch("ok"), "#{result.inspect}; #{@observation_failure.inspect}" assert_equal "process_exit", result.dig("data", "condition") assert_equal "unobserved", result.dig("data", "exit_status") @@ -53,7 +53,7 @@ def test_deadline_and_sdk_cancellation_close_observers_without_terminating_pane pending = Async::Task.current.async { call(app, target, {type: "screen_contains", text: "never"}, cancellation: cancellation) } await_ready(ready, pending) cancellation.cancel - failure = pending.wait(timeout: 0.5) + failure = pending.wait(timeout: HANG_GUARD_SECONDS) assert_equal "cancelled", failure.dig("error", "code") assert_empty scope.server.list_clients else @@ -78,11 +78,11 @@ def test_control_gap_and_repeated_cancellation_retire_all_owned_observers pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "absent"}) } await_ready(ready, pending) begin - control.pause_output(pane_id: pane.id, timeout: 0.5) + control.pause_output(pane_id: pane.id, timeout: HANG_GUARD_SECONDS) rescue LibTmux::ClosedError # The observed gap may retire the lane before the pause reply finishes. end - assert_equal "observation_lost", pending.wait(timeout: 0.5).dig("error", "code") + assert_equal "observation_lost", pending.wait(timeout: HANG_GUARD_SECONDS).dig("error", "code") assert control.closed? closing = Async::Queue.new @@ -105,9 +105,9 @@ def test_control_gap_and_repeated_cancellation_retire_all_owned_observers original.call(**options) end pending.cancel - Async::Task.current.with_timeout(0.5) { closing.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { closing.dequeue } pending.cancel - error = pending.wait(timeout: 0.5) + error = pending.wait(timeout: HANG_GUARD_SECONDS) assert_instance_of Async::Cancel, error assert control.closed? assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } @@ -134,7 +134,7 @@ def test_pending_control_retirement_keeps_process_descriptors_until_application_ end begin pane.send_text("finish-with-evidence") - failure = pending.wait(timeout: 0.5) + failure = pending.wait(timeout: HANG_GUARD_SECONDS) assert_equal "transport_error", failure.dig("error", "code"), failure.inspect refute_includes JSON.generate(failure), "PRIVATE" observer = app.instance_variable_get(:@retiring).first @@ -165,7 +165,7 @@ def test_application_close_cancels_and_joins_an_active_wait_before_returning refute pending.finished? app.close assert pending.finished?, "Application.close must join the admitted request's observer cleanup" - assert_equal "cancelled", pending.wait(timeout: 0.5).dig("error", "code") + assert_equal "cancelled", pending.wait(timeout: HANG_GUARD_SECONDS).dig("error", "code") assert_empty app.instance_variable_get(:@observers) assert_empty app.instance_variable_get(:@retiring) assert_empty scope.server.list_clients @@ -202,15 +202,15 @@ def test_application_close_keeps_request_ownership_through_repeated_cancellation rescue Exception => error error end - Async::Task.current.with_timeout(0.5) { closing.dequeue; waiting.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { closing.dequeue; waiting.dequeue } 2.times do closer.cancel - Async::Task.current.with_timeout(0.5) { waiting.dequeue } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { waiting.dequeue } end release.enqueue(true) - assert_instance_of Async::Cancel, closer.wait(timeout: 0.5) + assert_instance_of Async::Cancel, closer.wait(timeout: HANG_GUARD_SECONDS) assert pending.finished? - assert_equal "cancelled", pending.wait(timeout: 0.5).dig("error", "code") + assert_equal "cancelled", pending.wait(timeout: HANG_GUARD_SECONDS).dig("error", "code") assert control.closed? assert_empty app.instance_variable_get(:@calls) assert_empty app.instance_variable_get(:@observers) @@ -398,7 +398,7 @@ def test_wait_reports_a_lost_stream_when_the_control_client_detaches_from_a_live private def await_ready(ready, pending) - Async::Task.current.with_timeout(0.5) { ready.wait } + Async::Task.current.with_timeout(HANG_GUARD_SECONDS) { ready.wait } rescue Async::TimeoutError pending.wait if pending.finished? raise diff --git a/test/integration/operations_test.rb b/test/integration/operations_test.rb index 039e859b..f6403e93 100644 --- a/test/integration/operations_test.rb +++ b/test/integration/operations_test.rb @@ -321,13 +321,13 @@ def test_link_guard_rechecks_after_hook_wait_and_ignores_configured_command_alia assert fixture.tmux("link-window", "-k", "-s", replacement.id, "-t", "#{session.id}:8").last.success? assert fixture.tmux("set-hook", "-gu", "after-show-options[99]").last.success? assert fixture.tmux("wait-for", "-S", "link-release").last.success? - assert request.join(0.5), "link guard did not finish" + assert request.join(HANG_GUARD_SECONDS), "link guard did not finish" assert_instance_of LibTmux::TargetNotFoundError, request.value assert_equal replacement.id, session.list_window_links.find { |entry| entry.index == 8 }.id ensure fixture.tmux("set-hook", "-gu", "after-show-options[99]") fixture.tmux("wait-for", "-S", "link-release") - request.join(0.5) + request.join(HANG_GUARD_SECONDS) end end end @@ -341,7 +341,7 @@ def test_missing_alias_inventory_cannot_turn_a_guarded_mutation_into_false_succe server.options.set("command-alias", "if-shell=", index: 90) server.options.set("command-alias", "show-options=show-options -v", index: 91) outcome = begin - link.unlink(timeout: 0.5) + link.unlink(timeout: HANG_GUARD_SECONDS) rescue LibTmux::UnsupportedFeatureError => error error end @@ -357,7 +357,7 @@ def test_swapping_distinct_window_links_preserves_windows_and_invalidates_old_oc initial = session.list_windows.first other = session.new_window(name: "other", command: ["/bin/cat"]) first, second = session.list_window_links - assert first.swap(second.ref, timeout: 0.5).success? + assert first.swap(second.ref, timeout: HANG_GUARD_SECONDS).success? assert_equal [[0, other.id], [1, initial.id]], session.list_window_links.map { |link| [link.index, link.id] } assert_raises(LibTmux::TargetNotFoundError) { first.select } assert_raises(LibTmux::TargetNotFoundError) { second.select } @@ -365,7 +365,7 @@ def test_swapping_distinct_window_links_preserves_windows_and_invalidates_old_oc assert_equal "#{other.id}\n", other.display('#{window_id}').stdout left, right = initial.list_panes.first, other.list_panes.first - assert left.swap(right.ref, timeout: 0.5).success? + assert left.swap(right.ref, timeout: HANG_GUARD_SECONDS).success? assert_equal [right.id], initial.list_panes.map(&:id) assert_equal [left.id], other.list_panes.map(&:id) end @@ -454,29 +454,29 @@ def test_source_file_and_wait_channels_preserve_literal_arguments_and_final_outc with_server do |server, fixture| config = File.join(File.dirname(fixture.socket_path), 'config #{pid};.conf') File.write(config, "set-option -g @source-loaded 'literal ; value'\n") - assert server.source_file(config, timeout: 0.5).success? + assert server.source_file(config, timeout: HANG_GUARD_SECONDS).success? assert_equal "literal ; value", server.options(scope: :session).get("@source-loaded").raw File.write(config, "set-option -g @source-loaded changed\nset-option -g nonexistent-option invalid\n") - failure = assert_raises(LibTmux::CommandError) { server.source_file(config, timeout: 0.5) } + failure = assert_raises(LibTmux::CommandError) { server.source_file(config, timeout: HANG_GUARD_SECONDS) } assert_equal :observed, failure.delivery assert_equal "changed", server.options(scope: :session).get("@source-loaded").raw channel = 'channel #{pid};' - assert server.wait_for(channel, action: :signal, timeout: 0.5).success? - assert server.wait_for(channel, timeout: 0.5).success? - assert server.wait_for(channel, action: :lock, timeout: 0.5).success? + assert server.wait_for(channel, action: :signal, timeout: HANG_GUARD_SECONDS).success? + assert server.wait_for(channel, timeout: HANG_GUARD_SECONDS).success? + assert server.wait_for(channel, action: :lock, timeout: HANG_GUARD_SECONDS).success? blocked = assert_raises(LibTmux::DeadlineExceeded) { server.wait_for(channel, action: :lock, timeout: 0.1) } assert_equal :possibly_sent, blocked.delivery - assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? + assert server.wait_for(channel, action: :unlock, timeout: HANG_GUARD_SECONDS).success? # Before tmux 3.8 the retired client's queued lock still acquires in tmux # after unlock; 3.8 drops it, so the channel is no longer locked. if LibTmux::Internal::TmuxVersion.parse(server.tmux_version) < LibTmux::Internal::TmuxVersion.parse("3.8") - assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? + assert server.wait_for(channel, action: :unlock, timeout: HANG_GUARD_SECONDS).success? else - assert_raises(LibTmux::CommandError) { server.wait_for(channel, action: :unlock, timeout: 0.5) } + assert_raises(LibTmux::CommandError) { server.wait_for(channel, action: :unlock, timeout: HANG_GUARD_SECONDS) } end - assert server.wait_for(channel, action: :lock, timeout: 0.5).success? - assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? + assert server.wait_for(channel, action: :lock, timeout: HANG_GUARD_SECONDS).success? + assert server.wait_for(channel, action: :unlock, timeout: HANG_GUARD_SECONDS).success? end end diff --git a/test/integration/pane_io_test.rb b/test/integration/pane_io_test.rb index aee42ff4..724e3efa 100644 --- a/test/integration/pane_io_test.rb +++ b/test/integration/pane_io_test.rb @@ -37,8 +37,8 @@ def test_pipe_directions_preserve_bytes_and_toggle_closes_the_previous_pipe begin script = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(ARGV.fetch(1) + "\n"); IO.copy_stream(STDIN, io) }' command = [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", script, listener.path].shelljoin + " '\#{pane_id}'" - assert pane.pipe(shell_command: command, timeout: 0.5).success? - assert IO.select([listener], nil, nil, 0.5), "pipe process did not connect" + assert pane.pipe(shell_command: command, timeout: HANG_GUARD_SECONDS).success? + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "pipe process did not connect" pipe_reader = listener.accept assert_equal "#{pane.id}\n".b, read_bytes(pipe_reader, pane.id.bytesize + 1) assert_equal "1\n", pane.display('#{pane_pipe}').text @@ -46,22 +46,22 @@ def test_pipe_directions_preserve_bytes_and_toggle_closes_the_previous_pipe render(channel, payload) assert_equal payload + "\e[6n", read_bytes(pipe_reader, payload.bytesize + 4) - assert pane.pipe(shell_command: command, only_if_closed: true, timeout: 0.5).success? + assert pane.pipe(shell_command: command, only_if_closed: true, timeout: HANG_GUARD_SECONDS).success? assert_equal "0\n", pane.display('#{pane_pipe}').text - assert IO.select([pipe_reader], nil, nil, 0.5), "closed pipe did not reach EOF" + assert IO.select([pipe_reader], nil, nil, HANG_GUARD_SECONDS), "closed pipe did not reach EOF" assert_nil pipe_reader.read(1) assert_equal :wait_readable, listener.accept_nonblock(exception: false) input = "input\0\xff\n".b writer = [Gem.ruby, "--disable=rubyopt,gems", "-e", 'STDOUT.write([ARGV.fetch(0)].pack("H*"))', input.unpack1("H*")].shelljoin - assert pane.pipe(shell_command: writer, input: true, output: false, timeout: 0.5).success? + assert pane.pipe(shell_command: writer, input: true, output: false, timeout: HANG_GUARD_SECONDS).success? assert_equal input, receive_input(channel, input.bytesize) duplex = [Gem.ruby, "--disable=rubyopt,gems", "-e", 'STDOUT.sync = true; while (bytes = STDIN.readpartial(1024)); STDOUT.write(bytes); end'].shelljoin - assert pane.pipe(shell_command: duplex, input: true, output: true, timeout: 0.5).success? + assert pane.pipe(shell_command: duplex, input: true, output: true, timeout: HANG_GUARD_SECONDS).success? channel.write("O" + [payload.bytesize].pack("N") + payload) assert_equal payload, receive_input(channel, payload.bytesize) - assert pane.pipe(timeout: 0.5).success? + assert pane.pipe(timeout: HANG_GUARD_SECONDS).success? assert_equal "0\n", pane.display('#{pane_pipe}').text ensure pipe_reader&.close @@ -81,7 +81,7 @@ def with_pane LibTmux::Server.open(socket_path: fixture.socket_path) do |server| window = server.list_sessions.first.new_window(name: "io", command: program(listener.path)) pane = window.list_panes.first - assert IO.select([listener], nil, nil, 0.5), "pane program did not connect" + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "pane program did not connect" channel = listener.accept yield server, pane, channel, directory end @@ -128,7 +128,7 @@ def render(channel, bytes) def read_bytes(io, size) data = +"".b - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + HANG_GUARD_SECONDS while data.bytesize < size remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) assert remaining.positive? && IO.select([io], nil, nil, remaining), "pane I/O did not arrive" diff --git a/test/integration/server_control_test.rb b/test/integration/server_control_test.rb index 8a069730..1da2f163 100644 --- a/test/integration/server_control_test.rb +++ b/test/integration/server_control_test.rb @@ -15,14 +15,14 @@ def test_server_owns_bounded_control_clients_and_closes_pending_exchanges session = server.list_sessions.first control = server.open_control(session: session.ref) - assert_equal "ready\n", control.exchange("display-message -p ready", timeout: 0.5).blocks.last.body + assert_equal "ready\n", control.exchange("display-message -p ready", timeout: HANG_GUARD_SECONDS).blocks.last.body assert_equal 1, server.diagnostics.fetch(:control_connections) assert_raises(LibTmux::CapacityError) { server.open_control(session: session.ref) } assert server.list_clients.any? { |client| client[:pid] == control.pid && client[:control] } control.close replacement = server.open_control(session: session.ref) request = Thread.new do - replacement.exchange("wait-for -S scoped-ready ; wait-for scoped-held", timeout: 0.5) + replacement.exchange("wait-for -S scoped-ready ; wait-for scoped-held", timeout: HANG_GUARD_SECONDS) rescue LibTmux::Error => error error end @@ -30,12 +30,12 @@ def test_server_owns_bounded_control_clients_and_closes_pending_exchanges assert fixture.tmux("wait-for", "scoped-ready").last.success? server.close assert_equal 0, server.diagnostics.fetch(:control_connections) - assert request.join(0.5), "server close did not wake the pending exchange" + assert request.join(HANG_GUARD_SECONDS), "server close did not wake the pending exchange" assert_instance_of LibTmux::ClosedError, request.value assert_raises(Errno::ECHILD) { Process.waitpid(replacement.pid, Process::WNOHANG) } assert fixture.tmux("has-session", "-t", "fixture").last.success? ensure - request.join(0.5) + request.join(HANG_GUARD_SECONDS) end end end diff --git a/test/integration/server_test.rb b/test/integration/server_test.rb index 9b61d2c4..9b8f9340 100644 --- a/test/integration/server_test.rb +++ b/test/integration/server_test.rb @@ -50,10 +50,10 @@ def test_literal_creation_topology_and_terminal_input text = "C-a \#{pane_id};" assert pane.send_text(text).success? assert pane.send_keys("Enter").success? - assert IO.select([receipt], nil, nil, 0.5), "pane did not acknowledge literal input" + assert IO.select([receipt], nil, nil, HANG_GUARD_SECONDS), "pane did not acknowledge literal input" client = receipt.accept begin - assert IO.select([client], nil, nil, 0.5), "pane input receipt was empty" + assert IO.select([client], nil, nil, HANG_GUARD_SECONDS), "pane input receipt was empty" assert_equal "#{text}\n", client.read ensure client.close @@ -146,12 +146,12 @@ def test_close_cancels_owned_clients_and_preserves_the_borrowed_daemon begin assert fixture.tmux("wait-for", "ruby-ready").last.success? server.close - assert request.join(0.5), "server close did not retire its client" + assert request.join(HANG_GUARD_SECONDS), "server close did not retire its client" assert_instance_of LibTmux::Cancelled, request.value assert fixture.tmux("has-session", "-t", "fixture").last.success? ensure server.close - request.join(0.5) + request.join(HANG_GUARD_SECONDS) end end end @@ -209,7 +209,7 @@ def test_admission_is_bounded_and_close_can_retry_after_its_deadline assert_equal :not_sent, failure.delivery failure = assert_raises(LibTmux::DeadlineExceeded) { server.close } assert_equal :retire, failure.phase - requests.each { |request| assert request.join(0.5), "cancelled client did not retire" } + requests.each { |request| assert request.join(HANG_GUARD_SECONDS), "cancelled client did not retire" } server.close assert server.diagnostics.fetch(:closed) assert_equal 0, server.diagnostics.fetch(:admitted_requests) @@ -222,7 +222,7 @@ def test_admission_is_bounded_and_close_can_retry_after_its_deadline rescue LibTmux::DeadlineExceeded nil end - requests.each { |request| request.join(0.5) } + requests.each { |request| request.join(HANG_GUARD_SECONDS) } server.close end end @@ -250,11 +250,11 @@ def test_repeated_interrupt_preserves_the_block_error_during_close entered.pop worker.raise(deferred) release << true - assert worker.join(0.5), "cleanup did not finish" + assert worker.join(HANG_GUARD_SECONDS), "cleanup did not finish" assert_same original, worker.value ensure release << true - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) end end end @@ -283,13 +283,13 @@ def test_fork_close_cannot_cancel_a_parent_request end end writer.close - assert IO.select([reader], nil, nil, 0.5), "fork close blocked on parent requests" + assert IO.select([reader], nil, nil, HANG_GUARD_SECONDS), "fork close blocked on parent requests" assert_equal "closed", reader.read _, status = Process.wait2(child) child = nil assert status.success? assert fixture.tmux("wait-for", "-S", "fork-held").last.success? - assert request.join(0.5), "parent request did not finish" + assert request.join(HANG_GUARD_SECONDS), "parent request did not finish" assert_instance_of LibTmux::CommandResult, request.value assert request.value.success? ensure @@ -300,7 +300,7 @@ def test_fork_close_cannot_cancel_a_parent_request reader.close writer.close unless writer.closed? server.close - request.join(0.5) + request.join(HANG_GUARD_SECONDS) end end end diff --git a/test/integration/session_guard_test.rb b/test/integration/session_guard_test.rb index 18c30262..1b9de8e8 100644 --- a/test/integration/session_guard_test.rb +++ b/test/integration/session_guard_test.rb @@ -43,14 +43,14 @@ def test_guard_rechecks_panes_after_preflight_wait_and_bypasses_static_aliases assert fixture.tmux("join-pane", "-d", "-s", borrowed.id, "-t", created.pane.id).last.success? assert fixture.tmux("set-hook", "-gu", "after-show-options[99]").last.success? assert fixture.tmux("wait-for", "-S", "ownership-release").last.success? - assert request.join(0.5), "ownership guard did not settle" + assert request.join(HANG_GUARD_SECONDS), "ownership guard did not settle" assert_instance_of LibTmux::TargetNotFoundError, request.value assert_includes server.list_panes.map(&:ref), borrowed.ref assert_includes server.list_sessions.map(&:ref), created.entity.ref ensure fixture.tmux("set-hook", "-gu", "after-show-options[99]") fixture.tmux("wait-for", "-S", "ownership-release") - request.join(0.5) + request.join(HANG_GUARD_SECONDS) end end end diff --git a/test/integration/snapshot_test.rb b/test/integration/snapshot_test.rb index 6c8f7367..6202b877 100644 --- a/test/integration/snapshot_test.rb +++ b/test/integration/snapshot_test.rb @@ -52,10 +52,10 @@ def test_embedded_newlines_and_invalid_utf8_are_preserved_in_metadata code = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write("ready") }; STDIN.read' assert server.run(["new-window", "-d", "-t", "$0", "-c", directory, "--", Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", code, ready.path]).success? - assert IO.select([ready], nil, nil, 0.5), "pane did not announce its working directory" + assert IO.select([ready], nil, nil, HANG_GUARD_SECONDS), "pane did not announce its working directory" peer = ready.accept begin - assert IO.select([peer], nil, nil, 0.5), "pane readiness data did not arrive" + assert IO.select([peer], nil, nil, HANG_GUARD_SECONDS), "pane readiness data did not arrive" assert_equal "ready", peer.read ensure peer.close @@ -138,7 +138,7 @@ def test_requested_clients_are_observations_and_empty_server_is_a_complete_graph begin if require_control_binding(pin) LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0") do |control| - control.exchange("display-message -p ready", timeout: 0.5) + control.exchange("display-message -p ready", timeout: HANG_GUARD_SECONDS) capture = acquire(server, clients: true) client = capture.clients.one assert_equal control.pid, client.pid diff --git a/test/integration/startup_test.rb b/test/integration/startup_test.rb index 1d96ce01..f286a291 100644 --- a/test/integration/startup_test.rb +++ b/test/integration/startup_test.rb @@ -14,7 +14,7 @@ def test_log_readiness_disables_logging_before_exposing_the_owned_server log_readiness = LibTmux::Internal.const_get(:LogSocketReadiness, false).new(directory) end path = pid = nil - LibTmux::Server.start(timeout: 0.5) do |server| + LibTmux::Server.start(timeout: HANG_GUARD_SECONDS) do |server| path = File.dirname(server.endpoint.socket_path) pid = Integer(server.run(["display-message", "-p", '#{pid}']).text) assert log_readiness.stopped? @@ -44,7 +44,7 @@ def test_oversized_startup_log_fails_closed_and_reaps_its_writer "File.write(#{record.inspect}, Dir.pwd)\n" \ "File.binwrite(\"tmux-server-\#{Process.pid}.log\", 'x' * ((1 << 22) + 1))\nIO.select([])\n") File.chmod(0o700, executable) - error = assert_raises(LibTmux::CapacityError) { LibTmux::Server.start(executable: executable, timeout: 0.5) } + error = assert_raises(LibTmux::CapacityError) { LibTmux::Server.start(executable: executable, timeout: HANG_GUARD_SECONDS) } assert_equal :possibly_sent, error.delivery assert_equal :startup, error.phase assert_raises(Errno::ECHILD) { Process.waitpid(error.pid, Process::WNOHANG) } @@ -203,16 +203,16 @@ def test_repeated_interrupt_during_close_preserves_first_error_and_reaps error end begin - assert entered.pop(timeout: 0.5), "daemon close was not entered" + assert entered.pop(timeout: HANG_GUARD_SECONDS), "daemon close was not entered" worker.raise second release << true - assert worker.join(0.5), "daemon cleanup did not settle" + assert worker.join(HANG_GUARD_SECONDS), "daemon cleanup did not settle" assert_same first, worker.value assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } refute File.exist?(File.dirname(path)) ensure release << true - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) end end @@ -228,7 +228,7 @@ def test_forked_close_cannot_retire_parent_daemon end writer.close begin - assert IO.select([reader], nil, nil, 0.5), "fork child did not detach" + assert IO.select([reader], nil, nil, HANG_GUARD_SECONDS), "fork child did not detach" assert_equal "detached", reader.read assert Process.wait2(child).last.success? assert server.run(["display-message", "-p", "still-owned"]).success? diff --git a/test/integration/terminal_test.rb b/test/integration/terminal_test.rb index 86a7e1d2..f62c7061 100644 --- a/test/integration/terminal_test.rb +++ b/test/integration/terminal_test.rb @@ -25,13 +25,13 @@ def test_switch_client_uses_current_literal_selector_and_preserves_session_envir destination.options.set("update-environment", "LIBTMUX_SWITCH_PROOF") with_attached_client(server, fixture, source) do |client, _worker| assert fixture.tmux("set-option", "-s", "command-alias[199]", "switch-client=display-message -p aliased").last.success? - result = server.switch_client(client: client.fetch(:name), session: destination.ref, timeout: 0.5) + result = server.switch_client(client: client.fetch(:name), session: destination.ref, timeout: HANG_GUARD_SECONDS) assert_instance_of LibTmux::CommandResult, result assert result.success? assert_empty result.stdout assert_equal destination.id, server.list_clients.fetch(0).fetch(:session_id) assert_equal "preserved", destination.environment("LIBTMUX_SWITCH_PROOF") - assert_raises(LibTmux::CommandError) { server.switch_client(client: "*", session: source.ref, timeout: 0.5) } + assert_raises(LibTmux::CommandError) { server.switch_client(client: "*", session: source.ref, timeout: HANG_GUARD_SECONDS) } assert_equal destination.id, server.list_clients.fetch(0).fetch(:session_id) [nil, "", "invalid\0client", "x" * 1025].each do |selector| assert_raises(ArgumentError) { server.switch_client(client: selector, session: source.ref) } @@ -68,9 +68,9 @@ def test_vanished_switch_client_does_not_retarget_another_attached_client with_attached_client(server, fixture, source) do |gone, worker| with_attached_client(server, fixture, source) do |survivor, _other_worker| assert fixture.tmux("detach-client", "-t", gone.fetch(:name)).last.success? - assert worker.join(0.5), "detached client did not retire" + assert worker.join(HANG_GUARD_SECONDS), "detached client did not retire" error = assert_raises(LibTmux::CommandError) do - server.switch_client(client: gone.fetch(:name), session: destination.ref, timeout: 0.5) + server.switch_client(client: gone.fetch(:name), session: destination.ref, timeout: HANG_GUARD_SECONDS) end assert_equal :observed, error.delivery current = server.list_clients @@ -97,7 +97,7 @@ def test_explicit_terminal_attach_and_user_detach_return_final_status assert fixture.tmux("wait-for", "terminal-attached").last.success? assert_equal 1, server.list_clients.length master.write("\x02d") - assert worker.join(0.5), "terminal client did not detach" + assert worker.join(HANG_GUARD_SECONDS), "terminal client did not detach" result = worker.value assert_instance_of LibTmux::TerminalResult, result assert result.success? @@ -108,7 +108,7 @@ def test_explicit_terminal_attach_and_user_detach_return_final_status assert_empty server.list_clients ensure server.close - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) end end end @@ -131,7 +131,7 @@ def test_server_close_cancels_only_its_terminal_client_and_restores_borrowed_tty begin assert fixture.tmux("wait-for", "terminal-close").last.success? server.close - assert worker.join(0.5), "closed terminal client did not retire" + assert worker.join(HANG_GUARD_SECONDS), "closed terminal client did not retire" error = worker.value assert_instance_of LibTmux::Cancelled, error assert_equal :possibly_sent, error.delivery @@ -141,7 +141,7 @@ def test_server_close_cancels_only_its_terminal_client_and_restores_borrowed_tty refute slave.closed? ensure server.close - worker.join(0.5) + worker.join(HANG_GUARD_SECONDS) end end end @@ -217,7 +217,7 @@ def with_attached_client(server, fixture, session) yield client, worker ensure token.cancel - assert worker.join(0.5), "owned attached client did not retire" + assert worker.join(HANG_GUARD_SECONDS), "owned attached client did not retire" worker.value end end diff --git a/test/integration/workspace_cli_test.rb b/test/integration/workspace_cli_test.rb index 4cdbd11b..6c6ec685 100644 --- a/test/integration/workspace_cli_test.rb +++ b/test/integration/workspace_cli_test.rb @@ -51,7 +51,7 @@ def test_switch_selects_current_client_after_apply_and_retains_creations_on_fail end ensure token.cancel - assert worker.join(0.5), "owned terminal fixture client did not retire" + assert worker.join(HANG_GUARD_SECONDS), "owned terminal fixture client did not retire" worker.value end end diff --git a/test/integration/workspace_test.rb b/test/integration/workspace_test.rb index 37408c1d..26717afd 100644 --- a/test/integration/workspace_test.rb +++ b/test/integration/workspace_test.rb @@ -50,7 +50,7 @@ def test_apply_reuses_initial_entities_and_reports_dispatch_without_shell_comple assert_equal 3, session.list_panes.length assert_equal "root", session.environment("ROOT") assert_equal "#{result.created_refs.fetch('window:1').id}\n", session.display('#{window_id}').text - assert IO.select([listener], nil, nil, 0.5), "authored shell command did not send its receipt" + assert IO.select([listener], nil, nil, HANG_GUARD_SECONDS), "authored shell command did not send its receipt" client = listener.accept begin assert_equal [File.realpath(directory), "pane"], Marshal.load(client.read) diff --git a/test/support/control_assertions.rb b/test/support/control_assertions.rb index 2f6d032c..6e7674f5 100644 --- a/test/support/control_assertions.rb +++ b/test/support/control_assertions.rb @@ -3,7 +3,7 @@ module LibTmuxTest module ControlAssertions def assert_run_shell_routing(control, version) - reply = control.exchange(%q{run-shell 'printf "outside-reply\n"; exit 17'}, timeout: 0.5) + reply = control.exchange(%q{run-shell 'printf "outside-reply\n"; exit 17'}, timeout: HANG_GUARD_SECONDS) refute_includes reply.blocks.map(&:body).join, "outside-reply" assert reply.blocks.any?(&:guard_success?) release = LibTmux::Internal::TmuxVersion.parse(version) @@ -12,23 +12,23 @@ def assert_run_shell_routing(control, version) copy_view = "send-keys -X history-top ; send-keys -X begin-selection ; " \ "send-keys -X history-bottom ; send-keys -X end-of-line ; " \ "send-keys -X copy-selection-and-cancel ; show-buffer" - output = control.exchange(copy_view, timeout: 0.5).blocks.map(&:body).join + output = control.exchange(copy_view, timeout: HANG_GUARD_SECONDS).blocks.map(&:body).join assert_includes output, "outside-reply" assert_includes output, "returned 17" - control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: 0.5) - output = control.exchange(copy_view, timeout: 0.5).blocks.map(&:body).join + control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: HANG_GUARD_SECONDS) + output = control.exchange(copy_view, timeout: HANG_GUARD_SECONDS).blocks.map(&:body).join assert_includes output, "%end 1 1 1" - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body + assert_equal "alive\n", control.exchange("display-message -p alive", timeout: HANG_GUARD_SECONDS).blocks.last.body else observed = [] loop do - event = control.events.next(timeout: 0.5) + event = control.events.next(timeout: HANG_GUARD_SECONDS) observed << event.raw break if event.raw.include?("returned 17") end assert_includes observed.join, "outside-reply" error = assert_raises(LibTmux::ProtocolError) do - control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: 0.5) + control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: HANG_GUARD_SECONDS) end assert_equal :possibly_sent, error.delivery assert_raises(LibTmux::ClosedError) { control.exchange("display-message -p later") } diff --git a/test/support/controlling_terminal.rb b/test/support/controlling_terminal.rb index 4785e312..4e205226 100644 --- a/test/support/controlling_terminal.rb +++ b/test/support/controlling_terminal.rb @@ -27,18 +27,18 @@ def with_controlling_terminal(command, environment: {}, **options) def wait_for_terminal_draw(output, marker) display = +"".b - Timeout.timeout(5) do + Timeout.timeout(HANG_GUARD_SECONDS) do display << output.readpartial(4096) until display.include?(marker) end rescue EOFError, Errno::EIO flunk "Terminal closed before drawing #{marker.inspect}: #{display.inspect}" rescue Timeout::Error - flunk "Terminal did not draw #{marker.inspect} within 5 seconds: #{display.inspect}" + flunk "Terminal did not draw #{marker.inspect} within #{HANG_GUARD_SECONDS} seconds: #{display.inspect}" end def read_terminal_exit(output, pid) display = +"".b - Timeout.timeout(5) do + Timeout.timeout(HANG_GUARD_SECONDS) do begin loop { display << output.readpartial(4096) } rescue EOFError, Errno::EIO @@ -46,7 +46,7 @@ def read_terminal_exit(output, pid) [display, Process.waitpid2(pid).last.exitstatus] end rescue Timeout::Error - flunk "Terminal did not close within 5 seconds: #{display.inspect}" + flunk "Terminal did not close within #{HANG_GUARD_SECONDS} seconds: #{display.inspect}" end end end diff --git a/test/support/process_cursor_support.rb b/test/support/process_cursor_support.rb index c6b0c441..7bd6f168 100644 --- a/test/support/process_cursor_support.rb +++ b/test/support/process_cursor_support.rb @@ -9,7 +9,7 @@ def require_process_cursor_support(scope) begin lease = LibTmux::MCP.const_get(:ProcessIdentity).acquire(scope.server, server_pid: snapshot.server_info.fetch(:pid), pane_pid: snapshot.panes.first.pid, - budget: scope.server.__send__(:operation_budget, 0.5, nil)) + budget: scope.server.__send__(:operation_budget, HANG_GUARD_SECONDS, nil)) rescue LibTmux::Error => error failure = error ensure diff --git a/test/support/tmux_fixture.rb b/test/support/tmux_fixture.rb index d825a38c..14ef879a 100644 --- a/test/support/tmux_fixture.rb +++ b/test/support/tmux_fixture.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative "../test_helper" require "fileutils" require "fiddle" require "fcntl" @@ -38,7 +39,7 @@ def finish_signalling def value finish_signalling - raise Error, "owned tmux process did not finish reaping" unless join(0.5) + raise Error, "owned tmux process did not finish reaping" unless join(HANG_GUARD_SECONDS) if observation_error && !@error_reported @error_reported = true @@ -52,7 +53,7 @@ def value private_constant :CleanupDetails, :OwnedChild CLEAN_ENV = {"TMUX" => nil, "TMUX_PANE" => nil}.freeze - DEADLINE_SECONDS = 0.5 + DEADLINE_SECONDS = HANG_GUARD_SECONDS private_constant :CLEAN_ENV, :DEADLINE_SECONDS attr_reader :socket_path, :cleanup_errors, :executable @@ -249,7 +250,7 @@ def spawn_owned(*arguments, **options) ensure observer.finish_signalling end - raise Error, "failed spawn observer did not finish" unless observer.join(0.5) + raise Error, "failed spawn observer did not finish" unless observer.join(HANG_GUARD_SECONDS) observer.value if observer.pid ensure @@ -303,7 +304,7 @@ def retire(process) ensure waiter.finish_signalling end - raise Error, "owned tmux process did not exit" unless waiter.join(0.5) + raise Error, "owned tmux process did not exit" unless waiter.join(HANG_GUARD_SECONDS) waiter.value ensure waiter.close diff --git a/test/test_helper.rb b/test/test_helper.rb index 8ef2058a..3b57fbeb 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -6,3 +6,6 @@ Dir[File.expand_path("../gems/*/lib", __dir__)].sort.reverse_each do |path| $LOAD_PATH.unshift(path) end + +# Outer bound for event waits; it only fails a hung test. +HANG_GUARD_SECONDS = 10 From cd6434afabaef98d3053f6df3e2b927219a14bb2 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 06:44:23 -0500 Subject: [PATCH 02/17] Tests(fix[mcp]): Advance a clock, not race 0.1s why: test_one_deadline_covers_acquisition_and_mutation_and_preserves_ unknown_effects gave the request 0.1 s of real time to take a snapshot, run tmux's preflight commands and reach a held after-new-window hook. When that took longer on macOS-15 the deadline expired first, the hook never fired and the test raised "command deadline exceeded" from its own wait-for (CI jobs 108738309513, 108738309552, 111211994832). With a tmux shim on PATH that sleeps 10 ms per spawn, the old test fails; it cannot tell slow startup from an enforced deadline. what: - Give the request a long budget and advance Mutation's clock after target acquisition (or before it, for the not-sent case), so exactly 1 s of real time remains for the held command - Keep the assertions: the mutation budget is below the acquisition budget, both share one cancel token, delivery is possibly_sent with unknown effects after dispatch and not_sent with none before it - Wait on the wait-for channels and the pending request with the hang guard - With the same shim at 100 ms per spawn the new test passes --- test/integration/mcp_mutation_test.rb | 36 +++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/test/integration/mcp_mutation_test.rb b/test/integration/mcp_mutation_test.rb index d56a998d..50ae78f6 100644 --- a/test/integration/mcp_mutation_test.rb +++ b/test/integration/mcp_mutation_test.rb @@ -5,6 +5,31 @@ require "libtmux/mcp" class MCPMutationTest < Minitest::Test + # Moves the request clock forward so a long request budget has a known + # amount left, without waiting for it or racing tmux startup against it. + module AdvancingClock + class << self + attr_accessor :offset + end + self.offset = 0 + + private + + def clock + super + AdvancingClock.offset + end + end + LibTmux::MCP.const_get(:Mutation, false).prepend(AdvancingClock) + + # Real time left for the mutation after the clock advances. tmux is held + # on a hook until it passes, so this bounds only that one held command. + HELD_SECONDS = 1.0 + REQUEST_SECONDS = 600 + + def teardown + AdvancingClock.offset = 0 + end + MUTATORS = %w[tmux_send tmux_create tmux_close].freeze def test_opt_in_sdk_mutations_create_exact_entities_and_separate_text_from_keys @@ -132,7 +157,7 @@ def test_mutation_response_capacity_is_reserved_before_any_creation end def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effects - with_application(request_timeout: 0.1) do |app, sdk, scope, source, fixture| + with_application(request_timeout: REQUEST_SECONDS) do |app, sdk, scope, source, fixture| diagnose = lambda do |phase, &operation| operation.call rescue LibTmux::Error => error @@ -144,9 +169,14 @@ def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effe parent = ::Async::Task.current session = wire_ref(diagnose.call("initial snapshot") { scope.server.snapshot }.sessions.first.ref) seen = [] + advance = :after_acquisition scope.server.define_singleton_method(:snapshot) do |**options| seen << [:capture, options.fetch(:timeout), options.fetch(:cancel)] - super(**options) + if advance == :before_acquisition + AdvancingClock.offset = REQUEST_SECONDS - HELD_SECONDS + options = options.merge(timeout: options.fetch(:timeout) - AdvancingClock.offset) + end + super(**options).tap { AdvancingClock.offset = REQUEST_SECONDS - HELD_SECONDS if advance == :after_acquisition } end scope.server.define_singleton_method(:create_window) do |ref, **options| seen << [:mutation, options.fetch(:timeout), options.fetch(:cancel)] @@ -168,6 +198,8 @@ def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effe source.hooks.unset("after-new-window", index: 93) end + AdvancingClock.offset = 0 + advance = :before_acquisition # The snapshot reads the server identity with the run-shell probe. source.options.set("command-alias", "run-shel=wait-for -S mcp-acquire-ready ; wait-for mcp-acquire-held ; run-shell", index: 93) begin From 816f5f0a1e64fdb66fc922aed70efa9a5f1b1a2b Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 06:44:23 -0500 Subject: [PATCH 03/17] CI(feat[stress]): Repeat integration on macOS why: A macOS flake shows up once in about a hundred runs, so a single green pass proves nothing. A scheduled repeat gives each test a failure rate and an Ubuntu control to compare against. what: - Add scripts/stress: runs the real-tmux integration suite N times and writes each test's run and failure counts to failures.csv and a Markdown table - Add stress.yml: weekly and on dispatch (input repeat, default 10), one job per runner, macOS-15 and Ubuntu 24.04, tmux 3.7c, the table in the step summary and the CSV and logs as an artifact --- .github/workflows/stress.yml | 69 ++++++++++++++++++++++++++++++++++++ scripts/stress | 54 ++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 .github/workflows/stress.yml create mode 100755 scripts/stress diff --git a/.github/workflows/stress.yml b/.github/workflows/stress.yml new file mode 100644 index 00000000..d3f39a6c --- /dev/null +++ b/.github/workflows/stress.yml @@ -0,0 +1,69 @@ +name: stress + +on: + schedule: + - cron: '17 7 * * 1' + workflow_dispatch: + inputs: + repeat: + type: number + description: Repetitions of the real-tmux integration suite per runner + default: 10 + +permissions: + contents: read + +concurrency: + group: stress-${{ github.ref }} + cancel-in-progress: true + +jobs: + repeat: + name: ${{ matrix.runner }} / Ruby 4.0.7 / tmux 3.7c + runs-on: ${{ matrix.runner }} + timeout-minutes: 90 + strategy: + fail-fast: false + max-parallel: 1 + matrix: + runner: [ubuntu-24.04, macos-15] + env: + BUNDLE_FROZEN: 'true' + LIBTMUX_VERSION_CHECK_EXPECT: supported + TMPDIR: /tmp + REPEAT: ${{ inputs.repeat || 10 }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ruby/setup-ruby@145243922b4465b78e04dd66294782c7de45901f # v1.345.0 + with: + ruby-version: '4.0.7' + bundler-cache: true + - name: Install zsh + if: runner.os == 'Linux' + uses: libtmux/.github/actions/apt-get@30f81842b1e639ea4e25f93f1f2543504178e228 + with: + update: 'true' + args: install --yes zsh + - name: Build the exact tmux release + id: tmux + uses: libtmux/setup-tmux@96c8f0d575eae62d1c3419ef919b69ecc43f3cac # v0.1.0 + with: + version: 3.7c + configure-args: --disable-utf8proc + add-to-path: 'false' + - name: Repeat the integration suite + env: + LIBTMUX_TEST_TMUX: ${{ steps.tmux.outputs.binary }} + run: bundle exec scripts/stress --repeat "$REPEAT" --output build/stress + - name: Report each test's failure count + if: always() + run: cat build/stress/summary.md >> "$GITHUB_STEP_SUMMARY" + - name: Retain the CSV and run logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: stress-${{ matrix.runner }} + path: build/stress/ + if-no-files-found: warn diff --git a/scripts/stress b/scripts/stress new file mode 100755 index 00000000..07cc826e --- /dev/null +++ b/scripts/stress @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "fileutils" +require "open3" +require "optparse" + +# Repeats the real-tmux integration suite and counts each test's failures. +root = File.expand_path("..", __dir__) +Dir.chdir(root) +repeat = 10 +output = "build/stress" +OptionParser.new do |parser| + parser.on("--repeat N", Integer, "suite repetitions") { |value| repeat = value } + parser.on("--output DIR", "directory for the CSV and Markdown table") { |value| output = value } +end.parse! +abort "--repeat must be positive" unless repeat.positive? + +FileUtils.mkdir_p(output) +files = Dir["test/integration/**/*_test.rb", "scripts/*/tests/integration/**/*_test.rb"].sort +counts = Hash.new { |hash, name| hash[name] = {"runs" => 0, "failures" => 0} } +failed_runs = 0 +repeat.times do |index| + out, status = Open3.capture2e(Gem.ruby, "-Itest", "-rsupport/sandbox", "-rsupport/replay", + "-e", "ARGV.shift(#{files.length}).each { |file| require File.expand_path(file) }", + *files, "--verbose", "--seed", (index + 1).to_s) + File.write(File.join(output, "run-#{index + 1}.log"), out) + seen = 0 + out.each_line do |line| + next unless (match = line.match(/\A(\S+#\S+) = [\d.]+ s = ([.FES])\s*\z/)) + + seen += 1 + counts[match[1]]["runs"] += 1 + counts[match[1]]["failures"] += 1 if %w[F E].include?(match[2]) + end + abort "run #{index + 1} reported no tests" if seen.zero? + failed_runs += 1 unless status.success? + warn "run #{index + 1}/#{repeat}: #{status.success? ? "passed" : "failed"}" +end + +rows = counts.sort_by { |name, tally| [-tally["failures"], name] } +File.write(File.join(output, "failures.csv"), + (["test,runs,failures"] + rows.map { |name, tally| "#{name},#{tally["runs"]},#{tally["failures"]}" }).join("\n") + "\n") +failing = rows.select { |_, tally| tally["failures"].positive? } +table = +"### Stress run: #{repeat} repetitions, #{failed_runs} failed, #{rows.length} tests\n\n" +if failing.empty? + table << "No test failed.\n" +else + table << "| Test | Runs | Failures |\n| --- | ---: | ---: |\n" + failing.each { |name, tally| table << "| `#{name}` | #{tally["runs"]} | #{tally["failures"]} |\n" } +end +File.write(File.join(output, "summary.md"), table) +puts table +exit(failed_runs.zero? ? 0 : 1) From 690a3f7dbcb6222ef93b72633e95b9606bd1dde7 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 11:00:05 -0500 Subject: [PATCH 04/17] Tests(feat[fixture]): Reject long socket paths why: Darwin's sockaddr_un.sun_path holds 104 bytes, and the macOS temporary directory alone is long. An over-long path made tmux fail with an error that did not name the cause. what: - Make TmuxFixture raise a named error for a socket path of 104 bytes or more and remove its directory - Test a too-long TMPDIR against a short control --- test/integration/fixture_test.rb | 19 +++++++++++++++++++ test/support/tmux_fixture.rb | 8 +++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/test/integration/fixture_test.rb b/test/integration/fixture_test.rb index 1675fda1..ca50ff8e 100644 --- a/test/integration/fixture_test.rb +++ b/test/integration/fixture_test.rb @@ -6,6 +6,17 @@ require_relative "../support/tmux_fixture" class TmuxFixtureTest < Minitest::Test + def test_socket_path_beyond_the_darwin_limit_is_refused_by_name + Dir.mktmpdir("libtmux-ruby-") do |base| + long = File.join(base, "d" * (104 - base.bytesize - "/libtmux-ruby-".bytesize - 8)) + Dir.mkdir(long) + error = with_tmpdir(long) { assert_raises(LibTmuxTest::TmuxFixture::Error) { LibTmuxTest::TmuxFixture.new } } + assert_match(/sun_path limit/, error.message) + assert_empty Dir.children(long) + with_tmpdir(base) { LibTmuxTest::TmuxFixture.new.close } + end + end + def test_explicit_executable_selects_both_owned_daemon_and_client executable = ENV.fetch("LIBTMUX_TEST_TMUX") do ENV.fetch("PATH").split(File::PATH_SEPARATOR).map { |part| File.join(part, "tmux") } @@ -300,4 +311,12 @@ def server_pid(fixture) assert status.success?, error Integer(output, 10) end + + def with_tmpdir(directory) + previous = ENV["TMPDIR"] + ENV["TMPDIR"] = directory + yield + ensure + ENV["TMPDIR"] = previous + end end diff --git a/test/support/tmux_fixture.rb b/test/support/tmux_fixture.rb index 14ef879a..a4c16a2b 100644 --- a/test/support/tmux_fixture.rb +++ b/test/support/tmux_fixture.rb @@ -54,7 +54,9 @@ def value CLEAN_ENV = {"TMUX" => nil, "TMUX_PANE" => nil}.freeze DEADLINE_SECONDS = HANG_GUARD_SECONDS - private_constant :CLEAN_ENV, :DEADLINE_SECONDS + # Darwin's sockaddr_un.sun_path limit, terminator included. + SOCKET_PATH_LIMIT = 104 + private_constant :CLEAN_ENV, :DEADLINE_SECONDS, :SOCKET_PATH_LIMIT attr_reader :socket_path, :cleanup_errors, :executable @@ -90,6 +92,10 @@ def initialize(executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")) @process_wait = LibTmux::Internal::ProcessWait.new @directory = Dir.mktmpdir("libtmux-ruby-") @socket_path = File.join(@directory, "socket") + if @socket_path.bytesize >= SOCKET_PATH_LIMIT + FileUtils.remove_entry(@directory) + raise Error, "fixture socket path exceeds the #{SOCKET_PATH_LIMIT - 1}-byte sun_path limit; set TMPDIR to a shorter directory" + end @clients = {} @clients_mutex = Mutex.new @retirement_mutex = Mutex.new From 03d830dbb40eea37cbe3485ea38af3716b3cf89a Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 11:00:05 -0500 Subject: [PATCH 05/17] Docs(feat[macos]): Add MACOS_CI.md why: Tests that pass on Linux failed on the macOS runner through timing, path and process differences. Contributors need the rules and a way to reproduce each on Linux. what: - Add .github/MACOS_CI.md and link it from CONTRIBUTING.md - List the helpers this repository uses to follow it --- .github/CONTRIBUTING.md | 3 ++ .github/MACOS_CI.md | 65 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100755 .github/MACOS_CI.md diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d3ab2271..38523672 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -280,6 +280,9 @@ that `Endpoint` resolves the default to the same path. Two controls run the same client with another `TMUX_TMPDIR` and with an inherited `TMUX`, and require the canary's own test to reject both. +Tests must also pass on macOS; [MACOS_CI.md](MACOS_CI.md) lists what that +requires. + Record the actual tmux version when behavior depends on it. A passing subset does not establish support for an entire version range. diff --git a/.github/MACOS_CI.md b/.github/MACOS_CI.md new file mode 100755 index 00000000..7973aace --- /dev/null +++ b/.github/MACOS_CI.md @@ -0,0 +1,65 @@ +# macOS CI + +What a test needs so it passes on macOS as well as Linux. + +## Waiting + +- **Wait for the event, not the clock.** Subscribe, act, then wait for the + notification, `wait-for` channel, hook, or pane output the action causes. + Keep a timeout only as a hang guard. The macOS runner is slower to start + processes, so a deadline tuned on Linux fails there. +- **Read after the change, not after the command.** tmux renames windows, + starts pane processes and draws output after the command returns. Name + windows yourself unless the name is what the test checks. +- **Wait for the shell before typing.** Keys typed before the shell is ready + are echoed back, and a text wait can match a command that never ran. +- **Read control-mode output all the time.** tmux stops reading panes when its + only attached client is a control client nobody reads. + +## Paths and sockets + +- **Compare physical paths.** tmux reports `/private/tmp/...` for `/tmp/...`. + Resolve the expected path before comparing. +- **Keep socket paths short.** A socket path must fit in 104 bytes, and the + macOS temporary directory is long. Put sockets under a short directory. +- **Poll for a socket; don't watch for it.** Watchers built on FSEvents + (libuv, .NET, Julia) do not report a socket being created. + +## Shells and processes + +- **`/bin/sh` is bash 3.2.** Pin the pane's shell, avoid bash 4 syntax, and + expect `pane_current_command` to say `bash`. +- **No `/proc`, no `/bin/false`.** Use `ps` or tmux formats, and `false` from + `PATH`. +- **Reap before signalling a process group.** `killpg` fails with EPERM when + every member has exited but has not been reaped. +- **Stay well under 511 terminals.** Past that, tmux reports + `fork failed: Device not configured`. Kill every server a test starts. +- **Keep typed input under 1 KB.** Longer input is dropped. Send long text + through a file or a paste buffer. +- **Read a pane until its process exits.** On macOS a process cannot finish + exiting while its terminal output is unread. + +## Building tmux + +Configure with `--enable-utf8proc --enable-jemalloc`. Recent tmux refuses to +configure on macOS without a choice for both. + +## Reproducing on Linux + +- Slow runner: pin the test to one CPU beside busy loops, or put a `tmux` + wrapper that sleeps first on `PATH`. +- Physical paths: point the test's temporary directory at a symlink. +- `/bin/sh` as bash: `set -g default-shell /bin/sh` and + `set -g default-command "/bin/bash -i"`. +- Long socket paths: set `TMPDIR` to a deep directory. + +## In this repository + +- Event waits in tests and `TmuxFixture` use `HANG_GUARD_SECONDS` from + `test/test_helper.rb`. +- Tests that prove a deadline is enforced advance a clock the code reads, as in + `OperationBudgetTest` and `MCPMutationTest::AdvancingClock`. +- `TmuxFixture` refuses a socket path that does not fit and names the cause. +- `scripts/stress` and the stress workflow repeat the integration suite on + macOS with a Linux control. From 2d8ac47d6fd572b81fb9fca47742bbffbf0dd806 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:24:01 -0500 Subject: [PATCH 06/17] Tests(fix[async]): Guard the Async scope why: `with_scope` wrapped every async test in `with_timeout(0.8)`. That one bound covers ruby child spawns, 32-request admission, control opens and `Async.open`. A slow process start on a loaded runner expired it, so tests failed with `Async::TimeoutError` although nothing hung. what: - Replace the 0.8 s bound with `HANG_GUARD_SECONDS` (10 s). - Tests still return as soon as their events happen; the bound fires only when a test hangs. Evidence: pinned to one CPU beside 40 busy loops, async_test had 1 failure and 12 errors in 22 tests before this series and none after it. The slowest macOS async test in the 50-repetition stress run (run 37201292911) took 0.29 s, so 10 s is more than 30x it. --- test/integration/async_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/async_test.rb b/test/integration/async_test.rb index 4725a831..ecddab56 100644 --- a/test/integration/async_test.rb +++ b/test/integration/async_test.rb @@ -829,7 +829,7 @@ def with_scope(control: false, **options) LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |source| Async do |parent| - parent.with_timeout(0.8) do + parent.with_timeout(HANG_GUARD_SECONDS) do LibTmux::Async.open(parent: parent, server: source, **options) do |scope| next if control && !require_control_support(scope.server) From f38675eecff939c1fff127ef702b08e807474f3e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:24:02 -0500 Subject: [PATCH 07/17] Scripts(fix[bench]): Guard request waits why: `budget` capped every benchmark `timeout:` at 0.5 s, including `Server.start`, session creation, `wait_for` readiness and cleanup waits. A slow tmux or ruby start aborted the run with a deadline error. The benchmark times its own phases, so the cap only guards against hangs. what: - Raise `DEADLINE` from 0.5 s to 10 s. - Raise the 0.2 s `IO.select` that waits for the pipelined second request to be written to `DEADLINE`. --- scripts/bench | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/bench b/scripts/bench index 6e3705d4..5be39d88 100755 --- a/scripts/bench +++ b/scripts/bench @@ -20,7 +20,7 @@ require "etc" # transport the same acquisition work, then measures graph/query work separately. module TmuxBenchmark LANES = %w[process_serial async_bounded control_serial control_pipelined group].freeze - DEADLINE = 0.5 + DEADLINE = 10 MAX_RUN_SECONDS = 540 ROOT = File.expand_path("..", __dir__) CATALOG = LibTmux.const_get(:Internal)::Catalog @@ -616,7 +616,7 @@ module TmuxBenchmark end @server.wait_for(ready, timeout: budget) second = Thread.new { @control.exchange("display-message -p pipeline-second", timeout: budget) } - TmuxBenchmark.check(IO.select([reader], nil, nil, 0.2), "second control request waited for the first reply") + TmuxBenchmark.check(IO.select([reader], nil, nil, DEADLINE), "second control request waited for the first reply") TmuxBenchmark.check(first.alive? && second.alive?, "pipeline witness did not retain the first WAIT") peaks = @peaks.snapshot.find { |meter| meter.fetch(:kind) == :control }.fetch(:peaks) TmuxBenchmark.check(peaks.fetch(:unretired_requests) >= 2 && peaks.fetch(:written_unretired_requests) >= 2, From 6dd087a5f5d11b07f907a4ad70f5ef925b6f40ff Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:30:47 -0500 Subject: [PATCH 08/17] Tests(fix[spawn]): Guard process startup why: Several tests put a 0.08 to 1 s deadline around a step that starts a ruby or tmux client. On a loaded or slow-spawning runner the deadline fired before the process started, so the test failed on a hang-guard error, not on the behavior it checks. None of these tests asserts how fast a process starts. what: - Cleanup budgets that retire a TERM-ignoring child and assert empty `cleanup_errors` or a reaped pid use `HANG_GUARD_SECONDS`: two async_test tests (0.08 s) and one process_test test (0.1 s). The map-failure test also asserts ECHILD after cleanup, so it is not a deadline test and leaves the 0.08 s group. - `link.select` that must reach a tmux hook before the test cancels it (operation_budget_test, 0.5 s) and the terminal attach that covers client start (terminal_test, 1 s) use `HANG_GUARD_SECONDS`. - The installed MCP helper protocol deadline, executor timeout, connect wait and owner join (package_test, 0.5 s) share one `hang_guard` value passed in from `HANG_GUARD_SECONDS`. - The whole-command deadline on a ruby child that must write READY first (process_test, 0.1 s) becomes 2 s, and the join after it uses `HANG_GUARD_SECONDS`. The test checks that a deadline after dispatch reports possible effects. The executor has no injectable clock, so the deadline stays real; 2 s keeps the test short while leaving the child time to start. Evidence: with a `tmux` shim that sleeps before each exec, the operation_budget test errors at 0.7 s and 1.2 s per spawn before and passes after, and the terminal attach test errors at both delays before and passes after. --- test/integration/async_test.rb | 4 ++-- test/integration/operation_budget_test.rb | 2 +- test/integration/terminal_test.rb | 2 +- test/packaging/package_test.rb | 11 ++++++----- test/unit/process_test.rb | 6 +++--- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/test/integration/async_test.rb b/test/integration/async_test.rb index ecddab56..20d3edc2 100644 --- a/test/integration/async_test.rb +++ b/test/integration/async_test.rb @@ -216,7 +216,7 @@ def test_admission_caps_four_children_and_thirty_two_requests end def test_repeated_caller_cancellation_reaps_a_child_ignoring_term - with_scope(cleanup_timeout: 0.08) do |scope, parent, fixture| + with_scope(cleanup_timeout: HANG_GUARD_SECONDS) do |scope, parent, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "async-cancel")) reaping, notify = IO.pipe release = Queue.new @@ -307,7 +307,7 @@ def test_wrong_thread_closed_binding_and_byte_admission_are_refused end def test_map_failure_survives_repeated_cancellation_while_siblings_retire - with_scope(cleanup_timeout: 0.08) do |scope, parent, fixture| + with_scope(cleanup_timeout: HANG_GUARD_SECONDS) do |scope, parent, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "async-map-error")) reaping, notify = IO.pipe release = Queue.new diff --git a/test/integration/operation_budget_test.rb b/test/integration/operation_budget_test.rb index cef28e2b..0050322e 100644 --- a/test/integration/operation_budget_test.rb +++ b/test/integration/operation_budget_test.rb @@ -61,7 +61,7 @@ def test_cancellation_retires_a_typed_link_preflight_blocked_in_a_hook token = LibTmux::Internal::Cancellation.new assert fixture.tmux("set-hook", "-g", "after-show-options[98]", "wait-for -S budget-ready ; wait-for budget-held").last.success? request = Thread.new do - link.select(timeout: 0.5, cancel: token) + link.select(timeout: HANG_GUARD_SECONDS, cancel: token) rescue StandardError => error error end diff --git a/test/integration/terminal_test.rb b/test/integration/terminal_test.rb index f62c7061..5bc2459a 100644 --- a/test/integration/terminal_test.rb +++ b/test/integration/terminal_test.rb @@ -92,7 +92,7 @@ def test_explicit_terminal_attach_and_user_detach_return_final_status slave.winsize = [24, 80] before = slave.echo? assert server.run(["set-hook", "-g", "client-attached", "wait-for -S terminal-attached"]).success? - worker = Thread.new { server.attach(session: session.ref, terminal: slave, term: "xterm", timeout: 1) } + worker = Thread.new { server.attach(session: session.ref, terminal: slave, term: "xterm", timeout: HANG_GUARD_SECONDS) } begin assert fixture.tmux("wait-for", "terminal-attached").last.success? assert_equal 1, server.list_clients.length diff --git a/test/packaging/package_test.rb b/test/packaging/package_test.rb index 784b0dca..22b7a4f2 100644 --- a/test/packaging/package_test.rb +++ b/test/packaging/package_test.rb @@ -234,6 +234,7 @@ def run_installed_job_recipe(environment, directory, *ruby_options) def run_installed_shell_helper(environment, directory) source = <<~'RUBY' + hang_guard = Float(ARGV.fetch(0)) require 'libtmux/mcp' require 'libtmux/mcp/enrollment' path = File.join(Dir.pwd, 'helper.sock') @@ -251,12 +252,12 @@ def run_installed_shell_helper(environment, directory) script = "printf '%s\\n' \"$PWD\" \"$TMUX\" \"$TMUX_PANE\"; printf '\\000\\377' >&2; exit 9" digest = Digest::SHA256.hexdigest(script) run_id = 'a' * 32 - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + hang_guard command = ['/usr/bin/env', 'TMUX=literal $value;#', 'TMUX_PANE=%23', "RUBYOPT=-r#{poison}/poison", "RUBYLIB=#{poison}", "GEM_HOME=#{poison}", "GEM_PATH=#{poison}", ruby, '--disable=rubyopt,gems', '-I', load_path, helper, [path].pack('m0'), token, deadline.to_s, run_id, digest, 'ready'] - worker = Thread.new { LibTmux::Internal::ProcessExecutor.new.run(command, timeout: 0.5) } + worker = Thread.new { LibTmux::Internal::ProcessExecutor.new.run(command, timeout: hang_guard) } begin - raise 'installed helper did not connect' unless IO.select([listener], nil, nil, 0.5) + raise 'installed helper did not connect' unless IO.select([listener], nil, nil, hang_guard) peer = listener.accept read_line = lambda do line = +''.b @@ -278,11 +279,11 @@ def run_installed_shell_helper(environment, directory) peer&.close listener.close File.unlink(path) - raise 'helper owner did not settle' unless worker.join(0.5) + raise 'helper owner did not settle' unless worker.join(hang_guard) end raise 'helper failed' unless worker.value.success? RUBY - output, status = Open3.capture2e(environment, Gem.ruby, '-W:no-experimental', '-e', source, chdir: directory) + output, status = Open3.capture2e(environment, Gem.ruby, '-W:no-experimental', '-e', source, HANG_GUARD_SECONDS.to_s, chdir: directory) assert status.success?, "installed authored helper closure failed: #{output}" assert_empty output, 'installed authored helper wrote protocol data outside its socket' end diff --git a/test/unit/process_test.rb b/test/unit/process_test.rb index c4c8b698..0ef24341 100644 --- a/test/unit/process_test.rb +++ b/test/unit/process_test.rb @@ -97,7 +97,7 @@ def test_cancellation_escalates_and_reaps_a_child_ignoring_term cancellation = LibTmux::Cancellation.new with_child_readiness do |ready, environment| worker = task do - executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment, cancel: cancellation) + executor(cleanup_timeout: HANG_GUARD_SECONDS).run(ruby(<<~RUBY), env: environment, cancel: cancellation) trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe @@ -125,14 +125,14 @@ def test_cancellation_escalates_and_reaps_a_child_ignoring_term def test_deadline_after_dispatch_reports_possible_effects with_child_readiness do |ready, environment| worker = task do - executor.run(ruby(<<~RUBY), env: environment, timeout: 0.1) + executor.run(ruby(<<~RUBY), env: environment, timeout: 2.0) File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY end pid = Integer(read_event(ready), 10) - assert worker.join(0.5), "deadline did not retire the owned client" + assert worker.join(HANG_GUARD_SECONDS), "deadline did not retire the owned client" error = worker.value assert_instance_of LibTmux::DeadlineExceeded, error From 50a83a1920588c047f0c5e900e908e0d28f03db2 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:31:05 -0500 Subject: [PATCH 09/17] Tests(fix[waits]): Guard process and budget waits why: Joins and selects that wait for a spawned ruby child to start, connect, exit or be reaped used a 0.5 s literal beside `HANG_GUARD_SECONDS`, so the shared guard never applied to them. Each wait returns when its event arrives; the literal only failed a test whose child started late. what: - process_test: 16 asserted joins and selects, and the READY `read_event` deadline, move from 0.5 s to `HANG_GUARD_SECONDS`. - operation_budget_test: the join after cancelling a blocked preflight moves from 0.5 s to `HANG_GUARD_SECONDS`. - Joins inside `ensure` blocks stay at 0.5 s: they only release threads after a failure and assert nothing. Evidence: pinned to one CPU beside 40 busy loops, process_test had 11 failures in 21 tests before this series and none after it. --- test/integration/operation_budget_test.rb | 2 +- test/unit/process_test.rb | 34 +++++++++++------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/test/integration/operation_budget_test.rb b/test/integration/operation_budget_test.rb index 0050322e..274f2982 100644 --- a/test/integration/operation_budget_test.rb +++ b/test/integration/operation_budget_test.rb @@ -68,7 +68,7 @@ def test_cancellation_retires_a_typed_link_preflight_blocked_in_a_hook begin assert fixture.tmux("wait-for", "budget-ready").last.success? token.cancel - assert request.join(0.5), "cancellation did not retire the blocked preflight" + assert request.join(HANG_GUARD_SECONDS), "cancellation did not retire the blocked preflight" assert_instance_of LibTmux::Cancelled, request.value assert_equal :possibly_sent, request.value.delivery assert_equal "@0\n", session.display('#{window_id}').text diff --git a/test/unit/process_test.rb b/test/unit/process_test.rb index 0ef24341..9874a779 100644 --- a/test/unit/process_test.rb +++ b/test/unit/process_test.rb @@ -106,7 +106,7 @@ def test_cancellation_escalates_and_reaps_a_child_ignoring_term end pid = Integer(read_event(ready), 10) 20.times { cancellation.cancel } - assert worker.join(0.5), "cancellation did not retire the owned client" + assert worker.join(HANG_GUARD_SECONDS), "cancellation did not retire the owned client" error = worker.value assert_instance_of LibTmux::Cancelled, error @@ -158,12 +158,12 @@ def test_drain_deadline_bounds_a_pipe_retained_after_child_exit socket.close RUBY end - assert IO.select([server], nil, nil, 0.5), "child did not connect for pipe transfer" + assert IO.select([server], nil, nil, HANG_GUARD_SECONDS), "child did not connect for pipe transfer" connection = server.accept - assert IO.select([connection], nil, nil, 0.5), "child did not transfer its pipe" + assert IO.select([connection], nil, nil, HANG_GUARD_SECONDS), "child did not transfer its pipe" retained = connection.recv_io connection.close - assert worker.join(0.5), "another pipe owner prevented bounded command cleanup" + assert worker.join(HANG_GUARD_SECONDS), "another pipe owner prevented bounded command cleanup" error = worker.value assert_instance_of LibTmux::DeadlineExceeded, error @@ -193,7 +193,7 @@ def test_thread_exception_survives_owned_cleanup end pid = Integer(read_event(ready), 10) worker.raise(failure) - assert worker.join(0.5), "interrupted caller did not retire its client" + assert worker.join(HANG_GUARD_SECONDS), "interrupted caller did not retire its client" assert_same failure, worker.value assert_reaped(pid) @@ -230,7 +230,7 @@ def test_repeated_thread_cancellation_does_not_replace_the_first_failure assert_equal "reaping", read_event(ready) worker.raise(later) release << true - assert worker.join(0.5), "repeated cancellation stranded cleanup" + assert worker.join(HANG_GUARD_SECONDS), "repeated cancellation stranded cleanup" assert_same original, worker.value assert_reaped(pid) @@ -276,7 +276,7 @@ def test_exit_observation_leaves_child_waitable_until_owner_reaps wait = LibTmux::Internal::ProcessWait.new pid = Process.spawn(*ruby("exit 17"), out: File::NULL, err: File::NULL, close_others: true) observer = task { wait.observe(pid) } - assert observer.join(0.5), "exit observation did not complete" + assert observer.join(HANG_GUARD_SECONDS), "exit observation did not complete" raise observer.value if observer.value.is_a?(Exception) assert_equal 1, Process.kill(0, pid) assert_equal 1, Process.kill("TERM", pid) @@ -305,13 +305,13 @@ def test_shared_child_owner_reaps_only_after_final_signal_handoff child = LibTmux::Internal::OwnedChild.new pid = Process.spawn(*ruby("exit 17"), out: File::NULL, err: File::NULL, close_others: true) child.spawned(pid) - assert IO.select([child.reader], nil, nil, 0.5), "child observation did not notify its owner" + assert IO.select([child.reader], nil, nil, HANG_GUARD_SECONDS), "child observation did not notify its owner" assert child.observed? refute child.join(0), "observation must retain the wait obligation until final signalling" LibTmux::Internal::ProcessWait.new.observe(pid) child.finish_signalling assert_nil child.signal("KILL"), "retired signal permission must never use a recycled PID" - assert child.join(0.5), "native reaping bridge did not finish" + assert child.join(HANG_GUARD_SECONDS), "native reaping bridge did not finish" assert_equal 17, child.status.exitstatus assert_nil child.observation_error assert_nil child.retirement_error @@ -344,7 +344,7 @@ def test_observed_exit_wins_cancellation_before_native_status_publication end trace.enable worker = task { executor(cleanup_timeout: 0.02).run(ruby('STDOUT.write("done")'), cancel: cancel) } - assert worker.join(0.5), "observed command did not finish its bounded drain" + assert worker.join(HANG_GUARD_SECONDS), "observed command did not finish its bounded drain" assert_instance_of LibTmux::CommandResult, worker.value assert_equal "done", worker.value.stdout assert worker.value.success? @@ -371,10 +371,10 @@ def test_incomplete_cleanup_retains_the_obligation_to_reap end pid = Integer(read_event(ready), 10) cancellation.cancel - assert worker.join(0.5), "cleanup did not respect its deadline" + assert worker.join(HANG_GUARD_SECONDS), "cleanup did not respect its deadline" assert_instance_of LibTmux::Cancelled, worker.value (Thread.list - before).each do |thread| - assert thread.join(0.5), "an incomplete cleanup lost its owned retirement task" + assert thread.join(HANG_GUARD_SECONDS), "an incomplete cleanup lost its owned retirement task" end assert_reaped(pid) ensure @@ -430,7 +430,7 @@ def test_interrupted_exit_observer_does_not_abandon_a_live_owned_child end pid = Integer(read_event(ready), 10) release << true - assert worker.join(0.5), "failed exit observer did not release command ownership" + assert worker.join(HANG_GUARD_SECONDS), "failed exit observer did not release command ownership" assert_instance_of LibTmux::TransportError, worker.value assert_reaped(pid) ensure @@ -475,12 +475,12 @@ def test_late_observer_failure_receives_reaping_ownership_after_final_signal pid = Integer(read_event(ready), 10) cancellation.cancel witness = task { LibTmux::Internal::ProcessWait.new.observe(pid) } - assert witness.join(0.5), "final kill did not make the child waitable" + assert witness.join(HANG_GUARD_SECONDS), "final kill did not make the child waitable" raise witness.value if witness.value.is_a?(Exception) release << true - assert worker.join(0.5), "late observer failure lost its retirement token" + assert worker.join(HANG_GUARD_SECONDS), "late observer failure lost its retirement token" assert_instance_of LibTmux::Cancelled, worker.value - assert selected.join(0.5), "late observer did not retain its reaping obligation" + assert selected.join(HANG_GUARD_SECONDS), "late observer did not retain its reaping obligation" assert_reaped(pid) ensure trace.disable @@ -528,7 +528,7 @@ def with_child_readiness end def read_event(io) - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + HANG_GUARD_SECONDS value = +"" until value.end_with?("\n") remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) From d79fc4a84118a89a9b8e2b6067971ce106dbe945 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:32:36 -0500 Subject: [PATCH 10/17] Examples(fix[waits]): Guard example waits why: The shipped examples bounded readiness, held requests and process exits at 1 or 5 s. Each wait returns as soon as its event arrives, so the bound only fails a hung example, yet a slow tmux or ruby start on a loaded machine could still exhaust it. Readers copy these numbers, so they should be sized for the slowest start. what: - Raise every positive wait in examples/ from 1 or 5 s to 10 s: control exchanges, `wait_for`, held requests, `output.next`, MCP frame reads, shell connect and setup, and the MCP process exit. - Update the "five seconds" error text in api/capture.rb. - Regenerate the recipe and async README excerpts with `scripts/examples --write`. - With a `tmux` shim that sleeps 1.2 s before each exec, api/capture.rb fails with a control request deadline before this change and passes after. --- README.md | 2 +- docs/recipes.md | 22 +++++++++++----------- examples/api/capture.rb | 2 +- examples/async_cancel.rb | 4 ++-- examples/cancel.rb | 4 ++-- examples/control_overflow.rb | 10 +++++----- examples/layout_io.rb | 8 ++++---- examples/mcp_protocol.rb | 6 +++--- examples/support.rb | 4 ++-- gems/libtmux/README.md | 2 +- 10 files changed, 32 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index aaec5a72..e6bd0d3f 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ require "libtmux" require "rbconfig" def wait_until(message) - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10 loop do remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) raise message unless remaining.positive? diff --git a/docs/recipes.md b/docs/recipes.md index 84ea3c06..f10db4ca 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -70,10 +70,10 @@ LibTmux::Server.start do |server| pane.send_text("printf '\\n%s %s\\n' 'pane' 'prĂȘte'") pane.send_keys("Enter") end - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10 if server.supports_control? server.open_control(session: receipt.entity.ref) do |control| - control.exchange("display-message -p ready") + control.exchange("display-message -p ready", timeout: 10) output = control.subscribe( pane_id: pane.id, max_bytes: 8192, max_events: 32 ) @@ -81,7 +81,7 @@ LibTmux::Server.start do |server| received = +"".b until received.include?(expected.b) remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) - raise "No pane reply within five seconds" unless remaining.positive? + raise "No pane reply within ten seconds" unless remaining.positive? event = output.next(timeout: remaining) received << event.data if event.data end @@ -95,7 +95,7 @@ LibTmux::Server.start do |server| break if lines.include?(expected) if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline - raise "No captured reply within five seconds" + raise "No captured reply within ten seconds" end sleep 0.02 end @@ -187,11 +187,11 @@ LibTmux::Server.start do |server| LibTmux::Async.open(parent: parent, server: server) do |scope| waiting = parent.async do scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5) + timeout: 10) rescue LibTmux::Cancelled => error error end - scope.server.wait_for("ready", timeout: 5) + scope.server.wait_for("ready", timeout: 10) panes = scope.server.list_panes.map(&:ref) captures = scope.map(panes, concurrency: 2) do |ref| scope.server.pane(ref).capture @@ -243,24 +243,24 @@ LibTmux::Server.start do |server| end server.open_control(session: session.ref) do |control| - control.exchange("display-message -p ready", timeout: 5) + control.exchange("display-message -p ready", timeout: 10) reliable = control.subscribe(max_events: 1, max_bytes: 1024) tail = control.subscribe(mode: :tail, max_events: 1, max_bytes: 1024) 3.times { |index| window.rename("event#{index}") } - reply = control.exchange("display-message -p alive", timeout: 5) + reply = control.exchange("display-message -p alive", timeout: 10) raise "Expected the reply alive" unless reply.blocks.last.body == "alive\n" unless reply.attribution == :boundary_window raise "Reply names the wrong source" end - reliable.next(timeout: 5) + reliable.next(timeout: 10) begin - reliable.next(timeout: 5) + reliable.next(timeout: 10) raise "Expected the reliable subscriber to report overflow" rescue LibTmux::SubscriptionOverflow end - gap = tail.next(timeout: 5) + gap = tail.next(timeout: 10) raise "Expected an output gap with dropped bytes" unless gap.kind == :gap && gap.dropped_bytes.positive? end diff --git a/examples/api/capture.rb b/examples/api/capture.rb index a4b3f8f5..95e7d075 100644 --- a/examples/api/capture.rb +++ b/examples/api/capture.rb @@ -5,7 +5,7 @@ require "rbconfig" def wait_until(message) - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10 loop do remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) raise message unless remaining.positive? diff --git a/examples/async_cancel.rb b/examples/async_cancel.rb index 16b6fa5e..dda05708 100644 --- a/examples/async_cancel.rb +++ b/examples/async_cancel.rb @@ -10,11 +10,11 @@ LibTmux::Async.open(parent: parent, server: server) do |scope| waiting = parent.async do scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5) + timeout: 10) rescue LibTmux::Cancelled => error error end - scope.server.wait_for("ready", timeout: 5) + scope.server.wait_for("ready", timeout: 10) panes = scope.server.list_panes.map(&:ref) captures = scope.map(panes, concurrency: 2) do |ref| scope.server.pane(ref).capture diff --git a/examples/cancel.rb b/examples/cancel.rb index 08ce1018..b96c9491 100644 --- a/examples/cancel.rb +++ b/examples/cancel.rb @@ -11,11 +11,11 @@ begin waiting = Thread.new do server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5, cancel: cancellation) + timeout: 10, cancel: cancellation) rescue LibTmux::Cancelled => error error end - server.wait_for("ready", timeout: 5) + server.wait_for("ready", timeout: 10) cancellation.cancel failure = waiting.value Example.check(failure.is_a?(LibTmux::Cancelled), "cancellation lost") diff --git a/examples/control_overflow.rb b/examples/control_overflow.rb index 4d9c79ac..94219729 100644 --- a/examples/control_overflow.rb +++ b/examples/control_overflow.rb @@ -17,24 +17,24 @@ end server.open_control(session: session.ref) do |control| - control.exchange("display-message -p ready", timeout: 5) + control.exchange("display-message -p ready", timeout: 10) reliable = control.subscribe(max_events: 1, max_bytes: 1024) tail = control.subscribe(mode: :tail, max_events: 1, max_bytes: 1024) 3.times { |index| window.rename("event#{index}") } - reply = control.exchange("display-message -p alive", timeout: 5) + reply = control.exchange("display-message -p alive", timeout: 10) raise "Expected the reply alive" unless reply.blocks.last.body == "alive\n" unless reply.attribution == :boundary_window raise "Reply names the wrong source" end - reliable.next(timeout: 5) + reliable.next(timeout: 10) begin - reliable.next(timeout: 5) + reliable.next(timeout: 10) raise "Expected the reliable subscriber to report overflow" rescue LibTmux::SubscriptionOverflow end - gap = tail.next(timeout: 5) + gap = tail.next(timeout: 10) raise "Expected an output gap with dropped bytes" unless gap.kind == :gap && gap.dropped_bytes.positive? end diff --git a/examples/layout_io.rb b/examples/layout_io.rb index 9fae1033..3504d956 100644 --- a/examples/layout_io.rb +++ b/examples/layout_io.rb @@ -21,10 +21,10 @@ pane.send_text("printf '\\n%s %s\\n' 'pane' 'prĂȘte'") pane.send_keys("Enter") end - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10 if server.supports_control? server.open_control(session: receipt.entity.ref) do |control| - control.exchange("display-message -p ready") + control.exchange("display-message -p ready", timeout: 10) output = control.subscribe( pane_id: pane.id, max_bytes: 8192, max_events: 32 ) @@ -32,7 +32,7 @@ received = +"".b until received.include?(expected.b) remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) - raise "No pane reply within five seconds" unless remaining.positive? + raise "No pane reply within ten seconds" unless remaining.positive? event = output.next(timeout: remaining) received << event.data if event.data end @@ -46,7 +46,7 @@ break if lines.include?(expected) if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline - raise "No captured reply within five seconds" + raise "No captured reply within ten seconds" end sleep 0.02 end diff --git a/examples/mcp_protocol.rb b/examples/mcp_protocol.rb index f28045a7..0a6a2042 100644 --- a/examples/mcp_protocol.rb +++ b/examples/mcp_protocol.rb @@ -40,14 +40,14 @@ Example.check(application.call("tmux_close", {}).structured_content.dig("error", "code") == "policy_denied", "default policy permits mutation") cancellations = Queue.new sdk.define_custom_method(method_name: "example/wait") do |_, server_context:| - scope.server.run(["wait-for", "-S", "protocol-ready", ";", "wait-for", "protocol-held"], timeout: 5) + scope.server.run(["wait-for", "-S", "protocol-ready", ";", "wait-for", "protocol-held"], timeout: 10) {finished: true} rescue LibTmux::Cancelled => failure cancellations << failure {cancelled: true} end send_request.call(4, "example/wait", {_meta: envelope}) - scope.server.wait_for("protocol-ready", timeout: 5) + scope.server.wait_for("protocol-ready", timeout: 10) client_input.write(JSON.generate({jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 4}}) + "\n") send_request.call(5, "tools/call", {name: "tmux_capabilities", arguments: {}, _meta: envelope}) Example.check(receive.call("tmux_capabilities after cancellation").fetch("id") == 5, "cancelled request blocked protocol reader") @@ -57,7 +57,7 @@ ensure failure = $! cleanup = [-> { client_input&.close unless client_input&.closed? }, - -> { runner&.wait(timeout: 5) }, -> { transport&.close }, -> { application&.close }] + -> { runner&.wait(timeout: 10) }, -> { transport&.close }, -> { application&.close }] cleanup.concat([input, output, client_output].compact.map { |io| -> { io.close unless io.closed? } }) cleanup.each do |action| action.call diff --git a/examples/support.rb b/examples/support.rb index 714cb205..170adfc9 100644 --- a/examples/support.rb +++ b/examples/support.rb @@ -5,8 +5,8 @@ module Example MCP_STARTUP_TIMEOUT = 10 - MCP_RESPONSE_TIMEOUT = 5 - MCP_SHUTDOWN_TIMEOUT = 5 + MCP_RESPONSE_TIMEOUT = 10 + MCP_SHUTDOWN_TIMEOUT = 10 class FrameReader MAX_BYTES = 1 << 20 diff --git a/gems/libtmux/README.md b/gems/libtmux/README.md index 70b2e3e8..8625c68f 100644 --- a/gems/libtmux/README.md +++ b/gems/libtmux/README.md @@ -341,7 +341,7 @@ require "libtmux" require "rbconfig" def wait_until(message) - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10 loop do remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) raise message unless remaining.positive? From 347633812489848d67388f5d2425eab7c1b03a64 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:35:50 -0500 Subject: [PATCH 11/17] Scripts(feat[stress]): Record slowest runs why: Sizing a hang guard needs the slowest observed duration of the steps it bounds. The stress logs held per-test durations but the CSV and summary dropped them, and the unit tests that spawn ruby children never ran on macOS under repetition. what: - Add a `slowest_seconds` column to `failures.csv`. - Add a table of the five slowest tests to `summary.md`. - Include `test/unit/process_test.rb` in each repetition. --- .github/workflows/stress.yml | 2 +- scripts/stress | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.github/workflows/stress.yml b/.github/workflows/stress.yml index d3f39a6c..ca201448 100644 --- a/.github/workflows/stress.yml +++ b/.github/workflows/stress.yml @@ -52,7 +52,7 @@ jobs: with: version: 3.7c configure-args: --disable-utf8proc - add-to-path: 'false' + add-to-path: 'true' - name: Repeat the integration suite env: LIBTMUX_TEST_TMUX: ${{ steps.tmux.outputs.binary }} diff --git a/scripts/stress b/scripts/stress index 07cc826e..a20f89da 100755 --- a/scripts/stress +++ b/scripts/stress @@ -17,8 +17,9 @@ end.parse! abort "--repeat must be positive" unless repeat.positive? FileUtils.mkdir_p(output) -files = Dir["test/integration/**/*_test.rb", "scripts/*/tests/integration/**/*_test.rb"].sort -counts = Hash.new { |hash, name| hash[name] = {"runs" => 0, "failures" => 0} } +files = (Dir["test/integration/**/*_test.rb", "scripts/*/tests/integration/**/*_test.rb"] + + %w[test/unit/process_test.rb]).sort +counts = Hash.new { |hash, name| hash[name] = {"runs" => 0, "failures" => 0, "slowest" => 0.0} } failed_runs = 0 repeat.times do |index| out, status = Open3.capture2e(Gem.ruby, "-Itest", "-rsupport/sandbox", "-rsupport/replay", @@ -27,11 +28,12 @@ repeat.times do |index| File.write(File.join(output, "run-#{index + 1}.log"), out) seen = 0 out.each_line do |line| - next unless (match = line.match(/\A(\S+#\S+) = [\d.]+ s = ([.FES])\s*\z/)) + next unless (match = line.match(/\A(\S+#\S+) = ([\d.]+) s = ([.FES])\s*\z/)) seen += 1 counts[match[1]]["runs"] += 1 - counts[match[1]]["failures"] += 1 if %w[F E].include?(match[2]) + counts[match[1]]["failures"] += 1 if %w[F E].include?(match[3]) + counts[match[1]]["slowest"] = [counts[match[1]]["slowest"], match[2].to_f].max end abort "run #{index + 1} reported no tests" if seen.zero? failed_runs += 1 unless status.success? @@ -40,7 +42,7 @@ end rows = counts.sort_by { |name, tally| [-tally["failures"], name] } File.write(File.join(output, "failures.csv"), - (["test,runs,failures"] + rows.map { |name, tally| "#{name},#{tally["runs"]},#{tally["failures"]}" }).join("\n") + "\n") + (["test,runs,failures,slowest_seconds"] + rows.map { |name, tally| "#{name},#{tally["runs"]},#{tally["failures"]},#{tally["slowest"]}" }).join("\n") + "\n") failing = rows.select { |_, tally| tally["failures"].positive? } table = +"### Stress run: #{repeat} repetitions, #{failed_runs} failed, #{rows.length} tests\n\n" if failing.empty? @@ -49,6 +51,8 @@ else table << "| Test | Runs | Failures |\n| --- | ---: | ---: |\n" failing.each { |name, tally| table << "| `#{name}` | #{tally["runs"]} | #{tally["failures"]} |\n" } end +table << "\n| Slowest test | Seconds |\n| --- | ---: |\n" +rows.max_by(5) { |_, tally| tally["slowest"] }.each { |name, tally| table << "| `#{name}` | #{tally["slowest"]} |\n" } File.write(File.join(output, "summary.md"), table) puts table exit(failed_runs.zero? ? 0 : 1) From 807a896b1d685dc6332c9b147a2991cb8c90216f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 15:46:45 -0500 Subject: [PATCH 12/17] Tests(fix[async]): Await both missed-line copies why: The paused-control test refused to see "async-missed" in the resumed stream, and failed about 3 runs in 30 on Linux. The pane runs `cat`, so each sent line produces two outputs: the tty echo, then cat's reply. The observer wait broke on the first copy and the test resumed the pane. The second copy then reached tmux after `%continue`, which sets the pane offset to the current end of output (`control_continue_pane`, tmux 3.7c control.c), so it was delivered to the resumed stream ahead of "async-resumed". Output written while the pane is paused is dropped (`control_pause_pane` discards queued blocks), so the library and tmux behave as the test expects; only the ordering of the test's own synchronization was wrong. what: - Collect the observer's output until both copies of "async-missed" have arrived, then resume the pane. - No sleep and no timing change; the wait still ends on the event and stays bounded by `HANG_GUARD_SECONDS`. Evidence: the old wait failed this test in 3 of 30 runs. A copy of the test whose pane echoes immediately and replies to "async-missed" 0.3 s later failed 3 of 3 runs with the leak before this change and passed 3 of 3 after. With the default cat pane as a control, the new wait failed 0 of 40 runs. --- test/integration/async_test.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/integration/async_test.rb b/test/integration/async_test.rb index 20d3edc2..4a679f2e 100644 --- a/test/integration/async_test.rb +++ b/test/integration/async_test.rb @@ -793,7 +793,11 @@ def test_control_flow_and_explicit_reconnect_report_loss_on_the_owning_scope assert_includes [:pause, :pause_requested], pause.reason assert_nil pause.dropped_bytes scope.server.run(["send-keys", "-t", "%0", "-l", "async-missed\n"]) - loop { break if witness.next(timeout: HANG_GUARD_SECONDS).data&.include?("async-missed") } + # The pane runs cat, so the line arrives twice: the tty echo, then cat's output. + witnessed = +"".b + while witnessed.scan("async-missed").length < 2 + witnessed << witness.next(timeout: HANG_GUARD_SECONDS).data.to_s + end control.resume_output(pane_id: "%0", timeout: HANG_GUARD_SECONDS) resume = stream.next(timeout: HANG_GUARD_SECONDS) assert_includes [:resume, :resume_requested], resume.reason From d65657cdbd209c68d6ad432870d368e67a6ffeb5 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 4 Oct 2026 16:24:46 -0500 Subject: [PATCH 13/17] Tests(fix[release]): Stop fixture maintenance why: `ReleaseTest` builds a git repository, commits, then copies the whole tree with `FileUtils.cp_r`. Since git runs automatic maintenance after a commit, detached by default (`maintenance.autoDetach`), a background process can hold `.git/objects/maintenance.lock` (taken in builtin/gc.c before the detach) and remove it while the copy is walking the directory. The copy then fails with `ENOENT` on that file and 12 `ReleaseTest` cases error with "release source git check failed". It failed once on linux / Ruby 3.4.10 / tmux 3.7c in PR 18 (runner git 2.55.0). Release is an unrelated suite; nothing in this series touches it. what: - Set `maintenance.auto=false` and `gc.auto=0` in the fixture repository's config before its first commit, so no maintenance process starts in it. Evidence: with git 2.55.0, a commit spawned `git maintenance run --auto --quiet --detach` under the default config and none with the two settings. A seam that creates and deletes the lock during the copy failed 67 and 72 of 200 copies with the CI error text; the same copy with no lock activity failed 0 of 200. The race window under real maintenance was too short to hit locally (0 of 300 copies, also under 8 busy loops), so the seam stands in for it. Sources: git v2.55.0 builtin/gc.c lines 1791-1818 (lock, then detach) and run-command.c lines 1956-1985 (`--detach` unless autoDetach is false). --- scripts/release/tests/release_test.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/release/tests/release_test.rb b/scripts/release/tests/release_test.rb index d51ec631..e4e7c586 100644 --- a/scripts/release/tests/release_test.rb +++ b/scripts/release/tests/release_test.rb @@ -121,6 +121,9 @@ def build_source_fixture RUBY end git("init", "-q") + # Auto maintenance detaches and holds objects/maintenance.lock while the fixture is copied. + git("config", "maintenance.auto", "false") + git("config", "gc.auto", "0") git("add", ".") git("-c", "user.name=Release Test", "-c", "user.email=release@example.invalid", "commit", "-qm", "fixture") end From 52e5e9163758b3e2ffd57c7f319e9b6162017b4e Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:01:06 -0600 Subject: [PATCH 14/17] Scripts(chore[stress]): Follow script checks why: Current lint rejects unfreezing an interpolated string. Contributors also need the standalone stress command's supported options. what: Use the interpolated summary directly and document the invocation at the top of the script. --- scripts/stress | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/stress b/scripts/stress index a20f89da..d4422cfb 100755 --- a/scripts/stress +++ b/scripts/stress @@ -5,7 +5,7 @@ require "fileutils" require "open3" require "optparse" -# Repeats the real-tmux integration suite and counts each test's failures. +# Usage: bundle exec scripts/stress [--repeat N] [--output DIR] root = File.expand_path("..", __dir__) Dir.chdir(root) repeat = 10 @@ -44,7 +44,7 @@ rows = counts.sort_by { |name, tally| [-tally["failures"], name] } File.write(File.join(output, "failures.csv"), (["test,runs,failures,slowest_seconds"] + rows.map { |name, tally| "#{name},#{tally["runs"]},#{tally["failures"]},#{tally["slowest"]}" }).join("\n") + "\n") failing = rows.select { |_, tally| tally["failures"].positive? } -table = +"### Stress run: #{repeat} repetitions, #{failed_runs} failed, #{rows.length} tests\n\n" +table = "### Stress run: #{repeat} repetitions, #{failed_runs} failed, #{rows.length} tests\n\n" if failing.empty? table << "No test failed.\n" else From 94cb995424b643c0274feb458985e89e2cf81021 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:05:04 -0600 Subject: [PATCH 15/17] Scripts(fix[stress]): Count every test report why: A Ruby warning interrupted a verbose Minitest line and the CSV silently omitted that test. what: Parse Minitest's output separately from diagnostics. Check the rows against the run total and keep both streams in the log. --- scripts/stress | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/stress b/scripts/stress index d4422cfb..0afc8708 100755 --- a/scripts/stress +++ b/scripts/stress @@ -22,10 +22,10 @@ files = (Dir["test/integration/**/*_test.rb", "scripts/*/tests/integration/**/*_ counts = Hash.new { |hash, name| hash[name] = {"runs" => 0, "failures" => 0, "slowest" => 0.0} } failed_runs = 0 repeat.times do |index| - out, status = Open3.capture2e(Gem.ruby, "-Itest", "-rsupport/sandbox", "-rsupport/replay", + out, diagnostics, status = Open3.capture3(Gem.ruby, "-Itest", "-rsupport/sandbox", "-rsupport/replay", "-e", "ARGV.shift(#{files.length}).each { |file| require File.expand_path(file) }", *files, "--verbose", "--seed", (index + 1).to_s) - File.write(File.join(output, "run-#{index + 1}.log"), out) + File.write(File.join(output, "run-#{index + 1}.log"), out + diagnostics) seen = 0 out.each_line do |line| next unless (match = line.match(/\A(\S+#\S+) = ([\d.]+) s = ([.FES])\s*\z/)) @@ -35,7 +35,10 @@ repeat.times do |index| counts[match[1]]["failures"] += 1 if %w[F E].include?(match[3]) counts[match[1]]["slowest"] = [counts[match[1]]["slowest"], match[2].to_f].max end - abort "run #{index + 1} reported no tests" if seen.zero? + reported = out[/^(\d+) runs?, \d+ assertions?,/, 1]&.to_i + unless seen.positive? && seen == reported + abort "run #{index + 1} recorded #{seen} of #{reported || "an unknown number of"} tests" + end failed_runs += 1 unless status.success? warn "run #{index + 1}/#{repeat}: #{status.success? ? "passed" : "failed"}" end From 06e454289556c61724a1f2d0bdf86c9040c2eb3c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:16:48 -0600 Subject: [PATCH 16/17] Tests(fix[process]): Move the deadline test why: The post-dispatch case waits for a real Ruby child to reach its deadline, so it belongs in the outer suite. what: - Run the deadline case in integration through the normal executor. - Check the child PID, possible delivery and complete reaping. --- test/integration/operation_budget_test.rb | 29 +++++++++++++++++++++++ test/unit/process_test.rb | 24 ------------------- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/test/integration/operation_budget_test.rb b/test/integration/operation_budget_test.rb index 274f2982..9b8f87e7 100644 --- a/test/integration/operation_budget_test.rb +++ b/test/integration/operation_budget_test.rb @@ -1,8 +1,11 @@ # frozen_string_literal: true require_relative "../test_helper" +require_relative "../support/stub_executable" require_relative "../support/tmux_fixture" require "libtmux" +require "timeout" +require "tmpdir" class OperationBudgetTest < Minitest::Test # Advance the facade's clock after a real preflight, without a timer sleep. @@ -25,6 +28,32 @@ def monotonic end end + # The real command deadline elapses after a child starts and blocks. + def test_deadline_after_dispatch_reports_possible_effects + Dir.mktmpdir("libtmux-ruby-") do |directory| + receipt = File.join(directory, "ready") + worker = LibTmuxTest::StubExecutable.write(File.join(directory, "worker"), <<~'RUBY', READY: receipt) + File.write(READY, "#{Process.pid}\n") + IO.select([]) + RUBY + + error = Timeout.timeout(HANG_GUARD_SECONDS) do + assert_raises(LibTmux::DeadlineExceeded) do + LibTmux::Internal::ProcessExecutor.new.run([worker], timeout: 2.0) + end + end + assert File.file?(receipt), "child did not announce its PID before the deadline" + pid = Integer(File.read(receipt), 10) + + assert_instance_of LibTmux::DeadlineExceeded, error + assert_equal :possibly_sent, error.delivery + assert_equal pid, error.pid + assert_empty error.cleanup_errors + assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } + assert_raises(Errno::ESRCH) { Process.kill(0, pid) } + end + end + def test_link_and_copy_preflights_share_the_original_operation_deadline LibTmuxTest::TmuxFixture.open do |fixture| AdvancingServer.open(socket_path: fixture.socket_path) do |server| diff --git a/test/unit/process_test.rb b/test/unit/process_test.rb index 9874a779..4ee86574 100644 --- a/test/unit/process_test.rb +++ b/test/unit/process_test.rb @@ -122,30 +122,6 @@ def test_cancellation_escalates_and_reaps_a_child_ignoring_term cancellation&.close end - def test_deadline_after_dispatch_reports_possible_effects - with_child_readiness do |ready, environment| - worker = task do - executor.run(ruby(<<~RUBY), env: environment, timeout: 2.0) - File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") - input, output = IO.pipe - input.read(1) - RUBY - end - pid = Integer(read_event(ready), 10) - assert worker.join(HANG_GUARD_SECONDS), "deadline did not retire the owned client" - error = worker.value - - assert_instance_of LibTmux::DeadlineExceeded, error - assert_equal :possibly_sent, error.delivery - assert_equal pid, error.pid - assert_empty error.cleanup_errors - assert_reaped(pid) - ensure - worker&.kill - worker&.join(0.5) - end - end - def test_drain_deadline_bounds_a_pipe_retained_after_child_exit Dir.mktmpdir("libtmux-ruby-") do |directory| path = File.join(directory, "transfer") From 5012c40607f93300c4b4ab323bcce68fe0af188f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:01:19 -0600 Subject: [PATCH 17/17] Changelog(ci): Note stress checks and waits why: Contributors need to know how the integration runs report slow and failing tests. what: Record the longer event waits and weekly stress report under 0.1.4. --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 225ee9f2..7c4b92ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ at one version, so a release has a section in each changelog. ## 0.1.4 (unreleased) +- Test event waits allow slower runners to finish. The weekly stress + workflow reports failures and the slowest run of each test on macOS and + Linux. (#18) + ## 0.1.3 (2026-12-05) Core and Async can wait for visible pane text with a deadline. On tmux 3.7