Skip to content

test(backend): #1745 #1746 #1748 #1749 cancel, cursor, SSE and Redis gaps - #1938

Merged
K1NGD4VID merged 4 commits into
LabsCrypt:mainfrom
mallison031:1745-1746-1748-1749-test-gaps
Nov 21, 2026
Merged

K1NGD4VID merged 4 commits into
LabsCrypt:mainfrom
mallison031:1745-1746-1748-1749-test-gaps

Conversation

@mallison031

Copy link
Copy Markdown

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.ts and lib/redis.ts. No production code is changed by them.

One extra commit adapts a spec that main inherited broken (#1935 written
against the pre-#1932 ApiError). Without it the backend Build step fails
for 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

  • 🧪 Test addition or update
  • 🔧 Refactoring (no functional changes) — one stale spec adapted to the renamed error envelope; assertions unchanged

Related Issues

Closes #1745
Closes #1746
Closes #1748
Closes #1749

Changes Made

backend/tests/stream-cancel-idempotency.test.ts — #1745, 34 tests

POST /v1/streams/:streamId/cancel moves funds back and calls a public
contract, so what matters is what the second call does.

  • Two sequential cancels: the first broadcasts, the second is a 409, and
    sorobanService.cancelStream is called exactly once — its mock is
    mockResolvedValueOnce, so a second call rejects instead of passing quietly.
  • The loser of a cancel race reads the winner's committed row and reports the
    winner's status rather than re-deriving its own.
  • Liveness is isActive, not the status label (stream/cancel.ts:80): a
    COMPLETED stream is refused on the active flag, which is what the repository
    writes.
  • Every streamId shape reaching parseStreamId: '' → MISSING_STREAM_ID;
    ' 7 ', 'abc', '-1', '12.5', '1e3', '0x7b' → INVALID_STREAM_ID;
    '0' and 2**53+1 accepted; '007' looked up as 7n.
  • Failure taxonomy: simulation failure → 400 carrying the upstream message;
    any other throw → 500 with nothing written; the DB write failing after
    the on-chain success → 500; a lookup that throws → 500, never a fabricated
    404.
  • Guard precedence is part of the contract: 404, 403 and 409 each beat the
    400 for a missing senderSecret.

backend/tests/stream-events-cursor.test.ts — #1746, 27 tests

Premise. The issue cites backend/src/routes/v1/events.routes.ts, which
has no cursor — grep -ni cursor on that file returns nothing; it is
offset-paged through parsePagination (:115). The keyset cursor lives on
GET /v1/streams/:streamId/events
(backend/src/controllers/stream.controller.ts:336-410), so that is the route
covered here. Adding a cursor to the user-scoped route is a feature, not a
test gap.

  • cursor wins over offset: the query is { cursor: { id: cursor }, skip: 1 }
    (:396); with no cursor the offset passes through; '' and [] take the
    offset path.
  • count() is asserted unwindowed — { where: { streamId } } and nothing
    else (:398). It pages metadata, not the slice.
  • Both sort keys, both directions: [{ timestamp: order }, { id: order }]
    (:394), which is what keeps ordering stable when two events share a
    timestamp.
  • hasMore is decided differently per mode and both are pinned (:401-403):
    with a cursor events.length === limit (full / short / empty page), without
    one offset + events.length < total. Default 50, clamp 200.
  • 400 for limit of 0, -5, ten, 1.5, ' 5', for offset=-1, and for
    a non-numeric streamId; eventType is carried into the where clause and an
    invalid one is rejected.
  • Three tests pin today's recovery behaviour: a cursor row that no longer exists
    is a 500, with no retry and no fallback to offset paging. Reported under
    Additional Notes, not asserted as desirable.

backend/tests/sse-backpressure.test.ts — #1748, 28 tests

Premise. The issue asks for "queue limits". There is no queue:
grep -niE 'queue|backlog|pending' over sse.service.ts finds none. A slow
consumer is dropped, not buffered — writeToClient (:381-405) returns
false while client.paused, and once the buffer reaches
MAX_WRITABLE_BUFFER (64 KiB) it calls dropSlowClient (:375-379). The
suite pins that drop-don't-queue contract, including that frames skipped
during a pause are never replayed after drain.

  • Pause is honoured for events and heartbeats; the ceiling is tested from both
    sides (ceiling − 1 keeps the client, ceiling drops it) via
    res.writableLength, via res.socket.writableLength, and with neither
    present (read as 0, client kept). A paused client that later fills past the
    ceiling is still dropped.
  • One slow client cannot truncate a fan-out: every other subscriber still gets
    the frame.
  • Drop cleanup returns the per-IP and per-user slot while
    getPerIpPeakConnections() keeps its high-water mark; a client already
    writableEnded is not ended again; end() throwing still removes the client
    and leaves the service usable; a repeated close is idempotent; the heartbeat
    timer stops when the last client is dropped.
  • All three ceilings: MAX_SSE_CONNECTIONS → 503 with no Retry-After hint;
    5 per IP and 10 per user → 429 with Retry-After: 60; 503 wins when both
    apply; 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'.
  • Shutdown fans out event: reconnect\ndata: {}\n\n to everyone reachable, and
    a client whose write throws during shutdown is not removed by that path —
    pruning is the heartbeat's job.
  • Redis bridge: a local-only publish writes locally and does not publish; with
    Redis available it publishes sse:stream:7 / sse:user:GPUB123 with
    {event,data} and suppresses the direct write; the pmessage handler routes
    to subscribers of that stream and of *, excludes everyone else, survives
    malformed JSON from a publisher, and initRedisSubscription resolves when no
    subscriber exists.

backend/tests/redis-connection.test.ts — #1749, 29 tests

Premise. The issue names a "command timeout". None is configured:
makeClient (redis.ts:203-211) sets maxRetriesPerRequest: 3,
enableOfflineQueue: false, lazyConnect: true and no commandTimeout
(grep -ni commandtimeout backend/src/lib/redis.ts → no match), so a hung
command has no client-side bound. The suite pins the policy that is
configured, because that is what deployments rely on; the missing timeout is
reported rather than asserted as intended.

  • REDIS_URL unset and set to '': no client is constructed,
    connectRedis() resolves in single-instance mode, and disconnecting when
    nothing connected is safe.
  • Publisher and subscriber are distinct clients on the same URL, and
    availability flips only after both connect. An unreachable server makes
    connectRedis() resolve rather than reject — the app still starts.
  • Retry policy at the boundaries: maxRetriesPerRequest: 3,
    enableOfflineQueue: false, lazyConnect: true with exactly one connect()
    per client, and retryStrategy over [1,2,3,4,5] →
    [200,400,600,null,null]. The subscriber's scalars are compared field by
    field against the publisher's — toEqual(client.options) cannot express this,
    because retryStrategy is a fresh closure per client and compares by
    reference.
  • Reconnect after a failed boot recovers horizontal mode on the next client
    pair; disconnectRedis() quits both, clears availability, and is safe twice.
  • The tracker follows connection state: the shared in-memory instance when Redis
    is absent; a Redis-backed wrapper writing
    zadd('withdrawals', 1000, 'stream-1:25') on the publisher, then falling back
    after disconnectRedis(); detection keeps running on the fallback after a
    failed boot — it degrades instead of disappearing.
  • Command surface pinned exactly: insert order
    ['zremrangebyscore', 'zadd', 'pexpire'] with -inf / at − 24 h and
    pexpire(key, 24h); a read issues only
    zrangebyscore(key, 40_000, '+inf', 'WITHSCORES'); distinct uses zcount;
    clear uses del. A rejecting command propagates rather than returning an
    empty snapshot — an empty snapshot means "quiet", the wrong answer during an
    outage.
  • Reply decoding: weights from id:weight (stream:42:12.5 → sum 19.5), an
    unparsable weight falling back to 1 with the row still counted, a non-numeric
    score leaving firstAt/lastAt null while count still reflects the rows,
    and the empty snapshot being {0, 0, null, null} from a fresh object each
    time, so mutating one read cannot poison the next.
  • In-memory bounding: a narrow-window read does not delete the history a wide
    read needs, retention prunes on insert,
    new InMemorySlidingWindowTracker(3) keeps the three newest, re-adding an id
    refreshes 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 commit

main at e4f4b5c fails npm run build — 19 tsc errors, all in this one
file:

$ cd backend && npx tsc -p tsconfig.json --noEmit
tests/soroban_simulation_errors.test.ts(138,18): error TS2339: Property 'status' does not exist on type 'ApiError'.
tests/soroban_simulation_errors.test.ts(140,27): error TS2339: Property 'contractErrorCode' does not exist on type '{}'.
... 17 more, all in this file
19 errors

Proven pre-existing, not caused by this branch: the four new files were moved
out of the tree and tsc re-run at untouched e4f4b5c — same 19 errors. Cause:
#1935 landed this spec against ApiError as it was then; #1932, merged on top of
it afterwards, renamed status → statusCode, moved the module from types/
to lib/ and typed details as unknown. The rename broke it at runtime too —
expect(err.status) read undefined, 2 failing tests.

The repair is mechanical and weakens nothing: 2 × .status → .statusCode, plus
one local detailsOf() that narrows unknown once 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 a
throwaway postgres:16 (port 55444) with npx prisma generate and
prisma migrate deploy applied first:

$ cd backend && npm run build                          → exit 0
$ cd backend && npm run codegen:openapi                → exit 0
$ cd frontend && npm run codegen:api-types             → exit 0
$ git diff --exit-code -- backend/swagger/flowfi.openapi.json \
      frontend/src/lib/api-types.generated.ts           → exit 0 (no drift)

$ cd backend && DATABASE_URL=postgresql://postgres:password@127.0.0.1:55444/flowfi_test \
    NODE_ENV=test npx vitest run --coverage --reporter=basic
 Test Files  93 passed (93)
      Tests  1301 passed | 6 skipped (1307)
All files    | 80.51 | 84.19 | 80.03 | 80.51        (vitest gate: 60 on all four)
exit 0

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.ts and
tests/stream.test.ts — the suites that share one database and are timing
sensitive 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:

injected defect test that failed
!stream.isActive completion guard answers the first request 200 and the second 409 once the write is visible
skip: 1 → skip: 0 seeks past the cursor row instead of re-reading it
{ id: order } dropped from orderBy sorts by timestamp with id as the tiebreaker, newest first
hasMore from the total, not the page reports more pages when the cursor page came back exactly full
buffer ceiling >= → > drops a client at the ceiling, where the comparison is inclusive
bypass the paused short-circuit drops frames written while the client is behind and does not replay them after drain
IP slot not returned on drop gives the IP slot back when a client is dropped for being slow
connection ceiling >= → > rejects at MAX_SSE_CONNECTIONS with 503 and no Retry-After hint
enableOfflineQueue: false → true declines to queue commands while the link is down
retry cutoff times > 3 → > 5 backs off 200ms, 400ms, 600ms and then stops retrying
return the shared EMPTY_SNAPSHOT answers an empty window with zeroes and no timestamps
sample cap > → >= evicts the oldest samples once a key is over its cap

git status --porcelain was empty after the final restore: the src/ tree in
this PR is byte-identical to main.

Test Coverage

  • Unit tests added/updated (118 new tests across 4 files)
  • Integration tests — not applicable: every file here mocks Prisma or the
    Soroban RPC server, including the one adapted spec

Coverage of the modules these issues name, from the green run above:

file stmts branch funcs lines
src/controllers/stream/cancel.ts 100 96 100 100
src/lib/redis.ts 98.28 89.32 100 98.28
src/services/sse.service.ts 94.98 95.32 93.1 94.98
src/lib/stream-id.ts 93.75 90.9 100 93.75
src/routes/v1/events.routes.ts 92.85 90 100 92.85
src/controllers/stream.controller.ts 81.54 67.83 100 81.54

Test Steps

  1. npm install --include=optional at the repo root.
  2. Start Postgres 16 and export DATABASE_URL + NODE_ENV=test (only needed
    for step 4; the four new files mock Prisma entirely).
  3. cd backend && npx prisma generate && npx prisma migrate deploy.
  4. 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.
  5. npx tsc -p tsconfig.json --noEmit → exit 0 (this is the step that fails on
    main without the second commit).

Breaking Changes

Breaking Changes: None. No src/ file, route, response shape, metric,
migration, generated type or lockfile is modified.

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas (each
    suite opens with what it pins and why; the three premise corrections are
    in the file headers)
  • I have made corresponding changes to the documentation — deliberately not:
    see item 5 below, which is a docs-vs-code contradiction for a maintainer to
    settle
  • Updated Postman/Hoppscotch API collections if routes changed — no routes changed
  • Ran the OpenAPI api-types drift check and it produced no diff (exit 0)
  • My changes generate no new warnings (tsc clean; the build emits nothing
    for these files)
  • I have added tests that prove the behaviour is real — and removed the
    doubt from them with the 12-mutation check above
  • New and existing unit tests pass locally with my changes (93/93 files,
    1301 tests)
  • Any dependent changes have been merged and published — branch is on
    main at e4f4b5c
  • I have checked for breaking changes and documented them if applicable
  • Grafana dashboard / alert rules — no metric added or changed. Item 4 below
    is 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:

  1. A cursor that no longer resolves is a 500
    (stream.controller.ts:406-408). Prisma throws when the cursor row has
    been pruned; the handler forwards to errorHandler instead of falling back to
    offset paging or answering 400. A client replaying a stale cursor after a
    retention prune gets a server error forever.
  2. connectRedis()'s catch disconnects state it never assigned
    (redis.ts:235-236). It reads _publisher/_subscriber, which are only set
    after 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.
  3. The tracker's documented dedupe key is not the member key. add says id
    deduplicates, but the member is `${id}:${weight}` (redis.ts:297-299,
    used by both add implementations at :327 and :386 and counted by
    distinct at :372 and :428), so re-adding the same stream with a
    different volume is counted twice. The sentinel's "distinct streams" signal
    can over-report under a variable-volume drain.
  4. The per-user SSE rejection increments nothing.
    flowfi_sse_clients_dropped_total is documented with reasons
    slow_client / capacity / per_ip_limit
    (backend/docs/observability/README.md:58) and those are exactly its three
    call sites (sse.service.ts:93, :103, :377). The
    MAX_CONNECTIONS_PER_USER branch (sse.service.ts:117-124) has no reason
    label, so the limit an abuser hits most is invisible in the metric.
  5. backend/docs/SSE_IMPLEMENTATION.md:149-150 says "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.
  6. No commandTimeout on 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.ts re-imports the module under
test with vi.resetModules() — necessary because REDIS_URL is read at import
time and the memory-cache sweep interval starts on import — and stops every
loaded instance's sweep in afterEach so it cannot leak an interval into the
next file. No file in this PR touches package-lock.json, the OpenAPI spec,
generated types, or anything under src/.

…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.
@K1NGD4VID
K1NGD4VID marked this pull request as ready for review November 21, 2026 16:47
@K1NGD4VID
K1NGD4VID merged commit 11dc755 into LabsCrypt:main Nov 21, 2026
16 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

3 participants