How Argo CD decides a resource is out of sync
OutOfSync is a byte comparison of two normalised JSON documents. Argo CD v3.6.1 traced: three-way diff, server-side diff, managedFields, waves, health.
Every Argo CD operator eventually meets an Application that will not stay green. A Deployment flips to OutOfSync a few seconds after every sync, or it stays Synced while someone has plainly edited it by hand. The usual response is to add an ignoreDifferences entry and move on. That works until the entry hides a real change, or until a sync quietly writes back a value that a controller had set on purpose. Both failures have the same root: the operator does not know what the comparison actually compares.
For each resource, Argo CD builds two JSON documents, a predicted live state and a normalised live state, marshals both, and calls the resource modified when the bytes differ: Modified: !bytes.Equal(liveBytes, predictedBytes) in buildDiffResult1. There is no semantic comparison and no tolerance. Everything interesting happens before that line, in how the two documents are produced. This article follows that path through the Argo CD source at tag v3.6.1, the current release at the time of writing2, and then through the sync engine and the health model that decide what happens next. Paths below are relative to the repository root at that tag; the former gitops-engine repository now lives in-tree under gitops-engine/.
We run Argo CD as the GitOps layer for Korur's Kubernetes clusters: an app-of-apps root with automated sync, prune and selfHeal, ApplicationSets per workload, and a few platform charts synced with server-side apply. Where our own configuration illustrates a mechanism, it is quoted. Nothing here depends on it.
Desired state, live state and the pairing between them
A comparison starts in CompareAppState in controller/state.go3. The repo-server renders the source (plain YAML, Kustomize, Helm) into a list of unstructured objects; that is the desired, or target, state. The live state does not come from fresh GET requests. It comes from the controller's cluster cache, which is kept current by watches, so a comparison costs no API round trips for reading. Four things trigger a comparison. The first is a watch event on a resource the Application tracks, with an exception: when every changed field is covered by an ignoreResourceUpdates rule and the resource's health has not changed, the Application is not reconciled. resource.ignoreResourceUpdatesEnabled defaults to true4, and since 3.0 the stock argocd-cm that ships in the install manifest ignores /status on every resource, plus kind-specific fields on Applications, Rollouts, HPAs, ConfigMaps, ReplicaSets, EndpointSlices and Endpoints56. A status-only update to a tracked Deployment therefore does not start a comparison in a default v3.6.1 install unless it changes health. The second is the periodic refresh governed by timeout.reconciliation, which defaults to 120s plus up to 60s of jitter (timeout.reconciliation.jitter)7; the jitter exists to spread repo-server load when many Applications refresh together. The third is a Git provider webhook, whose refreshes have their own webhook.refresh.jitter78. The fourth is an explicit request, such as argocd app get --refresh or --hard-refresh, which the lab below uses9.
Pairing target objects with live objects is done by Reconcile in gitops-engine/pkg/sync/reconcile.go10. It first splits hooks out of the target list, then looks up each remaining target in a map keyed by ResourceKey, which is built from group, kind, namespace and name. The API version is not part of the key. That is deliberate: moving a manifest from one served version of a resource to another does not create a new identity, so it does not produce a create plus a prune. A target with no live partner is paired with nil; every live object left in the map after the loop is appended with a nil target, which is how extraneous resources enter the result. Before the loop, dedupLiveResources deals with one object (one UID) that the cache sees under several keys because the API serves it in more than one group; the source's examples are apps/Deployment also appearing as extensions/Deployment, and an OpenShift ClusterRole duplicated under rbac.authorization.k8s.io. It deletes the duplicate keys that the target list does not name, stopping when one is left. If Git names one of them, that one survives; if Git names none, the source comment says plainly that an arbitrary one stays10.
Which live objects belong to the Application at all is decided by resource tracking. The default method is the argocd.argoproj.io/tracking-id annotation, whose value has the form my-app:apps/Deployment:default/my-deployment11. The older label method used app.kubernetes.io/instance, which is limited to 63 characters and is written by other tools as well, so ownership became ambiguous11. The annotation also carries enough identity to detect copies: isSelfReferencedObj checks that the namespace, name, group and kind in the tracking id match the object that carries it3. An object that inherited the annotation from somewhere else, for example a resource copied by another controller, fails that check and is excluded from the sync status rather than being reported as drift or pruned.
After the diff, CompareAppState assigns a status per resource with a short switch3. Most confusion about green and yellow tiles comes from these few cases.
| Condition | Resource status | Effect on Application status |
|---|---|---|
Resource is a hook, is skipped, or fails isSelfReferencedObj | none recorded | none |
| Target exists, live is missing | OutOfSync | OutOfSync |
| Live exists, target is missing (needs pruning) | OutOfSync | OutOfSync, unless the object carries argocd.argoproj.io/compare-options: IgnoreExtraneous |
Both exist and DiffResult.Modified is true | OutOfSync | OutOfSync |
| Both exist and the bytes are equal | Synced | none |
| Group, kind or name not permitted by the AppProject | Unknown, overwritten after the cases above | still OutOfSync in the usual case: non-permitted live objects are dropped from the live map before pairing, so the target meets a nil live object and the earlier case has already set OutOfSync |
| Rendering or live-state loading failed | Unknown | Unknown |
IgnoreExtraneous only affects the status of resources that need pruning; the compare-options documentation is explicit that a degraded extraneous resource still degrades the Application12. And an object tracked by two Applications raises a SharedResourceWarning condition, which is the controller telling you that two sources of truth are fighting over one object.
The legacy diff: a three-way merge with a memory
Unless server-side diff is enabled, Diff in gitops-engine/pkg/diff/diff.go takes the client-side path1. Argo CD calls it the legacy strategy and it is still the default13. It reads the kubectl.kubernetes.io/last-applied-configuration annotation from the live object. When the annotation exists, ThreeWayDiff(orig, config, live) runs with orig set to that annotation; when it does not, TwoWayDiff runs, which is the same function with orig set to a copy of the desired state.
The three-way diff never compares desired against live directly. It predicts what live would look like after an apply, and compares that prediction with live. For a type registered in the client-go scheme (every built-in kind), threeWayMergePatch calls strategicpatch.CreateThreeWayMergePatch(orig, config, live) with patch metadata taken from the Go struct, which is what knows that containers merges by name and ports by containerPort. applyPatch then applies that patch to live and runs the scheme defaulting functions on both sides: it unmarshals into the typed struct, calls Scheme.Default, turns the delta into a second strategic merge patch with generateSchemeDefaultPatch, and applies it to the original JSON so that unknown fields survive. Both results are round-tripped through map[string]any and marshalled again, and Go's encoding/json sorts map keys when it encodes a map14. That last step is what makes the byte comparison stable.
The memory in this design is the annotation. A field that appears in neither the annotation nor the desired state is not mentioned in the patch, so the prediction keeps the live value and the field cannot produce a diff. That is why a label added with kubectl label leaves an Application Synced, while kubectl scale on a Deployment whose manifest sets replicas makes it OutOfSync. The table is the whole model for built-in kinds.
| In orig | In desired | In live | Patch effect | Diff? |
|---|---|---|---|---|
| no | no | yes | none, live value kept | no |
| no | yes | no or different | set to desired value | yes |
| yes | yes, same as live | yes | none | no |
| yes | yes | different | set to desired value | yes |
| yes | no | yes | delete the field | yes |
Custom resources take a different branch. scheme.Scheme.New fails for a kind the client does not compile in, so there is no struct and no patch metadata. threeWayMergePatch first calls jsonutil.RemoveMapFields(orig, live), which drops from live every map field that the last-applied annotation does not contain, and then builds a JSON merge patch with jsonmergepatch.CreateThreeWayJSONMergePatch. ThreeWayDiff applies it with jsonpatch.MergePatch. A JSON merge patch replaces arrays wholesale and deletes a member by setting it to null15, so list handling for custom resources is coarse, and fields a CRD defaults on the server are simply not seen because they were never in the annotation. StatefulSets get a dedicated fix: statefulSetWorkaround strips server-defaulted fields from volumeClaimTemplates, because the API server defaults the embedded PersistentVolumeClaim in ways the client cannot reproduce.
The weakness of this strategy is the annotation itself. It is a full copy of the object as last applied, stored inside the object, and annotations are capped at 262144 bytes in total. Large CRDs do not fit, which is why the Argo CD install instructions now require kubectl apply --server-side for Argo CD's own manifests16, and why the sync-options documentation lists the size limit as a reason for server-side apply17.
Normalisation: making two documents comparable
Before either strategy runs, both sides are normalised, and most false drift is a normalisation gap. The first pass is remarshal1. It marshals the object to JSON and back to strip Go type information, because an int64 from YAML and a float64 from JSON would otherwise produce different documents. It then decodes the JSON into the registered Go struct with DisallowUnknownFields, converts the struct back to unstructured and removes fields the struct's own marshaller added. The effect is that the desired state is formatted exactly as the API server would format it. The most visible case is resource.Quantity, which the API serialises in canonical form, so 1.5 becomes "1500m"18. If decoding fails, for example because the manifest has a field the struct does not know, remarshal returns the object untouched and logs at verbosity 1.
Custom resources get none of this, because there is no struct. A CRD that embeds a core type, such as a resource request inside a custom spec, will show cpu: 100m against whatever form the controller wrote back. Argo CD's answer is resource.customizations.knownTypeFields.<group>_<Kind> in argocd-cm, which tells the normaliser to treat a path as core/Quantity, meta/v1/Duration or another listed type19.
The second pass is Normalize, which applies fixed rules by kind1. It removes metadata.creationTimestamp. For a Secret it moves stringData into data, base64-encoding string values, because the API server performs the same merge and never returns stringData. For Role and ClusterRole it turns an empty rules list into null, and with resource.compareoptions ignoreAggregatedRoles: true it nulls rules on any role with an aggregationRule, since the aggregation controller owns that list19. For Endpoints it fills in the default TCP protocol and sorts subsets.
The third pass is the configurable one, built in util/argo/diff/diff.go by StateDiffs20. Application-level ignoreDifferences and system-level resource.customizations.ignoreDifferences.<group>_<Kind> entries become a single normaliser with three mechanisms19:
jsonPointersare compiled into RFC 6902 JSON Patch documents with a singleremoveoperation per path21. Path syntax is RFC 6901 JSON Pointer, so a/inside a key, common in annotation names, is written~122. A pointer to a field that does not exist yields an error that the normaliser deliberately does not log.jqPathExpressionsare compiled with gojq intodel(<expression>)and executed with a timeout that defaults to one second (DefaultJQExecutionTimeoutinutil/argo/normalizers/diff_normalizer.go)23. The application controller reads the override from the keycontroller.ignore.normalizer.jq.timeoutinargocd-cmd-params-cm, which the install manifest maps to the environment variableARGOCD_IGNORE_NORMALIZER_JQ_TIMEOUT2425. The diffing page names the key without thecontroller.prefix19, and a value set under that shorter key is not read by any component of the stock install. They are the only way to address one element of a list by content, such as one container by name.managedFieldsManagersare handled earlier, inpreDiffNormalize, bymanagedfields.Normalize. For each entry in the live object'smetadata.managedFieldswhose manager is trusted, it parses thefieldsV1set and intersects it with the fields where desired and live differ; the intersection is removed from both sides. The result is precise: only fields the named manager actually owns and actually changed are ignored.
We use the first two in our own ApplicationSets, and the shapes are typical. A pair of maintenance CronJobs, one scaling a handful of Deployments up before the weekly node-image upgrade window and one scaling them back down after it, writes spec.replicas outside Git, so those Applications ignore /spec/replicas by JSON pointer and by name. A controller stamps a rollout annotation onto the pod template whenever the configuration it tracks changes, so the same Applications ignore exactly that annotation with a jq path. The object and annotation names below are placeholders; the shape is ours:
ignoreDifferences:
- group: apps
kind: Deployment
name: web
jsonPointers:
- /spec/replicas
- group: apps
kind: Deployment
name: web
jqPathExpressions:
- '.spec.template.metadata.annotations."example.com/secrets-version"'
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- RespectIgnoreDifferences=trueThe name matters. An unscoped /spec/replicas rule on every Deployment in an Application turns off drift detection for a field that is part of the capacity contract of every workload in it. Ignore rules are exceptions to GitOps, and each one should name the object and the reason. The RespectIgnoreDifferences line matters even more, and it gets its own section below, because the ignore rule alone affects only the comparison and not what a sync writes.
managedFields and server-side apply
Server-side apply moves the merge from the client into the API server and replaces the last-applied annotation with per-field ownership. KEP-555 states the motivation bluntly: client-side kubectl apply was buggy and hard to fix because the lack of API support forced a client-side implementation26. The feature went alpha in Kubernetes 1.14, beta in 1.16 and stable in 1.2227, and it can no longer be switched off28.
An apply is an HTTP PATCH with content type application/apply-patch+yaml, and every request names a field manager28. The server records ownership in metadata.managedFields, one entry per manager and operation. Each entry has manager, operation (Apply for a server-side apply patch, Update for everything else), apiVersion, time, fieldsType: FieldsV1 and a fieldsV1 trie. The trie is defined by the FieldsV1 type: a key is f:<name> for a struct field or map key, v:<value> for a list item identified by its exact JSON value, i:<index> for a list position, or k:<keys> for a list item identified by its key fields, and the special key . stands for the field itself. A key that maps to an empty object is a member of the set29. A Deployment's container entry therefore appears as f:containers with a child like k:{"name":"guestbook-ui"}.
managedFields:
- manager: kubectl
operation: Apply
apiVersion: v1
time: "2010-10-10T0:00:00Z"
fieldsType: FieldsV1
fieldsV1:
f:metadata:
f:labels:
f:test-label: {}
f:data:
f:key: {}Three rules from the Kubernetes documentation carry the rest of this article28. When a value changes, ownership moves to the manager that changed it. When an Apply tries to change a field another manager owns, the request fails with a conflict unless force is set, in which case the applier takes sole ownership. And when an applier stops including a field it owns, the server deletes the field or resets it to its default, provided no other manager also owns it. Argo CD always sets force on its server-side applies, as the next sections show, so it never sees a conflict: a field another manager owns, such as replicas owned by an HPA, is silently taken over. The Kubernetes handover for that case relies on the applier receiving a conflict, so it does not protect an Argo CD-managed workload: the field has to leave Git, and the order in which it leaves decides whether the workload keeps its replica count, as the deletion rule below and the section on RespectIgnoreDifferences show. Merge granularity comes from the schema, not from the client:
| Go marker | OpenAPI extension | Values | Merge behaviour |
|---|---|---|---|
//+listType | x-kubernetes-list-type | atomic, set, map | atomic replaces the whole list and has one owner; set and map let managers own entries separately |
//+listMapKey | x-kubernetes-list-map-keys | list of scalar field names | identifies entries of a map list, for example port and protocol |
//+mapType | x-kubernetes-map-type | atomic, granular | atomic maps are replaced by a single manager; granular maps are owned per key |
//+structType | x-kubernetes-map-type | atomic, granular | same as mapType, for structs |
The deletion rule is the one that bites. The Kubernetes documentation walks through it with an HPA: if a user removes spec.replicas from their applied configuration before the HPA controller has written the field and become an owner, the server resets replicas to its default of 1, which can degrade a running workload28. Ownership is a protocol, and handing a field to another actor has to be done in order.
Argo CD's field manager is argocd-controller (ArgoCDSSAManager in common/common.go), and it uses that name for every apply, not only server-side ones. controller/sync.go passes it to the sync engine with WithServerSideApplyManager, applyObject hands sc.serverSideApplyManager to ApplyResource whatever the strategy (sync_context.go:1485)30, and newApplyOptions sets o.FieldManager = manager before kubectl's apply code runs (resource_ops.go:476)31. kubectl's client-side path builds its request helper with WithFieldManager(o.FieldManager)32, so a resource that Argo CD applied client-side carries an argocd-controller entry with operation Update, not a kubectl-client-side-apply entry. The lab shows exactly that.
Switching such a resource to ServerSideApply=true involves two migrations, and they target different objects. Argo CD's own, performCSAUpgradeMigration, runs before the server-side apply when the live object has an Update entry under the migration manager name, which defaults to kubectl-client-side-apply (DefaultClientSideApplyMigrationManager) and can be changed with the argocd.argoproj.io/client-side-apply-migration-manager annotation on the Application; ClientSideApplyMigration=false turns it off3017. It exists for objects first created by kubectl apply or another tool, and it does not match Argo CD's own argocd-controller Update entry. That entry is migrated one layer down, by kubectl. After every server-side apply, migrateToSSAIfNecessary in k8s.io/kubectl v0.37.0 (the version Argo CD v3.6.1 pins) looks for Update managers that own the kubectl.kubernetes.io/last-applied-configuration annotation, unions their field sets into the Apply entry of the applying manager with csaupgrade.UpgradeManagedFieldsPatch, deletes the Update entries, and re-sends the apply so that fields dropped from the configuration can finally be removed3233. Argo CD's client-side applies wrote the annotation, so its Update entry qualifies. In the lab, the result after one server-side sync is a single argocd-controller Apply entry, and the last-applied annotation itself is gone: after the union it belonged only to the applier, and the re-sent apply did not contain it.
Had the Update entry stayed, two different readers would treat it differently. The API server would count it as a separate owner, so a field removed from Git would survive as long as that entry still listed it. Argo CD's server-side diff would not notice: managerFieldSet in diff.go unions every managedFields entry whose manager is argocd-controller, whatever its operation1, so the diff would report the field as Argo CD's while the server kept it alive.
Server-side diff: asking the API server for the prediction
Server-side diff replaces the client-side prediction with the real one. For each resource that exists on both sides, serverSideDiff calls K8sServerSideDryRunner.Run1. That method, in gitops-engine/pkg/diff/diff_options.go, is a single call, ApplyResource(ctx, obj, cmdutil.DryRunServer, false, false, true, manager): a server dry run with force and validate set to false, serverSideApply set to true, and the manager the caller passed, which is argocd-controller34. The false it passes as force is kubectl's replace-style deletion force, and newApplyOptions disables that under server-side apply; the same function sets o.ForceConflicts = serverSideApply (resource_ops.go:496)31, which kubectl sends as Force in the patch options32. The dry run is therefore a forced server-side apply, the equivalent of --force-conflicts, exactly like every real ServerSideApply=true sync17. The response is the object as the API server would store it after defaulting, admission and the SSA merge. Argo CD marks the strategy stable since v3.1.013. It is enabled per Application with argocd.argoproj.io/compare-options: ServerSideDiff=true, globally with controller.diff.server.side: "true" in argocd-cmd-params-cm (the shipped default is "false")35, and, in v3.6.1, implicitly by the ServerSideApply=true sync option: shouldUseServerSideDiff in controller/state.go returns true for any of the three, and ServerSideDiff=false overrides them all3. The older structured-merge diff, which used to be selected for server-side apply, is described in the source as discontinued1.
The dry-run result cannot be compared with live as is, because the dry run also runs mutating admission webhooks, and a webhook that injects a sidecar would make every resource look modified. removeWebhookMutation handles this using ownership, not heuristics1:
- Convert predicted and live into typed values using the cluster's OpenAPI schema (
GvkParser), so lists and maps merge by their declared keys. - Take the field set owned by
argocd-controllerfrom the predicted object'smanagedFields, and compute the complement: every predicted field the manager does not own.excludeManagerOwnedAncestorskeeps parent paths whose descendants are owned, which matters underx-kubernetes-preserve-unknown-fieldswhere only leaves are recorded. - Compare live with predicted. For fields that the prediction removes, keep only removals of fields that
argocd-controllerowned in live. Server-side apply only removes fields its applier owned, so anything else missing from the prediction was removed by another actor after the cached live object was read. - Remove the non-owned fields from the prediction, except list-map key fields whose removal would violate the schema, merge the remainder onto live, and then remove the legitimately deleted fields again.
The result is live, overlaid with exactly the fields Argo CD would own after the apply. That is the right question for a GitOps controller: not whether the object equals the manifest, but whether applying the manifest would change anything Argo CD is responsible for. IncludeMutationWebhook=true in the compare-options annotation clears ignoreMutationWebhook, and serverSideDiff then skips removeWebhookMutation as a whole: none of the four steps run, and the raw dry-run response, normalised, is compared with live without the ownership overlay3113. Use it when webhook output is supposed to count. After the overlay, both sides lose managedFields, resourceVersion, generation and the last-applied annotation, are normalised, and go to the same bytes.Equal.
Ordering of normalisation changes too. On the server-side path, Diff sets WithSkipFullNormalize(true) before the dry run, so ignoreDifferences and known-type rules are not applied to the manifest that is sent to the server; they run on the dry-run output and on live afterwards. The source comment explains why: an ignored field may need to be present in the configuration for the apply to be valid1.
A resource that does not exist yet gets no dry run: ServerSideDiff falls back to handleResourceCreateOrDeleteDiff, which marks it modified without calling the API, so a webhook that would reject it is only met at sync time113. Dry-run results are also cached. A new dry run happens only on a refresh or hard refresh, a new revision, a change to the Application spec, or a change of the live object's resourceVersion13; useDiffCache in controller/state.go also keeps using the cache after the status has soft-expired when server-side diff is on, to spare the API server3.
| Aspect | Legacy (three-way) | Server-side diff |
|---|---|---|
| Prediction made by | client: strategic or JSON merge patch plus scheme defaults | API server: SSA dry run |
| Memory of what was applied | last-applied-configuration annotation | managedFields entry of argocd-controller |
| Server-side defaults and CRD defaults | built-in kinds via client scheme only | all, as the server applies them |
| Admission webhooks | not run | run; mutations removed unless IncludeMutationWebhook=true |
| Fields added by other actors | ignored if absent from annotation and desired state | ignored if not owned by argocd-controller |
| API calls for comparison | none | one dry-run apply per existing resource, cached |
| New resources | shallow diff | shallow diff |
Our split mirrors the trade-off. Application workloads, which are small built-in kinds with plain manifests, still use client-side apply and the legacy diff, which costs the API server nothing. Platform charts that ship large CRDs or webhook configurations sync with ServerSideApply=true. Where a chart contains a component that writes its own caBundle into webhooks[].clientConfig at runtime, the Application also carries an explicit jqPathExpressions rule for that path. Ownership bookkeeping should already exclude a field Git never sets; the explicit rule records the intent where a reviewer will look, and keeps the field ignored if the Application is ever moved back to the legacy diff.
RespectIgnoreDifferences, and who owns replicas
ignoreDifferences changes the comparison and nothing else. A sync still applies the full desired state, so an ignored replicas: 1 in Git is written back over a live value of 3 the next time anything in the Application syncs. With selfHeal, that is not immediate, because an ignored difference does not make the Application OutOfSync. It happens later, when an unrelated change such as an image tag bump triggers a sync. In our case that would mean the maintenance scale-up silently undone in the middle of the window, which is precisely the failure the comment in our ApplicationSet warns about.
RespectIgnoreDifferences=true makes the sync honour the rules. The implementation in normalizeTargetResources in controller/sync.go is a patch trick36. It normalises live and target with the ignore rules, computes a merge patch from normalised live to real live (which, by construction, contains only the ignored fields and their live values), and applies that patch to the normalised target. Live status is removed before the patch is computed, because merging it into the applied object would make argocd-controller a co-owner of status under server-side apply. A final step, restoreNonIgnoredFields, undoes collateral damage where a parent field has patchStrategy: replace and the patch would otherwise pull siblings from live. The documented limit follows from the mechanism: with no live object there is nothing to copy, so a new resource is applied as written17.
Under server-side apply, the applied object still contains spec.replicas, now carrying the live value, so argocd-controller keeps ownership of the field. In the lab it shares that ownership with the kubectl entry for the scale subresource, which wrote the same value last. That is harmless for our pair of CronJobs, one running kubectl scale before the window and the other after it, because the value Argo CD re-asserts is always the one written by whichever CronJob ran last. It is the wrong model for an HPA, where the Kubernetes guidance is to let the controller own the field and remove it from the applied configuration through an explicit ownership handover28. For autoscaled workloads, delete replicas from the manifest rather than papering over it with an ignore rule, but not as the first step. Right after a sync, argocd-controller is often the only owner of spec.replicas: under server-side apply the forced apply took the field from any other manager, and under the legacy path the field sits in the last-applied annotation. The first sync without the field then sets the Deployment to 1 replica until the HPA scales it up again, which is the case the Kubernetes documentation warns about in its HPA walkthrough28. On the legacy path this happens whoever else has written the field, because the three-way patch deletes every field that is in the annotation and absent from the desired state, and the API server fills in the default. Under server-side apply the handover can be done in order. While replicas is still in Git, add the named /spec/replicas ignore rule with RespectIgnoreDifferences=true, so that syncs re-apply the live value instead of taking the field back. Wait until the HPA has changed the value and kubectl get deploy -o yaml --show-managed-fields lists the HPA's manager on spec.replicas, next to argocd-controller or instead of it. Then remove the field and the ignore rule from Git in the same commit; a rule left in place would keep copying the live value into every apply through normalizeTargetResources, and Argo CD would never let go of the field. The next apply drops only Argo CD's claim, and because another manager still owns the field, the server keeps the HPA's value. On the legacy path, move the Application to ServerSideApply=true first and then follow the same order, or accept the drop to 1 and make the change when the workload can absorb it.
What a sync does: phases, waves and the dry run
A sync is a state machine driven by repeated calls to syncContext.Sync in gitops-engine/pkg/sync/sync_context.go30. Each call rebuilds the task list from current state, does at most one step of work, records results and returns; the operation processor calls it again. Progress is recorded in the Application's status.operationState and handed back to the engine through WithInitialState, so the state machine is resumable rather than held in a goroutine.
Tasks are sorted by syncTasks.Less in sync_tasks.go37: phase first (PreSync = -1, Sync = 0, PostSync = 1, SyncFail = 2), then wave from argocd.argoproj.io/sync-wave (falling back to the Helm hook weight, default 0), then a fixed kind order borrowed from Helm, then name. The kind order starts with Namespace, NetworkPolicy, ResourceQuota, LimitRange, puts ServiceAccount, Secret and ConfigMap before storage, CustomResourceDefinition before RBAC, and ends with Ingress and APIService. Every listed kind gets a negative rank, so custom resources, which are not in the table, sort after all of them within a wave. After sorting, adjustDeps moves a Namespace in front of the first task that references it, and a CRD in front of the first custom resource of its group and kind, and gives the moved task that task's phase and wave.
On the first call, Sync first creates the destination namespace for real if CreateNamespace=true requires it, through getNamespaceCreationTask and runTasks(..., false); the source comment notes that validation is expected to fail in several cases while the namespace is missing. It then runs a client-side dry run of the remaining tasks, narrowed by filterOutOfSyncTasks to the out-of-sync ones when ApplyOutOfSyncOnly is set. All of this is in sync_context.go, lines 520 to 55530. applyObject forces DryRunClient here regardless of other settings, and shouldUseServerSideApply returns false for dry runs, with a comment linking the issue where a server-side dry run broke namespace auto-creation30. A failure stops the operation with one or more objects failed to apply (dry run). The source is candid about the limit of this check: it catches syntax problems but not, for example, changes to immutable fields. Those surface in the real apply, mid-operation. This is one practical argument for server-side diff, which runs admission at comparison time for existing resources.
On later calls, Sync walks a fixed sequence. It refreshes the result of running tasks: hooks report their own operation state, other resources report health through health.GetResourceHealth, where Healthy completes a task and Degraded fails it. If the operation is multi-step, meaning the sorted task list spans more than one phase or wave (multiStep), it waits while any task is still running. It waits for pruned objects that are still terminating. It fails the operation and runs SyncFail hooks if any completed task failed. Otherwise it takes the phase and wave of the first pending task, applies exactly the tasks in that phase and wave, and calls the wave hook. The wave hook in controller/sync.go is delayBetweenSyncWaves, which sleeps 2 seconds between waves unless ARGOCD_SYNC_WAVE_DELAY says otherwise, and does not sleep after the final wave3638.
Waves gate on health, not on apply: the next wave starts only after every resource in the previous one reports Healthy, which is how the documentation can warn that one unhealthy resource in an early wave keeps the Application from ever finishing38. The final wave, by contrast, gates on nothing. When the last tasks are applied successfully and none of them is a hook, the operation ends as successfully synced (all tasks run), and the source comment adds that this is so even if those objects subsequently degrade30. A green sync result for a single-wave Application means the API server accepted the objects. Whether the rollout worked is the job of health.
Hooks are resources with argocd.argoproj.io/hook set to PreSync, Sync, PostSync, SyncFail, PreDelete, PostDelete or Skip, and argocd.argoproj.io/hook-delete-policy set to HookSucceeded, HookFailed or BeforeHookCreation, the last being the default38. They are split out in Reconcile, so they never contribute to sync status. Only PreSync, Sync, PostSync and SyncFail hooks run inside the phase and wave ordering above; those four are the whole of syncPhaseOrder37. PreDelete and PostDelete hooks run around the deletion of the Application, not during a sync, even one that prunes, and Skip means the manifest is not applied at all38. PruneLast=true turns pruning into an implicit final wave, and ApplyOutOfSyncOnly=true skips resources whose comparison was clean, which shortens syncs of large Applications but makes the sync depend on the diff being right17.
Automated sync adds its own rules on top. It runs only when the Application is OutOfSync, and it attempts one sync per combination of commit SHA and parameters39. A failed automated sync is never retried against the same revision and parameters, with or without selfHeal: autoSync in controller/appcontroller.go first asks alreadyAttemptedSync whether the last operation targeted the same revision and source, and if that operation was not Successful() it returns a SyncError condition (the log line reads "failed previous sync attempt ... will not retry") before the GetSelfHeal() branch is ever reached40. Inside one operation, though, the controller does retry, whether or not syncPolicy.retry is set. autoSync builds every automated operation with RetryStrategy{Limit: 5} and replaces it with syncPolicy.retry only when that field is present, and the operation processor moves a Failed or Error operation back to Running while RetryCount is below the limit (or the limit is -1)40. With no backoff block, NextRetryAt waits 5s times a factor of 2 per attempt, capped at 3m (DefaultSyncRetryDuration, DefaultSyncRetryFactor, DefaultSyncRetryMaxDuration)4142. The user guide presents retry as opt-in39, so this default is visible only in the source. Only when those retries are exhausted is the operation recorded as failed, and from then on it takes a new commit, a change to the Application's source or a manual sync. selfHeal covers the other case: the last sync to that revision succeeded and live state drifted afterwards. Only then is a second sync for the same commit allowed, limited to the resources that are not Synced, and paced by the exponential backoff keys controller.self.heal.backoff.timeout.seconds, controller.self.heal.backoff.factor and controller.self.heal.backoff.cap.seconds in argocd-cmd-params-cm4035.
Health: a second, independent verdict
Sync status says whether live matches Git. Health says whether what is running works. GetResourceHealth in gitops-engine/pkg/health/health.go consults a health override first, which is where Lua checks from resource.customizations.health.<group>_<kind> and the bundled checks for third-party kinds come in, and then falls back to built-in Go checks for Deployment, StatefulSet, ReplicaSet, DaemonSet, Ingress, Service, PersistentVolumeClaim, Pod, Job, HorizontalPodAutoscaler, APIService and Argo Workflows4344. A kind with no check has no health at all, which the sync engine treats as immediate success.
The Deployment check in health_deployment.go is a port of kubectl rollout status45. A paused Deployment is Suspended. If metadata.generation is ahead of status.observedGeneration, the controller has not seen the new spec yet and the result is Progressing. A Progressing condition with reason ProgressDeadlineExceeded is Degraded. Fewer updated replicas than desired, old replicas still present, or fewer available than updated replicas are all Progressing. Only after those checks pass is the Deployment Healthy. The generation comparison is the subtle part: immediately after an apply, the Deployment controller may not have observed the change, and without that check the stale status would read as healthy.
Application health is the worst resource health, ranked Healthy, Suspended, Progressing, Missing, Degraded, Unknown, computed by setApplicationHealth in controller/health.go4644. Hooks are skipped, resources annotated argocd.argoproj.io/ignore-healthcheck: "true" are skipped, and a missing resource does not count, because OutOfSync already reports it; only when every resource is missing does the Application become Missing. A child Application whose health is Missing or Unknown does not affect its parent either.
That last rule matters for app-of-apps. The health assessment of argoproj.io/Application itself was removed in Argo CD 1.844, and in v3.6.1 the bundled customisations for argoproj.io/Application contain actions but no health script47. A child Application therefore has no health, so a sync wave on child Applications only orders their creation; it does not wait for the child to become healthy. If the root Application's waves are meant to express dependencies between platform components, add the resource.customizations.health.argoproj.io_Application Lua check that the health documentation describes. Without it, the waves are decoration.
Lab: watching the diff decide
The lab reproduces the mechanisms above on a disposable cluster. Reference environment: Fedora 43 with kernel 7.2.13 and Podman 5.8.9 as the container runtime for kind; kind v0.33.048 with node image kindest/node:v1.36.4; kubectl v1.36; Argo CD v3.6.1, which is tested against Kubernetes 1.34 to 1.372, and the matching argocd CLI. The application is the guestbook directory of argoproj/argocd-example-apps, pinned to commit 8088f4c0d970abb09e250248cc97e35623447cb5, whose Deployment sets replicas: 149. Nothing here depends on kernel features; Docker works in place of Podman if you drop the provider variable. Every output quoted below is from a run of these commands in that environment. One deviation from a stock install was needed: with rootless Podman and the host's default fs.inotify.max_user_instances of 128, argocd-repo-server crashed on start with failed to create fsnotify Watcher: couldn't initialize inotify: too many open files. The kind known-issues page traces this error to inotify limits, which are not namespaced, and recommends raising them on the host with sysctl50. We left the host alone and disabled the repo-server's GnuPG feature instead, with the ARGOCD_GPG_ENABLED=false setting that the Argo CD documentation describes51; the lab does not use commit signature verification.
export KIND_EXPERIMENTAL_PROVIDER=podman
kind create cluster --name argo-diff \
--image kindest/node:v1.36.4@sha256:099e049362a1526b2db71494e1947aae99bd16290d7c895f2b7ea312e3cbfaed
kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts \
-f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.1/manifests/install.yaml
kubectl -n argocd rollout status statefulset/argocd-application-controller --timeout=300s
# Only needed when the host's inotify limits are low; see the note above.
kubectl -n argocd set env deploy/argocd-repo-server ARGOCD_GPG_ENABLED=false
kubectl -n argocd rollout status deployment/argocd-repo-server --timeout=300s
kubectl config set-context --current --namespace=argocd
argocd login --coreapiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: guestbook
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/argoproj/argocd-example-apps.git
targetRevision: 8088f4c0d970abb09e250248cc97e35623447cb5
path: guestbook
destination:
server: https://kubernetes.default.svc
namespace: guestbook
syncPolicy:
syncOptions:
- CreateNamespace=truekubectl apply -f guestbook-app.yaml
argocd app sync guestbook
argocd app wait guestbook --health --timeout 300
kubectl -n guestbook get deploy guestbook-ui \
-o jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}{"\n"}'
kubectl -n guestbook get deploy guestbook-ui --show-managed-fields \
-o jsonpath='{range .metadata.managedFields[*]}{.manager}{" "}{.operation}{"\n"}{end}'The first get prints the last-applied annotation that the legacy diff uses as orig: the full Deployment as rendered, with replicas: 1, plus the argocd.argoproj.io/tracking-id annotation Argo CD added, but not the last-applied annotation itself. The second prints two lines, argocd-controller Update and kube-controller-manager Update. The first is Argo CD's client-side apply, recorded under Argo CD's manager name as described above; there is no kubectl-client-side-apply entry. The second is the Deployment controller writing status. No entry has operation Apply yet.
kubectl -n guestbook label deploy guestbook-ui team=platform
argocd app get guestbook --refresh
kubectl -n guestbook scale deploy guestbook-ui --replicas=3
argocd app get guestbook --refresh
argocd app diff guestbook; echo "exit=$?"
kubectl -n guestbook get deploy guestbook-ui --show-managed-fields \
-o jsonpath='{range .metadata.managedFields[*]}{.manager}{" "}{.operation}{" "}{.subresource}{"\n"}{end}'After the label, the Application stays Synced: team is in neither the annotation nor the manifest, which is the first row of the three-way table. After the scale, it is OutOfSync, and argocd app diff prints the replicas change and exits with status 1, the documented code for a diff found52. The label is still on the live object and is still not reported. The listing now has four lines: kubectl Update scale, argocd-controller Update, kubectl-label Update and kube-controller-manager Update status. kubectl scale writes through the scale subresource under the manager kubectl, and it now owns spec.replicas.
kubectl -n argocd patch application guestbook --type merge -p \
'{"spec":{"ignoreDifferences":[{"group":"apps","kind":"Deployment","name":"guestbook-ui","jsonPointers":["/spec/replicas"]}]}}'
argocd app get guestbook --refresh
argocd app sync guestbook
kubectl -n guestbook get deploy guestbook-ui -o jsonpath='{.spec.replicas}{"\n"}'
kubectl -n guestbook get deploy guestbook-ui --show-managed-fields \
-o jsonpath='{range .metadata.managedFields[*]}{.manager}{" "}{.operation}{" "}{.subresource}{"\n"}{end}'
kubectl -n guestbook scale deploy guestbook-ui --replicas=3
kubectl -n argocd patch application guestbook --type merge -p \
'{"spec":{"syncPolicy":{"syncOptions":["CreateNamespace=true","RespectIgnoreDifferences=true"]}}}'
argocd app sync guestbook
kubectl -n guestbook get deploy guestbook-ui -o jsonpath='{.spec.replicas}{"\n"}'
kubectl -n guestbook get deploy guestbook-ui --show-managed-fields \
-o jsonpath='{range .metadata.managedFields[*]}{.manager}{" "}{.operation}{" "}{.subresource}{"\n"}{end}'With the ignore rule the Application returns to Synced while three replicas run. The first manual sync nonetheless applies the full manifest, because a sync applies every resource unless ApplyOutOfSyncOnly is set, so replicas reads 1 afterwards. The listing after that sync shows the ownership rule at work: the kubectl Update scale line is gone, because Argo CD changed the value and took the field, and three lines remain (kubectl-label Update, argocd-controller Update, kube-controller-manager Update status). After scaling again and adding RespectIgnoreDifferences=true, the sync copies the live value into the applied object through normalizeTargetResources, and replicas reads 3. The kubectl Update scale line is back, and this time it survives the sync, because Argo CD wrote the same value. This is the sequence that motivates the option in our own ApplicationSets.
kubectl -n argocd patch application guestbook --type merge -p \
'{"spec":{"syncPolicy":{"syncOptions":["CreateNamespace=true","RespectIgnoreDifferences=true","ServerSideApply=true"]}}}'
argocd app sync guestbook
kubectl -n guestbook get deploy guestbook-ui --show-managed-fields \
-o jsonpath='{range .metadata.managedFields[*]}{.manager}{" "}{.operation}{"\n"}{end}'
kubectl -n guestbook annotate deploy guestbook-ui example.com/owner=lab
argocd app get guestbook --hard-refreshThe sync reports serverside-applied, and the listing after it reads argocd-controller Apply, kubectl Update, kubectl-label Update, kube-controller-manager Update. The argocd-controller Update entry from Step 1 is gone. performCSAUpgradeMigration did not touch it, because the object has no kubectl-client-side-apply entry; kubectl's migrateToSSAIfNecessary folded it into the new Apply entry, which now lists spec.replicas, the container, the selector and the tracking annotation. The last-applied annotation has disappeared from the object as well, for the reason given in the managedFields section. The kubectl Update line is the scale subresource entry from Step 3, which this listing prints without its subresource. The annotation added by hand is owned by another manager, so the dry-run prediction reverts it to its live value in removeWebhookMutation, and the Application stays Synced under server-side diff as it did under the legacy diff, for a different reason. argocd app get still reports Synced after the hard refresh. Because RespectIgnoreDifferences applied the live replicas, spec.replicas reads 3 and is co-owned by argocd-controller (Apply) and kubectl (Update, subresource scale), which -o yaml --show-managed-fields shows in full.
kind delete cluster --name argo-diffWhat we configure, and why
Most drift problems are solved by choosing the comparison deliberately rather than by adding ignore rules. For new Applications built from large charts, or from anything that defines CRDs or admission webhooks, we use ServerSideApply=true. The annotation limit goes away, CRD defaults are predicted by the server that applies them, and ownership in managedFields replaces a 262144-byte copy of the object as the record of intent. The cost is one cached dry-run apply per existing resource, which is negligible for platform components that change weekly. For small Applications made of built-in kinds, the legacy diff is accurate enough and free, and we leave it alone.
Every ignoreDifferences entry names its object and carries a comment with the actor that owns the field. If the Application uses automated sync, the entry is paired with RespectIgnoreDifferences=true, because a rule that only affects comparison is a deferred revert. When the other actor is a controller that writes through server-side apply or a stable manager name, managedFieldsManagers is the better tool, because it ignores only what that manager owns and changed, and it stops ignoring the field the moment the manager stops writing it. When the field belongs to an autoscaler, it is removed from Git instead, together with any ignore rule for it, and only after --show-managed-fields shows the autoscaler as an owner of the field.
Finally, we treat sync success and health as different signals and alert on each. A successful sync of a single-wave Application tells you the objects were accepted; it does not tell you the rollout finished, and the source code says so. Health tells you that, through checks you can read in a few hundred lines of Go and extend with Lua where a kind has none. Once you know the comparison ends in bytes.Equal on two normalised documents, each yellow tile becomes a concrete question: which pass left a difference between the documents, and which actor wrote it.
Tixraacyada
- gitops-engine/pkg/diff/diff.go (Diff, serverSideDiff, removeWebhookMutation, ThreeWayDiff, Normalize, remarshal), tag v3.6.1 Argo Project
- Tested Kubernetes versions Argo Project
- controller/state.go (CompareAppState, shouldUseServerSideDiff, useDiffCache, isSelfReferencedObj), tag v3.6.1 Argo Project
- Reconcile Optimization Argo Project
- manifests/base/config/argocd-cm.yaml (default ignoreResourceUpdates), tag v3.6.1 Argo Project
- Upgrading v2.14 to 3.0 Argo Project
- argocd-cm.yaml reference (timeout.reconciliation, timeout.reconciliation.jitter, webhook.refresh.jitter) Argo Project
- Git Webhook Configuration Argo Project
- argocd app get command reference Argo Project
- gitops-engine/pkg/sync/reconcile.go (Reconcile, dedupLiveResources), tag v3.6.1 Argo Project
- Resource Tracking Argo Project
- Compare Options Argo Project
- Diff Strategies Argo Project
- encoding/json package documentation The Go Authors
- RFC 7386: JSON Merge Patch IETF
- Getting Started Argo Project
- Sync Options Argo Project
- Quantity Kubernetes
- Diffing Customization Argo Project
- util/argo/diff/diff.go (StateDiffs, preDiffNormalize), tag v3.6.1 Argo Project
- RFC 6902: JavaScript Object Notation (JSON) Patch IETF
- RFC 6901: JavaScript Object Notation (JSON) Pointer IETF
- util/argo/normalizers/diff_normalizer.go (DefaultJQExecutionTimeout, getJQExecutionTimeout), tag v3.6.1 Argo Project
- manifests/install.yaml (argocd-application-controller environment), tag v3.6.1 Argo Project
- cmd/argocd-application-controller/commands/argocd_application_controller.go (ignore-normalizer-jq-execution-timeout-seconds), tag v3.6.1 Argo Project
- KEP-555: Server-side apply Kubernetes SIG API Machinery
- KEP-555 kep.yaml (milestones) Kubernetes SIG API Machinery
- Server-Side Apply Kubernetes
- FieldsV1 v1 meta Kubernetes
- gitops-engine/pkg/sync/sync_context.go (Sync, applyObject, performCSAUpgradeMigration), tag v3.6.1 Argo Project
- gitops-engine/pkg/utils/kube/resource_ops.go (ApplyResource, newApplyOptions), tag v3.6.1 Argo Project
- k8s.io/kubectl pkg/cmd/apply/apply.go (applyOneObject, migrateToSSAIfNecessary), v0.37.0 Kubernetes
- k8s.io/client-go util/csaupgrade/upgrade.go (UpgradeManagedFieldsPatch), v0.37.0 Kubernetes
- gitops-engine/pkg/diff/diff_options.go (K8sServerSideDryRunner.Run), tag v3.6.1 Argo Project
- argocd-cmd-params-cm.yaml reference Argo Project
- controller/sync.go (normalizeTargetResources, delayBetweenSyncWaves), tag v3.6.1 Argo Project
- gitops-engine/pkg/sync/sync_tasks.go (syncPhaseOrder, kindOrder, Less, multiStep), tag v3.6.1 Argo Project
- Sync Phases and Waves Argo Project
- Automated Sync Policy Argo Project
- controller/appcontroller.go (autoSync, alreadyAttemptedSync, processRequestedAppOperation, selfHealRemainingBackoff), tag v3.6.1 Argo Project
- pkg/apis/application/v1alpha1/application_defaults.go (DefaultSyncRetryDuration, DefaultSyncRetryFactor, DefaultSyncRetryMaxDuration), tag v3.6.1 Argo Project
- pkg/apis/application/v1alpha1/types.go (RetryStrategy.NextRetryAt), tag v3.6.1 Argo Project
- gitops-engine/pkg/health/health.go (GetResourceHealth, healthOrder), tag v3.6.1 Argo Project
- Resource Health Argo Project
- gitops-engine/pkg/health/health_deployment.go, tag v3.6.1 Argo Project
- controller/health.go (setApplicationHealth), tag v3.6.1 Argo Project
- resource_customizations/argoproj.io/Application, tag v3.6.1 Argo Project
- kind v0.33.0 release notes (node images) Kubernetes SIGs
- argocd-example-apps guestbook at commit 8088f4c Argo Project
- kind known issues: pod errors due to "too many open files" Kubernetes SIGs
- Git commit signature verification: disabling the feature Argo Project
- argocd app diff command reference Argo Project