Skip to content

Dead-code inventory: ~3,980 unreachable non-test lines, plus two stranded-deployment inverses #811

Open

Description

@scttfrdmn

A whole-program reachability pass found ~3,980 non-test lines (3,508 Go +
472 Python) unreachable from every deployed entry point. Tracking issue; the
three items that are probably live defects rather than cleanup are filed
separately (#809, #810, and the note below).

Method, because the conclusion depends on it

golang.org/x/tools/cmd/deadcode (RTA), run from the union of all 11 deployed
entry points
— root module, cmd/spored, and each of the 9 lambda submodules —
with -test=false so tests-only callers correctly count as no caller. A symbol
counts as dead only if dead in the root run and in every lambda whose
dependency closure includes its package.

Then repeated for GOOS=linux, darwin and windows and intersected. That
step earned itself: the darwin run reported pkg/agent.isRecentActivity dead,
but it is called from sys_linux.go:120, which darwin never compiles. One false
positive in 179 candidates — and it would have been a wrong deletion, since
spored ships linux and windows.

Cross-repo: zero importers of any package below across all 9 sibling Go repos.
No dot-imports, no reflective dispatch (MethodByName/reflect.Value.Call), so
RTA is sound here. The 8 packages in api/public-surface.txt are excluded
throughout as wire contract.

Largest removable units

LOC what note
807 pkg/compliance report generator + standalone validators live API is only NewValidator + 4 methods; the whole NIST/FedRAMP report path has test callers only. There is no spawn compliance command
679 cmd/orchestrator + pkg/orchestrator a second binary no release produces — .goreleaser.yaml builds only spawn and spored. deployment/spawn-orchestrator.service ships an ExecStart for a path nothing writes
472 lambda/dns-updater/handler.py a complete Python implementation of a Lambda that is deployed as Go (scripts/deploy-custom-dns.sh:114 builds bootstrap, :243 sets provided.al2023). Never packaged
354 pkg/regions — 19 of 20 functions live part is the AllAWSRegions/GeographicGroups tables + IsValidRegion. Region filtering, constraint evaluation and haversine priority scoring are never invoked
234 pkg/observability/alerting (entire package) zero importers of any kind. Serves /alertmanager/webhook; deployment/prometheus/alertmanager.yaml:27 posts to exactly that path — config and server match, nothing starts the server
197 pkg/security EncryptSecret, DecryptSecret, MaskSecret, MaskURL, ValidateCommand, SanitizePath, ValidateMountPath, SanitizeForLog — all unreached
159 pkg/service local-execution path RunLocal + Local.Addr/URL/Wait/Stop
126 pkg/plugin/push_ssh.go + push_ssm.go filed separately as #810 — probable functional gap

Plus ~500 LOC spread across 20 packages (full list with per-file spans was
produced by the pass; pkg/userdata.GenerateContainerUserData at 56 LOC is
notable — a generator that emits boot-time user-data no launch path requests,
the GenerateScopedDynamoDBPolicy sibling).

Two that are not cleanup

pkg/security deserves a second look before deletion. These are secret
masking, command validation and mount-path sanitising helpers that read as though
they were meant to be on a path and never were wired in. Removing them is safe;
whether something should be calling SanitizeForLog/ValidateCommand is a
different question, and the security review separately found one place building a
su command by string interpolation while every sibling uses argv form.

cmd/launch_cost_limit.go:98 — costLimitScopeNote is a gate that cannot
fail.
Its only callers are cmd/launch_cost_limit_test.go:119,127. Its own doc
comment says it is "used in the launch preview so the scope is stated where the
number is shown rather than only in flag help"
, and
TestCostLimitScopeNoteStatesTheSplit opens with "the number is shown in the
launch preview"
. Neither is true — no preview path calls it. So the
user-facing note about what the --cost-limit cap can actually act on never
prints, and a green test is counted as coverage for behaviour that does not
happen. The honest fix is to call it, not delete it.

The inverse: deployed code with no deploy mechanism

docs/infra-account.md currently claims "Code with no deployment: None, as
of 2026-10-10"
— which I wrote, and which only considered one direction.

lambda/cost-history-collector/ is live and has no deploy mechanism in the
repo.
No template.yaml, no Makefile, no deploy.sh; the only reference
anywhere is a Dependabot entry. Yet spawn-cost-history-collector runs hourly
and lambda/dashboard-api/cost_history.go:16 reads its table. So it is
hand-deployed code with no reproducible deploy — the exact inverse of
alert-handler, and arguably worse: alert-handler was code nothing ran, this is
something running that nobody can rebuild.

Also stranded: deployment/prometheus/ and deployment/grafana/ (9 config
files) are referenced by no Makefile target, script, workflow, doc or compose
file. They are the config half of pkg/observability/alerting. #783 removed "the
stranded self-hosted stack"; this is the rest of it.

Suggested sequencing

  1. Fix the two live defects first (DCV/app sessions always use a self-signed cert: installDCVCert is unreachable, so the provisioned wildcard cert is never fetched #809, Plugin pushes only buffer in memory: both real transports (SSM, SSH tunnel) are never constructed #810) and call costLimitScopeNote.
  2. Decide pkg/compliance: the validator is live and used by spawn launch
    and spawn validate; the report generator is not. Keep the first, delete
    the second — do not remove the package wholesale.
  3. Delete the unambiguous ones: cmd/orchestrator + pkg/orchestrator + its
    service file and example config, handler.py, pkg/observability/alerting +
    deployment/prometheus + deployment/grafana, the dead pkg/regions half.
  4. Give cost-history-collector a deploy script, and correct the "Code with no
    deployment: None" claim to cover both directions.

Note ControlViolation.Error (pkg/compliance/controls.go:41) is uncalled but
is what makes the type satisfy error — deleting the method silently changes the
type's interface satisfaction.

Activity

  1. added
    enhancement
    on Oct 11, 2026
  2. scttfrdmn commented on Oct 12, 2026

    @scttfrdmn
    ContributorAuthor

    Progress, plus two corrections to this issue's own premises. Three PRs so far, each Refs not Closes.

    Landed

    Step 4 — a deploy script for cost-history-collector — landed earlier, along with correcting the "Code with no deployment: None" claim.

    Correction 1: deployment/prometheus and deployment/grafana are not the config half of alerting

    This issue groups them with pkg/observability/alerting for deletion. They're not:

    • prometheus.yaml scrapes port 9090 on EC2 instances — that is spored's live metrics server (pkg/observability/metrics, started at cmd/spored/main.go:198), and the Grafana dashboards sit over those metrics. Only alertmanager.yaml belonged to the dead bridge.
    • pkg/observability/metrics and tracing are both live in cmd/spored.
    • The AlertingConfig struct has a real reader: pkg/provider/local.go:89-91 carries PrometheusURL/AlertmanagerURL through it. So the struct survives the package built on it.

    Their real defect is different and arguably worse: undiscoverable, and silently non-functional. Two defaults mean the tree does nothing until changed — Metrics.Enabled is false by default, and nothing in spawn sets the spawn:metrics-enabled tag that the Prometheus EC2 service-discovery job filters on (read in one place, pkg/provider/ec2.go:613; written nowhere). An operator who copied the configs saw a healthy Prometheus with zero targets and no way to tell which half was missing. Documented and gated in #863 rather than deleted.

    Correction 2: pkg/security — the question is sharper than "second look"

    This issue says removing them is safe but something maybe should be calling them. That is now evidenced rather than speculative: the reaper's unquoted su was fixed earlier in this audit by giving lambda/ttl-reaper the pkg/security.ValidateUsername it did not import at all. So at least one of these helpers was wanted on a live path. Keeping this item last.

    Remaining

    • lambda/dns-updater/handler.py — 472 lines of Python for a function deployed as Go. Confirmed live: provided.al2023, handler bootstrap.
    • the dead pkg/regions half
    • the pkg/compliance split (keep NewValidator + its 4 methods, drop the report generator)
    • pkg/security, last

    One methodology note for whoever picks this up: of this issue's claims I have checked so far, the LOC counts and reachability conclusions have all held exactly — 679 for the orchestrator, 234 for the bridge, zero importers where it said zero. It is the groupings and the "what should happen next" judgements that needed revising. The reachability pass was sound; treat its inferences about intent as hypotheses.

  3. scttfrdmn commented on Oct 12, 2026

    @scttfrdmn
    ContributorAuthor

    Correction 3: "delete the dead pkg/regions half" is backwards

    This issue lists the dead pkg/regions half among the unambiguous deletions. It isn't. Deleting it would remove the tested implementation and leave an untested duplicate of the same logic running.

    What's actually there

    pkg/regions is 755 non-test lines across four files. Only two symbols have an external non-test reference, both from cmd/launch_regions.go:

    symbol external non-test refs
    GeographicGroups 2
    IsValidRegion 1
    AllAWSRegions 0 (but internally live — it backs IsValidRegion)
    ApplyConstraints, ValidateConstraint, Contains, ScoreRegions, GetRegionsByPriority, GetRegionMetadata, GetGeographicGroup, RegionConstraint, RegionPriority, RegionMetadata, LatLong 0

    So filter.go (159), constraints.go (83) and priority.go (152) look dead — 394 lines, close to this issue's 354.

    Why they're dead

    cmd/launch_regions.go reimplemented them. It has its own applyRegionConstraints, filterIncludeRegions, filterExcludeRegions, filterGeographicRegions, matchesAnyPattern and matchesWildcard, written against sweep.RegionConstraint instead of regions.RegionConstraint. The wildcard matchers are character-for-character the same function with different identifier names.

    The two structs are near-identical too — same five fields, same json/dynamodbav tags; regions.RegionConstraint adds only AllowEmpty. (sweep.RegionConstraint is the DynamoDB-persisted one, so it stays regardless.)

    The part that inverts the recommendation

    tests
    cmd/launch_regions.go's filtering (live) 0 — no test references any of its six filter functions
    pkg/regions/filter.go + constraints.go (dead) filter_test.go, 393 lines, covering ApplyConstraints, ValidateConstraint, matchWildcard, filterInclude, filterExclude, filterGeographic

    The logic deciding which AWS regions a launch targets runs untested, while its tested twin sits unreferenced. Deleting the dead half makes that permanent.

    Equivalence is proven, not assumed

    Before recommending anything I ran a differential test over the real region set — regions.AllAWSRegions as the input list, every combination of 9 include patterns × 9 exclude patterns × 7 geographic groups, comparing applyRegionConstraints against regions.ApplyConstraints:

    compared 567 constraint combinations, 0 mismatches
    

    The only behavioural differences are on paths cmd never takes: pkg/regions guards a nil constraint and honours AllowEmpty, where cmd's always errors on an empty result. shouldApplyRegionConstraints() already guards nil before the call.

    So the fix is de-duplication, in the other direction

    Route cmd/launch_regions.go through pkg/regions (a struct conversion), delete the ~100 duplicated lines from cmd/, and keep filter_test.go — which then covers a live path for the first time. That turns "delete 394 lines" into "delete ~100 lines and gain 393 lines of coverage on region selection."

    priority.go (152 lines — ScoreRegions, GetRegionsByPriority, haversine distance) has no duplicate and no caller, so it is a genuine deletion. GetRegionMetadata and GetGeographicGroup likewise.

    Not doing this in the current PR chain; filing it here so the sequencing above isn't followed as written.


    Tally of this issue's claims checked so far: every LOC count and reachability conclusion has held exactly. Three of three groupings/recommendations have needed revising. The reachability pass was sound; its inferences about what to do are hypotheses.

  4. scttfrdmn commented on Oct 12, 2026

    @scttfrdmn
    ContributorAuthor

    Correction 4, and the last item is done — as an inversion

    pkg/security is resolved, in #868 (advisory GHSA-xqx8-pcpv-cx2h). The answer is not "delete the eight helpers".

    Three of them should be wired in, and not wiring them is a live security defect. pkg/bot persists a chat-platform signing secret to spore-bot-workspaces in plaintext, while security.EncryptSecret/DecryptSecret/IsEncrypted — KMS helpers, with tests — have no caller anywhere. Confirmed against the live table without reading any secret value: four items carry a 32-character signing_secret, the plaintext form, which IsEncrypted would itself report as unencrypted. cmd/bot.go:508 already redacts it for display, so its sensitivity was never in doubt — it is protected on the way out and not at rest. Severity is moderate rather than high: the table has SSE-at-rest, and read access is scoped to one role rather than the account.

    This issue's own words were "these read as though they were meant to be on a path and never wired in". That was right, and it named the wrong three — SanitizeForLog and ValidateCommand rather than the KMS trio.

    Two must specifically NOT be wired in, which matters because this issue frames them as a judgement call rather than a hazard:

    • ValidateMountPath permits only /mnt, /data, /scratch. spawn launch's own defaults are --efs-mount-point /efs and --fsx-mount-point /fsx, neither allowed. Calling it would reject a default launch. A hand-written allowlist in a security helper that contradicts the product's defaults is rule 4's anti-pattern in the worst place for it.
    • ValidateCommand is a denylist of shell metacharacters, and its one plausible call site — the user's --pre-stop hook — is meant to be a shell command, so a legitimate hook containing a pipe would be rejected. The repo already uses the better pattern: buildPreStopCommand quotes with ShellQuote and validates the username with ValidateUsername. Someone trusting ValidateCommand as the fix would get a worse one.

    Also a factual correction: this issue describes pkg/security as 197 unreached lines. The package is substantially live — ValidateUsername has four callers (lambda/ttl-reaper, pkg/agent, pkg/launcher, pkg/pluginruntime), ValidatePathForReading two, ShellQuote two, ValidateBase64 and NormalizeUsername one each. The 197 refers to the eight helpers only; the package is not a deletion candidate.

    Final tally for this issue

    LOC counts and reachability conclusions 5 of 5 held exactly — 679 (orchestrator), 234 (alerting bridge), 472 (handler.py), ~394 (pkg/regions dead half), the eight pkg/security helpers
    Groupings and recommendations 5 of 5 needed revising

    The reachability pass was sound. Every inference it drew about what to do was wrong, in five different directions: a tested twin that should have been kept (pkg/regions), a live config tree misfiled as a dead one's companion (deployment/prometheus), an implementation that was the only thing backing two documented flags (priority.go), a function a live test needed to express its assertion (GetBaselineControlCount), and three helpers whose absence from the call graph was itself the bug (the KMS trio).

    The usable lesson for the next pass of this kind: a reachability tool answers "is this called", and the question that matters is "why isn't it". Those come apart more often than not — and "dead outside tests" turned out not to be a safe deletion criterion either.

    PRs: #861, #862, #863, #865, #866, #867. Spawned issues: #864 (--proximity-from/--cost-tier finish-or-withdraw), #868 (this), #859, #860.

  5. scttfrdmn commented on Oct 12, 2026

    @scttfrdmn
    ContributorAuthor

    All six PRs are merged (#861, #862, #863, #865, #866, #867) and main is green, including the three new gates. Leaving this open — the ~500 LOC spread across 20 packages tail is not done, and the reason it needs a fresh pass is itself a finding.

    Correction 5: GenerateContainerUserData is not a defect — it is by design

    This issue singles it out: "pkg/userdata.GenerateContainerUserData at 56 LOC is notable — a generator that emits boot-time user-data no launch path requests." Factually true. But no launch path was ever supposed to request it. Its own header says so:

    "this is the plain, non-interactive counterpart for a library consumer that just wants a container running headlessly… Intended for launcher.Options.ContainerScript, which Provision splices into the bootstrap after StorageScript and before CustomUserData."

    And the field it feeds is committed public surface:

    api/public-surface.txt:474: field BootstrapConfig.ContainerScript string
    api/public-surface.txt:483: field Options.ContainerScript string
    

    pkg/launcher is one of the eight contract packages, so removing either field is a MINOR break and api_surface_test.go would block it. Deleting the generator while keeping the fields would be worse: a consumer left with a documented field and no supported way to populate it.

    Checked properly, because gh search code is known not to find these consumers (it returned 0 for every repo, which proves nothing). Grepped local clones of all five, with a control to prove the greps work:

    repo sets ContainerScript uses launcher.Options imports pkg/launcher
    calque 0 0 2 files
    lagotto 0 7 files 11 files
    spore-host-mcp 0 1 file 1 file
    nf-spawn 0 0 0
    cohort 0 0 0

    So: a deliberately-built, contract-committed library affordance that no consumer has adopted yet. Nor is it a duplicate of the live container path — cmd/task.go → pkg/taskproto/wrapper.go runs containers for the CLI, and container.go's header explicitly separates the two ("that machinery is DCV-session-specific… stays there"). Do not delete.

    Why the remaining tail needs a fresh pass, not the old list

    Deletion cascades. Removing the thirteen pkg/compliance wrappers orphaned four more functions that had only ever been reachable through them — one round of deletion created the next round's candidates. Roughly 5,500 lines have now gone, so the original pass's "~500 LOC across 20 packages" list is stale in both directions: some entries are already deleted, and new ones exist that the first pass could not have seen.

    Anyone picking this up should re-run deadcode from the union of entry points rather than working the old list. Two criteria to carry forward, both learned the hard way here:

    • exclude nothing on the basis of tests. My pass excluded _test.go to answer "is this dead in production", which is right — but it is not a deletion criterion. GetBaselineControlCount has no production caller and a live test needs it to express its assertion.
    • for a symbol in one of the eight public packages, in-repo reachability is not reachability at all. ContainerScript above is the case in point, and gh search code will not tell you.

    Final tally

    LOC counts and reachability conclusions 6 of 6 held exactly
    Groupings and "what to do" recommendations 6 of 6 needed revising

    Six distinct ways the inference was wrong: a tested twin that had to be kept (pkg/regions), a live config tree misfiled as a dead one's companion (deployment/prometheus), the only implementation backing two documented flags (priority.go), a function a live test needed (GetBaselineControlCount), three helpers whose absence from the call graph was the bug (the KMS trio, #868), and now a contract-committed library affordance awaiting adoption (ContainerScript).

    A reachability tool answers "is this called". The question that decides what to do is "why isn't it." Those came apart every single time.

    Spawned: #864 (--proximity-from/--cost-tier finish-or-withdraw), #868 (bot signing secret at rest, GHSA-xqx8-pcpv-cx2h), #859, #860.

  6. modified the milestones: Later, Hardening on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions