Skip to content

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

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

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

Conversation

@seonghobae

@seonghobae seonghobae commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Objective

Advance issue #322 with a bounded viewer-runtime race fix. A superseded PDF.js render may finish internally, but it must not append stale canvas/metadata or publish later preview/link/Ready. state after a newer viewer operation has started.

Fresh exact state — 2026-08-10

Test-first evidence

RED

Historical test-only head 45b1f9add3424228bf690b8009a92dff553c74e7 added scripts/test_viewer_render_cancellation.py while production renderPdfInline still ignored the operation abort signal. The behavioral Node harness held an old page.render().promise, aborted its operation, then resolved the old render. The required contract was zero stale canvas/metadata publication.

GREEN and clean-base proof

renderPdfInline(path, abortSignal) now checks cancellation around PDF.js loading, page acquisition, render completion, and every subsequent DOM publication boundary. poll(...) passes the operation signal and stops later preview link and terminal ready-state publication after supersession.

Clean exact output identity:

  • src/main/resources/static/assets/viewer/viewer.js: 33ec05397abf8cb90aba312219e5e7a1af7da6a5;
  • scripts/test_viewer_render_cancellation.py: 307f8a8f21c5e6e25dc32e938d8ec650dcd26773.

Scope / remaining issue contract

This slice is path-disjoint from #264 demo.js/dom-utils.js, #318 Java controller branding, #306 Office conversion, #313 HMAC readiness, and #316/#337 OpenAPI contracts. Issue #317 separately owns viewer/session authorization semantics.

Do not close issue #322 when this PR integrates. Remaining acceptance includes active RenderTask.cancel() and loading-task destruction where supported, rapid multi-generation/error-state coverage, signed-token-mode lifecycle parity, terminal status/focus ownership, and no unhandled cancellation rejection.

Merge gate

Keep this exact head unchanged. Auto-merge may complete only after live repository protection still sees all required checks passing, zero valid unresolved findings, and the counted approving review from a qualifying independent reviewer with write access. Automated evidence is not approval.

Summary by CodeRabbit

  • 버그 수정

    • PDF 미리보기 렌더링을 중단할 때 취소된 결과가 캔버스나 메타데이터에 게시되지 않도록 개선했습니다.
    • 렌더링 과정의 각 단계에서 중단 상태를 확인해 오래된 미리보기 결과가 표시되는 문제를 방지했습니다.
  • 테스트

    • PDF 렌더링 취소 및 결과 게시 방지를 검증하는 회귀 테스트를 추가했습니다.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

PDF 렌더링 취소 처리

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

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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 최신 PDF 렌더링 결과만 게시하도록 수정한 PR의 핵심 변경을 정확하고 간결하게 설명합니다.
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.
✨ 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 on lines +171 to +186
def test_superseded_pdf_render_does_not_publish() -> None:
"""Abort an in-flight render and require zero stale DOM publication."""

node = shutil.which("node")
assert node is not None, "Node.js is required for the viewer runtime regression"

result = subprocess.run(
[node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
cwd=REPOSITORY_ROOT,
capture_output=True,
check=False,
text=True,
timeout=15,
)

assert result.returncode == 0, result.stdout + result.stderr

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

unittest 스위트로 감싸야 합니다.

이 파일은 모듈 수준 pytest 스타일 함수만 정의합니다. unittest.TestCase 서브클래스가 없습니다. 따라서 python3 -m unittest discover -s scripts는 이 모듈을 임포트하지만 테스트를 0개 수집합니다. 회귀 검증이 표준 명령에서 조용히 누락됩니다.

unittest.TestCase 기반으로 변환하십시오.

코딩 가이드라인에 따릅니다: "Python helper scripts use the standard-library unittest suite and must pass python3 -m unittest discover -s scripts".

♻️ 제안 수정
+import unittest
 import shutil
 import subprocess
 from pathlib import Path
-def test_superseded_pdf_render_does_not_publish() -> None:
-    """Abort an in-flight render and require zero stale DOM publication."""
-
-    node = shutil.which("node")
-    assert node is not None, "Node.js is required for the viewer runtime regression"
-
-    result = subprocess.run(
-        [node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
-        cwd=REPOSITORY_ROOT,
-        capture_output=True,
-        check=False,
-        text=True,
-        timeout=15,
-    )
-
-    assert result.returncode == 0, result.stdout + result.stderr
+class ViewerRenderCancellationTest(unittest.TestCase):
+    def test_superseded_pdf_render_does_not_publish(self) -> None:
+        """Abort an in-flight render and require zero stale DOM publication."""
+
+        node = shutil.which("node")
+        if node is None:
+            self.skipTest("Node.js is required for the viewer runtime regression")
+
+        result = subprocess.run(
+            [node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
+            cwd=REPOSITORY_ROOT,
+            capture_output=True,
+            check=False,
+            text=True,
+            timeout=15,
+        )
+
+        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+
+if __name__ == "__main__":
+    unittest.main()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_superseded_pdf_render_does_not_publish() -> None:
"""Abort an in-flight render and require zero stale DOM publication."""
node = shutil.which("node")
assert node is not None, "Node.js is required for the viewer runtime regression"
result = subprocess.run(
[node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
cwd=REPOSITORY_ROOT,
capture_output=True,
check=False,
text=True,
timeout=15,
)
assert result.returncode == 0, result.stdout + result.stderr
import unittest
class ViewerRenderCancellationTest(unittest.TestCase):
def test_superseded_pdf_render_does_not_publish(self) -> None:
"""Abort an in-flight render and require zero stale DOM publication."""
node = shutil.which("node")
if node is None:
self.skipTest("Node.js is required for the viewer runtime regression")
result = subprocess.run(
[node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
cwd=REPOSITORY_ROOT,
capture_output=True,
check=False,
text=True,
timeout=15,
)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
🧰 Tools
🪛 ast-grep (0.45.1)

[error] 176-183: Command coming from incoming request
Context: subprocess.run(
[node, "-e", NODE_HARNESS, str(VIEWER_SOURCE)],
cwd=REPOSITORY_ROOT,
capture_output=True,
check=False,
text=True,
timeout=15,
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(subprocess-from-request)

🪛 Ruff (0.16.1)

[error] 177-177: subprocess call: check for execution of untrusted input

(S603)

🤖 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 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.

Source: Coding guidelines

@opencode-agent
opencode-agent Bot disabled auto-merge August 12, 2026 11:39
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