Skip to content

READ_SOCKET: answer at once when the socket is empty - #1087

Open
JC-000 wants to merge 3 commits into
GideonZ:masterfrom
JC-000:fix/1086-read-socket-nowait
Open

JC-000 wants to merge 3 commits into
GideonZ:masterfrom
JC-000:fix/1086-read-socket-nowait

Conversation

@JC-000

@JC-000 JC-000 commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Fixes #1086

Problem

open_socket() sets SO_RCVTIMEO to 40 ms on every UCI socket, so a READ_SOCKET on an empty socket waits 40 ms before it answers "no data". The command interface takes no other command meanwhile. A program that sends one datagram a frame each way loses more than two frames per empty READ; #1086 has the measurements on two devices.

What changed

  • read_socket() passes MSG_DONTWAIT to lwip_recvmsg. An empty socket answers at once with length $FFFF and 02,NO DATA: 11, the same reply the timeout gave. A TCP end of stream still answers 01. MSG_DONTWAIT rather than O_NONBLOCK, so TCP writes keep blocking.
  • The 40 ms SO_RCVTIMEO is removed. Nothing else reads it: FTP and telnet set their own, and the multi-block READ continuation copies from its buffer without receiving again.

Compatibility

A program that counted READs as its timeout gets less patience. Of the programs found in #962, c64uploader, UltimateTerm, xlar54's u-sample.c and barryw's ucitest.c change behaviour; each is fixed by a few lines that bound the wait by time. The others (barryw's SDK, ReadyIRC, C64U-H2H, the Gameserver, c64u-radar, xahmol's tools, 8bit-Unity) already poll or have their own time bounds, and c64-https needed no change.

The 40 ms is not a behaviour these programs were built around:

  • READ has already behaved three ways (from the source): in effect no wait up to v3.11, about 4 s in v3.12, and 40 ms since v3.12a. Of the programs found, only c64uploader was written against the 40 ms. It allows 500 READs, which is 20 s today and 1.6 s without the wait, so a server that greets later than that is declared dead.
  • The wait hides bugs rather than preventing them. UltimateTerm uses telnet negotiation bytes without checking that the READ returned any. On today's firmware it already gets a negotiation split across two segments wrong 2 times in 5 when they are 15 ms apart, and every time at 60 ms. Without the wait it fails every time. With a few lines that check the READ, it passes every case without the wait, over WiFi and Ethernet.

The measurements and the patches for each program are in #962 (comment).

#962 also discussed an opt-in alternative: a sixth command byte that asks for no wait, with five-byte READs keeping the 40 ms. That leaves every program that doesn't send the byte paying the wait, including the network games #1086 measured. This PR makes no-wait the default. The sixth-byte variant is built and tested and can replace it if you prefer it.

How I tested it

Host: macOS. The firmware was RAM-loaded over JTAG on both devices, never flashed. Red = upstream master 18bea1392; green = this branch (firmware 338dc7793; the later commit only changes tests).

New E2E tests in tests/e2e/io/command_interface/net_target_test.py:

  • read-empty-answers-at-once: net_read_timing.asm issues 20 READs from the 6510 and counts cycles on the CIA2 timers, because a host cannot time a 40 ms difference through REST. It compares READs on an empty socket with READs on a handle the target doesn't own, which never waited. Limit: 1 ms extra per READ. It runs over UDP and TCP, and is skipped on an Ultimate-II cartridge in a C64 Ultimate, where 6510 code reaches the host's command interface rather than the cartridge's.
  • read-returns-waiting-data: a guard that a datagram already queued is still returned. It passes on master too.
Device Red: extra per empty READ Green: extra per empty READ
Ultimate 64 Elite 39 ms (785 ms per 20; test fails) under 0.1 ms (1.4 ms UDP, 1.8 ms TCP per 20)
C64 Ultimate 39 ms (781 ms per 20; test fails) under 0.1 ms (1.5 ms UDP, 1.6 ms TCP per 20)

Full suite on green: ./run-tests --profile deep -s uci-net-target passed on both devices, overlay and freeze transports, two runs each.

Untested

Written with Claude Opus and Claude Sonnet in Claude Code.

JC-000 and others added 2 commits November 11, 2026 19:43
READ waited up to 40 ms (SO_RCVTIMEO set at open) on an empty socket, and
the UCI takes no other command meanwhile. Pass MSG_DONTWAIT to the receive
instead: an empty socket answers with $FFFF and 02,NO DATA: 11, as the
timeout did, and a TCP end of stream is still 01. The receive timeout is
dropped; nothing else reads it (FTP and telnet set their own).

Tests time the READ on the C64 itself, UDP and TCP.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

(cherry picked from commit b2c75f6aa3f4f52d152281c1d8d7990bdab69f05)
Drop read-sixth-byte-refused (passes on master), skip read-empty on a
cartridge inside a C64 Ultimate, tighten the timing threshold to 1 ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@chrisgleissner chrisgleissner added bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects. network Networking and remote services: REST, Socket DMA, FTP, Telnet, and online access. labels Nov 12, 2026
@chrisgleissner

chrisgleissner commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

@JC-000 Thank you for the thorough investigation, application testing, and assembly-based timing tests. The measurements make a convincing case for nonblocking reads, and I would like to help get that improvement merged.

My remaining concern is backward compatibility. Your tests identify cases where existing application binaries would stop handling situations they handle today. The proposed application fixes are valuable, but users would still need to obtain updated versions.

Linus Torvalds expressed the Linux kernel’s compatibility principle as: “If a change results in user programs breaking, it’s a bug in the kernel.” I think that is useful guidance for firmware too: even unintended or undocumented behaviour deserves careful treatment once applications depend on it.

Could we therefore start with the optional sixth byte you have already implemented? Existing five-byte READs would retain their current behaviour, while a sixth byte of 0 would explicitly request a nonblocking read. That appears to provide the same latency benefit to applications that opt in while preserving compatibility for existing binaries.

To strengthen that version of the PR, could we:

  • Confirm the performance gains with the lockstep benchmark using explicit nonblocking reads.
  • Test both legacy and nonblocking behaviour, including receiving data after an earlier read returned “no data.”
  • Document support detection, fallback on older firmware, and recommended polling with time-based deadlines.

The compatibility research already done is valuable; I am not asking for an exhaustive application audit. This would give us a clear path to merge the improvement, while leaving a default change for a separate decision informed by application fixes and feedback from their maintainers.

@GideonZ, I’d welcome your view on this trade-off. Changing the default is ultimately a maintainer decision, but I would favour preserving compatibility here: the current behaviour is already in use, and the opt-in approach lets developers adopt non-blocking reads without making a firmware update unexpectedly break existing applications. That would let us deliver the improvement now and consider changing the default separately.

Also including @xahmol, @xlar54 , @barryw and @enver-haase into this discussion.

@chrisgleissner
chrisgleissner self-requested a review November 12, 2026 07:42

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Needs further work before it can be merged to avoid breaking apps that rely on the existing behavior.

@xahmol

xahmol commented Nov 12, 2026

Copy link
Copy Markdown

See myself mentioned here in the thread. Did not follow this at all yet (no time to follow the many firmware issue threads, just see some really good work going on).

But I think that the assessment of topic starter is probably correct that my code already has a time out loop. And actually busy updating all tools for 3.15a functionality anyway,

So from my perspective I prefer improved stability over forced backward compatibility, of course preferably with early communication on breaking changes.

@JC-000

JC-000 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for the offer to land the improvement first. I would like to make the argument here to keep the default change in this PR and not add the sixth byte. This is my case for it.

An opt-in makes the normal behaviour of an empty read something every developer has to discover and request, indefinitely, to preserve a 40 ms wait that no document mentions (doc/uci_network_target.docx lists only status 00 and 01 for READ) and that few programs use on purpose. I think the argument that removing the wait reverts an undocumented breaking change from a year and a half ago is almost unassailable.

Why now. AI-assisted coding makes new Ultimate network programs such as games very easy to write, and Commodore has invited this with Made for Ultimate (https://commodore.net/made-for-ultimate/). Every month the undocumented wait stays, more code gets written against it, which adds to the pressure to keep a wait whose only effect is to make weak polling somewhat more reliable and unintentionally encourage a bad polling structure in code. Fixing it now and killing off the technical debt, with fixes offered to every affected program, is cheaper than fixing it later and less confusing than carrying it forever. I really set out just to write programs that use networking and to prove I could make TLS 1.3 work on the 6510. This has turned into an engaging side quest, but every issue and PR I have worked on here has been a step along that path to make networking behave predictably, reliably and fast. To address the concern, I have agent teams building fixes now that will be tested and potentially PR'd to affected repos.

The wait was never stable. network_target.cc has set tv_sec = 4; tv_usec = 4; since 2015 (915cfbe, in 3.0c). With lwip 1.4.1 the first int is read as 4 ms, which is 0 ticks at the 5 ms tick, so READ did not wait in any release from 3.0 to v3.11. With lwip 2.2 (a 2.2.1 development snapshot, fbd597e) the same line meant 4 s in v3.12beta (2025-03-18) and v3.12 (2025-05-11). 57c7c8a ("Delays in socket polling set correctly for LWIP 2.1", 2025-05-22) made it 40 ms, in 3.12a and later. The C64 Ultimate line has only ever had 40 ms, an undocumented value it inherited from that same change. I found no issue reporting slow UCI reads during the 4 s period, indicating that the change in behaviour for programs written before it went unreported publicly for about two months (v3.12beta on 18 March 2025 until 57c7c8a on 22 May). #510 (Retroterm on 3.12, modem path, still open) may be the same lwip unit change on another socket; I have not confirmed that. The behaviour programs were first written against is no wait; the 2025 changes to 4 s and then 40 ms came with no notice.

Programs written before May 2025 were written for no wait. In my inventory of 20 UCI network clients (full table with file and line references: https://github.com/JC-000/1541ultimate/blob/f1f6c62e6f67153a056fe0c2b08f99f261631b9e/repro/1087-read-wait-inventory/INVENTORY.md), 9 started before 57c7c8a. They are the xlar54 library and samples (2018), 8bit-Unity, DMBoot, MultiRogueLike, ntp2ultimate, GeoUTools, UBoot64, CPMUTools and iss-tracker-u64. UBoot64 (commit 05631e7, 2023-09-08) reads up to four times, each after a delay commented "to avoid time to wait on response being too short". No-wait gives these programs back what they were built for. The other 11 date from August 2025 onwards. The programs that no-wait changes:

Program Written Count-based or single-shot polling Effect Fix
c64uploader 2026-01 gives up after 500 empty reads patience 20 s becomes 1.6 s time-based limit, hardware tested
SEE64YOU 2026-09 512 empty reads (three places) patience 42.5 s becomes 23.5 s (measured, C64U) time-based limit, hardware tested
jesters_maze 2026-01 one read after each UDP send, no retry works on a LAN today, reads the previous reply under no-wait retry to a time limit
ntp2ultimate 2021 one read right after the request, no retry works when the reply arrives within 40 ms, fails under no-wait as on 3.11 retry to a time limit
UltimateTerm 2021 telnet option bytes read unchecked splits wider than 40 ms already misread today; with no wait, any split (as on 3.11) poll each byte, hardware tested

The OkExt HTTPGET and TELNET commands pass the status length instead of the socket number, so they can't work on any firmware and are not affected. Two test or demo programs and one drain loop change in minor ways (full table); the rest is unaffected or faster. KANAL 7, a closed-source game by the author of 8bitcavern.de, has no released binary yet. Its page describes its Command Interface use as "nicht blockierend, ein Befehl je Bild" (non-blocking, one command per frame), so it looks like it landed on an approach like Michel's that would survive the change; If we agree on no wait, I can try to send the author a heads-up, provided I can find contact details: the page names no author, and the only address I found is on the parent site, 8bitcavern.de. It runs its lockstep over TCP, and I wonder whether that is because a fixed local UDP port isn't available until #962 (#1016) lands.

Count-based polling measures CPU speed and network latency, not time. An empty read costs 40 ms on 3.12a to 3.15, a few milliseconds without the wait, and 4 s on 3.12. On the Ultimate the CIA and TOD clocks stay real-time under turbo, so a deadline on them holds on the hardware, while a loop count changes with the turbo setting and with WiFi against Ethernet. The 40 ms hides this for some programs and costs every program two frames per empty read. A normal reply arrives in 10-100 ms on a LAN or across the internet, and even a geostationary satellite hop is about 600 ms, so c64uploader's 1.6 s limit from the no wait change only bites when the server itself takes longer than that. The wait also shapes new designs: the Wizard of Wor LAN edition discussed in #962 builds its UCI driver as an asynchronous state machine because "synchronous polling per frame is not feasible (42 ms is more than 2 frames)" (translated from PROMPT_WoW_LAN.md:66). @mfidder2026, as the author of that lockstep game, would no wait by default suit you better than today's 40 ms?

Upgrade path without an opt-in. Fixes of the same form for every affected program, being prepared as PRs to each program's own repo (c64uploader, UltimateTerm, jesters_maze, SEE64YOU, ntp2ultimate, plus the OkExt handle bug); the first two are already on https://github.com/JC-000/1541ultimate/tree/repro/962-read-nowait-fixes, a notice with the fix to each author before the release, and release-note text: "UCI network READ returns immediately when no data is queued (status 02, length $FFFF), as in 3.0 to 3.11. Bound polling by time, not by the number of reads." xahmol wrote above that his code probably already has a timeout loop (his NTP code waits a second before each of up to five READs) and that he prefers "improved stability over forced backward compatibility, of course preferably with early communication on breaking changes".

What I will add to the PR for the no-wait default: tests for both the no-data reply and data arriving after one, documentation of how to detect firmware that waits, how to fall back, and time-based deadlines for polling, and the lockstep benchmark with the new behaviour.

Written with Claude Sonnet 5.5 and Claude Opus 5.5 in Claude Code.

Keep master's send timeout slice, drop the receive timeout as this PR does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@barryw

barryw commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@JC-000, thanks for the timing work and the client inventory. My ultimate-uci-sdk hardware test has TCP and UDP probes capped at 40 READs; its comment explicitly relies on the current ~42 ms empty-read cost when setting that bound. An immediate return could exhaust those attempts before a delayed reply. I can update the test, but your inventory shows released clients with the same count-based assumption.

I favor the optional sixth byte for this PR: preserve the five-byte behavior and let new clients request no-wait explicitly. That delivers the measured latency benefit without requiring existing binaries to update. The older no-wait history explains the inconsistency, but clients written against 3.12a and later still matter. Document support detection and time-based polling, then revisit the default as a separate compatibility decision.

@chrisgleissner

chrisgleissner commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Hi @barryw, @JC-000 and @xahmol,

You've all made very reasonable arguments. I'm increasingly convinced that immediate, nonblocking reads are the cleaner long-term solution. The 40 ms delay was never intentional API behaviour, and preserving it indefinitely through an additional parameter introduces complexity we'd rather avoid.

However, I remain concerned about breaking existing applications. Preparing fixes is very helpful, but getting them merged, released and adopted depends on maintainers and users. Some applications may never be updated, and we don't know how many others are affected.

Perhaps a pragmatic middle ground would be:

  1. Introduce nonblocking reads as an explicit option now, preserving compatibility with existing binaries.
  2. Document nonblocking reads as the recommended behaviour for new applications.
  3. Consider making nonblocking the default in a subsequent firmware release, once affected applications have had some time to adapt.

This needn't become a lengthy migration process or require exhaustive compatibility audits. We could simply give developers some advance notice and avoid surprising users with broken applications immediately after upgrading.

The downside is temporarily carrying both behaviours, and potentially having to support the legacy option longer than intended. But that seems preferable to users discovering that a firmware upgrade has broken their favourite software.

@GideonZ, what do you think? I would favour the clean nonblocking default eventually, but with a lightweight transition that gives existing applications a reasonable chance to catch up.

@barryw

barryw commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@chrisgleissner, I do feel strongly about preserving the five-byte READ semantics. I need to correct my earlier suggestion to "revisit the default": changing that same request to no-wait in a later release would still break old binaries. Firmware cannot distinguish an old five-byte caller from a new one, and already-distributed binaries cannot add an opt-in byte. Advance notice helps maintained applications, but does not resolve that compatibility break.

That asymmetry breaks the tie for me. New clients can request no-wait with the sixth byte; older firmware will reject it, so clients need support detection and a five-byte fallback. Document the six-byte form as preferred for new code and retain five-byte READ as legacy behavior. If a future protocol wants a no-wait default, use a new opcode or versioned command instead of changing this request. I would merge the opt-in form after timing it and testing both forms.

@JC-000

JC-000 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

4s was a bug. 40ms is still a bug. Code that relies on it is bugged.

Kill them with fire before there are more of them.

@JC-000

JC-000 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Merged the current master into this branch (045436d). The one conflict was in open_socket(): master's new send-slice timeout stays, and the 40 ms receive timeout is removed as before. The network-target host suite passes (296 checks), and the U64 and U64-II firmware build. On an Ultimate 64 Elite running this head, read-empty-answers-at-once and read-returns-waiting-data pass.

Written with Claude Sonnet 5.5 and Claude Opus 5.5 in Claude Code.

@JC-000

JC-000 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Out of the programs written since the 40 ms bug was introduced, 6/11 are unaffected and 2/11 are already broken regardless.

  • Unaffected (6): UBoot64-v2, Commodore64_Gameserver, ReadyOs, c64u-radar, ultimate-uci-sdk's library (its hardware test does depend on the wait), C64U-H2H. They use time-based deadlines or an asynchronous driver, or they treat 02 as "no data yet".
  • Already broken (2): OkExt fails on every firmware because of a socket-handle bug. jesters_maze goes out of step on today's 40 ms firmware whenever a reply takes 60 ms.
  • The other 3 rely on the wait and work today: c64uploader and SEE64YOU, whose retry counts add up to 20 s and 42 s of patience (fixes posted), and c64jp's drain loop (minor).

Two older programs break the same way on today's firmware: ntp2ultimate gets no time once the NTP reply takes 100 ms, and UltimateTerm misreads a telnet command split by more than 40 ms. Every number above was measured on hardware except c64jp's.

The 40 ms wait doesn't make programs that rely on it reliable. It keeps them working only against a fast, nearby peer. Fixes are open for all six affected programs: c64uploader #3, ultimateii-dos-lib #65, SEE64YOU #75, ristola/C64 #2, jesters_maze #2, ntp2ultimate #2. The full table is in the inventory.

Written with Claude Sonnet 5.5 and Claude Opus 5.5 in Claude Code.

@enver-haase

Copy link
Copy Markdown
Contributor

@chrisgleissner thanks for including me. Commodore has not defined the UCI: the C64 Ultimate User's Guide doesn't mention it, and I know of no other Commodore document that does. As long as that is the case, the UCI doesn't exist in my world, so I'll leave this decision to the others.

@chrisgleissner chrisgleissner added the uci C64-side Ultimate Command Interface, command targets, and Ultimate DOS commands; REST is network. label Nov 20, 2026
@chrisgleissner

Copy link
Copy Markdown
Collaborator

@enver-haase @JC-000 @barryw @xahmol Many thanks for your thoughtful contributions to this discussion.

I've reviewed the discussion, implementation, hardware benchmarks, compatibility findings, and proposed alternatives, weighing performance, backward compatibility, API consistency, simplicity, and maintainability.

My conclusion is that nonblocking reads are clearly desirable, but changing existing five-byte READ semantics introduces avoidable compatibility risks. The optional sixth byte (0x00) delivers the same performance benefit to applications that opt in, at the modest cost of a protocol extension and support detection on older firmware.

I therefore favour introducing explicit nonblocking reads while preserving existing five-byte behaviour, including in future releases. While the known affected applications can be patched, we cannot assume that all existing binaries will be updated, nor can we assess the impact on private or unmaintained software.

@GideonZ, what is your view on this trade-off?

@JC-000

JC-000 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@chrisgleissner, on private and unmaintained software: there is no single five-byte behaviour to preserve. READ answered at once from 3.0 through v3.11, waited about 4 s in v3.12beta and v3.12, and has waited 40 ms only since v3.12a (June 2025, 57c7c8a). 10 of the 25 programs we examined were published before v3.12beta.

The 40 ms wait was never documented. The UCI documentation describes READ without any wait, and up to v3.11 READ in effect did not wait: the timeout constant was 4, which lwIP 1.4 took as 4 ms and rounded down to nothing. The move to lwIP 2 left that constant unchanged while its unit changed from milliseconds to seconds, so v3.12beta and v3.12 waited 4 s. The commit that corrected this, "Delays in socket polling set correctly for LWIP 2.1", set 40 ms. It gives no reason for that value, and it did not restore the behaviour programs had been written against, which was no wait. Removing the wait completes that correction. A program that depends on the 40 ms had to find it by measurement. We found two. Commodore64_Gameserver, whose request for a fixed UDP port (#962) is where this READ wait first came up, measured an empty READ at 42-45 ms and is worse off for it: its notes record that this rules out a synchronous poll per frame, and it carries an asynchronous read driver to get around the wait (docs/netcode.md). The hardware test in barryw's SDK (tests/hardware/ucitest.c) allows 40 tries for an echo reply, sized at 42 ms each; that one bound needs to become a time bound. I have run neither on no-wait firmware. Neither is a reason to keep the wait: one works around it, and the other needs one bound changed.

The wait does not make the affected programs reliable. Of the five whose behaviour changes without it, three already fail on 40 ms firmware when a reply takes longer than the wait or a TCP segment is split: jesters_maze, ntp2ultimate and UltimateTerm. The other two, c64uploader and SEE64YOU, count empty reads, so the wait sets their patience with a slow server. Fixes for all five are open.

Programs that bound waits by time are unaffected. c64-wireguard polls once per main-loop pass with deadlines on the jiffy clock; unchanged, its handshake test reached an active session in 6 of 6 runs on no-wait firmware and 6 of 6 on 40 ms firmware (C64 Ultimate, Ethernet, 1 MHz and 48 MHz), in the same times. c64-https counts polls, with budgets so large that no wait only shortens its silent-server timeout from about 44 to 3-4 minutes; unchanged, it completed 12 of 12 fetches on no-wait firmware.

Beyond GitHub:

Program Published Empty READ Effect
CCGMS Ultimate January 2019 timer NMI every ~66 ms, no counting faster
UltimateCLI October 2026 waits by frames, at most 100 passes faster
BELOTE LAN C64 November 2026 stops at the first empty READ none
Teletext64U 2026 jiffy-clock deadline none

Ultimate Desk (closed, paid) is not examined.

With the opt-in byte, every existing binary, including those written for no wait, keeps paying the undocumented wait penalty.

Written with Claude Fable 5.2 and Claude Opus 5.5 in Claude Code.

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

Labels

bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects. network Networking and remote services: REST, Socket DMA, FTP, Telnet, and online access. uci C64-side Ultimate Command Interface, command targets, and Ultimate DOS commands; REST is network.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UCI READ_SOCKET waits 40 ms on an empty socket, which stalls network action games

5 participants