Event feed connector: foundations (1/3) - #777
Conversation
There was a problem hiding this comment.
Pull request overview
Introduces the foundational Go event-feed components required by the forthcoming connector run loop.
Changes:
- Adds event models, seams, codecs, filtering, deduplication, timing, and checkpoint persistence.
- Adds a credential-isolated WebSocket transport and URL security policies.
- Adds deterministic test fakes and extensive contract/unit coverage.
Tip
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.
Reviewed changes
Copilot reviewed 41 out of 42 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
AGENTS.md |
Registers the sanctioned event-feed architecture. |
go/go.mod |
Adds the WebSocket dependency. |
go/go.sum |
Records dependency checksums. |
eventfeed/backoff.go |
Implements retry and repair jitter. |
eventfeed/backoff_test.go |
Tests timing boundaries and saturation. |
eventfeed/cable.go |
Implements Action Cable frame codecs. |
eventfeed/cable_test.go |
Tests frame parsing and commands. |
eventfeed/checkpoint.go |
Defines checkpoint identity and store seam. |
eventfeed/clock.go |
Provides the timer abstraction and system clock. |
eventfeed/clock_test.go |
Tests system timer registration. |
eventfeed/continuation.go |
Validates continuation origins. |
eventfeed/continuation_test.go |
Tests continuation security policy. |
eventfeed/dedupe.go |
Implements delivered-event LRU deduplication. |
eventfeed/dedupe_test.go |
Tests deduplication and eviction. |
eventfeed/digest.go |
Implements canonical filter digests. |
eventfeed/digest_test.go |
Verifies shared digest fixtures. |
eventfeed/doc.go |
Documents the package architecture. |
eventfeed/errors.go |
Defines terminal errors and reasons. |
eventfeed/errors_test.go |
Tests error taxonomy and rendering. |
eventfeed/event.go |
Defines event payloads. |
eventfeed/event_test.go |
Tests payload presence semantics. |
eventfeed/filestore.go |
Implements bounded atomic checkpoint storage. |
eventfeed/filestore_test.go |
Tests persistence, locking, and file safety. |
eventfeed/filters.go |
Defines and validates feed filters. |
eventfeed/filters_test.go |
Tests validation and cloning. |
eventfeed/redact.go |
Redacts observer-facing URLs. |
eventfeed/redact_test.go |
Tests credential-safe URL rendering. |
eventfeed/seams.go |
Defines connector interfaces and public types. |
eventfeed/transport.go |
Implements cable URL policy. |
eventfeed/transport_test.go |
Tests URL and proxy policy. |
eventfeed/transport_contract_test.go |
Defines the shared transport contract. |
eventfeed/websocket_transport.go |
Implements the default WebSocket transport. |
eventfeed/websocket_transport_test.go |
Tests real transport behavior and security. |
eventfeed/feedtest/clock.go |
Provides deterministic virtual time. |
eventfeed/feedtest/clock_test.go |
Tests virtual timer behavior. |
eventfeed/feedtest/minter.go |
Provides a scripted ticket minter. |
eventfeed/feedtest/minter_test.go |
Tests minter scripting and cancellation. |
eventfeed/feedtest/polls.go |
Provides a scripted poll source. |
eventfeed/feedtest/polls_test.go |
Tests poll scripting and cancellation. |
eventfeed/feedtest/store.go |
Provides a scripted checkpoint store. |
eventfeed/feedtest/transport.go |
Provides a scripted cable transport. |
eventfeed/feedtest/transport_test.go |
Tests fake connection behavior. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
a2875be to
60a2870
Compare
Review of 4cff076 (B1 excluded, since uncommitted at the time). All four P1s reproduce; each fix is red-proven against the reported shape. P1 — Observer.Disconnected still leaked ticket text. Both arguments carry peer-controlled strings: a raw disconnect frame's reason, and a WebSocket close reason rendered through the error. Both were BOUNDED by §9's cap, which limits how much of a credential escapes rather than whether any does — the identical trap dialFailure documents three review rounds of. The cable server is exactly the party that knows the ticket: it was dialed with it. Both now go through closed vocabularies. observableDisconnectReason keeps the two reasons that change behavior and reports everything else as "other"; observableSocketError passes the connector's own sentinels and typed errors and degrades anything from a seam to a generic cause. CloseError.Error() renders only the code — an integer cannot carry a credential, and RFC 6455 codes are what an operator classifies on; Reason stays a readable FIELD. A canary planting a ticket in every peer-controlled teardown string found MORE than was reported: raw seam read errors leak too, which seam documentation cannot repair because the connector forwarded them verbatim. Four arms, all red before and green after. P1 — durableGate deadlocked reentrantly and blocked Close. It held the lock across CheckpointStore.Save while Close waited for it: a store whose Save calls Close self-deadlocks on the caller's own goroutine, and a merely stalled store blocked EVERY Close indefinitely — contradicting the one thing Close promises unconditionally. The two promises could not coexist, so the waiting one is dropped: the gate is claimed and released atomically, Close latches and returns, and a save that already claimed still completes. The guarantee is unchanged in substance — no save COMMENCES after Close returns — with commencing defined as claiming the gate, which takes no host code with it. The old test asserted Close WAITS and is replaced by one asserting it does not; the gate-holding variant deadlocks the new test at 40s. P1 — Close precedence, reopened by #763. Arming staleness before Connected also starts the pump before it, so a fatal frame can already be queued when a Connected callback calls Close, leaving two ready select cases. Reproduced: 25/50 rounds emitted a terminal element after Close returned. Fixed at the ONE exit (emitTerminal) rather than per-select — many selects, one exit, and a rule every future select must remember is what produced this. P1 — B2 discarded an earlier socket verdict. A deferred protocol-fatal followed by a positionless page took poll_failed, because disposal clears the deferral. The failed-poll branch already dispatches the deferral first, with a comment giving this exact reason; the new guard did not follow it. Now it does. Also fixed: TestNoCheckpointSaveCommencesAfterClose was vacuous (it closed before the run reached a page) and now closes from Observer.PageDelivered, the callback immediately preceding the save; the cancellation check after the checkpoint load covers every result rather than only the failure, since a found-empty result became terminal and a successful one let the run fire Connecting after Close; and deliver()'s stale "no delivery begins after Close returns" claim is corrected in place — it is a check-then-act, and the honest guarantee is the one Close states. Two of these touch foundations files that belong to #777 — CloseError in seams.go and its test. They stay here because the leak is only observable through the loop's observer path, which is this PR's, and the canary that proves it lives here. TestCloseError_Message is INVERTED, not adjusted: it required Error() to render the peer's reason, so it pinned the wrong contract. Verified: build, vet, -race, 22/22 fixtures, go-lint 0 issues, gosec 0 issues.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 41 out of 42 changed files in this pull request and generated 1 comment.
Suppressed comments (3)
go/pkg/basecamp/eventfeed/websocket_transport.go:414
- A concurrent repeat
Closereturns as soon asclosedis set, while the first call may still be waiting for the graceful handshake and has not canceledlifetime. Pending reads/writes can therefore remain blocked after thatClosehas returned, violating theCableConn.Closecontract. Publish a shared completion channel/result so every concurrent caller waits for the first teardown to finish.
go/pkg/basecamp/eventfeed/filestore.go:398 - This rename does not preserve the documented support for a symlink to a regular store file: atomic rename replaces the symlink itself, leaving its target unchanged. A later consumer opening the target sees the stale checkpoint, while this spelling sees a new unrelated file. Either reject symlink paths consistently or resolve and lock/write the target identity without breaking atomic replacement.
go/pkg/basecamp/eventfeed/websocket_transport.go:310 - The method documents cancellation before local-close precedence, but this early return reverses it when both happen before entry. That can turn a canceled operation into a socket failure;
WriteFramealready checksctx.Err()first. Apply the same ordering here.
Suppressed comments, round 2 — three findings, two verdicts and a stopCopilot's review on 1.
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 41 out of 42 changed files in this pull request and generated 3 comments.
Suppressed comments (1)
go/pkg/basecamp/eventfeed/websocket_transport.go:423
- Concurrent callers do not observe completion of the same close. The first caller sets
closedbefore starting/waiting for the handshake, so a second caller can returnnilimmediately while the connection lifetime is still active and pending I/O remains blocked for up to the close budget. SinceCloseis documented as safe from any goroutine and as unblocking reads/writes, make repeated callers wait on a shared close-completion signal (and return the completed result) instead of treating an in-progress close as complete.
Stopping here: this is the fourth round on one question, not two more patchesRound 3 on The pattern
That round ended by replacing the redactor with a closed vocabulary keyed on error types — and generalised it to exactly one call site. Two other observer-facing renderings were left on the older model, "compose once and bound by §9's
Round 3's two comments are the observation that truncation is not redaction, applied to those two sites. That observation is correct, and it is the same observation the earlier three rounds made. Four rounds, one question, two models live in one package. What I think the real question isIs Until that is answered, any patch here is the fourth selector on an instrument nobody has sized — and the two obvious local fixes are both wrong in an instructive way:
So this is a SPEC §23/§9 decision with a conformance-schema and six-SDK blast radius, not a Go-file fix, and it should not be made inside a review round on the foundations PR. Flagging it for a human call; the threads carry the same reasoning and are resolved so the PR is not held open on a decision that is not mine. On merit, for the recordThe findings are true but the actor is narrow: the entity that can trigger either is the cable server the mint pointed us at, which already holds the ticket — it received it in the handshake URL. Nothing is disclosed to a party that did not have it; what is at stake is our own short-lived credential landing in the operator's log aggregator. Real, worth fixing, and not urgent enough to justify guessing at the spec. Also in round 3
|
|
Tracked as #788, so the analysis above survives this PR's squash-merge rather than living only in a comment thread. The issue carries the question as posed here — whether Not holding this PR on it. The threads are resolved because the decision isn't this PR's to make. |
A stacked-PR failure mode worth writing down: a moving base can silently disable Copilot reviewRecording this on the base PR because the diagnosis is not discoverable from the symptom, and the next person to hit it will be looking at #777's history rather than at the child PR. Symptom. Copilot posts, in place of a review:
What actually happened. #705 is stacked on this branch. When
The child PR crossed a reviewer's size limit without a single line of its own changing. Rebasing Why it is worth a note rather than a shrug. The failure is silent in the direction that matters: Diagnosis, for next time. If a stacked PR's reviewer goes quiet or refuses on size, compare what GitHub thinks the diff is against what the branch actually carries: A large disagreement means the base moved. Both of this branch's moves have now been absorbed downstream: |
Review of 4cff076 (B1 excluded, since uncommitted at the time). All four P1s reproduce; each fix is red-proven against the reported shape. P1 — Observer.Disconnected still leaked ticket text. Both arguments carry peer-controlled strings: a raw disconnect frame's reason, and a WebSocket close reason rendered through the error. Both were BOUNDED by §9's cap, which limits how much of a credential escapes rather than whether any does — the identical trap dialFailure documents three review rounds of. The cable server is exactly the party that knows the ticket: it was dialed with it. Both now go through closed vocabularies. observableDisconnectReason keeps the two reasons that change behavior and reports everything else as "other"; observableSocketError passes the connector's own sentinels and typed errors and degrades anything from a seam to a generic cause. CloseError.Error() renders only the code — an integer cannot carry a credential, and RFC 6455 codes are what an operator classifies on; Reason stays a readable FIELD. A canary planting a ticket in every peer-controlled teardown string found MORE than was reported: raw seam read errors leak too, which seam documentation cannot repair because the connector forwarded them verbatim. Four arms, all red before and green after. P1 — durableGate deadlocked reentrantly and blocked Close. It held the lock across CheckpointStore.Save while Close waited for it: a store whose Save calls Close self-deadlocks on the caller's own goroutine, and a merely stalled store blocked EVERY Close indefinitely — contradicting the one thing Close promises unconditionally. The two promises could not coexist, so the waiting one is dropped: the gate is claimed and released atomically, Close latches and returns, and a save that already claimed still completes. The guarantee is unchanged in substance — no save COMMENCES after Close returns — with commencing defined as claiming the gate, which takes no host code with it. The old test asserted Close WAITS and is replaced by one asserting it does not; the gate-holding variant deadlocks the new test at 40s. P1 — Close precedence, reopened by #763. Arming staleness before Connected also starts the pump before it, so a fatal frame can already be queued when a Connected callback calls Close, leaving two ready select cases. Reproduced: 25/50 rounds emitted a terminal element after Close returned. Fixed at the ONE exit (emitTerminal) rather than per-select — many selects, one exit, and a rule every future select must remember is what produced this. P1 — B2 discarded an earlier socket verdict. A deferred protocol-fatal followed by a positionless page took poll_failed, because disposal clears the deferral. The failed-poll branch already dispatches the deferral first, with a comment giving this exact reason; the new guard did not follow it. Now it does. Also fixed: TestNoCheckpointSaveCommencesAfterClose was vacuous (it closed before the run reached a page) and now closes from Observer.PageDelivered, the callback immediately preceding the save; the cancellation check after the checkpoint load covers every result rather than only the failure, since a found-empty result became terminal and a successful one let the run fire Connecting after Close; and deliver()'s stale "no delivery begins after Close returns" claim is corrected in place — it is a check-then-act, and the honest guarantee is the one Close states. Two of these touch foundations files that belong to #777 — CloseError in seams.go and its test. They stay here because the leak is only observable through the loop's observer path, which is this PR's, and the canary that proves it lives here. TestCloseError_Message is INVERTED, not adjusted: it required Error() to render the peer's reason, so it pinned the wrong contract. Verified: build, vet, -race, 22/22 fixtures, go-lint 0 issues, gosec 0 issues.
b15e8d0 to
f241597
Compare
Review of 4cff076 (B1 excluded, since uncommitted at the time). All four P1s reproduce; each fix is red-proven against the reported shape. P1 — Observer.Disconnected still leaked ticket text. Both arguments carry peer-controlled strings: a raw disconnect frame's reason, and a WebSocket close reason rendered through the error. Both were BOUNDED by §9's cap, which limits how much of a credential escapes rather than whether any does — the identical trap dialFailure documents three review rounds of. The cable server is exactly the party that knows the ticket: it was dialed with it. Both now go through closed vocabularies. observableDisconnectReason keeps the two reasons that change behavior and reports everything else as "other"; observableSocketError passes the connector's own sentinels and typed errors and degrades anything from a seam to a generic cause. CloseError.Error() renders only the code — an integer cannot carry a credential, and RFC 6455 codes are what an operator classifies on; Reason stays a readable FIELD. A canary planting a ticket in every peer-controlled teardown string found MORE than was reported: raw seam read errors leak too, which seam documentation cannot repair because the connector forwarded them verbatim. Four arms, all red before and green after. P1 — durableGate deadlocked reentrantly and blocked Close. It held the lock across CheckpointStore.Save while Close waited for it: a store whose Save calls Close self-deadlocks on the caller's own goroutine, and a merely stalled store blocked EVERY Close indefinitely — contradicting the one thing Close promises unconditionally. The two promises could not coexist, so the waiting one is dropped: the gate is claimed and released atomically, Close latches and returns, and a save that already claimed still completes. The guarantee is unchanged in substance — no save COMMENCES after Close returns — with commencing defined as claiming the gate, which takes no host code with it. The old test asserted Close WAITS and is replaced by one asserting it does not; the gate-holding variant deadlocks the new test at 40s. P1 — Close precedence, reopened by #763. Arming staleness before Connected also starts the pump before it, so a fatal frame can already be queued when a Connected callback calls Close, leaving two ready select cases. Reproduced: 25/50 rounds emitted a terminal element after Close returned. Fixed at the ONE exit (emitTerminal) rather than per-select — many selects, one exit, and a rule every future select must remember is what produced this. P1 — B2 discarded an earlier socket verdict. A deferred protocol-fatal followed by a positionless page took poll_failed, because disposal clears the deferral. The failed-poll branch already dispatches the deferral first, with a comment giving this exact reason; the new guard did not follow it. Now it does. Also fixed: TestNoCheckpointSaveCommencesAfterClose was vacuous (it closed before the run reached a page) and now closes from Observer.PageDelivered, the callback immediately preceding the save; the cancellation check after the checkpoint load covers every result rather than only the failure, since a found-empty result became terminal and a successful one let the run fire Connecting after Close; and deliver()'s stale "no delivery begins after Close returns" claim is corrected in place — it is a check-then-act, and the honest guarantee is the one Close states. Two of these touch foundations files that belong to #777 — CloseError in seams.go and its test. They stay here because the leak is only observable through the loop's observer path, which is this PR's, and the canary that proves it lives here. TestCloseError_Message is INVERTED, not adjusted: it required Error() to render the peer's reason, so it pinned the wrong contract. Verified: build, vet, -race, 22/22 fixtures, go-lint 0 issues, gosec 0 issues.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 42 out of 43 changed files in this pull request and generated no new comments.
Suppressed comments (1)
go/pkg/basecamp/eventfeed/seams.go:339
DialError.Error()bypasses the 500-byte cap that §23 says still applies to other error renderings.checkCableURLplaces the server-supplied scheme or explicit port inReason, andnet/urlaccepts arbitrarily long valid schemes, so a malformed mint response can produce an arbitrarily large observer/log message. Apply the package truncation helper to the composed result.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated no new comments.
Suppressed comments (3)
Previously missed (3) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/errors.go:88
TerminalError.Errorcan render unbounded server-controlled text. For example,checkContinuationplaces the parsed scheme/origin inMsg, andurl.Parseaccepts an arbitrarily long scheme; logging that terminal error bypasses §9's 500-byte rendering cap. Truncate the composed message asDialErrorandCloseErrordo, and add a long-continuation regression case.
return msg
go/pkg/basecamp/eventfeed/websocket_transport.go:335
- An oversized frame reaches this branch as coder/websocket's untyped read-limit error. The stacked run loop only preserves package-owned sentinels and
invalidFrameError; it reduces this error to genericevent feed socket failed, soObserver.Disconnectedloses the invalid-frame indication required by SPEC §23. Expose a stable package-owned size-violation classification from the transport and preserve it in the observer sanitizer.
go/pkg/basecamp/eventfeed/feedtest/polls.go:113 calland the ledger entry share the cloned filter backing arrays. If anOnCallcallback mutates or retainscall.Filters, it can rewritep.callsdespiteCallspromising immutable snapshots. Give the callback its own filter clone.
if onCall != nil {
onCall(call)
}
Copilot's re-review surfaced three more suppressed findings; all three are taken here. The previous commit capped DialError and left the class open: TerminalError, MintError, and PollError still composed server-derived text unbounded — checkContinuation places a rejected `next` URL's scheme or origin in Msg and url.Parse bounds neither, PollError.Msg carries the server's filter-invalid message verbatim, and MintError chains whatever cause a TicketMinter composed. All three Error() renderings now truncate like DialError and CloseError, which closes the set: every seam error that can carry server-derived text renders under §9's cap, and invalidFrameError never carries any. TestSeamErrors_RenderingsAreBounded pins the class in one table, entering TerminalError through checkContinuation so the unbounded input is the real one. An oversized inbound frame crossed the CableConn seam as coder/websocket's own error. SPEC §23 makes the size violation one of the three invalid-frame shapes, with Observer.disconnected carrying an invalid-frame indication — a classification a stack-specific untyped error cannot carry, and one a custom transport could not produce at all without importing our WebSocket library. ErrFrameOversize is now part of the seam contract: the default transport maps the library's ErrMessageTooBig sentinel to it (matched via errors.Is, never message text) and returns it flat — the over-limit frame is never materialized, so the library's rendering adds nothing. The run loop's dispatch and observer preservation of this classification land with the connector, which is where SPEC §23's disconnected requirement binds. And the previous commit's own fix left one aliasing direction open: the PollCall handed to OnCall shared the ledger entry's freshly-cloned arrays, so a callback mutating or retaining its argument rewrote history. The callback now gets its own clone, and the ledger-ownership test covers all three directions. Every new assertion was shown red against reverted code: the bounded- renderings table fails per type (TerminalError at 1088 bytes via the continuation path, MintError at 1040, PollError at 1041), the oversize test reports the untyped "websocket: message too big: read limited at 65 bytes" crossing the seam when the mapping is removed, and the callback case reads "mutated.in.callback" out of the ledger when the clone is dropped.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/cable.go:252
- A present
"reconnect": nullis silently treated as an absent flag because unmarshalling JSON null into*boolsucceeds with nil. This contradicts the parser contract that wrong-typed fields used by a recognized frame are invalid and collapses the documented absent/boolean wire distinction. Preserve presence separately and reject null while continuing to allow the key to be absent.
var env struct {
Reason string `json:"reason"`
Reconnect *bool `json:"reconnect"`
}
* origin/main: Police the endpoints a discovered issuer names, not only the issuer (#810) Refuse redirects on the signed download hop in every SDK (#809) Quiet known-noise CodeQL alerts without losing coverage (#807) Judge the advertised OAuth issuer's address, not just its spelling (#804) Let Go's raw GET retry loop see the Retry-After it already parses (#796) Deflake three tests that raced a wall clock, and gate the class that produced two of them (#794) SPEC §6: decide which statuses honour Retry-After, and how each loop composes it (#793) Pin the conformance runners' fixture reads, and give CI a leg that can see them break (#791) Report an anonymous embed the timestamp walk cannot resolve, instead of skipping it (#790) # Conflicts: # go/go.mod
Copilot: the fake's read-limit violation was a standalone fmt.Errorf, so errors.Is(err, ErrFrameOversize) was false through the seam the fake claims to mirror -- every loop test would pass against a classification the real transport defeats. The violation now wraps the sentinel, in the exact hunk PR #705's branch already carries (e4c595e), so the stack merge dedupes rather than conflicts. TestConn_OversizeFrameMatchesSentinelAndLatches pins the contract and the latch; red-proved against the unwrapped error (both reads report the missing sentinel), restored by copy, suite green.
Copilot pressed the scheme and port renderings a third time, this round with
the counterexample that unseats the decline: the ticket is opaque, so a mint
returning `t-abc://host/cable?ticket=t-abc` makes the scheme literally the
ticket, and an all-digit ticket can arrive as an out-of-range port
(`:99999?ticket=99999`). The declines reasoned by position — "the scheme is
structural, never secret" — but §23's Security Invariant is absolute about
the value ("Never log the ticket"), and when the server composes the URL, no
position in it can prove its text is not the ticket. Third variation of the
same finding means reassess the instrument, and the instrument here was the
echo itself.
Reasons are now a closed vocabulary. The one diagnostic worth keeping — the
realistic mis-mint of an http(s) URL where ws(s) belonged — survives as a
fixed-allowlist rendering ("mint returned an http(s) URL where ws(s) was
required"); every other refused scheme is named by class alone. The invalid
explicit port goes fully value-free: everything reaching that branch is out
of range or overlong, so the class is the whole story. §9's cap on
DialError.Error stays as the bound on what the TYPE can carry — a custom
transport composes its own reasons — with its test rebuilt off the closed
vocabulary.
TestCheckCableURL_NeverEchoesServerText pins the property with the
counterexamples themselves: restoring the scheme echo renders
`cable URL scheme "t-sekrit-99" is not ws(s)` and fails on "sekrit";
restoring the port echo renders the planted 987654321; reverting the cap
fails the bounded test at 1028 bytes.
The nil-preserving clone test said the srv1 digest and the subscription identifier "both distinguish 'no filter' from 'empty filter'". They do the opposite: canonicalJSON and subscribeIdentifier each branch on len, so nil and empty encode identically — which is exactly why the test's second assertion expects the filter key to remain EQUAL across the clone. The comment now describes only what the test pins: clone preserves the value verbatim instead of normalizing nil to empty, and nothing downstream can tell the two apart.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated 1 comment.
Suppressed comments (3)
Previously missed (3) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/checkpoint.go:98
url.URL.Port()preserves leading zeros, so an explicit default port such ashttps://example.com:0443is not stripped. That URL reaches the same TCP origin ashttps://example.com, but continuation validation rejects it as cross-origin and checkpoint identity splits it into a separate lineage, contrary to the numeric default-port normalization in SPEC §8. Canonicalize the port spelling before comparing it with the defaults.
port := u.Port()
if (scheme == "https" && port == "443") || (scheme == "http" && port == "80") {
port = ""
go/pkg/basecamp/eventfeed/backoff.go:104
- A valid positive repair interval of 1 ns produces a zero duration for every downward jitter draw because the float is truncated when converted to
time.Duration. The stacked connector accepts any positive interval and schedules this result directly, so these draws arm an immediate repair timer and can create a hot repair-poll loop. Clamp a positive jittered result to at least 1 ns (or reject intervals too small to jitter).
jittered := float64(interval) * (1 + repairJitterFraction*span)
if jittered >= float64(math.MaxInt64) {
return time.Duration(math.MaxInt64)
}
return time.Duration(jittered)
go/pkg/basecamp/eventfeed/filestore.go:420
- Renaming onto
s.pathreplaces the directory entry, not the target of a symlink. Thus a store path that is a symlink to a regular file reads the target, but its first successfulSavereplaces the symlink while leaving the target stale; later loads silently switch to the new file. This contradicts the documented symlink support aboveread. Either reject symlink store paths or preserve a stable target identity for writes.
…ver the server's Copilot carried the value invariant one surface further, and it holds: redactURL rendered CanonicalOrigin of a server-provided URL, which preserves scheme, host, and any non-default port — so a mint of `wss://cable.example:54321/cable?ticket=54321` handed an observer the ticket through the port, and a ticket-shaped host label would ride through the same way. That is the identical value-level leak checkCableURL's reasons just closed: §23's "never log the ticket" binds on the value, and the ticket is opaque, so "an origin cannot carry a secret" was the same positional reasoning the scheme decline died on. What the redactor is for decides the remedy. Observers get URL copies so an operator can tell which origin an errant walk touched; the diagnostic that matters is whether it was the configured one. So redactURL now takes the connector's canonical base origin and draws its output from a closed set: the empty string (a 410 with no resume URL), the CONFIGURED origin's own bytes when the input is same-origin with it, "[cross-origin URL]" when it points anywhere else, "[redacted]" when it cannot be reduced. No branch renders input bytes at all — the same-origin case deliberately returns the parameter, not the parsed origin — so the never-echoes property is by construction rather than by enumeration of components. The cable url, cross-origin by design, always renders the placeholder; its shard host was the one diagnostic lost, and it is exactly the server-chosen text the invariant forbids. checkContinuation's origin-in-the-error stays: SPEC §23 sanctions "carried redacted (origin only)" for the rejected continuation, and the poll lane's credential is an Authorization header, never a URL component — the cable URL is the only one whose bytes can contain the ticket. That rendering is also under §9's cap since the class was closed. TestRedactURL_OutputIsAClosedSet pins the property with the counterexamples themselves: reverting to origin-rendering leaks "wss://cable.example:54321" (the port is the ticket), the ticket-labeled host, and the hostile port on the configured host, all caught as outside the closed set. The run loop's call sites (PR 3) pass the connector's configured canonical base origin — the same value checkContinuation already takes.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated no new comments.
Suppressed comments (3)
Previously missed (3) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/cable_test.go:590
- This assertion comment still describes the superseded “truncate frame contents” rule. §23 now requires invalid-frame errors to render no frame contents at all, which is exactly the behavior this test verifies.
// §23 Security Invariants: error renderings of frame contents are
// bounded. The codec goes further — it never embeds frame bytes at all.
go/pkg/basecamp/eventfeed/dedupe.go:17
- A hit in
Seendeliberately leaves this list unchanged, so this is delivery recency rather than observation recency. Calling it “most-recently-seen” contradicts the new dedupe contract and can invite reintroducing the hit-refresh behavior.
// order holds ids most-recently-seen first.
go/pkg/basecamp/eventfeed/errors.go:104
- The updated §23 rule explicitly forbids invalid-frame errors from carrying frame contents; it no longer applies the truncation cap to them. This comment states the superseded rule and could encourage restoring the data leak that
invalidFrameErrornow prevents.
// maxErrorMessageBytes bounds every error rendering that can carry
// frame-derived text (SPEC.md §9 "Error Message Truncation",
// MAX_ERROR_MESSAGE_LENGTH = 500; §23's Security Invariants apply it to frame
// contents). Go's unit is bytes, matching the main client's
// MaxErrorMessageBytes.
Copilot's exact-head pass caught three comments describing superseded contracts — each one a doc that would misdirect the next reader toward reintroducing exactly what the code now prevents. Two restated the old "truncate frame contents" rule. §23's Security Invariants moved past it: frame contents are FORBIDDEN in renderings outright — invalidFrameError names its shape and nothing else, because bounding is not redacting — while §9's cap governs the package's other renderings (close reasons, terminal messages, mint and poll causes, dial reasons). The invalid-frame rendering test's comment called the absence "the codec going further" than a bounding rule, and maxErrorMessageBytes' doc said the cap applies "to frame contents"; both now state the rule the code implements, and the cap's doc names the renderings it actually binds. The third called the dedupe list "most-recently-seen first", which is the one thing Seen's own contract says it is not: a hit is a suppression, not a delivery, and deliberately never refreshes recency — the list is most-recently-DELIVERED first. The old wording is how the hit-refresh behavior, whose eviction pathology Seen's doc spells out, gets reintroduced by someone "fixing" the code to match the comment. Comment-only; no behavior or assertion changes, so no red proofs apply.
|
Covering note for the three suppressed findings in Copilot's review of
Comment-only — no behaviour or assertion moved, so no red proofs attach; verified against the SPEC sentences and code paths each comment describes. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated 2 comments.
Suppressed comments (4)
Previously missed (4) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/websocket_transport.go:161
strings.EqualFoldaccepts a server response such asACTIONCABLE-V1-JSON, although the client offered only the exactactioncable-v1-jsontoken. WebSocket subprotocol values are selected from the client's offered values, not compared as case-insensitive HTTP header names; accepting a different token also diverges from SPEC §23's literal protocol requirement. Enforce exact equality here (including the missing-protocol case).
go/pkg/basecamp/eventfeed/websocket_transport.go:112- This package-owned transport does not actually mirror
http.DefaultTransport: leavingMaxIdleConnsandIdleConnTimeoutat zero means no global idle-connection limit and no idle expiry, versus the standard defaults of 100 and 90 seconds. Because this client is global and callers cannot close its idle pool, failed handshakes across changing server-selected origins can retain connections indefinitely. Set both safe defaults explicitly.
go/pkg/basecamp/eventfeed/cable.go:206 encoding/jsonmatches struct tags case-insensitively, so this does not test the presence of the exact JSON membertype. For example,{"type":"ping","TYPE":"welcome"}overwrites the same field and is classified as a welcome, while a frame with onlyTYPEis treated as typed rather than as the typeless broadcast shape. Decode member names throughmap[string]json.RawMessage(and apply the same exact-name handling to the other envelope fields) so the wire grammar remains case-sensitive.
var envType struct {
Type json.RawMessage `json:"type"`
}
go/pkg/basecamp/eventfeed/cable.go:313
- These required-field checks are not exact: Go's JSON decoder accepts
ID,Kind, and other case variants for the tagged fields. A payload can therefore omit the schema's required lowercase key yet still be delivered, contrary to the stated nine-key push contract. Validate exact member names from a raw-message map before decoding values.
ID *int64 `json:"id"`
Copilot caught a fail-open: Dial passed a non-positive maxFrameBytes to the WebSocket stack as -1, the library's "no limit" sentinel — disabling the read cap on exactly the property the parameter exists to enforce. CableTransport.Dial promises the limit is enforced while reading, and §23 makes the bound a security invariant with no unlimited mode; a demonstration against the unfixed transport materialized a 2 MiB frame in full on a dial with limit 0. Both transports now refuse a non-positive limit as a usage-coded error before any I/O — checked ahead of everything else, ctx included, so a configuration bug surfaces as itself rather than as whichever transient condition also held. Clamping to the 1 MiB default was the alternative and loses to rejection: a silently-corrected value hides the caller bug the usage class exists to surface. The seam contract now states it (positive, refused otherwise, no unlimited mode), the fake refuses identically — a fake that accepted 0 would let run-loop tests pass against a value the real transport refuses — and the shared contract suite pins it for both implementations at once: with either refusal reverted, its harness fails "Dial with maxFrameBytes 0 succeeded, want a usage refusal".
read follows a symlink deliberately — an operator pointing the store through one is documented as ordinary — but writeAtomic renamed the staged temp onto the configured path itself, and rename replaces the directory ENTRY: the first save turned the symlink into a regular file and left its target untouched, silently splitting link-addressed consumers from target-addressed ones. Copilot flagged this on an earlier head too (suppressed, filestore.go:398); this closes both. Of the two consistent shapes — reject symlinked store paths outright, or write through them — rejection would contradict read's own documented contract, so Save now resolves the FINAL component before staging: writeAtomic renames onto the target the link names, stages the temp beside that target (which also keeps the rename same-filesystem when the link crosses one), and a dangling link gets its target created exactly as an open through it would. Only the last element is walked, bounded at the kernels' ELOOP-class 40; filepath.EvalSymlinks cannot serve here because it requires the full path to exist and this store's file is created on the first save. Lock identity stays the configured spelling by design (canonicalStorePath's reasoning is unchanged). Two fixture tests pin it with real symlinks: with the resolver reverted to a pass-through, Save leaves the link a regular file and the target still reading "pos-old", and the dangling-link save creates the file at the link's entry instead of its target — both caught.
golangci-lint flags the Lstat-error fall-through as nilerr; the comment above it already records why it is deliberate (the follow-up open/rename reports the failure with better context). The identical hunk exists on the connector branch so the stack merges dedupe.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 43 out of 44 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
go/pkg/basecamp/eventfeed/cable.go:271
- A broadcast with
"identifier": nullis silently classified asframeUnknown:encoding/jsonaccepts JSON null into astringand leaves it empty, so the condition below fails. This contradicts this parser's invalid-frame rule for wrong-typed fields and can silently discard an event instead of taking the socket-failure path that triggers poll repair. Decode identifier presence/value separately so absent remains non-broadcast while present null is rejected.
var env struct {
Identifier string `json:"identifier"`
Message json.RawMessage `json:"message"`
}
if err := json.Unmarshal(data, &env); err != nil {
return frame{}, newInvalidFrameError(invalidFrameParse)
}
if env.Identifier != "" && len(env.Message) > 0 {
return frame{kind: frameMessage, identifier: env.Identifier, message: env.Message}, nil
First half of the SPEC.md §23 event feed connector, split out of #705 so the
state machine can be reviewed on its own. #705 keeps the run loop, catch-up,
recovery and the tier-2 driver, and now stacks on this.
Eight bot rounds on #705 did not converge (12→3→5→2→2→1→3 threads, with late
findings in files no earlier round had touched), and a review pass found a P1
credential defect that all eight missed because it composes two files across a
package boundary. Splitting is the response to that shape.
Size: ~2.7k lines of production code, ~7k with tests.
What is here
Everything the run loop is built from and nothing that runs — each piece
testable without starting a feed:
seams.goTicketMinter/PollSource/CableTransport/CableConnevent.goEvent,Cursor,Page,Signal,Disposition,Observererrors.goTerminalErrorand its reason codesfilters.go,digest.gocheckpoint.goCheckpointKey/FlatKey/CanonicalOrigin, the store seamcontinuation.gofilestore.goFileCheckpointStorededupe.go,backoff.go,clock.go,cable.gotransport.go,websocket_transport.gofeedtest/There is no consumer entry point yet:
Newand the loop are on #705.The four fixes
1. The cable dial takes no credential it was not given (P1)
The cable origin is chosen by the server — the mint returns a url and the
connector dials it verbatim, cross-host by design — and the short-lived ticket
in its query is the only credential that origin is entitled to. Two paths handed
it more.
WebSocketTransport.HTTPClient, orhttp.DefaultClientwhen nil. An*http.Clientcarries three credentials invisible at the call site: aRoundTripper may inject
Authorization, a Jar attaches cookies, aTLSClientConfigmay present a client certificate. The DefaultClient fallbackis the same hazard with no call site at all. Deleted rather than validated —
a RoundTripper is opaque, so no runtime inspection could accept one client and
refuse another. Handshakes now run on a package-owned client. (The field had no
callers anywhere, so nothing regressed with it.)
URL userinfo.
net/http'ssend()turns it into a BasicAuthorizationheader, so a mint whose url carried userinfo made the connector authenticate
to a server-nominated origin with a credential the server chose. Refused before
any network I/O.
The proxy. A
wss://handshake reaches a proxy asCONNECT host:port, sothe ticket stays inside the tunnel; a
ws://handshake is forwarded in absoluteform, putting
/cable?ticket=…in the proxy's request line and access log inthe clear. Reachable, not theoretical: §9 admits
ws://for*.localhost, andnet/http's proxy rules exempt the literallocalhostand loopback IPs butnot
.localhostsubdomains. Cleartext dials no longer proxy; TLS dialsstill do.
Pre-fix transcript, against un-fixed code:
and from the proxy sentinel with the cleartext exemption removed:
TestCableHTTPClient_IsWiredShutexists because the first mutant writtenagainst the proxy fix survived:
Proxy: proxyFromEnvironmentcaptures thevar's value at init, so the behavior tests' sentinel never reached it — meaning
both would pass a regression to
Proxy: http.ProxyFromEnvironment. The wiringassertion holds the shape they cannot observe.
2. A suppressed duplicate is not a delivery
§23 defines the LRU as "actually-delivered event ids", recorded by every
delivery.
Seenrefreshed recency on a hit, which is the case where theevent is suppressed and no delivery happens. §23 says to expect poll-vs-push
duplication continuously, so a hot id was pinned at the front and evicted ids
delivered once and never seen again — which become eligible for exactly the
re-delivery the LRU prevents.
TestDedupe_HitRefreshesRecencyis inverted to..._HitDoesNotRefreshRecency,and I am calling that out rather than letting it look like a test edited to
accept a fix. It asserted the negation of the contract; nothing short of
inverting it is honest.
3. The checkpoint store reads a bounded regular file, under one lock
#761: the lock registry was keyed on the exact path spelling. On APFS or
NTFS
feed.jsonandFeed.jsonare one file, so two stores took two mutexes —the lost update the registry exists to prevent, reached by two call sites
disagreeing about capitalization. The lock key is now case-folded; the path each
store reads and writes is not.
The read followed whatever the path named. Against the pre-fix read, all four
cases fail:
The FIFO and device cases are hangs, so every assertion runs under a bound. Not
defensive dressing: the first draft bounded only the FIFO, and
/dev/zerotookthe package's 45s timeout with it, naming nothing.
4. One observer-safe URL redactor
The primitive #705 applies to every URL-bearing observer surface. Reduction is
via
CanonicalOriginrather than truncation at?, which matters for the casea naive redactor misses: userinfo is a credential in the authority, so
https://attacker:hunter2@evil.example/steal?ticket=…survives query-strippingintact and does not survive this.
Verification
Pristine worktree, one pass, clean tree before and after:
go build/go vet/go test -race -count=1/-count=5— all passmake go-lint— 0 issuesgosec -severity high -exclude-dir=pkg/generatedon the CI-pinned v2.23.0(module hash verified, not a scratchpad binary) — 0 issues
make check— exit 0Every fix was red-proven before it was written, and every test mutation-checked
after. Three tests were rewritten because mutation showed them vacuous.
One preparatory commit
1646f2c1frelocated the run-coupled declarations out ofcheckpoint.goandcontinuation.goso the two halves fall on file boundaries. The moved functionbodies are byte-identical. It also added direct tests for
checkContinuationand
Filters.clone, both of which were only reachable through a full run.Development history, review threads and proof lineage for every file here are on
#705, preserved at tag
pre-split/705-head.Five more from review
Copilot's rounds on this branch found five further defects; all five are fixed, each
red-proven against the un-fixed code first.
6c6e14f16typeis not a broadcast. A*stringgives the same nil for an absent key and a JSONnull, so{"type":null}was liveness-only while{"type":null,"identifier":…,"message":…}was delivered as an event — one wire value in two classes depending on its siblings. Presence is now decoded separately. A present-but-null type takes the ignore branch, not the reject branch: it names no type to recognize, which is §23's unrecognized-type case. BC3's push lane sends{identifier, message}with notypekey at all, checked against the current head of bc3 #9659, so the narrowing drops nothing real.fae998b16Closebounds the read, not just itself.closeGraceBudgetstoppedClosefrom waiting out the close handshake, but the socket is what releases a parked read and coder/websocket does not tear it down until its own 5s+5s ends — so a pendingReadFramestayed blocked four seconds afterClosereturned. Worse, a background read was uncancellable: the library installs its cancellation hook only when the read context has aDonechannel, andReadFrame(context.Background())is how a run loop parks a pump. The connection now owns a lifetime context every read and write derives from, cancelled onceCloseis done waiting — after the budget, never before, so the close frame is still written.60a28700dConnector, no constructor and no run loop here, and the docs said "runs the whole protocol". Now: foundations only, what has landed, both pending pieces, and that everything below documents the architecture they implement. AGENTS.md's row carried the same overclaim.791143207Savecrossing the cap renamed into place a file nothing can read again — and sinceSavereads before it writes,Savetoo. No in-band recovery; the operator must delete the file, discarding every other lineage's cursor. Reaching the cap is accretion, not an adversary: there is no delete, so a filter change leaves the old lineage in the file forever. Refusing degrades to the documented failed-save outcome instead of an unrecoverable one.b15e8d031ReadFramedocuments the precedence and honored it on the way out but not on the way in, so a cancelled read over a closed connection reported a connection failure — the shutdown a run loop performs.WriteFramealready checked the context first; the two disagreed. The assertion went in the shared transport contract, where thefeedtestfake already passed it and the real transport did not.Two findings were declined on merit with the reasoning in a comment rather than left open, and a third — the symlinked store path versus atomic rename — is flagged for a human call: it is the third round on one file, and every candidate remedy trades away a different documented property of what a store file's identity is.
Summary by cubic
Foundations for SPEC §23 Event Feed connector with hardened security invariants; no run loop yet. Splits out seams, models, codecs, persistence, and a default
WebSocketTransportso the state machine can be reviewed independently.Highlights
TicketMinter,PollSource,CableTransport,CheckpointStore,Clock; event/filter models; Action Cable frame parser and command encoder; backoff envelopes and named timers; continuation/resume URL validation; deterministicfeedtestfakes.ErrFrameOversize; bounded error renderings elsewhere; dedupe records only actually-delivered ids.wss://(allowws://only for localhost/loopback); never proxy cleartextws://; refuse redirects; negotiate Action Cable subprotocol; send no Origin; enforce positive max-frame limits; redact tickets in errors. DefaultWebSocketTransportusesgithub.com/coder/websocket.FileCheckpointStorereads/writes a single ≤8 MiB JSON file, requires a regular file, case-folds lock keys, preserves atomic writes, and saves through symlinks by resolving the final link and renaming onto its target.resolveStorePath’s deliberate nilerr fall-through; no behavior change.Migration
CableTransportimplementations must returnErrFrameOversizefor over-limit frames and must refuse non-positive max-frame limits as usage errors.Written for commit e7114fc. Summary will update on new commits.