Skip to content

Commit b45bdb7

Browse files
author
Christian Tabedzki
committed
feat: update BrainCogsEphysSorters before queuing ephys jobs, warn in Slack if it can't
Nothing updated the sorter checkout the slurm jobs run from. Before each ephys job is queued, fast-forward it on the cluster (ssh as the cluster user, from the public https URL so no GitHub key is needed) and update its submodules (Kilosort3, npy-matlab). Done once per cron run per checkout. If the pull fails (read-only mount, local commits, no network), post a warning to the automation error Slack channel and queue the job anyway on the code already checked out. The u19ha/u19proc mount of the checkout is read-only CIFS, so the update must run on the cluster side, where it is read-write NFS owned by u19prod. Assisted-by: ClaudeCode:claude-opus-5-5
1 parent 0c517f7 commit b45bdb7

5 files changed

Lines changed: 294 additions & 5 deletions

File tree

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
"""Tests for updating the processing repository (BrainCogsEphysSorters) before queuing a job.
2+
3+
The checkout lives on the cluster and is pulled there (fast-forward only) before each
4+
job is queued. If it can't be pulled (read-only mount, local commits, no network) the
5+
job still runs, and the reason is reported so a Slack warning can be sent.
6+
"""
7+
8+
import os
9+
import shlex
10+
import shutil
11+
import stat
12+
import subprocess
13+
14+
import pytest
15+
16+
from u19_pipeline.utils.slurm_utils import (
17+
repository_update_warning,
18+
update_repository,
19+
update_repository_command,
20+
)
21+
22+
pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git not found")
23+
24+
25+
def git(cwd, *args):
26+
return subprocess.run(
27+
["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True
28+
).stdout.strip()
29+
30+
31+
def commit(repo, name):
32+
(repo / name).write_text(name)
33+
git(repo, "add", name)
34+
git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", name)
35+
return git(repo, "rev-parse", "--short", "HEAD")
36+
37+
38+
@pytest.fixture
39+
def upstream_and_checkout(tmp_path):
40+
upstream = tmp_path / "upstream"
41+
upstream.mkdir()
42+
git(upstream, "init", "-q", "-b", "main")
43+
commit(upstream, "first")
44+
checkout = tmp_path / "checkout"
45+
subprocess.run(
46+
["git", "clone", "-q", str(upstream), str(checkout)],
47+
check=True,
48+
capture_output=True,
49+
)
50+
return upstream, checkout
51+
52+
53+
def test_fast_forwards_to_the_latest_commit(upstream_and_checkout):
54+
upstream, checkout = upstream_and_checkout
55+
latest = commit(upstream, "second")
56+
57+
updated, message = update_repository(str(checkout), upstream.as_uri())
58+
59+
assert updated
60+
assert message == latest
61+
assert git(checkout, "rev-parse", "--short", "HEAD") == latest
62+
63+
64+
def test_up_to_date_checkout_is_updated(upstream_and_checkout):
65+
upstream, checkout = upstream_and_checkout
66+
67+
updated, message = update_repository(str(checkout), upstream.as_uri())
68+
69+
assert updated
70+
assert message == git(upstream, "rev-parse", "--short", "HEAD")
71+
72+
73+
def test_submodule_moves_to_the_pinned_commit(
74+
upstream_and_checkout, tmp_path, monkeypatch
75+
):
76+
upstream, checkout = upstream_and_checkout
77+
# Local file:// submodules are blocked by default in recent git
78+
monkeypatch.setenv("GIT_CONFIG_COUNT", "1")
79+
monkeypatch.setenv("GIT_CONFIG_KEY_0", "protocol.file.allow")
80+
monkeypatch.setenv("GIT_CONFIG_VALUE_0", "always")
81+
sorter = tmp_path / "sorter"
82+
sorter.mkdir()
83+
git(sorter, "init", "-q", "-b", "main")
84+
commit(sorter, "v1")
85+
git(upstream, "submodule", "add", "-q", sorter.as_uri(), "sorters/sorter")
86+
git(upstream, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add")
87+
assert update_repository(str(checkout), upstream.as_uri())[0]
88+
89+
v2 = commit(sorter, "v2")
90+
git(upstream / "sorters" / "sorter", "pull", "-q", "origin", "main")
91+
git(upstream, "add", "sorters/sorter")
92+
git(upstream, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "bump")
93+
94+
updated, message = update_repository(str(checkout), upstream.as_uri())
95+
96+
assert updated, message
97+
assert git(checkout / "sorters" / "sorter", "rev-parse", "--short", "HEAD") == v2
98+
99+
100+
@pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")
101+
def test_read_only_checkout_is_reported(upstream_and_checkout):
102+
upstream, checkout = upstream_and_checkout
103+
commit(upstream, "second")
104+
git_dir = checkout / ".git"
105+
modes = {p: p.stat().st_mode for p in [git_dir, *git_dir.rglob("*")] if p.is_dir()}
106+
for p in modes:
107+
p.chmod(stat.S_IRUSR | stat.S_IXUSR)
108+
try:
109+
updated, message = update_repository(str(checkout), upstream.as_uri())
110+
finally:
111+
for p, mode in modes.items():
112+
p.chmod(mode)
113+
114+
assert not updated
115+
assert message
116+
117+
118+
def test_diverged_checkout_is_not_merged(upstream_and_checkout):
119+
upstream, checkout = upstream_and_checkout
120+
commit(upstream, "second")
121+
local = commit(checkout, "local_change")
122+
123+
updated, message = update_repository(str(checkout), upstream.as_uri())
124+
125+
assert not updated
126+
assert message
127+
assert git(checkout, "rev-parse", "--short", "HEAD") == local
128+
129+
130+
def test_missing_checkout_is_reported(tmp_path):
131+
updated, message = update_repository(str(tmp_path / "nope"), "https://x/y.git")
132+
133+
assert not updated
134+
assert message
135+
136+
137+
def test_command_through_ssh_quotes_the_paths():
138+
command = update_repository_command(
139+
"/mnt/dir with space/Repo", "https://github.com/o/r.git", "u19prod@host"
140+
)
141+
142+
assert command[:4] == ["ssh", "-o", "BatchMode=yes", "u19prod@host"]
143+
assert shlex.split(command[4]) == [
144+
"git", "-C", "/mnt/dir with space/Repo", "pull", "--ff-only", "--quiet",
145+
"https://github.com/o/r.git", "HEAD",
146+
"&&", "git", "-C", "/mnt/dir with space/Repo", "submodule", "update", "--init",
147+
"--recursive", "--quiet",
148+
"&&", "git", "-C", "/mnt/dir with space/Repo", "rev-parse", "--short", "HEAD",
149+
] # fmt: skip
150+
151+
152+
def test_warning_names_repository_host_and_job():
153+
warning = repository_update_warning(
154+
"BrainCogsEphysSorters",
155+
"/repo/dir",
156+
"u19prod@spock",
157+
42,
158+
"Read-only file system",
159+
)
160+
161+
text = warning["text"]
162+
assert "BrainCogsEphysSorters" in text
163+
assert "/repo/dir" in text
164+
assert "u19prod@spock" in text
165+
assert "job 42" in text
166+
assert "Read-only file system" in text

‎u19_pipeline/automatic_job/params_config.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@
2424
},
2525
]
2626

27+
# Processing repositories pulled (fast-forward only, on the cluster) before each job is queued,
28+
# so jobs run the latest code. Public https URLs: the cluster user needs no GitHub key.
29+
# A failed pull only warns in Slack; the job still runs on the code already checked out.
30+
process_repository_git_urls = {
31+
"BrainCogsEphysSorters": "https://github.com/BrainCOGS/BrainCogsEphysSorters.git",
32+
}
33+
2734
recording_modality_list = [list(i.values()) for i in recording_modality_dict]
2835
recording_modality_df = pd.DataFrame(recording_modality_dict)
2936

‎u19_pipeline/automatic_job/recording_process_handler.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,8 +393,13 @@ def slurm_job_queue(rec_series, status_series):
393393
)
394394
return (status_update, update_value_dict)
395395

396-
# Queue slurm file
396+
# Queue slurm file (on the latest processing code, warns in slack if it can't update)
397397
if status == config.system_process["SUCCESS"]:
398+
slurmlib.update_process_repository(
399+
rec_series["job_id"],
400+
rec_series["program_selection_params"],
401+
rec_series["recording_modality"],
402+
)
398403
status, slurm_jobid, error_message = slurmlib.queue_slurm_file(
399404
rec_series["job_id"],
400405
rec_series["program_selection_params"],

‎u19_pipeline/automatic_job/slurm_creator.py‎

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import u19_pipeline.automatic_job.params_config as config
1212
from u19_pipeline.utils.file_utils import write_file
1313
import u19_pipeline.utils.slurm_utils as slurm_utils
14+
import u19_pipeline.utils.slack_utils as slack_utils
1415

1516
# Functions to create slurm jobs
1617

@@ -82,6 +83,64 @@ def generate_slurm_file(job_id, program_selection_params):
8283
return status, slurm_destination
8384

8485

86+
def get_repository_dir(program_selection_params, modality):
87+
"""
88+
Path of the processing repository checkout in the processing cluster
89+
"""
90+
cluster_vars = ft.get_cluster_vars(program_selection_params["process_cluster"])
91+
return pathlib.Path(
92+
cluster_vars[modality + "_process_dir"],
93+
program_selection_params["process_repository"],
94+
).as_posix()
95+
96+
97+
# Result of the repository update of this run, by checkout (pull & warn once per cron run)
98+
repository_updates = dict()
99+
100+
101+
def update_process_repository(job_id, program_selection_params, modality):
102+
"""
103+
Fast-forward the processing repository in the cluster before queuing a job
104+
If it can't be updated, warn in Slack (once per run) and let the job run on the code there
105+
Returns:
106+
updated (bool) = True if the checkout is up to date (or isn't set to be updated)
107+
message (str) = new commit if updated, otherwise why it could not be updated
108+
"""
109+
repository = program_selection_params["process_repository"]
110+
git_url = config.process_repository_git_urls.get(repository)
111+
if git_url is None:
112+
return True, ""
113+
114+
repository_dir = get_repository_dir(program_selection_params, modality)
115+
if repository_dir in repository_updates:
116+
return repository_updates[repository_dir]
117+
118+
cluster = program_selection_params["process_cluster"]
119+
cluster_vars = ft.get_cluster_vars(cluster)
120+
ssh_target = cluster_vars["user"] + "@" + cluster_vars["hostname"]
121+
if cluster == "spock" and is_this_spock():
122+
ssh_target = None
123+
124+
updated, message = slurm_utils.update_repository(
125+
repository_dir, git_url, ssh_target
126+
)
127+
repository_updates[repository_dir] = (updated, message)
128+
print("update_process_repository", repository_dir, updated, message)
129+
130+
if not updated:
131+
try:
132+
slack_utils.send_slack_notification(
133+
config.slack_webhooks_dict["automation_pipeline_error_notification"],
134+
slurm_utils.repository_update_warning(
135+
repository, repository_dir, ssh_target or cluster, job_id, message
136+
),
137+
)
138+
except Exception as e:
139+
print("Could not send repository update warning to slack:", e)
140+
141+
return updated, message
142+
143+
85144
def queue_slurm_file(
86145
job_id,
87146
program_selection_params,
@@ -99,10 +158,7 @@ def queue_slurm_file(
99158

100159
print("queue_slurm_file **********************************")
101160

102-
processing_repository = program_selection_params["process_repository"]
103-
repository_dir = pathlib.Path(
104-
cluster_vars[modality + "_process_dir"], processing_repository
105-
).as_posix()
161+
repository_dir = get_repository_dir(program_selection_params, modality)
106162

107163
command = [
108164
"ssh",

‎u19_pipeline/utils/slurm_utils.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import re
2+
import shlex
23
import signal
4+
import subprocess
35

46
# Fields queried from sacct to explain why a job ended (one row per job and per job step)
57
sacct_format = [
@@ -145,3 +147,56 @@ def describe_slurm_job(job_info, max_length=150):
145147
description = description[: max_length - 4] + "...)"
146148

147149
return description
150+
151+
152+
def update_repository_command(repository_dir, git_url, ssh_target=None):
153+
"""
154+
Command that fast-forwards a checkout to the default branch of git_url, checks out the
155+
submodule commits it pins (sorters like Kilosort3) and prints its new commit
156+
Pulling from the URL (not origin) works even when origin is an ssh remote the user has no key for
157+
"""
158+
quoted_dir = shlex.quote(repository_dir)
159+
remote_command = (
160+
f"git -C {quoted_dir} pull --ff-only --quiet {shlex.quote(git_url)} HEAD"
161+
f" && git -C {quoted_dir} submodule update --init --recursive --quiet"
162+
f" && git -C {quoted_dir} rev-parse --short HEAD"
163+
)
164+
if ssh_target:
165+
return ["ssh", "-o", "BatchMode=yes", ssh_target, remote_command]
166+
return ["bash", "-c", remote_command]
167+
168+
169+
def update_repository(repository_dir, git_url, ssh_target=None, timeout=120):
170+
"""
171+
Fast-forward a processing repository checkout (through ssh if ssh_target is given)
172+
Returns:
173+
updated (bool) = True if the checkout is now at the latest commit of git_url
174+
message (str) = new commit if updated, otherwise why it could not be updated
175+
"""
176+
command = update_repository_command(repository_dir, git_url, ssh_target)
177+
try:
178+
p = subprocess.run(
179+
command, capture_output=True, text=True, timeout=timeout, check=False
180+
)
181+
except subprocess.TimeoutExpired:
182+
return False, "git pull did not finish in " + str(timeout) + " s"
183+
except OSError as e:
184+
return False, str(e)
185+
186+
if p.returncode != 0:
187+
output = (p.stderr.strip() or p.stdout.strip())[-1000:]
188+
return False, output or "git pull exited with code " + str(p.returncode)
189+
return True, p.stdout.strip()
190+
191+
192+
def repository_update_warning(repository, repository_dir, where, job_id, message):
193+
"""
194+
Slack message for a processing repository that could not be updated before queuing a job
195+
"""
196+
return {
197+
"text": (
198+
f":warning: Could not update *{repository}* (`{repository_dir}` on {where})"
199+
f" before queuing job {job_id}. The job will run on the code already checked out."
200+
f"\n```{message}```"
201+
)
202+
}

0 commit comments

Comments
 (0)