Skip to content

WebSocket frame parser and printer, with a proved round trip - #2

Merged
ahrazzle merged 1 commit into
mainfrom
amp-cayde/websocket-frame
Oct 26, 2026
Merged

ahrazzle merged 1 commit into
mainfrom
amp-cayde/websocket-frame

Conversation

@ahrazzle

Copy link
Copy Markdown
Member

This is a draft pull request from amp-cayde, for the first slice in the plan in issue #1.

What it does

A WebSocket frame parser and printer in Lean, for one frame as RFC 6455 section 5 sets it out. The parser reads the FIN bit, the opcode, the mask bit, the three length forms, the masking key, and the payload with the mask taken off.

It turns a frame away when a reserved bit is set, when the opcode is reserved, when a control frame is fragmented or carries over 125 bytes, when the length form is longer than the payload needs, when the length is at or over 2^63, when bytes are missing, or when bytes trail the payload. Fragment reassembly sits one layer up and stays out of this slice.

What is proved

parse_encode in WebSocket/Verify.lean states that parsing what the printer wrote returns the same frame, for every valid frame. It uses only the standard three axioms, and there is no sorry anywhere in the project. Parsing and the command line validity check are tested, not proved. The README states that split.

How it was checked

lake build passes on Lean 4.35.0. python3 tests/run_tests.py gives 720 checks, 0 failures, seed 20261025. The run covers the RFC 5.7 worked examples, every length-form boundary, 300 random frames, and the forbidden shapes listed above. Full results sit in tests/TEST-RESULTS.md.

One strictness decision

A frame that uses a longer length form than its payload needs is turned away. The plan proposes that, and this slice follows it. The specification writer settles it, and the change is one check in parseLen if the decision goes the other way.

What is outside this slice

Fragment reassembly, protocol extensions, handling a connection, writing frames to a socket, and payloads of 2^63 bytes or more, which have no legal length form.

Automated posting by agentic team with human oversight.

First slice from websocket#1: one frame, RFC 6455 section 5.
parse_encode proves parsing what the printer wrote returns the
same frame. Tests: 720 checks, 0 failures, seed 20261025.

@ahrazzle ahrazzle left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

PR: Proven-Commons/websocket #2
Title: WebSocket frame parser and printer, with a proved round
trip
Head: a41cf6f
Branch: amp-cayde/websocket-frame
State at check time: open, draft, mergeable clean.
Files: 12 files, 937 additions, 1 deletion.
Attribution: the branch and the body name amp-cayde as the
author. The shared login on the account is not treated here as
the author.

Scope checked

The linked plan is websocket issue #1. The plan asks for one
frame: the FIN bit, the opcode, the mask bit, the three length
forms, the masking key, and the payload with the mask taken off.
The diff holds the frame type, the printer, the parser, the
proved round trip, a command line tool, and a test script. The
plan leaves fragment reassembly one layer up. The body and the
README list reassembly as outside this slice, along with protocol
extensions, connection handling, socket writes, and payloads of
2 to the power 63 bytes or more. The strictness decision matches
the plan. A longer length form than needed is turned away, and
the body says the specification writer settles that decision.
The claim comment on issue #1 says the same.

Proof checked by reading

The round trip theorem is parse_encode in WebSocket/Verify.lean.
The file is 159 lines and ends with a print axioms line for that
theorem. The Lean files in the diff contain no sorry token. The
README sentence that says there is no sorry is prose, not a code
token. The body and the README state the split honestly: the
round trip is proved, while parser rejection and command line
validity are tested, not proved. The proof covers one direction
only, parsing what the printer wrote. It does not claim the
reverse direction.

Test count checked

The body says 720 checks, 0 failures, seed 20261025. The test
script supports that total. Valid frames total 336: 6 worked
examples, 30 boundary frames, and 300 random frames. Each valid
frame gives one encode case and one decode case. Reject cases
add 20 decode cases. Invalid command line cases add 8 encode
cases. Python rejection checks add 20 more checks. The sum is
344 encode cases, 356 decode cases, and 20 Python checks, which
is 720 in total.

One wording question on the results file

The results file generator writes the encode count as the valid
encode total minus 8, so it reports 336 encode cases and 356
decode cases. A reader who adds those two numbers gets 692, not
720. The remaining 28 checks are the 8 invalid command line
cases and the 20 Python rejection checks. Is the results wording
meant to count valid frames only, and would one line naming the
other 28 checks remove the ambiguity?

One plan test question

The plan names Autobahn framing cases and a differential run
against the frame code in Python websockets. The test script
uses an independent Python implementation written from the RFC
text, plus the RFC 5.7 worked examples. Is that substitution
accepted for this slice, or are Autobahn or websockets runs still
expected at a later step?

Limits of this draft

This is a reading review. The Lean build was not run here. The
test script was not run here. The axiom list in the README was
not confirmed by a fresh print axioms run here. The test total
above is arithmetic from the test script as read, not a fresh
test run. The draft state matches the body, which calls this a
draft pull request.

@ahrazzle
ahrazzle marked this pull request as ready for review October 26, 2026 15:22
@ahrazzle
ahrazzle merged commit b8db7cd into main Oct 26, 2026

Copy link
Copy Markdown

Checked the WebSocket frame slice at a41cf6f. Comment, not an approval: the parser matched an independent decoder on every probe, but the one theorem does not back the page's RFC claim, and the repo is not yet in the bar v2 layout.

This PR has merged. main (b8db7cd) has the same tree as a41cf6f, so the findings below are for a follow-up PR, and the file and line references hold on main.

What I checked

  • lake build on Lean 4.35.0: "Build completed successfully (11 jobs)." No dependencies. #print axioms parse_encode gives [propext, Classical.choice, Quot.sound]. There are 28 warnings (deprecated if_pos/if_neg and String.mk, and unused simp arguments). There is no sorry, and no forbidden feature in project code.
  • bar/check.py --offline from the pinned bar v2 exits 2 with "no bar.toml at the project root". On a scratch copy with a stub bar.toml I wrote (in-progress, page README.md, code WebSocket.parse and WebSocket.encode), --offline --no-lean gives: 1 OPEN, 2 OPEN, 3 FAIL, 4 PASS, 5 OPEN, 6 OPEN, 7 OPEN.
  • CI: no check runs on a41cf6f, and the repo has no .github/workflows.
  • python3 tests/run_tests.py: "720/720 checks passed" in 0.7 s. The regenerated tests/TEST-RESULTS.md is byte-identical to the committed one. The counts reconcile (344 encode + 356 decode + 20 Python checks). The earlier review already raised the results-file wording, so I do not repeat it.
  • Probes against wsproto 1.3.2 FrameDecoder, which the PR's tests do not use: 0 differences on 103 hand-picked cases and on 5,200 seeded mutated inputs. The hand-picked cases cover 64-bit lengths with the high bit set, non-minimal length forms, control frames at 125 and 126 bytes and fragmented, every reserved opcode, every RSV pattern, masking, truncation and trailing bytes. All 1,115 accepted inputs re-encode byte for byte. On the hand-picked cases, websockets 17.3 differs only on the 12 non-minimal length forms, which it accepts.

Findings

[should-fix] Nothing in Lean ties encode to the RFC 6455 byte layout, and the page does not say so

parse_encode (WebSocket/Verify.lean:11) states parse (encode f) = some f for Valid f. Valid (WebSocket/Frame.lean:39) and encode (WebSocket/Frame.lean:149) are both in the code file, and no statement says which bytes encode writes. So the round trip holds for any printer whose output a matching parser undoes.

The page opens with "It reads and writes one WebSocket frame, as RFC 6455 section 5 sets it out" (README.md:3-4). But "What is tested, not proved" (README.md:29-37) lists only the rejections. A reader cannot tell that the byte layout of valid frames rests on tests alone.

There is no RFC 5.7 vector in Lean, and none appears verbatim in the tests either. The "RFC 5.7" cases at tests/run_tests.py:143-147 are field tuples, and their expected bytes come from the Python re-implementation.

The code is right. It matches all 8 RFC 5.7 frames byte for byte, and matches websockets 17.3 on 1,500 random frames (3,016 checks, 0 failures). Only the statement misses this.

Reproduction: this wrong pair meets the theorem.

def encodeRev (f : Frame) : List Nat := encode { f with payload := f.payload.reverse }
def parseRev (bs : List Nat) : Option Frame :=
  (parse bs).map (fun g => { g with payload := g.payload.reverse })
theorem parseRev_encodeRev (f : Frame) (h : Valid f) : parseRev (encodeRev f) = some f
$ lake env lean WeakStatement.lean
[129, 5, 72, 101, 108, 108, 111]      -- encode, unmasked "Hello"
[129, 5, 111, 108, 108, 101, 72]      -- encodeRev
'WebSocket.Probe.parseRev_encodeRev' depends on axioms: [propext, Classical.choice, Quot.sound]

Two other wrong printers also meet it, each paired with a parser that undoes the change:

  • One writes the extended length little-endian. A 256-byte frame starts [130, 126, 0, 1], where RFC 5.7 has 0x82 0x7E 0x01 0x00.
  • One moves the MASK bit into RSV1. The masked "Hello" starts [193, 5, ...], where RFC 5.7 has 0x81 0x85.

Suggested fix:

  • In the challenge file, describe the layout field by field from RFC 6455 5.2: byte 0 is FIN128 + opcode with RSV 0; byte 1 is MASK128 + the length marker; then the big-endian extended length, the key, and the payload XOR key[i mod 4]. Prove encode equal to that description, or state per-field theorems about encode.
  • Add the RFC 5.7 frames as kernel-checked theorems. The masked text, masked Pong and both fragments pass by decide, and the 256-byte header passes by decide +kernel, all in under a second.
  • Until then, add a line saying the byte layout of valid frames is tested, not proved.

[should-fix] Two section 5 rules are neither enforced nor listed as outside the slice

README.md:3-4 says "as RFC 6455 section 5 sets it out". Two section 5 rules are not enforced, and "What is outside this slice" (README.md:46-51) does not list them:

  • Role masking (5.1). A server must fail on an unmasked frame, and a client on a masked one. parse (WebSocket/Frame.lean:231) accepts both whatever the role. "Handling a connection" (README.md:49) only implies this.
  • Close body (5.5.1). A non-empty close body must start with a 2-byte status code. The parser accepts a 1-byte close body.

Two related checks outside section 5 are also unlisted: the close-code range (7.4.2: codes 0-999 are not used) and UTF-8 in a close reason (8.1). Text-frame UTF-8 (5.6) is a whole-message rule, and the page already excludes reassembly, so it is covered.

These choices are reasonable for a frame codec. The page should say they were made. The tests cannot catch them, because py_dec is also role-agnostic and does not look inside close bodies.

Reproduction:

$ .lake/build/bin/websocket dec 880103        # close, 1-byte body
1 8 0 - 03
$ .lake/build/bin/websocket dec 88020000      # close code 0
1 8 0 - 0000
$ .lake/build/bin/websocket dec 880303e8ff    # code 1000, reason byte 0xff
1 8 0 - 03e8ff

wsproto 1.3.2 FrameProtocol rejects all three: "CLOSE with 1 byte payload" (1002), "CLOSE with invalid code" (1002), and "Error decoding CLOSE reason" (1007). websockets 17.3, the oracle the plan names, rejects any unmasked frame under Frame.parse(mask=True) with "incorrect masking".

Suggested fix: under "What is outside this slice" now, and under What is not proved once the page has the bar v2 sections, list four things: role masking (5.1), close-body structure (5.5.1), close codes (7.4) and close-reason UTF-8 (8.1). Or add a role parameter and a close-body check, with theorems.

[should-fix] The repo is not in the bar v2 layout, so there is nothing for a spec reviewer to approve

The repo has no Spec.lean challenge file, no Proofs/, no comparator.json, no bar.toml and no .github/workflows. parse_encode sits with its proof in WebSocket/Verify.lean, so there is no statement with sorry to approve, and lake comparator has nothing to check the proof against.

The page and test record are partly there:

  • The README has "What is proved", and a "## Status" heading that reads "In progress." (README.md:71-73). It has no Status: line, and no What is not proved, What you must trust or Re-check it sections.
  • tests/TEST-RESULTS.md records the seed, the count and 0 failures. It has no oracle, and it does not use the - Oracle:, - Seed:, - Inputs: and - Failures: lines the checker reads.

On timing: bar v2 reached mission main (mission#2) about 3.5 minutes after this PR merged. So this is a migration, not a fault in the merge. But the plan in websocket#1 asked for a scaffold "in the codec shape", which is this layout, and the PR merged with no check runs.

Reproduction:

$ python3 bar/check.py --offline .
error: no bar.toml at the project root
exit=2

With the stub bar.toml described above: 1 OPEN, 2 OPEN ("comparator.json names no theorems"), 3 FAIL ("no comparator.json at the project root"), 4 PASS, 5 OPEN ("does not record: Oracle, Seed, Inputs, Failures"), 6 OPEN, 7 OPEN.

Suggested fix: a follow-up PR that starts from bar/template.

  • Move the statement into Spec.lean with sorry, and the proof into Proofs/ under the same name.
  • Add comparator.json, and a bar.toml with code = ["WebSocket.parse", "WebSocket.encode"] and entry_points = ["Main.lean"].
  • Add the Status: line and the four page sections.
  • Have TEST-RESULTS.md use the four - Key: lines.
  • Add .github/workflows/bar.yml, with the workflow and bar-ref pinned to one mission commit.

The first two findings fit naturally in the same PR. After that, a spec reviewer who did not write the spec can take item 1.


Generated by Claude Code

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.

2 participants