Skip to content

Fix: Tell a stopped Cortex from a broken one in service status, on Linux - #1529

Merged
huang195 merged 5 commits into
mainfrom
service-status-states
Nov 3, 2026
Merged

huang195 merged 5 commits into
mainfrom
service-status-states

Conversation

@Alan-Cha

@Alan-Cha Alan-Cha commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

agentop service status could not tell a stopped Cortex from a broken one on Linux. This PR makes it ask systemd, fixes start/restart after a crash loop, and adds the real-systemd test that #945's last unchecked item, "service status | start | stop | restart accurate in every state", has been missing.

The bug

When nothing answered /healthz, status printed the same alarm whatever the reason. Measured on systemd 261:

State systemd agentop service status exit
running active/running Cortex is healthy 0
stopped with service stop inactive/dead, disabled Cortex is NOT answering … Claude Code and OpenCode will fail 1
crash-looping activating/auto-restart Cortex is NOT answering … Claude Code and OpenCode will fail 1

A deliberate stop read as a failure. Its log tail, the old proxy shutting down cleanly, made it more confusing.

What changed

status asks systemd why once the health probe has failed (one systemctl --user show), and names the case:

systemd says status says exit
inactive, disabled Cortex is stopped, and stays stopped across logins and reboots until you start it. 0
inactive, enabled Cortex is stopped, but still enabled, so it starts again at the next login or boot. 1
activating / auto-restart Cortex is NOT running: it exited (signal) and systemd is restarting it (restart 1). 1
failed Cortex is NOT running: systemd stopped restarting it (…) after 5 restart(s). … agentop service restart 1

Each message states only what systemd reports, not how the unit got there: "stopped and disabled" is what service stop leaves, but also what a never-enabled unit file looks like, and systemd can't tell them apart. Anything else keeps the existing NOT answering message, including its check for a foreign process holding the port: active but silent, still starting, a unit systemd hasn't loaded or that is masked, enablement that is neither enabled nor disabled, or systemd unreachable. macOS is unchanged.

Exit-code change, worth a release-notes line. A stopped Cortex now exits 0, the same as a healthy one; before, it exited 1. That's deliberate, since a stop isn't a failure, and the output still says Claude Code and OpenCode fail until Cortex runs again. But a script that reads exit 0 as "Cortex is serving" would now treat a stopped Cortex as fine. Both in-repo callers (scripts/release_smoke_test_linux.sh, scripts/dev/verify-reboot-lingering.sh) also check for Cortex is healthy according to, so neither is affected. docs/laptop-service.md now says to do the same.

start, restart and install clear systemd's start limit first. The unit allows five starts in five minutes (StartLimitBurst=5). A proxy that crash-loops uses them up in under a minute, and systemd then refuses every start until the window passes. So the advice status gives, fix the cause and run agentop service restart, failed with start of the service was attempted too often, and so did service start and a reinstall. They now run systemctl --user reset-failed cortex.service before starting. systemd's own restarts are untouched, so the limit still ends a crash loop by itself.

Testing

TestServiceLifecycle_RealSystemd (new) drives agentop service itself against a live systemd --user session:

  1. status: not installed
  2. install, then healthy, systemd active and enabled
  3. stop, then status says stopped (exit 0), systemd inactive and disabled
  4. start, then healthy
  5. restart, with a new main PID
  6. kill -9, then status says restarting, then recovered and healthy
  7. a binary that exits at once, crash-looping until systemd gives up, then status says it gave up
  8. binary fixed, restart, then healthy (failed before this PR)
  9. uninstall, then not installed and the unit inactive

It runs in ci.yaml's existing real-systemd job (the agentop leg, AGENTOP_SYSTEMD_TESTS=required), so no workflow change is needed. It uses a small Python stand-in that serves /healthz, not the real proxy. It installs the real cortex.service, so it skips on an account that already has one and cleans up after itself. It takes about 70 s, most of it waiting for systemd to give up on the crash loop.

On real hosts (cross-compiled test binary):

Host systemd Result
Debian 13, arm64 257.13 all three _RealSystemd tests pass
Ubuntu 26.10, arm64 261 all three _RealSystemd tests pass

The first Debian run caught a difference between versions: when systemd gives up, 257 records the cause as exit-code and 261 as start-limit-hit. Status prints whichever systemd reports, and the test checks only that it says systemd gave up.

Unit: TestSystemdUnitState (parsing, no systemctl, bus unreachable), TestReportUnitNotAnswering (ten states, with exit codes and text that must not appear), TestServiceStatusAsksSystemdOnlyWhenSilent (asks only when the probe fails, and not at all when healthy). The call-order tests in TestLoadService_Linux and TestControlService_Linux now pin reset-failed before each start. The full cmd/agentop suite passes under GOWORK=off; go vet and gofmt are clean.

Docs: docs/laptop-service.md's "Is it working?" gains a table of what status reports on Linux, and a note that scripts should check the output, not only the exit code.

Relates to #945.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • New Features

    • Linux service status now distinguishes stopped, disabled, restarting, and failed services when the health check does not respond. Stopped and disabled services exit successfully; other recognized unhealthy states exit with an error and report their status.
    • Starting, restarting, or installing a Linux service clears systemd’s recorded start failures before attempting to run it.
  • Documentation

    • Updated the laptop service guide with Linux status and recovery behavior.

When nothing answered /healthz, `agentop service status` printed "Cortex
is NOT answering … Claude Code and OpenCode will fail" and exited 1,
whatever the reason. A deliberate `agentop service stop` read exactly
like a crash, and its log tail, the old proxy shutting down cleanly, made
that worse. Measured on systemd 261:

  running            active/running              healthy, exit 0
  service stop       inactive/dead, disabled     NOT answering, exit 1
  crash-looping      activating/auto-restart     NOT answering, exit 1

On Linux, status now asks systemd for the unit's state once the probe
has failed (one `systemctl --user show`) and names the case:

- stopped by `service stop` (inactive and disabled): says so, exit 0;
- stopped some other way, still enabled: says it starts again at the
  next login or boot, exit 1;
- crashed and restarting (auto-restart): says systemd is restarting it;
- given up (failed): says systemd stopped restarting it, and to run
  `agentop service restart` once the cause is fixed.

Anything else, or systemd unreachable, keeps the old message.

That last advice did not work. After five crashes in five minutes
(StartLimitBurst) systemd refuses every start until the window passes,
so `service restart`, `service start` and a reinstall all failed with
"start of the service was attempted too often". They now run
`systemctl --user reset-failed` first. systemd's own restarts are
untouched, so the limit still ends a crash loop by itself.

TestServiceLifecycle_RealSystemd drives `agentop service` itself through
install, status, stop, start, restart, kill -9, a crash loop to the start
limit, recovery and uninstall, against a live systemd --user session.
It runs in ci.yaml's existing real-systemd job and skips on an account
that already has a Cortex installed. Passed on systemd 257 (Debian 13)
and 261 (Ubuntu 26.10). They record the give-up differently (exit-code
on 257, start-limit-hit on 261), so the test checks only that status
says systemd gave up.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
@Alan-Cha
Alan-Cha requested a review from a team as a code owner October 28, 2026 16:13
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Walkthrough

Linux service status now uses systemd state to report stopped, restarting, and failed conditions after an unsuccessful health probe. Install, start, and restart clear systemd’s failed-start counter. Tests cover status cases and a real systemd service lifecycle.

Changes: Linux systemd service behavior

Layer / File(s) Summary
Systemd state and control operations
cmd/agentop/cmd_service_platform.go, cmd/agentop/cmd_service_systemd_test.go
The service reads systemd unit properties. Install, start, and restart reset the failed-start counter; stop does not. Tests check state parsing and ordered systemctl calls.
Status reporting by systemd state
cmd/agentop/cmd_service.go, cmd/agentop/cmd_service_systemd_test.go, cmd/agentop/cmd_service_test.go, docs/laptop-service.md
Linux status uses systemd state after a failed health probe. Stopped-and-disabled units exit successfully; other recognized stopped or failure states exit with an error. Tests cover report text, exit codes, and holder-process details.
Live systemd lifecycle validation
cmd/agentop/cmd_service_systemd_integration_test.go
A live-systemd integration test covers installation, status, stop, start, restart, crash recovery, start-limit handling, recovery after the limit, and uninstall.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant ServiceStatus as Linux service status
  participant HealthProbe as Health probe
  participant systemdUnitState
  participant systemd as systemd user manager
  participant reportUnitNotAnswering
  ServiceStatus->>HealthProbe: Check service health
  HealthProbe-->>ServiceStatus: Return failed health result
  ServiceStatus->>systemdUnitState: Query unit properties
  systemdUnitState->>systemd: Run systemctl show
  systemd-->>systemdUnitState: Return unit state fields
  ServiceStatus->>reportUnitNotAnswering: Report state and holder details
Loading

Possibly related issues

  • rossoctl/cortex#945 — The changes address Linux service status accuracy by reporting systemd states and resetting the failure counter before start and restart.
  • rossoctl/cortex#1500 — The documentation describes Linux status output, and the service operations now include systemd failure-counter resets.

Suggested reviewers: huang195, cwiklik

Merge Risk: Minimal · up to c235f

No actionable issue is established that would prevent merging after normal checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main Linux service-status change: distinguishing a stopped Cortex service from a broken one.
Docstring Coverage Passed Docstring coverage is 81.25% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 81.25% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 16 functions across 5 files. (1 skipped: 1 unsupported.)

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

On Linux, status now asks systemd why nothing answers, and
TestServiceStatus_NotAnsweringNamesTheAgentsThatFail let it ask the
real one. That systemd knows nothing of the fixture's unit, so the
verdict depended on the machine: the CI runner reported "stopped, but
still enabled", and the test, which is about the active-but-silent
message, failed there while passing on macOS, where status never asks.

The test now pins the state it is about (active, running) through
unitStateOf, as TestServiceStatusAsksSystemdOnlyWhenSilent does.
Reproduced on Ubuntu 26.10: fails before, passes after.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
status claimed more than systemd tells it, in two ways:

- "Cortex is stopped (agentop service stop)" for any inactive, disabled
  unit. That is what `service stop` leaves, but so is a unit file that
  was never enabled; systemd cannot tell the two apart. Reproduced on
  Ubuntu 26.10 with a unit file written by hand: status named a stop
  nobody ran. The message now says what is true either way: "Cortex is
  stopped, and stays stopped across logins and reboots until you start
  it."
- "still enabled" for any inactive unit that was not disabled. A unit
  systemd has not loaded (LoadState=not-found) reports inactive with no
  enablement at all, and so did the CI runner, where the claim was
  false. "still enabled" now needs UnitFileState enabled (or
  enabled-runtime).

status now also reads LoadState, and gives the general "NOT answering"
message for a unit that is not loaded (not-found, masked) or whose
enablement is neither of those (static), rather than a guess.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
…aits

From a review of this PR:

- clearStartLimit and the unit-state code went in between
  supervisorRunning's doc comment and the function, so that comment
  sat on top of clearStartLimit's (go doc showed both) and
  supervisorRunning had none. It is back above supervisorRunning,
  unchanged from main.
- TestServiceLifecycle_RealSystemd waited a fixed 20s for a crash
  restart and 90s for the crash loop to hit the start limit. Both
  follow from the unit's RestartSec and StartLimitBurst, so a change to
  either in renderUnitFor would have failed the test as if agentop were
  wrong. The waits are now read from the installed unit: twice what the
  timings imply, plus 10s.
- A stopped Cortex now exits 0, like a healthy one.
  docs/laptop-service.md says so, and that a script should check the
  output for "Cortex is healthy according to" rather than rely on the
  exit code. Both in-repo callers already do.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes a real problem, and TestServiceLifecycle_RealSystemd is the coverage #945 was missing. It passed in CI's real-systemd job (70.65s).

One regression blocks it: on Linux, status no longer names a foreign process holding the port. That was #1122's diagnosis, and the crash-loop branches this PR adds are exactly the state that case produces. There is also one hazard in the new test. Details inline.

Checked locally: go vet and gofmt are clean, and the service, systemd and foreign-holder tests pass under GOWORK=off.

Author: Alan-Cha (MEMBER, maintainer)
Areas reviewed: Go (agentop service status/control), tests, docs
Agent/IDE config (.claude/.vscode): none
Commits: 4, all signed off
CI status: passing

Assisted-By: Claude (Anthropic AI) [email protected]

fmt.Fprintf(stdout, " %s\n", line)
}
return 1
case s.active == "activating" && s.sub == "auto-restart":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: on Linux, the port-holder line from #1122 is gone.

When another process holds the forward port, cortex exits 3 (exitPortInUse). Restart=on-failure then loops it: activating/auto-restart, and later failed. Those are the two branches here, and neither calls foreignHolderLines. Only the default branch (reportNotAnswering) still does, and on Linux it never sees this case, because a proxy that cannot bind never stays active.

So X is held by <exe> (pid N), not this Cortex and Stop the job that runs it: … no longer show up in the one state they were written for. I checked it by calling reportUnitNotAnswering with holderOnPort(t, "47600", 31337, "/usr/bin/python3"):

activating/auto-restart names holder: false
failed/failed           names holder: false
active/running          names holder: true

The log tail may still carry cortex's own cannot start: … line. But #1122 was about not making anyone dig that out of five lines.

Fix: print foreignHolderLines(p) in both branches, as reportNotAnswering does. Then add a holder case to TestReportUnitNotAnswering, since the existing tests call foreignHolderLines only directly, which is why none of them caught this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in c235f59. Both crash branches now print foreignHolderLines under the headline and before the consequence, through a shared printHolderLines that reportNotAnswering uses too. I also corrected the comment that claimed the default branch covered this case.

Reproduced it first on Debian 13 (systemd 257): a Python listener holding 127.0.0.1:47600, then service install. The unit sat in activating/auto-restart and status said only "systemd is restarting it". With the fix:

Cortex is NOT running: it exited (exit-code) and systemd is restarting it (restart 4).
  127.0.0.1:47600 is held by /usr/bin/python3.13 (pid 35487), not this Cortex
  Stop it:  kill 35487  — or, if it is an older Cortex service:  systemctl --user disable --now cortex.service
  If this repeats, the log says why. Claude Code and OpenCode will fail meanwhile. Last log lines:

TestReportUnitNotAnsweringNamesTheHolder sets forwardAddr and holderOnPort, neither of which TestReportUnitNotAnswering's fixture had. That's why the drop passed. It checks the holder is named, before the consequence, with a kill <pid> remedy, in four states: auto-restart, failed, active-but-silent and systemd unreachable. It also checks a stopped Cortex says nothing about the port. With the two printHolderLines calls removed, it fails in exactly the two crash states.

One nuance: the default branch can still name the holder, but only in the moment between cortex starting and its bind failing, while Type=simple reports it active. The comment now says that rather than claiming coverage.

limitWait := 2*time.Duration(burst)*restartSec + 10*time.Second

// A crash: the unit's own RestartSec brings it back.
pid := currentMainPID(systemdUnit)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: a pid of 0 here sends SIGKILL to the test's own process group.

currentMainPID returns 0 when the read fails or MainPID is momentarily 0, and syscall.Kill(0, SIGKILL) signals the caller's whole process group. That kills the test binary, and probably go test with it, with no output saying which step failed.

This can happen: the restart check just above uses t.Errorf on after == 0, so the test carries on with a zero pid.

Fix: use unitMainPID(t, systemdUnit, 5*time.Second) and t.Fatal on !ok, as TestSupervisorRestartsAfterCrash_RealSystemd does.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c235f59 as you suggested: the pid comes from unitMainPID(t, systemdUnit, 5*time.Second), with t.Fatalf on !ok. It's worse than a lost step name: cmd/go starts the test binary with no Setpgid, so kill(0, SIGKILL) also kills go test and its buffered output for the package. SIGKILL skips every t.Cleanup too, which would leave a real cortex.service enabled, and every later local run would then skip as already installed. I checked the other syscall.Kill calls in the package; they're all guarded against 0, by alive, pid > 0 or stopIfAlive.

From huang195's review:

- On Linux, status no longer named a foreign process holding the
  forward port (#1122). cortex exits 3 when it cannot bind, and
  Restart=on-failure loops it through auto-restart into failed: the two
  branches this PR added, neither of which printed foreignHolderLines.
  Only the default branch did, and a proxy that cannot bind never stays
  active long enough to reach it. Both crash branches now print the
  holder lines under the headline and before the consequence, as
  reportNotAnswering does, through a shared printHolderLines. The
  comment that said the default branch covered this case is corrected.

  TestReportUnitNotAnsweringNamesTheHolder sets a forward address and a
  holder, which TestReportUnitNotAnswering's fixture has neither of; that
  is why dropping the line passed. It fails without this change in the
  two crash states. Reproduced on Debian 13 (systemd 257) with a
  process holding 127.0.0.1:47600: status named it before, and does
  again.

- TestServiceLifecycle_RealSystemd read MainPID once before its kill -9.
  currentMainPID returns 0 on a failed read, and kill(2) treats pid 0 as
  the caller's process group, which holds go test too (cmd/go sets no
  Setpgid). That would kill the run silently, skip every Cleanup and
  leave a real cortex.service enabled. The pid now comes from
  unitMainPID, which never returns one below 1, and the test fails by
  name when there is none.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
@Alan-Cha
Alan-Cha requested a review from huang195 November 2, 2026 17:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional comments: 1
cmd/agentop/cmd_service_systemd_integration_test.go-334-334: 1

334-334: Minor · Maintainability & Code Quality · Quick win

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Rename restartSec to fix the ST1011 lint errors.

golangci-lint (staticcheck ST1011) rejects the unit-specific suffix Sec on a variable of type time.Duration. It reports Line 334 and Line 492. If CI runs golangci-lint, the lint step fails. Rename the variable at every use: Lines 334, 352, 362, 364, 492, 493 and 494.

Proposed fix
-func unitTimings(t *testing.T, path string) (restartSec time.Duration, burst int) {
+func unitTimings(t *testing.T, path string) (restartDelay time.Duration, burst int) {
-			restartSec = time.Duration(n) * time.Second
+			restartDelay = time.Duration(n) * time.Second
-	if restartSec <= 0 || burst <= 0 {
-		t.Fatalf("%s sets no RestartSec or StartLimitBurst (got %s, %d); the waits depend on both", path, restartSec, burst)
+	if restartDelay <= 0 || burst <= 0 {
+		t.Fatalf("%s sets no RestartSec or StartLimitBurst (got %s, %d); the waits depend on both", path, restartDelay, burst)
 	}
-	return restartSec, burst
+	return restartDelay, burst
-	restartSec, burst := unitTimings(t, realUnit)
-	restartWait := 2*restartSec + 10*time.Second
-	limitWait := 2*time.Duration(burst)*restartSec + 10*time.Second
+	restartDelay, burst := unitTimings(t, realUnit)
+	restartWait := 2*restartDelay + 10*time.Second
+	limitWait := 2*time.Duration(burst)*restartDelay + 10*time.Second

Also applies to: 492-492

Source: Linters/SAST tools


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 66a3ba37-1762-466f-8a62-8a3689d3cb96
Commits

Reviewing files that changed from the base of the PR and between a0d6616 and c235f59.

Files selected for processing: 6
  • cmd/agentop/cmd_service.go
  • cmd/agentop/cmd_service_platform.go
  • cmd/agentop/cmd_service_systemd_integration_test.go
  • cmd/agentop/cmd_service_systemd_test.go
  • cmd/agentop/cmd_service_test.go
  • docs/laptop-service.md

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This is a solid fix. status now separates a deliberate stop, a pending crash restart and a start-limit give-up from a plain "NOT answering". Each message states only what systemd reports, and reset-failed before user-requested starts closes the real "attempted too often" trap. Both items from huang195's review are resolved in c235f59: printHolderLines now runs in both crash branches, with a regression test, and the kill -9 uses unitMainPID with a t.Fatalf guard. I found nothing blocking. There is one suggestion about service stop on a unit that has already failed, and one stale comment.

Checked locally on c235f59 with GOWORK=off: go vet and gofmt are clean. TestSystemdUnitState, TestReportUnitNotAnswering, TestReportUnitNotAnsweringNamesTheHolder, TestServiceStatusAsksSystemdOnlyWhenSilent, TestServiceStatus_NotAnsweringNamesTheAgentsThatFail, TestControlService_Linux and TestLoadService_Linux all pass. TestServiceLifecycle_RealSystemd skips here because there is no user bus. It is covered by the CI agentop leg, which runs with AGENTOP_SYSTEMD_TESTS=required and passed. Both in-repo scripts that call service status also grep for Cortex is healthy according to, so the exit-0-on-stop change is safe for them.

Author: Alan-Cha (MEMBER — maintainer)
Areas reviewed: Go (agentop service status/control, systemd state parsing), tests (unit + real-systemd lifecycle), docs
Agent/IDE config (.claude/.vscode): none
Commits: 5 commits, all signed-off: yes
CI status: passing

case "start":
args = []string{"--user", "enable", "--now", systemdUnit}
}
if action != "stop" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: service stop on a unit that has already failed leaves it failed, so status then reports a crash instead of a stop.

In systemd's unit_stop() (src/core/unit.c), a unit that is inactive or failed returns -EALREADY before anything changes, and the stop job completes as a no-op. So the sequence is: crash loop, then failed/failed, then the user runs agentop service stop. disable --now turns enablement off, but ActiveState stays failed. reportUnitNotAnswering then takes the failed branch: "systemd stopped restarting it … Fix the cause in the log, then: agentop service restart", exit 1. The user just stopped Cortex on purpose, so this is the stop-reads-like-a-crash confusion this PR sets out to remove, in one more state. Following its advice (restart) would also start a unit that is now disabled.

A cheap fix is to call clearStartLimit() after the stop as well, so a stopped unit always ends up inactive/disabled and gets the "stopped, and stays stopped" message. The existing TestControlService_Linux stop case would then pin reset-failed after disable --now. Not blocking, since it only affects a unit that is already failed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced on Debian 13 (systemd 257) and Ubuntu (261): after a crash loop to the start limit, service stop left the unit failed/disabled, and status reported the crash and advised a restart. Fixed in #1660 as you suggested: reset-failed runs after a successful stop, so the unit ends inactive/disabled and status says stopped. TestServiceLifecycle_RealSystemd now covers that case, and it fails on both systemd versions with the fix reverted.

// the restarts run out.
active, sub string
// UnitFileState: enabled after `service start`, disabled after `service stop`,
// which is what tells our stop from someone else's `systemctl --user stop`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this comment says the opposite of what the code now does. Since 05adf0f, reportUnitNotAnswering deliberately does not tell our stop from anyone else's: "disabled" is also what a never-enabled unit file looks like, as its own doc comment says. Something like "enabled after service start, disabled after service stop (or a unit that was never enabled)" would keep the two in step.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that comment was out of date. #1660 fixes it: disabled is what service stop leaves, and also what a unit that was never enabled reports, so on its own it doesn't tell our stop apart from anyone else's.

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@huang195
huang195 merged commit d6b99c7 into main Nov 3, 2026
41 checks passed
@huang195
huang195 deleted the service-status-states branch November 3, 2026 16:19
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 3, 2026
@Alan-Cha

Alan-Cha commented Nov 4, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai On the restartSec → restartDelay rename (ST1011): declining. Neither golangci-lint nor staticcheck runs anywhere in this repo (not in CI, pre-commit or the Makefile), so no lint step can fail on it. The name also mirrors the unit's RestartSec=, the setting unitTimings reads it from.

@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@Alan-Cha Understood. restartSec mirrors systemd’s RestartSec= setting. I withdraw the rename suggestion and the unsupported claim that this name would cause a repository lint step to fail.

You are interacting with an AI system.

huang195 pushed a commit to huang195/kagenti-extensions that referenced this pull request Nov 6, 2026
`agentop service stop` on a unit systemd had already given up on (failed,
after a crash loop hit the start limit) left it failed: systemd's stop of
a failed unit is a no-op, so `disable --now` only flipped it to disabled.
`service status` then read the deliberate stop as a crash, said "systemd
stopped restarting it" and advised `agentop service restart`, exit 1.

Clear the failed state after a successful stop, so the unit ends inactive
and disabled, which status reports as stopped (exit 0). After the stop
rather than before: nothing is left running for the start limit to
protect, and systemd's own restarts are untouched.

Also correct the UnitFileState comment: disabled is also what a unit file
that was never enabled reports, so it does not by itself tell our stop
from anyone else's.

TestServiceLifecycle_RealSystemd gains the case: a second crash loop to
the start limit, then stop, then status. It passes on systemd 257 (Debian
13) and 261 (Ubuntu), and fails on both with the fix reverted.

Follow-up to rossoctl#1529, from review there.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
esnible pushed a commit to esnible/cortex that referenced this pull request Nov 23, 2026
…until it is down

On macOS, status said "Cortex is NOT answering ... will fail", exit 1,
after a deliberate `service stop`, exactly as after a crash: it never asked
launchd why nothing answered. It now does, as it asks systemd on Linux
(rossoctl#1529), and names the case:

- stopped and disabled, as `service stop` leaves it: "Cortex is stopped,
  and stays stopped ...", exit 0;
- booted out but not disabled, which the next login undoes;
- loaded but not running, as launchd leaves a job while it holds starts
  back for a while after login, with how to start it now;
- no desktop session, as over SSH to a Mac nobody is logged in to: Cortex
  runs only in one, and an SSH login does not start it.

`service stop` and uninstall also returned as soon as `launchctl bootout`
did, which is before teardown finishes, so they said "stopped" while the
supervisor was still taking the proxy down and holding its ports. Both now
wait for the label to leave the domain, as systemd's `disable --now` waits,
and only after a bootout that found a job.

TestServiceLifecycle_RealLaunchd now asserts the stopped wording.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Alan Cha <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants