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

Open
#6,780 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
frontend

Research direction

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.

Written by the indexing model from the issue text.

Description

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.

Dominant language
Python
Stars
37.7k
Forks
1.5k
PR merge metrics
No merged PRs in 30d

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Textualize/textual

All issues in Textualize/textual

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.