Skip to content

Fix correctness bugs, add tests, validate manifests before they ship - #4

Merged
krs2k merged 63 commits into
masterfrom
fix/correctness-and-tests
Oct 5, 2026
Merged

krs2k merged 63 commits into
masterfrom
fix/correctness-and-tests

Conversation

@krs2k

@krs2k krs2k commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR fixes correctness bugs across ct, adds tests, and takes the first step of a new direction: ct as a Helm replacement that people and AI coding agents can both drive. Every problem should fail at render time, with the .ct line that caused it. The direction, a Helm gap analysis and a phased roadmap are in docs/rfc/ai-friendly-helm-replacement.md.

Merge cloudticon/k8s#1 first: the new validation rejects the invalid objects that configMap(), secret() and namespace() currently produce on cloudticon/k8s@master (see Breaking changes).

Bugs fixed

Releases

  • Prune deleted live objects. ct apply deleted the object it had just applied whenever the namespace went from implicit to explicit, or the apiVersion changed (HPA autoscaling/v1 → v2). Prune now compares objects by API group, kind, effective namespace and name. Reproduced on a kind cluster before the fix.
  • Failed applies leaked objects. Objects created by an apply that failed halfway were missing from the inventory, so they were never pruned.
  • Wrong order. Apply and delete followed registration order. Apply now follows Helm's install order (by API group and kind), waits for CRDs created in the same run, and delete runs in reverse.
  • ct list:
    • showed every ConfigMap of a release as an extra release;
    • printed ANSI codes into pipes;
    • -o table didn't work.

Rendering

  • Empty objects and arrays were dropped. A NetworkPolicy ingress: [{}] (allow-all) became deny-all, and a CR's required spec: {} disappeared. Now only null/undefined is dropped, like JSON.stringify.
  • -n put a namespace on cluster-scoped kinds.
  • A shared JS object leaked a namespace into another object.
  • Duplicate objects silently overwrote each other.
  • YAML used 4-space indentation.

ct init overwrote an existing main.ct/values.json and scaffolded an invalid Deployment. The README examples were invalid too.

Values

  • --set didn't work without a values file.
  • An empty values.yaml combined with --set panicked.
  • --set tag=1.10 became the number 1.1.
  • Repeated -f files didn't merge, and dots in keys couldn't be escaped. --set-string is new.

Bundling and runtime

  • async/await detection had false positives on comments, strings and names like "async-worker".
  • Errors had no source positions and were printed twice.
  • Endless loops or recursion hung ct.

Cache

  • A failed download left a half-written entry that was trusted forever.
  • A crafted package version could make --no-cache delete a directory outside ~/.ct/cache.
  • --no-cache didn't refresh imported packages.
  • git could hang on a password prompt.
  • Custom git hosts didn't work.

Build

  • The module path was github.com/cloudticon/ctts, so go install github.com/cloudticon/ct/... failed.
  • CI used Go 1.22 against go 1.25 in go.mod.
  • There was no linux/arm64 release, although install.sh expects one.
  • Release binaries reported version dev.

ct dev (31 fixes; a selection):

  • Terminal, sync and logs failed on pods with a sidecar (Istio): no container was named.
  • Port-forward retried in a tight loop and leaked goroutines.
  • Sync lost files changed during the initial sync and never followed a replaced pod.
  • A crashed container was taken for a user exit.
  • SIGTERM left the TTY in raw mode.
  • Log streams replayed the whole log on reconnect.
  • .env parsing had several gaps, and env("X", false) returned a truthy string.

New: validation-first, errors that point at code

  • pkg/validate checks every rendered object before output or apply:

    • strict decoding of built-in kinds into the client-go types: unknown fields, wrong types, wrong or removed apiVersions;
    • a "did you mean" suggestion for misspelled kinds;
    • the admission rules the API server enforces: names, labels, finalizers, selector vs. template labels, containers, ports, volumes, Job restartPolicy, Services, Ingress, Secrets, CRD names.

    It is on by default; --validate=false skips it.

  • pkg/diag: bundles carry source maps, and ct records where each object was registered. Diagnostics read main.ct:3:11: Deployment "web": spec.template.metadata.labels: .... --error-format json prints stable codes, file, line, resource, field path and hint.

  • API server warnings are printed once each.

  • ct init writes an AGENTS.md for coding agents.

Breaking changes

  • Validation is on by default. Objects the API server would reject now fail ct template and ct apply. This includes configMap()/secret()/namespace() from the current cloudticon/k8s@master (core/v1); merge Fix core apiVersion, top-level fields and cluster scope in generated resources k8s#1 first.
  • Output order and format. ct template prints objects in Helm install order instead of registration order, and YAML uses 2-space indentation.
  • Empty objects and arrays are kept, exactly as written.
  • Duplicates are an error.
  • Release names must be DNS-1123 labels.
  • The Go module path is github.com/cloudticon/ct.

Test plan

  • go test -race ./... passes; coverage went from 76.8% to 86.0%. gofmt and vet are clean, and ct builds for all 6 CI targets.
  • An independent review of the first version of this branch found 13 bugs. All are fixed, with tests.
  • Kind cluster (Kubernetes 1.34):
    • apply with a CR, its CRD and a Namespace registered in the wrong order;
    • prune, recovery after a failed apply, delete order, list, --create-namespace;
    • the validation gate, and API server warnings;
    • ct dev: sync, live edits, port-forward, logs, pod replacement, Ctrl+C and --delete.
  • Real factory code (devticon/ct, k8s-factories) renders with no false positives.

🤖 Generated with Claude Code

krs2k and others added 30 commits October 5, 2026 07:40
The module path still said github.com/cloudticon/ctts while the repo
and README advertise github.com/cloudticon/ct, so
`go install github.com/cloudticon/ct/cmd/ct@latest` failed.

CI: use the Go version from go.mod (was 1.22 vs go 1.25 in go.mod),
add gofmt/vet/race checks, build linux/arm64 (install.sh already
expects it) and stamp the version into release binaries.

Also gofmt the tree and fix the README install URL typo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nds, Helm order

Rendering dropped every empty object, so `emptyDir: {}` (also emitted by
k8s-factories vol.emptyDir()), `podSelector: {}` and NetworkPolicy
`ingress: [{}]` disappeared, producing invalid or semantically different
objects. Now only null/undefined values are removed, plus objects and
arrays that became empty because of that, and empty arrays.

The cloudticon/k8s library no longer marks cluster-scoped kinds, so
`-n prod` injected a namespace into Namespace, ClusterRole, etc. The
engine now also knows the well-known cluster-scoped kinds.

New shared package pkg/manifest holds these pure transforms plus:
- duplicate detection: registering the same object twice is now an
  error instead of a silent last-write-wins,
- Helm install order for `ct template` output and `ct apply`
  (Namespaces and CRDs first), and apply waits for the API server to
  serve kinds whose CRD is applied in the same run.

YAML output uses the conventional 2-space indent, and serializing an
empty object no longer panics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… -f merge

- --set/--set-string work without a values file (was an error).
- An empty or comment-only values.yaml (or JSON null) plus --set
  panicked writing into a nil map.
- --set only types numbers that round-trip, so image tags like 1.10 or
  1.0 and zero-padded 0123 stay strings instead of becoming 1.1, 1, 123.
- New --set-string for values that must stay strings.
- Backslash escapes dots in --set keys, e.g.
  annotations.nginx\.ingress\.kubernetes\.io/rewrite-target=/.
- -f/--values is repeatable; files deep-merge left to right like Helm.
  A single -f still replaces the auto-detected values file.
- A relative -f that doesn't exist in the working directory is looked up
  in the project directory, so remote sources can pick their own
  values-prod.yaml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New pkg/diag: every bundle, runtime and render error is a diagnostic
with a stable code, file:line:column in the user's .ct sources, the
offending source line, a stack, and a hint. `--error-format json`
prints them as {"errors": [...]} so tools and AI agents can act on them
without scraping text.

- Bundles carry an inline source map, so goja stack traces point at
  main.ct/lib/*.ct lines instead of the generated bundle. Package files
  show as github.com/owner/repo@version/path.
- __ct_resources.push records where each object was registered, so
  duplicate-resource errors (and later validation) name the exact call.
- async/await detection uses esbuild's parser instead of a regex: words
  in comments, strings and names like "async-worker" no longer fail
  the build, and real uses get a precise position.
- Relative imports resolve .ct files without an extension.
- Unresolved imports get hints (npm isn't supported; paths are relative).
- Rendering has a 1 minute timeout, so endless loops fail with a stack
  instead of hanging.
- Errors were printed twice (cobra and main); now once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New pkg/validate checks every rendered object the way the API server
does on admission, so problems surface at render time with the .ct line
that produced them instead of on the cluster (or silently in Argo CD):

- built-in kinds are decoded strictly into client-go types: unknown
  fields (e.g. spec.image on a Deployment, spec on a ConfigMap) and wrong
  types are reported with their field path, all in one run;
- wrong apiVersions for built-in kinds ("core/v1", "apps/v2") and
  removed APIs (extensions/v1beta1 Ingress, batch/v1beta1 CronJob, ...)
  name the apiVersion to use; custom resources such as Knative's
  serving.knative.dev/v1 Service are left alone;
- names, namespaces, labels and annotations follow the API's rules;
- admission rules strict decoding can't see: selector must match the
  template labels, containers need name and image, volumes need exactly
  one source, volumeMounts must reference a volume, Jobs need
  restartPolicy OnFailure/Never, CronJob names are at most 52 chars,
  Services need ports, Ingress paths need pathType, Secret data must be
  base64, TLS secrets need tls.crt/tls.key, CRD names are plural.group.

Diagnostics carry the user-code call chain that registered the object
(helpers and their callers; package frames are skipped).

Validation is on by default for ct template and ct apply;
--validate=false skips it (e.g. for a cluster newer than this build).
Release names must be DNS-1123 labels, since they become label values
and the inventory ConfigMap name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ct init silently overwrote an existing main.ct and values.json. It now
refuses when any of its files exist (nothing is written) unless --force.

The scaffold used deployment({ image, replicas, ports }), which the
cloudticon/k8s primitives turn into an invalid Deployment (no selector or
template). It now uses webApp from k8s-factories, which renders a valid
Deployment and Service, so the first ct template passes validation.

ct init also writes AGENTS.md: the commands and rules an AI coding agent
needs to work on the project (render/validate loop, JSON errors, values
layering, URL imports, no async).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Package downloads are cloned into a temp dir next to the cache entry
  and renamed into place. A failed or interrupted clone used to leave a
  half-copied directory that every later run trusted.
- --no-cache now also re-downloads imported packages (once per run), so
  branch imports like @master can be refreshed; before it only refreshed
  a remote source.
- git runs with GIT_TERMINAL_PROMPT=0: a private repo without credentials
  fails fast instead of hanging on a prompt (CI, AI agents).
- A version marks the end of a package path, and hosts other than
  github.com/gitlab.com/bitbucket.org accept vanity (host/repo) and
  nested-group (host/group/sub/repo) paths. Custom hosts used to be split
  as host/repo by the resolver but rejected by the cache.
- packages.SyncPackages followed only https:// imports and .ts files; it
  now handles github.com/... imports and .ct files too.
- ct types quoted no keys, so values like annotation keys produced
  invalid .d.ts files.
- ct list -o table works, as the README documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
applyRelease saved the inventory only after a fully successful apply. If
an apply failed halfway, objects it had already created were untracked,
so removing them from the code later never pruned them and ct delete
missed them. Upgrades now record old+new refs before applying; the
final save narrows it back to the new set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A factory library imported from outside the project (a local checkout
or a monorepo path) counted as user code, so diagnostics pointed at its
__ct_resources.push line instead of the main.ct call. Error locations
now prefer frames inside the project directory, then frames outside
imported packages, then the innermost frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
README: examples now match the cloudticon/k8s API (the old ones used
deployment({ image, ports }), which renders an invalid Deployment),
document validation, diagnostics and --error-format json, values
layering and --set-string, imports, globals, release behavior, and the
updated CLI and source layout.

docs/rfc/ai-friendly-helm-replacement.md sets the direction: ct as a
Helm replacement that AI agents can drive. It covers principles, what
this branch delivers, a Helm gap analysis, a phased roadmap with
acceptance criteria, ecosystem fixes and open questions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found while running ct apply/delete against a kind cluster:

- delete removed objects in inventory (install) order, so a CRD went
  before its custom resources, which then disappeared through garbage
  collection rather than being deleted. Custom resources now go first,
  then known kinds in reverse Helm install order, then Namespaces and the
  inventory.
- ct list printed ANSI color codes into pipes and files. The table is
  styled only for a terminal, and NO_COLOR is honored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every ConfigMap a release renders gets the managed-by=ct and instance
labels, so ct list showed each such ConfigMap as an extra release with
0 resources (seen on a kind cluster).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- ct apply into a namespace that doesn't exist now suggests
  --create-namespace or a Namespace object.
- 'expected a string, got number' (e.g. --set a=2 into ConfigMap data)
  suggests String(...), quoting, or --set-string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous rule also dropped objects and arrays that became empty
after null removal, and all empty arrays. That still changed meaning:
NetworkPolicy egress: [{ to: undefined }] (allow all, as JSON.stringify
renders it) collapsed to no rules (deny all), a CRD default: [] vanished,
and a CR's required spec: {} was dropped.

Now only keys holding null/undefined and null array items are removed;
everything else is rendered as written. Real factories (k8s-factories,
devticon/ct) produce no extra noise from this.

Found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- goja exports a JS object used twice as one Go map, and Values maps are
  shared with the script. A metadata object reused by a ClusterRole and a
  Role got the Role's namespace, and cleaning mutated Values. Rendered
  objects are now deep-copied on export (cycles are rejected).
- Objects without a name (generateName) were all reported as duplicates
  of each other, and --validate=false couldn't bypass it. They are now
  left to validation's missing-name check.
- Install/delete order looked at the kind only, so a custom resource
  named like a built-in (Calico's NetworkPolicy) was applied before its
  CRD. Only Kubernetes' own API groups get built-in ranks now.

Found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
False positives (all accepted by the API server):
- a volume without a source (defaulted to emptyDir);
- StatefulSet containers mounting volumeClaimTemplates;
- Service targetPort "" (defaulted to port) and clusterIPs: [None]
  without ports (headless);
- CertificateSigningRequest names such as User:Alice.

Missed problems:
- a misspelled kind in a Kubernetes API group (apps/v1 Deploymnet,
  v1 Configmap) was treated as a custom resource; it is now reported
  with a did-you-mean suggestion;
- a fractional number in an integer field (replicas: 1.5) stopped
  decoding, hiding later errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A crafted import such as https://github.com/o/r@x/../../../../tmp/dir
made the cache key escape ~/.ct/cache, so --no-cache (which now
invalidates imported packages) removed an arbitrary directory, and a
download could be renamed into one. Package URLs now get their host,
path segments and version checked (git refs may contain '/', never '..'
or a leading '-'), branch names with '/' map to a single cache
directory, and cache paths are verified to stay inside the cache. Import
sub-paths can't climb out of their package either.

Found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Only esbuild's own messages for async constructs count as async
  errors; a syntax error near a name like asyncWorker was reported as
  async-not-supported, hiding the real error.
- Source paths are made relative to the project before checking the
  package cache. A remote source lives inside the cache, so its own files
  were shown as packages and errors pointed at library code.
- --no-cache: invalidating and re-downloading happen under one lock, and
  the remote source re-downloaded by the CLI is marked fresh, so a source
  importing its own repository no longer deletes itself mid-bundle.
- An existing local directory always counts as a local source, even if
  its first segment looks like a host (my.app/deploy).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…string

- Endless recursion grew until the 1-minute timeout and produced a
  diagnostic with hundreds of thousands of frames (8 MB at 3s). Goja's
  call stack is now capped at 10000 frames, so it fails at once with
  'Maximum call stack size exceeded', and diagnostics show at most 20
  frames.
- throw Object.create(null) made converting the exception to text panic.
- --set x=NaN/+Inf/-Inf became floats that JSON can't encode; they now
  stay strings.

Found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
computeOrphaned compared apiVersion|kind|namespace|name exactly. The
same object under another version (HPA autoscaling/v1 -> v2) or with a
defaulted vs explicit namespace (ct apply rel . then ct apply rel . -n
default) looked like a removed object, so ct applied it and then deleted
it. Reproduced on a kind cluster: the ConfigMap was gone after the
second apply.

Refs are now compared by API group, kind, effective namespace (empty
means the release namespace; none for cluster-scoped kinds) and name.

This bug predates this branch; found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- With --error-format json, progress lines ("applied ...", "deleted
  ...") went to stderr too, so it wasn't valid JSON. They are dropped
  in JSON mode.
- ct init no longer refuses because of an existing AGENTS.md (it may be
  the repository's own) and never overwrites it, even with --force.
- ct init [dir] accepts the directory as an argument; ct init foo used
  to ignore foo and initialize the current directory.
- ct types renders with the same timeout as ct template.

Found by review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… RFC

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PatchResources fell back to the FIRST container whenever the `container`
option did not match any container, so a typo (or naming an init
container) silently replaced the image/command of e.g. a sidecar.
Unknown names now leave the containers untouched, and Run validates the
option up front via ResolveContainers, failing with the list of
available containers. ResolveContainers also fills in the default (the
first container) so later stages can address the same container.

Overriding `command` kept the workload's `args`, so a typical dev
command such as ["sleep", "infinity"] ran as `sleep infinity --port
8080` and crash-looped. dev.ct has no args option, so the dev command is
the whole command line and args are removed.

The patched container is also marked as the pod's default container
(kubectl.kubernetes.io/default-container) so clients that do not name a
container (log streaming, kubectl) pick it in multi-container pods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The `container` option only steered the workload patch. The terminal
exec and every sync exec (mkdir, tar, rm) were sent without a container
name, so they ran in whatever the API server picked. For pods with more
than one container - e.g. any pod with an injected Istio/Linkerd
sidecar - the API server rejects such requests outright:

  initial sync failed: creating remote directory /app: a container
  name must be specified for pod web-x, choose one of: [app istio-proxy]

and the session gave up after five attempts. SyncRule gains a Container
field and the runner passes the target's (resolved) container to both
the syncer and the terminal.

The k8stest fake now validates ExecOpts.Container against
FakePod.Containers like the API server does, so tests can cover this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Log streaming (and the crash-log fetch in waitForPod) never named a
container, and the Cluster port has no container parameter for logs.
For any pod with more than one container - typically an injected
Istio/Linkerd sidecar - the API server rejects such requests ("a
container name must be specified for pod ..."), so `ct dev` in log mode
printed "failed to open stream ... reconnecting" every two seconds and
never showed a log line. Exec calls without a container had the same
problem for targets that rely on an explicit selector.

When no container is given, the live adapter now resolves the pod's
default container like kubectl: the kubectl.kubernetes.io/default-
container annotation (set by meshes and, since the previous commits, by
ct dev's workload patch), else the first container. An explicit
container still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Syncer.RunWithReady signalled "ready" from a defer even when the initial
sync failed, and the runner's feature wrapper only reported the error
and cancelled the session after RunWithReady had returned. The waiter
therefore usually saw "all syncs ready" first, printed "initial sync
complete" and started the interactive terminal on top of a failed sync
(it was torn down a moment later and, for non-exit-code errors, the
whole session was retried five times).

RunWithReady now reports the outcome: ready(nil) after a successful
initial sync, ready(err) with the failure otherwise. The runner records
the failure (and cancels the session) before releasing the waiter, and
the waiter re-checks the session context after the syncs are ready.

Also make waitFeatures deterministic: it selected between the error
channel and a "done" channel, and when both were ready (features that
already finished) Go picks at random, so the first feature error could
be dropped and the session reported as a clean exit. It now waits for
all features and then drains the error channel. Errors returned after
the session was asked to stop are no longer reported as failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The syncer created its watcher only after the initial sync had
finished, and the fsnotify watches were registered asynchronously after
Watch returned. A file saved while the initial tar was being uploaded
was in neither the snapshot nor the watch, so it was never synced (in
polling mode it ended up in the baseline snapshot, same result). The
same start-up race made TestWatcherFsnotify_DebouncesRapidChanges flaky.

Watch now sets the watcher up synchronously and returns an error, and
the syncer starts it before taking the initial snapshot; anything that
changes during the initial sync is delivered as an incremental batch.

Watcher failures used to be silent: if fsnotify could not be created
(inotify instance limit, EMFILE on macOS) the channel was closed and
Syncer.Run returned nil, i.e. sync just stopped; directories that could
not be watched because the watch limit was exhausted were skipped. Both
are now errors with a hint (exclude big directories, raise the inotify
limits or use polling: true).

The fsnotify loop no longer blocks on the receiver: while a sync is in
flight it keeps merging events instead of letting them pile up in the
kernel queue, a queue overflow triggers a rescan instead of being
ignored, and a continuous stream of events can delay a flush by at most
two seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In fsnotify mode a directory moved or extracted into the synced tree
(mv, git checkout of another branch, unzip, cp -r) produces a single
Create event for the directory and none for the files already inside
it. The batch then only held the directory path, which the tar writer
skips, so none of those files ever reached the pod.

When a new directory is detected, the watcher now reports every
non-excluded file below it as created while it registers the watches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
krs2k and others added 28 commits October 5, 2026 09:01
runDev passed cmd.Context() straight through and nothing installed a
signal handler, so the context the whole dev session is built around
was never cancelled in production: the graceful shutdown path (stop
port-forwards and syncs, restore the terminal, return nil) was dead
code, and a SIGTERM while the interactive terminal was attached killed
the process with the local TTY left in raw mode.

runDev now derives a context that is cancelled on SIGINT/SIGTERM; after
the first signal the default behavior is restored so a second Ctrl+C
still kills a session that does not stop.

Because Ctrl+C no longer kills the process, a prompt() in dev.ct that
is blocked on stdin now gives up when the context is cancelled (Run
returns "interrupted") instead of swallowing the first Ctrl+C.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parsePortRules accepted 0, negative and >65535 ports, and two rules
could forward the same local port. Neither can ever work: client-go
rejects the port spec or the second listener fails, and the port
forwarder retried such errors forever. Both are now reported up front
naming the target and rule (e.g. `local port 8080 is forwarded twice
(targets "web" and "api")`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
portForward retried every forwardPorts error immediately, forever. For
errors a reconnect cannot fix this became a busy loop that opened a new
SPDY connection to the API server on every iteration and logged a line
each time (invisible in terminal mode, where logs are silenced):

- a local port already in use ("unable to listen on any of the
  requested ports"), e.g. a second ct dev session or a local database;
- RBAC refusing pods/portforward ("... is forbidden").

Those now end the feature with an actionable error. Other errors
(connection lost, pod replaced) are retried with exponential backoff
(1s up to 10s, reset after a forward stayed up for 10s), interruptible
by ctx. The backoff also bounds a connection leak in apimachinery: the
SPDY round tripper never closes the TCP connection of a refused
upgrade, so the old loop could exhaust file descriptors.

forwardPorts leaked two goroutines per failed attempt (one waiting for
a ready signal that never came, one waiting for ctx to close the stop
channel); both now end when ForwardPorts returns. client-go's per-port
listen errors ("Unable to listen on port 8080") went to io.Discard and
are now logged, so a partially working forward is visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Log streaming read lines with bufio.Scanner, whose default limit is
64 KiB. A single longer line (JSON logs, stack traces, dumped payloads)
made the scanner fail with "token too long"; the stream was treated as
interrupted and reconnected - and every reconnect requested the pod's
entire log again, hit the same line and failed again, replaying the
whole history every two seconds, forever.

Lines are now read with a bufio.Reader (any length). Logs are requested
with kubelet timestamps; the timestamp of the last printed line is
tracked, a reconnect to the same pod asks for SinceTime and lines that
were already printed are dropped, so dropped connections no longer
duplicate output. Timestamps are stripped before printing and the \r of
TTY containers (ct dev enables tty) is removed.

The reconnect wait (also used after a clean end of stream now, so an
immediately ending stream cannot spin) is interruptible by ctx instead
of a plain two-second sleep.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
waitForPod only diagnosed container problems of Running pods. Image
pull errors (ErrImagePull/ImagePullBackOff/InvalidImageName), missing
secrets or config keys (CreateContainerConfigError) and unschedulable
pods all keep the pod Pending, so e.g. a typo in the dev `image:`
override left the spinner at "waiting for pod web..." forever without
a hint. Pending pods are now checked on the initial list and on every
watch event, and each distinct problem is printed once, including the
kubelet/scheduler message, e.g.

  [wait] pod "web-1": container "app" is in ImagePullBackOff: Back-off
  pulling image "web:dve" (still waiting)

The API server closes watches routinely (server-side timeout after
30-60 minutes, restarts). That used to abort the wait with "pod watch
channel closed before a running pod appeared", which ended the dev
feature (and for port-forward the whole log-mode session) of anyone
waiting for a slow image pull or scale-up. waitForPod now lists and
watches again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port-forward, log streaming, sync (which now re-checks its pod
periodically) and the session itself each call waitForPod for the same
pod. During a crash loop every one of them fetched and printed the same
previous-container logs every five seconds. A given pod/problem pair is
now reported at most every 30 seconds across all waiters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MakePromptFn created a new bufio.Scanner for every prompt. A scanner
reads ahead, so with piped input (scripts, CI, AI agents answering
prompts) the first prompt swallowed the answers to all later ones and
they got "".

At EOF the prompt also returned "" and cached it: a single run without
a terminal (stdin closed or /dev/null) permanently answered the prompt
with an empty string - e.g. namespace "dev-" - and later interactive
runs never asked again. A missing answer is now an error explaining how
to answer non-interactively (pipe it, or add it to the cache file); a
last line without a trailing newline still counts as an answer.

Also:
- the "[cached: ...]" line names the cache file, the only way to change
  a cached answer;
- a cache file containing `null` no longer panics on the next answer
  (assignment to a nil map);
- answers can be secrets, so the cache is written 0600 in a 0700
  directory instead of world-readable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
env(name, default) only coerced numbers:

- a boolean default was ignored, so env("DEBUG", false) with DEBUG=false
  returned the string "false" - truthy in JS, so `if (env("DEBUG",
  false))` took the debug branch;
- a value that did not parse as a number was returned as a string, and
  only failed much later with an unrelated-looking error such as
  `ports[0][0]: expected number, got string`;
- "8080.5" with an integer default and " 8080 " (padding from the shell
  environment) were returned as strings too.

Numbers now parse as integers or decimals (trimmed), booleans accept
true/false, 1/0, yes/no, on/off, and anything else is an error naming
the variable and its value. An empty value with a number/boolean
default falls back to the default (`PORT=` placeholders in .env files);
an empty string with a string default stays empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
LoadEnvFile mis-read common .env syntax, so env() in dev.ct silently got
the wrong value or nothing:

- `export FOO=bar` (files that are also sourced by shells) stored the
  key "export FOO";
- `PORT=3000 # web port` kept the comment in the value, which then
  failed number coercion;
- `KEY="value" # comment` was not unquoted at all;
- escapes in double quotes (`\"`, `\n` for multi-line secrets) were kept
  verbatim;
- a UTF-8 byte order mark (Windows editors) became part of the first
  key;
- a line over 64 KiB (certificates, base64 blobs) failed the whole file
  with "bufio.Scanner: token too long";
- `=value` produced an empty key.

Values now follow the usual dotenv rules: optional `export ` prefix,
" #" starts a comment in unquoted values (a # inside a value such as
COLOR=#fff stays), quoted values end at the closing quote, double
quotes interpret \n \r \t \" \\ (other backslashes, e.g. Windows paths,
are kept), single quotes are literal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dev() and config() silently dropped options of the wrong shape, so the
session started without the feature and gave no hint why:

- `command: "npm run dev"` (a string, not an array) kept the workload's
  original command;
- DevSpace-style `sync: ["./:/app"]` or `env: ["FOO=bar"]` entries were
  skipped, `ports: 3000` meant no port-forward, and
  `exclude: "node_modules"` synced node_modules;
- a null/undefined selector value became the label value "<nil>", so
  ct dev waited for a matching pod forever, and `selector: {}` matched
  every pod in the namespace;
- {name, value: undefined} env entries set the variable to "<nil>";
- probes/replicas/polling of the wrong type fell back to defaults;
- config() with an empty, undefined or non-string namespace (e.g.
  built from an unset env var) fell back to the kubeconfig's default
  namespace, applying and pruning dev resources there.

All of these are now errors naming the target and the option, e.g.
`target "web": command must be an array, got string`. Undefined/null
options still mean "not set", and a missing env value is "" as in
Kubernetes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Relative sync sources (`from: "./src"`) were resolved by the syncer
against the process working directory instead of RunOpts.Dir, the
directory dev.ct was loaded from. They only agreed because the CLI
happens to run in that directory.

A source that does not exist or is a file (e.g. `from:
"./package.json"`) was only noticed after the resources had been
applied, by the syncer, as "stat ...: no such file or directory" or
"watch root must be a directory" - without saying which target/rule -
and in terminal mode after five session attempts.

Run now resolves every sync source against the project directory and
checks it is a directory before touching the cluster, e.g.
`target "web": sync[0].from "./package.json" is not a directory`.

Adds end-to-end Run tests against the fake cluster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
To keep client-go/klog output from drawing over the interactive
terminal, runDevSession replaced the global os.Stderr with /dev/null
while the dev features were already running. client-go reports
port-forward problems through klog, which writes to os.Stderr from
those goroutines, so this was a data race (reproduced under -race), and
the /dev/null file was closed on restore while late writers could still
use it. The restore also reset klog's output to stderr instead of what
it had been.

The standard logger is still redirected with log.SetOutput, and klog is
now routed to a discarding logr.Logger (klog.SetLogger/ClearLogger);
both are synchronized internally and os.Stderr is left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A dir-only exclude rule such as `build/` was evaluated against deleted
paths as if they were files (a deleted path cannot be stat'ed), and the
file branch only recognised the literal top-level path. Removing an
excluded nested directory locally (`rm -rf src/build`) therefore
produced a delete event and `rm -rf /app/src/build` in the container -
deleting exactly what the user had excluded so the container keeps its
own copy (build output, installed dependencies).

The excluder now follows gitignore: dir-only rules match directories,
anything below an excluded directory is excluded, and a path that no
longer exists is treated as excluded if it would be excluded as a file
or as a directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
initialSync returned early when the source directory had no files yet,
without running `mkdir -p <to>`. The first file created afterwards was
then extracted with `tar -C <to>` into a directory that does not exist
in the image, and every incremental sync failed with "can't change
directory".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In log mode every target streams its logs from its own goroutine into
the same RunOpts.Stdout. That is only safe for *os.File; RunOpts takes
any io.Writer (cobra's configured output, a buffer in tests or an
embedding program), where the concurrent writes were a data race and
could interleave lines. Writes to stdout now go through a mutex; each
log line is written in a single call, so lines stay intact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PatchResources only patches workloads rendered by main.ct. Options such
as image, command, replicas, env, workingDir or probes on a target that
has an explicit selector but no workload of that name (e.g. an
operator-managed database), or whose name matches several workloads,
were silently not applied - the session started with the original
image/command and no hint. replicas on a DaemonSet or Job produced a
field that does not exist and failed server-side apply with a schema
error. These are now reported before anything is applied.

dev() calls with an empty name or the same name twice (which collided in
the per-target bookkeeping of the session) are rejected as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A typo in `ct dev --env-file .env.stagign` was ignored silently: a
missing env file was always treated like the optional default .env, so
env() quietly fell back to its defaults. RunOpts.EnvFileRequired (set by
the CLI when --env-file is given explicitly) makes a missing file an
error naming the path; the default .env stays optional.

Auto-resolving the pod selector of a workload without
spec.selector.matchLabels - typically a Job, whose selector the API
server generates - failed with "missing path [spec selector matchLabels]
in resource". The error now names the workload and says to add
selector: {...} to its dev() call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A single entry that cannot be stat'ed or read - a symlink loop ("too
many levels of symbolic links"), a 0600 file owned by another user
(typically written by a container into a bind-mounted project dir) -
aborted the whole initial sync, so ct dev could not start, and dropped
every other change of an incremental batch. Such files are now skipped
and reported in one warning line suggesting to exclude them.

Also covers tar headers: permission bits (executables stay executable)
and long / non-ASCII names round-trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
renderMainResources called engine.Execute without ReleaseName, so the
`Release.name` global was "" while main.ct ran under ct dev, whereas ct
template/apply set it. Anything derived from it (resource names,
labels, hosts) differed in dev mode: a Deployment named
`Release.name + "-web"` became "-web", and dev("my-dev-web") could not
find its workload. The dev release name (--name, default "dev") is now
passed through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The session resolves one pod per target and the health watcher watches
that pod, but the terminal was started with Exec(selector), which
resolves a pod again. When several pods match - typically during the
rollout that ct dev's own apply triggers - the terminal could land in a
different pod than the watched one: the watcher then tore down a healthy
terminal when the other pod went away, or missed the terminal's pod
dying. The terminal now uses ExecPod on the watched pod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The resize monitor offered new sizes with a non-blocking send into a
one-slot channel and dropped the new size when a previous one had not
been consumed yet. Resizing a window produces bursts of SIGWINCH, so the
final dimensions could be dropped while a stale size was delivered,
leaving the remote shell with the wrong layout until the next resize.
A pending size is now replaced by the newest one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pod check added to follow pod replacements waits in WaitPod, which
only returns healthy pods. If the pod became unhealthy but kept running
(e.g. a crash-looping injected sidecar next to a healthy app container),
the check blocked indefinitely and no further change was synced, while
before the syncer kept syncing into the running container. The periodic
check now gives up after one check interval; only a failed sync waits
for a new pod without a limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
While the receiver is busy the watcher keeps merging events; it rebuilt
the outgoing batch from the pending map on every loop iteration, i.e.
for every event - quadratic for large bursts such as a branch checkout
during the initial sync. The batch is now rebuilt only after pending
changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
syscall.SIGWINCH does not exist on Windows, so the pkg/k8s test package
no longer compiled there. The queue ignores the signal value; send
os.Interrupt instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestRunDevSession_TerminalUsesTheWatchedPod waited a fixed 10ms for the
health watcher to start and TestStartDevFeatures_LogStreamsShareStdout-
Safely gave the log streams 300ms; both could flake on a loaded CI
machine. The first now waits for the watcher explicitly, the second gets
a one second window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… name

env(name, false) now returns a boolean in dev.ct, but dev.d.ts had no
overload for it. Workload names collected for dev.d.ts were rendered
with an empty Release.name, so names like Release.name + "-web" came out
as "-web"; they now use ct dev's default release name.

Reported by the ct dev review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
client-go logged transient trouble through klog straight to stderr, e.g.
an 'Unhandled Error' line for every port-forward to a pod that had just
gone away, duplicating ct's own reconnect message. klog is now muted for
all commands. API server warnings (such as a non-functional seccomp
annotation) are printed once each as 'Warning: ...', through the same
writer as ct's progress lines, so --error-format json keeps stderr clean.

Seen while running ct dev against a kind cluster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A finalizer without a domain ("foo") is rejected by the API server
unless it is one of the standard ones; found while testing against a
kind cluster (Kubernetes 1.34).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@krs2k
krs2k merged commit 2203cda into master Oct 5, 2026
7 checks passed
@krs2k
krs2k deleted the fix/correctness-and-tests branch October 5, 2026 17:04
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