From 06b722160c4b01514e093b1383b79c493c3942fd Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 5 Nov 2026 09:38:33 +0300 Subject: [PATCH] fix(cms-deploy): preserve Compose-owned image labels --- infra/cms-deploy/R41_BASE_DISCOVERY.md | 5 ++ infra/cms-deploy/R41_COMPOSE_LABELS.md | 54 +++++++++++++++ infra/cms-deploy/README.md | 4 ++ infra/cms-deploy/autodeploy_runtime.py | 2 + infra/cms-deploy/release_runtime.py | 90 ++++++++++++++++++++----- infra/cms-deploy/test_build_base.py | 57 ++++++++++++++-- infra/deploy-runner/nodedc-deploy | 92 +++++++++++++++++++++----- 7 files changed, 263 insertions(+), 41 deletions(-) create mode 100644 infra/cms-deploy/R41_COMPOSE_LABELS.md diff --git a/infra/cms-deploy/R41_BASE_DISCOVERY.md b/infra/cms-deploy/R41_BASE_DISCOVERY.md index 485b623..b666197 100644 --- a/infra/cms-deploy/R41_BASE_DISCOVERY.md +++ b/infra/cms-deploy/R41_BASE_DISCOVERY.md @@ -56,3 +56,8 @@ runner is a relevant external-state change; no application artifact is changed or restaged. r39/r40 and bootstrap/reconciliation remain terminal and must not be replayed. An actual canonical application receipt is still required before multisite migration and public-site publication. + +Post-promotion evidence: the operator verified aa507dc and the controller reached +`cms-base-missing` at 06:29:54 UTC. The lookup worked but no candidate passed the +predicate. A reproducible Compose-label ownership error and the corrected +build model are documented in [the follow-up](R41_COMPOSE_LABELS.md). diff --git a/infra/cms-deploy/R41_COMPOSE_LABELS.md b/infra/cms-deploy/R41_COMPOSE_LABELS.md new file mode 100644 index 0000000..0ff97ba --- /dev/null +++ b/infra/cms-deploy/R41_COMPOSE_LABELS.md @@ -0,0 +1,54 @@ +# CMS r41: preserve Compose-owned image labels + +The operator installed and verified runner SHA +`aa507dc77acdead0d3cd76db0f0254dca1b2f707638361b6e5e8cac1b5d6448b` +on 2026-11-05. At 06:29:54 UTC its automatic preflight reported +`CmsBuildBaseError`, reason `cms-base-missing`. r41 remained staged, with no +application receipt or backup. This means no discovered candidate passed the +predicate, not that Docker necessarily lacks the filesystem base. + +The predicate had a reproducible ownership error: it required base-image Labels +to equal application-image Labels. Compose's BuildKit path adds its own project, +service and version labels to the application image. These are build metadata, +not inherited Node configuration. The behavior is explicit in +[Compose 2.20.3 getImageBuildLabels](https://github.com/docker/compose/blob/v2.20.3/pkg/compose/build.go#L502-L513). +The old direct-docker fixture omitted that production build path, so its passing +result did not test this case. Whether this is the sole NAS mismatch is still +unproven; do not claim the production base has already been accepted. + +The corrected model permits exactly three Compose-owned additions: project must +be dc-cms, service must be cms-app, and version must be a bounded-format numeric +version with an optional release suffix. Partial, unknown or malformed Compose +labels fail. All other labels must still match the base exactly. The builder +passes those same three accepted values through explicit --label arguments; +it does not choose the local Compose version or delete any metadata. The full +post-build Labels comparison remains exact, as do Env, layers, platform and +all existing runtime/rollback guards. No change to the registered Dockerfile, +payload, service set, dependencies, sites, authentication or release queue. + +Missing/ambiguous-base errors now carry a bounded diagnostic containing only +parent/node candidate counts and fixed rejection-category counts (layers, +platform, base shape, inherited config, labels, environment, Node version). +The public status validates this shape again; raw image fields, arbitrary keys, +label values, environment values and external stderr are never exported. + +Validation: 95 CMS tests and 95 Device Core tests. New cases cover exact Compose +additions, inherited-label drift, wrong project/service, partial/unknown labels, +malformed version, exact builder flags, final Env/Labels mismatch before runtime +recreation and diagnostic redaction. Python 3.8 AST and diff checks pass. + +A separate real local integration builds an isolated fixture with actual Docker +Compose/BuildKit (local Compose 5.0.0), without mocked image inspection. The +installed aa507dc predicate rejects that known base; the corrected predicate +accepts it through the real Node-only lookup. The canonical builder then builds +from the same immutable base using legacy Docker, retaining the exact full Env +and Compose labels. All exported layers exclude the private-project fixture, +and the registered source Dockerfile stays unchanged. Test tags are removed; +no NAS or workload containers are involved. Local evidence is not proof of NAS +cache availability. + +The candidate is promoted through the same tested SHA-pinned root gate, with +aa507dc as predecessor. The existing automatic controller then replans queued +r41; no manual Docker action, image pull, failed-run replay or new application +commit is required. A successful canonical application receipt remains required +before the multisite migration and public Mission Core publication. diff --git a/infra/cms-deploy/README.md b/infra/cms-deploy/README.md index d6f2f04..ed004e9 100644 --- a/infra/cms-deploy/README.md +++ b/infra/cms-deploy/README.md @@ -67,3 +67,7 @@ but the original global image lookup was rejected during preflight. The with a bounded Node-only cache fallback and safe public error codes. After runner promotion the controller may resume staged r41 with a fresh plan; no bootstrap or failed-release replay is needed. +The scoped runner was installed; its preflight reported no matching base. +The [Compose-label correction](R41_COMPOSE_LABELS.md) accounts for the three +labels added by Compose, reproduces them during build, and retains exact +post-build configuration comparison. Deployment is still pending its promotion. diff --git a/infra/cms-deploy/autodeploy_runtime.py b/infra/cms-deploy/autodeploy_runtime.py index a558497..f15e2fd 100644 --- a/infra/cms-deploy/autodeploy_runtime.py +++ b/infra/cms-deploy/autodeploy_runtime.py @@ -319,6 +319,8 @@ def cms_autodeploy_error_status(error, policy_errors): # private, even if a caller mutates the exception's message or code. if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES: result['reason']=error.code + diagnostic=cms_base_public_diagnostic(error.diagnostic) + if diagnostic is not None:result['baseLookup']=diagnostic return result diff --git a/infra/cms-deploy/release_runtime.py b/infra/cms-deploy/release_runtime.py index 783a5a3..f502be9 100644 --- a/infra/cms-deploy/release_runtime.py +++ b/infra/cms-deploy/release_runtime.py @@ -182,15 +182,27 @@ CMS_BUILD_BASE_ERROR_CODES = frozenset(( 'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch', 'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth', 'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format', - 'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous', + 'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous','cms-base-build-labels', )) +CMS_BASE_REJECTION_CODES = frozenset(('layers','platform','base-shape','inherited-config','labels','environment','node-version')) + + +def cms_base_public_diagnostic(value): + # Public counts only, never arbitrary keys/values from image inspection. + if not isinstance(value,dict) or set(value)!={'parentCount','nodeCount','rejected'}:return None + if any(type(value[k]) is not int or not 0<=value[k]<=384 for k in ('parentCount','nodeCount')):return None + rejected=value['rejected'] + if not isinstance(rejected,dict) or not set(rejected)<=CMS_BASE_REJECTION_CODES:return None + if any(type(v) is not int or not 0<=v<=384 for v in rejected.values()):return None + return {'parentCount':value['parentCount'],'nodeCount':value['nodeCount'],'rejected':dict(rejected)} class CmsBuildBaseError(DeployError): - def __init__(self, code): + def __init__(self, code, diagnostic=None): if code not in CMS_BUILD_BASE_ERROR_CODES: raise ValueError('Unknown CMS base error code') self.code=code + self.diagnostic=cms_base_public_diagnostic(diagnostic) super().__init__(code) @@ -221,7 +233,35 @@ def cms_inspect_image(identity): return rows[0] -def cms_node_base_matches(image, accepted): +def cms_image_build_labels(config): + labels=config.get('Labels') + if labels is None:return {} + if not isinstance(labels,dict) or any(not isinstance(k,str) or not isinstance(v,str) for k,v in labels.items()): + raise CmsBuildBaseError('cms-base-build-labels') + owned={k:v for k,v in labels.items() if k.startswith('com.docker.compose.')} + if not owned:return {} + prefix='com.docker.compose.' + if (set(owned)!={prefix+'project',prefix+'service',prefix+'version'} + or owned[prefix+'project']!='dc-cms' or owned[prefix+'service']!='cms-app' + or len(owned[prefix+'version'])>80 + or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?',owned[prefix+'version'])): + raise CmsBuildBaseError('cms-base-build-labels') + return owned + + +def cms_base_labels_match(config, accepted): + # Compose's BuildKit path adds exactly project/service/version to the app + # image, not its Node base. Reproduce these labels; never ignore drift. + try:build_labels=cms_image_build_labels(accepted) + except CmsBuildBaseError:return False + base=config.get('Labels');old=accepted.get('Labels') + if base==old:return True + if not build_labels or (base is not None and not isinstance(base,dict)):return False + base=base or {} + return not set(base)&set(build_labels) and {**base,**build_labels}==old + + +def cms_node_base_rejection(image, accepted): # Prove filesystem ancestry AND the exact config inherited by the fixed # Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof. layers=(image.get('RootFS') or {}).get('Layers') @@ -231,27 +271,39 @@ def cms_node_base_matches(image, accepted): or not isinstance(layers,list) or not isinstance(original,list) or not layers or len(layers)>=len(original) or original[:len(layers)]!=layers or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)): - return False + return 'layers' if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')): - return False + return 'platform' config=image.get('Config') or {};old=accepted.get('Config') or {} if (image.get('Os')!='linux' or config.get('Cmd')!=['node'] or config.get('WorkingDir') not in ('',None) or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{}) or config.get('ExposedPorts') not in (None,{})): - return False - for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck','Labels'): - if config.get(key)!=old.get(key):return False + return 'base-shape' + for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck'): + if config.get(key)!=old.get(key):return 'inherited-config' + if not cms_base_labels_match(config,old):return 'labels' try: env=cms_image_env(config);old_env=cms_image_env(old) except DeployError: - return False - if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return False - return {**env,'HOST':'0.0.0.0','PORT':'8090'}==old_env + return 'environment' + if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return 'node-version' + if {**env,'HOST':'0.0.0.0','PORT':'8090'}!=old_env:return 'environment' + return None + + +def cms_node_base_matches(image, accepted): + return cms_node_base_rejection(image,accepted) is None def cms_resolve_build_base(runtime): accepted=cms_inspect_image(runtime['imageId']) + diagnostic={'parentCount':0,'nodeCount':0,'rejected':{}} + def matches(image,kind): + diagnostic[kind]+=1 + reason=cms_node_base_rejection(image,accepted) + if reason is not None:diagnostic['rejected'][reason]=diagnostic['rejected'].get(reason,0)+1 + return reason is None # Legacy builds retain immutable Parent edges, including untagged bases. # Follow this app's ancestry, never enumerate another component's cache. current=accepted;seen={accepted['Id']};base=None @@ -272,7 +324,7 @@ def cms_resolve_build_base(runtime): raise CmsBuildBaseError('cms-base-parent-layers') if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')): raise CmsBuildBaseError('cms-base-parent-platform') - if cms_node_base_matches(image,accepted): + if matches(image,'parentCount'): base=image;break current=image else: @@ -287,13 +339,13 @@ def cms_resolve_build_base(runtime): if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit') if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows): raise CmsBuildBaseError('cms-base-inventory-format') - matches=[] + found=[] for identity in sorted(set(rows)): image=cms_inspect_image(identity) - if cms_node_base_matches(image,accepted):matches.append(image) - if not matches:raise CmsBuildBaseError('cms-base-missing') - if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous') - base=matches[0];method='node-cache' + if matches(image,'nodeCount'):found.append(image) + if not found:raise CmsBuildBaseError('cms-base-missing',diagnostic) + if len(found)!=1:raise CmsBuildBaseError('cms-base-ambiguous',diagnostic) + base=found[0];method='node-cache' proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'], 'layersSha256':cms_audit_digest(base['RootFS']['Layers']), 'configSha256':cms_audit_digest(base['Config'])} @@ -342,7 +394,9 @@ def build_cms_release(before): (context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1]) # Docker 24's legacy builder accepts a local image ID in FROM. BuildKit # interprets sha256: as a registry repository and must not be used. - subprocess.run([str(DOCKER),'build','--pull=false','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], + labels=cms_image_build_labels(accepted.get('Config') or {}) + label_args=[item for key,value in sorted(labels.items()) for item in ('--label',key+'='+value)] + subprocess.run([str(DOCKER),'build','--pull=false',*label_args,'--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'}) image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image') if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous') diff --git a/infra/cms-deploy/test_build_base.py b/infra/cms-deploy/test_build_base.py index 09370ad..a084c57 100644 --- a/infra/cms-deploy/test_build_base.py +++ b/infra/cms-deploy/test_build_base.py @@ -27,6 +27,10 @@ def proof(base,old): 'configSha256':r.cms_audit_digest(base['Config'])} +def compose_labels(): + return {'com.docker.compose.project':'dc-cms','com.docker.compose.service':'cms-app','com.docker.compose.version':'2.20.3'} + + class CmsBuildBaseTests(unittest.TestCase): def test_proves_actual_ancestry_and_inherited_environment(self): base,old=images();saved=copy.deepcopy(base) @@ -51,6 +55,29 @@ class CmsBuildBaseTests(unittest.TestCase): with self.assertRaises(r.DeployError) as error:r.cms_image_env({'Env':env}) self.assertNotIn('private-fixture',str(error.exception)) + def test_compose_build_labels_are_owned_additions_not_inherited_base_config(self): + base,old=images();old['Config']['Labels']=compose_labels() + original=copy.deepcopy((base,old)) + self.assertTrue(r.cms_node_base_matches(base,old)) + self.assertEqual(r.cms_image_build_labels(old['Config']),compose_labels()) + self.assertEqual((base,old),original) + # Extra inherited labels still have to match exactly. + base['Config']['Labels']={'vendor':'original'} + self.assertFalse(r.cms_node_base_matches(base,old)) + old['Config']['Labels']['vendor']='original' + self.assertTrue(r.cms_node_base_matches(base,old)) + for labels in [{'arbitrary':'private-fixture'}, {**compose_labels(),'com.docker.compose.extra':'private-fixture'}, + {**compose_labels(),'com.docker.compose.project':'other'}, + {**compose_labels(),'com.docker.compose.service':'other'}, + {**compose_labels(),'com.docker.compose.version':'bad\nprivate-fixture'}, + {**compose_labels(),'com.docker.compose.version':'2.20.3+'+'a'*81}, + {'com.docker.compose.project':'dc-cms'},['private-fixture']]: + b,o=images();o['Config']['Labels']=labels + self.assertFalse(r.cms_node_base_matches(b,o)) + for labels in [{**compose_labels(),'com.docker.compose.extra':'private-fixture'},['private-fixture']]: + with self.assertRaises(r.CmsBuildBaseError) as error:r.cms_image_build_labels({'Labels':labels}) + self.assertNotIn('private-fixture',str(error.exception)) + def test_parent_chain_finds_untagged_base_without_global_inventory(self): base,old=images();middle=copy.deepcopy(old);middle['Id']='sha256:'+'c'*64 old['Parent']=middle['Id'];middle['Parent']=base['Id'] @@ -135,9 +162,26 @@ class CmsBuildBaseTests(unittest.TestCase): self.assertNotIn('reason',result);self.assertNotIn('fixture',json.dumps(result)) with self.assertRaises(ValueError):r.CmsBuildBaseError('secret-fixture') + def test_missing_base_diagnostic_has_only_bounded_rejection_counts(self): + base,old=images();old['Config']['Labels']={'private-fixture':'never-export'} + inventory={i['Id']:i for i in (base,old)} + with patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__),patch.object(r,'cms_base_docker_json',return_value=[base['Id']]): + with self.assertRaises(r.CmsBuildBaseError) as error:r.cms_resolve_build_base({'imageId':old['Id']}) + status=r.cms_autodeploy_error_status(error.exception,()) + self.assertEqual(status['baseLookup'],{'parentCount':0,'nodeCount':1,'rejected':{'labels':1}}) + self.assertNotIn('private-fixture',json.dumps(status));self.assertNotIn('never-export',json.dumps(status)) + for value in [None,{}, {'parentCount':0,'nodeCount':1,'rejected':{'private-fixture':1}}, + {'parentCount':0,'nodeCount':1,'rejected':{'labels':'private-fixture'}}, + {'parentCount':True,'nodeCount':1,'rejected':{}}, + {'parentCount':0,'nodeCount':99999,'rejected':{}}, + {'parentCount':0,'nodeCount':1,'rejected':{},'extra':'private-fixture'}]: + error.exception.diagnostic=value + self.assertNotIn('baseLookup',r.cms_autodeploy_error_status(error.exception,())) + def test_build_pins_only_clean_temporary_recipe_and_rejects_drift_before_recreation(self): - base,old=images() - for drift in [False,True]: + for drift,with_labels in [(d,l) for d in ('none','env','labels') for l in (False,True)]: + base,old=images() + if with_labels:old['Config']['Labels']=compose_labels() with tempfile.TemporaryDirectory() as directory: root=Path(directory);entries,_=fixture(root) recipe=b'FROM node:24-alpine\nWORKDIR /app\n' @@ -145,17 +189,20 @@ class CmsBuildBaseTests(unittest.TestCase): (root/'projects').mkdir();(root/'projects/password.json').write_text('private-fixture') before={'entries':entries,'runtime':{'imageRef':'dc-cms-cms-app','imageId':old['Id']},'buildBase':proof(base,old)} built=copy.deepcopy(old);built['Id']='sha256:'+'e'*64 - if drift:built['Config']['Env'].append('TOKEN=private-fixture') + if drift=='env':built['Config']['Env'].append('TOKEN=private-fixture') + if drift=='labels':built['Config']['Labels']={**(built['Config'].get('Labels') or {}),'private':'private-fixture'} def build(cmd,**kwargs): self.assertIn('--pull=false',cmd) self.assertEqual(kwargs['env']['DOCKER_BUILDKIT'],'0') + actual_labels=[cmd[i+1] for i,value in enumerate(cmd) if value=='--label'] + self.assertEqual(actual_labels,[k+'='+v for k,v in sorted(compose_labels().items())] if with_labels else []) context=Path(cmd[-1]);self.assertEqual(list((context/'projects').iterdir()),[]) self.assertEqual((context/'Dockerfile').read_bytes(),('FROM '+base['Id']+'\nWORKDIR /app\n').encode()) self.assertEqual(set(p.relative_to(context).as_posix() for p in context.rglob('*') if p.is_file()),set(entries)|{'Dockerfile'}) self.assertNotIn('private-fixture',str(cmd)) with patch.object(r,'CMS_ROOT',root),patch.object(r,'TMP_DIR',root),patch.dict(r.CMS_FOUNDATION,{'Dockerfile':r.hashlib.sha256(recipe).hexdigest()}),patch.object(r,'cms_inspect_image',side_effect=[base,old]),patch.object(r.subprocess,'run',side_effect=build),patch.object(r,'docker_json',return_value=[built]),redirect_stdout(io.StringIO()): - if drift: - with self.assertRaisesRegex(r.DeployError,'before recreation: Env') as error:r.build_cms_release(before) + if drift!='none': + with self.assertRaisesRegex(r.DeployError,'before recreation: '+('Env' if drift=='env' else 'Labels')) as error:r.build_cms_release(before) self.assertNotIn('private-fixture',str(error.exception)) else:r.build_cms_release(before) self.assertEqual((root/'Dockerfile').read_bytes(),recipe) diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index c8a0b86..a6810ce 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -43141,15 +43141,27 @@ CMS_BUILD_BASE_ERROR_CODES = frozenset(( 'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch', 'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth', 'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format', - 'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous', + 'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous','cms-base-build-labels', )) +CMS_BASE_REJECTION_CODES = frozenset(('layers','platform','base-shape','inherited-config','labels','environment','node-version')) + + +def cms_base_public_diagnostic(value): + # Public counts only, never arbitrary keys/values from image inspection. + if not isinstance(value,dict) or set(value)!={'parentCount','nodeCount','rejected'}:return None + if any(type(value[k]) is not int or not 0<=value[k]<=384 for k in ('parentCount','nodeCount')):return None + rejected=value['rejected'] + if not isinstance(rejected,dict) or not set(rejected)<=CMS_BASE_REJECTION_CODES:return None + if any(type(v) is not int or not 0<=v<=384 for v in rejected.values()):return None + return {'parentCount':value['parentCount'],'nodeCount':value['nodeCount'],'rejected':dict(rejected)} class CmsBuildBaseError(DeployError): - def __init__(self, code): + def __init__(self, code, diagnostic=None): if code not in CMS_BUILD_BASE_ERROR_CODES: raise ValueError('Unknown CMS base error code') self.code=code + self.diagnostic=cms_base_public_diagnostic(diagnostic) super().__init__(code) @@ -43180,7 +43192,35 @@ def cms_inspect_image(identity): return rows[0] -def cms_node_base_matches(image, accepted): +def cms_image_build_labels(config): + labels=config.get('Labels') + if labels is None:return {} + if not isinstance(labels,dict) or any(not isinstance(k,str) or not isinstance(v,str) for k,v in labels.items()): + raise CmsBuildBaseError('cms-base-build-labels') + owned={k:v for k,v in labels.items() if k.startswith('com.docker.compose.')} + if not owned:return {} + prefix='com.docker.compose.' + if (set(owned)!={prefix+'project',prefix+'service',prefix+'version'} + or owned[prefix+'project']!='dc-cms' or owned[prefix+'service']!='cms-app' + or len(owned[prefix+'version'])>80 + or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?',owned[prefix+'version'])): + raise CmsBuildBaseError('cms-base-build-labels') + return owned + + +def cms_base_labels_match(config, accepted): + # Compose's BuildKit path adds exactly project/service/version to the app + # image, not its Node base. Reproduce these labels; never ignore drift. + try:build_labels=cms_image_build_labels(accepted) + except CmsBuildBaseError:return False + base=config.get('Labels');old=accepted.get('Labels') + if base==old:return True + if not build_labels or (base is not None and not isinstance(base,dict)):return False + base=base or {} + return not set(base)&set(build_labels) and {**base,**build_labels}==old + + +def cms_node_base_rejection(image, accepted): # Prove filesystem ancestry AND the exact config inherited by the fixed # Dockerfile. Neither a mutable tag nor a matching NODE_VERSION is proof. layers=(image.get('RootFS') or {}).get('Layers') @@ -43190,27 +43230,39 @@ def cms_node_base_matches(image, accepted): or not isinstance(layers,list) or not isinstance(original,list) or not layers or len(layers)>=len(original) or original[:len(layers)]!=layers or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in layers)): - return False + return 'layers' if any(image.get(key)!=accepted.get(key) for key in ('Os','Architecture','Variant')): - return False + return 'platform' config=image.get('Config') or {};old=accepted.get('Config') or {} if (image.get('Os')!='linux' or config.get('Cmd')!=['node'] or config.get('WorkingDir') not in ('',None) or config.get('OnBuild') not in (None,[]) or config.get('Volumes') not in (None,{}) or config.get('ExposedPorts') not in (None,{})): - return False - for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck','Labels'): - if config.get(key)!=old.get(key):return False + return 'base-shape' + for key in ('User','Entrypoint','Shell','StopSignal','Healthcheck'): + if config.get(key)!=old.get(key):return 'inherited-config' + if not cms_base_labels_match(config,old):return 'labels' try: env=cms_image_env(config);old_env=cms_image_env(old) except DeployError: - return False - if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return False - return {**env,'HOST':'0.0.0.0','PORT':'8090'}==old_env + return 'environment' + if not re.fullmatch(r'24\.[0-9]+\.[0-9]+',env.get('NODE_VERSION','')):return 'node-version' + if {**env,'HOST':'0.0.0.0','PORT':'8090'}!=old_env:return 'environment' + return None + + +def cms_node_base_matches(image, accepted): + return cms_node_base_rejection(image,accepted) is None def cms_resolve_build_base(runtime): accepted=cms_inspect_image(runtime['imageId']) + diagnostic={'parentCount':0,'nodeCount':0,'rejected':{}} + def matches(image,kind): + diagnostic[kind]+=1 + reason=cms_node_base_rejection(image,accepted) + if reason is not None:diagnostic['rejected'][reason]=diagnostic['rejected'].get(reason,0)+1 + return reason is None # Legacy builds retain immutable Parent edges, including untagged bases. # Follow this app's ancestry, never enumerate another component's cache. current=accepted;seen={accepted['Id']};base=None @@ -43231,7 +43283,7 @@ def cms_resolve_build_base(runtime): raise CmsBuildBaseError('cms-base-parent-layers') if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')): raise CmsBuildBaseError('cms-base-parent-platform') - if cms_node_base_matches(image,accepted): + if matches(image,'parentCount'): base=image;break current=image else: @@ -43246,13 +43298,13 @@ def cms_resolve_build_base(runtime): if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit') if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows): raise CmsBuildBaseError('cms-base-inventory-format') - matches=[] + found=[] for identity in sorted(set(rows)): image=cms_inspect_image(identity) - if cms_node_base_matches(image,accepted):matches.append(image) - if not matches:raise CmsBuildBaseError('cms-base-missing') - if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous') - base=matches[0];method='node-cache' + if matches(image,'nodeCount'):found.append(image) + if not found:raise CmsBuildBaseError('cms-base-missing',diagnostic) + if len(found)!=1:raise CmsBuildBaseError('cms-base-ambiguous',diagnostic) + base=found[0];method='node-cache' proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'], 'layersSha256':cms_audit_digest(base['RootFS']['Layers']), 'configSha256':cms_audit_digest(base['Config'])} @@ -43301,7 +43353,9 @@ def build_cms_release(before): (context/'Dockerfile').write_bytes(('FROM '+base['Id']+'\n').encode()+dockerfile.split(b'\n',1)[1]) # Docker 24's legacy builder accepts a local image ID in FROM. BuildKit # interprets sha256: as a registry repository and must not be used. - subprocess.run([str(DOCKER),'build','--pull=false','--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], + labels=cms_image_build_labels(accepted.get('Config') or {}) + label_args=[item for key,value in sorted(labels.items()) for item in ('--label',key+'='+value)] + subprocess.run([str(DOCKER),'build','--pull=false',*label_args,'--file',str(context/'Dockerfile'),'--tag',before['runtime']['imageRef'],str(context)], check=True,env={**os.environ,'DOCKER_BUILDKIT':'0'}) image=docker_json(['image','inspect',before['runtime']['imageRef']],'CMS built image') if not isinstance(image,list) or len(image)!=1:die('CMS built image is ambiguous') @@ -44036,6 +44090,8 @@ def cms_autodeploy_error_status(error, policy_errors): # private, even if a caller mutates the exception's message or code. if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES: result['reason']=error.code + diagnostic=cms_base_public_diagnostic(error.diagnostic) + if diagnostic is not None:result['baseLookup']=diagnostic return result