Repository navigation
v0.2.3: add resumable HTTP batch sessions - #5
Merged
Merged
Conversation
Contributor
Reviewer's GuideThis release adds capability-negotiated resumable HTTP batch sessions using bounded reliable-byte replay, offset validation, and attachment-safe recovery, extending session and yamux-stream continuity to pure batch and mixed HTTP directions while preserving compatibility with older peers. It also strengthens failure/lifecycle handling, adds extensive deterministic and end-to-end coverage, preserves resume during upload-probe fallback, and substantially documents configuration and operational constraints. Sequence diagram for resumable HTTP batch transport recoverysequenceDiagram
participant Client
participant Server
participant Session
participant ReliableLayer
participant Yamux
Client->>Server: POST /tunnel/connect
Server->>Session: Create resumable session
Server-->>Client: ConnectResponse resumable=true batch_resume=true
Client->>Yamux: Create session and streams
Client->>Server: POST /poll with X-Send-Offset and X-Recv-Offset
Server->>ReliableLayer: Validate offsets and receive bounded body
ReliableLayer->>Session: Deliver contiguous bytes
Server-->>Client: 200 with cumulative X-Recv-Offset
Note over Client,Server: Transport fails, unacknowledged bytes remain in replay buffers
Client->>Server: POST /resume with recv_offset
Server->>Session: Cancel and detach old attachments
Server-->>Client: 200 with server recv_offset
Client->>ReliableLayer: Replay bytes from server recv_offset
Server->>ReliableLayer: Replay bytes from client recv_offset
ReliableLayer->>ReliableLayer: Deduplicate overlaps and reject gaps
Client->>Server: Reattach batch upload and download requests
Client->>Yamux: Continue existing streams
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="batch.go" line_range="105" />
<code_context>
+ return
+ }
+ if send {
+ if err := s.rs.recvIn(off, data); err != nil {
+ status := http.StatusBadRequest
+ if errors.Is(err, io.ErrClosedPipe) {
</code_context>
<issue_to_address>
**Overflowing offsets silently discard uploads**
When an authenticated batch sender supplies an offset near `MaxUint64` whose addition with the body length wraps, `reliable.recvIn` evaluates `off + len(data)` without checking for unsigned overflow; a crafted offset near `MaxUint64` can wrap the sum below the current receive offset and be treated as a duplicate. The handler then returns 200 without delivering the upload, contrary to the batch protocol’s offset-validation contract.
Reject offsets whose body length would overflow before applying the duplicate-range comparison.
</issue_to_address>
### Comment 2
<location path="batch.go" line_range="68" />
<code_context>
+ // never have its cancellation deadline overwritten by a later reset.
+ rc.SetReadDeadline(time.Now().Add(cfg.PollTimeout + defaultStreamReadGrace))
+ }
+ att, err := s.att.attach(kind, func() {
+ cancel()
+ rc.SetReadDeadline(time.Now())
</code_context>
<issue_to_address>
**Stale poll consumes replay bytes**
When a batch poll is delayed before attachment while resume completes, and downstream bytes are queued when the canceled poll reaches `nextOut`, a pre-resume poll delayed before `attach` can attach after the handshake clears `resuming`. If its context is canceled, `nextOut` still advances `sentCursor` for queued data before the later context check returns without sending it; the next poll then skips those bytes, so the existing stream stalls or loses data.
Prevent requests begun before a resume handshake from attaching afterward, or check cancellation before reserving outbound bytes and rewind the cursor whenever delivery is abandoned.
</issue_to_address>
### Comment 3
<location path="resume_server.go" line_range="290" />
<code_context>
+ stop := pollmux.StartSweeper(store, cfg, hooks)
+ // One wrapper protects connect AND every subsequent session request.
+ return authenticate(mux), stop
+}
+```
+
</code_context>
<issue_to_address>
**Expired batch sessions can resume**
When a resume request arrives after the session's grace deadline but before the next sweeper pass, `negotiateResume` now enables resumability for batch-capable sessions, but `ResumeHandler` does not check the detached deadline before `beginPoll` increments the in-flight count. A request arriving after `ResumeGrace` but before the next sweeper pass therefore revives the session and extends its lifetime beyond the advertised recovery window.
Reject the resume under the session lifecycle lock once its detached deadline has passed, before marking the session active.
</issue_to_address>
### Comment 4
<location path="batch.go" line_range="51" />
<code_context>
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ } else if r.ContentLength != 0 {
+ writeError(w, http.StatusBadRequest, "receive-only batch must have an empty body")
+ return
</code_context>
<issue_to_address>
**Chunked polls get wrong results**
When a receive-only request uses chunked framing, `r.ContentLength` is -1, so `pollBatchResumable` rejects an empty poll with 400 but accepts a non-empty poll without consuming its body, denying compliant polls and accepting malformed ones.
Read and validate the request body to determine whether it is empty instead of relying on `ContentLength`.
</issue_to_address>
### Comment 5
<location path="batch.go" line_range="209" />
<code_context>
+ if err := c.rl.ack(ack); err != nil {
+ return false, err
+ }
+ return len(data) > 0, nil
+}
+
</code_context>
<issue_to_address>
**Empty responses cause poll spin**
When the peer returns status 200 with an empty body for a receive-only batch request, `doBatchPoll` treats an empty 200 body as no data instead of a protocol error; with the default zero `PollInterval`, `batchDownLoop` immediately issues another request, so a peer repeatedly returning empty 200 responses makes the client poll continuously rather than fail the transport.
Reject a 200 response with an empty body as malformed instead of treating it as an idle poll.
</issue_to_address>- Restart every batch poll response at the poll's cumulative ack, so a response lost without a handshake (e.g. a stale poll delivered late by a proxy) is resent instead of leaving a gap that breaks the session. - Refuse poll, WebSocket and resume attaches once a detached resumable session's grace has expired, even before the sweeper evicts it. - Accept an empty chunked receive-only poll; reject only actual body bytes. - Reject a 200 batch poll response with an empty body on the client. - Make the concurrent-streams test keep killing until a resume is observed.
…nt acks - A resumable pure-batch session has nothing attached between two polls, so the sweeper counted healthy clients against MaxDetachedResumable and could evict them. The client now declares poll_interval_ms at connect; the server counts such a session only once it has been detached longer than that interval (clamped to the grace) plus a fixed 10s allowance. - Batch requests and responses already carry the cumulative ack, so turn off the reliable layer's eager-ack wakeup for those directions and skip ack-only uploads when downloads are batch. An 8 MiB echo previously added about one empty 204 poll per upload plus several ack-only uploads. - Fix README code links whose line numbers had drifted.
The batch poll's whole-request timeout also covers the body and is the client's only stall detector (yamux keepalive is off), so it stays fixed. But when a full batch cannot cross the link within that deadline, every resume replays the same batch and times out again. Each leg outlasts the fast-resume guard, and a truncated body is not progress, so the session resumed forever without delivering anything or signalling failure. doBatchPoll now reports a deadline hit while reading a 200 body as errBatchBodyTimeout. supervise abandons the session after three consecutive legs that end that way with no downstream bytes received; any delivered byte or any other failure resets the count. The README documents sizing poll_buffer_bytes for the slowest supported link.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Tests
Validation completed locally:
Review follow-up (c881e3a)
Addresses the Sourcery review. Each thread has a reply with the details.
reliable.rewindToAcked). A response lost without a resume handshake, such as a stale poll that a proxy delivered after the client had already resumed, is resent by the next poll instead of leaving a gap that would end the session.resume_grace_ms. This also applied to stream/WebSocket resume before this PR.TestBatchResumeConcurrentStreamsoccasionally failed on the original commit too (about 1 in 10 runs) because no kill happened to land on an in-flight request. It now keeps killing until a resume is observed, with a bound, and its failure message names the failed condition.New regression tests:
TestBatchResumePollRestartsAtItsAcknowledgement,TestBatchResumeChunkedReceiveOnlyPoll,TestResumeExpiredGraceRefusesLateAttach, and anempty datacase inTestBatchResumeClientValidatesResponses. Each fails on the original commit and passes with the fixes.Validation after the follow-up:
TestBatchResumeConcurrentStreamspassed 30 consecutive runs.go vetand whitespace/diff checks passed.Second follow-up (143308e)
Found in a further review of the feature; both reproduced with temporary probes before fixing.
MaxDetachedResumable. With a cap of 2, four of six healthy clients polling every 300 ms were evicted within 3 seconds. The client now declarespoll_interval_msat connect. The server counts such a session only once it has been detached longer than that interval, clamped to the grace, plus a fixed 10 s allowance. Older servers ignore the field, and older clients never negotiate batch resume, so this is wire-compatible.New tests:
TestBatchResumeDetachedCapSparesHealthyPollers,TestBatchResumeDetachedCapCountsAfterPollGap,TestBatchResumeAcksAddNoRequests, andTestReliableDisabledEagerAckLeavesSenderParked. Each fails on c881e3a and passes now. The full race suite passed, and all resume/batch/reliable tests passed five consecutive race runs.Third follow-up (1e57222)
errBatchBodyTimeout. After three consecutive such legs with no downstream bytes received, the client abandons the session and signals transport failure. Any delivered byte, or a leg ending for another reason, resets the count, so idle sessions behind connection-cutting NATs are unaffected.poll_buffer_bytesfor the slowest supported link, so that a full batch transfers withinPollGrace.New tests:
TestBatchResumeAbandonsSessionWhoseBatchesNeverFinish(an end-to-end test with a trickling proxy; it keeps resuming on 143308e and now stops after exactly 2 resumes),TestBatchResumeClientTruncatedBodyIsNotABodyTimeout, andTestResumeStabilityGuardBodyTimeouts;TestBatchResumeClientBoundsStalledResponseBodynow also checks the new error. The full race suite passed, and all resume/batch/reliable tests passed five consecutive race runs.Release plan
Target release: v0.2.3.
No release tag is created or pushed by this PR. Create the v0.2.3 release tag on the merged main commit only after this PR is merged. The wire protocol version remains 1 because the new behavior is explicitly capability-negotiated and backward compatible.
Summary by Sourcery
Add backward-compatible resumable HTTP batch transport with bounded replay and reliable recovery across transport failures.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: