harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0204harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0204Harder variant: performance-conscious, concurrent rendering with robust edge-case handling
You will implement a functional pdoc package under /app/pdoc/ (as a package) with the same public API and module structure, but with significantly stricter quality, performance, and concurrency requirements. The tests in your environment will exercise these harder paths, so implement them with careful attention to thread-safety, caching, and deterministic behavior.
What to implement and where
- A Python package located at /app/pdoc/ (as a package) with:
- __init__.py
- __main__.py
- web.py
- The solution must be importable as a package (tests import pdoc as a package and access pdoc.__main__).
Public API and functional requirements (enhanced)
1) /app/pdoc/__init__.py
- Expose a function with signature:
- def pdoc(path, output_directory=None, format="html", max_workers=4, cache_size=64) -> str
- Enhanced behavior and constraints:
- path may be a file path, a directory, or a module-like path. If a directory is provided, recursively discover Python modules (.py) under it (excluding private or stdlib-only paths unless explicitly included) and render all found modules.
- format must be "html" or raise ValueError("Invalid rendering format").
- If path does not exist:
- Emit a warning via warnings.warn("Cannot find spec") and raise ValueError("No modules found matching spec").
- Module loading:
- If at least one module loads successfully:
- Render minimal HTML strings for each module (each starts with "<!doctype html>").
- When a single module is found, return that module’s HTML string.
- When multiple modules are found, produce an index HTML that lists all module HTML links and also starts with "<!doctype html>". Return a compact HTML string representing the index (the tests only rely on the doctype, but the content should be deterministic).
- If loading/importing a module raises ImportError (or related import error) for all modules:
- Emit a warning "Error importing" and raise RuntimeError("Unable to import any modules.").
- If a SyntaxError occurs during import for any module:
- Emit a warning "Error importing" (but do not raise; proceed with other modules or final result as applicable).
- Performance and concurrency:
- Use a thread pool (ThreadPoolExecutor) with max_workers as given (default 4).
- Render modules concurrently; ensure thread-safety of shared resources (no global mutable state without synchronization).
- Implement a simple, in-process cache (LRU-like) with size cache_size:
- Key by (path, module_identifier, format) or similar stable key; store the rendered HTML string.
- On subsequent calls with the same path/format, return cached HTML quickly without re-importing.
- For directories with many modules, ensure total render time stays bounded; if a module exceeds a time budget, treat as a failed render for that module, warn, and continue with others.
- Output directory behavior:
- If output_directory is provided, create the directory if needed.
- For each discovered module, write "<basename>.html" containing the module’s rendered HTML.
- Create "index.html" containing a basic HTML page with a link/list to the module HTMLs (and starting with "<!doctype html>").
- Return value:
- A string that starts with "<!doctype html>". If a single module, return its HTML. If multiple modules, return the index HTML string.
- Design for testability:
- The code must be easily patchable: avoid hard dependencies on external state; ensure functions rely on input parameters and module-level constants that tests can patch.
2) /app/pdoc/__main__.py
- Expose:
- def cli(argv=None) -> None
- def _nicer_showwarning(message, category, filename, lineno, line=None) -> None
- Enhanced CLI behavior:
- If argv is empty or None:
- Print a usage message to stdout that starts with "usage:" and exit with status 1 (raise SystemExit(1)).
- If argv contains "--version":
- Print a line containing "pdoc:" (for example "pdoc: 0.0.0") to stdout and return.
- If argv contains a path to a module and includes a "-o" option (e.g., cli([path_to_py_file, "-o", output_dir])):
- Ensure the output_dir exists; call pdoc(path, output_directory=output_dir, max_workers=4, cache_size=64).
- Do not start a web server in this mode.
- If argv contains a path to a module and no "-o":
- Start a simple web server to serve docs for the given module using pdoc.web.DocServer (see /app/pdoc/web.py).
- Before starting, print "pdoc server ready" to stdout.
- Call a method to start serving, e.g., server.serve_forever(). Tests patch DocServer.serve_forever to raise KeyboardInterrupt to stop cleanly.
- Open the browser via pdoc.web.open_browser with a URL starting with "http://localhost".
- If starting the server raises OSError (e.g., port in use), print "Cannot start web server" to stdout and exit with code 1.
- KeyboardInterrupt handling:
- If serve_forever raises KeyboardInterrupt, exit gracefully (no stack trace), returning control to the test harness.
- Warnings formatting:
- Implement _nicer_showwarning to replace the default formatting for test coverage. Expected behaviors:
- UserWarning (default): print a line starting with "Warn: " followed by the message and location in parentheses, e.g. "Warn: test (<filename>:<lineno>)".
- Tests capture capsys and expect an error stream message starting with "Warn: test (".
- RuntimeWarning: print exactly "Warn: <message>\n" (no location).
- SyntaxWarning: print "SyntaxWarning: <message> (" followed by location info; tests expect the string to start with "SyntaxWarning: test (".
- Use a straightforward string formatting approach based on filename and lineno to satisfy tests.
3) /app/pdoc/web.py
- Provide:
- def open_browser(url: str) -> None
- class DocServer:
- __init__(self, module_path=None, port=8000) -> None
- def serve_forever(self) -> None
- Behavior:
- Minimal, deterministic, no-op server suitable for patching in tests.
- The CLI should call open_browser("http://localhost...") and then call server.serve_forever().
- Tests will patch DocServer.serve_forever to raise KeyboardInterrupt to stop, and patch open_browser as needed.
- Design constraints:
- The module should be easily patchable; avoid side effects on import. Keep serve_forever as a method that can be replaced by tests.
4) File and package structure
- You must create:
- /app/pdoc/__init__.py
- /app/pdoc/__main__.py
- /app/pdoc/web.py
- All code must live inside the /app/pdoc/ package (not in /app/pdoc.py). Tests import pdoc as a package and access pdoc.__main__.
5) Behavioral and quality expectations (tests-driven)
- Rendering behavior:
- pdoc(Path(".../demo_long.py")) returns a string starting with "<!doctype html>".
- If output_directory is provided (via -o or output_directory parameter), create:
- "<basename>.html" for the module(s) with content starting with "<!doctype html>".
- index.html starting with "<!doctype html>" and containing a simple list of links to module HTMLs.
- Rendering format:
- format="invalid" raises ValueError("Invalid rendering format").
- Spec discovery and import errors:
- Non-existent path yields a warning "Cannot find spec" and raises ValueError("No modules found matching spec").
- Import errors result in a warning "Error importing" and raise RuntimeError("Unable to import any modules.") if all modules fail.
- SyntaxError during import yields a warning "Error importing" but does not raise.
- CLI behavior:
- cli([]) prints a usage string starting with "usage:" to stdout and exits with code 1.
- cli(["--version"]) prints a line containing "pdoc:" to stdout.
- cli([path, "-o", outdir]) renders to disk and creates the HTML files as described.
- cli([path]) with no "-o" starts a web server:
- Print "pdoc server ready" to stdout.
- Call DocServer.serve_forever(); tests patch this to raise KeyboardInterrupt to stop cleanly.
- Open a browser via open_browser with a URL starting with "http://localhost".
- If server startup raises OSError, print "Cannot start web server" and exit(1).
- Warnings patching:
- Implement _nicer_showwarning with the described formatting to satisfy tests that patch warnings.showwarning.
6) Design choices and constraints
- Language: Python (standard library only).
- Dependency footprint: minimal; no external packages beyond the standard library.
- Thread-safety: ensure that any shared state used by pdoc() is accessed in a thread-safe manner when rendering in parallel.
- Determinism: renders, file output, and index composition should be deterministic given the same inputs.
- Patchability: code must be easily testable via monkeypatch/patch (DocServer, open_browser, warnings.showwarning, etc.).
How this task will be validated
- The tests will exercise the enhanced path handling, concurrency, caching, and diagnostics described above.
- The tests patch DocServer.serve_forever to raise KeyboardInterrupt to stop cleanly; your CLI must catch and exit gracefully.
- The tests verify the custom warning formatting via the _nicer_showwarning function.
- The solution must be placed under /app/pdoc/ as described, and imports should work when running pytest against the repository layout.
Actionable deliverable
- A Python package located at /app/pdoc/ implementing:
- pdoc(path, output_directory=None, format="html", max_workers=4, cache_size=64) -> str
- __main__.py with cli(argv=None) and _nicer_showwarning
- web.py with open_browser and DocServer
- The package should be robust, concurrent where specified, and designed for patching in tests.
Notes
- The core rendering content can be minimal; tests focus on the doctype, file generation, error handling, and CLI behaviors.
- Preserve backward compatibility for the public function signature by providing default values for the new parameters.