From e66c282f9098f87d5df5d5a938e609fdbbede720 Mon Sep 17 00:00:00 2001 From: Jimmy Song Date: Thu, 21 May 2026 18:41:29 -0700 Subject: [PATCH 1/3] fix(topic): tie subscribe lifecycle to consumer-read, not send() The default TopicQuery.getConfig.subscribe only defined the cleanup half and depended on _topicAdapter being set inside TopicQueryAdapter.send. Whenever send short-circuited (pre-fulfilled topic via fulfillTopic, or in-memory cache within staleTime), subscribe never fired but unsubscribe still fired on consumer unmount, tearing down adapter state that was never registered. Set the adapter on the execution context eagerly in QueryResult.getOrCreateExecutionContext, implement both halves of the default subscribe, and drop the now-redundant subscribe call from send. reconcileSubscription is also called unconditionally on activation so that subscribe runs before the first fetch awaits. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../topic-subscribe-consumer-lifecycle.md | 5 +++ packages/fetchium/src/QueryResult.ts | 12 ++++-- .../src/__tests__/topic-query.test.ts | 43 +++++++++++++++++++ packages/fetchium/src/topic/TopicQuery.ts | 11 +++-- .../fetchium/src/topic/TopicQueryAdapter.ts | 5 +-- 5 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 .changeset/topic-subscribe-consumer-lifecycle.md diff --git a/.changeset/topic-subscribe-consumer-lifecycle.md b/.changeset/topic-subscribe-consumer-lifecycle.md new file mode 100644 index 0000000..3001f8a --- /dev/null +++ b/.changeset/topic-subscribe-consumer-lifecycle.md @@ -0,0 +1,5 @@ +--- +'fetchium': patch +--- + +Fix `TopicQuery` subscribe/unsubscribe to follow consumer-read lifecycle instead of the fetch path. Previously, `adapter.subscribe(topic)` was only invoked from `TopicQueryAdapter.send`, so it never fired when `send` short-circuited (pre-fulfilled topic via `fulfillTopic`, or in-memory cache within `staleTime`). The default `TopicQuery.getConfig.subscribe` only defined the cleanup half and depended on `_topicAdapter` being set inside `send`, so on those same paths the consumer's unmount would call `adapter.unsubscribe(topic)` without a matching subscribe, tearing down adapter state that was never registered. The adapter is now stashed on the execution context eagerly, the default `subscribe` implements both setup and cleanup, and the `subscribe` call is removed from `send`. Subscribe now fires on consumer activation and unsubscribe on deactivation, regardless of where the data came from. diff --git a/packages/fetchium/src/QueryResult.ts b/packages/fetchium/src/QueryResult.ts index d7d6e5a..f2dc5e2 100644 --- a/packages/fetchium/src/QueryResult.ts +++ b/packages/fetchium/src/QueryResult.ts @@ -268,9 +268,10 @@ export class QueryInstance { } try { - if (cached !== undefined) { - this.reconcileSubscription(); - } + // Wire up subscribe before the first fetch so adapters that resolve + // `send()` via stream events (TopicQuery) are on the wire by the time + // `send()` awaits. + this.reconcileSubscription(); if (cached === undefined || this.isStale) { await sleep(0); @@ -308,6 +309,11 @@ export class QueryInstance { ); this._executionCtx.refetch = () => this.refetch(); this._executionCtx.rawFetchNext = this.def.statics.rawFetchNext; + // `TopicQuery.getConfig.subscribe` reads `_topicAdapter` from the ctx; + // set it eagerly so subscribe/unsubscribe work on the cache-fresh and + // pre-fulfilled paths where `send()` never runs. + (this._executionCtx as unknown as Record)._topicAdapter = + this.queryClient.getAdapter(this.def.statics.adapterClass); this._resolvedOptions = reactiveSignal(() => this.def.resolveOptions(this._executionCtx!)); } diff --git a/packages/fetchium/src/__tests__/topic-query.test.ts b/packages/fetchium/src/__tests__/topic-query.test.ts index 01ddb9e..49a2adb 100644 --- a/packages/fetchium/src/__tests__/topic-query.test.ts +++ b/packages/fetchium/src/__tests__/topic-query.test.ts @@ -93,13 +93,24 @@ class MockTopicQueryAdapter extends TopicQueryAdapter { private _unsubscribers = new Map void>(); private _topicMeta = new Map(); + /** Per-topic subscribe call counter, for tests. */ + subscribeCalls = new Map(); + /** Per-topic unsubscribe call counter, for tests. */ + unsubscribeCalls = new Map(); + constructor(stream: MockStream, fetchFn: (url: string, init?: RequestInit) => Promise) { super(); this._stream = stream; this._fetch = fetchFn; } + /** Test helper: pre-fulfill a topic before any consumer mounts. */ + preload(topic: string, data: unknown): void { + this.fulfillTopic(topic, data); + } + subscribe(topic: string): void { + this.subscribeCalls.set(topic, (this.subscribeCalls.get(topic) ?? 0) + 1); const unsub = this._stream.subscribe(topic, { onData: (data, meta) => { if (meta) this._topicMeta.set(topic, meta); @@ -116,6 +127,7 @@ class MockTopicQueryAdapter extends TopicQueryAdapter { } unsubscribe(topic: string): void { + this.unsubscribeCalls.set(topic, (this.unsubscribeCalls.get(topic) ?? 0) + 1); this._unsubscribers.get(topic)?.(); this._unsubscribers.delete(topic); this.clearTopic(topic); @@ -546,6 +558,37 @@ describe('TopicQuery', () => { }); }); + it('should pair subscribe and unsubscribe to consumer lifecycle when topic is pre-fulfilled', async () => { + const adapter = client.getAdapter(MockTopicQueryAdapter) as MockTopicQueryAdapter; + + class GetPrices extends MockTopicQuery { + topic = 'prices:preloaded'; + result = { + items: t.array(t.entity(TopicPrice)), + }; + } + + adapter.preload('prices:preloaded', { + items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }], + }); + expect(adapter.subscribeCalls.get('prices:preloaded')).toBeUndefined(); + + await testWithClient(client, async () => { + const relay = fetchQuery(GetPrices); + await relay; + + expect(relay.isResolved).toBe(true); + expect(relay.value!.items[0].value).toBe(50000); + expect(adapter.subscribeCalls.get('prices:preloaded')).toBe(1); + expect(adapter.unsubscribeCalls.get('prices:preloaded')).toBeUndefined(); + }); + + await sleep(10); + + expect(adapter.subscribeCalls.get('prices:preloaded')).toBe(1); + expect(adapter.unsubscribeCalls.get('prices:preloaded')).toBe(1); + }); + it('should maintain entity identity across queries sharing entities', async () => { class GetPricesA extends MockTopicQuery { topic = 'prices:a'; diff --git a/packages/fetchium/src/topic/TopicQuery.ts b/packages/fetchium/src/topic/TopicQuery.ts index e337e09..c6569e8 100644 --- a/packages/fetchium/src/topic/TopicQuery.ts +++ b/packages/fetchium/src/topic/TopicQuery.ts @@ -24,11 +24,14 @@ export abstract class TopicQuery extends Query { return { staleTime: 0, subscribe: () => { + const adapter = (this as Record)._topicAdapter as TopicQueryAdapter | undefined; + const topic = this.getTopic ? this.getTopic() : this.topic; + if (adapter && topic !== undefined) { + adapter.subscribe(topic); + } return () => { - const adapter = (this as Record)._topicAdapter as TopicQueryAdapter | undefined; - const topic = this.getTopic ? this.getTopic() : this.topic; - if (topic !== undefined) { - adapter?.unsubscribe(topic); + if (adapter && topic !== undefined) { + adapter.unsubscribe(topic); } }; }, diff --git a/packages/fetchium/src/topic/TopicQueryAdapter.ts b/packages/fetchium/src/topic/TopicQueryAdapter.ts index eb42de4..584d79b 100644 --- a/packages/fetchium/src/topic/TopicQueryAdapter.ts +++ b/packages/fetchium/src/topic/TopicQueryAdapter.ts @@ -92,7 +92,6 @@ export abstract class TopicQueryAdapter extends QueryAdapter { override async send(ctx: Query, _signal: AbortSignal): Promise { const topicCtx = ctx as TopicCtx; - topicCtx._topicAdapter = this; const topic = topicCtx.getTopic ? topicCtx.getTopic() : topicCtx.topic; if (topic === undefined) { @@ -112,7 +111,8 @@ export abstract class TopicQueryAdapter extends QueryAdapter { } } - // No state yet — create a deferred and subscribe + // No state yet, create a deferred. Subscribe is handled by + // `TopicQuery.getConfig.subscribe`, which runs before this path. let resolve!: (data: unknown) => void; let reject!: (error: unknown) => void; const promise = new Promise((res, rej) => { @@ -121,7 +121,6 @@ export abstract class TopicQueryAdapter extends QueryAdapter { }); this._topics.set(topic, { status: 'pending', promise, resolve, reject }); - this.subscribe(topic); return promise; } From c9a0098a5eeaf6ac2fc3936f571dfaee564abe84 Mon Sep 17 00:00:00 2001 From: Jimmy Song Date: Thu, 21 May 2026 18:46:40 -0700 Subject: [PATCH 2/3] chore(changeset): tighten changelog entry Drop the internal-mechanism sentence and the restatement; CHANGELOG readers don't have the internal symbols and the first sentence already covers what changes for them. Co-Authored-By: Claude Opus 4.7 (1M context) --- .changeset/topic-subscribe-consumer-lifecycle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/topic-subscribe-consumer-lifecycle.md b/.changeset/topic-subscribe-consumer-lifecycle.md index 3001f8a..15fbf0d 100644 --- a/.changeset/topic-subscribe-consumer-lifecycle.md +++ b/.changeset/topic-subscribe-consumer-lifecycle.md @@ -2,4 +2,4 @@ 'fetchium': patch --- -Fix `TopicQuery` subscribe/unsubscribe to follow consumer-read lifecycle instead of the fetch path. Previously, `adapter.subscribe(topic)` was only invoked from `TopicQueryAdapter.send`, so it never fired when `send` short-circuited (pre-fulfilled topic via `fulfillTopic`, or in-memory cache within `staleTime`). The default `TopicQuery.getConfig.subscribe` only defined the cleanup half and depended on `_topicAdapter` being set inside `send`, so on those same paths the consumer's unmount would call `adapter.unsubscribe(topic)` without a matching subscribe, tearing down adapter state that was never registered. The adapter is now stashed on the execution context eagerly, the default `subscribe` implements both setup and cleanup, and the `subscribe` call is removed from `send`. Subscribe now fires on consumer activation and unsubscribe on deactivation, regardless of where the data came from. +Fix `TopicQuery` subscribe/unsubscribe to track consumer-read lifecycle instead of the fetch path. Previously, subscribe never fired when `send()` short-circuited (pre-fulfilled topic via `fulfillTopic`, or cache within `staleTime`), but the consumer's unmount would still call unsubscribe and tear down adapter state that was never registered. From 8bce9f07567df8c21e13b466d2f25b60a8f19c82 Mon Sep 17 00:00:00 2001 From: Jimmy Song Date: Fri, 22 May 2026 10:57:35 -0700 Subject: [PATCH 3/3] fix lint issues --- packages/fetchium/src/QueryResult.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/fetchium/src/QueryResult.ts b/packages/fetchium/src/QueryResult.ts index f2dc5e2..c695e5c 100644 --- a/packages/fetchium/src/QueryResult.ts +++ b/packages/fetchium/src/QueryResult.ts @@ -312,8 +312,9 @@ export class QueryInstance { // `TopicQuery.getConfig.subscribe` reads `_topicAdapter` from the ctx; // set it eagerly so subscribe/unsubscribe work on the cache-fresh and // pre-fulfilled paths where `send()` never runs. - (this._executionCtx as unknown as Record)._topicAdapter = - this.queryClient.getAdapter(this.def.statics.adapterClass); + (this._executionCtx as unknown as Record)._topicAdapter = this.queryClient.getAdapter( + this.def.statics.adapterClass, + ); this._resolvedOptions = reactiveSignal(() => this.def.resolveOptions(this._executionCtx!)); }