Skip to content

Lobby: keep incomplete server lines until the rest arrives - #933

Open
moss-orbit-9f339e wants to merge 1 commit into
ZeroK-RTS:masterfrom
moss-orbit-9f339e:fix/lobby-socket-line-buffer
Open

moss-orbit-9f339e wants to merge 1 commit into
ZeroK-RTS:masterfrom
moss-orbit-9f339e:fix/lobby-socket-line-buffer

Conversation

@moss-orbit-9f339e

Copy link
Copy Markdown

A socket read can end inside a server command. The lobby keeps the start of the command in raggedJsonStore and tries it again with the first line of the next read. A command that comes in three or more reads never becomes complete, so it is lost. Each split also logs Failed to parse JSON.

  • Fix: keep the incomplete last line in receiveBuffer and add the next read to it, as zk_loopback.lua does. Connect clears the buffer, so data from an old connection does not join Welcome (the cases in Sometimes multiplayer shows up empty. #776). Each line runs in xpcall, so a handler error does not drop the other lines of the read.
  • Seen in: 10 crash reports from 10 machines (Nov 2–11, Chobby v1.14.9.0) have Failed to parse JSON. In one of them, a BattleDebriefing arrives in parts of about 1.2 KB and is still incomplete after the second read, so it is lost. Most of the others are normal two-read splits, which this change also stops logging.

Offline test (Lua 5.1 harness): the harness loads the real interface_zerok.lua, interface_shared.lua, lobby.lua and LCS, and gives _SocketUpdate a fake socket. The commands are newline-terminated, as the server sends them.

master this change master
16-player BattleDebriefing (3.3 KB) in 3 reads lost received lost
300 commands (80 B–5 KB), random reads of 200–1500 B 19 lost, 200 with a missing middle 300 complete 19 lost, 200 with a missing middle
Failed to parse JSON errors in that stream 1660 0 1660
Partial line, then reconnect, then Welcome Welcome received, 2 errors Welcome received, 0 errors same as first run
Handler error in a middle line of a read later lines lost later lines received later lines lost

Live test (engine 2026.07.04, menu mode, Chobby with the Zero-K chobby_config.json, real server zero-k.info:8200): a test widget connects without a login, so the server sends only Welcome. Each run connects twice. The first connection uses normal reads. The second wraps the socket so that each read returns at most 64 bytes. Three runs, 120 s each:

master this change master
Normal reads: Welcome received, OnConnect yes yes yes
64-byte reads (765 B in 12 reads): Welcome received 128 B (middle lost) 764 B (complete) 128 B (middle lost)
Failed to parse JSON lines 10 0 10
Other LuaMenu error lines same same same

On master, the first and last reads joined into text that still parsed, so the lobby took a damaged Welcome.

Fixes #776

This PR was made with AI help (Claude Code); I checked the change and the test.

🤖 Generated with Claude Code

A socket read can end inside a server command. The ragged JSON store
joined only the first and the last read of a command, so a command that
came in three or more reads was lost or lost its middle part. Each split
also logged "Failed to parse JSON".

Keep the incomplete last line in a buffer and add the next read to it,
as zk_loopback.lua does. Clear the buffer when a new connection starts,
so data from an old connection does not join the Welcome command.
Process each line in xpcall, so one handler error does not drop the
other lines of the read.

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

Copy link
Copy Markdown

So... what if the second half of the command never arrives? The lobby will never again receive a valid command as it constantly tries to concatenate the first half of the command with things that do not match, resulting in nonsense.

@moss-orbit-9f339e

Copy link
Copy Markdown
Author

The buffer only holds the text after the last newline, and every newline empties it. So a fragment that never gets its second half can spoil at most the one line it is joined to; the commands after that line parse normally.

On a live connection the second half cannot go missing: the lobby socket is TCP, so bytes arrive in order or the connection fails, and the server ends every command with \n (CommandJsonSerializer.SerializeToLine; the JSON itself has no raw newlines). The next bytes after a partial line are the rest of that command. If the connection fails instead, the socket reports closed, and Connect clears receiveBuffer before the next connection, so an old fragment is never joined to new data. The server reads client commands the same way (TcpTransport uses StreamReader.ReadLineAsync).

The old raggedJsonStore code is the one that joined a fragment to unrelated text: it retried it with the first line of each of the next 10 reads.

Written entirely by Claude Code.

@Licho1

Licho1 commented Dec 3, 2026

Copy link
Copy Markdown
Member

Two notes:

  • while in theory it should not be possible for messages to get skipped or currupted, it has happened in practice, probably due to some issues in lua itself rather than transport which should be rock solid
  • how do you detect end of message? What I mean is that relying on \n might not be good enough. While server avoids putting it into messages it might happen due to some unforeseen things. Slightly more robust solution could count for unescaped { } or something similar.

@moss-orbit-9f339e

Copy link
Copy Markdown
Author

On detecting the end: the server writes every command with CommandJsonSerializer.SerializeToLine, which is Name {json}\n with Formatting.None. A newline inside a JSON value is always escaped as \n, so the only raw newline is the terminator. Counting braces would need to track strings and escapes (chat text can contain {), and it can't recover from a lost fragment any better. With line framing the next newline always resyncs, so a bad line spoils only itself, and each line runs in its own xpcall.

On corruption seen in practice: the old reassembly is a likely source. In this PR's live test, master joined the first and last reads of a Welcome that arrived in 12 pieces and dropped the middle. The result still parsed (128 of 765 bytes), so the lobby accepted a damaged command without any error. Commands that took three or more reads were lost entirely.

If you want an extra guard, I can add a cap that drops the buffer, and logs it, if it grows past for example 1 MB without a newline.

Written entirely by Claude Code.

@Licho1

Licho1 commented Dec 4, 2026

Copy link
Copy Markdown
Member

sounds reasonable to me @moss-orbit-9f339e should do full audit of various places where server sends data to lobby to confirm it is all serialized and not manipulated directly as text anywhere

@moss-orbit-9f339e

Copy link
Copy Markdown
Author

I went through Zero-K-Infrastructure master (6185c76c8). Every place the server writes to a lobby connection goes through CommandJsonSerializer.SerializeToLine:

  • ConnectedUser.SendCommand (ConnectedUser.cs:66) and ClientConnection.SendCommand (ClientConnection.cs:202);
  • both ZkLobbyServer.Broadcast overloads (ZkLobbyServer.cs:126, 136), which serialize once and send the same line to every target.

Those are the only callers of SendLine on the server. ConnectedUser.SendLine just passes the line to each of the user's connections, and TcpTransport.SendLine writes it as UTF-8 bytes. No server code builds or edits a command as text.

SerializeToLine is the class name, a space, JsonConvert.SerializeObject(value) with Formatting.None, and \n. LobbyClient, PlasmaShared and ZkLobbyServer have no custom JSON converters or raw-JSON writers. Json.NET's default escaping writes control characters in strings and property names (dictionary keys included) as escapes, so user text such as chat can't put a raw newline into a command. The launcher's local connection to Chobby (ChobbylaLocalListener.SendCommand) uses the same serializer. The only raw-text sender in the repo is TasClient.SendRaw, the old ZeroKLobby client's /raw command, which goes from client to server.

One thing I noticed on the way, separate from framing: TcpTransport.SendLine (TcpTransport.cs:84) starts stream.WriteAsync without awaiting it. The try/catch around it only covers starting the write, so if a write fails the exception is never observed and RequestClose isn't called; the connection only closes when its read fails. It also means a connection's writes are never awaited one after another, so their order on the wire is left to the socket. Windows keeps overlapped sends in the order they were issued, so I don't expect this to corrupt lines on the live server. I can make a small PR that awaits the write and queues sends per connection if you want it.

@moss-orbit-9f339e

Copy link
Copy Markdown
Author

Following up on corruption seen in practice, I checked both ends.

Server transport: I ran the real TcpTransport from master on Windows/.NET Framework, with up to 32 tasks sending on one connection, lines up to 300 KB and a slow reader with small socket buffers. All 41,400 lines arrived intact and in order. So the server side looks clean, both how commands are built and how they are sent.

Chobby: master's reassembly has a loss I hadn't described yet. When a read ends inside a command name, for example JoinedBa | ttle {"BattleID":12,"User":"B"}, the command is lost even when it arrives in just two pieces. _OnCommandReceived reports the unknown name JoinedBa as handled (it logs "No such function" and returns true), so the piece is never kept for joining. For short commands like JoinedBattle, LeftBattle or UserDisconnected, that is roughly a quarter of the cuts that land in them. A lost JoinedBattle then makes the later LeftBattle handler throw, and on master that drops the rest of the read too. In infologs this shows up as No such function: followed by a cut-off name or a JSON tail. This PR fixes both, because it only splits at newlines and runs each line separately.

Other things I found that this PR doesn't touch:

  • Data that arrives together with the server's close is dropped (receive('*a') returns it in the first value, which isn't read), so a kick reason sent just before RequestCloseAll is never shown.
  • Say de-duplication keys on Time and Text only, so two players saying the same thing in the same server clock tick show as one message.
  • The JSON decoder rejects an upper-case exponent, which Json.NET writes for small floats (4E-06), so such a command fails to parse. It also turns \uXXXX escapes into a literal uXXXX.
  • In zk_loopback.lua, one handler error removes the widget, which cuts the launcher link for the rest of the session.

I can send these as separate small PRs if you want them.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sometimes multiplayer shows up empty.

3 participants