Skip to content

fix(viewer): suppress stale PDF render publication - #323

Open
seonghobae wants to merge 10 commits into
mainfrom
fix/viewer-generation-safe-rendering
Open

fix(viewer): suppress stale PDF render publication#323
seonghobae wants to merge 10 commits into
mainfrom
fix/viewer-generation-safe-rendering

Conversation

@seonghobae

@seonghobae seonghobae commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Objective

Prevent a superseded PDF.js render from publishing stale canvas, metadata, preview links, or terminal Ready. state after a newer viewer operation starts.

Exact current-head evidence

  • protected base: eb0a32e87e7470469c8fa0f8c67d9583654bef57;
  • exact current head: 27689534a1c22ca088b4261225afb75db0009635;
  • changed paths: viewer.js and the executable Node/unittest regression only;
  • CI, Security Scan, SAST Semgrep, and fuzz: terminal-success;
  • mergeable: true;
  • all inline review threads: resolved or outdated.

Rendering contract

The runtime checks cancellation around PDF.js module loading, document loading, page acquisition, render completion, and every subsequent DOM/publication boundary. The regression is discoverable through python3 -m unittest discover -s scripts, waits for an observable render() start rather than a guessed microtask count, supersedes the operation, and proves the stale canvas, metadata, links, and terminal status cannot publish.

Scope boundary

This slice suppresses stale publication. It does not itself actively invoke RenderTask.cancel() or destroy an unresolved loading task; child #445 owns that resource-cancellation delta and must be rebuilt on protected main after this parent integrates. Issue #322 remains open for rapid multi-generation/error-state coverage, signed-token lifecycle parity, terminal focus ownership, and unhandled-rejection proof.

Merge gate

Keep this exact head unchanged. Auto-merge may act only after all live required checks remain terminal-success, zero valid unresolved findings remain, and a qualifying independent non-author approval is attached to this exact head. Automated evidence is not approval and predecessor-head evidence does not transfer.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d162e79-b4db-4924-bef3-fcb480c739dd

📥 Commits

Reviewing files that changed from the base of the PR and between 4d14ea8 and 89919e7.

📒 Files selected for processing (1)
  • scripts/test_viewer_render_cancellation.py

📝 Walkthrough

Walkthrough

PDF 인라인 렌더링이 AbortSignal을 처리하도록 변경되었습니다. 취소된 렌더링은 미리보기 DOM과 완료 상태를 갱신하지 않습니다. Node.js 기반 unittest 회귀 테스트가 이 동작을 검증합니다.

Changes

PDF 렌더링 취소 처리

Layer / File(s) Summary
viewer.js 렌더링 취소 흐름
src/main/resources/static/assets/viewer/viewer.js
renderPdfInline이 PDF 로딩, 페이지 조회, 캔버스 렌더링 후에 취소 상태를 확인합니다. 폴링 경로는 취소된 렌더링의 링크와 완료 상태를 게시하지 않습니다. 초기화는 void init()으로 실행됩니다.
취소 회귀 테스트
scripts/test_viewer_render_cancellation.py
Node.js VM에서 지연된 PDF 렌더링을 실행하고 AbortController로 취소합니다. 테스트는 결과가 false이고 미리보기 자식 요소가 없는지 확인합니다. Node.js 실행, 시간 초과 및 비정상 종료를 실패로 처리합니다.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Polling
  participant Viewer
  participant PDFjs
  participant PreviewDOM
  Polling->>Viewer: PDF 렌더링 요청 및 AbortSignal 전달
  Viewer->>PDFjs: PDF 로드, 페이지 조회, 캔버스 렌더링
  Polling->>Viewer: 렌더링 후 취소 상태 확인
  Viewer-->>Polling: false 반환
  Polling-->>PreviewDOM: 링크와 완료 상태를 게시하지 않음
Loading

Possibly related issues

  • ContextualWisdomLab/clearfolio/322: 오래된 PDF 렌더링이 캔버스, 메타데이터 또는 뷰어 상태를 게시하지 않도록 하는 변경과 직접 관련됩니다.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 오래된 PDF 렌더링 결과의 게시를 억제하는 이번 변경의 핵심 목적을 정확하고 간결하게 설명합니다.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/viewer-generation-safe-rendering

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copy link
Copy Markdown
Collaborator Author

@opencode-agent @cwl-noema-review Please independently review exact current head 79689f928d8552c65dbdecf85ed45e2e9a6f1109 against protected main 83ec6f7fe2b04bdcd28bf98ec350e41e55730a18. Exact-head CI 31374483914, Security Scan 31374483892, SAST Semgrep 31374483824, and fuzz 31374483908 are successful; no inline review thread is currently returned. Verify the bounded stale-render publication fix: superseded PDF.js work may finish internally but must not append stale canvas/metadata or publish later preview/Ready state after the operation abort signal. Review the behavioral Node regression and shipped viewer.js; keep issue #317 demo-auth authority separate. Submit a formal review only for this exact head if supported; do not mutate the branch, merge, or weaken gates.

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

Please review exact current head 79689f928d8552c65dbdecf85ed45e2e9a6f1109. Focus on whether abort-generation checks fully prevent stale PDF.js canvas/metadata/Ready publication without weakening current viewer behavior. Treat predecessor-head evidence as historical.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

head_sha="$(git rev-parse HEAD)"
base_sha="83ec6f7fe2b04bdcd28bf98ec350e41e55730a18"
expected_head="79689f928d8552c65dbdecf85ed45e2e9a6f1109"

printf 'HEAD=%s\nEXPECTED_HEAD=%s\nBASE=%s\n' "$head_sha" "$expected_head" "$base_sha"
git diff --check "${base_sha}..${expected_head}"
git diff --stat "${base_sha}..${expected_head}"
git diff --name-status "${base_sha}..${expected_head}"

printf '\n== Locate candidate files ==\n'
fd -HI '^(viewer\.js|test_viewer_render_cancellation\.py)$' . \
  -E .git -E node_modules -E dist -E build || true

printf '\n== JavaScript structure ==\n'
viewer_file="$(fd -HI '^viewer\.js$' . -E .git -E node_modules -E dist -E build | head -n 1)"
if [ -n "$viewer_file" ]; then
  ast-grep outline "$viewer_file" --items all --type function --match 'renderPdfInline|poll' --view expanded || true
  printf '\n== Relevant source occurrences ==\n'
  rg -n -C 16 -P '\b(renderPdfInline|poll)\s*\(|\.render\s*\(|appendChild\s*\(|textContent\s*=|innerHTML\s*=|ready|preview|abortSignal|aborted)\b' "$viewer_file"
fi

printf '\n== Exact source diff ==\n'
git diff --find-renames --find-copies --unified=80 "${base_sha}..${expected_head}" -- \
  ':(glob)**/viewer.js' \
  ':(glob)**/test_viewer_render_cancellation.py'

Length of output: 2440


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base_sha="83ec6f7fe2b04bdcd28bf98ec350e41e55730a18"
head_sha="79689f928d8552c65dbdecf85ed45e2e9a6f1109"
viewer="src/main/resources/static/assets/viewer/viewer.js"
test_file="scripts/test_viewer_render_cancellation.py"

printf '%s\n' '== viewer.js: imports, state, and renderPdfInline =='
sed -n '1,235p' "$viewer" | cat -n

printf '%s\n' '== viewer.js: poll and subsequent state publication =='
sed -n '236,430p' "$viewer" | cat -n

printf '%s\n' '== Regression test =='
cat -n "$test_file"

printf '%s\n' '== Exact diff =='
git diff --check "${base_sha}..${head_sha}"
git diff --unified=60 "${base_sha}..${head_sha}" -- "$viewer" "$test_file"

printf '%s\n' '== All DOM/state publication calls in viewer.js =='
rg -n -C 5 -e 'appendChild\s*\(' -e 'replaceChildren\s*\(' -e '\.textContent\s*=' \
  -e '\.innerHTML\s*=' -e 'setAttribute\s*\(' -e 'updateStatus\s*\(' \
  -e 'renderPdfInline\s*\(' -e 'await\s+' "$viewer"

Length of output: 42342


@seonghobae Reviewed exact head 79689f928d8552c65dbdecf85ed45e2e9a6f1109 against protected base 83ec6f7fe2b04bdcd28bf98ec350e41e55730a18.

No findings.

renderPdfInline(path, abortSignal) checks cancellation after each asynchronous PDF.js boundary. The check after page.render(...).promise occurs before canvas and metadata publication.

poll(docId, abortSignal) passes the operation signal to the renderer. It stops before preview-link publication after the render. It also stops before busy-state and Ready. publication.

The Node regression holds the PDF.js render promise, aborts the operation, completes the old render, and verifies zero preview children. This test covers stale canvas and metadata publication.

The change does not modify the separate signed external-artifact path or #317 demo-auth behavior.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@seonghobae
seonghobae force-pushed the fix/viewer-generation-safe-rendering branch from d7a3342 to 4ea2cce Compare August 10, 2026 12:54

Copy link
Copy Markdown
Collaborator Author

@opencode-agent @cwl-noema-review Please independently review exact current head 4ea2cce1a07462185ada525513de39c90cb9e085 against protected main 55d7ae8647208e301f282350f076eeddaba61d11. Exact-head CI 31390258726, Security Scan 31390258088, SAST 31390257890, and fuzz 31390257815 are successful. Verify superseded PDF.js work cannot append stale canvas/metadata or later preview/Ready state after abort, the behavioral Node harness exercises late render completion, and this remains only the first issue-#322 slice rather than active task cancellation/destruction or session-authority completion. Advisory review only; do not mutate, count as human approval, merge, or weaken gates.

@seonghobae
seonghobae marked this pull request as draft August 12, 2026 02:22
auto-merge was automatically disabled August 12, 2026 02:22

Pull request was converted to draft

@seonghobae
seonghobae marked this pull request as ready for review August 12, 2026 03:44
@seonghobae
seonghobae enabled auto-merge (squash) August 12, 2026 03:45

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
scripts/test_viewer_render_cancellation.py (1)

151-156: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

마이크로태스크 개수에 의존하면 검증 대상 경로가 달라집니다.

renderPdfInline은 abort 전에 getPdfJsModule(), loadingTask.promise, pdfDocument.getPage(1)을 순차로 await합니다. getPageasync 함수이므로 필요한 마이크로태스크 수가 두 번을 초과할 수 있습니다. 이 경우 abort는 Line 160의 getPage 이후 확인에서 감지됩니다. assert는 통과하지만 렌더 완료 후 게시 억제 경로(viewer.js Line 183-186)는 검증되지 않습니다.

render() 호출 시점을 관측 가능한 신호로 만들고 그 신호를 await한 후 abort하십시오. 그러면 검증 대상 경로가 결정됩니다.

♻️ 제안 수정
+  let renderStarted;
+  const renderStartedPromise = new Promise(resolve => {
+    renderStarted = resolve;
+  });
   let resolveRender;
   const renderPromise = new Promise(resolve => {
     resolveRender = resolve;
   });
   const pdfDocument = {
     numPages: 1,
     async getPage() {
       return {
         getViewport({ scale }) {
           return { width: 100 * scale, height: 200 * scale };
         },
         render() {
+          renderStarted();
           return { promise: renderPromise };
         },
       };
     },
     async destroy() {},
   };
-  // Let getDocument/getPage reach the deliberately unresolved render promise.
-  await Promise.resolve();
-  await Promise.resolve();
+  // Wait until page.render() actually starts, then supersede the operation.
+  await renderStartedPromise;
   controller.abort();
   resolveRender();
-  await rendering;
+  assert.equal(await rendering, false, "an aborted render must report failure");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/test_viewer_render_cancellation.py` around lines 151 - 156, Update
the cancellation test around renderPdfInline so it observes a signal when
render() is invoked, awaits that signal, and only then calls controller.abort()
and resolveRender(). Remove the fixed double Promise.resolve() scheduling,
ensuring the test deterministically exercises the post-render
publication-suppression path rather than relying on getDocument/getPage
microtask timing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/test_viewer_render_cancellation.py`:
- Around line 171-186: Convert the module-level
test_superseded_pdf_render_does_not_publish function into a method on a
unittest.TestCase subclass, preserving its existing Node.js harness execution
and assertions. Ensure the module imports unittest and the resulting test class
and method are discoverable by python3 -m unittest discover -s scripts.

---

Nitpick comments:
In `@scripts/test_viewer_render_cancellation.py`:
- Around line 151-156: Update the cancellation test around renderPdfInline so it
observes a signal when render() is invoked, awaits that signal, and only then
calls controller.abort() and resolveRender(). Remove the fixed double
Promise.resolve() scheduling, ensuring the test deterministically exercises the
post-render publication-suppression path rather than relying on
getDocument/getPage microtask timing.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c609e833-b01a-4e9c-a495-1ef3b4e6b369

📥 Commits

Reviewing files that changed from the base of the PR and between b66b692 and 4d14ea8.

📒 Files selected for processing (2)
  • scripts/test_viewer_render_cancellation.py
  • src/main/resources/static/assets/viewer/viewer.js

Comment thread scripts/test_viewer_render_cancellation.py Outdated
@opencode-agent
opencode-agent Bot disabled auto-merge August 12, 2026 11:39
@seonghobae
seonghobae enabled auto-merge (squash) August 12, 2026 19:29

Copy link
Copy Markdown
Collaborator Author

Exact-current-head read-only review request for 75e49391ddc13de378b8572d444bf02d686ef84c on protected main 961f44a19c4ced87f8062b3ab9842a9a08d05235. CI, Security Scan, SAST Semgrep, and fuzz are terminal-success; the two-file runtime/test delta is mergeable and all inline threads are resolved/outdated. Verify deterministic post-render abort synchronization, stale DOM/status suppression, unittest discovery, and absence of unhandled cancellation publication. Do not mutate the branch or bypass independent approval.

@opencode-agent review
@cwl-noema-review review
@strix review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown

Rate Limit Exceeded

@seonghobae have exceeded the limit for the number of chat messages per hour. Please wait 6 minutes and 34 seconds before sending another message.

Copy link
Copy Markdown
Collaborator Author

@opencode-agent review
@coderabbitai review
@cwl-noema-review review
@strix review

Review exact head 27689534a1c22ca088b4261225afb75db0009635 over protected base eb0a32e87e7470469c8fa0f8c67d9583654bef57 only. Current-head CI, Security Scan, SAST Semgrep, and fuzz are terminal-success; prior inline findings are resolved/outdated. Verify stale-publication suppression after supersession without conflating this bounded slice with active PDF.js resource destruction in child #445.

Review read-only; preserve independent reviewer identity. Do not mutate the branch, synthesize author approval, weaken protection, or merge.

@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

base_sha="eb0a32e87e7470469c8fa0f8c67d9583654bef57"
head_sha="27689534a1c22ca088b4261225afb75db0009635"

printf 'checked_out_head=%s\nrequested_head=%s\nrequested_base=%s\n' \
  "$(git rev-parse HEAD)" "$head_sha" "$base_sha"
git cat-file -e "${base_sha}^{commit}"
git cat-file -e "${head_sha}^{commit}"

printf '\n== Range integrity ==\n'
git merge-base --is-ancestor "$base_sha" "$head_sha"
git diff --check "${base_sha}..${head_sha}"
git diff --stat "${base_sha}..${head_sha}"
git diff --name-status "${base_sha}..${head_sha}"

printf '\n== Changed paths ==\n'
git diff --name-only "${base_sha}..${head_sha}"

printf '\n== Viewer structure ==\n'
viewer="$(fd -HI '^viewer\.js$' . -E .git -E node_modules -E dist -E build | head -n 1)"
printf 'viewer=%s\n' "$viewer"
ast-grep outline "$viewer" --items all --type function --match 'renderPdfInline|poll|start|init' --view expanded || true

printf '\n== Viewer publication and cancellation contexts ==\n'
rg -n -C 18 -P '\b(renderPdfInline|poll)\s*\(|await\s+|abortSignal|\.aborted|\.render\s*\(|appendChild\s*\(|replaceChildren\s*\(|textContent\s*=|innerHTML\s*=|updateStatus\s*\(' "$viewer"

printf '\n== Regression test candidates and test configuration ==\n'
fd -HI '^test_viewer_render_cancellation\.py$|^(pyproject\.toml|pytest\.ini|setup\.cfg|tox\.ini)$' . \
  -E .git -E node_modules -E dist -E build \
  -x sh -c 'echo "== $1 =="; cat -n "$1"' sh {}

printf '\n== Exact diff ==\n'
git diff --find-renames --find-copies --unified=100 "${base_sha}..${head_sha}" -- \
  ':(glob)**/viewer.js' \
  ':(glob)**/test_viewer_render_cancellation.py' \
  ':(glob)**/pyproject.toml' \
  ':(glob)**/pytest.ini' \
  ':(glob)**/setup.cfg' \
  ':(glob)**/tox.ini'

Length of output: 36206


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== Tracked automation and project files that can configure or invoke Python tests =='
fd -HI -t f . \
  -E .git -E node_modules -E dist -E build \
  | rg '(^|/)(\.github/workflows/[^/]+|Makefile|README\.md|pyproject\.toml|pytest\.ini|setup\.cfg|tox\.ini|.*\.(ya?ml|json|sh))$' \
  | while IFS= read -r file; do
      if rg -n -i -C 3 \
        -e 'python[0-9.]*\s+-m\s+unittest' \
        -e 'unittest\s+discover' \
        -e 'test_viewer_render_cancellation' \
        -e 'scripts/test_.*\.py' \
        -e 'pytest' \
        "$file"; then
        printf '\n== %s ==\n' "$file"
        rg -n -i -C 3 \
          -e 'python[0-9.]*\s+-m\s+unittest' \
          -e 'unittest\s+discover' \
          -e 'test_viewer_render_cancellation' \
          -e 'scripts/test_.*\.py' \
          -e 'pytest' \
          "$file"
      fi
    done

printf '%s\n' '== All tracked test modules under scripts =='
fd -HI -t f '^test_.*\.py$' scripts 2>/dev/null | sort

printf '%s\n' '== Repository-wide static references to the new test module =='
rg -n -C 3 -P '\btest_viewer_render_cancellation\b|python[0-9.]*\s+-m\s+unittest|unittest\s+discover' \
  -g '!**/node_modules/**' -g '!**/dist/**' -g '!**/build/**' .

Length of output: 7383


@seonghobae Reviewed exact head 27689534a1c22ca088b4261225afb75db0009635 against protected base eb0a32e87e7470469c8fa0f8c67d9583654bef57.

No findings.

renderPdfInline(path, abortSignal) checks the abort signal after each asynchronous PDF.js boundary. The post-render check occurs before canvas and metadata publication.

poll(docId, abortSignal) passes the operation signal to renderPdfInline. It returns after a superseded render and before preview-link publication. It also checks the signal before terminal aria-busy and Ready. publication.

The Node regression waits until page.render() starts. It aborts the signal, resolves the late render, and verifies that renderPdfInline returns false with zero preview children. CI collects this test through python -m pytest -q scripts in .github/workflows/ci.yml.

This range does not add active PDF.js render-task cancellation or loading-task destruction. That work remains outside this bounded slice and separate from child issue #445.

⚠️ Action not completed

No files to review.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Collaborator Author

Exact-current-head independent review request for 27689534a1c22ca088b4261225afb75db0009635 over protected main eb0a32e87e7470469c8fa0f8c67d9583654bef57.

CI, Security Scan, SAST Semgrep, and fuzz are terminal-success; every inline finding is resolved or outdated. The deterministic unittest/Node regression now observes actual render start and proves stale publication suppression.

@opencode-agent review
@coderabbitai review
@cwl-noema-review review
@strix review

Review this exact head read-only. Do not mutate the branch, synthesize author approval, weaken protection, or merge.

@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown

Rate Limit Exceeded

@seonghobae have exceeded the limit for the number of chat messages per hour. Please wait 24 minutes and 6 seconds before sending another message.

Copy link
Copy Markdown
Collaborator Author

Exact-current-head independent review request for 27689534a1c22ca088b4261225afb75db0009635 over protected main eb0a32e87e7470469c8fa0f8c67d9583654bef57.

Freshly rechecked: CI, Security Scan, SAST Semgrep, and fuzz are terminal-success; mergeable is true; every inline review thread is resolved or outdated. Review this exact head only. Do not mutate the branch, synthesize author approval, or bypass protection.

@coderabbitai review
@opencode-agent review
@cwl-noema-review review
@strix review

@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown

Rate Limit Exceeded

@seonghobae have exceeded the limit for the number of chat messages per hour. Please wait 27 minutes and 33 seconds before sending another message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant