Skip to content

fix(reaper): keep spawn-instance-* roles an enabled schedule still names (#1378) - #1386

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/1378-schedule-referenced-roles
Oct 28, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/1378-schedule-referenced-roles

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #1378

The per-task role sweep (pkg/instancerole, used by the TTL reaper's REAPER_INSTANCE_ROLES and by spawn cleanup --instance-roles) now keeps a spawn-instance-* role while an enabled schedule still names it. If the schedules can't be read completely, it deletes nothing.

Deferred launchers, and which ones need a reference source

Path Stores a profile name for later? Covered
Schedules (spawn schedule create) Yes. The record has no profile field; the params object (S3ParamsBucket/S3ParamsKey, in the infra account's spawn-schedules-* bucket) holds defaults.iam_role and each row's iam_role. That's the only key the sweep orchestrator passes to RunInstances (spored.go), and nothing re-creates the role at a firing. Yes: instancerole.ScheduleSource
Detached sweeps in flight (spawn-sweep-orchestration + spawn-sweeps-* params) Yes, but the orchestrator launches the next member within one invocation (13 min) of the last one ending, and that member held the profile and refreshed RoleLastUsed. The role can't sit unused for the 24h grace while the sweep still has members to launch. No (reasoned in references.go)
Pipelines in flight (PipelineState.InstanceProfile) Same argument: the next stage launches as soon as the previous one ends. No (reasoned)
Batch queues, pools Their workers hold the profile while they run (the issue says the same). No
lagotto watches The watcher calls CreateOrGetInstanceProfile at match time, so a deleted role is re-created. No
Persistent Spot requests Stop/hibernate interruption leaves the instance stopped, which ProfilesInUse already counts. A replacement launch is unwanted (spored retires it). No
spawn sweep resume (local ~/.spawn/sweeps/<id>.json) Yes, but it's a local file neither caller can read. Filed #1385

Behaviour

  • What protects a role: a schedule that scheduler-handler would launch if it fired now. That check, ScheduleRecord.FiringAt, is now in pkg/scheduler, and the handler uses it too, so the two can't drift. It means status active, under max_executions, before end_after.
  • What doesn't: a paused, cancelled or deleted schedule. Nor does a schedule that has run out: the handler refuses every later firing, and no command raises those limits on an existing record. A one-time schedule that already fired still protects its role: the handler would launch it again if it were invoked, and keeping the role costs one role.
  • Fails closed: nothing is deleted, and the reason is logged and counted, when any of these happens:
    • the Scan fails on any page (AccessDenied, missing table, throttling);
    • a record can't be decoded;
    • an enabled schedule's params object is missing, unreadable or undecodable;
    • no reference source is configured.
  • Structural guard: Sweep returns ErrReferencesNotCollected for a References value that CollectReferences didn't produce, before it reads a single role.
  • Reaper:
    • logs instance-roles: <acct>: role <name> kept: referenced by schedule <id> in report and reap mode;
    • new counters instance_roles_referenced and instance_roles_references_unreadable, the latter also counted in errors unless the cause is AccessDenied.
  • CLI:
    • the preview's WHY KEPT column shows referenced by schedule <id>;
    • unreadable schedules → no IAM role was deleted: ...;
    • the schedules are read again right before the deleting pass.
  • One helper, two callers: instancerole.NewScheduleSource(cfg) reads the table spawn-schedules in us-east-1 (scheduler.TableName/TableRegion, where the CLI writes it) and each params object in its schedule's region. The reaper builds it with its own base credentials (the infra account); the CLI builds it with LoadInfraAWSConfig, the config spawn schedule uses.
  • Missing table is fail-closed (judgement call): treating it as "no schedules" would be sound for the CLI. It isn't sound for a scan-self reaper in a compute account whose schedules live in another infra account. The consequence is that an account with no scheduler never deletes roles; that's filed as Role sweep can never delete in an account without the schedules table (fail-closed since #1378) #1384.

IAM

New grants, read-only, scoped to exactly the schedule data. They're on the reaper's own role only. The member-account role is unchanged and is gated never to get them.

  • dynamodb:Scan on arn:aws:dynamodb:us-east-1:${AWS::AccountId}:table/spawn-schedules. Scan rather than Query, because the GSI is sparse.
  • s3:GetObject on arn:aws:s3:::spawn-schedules-*/schedules/*, the resources scheduler-handler's role already reads.

Where the grants live:

  • Source of truth: pkg/reaperiam.ScheduleReferenceStatements.
  • SAM template: an unconditional statement outside the ScanSelf branch.
  • spawn reaper deploy: ScanSelfPolicyDocument now renders ScanSelf + schedule statements, because that single role is both base and target.
  • grantedElsewhere: s3:GetObject added, and the dynamodb:Scan reason updated.
  • internal/iamcoverage: the reaper's function-role context claims s3:GetObject (new support for exact-action context entries).

For users: spawn cleanup now also calls dynamodb:Scan and s3:GetObject, with the infra profile (docs/reference/cli-iam-actions.md regenerated).

Gates (each watched failing against a compiling revert)

Gate Revert Failed
Idle role named by an enabled schedule's defaults is kept (Substrate: real SaveSchedule + UploadScheduleParams + NewScheduleSource) defaults not collected (_ = pf.Defaults) TestScheduleReferencedRolesAreKept, TestDisablingAScheduleReleasesItsRole, reaper + CLI scenario tests
Role named by a row is kept rows loop body _ = row TestScheduleReferencedRolesAreKept, reaper + CLI scenario tests
Same role, schedule paused / deleted, is deleted; run-out schedules don't protect if false && rec.FiringAt(...) TestDisablingAScheduleReleasesItsRole/paused, TestScheduleReferencedRolesAreKept, scenario tests
Decide keeps a referenced role case len(f.ReferencedBy) > 0 && false TestDecideKeepsAReferencedRole, TestSweepKeepsReferencedRoles, Substrate, reaper and CLI tests
Unreadable table (AccessDenied, second page, missing table) deletes nothing Scan error → break TestScheduleReferencesFailClosedOnScanErrors/*, .../no_schedules_table, reaper TestInstanceRoleSweepFailsClosedOnUnreadableSchedules/{access_denied,throttled}, CLI .../access_denied
Missing params object deletes nothing params error ignored (&& false) Substrate missing_params_object, reaper + CLI missing_params_object
Reaper counts it counter line removed reaper FailsClosedOnUnreadableSchedules/*, WithoutReferenceSourcesDeletesNothing
Reaper/CLI ignore the error and Sweep accepts uncollected refs both && false reaper + CLI fail-closed tests, TestSweepRefusesUncollectedReferences
Consistent read ConsistentRead: false TestScheduleReferencesFailClosedOnScanErrors
CLI and reaper agree on the shared instanceroletest scenario (#1351 poolqueuetest pattern) (any of the above) TestInstanceRoleSweepAgreesWithTheCLI, TestCleanupInstanceRolesAgreesWithTheReaper
IAM scoped to the table + params prefix, and agreeing with pkg/scheduler table ARN → table/* TestScheduleReadIsScopedToTheSchedules, TestSAMTemplateGrantsTheScheduleRead
Template drift params ARN widened; GetObject removed; grant put under an !If TestSAMTemplateGrantsTheScheduleRead (+ TestGrantedElsewhereIsInTheSAMTemplate, iamcoverage TestEveryPrincipalCallIsGranted on removal)
Read only on the reaper's own role ScanSelfStatements gets GetObject; reaper-deploy doc drops the read TestScheduleReadIsOnTheReapersOwnRoleOnly (+ both scan-self drift tests)

Deploy steps

  1. Reaper redeploy (lambda/ttl-reaper: make deploy / sam deploy). This carries the code and the two new grants together. Snapshot the stack parameters first and diff them for zero drift after; InstanceRoles stays report.
    • Simulate the new grants in both directions: allow dynamodb:Scan on spawn-schedules, deny on another table; allow s3:GetObject on spawn-schedules-us-east-1/schedules/x, deny outside schedules/.
    • After the first run, read the log: expect role ... kept: referenced by schedule ... for any schedule-held roles, and instance_roles_references_unreadable == 0.
    • If it's non-zero, the log names the schedule. It's probably Schedule params expire after 7 days (bucket lifecycle), so recurring schedules fail after their first week #1382 (params expire after 7 days); cancel or fix that schedule before arming reap.
  2. Member-account stack (ttl-reaper-cross-account-role.yaml): no change, no redeploy.
  3. Self-hosted reapers pick up the grant on their next spawn reaper deploy.

Follow-ups filed

Checks

make check, make lint (0 issues, all 10 modules) and semgrep scan --config=auto --error . (0 findings) pass from /private/tmp/spawn-1378. make cli-iam-actions was regenerated, and make gen-docs regenerated docs-gen/cleanup.md.

@codecov

codecov Bot commented Oct 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 47.60000% with 131 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../instancerole/instanceroletest/instanceroletest.go 0.00% 115 Missing ⚠️
cmd/cleanup.go 46.66% 8 Missing ⚠️
pkg/instancerole/schedules.go 94.02% 4 Missing ⚠️
pkg/scheduler/types.go 62.50% 3 Missing ⚠️
pkg/instancerole/references.go 96.55% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…mes (#1378)

The per-task role sweep (pkg/instancerole) deleted a role once no instance
held its profile and it was unused for 24h. A schedule stores a
spawn-instance-* profile name in its params and launches with it at every
firing without re-creating it, so an armed reaper or spawn cleanup
--instance-roles would delete a rarely-firing schedule's role and fail its
next firing.

Both callers now collect References from a shared ScheduleSource (the
spawn-schedules table in us-east-1 plus each params object) before the
sweep, and Decide keeps any profile an active, not-run-out schedule names in
defaults.iam_role or a row's iam_role. Whether a schedule counts is
scheduler-handler's own check (ScheduleRecord.FiringAt, now shared). Any
incomplete read fails closed: no role is deleted, the reaper counts the
account in instance_roles_references_unreadable, the CLI refuses. Sweep
refuses References that were not collected.

IAM: dynamodb:Scan on spawn-schedules (us-east-1) and s3:GetObject on
spawn-schedules-*/schedules/* on the reaper's own role (SAM template and
spawn reaper deploy), from pkg/reaperiam.ScheduleReferenceStatements, with
drift gates; the member role is unchanged.
@scttfrdmn
scttfrdmn force-pushed the fix/1378-schedule-referenced-roles branch from 9092aee to 8bbb317 Compare October 28, 2026 18:43
@scttfrdmn
scttfrdmn merged commit a79f4b3 into main Oct 28, 2026
9 checks passed
@scttfrdmn
scttfrdmn deleted the fix/1378-schedule-referenced-roles branch October 28, 2026 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reaper InstanceRoles would delete a spawn-instance-* role that an enabled schedule still names

1 participant