From 2687269ea24b01e1377e3064d4f13cbd081dcc52 Mon Sep 17 00:00:00 2001 From: Gustavo Aires <39544919+gustavomts@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:47:04 -0300 Subject: [PATCH 1/5] fix(ios): load documents on serial queues so iOS 26 can't starve them iOS 26 PDFKit blocks a Vision thread for good for each PDFView closed while it analyzes a page. Those threads come from GCD's 64 constrained worker threads, which every concurrent queue shares. After 64 of them, work on the loader's concurrent queue never starts, so no document loads again for the rest of the process. Serial queues run on GCD's overcommit threads, which this limit does not apply to. The loader, the download cache and the PdfCache API queues are now serial. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011ViQPije4UJWykNcYnbmgv --- package/ios/DocumentCache.swift | 3 ++- package/ios/HybridBetterPdfCache.swift | 3 ++- package/ios/PdfDocumentLoader.swift | 7 ++++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/package/ios/DocumentCache.swift b/package/ios/DocumentCache.swift index 386a1b0..1872103 100644 --- a/package/ios/DocumentCache.swift +++ b/package/ios/DocumentCache.swift @@ -49,7 +49,8 @@ final class DocumentCache { let store: DocumentCacheStore private let clock: () -> Int64 - private let workQueue = DispatchQueue(label: "com.betterpdf.cache", qos: .userInitiated, attributes: .concurrent) + // Serial on purpose; see PdfDocumentLoader.workQueue. + private let workQueue = DispatchQueue(label: "com.betterpdf.cache", qos: .userInitiated) private let lock = NSLock() private var inFlight: [String: SharedDownload] = [:] diff --git a/package/ios/HybridBetterPdfCache.swift b/package/ios/HybridBetterPdfCache.swift index c4d7eef..03d95e5 100644 --- a/package/ios/HybridBetterPdfCache.swift +++ b/package/ios/HybridBetterPdfCache.swift @@ -70,7 +70,8 @@ final class HybridBetterPdfCache: HybridBetterPdfCacheSpec { } } - private static let queue = DispatchQueue(label: "com.betterpdf.cache.api", qos: .userInitiated, attributes: .concurrent) + // Serial on purpose; see PdfDocumentLoader.workQueue. + private static let queue = DispatchQueue(label: "com.betterpdf.cache.api", qos: .userInitiated) private func finish(_ requestId: Double) { lock.withLock { diff --git a/package/ios/PdfDocumentLoader.swift b/package/ios/PdfDocumentLoader.swift index 18c5062..e37b217 100644 --- a/package/ios/PdfDocumentLoader.swift +++ b/package/ios/PdfDocumentLoader.swift @@ -10,7 +10,12 @@ import PDFKit /// reads of the same file (outline, page sizes, page images) keep finding it /// when the copy is replaced or removed while displayed. final class PdfDocumentLoader { - private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated, attributes: .concurrent) + // Serial, like every queue here: GCD runs a serial queue on its overcommit + // threads. A concurrent queue shares the process's 64 constrained threads, + // and iOS 26 PDFKit blocks one of them for good per PDFView closed while + // it analyzes a page (PDFPageAnalyzerV2 → Vision). After 64, no work on a + // concurrent queue ever starts again, so no document would load. + private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated) /// Loads the document. `progress` (remote downloads only, throttled) and /// `completion` are called on the main queue, unless cancelled; the final From a516ddb9ecb073e2fab1127b6164d1077f0fd867 Mon Sep 17 00:00:00 2001 From: Gustavo Aires <39544919+gustavomts@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:47:06 -0300 Subject: [PATCH 2/5] test(e2e): reopen a document 80 times in a row betterpdfexample://reopen?count=N&source=bundled|file|remote opens a document N times, closing each viewer right after it loads. The stress-reopen flow waits for all 80 opens. On iOS 26 without the serial queues, open 65 never loads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011ViQPije4UJWykNcYnbmgv --- CONTRIBUTING.md | 3 +- example/App.tsx | 44 ++++++++++++++++ example/e2e/stress-reopen.yaml | 16 ++++++ example/screens/ReopenScreen.tsx | 86 ++++++++++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 example/e2e/stress-reopen.yaml create mode 100644 example/screens/ReopenScreen.tsx diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 555e569..964c9ce 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,7 +52,7 @@ Flows live in `example/e2e/` and run on both platforms: ```sh example/e2e/run.sh # functional flows -example/e2e/run.sh stress-open-close stress-rapid # stress flows +example/e2e/run.sh stress-open-close stress-rapid stress-reopen # stress flows ``` | Flow | Covers | @@ -63,6 +63,7 @@ example/e2e/run.sh stress-open-close stress-rapid # stress flows | `viewer-password` | `password-required` → `invalid-password` → unlock | | `stress-open-close` | 10× open/close of the 1000- and 500-page scans | | `stress-close-during-work` | documents closed while their work runs — renders in a fling, a search, a page image, a download, the outline, a form fill and export, `PdfDocument` page images — 5 rounds; watch logcat (`adb logcat -b crash`) and the iOS crash reports while it runs | +| `stress-reopen` | a document opened 80 times in a row, each viewer closed right after it loads; iOS 26 blocks a thread per viewer closed mid-analysis, and loads must go on past 64 of them. `SOURCE=file` or `SOURCE=remote` (`maestro test -e SOURCE=remote`) instead of the bundled sample | | `stress-rapid` | rapid flings, direction changes, jumps and zooms on 1000 pages | | `viewer-links` | page tap coordinates in PDF points, URL link reported (not opened), internal link followed, double tap not reported as a tap; a `/Dest` with `/Fit` and a name-tree destination, and a JavaScript action reported as a page tap (`links-all`). Run it on an Android 14 emulator without SDK extension 13 too: links there come from the library's parser alone | | `viewer-load-progress` | download progress of a remote document (fixture server throttled via `?bytesPerSecond=`) | diff --git a/example/App.tsx b/example/App.tsx index 73c6787..dd8c4c9 100644 --- a/example/App.tsx +++ b/example/App.tsx @@ -8,6 +8,7 @@ import { BenchmarkScreen, type BenchRequest } from './screens/BenchmarkScreen'; import { DocumentsScreen } from './screens/DocumentsScreen'; import { EmbeddedScreen } from './screens/EmbeddedScreen'; import { OfflineScreen } from './screens/OfflineScreen'; +import { ReopenScreen, type ReopenSource } from './screens/ReopenScreen'; import { SHOWCASE_FEATURES, ShowcaseScreen, @@ -60,6 +61,25 @@ function parseShowcaseLink(url: string | null): ShowcaseFeature | null { return SHOWCASE_FEATURES.find((name) => name === feature) ?? null; } +/** + * `betterpdfexample://reopen?count=80[&source=bundled|file|remote]` opens a + * document `count` times in a row. + */ +function parseReopenLink( + url: string | null, +): { count: number; source: ReopenSource; key: number } | null { + const match = url == null ? null : /^[a-z]+:\/\/reopen\?(.*)$/.exec(url); + if (match == null) return null; + const params = new URLSearchParams(match[1]); + const count = Number(params.get('count') ?? 80); + const source = params.get('source') ?? 'bundled'; + if (!(count > 0)) return null; + if (source !== 'bundled' && source !== 'file' && source !== 'remote') { + return null; + } + return { count, source, key: Date.now() }; +} + export default function App() { const [tab, setTab] = useState('viewer'); const [autoRun, setAutoRun] = useState(null); @@ -67,9 +87,18 @@ export default function App() { feature: ShowcaseFeature; key: number; } | null>(null); + const [reopen, setReopen] = + useState>(null); useEffect(() => { const handle = (url: string | null) => { + const reopenRequest = parseReopenLink(url); + if (reopenRequest != null) { + setShowcase(null); + setReopen(reopenRequest); + return; + } + setReopen(null); const feature = parseShowcaseLink(url); if (feature != null) { setShowcase({ feature, key: Date.now() }); @@ -88,6 +117,21 @@ export default function App() { return () => subscription.remove(); }, []); + if (reopen != null) { + return ( + + + + + + + ); + } + if (showcase != null) { return ( diff --git a/example/e2e/stress-reopen.yaml b/example/e2e/stress-reopen.yaml new file mode 100644 index 0000000..30d3040 --- /dev/null +++ b/example/e2e/stress-reopen.yaml @@ -0,0 +1,16 @@ +# Opens a document 80 times in a row, closing each viewer right after it +# loads. iOS 26 leaves one thread blocked for good per viewer closed while +# PDFKit still analyzes its page; past 64 of them, documents must still load. +# Debug builds load the bundled sample from Metro over HTTP (DocumentCache); +# `file` and `remote` need the fixture server. +appId: software.gmi.betterpdf.example +--- +- runFlow: _start.yaml +- openLink: betterpdfexample://reopen?count=80&source=${SOURCE || 'bundled'} +# iOS asks before a link opens the app. +- tapOn: + text: "Open" + optional: true +- extendedWaitUntil: + visible: "Reopened 80 / 80" + timeout: 180000 diff --git a/example/screens/ReopenScreen.tsx b/example/screens/ReopenScreen.tsx new file mode 100644 index 0000000..f9bc71c --- /dev/null +++ b/example/screens/ReopenScreen.tsx @@ -0,0 +1,86 @@ +import { useEffect, useState } from 'react'; +import { StyleSheet, Text, View } from 'react-native'; +import { PdfView, type PdfSource } from 'react-native-better-pdf'; +import { ensureFixture, FIXTURE_SERVER } from '../documents'; +import { colors } from '../ui'; + +export type ReopenSource = 'bundled' | 'file' | 'remote'; + +/** A load that takes longer than this counts as stalled. */ +const STALL_MS = 10_000; + +async function resolveSource(source: ReopenSource): Promise { + switch (source) { + case 'bundled': + // Metro bundles PDF assets through require(). + // eslint-disable-next-line @typescript-eslint/no-require-imports + return require('../assets/sample.pdf') as number; + case 'file': + return { uri: (await ensureFixture('small')).uri }; + case 'remote': + return { uri: `${FIXTURE_SERVER}/small.pdf` }; + } +} + +/** + * Opens a document `count` times in a row, closing each viewer right after + * its load event, the way a list of documents is browsed quickly. On iOS 26, + * each viewer closed while PDFKit still analyzes its page leaves a thread + * blocked for good; the viewer must keep loading documents regardless. + */ +export function ReopenScreen({ + count, + source, +}: { + count: number; + source: ReopenSource; +}) { + const [resolved, setResolved] = useState(null); + const [opened, setOpened] = useState(0); + const [stalled, setStalled] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + resolveSource(source).then(setResolved, (e: Error) => setError(e.message)); + }, [source]); + + const isDone = opened >= count; + useEffect(() => { + if (resolved == null || isDone || error != null) return; + const timer = setTimeout(() => setStalled(true), STALL_MS); + return () => clearTimeout(timer); + }, [resolved, opened, isDone, error]); + + let status = `Reopening ${opened} / ${count}`; + if (isDone) status = `Reopened ${count} / ${count}`; + else if (error != null) status = `Failed at ${opened + 1}: ${error}`; + else if (stalled) status = `Stalled: open ${opened + 1} never loaded`; + + return ( + + + {status} + + {resolved != null && !isDone && !stalled && error == null && ( + setOpened((n) => n + 1)} + onError={(pdfError) => setError(pdfError.code)} + /> + )} + + ); +} + +const styles = StyleSheet.create({ + fill: { flex: 1, backgroundColor: colors.card }, + status: { + padding: 16, + fontSize: 16, + color: colors.text, + fontVariant: ['tabular-nums'], + }, + pdf: { flex: 1, backgroundColor: colors.canvas }, +}); From e0697891408bf3903d54762c50c940a031b37699 Mon Sep 17 00:00:00 2001 From: Gustavo Aires <39544919+gustavomts@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:54:20 -0300 Subject: [PATCH 3/5] fix(example): reject invalid PDF reopen counts Co-Authored-By: Claude Opus 5.5 --- example/App.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/App.tsx b/example/App.tsx index dd8c4c9..6d7138b 100644 --- a/example/App.tsx +++ b/example/App.tsx @@ -73,7 +73,7 @@ function parseReopenLink( const params = new URLSearchParams(match[1]); const count = Number(params.get('count') ?? 80); const source = params.get('source') ?? 'bundled'; - if (!(count > 0)) return null; + if (!Number.isSafeInteger(count) || count <= 0) return null; if (source !== 'bundled' && source !== 'file' && source !== 'remote') { return null; } From 3809cc75bba8667065ba273608ba3845a8d95d2d Mon Sep 17 00:00:00 2001 From: Gustavo Aires <39544919+gustavomts@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:50:38 -0300 Subject: [PATCH 4/5] test(example): drop the stress-reopen flow, reopen 150 times by default Once the Vision threads are blocked, Maestro's hierarchy snapshots take minutes, so the flow failed with and without the fix. The reopen deep link stays as a manual check, documented in CONTRIBUTING. The constrained thread limit depends on the machine (75 on a 15-core Mac), so the default count is 150 and the comments no longer name 64. The loader comment also says the serial queues only delay the stall: overcommit threads run out too. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 13 +++++++++++-- example/App.tsx | 4 ++-- example/e2e/stress-reopen.yaml | 16 ---------------- package/ios/PdfDocumentLoader.swift | 9 ++++++--- 4 files changed, 19 insertions(+), 23 deletions(-) delete mode 100644 example/e2e/stress-reopen.yaml diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 964c9ce..a218512 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,13 +46,23 @@ adb reverse tcp:8090 tcp:8090 # Android only cd example && bunx expo run:ios # or run:android ``` +`betterpdfexample://reopen?count=150` opens a document 150 times in a row and +closes each viewer right after it loads. Add `&source=file` or `&source=remote` +for a downloaded copy or a remote document instead of the bundled sample. Read +the result on screen: `Reopened 150 / 150`, or `Stalled: open N never loaded`. +On iOS 26 each viewer closed while PDFKit still analyzes its page blocks a +thread for good, and loads must go on past the process's constrained thread +limit (`sysctl kern.wq_max_constrained_threads`, 64 or more depending on the +Mac). It is not a Maestro flow: once those threads are blocked, Maestro's +hierarchy snapshots slow down enough to time out. + ## End-to-end tests (Maestro) Flows live in `example/e2e/` and run on both platforms: ```sh example/e2e/run.sh # functional flows -example/e2e/run.sh stress-open-close stress-rapid stress-reopen # stress flows +example/e2e/run.sh stress-open-close stress-rapid # stress flows ``` | Flow | Covers | @@ -63,7 +73,6 @@ example/e2e/run.sh stress-open-close stress-rapid stress-reopen # stre | `viewer-password` | `password-required` → `invalid-password` → unlock | | `stress-open-close` | 10× open/close of the 1000- and 500-page scans | | `stress-close-during-work` | documents closed while their work runs — renders in a fling, a search, a page image, a download, the outline, a form fill and export, `PdfDocument` page images — 5 rounds; watch logcat (`adb logcat -b crash`) and the iOS crash reports while it runs | -| `stress-reopen` | a document opened 80 times in a row, each viewer closed right after it loads; iOS 26 blocks a thread per viewer closed mid-analysis, and loads must go on past 64 of them. `SOURCE=file` or `SOURCE=remote` (`maestro test -e SOURCE=remote`) instead of the bundled sample | | `stress-rapid` | rapid flings, direction changes, jumps and zooms on 1000 pages | | `viewer-links` | page tap coordinates in PDF points, URL link reported (not opened), internal link followed, double tap not reported as a tap; a `/Dest` with `/Fit` and a name-tree destination, and a JavaScript action reported as a page tap (`links-all`). Run it on an Android 14 emulator without SDK extension 13 too: links there come from the library's parser alone | | `viewer-load-progress` | download progress of a remote document (fixture server throttled via `?bytesPerSecond=`) | diff --git a/example/App.tsx b/example/App.tsx index 6d7138b..cf377aa 100644 --- a/example/App.tsx +++ b/example/App.tsx @@ -62,7 +62,7 @@ function parseShowcaseLink(url: string | null): ShowcaseFeature | null { } /** - * `betterpdfexample://reopen?count=80[&source=bundled|file|remote]` opens a + * `betterpdfexample://reopen?count=150[&source=bundled|file|remote]` opens a * document `count` times in a row. */ function parseReopenLink( @@ -71,7 +71,7 @@ function parseReopenLink( const match = url == null ? null : /^[a-z]+:\/\/reopen\?(.*)$/.exec(url); if (match == null) return null; const params = new URLSearchParams(match[1]); - const count = Number(params.get('count') ?? 80); + const count = Number(params.get('count') ?? 150); const source = params.get('source') ?? 'bundled'; if (!Number.isSafeInteger(count) || count <= 0) return null; if (source !== 'bundled' && source !== 'file' && source !== 'remote') { diff --git a/example/e2e/stress-reopen.yaml b/example/e2e/stress-reopen.yaml deleted file mode 100644 index 30d3040..0000000 --- a/example/e2e/stress-reopen.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# Opens a document 80 times in a row, closing each viewer right after it -# loads. iOS 26 leaves one thread blocked for good per viewer closed while -# PDFKit still analyzes its page; past 64 of them, documents must still load. -# Debug builds load the bundled sample from Metro over HTTP (DocumentCache); -# `file` and `remote` need the fixture server. -appId: software.gmi.betterpdf.example ---- -- runFlow: _start.yaml -- openLink: betterpdfexample://reopen?count=80&source=${SOURCE || 'bundled'} -# iOS asks before a link opens the app. -- tapOn: - text: "Open" - optional: true -- extendedWaitUntil: - visible: "Reopened 80 / 80" - timeout: 180000 diff --git a/package/ios/PdfDocumentLoader.swift b/package/ios/PdfDocumentLoader.swift index e37b217..67ca8a2 100644 --- a/package/ios/PdfDocumentLoader.swift +++ b/package/ios/PdfDocumentLoader.swift @@ -11,10 +11,13 @@ import PDFKit /// when the copy is replaced or removed while displayed. final class PdfDocumentLoader { // Serial, like every queue here: GCD runs a serial queue on its overcommit - // threads. A concurrent queue shares the process's 64 constrained threads, + // threads. A concurrent queue shares the process's constrained threads + // (`kern.wq_max_constrained_threads`, 64 or more depending on the machine), // and iOS 26 PDFKit blocks one of them for good per PDFView closed while - // it analyzes a page (PDFPageAnalyzerV2 → Vision). After 64, no work on a - // concurrent queue ever starts again, so no document would load. + // it analyzes a page (PDFPageAnalyzerV2 → Vision). Once all are blocked, no + // work on a concurrent queue ever starts again, so no document would load. + // Overcommit threads run out too (`kern.wq_max_threads`), much later: this + // delays the stall, it does not remove it. private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated) /// Loads the document. `progress` (remote downloads only, throttled) and From 4069a9c462d6a19c96b4ec28167dbec9fd425337 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Fri, 6 Nov 2026 15:26:02 +0100 Subject: [PATCH 5/5] docs: tie the iOS 26 stall to overlapping page analyses, not closing The harness runs in #78 show that closing a PDFView mid-analysis is harmless on its own: threads get stuck when page analyses in different views overlap. Reword the loader comment, the ReopenScreen doc comment and CONTRIBUTING to match. --- CONTRIBUTING.md | 10 +++++----- example/screens/ReopenScreen.tsx | 7 ++++--- package/ios/PdfDocumentLoader.swift | 10 +++++----- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a218512..2985e55 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,11 +50,11 @@ cd example && bunx expo run:ios # or run:android closes each viewer right after it loads. Add `&source=file` or `&source=remote` for a downloaded copy or a remote document instead of the bundled sample. Read the result on screen: `Reopened 150 / 150`, or `Stalled: open N never loaded`. -On iOS 26 each viewer closed while PDFKit still analyzes its page blocks a -thread for good, and loads must go on past the process's constrained thread -limit (`sysctl kern.wq_max_constrained_threads`, 64 or more depending on the -Mac). It is not a Maestro flow: once those threads are blocked, Maestro's -hierarchy snapshots slow down enough to time out. +On iOS 26 PDFKit can block a thread for good when page analyses in different +viewers overlap, as they do here, and loads must go on past the process's +constrained thread limit (`sysctl kern.wq_max_constrained_threads`, 64 or more +depending on the Mac). It is not a Maestro flow: once those threads are +blocked, Maestro's hierarchy snapshots slow down enough to time out. ## End-to-end tests (Maestro) diff --git a/example/screens/ReopenScreen.tsx b/example/screens/ReopenScreen.tsx index f9bc71c..576dae1 100644 --- a/example/screens/ReopenScreen.tsx +++ b/example/screens/ReopenScreen.tsx @@ -24,9 +24,10 @@ async function resolveSource(source: ReopenSource): Promise { /** * Opens a document `count` times in a row, closing each viewer right after - * its load event, the way a list of documents is browsed quickly. On iOS 26, - * each viewer closed while PDFKit still analyzes its page leaves a thread - * blocked for good; the viewer must keep loading documents regardless. + * its load event, the way a list of documents is browsed quickly. The next + * viewer opens at once, so PDFKit's page analyses overlap, which on iOS 26 + * can leave a thread blocked for good; the viewer must keep loading + * documents regardless. */ export function ReopenScreen({ count, diff --git a/package/ios/PdfDocumentLoader.swift b/package/ios/PdfDocumentLoader.swift index 67ca8a2..f8a09c4 100644 --- a/package/ios/PdfDocumentLoader.swift +++ b/package/ios/PdfDocumentLoader.swift @@ -13,11 +13,11 @@ final class PdfDocumentLoader { // Serial, like every queue here: GCD runs a serial queue on its overcommit // threads. A concurrent queue shares the process's constrained threads // (`kern.wq_max_constrained_threads`, 64 or more depending on the machine), - // and iOS 26 PDFKit blocks one of them for good per PDFView closed while - // it analyzes a page (PDFPageAnalyzerV2 → Vision). Once all are blocked, no - // work on a concurrent queue ever starts again, so no document would load. - // Overcommit threads run out too (`kern.wq_max_threads`), much later: this - // delays the stall, it does not remove it. + // and iOS 26 PDFKit can block one of them for good whenever page analyses + // in different PDFViews overlap (PDFPageAnalyzerV2 → Vision). Once all are + // blocked, no work on a concurrent queue ever starts again, so no document + // would load. Overcommit threads run out too (`kern.wq_max_threads`), much + // later: this delays the stall, it does not remove it. private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated) /// Loads the document. `progress` (remote downloads only, throttled) and