Skip to content

fix(network): resolve hostnames natively in coroutines to stop RemoteObject leak - #13952

Merged
ChiragAgg5k merged 2 commits into
mainfrom
fix/public-hostname-dns-leak
Sep 28, 2026
Merged

ChiragAgg5k merged 2 commits into
mainfrom
fix/public-hostname-dns-leak

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

PublicHostname::resolve() now uses Swoole\Coroutine\System::getaddrinfo() when it runs inside a coroutine, instead of dns_get_record(). The fix is for a memory leak that has been OOM-killing worker-webhooks in Cloud nyc3 (13 kills in 7 days; the pod reaches its 1 GiB limit within about 3–12 hours).

Under SWOOLE_HOOK_ALL, Swoole 6.2 hooks dns_get_record() to swoole_dns_get_record(). That function calls swoole_get_default_remote_object_client(), which runs new Swoole\RemoteObject\Client(...) on every call. The client's constructor stores itself in the static Client::$clients array, and nothing removes it. Each lookup therefore keeps a client and its coroutine HTTP client alive, about 140 KiB, until the process exits.

PublicHostname runs before every production webhook delivery (Webhooks::execute). It also runs in the avatars image, favicon and screenshot endpoints. Memory grows with the number of hostname lookups, not with job count, so in production it looked as if the leak depended on the destination. In nyc3 one project's webhook bursts (585 / 1,448 / 544 jobs per 15 min) lined up with memory jumps of +216 / +258 / +66 MiB. The rare Swoole\RemoteObject\Exception: No such file or directory delivery failures come from the same proxy.

getaddrinfo() resolves in Swoole's thread pool, returns every A/AAAA address (the SSRF check still sees all of them), and keeps no memory. It needs a non-empty service argument: with '' it returns false with EAI_SERVICE (-8), so the code passes '80', which only selects a port and doesn't affect which addresses come back. Outside a coroutine the existing dns_get_record() path is unchanged.

Benchmark

Environment: appwrite/base:2.1.0 (PHP 8.5, Swoole 6.2.2), SWOOLE_HOOK_ALL, 30 concurrent coroutines (matching _APP_WORKER_MAX_COROUTINES=30), one new PublicHostname()->isValid('example.com') per simulated delivery, as the webhooks worker does. The heap and RSS deltas are measured after gc_collect_cycles().

Before (main)

Lookups Valid / failed RemoteObject clients retained Heap growth Heap per lookup RSS growth Lookups/s
1000 1020 / 0 +1020 +139.1 MiB +142.4 KiB +65.0 MiB 1783
3000 3000 / 0 +3000 +409.2 MiB +139.7 KiB +190.5 MiB 1866
6000 6000 / 0 +6000 +818.4 MiB +139.7 KiB +380.9 MiB 1859

After (this PR)

Lookups Valid / failed RemoteObject clients retained Heap growth Heap per lookup RSS growth Lookups/s
1000 1020 / 0 +0 +0.0 MiB +0.0 KiB +1.3 MiB 2333
3000 3000 / 0 +0 +0.0 MiB +0.0 KiB +1.4 MiB 2137
6000 6000 / 0 +0 +0.0 MiB +0.0 KiB +1.3 MiB 1975

Before the fix, heap grows linearly at about 140 KiB per lookup and one retained client per call. After it, nothing is retained and throughput is equal or better. Resolution results are identical: every lookup validated in both runs. (The 1000 row shows 1020 because the loop runs in batches of 30.)

Benchmark script
<?php
// Mirrors worker-webhooks: SWOOLE_HOOK_ALL, 30 concurrent coroutines, one PublicHostname check per delivery.
require '/app/vendor/autoload.php';

use Appwrite\Network\Validator\PublicHostname;
use Swoole\Coroutine;
use Swoole\Coroutine\WaitGroup;

$calls = (int) ($argv[1] ?? 3000);
$host = $argv[2] ?? 'example.com';
$concurrency = 30;

Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL]);
Coroutine\run(function () use ($calls, $host, $concurrency) {
    $rss = function (): float {
        preg_match('/VmRSS:\s+(\d+)/', file_get_contents('/proc/self/status'), $m);
        return $m[1] / 1024;
    };
    $clients = function (): int {
        return class_exists(Swoole\RemoteObject\Client::class, false)
            ? count((new ReflectionClass(Swoole\RemoteObject\Client::class))->getStaticPropertyValue('clients'))
            : 0;
    };

    (new PublicHostname())->isValid($host); // warm-up
    gc_collect_cycles();
    $heap0 = memory_get_usage();
    $rss0 = $rss();
    $clients0 = $clients();
    $start = microtime(true);
    $valid = 0;
    $failed = 0;

    for ($done = 0; $done < $calls; $done += $concurrency) {
        $group = new WaitGroup();
        for ($i = 0; $i < $concurrency; $i++) {
            $group->add();
            go(function () use ($group, $host, &$valid, &$failed) {
                try {
                    (new PublicHostname())->isValid($host) ? $valid++ : $failed++;
                } catch (Throwable) {
                    $failed++;
                }
                $group->done();
            });
        }
        $group->wait();
    }

    $elapsed = microtime(true) - $start;
    gc_collect_cycles();
    printf(
        "| %d | %d / %d | %+d | %+.1f MiB | %+.1f KiB | %+.1f MiB | %.0f |\n",
        $calls, $valid, $failed, $clients() - $clients0,
        (memory_get_usage() - $heap0) / 1048576, (memory_get_usage() - $heap0) / $calls / 1024,
        $rss() - $rss0, $calls / $elapsed
    );
});

Run: docker run --rm -v $PWD:/app:ro -v <dir>:/s -w /app --entrypoint php appwrite/base:2.1.0 -d memory_limit=-1 /s/bench.php 6000 example.com

Test Plan

  • New testResolvingInsideCoroutineRetainsNoMemoryPerLookup does 200 lookups inside a hooked coroutine and asserts that less than 4 KiB is retained per lookup (the leak is about 140 KiB). I watched it fail against main's implementation (Failed asserting that 142636.8 is less than 4096.) and pass with the fix.
  • New testResolvesHostnameInsideCoroutine checks that the coroutine path still resolves and rejects a hostname that points at a private address (localhost).
  • Both coroutine tests are marked #[RunInSeparateProcess], so Swoole hook flags never leak into the shared unit process (AGENTS.md).
  • tests/unit/Network/Validators/PublicHostnameTest.php: 40 tests, 91 assertions, all passing in appwrite/base:2.1.0. pint, phpstan and rector --dry-run are clean on the changed files.
  • Not covered: there's no E2E test that runs the webhooks worker long enough to observe RSS. The production check is worker-webhooks memory in Cloud nyc3 after this reaches Cloud through composer update appwrite/server-ce.

Related PRs and Issues

  • Swoole upstream: swoole_get_default_remote_object_client() builds a new client per call, and RemoteObject\Client never removes itself from Client::$clients. That also affects hooked gethostbyaddr, checkdnsrr, getmxrr and mail, none of which Appwrite calls in coroutines today.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? (N/A)

…Object leak

Under SWOOLE_HOOK_ALL, Swoole 6.2 routes dns_get_record() through a
RemoteObject client that is created per call and kept forever in a static
registry, retaining ~140 KiB per lookup. PublicHostname runs on every
webhook delivery, which OOM-killed worker-webhooks repeatedly in cloud nyc3.
@ghost

ghost commented Sep 28, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The new test-isolation and assertion changes introduce no concrete issues requiring a fix.

Hostname resolution inside Swoole coroutines now uses native getaddrinfo() instead of hooked dns_get_record() to avoid retaining RemoteObject clients. Resolution outside coroutines remains unchanged. Unit tests cover private-address rejection and memory growth across repeated coroutine lookups.

Latest changes: The newest commit isolates the coroutine tests in separate processes, allows either private localhost address in the resolution assertion, and measures memory growth per lookup.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 2
File Change
src/Appwrite/Network/Validator/PublicHostname.php Uses coroutine-native IPv4 and IPv6 resolution while retaining the existing non-coroutine path.
tests/unit/Network/Validators/PublicHostnameTest.php Tests coroutine resolution and memory retention, now with process isolation and a per-lookup growth limit.

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

@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

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Changes hostname resolution in network validation.

The PR appears safe to merge; no new actionable issue remains from the changes since the previous review.

Summary

The PR uses Swoole’s native address lookup inside coroutines to avoid the reported RemoteObject retention. Since the previous review, it isolates both coroutine tests, relaxes the loopback-address assertion, and changes the memory assertion to a per-lookup threshold.

Reviews (2) · Last reviewed commit: "test(network): isolate coroutine resolve..."

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/public-hostname-dns-leak (after).

Metric Before After Change
🚀 Requests/sec 190.44 188.97 ⚪ -0.8%
⏱️ Latency P50 90.09 ms 90.61 ms ⚪ +0.6%
⏱️ Latency P95 217.97 ms 217.48 ms ⚪ -0.2%
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 90.61 217.48 11,970 188.97 -0.49
Account 181.8 321.72 630 10.41 -35.06
TablesDB 87.56 172.45 6,510 105.24 +5.67
Storage 82.92 183.68 3,150 52.5 +4.65
Functions 128.71 267.98 1,680 28.63 -1.98

Top API waits (after)

API request Max wait (ms)
account.name.update 603.63
account.prefs.update 475.34
functions.create 408.31
tablesdb.rows.increment 402.35
functions.variables.update 386.57

AGENTS.md forbids Swoole coroutine work in the shared unit process, and the exact loopback address depends on the host resolver configuration. Bound the leak per lookup so allocator noise cannot fail the test.
@ChiragAgg5k
ChiragAgg5k merged commit 050cc4c into main Sep 28, 2026
51 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/public-hostname-dns-leak branch September 28, 2026 19:27
@JoshiJoshiJoshi

Copy link
Copy Markdown

An additional data point from 2.3.0 (released before this fix), self-hosted, _APP_ENV=production, Swoole 6.2.2, default open-files limit of 1024:

Besides the memory growth, every webhook delivery keeps one AF_UNIX socket to /root/.swoole/remote-object-server.sock open in the webhooks worker process. The number of open file descriptors grows by exactly one per delivery (10 → 212 → 412 → … → 1,024 over 1,000 deliveries). After roughly 1,000 deliveries the worker hits the limit, and from then on:

  • every delivery fails with Swoole\RemoteObject\Exception: No file descriptors available,
  • the same worker can no longer resolve hosts or reach Postgres (could not translate host name "postgresql", Class "Utopia\Client\Exception\NetworkException" not found because the autoloader cannot open files),
  • the webhook stays enabled with attempts = 0, because the failure cannot be written either – so nothing in the console shows that deliveries stopped.

Only restarting the worker recovers. On 2.3.0 this happens long before the memory limit, after a single burst of ~1,000 events. It may be worth a note in the release notes or a backport to 2.3.x.

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.

3 participants