Repository navigation
test(backend): #1745 #1746 #1748 #1749 cancel, cursor, SSE and Redis gaps - #1938
Merged
K1NGD4VID merged 4 commits intoNov 21, 2026
Merged
Conversation
…ure and Redis failure modes Four suites for the LabsCrypt#1745/LabsCrypt#1746/LabsCrypt#1748/LabsCrypt#1749 test gaps, each pinned to the contract the route or service actually publishes rather than the wording of the issue.
LabsCrypt#1932 renamed ApiError.status to statusCode and typed details as unknown, which left the LabsCrypt#1935 simulation spec failing the build gate for every backend branch. Assertions are unchanged: same status, same detail keys.
# Conflicts: # backend/tests/soroban_simulation_errors.test.ts
LabsCrypt#1930 put `requestId` into every `sendApiError` body, so three cursor assertions that pinned the two-field envelope went red. Assert the header value instead of dropping the field: the envelope is still compared in full.
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.
Description
Four test suites closing the backend regression gaps in #1745, #1746, #1748 and
#1749 — 118 tests over
stream/cancel.ts, the stream-events cursor route,sse.service.tsandlib/redis.ts. No production code is changed by them.One extra commit adapts a spec that
maininherited broken (#1935 writtenagainst the pre-#1932
ApiError). Without it the backend Build step failsfor every branch before a single test runs, so it is included and explained in
Why this PR touches a file it does not own.
Where an issue's wording does not match the code, this PR says so and tests the
behaviour that ships rather than the description.
Type of Change
Related Issues
Closes #1745
Closes #1746
Closes #1748
Closes #1749
Changes Made
backend/tests/stream-cancel-idempotency.test.ts— #1745, 34 testsPOST /v1/streams/:streamId/cancelmoves funds back and calls a publiccontract, so what matters is what the second call does.
409, andsorobanService.cancelStreamis called exactly once — its mock ismockResolvedValueOnce, so a second call rejects instead of passing quietly.winner's status rather than re-deriving its own.
isActive, not the status label (stream/cancel.ts:80): aCOMPLETEDstream is refused on the active flag, which is what the repositorywrites.
streamIdshape reachingparseStreamId:''→MISSING_STREAM_ID;' 7 ','abc','-1','12.5','1e3','0x7b'→INVALID_STREAM_ID;'0'and2**53+1accepted;'007'looked up as7n.400carrying the upstream message;any other throw →
500with nothing written; the DB write failing afterthe on-chain success →
500; a lookup that throws →500, never a fabricated404.404,403and409each beat the400for a missingsenderSecret.backend/tests/stream-events-cursor.test.ts— #1746, 27 testscursorwins overoffset: the query is{ cursor: { id: cursor }, skip: 1 }(
:396); with no cursor the offset passes through;''and[]take theoffset path.
count()is asserted unwindowed —{ where: { streamId } }and nothingelse (
:398). It pages metadata, not the slice.[{ timestamp: order }, { id: order }](
:394), which is what keeps ordering stable when two events share atimestamp.
hasMoreis decided differently per mode and both are pinned (:401-403):with a cursor
events.length === limit(full / short / empty page), withoutone
offset + events.length < total. Default 50, clamp 200.400forlimitof0,-5,ten,1.5,' 5', foroffset=-1, and fora non-numeric
streamId;eventTypeis carried into thewhereclause and aninvalid one is rejected.
is a
500, with no retry and no fallback to offset paging. Reported underAdditional Notes, not asserted as desirable.
backend/tests/sse-backpressure.test.ts— #1748, 28 testssides (
ceiling − 1keeps the client,ceilingdrops it) viares.writableLength, viares.socket.writableLength, and with neitherpresent (read as 0, client kept). A paused client that later fills past the
ceiling is still dropped.
the frame.
getPerIpPeakConnections()keeps its high-water mark; a client alreadywritableEndedis not ended again;end()throwing still removes the clientand leaves the service usable; a repeated
closeis idempotent; the heartbeattimer stops when the last client is dropped.
MAX_SSE_CONNECTIONS→503with noRetry-Afterhint;5 per IP and 10 per user →
429withRetry-After: 60;503wins when bothapply; the per-IP cap is scoped per address, not global. The env override
parses
'1.9'→ 1 and falls back to 10000 for'0' | '-4' | 'abc' | '' | ' ' | 'Infinity'.event: reconnect\ndata: {}\n\nto everyone reachable, anda client whose write throws during shutdown is not removed by that path —
pruning is the heartbeat's job.
Redis available it publishes
sse:stream:7/sse:user:GPUB123with{event,data}and suppresses the direct write; thepmessagehandler routesto subscribers of that stream and of
*, excludes everyone else, survivesmalformed JSON from a publisher, and
initRedisSubscriptionresolves when nosubscriber exists.
backend/tests/redis-connection.test.ts— #1749, 29 testsREDIS_URLunset and set to'': no client is constructed,connectRedis()resolves in single-instance mode, and disconnecting whennothing connected is safe.
availability flips only after both connect. An unreachable server makes
connectRedis()resolve rather than reject — the app still starts.maxRetriesPerRequest: 3,enableOfflineQueue: false,lazyConnect: truewith exactly oneconnect()per client, and
retryStrategyover[1,2,3,4,5]→[200,400,600,null,null]. The subscriber's scalars are compared field byfield against the publisher's —
toEqual(client.options)cannot express this,because
retryStrategyis a fresh closure per client and compares byreference.
pair;
disconnectRedis()quits both, clears availability, and is safe twice.is absent; a Redis-backed wrapper writing
zadd('withdrawals', 1000, 'stream-1:25')on the publisher, then falling backafter
disconnectRedis(); detection keeps running on the fallback after afailed boot — it degrades instead of disappearing.
['zremrangebyscore', 'zadd', 'pexpire']with-inf/at − 24 handpexpire(key, 24h); a read issues onlyzrangebyscore(key, 40_000, '+inf', 'WITHSCORES');distinctuseszcount;clearusesdel. A rejecting command propagates rather than returning anempty snapshot — an empty snapshot means "quiet", the wrong answer during an
outage.
id:weight(stream:42:12.5→ sum 19.5), anunparsable weight falling back to 1 with the row still counted, a non-numeric
score leaving
firstAt/lastAtnull whilecountstill reflects the rows,and the empty snapshot being
{0, 0, null, null}from a fresh object eachtime, so mutating one read cannot poison the next.
read needs, retention prunes on insert,
new InMemorySlidingWindowTracker(3)keeps the three newest, re-adding an idrefreshes it in place, and a never-written key answers zeroes.
Two behaviours are deliberately not pinned because they read as defects
rather than design (items 2 and 3 under Additional Notes): the
disconnect()of module state that was never assigned, and the
id+weight member encoding.Pinning them would freeze a bug in place.
backend/tests/soroban_simulation_errors.test.ts— the unblocking commitmainate4f4b5cfailsnpm run build— 19tscerrors, all in this onefile:
Proven pre-existing, not caused by this branch: the four new files were moved
out of the tree and
tscre-run at untouchede4f4b5c— same 19 errors. Cause:#1935 landed this spec against
ApiErroras it was then; #1932, merged on top ofit afterwards, renamed
status→statusCode, moved the module fromtypes/to
lib/and typeddetailsasunknown. The rename broke it at runtime too —expect(err.status)readundefined, 2 failing tests.The repair is mechanical and weakens nothing: 2 ×
.status→.statusCode, plusone local
detailsOf()that narrowsunknownonce instead of at 15 call sites.The file now runs 28/28. No other open PR touches it. If @Dreal-pyper or
@eazeeshow would rather carry it, say so and I will drop the commit — but while
it stands, no backend PR can go green.
Testing
CI's exact commands, run locally on Node
v22.23.3(.nvmrc) against athrowaway
postgres:16(port 55444) withnpx prisma generateandprisma migrate deployapplied first:Same base, same commit, with the four new files removed: 89 files, 1180
passed | 3 failed | 6 skipped. Those 3 failures were
tests/auth.test.tsandtests/stream.test.ts— the suites that share one database and are timingsensitive on an 8-core machine; both pass in the run above. Nothing was
serialised, skipped, or had a threshold lowered to obtain a green local run
(vitest suppresses the coverage table on a failing run, which is why that
baseline reports no coverage figure).
Non-vacuity
Assertions that cannot fail are worse than no tests, so each behaviour these
suites claim was checked by injecting the defect it is meant to catch — one
source mutation at a time, run, restore, next. 12 injected defects, 12
caught, each by the test that claims it:
!stream.isActivecompletion guardskip: 1→skip: 0{ id: order }dropped fromorderByhasMorefrom the total, not the page>=→>pausedshort-circuit>=→>enableOfflineQueue: false→truetimes > 3→> 5EMPTY_SNAPSHOT>→>=git status --porcelainwas empty after the final restore: thesrc/tree inthis PR is byte-identical to
main.Test Coverage
Soroban RPC server, including the one adapted spec
Coverage of the modules these issues name, from the green run above:
src/controllers/stream/cancel.tssrc/lib/redis.tssrc/services/sse.service.tssrc/lib/stream-id.tssrc/routes/v1/events.routes.tssrc/controllers/stream.controller.tsTest Steps
npm install --include=optionalat the repo root.DATABASE_URL+NODE_ENV=test(only neededfor step 4; the four new files mock Prisma entirely).
cd backend && npx prisma generate && npx prisma migrate deploy.npx vitest run tests/stream-cancel-idempotency.test.ts tests/stream-events-cursor.test.ts tests/sse-backpressure.test.ts tests/redis-connection.test.ts --coverage.enabled=false→ 118 passed.npx tsc -p tsconfig.json --noEmit→ exit 0 (this is the step that fails onmainwithout the second commit).Breaking Changes
Breaking Changes: None. No
src/file, route, response shape, metric,migration, generated type or lockfile is modified.
Checklist
suite opens with what it pins and why; the three premise corrections are
in the file headers)
see item 5 below, which is a docs-vs-code contradiction for a maintainer to
settle
exit 0)tscclean; the build emits nothingfor these files)
doubt from them with the 12-mutation check above
1301 tests)
mainate4f4b5cis an existing metric whose label set a code path fails to use; flagged
rather than changed here.
Additional Notes
Six things the code does that look wrong. All confirmed against the current
source and asserted nowhere, because each needs a product or owner decision:
500(
stream.controller.ts:406-408). Prisma throws when thecursorrow hasbeen pruned; the handler forwards to
errorHandlerinstead of falling back tooffset paging or answering
400. A client replaying a stale cursor after aretention prune gets a server error forever.
connectRedis()'s catch disconnects state it never assigned(
redis.ts:235-236). It reads_publisher/_subscriber, which are only setafter both connects succeed. If the publisher connects and the subscriber
fails, the publisher's socket stays open while the app reports Redis
unavailable — one leaked connection per failed boot, per instance.
addsaysiddeduplicates, but the member is
`${id}:${weight}`(redis.ts:297-299,used by both
addimplementations at:327and:386and counted bydistinctat:372and:428), so re-adding the same stream with adifferent volume is counted twice. The sentinel's "distinct streams" signal
can over-report under a variable-volume drain.
flowfi_sse_clients_dropped_totalis documented with reasonsslow_client/capacity/per_ip_limit(
backend/docs/observability/README.md:58) and those are exactly its threecall sites (
sse.service.ts:93,:103,:377). TheMAX_CONNECTIONS_PER_USERbranch (sse.service.ts:117-124) has no reasonlabel, so the limit an abuser hits most is invisible in the metric.
backend/docs/SSE_IMPLEMENTATION.md:149-150says "Connection Limits —Default: No hard limit, constrained by system resources." The service
enforces a 64 KiB writable buffer, 5 connections per IP, 10 per user and
10 000 in total.
commandTimeouton either Redis client — the [test] Cover Redis reconnect and command failures #1749 premise names one.A command that never returns is bounded only by the process.
Two notes on the suites themselves. They are pure-mock: no database, no real
socket, no live timer.
redis-connection.test.tsre-imports the module undertest with
vi.resetModules()— necessary becauseREDIS_URLis read at importtime and the memory-cache sweep interval starts on import — and stops every
loaded instance's sweep in
afterEachso it cannot leak an interval into thenext file. No file in this PR touches
package-lock.json, the OpenAPI spec,generated types, or anything under
src/.