Skip to content

v0.2.3: add resumable HTTP batch sessions - #5

Merged
DiamondGo merged 4 commits into
mainfrom
feat/resumable-batch-v0.2.3
Oct 25, 2026
Merged

DiamondGo merged 4 commits into
mainfrom
feat/resumable-batch-v0.2.3

Conversation

@DiamondGo

@DiamondGo DiamondGo commented Oct 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Preserve the same session and existing yamux streams across HTTP batch transport failures, including mixed batch/stream directions.
  • Keep batch bodies finite and bounded. Add absolute byte offsets, cumulative acknowledgments, replay, and deduplication using the existing reliable byte layer.
  • Add explicit batch-resume capability negotiation to preserve compatibility with older clients and servers.
  • Preserve resume when an upload-stream probe fails by renegotiating batch uploads on capable servers.
  • Serialize transport attachments against resume handshakes, cancel incomplete uploads safely, bound stalled batch responses, and avoid resuming missing/closed sessions.
  • Replace the default README with comprehensive English configuration, protocol, compatibility, recovery-limit, and operational documentation.

Tests

  • Add deterministic tests for lost upload responses and truncated download responses.
  • Cover incomplete and oversized uploads, offset validation, replay/deduplication, stalled responses, recovery expiry, explicit closure, replay overflow, offline shutdown, metadata/authentication, and chunk limits.
  • Exercise concurrent yamux streams and repeated transport kills with pure batch and both mixed HTTP combinations.
  • Cover compatibility with older peers and upload-probe fallback behavior.

Validation completed locally:

  • Full uncached test suite passed.
  • Full uncached race-detection suite passed.
  • Focused batch/mixed-direction race tests passed five consecutive runs.
  • Go static analysis and whitespace/diff checks passed.

Review follow-up (c881e3a)

Addresses the Sourcery review. Each thread has a reply with the details.

  • Stale poll consumes replay bytes (fixed). Batch downloads are strictly serial, so every receive-only poll now starts its response at that poll's cumulative ack (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.
  • Expired sessions can be revived (fixed). Poll, WebSocket, and resume attaches now refuse a detached resumable session past its grace with 410, even before the sweeper evicts it, so the recovery window is exactly resume_grace_ms. This also applied to stream/WebSocket resume before this PR.
  • Chunked receive-only polls (fixed). An empty chunked poll is now accepted; only actual body bytes are rejected. Non-empty chunked polls were already rejected.
  • Empty 200 poll responses (fixed). The client rejects a 200 batch poll response with an empty body as malformed; idle polls are 204.
  • Offset overflow (no change). False positive: an offset past the receive position is rejected as a gap (400) before the duplicate comparison, which cannot overflow in practice.
  • Test flake. TestBatchResumeConcurrentStreams occasionally 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 an empty data case in TestBatchResumeClientValidatesResponses. Each fails on the original commit and passes with the fixes.

Validation after the follow-up:

  • Full race-detection suite passed twice.
  • Focused batch/mixed-direction race tests passed five consecutive runs; TestBatchResumeConcurrentStreams passed 30 consecutive runs.
  • go vet and whitespace/diff checks passed.

Second follow-up (143308e)

Found in a further review of the feature; both reproduced with temporary probes before fixing.

  • Detached-session cap evicted healthy pure-batch sessions (fixed). A resumable pure-batch session has nothing attached between two polls, so the sweeper counted healthy clients against MaxDetachedResumable. With a cap of 2, four of six healthy clients polling every 300 ms were evicted within 3 seconds. 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 10 s allowance. Older servers ignore the field, and older clients never negotiate batch resume, so this is wire-compatible.
  • Redundant ack traffic in batch directions (fixed). Batch requests and responses already carry the cumulative ack, but the eager-ack wakeup still fired. An 8 MiB echo produced 89 early 204 polls (about one per upload) and 15 ack-only uploads. Eager acks are now off for directions whose acks travel in batch headers, and the client skips ack-only uploads when downloads are batch. Mixed sessions keep eager acks where the ack must travel on a stream leg.
  • Fixed README code links whose line numbers had drifted.

New tests: TestBatchResumeDetachedCapSparesHealthyPollers, TestBatchResumeDetachedCapCountsAfterPollGap, TestBatchResumeAcksAddNoRequests, and TestReliableDisabledEagerAckLeavesSenderParked. 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)

  • Endless resume when batches cannot finish arriving (fixed). The batch poll's whole-request timeout also covers the body. It is intentionally left unchanged: with yamux keepalive off, it is the client's only stall detector, and loosening it would slow detection of real stalls. 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 data or signalling failure. Reproduced: 11 resumes in 30 s with nothing delivered. A 200 body that hits the deadline is now reported as 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.
  • Docs. The README now explains sizing poll_buffer_bytes for the slowest supported link, so that a full batch transfers within PollGrace.

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, and TestResumeStabilityGuardBodyTimeouts; TestBatchResumeClientBoundsStalledResponseBody now 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:

  • Add capability-negotiated resumable HTTP batch sessions across pure-batch and mixed stream/batch directions while preserving existing sessions and yamux streams through transport failures.
  • Add bounded batch replay with absolute offsets, cumulative acknowledgments, deduplication, validation, and recovery safeguards.
  • Add upload-stream probe fallback that renegotiates batch uploads while retaining resume support on capable peers.

Bug Fixes:

  • Prevent stale polls, expired sessions, stalled or malformed batch bodies, and detached-session accounting from causing data loss, unintended revival, or premature eviction.
  • Avoid redundant acknowledgment traffic for batch directions and safely coordinate transport attachments with resume handshakes.

Enhancements:

  • Extend resume support to all HTTP direction combinations with backward-compatible capability negotiation and bounded recovery behavior.

Documentation:

  • Replace the README with comprehensive English documentation covering configuration, routing, transport behavior, compatibility, recovery limits, authentication, and operations.

Tests:

  • Add deterministic coverage for batch replay, truncation, lost responses, offset validation, lifecycle handling, compatibility, mixed-direction recovery, concurrent streams, and transport failures.

@sourcery-ai

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This 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 recovery

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Adds resumable finite HTTP batch transport while preserving the existing session and yamux streams across failures.
  • Introduces absolute send offsets and cumulative receive acknowledgments in batch headers.
  • Retains bounded unacknowledged bytes for replay, deduplicates overlaps, validates gaps and acknowledgments, and detects incomplete, oversized, truncated, or stalled bodies.
  • Coordinates batch attachments with resume handshakes and safely cancels prior polls or uploads.
batch.go
protocol.go
resumable_client.go
resume_server.go
handler.go
session.go
session_guard.go
Extends capability negotiation and recovery across all HTTP direction combinations without breaking older peers.
  • Adds the batch_resume request/response capability and enables resumability for pure batch and mixed batch/stream sessions only when explicitly negotiated.
  • Keeps protocol version 1 and falls back to legacy non-resumable behavior when peers lack the capability.
  • Renegotiates batch uploads after an automatic upload-stream probe fails while retaining resume where supported.
client.go
handler.go
protocol.go
resume_server.go
resume_test.go
batch_resume_test.go
Hardens lifecycle, limits, and transport failure handling around resumable sessions.
  • Bounds resume grace, detached session population, replay memory, batch payloads, response bodies, and stalled requests.
  • Prevents resuming missing, closed, expired, or invalid-offset sessions and preserves authentication, metadata, chunk limits, and attachment ownership.
  • Maintains the same session ID and yamux session through successful recovery, including concurrent streams and repeated transport failures.
batch.go
resumable_client.go
resume_server.go
batch_resume_test.go
Adds broad deterministic and end-to-end coverage for resumable batch and mixed-direction behavior.
  • Tests lost upload responses, truncated downloads, replay/deduplication, malformed offsets, incomplete and oversized uploads, stalled responses, expiry, closure, overflow, shutdown, and concurrent streams.
  • Exercises pure batch, stream-batch, batch-stream, compatibility with older peers, and upload-probe fallback.
batch_resume_test.go
resume_test.go
Replaces the README with comprehensive English implementation and operations documentation.
  • Documents configuration, routing, authentication boundaries, negotiated modes, batch wire semantics, resume lifecycle, recovery limits, proxy caveats, throughput, status codes, reconnect behavior, and testing.
  • Clarifies yamux keepalive requirements, memory implications, deployment affinity, and WebSocket versus HTTP transport behavior.
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread batch.go Resolved
Comment thread batch.go Resolved
Comment thread resume_server.go Resolved
Comment thread batch.go Resolved
Comment thread batch.go Resolved
- 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.
@DiamondGo
DiamondGo merged commit 1c715cd into main Oct 25, 2026
2 checks passed
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.

1 participant