Skip to content

fix(provider): recover and clean up closed leases - #438

Merged
troian merged 5 commits into
mainfrom
fix/closed-lease-recovery
Oct 9, 2026
Merged

troian merged 5 commits into
mainfrom
fix/closed-lease-recovery

Conversation

@chalabi2

@chalabi2 chalabi2 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Closed leases can leave workloads running when closure events are missed or occur while the provider is offline. Check chain state during balance checks and startup, fix funds-monitor shutdown deadlocks, and retry failed Kubernetes cleanup. Only confirmed terminal leases trigger local teardown; uncertain queries do not trigger deletion.

Active and reclaiming leases continue through funds checks and withdrawals. Count both states when estimating the shared escrow burn rate so exhausted reclaiming leases still trigger settlement even when periodic withdrawals are disabled.

Complements akash-network/chain-sdk#361 by recovering existing zombies and handling cleanup failures.

Validation: local unit/race tests for the provider, cluster, and Kubernetes packages passed; scoped lint passed. Regression coverage includes funded and exhausted reclaiming leases, shared escrow, scheduled withdrawals, and query failures. The exhausted-lease test failed before the fix and passes afterward. Earlier testnet validation covered normal closure, missed-event recovery, restart recovery, and active-lease controls; the reclamation withdrawal fix is validated locally. The combined SDK build has not been tested on a live cluster.

AfterFunc timers have no channel to drain. Waiting on that channel after
a timer fires blocks monitor removal and provider shutdown indefinitely.

Signed-off-by: Joseph Chalabi <chalabi.joseph@gmail.com>
Recover missed closure events by querying the monitored lease before
checking funds or withdrawing. Confirmed terminal leases request local
teardown and leave monitoring; active and reclaiming leases remain.

Retry uncertain queries without withdrawing or deleting deployments.

Signed-off-by: Joseph Chalabi <chalabi.joseph@gmail.com>
A persisted manifest can outlive its lease. Retire its funds monitor and
run normal teardown when recovery confirms a terminal lease state.
Register monitoring before recovery starts so fast cleanup cannot be
followed by a stale registration.

Keep missing, unknown, and mismatched lease responses distinct from a
confirmed closure. Active and reclaiming leases remain deployable.

Signed-off-by: Joseph Chalabi <chalabi.joseph@gmail.com>
Propagate manifest deletion failures so persisted deployments cannot be
silently recovered after cleanup reports success. Treat missing objects
as already removed and retain errors from both deletion operations.

Keep the deployment manager and resource reservation while cleanup fails,
and retry instead of retiring the manager after exhausted attempts.

Signed-off-by: Joseph Chalabi <chalabi.joseph@gmail.com>
@chalabi2
chalabi2 requested a review from a team as a code owner September 29, 2026 22:26

@claude claude 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.

⚠️ Code review skipped: your organization has reached its API usage limit, so Code Review can't run right now.

An organization admin can review the limit in your organization's usage and billing settings.

Once the limit resets or is raised, reopen this pull request to trigger a review.

@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: akash-network/provider/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a2922b2e-a10b-4590-a324-d6b8b089a36a
📥 Commits

Reviewing files that changed from the base of the PR and between 56248cc and fec8152.

📒 Files selected for processing (2)
  • balance_checker.go
  • balance_checker_test.go

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


Walkthrough

The balance checker validates lease states before querying deployment escrow, includes active and reclaiming lease costs, and publishes closure events. The deployment manager handles inactive leases through teardown and retries failures. Kubernetes lease teardown preserves errors from both deletion operations.

Changes

Lease lifecycle reconciliation

Layer / File(s) Summary
Balance checker lease reconciliation
balance_checker.go, balance_checker_test.go
The checker validates lease state and ID, includes active and reclaiming lease costs, and publishes closure events for closed or insufficient-funds leases. Tests cover state handling, errors, closure events, and expired timers.
Deployment manager lease-state handling
cluster/manager.go, cluster/manager_recovery_test.go
The manager verifies lease IDs and states. Missing leases and unexpected states return errors distinct from ErrLeaseInactive. Tests cover these state outcomes.
Deployment manager teardown and recovery
cluster/manager.go, cluster/manager_recovery_test.go
The manager starts teardown for inactive leases, publishes monitor-removal events, and retries failed teardown after five seconds. Tests cover recovery and teardown retries.
Kubernetes lease cleanup errors
cluster/kube/client.go, cluster/kube/client_teardown_test.go
TeardownLease treats a missing manifest as non-error and joins namespace and manifest deletion errors. Tests cover retry and combined errors.

Priority: ⬆️ High

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant BalanceChecker
  participant LeaseQuery
  participant EventBus
  BalanceChecker->>LeaseQuery: query lease state
  LeaseQuery-->>BalanceChecker: return lease state
  BalanceChecker->>EventBus: publish closure event for closed or insufficient-funds lease
Loading

Suggested reviewers: troian

Merge Risk: 🔵 Low · up to fec81

The change recovers and cleans up closed leases, and the supplied context shows no concrete defect. It has not been tested together with the companion SDK change, so verify the combined build before or soon after merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to fec81

The change improves cleanup and explicitly preserves active and reclaiming leases. Recovery after interrupted cleanup, endpoint trust, and combined-release validation remain incompletely established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The sensitive outcome is deletion of a monitored or recovered lease's namespace and manifest, plus lease-selected hostname and IP declarations, through the provider's Kubernetes client. A compromised authoritative chain endpoint could supply terminal responses for multiple monitored leases on that provider. Independent tenant control over that endpoint was not established.

Trust Boundaries and Controls

  • observed — The endpoint context originates in operator startup configuration rather than the supplied tests or a tenant request. Before acting, reconciliation validates the returned lease identity and distinguishes terminal, active, reclaiming, missing, erroneous, and unexpected states. The balance checker also rejects a catching-up node. These controls do not independently authenticate the truth of an RPC response.

Resilience and Maintainability Implications

  • inferred — If namespace deletion fails while manifest deletion succeeds, interruption can leave workloads without a discoverable cleanup owner: startup reconstructs managers from manifests, and in-memory retries end with the process. This limitation predates the PR. The head improves failure containment through retained managers and retries, but does not provide durable recovery for that partial-success state.

Hardening Proposals

  • proposed — Preserve durable cleanup ownership until namespace and routing-resource cleanup are confirmed, and validate restart recovery after each partial-success outcome. This would address the existing interruption limitation rather than a verified vulnerability introduced by this PR.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main change: recovering and cleaning up closed leases.
Description check ✅ Passed The description directly explains closed-lease recovery, funds-monitor behavior, Kubernetes cleanup retries, lease-state handling, and validation results.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

I’m a rabbit, counting leases in the moonlit glow
Active and reclaiming funds now join the flow
Closed leases send a notice on their way
Timers rest without a channel drain today
Teardown tries again when cleanup cannot complete
I nibble clover, pleased the states align neat

Comment @coderabbitai help to get the list of available commands.

Run the escrow check for both active and reclaiming leases, counting both
states in the shared account burn rate. Low funds still trigger a withdrawal
so the chain decides whether to close the lease.

Cover funded, exhausted, shared-escrow, scheduled-withdrawal, and query-error
cases, including disabled periodic withdrawals.

Signed-off-by: Joseph Chalabi <chalabi.joseph@gmail.com>
@troian
troian merged commit 112819b into main Oct 9, 2026
13 checks passed
@troian
troian deleted the fix/closed-lease-recovery branch October 9, 2026 14:14
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.

2 participants