fix(container): skip repos still cloning, re-check idleness after the idle push, trap TERM before background work
- clone_repos records `<folder>\tcloning` as each clone begins; triple-c-wip-push skips a folder whose last state is `cloning` while the clone is not done (dry run reports "cloning": true; RepoState/TS carry it, the stop guard lists it as "still cloning — nothing to push" and never asks because of it). - The idle watcher re-checks quiet() after a successful push and goes back to watching if someone came back during it. - The entrypoint installs its stop trap before the idle watcher and the background clone start, so a TERM in between still runs aws_before_stop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
276f5378a4
commit
170ba1e94d
11 files changed
+178
-18
No files matched your search
@@ -280,7 +280,7 @@ pub(crate) mod tests {
|
||||
{\"folder\":\"web\",\"dirty\":false,\"unpushed\":2,\"branch\":\"HEAD\"}\n";
|
||||
let repos = parse_dry_run(out).unwrap();
|
||||
assert_eq!(repos.len(), 2);
|
||||
assert_eq!(repos[0], RepoState { folder: "api".into(), dirty: true, unpushed: 0, branch: "main".into() });
|
||||
assert_eq!(repos[0], RepoState { folder: "api".into(), dirty: true, unpushed: 0, branch: "main".into(), cloning: false });
|
||||
assert_eq!(repos[1].unpushed, 2);
|
||||
assert!(parse_dry_run("{\"folder\":1}").is_err());
|
||||
assert!(parse_dry_run("").unwrap().is_empty());
|
||||
|
||||
@@ -421,7 +421,8 @@ fn clone_repos_clones_skips_existing_and_reports_failures_without_failing() {
|
||||
assert_eq!(fs::read_to_string(ws.join(".dotted/README")).unwrap(), "hello");
|
||||
assert_eq!(
|
||||
fs::read_to_string(status.join("repos")).unwrap(),
|
||||
"main-copy\tcloned\ndev-copy\tcloned\nexisting\texists\nbroken\tfailed\n.dotted\tcloned\n"
|
||||
"main-copy\tcloning\nmain-copy\tcloned\ndev-copy\tcloning\ndev-copy\tcloned\n\
|
||||
existing\texists\nbroken\tcloning\nbroken\tfailed\n.dotted\tcloning\n.dotted\tcloned\n"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -473,6 +474,11 @@ fn write_script(dir: &Path, name: &str, body: &str) -> std::path::PathBuf {
|
||||
}
|
||||
|
||||
fn wip_push(ws: &Path, args: &[&str]) -> Output {
|
||||
let tmp = ws.parent().unwrap();
|
||||
wip_push_with_clone_dir(ws, args, &tmp.join("no-clone-status"))
|
||||
}
|
||||
|
||||
fn wip_push_with_clone_dir(ws: &Path, args: &[&str], clone_dir: &Path) -> Output {
|
||||
let tmp = ws.parent().unwrap();
|
||||
let script = write_script(tmp, "triple-c-wip-push", WIP_PUSH);
|
||||
// Through bash rather than exec'd: a script written a moment ago can be
|
||||
@@ -481,6 +487,7 @@ fn wip_push(ws: &Path, args: &[&str]) -> Output {
|
||||
.arg(script)
|
||||
.args(args)
|
||||
.env("TRIPLEC_WORKSPACE_ROOT", ws)
|
||||
.env("TRIPLEC_CLONE_STATUS_DIR", clone_dir)
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("HOME", tmp)
|
||||
.output()
|
||||
@@ -673,6 +680,44 @@ fn wip_push_uploads_lfs_objects_before_the_no_verify_push() {
|
||||
assert_eq!(fs::read_to_string(&log).unwrap().trim(), format!("push origin {pushed}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wip_push_skips_a_repo_the_background_clone_is_still_writing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (ws, repo, remote) = workspace_with_clone(tmp.path());
|
||||
// `half` is mid-clone: a checkout in progress reads as a dirty tree.
|
||||
git(&ws, &["clone", "-q", remote.to_str().unwrap(), "half"]);
|
||||
fs::remove_file(ws.join("half/README")).unwrap();
|
||||
fs::write(repo.join("y"), "y").unwrap();
|
||||
let clone = tmp.path().join("clone");
|
||||
fs::create_dir_all(&clone).unwrap();
|
||||
fs::write(clone.join("repos"), "proj\tcloning\nproj\tcloned\nhalf\tcloning\n").unwrap();
|
||||
|
||||
let out = wip_push_with_clone_dir(&ws, &["--dry-run"], &clone);
|
||||
assert!(out.status.success(), "{}", text(&out));
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let lines: Vec<serde_json::Value> = stdout.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
let by = |f: &str| lines.iter().find(|v| v["folder"] == f).unwrap().clone();
|
||||
assert_eq!(
|
||||
by("half"),
|
||||
serde_json::json!({"folder": "half", "dirty": false, "unpushed": 0, "branch": "", "cloning": true})
|
||||
);
|
||||
assert_eq!(by("proj")["dirty"], true, "a finished clone is checked as usual");
|
||||
// The Rust side parses that line.
|
||||
let parsed = crate::commands::stop_guard::parse_dry_run(&stdout).unwrap();
|
||||
assert!(parsed.iter().any(|r| r.folder == "half" && r.cloning));
|
||||
|
||||
let out = wip_push_with_clone_dir(&ws, &[], &clone);
|
||||
assert!(out.status.success(), "{}", text(&out));
|
||||
assert!(text(&out).contains("half: still cloning"), "{}", text(&out));
|
||||
assert_eq!(wip_refs(&remote).len(), 1, "only proj was pushed");
|
||||
|
||||
// Once the clone is done, the folder is an ordinary repository again.
|
||||
fs::write(clone.join("done"), "").unwrap();
|
||||
let out = wip_push_with_clone_dir(&ws, &["--dry-run"], &clone);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(stdout.contains(r#"{"folder":"half","dirty":true"#), "{stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wip_push_rejects_an_unknown_reason() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -977,6 +1022,45 @@ fn idle_watch_pushes_before_an_idle_stop_and_stays_up_while_the_push_fails() {
|
||||
assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), "idle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_watch_goes_back_to_watching_when_someone_comes_back_during_the_push() {
|
||||
let w = Watch::new();
|
||||
w.dirty();
|
||||
let d = w.tmp.path();
|
||||
// The push starts a process the watcher counts as `claude` (a renamed
|
||||
// `sleep`, so `pgrep -x` matches it), as a user returning mid-push would.
|
||||
let busy_name = format!("tcbusy{}", std::process::id() % 100_000);
|
||||
let sleep = Command::new("sh").arg("-c").arg("command -v sleep").output().unwrap();
|
||||
let sleep = String::from_utf8_lossy(&sleep.stdout).trim().to_string();
|
||||
fs::copy(&sleep, d.join(&busy_name)).unwrap();
|
||||
fs::set_permissions(d.join(&busy_name), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_script(
|
||||
d,
|
||||
"triple-c-wip-push",
|
||||
&format!(
|
||||
"#!/bin/bash\nif [ \"$1\" = --dry-run ]; then cat '{p}/dry'; exit 0; fi\n\
|
||||
echo \"$*\" >> '{p}/pushes'\n'{p}/{busy_name}' 30 </dev/null >/dev/null 2>&1 &\n\
|
||||
echo $! > '{p}/busy.pid'\nexit 0\n",
|
||||
p = d.display()
|
||||
),
|
||||
);
|
||||
let (url, mut agent) = fake_agent(d, OLD_ACTIVITY);
|
||||
let mut target = fake_entrypoint(d);
|
||||
let mut cmd = w.cmd(&url, target.id());
|
||||
cmd.env("TRIPLEC_WIP_PUSH", "1").env("TRIPLEC_IDLE_PROC_NAME", &busy_name);
|
||||
let ran = run_watch_for(cmd, 5);
|
||||
if let Ok(pid) = fs::read_to_string(d.join("busy.pid")) {
|
||||
let _ = Command::new("kill").arg(pid.trim()).status();
|
||||
}
|
||||
target.kill().ok();
|
||||
target.wait().ok();
|
||||
agent.kill().ok();
|
||||
assert!(ran.is_none(), "it must not stop: {:?}", ran.map(|o| text(&o)));
|
||||
assert_eq!(w.pushes(), "--reason idle\n", "it pushed once, then saw the activity");
|
||||
assert!(!d.join("got").exists(), "no TERM");
|
||||
assert!(!d.join("reason").exists(), "no idle marker");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_watch_keeps_a_stop_guard_marker_already_recorded() {
|
||||
for marker in ["pushed", "discard"] {
|
||||
@@ -1138,6 +1222,12 @@ fn docker_mode_never_reaches_the_aws_blocks() {
|
||||
};
|
||||
let agent_call = lines.iter().position(|l| l.trim() == "start_agent").expect("start_agent call");
|
||||
assert!(agent_call < pos("start_clone_repos"), "clones must start after the agent");
|
||||
// The stop trap is in place before any AWS background work starts, so a
|
||||
// TERM in between still runs aws_before_stop.
|
||||
let trap = pos("trap stop_keepalive TERM INT HUP");
|
||||
assert!(trap < pos("start_clone_repos"), "the trap must precede the clone");
|
||||
assert!(trap < pos("start_idle_watch"), "the trap must precede the idle watcher");
|
||||
assert!(pos("stop_keepalive()") < trap);
|
||||
assert!(block(ENTRYPOINT, "aws_repos").contains(") &"), "start_clone_repos backgrounds the clone");
|
||||
// And the snapshot-sensitive variables are gone before the agent's
|
||||
// environment snapshot is taken.
|
||||
|
||||
@@ -727,6 +727,9 @@ pub struct RepoState {
|
||||
pub dirty: bool,
|
||||
pub unpushed: u64,
|
||||
pub branch: String,
|
||||
/// The start's background clone is still writing it: nothing to push.
|
||||
#[serde(default)]
|
||||
pub cloning: bool,
|
||||
}
|
||||
|
||||
/// What `check_unsaved_work` found. `checked: false` (with `error`) when the
|
||||
|
||||
@@ -25,6 +25,17 @@ describe("StopGuardModal", () => {
|
||||
expect(onChoose).toHaveBeenCalledWith("push");
|
||||
});
|
||||
|
||||
it("lists a repository still cloning as having nothing to push", () => {
|
||||
const work: UnsavedWork = {
|
||||
...dirty,
|
||||
repos: [...dirty.repos, { folder: "big", branch: "", dirty: false, unpushed: 0, cloning: true }],
|
||||
};
|
||||
render(<StopGuardModal projectName="api" work={work} onChoose={vi.fn()} />);
|
||||
expect(screen.getByText("/workspace/big")).toBeInTheDocument();
|
||||
expect(screen.getByText("still cloning — nothing to push")).toBeInTheDocument();
|
||||
expect(screen.getByText("/workspace/api")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers Stop without pushing and Cancel", () => {
|
||||
const onChoose = vi.fn();
|
||||
render(<StopGuardModal projectName="api" work={dirty} onChoose={onChoose} />);
|
||||
|
||||
@@ -31,7 +31,8 @@ function describeRepo(dirty: boolean, unpushed: number): string {
|
||||
export default function StopGuardModal({ projectName, work, wipPushOnStop = false, onChoose }: Props) {
|
||||
const pushRef = useRef<HTMLButtonElement>(null);
|
||||
const stopRef = useRef<HTMLButtonElement>(null);
|
||||
const atRisk = work.repos.filter((r) => r.dirty || r.unpushed > 0);
|
||||
const atRisk = work.repos.filter((r) => !r.cloning && (r.dirty || r.unpushed > 0));
|
||||
const cloning = work.repos.filter((r) => r.cloning);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -75,6 +76,14 @@ export default function StopGuardModal({ projectName, work, wipPushOnStop = fals
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{cloning.map((r) => (
|
||||
<li key={r.folder} className="text-[13px] text-[var(--text-primary)]">
|
||||
<span className="font-mono">/workspace/{r.folder}</span>{" "}
|
||||
<span className="text-[var(--text-secondary)]">
|
||||
still cloning — nothing to push
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-3 text-[13px] text-[var(--text-secondary)]">
|
||||
Push to WIP branch saves a snapshot of each repository to a{" "}
|
||||
|
||||
@@ -48,6 +48,8 @@ describe("awsWorkspace", () => {
|
||||
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, dirty: true }], error: null })).toBe(true);
|
||||
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, unpushed: 1 }], error: null })).toBe(true);
|
||||
expect(stopGuardNeeded({ checked: false, repos: [], error: "x" })).toBe(true);
|
||||
// A repository still cloning has nothing to push.
|
||||
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, cloning: true }], error: null })).toBe(false);
|
||||
});
|
||||
|
||||
it("selects only ready environments the user joined", () => {
|
||||
|
||||
@@ -109,7 +109,7 @@ export function cleanRepos(rows: RepoSource[]): RepoSource[] {
|
||||
|
||||
/** Whether Stop must ask first (the one place this rule lives). */
|
||||
export function stopGuardNeeded(work: UnsavedWork): boolean {
|
||||
return !work.checked || work.repos.some((r) => r.dirty || r.unpushed > 0);
|
||||
return !work.checked || work.repos.some((r) => !r.cloning && (r.dirty || r.unpushed > 0));
|
||||
}
|
||||
|
||||
/** An environment a project can be placed in: ready (or merely behind) and joined. */
|
||||
|
||||
@@ -136,6 +136,8 @@ export interface RepoState {
|
||||
dirty: boolean;
|
||||
unpushed: number;
|
||||
branch: string;
|
||||
/** The start's background clone is still writing it: nothing to push. */
|
||||
cloning?: boolean;
|
||||
}
|
||||
|
||||
/** What `checkUnsavedWork` found (Rust `UnsavedWork`). `checked: false` (with
|
||||
|
||||
+18
-10
@@ -635,9 +635,12 @@ chown claude:claude /home/claude/.gitconfig 2>/dev/null || true
|
||||
# app gives a starting task's agent only seconds to answer, so a clone in the
|
||||
# way of the agent would fail every start with a large repository. Terminals
|
||||
# work while the repos arrive. Progress, for the app to show later, is in
|
||||
# /run/triple-c-clone (world-readable, root-written): `repos` gets one
|
||||
# "<folder>\t<cloned|failed|exists>" line per repo, and `done` appears when
|
||||
# all are finished. The idle watcher counts an unfinished clone as activity.
|
||||
# /run/triple-c-clone (world-readable, root-written): `repos` gets a
|
||||
# "<folder>\tcloning" line as a clone begins and a
|
||||
# "<folder>\t<cloned|failed|exists>" line when it ends (the last line for a
|
||||
# folder is its state), and `done` appears when all are finished. The idle
|
||||
# watcher counts an unfinished clone as activity; triple-c-wip-push skips a
|
||||
# folder still `cloning`.
|
||||
# >>> aws_repos
|
||||
# clone_repos json root [status_dir]
|
||||
clone_repos() {
|
||||
@@ -658,6 +661,7 @@ clone_repos() {
|
||||
[ -n "$branch" ] && args+=(--branch "$branch")
|
||||
args+=(-- "$url" "$dest")
|
||||
echo "entrypoint: cloning $folder..."
|
||||
_clone_status "$folder" cloning
|
||||
# BatchMode is appended to whatever ssh command the user's git config
|
||||
# names (core.sshCommand), read as the user, rather than replacing it.
|
||||
err=$(_triplec_as_user sh -c '
|
||||
@@ -1244,6 +1248,17 @@ start_idle_watch() {
|
||||
) &
|
||||
}
|
||||
# <<< aws_stop
|
||||
# The stop trap goes in before any background work starts (the idle watcher
|
||||
# can signal this script; a clone is work a stop must account for), so a TERM
|
||||
# from here on always runs aws_before_stop. Defined after aws_stop, which
|
||||
# holds the function it calls.
|
||||
keepalive_pid=""
|
||||
stop_keepalive() {
|
||||
[ "$triplec_aws" = 1 ] && aws_before_stop
|
||||
[ -n "$keepalive_pid" ] && kill "$keepalive_pid" 2>/dev/null
|
||||
exit "${triplec_exit_status:-0}"
|
||||
}
|
||||
trap stop_keepalive TERM INT HUP
|
||||
if [ "$triplec_aws" = 1 ] && [ -n "${TRIPLEC_IDLE_STOP_MINUTES:-}" ]; then
|
||||
start_idle_watch "$TRIPLEC_IDLE_STOP_MINUTES" "$$"
|
||||
fi
|
||||
@@ -1253,13 +1268,6 @@ if [ "$triplec_aws" = 1 ]; then
|
||||
fi
|
||||
|
||||
echo "Triple-C container ready."
|
||||
keepalive_pid=""
|
||||
stop_keepalive() {
|
||||
[ "$triplec_aws" = 1 ] && aws_before_stop
|
||||
[ -n "$keepalive_pid" ] && kill "$keepalive_pid" 2>/dev/null
|
||||
exit "${triplec_exit_status:-0}"
|
||||
}
|
||||
trap stop_keepalive TERM INT HUP
|
||||
throttle_fifo=/run/triple-c-keepalive.throttle
|
||||
rm -f "$throttle_fifo"
|
||||
mkfifo -m 600 "$throttle_fifo" 2>/dev/null && exec 3<>"$throttle_fifo"
|
||||
|
||||
@@ -19,9 +19,10 @@
|
||||
# * no work would be lost: `triple-c-wip-push --dry-run` (as claude) finds
|
||||
# no dirty repository and no unpushed commit. With the WIP push on
|
||||
# (TRIPLEC_WIP_PUSH=1) such work is pushed here, before the stop, and the
|
||||
# workspace stops only once that push succeeded; a failed push keeps it
|
||||
# running and is retried later (backing off). With it off, unsaved work
|
||||
# simply keeps the workspace up.
|
||||
# workspace stops only once that push succeeded and the workspace is
|
||||
# still quiet afterwards (activity during the push sends it back to
|
||||
# watching); a failed push keeps it running and is retried later (backing
|
||||
# off). With it off, unsaved work simply keeps the workspace up.
|
||||
#
|
||||
# Anything it cannot read counts as NOT idle: a stop is the one thing here
|
||||
# that cannot be undone, so every doubt keeps the workspace running.
|
||||
@@ -206,6 +207,14 @@ while :; do
|
||||
echo "triple-c-idle-watch: the WIP push failed — staying up; retrying in ${wait_s}s"
|
||||
continue
|
||||
fi
|
||||
# The push took a while: someone may have come back meanwhile (a
|
||||
# terminal, a `claude`, a scheduler job). Their new work would be
|
||||
# lost, since the stop hook does not push again after an idle push.
|
||||
if ! quiet; then
|
||||
echo "triple-c-idle-watch: activity during the WIP push — not stopping"
|
||||
said=""
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
echo "triple-c-idle-watch: idle for ${minutes} minutes — stopping the workspace"
|
||||
mkdir -p "$(dirname "$reason_file")" 2>/dev/null
|
||||
|
||||
@@ -22,14 +22,22 @@
|
||||
# {"folder":…, "dirty":bool, "unpushed":n, "branch":…}
|
||||
# and changes nothing.
|
||||
#
|
||||
# A repository the start's background clone is still writing (the entrypoint's
|
||||
# /run/triple-c-clone: its `repos` file's last line for the folder says
|
||||
# `cloning` and `done` is absent) is skipped: a half-made checkout is not the
|
||||
# user's work. The dry run reports it as
|
||||
# {"folder":…, "dirty":false, "unpushed":0, "branch":"", "cloning":true}
|
||||
#
|
||||
# Exit 0 when every needed push succeeded (or nothing needed pushing), 1 when
|
||||
# any failed, 2 on bad usage.
|
||||
#
|
||||
# TRIPLEC_WORKSPACE_ROOT overrides /workspace (tests).
|
||||
# TRIPLEC_WORKSPACE_ROOT overrides /workspace, TRIPLEC_CLONE_STATUS_DIR
|
||||
# /run/triple-c-clone (tests).
|
||||
|
||||
set -u
|
||||
|
||||
root="${TRIPLEC_WORKSPACE_ROOT:-/workspace}"
|
||||
clone_dir="${TRIPLEC_CLONE_STATUS_DIR:-/run/triple-c-clone}"
|
||||
dry_run=0
|
||||
reason=stop
|
||||
|
||||
@@ -62,6 +70,14 @@ pick_remote() {
|
||||
if [ "$(git remote | wc -l)" -eq 1 ]; then git remote; fi
|
||||
}
|
||||
|
||||
# Whether the background clone is still writing folder $1: the clone is not
|
||||
# `done` and the last state it recorded for the folder is `cloning`.
|
||||
still_cloning() {
|
||||
[ -d "$clone_dir" ] && [ ! -e "$clone_dir/done" ] || return 1
|
||||
# ENVIRON, not -v: -v would read backslashes in a folder name as escapes.
|
||||
[ "$(F="$1" awk -F '\t' '$1 == ENVIRON["F"] { s = $2 } END { print s }' "$clone_dir/repos" 2>/dev/null)" = cloning ]
|
||||
}
|
||||
|
||||
user_ssh_command="${GIT_SSH_COMMAND:-}"
|
||||
|
||||
for dir in "$root"/*/; do
|
||||
@@ -73,6 +89,16 @@ for dir in "$root"/*/; do
|
||||
[ "$top" = "$(cd "$dir" && pwd -P)" ] || continue
|
||||
folder=$(basename "$dir")
|
||||
|
||||
if still_cloning "$folder"; then
|
||||
if [ "$dry_run" = 1 ]; then
|
||||
jq -cn --arg folder "$folder" \
|
||||
'{folder: $folder, dirty: false, unpushed: 0, branch: "", cloning: true}'
|
||||
else
|
||||
echo "triple-c-wip-push: $folder: still cloning — nothing to push"
|
||||
fi
|
||||
continue
|
||||
fi
|
||||
|
||||
(
|
||||
cd "$dir" || exit 1
|
||||
# BatchMode: an unknown host key or a passphrase prompt fails at once
|
||||
|
||||
Reference in new issue
Block a user