MarkdownViewer: a failed or superseded `go()` leaves the history out of step with the document shown

オープン
#6,780 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
3/5
見積もり時間
1〜2日
初心者へのやさしさ
72/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python
領域
frontend

調査の方向性

Read the implementations of MarkdownViewer.go() and Markdown.load(), then find the existing MarkdownViewer tests. Start by adding regression tests for a failed load and for two overlapping go() calls; the issue includes runnable reproductions for both. Done means failed or superseded loads leave the displayed document and navigation history consistent.

索引モデルが issue の本文から書いたものです。

説明

Hi! I hit this while writing generated tests against Textual's widgets.

MarkdownViewer.go() pushes the new location onto its Navigator first and then awaits Markdown.load(). Two things follow from that order.

1. A document that fails to load stays in the history. Markdown.load documents that it raises OSError, so an app may catch it. But by then the missing path is the current location, and back() from a later document goes to it and raises again.

import asyncio
import os
import tempfile
from pathlib import Path

import textual
from textual.app import App, ComposeResult
from textual.widgets import MarkdownViewer

class ViewerApp(App):
    def compose(self) -> ComposeResult:
        yield MarkdownViewer()

async def main() -> None:
    os.chdir(tempfile.mkdtemp())
    Path("a.md").write_text("# A doc\n")
    Path("b.md").write_text("# B doc\n")
    app = ViewerApp()
    async with app.run_test() as pilot:
        viewer = app.query_one(MarkdownViewer)
        await viewer.go("a.md")
        try:
            await viewer.go("missing.md")
        except OSError as error:
            print("go(missing.md) raised", type(error).__name__)
        await pilot.pause()
        print("location:", viewer.navigator.location.name)
        print("history: ", [path.name for path in viewer.navigator.stack])
        await viewer.go("b.md")
        try:
            await viewer.back()
        except OSError as error:
            print("back() raised", type(error).__name__)
        print("after back, location:", viewer.navigator.location.name)

print("Textual", textual.__version__)
asyncio.run(main())
Textual 8.2.7
go(missing.md) raised FileNotFoundError
location: missing.md
history:  ['a.md', 'missing.md']
back() raised FileNotFoundError
after back, location: missing.md

I'd expect location: a.md and history: ['a.md'] after the failed go, and back() to return to a.md.

2. Two go() calls in a row aren't ordered. Each pushes its path and then awaits a read in a thread, so whichever read finishes last decides what's shown, while the navigator ends at whichever was called last. This repro starts go("b.md"), then awaits go("a.md") (like clicking one link, then another before the first has loaded). With a slow read for b.md it always disagrees; with no delay at all, it depends on thread timing:

import asyncio
import os
import sys
import tempfile
import time
from pathlib import Path

import textual
from textual.app import App, ComposeResult
from textual.widgets import MarkdownViewer

SLOW = "--no-delay" not in sys.argv
RUNS = int(sys.argv[sys.argv.index("--runs") + 1]) if "--runs" in sys.argv else 1

read_text = Path.read_text

def slow_read_text(self: Path, *args, **kwargs) -> str:
    # Simulate a slow disk (or network file system) for b.md only.
    if SLOW and self.name == "b.md":
        time.sleep(0.2)
    return read_text(self, *args, **kwargs)

Path.read_text = slow_read_text

class ViewerApp(App):
    def compose(self) -> ComposeResult:
        yield MarkdownViewer()

async def main() -> tuple[str, str]:
    app = ViewerApp()
    async with app.run_test() as pilot:
        viewer = app.query_one(MarkdownViewer)
        # The user clicks a link to b.md, then (before it has loaded) a link to a.md.
        first = asyncio.create_task(viewer.go("b.md"))
        await asyncio.sleep(0)  # let it start
        await viewer.go("a.md")
        await first
        await pilot.pause()
        return viewer.navigator.location.name, viewer.document.source.strip()

os.chdir(tempfile.mkdtemp())
Path("a.md").write_text("# A doc\n")
Path("b.md").write_text("# B doc\n")
print("Textual", textual.__version__, "slow b.md" if SLOW else "no delay")
results: dict[tuple[str, str], int] = {}
for _ in range(RUNS):
    result = asyncio.run(main())
    results[result] = results.get(result, 0) + 1
for (location, shown), count in sorted(results.items()):
    print(f"location={location} shows={shown!r}: {count} of {RUNS}")
Textual 8.2.7 slow b.md
location=a.md shows='# B doc': 1 of 1
Textual 8.2.7 no delay
location=a.md shows='# A doc': 125 of 200
location=a.md shows='# B doc': 75 of 200

On main at 5e5b7ef:

Textual 8.2.8 slow b.md
location=a.md shows='# B doc': 1 of 1
Textual 8.2.8 no delay
location=a.md shows='# A doc': 100 of 200
location=a.md shows='# B doc': 100 of 200

In the B doc cases the viewer shows b.md while its location is a.md, so back() and the next relative link both work from the wrong document.

I think both are fixed by adding a location to the history only once its document has loaded, and by having Markdown.load drop a read that a later load call has superseded. I'm happy to send a PR.

主要言語
Python
スター
37.7k
フォーク
1.5k
PR マージ指標
30日以内にマージされた PR はありません

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

Textualize/textual のほかの issue

Textualize/textual の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。