Skip to content

feat: maintain inactive projects through a maintenance worker - #14695

Merged
ChiragAgg5k merged 45 commits into
mainfrom
feat/maintenance-cohorts
Oct 21, 2026
Merged

ChiragAgg5k merged 45 commits into
mainfrom
feat/maintenance-cohorts

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

What

Active projects keep the daily maintenance task, unchanged.

Projects not accessed in 30 days (or never) are split into slots, one per five minutes of _APP_MAINTENANCE_INACTIVE_INTERVAL (default 7d → 2016 slots). Each project keeps the same slot, so every inactive project is maintained once per interval.

Every five minutes the scheduler publishes the current slot; a new maintenance worker reads that slot's projects (~1/2016 of the inactive set) and enqueues their maintenance, holding back while the deletes queue is backed up.

schedule-maintenance  (no DB reads, no queue-size reads; Store\Redis watermark + recover window)
  └─ per occurrence → Maintenance{slot, slots, due, period, region} → v1-maintenance (commit)
worker-maintenance    (1 coroutine: _APP_WORKER_MAX_COROUTINES=1 in its container)
  └─ inactive projects in slot (cutoff = due − 30d) → DeleteMessage(MAINTENANCE) → v1-deletes
     deletes queue ≥ 100 → wait 10s once → still backed up → republish with resume cursor, commit
     message older than one period → skipped (newer one for the slot exists)
     DB error / refused publish → throw (job parked on failed list; slot recurs next cycle)
worker-deletes        (unchanged; skips projects deleted after enqueue)

Backpressure, in Sweep:

$pending = $this->publisherForDeletes->getSize();
if ($pending >= self::BACKLOG) {
    $this->clock->sleep(self::WAIT);
    $pending = $this->publisherForDeletes->getSize();
}

if ($pending >= self::BACKLOG) {
    // same slot, resume where this job stopped
    $this->publisherForMaintenance->enqueue(new MaintenanceMessage(..., pass: $pass, cursor: $cursor));
    return;
}

Why defer instead of fail: on the Redis broker a rejected job is parked on the failed list and never retried automatically (NATS NAKs with backoff instead). Republishing works the same on both, and no job outlives a 10s wait.

Slot ownership:

// integer sequences: range reads on the primary key, cursor = last $sequence
intdiv($sequence, 100) % $slots

// other adapters: cursor = last project ID, one pass per inactive condition
crc32($id) % $slots

Missed occurrences are recovered for one full cycle; the worker drops any the next run for that slot has superseded. Replicas share the Redis claim; one leads.

Runs as

Topology Scheduler Worker
combined inside schedule inside appwrite-worker
separate appwrite-task-scheduler-maintenance (bin/schedule-maintenance) appwrite-worker-maintenance (bin/worker-maintenance)

Config

Variable Default Notes
_APP_MAINTENANCE_INACTIVE_INTERVAL 604800 (7d) Whole seconds; use a multiple of 300. Under 600 gives one slot that reaches every inactive project each run. A non-integer or < 1 value refuses to start.
_APP_MAINTENANCE_QUEUE_NAME v1-maintenance Queue between the scheduler and the maintenance worker.

Also

  • Deletes worker skips maintenance for a project deleted after the message was enqueued.
  • Combined schedule names each loop in its span and logs which one stopped.
  • docker-compose.override.yml: dev builds for the new services and stats-resources.
  • Self-hosting docs: topologies and environment variables list the new scheduler and worker.

Tests

  • Unit: tests/unit/Maintenance (Cycle, Dispatcher, Sweep), tests/unit/Event/Message/MaintenanceTest.php, tests/unit/Platform/Workers/DeletesTest.php, tests/unit/Platform/Tasks/ScheduleTest.php, tests/unit/Schedule/Source/MaintenanceTest.php
  • E2E: tests/e2e/Services/Projects/InactiveProjectMaintenanceTest.php: a backdated project's expired presence row is removed through scheduler → maintenance worker → deletes worker; an active project's row is untouched. CI runs the Projects suite with interval 30 (one slot), so it proves wiring and outcome; unit tests cover slot spreading, deferral and resume.

Related: appwrite-labs/cloud#6628

@luxor-code-review

luxor-code-review Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 2 nitpicks below.

🧹 Nitpicks (2) — 🟢 2 low
  • 🟢 Failed enqueues are invisible in drop accounting (Sweep.php:239) — enqueue() discards failed publishes: when the publisher returns false the project is neither counted nor reported (src/Appwrite/Maintenance/Sweep.php:239).
  • 🟢 Regex assertions in the new cohort e2e test (MaintenanceCohortsTest.php:64) — The new e2e test asserts the trigger output with assertMatchesRegularExpression patterns (tests/e2e/Services/Projects/MaintenanceCohortsTest.php:64).

This PR replaces the monolithic maintenance task with a new src/Appwrite/Maintenance library built around Cadence, Slot, Ticker, Tick, Sweep, Cohort, and Outcome, driven by a rewritten coroutine-based Tasks/Maintenance.php that loops cohorts on a tick schedule and supports a one-shot trigger mode. The sweep walks projects in blocks, partitions them into active/inactive cohorts by an accessedAt cutoff, and enqueues maintenance messages into the deletes queue with a backlog gate and deadline. The Deletes worker gains an empty-project guard for maintenance messages, and a ProjectContext message carries a minimal project attribute subset. The new _APP_MAINTENANCE_INACTIVE_INTERVAL env var is propagated across .env, docker-compose.yml, composeData.ts, variables.php, and docs, with unit tests for the cadence/slot math and an e2e cohort test.

Files Change
src/Appwrite/Maintenance/* New scheduling/sweeping library: cadence math, slot ownership, cohort partitioning, paged sweeps, and backpressured deletes-queue enqueueing
src/Appwrite/Platform/Tasks/Maintenance.php, src/Appwrite/Event/Message/ProjectContext.php Rewritten maintenance task with coroutine cohort loop and trigger mode; slim project context message for workers
src/Appwrite/Platform/Workers/Deletes.php Guards maintenance messages against deleted/empty projects before project-DB access
.env, docker-compose.yml, app/config/variables.php, composeData.ts, console docs Plumb the new _APP_MAINTENANCE_INACTIVE_INTERVAL default (604800) across runtime config and documentation
tests/unit/Maintenance/*, tests/unit/Platform/Workers/DeletesTest.php, tests/e2e/Services/Projects/MaintenanceCohortsTest.php Unit tests for cadence/slot/sweep math and the deletes guard, plus an e2e cohort sweep test

Reviewed commit: 46580cc

@appwrite

appwrite Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

New Console

Project ID: new-console

Sites (1)
Site Status Logs Preview QR
 New Console
new-console
Ready Ready View Logs Preview URL QR Code

Tip

Preview deployments create instant URLs for every branch and commit

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 20, 2026
@ghost

ghost commented Oct 20, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental test setup change matches the Deletes action's required arguments, and no new defect is evident.

Adds a slot-based maintenance pipeline for inactive projects: the scheduler publishes due slots, and a dedicated worker sweeps projects in resumable batches while deferring when the deletes queue is backed up. The change wires the queue, worker, scheduler, and deployment options into combined and separate topologies, documents the configuration, and adds unit and end-to-end coverage. The latest update also supplies the deployment-retention dependency in the deletes worker test setup.

Latest changes: The latest commit updates DeletesTest to pass the deploymentRetention dependency when invoking Deletes::action.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 7
File Change
src/Appwrite/Maintenance/; src/Appwrite/Schedule/Source/Maintenance.php; src/Appwrite/Event/Message/Maintenance.php; src/Appwrite/Event/Publisher/Maintenance.php Adds inactive-project slot calculation, message dispatch, and resumable sweeps with deletes-queue backpressure.
src/Appwrite/Event/Event.php; src/Appwrite/Event/Message/; src/Appwrite/Platform/Workers/Deletes.php Registers maintenance messages and avoids maintenance deletes for projects already removed.
src/Appwrite/Platform/Tasks/; src/Appwrite/Platform/Workers/; app/config/workers.php; app/init/resources.php; app/worker.php; bin/schedule-maintenance; bin/worker-maintenance Wires the maintenance scheduler and worker into platform task, worker, and CLI entry points.
Dockerfile; docker-compose.yml; docker-compose.override.yml; apps/console/src/lib/docs/compose-generator/composeData.ts; .github/ci/e2e.json; .github/workflows/ci.yml Integrates the new services and test coverage into builds, combined and separate deployment configurations, and CI.
app/config/variables.php; .env; apps/console/src/content/docs/advanced/self-hosting/configuration/ Exposes and documents the inactive-maintenance interval, queue name, and deployment topologies.
tests/e2e/Services/Projects/InactiveProjectMaintenanceTest.php; tests/unit/Event/Message/MaintenanceTest.php; tests/unit/Maintenance/; tests/unit/Platform/Tasks/ScheduleTest.php; tests/unit/Platform/Workers/DeletesTest.php; tests/unit/Schedule/Source/MaintenanceTest.php; tests/unit/Workers/JobsTest.php Covers inactive-project cleanup, scheduling and sweep behavior, message contracts, worker setup, and the required deployment-retention dependency.
src/Appwrite/Platform/Workers/Deletes.php Skip maintenance work when its project no longer exists.

Reviewed the commits since 4e4053f · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@pkg-pr-new

pkg-pr-new Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/appwrite/appwrite/@appwrite.io/console@14695

commit: dd8a182

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat/maintenance-cohorts (after).

Metric Before After Change
🚀 Requests/sec 168.9 171.69 ⚪ +1.7%
⏱️ Latency P50 99.89 ms 99.9 ms ⚪ 0%
⏱️ Latency P95 245.99 ms 234.19 ms ⚪ -4.8%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 99.9 234.19 10,887 171.69 -11.8
Account 190.57 350.88 573 9.5 +3.9
TablesDB 96.75 177.44 5,921 95.91 -8.04
Storage 93.17 216.02 2,865 48.15 -29.43
Functions 138.63 273.89 1,528 26.3 -18.66

Top API waits (after)

API request Max wait (ms)
account.name.update 724.27
account.prefs.update 509.9
functions.variables.create 478.18
tablesdb.rows.create 477.38
functions.create 471.04

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

🔵 Tier A · Looks good to merge. Summary

Comment thread src/Appwrite/Maintenance/Sweep.php Resolved
The task only swept projects accessed in the last 30 days, so a project that went idle never had its expired sessions, tokens, presences or logs cleaned again. Projects now split into an active cohort (accessed since the cutoff, every _APP_MAINTENANCE_INTERVAL) and an inactive cohort (older or never accessed, every _APP_MAINTENANCE_INACTIVE_INTERVAL). Each cohort is spread over hourly slots derived from the clock, so every instance agrees on the slot without shared state.

Slots count from _APP_MAINTENANCE_START_TIME on 1970-01-01, not from the next start time after boot, so a restart does not re-phase a cycle. With a boot-relative anchor, daily restarts would keep running the first day of a weekly cycle and never reach the rest. Slot 0 of the daily cycle still lands on the start time every day. The loop never moves its idea of now forward, so a tick never fires before its boundary, even when the clock steps back. A boundary missed behind an overrunning sweep is skipped with a warning and a maintenance.skipped span attribute instead of being caught up.

The inactive cohort waits while the deletes queue is backlogged and drops what it has not reached by the end of its tick. The next cycle starts at a different block, so a dropped tail is not starved. The cohort is read as two filter sets, accessedAt before the cutoff and accessedAt null, so each can use the region and accessedAt index instead of an or(). The active cohort enqueues without waiting, as before. A trigger without parameters enqueues the same jobs as before. --cohort and --project run one cohort or one project for manual checks, and warn when the project is missing or in another region.
The worker reloads the project by the payload ID; a project deleted after enqueue comes back empty, and getProjectDB() maps an empty project to the platform database, so the project cleanups ran there. Sweeping inactive projects queues many more of these jobs, which makes the window wider.
Operators need to know the new variable exists and that the existing interval now governs only recently accessed projects.
#14694 pointed the sites create links at /sites/create, which removed the
route errors the baseline still allowed, so lint:types failed on main.
@ChiragAgg5k
ChiragAgg5k force-pushed the feat/maintenance-cohorts branch from 46580cc to 77d93f3 Compare October 20, 2026 07:42
ghost
ghost previously requested changes Oct 20, 2026

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

🟡 Tier B · 1 blocking finding to address. Summary

Comment thread src/Appwrite/Maintenance/Cohort.php Resolved
@ChiragAgg5k
ChiragAgg5k force-pushed the feat/maintenance-cohorts branch from 77d93f3 to ec2bd34 Compare October 20, 2026 07:51

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

🔵 Tier A · Looks good to merge. Summary

…contract

A distribution may register a databaseFactory resource that is not an Appwrite\Database\Factory, and the maintenance task then dies with a TypeError at boot before it sweeps anything. platform() joins the contract so the task can depend on it, as project creation already does.
The e2e reads the platform and project databases through whichever databaseFactory resource is registered, so typing the concrete Factory failed with a TypeError on a distribution that registers its own. project() joins the contract for it.
Writing a project decodes every subquery filter its collection declares, so the seed failed with Collection not found wherever the projects collection carries a subquery beyond platforms, webhooks and keys. The test now writes and reads projects with APP_PROJECTS_SUBQUERIES skipped, as Sweep does.
The inactive-project cohort moves to its own task on the schedule framework, so the maintenance task goes back to its daily loop over recently accessed projects. The slot, cadence and ticker types existed only to interleave both cohorts inside one loop and are no longer needed.
The combined scheduler reads _APP_MAINTENANCE_INACTIVE_INTERVAL, and the separate topology gets its own appwrite-task-scheduler-maintenance container. The daily maintenance task no longer needs the variable.
_APP_MAINTENANCE_INTERVAL goes back to its original text since the daily task is unchanged; the inactive interval now describes the scheduler's five-minute slices and the backlog skip.
…ject

CI sets _APP_MAINTENANCE_INACTIVE_INTERVAL to 30 so one slice covers every inactive project and the scheduler reaches the backdated project within a minute, without a CLI trigger.
…e scheduler

Projects not accessed in 30 days, or never accessed, are split into slots of sequence blocks, one slot per five-minute moment on an epoch grid, so a full period reaches each project once without a daily burst on the deletes queue. A backlogged queue leaves the tick uncommitted and the scheduler delivers it again; moments already enqueued are skipped on redelivery.
Each test drives the sweep the way the scheduler hands it occurrences and asserts what reached the deletes queue: a full week of slices reaches every inactive project once, the slice and the cutoff follow the due rather than the clock, and a backlogged slice is redelivered rather than dropped or repeated.
A schedule-maintenance task drives a fixed maintenance.inactive source on the Scheduler; the Sweep handler derives the slot and cutoff from the occurrence's due time and throws Backlog while the deletes queue is full so the occurrence is retried instead of committed.
Pins the slot and cutoff to the occurrence's due time, the backlog refusal, and the skip of slices already handled when an occurrence is redelivered.
Adds the bin entry, image and compose service, the interval variable and its docs, and points the e2e job at the renamed inactive-project test with a short interval so the sweep fires within the run.

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

🔵 Tier A · See the inline comments. Summary

Comment thread src/Appwrite/Maintenance/Sweep.php Resolved
…ublished messages

A slice can span many blocks or pages, so checking the queue once per moment let a single slice overshoot the backlog by its whole size. The check now runs before each block or page, and a redelivered moment resumes after the blocks it already enqueued instead of sending them again.

The publisher reports a failed publish by returning false; that was ignored, so the tick committed and the slice waited a full cycle. It now throws, leaving the tick uncommitted.
@ghost
ghost dismissed their stale review October 20, 2026 20:04

The findings that requested changes are resolved. See the summary comment for what is still open.

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

🔵 Tier A · See the inline comments. Summary

Comment thread src/Appwrite/Maintenance/Sweep.php Resolved
…scheduler cannot lag

The scheduler used to query the inactive cohort and publish deletes inside its tick, so a backed-up deletes queue held the tick and its catch-up state open. It now publishes one Maintenance(slot, slots, due, period) message per due moment to v1-maintenance and commits; a refused publish throws so the tick is redelivered.

The new maintenance worker runs the sweep for one slot. It waits in-job while the deletes queue holds 100 or more messages instead of throwing, because a thrown job is parked on the failed list and never retried, which would lose the slot. A refused delete publish still throws. A message more than one cycle old is skipped, since the dispatcher keeps sending during a long backlog and a newer one for the same slot supersedes it.

Backlog and the resume state it needed are removed.
Drives the real scheduler with a memory store and test clock to show each due moment is published once, in order, and that a refused publish leaves the tick uncommitted until the queue accepts it. The worker case resolves its injections by name, so a renamed resource or a dropped region filter fails it.
…er the separate topology

The scheduler now hands each inactive-project slice to a maintenance queue, so separate-topology installs need a container consuming it, and the Projects E2E suite has to run when the worker or its message types change.
…eletes backlog

The backlog wait moved out of the scheduler, so the interval description and the separate topology table now name the maintenance worker. composeData.ts is regenerated from docker-compose.yml, which also picks up compose changes from main that had not been regenerated yet.
…nance queue

Deleted rows alone would also pass if the scheduler kept publishing deletes directly, so the test also requires the worker container and asserts the queue's committed-job counter moved.
The e2e carried a literal queue name because its base predated Event::MAINTENANCE_QUEUE_NAME; reading the constant keeps the test on the queue the worker actually consumes.
…container

The maintenance worker container extends appwrite-worker, which sets _APP_WORKER_MAX_COROUTINES to the pool total, and Jobs let that override every dedicated queue except databases. A dedicated maintenance worker would therefore run 78 sweeps at once against the same deletes backlog. Maintenance is now pinned alongside databases, and the documented pool total counts its coroutine.
…ding the job

The sweep waited in-job for as long as the deletes queue stayed at 100 or more, so a long backlog held a job open through shutdown and redeploys. It now waits 10 seconds once; if the queue is still backed up it sends the slot's message back to the maintenance queue with a pass and cursor at the block or page it had not yet published, and the job commits. The stale check on entry drops a deferred message once its slot's next run has superseded it. Errors still throw and park the job, since the slot recurs every cycle.

The message now carries the region the scheduler runs for, so the worker no longer reads _APP_REGION separately, and a payload without slots, period or region is a PermanentFailure rather than a sweep of defaults. The dispatcher remembers the latest due it published, so a tick redelivered after a refused publish does not resend the moments before it.
…proves

The interval docs now say a backed-up slice is deferred and gives way to its next run after a full interval. The e2e's success counter only shows a worker consumed the maintenance queue, so its message says that and the row outcomes stay the proof of the sweep. The Projects suite also runs when the publisher resources change.
Every message implements Base's toArray and fromArray; #[\Override] makes a renamed or dropped base method fail at compile time.
… deferral

A mutation run showed both survived every test. Seeding old and never-accessed projects contiguously meant the accessedAt cursor sat before every never-accessed project, so carrying it into the next pass skipped nothing; interleaving them exposes the skipped never-2 to never-54. Nothing refused the maintenance republish itself, so a deferral that silently dropped the slot's remaining work went unnoticed.
@ChiragAgg5k ChiragAgg5k changed the title feat: maintain inactive projects on the scheduler feat: maintain inactive projects through a maintenance worker Oct 20, 2026

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

🔵 Tier A · See the inline comments. Summary

The refactor check enforces YieldDataProviderRector on data providers, so the array-returning provider failed the static gate.
…nd scheduler

The worker reads _APP_MAINTENANCE_QUEUE_NAME and the scheduler publishes to it, but neither compose service forwarded it, so a custom maintenance queue was published to and consumed from the default.
…f pinning it in Jobs

Each job re-checks the deletes backlog before every block, so extra coroutines overshoot by at most one block each, and only when several slot messages queue at once. That is a deployment choice, so the separate container sets _APP_WORKER_MAX_COROUTINES=1 and Jobs exempts only databases again. The container gets its own definition because both compose generators replace an extended environment list by index rather than by key.
Workers are covered end to end. SweepTest already holds the slice selection, backlog deferral with its resume cursor, the stale message skip and the refused publish, and InactiveProjectMaintenanceTest drives the worker through the maintenance queue.

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

🔵 Tier A · See the inline comments. Summary

Comment thread docker-compose.yml Resolved
…ombined one

It stopped inheriting restart: unless-stopped when it got its own definition, so a crash left the maintenance queue without a consumer.
…f the console

The injected project is empty for a deleted one, so the span takes the id from the message.

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

🟢 Tier S · Looks good to merge. Summary

@ChiragAgg5k
ChiragAgg5k merged commit d059011 into main Oct 21, 2026
119 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the feat/maintenance-cohorts branch October 21, 2026 09:31
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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.

1 participant