#!/usr/bin/env python3
"""Gives the SDK inside customer containers gRPC's normal connect timeout instead of 200 ms.

The SDK sets grpc.min_reconnect_backoff_ms to 200, and gRPC also uses that value as the time one connection
attempt may take. From a rented machine a TCP connect to the gateway takes 29 ms on some flows and 213 ms on
others, so about half of first attempts time out, and in a live test 9 of 10 fresh channels then stayed
failed. An endpoint in that state answers every request with a 503 after six minutes. See
forge-gpu/docs/gpu-run-2026-10.md. klio_compute/_connect.py fixes the same line for the CLI, but it does not
run inside containers, where the SDK comes from the worker image.

Exits non-zero if the line is not there exactly once, so a beta9 upgrade cannot silently lose this.
"""
import sys

ORIGINAL = '("grpc.min_reconnect_backoff_ms", int(RECOVERY_INITIAL_DELAY * 1000)),'
PATCHED = '("grpc.min_reconnect_backoff_ms", 20_000),  # Klio: see deploy/gcp/worker/patch_sdk_connect.py'


def patch(source):
    if source.count(ORIGINAL) != 1:
        raise ValueError(f"expected the line once, found it {source.count(ORIGINAL)} times")
    return source.replace(ORIGINAL, PATCHED)


def main(path):
    with open(path) as handle:
        source = handle.read()
    with open(path, "w") as handle:
        handle.write(patch(source))


if __name__ == "__main__":
    main(sys.argv[1])
