{"record":{"id":"5e6d5e65ec9f82e3","repo":"zhisheng17/flink-learning","slug":"already-exists-in-configmap","errorCode":null,"errorMessage":"{} already exists in ConfigMap {}","messagePattern":"(.+?) already exists in ConfigMap (.+?)","errorType":"exception","errorClass":"AlreadyExistException","httpStatus":null,"severity":"error","filePath":"flink-learning-k8s/flink-k8s/src/main/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStore.java","lineNumber":128,"sourceCode":"\tpublic RetrievableStateHandle<T> addAndLock(String key, T state) throws Exception {\n\t\tcheckNotNull(key, \"Key in ConfigMap.\");\n\t\tcheckNotNull(state, \"State.\");\n\n\t\tfinal RetrievableStateHandle<T> storeHandle = storage.store(state);\n\n\t\tboolean success = false;\n\n\t\ttry {\n\t\t\tfinal byte[] serializedStoreHandle = InstantiationUtil.serializeObject(storeHandle);\n\t\t\tsuccess = kubeClient.checkAndUpdateConfigMap(\n\t\t\t\tconfigMapName,\n\t\t\t\tc -> {\n\t\t\t\t\tif (KubernetesLeaderElector.hasLeadership(c, lockIdentity)) {\n\t\t\t\t\t\tif (!c.getData().containsKey(key)) {\n\t\t\t\t\t\t\tc.getData().put(key, encodeStateHandle(serializedStoreHandle));\n\t\t\t\t\t\t\treturn Optional.of(c);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow new CompletionException(getKeyAlreadyExistException(key));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn Optional.empty();\n\t\t\t\t}).get();\n\t\t\treturn storeHandle;\n\t\t} catch (Exception ex) {\n\t\t\tthrow ExceptionUtils.findThrowable(ex, AlreadyExistException.class).orElseThrow(() -> ex);\n\t\t} finally {\n\t\t\tif (!success) {\n\t\t\t\t// Cleanup the state handle if it was not written to ConfigMap.\n\t\t\t\tif (storeHandle != null) {\n\t\t\t\t\tstoreHandle.discardState();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**","sourceCodeStart":110,"sourceCodeEnd":146,"githubUrl":"https://github.com/zhisheng17/flink-learning/blob/d731cee7618021be56d132cc925102ffff8d75e6/flink-learning-k8s/flink-k8s/src/main/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStore.java#L110-L146","documentation":"KubernetesStateHandleStore.addAndLock() throws this when the key being added already exists in the ConfigMap and the caller holds leadership. It maps getKeyAlreadyExistException(key) through the completed transaction, signalling a duplicate state-handle insert under the same key.","triggerScenarios":"addAndLock(key, stateHandle) called with a key whose value is already present in the ConfigMap while hasLeadership(c, lockIdentity) is true; the CompletionException wrapping it surfaces on .get().","commonSituations":"A retried job registration after a partially failed first attempt; stale leader re-adding a job state handle that a previous leader already stored; recovery/restart that re-runs the same key before cleanup.","solutions":["Check for the key first via check(name)/getAndLock, or delete the stale key before re-adding.","Retry with a new unique key (state handles are usually keyed by job/checkpoint id — deduplicate on retry).","Ensure leadership changed cleanly: a stale leader writing duplicate keys indicates a fence/lock problem in the ConfigMap lock identity.","If this follows a crash, clear leftover job state (KubernetesRunningJobsRegistry/state store cleanup) before re-submitting the job."],"exampleFix":"// before: blind add\nstateHandleStore.addAndLock(jobKey, handle);\n// after: guard against existing key\nif (stateHandleStore.check(jobKey).isPresent()) {\n    stateHandleStore.releaseAndTryRemove(jobKey);\n}\nstateHandleStore.addAndLock(jobKey, handle);","handlingStrategy":"validation","validationCode":"// pre-check for an existing key before addAndLock\nOptional<StoredStateHandle> existing = stateHandleStore.check(key);\nif (existing.isPresent()) {\n    stateHandleStore.releaseAndTryRemove(key);\n}\nstateHandleStore.addAndLock(key, handle);","typeGuard":null,"tryCatchPattern":"try {\n    stateHandleStore.addAndLock(key, handle);\n} catch (Exception e) {\n    if (e.getCause() != null && e.getCause().getMessage().contains(\"already exists\")) {\n        // stale key from a previous attempt — remove and retry once\n    }\n}","preventionTips":["Make add idempotent: check-then-add or remove-then-add on retry.","Clean leftover HA state after crashed runs before resubmitting.","Keep leadership fencing consistent (single lockIdentity).","Use unique keys per job/checkpoint generation."],"tags":["kubernetes","configmap","duplicate-key","high-availability"],"backgroundTag":"file-already-exists","analyzedSha":"d731cee7618021be56d132cc925102ffff8d75e6","analyzedAt":"2026-09-06T05:35:08.496Z","contentChangedAt":"2026-09-06T05:35:08.496Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}