Skip to content

Commit 9b92f07

Browse files
committed
chore(showcase): take Go and Rust hover shots, and stop only the daemons this run started
Add code-intelligence-go-hover (strings.Split in a seeded Go attempt of group-anagrams, with its links to SplitN and Cut) and code-intelligence-rust-hover (Vec in a seeded Rust attempt of product-except-self). The settings shot waits for gopls and rust-analyzer too, and each hover shot waits for its own server to stop, found below cstudy serve, so two never run at once. stop_gradle stopped every Gradle daemon that appeared while the script ran, whoever started it, so another build on the same machine could lose its daemon. A watcher now notes the Gradle and Kotlin daemons below the script's own process every half second, since a daemon belongs to the build that started it until that build ends, and stops only those, by PID and only while each still runs the command it was noted with.
1 parent 65205a9 commit 9b92f07

2 files changed

Lines changed: 163 additions & 18 deletions

File tree

‎tools/showcase/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ A run takes several minutes and runs one Chromium, `cstudy serve` and the langua
3030

3131
`--shots` takes some of the screenshots of the `shots` stage, by name, such as `--shots web-ui-attempt,web-ui-settings`; a shot left out does not open its view, so leaving out `web-ui-health` starts no Gradle. `--variants` takes the screenshots in some themes and widths only, such as `--variants light-phone`: on a machine short of memory, one variant per run starts one Chromium and one Java language server at a time, and frees them in between. `--video-theme dark` records the animations in the dark theme.
3232

33-
When it ends, stop what it may have left: `ps -Ao pid,ppid,etime,command | rg -i "basedpyright|typescript-language-server|jdtls|uvicorn|cstudy serve|ms-playwright|GradleDaemon"`. The script stops the server and the browser, and the Gradle daemons that started while it ran (`cstudy doctor --fix` and the Health view start them). A daemon that was already running stays, and so may be shared with other work: check its builds before you kill it, by PID.
33+
When it ends, stop what it may have left: `ps -Ao pid,ppid,etime,command | rg -i "basedpyright|typescript-language-server|jdtls|gopls|rust-analyzer|uvicorn|cstudy serve|ms-playwright|GradleDaemon|KotlinCompileDaemon"`. The script stops the server and the browser, and the Gradle and Kotlin daemons that its own processes started (`cstudy doctor --fix`, the Health view and JDT LS start them): it looks at the processes below it every half second while it runs, notes the daemons it finds there, and stops those by PID at the end. A daemon that was running before, or that other work on this machine starts meanwhile, is never below the script, so it stays.
3434

3535
## What it makes
3636

@@ -42,6 +42,8 @@ Desktop images are 1440 by 900, the phone ones 390 wide at 2x. A name is `<name>
4242
| `code-intelligence-error` | An undefined name underlined, with its message |
4343
| `autocomplete-list` | The completion list with its documentation panel |
4444
| `code-intelligence-java-hover` | The Javadoc tooltip on `getOrDefault` in top-k-frequent-elements (Java), from Eclipse JDT LS; the seed stage starts that attempt |
45+
| `code-intelligence-go-hover` | The documentation of `strings.Split` in group-anagrams (Go), from gopls, with its links to `SplitN` and `Cut`; the seed stage starts that attempt |
46+
| `code-intelligence-rust-hover` | The documentation of `Vec` in product-except-self (Rust), from rust-analyzer and the toolchain's standard library; the seed stage starts that attempt |
4547
| `web-ui-problems` | The problem list |
4648
| `web-ui-attempt` | A project attempt with the file tree, the editor, a run's results and the statement |
4749
| `web-ui-project` | The same attempt with several file tabs open |
@@ -68,4 +70,5 @@ Recording uses Playwright's `record_video_dir` with a small injected pointer, si
6870
- The script writes files only into `--work` and `--out`. Nothing it makes is committed for you.
6971
- It needs the language servers, so it runs `cstudy doctor --fix` with the network. After that it works offline.
7072
- A new language server needs a new feature shot, as Java's has, and a scene in `code_intelligence_scene` if the animation should show it. The health shot picks up new rows by itself; the settings shot also waits for each server's line, so a JDK outside 25 and 26 stops it instead of showing Java's `needs JDK 25 or 26`.
71-
- JDT LS says ready before its first Gradle import ends, so the Java shot hovers again until the Javadoc shows, for up to three minutes, and waits for the server to stop before the next variant, so that two never run at once.
73+
- JDT LS says ready before its first Gradle import ends, so the Java shot hovers again until the Javadoc shows, for up to three minutes. The Go and Rust shots hover the same way. Each of the three waits for its server to stop before the next shot, so that two never run at once.
74+
- The Go and Rust shots need gopls, which `cstudy doctor --fix` builds with the selected Go, and rust-analyzer on `PATH` (`rustup component add rust-analyzer`), which the script never installs. The settings shot waits for both lines.

‎tools/showcase/showcase.py‎

Lines changed: 158 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import signal
2424
import subprocess
2525
import sys
26+
import threading
2627
import time
2728
from collections.abc import Callable, Iterator
2829
from dataclasses import dataclass
@@ -42,6 +43,8 @@
4243
"code-intelligence-error",
4344
"autocomplete-list",
4445
"code-intelligence-java-hover",
46+
"code-intelligence-go-hover",
47+
"code-intelligence-rust-hover",
4548
"web-ui-problems",
4649
"web-ui-attempt",
4750
"web-ui-project",
@@ -103,6 +106,43 @@
103106
}
104107
"""
105108
JAVA_SLUG = "top-k-frequent-elements"
109+
GROUP_ANAGRAMS_GO = """import (
110+
"slices"
111+
"strings"
112+
)
113+
114+
func groupAnagrams(strs []string) [][]string {
115+
groups := map[string][]string{}
116+
for _, word := range strs {
117+
letters := strings.Split(word, "")
118+
slices.Sort(letters)
119+
key := strings.Join(letters, "")
120+
groups[key] = append(groups[key], word)
121+
}
122+
answer := make([][]string, 0, len(groups))
123+
for _, group := range groups {
124+
answer = append(answer, group)
125+
}
126+
return answer
127+
}
128+
"""
129+
GO_SLUG = "group-anagrams"
130+
PRODUCT_RUST = """pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
131+
let mut answer = vec![1; nums.len()];
132+
let mut prefix = 1;
133+
for i in 0..nums.len() {
134+
answer[i] = prefix;
135+
prefix *= nums[i];
136+
}
137+
let mut suffix = 1;
138+
for i in (0..nums.len()).rev() {
139+
answer[i] *= suffix;
140+
suffix *= nums[i];
141+
}
142+
answer
143+
}
144+
"""
145+
RUST_SLUG = "product-except-self"
106146
TWO_SUM_WITH_TYPO = TWO_SUM.replace("high = 0, len(nums) - 1", "high = 0, len(num) - 1")
107147
TWO_SUM_WITH_ROOM = TWO_SUM + "\n\n"
108148
MOVE_ZEROES = (
@@ -208,11 +248,70 @@ def run(command: list[str | Path], cwd: Path | None = None, env: dict[str, str]
208248
return done
209249

210250

211-
def gradle_daemons() -> set[int]:
212-
listing = run(["ps", "-Ao", "pid,command"], check=False).stdout
213-
return {
214-
int(line.split()[0]) for line in listing.splitlines() if "GradleDaemon" in line
215-
}
251+
DAEMONS = ("GradleDaemon", "KotlinCompileDaemon")
252+
"""What a Gradle build may leave running after it ends: its daemon, and Kotlin's compile daemon."""
253+
254+
255+
def processes() -> dict[int, tuple[int, str]]:
256+
"""Every process, as its parent's PID and its command."""
257+
listing = run(["ps", "-Aww", "-o", "pid=,ppid=,command="], check=False).stdout
258+
table: dict[int, tuple[int, str]] = {}
259+
for line in listing.splitlines():
260+
parts = line.split(None, 2)
261+
if len(parts) == 3:
262+
table[int(parts[0])] = (int(parts[1]), parts[2])
263+
return table
264+
265+
266+
def descendants(root: int, table: dict[int, tuple[int, str]]) -> dict[int, str]:
267+
"""The processes below `root`, by PID, with their commands."""
268+
children: dict[int, list[int]] = {}
269+
for pid, (parent, _command) in table.items():
270+
children.setdefault(parent, []).append(pid)
271+
found: dict[int, str] = {}
272+
waiting = [root]
273+
while waiting:
274+
for child in children.get(waiting.pop(), []):
275+
found[child] = table[child][1]
276+
waiting.append(child)
277+
return found
278+
279+
280+
class DaemonWatch:
281+
"""Notes the Gradle and Kotlin daemons that this script's own processes start, so that only
282+
those are stopped. A daemon runs below the build that started it until that build ends, then
283+
belongs to no one, so a look every half second while the script runs finds it. A daemon that
284+
was running before, or that other work starts meanwhile, is never below this script, and
285+
stays."""
286+
287+
def __init__(self) -> None:
288+
self.started: dict[int, str] = {}
289+
self.done = threading.Event()
290+
self.thread = threading.Thread(target=self.watch, daemon=True)
291+
self.thread.start()
292+
293+
def watch(self) -> None:
294+
while not self.done.wait(0.5):
295+
self.look()
296+
297+
def look(self) -> None:
298+
for pid, command in descendants(os.getpid(), processes()).items():
299+
if any(name in command for name in DAEMONS):
300+
self.started[pid] = command
301+
302+
def stop(self) -> None:
303+
"""Stops the noted daemons by PID, each only while it still runs the command it ran when
304+
it was noted, so a PID reused since is left alone."""
305+
self.done.set()
306+
self.thread.join()
307+
self.look()
308+
table = processes()
309+
for pid, command in self.started.items():
310+
if pid in table and table[pid][1] == command:
311+
with contextlib.suppress(ProcessLookupError):
312+
os.kill(pid, signal.SIGTERM)
313+
name = next(name for name in DAEMONS if name in command)
314+
say(f"stopped {name} {pid}, started by this run")
216315

217316

218317
class Showcase:
@@ -227,7 +326,8 @@ def __init__(self, work: Path, out: Path, shots: tuple[str, ...] = SHOTS) -> Non
227326
self.toolbin = self.work / "toolbin"
228327
self.clips = self.work / "clips"
229328
self.cstudy = self.venv / "bin" / "cstudy"
230-
self.daemons_before = gradle_daemons()
329+
self.daemons = DaemonWatch()
330+
self.server_pid = 0
231331
self.base = ""
232332
self.token_url = ""
233333
self.attempts: dict[str, str] = {}
@@ -295,6 +395,10 @@ def seed(self) -> None:
295395
self.cs("start", "move-zeroes", "--lang", "python", "--no-open")
296396
self.cs("start", JAVA_SLUG, "--lang", "java", "--no-open")
297397
self.write_java_stub(JAVA_SLUG, TOP_K_JAVA)
398+
self.cs("start", GO_SLUG, "--lang", "go", "--no-open")
399+
self.write_code_after(self.go_stub(GO_SLUG), "\nfunc ", GROUP_ANAGRAMS_GO)
400+
self.cs("start", RUST_SLUG, "--lang", "rust", "--no-open")
401+
self.write_code_after(self.rust_stub(RUST_SLUG), "\npub fn ", PRODUCT_RUST)
298402
self.cs("start", "bank-project-python", "--no-open")
299403
project = self.workspace / "projects" / "bank-project-python"
300404
(project / "bank" / "ledger.py").write_text(LEDGER)
@@ -323,6 +427,20 @@ def write_java_stub(self, slug: str, code: str) -> None:
323427
text = self.java_stub(slug).read_text()
324428
self.java_stub(slug).write_text(text[: text.index("\npublic class ") + 1] + code)
325429

430+
def go_stub(self, slug: str) -> Path:
431+
name = slug.replace("-", "_")
432+
return self.workspace / "go" / "practice" / name / f"{name}.go"
433+
434+
def rust_stub(self, slug: str) -> Path:
435+
return self.workspace / "rust" / "practice" / f"{slug.replace('-', '_')}.rs"
436+
437+
@staticmethod
438+
def write_code_after(path: Path, start: str, code: str) -> None:
439+
"""Replaces the stub's code from the line that begins with `start`, and keeps the header
440+
and the package line `cstudy start` wrote above it."""
441+
text = path.read_text()
442+
path.write_text(text[: text.index(start) + 1] + code)
443+
326444
def wants(self, name: str) -> bool:
327445
return name in self.shots
328446

@@ -338,6 +456,7 @@ def serving(self) -> Iterator[None]:
338456
[self.cstudy, "serve", "--port", "0"], cwd=self.workspace, env=self.environment(),
339457
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
340458
)
459+
self.server_pid = server.pid
341460
try:
342461
assert server.stdout is not None
343462
for line in server.stdout:
@@ -357,21 +476,20 @@ def serving(self) -> Iterator[None]:
357476
server.kill()
358477
server.wait()
359478

360-
def wait_for_jdtls_to_stop(self) -> None:
361-
"""Waits, up to 30 s, until no JDT LS of this workspace runs, so that the next session
362-
reuses its data directory and two never run at once."""
363-
marker = str(self.workspace / ".cs" / "lsp" / "jdtls")
479+
def wait_for_server_to_stop(self, name: str) -> None:
480+
"""Waits, up to 30 s, until no process of the server's runs `name` (a language server, or
481+
what it started, such as rust-analyzer's `cargo check`), so that two servers never run at
482+
once and JDT LS's next session reuses its data directory."""
364483
deadline = time.monotonic() + 30
365484
while time.monotonic() < deadline:
366-
if marker not in run(["ps", "-Aww", "-o", "command"], check=False).stdout:
485+
below = descendants(self.server_pid, processes()).values()
486+
if not any(name in command for command in below):
367487
return
368488
time.sleep(0.5)
369489

370490
def stop_gradle(self) -> None:
371-
"""Stops the Gradle daemons that appeared while this script ran, by PID."""
372-
for pid in gradle_daemons() - self.daemons_before:
373-
with contextlib.suppress(ProcessLookupError):
374-
os.kill(pid, signal.SIGTERM)
491+
"""Stops the Gradle and Kotlin daemons that this script's processes started, by PID."""
492+
self.daemons.stop()
375493

376494
# Browser helpers -----------------------------------------------------------------------
377495

@@ -670,7 +788,29 @@ def feature_shots(app: Showcase, context: BrowserContext, variant: Variant) -> N
670788
page.wait_for_timeout(400)
671789
app.screenshot(page, "code-intelligence-java-hover", variant)
672790
page.close()
673-
app.wait_for_jdtls_to_stop()
791+
app.wait_for_server_to_stop("jdtls")
792+
793+
if app.wants("code-intelligence-go-hover"):
794+
page = app.attempt(context, GO_SLUG)
795+
open_file(page, "group_anagrams.go")
796+
wait_ready(page, "gopls")
797+
pointer = Pointer(page)
798+
hover_until(page, pointer, "strings.Split", "Split", "Split slices s into all substrings")
799+
page.wait_for_timeout(400)
800+
app.screenshot(page, "code-intelligence-go-hover", variant)
801+
page.close()
802+
app.wait_for_server_to_stop("gopls")
803+
804+
if app.wants("code-intelligence-rust-hover"):
805+
page = app.attempt(context, RUST_SLUG)
806+
open_file(page, "product_except_self.rs")
807+
wait_ready(page, "rust-analyzer")
808+
pointer = Pointer(page)
809+
hover_until(page, pointer, "nums: Vec<i32>", "Vec", "A contiguous growable array type")
810+
page.wait_for_timeout(400)
811+
app.screenshot(page, "code-intelligence-rust-hover", variant)
812+
page.close()
813+
app.wait_for_server_to_stop("rust-analyzer")
674814

675815

676816
def app_shots(app: Showcase, context: BrowserContext, variant: Variant) -> None:
@@ -737,6 +877,8 @@ def app_shots(app: Showcase, context: BrowserContext, variant: Variant) -> None:
737877
page.wait_for_selector("text=basedpyright 1.")
738878
page.wait_for_selector("text=typescript-language-server")
739879
page.wait_for_selector("text=jdtls 1.")
880+
page.wait_for_selector("text=gopls 0.")
881+
page.wait_for_selector("text=rust-analyzer 1.")
740882
page.wait_for_timeout(300)
741883
app.screenshot(page, "web-ui-settings", variant, redact=True)
742884
page.close()

0 commit comments

Comments
 (0)