Compare commits

..

62 Commits

Author SHA1 Message Date
alberto 8f7f7cc694 Merge pull request 'Preview of one EDF and its ADOS-2 report: notes and pointer (#213)' (#214) from feature/tea-eeg-analysis into dev 2026-11-23 12:28:13 -06:00
ulises 71adac469e ISSSTELEON pointer: results of one EDF and its ADOS-2 report without storing them (#213)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-23 12:27:38 -06:00
ulises b1a2b21fac Preview of one EDF and its ADOS-2 report: route in the architecture notes (#213) 2026-11-23 12:27:38 -06:00
alberto 7fe574c5dc Merge pull request 'TEA EEG from the app: manual-deploy flow, 10-pod Dask cluster, plan (#211)' (#212) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:40 -06:00
ulises 0b4a1ccb87 ISSSTELEON pointer: TEA EEG in Gobernanza (#211)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-23 09:35:52 -06:00
ulises 5ce450a36a TEA EEG from the app: manual-deploy README and settings, one 10-pod Dask cluster, worker build checks the Python patch, rule on the 5310 stack (#211) 2026-11-23 09:35:52 -06:00
ulises 7f8232be5d dev-data pointer: merge with dev (#184) 2026-11-23 09:35:52 -06:00
Roberto Treviño Cervantes 6f0897afcb CaMa demo: Trazabilidad loaded from the precomputed history 2026-11-23 03:37:27 -06:00
Roberto Treviño Cervantes 678aef8f1f Merge dev 2026-11-23 01:33:42 -06:00
Roberto Treviño Cervantes f28c75c600 CaMa demo patients and how to reach them; plan status after the redeploy from dev; ISSSTELEON pin 2026-11-23 01:33:22 -06:00
Roberto Treviño Cervantes 9e946b9a97 Plan: owner's decisions on the CaMa redeploy data and the survival model 2026-11-22 23:37:40 -06:00
Roberto Treviño Cervantes d4e3baa838 Plan: how to get the CaMa models and the example patients 2026-11-22 23:35:26 -06:00
Roberto Treviño Cervantes a5c19a7d21 Plan: CaMa consolidation into dev and a clean redeploy from dev 2026-11-22 23:24:44 -06:00
alberto 3c84918b85 Merge pull request 'ADOS-2 scoring by the platform: open items and pointers (#184)' (#209) from feature/tea-eeg-analysis into dev
Reviewed-on: #209
2026-11-22 22:12:45 -06:00
ulises ec91a234b8 ISSSTELEON pointer: WebApp merge (#184)
selective-ci / selective-ci (pull_request) Failing after 5s
2026-11-22 22:11:41 -06:00
ulises d7c5635641 ADOS-2 scoring by the platform: open items, submodule pointers (#184)
selective-ci / selective-ci (pull_request) Failing after 4s
2026-11-22 22:01:54 -06:00
ulises e1f0d251e1 ADOS-2 items read from the evaluation PDF: ISSSTELEON and dev-data (#184) 2026-11-22 12:10:28 -06:00
ulises 03c4a7f77b ISSSTELEON rebased onto dev with the CaCu indicators integration; open item on the CaCu risk index date migration over existing views (#184) 2026-11-22 09:53:26 -06:00
ulises d4d75a3245 TEA ADOS-2 association and EEG zones: submodules, new EEG baselines bundle, cluster image with bokeh, open items (#184) 2026-11-21 23:18:40 -06:00
ulises 3295d6d8b1 manual-deploy: TEA section for training the EEG age baselines on the Dask cluster and loading them in a second deployment (#184) 2026-11-21 20:54:10 -06:00
alberto 21062d6ad3 manual-deploy: the exported EEG baselines bundle the deployment imports (#184) 2026-11-21 20:54:10 -06:00
alberto b6eb3c836b manual-deploy: ports, EDF folder and Dask scheduler address, and the EEG baselines import log (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM fd583a630b manual-deploy: deployment A trains on the k3s Dask cluster, the simulated hospital takes the real EDFs (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM 5f9d61cf96 plans: TEA EEG analysis on the Dask cluster, what the first runs showed and the tasks that follow (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM 3b76b07fb5 dask-cluster: sync-reference checks each copied file by size, so files left by an earlier sync don't fail it (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM e428b490e4 dask-cluster: image with only the tea library and models at the platform's versions, dask worker/scheduler commands, HTTP sync of the reference folder (#184) 2026-11-21 20:54:10 -06:00
AlbertoPMDM cb399a8006 dask-cluster: Kubernetes Dask image and cluster for the TEA EEG baselines, reading reference EDFs from a local folder (#184) 2026-11-21 20:54:10 -06:00
roberto 05872352f3 Merge pull request 'Pin ISSSTELEON and dev-data with the TEA age norm and ADOS-2 relation' (#196) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: #196
2026-11-21 15:38:12 -06:00
Angel Capetillo Zavala af36309845 Pin ISSSTELEON and dev-data with the TEA age norm and ADOS-2 relation
selective-ci / selective-ci (pull_request) Failing after 6s
2026-11-21 12:23:57 -06:00
Angel Capetillo Zavala cfde376aaa Update ISSSTELEON with CaCu's figures, category groups and stratified views 2026-11-21 01:29:51 -06:00
Angel Capetillo Zavala b1e2693c99 Update ISSSTELEON with the TEA EEG follow-up fixes 2026-11-20 21:58:09 -06:00
Angel Capetillo Zavala a10485e18e Check the simulated hospital before loading it and verify every table after
The load now reads the hospital with the pinned loader image before anything is
written to the platform and refuses a missing table, missing columns, an
unreadable database or a project with no rows. A refusal leaves the instance
installed and loadable, and is recorded on it as load_attempt. After the import,
every expected table must report counts and store every row it read.
2026-11-20 21:44:29 -06:00
Angel Capetillo Zavala df3371d66f Protect the reference DEV installations from deploy, reinstall and load
Ports 18090, 18096 and 18097 hold installations kept for reference. Add them to
PROTECTED_PORTS so deploy-dev, reinstall-dev and load-dev-data refuse them even
when their registry record would otherwise allow a replacement.
2026-11-20 21:44:05 -06:00
Angel Capetillo Zavala 03c87fe922 Pin ISSSTELEON with WebApp's full domain names and shared summary layout 2026-11-20 19:55:28 -06:00
Angel Capetillo Zavala 05cf3858b1 Pin ISSSTELEON and dev-data with the tea library declared by the WebApi 2026-11-20 16:56:55 -06:00
Angel Capetillo Zavala 1433b6656e Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:45:42 -06:00
AlbertoPMDM 61d454110e dev-data submodule pointer: poblar tea --edf with files gives only the children of those files (#185) 2026-11-20 13:22:55 -06:00
angel 359e5f5f26 Merge pull request 'Pin ISSSTELEON with the CaMa selective rollback' (#188) from chore/pin-isssteleon-cama-reversion into dev
Reviewed-on: #188
2026-11-20 10:49:41 -06:00
Angel Capetillo Zavala 84160125fb Pin ISSSTELEON with the CaMa selective rollback
selective-ci / selective-ci (pull_request) Successful in 2m19s
2026-11-20 10:03:50 -06:00
AlbertoPMDM fadf94e805 Merge feature/tea-eeg-analysis into feature/tea-eeg-baseline-bundles 2026-11-20 09:40:40 -06:00
AlbertoPMDM 736a2bfb3c ISSSTELEON: TEA EEG baselines trained on site and shipped as a bundle 2026-11-20 09:36:41 -06:00
AlbertoPMDM 564a84b775 ISSSTELEON: loading a TEA EEG baseline leaves sys.path as it was (#184) 2026-11-20 09:33:21 -06:00
angel 322dd5dbad Merge pull request 'Pin ISSSTELEON with final CaMa demo composition' (#187) from feature/cama-clasificacion-histologica-isssteleon-pin into dev 2026-11-20 00:58:47 -06:00
Angel Capetillo Zavala 3a5ebe5d36 Pin ISSSTELEON with final CaMa demo composition
selective-ci / selective-ci (pull_request) Successful in 3m55s
2026-11-20 00:52:56 -06:00
AlbertoPMDM 175f3b8584 ISSSTELEON: TEA EEG baselines keep their artifacts under MLFLOW_ARTIFACT_ROOT (#184) 2026-11-19 23:17:42 -06:00
angel 5fb6677d1d Merge pull request 'Pin ISSSTELEON with the CaMa BI-RADS and histopathology updates' (#186) from feature/cama-histopathology-isssteleon-pin-2 into dev
Reviewed-on: #186
2026-11-19 21:16:08 -06:00
AlbertoPMDM 11206d9531 ISSSTELEON: WebApi locks the tea library at 0.2.0 (#184) 2026-11-19 20:34:09 -06:00
angel d12fa75196 Merge pull request 'Pin ISSSTELEON with the CaMa diagnosis-to-treatment card' (#182) from feature/cama-diagnosis-treatment-isssteleon-pin into dev
Reviewed-on: #182
2026-11-19 19:49:36 -06:00
AlbertoPMDM ecd013b08d manual-deploy: notebooks runs the webapi image the project builds instead of isssteleon/webapi:dev 2026-11-19 19:49:28 -06:00
Angel Capetillo Zavala ecc8005258 Pin ISSSTELEON with the CaMa BI-RADS and histopathology updates
selective-ci / selective-ci (pull_request) Successful in 2m14s
2026-11-19 19:48:50 -06:00
AlbertoPMDM 51d88c6d5f manual-deploy: EDF_CARPETA, real EDF files into the simulated hospital as confirmed autism cases (#185) 2026-11-19 19:20:29 -06:00
AlbertoPMDM 0693272611 ISSSTELEON: the TEA EEG analysis takes the age from the EDF header (#184) 2026-11-19 19:20:29 -06:00
Angel Capetillo Zavala f8c31cfd6e Pin ISSSTELEON with the CaMa diagnosis-to-treatment card
selective-ci / selective-ci (pull_request) Successful in 16m10s
2026-11-19 17:50:49 -06:00
Roberto Treviño Cervantes fea7970b2a wording fixes 2026-11-19 17:27:55 -06:00
Angel Capetillo Zavala c18cb4945e Update ISSSTELEON pin for CaMa WebApp changes 2026-11-19 16:07:05 -06:00
AlbertoPMDM e248d53346 TEA EEG analysis on the tea library: deploy and CI trust its submodule, migration heads and open items 2026-11-19 15:43:36 -06:00
Angel Capetillo Zavala 73d270a789 Pin DEV composition with WebApp test fixes 2026-11-19 11:45:23 -06:00
Angel Capetillo Zavala 5b2984a47c Document the simulated-hospital load trial and its limits
Records the local Docker trial of load-dev-data (throwaway hospital, real
install, loader built from the recorded commits, three indicator
recalculations ok, a second load refused), what it did not cover, and the
known limits of the generated data.
2026-11-19 01:35:21 -06:00
Angel Capetillo Zavala 43669271dd Make the disposable installer the DEV workflow and retire the conservative updater
deploy-dev now installs a selected reference on a free port with a plan and
a confirmation, and reinstall-dev and load-dev-data cover the other two
operations. The in-place updater, its backup and schema guards, the recovery
tools for failed updates and the tests of all of them are removed: DEV
instances are disposable and a reinstall does not preserve data. Nothing else
in the repository imports them; the terminal release deployment and the Docker
probe are independent.

INTEGRATION.md lists, capability by capability, what the retired tooling did
and where it went, and what was and was not exercised.
2026-11-19 01:35:21 -06:00
Angel Capetillo Zavala fab9af2e11 Add the disposable DEV installer: plan, install, clean reinstall, data load
A new installer under .gitea/deploy installs a selected WorkingNarrative
reference on a free port, replaces a registered DEV instance, and loads the
simulated hospital into an installed one. Every operation first prints a plan
that changes nothing, together with a confirmation bound to that plan's digest
(resolved commits and gitlinks, port, and the resources to remove). The
confirmed run recomputes the plan under the host lock and acts only if it is
unchanged.

References may be a branch, a tag or a full commit SHA, resolved against the
official remote. Ownership of an instance is proven by its registry record,
project name, images, mounts, volume and network; foreign resources, protected
ports and unproven instances are refused. A reinstall builds the new images
before removing anything and removes only the planned resources by ID or exact
name; no prune, compose down or forced removal is used.

The existing deploy-dev workflow and its updater are left in place; the
reinstall-dev and load-dev-data workflows are added.
2026-11-19 01:35:21 -06:00
angel 5bef06e75f Merge pull request 'Fix/notebooks deploy integration' (#180) from fix/notebooks-deploy-integration into dev
Reviewed-on: #180
2026-11-19 00:34:39 -06:00
angel a65f4759d5 Merge pull request 'Compile dbt's manifest for the WebApi CI check' (#181) from fix/ci-webapi-webapp-repair into fix/notebooks-deploy-integration
selective-ci / selective-ci (pull_request) Successful in 18m13s
Reviewed-on: #181
2026-11-19 00:13:47 -06:00
95 changed files with 5647 additions and 8033 deletions
+20 -3
View File
@@ -20,9 +20,15 @@ IMPACT = {
RETIRED_GITLINKS = {
"ISSSTELEON/indicadores_kit": {"Transformation", "models", "WebApi"},
}
DEPLOY_FILES = {".gitea/deploy/dev.py", ".gitea/deploy/host.py", ".gitea/deploy/test_dev.py",
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/deploy-dev-diagnostic.yml",
".gitea/workflows/deploy-terminal-release.yml"}
# Gitlinks whose first appearance is a recognized structural change, with the checks covering the code that uses
# them. Removing or replacing them still requires a manual mapping; later moves are compared like any gitlink.
ADDED_GITLINKS = {
"ISSSTELEON/models/libs/tea": {"models", "WebApi"},
}
DEPLOY_FILES = {".gitea/deploy/installer.py", ".gitea/deploy/registry.py", ".gitea/deploy/test_installer.py",
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/reinstall-dev.yml", ".gitea/workflows/load-dev-data.yml",
".gitea/deploy/README.md", ".gitea/deploy/INTEGRATION.md",
".gitea/workflows/deploy-dev-diagnostic.yml", ".gitea/workflows/deploy-terminal-release.yml"}
PROBE_FILES = {".gitea/probe/README.md", ".gitea/probe/docker_probe.py", ".gitea/probe/test_docker_probe.py",
".gitea/workflows/docker-persistence-probe.yml"}
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/select_checks.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
@@ -58,6 +64,11 @@ def retired_removal(full, path, left, right, after):
and not any(other.startswith(path + "/") for other in after))
def added(full, left, right):
"""Whether a known gitlink appears where nothing was before."""
return full in ADDED_GITLINKS and left is None and right is not None and right[0] == "160000"
def compare(repo, old, new, prefix, changed):
before, after = entries(repo, old), entries(repo, new)
for path in sorted(before.keys() | after.keys()):
@@ -71,6 +82,10 @@ def compare(repo, old, new, prefix, changed):
print(f"Retired submodule removed: {full}")
changed.add(full)
continue
if added(full, left, right):
print(f"Known submodule added: {full}")
changed.add(full)
continue
if not left or not right or left[0] != "160000" or right[0] != "160000":
raise RuntimeError(f"Submodule added, removed or replaced: {full}; manual CI mapping required")
child = repo / path
@@ -93,6 +108,8 @@ def select(changed):
parts = path.split("/")
if path in RETIRED_GITLINKS:
selected.update(RETIRED_GITLINKS[path])
elif path in ADDED_GITLINKS:
selected.update(ADDED_GITLINKS[path])
elif parts[0] != "ISSSTELEON":
if deploy_file(path) or path in PROBE_FILES:
continue
+35 -2
View File
@@ -36,7 +36,7 @@ class SelectionTests(unittest.TestCase):
def test_host_script_selects_deploy_checks(self):
"""A host-only change selects installer tests without selecting application suites."""
changed = {'.gitea/deploy/host.py'}
changed = {'.gitea/deploy/registry.py'}
self.assertTrue(changed & selector.DEPLOY_FILES)
self.assertEqual(selector.select(changed), set())
@@ -260,6 +260,38 @@ class SelectionTests(unittest.TestCase):
with self.assertRaisesRegex(RuntimeError, "manual CI mapping required"):
selector.compare(Path(temp), old, new, "", set())
def test_adding_the_eeg_library_is_recognized(self):
"""Adding the EEG library's gitlink below models selects the checks of the code that installs it.
Fails if the selector stops recognizing that addition (CI rejects the PR that brings the library in) or maps
it to anything but models and the WebApi, the two environments that install it."""
with tempfile.TemporaryDirectory() as temp:
old, new = self.kit_history(Path(temp), lambda run, child: run(
child, "update-index", "--add", "--cacheinfo", "160000," + "4" * 40 + ",models/libs/tea"))
changes = set()
selector.compare(Path(temp), old, new, "", changes)
self.assertEqual(changes, {"ISSSTELEON/models/libs/tea"})
self.assertEqual(selector.select(changes), {"models", "WebApi"})
def test_removing_the_eeg_library_still_fails(self):
"""Removing a known added gitlink is not covered by its entry.
Fails if the added-gitlink exception is widened to removals."""
def add(run, child):
run(child, "update-index", "--add", "--cacheinfo", "160000," + "4" * 40 + ",models/libs/tea")
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
old, new = self.kit_history(root, add)
subprocess.check_output(["git", "-C", str(root / "ISSSTELEON"), "update-index", "--force-remove",
"models/libs/tea"])
subprocess.check_output(["git", "-C", str(root / "ISSSTELEON"), "commit", "-qm", "drop"])
subprocess.check_output(["git", "-C", str(root), "add", "ISSSTELEON"])
subprocess.check_output(["git", "-C", str(root), "commit", "-qm", "drop"])
dropped = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"]).decode().strip()
with self.assertRaisesRegex(RuntimeError, "manual CI mapping required"):
selector.compare(root, new, dropped, "", set())
def test_files_under_retired_path_select_everything(self):
"""A regular path under the retired kit is unmapped, so it selects every check.
@@ -276,7 +308,8 @@ class SelectionTests(unittest.TestCase):
self.assertEqual(outputs - set(selector.CHECKS), {"probe", "deploy", "python"})
for check in selector.CHECKS:
self.assertGreaterEqual(workflow.count(f"if: steps.select.outputs.{check} == 'true'\n"), 1, check)
for impacted in [*selector.IMPACT.values(), *selector.RETIRED_GITLINKS.values()]:
for impacted in [*selector.IMPACT.values(), *selector.RETIRED_GITLINKS.values(),
*selector.ADDED_GITLINKS.values()]:
self.assertLessEqual(impacted, set(selector.CHECKS))
def test_webapi_step_serves_the_compiled_dbt_manifest(self):
+9 -6
View File
@@ -6,12 +6,15 @@ from pathlib import Path
import re
import subprocess
INSTITUTIONAL = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
# The exact origin each gitlink may come from; the EEG library is the one repository outside the organisation.
ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
'ISSSTELEON': INSTITUTIONAL + 'ISSSTELEON.git',
'ISSSTELEON/WebApi': INSTITUTIONAL + 'WebApi.git',
'ISSSTELEON/WebApp': INSTITUTIONAL + 'WebApp.git',
'ISSSTELEON/models': INSTITUTIONAL + 'models.git',
'ISSSTELEON/models/libs/tea': 'ssh://git@10.0.10.41:2222/alberto/tea.git',
'ISSSTELEON/indicadores_kit': INSTITUTIONAL + 'indicadores_kit.git',
}
SHA = re.compile(r'^[0-9a-f]{40}$')
@@ -75,7 +78,7 @@ def checkout_pinned(root):
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise ValueError('ambiguous submodule mapping: ' + full)
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + ORIGINS[full] + '.git'
origin = ORIGINS[full]
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url') != origin:
raise ValueError('untrusted submodule origin: ' + full)
git(repo, '-c', 'protocol.file.allow=never', '-c', f'submodule.{name}.url={origin}',
+36
View File
@@ -65,6 +65,42 @@ class SourceTests(unittest.TestCase):
source.checkout_pinned(self.outer)
self.assertFalse(any('--checkout' in args for _, args in self.calls))
def library_git(self, library_url):
"""`fake_git` with models pinned below the application and the EEG library pinned below models."""
models, library = self.application / 'models', self.application / 'models' / 'libs' / 'tea'
c = 'c' * 40
def fake(repo, *args, **kwargs):
repo = Path(repo)
self.calls.append((repo, args))
if args[:1] == ('ls-tree',):
links = {self.outer: f'160000 commit {self.a}\tISSSTELEON\0',
self.application: f'160000 commit {self.b}\tmodels\0', models: f'160000 commit {c}\tlibs/tea\0'}
return links.get(repo, '').encode()
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
return {self.outer: 'submodule.ISSSTELEON.path ISSSTELEON',
self.application: 'submodule.models.path models'}.get(repo, 'submodule.tea.path libs/tea')
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
return {self.outer: 'ssh://git@10.0.10.41:2222/ISSSTELEON/ISSSTELEON.git',
self.application: 'ssh://git@10.0.10.41:2222/ISSSTELEON/models.git'}.get(repo, library_url)
if args[:2] == ('rev-parse', 'HEAD'):
return {self.application: self.a, models: self.b, library: c}[repo]
return ''
return fake
def test_the_eeg_library_is_pinned_from_alberto_tea(self):
"""Fails if the library below models stops being initialised from its own origin, alberto/tea."""
with patch.object(source, 'git', side_effect=self.library_git('ssh://git@10.0.10.41:2222/alberto/tea.git')):
result = source.checkout_pinned(self.outer)
self.assertEqual(result['ISSSTELEON/models/libs/tea'], 'c' * 40)
def test_the_eeg_library_from_another_repository_is_rejected(self):
"""Fails if trusting alberto/tea lets any other repository of that owner through."""
with patch.object(source, 'git', side_effect=self.library_git('ssh://git@10.0.10.41:2222/alberto/other.git')):
with self.assertRaisesRegex(ValueError, 'untrusted submodule origin'):
source.checkout_pinned(self.outer)
self.assertFalse(any('libs/tea' in args for _, args in self.calls if '--checkout' in args))
def test_wrong_nested_checkout_is_rejected(self):
"""A nested checkout that differs from its gitlink must stop preparation."""
def fake(repo, *args, **kwargs):
+78 -22
View File
@@ -1,27 +1,83 @@
# General DEV workflow integration
# What was exercised, and what was not
`.gitea/workflows/deploy-dev.yml` accepts `puerto` and `rama`. The workflow
branch supplies the installer; `rama` resolves independently to an application
commit and its recognized recursive gitlinks, then routes an unregistered
free port to installation and a registered installation to conservative update.
The same revision takes a verified no-op path. Existing storage is never reset as
a fallback. Pending migrations are rejected for updates; post-activation failures
require manual recovery as described in [README.md](README.md).
Status of the disposable DEV installer (`installer.py`, `dataload.py`). See [README.md](README.md) for use.
Physical acceptance supplied by the operator: on 2026-11-10, port 18080 completed
an update and port 18082 a new installation, both with `status=installed` and
`recalculation=complete` at `ea198c43246e53b37b6d4fb655d8b06806560b17`. Port
18081 retained revision `55e90fd49c6982793afb0633e974b33e44e58d94`. These results
do not establish the behavior of every host, failure or recovery scenario.
## Capabilities of the retired updater and where each went
Run the deployment and selector suites from the repository root:
The conservative updater, its recovery tools and the data guards were removed after checking, one by one, that
nothing else needs them:
```sh
python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
python3 -B -m unittest discover -s .gitea/ci -p 'test_*.py' -v
git diff --check
```
| Capability of the retired tooling | Now | Why |
| --- | --- | --- |
| Install on a free port | `deploy-dev` | Covered, with a plan and a confirmation. |
| Select the application revision | `referencia`: branch, tag or full SHA | Extended; the old input took a branch only. |
| Resolve to exact commits and recursive gitlinks, record them | Same, recorded as `reference`, `revision`, `gitlinks` | Covered. |
| Compose safety checks (services, mounts, ports, notebook runner isolation, no privileged options) | `installer.verify_config` | Kept unchanged in substance. |
| Shared host lock and registry of instances | `registry.py` and the locked helper | Kept; a plan runs the helper read-only without the lock. |
| Foreign container, volume, network and port detection | `resources.py` | Kept and made stricter (exact names, mounts, image IDs). |
| Update in place with backup, schema and data guards, quiescing, recalculation checks | none | Retired by decision: DEV instances are disposable and data is not preserved on reinstall. |
| Verified no-op on the same revision | none | Retired with the updater. |
| Recovery tools for failed updates (`reconcile.py`, `reset_lab_18080.py`, `diagnose_storage.py`) | none | They only repair `updating` / `update_failed` records, which nothing creates any more. A record left in such a state is refused and needs manual inspection. The tools remain in Git history. |
| Notebook jobs volume backup | none | A reinstall deletes the volume with the instance. |
| Checked recalculation during a new install | none | Retired by decision: the worker starts with `INDICADORES_AL_INICIAR=0`. Health and routes are checked instead. |
| Clean reinstall of an instance | `reinstall-dev` | New. |
| Loading the simulated hospital | `load-dev-data` | New, replacing the manual steps of `docs/operations/dev-data-ingest.md`. |
| Terminal (native) release deployment | unchanged | Independent: `deploy-terminal/` imports nothing from here and its workflow test asserts it. |
| Host and Docker probe, checkout origin diagnostic | unchanged | `docker-persistence-probe.yml` and `origin_diagnostic.py` are independent of the installer. |
See the [operator README](README.md) for compatibility, recovery, optional pinned
schema tests and remaining operational limits. The incident-specific reset tool
and its [procedure](RESET-18080.md) are retained for existing recovery needs.
Instances created by the old workflow keep their records. They can be reinstalled when they are named
`isssteleon-dev-<puerto>`, have a commit in `revision` and a replaceable state. Instances with another name
(for example `isssteleon-dev-prueba-02` on 18080) are not reinstallable by this tooling and are never touched by it.
## Exercised
Unit tests, `python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py'` (Windows with Python 3.12 and, for
the registry, installer, data-load and workflow tests, Linux in a `python:3.12-slim` container where the symlink
cases also run):
- reference resolution against local Git repositories: branch, lightweight and annotated tag, full SHA, ambiguity,
abbreviations and ref paths refused, a reference that moves between resolution and checkout, an untrusted
submodule origin;
- registry ownership (marker, earlier DEV records, other installers, other names, non-replaceable states), linked
directories, removal that never follows links, record removed last;
- planning without side effects (no mutating Docker command, no registry entry, no write lock), the plan bound to the
composition, port free, port held by a foreign container or by the host, registered port, protected ports, existing
Docker resources;
- install, reinstall of an own instance with foreign resources left untouched, no prune/down/forced removal, a
reference that moves between plan and execution and after the build, resources that change after the build, a failed
build before removal, a failed removal (kept, recorded, new confirmation needed), a failed start (recorded,
retryable), the removal volume replaced mid-run;
- data load: plan checks (running instance, no import attempts, no earlier load, reachable hospital, pins present),
the loader built from the recorded pins, per-table counts, rejected rows, empty hospital, loader failure, indicator
recalculation error and timeout, no installation resource touched;
- the workflows' inputs, the environment-only passing of inputs and the dispatch validation.
Real Docker (Docker Desktop, Linux daemon), `ISSSTELEON-Deploy-Audit/scripts/dev_installer_trial.py`, 25 checks
passed, nothing left behind, every pre-existing resource still present. Real: Git resolution and recursive checkout
of `dev` over HTTP (outer `5bef06e`, ISSSTELEON `aa840b9`, WebApi `b1bbbc2`, WebApp `baf5edc`, models `7b2eae2`,
dev-data `3dea0ad`), export of the pinned tree, `docker compose config` of the real `dist/docker-compose.yml`,
the locked helper with the real registry, four real containers, the published port, `/health`, `/api` and `/`, the
reinstall (old containers, data, volume and network gone; a foreign container and volume untouched), refusal of
protected ports, of a port held by a foreign container and of an unknown reference.
Real Docker, `ISSSTELEON-Deploy-Audit/scripts/dev_data_load_trial.py`, 17 checks passed, nothing left behind. A
throwaway MySQL 8.4 hospital (`wnrt-hospital`) was filled by `dev_data poblar` with 60 CaCu, 60 CaMa and 40 TEA
patients; an instance was installed as above; the loader image was built by `dataload.build_loader` from the
recorded commits (dev-data `3dea0ad` and the application's `Core`, fetched from Gitea by SHA); the load ran through
the instance's published port and its own import API, which read the hospital at `host.docker.internal:39883`.
Loaded without rejections: CaCu `Paciente` 60, `CitologiaCervical` 88, `BiopsiaCervical` 7, `NotaMedica` 43; CaMa
`Paciente` 60, `Mastografia` 84, `BiopsiaMama` 17, `NotaMedica` 42; TEA 1,387 rows over eight tables. The three
indicator recalculations ended `ok`, `/reportes/importaciones` listed the loads, and a second load was refused. The
installed image was the earlier composition's (see below), so the import contract of the pinned WebApi was not
the one exercised.
## Not exercised
- The institutional daemon host (`/srv/workingnarrative-dev`, the Gitea runner, the labserver Docker daemon).
- A real image build in the trials: they tagged two local images of an earlier composition instead. The pinned
composition's own build (dbt manifest, Angular build) was verified by the CI, not here.
- Concurrent runs contending for the lock.
- The data load against the shared hospital on the server (`10.0.10.41:9505`), or on the institutional host.
- The data load against the pinned WebApi's import contract: the trial's instance ran an earlier composition's images.
- CaMa stage, receptor, Ki-67 and T strata after a load: not inspected.
- A reinstall of an instance created by the retired workflow.
+119 -522
View File
@@ -1,558 +1,155 @@
# DEV installation and conservative updates
# Disposable DEV instances
The manual `deploy-dev` workflow accepts `puerto` and the application branch `rama` (default `dev`). An unregistered,
available port installs a new instance. A registered port updates its existing
managed instance, retaining the original `data/`, project, port and connections.
Repeating the same outer revision verifies recursive gitlinks, recorded image
identities, retained configuration, storage compatibility and service health.
It records `result=unchanged` without builds, backups, restarts or recalculation.
An inconsistent installation or failed update is rejected; it never falls back
to resetting or recreating storage.
Two manual workflows manage throwaway DEV instances of ISSSTELEON on the Docker host:
## Operator quick start
After the reviewed change reaches `dev`, open **Actions → deploy-dev → Run workflow**.
Select `dev` under **Use workflow from** for the central installer, enter the public
`puerto` and application `rama` (for example `18083` and `staging`), then inspect
the workflow and application revisions and final log. The same action installs a free port or updates its registered
installation. Existing projects are discovered from their records; their names
do not have to contain the port.
| Port / record | Outcome |
| Workflow | Does |
| --- | --- |
| Unregistered and free on the daemon host | Existing fresh-install pipeline, initial migrations and checked recalculation. |
| Valid `installed`, different outer revision | Conservative backup, code/image activation, preservation checks and recalculation. |
| Valid `installed`, same outer revision | Verified no-op; preserve images, data and prior recalculation metadata. |
| Foreign port owner, missing/duplicate record, wrong images/binds or missing data | Reject; inspect the diagnosed resource or record without deleting it. |
| `updating`, `update_failed`, `failed` or another incomplete status | Reject; complete manual recovery/reconciliation before another deployment. |
| Unknown revision, schema drift, pending migration or unsupported storage | Reject before stopping services; review compatibility separately. |
| `deploy-dev` | Installs the selected version on a free port. |
| `reinstall-dev` | Removes a registered DEV instance, data included, and installs the selected version in its place. |
The outer commit, not just the application gitlink, defines the release. A new
outer commit with unchanged application pins still takes the checked update path.
Updates do not execute pending migrations: they retain the existing migration
compatibility gate. New installations continue to run their initial migrations.
Both take `puerto`, `referencia` and `confirmacion`. Data is not preserved on a reinstall: these instances are
meant to be replaced, not kept. Nothing here updates an instance in place.
Successful records contain `status=installed`, `branch`, `workflow_ref`, `workflow_sha`, `revision`, `gitlinks`, `images`
and `result=installed|updated|unchanged`. Updates also retain operation, target,
backup and archive references. `unchanged` preserves previous recovery evidence
and records `verification=complete`; it does not claim a new recalculation.
The daemon-host record is `/srv/workingnarrative-dev/<registered-project>/installation.json`.
To inspect it by port on that host without knowing the project:
## Using them
```sh
python3 -B - "$PORT" <<'PY'
import json, pathlib, sys
port = int(sys.argv[1])
matches = []
for path in pathlib.Path('/srv/workingnarrative-dev').glob('*/installation.json'):
record = json.loads(path.read_text())
if record.get('port') == port:
matches.append(record)
if len(matches) != 1:
raise SystemExit('Expected exactly one registered installation; inspect the registry')
record = matches[0]
keys = ('project', 'port', 'status', 'phase', 'result', 'branch', 'workflow_ref', 'workflow_sha', 'revision', 'gitlinks', 'images',
'verification', 'recalculation', 'operation_id', 'target_revision', 'target_images',
'backup', 'archive', 'recovery')
print(json.dumps({key: record[key] for key in keys if key in record}, indent=2))
PY
Open **Actions**, choose the workflow, select `dev` under **Use workflow from** (the installer itself comes from
that branch) and fill the inputs:
- `puerto`: the public port of the instance (1024 to 65535).
- `referencia`: a branch, a tag or the full 40-character SHA of the `WorkingNarrative` commit to install. A short
SHA, `refs/...` paths and names that are both a branch and a tag are refused.
- `confirmacion`: leave it **empty** on the first run.
The first run is a plan: it changes nothing. It resolves the reference to an exact commit, initialises the
recognised application gitlinks, checks the host, Docker and the composition, and prints the plan with a line like
```
Nothing was changed. To approve exactly this plan, run again with confirmacion=instalar-18083-4ab9210e4d779764
```
### Central workflow and application branch
Run the workflow again with the same inputs and that text in `confirmacion`. The confirmation is a digest of the
plan, so it only works for what was shown: the resolved commit and gitlinks, the port, and (for a reinstall) the
containers, volume, network and directory to remove. If anything differs when the second run recomputes the plan,
including the reference having moved to a new commit, it stops with nothing changed and prints the new
confirmation.
Gitea 1.26.2 loads the workflow from the selected **Use workflow from** branch,
as shown by its [dispatch implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go).
Choose a trusted stable branch that contains this reviewed workflow and installer.
At the time of review, remote `main` does not contain `deploy-dev.yml`; use `dev`
after this change is integrated there, or another reviewed branch containing it.
A different or old workflow can omit these controls, so protect the stable branch
and restrict workflow dispatch to trusted operators.
### Install
`rama` is independent of the workflow ref. The central installer validates the
branch name, fetches its exact `refs/heads/...` from the official repository,
and freezes the resulting commit in a separate temporary checkout. It does not
execute the target branch's workflow or deployment scripts. The target branch
may lack the workflow or contain an older version. A missing branch fails; a tag,
SHA or arbitrary ref is not substituted. A branch move after fetch does not alter
the selected commit. Builds still execute code from the application branch;
choose trusted code and retain existing Actions authorization.
Refused unless the port is free: no registry record on it, nothing on the host listening, no container publishing
it, no Docker resource named after the project, and the port not protected. On success the instance is
`isssteleon-dev-<puerto>`, with its records under `/srv/workingnarrative-dev/isssteleon-dev-<puerto>/`.
The installer verifies the workflow event and checkout, then uses the exact
recursive application gitlinks. Supported paths are ISSSTELEON, WebApp, WebApi,
models and indicadores_kit at their institutional origins; unknown paths and
origins are rejected. `branch` and `revision` describe the application, while
`workflow_ref` and `workflow_sha` describe the installer. Older records remain
eligible; a verified same-SHA no-op records the new selection without rebuilding.
The install builds the two images, starts the four services (`webapi`, `indicadores`, `notebooks`, `webapp`) and
checks the published port: `/health` answers `ok`, `/api` lists routes and `/` serves the web app. It does **not**
recalculate indicators: the worker starts with `INDICADORES_AL_INICIAR=0` and recalculates after imports.
An authorized operator can also use the [workflow dispatch API](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
with `ref` naming the stable workflow branch and both inputs, for example
`{"ref":"dev","inputs":{"puerto":"18083","rama":"staging"}}`.
This submits a real deployment. Review the selected workflow, target branch and
environment first. Local validation did not exercise the Gitea UI or runner.
See [INTEGRATION.md](INTEGRATION.md) for the controlled trial; do not use existing
installations for fault injection.
### Reinstall
## Four distinct operations
The instance must be proven to be a DEV one of this installer before anything is planned:
| Operation | Storage behavior |
| --- | --- |
| Install | Reserve a new project and create new storage; run initial migrations. |
| Update | Replace application code/images while preserving existing storage; reject pending migrations. |
| Regenerate data | Independent, explicitly authorized operation; never an automatic update or seed step. |
| Recover | Validate a backup or historical archive and restore into a new isolated location before considering a live cutover. |
- exactly one registry record on the port, named `isssteleon-dev-<puerto>`, with this installer's marker
(`installer: dev-disposable`) or the shape earlier DEV installs wrote (a commit in `revision`), in a state that can
be replaced (`preparing`, `building`, `starting`, `installed`, `failed`, `removing`);
- every container labelled as the Compose project is named as one of its services, uses only the instance's data
directory, its jobs volume and its default network, and runs an image of the record;
- the only volume of the project is its notebook jobs volume, and its only network is its default one, held only
by those containers;
- no other container reaches the instance's directory, volume or network or publishes its port.
The previous replacement path archived `codigo/`, `deploy/` and `data/`, then
created empty storage. The updater archives only `codigo/` and `deploy/`.
Existing `.archive/` contents remain untouched. Missing existing storage is an
error, including when only one required database is missing.
The plan lists each container (ID, name, image), volume, network and directory. After confirmation the installer
builds the new images first, so a reference that cannot be built never costs an instance. Immediately before
removing it re-resolves the reference and recomputes the plan; any difference stops it. Then it removes, in order,
the containers by ID, the jobs volume by name, the network by ID and the directory (links are unlinked, never
followed; the record goes last), and installs.
## Prerequisites and supported origins
Never used: `docker system prune`, `docker volume prune`, `docker network prune`, `docker compose down`, forced
removal, or any listing-based cleanup. Images are kept (see the limits).
The runner needs Python 3.12+, Git, Docker, Compose v2 (`config --format json`,
`up --pull never`) and access to exact source pins and build registries.
The daemon must be Linux and support host networking for the lock helper.
An administrator must provision `/srv/workingnarrative-dev`, private to the
deployment account, on the **daemon host**. Bind mounts must work with the
images' default user and host security policy. The helper uses `python:3.12-slim`.
Confirm which runner and daemon `ubuntu-latest` actually selects.
Refused, with nothing changed: a port with no record (use `deploy-dev`), a record of another installer or project
name, the states `updating`, `update_failed`, `replacing` and `replace_failed` left by earlier updaters (inspect them
by hand), any foreign resource sharing the instance, and the protected ports **18087** and **4397**, which are
refused by both workflows whatever their state.
Only a valid `installed` record with all expected containers matching and running is
eligible. Checks cover project/service labels, actual image IDs, published port,
exact writable `/data` binds and effective configuration against the running
API/worker environment. Foreign overlapping mounts, port owners and peers on the
instance's Docker networks are rejected. A daemon-host `flock` serializes
cooperating installation/update jobs for the whole operation.
A failure while removing keeps what remains, marks the record `removing` with the phase and error, and tells you a
new plan is needed. A failure while installing marks the record `failed` with the error and the Compose
diagnostics. Run `reinstall-dev` again to continue from either state.
This first version supports the managed local SQLite layout only:
| Setting | Required existing value |
| --- | --- |
| `CACU_DATABASE_URL` | `sqlite:////data/cacu.db` |
| `CAMA_DATABASE_URL` | `sqlite:////data/cama.db` |
| `TEA_DATABASE_URL` | `sqlite:////data/tea.db` |
| `GOVERNANCE_DATABASE_URL` | `sqlite:////data/governance.db` |
| `MLFLOW_TRACKING_URI` | `sqlite:////data/mlflow.db` |
| `MLFLOW_ARTIFACT_ROOT` | `/data/mlflow-artefactos` |
| `WEBAPI_REPORT_DIR` | `/data/reportes` |
| `INDICADORES_DIR` | `/data/indicadores` |
Operator `.env` values are retained; managed paths/version/port are fixed.
The effective Compose specification is saved privately, escaping literal dollar
signs. The one-shot worker receives resolved environment values through stdin,
avoiding Docker env-file quoting differences and secret command arguments.
External databases, custom persistent locations, linked/special storage entries,
triggers and hidden/generated columns are unsupported and rejected. Connections
are never redirected from custom storage to new local databases.
Each database must have exactly one Alembic revision, recognized by the candidate
and already at its sole head. Tables, ordered columns, types, nullability,
defaults, primary keys, indexes, foreign keys and CHECK constraints must match
the candidate's in-memory model schema. SQLite integrity and foreign key checks
must pass. Inspection overrides the application entrypoint, has no network, a
read-only root and read-only data bind. It reads migration definitions, without
invoking application migration environments.
For the currently pinned composition, admitted heads are:
| Database | Required head |
| --- | --- |
| CaCu | `b4f2d8c01e23` |
| CaMa | `c5a3e9d12f34` |
| TEA | `a3e1c7b90d12` |
| Governance | `e7c5a1f34b56` |
The candidate computes these values dynamically. Governance at `d6b4f0e23a45`
is rejected before stopping services: its next revision drops four historical
cohort tables. The fifteen removed historical revisions, absent version tables,
multiple revisions, a head stamp over mismatching structure and **every pending
migration** are rejected. There is no stamp, downgrade, automatic conversion or
historical bridge. Other engines/transitions need separate reviewed support.
## Update phases
1. Verify installation, running containers and retained configuration. Export the
complete pinned composition, build both uniquely tagged application images
and validate the controlled Compose specification. Existing services keep
running throughout preparation.
2. Inspect revisions/structure without writes. Check daemon-host space for backup,
staged source and SQLite working pages. Recheck container identities. Preparation
or compatibility failures leave the installed record/services untouched.
Candidate images may remain for investigation.
3. Record `updating` and operation/target references. Disable restart and stop the
validated worker, API and frontend, then confirm they stopped. Recheck data
directory/database identities and schema after quiescing.
4. Verify a backup at `/srv/workingnarrative-dev/.backups/<project>/<operation>/`.
Include all persistent files and empty directories. Every SQLite file, including
optional MLflow storage, uses SQLite's backup API with a standalone destination
journal mode; committed WAL pages are included. Other artifacts/logs are copied
with checksums. Recognized SQLite sidecars are represented by the normalized
backup. Source state must remain unchanged throughout.
5. Stage all code/configuration under `.updates/<operation>/`, archive only old
`codigo/` and `deploy/` under `.archive/<operation>/`, then rename staged code
into place. Original `data/` and database files stay in place.
6. Start only WebApi with a direct Gunicorn entrypoint. **Existing-instance updates
never run the image's automatic Alembic entrypoint.** Verify API health, actual
image, environment and original bind, then compare every table/file with the
quiesced snapshot before allowing recalculation.
7. Run the image's worker queue once for CaCu, CaMa and TEA, without the migration
step: `RecomputationQueue.run` (`webapi.recomputation`), or `ColaDeRecalculo.correr`
(`webapi.indicadores_vivos`) in images that predate it; the `runtime` guard action
reports which one the candidate has and the controlled worker uses the same module.
Consume old markers, require `estado=ok` for all three and no pending markers.
Check preservation with declared derived changes allowed. Start the regular
worker with `INDICADORES_AL_INICIAR=0`, then the frontend.
8. Verify services, frontend/proxied health, image/mount identities and storage
again. Record `installed`, full Git provenance and completed recalculation.
HTTP 200 alone never establishes success.
First installation reserves fresh `data/`, probes writable SQLite using the built
image's default user, and starts only the API's normal initial migration entrypoint.
It then uses the same controlled recalculation/persistence checks before starting
worker and frontend. The worker cannot migrate concurrently.
The integrity policy protects original clinical/staging tables and all Governance
rows exactly. Prior `carga`, report and cohort-history rows must survive; additions
are allowed. Declared projections, catalogs, parameter definitions and calendar/
period tables may change during recalculation. Indicator status/markers may change;
the indicator JSONL log must preserve its old prefix. All other persistent files,
including MLflow storage/artifacts and import logs, must remain unchanged. Worker
views may be rebuilt. Metadata contains hashes/counts and per-row multiplicities
for append-only history, without copying raw records into deployment metadata.
Three narrower rules come from what the current release does on real storage:
- Schema contract: each table's columns are compared by name. A migration may
create them in another order than the models declare (TEA `ordenes_estudio`
lists `ord_fecha` before `ord_tipo_estudio`); every access names its columns
(ORM repositories, import schemas, silver loaders, dbt models). Name, type,
nullability, default and primary-key position of every column, and every
index, foreign key and check, must still match exactly.
- Source mappings (`cat_sistema_fuente`, `cat_mapeo`) are written by the
application (`register`, `close`) and seeded by the `catalogs` step, which only
adds the catalog's missing forms and never changes a stored row. During a
recalculation every stored row, seeded or entered by an operator, must survive
byte for byte (closing one changes it, so it is refused). An added row must be
the catalog's own: system `catalogo`, `registrado_por=catalogo`, valid from
1900-01-01, open-ended, without `motivo`, for a form no stored row has; a new
source system other than `catalogo` is refused. Outside a recalculation any
change is refused.
- `mlflow.db` may appear during a recalculation only when it was absent and is the
store MLflow creates on first use: one schema version, the `Default`
experiment (id 0, active, workspace `default`), at most the `default` workspace
with no artifact root or archival settings, and every other table empty. An
existing store still may not change or disappear; an MLflow release that needs
a schema upgrade therefore stays refused.
## Notebook runner and its jobs volume
A composition with the `notebooks` service also declares the `trabajos_notebooks`
volume, created by Compose as `<project>_trabajos_notebooks` and mounted at
`/trabajos` in `webapi` and `notebooks` only. It holds job folders in transit: the
API assembles `.<run>-*`, renames it to `<run>/` with `job.json`, the runner adds
`result.json`, and the API imports the result into MLflow under `data/` and deletes
the folder. Finished folders remain only with `NOTEBOOK_KEEP_JOBS` or after a crash.
Queued runs exist only in the API process and as `RUNNING` MLflow runs.
| Installed / candidate | Behavior |
| --- | --- |
| Three services / three services | Unchanged procedure. |
| Three services / notebooks | Refused if any volume already has the jobs name. Compose creates it when the API starts; it must carry this project's labels and be empty. |
| Notebooks / notebooks | The record's `notebook_volume`, the retained composition and the running containers must agree. The volume is backed up, verified and compared again before the frontend starts. |
| Notebooks / three services | Refused before stopping; the volume would be orphaned. |
Checks added to every notebook installation:
- Composition: exactly `webapi`, `indicadores`, `notebooks`, `webapp`, plus the
profile-gated `entrenar` only when `docker compose config` lists it (its profile is
enabled, for example by `COMPOSE_PROFILES` in the retained `.env`) with the API
image and the single data bind. Nothing starts `entrenar`. The runner has the
candidate WebApi image, `command: [notebooks]`, user `10001:10001`, no network,
a read-only root, `cap_drop: ALL`, `no-new-privileges`, no ports and only the
jobs volume; the only top-level volume is the jobs volume with no driver, options
or `external`.
- Identity: `docker volume inspect` must report the expected name, the `local`
driver and scope, no options, and the labels `com.docker.compose.project=<project>`
and `com.docker.compose.volume=trabajos_notebooks`. Compose itself adopts an
unlabelled volume with that name without an error, so a first installation also
refuses any existing volume with it.
- Running containers: four owned containers with the expected mounts and runner
isolation; any other container that mounts the volume or its mount point, and any
one-shot (`docker compose run`) container of the project, such as `entrenar`, is
refused.
- Activity, before stopping anything, again once the frontend (the only published
port) has stopped, and after all writers stop: no `RUNNING` notebook run in
`mlflow.db` started within `NOTEBOOK_JOB_TIMEOUT` plus 30 minutes, and no job
folder that is being assembled, lacks `job.json` or `result.json`, or is not a
folder. A store whose `runs`/`tags` columns are not MLflow's is unverifiable and refused.
Every update, with or without notebooks, also refuses other writers in the
original `indicadores`, `webapi` and `notebooks` containers, before stopping
anything and again once the frontend has stopped:
- Processes (`docker top`): only what each container starts itself is accepted:
Gunicorn serving `webapi:create_app()` (directly or under `uv run`) and the
container's own `CMD` health check in `webapi`, `python -m <worker module>` in
`indicadores`, `python -m models notebooks serve` in `notebooks`. A `docker exec`
shell or job, `python -m models run ... --train`, OCR (`tesseract`), a notebook
kernel or a worker still starting up refuses the update.
- Requests (once the frontend is down, so no new one can arrive): any connection to
port 5000 from outside the API container that is established or that the API has
not closed yet (`/proc/net/tcp`, `tcp6`), which is how an import, OCR or a
`/governance/model-versions/.../train` call still being served shows up. Loopback
connections, the health check's, are ignored.
- MLflow runs: besides notebook runs, any other `RUNNING` run started within the
API's `WEBAPI_TIMEOUT` (600 s by default) plus 30 minutes refuses the update. That
is how a training or the extraction ranker's learning shows up; the learning runs
in a background thread of the API after an import has answered, with no request
and no process of its own. An older running run is taken as one a crash cut off.
The MLflow store is checked too, before stopping and after quiescing:
- Its schema revision must be the candidate MLflow's head. MLflow refuses to open
an older store ("out-of-date database schema") and updates never upgrade it, so
an update to a newer MLflow is refused until that upgrade is decided separately.
- No registered model may have a version under the `produccion` alias. With one,
the recalculation's live estimators export a cohort file to `data/cohorts/` and
store a risk batch (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), which the
persistence check protects because those tables also hold the confirmations made
in the application. Without this check the update would fail after activation.
MLflow artifacts live under `data/mlflow-artefactos/<experiment>/`: every
experiment the platform creates takes `MLFLOW_ARTIFACT_ROOT`, which the image sets,
the controlled configuration enforces for `webapi` and `indicadores` and the
installer requires of `entrenar` when its `.env` sets it. They are in the data
backup and its restore. MLflow's own `Default` experiment points at
`/app/WebApi/mlruns/0`, in the container layer; no platform code logs to it.
The jobs backup runs after the data backup, in the candidate image as root with
the volume read-only, no network and only `CHOWN`, `DAC_OVERRIDE` and `FOWNER`. It
walks with `lstat`, keeps links as links and refuses FIFOs, sockets and devices. It
writes `.backups/<project>/<operation>/notebooks/content/` and `manifest.json`
(every entry's type, mode, owner, mtime and SHA-256) and fails if the volume changes
during the copy. The helper verifies it again; `verify_restore` also restores it
to `.restores/<project>/<operation>.notebooks`. To restore by hand into an empty
volume, run `notebook_guard.py restore` with the backup read-only at `/respaldo`
and the volume at `/restaurado`, as root, with services stopped.
## Failures and recovery
No automatic image rollback or live data restore occurs. A failure after quiescing
reserves project/port as `update_failed`, with phase, operation, origin/target
references and expected backup/archive paths. Interruption may leave `updating`.
Both statuses block another automatic deploy. Partial backups/archives/stages,
old image tags and code/configuration are retained. No prune or archive cleanup runs.
Backup and optional isolated-restore parent directories are created and probed by
the locked helper before quiescing. This catches some path and permission failures
while services are still running; it does not guarantee later backup success or
identify the cause of an earlier failure.
To diagnose candidate compatibility without an update, use a trusted checkout
containing `diagnose_storage.py` and the exact retained candidate WebApi image on
the daemon host. For example, with an independently verified instance path:
### Inspecting an instance
```sh
INSTANCE=/srv/workingnarrative-dev/isssteleon-dev-prueba-02
IMAGE=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["target_images"][0])' "$INSTANCE/installation.json")
python3 -B .gitea/deploy/diagnose_storage.py --image "$IMAGE" --data "$INSTANCE/data"
cat /srv/workingnarrative-dev/isssteleon-dev-<puerto>/installation.json
```
This starts temporary read-only, network-isolated containers using the existing
candidate image without pulling it; it does not stop or start application services
or write the data mount. It emits only allowlisted rejection categories, a domain,
exception type, SQLite error name and numeric errno. A pass while services are
running cannot rule out a failure after they stop; reproduce the same state only
when the services are already stopped under an independently authorized plan.
It does not compare the before/after directory or database identities.
The record has `reference`, `reference_kind`, `revision` (the outer commit), `gitlinks` (the outer commit,
`dev-data`, `ISSSTELEON` and each application), `images`, `installer`, `plan_digest`, `status`, `verification`
and, after a reinstall, `replaced`.
### Reconcile a manually recovered pre-activation failure
## Prerequisites
Use this only after an operator has independently established that the original
installation is running unchanged. It is not a general recovery procedure.
Keep the original failed record and all artifacts; never restore over live data.
The runner needs Python 3.12+, Git and Docker with Compose v2 (`config --format json`, `up --pull never`), and
access to Gitea and the build registries. A Linux daemon is required. `/srv/workingnarrative-dev` must exist on the
daemon host, private to the deployment account. The installer starts a short-lived helper container from
`python:3.12-slim` (override with `DEV_INSTALLER_HELPER_IMAGE`) on the host network to take the host-wide lock,
write the registry and probe ports; a plan runs it read-only and without the lock.
`reconcile.py` implements an explicit `check` and `apply` on the Docker daemon
host. Both acquire the shared helper lock, check the failed record, original
revision and source gitlink, supplied container IDs, image tags and IDs, mounts,
Compose configuration, restart policies, service health, live SQLite state, the
recovery archive SHA-256 and five SQLite files in an isolated restore. The archive
must have one regular `data/<database>` member for each of those databases; the
restored data directory must match the database files and SQLite sidecars in the
archive. Integrity checks use temporary database copies including WAL and journal
files; the shared-memory index is rebuilt. Neither the tar hash nor SQLite integrity establishes full backup or
functional consistency. The external-copy flag is an operator attestation, not
an automated check of remote storage. Confirm the application and recovery copy
independently before applying. Temporary helper containers, the existing lock file and local
temporary configuration are used; the check does not write the installation or
backup. The source checkout must contain the original outer-repository revision.
The managed layout is the SQLite one under `/data`; the effective Compose file is checked (services, mounts,
ports, notebook runner isolation, no privileged options) and saved, so what runs is what was verified.
Example, from a trusted checkout on the daemon host, after setting the independently
verified original revision and the actual isolated restored `data` directory. Replace
the placeholders with verified values (without angle brackets):
```sh
REVISION_ORIGINAL=<verified-original-40-character-commit>
RESTORED_DATA=<absolute-path-to-isolated-restored-data>
python3 -B .gitea/deploy/reconcile.py check \
--instance <instance> --port <port> --revision "$REVISION_ORIGINAL" \
--operation <operation-id> \
--webapi <webapi-container-id> \
--webapp <webapp-container-id> \
--indicadores <indicadores-container-id> \
--backup <absolute-backup-path> \
--backup-sha256 <backup-sha256> \
--restored-data "$RESTORED_DATA" --external-copy-verified
```
After reviewing a successful check and authorizing the write, repeat the exact
command with `apply` in place of `check`. Apply repeats all checks under a new
lock and changes only `status` atomically, provided the record is unchanged.
An `eligible` check is not a reservation: validate again with `apply`.
1. Stop deployment jobs, acquire the same shared helper lock and retain it through
the checks and record write. Privately copy `installation.json` outside the
instance and record its hash. Confirm project, port and operation ID against
the incident, and require `update_failed` in `quiescing`, `backup`, or
`restore-verification`. If activation may have started, stop and investigate.
2. Verify the original `codigo` and `deploy` are still active, no archive or
staged activation for that operation was applied, and the recorded origin
revision, gitlinks, image IDs, configuration, container IDs, project labels,
port, network and writable data mounts match the original installation. Check
no foreign writer can access its data. Use `verify_existing_containers` under
the helper lock and independently check provenance and the retained Compose
configuration; a running container alone does not prove data integrity.
3. Confirm database integrity and expected existing data, application health and
a verified independent recovery copy, including an isolated restore. Verify
the original container restart policies against the retained Compose config;
restore the declared policies on the identified containers if necessary and
verify them. Do not recreate containers or run migrations for this step.
4. Under the same lock, reread the record and require it still matches the saved
hash. After all checks pass, use the trusted `host.write_record` atomic writer
to change only `status` to `installed`, retaining the failure phase, operation,
error and target fields as evidence. Reread and verify the result. If any check
fails or the record changes, leave it blocked and investigate. A subsequent
update must pass all normal preparation, compatibility and backup checks.
On API/recalculation/availability failure the updater tries to disable restart and
stop only containers whose project, service and mounts it can verify. It retains
storage. `quarantine` records an incomplete containment attempt. Failures during
stopping or backup triggers a best-effort restart of the verified original containers
with their original restart policies, after checking the original storage contract.
Automatic restart requires known migration-free API and worker entrypoints; older
entrypoints that may run migrations are left for explicit manual recovery.
The record remains `update_failed` even when recovery succeeds. A failed or interrupted
recovery can leave partially stopped services; inspect actual containers before recovery.
Inspect `installation.json`, `.archive/<operation>/`, `.updates/<operation>/`, the
external backup manifest, specific project containers and private Docker logs.
Archives from the old resetting installer are **not** consistency-certified backups.
Do not assume copying a bare `.db` without its WAL history is sufficient.
With trusted deployment scripts on the host, verify and restore to a **new isolated
directory** using Python's stdlib, without application imports:
```sh
export PYTHONPATH=/path/to/WorkingNarrative/.gitea/deploy
python3 -B -c 'import data_guard,sys; data_guard.verify_backup(sys.argv[1])' /path/to/backup
python3 -B -c 'import data_guard,sys; data_guard.restore_backup(sys.argv[1],sys.argv[2])' /path/to/backup /new/isolated/data
```
Restore refuses an existing destination, verifies checksums/integrity and compares
the four databases' logical contents with the manifest. Before authorized live
recovery, validate the old application's compatibility against that isolated copy,
ownership/permissions, mounts, full configuration and successful recalculation.
Preserve failed live storage as evidence and review a specific cutover procedure.
Do not overwrite live files, change statuses to bypass checks or start old automatic
migration entrypoints on an unvalidated schema. These restore commands do not
cut over a service.
A killed job can leave its uniquely named `isssteleon-prepare-*` helper holding
the lock. Verify no deployment is active before removing that specific helper.
Never use global Docker cleanup to release it.
## Local validation and an isolated Docker trial
The general workflow has been physically exercised for a conservative update and
a fresh installation. Use separate disposable resources for fault injection and
recovery testing.
Run the synthetic suite from the WorkingNarrative root:
## Tests
```sh
python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
python3 -B -m unittest discover -s .gitea/ci -p 'test_*.py' -v
git diff --check
```
`test_conservative.py` uses temporary synthetic databases, witnesses, blobs,
MLflow state, artifacts, logs and archives; an adapter replaces all Docker calls.
It exercises code updates, repeated versions, rejected origins, WAL backup,
corruption, derived changes, protected loss and failures. `test_target_contract.py`
also compares real pinned migration definitions with metadata and tests schema
backup/restore. Opt in with `ISSSTELEON_CONTRACT_SOURCE=/path/to/pinned/ISSSTELEON`
and a disposable Python environment containing exact schema packages/hashes from
WebApi's `uv.lock`. It applies revision functions only to newly created temporary
SQLite files, without loading migration environments or institutional data.
The stdlib suite skips these two opt-in tests without the selected source/runtime.
`test_composition.py` resolves references against local Git repositories, `test_registry.py` covers ownership and
removal on a temporary directory, and `test_installer.py` runs the flows against an in-memory Docker daemon. None of
them contacts Docker or Gitea. [INTEGRATION.md](INTEGRATION.md) lists what was exercised on real Docker and what
was not.
After review, a separately authorized physical trial needs an isolated Linux Docker
daemon, synthetic storage and an empty private deployment base. Initialize recursive
submodules at recorded pins; build without modifying locks. Run a first install on
a disposable port, add clinical/Governance witnesses, registered-model state,
artifacts and logs through supported interfaces, then repeat the same version and
a compatible code revision. Compare original directory/file identities, data,
history and mounts. Verify functional reads, completed indicator work, external
client access and restart. Inject missing databases, unknown revisions, pending
Governance drop, changed binds and build/startup/worker failures. Confirm early
rejection or reserved failure state; restore backups to separate locations.
Use separate disposable resources for fault injection and general recovery
testing. A shared institutional daemon does not provide the same isolation.
A later real dispatch requires separate authorization.
## Limits
## Remaining limits before institutional use
- Images are never removed. Each install leaves two images tagged with the project and an operation ID; remove an
unused tag by name when disk space matters.
- A process outside Docker that starts listening between the plan and the install is only detected when the
helper tries the port.
- Only the Compose project, its containers, volume, network and directory are identified. Anything else on the host
that the instance's data directory was bind-mounted into by hand is not.
- The installer trusts the registry directory: it is writable only by the deployment account.
- Not tried on the institutional daemon host.
- The lock coordinates these scripts; it cannot stop host processes, privileged
daemon users or direct network clients. Ensure exclusive maintenance access and
no external writers until final verification. Docker ownership checks are not
host-wide access control.
- Databases are backed up sequentially after known writers stop. Snapshots and
before/after checks detect changes, without a distributed transaction across
uncontrolled writers. An incompatible read-only WAL probe must abort, not repair.
- Verification scans all rows/files and stores append-only row hashes. Measure
memory, disk, runtime and downtime on realistic synthetic volumes. The space
estimate does not reserve Docker image/build space or exclude other disk users.
Power-loss durability needs host testing.
- Derived changes are scoped, but preservation checks do not prove clinical
correctness, risk-estimate completeness or API behavior beyond checked paths.
Future worker/model changes require integrity-policy review.
- Container-user permissions, WAL, Compose interpolation, direct Gunicorn startup,
actual worker completion, containment and restart/recovery need the isolated
physical trial. Backup preserves file contents/modes/timestamps; ACLs, security
labels and original uid/gid restoration need separate recovery validation.
- Writer checks are samples, not a proof of inactivity: they see processes inside
the installation containers, requests that reach the API over the network and
running MLflow runs. Not detected: a writer outside the containers (root on the
host; other containers with the data path or the jobs volume are refused), a
loopback client, the extraction learning before its run is created (while it
loads the previous ranker), a running run older than the request window, and the
indicator worker's cycle, whose writes are derived and redone by the checked
recalculation. `docker stop` gives a container 10 s before killing it, while
Gunicorn would wait 30 s for requests. An interrupted learning step loses that
batch's training (the corrections stay in the import) and can leave a run
`RUNNING` with partial artifacts; SQLite transactions keep every database
consistent and the backup is taken after the stop. Proving inactivity would need
a maintenance mode in the application itself.
- `reconcile.py` accepts the notebook runner's original ID (`--notebooks`) and
requires it exactly for installations whose record has `notebook_volume`. It
does not re-verify the notebook backup, which only a pre-activation failure
leaves and which the update never writes back.
- The jobs backup has run against real Docker volumes on Docker Desktop, not on the
institutional daemon host; its bind destination under the deployment base and its
disk usage there need the isolated physical trial.
- Backups remain on the daemon host. Off-host replication, encryption, retention,
confidential log handling and disaster recovery remain operator responsibilities.
Simulated tests alone do not establish institutional deployment safety.
## Loading simulated data (optional, after an install)
The incident-specific [18080 recovery procedure](RESET-18080.md) and its tested
script remain available for the historical failed operation; they are not part of
the general deployment workflow.
`load-dev-data` fills an installed, still empty DEV instance with the simulated hospital that `dev-data` generates.
It is a separate operation with the same plan and confirmation steps (`cargar-<puerto>-<digest>`) and takes
`puerto`, `hospital` (`host:port`, default `10.0.10.41:9505`) and `confirmacion`.
How it works: the instance's API reads the hospital through its own import API, as a person would connect it in
`/conectar`. The installer only builds the `dev-data` loader from the commit recorded in the instance
(`gitlinks.dev-data`, plus `Core` of the recorded application commit), runs `dev_data cargar` for `cacu`, `cama` and
`tea` against the published port, and then waits for the three indicator recalculations to end `ok`. It records
`synthetic_data` (hospital, `dev-data` commit, per-table counts, indicator states) in the instance record.
It refuses an instance that is not a verified, running DEV installation, one with any import attempt
(`/reportes/importaciones`) or an earlier load, an unreachable hospital address and anything that is not `host:port`.
It fails, visibly and with the stage, on a loader error, any rejected row, a project with no rows, or a
recalculation that errors or does not finish. After a failure the instance may be partly loaded, so it is marked
and must be reinstalled before another attempt: the hospital's ids travel with the rows, so a load only works on
an empty platform.
Limits, none of which this installer works around or decides:
- The hospital is an external MySQL (`dev-data-prueba` on the server, port 9505). The installer reads its TCP port
from the daemon host and never writes to it; filling it is dev-data's own workflow (`montura/poblar.sh`). The
WebApi blocks SQLite as an import source, so the hospital must be MySQL, MariaDB, PostgreSQL or SQL Server. The
simulated hospital's credentials (`hospital`/`hospital`) are fixed in `dataload.py`.
- The generated data is synthetic and deterministic (seed and reference date in `dev-data`); the volumes are
dev-data's defaults for what is in the hospital.
- A trial load of 60 CaCu, 60 CaMa and 40 TEA patients from a throwaway hospital completed without rejections (see
[INTEGRATION.md](INTEGRATION.md)). What dev-data does not generate comes from reading its code, not from that load:
CaMa stage, receptor, Ki-67 and T strata stay empty because dev-data generates BI-RADS, biopsy grade and notes
with ICD-10 codes but no report text, which is where those values come from. Adding it is development in
`dev-data` and a decision on which fields and rules to simulate; none is assumed here.
- CaCu loads patients, cytologies, biopsies and notes only, without orders, episodes or blood counts. TEA loads all
its tables.
- Cohort definitions, metrics and clinical contracts are untouched: only the staging tables are loaded and the
platform's own recalculation runs.
-48
View File
@@ -1,48 +0,0 @@
# Authorized laboratory reset
Run only on `labserver`, with a trusted checkout containing the reset script,
root access, Python 3, Docker Compose, GNU `cp` and `lsof`. The Docker daemon must
be local. The target and original revision are fixed in the script. Read the
operation ID from the failed installation record and use it for all three commands:
```sh
OPERATION_ID=$(sudo python3 -c "import json; print(json.load(open('/srv/workingnarrative-dev/isssteleon-dev-prueba-02/installation.json'))['operation_id'])")
sudo python3 -B .gitea/deploy/reset_lab_18080.py check --operation "$OPERATION_ID"
sudo python3 -B .gitea/deploy/reset_lab_18080.py apply --operation "$OPERATION_ID"
sudo python3 -B .gitea/deploy/reset_lab_18080.py check --operation "$OPERATION_ID"
```
Check uses temporary isolated copies, never changes the installation, and takes
the existing installer file lock. Apply preserves failed code, configuration,
data, record and container descriptions at:
`/srv/workingnarrative-dev/.reset-18080-<operation_id>/`
The installer backup is a normalized SQLite snapshot: committed WAL pages are
already in its database files. Unexpected WAL/journal files in that snapshot
cause rejection, not deletion. All persisted files, owners, modes and extended
attributes are copied and checked. API/worker commands are overridden with the
existing migration-free configuration; initial recalculation is disabled.
Success requires original image IDs, correct mounts/environment, healthy services,
HTTP `/` and `/health`, exact database rows and the existing persistent-file/audit
policy. Only then is the archived record atomically reinstated as `installed`,
with a link to preserved incident evidence. A final check reports `already recovered`.
After a normal failure, the script attempts to stop only this project's services
and leaves `update_failed`. Repeat apply after correcting the failed prerequisite.
Each later data attempt is preserved separately; original incident evidence is
never replaced. If killed while services are running, explicitly stop this
project before retrying:
```sh
sudo docker compose --project-name isssteleon-dev-prueba-02 \
--project-directory /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy \
--env-file /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy/.env \
-f /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy/docker-compose.yml stop
```
An interrupted preparation without `prepared` has made no active-directory swaps.
Retain that incomplete work directory under another unique name before retrying.
Ambiguous filesystem states are rejected. Do not delete evidence to bypass checks.
No command targets 18081, other projects, remote Git or Actions.
+240
View File
@@ -0,0 +1,240 @@
"""Resolve a Git reference to the exact composition an installation is built from.
A composition is the outer commit plus the commits of every recognised gitlink below `ISSSTELEON`. Everything
here works in temporary directories and never touches Docker or the installation registry.
"""
import io
import json
import os
from pathlib import Path
import re
import shutil
import tarfile
import proc
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
ORIGIN_BASE = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
# Public ports that belong to other installations and are never installed over or removed.
PROTECTED_PORTS = {
18087: 'CaMa installation',
4397: 'installation kept for inspection',
18090: 'DEV installation kept as a reference',
18096: 'DEV installation kept as a reference',
18097: 'DEV installation kept as a functional reference',
}
SHA = re.compile(r'[0-9a-f]{40}')
TARGET_REF = 'refs/deploy/target'
TEA_ORIGIN = 'ssh://git@10.0.10.41:2222/alberto/tea.git'
# The exact origin each gitlink may come from; the EEG library is the one repository outside the organisation.
SUBMODULE_ORIGINS = {
'ISSSTELEON': ORIGIN_BASE + 'ISSSTELEON.git',
'ISSSTELEON/WebApp': ORIGIN_BASE + 'WebApp.git',
'ISSSTELEON/WebApi': ORIGIN_BASE + 'WebApi.git',
'ISSSTELEON/models': ORIGIN_BASE + 'models.git',
'ISSSTELEON/models/libs/tea': TEA_ORIGIN,
}
# Application settings the installer fixes; an unset value falls back to the image's default, which is the same.
PERSISTENT_ENV = {
**{domain + '_DATABASE_URL': 'sqlite:////data/' + domain.lower() + '.db'
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')},
'MLFLOW_TRACKING_URI': 'sqlite:////data/mlflow.db',
'MLFLOW_ARTIFACT_ROOT': '/data/mlflow-artefactos',
'WEBAPI_REPORT_DIR': '/data/reportes',
'INDICADORES_DIR': '/data/indicadores',
}
BASE_SERVICES = ('webapi', 'webapp', 'indicadores')
NOTEBOOK_SERVICE = 'notebooks'
NOTEBOOK_VOLUME = 'trabajos_notebooks'
NOTEBOOK_JOBS = '/trabajos'
NOTEBOOK_USER = '10001:10001'
# Declared services that Compose leaves inactive unless their profile is enabled; never started here.
PROFILE_SERVICES = ('entrenar',)
def validate_port(text):
"""The public port as an integer; protected ports are refused."""
if not re.fullmatch(r'[0-9]{1,5}', str(text)) or not 1024 <= int(text) <= 65535:
raise ValueError('puerto must be an integer from 1024 to 65535')
port = int(text)
if port in PROTECTED_PORTS:
raise ValueError(f'port {port} is protected ({PROTECTED_PORTS[port]})')
return port
def project_for(port):
return f'isssteleon-dev-{port}'
def notebook_volume_name(project):
return f'{project}_{NOTEBOOK_VOLUME}'
def parse_reference(text):
"""Classify a reference as a full commit SHA or a branch/tag name; abbreviations and ref paths are refused."""
text = (text or '').strip()
if not text:
raise ValueError('referencia is required')
if SHA.fullmatch(text):
return 'commit', text
if re.fullmatch(r'[0-9a-fA-F]{7,40}', text):
raise ValueError('a commit must be given as its 40 lowercase hexadecimal characters')
if text.startswith(('refs/', '-')) or text == '@' or any(c in text for c in ' \t\n\\'):
raise ValueError('referencia must be a branch name, a tag name or a full commit SHA')
try:
proc.run(['git', 'check-ref-format', 'refs/heads/' + text])
except Exception:
raise ValueError('referencia is not a valid Git name') from None
return 'name', text
def resolve_reference(text, remote=None):
"""Resolve a reference against the remote to `{'reference', 'kind', 'commit'}`.
A name that is both a branch and a tag, or neither, is refused. A commit is taken as given and checked
when it is fetched."""
remote = remote or OFFICIAL
kind, value = parse_reference(text)
if kind == 'commit':
return {'reference': value, 'kind': 'commit', 'commit': value}
listing = proc.run(['git', 'ls-remote', '--heads', '--tags', remote, 'refs/heads/' + value,
'refs/tags/' + value, 'refs/tags/' + value + '^{}'])
heads, tags, peeled = {}, {}, {}
for line in listing.splitlines():
sha, _, ref = line.partition('\t')
if ref == 'refs/heads/' + value:
heads[ref] = sha
elif ref == 'refs/tags/' + value:
tags[ref] = sha
elif ref == 'refs/tags/' + value + '^{}':
peeled[ref] = sha
if heads and tags:
raise ValueError(f'{value} is both a branch and a tag; use the full commit SHA')
if not heads and not tags:
raise ValueError(f'{value} is not a branch or a tag of the official repository')
if heads:
kind, commit = 'branch', next(iter(heads.values()))
else:
kind, commit = 'tag', next(iter(peeled.values()), None) or next(iter(tags.values()))
if not SHA.fullmatch(commit):
raise RuntimeError('the remote did not return a full commit SHA')
return {'reference': value, 'kind': kind, 'commit': commit}
def checkout(resolved, directory, remote=None):
"""Fetch the resolved commit into `directory`, check it out and initialise the recognised gitlinks.
Returns the composition. Fails if the reference moved since it was resolved."""
remote = remote or OFFICIAL
directory = Path(directory)
proc.run(['git', 'init', '--quiet', directory])
if resolved['kind'] == 'commit':
proc.git(directory, 'fetch', '--no-tags', remote, resolved['commit'])
fetched = 'FETCH_HEAD'
else:
prefix = 'refs/heads/' if resolved['kind'] == 'branch' else 'refs/tags/'
proc.git(directory, 'fetch', '--no-tags', remote, f'+{prefix}{resolved["reference"]}:{TARGET_REF}')
fetched = TARGET_REF
sha = proc.git(directory, 'rev-parse', '--verify', fetched + '^{commit}').strip()
if sha != resolved['commit']:
raise RuntimeError(f'{resolved["reference"]} moved from {resolved["commit"]} to {sha} while it was being resolved')
proc.git(directory, 'checkout', '--quiet', '--detach', sha)
checkout_pinned(directory)
return composition_of(directory, resolved)
def checkout_pinned(root):
"""Initialise only recognised institutional gitlinks, each at the commit the parent records."""
def visit(repo, prefix, selected=None):
entries = proc.git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, _, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if selected is not None and path != selected:
continue
full = f'{prefix}/{path}' if prefix else path
if full not in SUBMODULE_ORIGINS or path in ('', '.', '..') or '..' in Path(path).parts:
raise RuntimeError(f'unsupported application gitlink: {full}')
config = proc.git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = [line.split(None, 1)[0][len('submodule.'):-len('.path')]
for line in config.splitlines() if len(line.split(None, 1)) == 2
and line.split(None, 1)[1] == path]
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise RuntimeError(f'invalid submodule mapping: {full}')
name = matches[0]
origin = SUBMODULE_ORIGINS[full]
if proc.git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url').strip() != origin:
raise RuntimeError(f'untrusted submodule origin: {full}')
proc.git(repo, '-c', f'submodule.{name}.url={origin}', 'submodule', 'update', '--init', '--checkout',
'--', path)
child = repo / path
if proc.git(child, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError(f'gitlink checkout mismatch: {full}')
visit(child, full)
visit(Path(root), '', 'ISSSTELEON')
def committed_trees(repo, revision, prefix=''):
"""Walk the exact recursive gitlinks and reject any checkout that is not the recorded commit."""
actual = proc.git(repo, 'rev-parse', 'HEAD').strip()
if actual != revision:
raise RuntimeError(f'{repo}: expected {revision}, found {actual}; initialize submodules recursively')
yield repo, revision, prefix
entries = proc.git(repo, 'ls-tree', '-rz', '--full-tree', revision, binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, _, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if Path(path).is_absolute() or '..' in Path(path).parts:
raise RuntimeError(f'unsafe gitlink path: {path}')
yield from committed_trees(repo / path, sha, f'{prefix}/{path}' if prefix else path)
def composition_of(root, resolved):
"""The outer commit and the commit of every recognised gitlink, as an ordered mapping."""
root = Path(root)
outer = proc.git(root, 'rev-parse', 'HEAD').strip()
pins = {}
for line in proc.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON', 'dev-data').splitlines():
meta, _, path = line.partition('\t')
mode, _, sha = meta.split()
if mode == '160000':
pins[path] = sha
if 'ISSSTELEON' not in pins:
raise RuntimeError('the outer repository does not pin ISSSTELEON')
gitlinks = {'WorkingNarrative': outer, 'dev-data': pins.get('dev-data')}
for prefix, sha in ((p or 'ISSSTELEON', s) for _, s, p in committed_trees(root / 'ISSSTELEON', pins['ISSSTELEON'])):
gitlinks[prefix] = sha
return {'reference': resolved['reference'], 'kind': resolved['kind'], 'commit': outer,
'application': pins['ISSSTELEON'], 'gitlinks': gitlinks}
def export_tree(repo, revision, dest, prefix=''):
"""Export each committed tree below `repo`, following its exact gitlinks."""
for child, sha, relative in committed_trees(repo, revision, prefix):
target = Path(dest) / relative.removeprefix(prefix).lstrip('/')
target.mkdir(parents=True, exist_ok=True)
archive = proc.git(child, 'archive', '--format=tar', sha, binary=True)
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
tar.extractall(target, filter='data')
def digest_text(value):
"""Canonical JSON used to compare plans."""
return json.dumps(value, sort_keys=True, separators=(',', ':'))
def copy_deploy(source, deploy):
shutil.copytree(Path(source) / 'dist', deploy, symlinks=True)
-855
View File
@@ -1,855 +0,0 @@
"""Coordinate a schema-compatible application update without replacing storage."""
import json
import re
import subprocess
from pathlib import Path
import tempfile
import time
import uuid
import shutil
import sqlite3
import data_guard
INSPECTION_REASONS = frozenset({
'persistent_directory_invalid', 'linked_persistent_entry', 'special_persistent_entry',
'database_missing_or_linked', 'contract_domains_invalid', 'migration_version_unavailable',
'migration_version_count', 'migration_revision_unknown', 'migration_pending', 'schema_mismatch',
'sqlite_integrity_failed', 'sqlite_foreign_key_failed', 'schema_triggers_unsupported',
'schema_options_unsupported', 'schema_columns_unsupported', 'schema_partial_indexes_unsupported',
'schema_expression_indexes_unsupported', 'schema_constraint_invalid', 'unclassified',
'directory_identity_changed', 'directory_disappeared', 'database_identity_changed',
'audit_log_disappeared', 'audit_history_changed', 'auxiliary_integrity_failed',
'protected_rows_changed', 'historical_rows_changed', 'persistent_file_changed',
'worker_module_unavailable', 'notebook_runs_unverifiable', 'seeded_rows_invalid', 'mlflow_store_not_initial',
'mlflow_store_unverifiable',
})
INSPECTION_TYPES = frozenset({'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
'TypeError', 'KeyError', 'MemoryError', 'Other'})
SQLITE_NAMES = {name for name in dir(sqlite3) if name.startswith('SQLITE_')
and isinstance(getattr(sqlite3, name), int)}
PERSISTENT_ENV = {
**{domain + '_DATABASE_URL': 'sqlite:////data/' + domain.lower() + '.db'
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')},
'MLFLOW_TRACKING_URI': 'sqlite:////data/mlflow.db',
'MLFLOW_ARTIFACT_ROOT': '/data/mlflow-artefactos',
'WEBAPI_REPORT_DIR': '/data/reportes',
'INDICADORES_DIR': '/data/indicadores',
}
NOTEBOOK_JOB_TIMEOUT = 6 * 3600
NOTEBOOK_REASONS = frozenset({
'notebook jobs are active', 'notebook jobs changed while creating the backup',
'notebook backup differs from the volume', 'notebook job entry type is unsupported',
'notebook job entry changed type', 'notebook jobs root is missing or linked',
'notebook backup destination is missing or linked', 'notebook backup destination is not empty',
'notebook backup manifest is invalid', 'notebook backup manifest is inconsistent',
'notebook backup content differs', 'notebook backup directory is invalid',
'notebook restore differs from the backup',
})
def failure_detail(exc):
"""Describe subprocess failures without exposing their potentially sensitive output."""
if not isinstance(exc, subprocess.CalledProcessError):
return 'error type=' + type(exc).__name__
detail = 'exit=' + str(exc.returncode)
stderr = exc.stderr if isinstance(exc.stderr, str) else ''
frames = re.findall(r'File "<string>", line (\d+), in ([A-Za-z_][A-Za-z_0-9]*)', stderr)
allowed = {'main', 'backup_installation', 'verify_isolated_restore', 'create_backup',
'verify_backup', 'restore_backup', 'storage_state', 'regular_tree',
'inspect_databases', 'readonly', 'digest', 'sqlite_digest', 'require'}
frames = [(line, name) for line, name in frames if name in allowed]
if len(frames) > 1 and frames[-1][1] == 'require':
frames.pop()
if frames:
line, name = frames[-1]
detail += f', location={name}:{line}'
match = re.search(r'(?m)^(PermissionError|FileNotFoundError|FileExistsError|OSError|'
r'OperationalError|DatabaseError|IntegrityError|RuntimeError|ValueError|'
r'JSONDecodeError|KeyError|TypeError|MemoryError)(?::|$)', stderr)
if match:
detail += ', error type=' + match.group(1)
match = re.search(r'\[Errno (\d{1,4})\]', stderr)
if match:
detail += ', errno=' + match.group(1)
for line in stderr.splitlines():
prefix = line.partition('=')[0]
if prefix not in ('WN_INSPECT_DIAGNOSTIC', 'WN_RECALC_DIAGNOSTIC', 'WN_VERIFY_DIAGNOSTIC'):
continue
try:
diagnostic = json.loads(line.partition('=')[2])
fields = {'reason', 'domain', 'type', 'sqlite', 'errno'}
if prefix == 'WN_RECALC_DIAGNOSTIC':
fields.add('stage')
if (not isinstance(diagnostic, dict)
or set(diagnostic) != fields
or diagnostic['reason'] not in INSPECTION_REASONS
or diagnostic['domain'] not in {'cacu', 'cama', 'tea', 'governance', 'none'}
or diagnostic['type'] not in INSPECTION_TYPES
or diagnostic['sqlite'] not in SQLITE_NAMES | {'none'}
or (prefix == 'WN_RECALC_DIAGNOSTIC' and diagnostic['stage'] not in
{'environment', 'import', 'initialize', 'enqueue', 'execute', 'domain_result', 'pending', 'unknown'})
or (diagnostic['errno'] is not None and
(type(diagnostic['errno']) is not int or not 0 <= diagnostic['errno'] <= 4095))):
continue
except (ValueError, TypeError):
continue
detail += (f", reason={diagnostic['reason']}, domain={diagnostic['domain']}, "
f"type={diagnostic['type']}, sqlite={diagnostic['sqlite']}")
if prefix == 'WN_RECALC_DIAGNOSTIC':
detail += ', stage=' + diagnostic['stage']
if diagnostic['errno'] is not None:
detail += ', errno=' + str(diagnostic['errno'])
break
return detail
class GuardFailure(RuntimeError):
"""A storage inspection failure with sanitized diagnostics."""
def __init__(self, action, detail):
self.detail = detail
super().__init__(action + ': candidate storage validation failed (' + detail + ')')
class RecalculationFailure(RuntimeError):
"""A sanitized failure in a specific recalculation operation."""
def __init__(self, step, category):
self.step, self.category = step, category
super().__init__('recalculation failed')
def recalculation_step(step, operation):
try:
return operation()
except GuardFailure as exc:
raise RecalculationFailure(step, exc.detail) from None
except Exception as exc:
kind = type(exc).__name__
kind = kind if kind in INSPECTION_TYPES | {'JSONDecodeError'} else 'Other'
raise RecalculationFailure(step, 'error type=' + kind) from None
class UpdateRefusal(RuntimeError):
"""A check of notebook work or other writers that refused the update; its message carries counts and
categories only."""
def notebook_detail(exc):
if not isinstance(exc, subprocess.CalledProcessError):
return 'error type=' + type(exc).__name__
detail = 'exit=' + str(exc.returncode)
for line in (exc.stderr if isinstance(exc.stderr, str) else '').splitlines():
if line.startswith('WN_NOTEBOOK_DIAGNOSTIC='):
try:
diagnostic = json.loads(line.partition('=')[2])
except ValueError:
break
if isinstance(diagnostic, dict) and diagnostic.get('type') in INSPECTION_TYPES | {'FileExistsError'}:
detail += ', error type=' + diagnostic['type']
if isinstance(diagnostic, dict) and diagnostic.get('reason') in NOTEBOOK_REASONS:
detail += ', reason=' + diagnostic['reason']
break
return detail
def notebook_guard(api, image, action, payload, volume, backup=None):
"""Run the jobs volume guard as root in the candidate image, with the volume always read-only.
Root reads files a notebook made unreadable; a backup also needs to restore their owners."""
script = Path(__file__).with_name('notebook_guard.py').read_text(encoding='utf-8')
args = ['docker', 'run', '--rm', '-i', '--pull', 'never', '--network', 'none', '--read-only',
'--tmpfs', '/tmp:rw,nosuid,nodev', '--user', '0:0', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges:true', '--env', 'PYTHONDONTWRITEBYTECODE=1', '--env', 'HOME=/tmp',
'--mount', f'type=volume,src={volume},dst=/trabajos,readonly,volume-nocopy']
if backup is None:
args += ['--cap-add', 'DAC_READ_SEARCH']
else:
args += ['--cap-add', 'DAC_OVERRIDE', '--cap-add', 'CHOWN', '--cap-add', 'FOWNER',
'--mount', f'type=bind,src={backup},dst=/respaldo']
args += ['--entrypoint', '/app/WebApi/.venv/bin/python', image, '-B', '-c', script, action]
try:
return json.loads(api.run(args, stdin=json.dumps(payload)))
except Exception as exc:
raise UpdateRefusal('notebook jobs ' + action + ' failed (' + notebook_detail(exc) + ')') from None
def notebook_timeout(api, ids):
"""The API's notebook job timeout and request timeout, which bound how long a run it started stays running."""
items = json.loads(api.run(['docker', 'inspect', *ids]))
env = next(environment(item) for item in items
if item['Config']['Labels']['com.docker.compose.service'] == 'webapi')
values = {'timeout': env.get('NOTEBOOK_JOB_TIMEOUT', str(NOTEBOOK_JOB_TIMEOUT)),
'request_timeout': env.get('WEBAPI_TIMEOUT', '600')}
if any(not value.isdigit() or int(value) < 1 for value in values.values()):
raise RuntimeError('notebook job timeout is not verifiable')
return {key: int(value) for key, value in values.items()}
def notebook_activity(api, image, data, volume, timeouts, *, quiesced=False):
"""Reject queued, running or half-assembled notebook work and running trainings or learning steps; return the
jobs volume summary, if any."""
runs = guard(api, image, 'notebook-runs', {'data': '/data', **timeouts,
'now': int(time.time() * 1000), 'quiesced': quiesced}, data)
if any(type(runs.get(key)) is not int or runs[key] < 0 for key in ('active', 'training')):
raise RuntimeError('notebook run status is not verifiable')
if runs['active']:
raise UpdateRefusal(str(runs['active']) + ' notebook run(s) are queued or running; retry when they finish')
if runs['training']:
raise UpdateRefusal(str(runs['training']) + ' training or learning run(s) are running in MLflow; retry when '
'they finish')
if volume is None:
return None
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, volume)
if jobs['active']:
raise UpdateRefusal('notebook jobs volume holds unfinished jobs (' + ', '.join(jobs['active'])
+ '); retry when they finish or inspect them manually')
return jobs
API_PORT = 5000
def expected_process(service, command, healthcheck):
"""Whether a process of an original container is its own service, as its entrypoint or image starts it.
Anything else (a `docker exec` shell, a one-off `python -m models`, an OCR or notebook kernel subprocess) may
be writing data or doing work that stopping the container would cut short."""
tokens = command.split()
if not tokens:
return False
if service == 'webapi':
return command == healthcheck or (tokens[-1] == 'webapi:create_app()'
and any(token.endswith('gunicorn') for token in tokens[:4]))
if service == 'indicadores':
return any(tokens[-2:] == ['-m', module] for module in data_guard.WORKERS)
if service == 'notebooks':
return tokens[-4:] == ['-m', 'models', 'notebooks', 'serve']
return False
def container_processes(api, container):
lines = api.run(['docker', 'top', container, '-eo', 'pid,args']).splitlines()
if not lines or lines[0].split()[:2] != ['PID', 'COMMAND']:
raise UpdateRefusal('installation processes are not verifiable')
return [line.split(None, 1)[1] if len(line.split(None, 1)) == 2 else '' for line in lines[1:] if line.strip()]
def loopback(address):
"""Whether a `/proc/net/tcp` or `tcp6` address (host byte order, hexadecimal) is a loopback one."""
if len(address) == 8:
return address[6:8] == '7F'
if len(address) == 32:
return (address == '00000000000000000000000001000000'
or (address[:24] == '0000000000000000FFFF0000' and address[30:32] == '7F'))
return False
def served_requests(api, container):
"""Connections to the API port from outside the container that are open or that the API has not closed yet,
which is a request still being served. Once the frontend is stopped no new one can arrive."""
try:
table = api.run(['docker', 'exec', container, 'cat', '/proc/net/tcp', '/proc/net/tcp6'])
except Exception:
raise UpdateRefusal('open API requests are not verifiable') from None
count = 0
for line in table.splitlines():
fields = line.split()
if len(fields) < 4 or fields[0] == 'sl' or ':' not in fields[1] or ':' not in fields[2]:
continue
port = fields[1].rpartition(':')[2]
# 01 ESTABLISHED, 08 CLOSE_WAIT: the client may have gone, the request handler has not finished.
if int(port, 16) == API_PORT and fields[3] in ('01', '08') and not loopback(fields[2].rpartition(':')[0]):
count += 1
return count
def writer_activity(api, ids, *, requests):
"""Reject processes the original containers did not start themselves and, with `requests`, API requests still
being served (an import, OCR or a `/train` call)."""
items = {item['Id']: item for item in json.loads(api.run(['docker', 'inspect', *ids]))}
unexpected = 0
for index, service in ((0, 'indicadores'), (1, 'webapi'), (3, 'notebooks')):
if index >= len(ids):
continue
test = ((items.get(ids[index], {}).get('Config') or {}).get('Healthcheck') or {}).get('Test') or []
healthcheck = ' '.join(test[1:]) if test[:1] == ['CMD'] else None
unexpected += sum(not expected_process(service, command, healthcheck)
for command in container_processes(api, ids[index]))
if unexpected:
raise UpdateRefusal(str(unexpected) + ' process(es) the installation did not start run in its containers '
'(docker exec, a one-off job, OCR or a notebook kernel); retry when they finish')
if requests:
served = served_requests(api, ids[1])
if served:
raise UpdateRefusal(str(served) + ' API request(s) are still being served; retry when they finish')
def mlflow_compatibility(api, image, data, *, quiesced=False):
"""Refuse an MLflow store the candidate cannot open without a schema upgrade, or one with a production
version: the recalculation would then store risk batches and export cohort files, which the persistence
check treats as protected (they mix derived rows with confirmations made in the application)."""
store = guard(api, image, 'mlflow-store', {'data': '/data', 'quiesced': quiesced}, data)
if not store['exists']:
return store
if [store['revision']] != guard(api, image, 'mlflow-heads', {})['heads']:
raise UpdateRefusal('the MLflow store needs a schema upgrade, which updates do not apply')
if store['production']:
raise UpdateRefusal(str(store['production']) + ' registered model(s) have a version in production; the '
'recalculation would store risk batches and cohort files outside the derived state')
return store
def verify_notebook_jobs(api, image, project, identity, digest):
"""Require the same volume and contents, before the frontend lets anyone submit a notebook."""
if api.notebook_volume_identity(project) != identity:
raise RuntimeError('notebook jobs volume identity changed')
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, identity['name'])
if jobs['digest'] != digest or jobs['active']:
raise RuntimeError('notebook jobs changed during activation')
def verify_new_notebook_volume(api, image, project):
"""A volume Compose created for this project with no job in it yet."""
identity = api.notebook_volume_identity(project)
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, identity['name'])
if jobs['entries'] != 1:
raise RuntimeError('new notebook jobs volume is not empty')
return {'identity': identity, 'digest': jobs['digest']}
def guard(api, image, action, payload, data=None, *, writable=False):
"""Run inspection in the candidate image, overriding every application entrypoint."""
script = Path(__file__).with_name('data_guard.py').read_text(encoding='utf-8')
args = ['docker', 'run', '--rm', '-i', '--pull', 'never', '--network', 'none', '--read-only',
'--tmpfs', '/tmp:rw,nosuid,nodev', '--workdir', '/app/WebApi']
args += ['--env', 'PYTHONDONTWRITEBYTECODE=1', '--env', 'HOME=/tmp']
if data is not None:
args += ['--mount', f'type=bind,src={data},dst=/data' + ('' if writable else ',readonly')]
args += ['--entrypoint', '/app/WebApi/.venv/bin/python', image, '-B', '-c', script, action]
try:
return json.loads(api.run(args, stdin=json.dumps(payload)))
except Exception as exc:
raise GuardFailure(action, failure_detail(exc)) from None
def environment(container):
return dict(value.split('=', 1) for value in container.get('Config', {}).get('Env', []) if '=' in value)
def read_deployment(api, helper, project, directory):
document = json.loads(api.host_action(helper, 'read-deploy', project, ''))
directory.mkdir()
for name in ('.env', 'docker-compose.yml'):
(directory / name).write_text(document[name], encoding='utf-8')
(directory / name).chmod(0o600)
return document
def current_environment(api, ids, config):
items = json.loads(api.run(['docker', 'inspect', *ids]))
services = {item['Config']['Labels']['com.docker.compose.service']: item for item in items}
for name in ('webapi', 'indicadores'):
actual = environment(services[name])
if any(actual.get(key) != value for key, value in PERSISTENT_ENV.items()):
raise RuntimeError('only the managed local SQLite storage layout is supported')
declared = config['services'][name].get('environment', {})
if any(value is None or actual.get(key) != str(value) for key, value in declared.items()):
raise RuntimeError('running environment differs from retained deployment configuration')
def write_configuration(api, deploy, data, record, revision, original_env):
tag = api.configure(deploy, data, record['project'], revision, record['port'])
# Retain operator configuration, including values absent from a newer image's defaults.
replacements = {'ISSSTELEON_VERSION': tag, 'ISSSTELEON_DATOS': str(data),
'ISSSTELEON_PUERTO': str(record['port']), **PERSISTENT_ENV}
text = original_env.rstrip() + '\n'
for key, value in replacements.items():
if any(char in str(value) for char in ("'", '\n', '\r', '\x00')):
raise RuntimeError('invalid managed configuration value')
text += key + "='" + str(value) + "'\n"
(deploy / '.env').write_text(text, encoding='utf-8')
(deploy / '.env').chmod(0o600)
return tag
def controlled_config(config, *, migrate_on_start=False, worker='webapi.indicadores_vivos'):
"""Keep the worker idle until the checked one-shot recalculation has completed.
`worker` is the image's worker module (`runtime` guard action)."""
if worker not in data_guard.WORKERS:
raise RuntimeError('unsupported worker module')
api = config['services']['webapi']
for service in (api, config['services']['indicadores']):
service['environment'] = dict(service.get('environment', {}), **PERSISTENT_ENV)
if any(not isinstance(value, str) for value in service['environment'].values()):
raise RuntimeError('all candidate environment values must be resolved strings')
if not migrate_on_start:
env = api['environment']
if str(env.get('PORT', '5000')) != '5000':
raise RuntimeError('the managed API must listen on port 5000')
workers, timeout = str(env.get('WEBAPI_WORKERS', '2')), str(env.get('WEBAPI_TIMEOUT', '600'))
if not workers.isdigit() or not 1 <= int(workers) <= 32 or not timeout.isdigit() or int(timeout) < 1:
raise RuntimeError('invalid API process configuration')
api['working_dir'] = '/app/WebApi'
api['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn',
'--bind', '0.0.0.0:5000', '--workers', workers,
'--timeout', timeout, '--access-logfile', '-', 'webapi:create_app()']
api['command'] = []
service = config['services']['indicadores']
service['working_dir'] = '/app/WebApi'
service['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', worker]
service['command'] = []
service['environment']['INDICADORES_AL_INICIAR'] = '0'
return config
def persist_config(deploy, config):
def literal(value):
if isinstance(value, str):
return value.replace('$', '$$')
if isinstance(value, list):
return [literal(item) for item in value]
if isinstance(value, dict):
return {key: literal(item) for key, item in value.items()}
return value
path = deploy / 'docker-compose.yml'
path.write_text(json.dumps(literal(config), indent=2), encoding='utf-8')
path.chmod(0o600)
def api_mounts(mounts, data, notebook_volume):
"""Whether the API has exactly its data bind and, with notebooks, the jobs volume."""
wanted = [{'Type': 'bind', 'Source': str(data), 'Destination': '/data', 'RW': True}]
if notebook_volume:
wanted.append({'Type': 'volume', 'Name': notebook_volume, 'Destination': '/trabajos', 'RW': True})
shapes = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
'Destination', 'RW')} for mount in mounts]
return len(shapes) == len(wanted) and all(mount in shapes for mount in wanted)
def verify_api(api, cmd, data, image, *, timeout=300, notebook_volume=None):
deadline = time.monotonic() + timeout
expected = api.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
while time.monotonic() < deadline:
ids = api.run([*cmd, 'ps', '-q', 'webapi']).splitlines()
if len(ids) == 1:
item = json.loads(api.run(['docker', 'inspect', ids[0]]))[0]
if item.get('State', {}).get('Health', {}).get('Status') == 'healthy':
if (item.get('Image') != expected
or not api_mounts(item.get('Mounts', []), data, notebook_volume)
or any(environment(item).get(k) != v for k, v in PERSISTENT_ENV.items())):
raise RuntimeError('updated API storage or image identity differs')
return
time.sleep(2)
raise RuntimeError('updated API did not become healthy')
def finish(api, cmd, image, deploy, data, contract, before, progress=None, *, notebook_volume=None,
before_frontend=None):
"""Recalculate under persistence checks, then start the worker, the notebook runner and the frontend.
`before_frontend` runs while no request can reach the API yet."""
progress = progress or (lambda phase: None)
verify_api(api, cmd, data, image, notebook_volume=notebook_volume)
guard(api, image, 'verify', {'data': '/data', 'contract': contract, 'before': before}, data, writable=True)
progress('recalculation-and-persistence')
def load_configuration():
environment = json.loads((deploy / 'docker-compose.yml').read_text(encoding='utf-8'))[
'services']['indicadores']['environment']
return {key: value.replace('$$', '$') for key, value in environment.items()}
worker_environment = recalculation_step('load-configuration', load_configuration)
# Compose .env quoting differs from docker --env-file. Transport resolved values privately.
result = recalculation_step('execute-recalculation', lambda: guard(
api, image, 'recalculate', {'environment': worker_environment}, data, writable=True))
def validate_result():
if result != {'completed': ['cacu', 'cama', 'tea']}:
raise RecalculationFailure('validate-result', 'incomplete or invalid result')
validate_result()
after = recalculation_step('verify-persistence', lambda: guard(
api, image, 'verify', {'data': '/data', 'contract': contract, 'before': before, 'derived': True}, data,
writable=True))
progress('worker')
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'indicadores'])
if notebook_volume:
progress('notebooks')
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'notebooks'])
if before_frontend:
before_frontend()
progress('frontend')
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapp'])
return after
def freeze_failed(api, cmd, project, data, notebook_volume=None):
"""Stop only verified instance containers; retain them and all storage for recovery."""
ids = api.run([*cmd, 'ps', '-a', '-q']).splitlines()
if not ids:
return
items = json.loads(api.run(['docker', 'inspect', *ids]))
services = ('webapi', 'webapp', 'indicadores') + (('notebooks',) if notebook_volume else ())
jobs = {'Type': 'volume', 'Name': notebook_volume, 'Destination': '/trabajos'}
for item in items:
labels = item.get('Config', {}).get('Labels') or {}
service = labels.get('com.docker.compose.service')
if labels.get('com.docker.compose.project') != project or service not in services:
raise RuntimeError('failed container ownership is uncertain')
mounts = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
'Destination')} for mount in item.get('Mounts', [])]
wanted = {'webapi': [{'Type': 'bind', 'Source': str(data), 'Destination': '/data'}]
+ ([jobs] if notebook_volume else []),
'indicadores': [{'Type': 'bind', 'Source': str(data), 'Destination': '/data'}],
'notebooks': [jobs]}
if service != 'webapp' and (len(mounts) != len(wanted[service])
or any(mount not in mounts for mount in wanted[service])):
raise RuntimeError('failed container storage is uncertain')
for container in ids:
api.run(['docker', 'update', '--restart=no', container])
api.run(['docker', 'stop', container])
def container_snapshot(api, ids):
items = json.loads(api.run(['docker', 'inspect', *ids]))
if len(items) != len(ids) or [item.get('Id') for item in items] != ids:
raise RuntimeError('original container identities changed')
return items
def recover_original(api, record, helper, base, ids, original, previous_cmd, initial, volume_identity=None):
"""Restart only the original containers after confirming their retained state."""
current = container_snapshot(api, ids)
for old, item in zip(original, current):
if (item.get('Image') != old.get('Image') or item.get('Mounts') != old.get('Mounts')
or item.get('Config') != old.get('Config')):
raise RuntimeError('original container identity or mounts changed')
policy = old.get('HostConfig', {}).get('RestartPolicy', {})
if policy.get('Name') not in ('no', 'always', 'unless-stopped', 'on-failure'):
raise RuntimeError('original restart policy is unsupported')
if type(policy.get('MaximumRetryCount', 0)) is not int or policy.get('MaximumRetryCount', 0) < 0:
raise RuntimeError('original restart retry count is invalid')
api_config = current[1]['Config']
if not current[1].get('State', {}).get('Running'):
entry = api_config.get('Entrypoint')
if (not isinstance(entry, list) or len(entry) != 12
or entry[:5] != ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn', '--bind', '0.0.0.0:5000']
or entry[5] != '--workers' or not str(entry[6]).isdigit()
or entry[7] != '--timeout' or not str(entry[8]).isdigit()
or entry[9:] != ['--access-logfile', '-', 'webapi:create_app()']
or api_config.get('Cmd') not in (None, [])):
raise RuntimeError('original API restart entrypoint is not verified migration-free')
worker_config = current[0]['Config']
if not current[0].get('State', {}).get('Running'):
if (worker_config.get('Entrypoint') not in [['/app/WebApi/.venv/bin/python', '-m', module]
for module in data_guard.WORKERS]
or worker_config.get('Cmd') not in (None, [])
or environment(current[0]).get('INDICADORES_AL_INICIAR') != '0'):
raise RuntimeError('original worker restart entrypoint is not verified safe')
if len(ids) == 4:
runner = current[3]
if not runner.get('State', {}).get('Running') and (
runner['Config'].get('Cmd') != ['notebooks'] or runner['Config'].get('User') != '10001:10001'
or runner.get('HostConfig', {}).get('NetworkMode') != 'none'
or runner.get('HostConfig', {}).get('ReadonlyRootfs') is not True):
raise RuntimeError('original notebook runner is not verified isolated')
if api.notebook_volume_identity(record['project']) != volume_identity:
raise RuntimeError('original notebook jobs volume changed')
image = record['images'][0]
contract = guard(api, image, 'contract', {})
all_stopped = all(item.get('State', {}).get('Running') is False for item in current)
state = guard(api, image, 'inspect', {'data': '/data', 'contract': contract, 'quiesced': all_stopped},
base / record['project'] / 'data')
if state != initial:
raise RuntimeError('original storage identity or schema changed')
for old, item in zip(original, current):
policy = old['HostConfig']['RestartPolicy']
value = policy['Name']
if value == 'on-failure' and policy.get('MaximumRetryCount', 0):
value += ':' + str(policy['MaximumRetryCount'])
api.run(['docker', 'update', '--restart=' + value, item['Id']])
for index in ((1, 0, 3, 2) if len(ids) == 4 else (1, 0, 2)):
if not current[index].get('State', {}).get('Running'):
api.run(['docker', 'start', ids[index]])
if api.verify_existing_containers(record, base, helper) != ids:
raise RuntimeError('original container identities changed after restart')
api.verify_services(previous_cmd, record['port'], notebooks=len(ids) == 4)
for old, item in zip(original, container_snapshot(api, ids)):
if (item.get('HostConfig', {}).get('RestartPolicy')
!= old.get('HostConfig', {}).get('RestartPolicy')):
raise RuntimeError('original restart policy was not restored')
def update(api, record, helper, root, base, *, verify_restore=False):
if (record.get('status') != 'installed'
or not isinstance(record.get('revision'), str)
or not re.fullmatch(r'[0-9a-f]{40}', record['revision'])
or not isinstance(record.get('gitlinks'), dict)
or 'ISSSTELEON' not in record['gitlinks']
or any(not isinstance(sha, str) or not re.fullmatch(r'[0-9a-f]{40}', sha)
for sha in record['gitlinks'].values())):
raise RuntimeError('installation status or Git provenance is invalid; manual inspection required')
project, port = record['project'], record['port']
metadata = getattr(api, 'request_metadata', lambda root: {})(root)
revision = api.git(root, 'rev-parse', 'HEAD').strip()
getattr(api, 'verify_target_revision', lambda revision: None)(revision)
expected = api.git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
old_ids = api.verify_existing_containers(record, base, helper)
phase = 'preparing'
current = None
operation_step = None
volume = old_volume = volume_identity = None
with tempfile.TemporaryDirectory(prefix='isssteleon-update-') as tmp:
directory = Path(tmp)
source, deploy, old_deploy = directory / 'codigo', directory / 'deploy', directory / 'old-deploy'
data = base / project / 'data'
try:
retained = read_deployment(api, helper, project, old_deploy)
previous_cmd = api.compose(project, old_deploy)
old_config = json.loads(api.run([*previous_cmd, 'config', '--format', 'json']))
old_tag = record['images'][0].removeprefix('isssteleon/webapi:')
old_volume = api.verify_config(old_config, project, data, old_tag, port)
if old_volume != record.get('notebook_volume'):
raise UpdateRefusal('retained composition and installation record disagree on notebook jobs')
if old_volume:
volume_identity = api.notebook_volume_identity(project)
current_environment(api, old_ids, old_config)
if revision == record['revision']:
phase = 'same-revision-verification'
operation_step = 'verify dispatched gitlinks against installation record'
manifest = api.pinned_manifest(root / 'ISSSTELEON', expected)
if record['gitlinks'] != manifest:
raise RuntimeError('recorded gitlinks differ from the dispatched revision')
operation_step = 'inspect installed storage contract'
contract = guard(api, record['images'][0], 'contract', {})
guard(api, record['images'][0], 'inspect', {'data': '/data', 'contract': contract}, data)
operation_step = 'verify installed services and image identities'
verify_api(api, previous_cmd, data, record['images'][0], notebook_volume=old_volume)
api.verify_services(previous_cmd, port, notebooks=bool(old_volume))
if api.verify_existing_containers(record, base, helper) != old_ids:
raise RuntimeError('installation containers changed during verification')
operation_step = 'record verified no-op'
api.host_action(helper, 'save', project, json.dumps(dict(
record, **metadata, result='unchanged', verification='complete')))
print(f'Unchanged {project} on port {port} at {revision}; verification complete')
return
manifest = {}
api.export_tree(root / 'ISSSTELEON', expected, source, manifest)
shutil.copytree(source / 'dist', deploy, symlinks=True)
tag = write_configuration(api, deploy, data, record, revision, retained['.env'])
images = [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}']
api.run(['docker', 'build', '-t', images[0], '-f', source / 'WebApi/Dockerfile', source])
api.run(['docker', 'build', '-t', images[1], source / 'WebApp'])
cmd = api.compose(project, deploy)
runtime = guard(api, images[0], 'runtime', {})
config = controlled_config(json.loads(api.run([*cmd, 'config', '--format', 'json'])),
worker=runtime['worker'])
volume = api.verify_config(config, project, data, tag, port)
if old_volume and not volume:
raise UpdateRefusal('candidate composition drops the notebook jobs volume; unsupported')
if volume and not old_volume and api.notebook_volume_identity(
project, missing_ok=True, verify=False) is not None:
raise UpdateRefusal('a volume named ' + volume + ' already exists and was not created by this '
'installation')
persist_config(deploy, config)
phase = 'compatibility'
contract = guard(api, images[0], 'contract', {})
initial = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract}, data)
operation_step = 'check notebook activity'
timeout = notebook_timeout(api, old_ids)
jobs = notebook_activity(api, images[0], data, old_volume, timeout)
operation_step = 'check other writers'
writer_activity(api, old_ids, requests=False)
operation_step = 'check the MLflow store'
mlflow_compatibility(api, images[0], data)
operation_step = None
prepared_bytes = sum(p.stat().st_size for tree in (source, deploy)
for p in tree.rglob('*') if p.is_file())
prepared_bytes += (jobs['bytes'] if jobs else 0) * (2 if verify_restore else 1)
api.host_action(helper, 'update-space-restore' if verify_restore else 'update-space',
project, str(prepared_bytes))
operation_step = 'prepare backup destinations in helper'
api.host_action(helper, 'prepare-backup', project,
json.dumps({'verify_restore': verify_restore}))
operation_step = None
if api.verify_existing_containers(record, base, helper) != old_ids:
raise RuntimeError('installation containers changed during preparation')
original_containers = container_snapshot(api, old_ids)
operation = uuid.uuid4().hex
current = dict(record, status='updating', operation_id=operation, phase='quiescing',
target_revision=revision, target_images=images, target_gitlinks=manifest,
target_branch=metadata.get('branch'), target_notebook_volume=volume,
migrations='none-pending', recalculation='not-started')
def save():
api.host_action(helper, 'save', project, json.dumps(current))
save()
phase = 'quiescing'
# The frontend publishes the only port, so once it stops no notebook can be submitted.
frontend = old_ids[2]
for container in [frontend] + [ident for ident in old_ids if ident != frontend]:
api.run(['docker', 'update', '--restart=no', container])
api.run(['docker', 'stop', container])
if container == frontend:
operation_step = 'check notebook activity with the frontend stopped'
notebook_activity(api, images[0], data, old_volume, timeout)
operation_step = 'check other writers with the frontend stopped'
writer_activity(api, old_ids, requests=True)
operation_step = None
for container in old_ids:
state = json.loads(api.run(['docker', 'inspect', '--format', '{{json .State}}', container]))
if state.get('Running') is not False:
raise RuntimeError('an existing writer did not stop')
phase = 'backup'
current['phase'] = phase
current['backup'] = str(base / '.backups' / project / operation)
operation_step = 'save backup phase record'
save()
operation_step = 'inspect quiesced storage'
quiesced = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract,
'quiesced': True}, data)
operation_step = 'compare storage identity and schema'
if quiesced != initial:
raise RuntimeError('storage identity or schema changed during preparation')
operation_step = 'check notebook activity after quiescing'
jobs = notebook_activity(api, images[0], data, old_volume, timeout, quiesced=True)
operation_step = 'check the MLflow store after quiescing'
mlflow_compatibility(api, images[0], data, quiesced=True)
origin = {key: record[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images') if key in record}
operation_step = 'create and verify backup in helper'
backup = json.loads(api.host_action(helper, 'backup', project, json.dumps({
'operation_id': operation, 'contract': contract, 'origin': origin})))
expected_jobs = None
if old_volume:
operation_step = 'prepare notebook backup destination in helper'
api.host_action(helper, 'prepare-notebook-backup', project, operation)
# The helper creates the directory under /host. Docker resolves binds on the daemon host.
target = str(base / '.backups' / project / operation / 'notebooks')
operation_step = 'verify notebook jobs volume identity'
if api.notebook_volume_identity(project) != volume_identity:
raise RuntimeError('notebook jobs volume identity changed during preparation')
operation_step = 'create notebook backup'
created = notebook_guard(api, images[0], 'backup', {
'root': '/trabajos', 'destination': '/respaldo', 'volume': volume_identity}, old_volume, target)
operation_step = 'verify notebook backup in helper'
verified = json.loads(api.host_action(helper, 'verify-notebook-backup', project, operation))
if not created['digest'] == verified['digest'] == jobs['digest']:
raise RuntimeError('notebook backup does not match the quiesced volume')
expected_jobs = jobs['digest']
current['notebook_backup'] = {'path': target, 'volume': old_volume, 'digest': expected_jobs}
operation_step = 'save notebook backup record'
save()
if verify_restore:
current['phase'] = phase = 'restore-verification'
current['restore_check'] = str(base / '.restores' / project / operation)
operation_step = 'save restore verification record'
save()
operation_step = 'restore and verify backup in helper'
api.host_action(helper, 'verify-restore', project, operation)
current['phase'] = phase = 'activating'
current['archive'] = str(base / project / '.archive' / operation)
save()
api.host_action(helper, 'stage', project, operation)
for name, path in (('codigo', source), ('deploy', deploy)):
api.copy_to_host(helper, path, project, '.updates/' + operation + '/' + name)
api.host_action(helper, 'activate', project, json.dumps({
'operation_id': operation, 'previous': record}))
current['phase'] = phase = 'api'
save()
# No pending migrations are supported; the direct entrypoint cannot run Alembic.
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
if volume and not old_volume:
created = verify_new_notebook_volume(api, images[0], project)
volume_identity, expected_jobs = created['identity'], created['digest']
elif volume and api.notebook_volume_identity(project) != volume_identity:
raise RuntimeError('notebook jobs volume identity changed during activation')
check_jobs = (lambda: verify_notebook_jobs(api, images[0], project, volume_identity, expected_jobs)
) if volume else None
def progress(next_phase):
nonlocal phase
current['phase'] = phase = next_phase
if next_phase == 'recalculation-and-persistence':
current['recalculation'] = 'running'
elif next_phase == 'worker':
current['recalculation'] = 'complete'
save()
finish(api, cmd, images[0], deploy, data, contract, backup['state'], progress,
notebook_volume=volume, before_frontend=check_jobs)
current['phase'] = phase = 'availability'
save()
api.verify_services(cmd, port, notebooks=bool(volume))
target_record = dict(record, images=images, notebook_volume=volume)
if not volume:
target_record.pop('notebook_volume')
api.verify_existing_containers(target_record, base, helper)
guard(api, images[0], 'verify',
{'data': '/data', 'contract': contract, 'before': backup['state'], 'derived': True}, data)
current.update(status='installed', revision=revision, gitlinks=manifest, images=images,
phase='complete', result='updated', recalculation='complete', verification='complete')
if volume:
current['notebook_volume'] = volume
current.update(metadata)
current.pop('error', None)
save()
print(f'Updated {project} on port {port} at {revision}')
except Exception as exc:
failure_record_unavailable = False
if current is not None:
if phase in ('api', 'recalculation-and-persistence', 'worker', 'notebooks', 'frontend',
'availability'):
try:
freeze_failed(api, cmd, project, data, volume)
except Exception:
current['quarantine'] = 'incomplete; inspect owned containers before recovery'
current.update(status='update_failed', phase=phase,
error='Update failed; preserve storage and inspect recovery metadata.',
recovery='manual; never restore over live data automatically')
# Retain original provenance; target references remain separate for recovery.
for key in ('revision', 'gitlinks', 'images', 'notebook_volume'):
current.pop(key, None)
if key in record:
current[key] = record[key]
if phase in ('quiescing', 'backup', 'restore-verification'):
try:
api.host_action(helper, 'save', project, json.dumps(current))
except Exception:
failure_record_unavailable = True
try:
recover_original(api, record, helper, base, old_ids, original_containers,
previous_cmd, initial, volume_identity)
current['recovery'] = 'original services verified; reconciliation required'
except Exception:
current['recovery'] = 'incomplete; inspect original services before reconciliation'
try:
api.host_action(helper, 'save', project, json.dumps(current))
failure_record_unavailable = False
except Exception:
failure_record_unavailable = True
else:
api.host_action(helper, 'save', project, json.dumps(current))
detail = ''
if isinstance(exc, UpdateRefusal):
detail = ('; operation=' + operation_step if operation_step else '') + '; ' + str(exc)
elif phase in ('compatibility', 'same-revision-verification') and isinstance(exc, GuardFailure):
detail = '; ' + str(exc)
elif phase == 'same-revision-verification':
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
if (phase in ('compatibility', 'backup', 'restore-verification') and operation_step
and not isinstance(exc, UpdateRefusal)):
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
if operation_step == 'inspect quiesced storage' and isinstance(exc, GuardFailure):
detail = '; operation=' + operation_step + '; ' + str(exc)
if phase == 'recalculation-and-persistence' and isinstance(exc, RecalculationFailure):
detail = '; operation=' + exc.step + '; ' + exc.category
if failure_record_unavailable:
detail += '; failure record could not be saved; inspect the installation manually'
raise RuntimeError('Conservative update failed during ' + phase
+ '; existing storage was not replaced' + detail) from None
-780
View File
@@ -1,780 +0,0 @@
"""Inspect SQLite metadata and verify quiesced synthetic or deployed storage.
Only contract generation imports application packages. Inspection never imports
Persistance's engine factories or runs a migration.
"""
from collections import Counter
from contextlib import closing
import hashlib
import importlib
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import sqlite3
import stat
import sys
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
APP_DATABASES = {domain + '.db' for domain in DOMAINS}
INSPECTION_REASONS = {
'persistent directory is missing or linked': 'persistent_directory_invalid',
'linked persistent entry is unsupported': 'linked_persistent_entry',
'special persistent entry is unsupported': 'special_persistent_entry',
'required SQLite file is missing or linked': 'database_missing_or_linked',
'four domain contracts are required': 'contract_domains_invalid',
'Alembic version is unavailable': 'migration_version_unavailable',
'exactly one installed revision is required': 'migration_version_count',
'unknown Alembic revision': 'migration_revision_unknown',
'pending migrations are not supported': 'migration_pending',
'structure differs from the candidate': 'schema_mismatch',
'SQLite integrity check failed': 'sqlite_integrity_failed',
'SQLite foreign key check failed': 'sqlite_foreign_key_failed',
'database triggers are unsupported': 'schema_triggers_unsupported',
'custom table options are unsupported': 'schema_options_unsupported',
'hidden or generated columns are unsupported': 'schema_columns_unsupported',
'partial indexes are unsupported': 'schema_partial_indexes_unsupported',
'expression indexes are unsupported': 'schema_expression_indexes_unsupported',
'unclosed schema constraint': 'schema_constraint_invalid',
'persistent directory identity changed': 'directory_identity_changed',
'persistent directory disappeared': 'directory_disappeared',
'database file identity changed': 'database_identity_changed',
'indicator audit log disappeared': 'audit_log_disappeared',
'indicator audit history changed': 'audit_history_changed',
'auxiliary SQLite integrity check failed': 'auxiliary_integrity_failed',
'worker module is unavailable': 'worker_module_unavailable',
'MLflow run status is unverifiable': 'notebook_runs_unverifiable',
'MLflow store created with content': 'mlflow_store_not_initial',
'MLflow store is unverifiable': 'mlflow_store_unverifiable',
}
INSPECTION_ERROR_TYPES = {'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
'TypeError', 'KeyError', 'MemoryError', 'Other'}
SQLITE_ERROR_NAMES = {name for name in dir(sqlite3) if name.startswith('SQLITE_')
and isinstance(getattr(sqlite3, name), int)}
MUTABLE = {
'persona', 'procedimiento', 'observacion_clinica', 'def_parametro',
'dim_fecha', 'dim_grupo_edad', 'periodo_observacion', 'dim_periodo',
'cat_estudio', 'cat_resultado', 'cat_valor', 'cat_estrato',
'cat_estrato_valor', 'cat_measure', 'cat_measure_resultado',
'cat_measure_valor', 'cat_measure_grupo', 'cat_measure_estrato',
}
# Tables the recalculation's `catalogs` step only adds to (`SourceMappingRepository.ensure_system` and `seed`):
# the catalog's own source system and its mappings, in force since 1900-01-01 and never changing a stored row.
# The application adds and closes the other rows, so every row already stored must survive unchanged, and an
# added row must carry these values and a form no stored row has.
SEEDED = {
'cat_sistema_fuente': {'sistema_fuente_id': 'catalogo', 'fuente_tabla': None, 'vigente_desde': '1900-01-01',
'vigente_hasta': None},
'cat_mapeo': {'sistema_fuente_id': 'catalogo', 'registrado_por': 'catalogo', 'vigente_desde': '1900-01-01',
'vigente_hasta': None, 'motivo': None},
}
SEEDED_FORM = {
'cat_sistema_fuente': ('sistema_fuente_id',),
'cat_mapeo': ('sistema_fuente_id', 'clase', 'resultado_id', 'estudio_id', 'forma_normalizada'),
}
# MLflow's store under /data: the live estimators open the registry, which creates an empty store when absent.
MLFLOW_STORE = 'mlflow.db'
# The registered-model alias of the version in production (`models.io.registry`).
PRODUCTION_ALIAS = 'produccion'
# Worker modules an image may provide, newest first, with their queue class and its methods
# (take a marker, run a domain, list pending markers).
WORKERS = {
'webapi.recomputation': ('RecomputationQueue', 'take', 'run', 'pending'),
'webapi.indicadores_vivos': ('ColaDeRecalculo', 'tomar', 'correr', 'pendientes'),
}
# A notebook run still marked RUNNING this long after its job timeout is shown as interrupted.
NOTEBOOK_STALE_MARGIN_S = 1800
APPEND_ONLY = {
'carga', 'measure_report', 'measure_report_unidad',
'measure_report_unidad_estrato', 'cohorte_armado', 'cohorte_miembro',
'cohorte_exclusion', 'cohorte_variable',
}
def require(condition, message):
if not condition:
raise RuntimeError(message)
def quote(name):
return '"' + name.replace('"', '""') + '"'
def identity(path):
info = Path(path).stat()
return [info.st_dev, info.st_ino]
def digest(path):
result = hashlib.sha256()
with Path(path).open('rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
result.update(chunk)
return result.hexdigest()
def regular_tree(root):
root = Path(root)
require(root.is_dir() and not root.is_symlink(), 'persistent directory is missing or linked')
files = {}
for path in sorted(root.rglob('*')):
require(not path.is_symlink(), 'linked persistent entry is unsupported')
mode = path.stat().st_mode
require(stat.S_ISDIR(mode) or stat.S_ISREG(mode), 'special persistent entry is unsupported')
if path.is_file():
files[path.relative_to(root).as_posix()] = path
return files
def readonly(path, *, immutable=False):
path = Path(path)
require(path.is_file() and not path.is_symlink(), 'required SQLite file is missing or linked')
connection = sqlite3.connect(path.resolve().as_uri() + '?mode=ro' + ('&immutable=1' if immutable else ''),
uri=True, timeout=10)
connection.execute('PRAGMA query_only=ON')
return connection
def checks(sql):
"""Normalize CHECK bodies without depending on generated constraint names."""
result = []
for match in re.finditer(r'\bCHECK\s*\(', sql or '', re.I):
start = match.end()
depth, quoted, i = 1, None, start
while depth and i < len(sql):
char = sql[i]
if quoted:
if char == quoted:
if i + 1 < len(sql) and sql[i + 1] == quoted:
i += 1
else:
quoted = None
elif char in ("'", '"'):
quoted = char
elif char == '(':
depth += 1
elif char == ')':
depth -= 1
i += 1
require(depth == 0, 'unclosed schema constraint')
result.append(re.sub(r'\s+', ' ', sql[start:i - 1]).strip())
return sorted(result)
def schema(connection):
require(not connection.execute("SELECT 1 FROM sqlite_master WHERE type='trigger'").fetchone(),
'database triggers are unsupported')
result = {}
tables = connection.execute(
"SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
).fetchall()
for table, sql in tables:
if table == 'alembic_version':
continue
require(not re.search(r'\b(WITHOUT\s+ROWID|STRICT|DEFERRABLE|COLLATE)\b', sql, re.I),
'custom table options are unsupported')
require(not any(row[6] for row in connection.execute('PRAGMA table_xinfo(' + quote(table) + ')')),
'hidden or generated columns are unsupported')
columns = [list(row[1:6]) for row in connection.execute('PRAGMA table_info(' + quote(table) + ')')]
for column in columns:
column[1] = re.sub(r'\s+', '', column[1]).upper()
indexes = set()
for index in connection.execute('PRAGMA index_list(' + quote(table) + ')'):
require(not index[4], 'partial indexes are unsupported')
if index[3] != 'pk':
fields = tuple((row[2], row[3], row[4]) for row in connection.execute(
'PRAGMA index_xinfo(' + quote(index[1]) + ')') if row[5])
require(all(field[0] for field in fields), 'expression indexes are unsupported')
indexes.add((bool(index[2]), fields))
foreign = {}
for row in connection.execute('PRAGMA foreign_key_list(' + quote(table) + ')'):
foreign.setdefault(row[0], []).append(row)
foreign = sorted(
[[row[2], row[3], row[4], row[5], row[6], row[7]] for row in sorted(group, key=lambda r: r[1])]
for group in foreign.values()
)
result[table] = {
'columns': columns,
'indexes': [[unique, [list(field) for field in fields]] for unique, fields in sorted(indexes)],
'foreign_keys': foreign, 'checks': checks(sql),
}
return result
def same_structure(actual, expected):
"""Whether two `schema` results match, apart from the physical order of each table's columns.
A migration that creates a table lists its columns in its own order; the models may declare another. Every
other column property (name, type, nullability, default, primary-key position) and every index, foreign key
and check still has to match exactly."""
def by_name(structure):
return {table: dict(metadata, columns=sorted(metadata['columns'], key=lambda column: column[0]))
for table, metadata in structure.items()}
return by_name(actual) == by_name(expected)
def target_contract():
"""Create only in-memory reference schemas using the candidate's own metadata."""
from alembic.config import Config
from alembic.script import ScriptDirectory
from sqlalchemy import create_engine
import persistance
result = {}
for domain in DOMAINS:
importlib.import_module('core.' + domain + '.models')
if domain != 'governance':
importlib.import_module('core.' + domain + '.indicadores.models')
base = importlib.import_module('core.' + domain + '.base')
model = getattr(base, {'cacu': 'CaCuModel', 'cama': 'CaMaModel',
'tea': 'TeaModel', 'governance': 'GovernanceModel'}[domain])
config = Config(str(Path(persistance.__file__).parent / domain / 'alembic.ini'))
scripts = ScriptDirectory.from_config(config)
heads = scripts.get_heads()
require(len(heads) == 1, 'candidate must have one migration head per domain')
engine = create_engine('sqlite://')
try:
model.metadata.create_all(engine)
with closing(engine.raw_connection()) as connection:
expected = schema(connection)
finally:
engine.dispose()
result[domain] = {'head': heads[0], 'known': sorted(r.revision for r in scripts.walk_revisions()),
'schema': expected}
return result
def inspect_databases(root, contract, *, rows=False, quiesced=False):
root = Path(root)
regular_tree(root)
require(set(contract) == set(DOMAINS), 'four domain contracts are required')
result = {}
for domain in DOMAINS:
try:
path = root / (domain + '.db')
def inspect_one(immutable=False):
with closing(readonly(path, immutable=True) if immutable else readonly(path)) as connection:
connection.execute('BEGIN')
try:
versions = connection.execute('SELECT version_num FROM alembic_version').fetchall()
except sqlite3.Error as exc:
error = RuntimeError(domain + ': Alembic version is unavailable')
error.sqlite_errorname = getattr(exc, 'sqlite_errorname', None)
raise error from None
require(len(versions) == 1, domain + ': exactly one installed revision is required')
current = versions[0][0]
expected = contract[domain]
require(current in expected['known'], domain + ': unknown Alembic revision')
require(current == expected['head'], domain + ': pending migrations are not supported')
actual = schema(connection)
require(same_structure(actual, expected['schema']),
domain + ': structure differs from the candidate')
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
domain + ': SQLite integrity check failed')
require(not connection.execute('PRAGMA foreign_key_check').fetchall(),
domain + ': SQLite foreign key check failed')
state = {'revision': current, 'schema': actual, 'identity': identity(path)}
if rows:
state['tables'] = table_state(connection, domain)
return state
try:
result[domain] = inspect_one()
except (RuntimeError, sqlite3.OperationalError) as exc:
if not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN':
raise
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
if any(p.exists() or p.is_symlink() for p in sidecars):
raise
before = path.stat()
result[domain] = inspect_one(immutable=True)
after = path.stat()
if (any(p.exists() or p.is_symlink() for p in sidecars)
or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns)
!= (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns)):
raise RuntimeError('database changed during quiesced inspection')
except Exception as exc:
exc.inspection_domain = domain
raise
return {'directory': identity(root), 'databases': result}
def inspection_diagnostic(exc):
"""Return only allowlisted rejection categories, never exception text or data."""
domain = getattr(exc, 'inspection_domain', None)
domain = domain if domain in DOMAINS else 'none'
message = str(exc)
if domain == 'none':
for candidate in DOMAINS:
if message.startswith(candidate + ': '):
domain = candidate
break
if domain != 'none' and message.startswith(domain + ': '):
message = message[len(domain) + 2:]
reason = INSPECTION_REASONS.get(message, 'unclassified')
if message.startswith('persistent rows changed in '):
reason = 'protected_rows_changed'
elif message.startswith('historical rows changed in '):
reason = 'historical_rows_changed'
elif message.startswith('persistent file changed: '):
reason = 'persistent_file_changed'
elif message.startswith('seeded rows are not the catalog'):
reason = 'seeded_rows_invalid'
kind = type(exc).__name__
kind = kind if kind in INSPECTION_ERROR_TYPES else 'Other'
sqlite_name = getattr(exc, 'sqlite_errorname', None)
if sqlite_name not in SQLITE_ERROR_NAMES:
sqlite_name = 'none'
number = getattr(exc, 'errno', None)
number = number if type(number) is int and 0 <= number <= 4095 else None
return {'reason': reason, 'domain': domain, 'type': kind, 'sqlite': sqlite_name, 'errno': number}
def row_hash(row):
encoded = json.dumps(row, default=lambda v: {'blob_sha256': hashlib.sha256(v).hexdigest()},
ensure_ascii=True, separators=(',', ':')).encode()
return hashlib.sha256(encoded).hexdigest()
def table_state(connection, domain):
result = {}
for table, metadata in schema(connection).items():
keys = [column[0] for column in sorted(metadata['columns'], key=lambda c: c[4]) if column[4]]
require(keys, 'tables without primary keys are unsupported')
query = 'SELECT * FROM ' + quote(table) + ' ORDER BY ' + ','.join(map(quote, keys))
mode = ('mutable' if table in MUTABLE else 'append' if table in APPEND_ONLY
else 'seeded' if table in SEEDED else 'exact')
if domain == 'governance':
mode = 'exact'
value_hash, row_hashes, count = hashlib.sha256(), Counter(), 0
for row in connection.execute(query):
hashed = row_hash(row)
value_hash.update(hashed.encode())
if mode in ('append', 'seeded'):
row_hashes[hashed] += 1
count += 1
result[table] = {'mode': mode, 'count': count, 'sha256': value_hash.hexdigest()}
if mode in ('append', 'seeded'):
result[table]['rows'] = dict(row_hashes)
return result
def verify_seeded(path, domain, table, retained):
"""Rows not among `retained` (hashes of the rows stored before) must be the catalog's own seed rows."""
message = domain + ': seeded rows are not the catalog\'s own in ' + table
with closing(readonly(path)) as connection:
connection.execute('BEGIN')
cursor = connection.execute('SELECT * FROM ' + quote(table))
names = [column[0] for column in cursor.description]
signature, form = SEEDED[table], SEEDED_FORM[table]
require(set(signature) | set(form) <= set(names), message)
kept, added = set(), []
for row in cursor:
record = dict(zip(names, row))
if row_hash(row) in retained:
kept.add(tuple(record[column] for column in form))
else:
added.append(record)
forms = [tuple(record[column] for column in form) for record in added]
require(all(record[column] == value for record in added for column, value in signature.items()), message)
require(len(set(forms)) == len(forms) and not set(forms) & kept, message)
return len(added)
def initial_mlflow_store(path):
"""Whether `path` is the empty store MLflow creates on first use: its schema version, the `Default` experiment,
the `default` workspace of MLflow 3 stores and nothing else."""
with closing(readonly(path)) as connection:
connection.execute('BEGIN')
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
'auxiliary SQLite integrity check failed')
tables = [name for (name,) in connection.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
if not {'alembic_version', 'experiments', 'runs', 'registered_models', 'model_versions'} <= set(tables):
return False
for table in tables:
rows = connection.execute('SELECT * FROM ' + quote(table)).fetchall()
if table == 'alembic_version':
if len(rows) != 1:
return False
elif table == 'experiments':
columns = [row[1] for row in connection.execute('PRAGMA table_info(experiments)')]
if len(rows) != 1 or not {'experiment_id', 'name', 'lifecycle_stage'} <= set(columns):
return False
experiment = dict(zip(columns, rows[0]))
if ((experiment['experiment_id'], experiment['name'], experiment['lifecycle_stage']) != (
0, 'Default', 'active') or experiment.get('workspace', 'default') != 'default'):
return False
elif table == 'workspaces':
columns = [row[1] for row in connection.execute('PRAGMA table_info(workspaces)')]
if len(rows) != 1 or 'name' not in columns:
return False
workspace = dict(zip(columns, rows[0]))
if workspace['name'] != 'default' or any(
value is not None for key, value in workspace.items() if key not in ('name', 'description')):
return False
elif rows:
return False
return True
def is_sqlite(path):
with Path(path).open('rb') as stream:
return stream.read(16) == b'SQLite format 3\x00'
def auxiliary(name, files):
return any(name.endswith(suffix) and name[:-len(suffix)] in files
and is_sqlite(files[name[:-len(suffix)]])
for suffix in ('-wal', '-shm', '-journal'))
def sqlite_digest(path):
result = hashlib.sha256()
with closing(readonly(path)) as connection:
connection.execute('BEGIN')
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
'auxiliary SQLite integrity check failed')
for statement in connection.iterdump():
result.update(statement.encode('utf-8'))
result.update(b'\n')
return result.hexdigest()
def storage_state(root, contract):
result = inspect_databases(root, contract, rows=True)
files = regular_tree(root)
result['files'] = {
name: {'size': path.stat().st_size, 'sha256': digest(path),
**({'sqlite_sha256': sqlite_digest(path)} if is_sqlite(path) else {})}
for name, path in files.items() if name not in APP_DATABASES and not auxiliary(name, files)
}
result['directories'] = sorted(path.relative_to(root).as_posix() for path in Path(root).rglob('*')
if path.is_dir())
return result
def verify_state(root, contract, before, *, derived=False):
after = storage_state(root, contract)
require(after['directory'] == before['directory'], 'persistent directory identity changed')
require(set(before['directories']) <= set(after['directories']), 'persistent directory disappeared')
for domain in DOMAINS:
old, new = before['databases'][domain], after['databases'][domain]
require(new['identity'] == old['identity'], domain + ': database file identity changed')
for table, prior in old['tables'].items():
current = new['tables'][table]
if derived and prior['mode'] == 'mutable':
continue
if derived and prior['mode'] in ('append', 'seeded'):
require(not (Counter(prior['rows']) - Counter(current['rows'])),
domain + ': historical rows changed in ' + table)
if prior['mode'] == 'seeded' and Counter(current['rows']) - Counter(prior['rows']):
verify_seeded(Path(root) / (domain + '.db'), domain, table, set(prior['rows']))
else:
require(current == prior, domain + ': persistent rows changed in ' + table)
permitted = {'indicadores/estado.json', 'indicadores/.estado.lock',
*('indicadores/pendiente/' + domain for domain in DOMAINS if domain != 'governance')}
for name in before['files'].keys() | after['files'].keys():
if derived and name in permitted:
continue
if derived and name == MLFLOW_STORE and name not in before['files']:
require(initial_mlflow_store(Path(root) / name), 'MLflow store created with content')
continue
if derived and name == 'reportes/indicadores.jsonl':
if name in before['files']:
path = Path(root) / name
require(path.is_file(), 'indicator audit log disappeared')
with path.open('rb') as stream:
prefix = hashlib.sha256(stream.read(before['files'][name]['size'])).hexdigest()
require(prefix == before['files'][name]['sha256'], 'indicator audit history changed')
continue
require(after['files'].get(name) == before['files'].get(name), 'persistent file changed: ' + name)
return after
def create_backup(root, destination, contract, origin):
"""Snapshot only quiesced writers; normalize SQLite WAL through its backup API."""
root, destination = Path(root), Path(destination)
require(not destination.resolve().is_relative_to(root.resolve()), 'backup must be outside persistent storage')
before = storage_state(root, contract)
files = regular_tree(root)
require({name for name in files if not auxiliary(name, files)} == APP_DATABASES | before['files'].keys(),
'storage changed while creating the backup')
require(not destination.exists() and not destination.is_symlink(), 'backup destination already exists')
destination.mkdir(mode=0o700)
data = destination / 'data'
data.mkdir(mode=0o700)
for path in root.rglob('*'):
if path.is_dir():
(data / path.relative_to(root)).mkdir(parents=True, exist_ok=True)
shutil.copystat(path, data / path.relative_to(root))
sqlite_files = []
for name, path in files.items():
if auxiliary(name, files):
continue
target = data / name
target.parent.mkdir(parents=True, exist_ok=True)
if is_sqlite(path):
with closing(readonly(path)) as source, closing(sqlite3.connect(target)) as copy:
source.backup(copy)
# A backup inherits WAL mode; use a standalone file for portable recovery.
copy.execute('PRAGMA journal_mode=DELETE')
require(copy.execute('PRAGMA integrity_check').fetchall() == [('ok',)], 'backup integrity failed')
shutil.copystat(path, target)
sqlite_files.append(name)
if name not in APP_DATABASES:
require(sqlite_digest(target) == before['files'][name]['sqlite_sha256'],
'auxiliary SQLite backup content differs')
else:
shutil.copy2(path, target)
require(digest(target) == before['files'][name]['sha256'], 'copied artifact differs from source')
require(storage_state(root, contract) == before, 'storage changed while creating the backup')
snapshot = inspect_databases(data, contract, rows=True)
for domain in DOMAINS:
require(snapshot['databases'][domain]['tables'] == before['databases'][domain]['tables'],
domain + ': backup rows differ')
manifest = {'format': 1, 'origin': origin, 'contract': contract, 'state': before,
'sqlite_files': sqlite_files,
'files': {name: digest(path) for name, path in regular_tree(data).items()}}
with (destination / 'manifest.json').open('x', encoding='utf-8') as stream:
json.dump(manifest, stream, sort_keys=True)
stream.flush()
os.fsync(stream.fileno())
verify_backup(destination)
return manifest
def verify_backup(destination):
destination = Path(destination)
require(destination.is_dir() and not destination.is_symlink(), 'invalid backup directory')
manifest = json.loads((destination / 'manifest.json').read_text(encoding='utf-8'))
files = regular_tree(destination / 'data')
require(manifest['format'] == 1 and set(files) == set(manifest['files']), 'backup inventory differs')
directories = sorted(path.relative_to(destination / 'data').as_posix()
for path in (destination / 'data').rglob('*') if path.is_dir())
require(directories == manifest['state']['directories'], 'backup directory inventory differs')
for name, path in files.items():
require(digest(path) == manifest['files'][name], 'backup checksum mismatch')
for name in manifest['sqlite_files']:
with closing(readonly(files[name])) as connection:
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)], 'backup integrity failed')
current = inspect_databases(destination / 'data', manifest['contract'], rows=True)
for domain in DOMAINS:
require(current['databases'][domain]['tables'] == manifest['state']['databases'][domain]['tables'],
'backup logical content differs')
return manifest
def restore_backup(source, destination):
"""Restore only to a new isolated directory; never overwrite an installation."""
manifest = verify_backup(source)
destination = Path(destination)
require(not destination.resolve().is_relative_to(Path(source).resolve()),
'restore destination must be outside the backup')
require(not destination.exists() and not destination.is_symlink(), 'restore destination must be new')
shutil.copytree(Path(source) / 'data', destination)
files = regular_tree(destination)
require({name: digest(path) for name, path in files.items()} == manifest['files'], 'restored files differ')
actual = inspect_databases(destination, manifest['contract'], rows=True)
for domain in DOMAINS:
require(actual['databases'][domain]['tables'] == manifest['state']['databases'][domain]['tables'],
'restored rows differ')
return actual
def worker_module():
"""The image's worker module, found on disk without importing the application package."""
spec = importlib.util.find_spec('webapi')
require(spec is not None and spec.submodule_search_locations, 'worker module is unavailable')
for module in WORKERS:
name = module.split('.', 1)[1] + '.py'
if any((Path(location) / name).is_file() for location in spec.submodule_search_locations):
return module
raise RuntimeError('worker module is unavailable')
def recalculate(environment):
"""Run each domain once and retain only safe failure context."""
stage, domain = 'environment', 'none'
try:
require(isinstance(environment, dict) and all(isinstance(k, str) and isinstance(v, str)
and '=' not in k and '\x00' not in k + v for k, v in environment.items()),
'invalid resolved worker environment')
os.environ.update(environment)
stage = 'import'
module = worker_module()
name, take, run, pending = WORKERS[module]
stage = 'initialize'
queue = getattr(importlib.import_module(module), name)()
completed = []
for domain in DOMAINS:
if domain == 'governance':
continue
stage = 'enqueue'
getattr(queue, take)(domain)
stage = 'execute'
result = getattr(queue, run)(domain)
stage = 'domain_result'
require(isinstance(result, dict) and result.get('estado') == 'ok', 'indicator recalculation failed')
completed.append(domain)
domain, stage = 'none', 'pending'
require(not getattr(queue, pending)(), 'unexpected pending recalculations')
return {'completed': completed}
except Exception as exc:
exc.recalculation_stage = stage
exc.inspection_domain = domain
raise
def notebook_runs(root, timeout_s, now_ms, *, request_timeout_s=None, quiesced=False):
"""Count notebook runs MLflow still holds as running and not yet stale (`models.pipelines.experiment`), and,
with `request_timeout_s`, the other running runs started within that time plus the same margin.
A notebook run is queued or executing in the API process from its creation until it is terminated, so a
positive count means stopping the API would interrupt it. The other runs are trainings and the extraction
ranker's learning (`models.io.extraction_ranker.learn`, a background thread after an import); a request or
a learning step ends well within the API's request timeout, so an older running one was cut off before."""
path = Path(root) / 'mlflow.db'
require(type(timeout_s) is int and timeout_s > 0 and type(now_ms) is int, 'invalid notebook run window')
require(request_timeout_s is None or (type(request_timeout_s) is int and request_timeout_s > 0),
'invalid notebook run window')
if not path.exists() and not path.is_symlink():
return {'active': 0, 'training': 0}
def count(immutable):
with closing(readonly(path, immutable=immutable)) as connection:
connection.execute('BEGIN')
tables = {name: {row[1] for row in connection.execute('PRAGMA table_info(' + quote(name) + ')')}
for (name,) in connection.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('runs', 'tags')")}
if not tables:
return {'active': 0, 'training': 0}
require(tables.get('runs', set()) >= {'run_uuid', 'status', 'lifecycle_stage', 'start_time'}
and tables.get('tags', set()) >= {'run_uuid', 'key', 'value'},
'MLflow run status is unverifiable')
notebook = ("EXISTS (SELECT 1 FROM tags t WHERE t.run_uuid = r.run_uuid AND t.key = 'experiment'"
" AND t.value = 'notebook')")
running = ("SELECT count(*) FROM runs r WHERE r.status = 'RUNNING' AND r.lifecycle_stage = 'active'"
" AND (r.start_time IS NULL OR r.start_time >= ?) AND ")
limit = now_ms - (timeout_s + NOTEBOOK_STALE_MARGIN_S) * 1000
result = {'active': connection.execute(running + notebook, (limit,)).fetchone()[0], 'training': 0}
if request_timeout_s is not None:
limit = now_ms - (request_timeout_s + NOTEBOOK_STALE_MARGIN_S) * 1000
result['training'] = connection.execute(running + 'NOT ' + notebook, (limit,)).fetchone()[0]
return result
try:
return count(False)
except sqlite3.OperationalError as exc:
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
if (not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN'
or any(p.exists() or p.is_symlink() for p in sidecars)):
raise RuntimeError('MLflow run status is unverifiable') from None
return count(True)
def mlflow_store(root, *, quiesced=False):
"""The MLflow store's schema revision and how many registered models have a version in production.
MLflow refuses to open a store whose schema is older than its own, and with a production version the
recalculation's live estimators export a cohort file and store a risk batch."""
path = Path(root) / MLFLOW_STORE
if not path.exists() and not path.is_symlink():
return {'exists': False, 'revision': None, 'production': 0}
def read(immutable):
with closing(readonly(path, immutable=immutable)) as connection:
connection.execute('BEGIN')
tables = {name for (name,) in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")}
require('alembic_version' in tables, 'MLflow store is unverifiable')
versions = connection.execute('SELECT version_num FROM alembic_version').fetchall()
require(len(versions) == 1, 'MLflow store is unverifiable')
production = 0
if 'registered_model_aliases' in tables:
production = connection.execute('SELECT count(*) FROM registered_model_aliases WHERE alias = ?',
(PRODUCTION_ALIAS,)).fetchone()[0]
return {'exists': True, 'revision': versions[0][0], 'production': production}
try:
return read(False)
except sqlite3.OperationalError as exc:
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
if (not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN'
or any(p.exists() or p.is_symlink() for p in sidecars)):
raise RuntimeError('MLflow store is unverifiable') from None
return read(True)
def mlflow_heads():
"""The schema revisions this image's MLflow expects, from its own migration scripts."""
from alembic.config import Config
from alembic.script import ScriptDirectory
import mlflow.store.db_migrations as migrations
config = Config()
config.set_main_option('script_location', os.path.dirname(migrations.__file__))
return {'heads': sorted(ScriptDirectory.from_config(config).get_heads())}
def silent_recalculate(environment):
"""Keep library stdout out of the machine-readable response."""
sys.stdout.flush()
saved = os.dup(1)
try:
with open(os.devnull, 'w') as sink:
os.dup2(sink.fileno(), 1)
try:
return recalculate(environment)
finally:
sys.stdout.flush()
finally:
os.dup2(saved, 1)
os.close(saved)
def main():
action, payload = sys.argv[1], json.load(sys.stdin)
if action == 'contract':
result = target_contract()
elif action == 'inspect':
result = inspect_databases(payload['data'], payload['contract'], quiesced=payload.get('quiesced', False))
elif action == 'state':
result = storage_state(payload['data'], payload['contract'])
elif action == 'verify':
result = verify_state(payload['data'], payload['contract'], payload['before'],
derived=payload.get('derived', False))
elif action == 'recalculate':
result = silent_recalculate(payload['environment'])
elif action == 'mlflow-store':
result = mlflow_store(payload['data'], quiesced=payload.get('quiesced', False))
elif action == 'mlflow-heads':
result = mlflow_heads()
elif action == 'runtime':
result = {'worker': worker_module()}
elif action == 'notebook-runs':
result = notebook_runs(payload['data'], payload['timeout'], payload['now'],
request_timeout_s=payload.get('request_timeout'), quiesced=payload.get('quiesced', False))
else:
raise RuntimeError('unsupported guard action')
print(json.dumps(result))
if __name__ == '__main__':
try:
main()
except Exception as exc:
if len(sys.argv) > 1 and sys.argv[1] in ('inspect', 'state', 'notebook-runs', 'runtime', 'mlflow-store', 'mlflow-heads'):
print('WN_INSPECT_DIAGNOSTIC=' + json.dumps(inspection_diagnostic(exc)), file=sys.stderr)
if len(sys.argv) > 1 and sys.argv[1] == 'recalculate':
diagnostic = inspection_diagnostic(exc)
stage = getattr(exc, 'recalculation_stage', 'unknown')
diagnostic['stage'] = stage if stage in ('environment', 'import', 'initialize', 'enqueue',
'execute', 'domain_result', 'pending') else 'unknown'
print('WN_RECALC_DIAGNOSTIC=' + json.dumps(diagnostic), file=sys.stderr)
if len(sys.argv) > 1 and sys.argv[1] == 'verify':
print('WN_VERIFY_DIAGNOSTIC=' + json.dumps(inspection_diagnostic(exc)), file=sys.stderr)
print('Persistent storage validation failed; inspect the phase and metadata privately.', file=sys.stderr)
raise SystemExit(1)
+283
View File
@@ -0,0 +1,283 @@
"""Load the simulated hospital into an installed DEV instance.
The simulated hospital is a MySQL server filled by `dev-data`. The instance's API reads it through its own import
API (`POST /imports/commit`), the same way a person connects a hospital; this installer only starts the `dev-data`
loader at the commit the instance was installed with and checks the outcome. It never writes to the hospital.
Like the install, the operation has a plan step (no changes) and a confirmed step. It refuses an instance that is
not a verified DEV installation of this installer, one that is not running, one that already has import attempts or
an earlier load, and a hospital address that is not `host:port`.
"""
import json
import re
import subprocess
import tempfile
import time
from pathlib import Path
import tarfile
import io
import composition
import installer
import proc
import resources
HOSPITAL_DEFAULT = '10.0.10.41:9505'
DEV_DATA_REMOTE = 'http://10.0.10.41:3000/edgar/dev-data.git'
APPLICATION_REMOTE = 'http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON.git'
# Credentials of the simulated hospital, which holds only generated data.
HOSPITAL_USER = HOSPITAL_PASSWORD = 'hospital'
PROJECTS = (('cacu', 'hospital_cacu'), ('cama', 'hospital_cama'), ('tea', 'hospital'))
LINE = re.compile(r'^(?P<target>\S+): (?P<total>\d+) le\S+, (?P<created>\d+) nuevas, (?P<updated>\d+) actualizadas, '
r'(?P<rejected>\d+) rechazadas', re.M)
# Runs inside the loader image, which has the pinned generator's tables and a MySQL driver. It reads the hospital
# (information_schema and row counts) and prints, per project, what the pinned generator expects and what is there.
HOSPITAL_SCRIPT = """import json, sys
import pymysql
from dev_data.proyectos import PROYECTOS
config = json.loads(sys.argv[1])
report = {}
for name, database in config['projects']:
try:
connection = pymysql.connect(host=config['host'], port=config['port'], user=config['user'],
password=config['password'], database=database, connect_timeout=10,
read_timeout=120)
except pymysql.MySQLError as error:
report[name] = {'database': database, 'error': type(error).__name__ + ': ' + str(error.args[-1])[:200]}
continue
with connection, connection.cursor() as cursor:
cursor.execute('select table_name, column_name from information_schema.columns where table_schema = %s',
(database,))
present = {}
for table, column in cursor.fetchall():
present.setdefault(table, set()).add(column)
tables = {}
for model in PROYECTOS[name].modelos.values():
table = model.__tablename__
entry = {'target': name + '.' + model.__name__, 'exists': table in present, 'rows': None,
'missing_columns': []}
if entry['exists']:
entry['missing_columns'] = sorted(c.name for c in model.__table__.columns if c.name not in present[table])
cursor.execute('select count(*) from `' + table + '`')
entry['rows'] = cursor.fetchone()[0]
tables[table] = entry
report[name] = {'database': database, 'tables': tables}
print(json.dumps(report))
"""
def validate_hospital(text):
"""`host:port` of the simulated hospital as the instance's API reaches it; never a URL or credentials."""
text = (text or '').strip()
match = re.fullmatch(r'([A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?):([0-9]{1,5})', text)
if not match or not 1 <= int(match.group(3)) <= 65535:
raise ValueError('hospital must be host:port, for example 10.0.10.41:9505')
return text
def fetch_tree(remote, commit, directory, paths=()):
"""Export `paths` (or everything) of one commit of `remote` into `directory`; the commit is fetched by SHA."""
if not composition.SHA.fullmatch(commit or ''):
raise RuntimeError('the installation record lacks a full commit for this repository')
with tempfile.TemporaryDirectory(prefix='isssteleon-fetch-') as tmp:
proc.run(['git', 'init', '--quiet', tmp])
proc.git(tmp, 'fetch', '--no-tags', remote, commit)
if proc.git(tmp, 'rev-parse', 'FETCH_HEAD^{commit}').strip() != commit:
raise RuntimeError(f'{remote} did not return {commit}')
archive = proc.git(tmp, 'archive', '--format=tar', commit, *paths, binary=True)
Path(directory).mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
tar.extractall(directory, filter='data')
def plan_load(host, base, port, hospital):
"""Check that the instance can take the load; nothing is created or started."""
record = host.call('lookup', '-', port)
if record is None:
raise RuntimeError(f'no installation is registered on port {port}')
project = record['project']
identity = host.call('identity', project, {'port': port})
if record['status'] != 'installed':
raise RuntimeError(f'the instance is {record["status"]}, not installed')
if record.get('synthetic_data'):
raise RuntimeError('the instance already has a simulated-hospital load (or a failed attempt); '
'reinstall it for a clean one')
pins = record.get('gitlinks') or {}
for name in ('dev-data', 'ISSSTELEON'):
if not composition.SHA.fullmatch(pins.get(name) or ''):
raise RuntimeError(f'the installation record does not pin {name}')
resources.verify_running(project, port, base, record['images'], bool(record.get('notebook_volume')))
attempts = json.loads(host.http_get(f'http://127.0.0.1:{port}/reportes/importaciones')['body']).get('intentos')
if attempts:
raise RuntimeError('the instance already has import attempts; the load needs an empty platform')
host.tcp_check(hospital)
return {'operation': 'load', 'port': port, 'project': project, 'hospital': hospital,
'dev_data': pins['dev-data'], 'application': pins['ISSSTELEON'], 'record_sha256': identity['record_sha256'],
'projects': [name for name, _ in PROJECTS]}
def build_loader(plan, workdir):
"""Build the loader image from the pinned `dev-data` and the pinned application's `Core`."""
context = Path(workdir) / 'context'
fetch_tree(DEV_DATA_REMOTE, plan['dev_data'], context / 'dev-data')
fetch_tree(APPLICATION_REMOTE, plan['application'], context / 'ISSSTELEON', ('Core',))
image = f'isssteleon-dev-data-load:{plan["project"]}-{plan["dev_data"][:12]}'
proc.run(['docker', 'build', '-q', '-t', image, '-f', context / 'dev-data' / 'Dockerfile', context])
return image
def run_loader(plan, image):
"""Load each project through the instance's published port and return the per-table counts."""
counts = {}
for name, database in PROJECTS:
hospital = f'mysql+pymysql://{HOSPITAL_USER}:{HOSPITAL_PASSWORD}@{plan["hospital"]}/{database}'
try:
out = proc.run(['docker', 'run', '--rm', '--network', 'host', image, 'cargar', name,
'--api', f'http://127.0.0.1:{plan["port"]}', '--hospital', hospital])
except subprocess.CalledProcessError as exc:
# The command line carries the hospital connection string, so only the loader's own words are kept.
raise RuntimeError(f'the loader failed for {name}: {(exc.stderr or exc.stdout or "")[-1500:].strip()}') from None
rows = [m.groupdict() for m in LINE.finditer(out)]
if not rows:
raise RuntimeError(f'the loader printed no table counts for {name}')
counts[name] = {r['target']: {k: int(v) for k, v in r.items() if k != 'target'} for r in rows}
return counts
def check_hospital(plan, image):
"""Read the hospital with the loader image and refuse it unless it has what the pinned generator expects.
Nothing is written anywhere. Returns the expected targets per project and the tables that hold no rows."""
host, _, port = plan['hospital'].rpartition(':')
config = json.dumps({'host': host, 'port': int(port), 'user': HOSPITAL_USER, 'password': HOSPITAL_PASSWORD,
'projects': PROJECTS})
try:
out = proc.run(['docker', 'run', '--rm', '--network', 'host', '--entrypoint', 'uv', image, 'run', '--frozen',
'--no-dev', 'python', '-c', HOSPITAL_SCRIPT, config])
except subprocess.CalledProcessError as exc:
raise RuntimeError(f'the hospital could not be read: {(exc.stderr or exc.stdout or "")[-1500:].strip()}') from None
try:
report = json.loads(out.strip().splitlines()[-1])
except (ValueError, IndexError):
raise RuntimeError('the hospital check printed no report') from None
problems, expected, empty = [], {}, []
for name, _ in PROJECTS:
entry = report.get(name) or {}
if 'error' in entry:
problems.append(f'{name}: {entry["database"]} cannot be read ({entry["error"]})')
continue
tables = entry.get('tables') or {}
expected[name] = [t['target'] for t in tables.values()]
for table, found in tables.items():
if not found['exists']:
problems.append(f'{name}: table {table} is missing from {entry["database"]}')
elif found['missing_columns']:
problems.append(f'{name}: {table} lacks the columns {", ".join(found["missing_columns"])}')
elif not found['rows']:
empty.append(found['target'])
if tables and all(t['exists'] and not t['rows'] for t in tables.values()):
problems.append(f'{name}: {entry["database"]} has no rows')
if problems:
raise RuntimeError('the hospital does not have the schema and data the pinned dev-data expects, '
'so nothing was loaded: ' + '; '.join(problems))
return {'expected': expected, 'empty_tables': empty}
def check_counts(counts, expected=None):
"""A load is complete only if every expected table was loaded, stored every row it read and rejected none."""
for name, tables in counts.items():
if sum(t['total'] for t in tables.values()) == 0:
raise RuntimeError(f'{name}: the hospital has no rows to load')
missing = sorted(set((expected or {}).get(name, [])) - set(tables))
if missing:
raise RuntimeError(f'{name}: the loader reported no counts for {", ".join(missing)}')
rejected = {target: t['rejected'] for target, t in tables.items() if t['rejected']}
if rejected:
raise RuntimeError(f'{name}: rows were rejected: {rejected}')
short = {target: t['total'] - t['created'] - t['updated'] for target, t in tables.items()
if t['created'] + t['updated'] != t['total']}
if short:
raise RuntimeError(f'{name}: rows were read but not stored: {short}')
def wait_for_recalculation(host, port, timeout=1800):
"""The worker recalculates after the imports; every domain must end `ok`, and an error stops the wait."""
deadline = time.monotonic() + timeout
status = {}
while time.monotonic() < deadline:
status = json.loads(host.http_get(f'http://127.0.0.1:{port}/reportes/indicadores')['body'])
states = {domain: entry.get('estado') for domain, entry in status.items()}
errors = {domain: entry.get('error') for domain, entry in status.items() if entry.get('estado') == 'error'}
if errors:
raise RuntimeError(f'indicator recalculation failed: {errors}')
if states and all(state == 'ok' and not status[d].get('pendiente') for d, state in states.items()):
return states
time.sleep(15)
raise RuntimeError(f'indicator recalculation did not finish: {status}')
def execute_load(host, base, plan, workdir):
"""Run the confirmed load. The hospital is checked before anything is written to the platform, so a hospital
that cannot be loaded leaves the instance clean; a failure after that leaves it marked, because the platform
may be half loaded."""
project, port = plan['project'], plan['port']
record = host.call('lookup', '-', port)
def mark(**data):
record['synthetic_data'] = dict(record.get('synthetic_data') or {}, hospital=plan['hospital'],
dev_data=plan['dev_data'], **data)
host.call('save', project, record)
try:
image = build_loader(plan, workdir)
preflight = check_hospital(plan, image)
except Exception as exc:
detail = installer.failure_detail(exc)[:900]
# Not a `synthetic_data` entry: nothing was written, so the load stays plannable. The changed record
# invalidates the confirmation that led here.
record['load_attempt'] = {'status': 'not_started', 'hospital': plan['hospital'], 'error': detail,
'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}
try:
host.call('save', project, record)
except Exception: # noqa: BLE001
pass
raise RuntimeError(f'the load did not start and the instance was not loaded, so it can be tried again ({detail})') from None
mark(status='loading', empty_tables=preflight['empty_tables'])
try:
counts = run_loader(plan, image)
mark(status='verifying', counts=counts)
check_counts(counts, preflight['expected'])
states = wait_for_recalculation(host, port)
mark(status='loaded', counts=counts, indicators=states, empty_tables=preflight['empty_tables'])
except Exception as exc:
detail = installer.failure_detail(exc)
mark(status='failed', error=detail)
raise RuntimeError(f'the load failed ({detail[:600]}); the instance may be partly loaded, '
'so reinstall it before trying again') from None
return record['synthetic_data']
def run_load(port_text, hospital_text, confirmation='', base=installer.BASE, host_factory=installer.Host):
"""Plan, or with the matching confirmation execute, the load of the simulated hospital."""
port = composition.validate_port(port_text)
hospital = validate_hospital(hospital_text or HOSPITAL_DEFAULT)
confirmation = (confirmation or '').strip()
if confirmation and not re.fullmatch(rf'cargar-{port}-[0-9a-f]{{16}}', confirmation):
raise ValueError(f'confirmacion must be cargar-{port}-<digest>, as printed by a run without it')
with host_factory(base, bool(confirmation)) as host, tempfile.TemporaryDirectory(prefix='isssteleon-load-') as tmp:
plan = plan_load(host, base, port, hospital)
expected = f'cargar-{port}-{installer.digest(plan)}'
print('Plan:', json.dumps(plan, indent=1, sort_keys=True))
if not confirmation:
print('Nothing was changed. To approve exactly this plan, run again with confirmacion=' + expected)
return None
if confirmation != expected:
raise RuntimeError(f'confirmacion does not match the current plan ({expected}); nothing was changed')
result = execute_load(host, base, plan, tmp)
for tables in result['counts'].values():
for target, t in tables.items():
print(f'{target}: {t["total"]} read, {t["created"]} new, {t["updated"]} updated, {t["rejected"]} rejected')
print(f'Loaded the simulated hospital into {plan["project"]}: {json.dumps(result["counts"], sort_keys=True)}')
return result
-702
View File
@@ -1,702 +0,0 @@
#!/usr/bin/env python3
"""Install isolated DEV instances from committed Git trees."""
import argparse
import io
import json
import os
import posixpath
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import time
import tempfile
import uuid
import conservative
ROOT = Path(__file__).resolve().parents[2]
BASE = Path('/srv/workingnarrative-dev')
# The image of the locked helper container; it only needs Python's standard library.
HELPER_IMAGE = 'python:3.12-slim'
BASE_SERVICES = ('webapi', 'webapp', 'indicadores')
NOTEBOOK_SERVICE = 'notebooks'
NOTEBOOK_VOLUME = 'trabajos_notebooks'
NOTEBOOK_JOBS = '/trabajos'
NOTEBOOK_USER = '10001:10001'
# Declared services that Compose leaves inactive unless their profile is enabled; never started here.
PROFILE_SERVICES = ('entrenar',)
def notebook_volume_name(project):
return f'{project}_{NOTEBOOK_VOLUME}'
def validate_port(port):
if not re.fullmatch(r'[0-9]{1,5}', port) or not 1024 <= int(port) <= 65535:
raise ValueError('port must be an integer from 1024 to 65535')
return int(port)
def automatic_instance(port):
return f'dev-{validate_port(port)}'
def validate(instance, port, operation):
if not re.fullmatch(r'[a-z][a-z0-9]*(?:-[a-z0-9]+)*', instance) or len(instance) > 40:
raise ValueError('instance must be 1-40 lowercase letters, digits or single hyphens, starting with a letter')
port = validate_port(port)
if operation != 'instalar':
raise ValueError('only instalar is supported; no changes were made')
return f'isssteleon-{instance}', port
def run(args, cwd=None, binary=False, stdin=None):
result = subprocess.run([str(a) for a in args], cwd=cwd, check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=not binary, env=clean_env(), input=stdin)
return result.stdout
def clean_env():
return {k: v for k, v in os.environ.items() if not k.startswith(('COMPOSE_', 'ISSSTELEON_'))}
def git(repo, *args, binary=False):
return run(['git', '-C', repo, *args], binary=binary)
def dispatch_metadata(root=ROOT):
"""Validate the event identity and its immutable checked-out commit."""
ref = os.environ.get('DISPATCH_REF', '')
name = os.environ.get('DISPATCH_REF_NAME', '')
sha = os.environ.get('DISPATCH_SHA', '')
if (os.environ.get('DISPATCH_REPOSITORY') != 'ISSSTELEON/WorkingNarrative'
or os.environ.get('DISPATCH_SERVER', '').rstrip('/') != 'http://10.0.10.41:3000'
or os.environ.get('DISPATCH_REF_TYPE') != 'branch'
or not name or ref != 'refs/heads/' + name
or not re.fullmatch(r'[0-9a-f]{40}', sha)):
raise ValueError('invalid deployment event identity or branch reference')
run(['git', 'check-ref-format', ref])
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('checkout does not match the dispatched SHA')
return {'workflow_ref': ref, 'workflow_sha': sha}
_target_request = None
def validate_branch(branch):
if (not branch or branch.startswith(('refs/', '-')) or branch == '@'
or re.fullmatch(r'[0-9a-fA-F]{40}', branch)):
raise ValueError('target must be a branch name')
run(['git', 'check-ref-format', 'refs/heads/' + branch])
return branch
def verify_target_revision(revision):
if _target_request is not None and revision != _target_request[1]:
raise RuntimeError('application checkout changed during deployment preparation')
def request_metadata(root=ROOT):
if _target_request is None:
return {}
branch, sha = _target_request
metadata = dispatch_metadata(ROOT)
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('application checkout does not match resolved branch commit')
return dict(metadata, branch=branch)
def deploy_branch(port, branch, workflow_root=ROOT, base=BASE):
"""Fetch one official branch and deploy its fixed commit using this installer."""
global _target_request
validate_port(port)
validate_branch(branch)
dispatch_metadata(workflow_root)
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if git(workflow_root, 'remote', 'get-url', 'origin').strip() not in (official, official.removesuffix('.git')):
raise RuntimeError('workflow checkout origin is not the official repository')
target_ref = 'refs/deploy/' + uuid.uuid4().hex
try:
git(workflow_root, 'fetch', '--no-tags', 'origin',
'+refs/heads/' + branch + ':' + target_ref)
sha = git(workflow_root, 'rev-parse', '--verify', target_ref + '^{commit}').strip()
if not re.fullmatch(r'[0-9a-f]{40}', sha):
raise RuntimeError('remote branch did not resolve to a full commit SHA')
with tempfile.TemporaryDirectory(prefix='isssteleon-source-') as tmp:
source = Path(tmp)
run(['git', 'init', '--quiet', source])
git(source, 'fetch', '--no-tags', str(workflow_root), target_ref)
git(source, 'checkout', '--quiet', '--detach', sha)
_target_request = (branch, sha)
request_metadata(source)
print('Deployment source:', json.dumps({'branch': branch, 'revision': sha}, sort_keys=True))
checkout_pinned(source)
install_auto(port, source, base)
finally:
_target_request = None
git(workflow_root, 'update-ref', '-d', target_ref)
SUBMODULE_ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
def checkout_pinned(root=ROOT):
"""Initialize only recognized institutional gitlinks at the captured revision."""
request_metadata(root)
def visit(repo, prefix, selected=None):
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, _, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if selected is not None and path != selected:
continue
full = f'{prefix}/{path}' if prefix else path
if full not in SUBMODULE_ORIGINS or path in ('', '.', '..') or '..' in Path(path).parts:
raise RuntimeError(f'unsupported application gitlink: {full}')
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = [line.split(None, 1)[0][len('submodule.'):-len('.path')]
for line in config.splitlines() if len(line.split(None, 1)) == 2
and line.split(None, 1)[1] == path]
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise RuntimeError(f'invalid submodule mapping: {full}')
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + SUBMODULE_ORIGINS[full] + '.git'
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url').strip() != origin:
raise RuntimeError(f'untrusted submodule origin: {full}')
git(repo, '-c', f'submodule.{name}.url={origin}', 'submodule', 'update', '--init', '--checkout', '--', path)
child = repo / path
if git(child, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError(f'gitlink checkout mismatch: {full}')
visit(child, full)
visit(root, '', 'ISSSTELEON')
print('Pinned application gitlinks:', json.dumps(pinned_manifest(root / 'ISSSTELEON',
git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]), sort_keys=True))
def committed_trees(repo, revision, prefix=''):
"""Walk exact recursive gitlinks and reject mismatching checked-out commits."""
actual = git(repo, 'rev-parse', 'HEAD').strip()
if actual != revision:
raise RuntimeError(f'{repo}: expected {revision}, found {actual}; initialize submodules recursively')
yield repo, revision, prefix
entries = git(repo, 'ls-tree', '-rz', '--full-tree', revision, binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, kind, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if Path(path).is_absolute() or '..' in Path(path).parts:
raise RuntimeError(f'unsafe gitlink path: {path}')
yield from committed_trees(repo / path, sha, f'{prefix}/{path}' if prefix else path)
def pinned_manifest(repo, revision):
return {prefix or 'ISSSTELEON': sha for _, sha, prefix in committed_trees(repo, revision)}
def export_tree(repo, revision, dest, manifest, prefix=''):
"""Export each committed tree and recursively follow its exact gitlinks."""
for child, sha, relative in committed_trees(repo, revision, prefix):
manifest[relative or 'ISSSTELEON'] = sha
target = dest / relative.removeprefix(prefix).lstrip('/')
target.mkdir(parents=True, exist_ok=True)
archive = git(child, 'archive', '--format=tar', sha, binary=True)
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
tar.extractall(target, filter='data')
def compose(project, deploy, *args):
return ['docker', 'compose', '--project-name', project, '--project-directory', str(deploy),
'--env-file', str(deploy / '.env'), '-f', str(deploy / 'docker-compose.yml'), *args]
def helper_exec(helper, script, *args, stdin=None):
return run(['docker', 'exec', *(['-i'] if stdin is not None else []),
helper, 'python3', '-c', script, *args], stdin=stdin)
def start_helper(base):
name = 'isssteleon-prepare-' + uuid.uuid4().hex
script = """import fcntl, time
with open('/host/.install.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
open('/tmp/locked', 'w').close()
while True: time.sleep(60)
"""
try:
run(['docker', 'run', '-d', '--network', 'host', '--name', name, '--mount',
f'type=bind,src={base},dst=/host', HELPER_IMAGE, 'python3', '-c', script])
deadline = time.monotonic() + 300
while time.monotonic() < deadline:
if helper_exec(name, "import os; print(int(os.path.exists('/tmp/locked')))").strip() == '1':
return name
time.sleep(2)
raise RuntimeError('timed out waiting for the shared installation lock')
except Exception as exc:
try:
run(['docker', 'rm', '-f', name])
except Exception:
pass
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) else str(exc)
raise RuntimeError(f'preparation failed; daemon host directory {base} must already exist: {detail}') from exc
def reserve(helper, project, port):
for kind, args in [('containers', ['docker', 'ps', '-aq']),
('networks', ['docker', 'network', 'ls', '-q']),
('volumes', ['docker', 'volume', 'ls', '-q'])]:
if run([*args, '--filter', f'label=com.docker.compose.project={project}']).strip():
raise RuntimeError(f'Compose project already owns {kind}: {project}')
# Compose silently adopts an existing volume with the expected name, whoever created it.
if notebook_volume_identity(project, missing_ok=True, verify=False) is not None:
raise RuntimeError(f'a volume named {notebook_volume_name(project)} already exists')
host_action(helper, 'reserve', project, str(port))
def notebook_volume_identity(project, *, missing_ok=False, verify=True):
"""The Compose-created local volume holding this installation's notebook jobs, or None if absent."""
name = notebook_volume_name(project)
if name not in run(['docker', 'volume', 'ls', '-q', '--filter', 'name=' + name]).split():
if missing_ok:
return None
raise RuntimeError('notebook jobs volume is missing')
items = json.loads(run(['docker', 'volume', 'inspect', name]))
if not verify:
return {'name': name}
if len(items) != 1:
raise RuntimeError('notebook jobs volume identity is not verifiable')
volume = items[0]
labels = volume.get('Labels') or {}
mountpoint = volume.get('Mountpoint')
if (volume.get('Name') != name or volume.get('Driver') != 'local' or volume.get('Scope') != 'local'
or volume.get('Options') or labels.get('com.docker.compose.project') != project
or labels.get('com.docker.compose.volume') != NOTEBOOK_VOLUME
or not isinstance(mountpoint, str) or not mountpoint.startswith('/')
or not isinstance(volume.get('CreatedAt'), str) or not volume['CreatedAt']):
raise RuntimeError('notebook jobs volume identity is not verifiable')
return {'name': name, 'created': volume['CreatedAt'], 'mountpoint': posixpath.normpath(mountpoint)}
def host_action(helper, action, *args):
"""Run a host action with its guard modules in the locked helper."""
script = Path(__file__).with_name('host.py').read_text(encoding='utf-8')
prefix = "import sys, types\n"
for name in ('data_guard', 'notebook_guard'):
source = Path(__file__).with_name(name + '.py').read_text(encoding='utf-8')
prefix += (f"module = types.ModuleType({name!r})\n"
f"sys.modules[{name!r}] = module\n"
f"exec({source!r}, module.__dict__)\n")
return helper_exec(helper, prefix + script, '/host', action, *args[:-1], '-', stdin=str(args[-1]))
def copy_to_host(helper, source, project, destination):
run(['docker', 'cp', str(source), f'{helper}:/host/{project}/{destination}'])
def configure(deploy, data, project, revision, port):
tag = f'{project}-{revision[:12]}-{uuid.uuid4().hex}'
env = (f'ISSSTELEON_VERSION={tag}\nISSSTELEON_DATOS={data}\nISSSTELEON_PUERTO={port}\n'
+ ''.join(f'{name}_DATABASE_URL=sqlite:////data/{name.lower()}.db\n'
for name in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')))
(deploy / '.env').write_text(env, encoding='utf-8')
return tag
def unsafe_service(service):
namespaces = [str(service.get(key, '')) for key in ('network_mode', 'pid', 'ipc', 'userns_mode', 'cgroup')]
unmanaged = {'privileged', 'devices', 'device_cgroup_rules', 'cap_add', 'volumes_from', 'use_api_socket',
'post_start', 'pre_stop', 'develop', 'secrets', 'configs', 'external_links'}
return (any(service.get(key) for key in unmanaged)
or any(value == 'host' or value.startswith(('container:', 'service:')) for value in namespaces))
def data_mount(volume, data):
return (volume.get('type') == 'bind' and volume.get('source') == str(data) and volume.get('target') == '/data'
and not volume.get('read_only'))
def jobs_mount(volume):
return (volume.get('type') == 'volume' and volume.get('source') == NOTEBOOK_VOLUME
and volume.get('target') == NOTEBOOK_JOBS and not volume.get('read_only')
and volume.get('volume') in (None, {}))
def verify_config(config, project, data, tag, port):
"""Check the effective composition; return its notebook jobs volume name, or None without notebooks."""
if config.get('name') != project:
raise RuntimeError('effective Compose project name does not match')
services = config.get('services', {})
notebooks = NOTEBOOK_SERVICE in services
required = set(BASE_SERVICES) | ({NOTEBOOK_SERVICE} if notebooks else set())
declared = {name for name in services if name in PROFILE_SERVICES and services[name].get('profiles') == [name]}
if set(services) - declared != required:
raise RuntimeError('unexpected Compose services')
volume = notebook_volume_name(project) if notebooks else None
if (config.get('volumes') or {}) != ({NOTEBOOK_VOLUME: {'name': volume}} if notebooks else {}):
raise RuntimeError('unexpected Compose volumes')
networks = config.get('networks') or {}
if networks:
default = networks.get('default') or {}
if (set(networks) != {'default'} or default.get('name') != project + '_default'
or set(default) - {'name', 'ipam'} or default.get('ipam')):
raise RuntimeError('unexpected Compose networks')
for name, service in services.items():
if unsafe_service(service):
raise RuntimeError(f'unsafe Compose service: {name}')
for name in ('webapi', 'indicadores', *sorted(declared)):
service = services[name]
if service.get('image') != f'isssteleon/webapi:{tag}':
raise RuntimeError(f'unexpected {name} image')
volumes = service.get('volumes', [])
expected = 2 if notebooks and name == 'webapi' else 1
if (len(volumes) != expected or sum(data_mount(v, data) for v in volumes) != 1
or sum(jobs_mount(v) for v in volumes) != expected - 1):
raise RuntimeError(f'unexpected {name} data mount')
if service.get('ports'):
raise RuntimeError(f'unexpected {name} published ports')
env = service.get('environment', {})
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
if env.get(f'{domain}_DATABASE_URL') != f'sqlite:////data/{domain.lower()}.db':
raise RuntimeError(f'unexpected {name} database configuration')
# Unset, the image's own values apply (MLflow, reports and indicators under /data); set, they must match.
if any(key in env and env[key] != value for key, value in conservative.PERSISTENT_ENV.items()):
raise RuntimeError(f'unexpected {name} storage configuration')
if notebooks:
env = services['webapi'].get('environment', {})
if env.get('NOTEBOOK_JOBS_DIR') != NOTEBOOK_JOBS or env.get('NOTEBOOK_RUNNER_UID') != NOTEBOOK_USER.split(':')[0]:
raise RuntimeError('unexpected webapi notebook configuration')
runner = services[NOTEBOOK_SERVICE]
env = runner.get('environment', {})
if (runner.get('image') != f'isssteleon/webapi:{tag}' or runner.get('command') != ['notebooks']
or runner.get('entrypoint') or runner.get('user') != NOTEBOOK_USER
or runner.get('network_mode') != 'none' or runner.get('read_only') is not True
or 'ALL' not in (runner.get('cap_drop') or [])
or 'no-new-privileges:true' not in (runner.get('security_opt') or [])
or runner.get('ports') or len(runner.get('volumes', [])) != 1
or not jobs_mount(runner['volumes'][0]) or env.get('NOTEBOOK_JOBS_DIR') != NOTEBOOK_JOBS
or any('/data' in str(value) for value in env.values())):
raise RuntimeError('unexpected notebooks isolation')
if services['webapp'].get('image') != f'isssteleon/webapp:{tag}':
raise RuntimeError('unexpected webapp image')
if services['webapp'].get('volumes'):
raise RuntimeError('unexpected webapp mounts')
ports = services['webapp'].get('ports', [])
if len(ports) != 1 or str(ports[0].get('published')) != str(port) or int(ports[0].get('target', 0)) != 80:
raise RuntimeError('unexpected webapp port')
return volume
def verify_services(cmd, port, timeout=300, *, notebooks=False):
deadline = time.monotonic() + timeout
last = 'services did not start'
while time.monotonic() < deadline:
try:
for service in BASE_SERVICES + ((NOTEBOOK_SERVICE,) if notebooks else ()):
ids = run([*cmd, 'ps', '-q', service]).splitlines()
if len(ids) != 1:
raise RuntimeError(f'{service}: expected one running container')
state = json.loads(run(['docker', 'inspect', '--format', '{{json .State}}', ids[0]]))
if state.get('Status') != 'running':
raise RuntimeError(f'{service}: {state.get("Status")}')
if service == 'webapi' and state.get('Health', {}).get('Status') != 'healthy':
raise RuntimeError(f'webapi health: {state.get("Health", {}).get("Status", "missing")}')
if service == 'webapp':
for path in ('/health', '/'):
run(['docker', 'exec', ids[0], 'wget', '-q', '-O', '/dev/null',
f'http://127.0.0.1{path}'])
return
except Exception as exc:
last = str(exc)
time.sleep(3)
raise RuntimeError(f'availability check failed: {last}')
def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
project, port = validate(instance, port_text, operation)
revision = git(root, 'rev-parse', 'HEAD').strip()
metadata = request_metadata(root)
verify_target_revision(revision)
expected = git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
owns_helper = helper is None
if owns_helper:
helper = start_helper(base)
try:
reserve(helper, project, port)
with tempfile.TemporaryDirectory(prefix='isssteleon-deploy-') as tmp:
directory = Path(tmp)
source, deploy, data = directory / 'codigo', directory / 'deploy', base / project / 'data'
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing',
**metadata}
def save():
host_action(helper, 'save', project, json.dumps(record))
cmd = None
try:
save()
manifest = {}
export_tree(root / 'ISSSTELEON', expected, source, manifest)
record['gitlinks'] = manifest
shutil.copytree(source / 'dist', deploy, symlinks=True)
tag = configure(deploy, data, project, revision, port)
record['images'] = [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}']
copy_to_host(helper, source, project, 'codigo')
copy_to_host(helper, deploy, project, 'deploy')
record['status'] = 'building'
save()
run(['docker', 'build', '-t', record['images'][0], '-f', source / 'WebApi/Dockerfile', source])
run(['docker', 'build', '-t', record['images'][1], source / 'WebApp'])
probe = "import sqlite3, os; p='/data/.permission-probe.db'; c=sqlite3.connect(p); c.execute('create table probe (x int)'); c.execute('insert into probe values (1)'); c.commit(); c.close(); os.remove(p)"
run(['docker', 'run', '--rm', '--mount', f'type=bind,src={data},dst=/data',
'--entrypoint', 'python3', record['images'][0], '-c', probe])
cmd = compose(project, deploy)
runtime = conservative.guard(sys.modules[__name__], record['images'][0], 'runtime', {})
config = conservative.controlled_config(
json.loads(run([*cmd, 'config', '--format', 'json'])), migrate_on_start=True,
worker=runtime['worker'])
volume = verify_config(config, project, data, tag, port)
if volume:
record['notebook_volume'] = volume
conservative.persist_config(deploy, config)
copy_to_host(helper, deploy / 'docker-compose.yml', project, 'deploy/docker-compose.yml')
record['status'] = 'starting'
record['phase'] = 'initial-migration-and-api'
save()
run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
api = sys.modules[__name__]
conservative.verify_api(api, cmd, data, record['images'][0], notebook_volume=volume)
check_jobs = None
if volume:
jobs = conservative.verify_new_notebook_volume(api, record['images'][0], project)
check_jobs = lambda: conservative.verify_notebook_jobs(api, record['images'][0], project,
jobs['identity'], jobs['digest'])
contract = conservative.guard(api, record['images'][0], 'contract', {})
before = conservative.guard(api, record['images'][0], 'state',
{'data': '/data', 'contract': contract}, data)
record['phase'] = 'recalculation-and-persistence'
save()
conservative.finish(api, cmd, record['images'][0], deploy, data, contract, before,
notebook_volume=volume, before_frontend=check_jobs)
verify_services(cmd, port, notebooks=bool(volume))
verify_existing_containers(record, base, helper)
record['status'] = 'installed'
record['result'] = 'installed'
record['phase'] = 'complete'
record['recalculation'] = 'complete'
save()
print(f'Installed {project} on port {port} at {revision}')
except Exception as exc:
record['status'] = 'failed'
record['error'] = str(exc)
if isinstance(exc, subprocess.CalledProcessError):
record['error'] += f'\ncommand: {exc.cmd}\nstdout: {exc.stdout}\nstderr: {exc.stderr}'
save()
if cmd:
try:
diagnostics = run([*cmd, 'ps', '-a']) + '\n' + run([*cmd, 'logs', '--no-color', '--tail', '100'])
except Exception as diagnostic_error:
diagnostics = str(diagnostic_error)
path = directory / 'diagnostics.txt'
path.write_text(diagnostics, encoding='utf-8')
copy_to_host(helper, path, project, 'diagnostics.txt')
raise
finally:
if owns_helper:
run(['docker', 'rm', '-f', helper])
def record_volume(record):
"""The notebook jobs volume an installation record declares; a record without one predates notebooks."""
volume = record.get('notebook_volume')
if volume is not None and volume != notebook_volume_name(record['project']):
raise RuntimeError('installation record names an unexpected notebook jobs volume')
return volume
def verify_existing_containers(record, base, helper):
"""Reject unexpected containers, image identities, mounts, volume owners and port owners.
Returns the container IDs as indicadores, webapi, webapp and, with notebooks, the runner."""
project, port = record['project'], record['port']
images = record.get('images')
if not isinstance(images, list) or len(images) != 2 or not all(isinstance(x, str) for x in images):
raise RuntimeError('installation image record is missing')
volume = record_volume(record)
jobs = notebook_volume_identity(project) if volume else None
expected_services = BASE_SERVICES + ((NOTEBOOK_SERVICE,) if volume else ())
image_ids = [run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip() for image in images]
if not all(image_ids):
raise RuntimeError('recorded image not found')
ids = run(['docker', 'ps', '-aq', '--no-trunc']).splitlines()
containers = json.loads(run(['docker', 'inspect', *ids])) if ids else []
found = {}
root = posixpath.normpath(str(base / project))
data = posixpath.join(root, 'data')
data_bind = {'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}
for item in containers:
name = item.get('Name', '').lstrip('/')
if name == helper:
continue
labels = item.get('Config', {}).get('Labels') or {}
own = labels.get('com.docker.compose.project') == project
mounts = item.get('Mounts') or []
for mount in mounts:
source = mount.get('Source', '')
if not source.startswith('/'):
raise RuntimeError(f'unknown container mount: {name}')
source = posixpath.normpath(source)
overlap = source == root or source.startswith(root + '/') or root.startswith(source.rstrip('/') + '/')
if overlap and not own:
raise RuntimeError(f'foreign container can access installation: {name}')
if not own and (mount.get('Name') == notebook_volume_name(project) or (jobs and (
source == jobs['mountpoint'] or source.startswith(jobs['mountpoint'] + '/')
or jobs['mountpoint'].startswith(source.rstrip('/') + '/')))):
raise RuntimeError(f'foreign container can access notebook jobs: {name}')
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
if not own and any(str(b.get('HostPort')) == str(port) for values in bindings.values() for b in (values or [])):
raise RuntimeError(f'foreign container reserves port {port}: {name}')
if not own:
continue
service = labels.get('com.docker.compose.service')
if labels.get('com.docker.compose.oneoff') == 'True' or service in PROFILE_SERVICES:
raise RuntimeError(f'one-shot {service} container is present; remove it once it has finished')
if service not in expected_services or service in found:
raise RuntimeError('unexpected container in Compose project')
if item.get('State', {}).get('Status') != 'running':
raise RuntimeError(f'{service} is not running')
expected = image_ids[1 if service == 'webapp' else 0]
if item.get('Image') != expected:
raise RuntimeError(f'{service} image does not match installation record')
jobs_volume = {'Type': 'volume', 'Name': volume, 'Destination': NOTEBOOK_JOBS, 'RW': True}
shapes = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
'Destination', 'RW')} for mount in mounts]
if service in ('webapi', 'indicadores'):
wanted = [data_bind] + ([jobs_volume] if volume and service == 'webapi' else [])
if len(shapes) != len(wanted) or any(mount not in shapes for mount in wanted):
raise RuntimeError(f'{service} data mount does not match')
if bindings:
raise RuntimeError(f'{service} publishes an unexpected port')
elif service == NOTEBOOK_SERVICE:
host = item.get('HostConfig', {})
if shapes != [jobs_volume] or bindings:
raise RuntimeError('notebooks mount does not match')
if (host.get('NetworkMode') != 'none' or host.get('ReadonlyRootfs') is not True or host.get('Privileged')
or 'ALL' not in (host.get('CapDrop') or []) or host.get('CapAdd')
or 'no-new-privileges:true' not in (host.get('SecurityOpt') or [])
or item.get('Config', {}).get('User') != NOTEBOOK_USER):
raise RuntimeError('notebooks isolation does not match')
else:
published = bindings.get('80/tcp') or []
if (mounts or set(bindings) != {'80/tcp'} or not published
or any(str(binding.get('HostPort')) != str(port) for binding in published)):
raise RuntimeError('webapp port does not match')
found[service] = item['Id']
if set(found) != set(expected_services):
raise RuntimeError('missing Compose project containers')
own_networks = {network.get('NetworkID')
for item in containers if item.get('Id') in found.values()
for name, network in (item.get('NetworkSettings', {}).get('Networks') or {}).items()
if name != 'none' and network.get('NetworkID')}
for item in containers:
if item.get('Id') in found.values() or item.get('Name', '').lstrip('/') == helper:
continue
networks = item.get('NetworkSettings', {}).get('Networks') or {}
if any(network.get('NetworkID') in own_networks for network in networks.values()):
raise RuntimeError('foreign container shares the installation network')
return [found[name] for name in ('indicadores', 'webapi', 'webapp', NOTEBOOK_SERVICE) if name in found]
def update(record, helper, root=ROOT, base=BASE, *, verify_restore=False):
return conservative.update(sys.modules[__name__], record, helper, root, base,
verify_restore=verify_restore)
def install_free_port(port, root, base, helper):
"""Install a new instance on a port no record or container holds, under the caller's helper lock."""
normalized = validate_port(port)
ids = run(['docker', 'ps', '-aq', '--no-trunc']).splitlines()
for item in json.loads(run(['docker', 'inspect', *ids])) if ids else []:
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
if any(str(b.get('HostPort')) == str(normalized) for values in bindings.values() for b in (values or [])):
raise RuntimeError(f'port {normalized} is reserved by another container')
host_action(helper, 'check-port', '-', str(normalized))
install(automatic_instance(port), port, 'instalar', root, base, helper=helper)
def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
"""Route under the shared lock after checking any caller-specific record precondition."""
normalized = validate_port(port)
helper = start_helper(base)
try:
record = json.loads(host_action(helper, 'lookup', '-', str(normalized)))
if check_record is not None:
check_record(record)
if record is None:
install_free_port(port, root, base, helper)
else:
update(record, helper, root, base)
finally:
run(['docker', 'rm', '-f', helper])
def main():
parser = argparse.ArgumentParser()
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto', 'validate-dispatch', 'deploy-branch'])
parser.add_argument('arguments', nargs='*')
args = parser.parse_args()
try:
if args.command == 'validate-dispatch':
if args.arguments:
raise ValueError('validate-dispatch takes no arguments')
print('Workflow event:', json.dumps(dispatch_metadata(), sort_keys=True))
elif args.command == 'deploy-branch':
if len(args.arguments) != 2:
raise ValueError('deploy-branch requires port and branch')
deploy_branch(*args.arguments)
elif args.command in ('validate-auto', 'install-auto'):
if len(args.arguments) != 1:
raise ValueError('automatic commands require exactly one port')
port_text = args.arguments[0]
instance = automatic_instance(port_text)
if args.command == 'validate-auto':
project, port = validate(instance, port_text, 'instalar')
print(f'Validated request: project={project}, port={port}')
else:
install_auto(port_text)
else:
if len(args.arguments) != 3:
raise ValueError('commands require instance, port and operation')
if args.command == 'validate':
project, port = validate(*args.arguments)
print(f'Validated request: project={project}, port={port}')
else:
install(*args.arguments)
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as exc:
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
print(f'Deployment failed: {detail}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env python3
"""Run candidate storage compatibility checks without changing the installation."""
import argparse
from pathlib import Path
import sys
import conservative
import dev
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--image', required=True, help='exact candidate WebApi image tag or ID')
parser.add_argument('--data', required=True, type=Path, help='absolute daemon-host data directory')
args = parser.parse_args()
if not args.data.is_absolute():
parser.error('--data must be an absolute daemon-host path')
try:
contract = conservative.guard(dev, args.image, 'contract', {})
conservative.guard(dev, args.image, 'inspect', {'data': '/data', 'contract': contract}, args.data)
except conservative.GuardFailure as exc:
print(str(exc), file=sys.stderr)
return 1
print('Candidate storage inspection passed.')
return 0
if __name__ == '__main__':
raise SystemExit(main())
+277
View File
@@ -0,0 +1,277 @@
"""A small in-memory Docker daemon and installation host for installer tests.
`FakeDocker.run` replaces `proc.run`: it answers the Docker and Compose commands the installer issues, keeps
containers, volumes, networks and images in dictionaries and records every command in `calls`. `LocalHost`
replaces the helper container: it runs the registry actions on a temporary directory.
"""
import json
from pathlib import Path
import shutil
import subprocess
import registry
def failure(args, message='simulated failure'):
return subprocess.CalledProcessError(1, args, output='', stderr=message)
def compose_config(project, env, notebooks=True):
"""The effective configuration `docker compose config` prints for the pinned composition."""
tag, data, port = env['ISSSTELEON_VERSION'], env['ISSSTELEON_DATOS'], env['ISSSTELEON_PUERTO']
urls = {key: value for key, value in env.items() if key.endswith('_DATABASE_URL')}
bind = {'type': 'bind', 'source': data, 'target': '/data'}
jobs = {'type': 'volume', 'source': 'trabajos_notebooks', 'target': '/trabajos'}
api = f'isssteleon/webapi:{tag}'
services = {
'webapi': {'image': api, 'environment': {**urls, 'NOTEBOOK_JOBS_DIR': '/trabajos',
'NOTEBOOK_RUNNER_UID': '10001'},
'volumes': [bind] + ([jobs] if notebooks else [])},
'indicadores': {'image': api, 'command': ['indicadores'], 'environment': dict(urls), 'volumes': [bind]},
'entrenar': {'image': api, 'command': ['entrenar'], 'profiles': ['entrenar'], 'environment': dict(urls),
'volumes': [bind]},
'webapp': {'image': f'isssteleon/webapp:{tag}', 'ports': [{'published': port, 'target': 80}]},
}
if notebooks:
services['notebooks'] = {
'image': api, 'command': ['notebooks'], 'user': '10001:10001', 'network_mode': 'none',
'read_only': True, 'cap_drop': ['ALL'], 'security_opt': ['no-new-privileges:true'],
'environment': {'NOTEBOOK_JOBS_DIR': '/trabajos'}, 'volumes': [jobs]}
config = {'name': project, 'services': services, 'networks': {'default': {'name': project + '_default'}}}
if notebooks:
config['volumes'] = {'trabajos_notebooks': {'name': f'{project}_trabajos_notebooks'}}
return config
class FakeDocker:
def __init__(self, base, notebooks=True):
self.base, self.notebooks = base, notebooks
self.containers, self.volumes, self.networks, self.images = {}, {}, {}, {}
self.calls, self.hooks, self.counter = [], [], 0
self.loader_output = lambda args: ''
self.hospital_report = lambda args: ''
def new_id(self):
self.counter += 1
return f'{self.counter:064x}'
def mutating(self):
"""Commands that change the daemon or the host, in order; listing and inspecting are not among them."""
def changes(call):
return (call[1] in ('build', 'run', 'update', 'stop', 'rm', 'cp', 'create', 'kill', 'system', 'prune')
or call[1:3] in (['volume', 'rm'], ['volume', 'create'], ['volume', 'prune'],
['network', 'rm'], ['network', 'create'], ['network', 'prune'])
or (call[1] == 'compose' and ('up' in call or 'down' in call)))
return [call for call in self.calls if changes(call)]
# -- seeding helpers -------------------------------------------------------------------------------
def add_foreign(self, name, mounts=(), networks=('bridge',), ports=(), labels=None, image='foreign'):
ident = self.new_id()
self.containers[ident] = {
'Id': ident, 'Name': '/' + name, 'Image': image, 'State': {'Status': 'running'},
'Config': {'Labels': labels or {}}, 'Mounts': list(mounts),
'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': str(p)}] for p in ports}},
'NetworkSettings': {'Networks': {n: {'NetworkID': n} for n in networks}}}
return ident
def add_volume(self, name, labels=None):
self.volumes[name] = {'Name': name, 'Driver': 'local', 'Scope': 'local', 'Options': None,
'Labels': labels or {}, 'CreatedAt': '2026-11-19T00:00:00Z',
'Mountpoint': f'/var/lib/docker/volumes/{name}/_data'}
def add_network(self, name, labels=None):
ident = self.new_id()
self.networks[ident] = {'Id': ident, 'Name': name, 'Driver': 'bridge', 'Labels': labels or {}}
return ident
# -- the command interpreter -----------------------------------------------------------------------
def run(self, args, cwd=None, binary=False, stdin=None):
args = [str(a) for a in args]
self.calls.append(args)
for hook in self.hooks:
hook(self, args)
if args[0] == 'git':
raise AssertionError('tests must not run git through the fake daemon')
verb = args[1]
if verb == 'compose':
return self.compose(args)
method = getattr(self, 'do_' + verb.replace('-', '_'), None)
if method is None:
raise failure(args, f'unsupported docker command: {verb}')
return method(args)
def do_ps(self, args):
return '\n'.join(self.containers) + ('\n' if self.containers else '')
def do_inspect(self, args):
if args[2] == '--format':
return json.dumps(self.containers[args[4]]['State'])
return json.dumps([self.containers[i] for i in args[2:]])
def do_image(self, args):
tag = args[-1]
if tag not in self.images:
raise failure(args, 'no such image')
return self.images[tag] + '\n'
def do_build(self, args):
self.images[args[args.index('-t') + 1]] = 'sha256:' + self.new_id()
return ''
def do_run(self, args):
if 'cargar' in args:
return self.loader_output(args)
if '--entrypoint' in args and '-c' in args:
return self.hospital_report(args)
return ''
def do_update(self, args):
return ''
def do_stop(self, args):
self.containers[args[2]]['State'] = {'Status': 'exited'}
return ''
def do_rm(self, args):
self.containers.pop(args[2])
return ''
def do_volume(self, args):
if args[2] == 'ls':
names = list(self.volumes)
for i, a in enumerate(args):
if a == '--filter':
key, _, value = args[i + 1].partition('=')
if key == 'name':
names = [n for n in names if value in n]
elif key == 'label':
label, _, expected = value.partition('=')
names = [n for n in names if self.volumes[n]['Labels'].get(label) == expected]
return '\n'.join(names) + ('\n' if names else '')
if args[2] == 'inspect':
return json.dumps([self.volumes[args[3]]])
if args[2] == 'rm':
name = args[3]
if any(m.get('Name') == name for c in self.containers.values() for m in c['Mounts']):
raise failure(args, 'volume is in use')
self.volumes.pop(name)
return ''
raise failure(args, 'unsupported volume command')
def do_network(self, args):
if args[2] == 'ls':
if '--format' in args:
return '\n'.join(f'{i} {n["Name"]}' for i, n in self.networks.items()) + '\n'
found = list(self.networks)
if '--filter' in args:
key, _, value = args[args.index('--filter') + 1].partition('=')
label, _, expected = value.partition('=')
found = [i for i in found if self.networks[i]['Labels'].get(label) == expected]
return '\n'.join(found) + ('\n' if found else '')
if args[2] == 'inspect':
item = dict(self.networks[args[3]])
item['Containers'] = {c['Id']: {} for c in self.containers.values()
if args[3] in (c['NetworkSettings']['Networks'].get(item['Name'], {}).get('NetworkID'),)}
return json.dumps([item])
if args[2] == 'rm':
self.networks.pop(args[3])
return ''
raise failure(args, 'unsupported network command')
def do_cp(self, args):
return ''
# -- Compose ---------------------------------------------------------------------------------------
def compose(self, args):
deploy = Path(args[args.index('--project-directory') + 1])
project = args[args.index('--project-name') + 1]
action = next(a for a in args[args.index('-f') + 2:] if not a.startswith('-'))
if action == 'config':
env = dict(line.split('=', 1) for line in (deploy / '.env').read_text().splitlines() if line)
return json.dumps(compose_config(project, env, self.notebooks))
config = json.loads((deploy / 'docker-compose.yml').read_text().replace('$$', '$'))
if action == 'up':
self.up(project, config)
return ''
if action == 'ps':
if '-q' in args:
service = args[-1]
return '\n'.join(i for i, c in self.containers.items()
if c['Config']['Labels'].get('com.docker.compose.project') == project
and c['Config']['Labels'].get('com.docker.compose.service') == service) + '\n'
return 'ps output'
if action == 'logs':
return 'log output'
raise failure(args, f'unsupported compose command: {action}')
def up(self, project, config):
network = project + '_default'
if network not in [n['Name'] for n in self.networks.values()]:
self.add_network(network, {'com.docker.compose.project': project,
'com.docker.compose.network': 'default'})
volume = f'{project}_trabajos_notebooks'
if 'volumes' in config and volume not in self.volumes:
self.add_volume(volume, {'com.docker.compose.project': project,
'com.docker.compose.volume': 'trabajos_notebooks'})
net_id = next(i for i, n in self.networks.items() if n['Name'] == network)
for service, spec in config['services'].items():
if 'profiles' in spec:
continue
mounts = [{'Type': 'bind', 'Source': m['source'], 'Destination': m['target'], 'RW': True}
if m['type'] == 'bind' else
{'Type': 'volume', 'Name': volume, 'Destination': m['target'], 'RW': True}
for m in spec.get('volumes', [])]
ident = self.new_id()
published = {f'{p["target"]}/tcp': [{'HostPort': str(p['published'])}] for p in spec.get('ports', [])}
health = {'Health': {'Status': 'healthy'}} if service == 'webapi' else {}
nets = {'none': {}} if spec.get('network_mode') == 'none' else {network: {'NetworkID': net_id}}
self.containers[ident] = {
'Id': ident, 'Name': f'/{project}-{service}-1', 'Image': self.images[spec['image']],
'State': {'Status': 'running', **health},
'Config': {'Labels': {'com.docker.compose.project': project,
'com.docker.compose.service': service}, 'User': spec.get('user', '')},
'Mounts': mounts, 'HostConfig': {'PortBindings': published},
'NetworkSettings': {'Networks': nets}}
class LocalHost:
"""The daemon-host helper, running the registry actions on a temporary directory."""
def __init__(self, directory, responses=None):
self.directory, self.entered = Path(directory), []
self.name = 'local-helper'
self.responses = responses or {}
self.calls = []
self.unreachable = set()
def __call__(self, base, lock):
self.entered.append(lock)
return self
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def call(self, action, project, payload):
self.calls.append((action, project))
return json.loads(json.dumps(registry.dispatch(self.directory, action, project, json.dumps(payload))))
def copy(self, source, project):
shutil.copytree(source, self.directory / project / 'deploy')
def tcp_check(self, address):
if address in self.unreachable:
raise RuntimeError(f'{address} does not accept connections')
def http_get(self, url):
path = '/' + url.split('/', 3)[3] if url.count('/') >= 3 else '/'
if path in self.responses:
return self.responses[path]
return {'/reportes/importaciones': {'status': 200, 'body': '{"resumen": {}, "intentos": []}'},
'/reportes/indicadores': {'status': 200, 'body': json.dumps(
{d: {'estado': 'ok', 'pendiente': False} for d in ('cacu', 'cama', 'tea')})},
'/health': {'status': 200, 'body': '{"status": "ok"}'},
'/api': {'status': 200, 'body': '{"routes": [{"path": "/health"}]}'},
'/': {'status': 200, 'body': '<html><body>app</body></html>'}}[path]
+84
View File
@@ -0,0 +1,84 @@
"""Local Git repositories shaped like the official ones, for tests of reference resolution.
`build(root)` creates the remotes below `root/remotes`: the EEG library `alberto/tea`, WebApi, WebApp and models
(pinning the library at `libs/tea`), ISSSTELEON pinning them, and an outer repository pinning ISSSTELEON plus a
`dev-data` gitlink. Submodule URLs are the real ones; `environment(root)` redirects them to the local copies for every
Git command run with it.
"""
import os
from pathlib import Path
import subprocess
ORIGIN = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
TEA_ORIGIN = 'ssh://git@10.0.10.41:2222/alberto/tea.git'
IDENTITY = {'GIT_AUTHOR_NAME': 'test', 'GIT_AUTHOR_EMAIL': 'test@example.invalid',
'GIT_COMMITTER_NAME': 'test', 'GIT_COMMITTER_EMAIL': 'test@example.invalid'}
def environment(root):
remotes = (Path(root) / 'remotes').as_posix()
return {**IDENTITY, 'GIT_CONFIG_COUNT': '3',
'GIT_CONFIG_KEY_0': f'url.file:///{remotes}/.insteadOf', 'GIT_CONFIG_VALUE_0': ORIGIN,
'GIT_CONFIG_KEY_1': 'protocol.file.allow', 'GIT_CONFIG_VALUE_1': 'always',
'GIT_CONFIG_KEY_2': f'url.file:///{remotes}/alberto/tea.git.insteadOf', 'GIT_CONFIG_VALUE_2': TEA_ORIGIN}
def git(repo, *args, env=None):
result = subprocess.run(['git', '-C', str(repo), *args], check=True, capture_output=True, text=True,
env={**os.environ, **(env or {})})
return result.stdout.strip()
def commit(repo, name, text, env):
path = Path(repo) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding='utf-8')
git(repo, 'add', '-A', env=env)
git(repo, 'commit', '-q', '-m', f'change {name}', env=env)
return git(repo, 'rev-parse', 'HEAD', env=env)
def init(path, env):
Path(path).mkdir(parents=True)
git(path, 'init', '-q', '-b', 'dev', env=env)
git(path, 'config', 'commit.gpgsign', 'false', env=env)
def build(root):
"""Create the remotes; returns their paths and the commit each one is at."""
env = environment(root)
remotes = Path(root) / 'remotes'
result = {'env': env, 'remotes': remotes}
init(remotes / 'alberto' / 'tea.git', env)
result['tea'] = commit(remotes / 'alberto' / 'tea.git', 'pyproject.toml', '[project]\nname = "tea"\n', env)
for name in ('WebApi', 'WebApp', 'models'):
init(remotes / f'{name}.git', env)
result[name] = commit(remotes / f'{name}.git', 'Dockerfile', f'FROM scratch # {name}\n', env)
models = remotes / 'models.git'
git(models, 'submodule', 'add', '-q', '--name', 'tea', TEA_ORIGIN, 'libs/tea', env=env)
git(models, 'commit', '-q', '-m', 'pin the EEG library', env=env)
result['models'] = git(models, 'rev-parse', 'HEAD', env=env)
application = remotes / 'ISSSTELEON.git'
init(application, env)
commit(application, 'dist/docker-compose.yml', 'name: isssteleon\n', env)
for name in ('WebApi', 'WebApp', 'models'):
git(application, 'submodule', 'add', '-q', f'{ORIGIN}{name}.git', name, env=env)
git(application, 'commit', '-q', '-m', 'pin applications', env=env)
result['ISSSTELEON'] = git(application, 'rev-parse', 'HEAD', env=env)
outer = remotes / 'WorkingNarrative.git'
init(outer, env)
git(outer, 'submodule', 'add', '-q', f'{ORIGIN}ISSSTELEON.git', 'ISSSTELEON', env=env)
result['dev-data'] = 'd' * 40
git(outer, 'update-index', '--add', '--cacheinfo', f'160000,{result["dev-data"]},dev-data', env=env)
git(outer, 'commit', '-q', '-m', 'pin ISSSTELEON', env=env)
result['outer'] = git(outer, 'rev-parse', 'HEAD', env=env)
result['url'] = outer.as_posix()
return result
def advance(fixture, branch='dev'):
"""Add a commit to the outer repository's branch and return its SHA."""
outer = fixture['remotes'] / 'WorkingNarrative.git'
git(outer, 'checkout', '-q', branch, env=fixture['env'])
return commit(outer, 'notes.txt', os.urandom(8).hex(), fixture['env'])
-350
View File
@@ -1,350 +0,0 @@
"""Reserve projects and atomically persist records under the installer lock."""
import json
import hashlib
import errno
import os
from pathlib import Path
import re
import shutil
import socket
import sys
import tempfile
import data_guard
import notebook_guard
def write_record(directory, record):
fd, name = tempfile.mkstemp(prefix='.installation-', dir=directory)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
json.dump(record, stream, indent=2)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(name, directory / 'installation.json')
if os.name != 'nt':
directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
finally:
if os.path.exists(name):
os.unlink(name)
def read_record(directory):
if (directory / 'installation.json').is_symlink():
raise RuntimeError(f'symlinked installation record: {directory}')
record = json.loads((directory / 'installation.json').read_text(encoding='utf-8'))
if (not isinstance(record, dict) or record.get('project') != directory.name
or type(record.get('port')) is not int or not 1024 <= record['port'] <= 65535
or record.get('status') not in ('preparing', 'building', 'starting', 'installed', 'failed',
'updating', 'update_failed', 'replacing', 'replace_failed')):
raise RuntimeError(f'invalid installation record: {directory}')
return record
def reconcile_record(base, project, payload, *, apply=False):
"""Check pre-activation state and optionally change only its status."""
directory = base / project
if directory.is_symlink() or not directory.is_dir():
raise RuntimeError('invalid installation directory')
record = read_record(directory)
operation = payload['operation_id']
if (not re.fullmatch(r'[0-9a-f]{32}', operation)
or record.get('operation_id') != operation or record.get('status') != 'update_failed'
or record.get('phase') not in ('quiescing', 'backup', 'restore-verification')):
raise RuntimeError('record is not the expected pre-activation failure')
if record['port'] != payload['port'] or record.get('revision') != payload['revision']:
raise RuntimeError('recorded port or original revision differs')
for entry in base.iterdir():
if entry.name == project:
continue
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
if entry.is_symlink() or not entry.is_dir():
raise RuntimeError('invalid installation directory in registry')
if read_record(entry)['port'] == record['port']:
raise RuntimeError('port is reserved by another installation')
if not re.fullmatch(r'[0-9a-f]{40}', record['revision']):
raise RuntimeError('invalid original revision')
if not isinstance(record.get('gitlinks'), dict) or not record['gitlinks']:
raise RuntimeError('original gitlinks are missing')
for name in ('codigo', 'deploy', 'data'):
path = directory / name
if path.is_symlink() or not path.is_dir() or path.stat().st_dev != directory.stat().st_dev:
raise RuntimeError('invalid original installation path: ' + name)
for name in ('.archive', '.updates'):
parent = directory / name
if parent.is_symlink() or (parent.exists() and not parent.is_dir()):
raise RuntimeError('invalid activation directory: ' + name)
if (parent / operation).exists() or (parent / operation).is_symlink():
raise RuntimeError('operation has activation or staging artifacts')
path = directory / 'installation.json'
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if apply:
if payload.get('record_sha256') != digest:
raise RuntimeError('record changed during reconciliation')
write_record(directory, dict(record, status='installed'))
return {'record': record, 'record_sha256': digest}
def archive_installation(base, project, operation, previous):
"""Archive application payloads while retaining the original data directory."""
if not re.fullmatch(r'[0-9a-f]{32}', operation):
raise ValueError('invalid operation id')
directory = base / project
record = read_record(directory)
if record['status'] != 'updating' or record.get('operation_id') != operation:
raise RuntimeError('update is not reserved')
archive_root = directory / '.archive'
if archive_root.is_symlink() or (archive_root.exists() and not archive_root.is_dir()):
raise RuntimeError('invalid archive directory')
for name in ('codigo', 'deploy', 'data'):
path = directory / name
if path.is_symlink() or not path.is_dir() or path.stat().st_dev != directory.stat().st_dev:
raise RuntimeError(f'invalid installation path: {path}')
archive_root.mkdir(mode=0o700, exist_ok=True)
if archive_root.stat().st_dev != directory.stat().st_dev:
raise RuntimeError('archive must be on the installation filesystem')
target = archive_root / operation
target.mkdir(mode=0o700)
write_record(target, previous)
for name in ('codigo', 'deploy'):
os.rename(directory / name, target / name)
return target
def operation_directory(base, project, operation):
if not re.fullmatch(r'[0-9a-f]{32}', operation):
raise ValueError('invalid operation id')
directory = base / project
record = read_record(directory)
if record['status'] != 'updating' or record.get('operation_id') != operation:
raise RuntimeError('update is not reserved')
data_guard.regular_tree(directory / 'data')
return directory
def private_directory(path):
if path.is_symlink() or (path.exists() and not path.is_dir()):
raise RuntimeError('invalid private directory')
path.mkdir(mode=0o700, exist_ok=True)
return path
def prepare_backup(base, project, verify_restore):
"""Check destination creation and helper write access before quiescing."""
for name in (('.backups', '.restores') if verify_restore else ('.backups',)):
directory = private_directory(private_directory(base / name) / project)
fd, probe = tempfile.mkstemp(prefix='.write-check-', dir=directory)
try:
os.close(fd)
finally:
os.unlink(probe)
def backup_installation(base, project, payload):
"""Back up quiesced storage outside the application instance."""
operation = payload['operation_id']
directory = operation_directory(base, project, operation)
backups = private_directory(base / '.backups')
project_backups = private_directory(backups / project)
destination = project_backups / operation
manifest = data_guard.create_backup(directory / 'data', destination, payload['contract'], payload['origin'])
return {'path': str(destination), 'state': manifest['state']}
def notebook_backup_directory(base, project, operation):
"""Create the empty notebook jobs destination inside an existing operation backup."""
operation_directory(base, project, operation)
parent = base / '.backups' / project / operation
if parent.is_symlink() or not parent.is_dir() or not (parent / 'manifest.json').is_file():
raise RuntimeError('operation data backup is missing')
target = parent / 'notebooks'
target.mkdir(mode=0o700)
return target
def verify_notebook_backup(base, project, operation):
operation_directory(base, project, operation)
return notebook_guard.verify_backup(base / '.backups' / project / operation / 'notebooks')
def verify_isolated_restore(base, project, operation):
"""Restore the operation backup, with its notebook jobs if it has them, to new private locations."""
operation_directory(base, project, operation)
source = base / '.backups' / project / operation
restores = private_directory(base / '.restores')
project_restores = private_directory(restores / project)
destination = project_restores / operation
data_guard.restore_backup(source, destination)
if (source / 'notebooks').exists() or (source / 'notebooks').is_symlink():
notebook_guard.restore(source / 'notebooks', project_restores / (operation + '.notebooks'))
return destination
def stage_installation(base, project, operation):
directory = operation_directory(base, project, operation)
updates = private_directory(directory / '.updates')
target = updates / operation
target.mkdir(mode=0o700)
return target
def activate_installation(base, project, operation, previous):
directory = operation_directory(base, project, operation)
candidate = directory / '.updates' / operation
if candidate.is_symlink() or not candidate.is_dir():
raise RuntimeError('staged application is missing')
for name in ('codigo', 'deploy'):
path = candidate / name
if path.is_symlink() or not path.is_dir():
raise RuntimeError('staged application is incomplete')
archive = archive_installation(base, project, operation, previous)
for name in ('codigo', 'deploy'):
os.rename(candidate / name, directory / name)
return archive
def find_installation(base, port, *, missing_ok=False):
"""Resolve a unique installed project by its recorded port under the shared lock."""
if type(port) is not int or not 1024 <= port <= 65535:
raise ValueError('invalid port')
matches = []
ports = {}
for entry in base.iterdir():
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
if entry.is_symlink() or not entry.is_dir():
raise RuntimeError(f'invalid instance directory: {entry}')
record = read_record(entry)
if not re.fullmatch(r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*', entry.name) or len(entry.name) > 51:
raise RuntimeError(f'invalid project name: {entry.name}')
if record['port'] in ports:
raise RuntimeError(f'duplicate recorded port {record["port"]}: {ports[record["port"]]} and {entry.name}')
ports[record['port']] = entry.name
if record['port'] == port:
matches.append((entry, record))
if not matches and missing_ok:
return None
if len(matches) != 1:
raise RuntimeError(f'no installation registered on port {port}')
directory, record = matches[0]
if record['status'] != 'installed':
raise RuntimeError(f'installation is not installed: {directory} (status={record["status"]}); '
'manual recovery or reconciliation required; no deployment was attempted')
for name in ('codigo', 'deploy', 'data'):
path = directory / name
if path.is_symlink() or not path.is_dir():
raise RuntimeError(f'invalid installation path: {path}')
archive_root = directory / '.archive'
if archive_root.is_symlink() or (archive_root.exists() and not archive_root.is_dir()):
raise RuntimeError(f'invalid archive directory: {archive_root}')
if archive_root.exists() and archive_root.stat().st_dev != directory.stat().st_dev:
raise RuntimeError('archive must be on the installation filesystem')
if any((directory / name).stat().st_dev != directory.stat().st_dev for name in ('codigo', 'deploy', 'data')):
raise RuntimeError('installation paths must be on the same filesystem')
for name in ('.env', 'docker-compose.yml'):
path = directory / 'deploy' / name
if path.is_symlink():
raise RuntimeError(f'symlinked deployment file: {path}')
return record
def reserve(base, project, port):
directory = base / project
if directory.exists() or directory.is_symlink():
raise RuntimeError(f'instance directory already exists: {directory}')
ports = {}
for entry in base.iterdir():
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
if entry.is_symlink() or not entry.is_dir():
raise RuntimeError(f'invalid instance directory: {entry}')
record = read_record(entry)
if record['port'] in ports:
raise RuntimeError(f'duplicate recorded port {record["port"]}: {ports[record["port"]]} and {entry.name}')
ports[record['port']] = entry.name
if record['port'] == port:
raise RuntimeError(f'port {port} is reserved by {entry.name}')
directory.mkdir(mode=0o700)
write_record(directory, {'project': project, 'port': port, 'status': 'preparing'})
(directory / 'data').mkdir(mode=0o700)
def main():
base, action, project, value = sys.argv[1:]
if value == '-':
value = sys.stdin.read()
base = Path(base)
if action not in ('lookup', 'check-port') and not re.fullmatch(
r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*', project):
raise ValueError('invalid project')
if action == 'reserve':
reserve(base, project, int(value))
elif action == 'lookup':
print(json.dumps(find_installation(base, int(value), missing_ok=True)))
elif action == 'archive':
payload = json.loads(value)
print(archive_installation(base, project, payload['operation_id'], payload['previous']))
elif action == 'read-deploy':
directory = base / project / 'deploy'
result = {}
for name in ('.env', 'docker-compose.yml'):
path = directory / name
if path.is_symlink() or not path.is_file():
raise RuntimeError('deployment configuration is missing or linked')
result[name] = path.read_text(encoding='utf-8')
print(json.dumps(result))
elif action in ('reconcile-check', 'reconcile-apply'):
print(json.dumps(reconcile_record(base, project, json.loads(value),
apply=action == 'reconcile-apply')))
elif action == 'backup':
print(json.dumps(backup_installation(base, project, json.loads(value))))
elif action == 'prepare-backup':
prepare_backup(base, project, json.loads(value)['verify_restore'])
elif action == 'verify-restore':
print(verify_isolated_restore(base, project, value))
elif action == 'prepare-notebook-backup':
notebook_backup_directory(base, project, value)
elif action == 'verify-notebook-backup':
print(json.dumps(verify_notebook_backup(base, project, value)))
elif action == 'stage':
print(stage_installation(base, project, value))
elif action == 'activate':
payload = json.loads(value)
print(activate_installation(base, project, payload['operation_id'], payload['previous']))
elif action == 'space':
if shutil.disk_usage(base).free < int(value):
raise RuntimeError('insufficient space for prepared installation')
elif action in ('update-space', 'update-space-restore'):
files = data_guard.regular_tree(base / project / 'data')
# Leave room for the normalized backup, staged source, and temporary SQLite pages.
copies = 3 if action == 'update-space-restore' else 2
required = copies * sum(path.stat().st_size for path in files.values()) + int(value) + 64 * 1024 * 1024
if int(value) < 0 or shutil.disk_usage(base).free < required:
raise RuntimeError('insufficient space for update backup and prepared application')
elif action == 'check-port':
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('0.0.0.0', int(value)))
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind(('::', int(value)))
except OSError as exc:
if exc.errno not in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
raise
elif action == 'save':
directory = base / project
previous = read_record(directory)
record = json.loads(value)
if record.get('project') != project or record.get('port') != previous['port']:
raise RuntimeError('installation identity changed')
write_record(directory, record)
else:
raise ValueError(f'unknown action: {action}')
if __name__ == '__main__':
main()
+529
View File
@@ -0,0 +1,529 @@
#!/usr/bin/env python3
"""Install and cleanly reinstall disposable DEV instances of ISSSTELEON.
Two operations, each in two steps. Run without a confirmation, an operation only reads: it resolves the Git
reference to exact commits, checks the host, Docker and the composition, and prints the plan together with the
confirmation that approves exactly that plan. Run with the confirmation, it recomputes the plan under the
installer lock and acts only if it is unchanged.
installer.py install <puerto> <referencia> [confirmacion]
installer.py reinstall <puerto> <referencia> [confirmacion]
installer.py load-data <puerto> <hospital> [confirmacion]
installer.py validate-dispatch
Reinstalling removes the registered instance's containers, notebook jobs volume, default network and directory,
data included, after proving the instance is a DEV installation of this installer. No global cleanup is used.
"""
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import subprocess
import sys
import tempfile
import time
import uuid
import composition
import proc
import registry
import resources
ROOT = Path(__file__).resolve().parents[2]
BASE = PurePosixPath('/srv/workingnarrative-dev')
HELPER_IMAGE = os.environ.get('DEV_INSTALLER_HELPER_IMAGE', 'python:3.12-slim')
OFFICIAL_SERVER = 'http://10.0.10.41:3000'
LOCK_SCRIPT = """import fcntl, time
with open('/host/.install.lock', 'a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
open('/tmp/ready', 'w').close()
while True: time.sleep(60)
"""
READ_ONLY_SCRIPT = """import time
open('/tmp/ready', 'w').close()
while True: time.sleep(60)
"""
TCP_SCRIPT = """import socket, sys
host, _, port = sys.argv[1].rpartition(':')
socket.create_connection((host, int(port)), timeout=10).close()
"""
HTTP_SCRIPT = """import json, sys, urllib.request
with urllib.request.urlopen(sys.argv[1], timeout=15) as response:
print(json.dumps({'status': response.status, 'body': response.read(200000).decode('utf-8', 'replace')}))
"""
def dispatch_metadata(root=ROOT):
"""Validate the event identity and its immutable checked-out commit; return the workflow reference."""
ref = os.environ.get('DISPATCH_REF', '')
name = os.environ.get('DISPATCH_REF_NAME', '')
sha = os.environ.get('DISPATCH_SHA', '')
if (os.environ.get('DISPATCH_REPOSITORY') != 'ISSSTELEON/WorkingNarrative'
or os.environ.get('DISPATCH_SERVER', '').rstrip('/') != OFFICIAL_SERVER
or os.environ.get('DISPATCH_REF_TYPE') != 'branch'
or not name or ref != 'refs/heads/' + name
or not re.fullmatch(r'[0-9a-f]{40}', sha)):
raise ValueError('invalid deployment event identity or branch reference')
proc.run(['git', 'check-ref-format', ref])
if proc.git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('checkout does not match the dispatched SHA')
return {'workflow_ref': ref, 'workflow_sha': sha}
class Host:
"""Registry actions and local HTTP checks on the Docker daemon host, through a helper container.
With `lock` the helper holds the host-wide installer lock and can write the base directory; without it the
helper only reads, which is what a plan needs."""
def __init__(self, base, lock):
self.base, self.lock, self.name = base, lock, None
def __enter__(self):
name = resources.HELPER_PREFIX + uuid.uuid4().hex
mount = f'type=bind,src={self.base},dst=/host' + ('' if self.lock else ',readonly')
try:
proc.run(['docker', 'run', '-d', '--network', 'host', '--label', resources.HELPER_LABEL + '=helper',
'--name', name, '--mount', mount, HELPER_IMAGE, 'python3', '-c',
LOCK_SCRIPT if self.lock else READ_ONLY_SCRIPT])
self.name = name
deadline = time.monotonic() + 300
while time.monotonic() < deadline:
if self.exec("import os; print(int(os.path.exists('/tmp/ready')))").strip() == '1':
return self
time.sleep(2)
raise RuntimeError('timed out waiting for the shared installation lock')
except Exception as exc:
self.close(name)
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
raise RuntimeError(f'helper failed; the daemon host directory {self.base} must already exist: {detail}') from exc
def __exit__(self, *exc):
self.close(self.name)
@staticmethod
def close(name):
if name:
try:
proc.run(['docker', 'rm', '-f', name])
except Exception:
pass
def exec(self, script, *args, stdin=None):
return proc.run(['docker', 'exec', *(['-i'] if stdin is not None else []), self.name, 'python3', '-c',
script, *args], stdin=stdin)
def call(self, action, project, payload):
source = Path(__file__).with_name('registry.py').read_text(encoding='utf-8')
out = self.exec(source, '/host', action, project, '-', stdin=json.dumps(payload))
return json.loads(out)
def copy(self, directory, project):
"""Place the instance's deployment files next to its record."""
proc.run(['docker', 'cp', str(directory), f'{self.name}:/host/{project}/deploy'])
def http_get(self, url):
return json.loads(self.exec(HTTP_SCRIPT, url))
def tcp_check(self, address):
"""Fail unless the daemon host can open a connection to `host:port`."""
try:
self.exec(TCP_SCRIPT, address)
except subprocess.CalledProcessError as exc:
raise RuntimeError(f'{address} does not accept connections from the daemon host: '
f'{(exc.stderr or "").strip()[-200:]}') from None
def compose(project, deploy, *args):
return ['docker', 'compose', '--project-name', project, '--project-directory', str(deploy),
'--env-file', str(deploy / '.env'), '-f', str(deploy / 'docker-compose.yml'), *args]
def configure(deploy, data, project, revision, port, operation):
tag = f'{project}-{revision[:12]}-{operation}'
env = (f'ISSSTELEON_VERSION={tag}\nISSSTELEON_DATOS={data}\nISSSTELEON_PUERTO={port}\n'
+ ''.join(f'{name}_DATABASE_URL=sqlite:////data/{name.lower()}.db\n'
for name in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')))
(deploy / '.env').write_text(env, encoding='utf-8')
return tag
def unsafe_service(service):
namespaces = [str(service.get(key, '')) for key in ('network_mode', 'pid', 'ipc', 'userns_mode', 'cgroup')]
unmanaged = {'privileged', 'devices', 'device_cgroup_rules', 'cap_add', 'volumes_from', 'use_api_socket',
'post_start', 'pre_stop', 'develop', 'secrets', 'configs', 'external_links'}
return (any(service.get(key) for key in unmanaged)
or any(value == 'host' or value.startswith(('container:', 'service:')) for value in namespaces))
def data_mount(volume, data):
return (volume.get('type') == 'bind' and volume.get('source') == str(data) and volume.get('target') == '/data'
and not volume.get('read_only'))
def jobs_mount(volume):
return (volume.get('type') == 'volume' and volume.get('source') == composition.NOTEBOOK_VOLUME
and volume.get('target') == composition.NOTEBOOK_JOBS and not volume.get('read_only')
and volume.get('volume') in (None, {}))
def verify_config(config, project, data, tag, port):
"""Check the effective composition against what the installer manages; return whether it has notebooks."""
if config.get('name') != project:
raise RuntimeError('effective Compose project name does not match')
services = config.get('services', {})
notebooks = composition.NOTEBOOK_SERVICE in services
required = set(composition.BASE_SERVICES) | ({composition.NOTEBOOK_SERVICE} if notebooks else set())
declared = {name for name in services
if name in composition.PROFILE_SERVICES and services[name].get('profiles') == [name]}
if set(services) - declared != required:
raise RuntimeError('unexpected Compose services')
volume = composition.notebook_volume_name(project)
if (config.get('volumes') or {}) != ({composition.NOTEBOOK_VOLUME: {'name': volume}} if notebooks else {}):
raise RuntimeError('unexpected Compose volumes')
networks = config.get('networks') or {}
if networks:
default = networks.get('default') or {}
if (set(networks) != {'default'} or default.get('name') != project + '_default'
or set(default) - {'name', 'ipam'} or default.get('ipam')):
raise RuntimeError('unexpected Compose networks')
for name, service in services.items():
if unsafe_service(service):
raise RuntimeError(f'unsafe Compose service: {name}')
for name in ('webapi', 'indicadores', *sorted(declared)):
service = services[name]
if service.get('image') != f'isssteleon/webapi:{tag}':
raise RuntimeError(f'unexpected {name} image')
volumes = service.get('volumes', [])
expected = 2 if notebooks and name == 'webapi' else 1
if (len(volumes) != expected or sum(data_mount(v, data) for v in volumes) != 1
or sum(jobs_mount(v) for v in volumes) != expected - 1):
raise RuntimeError(f'unexpected {name} data mount')
if service.get('ports'):
raise RuntimeError(f'unexpected {name} published ports')
env = service.get('environment', {})
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
if env.get(f'{domain}_DATABASE_URL') != f'sqlite:////data/{domain.lower()}.db':
raise RuntimeError(f'unexpected {name} database configuration')
if any(key in env and env[key] != value for key, value in composition.PERSISTENT_ENV.items()):
raise RuntimeError(f'unexpected {name} storage configuration')
if notebooks:
env = services['webapi'].get('environment', {})
if (env.get('NOTEBOOK_JOBS_DIR') != composition.NOTEBOOK_JOBS
or env.get('NOTEBOOK_RUNNER_UID') != composition.NOTEBOOK_USER.split(':')[0]):
raise RuntimeError('unexpected webapi notebook configuration')
runner = services[composition.NOTEBOOK_SERVICE]
env = runner.get('environment', {})
if (runner.get('image') != f'isssteleon/webapi:{tag}' or runner.get('command') != ['notebooks']
or runner.get('entrypoint') or runner.get('user') != composition.NOTEBOOK_USER
or runner.get('network_mode') != 'none' or runner.get('read_only') is not True
or 'ALL' not in (runner.get('cap_drop') or [])
or 'no-new-privileges:true' not in (runner.get('security_opt') or [])
or runner.get('ports') or len(runner.get('volumes', [])) != 1
or not jobs_mount(runner['volumes'][0]) or env.get('NOTEBOOK_JOBS_DIR') != composition.NOTEBOOK_JOBS
or any('/data' in str(value) for value in env.values())):
raise RuntimeError('unexpected notebooks isolation')
if services['webapp'].get('image') != f'isssteleon/webapp:{tag}':
raise RuntimeError('unexpected webapp image')
if services['webapp'].get('volumes'):
raise RuntimeError('unexpected webapp mounts')
ports = services['webapp'].get('ports', [])
if len(ports) != 1 or str(ports[0].get('published')) != str(port) or int(ports[0].get('target', 0)) != 80:
raise RuntimeError('unexpected webapp port')
return notebooks
def persist_config(deploy, config):
"""Save the verified effective composition, so what runs is exactly what was checked."""
def literal(value):
if isinstance(value, str):
return value.replace('$', '$$')
if isinstance(value, list):
return [literal(item) for item in value]
if isinstance(value, dict):
return {key: literal(item) for key, item in value.items()}
return value
path = deploy / 'docker-compose.yml'
path.write_text(json.dumps(literal(config), indent=2), encoding='utf-8')
path.chmod(0o600)
def prepare(checkout_dir, comp, project, port, base, workdir):
"""Export the composition and check that it can be built and run as this installer requires.
Writes only inside `workdir`; builds nothing."""
operation = uuid.uuid4().hex[:16]
source, deploy = Path(workdir) / 'codigo', Path(workdir) / 'deploy'
composition.export_tree(Path(checkout_dir) / 'ISSSTELEON', comp['application'], source)
for needed in ('WebApi/Dockerfile', 'WebApp/Dockerfile', 'dist/docker-compose.yml'):
if not (source / needed).is_file():
raise RuntimeError(f'the composition lacks {needed}')
composition.copy_deploy(source, deploy)
data = PurePosixPath(str(base)) / project / 'data'
tag = configure(deploy, data, project, comp['commit'], port, operation)
cmd = compose(project, deploy)
config = json.loads(proc.run([*cmd, 'config', '--format', 'json']))
notebooks = verify_config(config, project, data, tag, port)
# The worker recalculates after imports; it does not recalculate on its own at start.
worker = config['services']['indicadores']
worker['environment'] = dict(worker.get('environment', {}), INDICADORES_AL_INICIAR='0')
return {'source': source, 'deploy': deploy, 'data': data, 'tag': tag, 'operation': operation,
'images': [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}'], 'config': config,
'notebooks': notebooks, 'cmd': cmd}
def build_images(candidate):
source = candidate['source']
proc.run(['docker', 'build', '-t', candidate['images'][0], '-f', source / 'WebApi/Dockerfile', source])
proc.run(['docker', 'build', '-t', candidate['images'][1], source / 'WebApp'])
def digest(plan):
return hashlib.sha256(composition.digest_text(plan).encode()).hexdigest()[:16]
def confirmation_for(plan):
word = 'instalar' if plan['operation'] == 'install' else 'reinstalar'
return f'{word}-{plan["port"]}-{digest(plan)}'
def existing_image_ids(images):
"""IDs of the recorded images that still exist; one that was removed cannot be in use."""
ids = set()
for image in images or []:
try:
ids.add(proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip())
except subprocess.CalledProcessError:
continue
return ids
def plan_install(host, base, port, comp):
"""Check that a new instance can take `port`; nothing is registered or created."""
project = composition.project_for(port)
if host.call('lookup', '-', port) is not None:
raise RuntimeError(f'port {port} is already registered; use the reinstall workflow if it is a DEV instance')
resources.assert_absent(project, port, base)
host.call('check-port', '-', port)
return {'operation': 'install', 'port': port, 'project': project, 'composition': comp}
def plan_reinstall(host, base, port, comp):
"""Describe everything a clean reinstallation would remove; the instance must prove to be a DEV one."""
record = host.call('lookup', '-', port)
if record is None:
raise RuntimeError(f'no installation is registered on port {port}; use the install workflow')
project = record['project']
identity = host.call('identity', project, {'port': port})
found = resources.discover(project, port, base, existing_image_ids(record.get('images')))
if not found['containers']:
host.call('check-port', '-', port)
return {'operation': 'reinstall', 'port': port, 'project': project, 'composition': comp,
'directory': identity, 'resources': resources.plan_view(found)}
def verify_services(cmd, notebooks, timeout=600):
deadline = time.monotonic() + timeout
last = 'services did not start'
expected = composition.BASE_SERVICES + ((composition.NOTEBOOK_SERVICE,) if notebooks else ())
while time.monotonic() < deadline:
try:
for service in expected:
ids = proc.run([*cmd, 'ps', '-q', service]).splitlines()
if len(ids) != 1:
raise RuntimeError(f'{service}: expected one running container')
state = json.loads(proc.run(['docker', 'inspect', '--format', '{{json .State}}', ids[0]]))
if state.get('Status') != 'running':
raise RuntimeError(f'{service}: {state.get("Status")}')
if service == 'webapi' and state.get('Health', {}).get('Status') != 'healthy':
raise RuntimeError(f'webapi health: {state.get("Health", {}).get("Status", "missing")}')
return
except Exception as exc:
last = str(exc)
time.sleep(3)
raise RuntimeError(f'availability check failed: {last}')
def verify_endpoints(host, port):
"""The published port answers as the platform: web app, proxied API health and the API's route index."""
url = f'http://127.0.0.1:{port}'
health = host.http_get(url + '/health')
if health['status'] != 200 or json.loads(health['body']).get('status') != 'ok':
raise RuntimeError('API health through the published port is not ok')
routes = host.http_get(url + '/api')
if routes['status'] != 200 or not json.loads(routes['body']).get('routes'):
raise RuntimeError('API route index through the published port is empty')
home = host.http_get(url + '/')
if home['status'] != 200 or '<html' not in home['body'].lower():
raise RuntimeError('web app page through the published port is not served')
return {'health': 'ok', 'api_routes': len(json.loads(routes['body'])['routes']), 'web': 'ok'}
def failure_detail(exc):
detail = str(exc)
if isinstance(exc, subprocess.CalledProcessError):
detail += f'\ncommand: {exc.cmd}\nstderr: {exc.stderr}'
return detail[:4000]
def activate(host, base, plan, candidate, metadata, replaced=None):
"""Register the instance and start it; the images are already built. Any failure is recorded on the instance."""
project, port, comp = plan['project'], plan['port'], plan['composition']
record = {'project': project, 'port': port, 'status': 'preparing', 'installer': registry.INSTALLER,
'reference': comp['reference'], 'reference_kind': comp['kind'], 'revision': comp['commit'],
'gitlinks': comp['gitlinks'], 'images': candidate['images'], 'plan_digest': digest(plan),
'operation_id': candidate['operation'], **metadata}
if candidate['notebooks']:
record['notebook_volume'] = composition.notebook_volume_name(project)
if replaced:
record['replaced'] = replaced
host.call('reserve', project, {'port': port, 'record': record})
def save(**changes):
record.update(changes)
host.call('save', project, record)
try:
probe = ("import sqlite3, os; p='/data/.permission-probe.db'; c=sqlite3.connect(p); "
"c.execute('create table probe (x int)'); c.execute('insert into probe values (1)'); c.commit(); "
"c.close(); os.remove(p)")
proc.run(['docker', 'run', '--rm', '--pull', 'never', '--mount',
f'type=bind,src={candidate["data"]},dst=/data', '--entrypoint', 'python3',
candidate['images'][0], '-c', probe])
persist_config(candidate['deploy'], candidate['config'])
host.copy(candidate['deploy'], project)
save(status='starting')
proc.run([*candidate['cmd'], 'up', '-d', '--no-build', '--pull', 'never'])
verify_services(candidate['cmd'], candidate['notebooks'])
resources.verify_running(project, port, base, candidate['images'], candidate['notebooks'])
verification = verify_endpoints(host, port)
save(status='installed', result='reinstalled' if replaced else 'installed', verification=verification)
except Exception as exc:
try:
diagnostics = proc.run([*candidate['cmd'], 'ps', '-a']) + '\n' + proc.run(
[*candidate['cmd'], 'logs', '--no-color', '--tail', '60'])
except Exception as diagnostic_error:
diagnostics = str(diagnostic_error)
save(status='failed', error=failure_detail(exc), diagnostics=diagnostics[-8000:])
raise
return record
def remove_installation(host, base, plan, digest_value):
"""Remove exactly the planned resources of the instance, then its directory. Docker resources go by ID or
exact name, each after confirming it is still the one planned."""
project, port = plan['project'], plan['port']
record = host.call('lookup', '-', port)
phase = 'marking'
def mark(new_phase, **extra):
nonlocal phase
phase = new_phase
current = host.call('lookup', '-', port)
reinstall = dict(current.get('reinstall') or {}, digest=digest_value, phase=new_phase, **extra)
host.call('save', project, dict(current, status='removing', reinstall=reinstall))
try:
mark('containers')
for container in plan['resources']['containers']:
proc.run(['docker', 'update', '--restart=no', container['id']])
proc.run(['docker', 'stop', container['id']])
proc.run(['docker', 'rm', container['id']])
for volume in plan['resources']['volumes']:
mark('volume')
if resources.volume_identity(project) != volume:
raise RuntimeError('notebook jobs volume changed since the plan')
proc.run(['docker', 'volume', 'rm', volume['name']])
for network in plan['resources']['networks']:
mark('network')
item = json.loads(proc.run(['docker', 'network', 'inspect', network['id']]))[0]
if item.get('Name') != network['name'] or item.get('Containers'):
raise RuntimeError('project network changed since the plan')
proc.run(['docker', 'network', 'rm', network['id']])
mark('directory')
host.call('remove', project, {'identity': plan['directory'], 'digest': digest_value})
except Exception as exc:
try:
current = host.call('lookup', '-', port)
if current and current['project'] == project:
reinstall = dict(current.get('reinstall') or {}, phase=phase, error=failure_detail(exc)[:2000])
host.call('save', project, dict(current, status='removing', reinstall=reinstall))
except Exception:
pass
raise RuntimeError(f'removal stopped during {phase} ({str(exc)[:500]}); what remains is kept and recorded; '
'a new plan and confirmation are needed to continue') from None
return {'operation_id': (record or {}).get('operation_id'), 'revision': (record or {}).get('revision'),
'removed': {'containers': [c['name'] for c in plan['resources']['containers']],
'volumes': [v['name'] for v in plan['resources']['volumes']],
'networks': [n['name'] for n in plan['resources']['networks']]}}
def validate_confirmation(operation, port, confirmation):
word = 'instalar' if operation == 'install' else 'reinstalar'
if confirmation and not re.fullmatch(rf'{word}-{port}-[0-9a-f]{{16}}', confirmation):
raise ValueError(f'confirmacion must be {word}-{port}-<digest>, as printed by a run without it')
def run_operation(operation, port_text, reference, confirmation='', base=BASE, metadata=None, host_factory=Host,
remote=None):
"""Plan, or with the matching confirmation execute, an installation or a clean reinstallation."""
port = composition.validate_port(port_text)
confirmation = (confirmation or '').strip()
validate_confirmation(operation, port, confirmation)
resolved = composition.resolve_reference(reference, remote)
metadata = metadata or {}
with host_factory(base, bool(confirmation)) as host, tempfile.TemporaryDirectory(prefix='isssteleon-dev-') as tmp:
checkout_dir = Path(tmp) / 'checkout'
comp = composition.checkout(resolved, checkout_dir, remote)
planner = plan_install if operation == 'install' else plan_reinstall
plan = planner(host, base, port, comp)
candidate = prepare(checkout_dir, comp, plan['project'], port, base, Path(tmp) / 'candidate')
expected = confirmation_for(plan)
print('Plan:', json.dumps(plan, indent=1, sort_keys=True))
if not confirmation:
print('Nothing was changed. To approve exactly this plan, run again with confirmacion=' + expected)
return None
if confirmation != expected:
raise RuntimeError(f'confirmacion does not match the current plan ({expected}); nothing was changed')
build_images(candidate)
replaced = None
if operation == 'reinstall':
recheck = composition.resolve_reference(reference, remote)
if recheck['commit'] != comp['commit']:
raise RuntimeError('the reference moved after the plan; nothing was removed')
if confirmation_for(plan_reinstall(host, base, port, comp)) != expected:
raise RuntimeError('the instance or its resources changed after the plan; nothing was removed')
replaced = remove_installation(host, base, plan, digest(plan))
host.call('check-port', '-', port)
resources.assert_absent(plan['project'], port, base)
record = activate(host, base, plan, candidate, metadata, replaced)
print(f'{"Reinstalled" if replaced else "Installed"} {plan["project"]} on port {port} at {comp["commit"]}')
return record
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
try:
if argv[:1] == ['validate-dispatch'] and len(argv) == 1:
print('Workflow event:', json.dumps(dispatch_metadata(), sort_keys=True))
elif argv[:1] in (['install'], ['reinstall']) and 3 <= len(argv) <= 4:
run_operation(argv[0], argv[1], argv[2], argv[3] if len(argv) == 4 else '',
metadata=dispatch_metadata())
elif argv[:1] == ['load-data'] and 3 <= len(argv) <= 4:
import dataload
dataload.run_load(argv[1], argv[2], argv[3] if len(argv) == 4 else '')
else:
raise ValueError('usage: installer.py install|reinstall <puerto> <referencia> [confirmacion] '
'| load-data <puerto> <hospital> [confirmacion] | validate-dispatch')
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as exc:
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
print(f'Deployment failed: {detail}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
-207
View File
@@ -1,207 +0,0 @@
"""Inspect, back up and restore the notebook jobs volume without following links.
The volume holds the job folders the WebApi hands to the notebook runner
(`models.io.notebook_jobs`): `<run_id>/` with `job.json`, then `result.json`
once the runner finishes; `.<run_id>-*` while a job is being assembled. Its
contents are written by untrusted notebooks, so every walk uses `lstat`, links
are stored and restored as links, and any other special file is rejected.
Standard library only: it runs both in the locked helper and in the candidate
image.
"""
import hashlib
import json
import os
from pathlib import Path
import stat
import sys
FORMAT = 1
JOB_FILE, RESULT_FILE = 'job.json', 'result.json'
def require(condition, message):
if not condition:
raise RuntimeError(message)
def file_digest(path):
result = hashlib.sha256()
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
with os.fdopen(descriptor, 'rb') as stream:
require(stat.S_ISREG(os.fstat(stream.fileno()).st_mode), 'notebook job entry changed type')
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
result.update(chunk)
return result.hexdigest()
def describe(path):
info = os.lstat(path)
entry = {'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid,
'mtime_ns': info.st_mtime_ns}
if stat.S_ISDIR(info.st_mode):
entry['type'] = 'dir'
elif stat.S_ISREG(info.st_mode):
entry.update(type='file', size=info.st_size, sha256=file_digest(path))
elif stat.S_ISLNK(info.st_mode):
entry.update(type='link', target=os.readlink(path))
else:
raise RuntimeError('notebook job entry type is unsupported')
return entry
def scan(root):
"""Every entry below `root` keyed by its relative POSIX path; the root itself is `.`."""
root = Path(root)
require(stat.S_ISDIR(os.lstat(root).st_mode), 'notebook jobs root is missing or linked')
entries = {'.': describe(root)}
pending = [root]
while pending:
directory = pending.pop()
with os.scandir(directory) as listing:
for item in listing:
path = Path(item.path)
name = path.relative_to(root).as_posix()
entries[name] = describe(path)
if entries[name]['type'] == 'dir':
pending.append(path)
return dict(sorted(entries.items()))
def state_digest(entries):
return hashlib.sha256(json.dumps(entries, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def activity(entries):
"""Top-level entries that show a job being assembled, waiting or running, or anything unrecognized."""
active = {}
for name, entry in entries.items():
if name == '.' or '/' in name:
continue
if name.startswith('.'):
active[name] = 'assembling'
elif entry['type'] != 'dir':
active[name] = 'unexpected'
elif entries.get(name + '/' + JOB_FILE, {}).get('type') != 'file':
active[name] = 'incomplete'
elif entries.get(name + '/' + RESULT_FILE, {}).get('type') != 'file':
active[name] = 'pending'
return active
def inspect(root):
entries = scan(root)
active = activity(entries)
return {'digest': state_digest(entries), 'entries': len(entries),
'bytes': sum(entry.get('size', 0) for entry in entries.values()),
'jobs': sum(1 for name in entries if name != '.' and '/' not in name),
'active': sorted(set(active.values()))}
def copy_entries(source, target, entries):
"""Recreate `entries` from `source` under the existing empty `target` with their metadata."""
source, target = Path(source), Path(target)
for name, entry in entries.items():
if name == '.':
continue
origin, destination = source / name, target / name
if entry['type'] == 'dir':
os.mkdir(destination, 0o700)
elif entry['type'] == 'link':
os.symlink(entry['target'], destination)
else:
descriptor = os.open(origin, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
with os.fdopen(descriptor, 'rb') as reader:
require(stat.S_ISREG(os.fstat(reader.fileno()).st_mode), 'notebook job entry changed type')
output = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0),
0o600)
with os.fdopen(output, 'wb') as writer:
for chunk in iter(lambda: reader.read(1024 * 1024), b''):
writer.write(chunk)
writer.flush()
os.fsync(writer.fileno())
# Metadata goes last: creating an entry would change its parent's mtime.
for name in entries:
entry = entries[name]
path = target if name == '.' else target / name
link = entry['type'] == 'link'
if not link:
os.chmod(path, entry['mode'])
os.utime(path, ns=(entry['mtime_ns'], entry['mtime_ns']), follow_symlinks=not link)
if hasattr(os, 'chown'):
os.chown(path, entry['uid'], entry['gid'], follow_symlinks=not link)
def empty_directory(path):
path = Path(path)
require(stat.S_ISDIR(os.lstat(path).st_mode), 'notebook backup destination is missing or linked')
require(not any(path.iterdir()), 'notebook backup destination is not empty')
return path
def backup(root, destination, volume):
"""Copy idle jobs to `destination/content` and verify their manifest against the quiesced volume."""
destination = empty_directory(destination)
before = scan(root)
require(not activity(before), 'notebook jobs are active')
content = destination / 'content'
os.mkdir(content, 0o700)
copy_entries(root, content, before)
require(scan(root) == before, 'notebook jobs changed while creating the backup')
require(scan(content) == before, 'notebook backup differs from the volume')
manifest = {'format': FORMAT, 'volume': volume, 'digest': state_digest(before), 'entries': before}
descriptor = os.open(destination / 'manifest.json', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
json.dump(manifest, stream, sort_keys=True)
stream.flush()
os.fsync(stream.fileno())
return verify_backup(destination)
def verify_backup(destination):
destination = Path(destination)
require(stat.S_ISDIR(os.lstat(destination).st_mode), 'notebook backup directory is invalid')
manifest = json.loads((destination / 'manifest.json').read_text(encoding='utf-8'))
require(manifest.get('format') == FORMAT and isinstance(manifest.get('entries'), dict),
'notebook backup manifest is invalid')
require(state_digest(manifest['entries']) == manifest['digest'], 'notebook backup manifest is inconsistent')
require(scan(destination / 'content') == manifest['entries'], 'notebook backup content differs')
return {'digest': manifest['digest'], 'volume': manifest['volume'], 'entries': len(manifest['entries'])}
def restore(source, target):
"""Restore a verified backup into an empty directory, a new isolated one or an empty volume root."""
verify_backup(source)
manifest = json.loads((Path(source) / 'manifest.json').read_text(encoding='utf-8'))
target = Path(target)
if not os.path.lexists(target):
os.mkdir(target, 0o700)
empty_directory(target)
copy_entries(Path(source) / 'content', target, manifest['entries'])
require(scan(target) == manifest['entries'], 'notebook restore differs from the backup')
return {'digest': manifest['digest']}
def main():
action, payload = sys.argv[1], json.load(sys.stdin)
if action == 'inspect':
result = inspect(payload['root'])
elif action == 'backup':
result = backup(payload['root'], payload['destination'], payload['volume'])
elif action == 'verify':
result = verify_backup(payload['destination'])
elif action == 'restore':
result = restore(payload['source'], payload['target'])
else:
raise RuntimeError('unsupported notebook guard action')
print(json.dumps(result))
if __name__ == '__main__':
try:
main()
except Exception as exc:
reason = str(exc) if isinstance(exc, RuntimeError) and str(exc).startswith('notebook') else ''
print('WN_NOTEBOOK_DIAGNOSTIC=' + json.dumps({'type': type(exc).__name__, 'reason': reason}),
file=sys.stderr)
raise SystemExit(1)
+21
View File
@@ -0,0 +1,21 @@
"""External commands used by the DEV installer; one place to replace in tests."""
import os
import subprocess
def clean_env():
"""The process environment without Compose or installer variables that could redirect a command."""
return {k: v for k, v in os.environ.items() if not k.startswith(('COMPOSE_', 'ISSSTELEON_'))}
def run(args, cwd=None, binary=False, stdin=None):
"""Run a command and return its stdout; a non-zero exit raises `CalledProcessError`."""
result = subprocess.run([str(a) for a in args], cwd=cwd, check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=not binary, env=clean_env(), input=stdin)
return result.stdout
def git(repo, *args, binary=False):
return run(['git', '-C', repo, *args], binary=binary)
-164
View File
@@ -1,164 +0,0 @@
#!/usr/bin/env python3
"""Check or explicitly reconcile a manually recovered installation on the daemon host."""
import argparse
from contextlib import closing
import hashlib
import json
from pathlib import Path
import re
import shutil
import sqlite3
import sys
import tarfile
import tempfile
import conservative
import dev
DATABASES = ('cacu.db', 'cama.db', 'tea.db', 'governance.db', 'mlflow.db')
def sha256_stream(stream):
digest = hashlib.sha256()
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(chunk)
return digest.hexdigest()
def recovery_evidence(archive, restored, expected, installation):
"""Check archive identity and five isolated SQLite copies without writing."""
archive, restored, installation = Path(archive), Path(restored), Path(installation)
if not re.fullmatch(r'[0-9a-fA-F]{64}', expected):
raise ValueError('expected backup SHA-256 must contain 64 hexadecimal characters')
if archive.is_symlink() or not archive.is_file() or restored.is_symlink() or not restored.is_dir():
raise RuntimeError('backup archive or isolated restore is missing or linked')
for path in (archive.resolve(), restored.resolve()):
if path.is_relative_to(installation.resolve()) or installation.resolve().is_relative_to(path):
raise RuntimeError('backup evidence must be outside the installation')
with archive.open('rb') as stream:
if sha256_stream(stream) != expected.lower():
raise RuntimeError('backup archive SHA-256 differs')
with tarfile.open(archive, 'r:gz') as tar:
members = tar.getmembers()
for name in DATABASES:
matches = [m for m in members if m.name.rstrip('/').split('/')[-2:] == ['data', name]]
if len(matches) != 1 or not matches[0].isfile():
raise RuntimeError('backup archive lacks a unique regular data/' + name)
path = restored / name
if path.is_symlink() or not path.is_file():
raise RuntimeError('isolated restore lacks ' + name)
with tar.extractfile(matches[0]) as source, path.open('rb') as copy:
if sha256_stream(source) != sha256_stream(copy):
raise RuntimeError('isolated restore differs from archive: ' + name)
with tempfile.TemporaryDirectory(prefix='isssteleon-recovery-check-') as tmp:
temporary = Path(tmp) / name
shutil.copyfile(path, temporary)
with tar.extractfile(matches[0]) as source, temporary.open('rb') as copy:
if sha256_stream(source) != sha256_stream(copy):
raise RuntimeError('SQLite copy differs from archive: ' + name)
for suffix in ('-wal', '-shm', '-journal'):
member = [m for m in members if m.name.rstrip('/').split('/')[-2:] == ['data', name + suffix]]
sidecar = restored / (name + suffix)
if len(member) > 1 or bool(member) != (sidecar.exists() or sidecar.is_symlink()):
raise RuntimeError('isolated SQLite sidecar inventory differs: ' + name)
if member:
if not member[0].isfile() or sidecar.is_symlink() or not sidecar.is_file():
raise RuntimeError('invalid SQLite sidecar: ' + name)
with tar.extractfile(member[0]) as source, sidecar.open('rb') as copy:
if sha256_stream(source) != sha256_stream(copy):
raise RuntimeError('isolated SQLite sidecar differs: ' + name)
if suffix != '-shm':
shutil.copyfile(sidecar, Path(str(temporary) + suffix))
with tar.extractfile(member[0]) as source, Path(str(temporary) + suffix).open('rb') as copy:
if sha256_stream(source) != sha256_stream(copy):
raise RuntimeError('SQLite sidecar copy differs: ' + name)
with closing(sqlite3.connect(temporary)) as db:
if db.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
raise RuntimeError('isolated SQLite integrity failed: ' + name)
def reconcile(args, api=dev):
"""Hold the installer lock through every check and the optional atomic write."""
project, port = api.validate(args.instance, str(args.port), 'instalar')
runner = getattr(args, 'notebooks', None)
ids = [args.indicadores, args.webapi, args.webapp] + ([runner] if runner else [])
if len(set(ids)) != len(ids) or any(not re.fullmatch(r'[0-9a-f]{64}', value) for value in ids):
raise ValueError('distinct full original container IDs are required: indicadores, webapi, webapp and, '
'with notebooks, the runner')
if not args.external_copy_verified:
raise RuntimeError('operator must attest the external backup copy was verified')
lock = api.BASE / '.install.lock'
if lock.is_symlink() or not lock.is_file():
raise RuntimeError('existing shared installer lock file is missing or linked')
helper = api.start_helper(api.BASE)
try:
request = {'port': port, 'revision': args.revision, 'operation_id': args.operation}
result = json.loads(api.host_action(helper, 'reconcile-check', project, json.dumps(request)))
record = result['record']
if bool(record.get('notebook_volume')) != bool(runner):
raise RuntimeError('the notebook runner ID is required exactly for installations with notebooks')
expected_tag_prefix = project + '-' + args.revision[:12] + '-'
images = record.get('images', [])
if (len(images) != 2 or not images[0].startswith('isssteleon/webapi:' + expected_tag_prefix)
or not images[1].startswith('isssteleon/webapp:' + expected_tag_prefix)
or images[0].split(':', 1)[1] != images[1].split(':', 1)[1]):
raise RuntimeError('recorded image tags do not match the original revision')
link = api.git(api.ROOT, 'ls-tree', args.revision, 'ISSSTELEON').split()
if len(link) < 3 or link[2] != record['gitlinks'].get('ISSSTELEON'):
raise RuntimeError('original revision and recorded source gitlink differ')
if api.verify_existing_containers(record, api.BASE, helper) != ids:
raise RuntimeError('running container IDs differ from the original IDs')
with tempfile.TemporaryDirectory(prefix='isssteleon-reconcile-') as tmp:
deploy = Path(tmp) / 'deploy'
conservative.read_deployment(api, helper, project, deploy)
cmd = api.compose(project, deploy)
config = json.loads(api.run([*cmd, 'config', '--format', 'json']))
volume = api.verify_config(config, project, api.BASE / project / 'data', images[0].split(':', 1)[1], port)
if volume != record.get('notebook_volume'):
raise RuntimeError('retained composition and installation record disagree on notebook jobs')
conservative.current_environment(api, ids, config)
containers = json.loads(api.run(['docker', 'inspect', *ids]))
for item in containers:
service = item['Config']['Labels']['com.docker.compose.service']
expected_restart = config['services'][service].get('restart', 'no')
actual_restart = item['HostConfig']['RestartPolicy']
if expected_restart != actual_restart.get('Name') or actual_restart.get('MaximumRetryCount', 0):
raise RuntimeError('restart policy differs for ' + service)
api.verify_services(cmd, port, timeout=1, notebooks=bool(runner))
contract = conservative.guard(api, images[0], 'contract', {})
conservative.guard(api, images[0], 'state', {'data': '/data', 'contract': contract},
api.BASE / project / 'data')
recovery_evidence(args.backup, args.restored_data, args.backup_sha256, api.BASE / project)
if api.verify_existing_containers(record, api.BASE, helper) != ids:
raise RuntimeError('container identities changed during validation')
if args.mode == 'apply':
request['record_sha256'] = result['record_sha256']
api.host_action(helper, 'reconcile-apply', project, json.dumps(request))
return {'result': 'reconciled' if args.mode == 'apply' else 'eligible', 'project': project,
'note': 'External copy and functional recovery are operator attestations; '
'SQLite integrity and archive hashes do not certify functional consistency.'}
finally:
api.run(['docker', 'rm', '-f', helper])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('mode', choices=('check', 'apply'))
for name in ('instance', 'revision', 'operation', 'webapi', 'webapp', 'indicadores',
'backup', 'backup-sha256', 'restored-data'):
parser.add_argument('--' + name, required=True)
parser.add_argument('--port', required=True, type=int)
parser.add_argument('--notebooks', help='original notebook runner container ID, for installations with notebooks')
parser.add_argument('--external-copy-verified', action='store_true')
args = parser.parse_args()
try:
print(json.dumps(reconcile(args)))
except Exception as exc:
print('Reconciliation rejected: ' + str(exc), file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
+232
View File
@@ -0,0 +1,232 @@
"""Installation registry actions, run on the Docker daemon host inside the locked helper container.
The base directory holds one directory per installation, each with an `installation.json` record. Only the
Python standard library is used because the helper image has nothing else. Usage:
`registry.py <base> <action> <project> <value>` where `value` is `-` to read it from stdin.
"""
import errno
import hashlib
import json
import os
from pathlib import Path
import re
import socket
import sys
import tempfile
PROJECT = re.compile(r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*')
INSTALLER = 'dev-disposable'
# `updating`, `update_failed`, `replacing` and `replace_failed` are written by the retired in-place updater; they
# are read, never replaced.
STATUSES = ('preparing', 'building', 'starting', 'installed', 'failed', 'removing',
'updating', 'update_failed', 'replacing', 'replace_failed')
REPLACEABLE = ('preparing', 'building', 'starting', 'installed', 'failed', 'removing')
SHA = re.compile(r'[0-9a-f]{40}')
def write_record(directory, record):
"""Replace the record atomically."""
fd, name = tempfile.mkstemp(prefix='.installation-', dir=directory)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
json.dump(record, stream, indent=2, sort_keys=True)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(name, Path(directory) / 'installation.json')
finally:
if os.path.exists(name):
os.unlink(name)
def read_record(directory):
directory = Path(directory)
path = directory / 'installation.json'
if path.is_symlink():
raise RuntimeError(f'symlinked installation record: {directory.name}')
record = json.loads(path.read_text(encoding='utf-8'))
if (not isinstance(record, dict) or record.get('project') != directory.name
or type(record.get('port')) is not int or not 1024 <= record['port'] <= 65535
or record.get('status') not in STATUSES):
raise RuntimeError(f'invalid installation record: {directory.name}')
return record
def scan(base):
"""Every registered installation as `{port: (directory, record)}`; invalid or duplicate entries fail."""
found = {}
for entry in sorted(Path(base).iterdir()):
if entry.name.startswith('.'):
continue
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
if entry.is_symlink() or not entry.is_dir():
raise RuntimeError(f'invalid instance directory: {entry.name}')
if not PROJECT.fullmatch(entry.name) or len(entry.name) > 51:
raise RuntimeError(f'invalid project name: {entry.name}')
record = read_record(entry)
if record['port'] in found:
raise RuntimeError(f'duplicate recorded port {record["port"]}: {found[record["port"]][0].name} '
f'and {entry.name}')
found[record['port']] = (entry, record)
return found
def owned(record, port):
"""How the record proves the installation is a DEV one: its own marker, or the shape earlier DEV runs wrote.
A record naming another project, another installer or no commit is not owned."""
if record.get('project') != f'isssteleon-dev-{port}':
return None
marker = record.get('installer')
if marker == INSTALLER:
return 'marker'
if marker is None and isinstance(record.get('revision'), str) and SHA.fullmatch(record['revision']):
return 'legacy'
return None
def lookup(base, port):
"""The record registered on `port`, or None."""
found = scan(base).get(port)
return found[1] if found else None
def tree_entries(root):
"""Every path below `root` without following links, so a link is a leaf."""
for current, folders, files in os.walk(root, followlinks=False):
for name in folders + files:
yield Path(current) / name
def identity(base, project, port):
"""Check that the directory of `project` is a replaceable DEV installation and describe it for a plan."""
base = Path(base)
directory = base / project
if not PROJECT.fullmatch(project):
raise RuntimeError('invalid project name')
if directory.is_symlink() or not directory.is_dir():
raise RuntimeError('installation directory is missing or linked')
found = scan(base).get(port)
if found is None or found[0].name != project:
raise RuntimeError(f'no installation of {project} is registered on port {port}')
record = found[1]
how = owned(record, port)
if how is None:
raise RuntimeError('the installation record does not prove a DEV installation of this installer')
if record['status'] not in REPLACEABLE:
raise RuntimeError(f'installation status {record["status"]} is not replaceable; inspect it manually')
device = base.stat().st_dev
if directory.stat().st_dev != device:
raise RuntimeError('installation directory is on another filesystem')
for path in tree_entries(directory):
if os.lstat(path).st_dev != device:
raise RuntimeError('installation directory crosses a filesystem boundary')
info = directory.stat()
return {'project': project, 'port': port, 'status': record['status'], 'ownership': how,
'record_sha256': hashlib.sha256((directory / 'installation.json').read_bytes()).hexdigest(),
'directory': [info.st_dev, info.st_ino], 'entries': sorted(p.name for p in directory.iterdir())}
def reserve(base, project, port, record):
"""Create the directory of a new installation and its first record; refuse any existing owner of either."""
base = Path(base)
if not PROJECT.fullmatch(project) or project != f'isssteleon-dev-{port}':
raise RuntimeError('invalid project for this port')
directory = base / project
if directory.exists() or directory.is_symlink():
raise RuntimeError(f'instance directory already exists: {project}')
if port in scan(base):
raise RuntimeError(f'port {port} is registered by another installation')
if record.get('project') != project or record.get('port') != port or record.get('installer') != INSTALLER:
raise RuntimeError('record does not describe this installation')
directory.mkdir(mode=0o700)
write_record(directory, record)
(directory / 'data').mkdir(mode=0o700)
def save(base, project, record):
directory = Path(base) / project
if directory.is_symlink() or not directory.is_dir():
raise RuntimeError('installation directory is missing or linked')
previous = read_record(directory)
if record.get('project') != project or record.get('port') != previous['port']:
raise RuntimeError('installation identity changed')
write_record(directory, record)
def remove(base, project, expected, digest):
"""Delete the installation directory once it is still the one the plan named.
The directory must be marked `removing` by the operation whose plan has this digest. The record goes last,
so a failure leaves a `removing` record that a new plan can resume."""
base = Path(base)
current = identity(base, project, expected['port'])
if any(current[key] != expected[key] for key in ('project', 'port', 'ownership', 'directory')):
raise RuntimeError('installation directory changed since the plan')
directory = base / project
record = read_record(directory)
if record['status'] != 'removing' or (record.get('reinstall') or {}).get('digest') != digest:
raise RuntimeError('installation is not marked as being removed by this plan')
device = base.stat().st_dev
paths = sorted(tree_entries(directory), key=lambda p: len(p.parts), reverse=True)
keep = directory / 'installation.json'
for path in paths:
if path == keep:
continue
if os.lstat(path).st_dev != device:
raise RuntimeError('installation directory crosses a filesystem boundary')
if os.path.islink(path) or not path.is_dir():
os.unlink(path)
else:
os.rmdir(path)
os.unlink(keep)
os.rmdir(directory)
def check_port(port):
"""Fail if something on the host already listens on `port`, on IPv4 or IPv6."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('0.0.0.0', port))
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind(('::', port))
except OSError as exc:
if exc.errno not in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
raise
def dispatch(base, action, project, value):
"""Run one action; the result is JSON-serialisable."""
if action not in ('lookup', 'check-port') and not PROJECT.fullmatch(project):
raise ValueError('invalid project')
if action == 'lookup':
return lookup(base, int(value))
if action == 'check-port':
check_port(int(value))
return None
payload = json.loads(value)
if action == 'identity':
return identity(base, project, int(payload['port']))
if action == 'reserve':
reserve(base, project, int(payload['port']), payload['record'])
return None
if action == 'save':
save(base, project, payload)
return None
if action == 'remove':
remove(base, project, payload['identity'], payload['digest'])
return None
raise ValueError(f'unknown action: {action}')
def main():
base, action, project, value = sys.argv[1:]
if value == '-':
value = sys.stdin.read()
print(json.dumps(dispatch(Path(base), action, project, value)))
if __name__ == '__main__':
main()
-410
View File
@@ -1,410 +0,0 @@
#!/usr/bin/env python3
"""Reset only the approved 18080 laboratory incident on the local daemon host."""
import argparse
from contextlib import contextmanager
import json
import os
import re
from pathlib import Path
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import uuid
from urllib.request import ProxyHandler, build_opener
import conservative
import data_guard
import dev
import host
PROJECT = 'isssteleon-dev-prueba-02'
ORIGINAL = '55e90fd49c6982793afb0633e974b33e44e58d94'
def sync_directory(path):
if os.name == 'posix':
descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
def marker(path):
with path.open('xb') as stream:
stream.flush()
os.fsync(stream.fileno())
sync_directory(path.parent)
def fingerprint(path, link_roots=()):
"""Fingerprint entries without following links, restricted to authorized trees."""
path = Path(path)
if path.is_symlink() or not path.is_dir():
raise RuntimeError('missing or linked tree root')
result = {}
for entry in [path, *sorted(path.rglob('*'))]:
info = entry.lstat()
destination = None
if stat.S_ISLNK(info.st_mode):
root = next((root for root in link_roots if entry.is_relative_to(root)), None)
destination = os.readlink(entry)
if root is None or os.path.isabs(destination):
raise RuntimeError('unsupported tree link')
lexical = Path(os.path.abspath(entry.parent / destination))
try:
resolved = entry.resolve(strict=True)
except (OSError, RuntimeError) as exc:
raise RuntimeError('invalid tree link') from exc
if (not lexical.is_relative_to(root) or not resolved.is_relative_to(root)
or not (resolved.is_file() or resolved.is_dir())):
raise RuntimeError('tree link escapes or targets a special entry')
elif not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
raise RuntimeError('special tree entry is unsupported')
attributes = ({name: os.getxattr(entry, name, follow_symlinks=False).hex()
for name in os.listxattr(entry, follow_symlinks=False)}
if hasattr(os, 'listxattr') else {})
result[str(entry.relative_to(path))] = [info.st_mode & 0o7777, info.st_uid, info.st_gid,
attributes, destination if stat.S_ISLNK(info.st_mode) else
data_guard.digest(entry) if stat.S_ISREG(info.st_mode) else None]
return result
def tree(path):
data_guard.regular_tree(path)
return fingerprint(path)
def code_tree(path):
path = Path(path).absolute()
return fingerprint(path, (path,))
def recovery_tree(path):
path = Path(path).absolute()
roots = tuple(path / stage / name for stage in ('ready', 'failed') for name in ('codigo', 'deploy'))
return fingerprint(path, roots)
def copy_preserved(source, target):
inspect = code_tree if Path(source).name in ('codigo', 'deploy') else tree
inspect(source)
dev.run(['cp', '-a', '--', source, target])
if inspect(source) != inspect(target):
raise RuntimeError('copy content or permissions differ')
for path in target.rglob('*'):
if stat.S_ISREG(path.lstat().st_mode):
with path.open('rb') as stream:
os.fsync(stream.fileno())
for path in [*target.rglob('*'), target]:
if stat.S_ISDIR(path.lstat().st_mode):
sync_directory(path)
def no_host_users(path):
if not path.exists():
return
result = subprocess.run(['lsof', '-t', '+D', str(path)], capture_output=True, text=True)
if result.stdout.strip() or result.stderr.strip() or result.returncode not in (0, 1):
raise RuntimeError('host processes or incomplete lsof visibility prevent writer exclusion')
def check_http():
opener = build_opener(ProxyHandler({}))
for path in ('/', '/health'):
with opener.open('http://127.0.0.1:18080' + path, timeout=10) as response:
if response.status != 200:
raise RuntimeError('laboratory HTTP availability failed')
def swap(root, work, name):
"""Resume either rename without overwriting preserved or staged directories."""
ready, active, failed = work / 'ready' / name, root / name, work / 'failed' / name
if any(path.is_symlink() for path in (ready, active, failed)):
raise RuntimeError('linked swap path')
if ready.is_dir() and active.is_dir() and not failed.exists():
os.rename(active, failed)
sync_directory(root)
sync_directory(failed.parent)
if ready.is_dir() and not active.exists() and failed.is_dir():
os.rename(ready, active)
sync_directory(ready.parent)
sync_directory(root)
if ready.exists() or not active.is_dir() or not failed.is_dir():
raise RuntimeError('ambiguous interrupted swap: ' + name)
class LabReset:
def __init__(self, base=dev.BASE, api=dev, copier=copy_preserved, *, operation):
if not re.fullmatch(r'[0-9a-f]{32}', operation):
raise RuntimeError('invalid incident operation ID')
self.operation = operation
self.base, self.api, self.copy = base, api, copier
self.root = base / PROJECT
self.archive = self.root / '.archive' / operation
self.backup = base / '.backups' / PROJECT / operation
self.work = base / ('.reset-18080-' + operation)
def identity(self):
for path in (self.base, self.root, self.archive, self.backup):
if path.resolve() != path.absolute() or not path.is_dir():
raise RuntimeError('missing or linked incident directory')
failed = host.read_record(self.root)
if self.work.exists():
if self.work.is_symlink():
raise RuntimeError('linked recovery directory')
failed = json.loads((self.work / 'failed-record.json').read_text())
recovery_tree(self.work)
if (failed.get('project') != PROJECT or failed.get('port') != 18080
or failed.get('operation_id') != self.operation or failed.get('revision') != ORIGINAL
or failed.get('status') != 'update_failed'
or failed.get('phase') != 'recalculation-and-persistence'):
raise RuntimeError('incident identity differs')
candidate = failed.get('target_revision')
images = failed.get('target_images')
gitlinks = failed.get('target_gitlinks')
if not isinstance(candidate, str) or not re.fullmatch(r'[0-9a-f]{40}', candidate):
raise RuntimeError('invalid incident candidate revision')
pattern = re.escape(PROJECT + '-' + candidate[:12] + '-') + r'[0-9a-f]{32}'
if (not isinstance(images, list) or len(images) != 2
or not all(isinstance(image, str) for image in images)
or not images[0].startswith('isssteleon/webapi:')
or not re.fullmatch(pattern, images[0].removeprefix('isssteleon/webapi:'))
or images[1] != images[0].replace('isssteleon/webapi:', 'isssteleon/webapp:', 1)
or not isinstance(gitlinks, dict) or 'ISSSTELEON' not in gitlinks
or not all(isinstance(k, str) and isinstance(v, str) and re.fullmatch(r'[0-9a-f]{40}', v)
for k, v in gitlinks.items())
or failed.get('backup') != str(self.backup)
or failed.get('archive') != str(self.archive)):
raise RuntimeError('incident candidate evidence differs')
if (self.archive / 'installation.json').is_symlink():
raise RuntimeError('linked archived record')
original = json.loads((self.archive / 'installation.json').read_text())
if (original.get('project') != PROJECT or original.get('port') != 18080
or original.get('status') != 'installed' or original.get('revision') != ORIGINAL
or original.get('gitlinks') != failed.get('gitlinks')
or original.get('images') != failed.get('images')):
raise RuntimeError('original provenance differs')
self.failed, self.original = failed, original
tree(self.backup)
manifest = data_guard.verify_backup(self.backup)
if manifest['origin'] != {key: original[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images')}:
raise RuntimeError('backup provenance differs')
# Installer backups normalize committed WAL into standalone SQLite files.
for name in manifest['sqlite_files']:
if any((self.backup / 'data' / (name + suffix)).exists() for suffix in ('-wal', '-shm', '-journal')):
raise RuntimeError('backup is not the normalized pre-activation snapshot')
code_tree(self.archive / 'codigo')
code_tree(self.archive / 'deploy')
self.image_ids = {}
for image in original['images']:
self.image_ids[image] = self.api.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
if not self.image_ids[image]:
raise RuntimeError('original image missing')
return failed, original, manifest
def stopped(self):
no_host_users(self.root / 'data')
if self.work.exists():
no_host_users(self.work)
ids = self.api.run(['docker', 'ps', '-aq', '--no-trunc']).split()
items = json.loads(self.api.run(['docker', 'inspect', *ids])) if ids else []
own = []
for item in items:
labels = item.get('Config', {}).get('Labels') or {}
ours = labels.get('com.docker.compose.project') == PROJECT
for mount in item.get('Mounts', []):
source = Path(mount.get('Source', '/'))
if source == self.root or source.is_relative_to(self.root) or self.root.is_relative_to(source):
if not ours:
raise RuntimeError('foreign container can access laboratory')
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
if not ours and any(str(binding.get('HostPort')) == '18080'
for values in bindings.values() for binding in (values or [])):
raise RuntimeError('foreign port owner')
if ours:
service = labels.get('com.docker.compose.service')
if service not in ('webapi', 'webapp', 'indicadores') or service in own:
raise RuntimeError('unexpected laboratory service')
own.append(service)
allowed = set(self.original['images'] + self.failed.get('target_images', []))
if item.get('Config', {}).get('Image') not in allowed:
raise RuntimeError('unexpected laboratory image identity')
mounts = item.get('Mounts', [])
if service == 'webapp':
if mounts:
raise RuntimeError('unexpected frontend mount')
elif (len(mounts) != 1 or mounts[0].get('Type') != 'bind'
or mounts[0].get('Source') != str(self.root / 'data')
or mounts[0].get('Destination') != '/data' or mounts[0].get('RW') is not True):
raise RuntimeError('unexpected writer storage mount')
if item.get('State', {}).get('Running') is not False:
raise RuntimeError('laboratory writers must be stopped before check/apply')
if not self.work.exists() and set(own) != {'webapi', 'webapp', 'indicadores'}:
raise RuntimeError('initial laboratory containers are incomplete')
return items
def configuration(self, deploy, original):
cmd = self.api.compose(PROJECT, deploy)
config = json.loads(self.api.run([*cmd, 'config', '--format', 'json']))
tag = original['images'][0].removeprefix('isssteleon/webapi:')
if self.api.verify_config(config, PROJECT, self.root / 'data', tag, 18080) is not None:
raise RuntimeError('the laboratory reset supports only the three-service composition')
if any(set(service) & {'post_start', 'pre_stop', 'develop', 'secrets', 'configs',
'volumes_from', 'external_links', 'use_api_socket'}
for service in config['services'].values()):
raise RuntimeError('unsupported Compose lifecycle hooks')
if any(network.get('external') for network in config.get('networks', {}).values()):
raise RuntimeError('external recovery networks are not allowed')
return conservative.controlled_config(config)
def validate_storage(self, original, manifest):
contract = conservative.guard(self.api, original['images'][0], 'contract', {})
if contract != manifest['contract']:
raise RuntimeError('original image contract differs from backup')
def run(self, mode):
failed, original, manifest = self.identity()
if self.work.exists() and (self.work / 'complete').exists():
active = host.read_record(self.root)
if active.get('status') != 'installed' or active.get('revision') != ORIGINAL:
raise RuntimeError('completed reset no longer matches active record')
self.api.verify_existing_containers(original, self.base, '')
self.api.verify_services(self.api.compose(PROJECT, self.root / 'deploy'), 18080)
check_http()
return 'already recovered'
if self.work.exists() and not (self.work / 'prepared').exists():
raise RuntimeError('preparation interrupted before swaps; retain this work directory under another name and retry')
inspection = self.stopped()
self.validate_storage(original, manifest)
with tempfile.TemporaryDirectory(prefix='lab-18080-check-') as tmp:
data_guard.restore_backup(self.backup, Path(tmp) / 'data')
config = self.configuration(self.archive / 'deploy', original)
if mode == 'check':
return 'eligible; backup restored in isolation, images/configuration verified, no writers'
if not self.work.exists():
# Refuse cross-filesystem swaps before preserving any active directory.
if any((self.root / name).stat().st_dev != self.base.stat().st_dev for name in ('codigo', 'deploy', 'data')):
raise RuntimeError('active paths must share the recovery filesystem')
for name in ('codigo', 'deploy', 'data'):
(tree if name == 'data' else code_tree)(self.root / name)
self.work.mkdir(mode=0o700)
for name, value in (('failed-record.json', failed), ('containers.json', inspection)):
with (self.work / name).open('x', encoding='utf-8') as stream:
json.dump(value, stream)
stream.flush()
os.fsync(stream.fileno())
sync_directory(self.work)
(self.work / 'ready').mkdir()
(self.work / 'failed').mkdir()
try:
if not (self.work / 'prepared').exists():
if any((self.work / 'ready').iterdir()) or any((self.work / 'failed').iterdir()):
raise RuntimeError('incomplete preparation retained; inspect recovery directory before retry')
for name in ('codigo', 'deploy'):
self.copy(self.archive / name, self.work / 'ready' / name)
self.copy(self.backup / 'data', self.work / 'ready' / 'data')
data_guard.verify_backup(self.backup)
conservative.persist_config(self.work / 'ready' / 'deploy', config)
shutil.copystat(self.archive / 'deploy' / 'docker-compose.yml',
self.work / 'ready' / 'deploy' / 'docker-compose.yml')
if os.name == 'posix':
with (self.work / 'ready' / 'deploy' / 'docker-compose.yml').open('rb') as stream:
os.fsync(stream.fileno())
marker(self.work / 'prepared')
self.stopped()
for name in ('codigo', 'deploy', 'data'):
if (name == 'data' and (self.work / 'failed' / name).exists()
and (self.work / 'ready' / name).exists() and (self.root / name).exists()):
if tree(self.work / 'ready' / name) != tree(self.backup / 'data'):
raise RuntimeError('interrupted data preparation differs from backup')
os.rename(self.root / name, self.work / ('attempt-data-' + uuid.uuid4().hex))
sync_directory(self.work)
swap(self.root, self.work, name)
if tree(self.root / 'data') != tree(self.backup / 'data'):
self.copy(self.backup / 'data', self.work / 'ready' / 'data')
os.rename(self.root / 'data', self.work / ('attempt-data-' + uuid.uuid4().hex))
sync_directory(self.work)
swap(self.root, self.work, 'data')
# Verify the restored inventory before any application can write.
if tree(self.root / 'data') != tree(self.backup / 'data'):
raise RuntimeError('restored storage differs; preserve recovery directory for manual review')
cmd = self.api.compose(PROJECT, self.root / 'deploy')
effective = self.configuration(self.root / 'deploy', original)
baseline = data_guard.storage_state(self.root / 'data', manifest['contract'])
self.api.run([*cmd, 'up', '-d', '--force-recreate', '--no-build', '--pull', 'never'])
self.api.verify_services(cmd, 18080)
check_http()
verified_ids = self.api.verify_existing_containers(original, self.base, '')
conservative.current_environment(self.api, verified_ids, effective)
before = data_guard.storage_state(self.root / 'data', manifest['contract'])
for domain in data_guard.DOMAINS:
if before['databases'][domain]['tables'] != manifest['state']['databases'][domain]['tables']:
raise RuntimeError('restored database contents changed during startup')
# Permit only the updater's existing marker/audit-file policy. All table
# contents, including derived tables, were compared exactly above.
data_guard.verify_state(self.root / 'data', manifest['contract'], baseline, derived=True)
ids = self.api.run(['docker', 'ps', '-q', '--filter', 'label=com.docker.compose.project=' + PROJECT]).split()
items = json.loads(self.api.run(['docker', 'inspect', *ids]))
if len(items) != 3 or any(item['Image'] != self.image_ids[original['images'][
1 if item['Config']['Labels']['com.docker.compose.service'] == 'webapp' else 0]] for item in items):
raise RuntimeError('original image IDs changed')
for item in items:
name = item['Config']['Labels']['com.docker.compose.service']
expected_policy = effective['services'][name].get('restart', 'no').split(':')
policy = item.get('HostConfig', {}).get('RestartPolicy', {})
retries = int(expected_policy[1]) if len(expected_policy) == 2 else 0
if policy.get('Name') != expected_policy[0] or policy.get('MaximumRetryCount', 0) != retries:
raise RuntimeError('service restart policy differs from verified configuration')
if name in ('webapi', 'indicadores') and (
item['Config'].get('Entrypoint') != effective['services'][name]['entrypoint']
or item['Config'].get('Cmd') not in (None, [])):
raise RuntimeError('service startup command differs from verified configuration')
host.write_record(self.root, dict(original, recovery_incident=str(self.work)))
marker(self.work / 'complete')
return 'recovered and verified; status=installed'
except BaseException:
try:
cmd = self.api.compose(PROJECT, self.root / 'deploy')
conservative.freeze_failed(self.api, cmd, PROJECT, self.root / 'data')
finally:
host.write_record(self.root, dict(failed, recovery='lab reset incomplete; inspect ' + str(self.work)))
raise
@contextmanager
def installer_lock(base):
import fcntl
path = base / '.install.lock'
if path.is_symlink() or not path.is_file():
raise RuntimeError('existing installer lock required')
with path.open('r') as stream:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('mode', choices=('check', 'apply'))
parser.add_argument('--operation', required=True, help='operation ID from the failed installation record')
args = parser.parse_args()
try:
if os.name != 'posix' or os.geteuid() != 0 or socket.gethostname().split('.')[0] != 'labserver':
raise RuntimeError('run as root on labserver with the local Docker daemon')
info = json.loads(dev.run(['docker', 'info', '--format', '{{json .}}']))
if info.get('Name', '').split('.')[0] != 'labserver' or info.get('OSType') != 'linux':
raise RuntimeError('Docker daemon must be local labserver/Linux')
with installer_lock(dev.BASE):
print(LabReset(operation=args.operation).run(args.mode))
except Exception as exc:
print('Laboratory reset failed; category=' + type(exc).__name__ + '; ' + str(exc), file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
+240
View File
@@ -0,0 +1,240 @@
"""Docker resources of one installation, and the checks that decide whether they are its own.
Nothing here changes Docker; every function only lists and inspects. An installation owns the containers,
the notebook jobs volume and the default network of its Compose project, matched by label, exact name and use.
Anything that touches its storage, volume, network or port without being one of those refuses the plan.
"""
import json
import posixpath
import re
import composition
import proc
PROJECT_LABEL = 'com.docker.compose.project'
HELPER_LABEL = 'isssteleon.dev-installer'
HELPER_PREFIX = 'isssteleon-prepare-'
SERVICES = composition.BASE_SERVICES + (composition.NOTEBOOK_SERVICE,) + composition.PROFILE_SERVICES
PLAN_KEYS = ('id', 'name', 'service', 'image', 'mounts')
def daemon_path(path):
"""A daemon-host path as text with `/` separators, so paths compare the same wherever this runs."""
return posixpath.normpath(str(path).replace('\\', '/'))
def overlaps(source, root):
source = daemon_path(source)
return source == root or source.startswith(root + '/') or root.startswith(source.rstrip('/') + '/')
def inspect_all():
ids = proc.run(['docker', 'ps', '-aq', '--no-trunc']).split()
return json.loads(proc.run(['docker', 'inspect', *ids])) if ids else []
def is_helper(item, base):
"""A locked helper container of this installer: its name, label and single mount of the base directory."""
labels = item.get('Config', {}).get('Labels') or {}
mounts = item.get('Mounts') or []
return (item.get('Name', '').startswith('/' + HELPER_PREFIX) and labels.get(HELPER_LABEL) == 'helper'
and len(mounts) == 1 and mounts[0].get('Type') == 'bind'
and daemon_path(mounts[0].get('Source', '')) == daemon_path(base)
and mounts[0].get('Destination') == '/host')
def mount_shape(mount):
key = 'Name' if mount.get('Type') == 'volume' else 'Source'
return {'type': mount.get('Type'), key.lower(): mount.get(key), 'target': mount.get('Destination')}
def published_ports(item):
bindings = (item.get('HostConfig') or {}).get('PortBindings') or {}
return sorted({str(b.get('HostPort')) for values in bindings.values() for b in (values or [])})
def volume_identity(project, *, missing_ok=False):
"""The Compose-created local volume holding this installation's notebook jobs, or None if absent."""
name = composition.notebook_volume_name(project)
if name not in proc.run(['docker', 'volume', 'ls', '-q', '--filter', 'name=' + name]).split():
if missing_ok:
return None
raise RuntimeError('notebook jobs volume is missing')
items = json.loads(proc.run(['docker', 'volume', 'inspect', name]))
if len(items) != 1:
raise RuntimeError('notebook jobs volume identity is not verifiable')
volume = items[0]
labels = volume.get('Labels') or {}
mountpoint = volume.get('Mountpoint')
if (volume.get('Name') != name or volume.get('Driver') != 'local' or volume.get('Scope') != 'local'
or volume.get('Options') or labels.get(PROJECT_LABEL) != project
or labels.get('com.docker.compose.volume') != composition.NOTEBOOK_VOLUME
or not isinstance(mountpoint, str) or not mountpoint.startswith('/')
or not isinstance(volume.get('CreatedAt'), str) or not volume['CreatedAt']):
raise RuntimeError('notebook jobs volume identity is not verifiable')
return {'name': name, 'created': volume['CreatedAt'], 'mountpoint': posixpath.normpath(mountpoint)}
def classify(items, project, base):
"""Split containers into the project's and everyone else's; a lookalike without the label refuses."""
own, foreign = [], []
for item in items:
if is_helper(item, base):
continue
labels = item.get('Config', {}).get('Labels') or {}
name = item.get('Name', '')
if labels.get(PROJECT_LABEL) == project:
own.append(item)
elif name.startswith('/' + project + '-'):
raise RuntimeError(f'container {name.lstrip("/")} looks like the project without its label')
else:
foreign.append(item)
return own, foreign
def check_foreign(foreign, project, port, base):
"""Refuse any other container that reaches the installation's storage, volume or network, or holds its port."""
root = daemon_path(base) + '/' + project
volume, network = composition.notebook_volume_name(project), project + '_default'
for item in foreign:
label = item.get('Name', '').lstrip('/')
for mount in item.get('Mounts') or []:
if mount.get('Name') == volume or overlaps(mount.get('Source') or '/', root):
raise RuntimeError(f'container {label} shares the installation storage')
if network in ((item.get('NetworkSettings') or {}).get('Networks') or {}):
raise RuntimeError(f'container {label} shares the installation network')
if str(port) in published_ports(item):
raise RuntimeError(f'container {label} holds port {port}')
def own_containers(own, project, base, image_ids):
"""Summaries of the project's containers; each must be a known service, use only its own mounts and image."""
root = daemon_path(base) + '/' + project
data, volume, network = root + '/data', composition.notebook_volume_name(project), project + '_default'
pattern = re.compile('/' + re.escape(project) + '-(' + '|'.join(SERVICES) + r')-(\d+|run-[0-9a-f]{12})')
allowed = ({'type': 'bind', 'source': data, 'target': '/data'},
{'type': 'volume', 'name': volume, 'target': composition.NOTEBOOK_JOBS})
result = []
for item in own:
name = item.get('Name', '')
match = pattern.fullmatch(name)
if not match or item['Config']['Labels'].get('com.docker.compose.service') != match.group(1):
raise RuntimeError(f'project container has an unexpected name or service: {name.lstrip("/")}')
mounts = sorted((mount_shape(m) for m in item.get('Mounts') or []), key=json.dumps)
for mount in mounts:
if mount.get('source') is not None:
mount['source'] = daemon_path(mount['source'])
if any(mount not in allowed for mount in mounts):
raise RuntimeError(f'project container mounts a path outside the installation: {name.lstrip("/")}')
if set((item.get('NetworkSettings') or {}).get('Networks') or {}) - {network, 'none'}:
raise RuntimeError(f'project container joins another network: {name.lstrip("/")}')
if image_ids is not None and item.get('Image') not in image_ids:
raise RuntimeError(f'project container does not use an image of the installation record: {name.lstrip("/")}')
result.append({'id': item['Id'], 'name': name.lstrip('/'), 'service': match.group(1),
'image': item.get('Image'), 'mounts': mounts,
'state': (item.get('State') or {}).get('Status'), 'ports': published_ports(item)})
return sorted(result, key=lambda c: c['name'])
def volume_names(project):
"""Names of the volumes labelled with the project or starting with its prefix."""
labelled = set(proc.run(['docker', 'volume', 'ls', '-q', '--filter', f'label={PROJECT_LABEL}={project}']).split())
named = {name for name in proc.run(['docker', 'volume', 'ls', '-q']).split() if name.startswith(project + '_')}
return labelled | named
def project_volumes(project):
"""The notebook jobs volume if it exists; any other volume of the project or with its prefix refuses."""
expected = composition.notebook_volume_name(project)
names = volume_names(project)
if names - {expected}:
raise RuntimeError('unexpected volume of the project: ' + ', '.join(sorted(names - {expected})))
return [volume_identity(project)] if expected in names else []
def project_networks(project, own_ids):
"""The project's default network if it exists, attached only by the project's own containers."""
expected = project + '_default'
listing = proc.run(['docker', 'network', 'ls', '--no-trunc', '--format', '{{.ID}} {{.Name}}']).splitlines()
labelled = set(proc.run(['docker', 'network', 'ls', '-q', '--no-trunc', '--filter',
f'label={PROJECT_LABEL}={project}']).split())
found = [line.split(None, 1) for line in listing if len(line.split(None, 1)) == 2]
candidates = {ident for ident, name in found if name == expected or name.startswith(project + '_')} | labelled
result = []
for ident in sorted(candidates):
item = json.loads(proc.run(['docker', 'network', 'inspect', ident]))[0]
labels = item.get('Labels') or {}
if (item.get('Name') != expected or labels.get(PROJECT_LABEL) != project
or labels.get('com.docker.compose.network') != 'default' or item.get('Driver') != 'bridge'):
raise RuntimeError(f'network {item.get("Name")} is not the project default network')
if set(item.get('Containers') or {}) - own_ids:
raise RuntimeError(f'network {expected} has containers outside the project')
result.append({'id': item['Id'], 'name': item['Name']})
return result
def discover(project, port, base, image_ids):
"""Everything Docker holds for the project, checked. `image_ids` are the image IDs of the installation record;
a container using another image is not part of it."""
own, foreign = classify(inspect_all(), project, base)
check_foreign(foreign, project, port, base)
containers = own_containers(own, project, base, image_ids)
return {'containers': containers, 'volumes': project_volumes(project),
'networks': project_networks(project, {item['Id'] for item in own})}
def plan_view(found):
"""The part of `discover` that belongs in a plan: identities, not volatile state."""
return {'containers': [{key: c[key] for key in PLAN_KEYS} for c in found['containers']],
'volumes': found['volumes'], 'networks': found['networks']}
def assert_absent(project, port, base):
"""A project that is about to be installed owns nothing in Docker, and nobody else holds its port."""
own, foreign = classify(inspect_all(), project, base)
check_foreign(foreign, project, port, base)
if own or volume_names(project) or project_networks(project, set()):
raise RuntimeError(f'Docker already holds resources of {project}')
def image_ids(images):
"""Image IDs of the recorded tags; a missing image is an error, not an empty set."""
ids = set()
for image in images:
ids.add(proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip())
if not ids or not all(ids):
raise RuntimeError('a recorded image was not found')
return ids
def verify_running(project, port, base, images, notebooks):
"""After an installation: exactly the expected services run, on the recorded images and mounts, and only the
web app publishes the port."""
api_id, app_id = (proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
for image in images)
found = discover(project, port, base, {api_id, app_id})
services = {}
for item in found['containers']:
if item['service'] in services or item['service'] in composition.PROFILE_SERVICES:
raise RuntimeError('unexpected container in the Compose project')
services[item['service']] = item
expected = set(composition.BASE_SERVICES) | ({composition.NOTEBOOK_SERVICE} if notebooks else set())
if set(services) != expected:
raise RuntimeError('missing or unexpected Compose project containers')
root = daemon_path(base) + '/' + project
data = {'type': 'bind', 'source': root + '/data', 'target': '/data'}
jobs = {'type': 'volume', 'name': composition.notebook_volume_name(project), 'target': composition.NOTEBOOK_JOBS}
for name, item in services.items():
if item['state'] != 'running':
raise RuntimeError(f'{name} is not running')
wanted = {'webapi': [data] + ([jobs] if notebooks else []), 'indicadores': [data],
'notebooks': [jobs], 'webapp': []}[name]
if sorted(item['mounts'], key=json.dumps) != sorted(wanted, key=json.dumps):
raise RuntimeError(f'{name} mounts do not match')
wanted_image = app_id if name == 'webapp' else api_id
if item['image'] != wanted_image:
raise RuntimeError(f'{name} image does not match the installation record')
if item['ports'] != ([str(port)] if name == 'webapp' else []):
raise RuntimeError(f'{name} publishes unexpected ports')
return found
+131
View File
@@ -0,0 +1,131 @@
"""Reference resolution and composition checkout, against local Git repositories (see gitfixture.py).
Fixtures: `Fixture` builds an outer repository on branch `dev` pinning ISSSTELEON, which pins WebApi, WebApp and
models (which pins the EEG library at `libs/tea`), with the submodule URLs redirected to local copies for the duration
of each test.
"""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import composition
import gitfixture
class Fixture(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.fx = gitfixture.build(self.tmp.name)
patcher = patch.dict(os.environ, self.fx['env'])
patcher.start()
self.addCleanup(patcher.stop)
self.remote = self.fx['url']
self.checkout_dir = Path(self.tmp.name) / 'checkout'
class ResolveTests(Fixture):
def test_branch_tag_and_commit_resolve_to_commits(self):
"""Fails if a branch, a lightweight or annotated tag, or a full SHA stops resolving to its commit."""
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
gitfixture.git(outer, 'tag', 'light', env=self.fx['env'])
gitfixture.git(outer, 'tag', '-a', 'annotated', '-m', 'release', env=self.fx['env'])
for reference, kind in (('dev', 'branch'), ('light', 'tag'), ('annotated', 'tag')):
with self.subTest(reference):
resolved = composition.resolve_reference(reference, self.remote)
self.assertEqual((resolved['kind'], resolved['commit']), (kind, self.fx['outer']))
resolved = composition.resolve_reference(self.fx['outer'], self.remote)
self.assertEqual((resolved['kind'], resolved['commit']), ('commit', self.fx['outer']))
def test_unknown_ambiguous_and_malformed_references_are_refused(self):
"""Fails if a missing name, a name that is both branch and tag, an abbreviated SHA or a ref path is accepted."""
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
gitfixture.git(outer, 'tag', 'dev', env=self.fx['env'])
with self.assertRaisesRegex(ValueError, 'both a branch and a tag'):
composition.resolve_reference('dev', self.remote)
with self.assertRaisesRegex(ValueError, 'not a branch or a tag'):
composition.resolve_reference('missing', self.remote)
for bad in ('', ' ', self.fx['outer'][:12], self.fx['outer'].upper(), 'refs/heads/dev', '-x', '@', 'a b',
'a..b', 'x.lock'):
with self.subTest(bad), self.assertRaises(ValueError):
composition.resolve_reference(bad, self.remote)
class CheckoutTests(Fixture):
def test_composition_lists_the_exact_gitlinks(self):
"""Fails if the composition omits the outer commit, the dev-data pin or any application gitlink."""
resolved = composition.resolve_reference('dev', self.remote)
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
self.assertEqual(comp['commit'], self.fx['outer'])
self.assertEqual(comp['application'], self.fx['ISSSTELEON'])
self.assertEqual(comp['gitlinks'], {
'WorkingNarrative': self.fx['outer'], 'dev-data': self.fx['dev-data'],
'ISSSTELEON': self.fx['ISSSTELEON'], 'WebApi': self.fx['WebApi'], 'WebApp': self.fx['WebApp'],
'models': self.fx['models'], 'models/libs/tea': self.fx['tea']})
def test_a_reference_that_moved_since_resolution_is_refused(self):
"""Fails if the checkout silently takes a newer commit than the one that was resolved and approved."""
resolved = composition.resolve_reference('dev', self.remote)
gitfixture.advance(self.fx)
with self.assertRaisesRegex(RuntimeError, 'moved from'):
composition.checkout(resolved, self.checkout_dir, self.remote)
def test_commit_reference_checks_out_that_commit_only(self):
"""Fails if a full SHA checks out the branch tip instead of the requested commit."""
gitfixture.advance(self.fx)
resolved = composition.resolve_reference(self.fx['outer'], self.remote)
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
self.assertEqual(comp['commit'], self.fx['outer'])
def test_untrusted_submodule_origin_is_refused(self):
"""Fails if a gitlink whose URL is not the institutional one is initialised."""
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
gitfixture.git(outer, 'config', '-f', '.gitmodules', 'submodule.ISSSTELEON.url',
'ssh://git@example.invalid/x/ISSSTELEON.git', env=self.fx['env'])
gitfixture.git(outer, 'commit', '-q', '-am', 'redirect', env=self.fx['env'])
resolved = composition.resolve_reference('dev', self.remote)
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin'):
composition.checkout(resolved, self.checkout_dir, self.remote)
def test_the_eeg_library_is_trusted_only_at_its_own_origin(self):
"""Fails if the library's gitlink is initialised from any URL but alberto/tea, or refused at that one."""
models = Path(self.tmp.name) / 'remotes' / 'models.git'
gitfixture.git(models, 'config', '-f', '.gitmodules', 'submodule.tea.url',
'ssh://git@10.0.10.41:2222/alberto/other.git', env=self.fx['env'])
gitfixture.git(models, 'commit', '-q', '-am', 'redirect the library', env=self.fx['env'])
application = Path(self.tmp.name) / 'remotes' / 'ISSSTELEON.git'
gitfixture.git(application / 'models', 'pull', '-q', 'origin', 'dev', env=self.fx['env'])
gitfixture.git(application, 'commit', '-q', '-am', 'move models', env=self.fx['env'])
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
gitfixture.git(outer / 'ISSSTELEON', 'pull', '-q', 'origin', 'dev', env=self.fx['env'])
gitfixture.git(outer, 'commit', '-q', '-am', 'move ISSSTELEON', env=self.fx['env'])
resolved = composition.resolve_reference('dev', self.remote)
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin: ISSSTELEON/models/libs/tea'):
composition.checkout(resolved, self.checkout_dir, self.remote)
def test_export_contains_every_pinned_tree(self):
"""Fails if the exported source lacks a pinned application's files, which the image builds need."""
resolved = composition.resolve_reference('dev', self.remote)
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
export = Path(self.tmp.name) / 'export'
composition.export_tree(self.checkout_dir / 'ISSSTELEON', comp['application'], export)
for path in ('dist/docker-compose.yml', 'WebApi/Dockerfile', 'WebApp/Dockerfile', 'models/Dockerfile',
'models/libs/tea/pyproject.toml'):
self.assertTrue((export / path).is_file(), path)
class PortTests(unittest.TestCase):
def test_protected_and_out_of_range_ports_are_refused(self):
"""Fails if a protected port (including the reference installations 18090, 18096 and 18097), a privileged or
an oversized port, or non-numeric text is accepted."""
for bad in ('18087', '4397', '18090', '18096', '18097', '80', '70000', 'abc', '', '18083.5'):
with self.subTest(bad), self.assertRaises(ValueError):
composition.validate_port(bad)
self.assertEqual(composition.validate_port('18083'), 18083)
if __name__ == '__main__':
unittest.main()
-949
View File
@@ -1,949 +0,0 @@
"""Conservative updates against temporary SQLite files and a simulated Docker adapter.
The fixture has four versioned databases, protected patients, mutable projections,
historical reports, an artifact and an existing archive. No daemon is contacted.
"""
from contextlib import closing
import copy
import csv
import json
import os
from pathlib import Path
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
import conservative
import data_guard as guard
import dev
import host
HEADS = {'cacu': 'b4f2d8c01e23', 'cama': 'c5a3e9d12f34',
'tea': 'a3e1c7b90d12', 'governance': 'e7c5a1f34b56'}
def fixture(base, project='isssteleon-old', port=18080):
"""Create synthetic witnesses and derive an independent expected schema before mutations."""
root = base / project
for name in ('codigo', 'deploy', 'data'):
(root / name).mkdir(parents=True)
(root / 'codigo' / 'version.txt').write_text('old')
contract = {}
for domain in guard.DOMAINS:
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
connection.executescript("""
CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY NOT NULL);
CREATE TABLE patient (id INTEGER PRIMARY KEY, value TEXT NOT NULL, document BLOB);
CREATE UNIQUE INDEX patient_value ON patient(value);
CREATE TABLE persona (id INTEGER PRIMARY KEY, value TEXT);
CREATE TABLE measure_report (id INTEGER PRIMARY KEY, value TEXT);
INSERT INTO patient VALUES (1, 'SYNTHETIC-WITNESS', X'010203');
INSERT INTO persona VALUES (1, 'original projection');
INSERT INTO measure_report VALUES (1, 'historical report');
""")
connection.execute('INSERT INTO alembic_version VALUES (?)', (HEADS[domain],))
connection.commit()
contract[domain] = {'head': HEADS[domain], 'known': [HEADS[domain]],
'schema': guard.schema(connection)}
contract['governance']['known'].append('d6b4f0e23a45')
(root / 'data' / 'mlflow-artefactos').mkdir()
(root / 'data' / 'mlflow-artefactos' / 'model.bin').write_bytes(b'synthetic-model')
with closing(sqlite3.connect(root / 'data' / 'mlflow.db')) as connection:
connection.executescript("CREATE TABLE runs (id INTEGER PRIMARY KEY, value TEXT);"
"INSERT INTO runs VALUES (1, 'synthetic registered model');")
(root / 'data' / 'reportes').mkdir()
(root / 'data' / 'reportes' / 'imports.jsonl').write_text('{"synthetic":true}\n')
(root / 'data' / 'empty-directory').mkdir()
(root / '.archive' / 'previous' / 'data').mkdir(parents=True)
(root / '.archive' / 'previous' / 'data' / 'keep').write_text('historical archive')
record = {'project': project, 'port': port, 'revision': 'a' * 40,
'gitlinks': {'ISSSTELEON': 'b' * 40}, 'status': 'installed',
'images': ['isssteleon/webapi:old', 'isssteleon/webapp:old']}
host.write_record(root, record)
return root, contract, record
def change(root, domain, sql):
"""Modify only a temporary fixture database for a rejection or worker scenario."""
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
connection.execute(sql)
connection.commit()
class GuardTests(unittest.TestCase):
def setUp(self):
"""Reserve a private directory containing four synthetic databases."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base)
self.data = self.root / 'data'
def test_known_heads_and_structures_are_read_only(self):
"""Fail if compatible inspection changes any SQLite bytes or file identity."""
before = {p.name: guard.digest(p) for p in self.data.glob('*.db')}
state = guard.inspect_databases(self.data, self.contract)
self.assertEqual(state['directory'], guard.identity(self.data))
self.assertEqual(before, {p.name: guard.digest(p) for p in self.data.glob('*.db')})
@unittest.skipUnless(os.name == 'nt', 'requires Windows directory ACLs')
def test_stopped_wal_reader_when_directory_forbids_sidecars(self):
"""Fail if closing the WAL writer makes a read-only post-stop inspection fail."""
sid = '*' + next(csv.reader(subprocess.check_output(
['whoami', '/user', '/fo', 'csv', '/nh'], text=True).splitlines()))[1]
db = sqlite3.connect(self.data / 'cama.db')
db.execute('PRAGMA journal_mode=WAL')
db.execute("INSERT INTO patient VALUES (2, 'wal witness', NULL)")
db.commit()
acl = subprocess.run(['icacls', str(self.data), '/deny', sid + ':(WD,AD)'], capture_output=True)
if acl.returncode:
db.close()
self.skipTest('cannot set temporary directory ACL')
try:
guard.inspect_databases(self.data, self.contract)
db.close()
self.assertFalse((self.data / 'cama.db-wal').exists())
with self.assertRaises(RuntimeError) as error:
guard.inspect_databases(self.data, self.contract)
self.assertEqual(getattr(error.exception, 'sqlite_errorname', None), 'SQLITE_CANTOPEN')
guard.inspect_databases(self.data, self.contract, quiesced=True)
finally:
db.close()
subprocess.run(['icacls', str(self.data), '/remove:d', sid], check=True, capture_output=True)
def test_quiesced_fallback_never_ignores_wal(self):
"""Fail if the post-stop fallback reads an immutable main file while a WAL exists."""
(self.data / 'cama.db-wal').write_bytes(b'committed pages')
failure = sqlite3.OperationalError('cannot open')
failure.sqlite_errorname = 'SQLITE_CANTOPEN'
original = guard.readonly
def open_db(path, **kwargs):
if path.name == 'cama.db':
raise failure
return original(path, **kwargs)
with patch.object(guard, 'readonly', side_effect=open_db), self.assertRaises(sqlite3.OperationalError):
guard.inspect_databases(self.data, self.contract, quiesced=True)
def test_quiesced_inspection_reads_committed_wal_rows(self):
"""Fail if post-stop inspection ignores committed rows still present in a WAL."""
with closing(sqlite3.connect(self.data / 'cama.db')) as db:
db.execute('PRAGMA journal_mode=WAL')
db.execute('PRAGMA wal_autocheckpoint=0')
db.execute("INSERT INTO patient VALUES (2, 'wal witness', NULL)")
db.commit()
state = guard.inspect_databases(self.data, self.contract, rows=True, quiesced=True)
self.assertEqual(state['databases']['cama']['tables']['patient']['count'], 2)
def test_verify_reads_live_recalculation_wal(self):
"""Verification sees committed projection changes in WAL with the writer still open."""
before = guard.storage_state(self.data, self.contract)
path = self.data / 'cacu.db'
with closing(sqlite3.connect(path)) as writer:
writer.execute('PRAGMA journal_mode=WAL')
writer.execute('PRAGMA wal_autocheckpoint=0')
writer.execute("UPDATE persona SET value='recalculated'")
writer.commit()
self.assertTrue(Path(str(path) + '-wal').is_file())
original = guard.digest(path)
after = guard.verify_state(self.data, self.contract, before, derived=True)
self.assertNotEqual(before['databases']['cacu']['tables']['persona']['sha256'],
after['databases']['cacu']['tables']['persona']['sha256'])
self.assertEqual(original, guard.digest(path))
@unittest.skipUnless(os.name == 'nt', 'requires Windows file ACLs')
def test_quiesced_inspection_rejects_unreadable_database(self):
"""Fail if the fallback bypasses denied database file permissions."""
sid = '*' + next(csv.reader(subprocess.check_output(
['whoami', '/user', '/fo', 'csv', '/nh'], text=True).splitlines()))[1]
path = self.data / 'cama.db'
if subprocess.run(['icacls', str(path), '/deny', sid + ':(RD)'], capture_output=True).returncode:
self.skipTest('cannot set temporary database ACL')
try:
with self.assertRaises((RuntimeError, OSError, sqlite3.Error)):
guard.inspect_databases(self.data, self.contract, quiesced=True)
finally:
subprocess.run(['icacls', str(path), '/remove:d', sid], check=True, capture_output=True)
def test_missing_database_is_not_created(self):
"""Fail if a missing database is silently replaced by an empty SQLite file."""
(self.data / 'tea.db').unlink()
with self.assertRaisesRegex(RuntimeError, 'missing'):
guard.inspect_databases(self.data, self.contract)
self.assertFalse((self.data / 'tea.db').exists())
def test_unknown_revision_is_rejected_without_changes(self):
"""Fail if an unknown historical revision is accepted or rewritten."""
change(self.root, 'tea', "UPDATE alembic_version SET version_num='047529ced337'")
before = guard.digest(self.data / 'tea.db')
with self.assertRaisesRegex(RuntimeError, 'unknown'):
guard.inspect_databases(self.data, self.contract)
self.assertEqual(guard.digest(self.data / 'tea.db'), before)
def test_validator_emits_safe_specific_rejection(self):
"""Fail if an unknown revision is hidden or its actual value leaks from the subprocess."""
change(self.root, 'tea', "UPDATE alembic_version SET version_num='private-revision-value'")
payload = json.dumps({'data': str(self.data), 'contract': self.contract})
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'inspect'],
input=payload, text=True, capture_output=True)
self.assertEqual(result.returncode, 1)
self.assertNotIn('private-revision-value', result.stderr)
failure = subprocess.CalledProcessError(result.returncode, ['private'], stderr=result.stderr)
detail = conservative.failure_detail(failure)
self.assertIn('reason=migration_revision_unknown, domain=tea', detail)
self.assertNotIn('private-revision-value', detail)
def test_sqlite_error_classification_discards_sensitive_text(self):
"""Fail if SQLite diagnostic codes disappear or raw exception messages are emitted."""
exc = sqlite3.OperationalError('secret SQL and private file')
exc.sqlite_errorname = 'SQLITE_READONLY_CANTINIT'
exc.inspection_domain = 'cacu'
diagnostic = guard.inspection_diagnostic(exc)
self.assertEqual(diagnostic['sqlite'], 'SQLITE_READONLY_CANTINIT')
self.assertEqual(diagnostic['domain'], 'cacu')
self.assertNotIn('secret', json.dumps(diagnostic))
def test_recalculation_stdout_cannot_corrupt_result(self):
"""Fail if Python or native stdout makes a successful one-shot response invalid JSON."""
package = self.base / 'webapi'
package.mkdir()
(package / '__init__.py').write_text('')
(package / 'indicadores_vivos.py').write_text(
'import os\n'
'class ColaDeRecalculo:\n'
' def tomar(self, domain): print("private witness")\n'
' def correr(self, domain):\n'
' os.write(1, b"native private witness\\n")\n'
' return {"estado": "ok"}\n'
' def pendientes(self): return []\n')
env = dict(os.environ, PYTHONPATH=str(self.base))
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'recalculate'],
input=json.dumps({'environment': {}}), text=True, capture_output=True, env=env)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout), {'completed': ['cacu', 'cama', 'tea']})
self.assertNotIn('private witness', result.stdout)
def test_recalculation_rejection_identifies_domain_without_data(self):
"""Fail if a failed domain is hidden or private worker errors reach diagnostics."""
package = self.base / 'webapi'
package.mkdir()
(package / '__init__.py').write_text('')
(package / 'indicadores_vivos.py').write_text(
'class ColaDeRecalculo:\n'
' def tomar(self, domain): pass\n'
' def correr(self, domain):\n'
' if domain == "cama": raise ValueError("private clinical data")\n'
' return {"estado": "ok"}\n')
env = dict(os.environ, PYTHONPATH=str(self.base))
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'recalculate'],
input=json.dumps({'environment': {}}), text=True, capture_output=True, env=env)
self.assertEqual(result.returncode, 1)
detail = conservative.failure_detail(subprocess.CalledProcessError(1, ['private'], stderr=result.stderr))
self.assertIn('domain=cama', detail)
self.assertIn('stage=execute', detail)
self.assertIn('type=ValueError', detail)
self.assertNotIn('clinical', detail + result.stderr)
def test_diagnostic_parser_rejects_untrusted_error_text(self):
"""Fail if crafted subprocess output can inject arbitrary text into workflow diagnostics."""
fake = {'reason': 'secret patient', 'domain': 'tea', 'type': 'RuntimeError',
'sqlite': 'none', 'errno': None}
error = subprocess.CalledProcessError(1, ['private'],
stderr='WN_INSPECT_DIAGNOSTIC=' + json.dumps(fake))
self.assertEqual(conservative.failure_detail(error), 'exit=1')
def test_pending_governance_drop_is_rejected(self):
"""Fail if the recognized predecessor of the destructive revision is admitted."""
change(self.root, 'governance', "UPDATE alembic_version SET version_num='d6b4f0e23a45'")
with self.assertRaisesRegex(RuntimeError, 'pending migrations'):
guard.inspect_databases(self.data, self.contract)
def test_schema_drift_and_unversioned_databases_are_rejected(self):
"""Fail if a head stamp hides a missing index, column or version table."""
for sql in ('DROP INDEX patient_value', 'ALTER TABLE patient ADD COLUMN unexpected TEXT',
'DROP TABLE alembic_version',
'CREATE TRIGGER unexpected AFTER INSERT ON patient BEGIN DELETE FROM persona; END',
'CREATE INDEX descending_value ON patient(value DESC)'):
with self.subTest(sql=sql):
other = self.base / ('case-' + str(len(list(self.base.iterdir()))))
other.mkdir()
root, contract, _ = fixture(other)
change(root, 'cacu', sql)
with self.assertRaises(RuntimeError):
guard.inspect_databases(root / 'data', contract)
def test_backup_restore_preserves_rows_artifacts_and_empty_directories(self):
"""Fail if a verified isolated restore loses witnesses, blobs, artifacts or directories."""
backup = self.base / 'backup'
guard.create_backup(self.data, backup, self.contract, self.record)
restored = self.base / 'restored'
guard.restore_backup(backup, restored)
with closing(guard.readonly(restored / 'tea.db')) as connection:
self.assertEqual(connection.execute('SELECT value, document FROM patient').fetchone(),
('SYNTHETIC-WITNESS', b'\x01\x02\x03'))
self.assertEqual((restored / 'mlflow-artefactos' / 'model.bin').read_bytes(), b'synthetic-model')
self.assertTrue((restored / 'empty-directory').is_dir())
with self.assertRaisesRegex(RuntimeError, 'must be new'):
guard.restore_backup(backup, self.data)
def test_wal_backup_includes_committed_pages(self):
"""Fail if the backup copies only the main SQLite file and misses committed WAL rows."""
connection = sqlite3.connect(self.data / 'tea.db')
self.addCleanup(connection.close)
connection.execute('PRAGMA journal_mode=WAL')
connection.execute('PRAGMA wal_autocheckpoint=0')
connection.execute("INSERT INTO patient VALUES (2,'WAL-WITNESS',NULL)")
connection.commit()
self.assertTrue((self.data / 'tea.db-wal').exists())
backup = self.base / 'wal-backup'
guard.create_backup(self.data, backup, self.contract, self.record)
with closing(guard.readonly(backup / 'data' / 'tea.db')) as copy_db:
self.assertEqual(copy_db.execute('SELECT count(*) FROM patient').fetchone()[0], 2)
self.assertFalse((backup / 'data' / 'tea.db-wal').exists())
def test_corrupted_backup_is_rejected(self):
"""Fail if checksum verification accepts changed artifacts before restoration."""
backup = self.base / 'backup'
guard.create_backup(self.data, backup, self.contract, self.record)
(backup / 'data' / 'mlflow-artefactos' / 'model.bin').write_bytes(b'changed')
with self.assertRaisesRegex(RuntimeError, 'checksum'):
guard.restore_backup(backup, self.base / 'restored')
self.assertFalse((self.base / 'restored').exists())
def test_worker_changes_are_scoped_and_history_is_retained(self):
"""Allow declared projections and appended reports while rejecting clinical loss."""
before = guard.storage_state(self.data, self.contract)
change(self.root, 'cacu', "UPDATE persona SET value='recomputed'")
change(self.root, 'cacu', "INSERT INTO measure_report VALUES (2,'new report')")
with self.assertRaisesRegex(RuntimeError, 'persistent rows changed'):
guard.verify_state(self.data, self.contract, before)
guard.verify_state(self.data, self.contract, before, derived=True)
change(self.root, 'cacu', "UPDATE patient SET value='unexpected change'")
with self.assertRaisesRegex(RuntimeError, 'patient'):
guard.verify_state(self.data, self.contract, before, derived=True)
def test_derived_check_rejects_loss_of_historical_reports(self):
"""Fail if an unchanged report count conceals replacement of a historical row."""
before = guard.storage_state(self.data, self.contract)
change(self.root, 'cacu', "UPDATE measure_report SET value='replacement'")
with self.assertRaisesRegex(RuntimeError, 'historical rows'):
guard.verify_state(self.data, self.contract, before, derived=True)
def test_unknown_persistent_file_is_protected(self):
"""Fail if the derived allowlist hides deletion of an unrelated persistent file."""
path = self.data / 'custom.bin'
path.write_bytes(b'custom witness')
before = guard.storage_state(self.data, self.contract)
path.unlink()
with self.assertRaisesRegex(RuntimeError, 'persistent file'):
guard.verify_state(self.data, self.contract, before, derived=True)
def test_only_sqlite_sidecars_are_excluded(self):
"""Fail if a filename suffix silently excludes a regular persistent file from backup."""
(self.data / 'notes').write_text('ordinary file')
(self.data / 'notes-wal').write_text('ordinary auxiliary witness')
backup = self.base / 'backup'
guard.create_backup(self.data, backup, self.contract, self.record)
restored = self.base / 'restore'
guard.restore_backup(backup, restored)
self.assertEqual((restored / 'notes-wal').read_text(), 'ordinary auxiliary witness')
with closing(guard.readonly(restored / 'mlflow.db')) as db:
self.assertEqual(db.execute('SELECT value FROM runs').fetchone()[0], 'synthetic registered model')
def test_backup_rejects_a_writer_that_changes_storage(self):
"""Fail if a changing source can be certified as a quiesced backup."""
original = guard.sqlite_digest
changed = False
def concurrent_write(path):
nonlocal changed
if Path(path).parent.name == 'data' and not changed:
changed = True
(self.data / 'concurrent-writer').write_text('unexpected writer')
return original(path)
with patch.object(guard, 'sqlite_digest', side_effect=concurrent_write), \
self.assertRaisesRegex(RuntimeError, 'changed while'):
guard.create_backup(self.data, self.base / 'backup', self.contract, self.record)
def test_backup_and_restore_reject_nested_destinations(self):
"""Fail if recursive copying can include its own destination or mutate a verified backup."""
with self.assertRaisesRegex(RuntimeError, 'outside persistent'):
guard.create_backup(self.data, self.data / 'nested', self.contract, self.record)
backup = self.base / 'backup'
guard.create_backup(self.data, backup, self.contract, self.record)
with self.assertRaisesRegex(RuntimeError, 'outside the backup'):
guard.restore_backup(backup, backup / 'data' / 'nested')
def test_missing_empty_backup_directory_is_detected(self):
"""Fail if checksum-only validation overlooks loss of an empty persistent directory."""
backup = self.base / 'backup'
guard.create_backup(self.data, backup, self.contract, self.record)
(backup / 'data' / 'empty-directory').rmdir()
with self.assertRaisesRegex(RuntimeError, 'directory inventory'):
guard.verify_backup(backup)
class SimulatedDeployment:
"""Use real host/data guards and synthetic files while substituting every Docker command."""
def __init__(self, root, contract, record):
self.root, self.contract, self.record = root, contract, record
self.calls = []
self.revision = 'c' * 40
self.fail = None
self.mount_changed = False
self.finished = False
self.running = {name: True for name in ('worker', 'api', 'app')}
self.active_runs = self.training_runs = 0
# What the `mlflow-store` guard reports about data/mlflow.db.
self.mlflow = {'exists': True, 'revision': 'dc11669786a5', 'production': 0}
gunicorn = ('/app/WebApi/.venv/bin/python -m gunicorn --bind 0.0.0.0:5000 --workers 2 --timeout 600 '
'--access-logfile - webapi:create_app()')
# What `docker top` lists per original container, and the API's `/proc/net/tcp` rows past the header.
self.processes = {'worker': ['/app/WebApi/.venv/bin/python -m webapi.indicadores_vivos'],
'api': [gunicorn, gunicorn], 'app': [],
'runner': ['/app/WebApi/.venv/bin/python -m models notebooks serve']}
self.connections = []
self.configure = dev.configure
self.compose = dev.compose
self.verify_config = dev.verify_config
self.env = {**conservative.PERSISTENT_ENV,
'ISSSTELEON_VERSION': record['images'][0].removeprefix('isssteleon/webapi:'),
'ISSSTELEON_DATOS': str(root / 'data'), 'ISSSTELEON_PUERTO': str(record['port']),
'KEEP_THIS': 'unchanged', 'WEBAPI_TIMEOUT': '42'}
(root / 'deploy' / '.env').write_text('\n'.join(k + '=' + v for k, v in self.env.items()))
(root / 'deploy' / 'docker-compose.yml').write_text(json.dumps(self.config(self.env)))
def config(self, env):
service = {'image': 'isssteleon/webapi:' + env['ISSSTELEON_VERSION'],
'environment': dict(env),
'volumes': [{'type': 'bind', 'source': str(self.root / 'data'), 'target': '/data'}]}
return {'name': self.record['project'], 'services': {
'webapi': copy.deepcopy(service), 'indicadores': copy.deepcopy(service),
'webapp': {'image': 'isssteleon/webapp:' + env['ISSSTELEON_VERSION'],
'ports': [{'published': str(self.record['port']), 'target': 80}]}}}
def git(self, root, *args):
return self.revision if args[0] == 'rev-parse' else '160000 commit ' + 'd' * 40 + '\tISSSTELEON'
def export_tree(self, repo, revision, source, manifest):
(source / 'dist').mkdir(parents=True)
(source / 'dist' / 'docker-compose.yml').write_text('{}')
(source / 'version.txt').write_text(self.revision)
manifest.update(self.pinned_manifest(repo, revision))
def pinned_manifest(self, repo, revision):
return {'ISSSTELEON': revision, 'WebApi': 'e' * 40, 'WebApp': 'f' * 40,
'models': '1' * 40, 'indicadores_kit': '2' * 40}
def run(self, args, **kwargs):
args = list(map(str, args))
self.calls.append(args)
if args[:2] == ['docker', 'top']:
rows = [f'{pid} {command}' for pid, command in enumerate(self.processes[args[2]], 100)]
return '\n'.join(['PID COMMAND', *rows]) + '\n'
if args[:2] == ['docker', 'exec'] and '/proc/net/tcp' in args:
rows = [f' {n}: {row}' for n, row in enumerate(self.connections)]
return '\n'.join([' sl local_address rem_address st tx_queue rx_queue', *rows]) + '\n'
if args[:2] == ['docker', 'build'] and self.fail == 'build':
raise RuntimeError('synthetic build failure')
if 'config' in args:
directory = Path(args[args.index('--project-directory') + 1])
env = dict(line.split('=', 1) for line in (directory / '.env').read_text().splitlines()
if '=' in line and not line.startswith('#'))
env = {k: v.strip("'") for k, v in env.items()}
return json.dumps(self.config(env))
if args[:2] == ['docker', 'inspect']:
if '--format' in args:
return json.dumps({'Running': self.running[args[-1]]})
return json.dumps([{'Id': ident, 'Image': 'old-image', 'Mounts': [],
'State': {'Running': self.running[ident]},
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}},
'Config': {'Labels': {'com.docker.compose.service': name},
'Env': [k + '=' + v for k, v in self.env.items()] + ['INDICADORES_AL_INICIAR=0'],
'Entrypoint': (['/app/WebApi/.venv/bin/python', '-m', 'gunicorn',
'--bind', '0.0.0.0:5000', '--workers', '2',
'--timeout', '600', '--access-logfile', '-',
'webapi:create_app()'] if name == 'webapi' else
['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']),
'Cmd': []}}
for ident, name in zip(('worker', 'api', 'app'), ('indicadores', 'webapi', 'webapp'))])
if args[:2] == ['docker', 'stop']:
self.running[args[-1]] = False
if args[:2] == ['docker', 'start']:
self.running[args[-1]] = True
if 'up' in args and args[-1] == 'webapi' and self.fail == 'cutover':
raise RuntimeError('synthetic cutover failure')
if 'up' in args and args[-1] in ('indicadores', 'webapp') and not self.finished:
raise AssertionError('regular services cannot start before checked recalculation')
return ''
def host_action(self, helper, action, project, value):
if action == 'lookup':
return json.dumps(host.find_installation(self.root.parent, int(value), missing_ok=True))
if action == 'update-space' and self.fail == 'space':
raise RuntimeError('synthetic space failure')
if action == 'read-deploy':
return json.dumps({name: (self.root / 'deploy' / name).read_text()
for name in ('.env', 'docker-compose.yml')})
if action == 'prepare-backup':
if self.fail == 'backup-preparation':
raise PermissionError('synthetic preparation failure')
host.prepare_backup(self.root.parent, project, json.loads(value)['verify_restore'])
if action == 'save':
host.write_record(self.root, json.loads(value))
elif action == 'backup':
if self.fail == 'backup':
raise RuntimeError('synthetic backup failure')
return json.dumps(host.backup_installation(self.root.parent, project, json.loads(value)))
elif action == 'verify-restore':
if self.fail == 'restore':
raise RuntimeError('synthetic restore verification failure')
return str(host.verify_isolated_restore(self.root.parent, project, value))
elif action == 'stage':
host.stage_installation(self.root.parent, project, value)
elif action == 'activate':
payload = json.loads(value)
return str(host.activate_installation(self.root.parent, project,
payload['operation_id'], payload['previous']))
return ''
def copy_to_host(self, helper, source, project, destination):
shutil.copytree(source, self.root / destination)
def verify_existing_containers(self, record, base, helper):
if self.mount_changed:
raise RuntimeError('data mount does not match')
return ['worker', 'api', 'app']
def verify_services(self, cmd, port, notebooks=False):
record = host.read_record(self.root)
if not self.finished and record['status'] != 'update_failed' and record['revision'] != self.revision:
raise RuntimeError('worker completion was not verified')
def guard(self, api, image, action, payload, data=None, **kwargs):
if action == 'contract':
return self.contract
if action == 'runtime':
return {'worker': 'webapi.recomputation'}
if action == 'notebook-runs':
return {'active': self.active_runs, 'training': self.training_runs}
if action == 'mlflow-store':
return dict(self.mlflow)
if action == 'mlflow-heads':
return {'heads': ['dc11669786a5']}
if action == 'inspect':
return guard.inspect_databases(self.root / 'data', self.contract)
if action == 'verify':
return guard.verify_state(self.root / 'data', self.contract, payload['before'],
derived=payload.get('derived', False))
if action == 'recalculate':
if self.fail == 'worker':
change(self.root, 'tea', "UPDATE patient SET value='lost value'")
else:
change(self.root, 'tea', "UPDATE persona SET value='expected derived change'")
with closing(sqlite3.connect(self.root / 'data' / 'tea.db')) as connection:
next_id = connection.execute('SELECT max(id)+1 FROM measure_report').fetchone()[0]
connection.execute('INSERT INTO measure_report VALUES (?,?)', (next_id, 'new report'))
connection.commit()
self.finished = True
return {'completed': ['cacu', 'cama', 'tea']}
raise AssertionError(action)
class UpdateTests(unittest.TestCase):
def setUp(self):
"""Prepare a managed synthetic installation and retain its original data identity."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
self.original_identity = guard.identity(self.root / 'data')
def execute(self):
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
def test_update_keeps_original_data_and_all_components(self):
"""Fail if complete code replacement moves data, drops witnesses or rewrites operator settings."""
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['result'], 'updated')
self.assertEqual(record['phase'], 'complete')
self.assertEqual(set(record['gitlinks']), {'ISSSTELEON', 'WebApi', 'WebApp', 'models', 'indicadores_kit'})
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), self.runtime.revision)
self.assertEqual((Path(record['archive']) / 'codigo' / 'version.txt').read_text(), 'old')
self.assertFalse((Path(record['archive']) / 'data').exists())
self.assertEqual((self.root / '.archive' / 'previous' / 'data' / 'keep').read_text(), 'historical archive')
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
self.assertEqual(config['services']['webapi']['environment']['KEEP_THIS'], 'unchanged')
self.assertNotIn('alembic', str(config['services']['webapi']['entrypoint']))
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
self.assertEqual(host.find_installation(self.base, 18080)['project'], self.record['project'])
guard.restore_backup(Path(record['backup']), self.base / 'isolated-restore')
def test_same_revision_and_next_revision_preserve_witnesses(self):
"""Fail if repeating a release or changing only code resets databases."""
for revision in ('c' * 40, 'c' * 40, 'f' * 40):
self.runtime.revision = revision
self.execute()
self.record = host.read_record(self.root)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
with closing(guard.readonly(self.root / 'data' / 'cacu.db')) as connection:
self.assertEqual(connection.execute('SELECT value FROM patient').fetchone()[0], 'SYNTHETIC-WITNESS')
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
def test_missing_unknown_and_pending_sources_abort_before_stop(self):
"""Fail if missing data or incompatible versions reach the quiescing phase."""
for kind in ('missing', 'unknown', 'governance'):
with self.subTest(kind=kind), tempfile.TemporaryDirectory() as tmp:
root, contract, record = fixture(Path(tmp))
runtime = SimulatedDeployment(root, contract, record)
if kind == 'missing':
(root / 'data' / 'tea.db').unlink()
else:
domain = 'governance' if kind == 'governance' else 'tea'
version = 'd6b4f0e23a45' if kind == 'governance' else 'unknown'
change(root, domain, "UPDATE alembic_version SET version_num='" + version + "'")
with patch.object(conservative, 'guard', side_effect=runtime.guard), self.assertRaises(RuntimeError):
conservative.update(runtime, record, 'helper', Path('/source'), Path(tmp))
self.assertFalse(any('stop' in args for args in runtime.calls))
self.assertEqual(host.read_record(root), record)
self.assertFalse((root.parent / '.backups').exists())
def test_build_failure_and_changed_mount_do_not_touch_running_installation(self):
"""Fail if preparation errors stop services or alter the installed record."""
for failure in ('build', 'mount', 'space', 'backup-preparation'):
self.runtime.fail = failure
self.runtime.mount_changed = failure == 'mount'
with self.subTest(failure=failure), self.assertRaises(RuntimeError):
self.execute()
self.assertFalse(any('stop' in args for args in self.runtime.calls))
self.assertEqual(host.read_record(self.root), self.record)
def test_backup_destinations_are_prepared_and_probed(self):
"""Fail if destination preparation omits restore or leaves its write probe behind."""
host.prepare_backup(self.base, self.record['project'], True)
for name in ('.backups', '.restores'):
directory = self.base / name / self.record['project']
self.assertTrue(directory.is_dir())
self.assertEqual(list(directory.iterdir()), [])
def test_invalid_backup_parent_does_not_stop_services(self):
"""Fail if an unusable backup parent is discovered only after stopping services."""
(self.base / '.backups').write_text('not a directory')
with self.assertRaises(RuntimeError):
self.execute()
self.assertFalse(any('stop' in args for args in self.runtime.calls))
self.assertEqual(host.read_record(self.root), self.record)
def test_cutover_failure_retains_backup_original_data_and_recovery_record(self):
"""Fail if a startup failure loses storage or is recorded as a successful update."""
self.runtime.fail = 'cutover'
with self.assertRaisesRegex(RuntimeError, 'during api'):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
self.assertEqual(record['revision'], self.record['revision'])
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
guard.verify_backup(Path(record['backup']))
self.assertTrue((Path(record['archive']) / 'deploy' / '.env').is_file())
def test_backup_failure_never_activates_candidate_code(self):
"""Fail if an unverified backup allows code activation or loses the original payload."""
self.runtime.fail = 'backup'
with self.assertRaisesRegex(RuntimeError, 'during backup'):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
self.assertFalse((self.root / '.updates').exists())
self.assertIn(str(self.base / '.backups'), record['backup'])
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
self.assertTrue(all(self.runtime.running.values()))
starts = [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'start']]
self.assertEqual(starts, ['api', 'worker', 'app'])
def test_recovery_rejects_changed_container(self):
"""Fail if a changed container is started or the failed installation is marked installed."""
self.runtime.fail = 'backup'
original_run = self.runtime.run
def changed(args, **kwargs):
output = original_run(args, **kwargs)
if list(map(str, args))[:2] == ['docker', 'inspect'] and '--format' not in args:
items = json.loads(output)
if not any(self.runtime.running.values()):
items[0]['Mounts'] = [{'Source': '/unexpected'}]
return json.dumps(items)
return output
self.runtime.run = changed
with self.assertRaises(RuntimeError):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
self.assertIn('incomplete', record['recovery'])
self.assertFalse(any(args[:2] == ['docker', 'start'] for args in self.runtime.calls))
def test_recovery_rejects_unverified_api_entrypoint(self):
"""Fail if recovery restarts an API whose entrypoint could run migrations."""
self.runtime.fail = 'backup'
original_run = self.runtime.run
def legacy(args, **kwargs):
output = original_run(args, **kwargs)
if list(map(str, args))[:2] == ['docker', 'inspect'] and '--format' not in args:
items = json.loads(output)
items[1]['Config']['Entrypoint'] = ['/app/entrypoint.sh']
return json.dumps(items)
return output
self.runtime.run = legacy
with self.assertRaises(RuntimeError):
self.execute()
self.assertIn('incomplete', host.read_record(self.root)['recovery'])
self.assertFalse(any(args[:2] == ['docker', 'start'] for args in self.runtime.calls))
def test_recovery_attempted_when_failure_record_cannot_be_saved(self):
"""Fail if a record write error prevents original services from being restarted."""
self.runtime.fail = 'backup'
original = self.runtime.host_action
def action(helper, name, project, value):
if name == 'save' and json.loads(value)['status'] == 'update_failed':
raise OSError('record write failed')
return original(helper, name, project, value)
self.runtime.host_action = action
with self.assertRaisesRegex(RuntimeError, 'failure record could not be saved'):
self.execute()
self.assertTrue(all(self.runtime.running.values()))
self.assertEqual(host.read_record(self.root)['status'], 'updating')
def test_backup_helper_reports_safe_failure_metadata(self):
"""Fail if a helper error loses its location or exposes stderr and command contents."""
stderr = ('Traceback (most recent call last):\n'
' File "<string>", line 320, in create_backup\n'
" secret patient data\nPermissionError: [Errno 13] private-path\n")
failure = subprocess.CalledProcessError(7, ['secret-command'], stderr=stderr)
original = self.runtime.host_action
def action(helper, name, project, value):
if name == 'backup':
raise failure
return original(helper, name, project, value)
self.runtime.host_action = action
with self.assertRaises(RuntimeError) as raised:
self.execute()
message = str(raised.exception)
self.assertIn('operation=create and verify backup in helper', message)
self.assertIn('exit=7, location=create_backup:320, error type=PermissionError, errno=13', message)
self.assertNotIn('patient', message)
self.assertNotIn('private-path', message)
self.assertNotIn('secret-command', message)
self.assertIs(raised.exception.__context__, failure)
self.assertTrue(raised.exception.__suppress_context__)
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
def test_guard_reports_safe_subprocess_metadata(self):
"""Fail if the quiesced inspection drops the exit code or prints sensitive stderr."""
failure = subprocess.CalledProcessError(3, ['private'], stderr='RuntimeError: patient secret')
with patch.object(self.runtime, 'run', side_effect=failure), self.assertRaises(conservative.GuardFailure) as raised:
conservative.guard(self.runtime, 'image', 'inspect', {})
self.assertIn('exit=3, error type=RuntimeError', str(raised.exception))
self.assertNotIn('patient secret', str(raised.exception))
def test_quiesced_rejection_reaches_update_error_without_activation(self):
"""Fail if post-stop validation loses its safe reason or permits code activation."""
calls = 0
diagnostic = {'reason': 'schema_mismatch', 'domain': 'tea', 'type': 'RuntimeError',
'sqlite': 'none', 'errno': None}
failure = subprocess.CalledProcessError(1, ['private'], stderr=(
'WN_INSPECT_DIAGNOSTIC=' + json.dumps(diagnostic) + '\nprivate patient secret'))
original_guard = conservative.guard
def validate_with_transport(api, image, action, payload, data=None, **kwargs):
nonlocal calls
if action == 'inspect':
calls += 1
if calls == 2:
adapter = types.SimpleNamespace(run=lambda *a, **kw: (_ for _ in ()).throw(failure))
return original_guard(adapter, image, action, payload, data)
return self.runtime.guard(api, image, action, payload, data, **kwargs)
with patch.object(conservative, 'guard', side_effect=validate_with_transport), \
self.assertRaises(RuntimeError) as raised:
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base)
self.assertIn('operation=inspect quiesced storage', str(raised.exception))
self.assertIn('reason=schema_mismatch, domain=tea', str(raised.exception))
self.assertNotIn('patient secret', str(raised.exception))
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
self.assertFalse((self.root / '.updates').exists())
def test_guard_inspection_uses_existing_image_and_readonly_mount(self):
"""Fail if a diagnostic inspection pulls an image or permits writes to storage."""
with patch.object(self.runtime, 'run', return_value='{}') as run:
conservative.guard(self.runtime, 'candidate', 'inspect', {}, self.base / 'data')
args = run.call_args.args[0]
self.assertEqual(args[args.index('--pull') + 1], 'never')
self.assertEqual(args[args.index('--network') + 1], 'none')
self.assertIn('--read-only', args)
self.assertTrue(args[args.index('--mount') + 1].endswith(',dst=/data,readonly'))
def test_restore_helper_reports_safe_failure_metadata(self):
"""Fail if isolated restore errors hide their location or expose helper stderr."""
failure = subprocess.CalledProcessError(
1, ['private'], stderr=' File "<string>", line 376, in restore_backup\n'
'RuntimeError: secret filename\n')
original = self.runtime.host_action
def action(helper, name, project, value):
if name == 'verify-restore':
raise failure
return original(helper, name, project, value)
self.runtime.host_action = action
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
self.assertRaises(RuntimeError) as raised:
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
verify_restore=True)
self.assertIn('operation=restore and verify backup in helper', str(raised.exception))
self.assertIn('exit=1, location=restore_backup:376, error type=RuntimeError', str(raised.exception))
self.assertNotIn('secret filename', str(raised.exception))
self.assertEqual(host.read_record(self.root)['phase'], 'restore-verification')
def test_trial_restore_is_verified_before_activation(self):
"""Fail if a trial activates code before restoring and verifying its backup."""
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
verify_restore=True)
record = host.read_record(self.root)
self.assertTrue((Path(record['restore_check']) / 'cacu.db').is_file())
self.assertEqual(record['result'], 'updated')
def test_trial_restore_failure_keeps_old_code_and_backup(self):
"""Fail if a rejected isolated restore can activate the replacement application."""
self.runtime.fail = 'restore'
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'), \
self.assertRaisesRegex(RuntimeError, 'restore-verification'):
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
verify_restore=True)
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
guard.verify_backup(Path(record['backup']))
self.assertFalse((self.root / '.updates').exists())
def test_custom_connection_is_rejected_before_build_or_stop(self):
"""Fail if a custom database connection is redirected to the managed SQLite layout."""
self.runtime.env['TEA_DATABASE_URL'] = 'sqlite:////custom/tea.db'
with self.assertRaisesRegex(RuntimeError, 'during preparing'):
self.execute()
self.assertFalse(any('stop' in args or 'build' in args for args in self.runtime.calls))
self.assertEqual(host.read_record(self.root), self.record)
def test_worker_cannot_turn_clinical_loss_into_success(self):
"""Fail if successful health/recalculation responses hide changed protected patient values."""
self.runtime.fail = 'worker'
with self.assertRaisesRegex(RuntimeError, 'operation=verify-persistence'):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
restored = self.base / 'recoverable'
guard.restore_backup(Path(record['backup']), restored)
with closing(guard.readonly(restored / 'tea.db')) as connection:
self.assertEqual(connection.execute('SELECT value FROM patient').fetchone()[0], 'SYNTHETIC-WITNESS')
def test_recalculation_step_categories_and_no_retry(self):
"""Fail if any recalculation step loses its category, exposes details, or repeats a write."""
deploy = self.base / 'steps'
deploy.mkdir()
config = deploy / 'docker-compose.yml'
for step in ('load-configuration', 'execute-recalculation', 'validate-result', 'verify-persistence'):
with self.subTest(step=step):
config.write_text('invalid private secret' if step == 'load-configuration' else
json.dumps({'services': {'indicadores': {'environment': {}}}}))
calls = []
def run_guard(api, image, action, payload, data=None, **kwargs):
calls.append(action)
if action == 'recalculate':
if step == 'execute-recalculation':
raise conservative.GuardFailure('recalculate', 'exit=1, type=OperationalError')
if step == 'validate-result':
return {'completed': ['cacu']}
return {'completed': ['cacu', 'cama', 'tea']}
if action == 'verify' and payload.get('derived') and step == 'verify-persistence':
raise conservative.GuardFailure('verify', 'exit=1, type=DatabaseError')
return {}
with patch.object(conservative, 'verify_api'), patch.object(conservative, 'guard', side_effect=run_guard), \
self.assertRaises(conservative.RecalculationFailure) as raised:
conservative.finish(types.SimpleNamespace(run=lambda *a: ''), [], 'image',
deploy, self.root / 'data', {}, {})
self.assertEqual(raised.exception.step, step)
self.assertNotIn('private secret', raised.exception.category)
self.assertLessEqual(calls.count('recalculate'), 1)
def test_guard_transport_is_readonly_and_has_no_application_entrypoint(self):
"""Fail if compatibility inspection starts the image entrypoint or permits storage writes."""
calls = []
adapter = types.SimpleNamespace(run=lambda args, **kwargs: calls.append((args, kwargs)) or '{}')
conservative.guard(adapter, 'image', 'inspect', {'contract': {}}, Path('/srv/data'))
args, kwargs = calls[0]
self.assertIn('type=bind,src=' + str(Path('/srv/data')) + ',dst=/data,readonly', args)
self.assertIn('--read-only', args)
self.assertEqual(args[args.index('--entrypoint') + 1], '/app/WebApi/.venv/bin/python')
self.assertIn('contract', kwargs['stdin'])
def test_resolved_worker_environment_keeps_literal_values(self):
"""Fail if Compose or docker env-file quoting changes a retained worker value."""
deploy = self.base / 'resolved'
deploy.mkdir()
environment = {**conservative.PERSISTENT_ENV, 'TOKEN': "literal $value and 'quotes'"}
conservative.persist_config(deploy, {'services': {'indicadores': {'environment': environment}}})
document = json.loads((deploy / 'docker-compose.yml').read_text())
self.assertEqual(document['services']['indicadores']['environment']['TOKEN'], "literal $$value and 'quotes'")
calls = []
def guard_call(api, image, action, payload, data=None, **kwargs):
if action == 'verify':
self.assertTrue(kwargs.get('writable'), 'live SQLite requires writable WAL coordination')
calls.append((action, payload))
return {'completed': ['cacu', 'cama', 'tea']} if action == 'recalculate' else {}
with patch.object(conservative, 'verify_api'), patch.object(conservative, 'guard', side_effect=guard_call):
conservative.finish(types.SimpleNamespace(run=lambda args: ''), ['compose'], 'image',
deploy, self.root / 'data', {}, {})
recalc = next(payload for action, payload in calls if action == 'recalculate')
self.assertEqual(recalc['environment'], environment)
def test_failure_containment_checks_ownership_before_stopping(self):
"""Fail if uncertain ownership or mounts can stop a foreign container during recovery."""
calls = []
item = {'Config': {'Labels': {'com.docker.compose.project': self.record['project'],
'com.docker.compose.service': 'webapi'}},
'Mounts': [{'Type': 'bind', 'Source': '/foreign', 'Destination': '/data'}]}
def run(args):
calls.append(args)
return json.dumps([item]) if args[:2] == ['docker', 'inspect'] else 'candidate\n'
adapter = types.SimpleNamespace(run=run)
with self.assertRaisesRegex(RuntimeError, 'storage is uncertain'):
conservative.freeze_failed(adapter, ['compose'], self.record['project'], self.root / 'data')
self.assertFalse(any('stop' in args for args in calls))
item['Mounts'][0]['Source'] = str(self.root / 'data')
conservative.freeze_failed(adapter, ['compose'], self.record['project'], self.root / 'data')
self.assertIn(['docker', 'stop', 'candidate'], calls)
if __name__ == '__main__':
unittest.main()
+342
View File
@@ -0,0 +1,342 @@
"""Loading the simulated hospital into an installed instance, against the in-memory daemon of test_installer.py.
Fixtures: `LoadCase` extends `FlowCase` with a stand-in for the Git fetches of the loader sources, a loader that
prints one count line per table and a hospital check that reports two tables per project (`good_hospital`); each
test starts from an instance installed on port 18083.
"""
import contextlib
import io
import json
import re
import subprocess
import unittest
from unittest.mock import patch
import dataload
import fakedocker
import registry
from test_installer import BASE, FlowCase
LOADER_OUTPUT = ('Paciente: 300 leídas, 300 nuevas, 0 actualizadas, 0 rechazadas\n'
'Citologia: 779 leídas, 779 nuevas, 0 actualizadas, 0 rechazadas\n')
def good_hospital(**changes):
"""What the hospital check prints for a hospital that has, per project, the tables of LOADER_OUTPUT with rows;
`changes` maps a project to the entry that replaces its own."""
tables = {'paciente': {'target': 'Paciente', 'exists': True, 'rows': 300, 'missing_columns': []},
'citologia': {'target': 'Citologia', 'exists': True, 'rows': 779, 'missing_columns': []}}
report = {name: {'database': database, 'tables': json.loads(json.dumps(tables))}
for name, database in dataload.PROJECTS}
report.update(changes)
return report
class LoadCase(FlowCase):
def setUp(self):
super().setUp()
self.fetched = []
self.hospital = good_hospital()
self.docker.loader_output = lambda args: LOADER_OUTPUT
self.docker.hospital_report = lambda args: json.dumps(self.hospital)
for module, name, value in ((dataload, 'fetch_tree', self.fetch_tree), (dataload.time, 'sleep', lambda s: None)):
patcher = patch.object(module, name, value)
patcher.start()
self.addCleanup(patcher.stop)
self.install(18083)
def fetch_tree(self, remote, commit, directory, paths=()):
self.fetched.append((remote, commit, tuple(paths)))
directory.mkdir(parents=True, exist_ok=True)
(directory / 'Dockerfile').write_text('FROM scratch')
def load(self, confirmation='', hospital='10.0.10.41:9505', port=18083):
out = io.StringIO()
with contextlib.redirect_stdout(out):
dataload.run_load(str(port), hospital, confirmation, base=BASE, host_factory=self.host)
return out.getvalue()
def load_token(self, **kwargs):
return re.search(r'confirmacion=(\S+)', self.load(**kwargs)).group(1)
def synthetic(self):
return (self.record(18083) or {}).get('synthetic_data')
class HospitalAddressTests(unittest.TestCase):
def test_only_host_and_port_are_accepted(self):
"""Fails if a URL, credentials, a path or an out-of-range port can be passed as the hospital address."""
for good in ('10.0.10.41:9505', 'hospital.example:3306', 'h:1'):
self.assertEqual(dataload.validate_hospital(good), good)
for bad in ('', 'host', 'mysql://host:3306', 'user:pw@host:3306', 'host:0', 'host:70000', 'host:3306/db',
'ho st:3306', '-host:3306'):
with self.subTest(bad), self.assertRaises(ValueError):
dataload.validate_hospital(bad)
class PlanTests(LoadCase):
def test_plan_changes_nothing_and_is_bound_to_the_pins_and_the_hospital(self):
"""Fails if planning builds or runs anything, or one confirmation is valid for another hospital."""
self.docker.calls.clear()
token = self.load_token()
self.assertEqual(self.docker.mutating(), [])
self.assertEqual(self.host.entered[-1], False)
self.assertIsNone(self.synthetic())
self.assertNotEqual(token, self.load_token(hospital='10.0.10.42:9505'))
def test_plan_refuses_what_is_not_a_clean_installed_dev_instance(self):
"""Fails if the load can be planned for an unregistered, protected, failed, loaded or busy instance."""
record = self.record(18083)
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
self.load(port=18110)
for port in (18090, 18096, 18097):
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
self.load(port=port)
with self.assertRaisesRegex(ValueError, 'protected'):
self.load(port=18087)
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, status='failed'))
with self.assertRaisesRegex(RuntimeError, 'not installed'):
self.load()
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, synthetic_data={'status': 'loaded'}))
with self.assertRaisesRegex(RuntimeError, 'already has a simulated-hospital load'):
self.load()
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, installer='someone-else'))
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
self.load()
def test_plan_refuses_an_instance_that_already_has_import_attempts(self):
"""Fails if a platform that was already imported into is treated as empty."""
self.host.responses['/reportes/importaciones'] = {'status': 200, 'body': '{"intentos": [{"operacion": "carga"}]}'}
with self.assertRaisesRegex(RuntimeError, 'import attempts'):
self.load()
def test_plan_refuses_an_instance_that_is_not_running(self):
"""Fails if a stopped or altered instance is loaded."""
for container in self.docker.containers.values():
container['State'] = {'Status': 'exited'}
with self.assertRaisesRegex(RuntimeError, 'is not running'):
self.load()
def test_plan_refuses_an_unreachable_hospital(self):
"""Fails if a hospital the host cannot reach is accepted, so the failure would come after building."""
self.host.unreachable.add('10.0.10.41:9505')
with self.assertRaisesRegex(RuntimeError, 'does not accept connections'):
self.load()
def test_plan_refuses_a_record_without_the_dev_data_pin(self):
"""Fails if a load can proceed without the commit of the generator to build."""
record = self.record(18083)
record['gitlinks'] = {k: v for k, v in record['gitlinks'].items() if k != 'dev-data'}
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', record)
with self.assertRaisesRegex(RuntimeError, 'does not pin dev-data'):
self.load()
class ExecuteTests(LoadCase):
def test_confirmed_load_builds_the_pinned_loader_and_records_the_result(self):
"""Fails if the loader is built from anything but the pinned commits, or the outcome is not recorded."""
token = self.load_token()
self.docker.calls.clear()
self.load(token)
record = self.synthetic()
self.assertEqual(record['status'], 'loaded')
self.assertEqual(record['hospital'], '10.0.10.41:9505')
self.assertEqual(record['counts']['cacu']['Paciente']['total'], 300)
self.assertEqual(record['indicators'], {'cacu': 'ok', 'cama': 'ok', 'tea': 'ok'})
gitlinks = self.record(18083)['gitlinks']
self.assertEqual(self.fetched, [(dataload.DEV_DATA_REMOTE, gitlinks['dev-data'], ()),
(dataload.APPLICATION_REMOTE, gitlinks['ISSSTELEON'], ('Core',))])
verbs = [c[1] for c in self.docker.mutating()]
self.assertEqual(verbs, ['build', 'run', 'run', 'run', 'run'])
runs = [c for c in self.docker.calls if c[1] == 'run']
self.assertTrue(all('--rm' in c and '--network' in c for c in runs))
self.assertNotIn('cargar', runs[0])
self.assertEqual([c[c.index('cargar') + 1] for c in runs[1:]], ['cacu', 'cama', 'tea'])
def test_wrong_confirmation_loads_nothing(self):
"""Fails if a confirmation that is not the plan's starts a build or a load."""
self.docker.calls.clear()
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
self.load('cargar-18083-0000000000000000')
with self.assertRaises(ValueError):
self.load('instalar-18083-0000000000000000')
self.assertEqual(self.docker.mutating(), [])
self.assertIsNone(self.synthetic())
def test_loader_failure_is_visible_and_blocks_a_second_load(self):
"""Fails if a failed stage is swallowed, or a half-loaded instance can be loaded again."""
token = self.load_token()
def fail(args):
raise fakedocker.failure(args, 'POST /imports/commit: 500 boom')
self.docker.loader_output = fail
with self.assertRaisesRegex(RuntimeError, 'the load failed.*the loader failed for cacu.*boom.*reinstall'):
self.load(token)
self.assertEqual(self.synthetic()['status'], 'failed')
self.assertIn('boom', self.synthetic()['error'])
with self.assertRaisesRegex(RuntimeError, 'already has a simulated-hospital load'):
self.load()
def test_rejected_rows_and_empty_hospitals_fail_the_load(self):
"""Fails if a load with rejected rows, or from a hospital with no rows, is reported as complete."""
for output, message in (('Paciente: 3 leídas, 2 nuevas, 0 actualizadas, 1 rechazadas\n'
'Citologia: 1 leídas, 1 nuevas, 0 actualizadas, 0 rechazadas\n', 'rows were rejected'),
('Paciente: 0 leídas, 0 nuevas, 0 actualizadas, 0 rechazadas\n'
'Citologia: 0 leídas, 0 nuevas, 0 actualizadas, 0 rechazadas\n', 'no rows to load'),
('nothing useful\n', 'printed no table counts')):
with self.subTest(message):
self.setUp()
token = self.load_token()
self.docker.loader_output = lambda args, o=output: o
with self.assertRaisesRegex(RuntimeError, message):
self.load(token)
self.assertEqual(self.synthetic()['status'], 'failed')
def test_indicator_recalculation_error_fails_the_load(self):
"""Fails if the load is reported complete while a domain's recalculation ended in error."""
token = self.load_token()
self.host.responses['/reportes/indicadores'] = {'status': 200, 'body': json.dumps({
'cacu': {'estado': 'ok'}, 'cama': {'estado': 'error', 'error': {'tipo': 'ValueError'}},
'tea': {'estado': 'ok'}})}
with self.assertRaisesRegex(RuntimeError, 'recalculation failed'):
self.load(token)
self.assertEqual(self.synthetic()['status'], 'failed')
def test_recalculation_that_never_finishes_fails_the_load(self):
"""Fails if the load waits forever, or succeeds, while a domain is still pending."""
token = self.load_token()
self.host.responses['/reportes/indicadores'] = {'status': 200, 'body': json.dumps({
d: {'estado': 'en_curso', 'pendiente': True} for d in ('cacu', 'cama', 'tea')})}
times = iter([0, 1, 5000])
with patch.object(dataload.time, 'monotonic', lambda: next(times)), \
self.assertRaisesRegex(RuntimeError, 'did not finish'):
self.load(token)
def test_load_touches_no_installation_resource(self):
"""Fails if the load stops, removes or recreates any container, volume or network of the instance."""
before = (sorted(self.docker.containers), sorted(self.docker.volumes), sorted(self.docker.networks))
self.docker.calls.clear()
self.load(self.load_token())
self.assertEqual((sorted(self.docker.containers), sorted(self.docker.volumes), sorted(self.docker.networks)), before)
self.assertEqual([c[1] for c in self.docker.mutating()], ['build', 'run', 'run', 'run', 'run'])
self.assertNotIn('hospital:hospital', json.dumps(self.synthetic()))
class HospitalCheckTests(LoadCase):
"""The hospital is read before anything is written to the platform, and every table is verified after."""
def writes(self):
"""The loader runs (the commands that import into the platform)."""
return [c for c in self.docker.calls if c[1] == 'run' and 'cargar' in c]
def attempt(self):
"""The instance record the registry holds."""
return self.record(18083)
def test_a_hospital_with_the_old_schema_is_refused_before_anything_is_written(self):
"""Fails if a hospital that lacks a table of the pinned generator (the schema before the TEA redesign) is
loaded, if refusing it leaves the instance marked so that it cannot be tried again, or if the refusal is
not recorded on the instance."""
token = self.load_token()
del self.hospital['tea']['tables']['citologia']
self.hospital['tea']['tables']['mchat'] = {'target': 'tea.Mchat', 'exists': False, 'rows': None,
'missing_columns': []}
with self.assertRaisesRegex(RuntimeError, 'did not start.*table mchat is missing from hospital'):
self.load(token)
self.assertEqual(self.writes(), [])
self.assertIsNone(self.synthetic())
record = self.attempt()
self.assertEqual(record['status'], 'installed')
self.assertEqual(record['load_attempt']['status'], 'not_started')
self.assertIn('table mchat is missing', record['load_attempt']['error'])
self.assertEqual(record['load_attempt']['hospital'], '10.0.10.41:9505')
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
self.load(token)
self.hospital = good_hospital()
self.load(self.load_token())
self.assertEqual(self.synthetic()['status'], 'loaded')
self.assertEqual(self.attempt()['status'], 'installed')
def test_a_loader_that_cannot_be_built_leaves_the_instance_clean_and_recorded(self):
"""Fails if a failed build of the loader marks the instance as loaded or failed, blocks a retry, or goes
unrecorded."""
token = self.load_token()
good_fetch = self.fetch_tree
def broken(remote, commit, directory, paths=()):
raise RuntimeError('git fetch failed: network unreachable')
with patch.object(dataload, 'fetch_tree', broken), \
self.assertRaisesRegex(RuntimeError, 'did not start.*network unreachable'):
self.load(token)
self.assertIsNone(self.synthetic())
self.assertEqual(self.attempt()['status'], 'installed')
self.assertIn('network unreachable', self.attempt()['load_attempt']['error'])
self.assertEqual(self.writes(), [])
with patch.object(dataload, 'fetch_tree', good_fetch):
self.load(self.load_token())
self.assertEqual(self.synthetic()['status'], 'loaded')
def test_missing_columns_unreadable_databases_and_empty_projects_are_refused(self):
"""Fails if a table with a column the generator expects missing, a database the check cannot read or a
project whose tables are all empty gets through to the loader."""
cases = {
'lacks the columns ord_pdf_blob': {'cacu': dict(self.hospital['cacu'], tables={
'paciente': {'target': 'Paciente', 'exists': True, 'rows': 3, 'missing_columns': ['ord_pdf_blob']}})},
'cannot be read': {'cama': {'database': 'hospital_cama', 'error': 'OperationalError: unknown database'}},
'hospital has no rows': {'tea': dict(self.hospital['tea'], tables={
'paciente': {'target': 'Paciente', 'exists': True, 'rows': 0, 'missing_columns': []}})},
}
for message, change in cases.items():
with self.subTest(message):
token = self.load_token()
self.hospital = good_hospital(**change)
with self.assertRaisesRegex(RuntimeError, message):
self.load(token)
self.assertEqual(self.writes(), [])
self.assertIsNone(self.synthetic())
def test_an_empty_table_in_a_populated_project_is_recorded_and_does_not_stop_the_load(self):
"""Fails if a table that legitimately has no rows (small hospitals) blocks the load, or goes unrecorded."""
self.hospital['cacu']['tables']['citologia']['rows'] = 0
self.load(self.load_token())
self.assertEqual(self.synthetic()['status'], 'loaded')
self.assertEqual(self.synthetic()['empty_tables'], ['Citologia'])
def test_a_table_the_loader_never_reported_fails_the_load(self):
"""Fails if a project is accepted when the loader printed counts for only some of the tables the generator
has, which is how a load that skipped a table would look."""
token = self.load_token()
self.docker.loader_output = lambda args: 'Paciente: 300 leídas, 300 nuevas, 0 actualizadas, 0 rechazadas\n'
with self.assertRaisesRegex(RuntimeError, 'reported no counts for Citologia'):
self.load(token)
self.assertEqual(self.synthetic()['status'], 'failed')
def test_rows_read_but_not_stored_fail_the_load(self):
"""Fails if a table that read more rows than it created or updated, with no rejection, counts as loaded."""
token = self.load_token()
self.docker.loader_output = lambda args: ('Paciente: 300 leídas, 290 nuevas, 0 actualizadas, 0 rechazadas\n'
'Citologia: 779 leídas, 779 nuevas, 0 actualizadas, 0 rechazadas\n')
with self.assertRaisesRegex(RuntimeError, r'read but not stored.*Paciente.*10'):
self.load(token)
self.assertEqual(self.synthetic()['status'], 'failed')
def test_a_hospital_check_that_prints_no_report_is_refused(self):
"""Fails if a check that crashed or printed nothing is read as a clean hospital."""
token = self.load_token()
self.docker.hospital_report = lambda args: ''
with self.assertRaisesRegex(RuntimeError, 'printed no report'):
self.load(token)
self.assertEqual(self.writes(), [])
self.assertIsNone(self.synthetic())
token = self.load_token()
def crash(args):
raise fakedocker.failure(args, 'pymysql.err.OperationalError: connection refused')
self.docker.hospital_report = crash
with self.assertRaisesRegex(RuntimeError, 'could not be read.*connection refused'):
self.load(token)
self.assertIsNone(self.synthetic())
if __name__ == '__main__':
unittest.main()
-282
View File
@@ -1,282 +0,0 @@
"""Exercise the workflow entrypoint with synthetic SQLite data and a fake daemon.
The update adapter uses real registry, backup, activation and preservation checks.
All Docker, host port probes and application processes are substituted locally.
"""
from contextlib import ExitStack
import copy
import json
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest.mock import patch
import conservative
import data_guard
import dev
import host
from test_conservative import SimulatedDeployment, change, fixture
class AutomaticDeploymentTests(unittest.TestCase):
def setUp(self):
"""Create a named installation whose identity is independent of its public port."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base, 'isssteleon-clinic-west', 23456)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
def execute(self):
"""Invoke exactly the automatic command used by deploy-dev with no real daemon."""
with ExitStack() as stack:
for name in ('git', 'export_tree', 'pinned_manifest', 'run', 'host_action',
'copy_to_host', 'verify_existing_containers', 'verify_services'):
stack.enter_context(patch.object(dev, name, side_effect=getattr(self.runtime, name)))
stack.enter_context(patch.object(dev, 'start_helper', return_value='owned-helper'))
stack.enter_context(patch.object(conservative, 'guard', side_effect=self.runtime.guard))
stack.enter_context(patch.object(conservative, 'verify_api'))
stack.enter_context(patch.object(conservative, 'freeze_failed'))
install = stack.enter_context(patch.object(dev, 'install', side_effect=AssertionError('unexpected install')))
try:
dev.install_auto(str(self.record['port']), Path('/synthetic-source'), self.base)
finally:
install.assert_not_called()
self.assertEqual(self.runtime.calls[-1], ['docker', 'rm', '-f', 'owned-helper'])
def select_same_revision(self):
"""Record a complete pinned manifest and completed work for an already installed release."""
self.record.update(revision=self.runtime.revision, phase='complete', recalculation='complete',
gitlinks=self.runtime.pinned_manifest(None, 'd' * 40))
host.write_record(self.root, self.record)
def test_registered_port_updates_preserving_data_and_provenance(self):
"""Fail if automatic dispatch resets storage or records images unrelated to its candidate."""
before = data_guard.storage_state(self.root / 'data', self.contract)
self.execute()
record = host.read_record(self.root)
data_guard.verify_state(self.root / 'data', self.contract, before, derived=True)
self.assertEqual((record['project'], record['port']), ('isssteleon-clinic-west', 23456))
self.assertEqual((record['revision'], record['target_revision']), (self.runtime.revision,) * 2)
self.assertEqual(record['gitlinks'], self.runtime.pinned_manifest(None, 'd' * 40))
self.assertEqual(record['gitlinks'], record['target_gitlinks'])
builds = [args[args.index('-t') + 1] for args in self.runtime.calls if args[:2] == ['docker', 'build']]
self.assertEqual(record['images'], builds)
self.assertEqual(record['images'], record['target_images'])
self.assertTrue(all(self.runtime.revision[:12] in image for image in builds))
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
self.assertEqual(config['services']['webapi']['image'], builds[0])
self.assertEqual(config['services']['indicadores']['image'], builds[0])
self.assertEqual(config['services']['webapp']['image'], builds[1])
self.assertEqual((record['status'], record['result'], record['recalculation']),
('installed', 'updated', 'complete'))
def test_same_revision_verifies_without_build_backup_restart_or_recalculation(self):
"""Fail if a repeated release rebuilds, archives, recalculates or changes persistent bytes."""
self.select_same_revision()
before = {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
if p.is_file() and p.name != 'installation.json'}
self.execute()
record = host.read_record(self.root)
self.assertEqual(record, dict(self.record, result='unchanged', verification='complete'))
self.assertFalse(self.runtime.finished)
self.assertFalse((self.base / '.backups').exists())
self.assertFalse(any('build' in args or 'stop' in args or 'up' in args or 'update' in args
for args in self.runtime.calls))
self.assertEqual(before, {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
if p.is_file() and p.name != 'installation.json'})
def test_selected_branch_updates_legacy_record(self):
"""Fail if updating an older record loses the selected branch or retained data."""
before = data_guard.storage_state(self.root / 'data', self.contract)
with patch.object(dev, 'request_metadata', return_value={'branch': 'staging',
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['branch'], 'staging')
self.assertEqual(record['revision'], self.runtime.revision)
self.assertEqual((record['workflow_ref'], record['workflow_sha']), ('refs/heads/dev', 'f' * 40))
data_guard.verify_state(self.root / 'data', self.contract, before, derived=True)
def test_different_branch_same_commit_records_verified_noop(self):
"""Fail if selecting another branch at the same SHA rebuilds or leaves stale provenance."""
self.select_same_revision()
with patch.object(dev, 'request_metadata', return_value={'branch': 'feature/demo',
'workflow_ref': 'refs/heads/feature/demo', 'workflow_sha': self.runtime.revision}):
self.execute()
record = host.read_record(self.root)
self.assertEqual((record['result'], record['branch']), ('unchanged', 'feature/demo'))
self.assertFalse(any('build' in args or 'stop' in args for args in self.runtime.calls))
def test_same_revision_rejects_mismatching_gitlinks(self):
"""Fail if the outer SHA alone can hide inconsistent installed recursive gitlinks."""
self.select_same_revision()
self.record['gitlinks']['WebApi'] = '9' * 40
host.write_record(self.root, self.record)
with self.assertRaisesRegex(RuntimeError, 'same-revision-verification'):
self.execute()
self.assertEqual(host.read_record(self.root), self.record)
def test_same_revision_checks_storage_and_health_before_success(self):
"""Fail if a repeated release skips schema, image, configuration or service verification."""
self.select_same_revision()
for problem in ('schema', 'health', 'image', 'configuration'):
with self.subTest(problem=problem):
original = self.runtime.verify_services
if problem == 'schema':
change(self.root, 'tea', "UPDATE alembic_version SET version_num='unknown'")
elif problem == 'health':
def unhealthy(*args):
raise RuntimeError('unhealthy')
self.runtime.verify_services = unhealthy
elif problem == 'image':
self.runtime.mount_changed = True
else:
self.runtime.env['CACU_DATABASE_URL'] = 'sqlite:////elsewhere/private.db'
with self.assertRaises(RuntimeError):
self.execute()
self.assertEqual(host.read_record(self.root), self.record)
self.assertFalse(any('stop' in args or 'build' in args for args in self.runtime.calls))
change(self.root, 'tea', "UPDATE alembic_version SET version_num='" + self.contract['tea']['head'] + "'")
self.runtime.verify_services = original
self.runtime.mount_changed = False
self.runtime.env['CACU_DATABASE_URL'] = conservative.PERSISTENT_ENV['CACU_DATABASE_URL']
def test_recovery_states_never_fall_back_to_installation(self):
"""Fail if any interrupted or failed state is automatically retried or recreated."""
for status in ('preparing', 'building', 'starting', 'failed', 'updating', 'update_failed',
'replacing', 'replace_failed'):
with self.subTest(status=status):
record = dict(self.record, status=status)
host.write_record(self.root, record)
with self.assertRaisesRegex(RuntimeError, 'not installed'):
self.execute()
self.assertEqual(host.read_record(self.root), record)
def test_inconsistent_provenance_is_rejected_before_build_or_stop(self):
"""Fail if a nominally installed record with missing or invalid provenance reaches Docker writes."""
for fields in ({'revision': 'unknown'}, {'gitlinks': {}}, {'gitlinks': {'ISSSTELEON': 'bad'}}):
with self.subTest(fields=fields):
record = dict(self.record, **fields)
host.write_record(self.root, record)
with self.assertRaisesRegex(RuntimeError, 'Git provenance is invalid'):
self.execute()
self.assertEqual(host.read_record(self.root), record)
def test_incompatible_candidate_never_recreates_or_stops_instance(self):
"""Fail if a pending migration at the public entrypoint reaches backup, cutover or installation."""
change(self.root, 'governance', "UPDATE alembic_version SET version_num='d6b4f0e23a45'")
with self.assertRaisesRegex(RuntimeError, 'compatibility'):
self.execute()
self.assertEqual(host.read_record(self.root), self.record)
self.assertFalse(any('stop' in args for args in self.runtime.calls))
self.assertFalse((self.base / '.backups').exists())
def test_compatibility_rejection_exposes_only_safe_reason(self):
"""Fail if the public update loses the candidate's allowlisted compatibility diagnostic."""
original = self.runtime.guard
def reject(api, image, action, payload, *args, **kwargs):
if action == 'inspect':
raise conservative.GuardFailure('inspect', 'reason=migration_pending, domain=governance')
return original(api, image, action, payload, *args, **kwargs)
self.runtime.guard = reject
with self.assertRaisesRegex(RuntimeError, 'reason=migration_pending, domain=governance'):
self.execute()
self.assertEqual(host.read_record(self.root), self.record)
self.assertFalse(any('stop' in args for args in self.runtime.calls))
def test_candidate_failure_never_retries_as_a_fresh_install(self):
"""Fail if build, backup, activation or recalculation failure triggers destructive fallback."""
for failure in ('build', 'backup', 'cutover', 'worker'):
with self.subTest(failure=failure), tempfile.TemporaryDirectory() as tmp:
self.base = Path(tmp)
self.root, self.contract, self.record = fixture(self.base, 'isssteleon-another', 31567)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
self.runtime.fail = failure
identity = data_guard.identity(self.root / 'data')
with self.assertRaises(RuntimeError):
self.execute()
self.assertEqual(data_guard.identity(self.root / 'data'), identity)
self.assertFalse(any('down' in args or 'prune' in args for args in self.runtime.calls))
def test_unregistered_host_port_conflict_never_reserves_or_installs(self):
"""Fail if a foreign non-Docker listener permits a new installation or skips lock cleanup."""
actions = []
def host_action(helper, action, project, value):
actions.append(action)
if action == 'lookup':
return 'null'
raise OSError('requested port is occupied')
with patch.object(dev, 'start_helper', return_value='owned-helper'), \
patch.object(dev, 'host_action', side_effect=host_action), \
patch.object(dev, 'run', return_value='') as run, patch.object(dev, 'install') as install:
with self.assertRaises(OSError):
dev.install_auto('34567')
install.assert_not_called()
self.assertEqual(actions, ['lookup', 'check-port'])
self.assertEqual(run.call_args.args[0], ['docker', 'rm', '-f', 'owned-helper'])
def test_free_port_runs_existing_fresh_install_and_records_built_images(self):
"""Fail if the public entrypoint bypasses fresh-install phases or loses candidate/image provenance."""
with tempfile.TemporaryDirectory() as tmp:
base, calls, checks = Path(tmp), [], []
project, port = 'isssteleon-dev-34567', 34567
revision, pin = 'a' * 40, 'b' * 40
def host_action(helper, action, project, value):
checks.append(action)
if action == 'lookup':
return json.dumps(host.find_installation(base, int(value), missing_ok=True))
if action == 'save':
host.write_record(base / project, json.loads(value))
return ''
def export(repo, sha, source, manifest):
(source / 'dist').mkdir(parents=True)
(source / 'dist' / 'docker-compose.yml').write_text('{}')
manifest['ISSSTELEON'] = sha
def copy_to_host(helper, source, project, destination):
target = base / project / destination
if source.is_dir():
shutil.copytree(source, target)
else:
shutil.copy2(source, target)
def run(args, **kwargs):
calls.append(list(map(str, args)))
if 'config' in args:
directory = Path(args[args.index('--project-directory') + 1])
env = dict(line.split('=', 1) for line in (directory / '.env').read_text().splitlines())
api = {'image': 'isssteleon/webapi:' + env['ISSSTELEON_VERSION'],
'environment': {**env, **conservative.PERSISTENT_ENV},
'volumes': [{'type': 'bind', 'source': str(base / project / 'data'), 'target': '/data'}]}
return json.dumps({'name': project, 'services': {'webapi': api, 'indicadores': copy.deepcopy(api),
'webapp': {'image': 'isssteleon/webapp:' + env['ISSSTELEON_VERSION'],
'ports': [{'published': str(port), 'target': 80}]}}})
return ''
with patch.object(dev, 'start_helper', return_value='owned-helper'), \
patch.object(dev, 'host_action', side_effect=host_action), patch.object(dev, 'run', side_effect=run), \
patch.object(dev, 'git', side_effect=lambda repo, *args: revision if args[0] == 'rev-parse' else
'160000 commit ' + pin + '\tISSSTELEON'), \
patch.object(dev, 'export_tree', side_effect=export), \
patch.object(dev, 'request_metadata', return_value={'branch': 'main', 'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}), \
patch.object(dev, 'copy_to_host', side_effect=copy_to_host), \
patch.object(dev, 'reserve', side_effect=lambda helper, project, port: host.reserve(base, project, port)), \
patch.object(conservative, 'guard', return_value={'worker': 'webapi.recomputation'}), \
patch.object(conservative, 'verify_api'), \
patch.object(conservative, 'finish') as finish, patch.object(dev, 'verify_services'), \
patch.object(dev, 'verify_existing_containers') as verify:
dev.install_auto(str(port), Path('/synthetic-source'), base)
record = host.find_installation(base, port)
self.assertEqual(checks[:2], ['lookup', 'check-port'])
self.assertEqual((record['status'], record['result'], record['phase'], record['revision']),
('installed', 'installed', 'complete', revision))
self.assertEqual(record['gitlinks'], {'ISSSTELEON': pin})
self.assertEqual((record['branch'], record['workflow_sha']), ('main', 'f' * 40))
self.assertEqual(record['images'], [c[c.index('-t') + 1] for c in calls if c[:2] == ['docker', 'build']])
self.assertEqual(finish.call_count, 1)
self.assertEqual(verify.call_count, 1)
self.assertEqual(calls[-1], ['docker', 'rm', '-f', 'owned-helper'])
if __name__ == '__main__':
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
"""Pin the general workflow's deployment safety boundaries using its checked-in YAML.
The fixture is the workflow text; no runner, network, Docker or dispatch is used.
Behavioral routing and preservation are exercised in test_deploy_auto.py.
"""
from pathlib import Path
import re
import unittest
class GeneralWorkflowTests(unittest.TestCase):
def test_dispatch_separates_workflow_and_target_branch(self):
"""Fail if the central workflow omits the independent target branch or event validation."""
text = (Path(__file__).resolve().parents[1] / 'workflows' / 'deploy-dev.yml').read_text()
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto', 'rama'])
for boundary in ('${{ gitea.ref }}', '${{ gitea.ref_name }}', '${{ gitea.ref_type }}',
'ref: ${{ gitea.sha }}', 'dev.py validate-dispatch',
'dev.py validate-auto "$PORT"', 'dev.py deploy-branch "$PORT" "$TARGET_BRANCH"',
'default: dev'):
self.assertIn(boundary, text)
self.assertLess(text.index('validate-dispatch'), text.index('deploy-branch'))
self.assertNotIn('refs/heads/dev', text)
self.assertNotIn('--remote', text)
def test_general_path_has_no_laboratory_identity_or_reset_fallback(self):
"""Fail if production routing acquires a fixed trial identity or destructive reset command."""
directory = Path(__file__).parent
paths = [directory / name for name in ('dev.py', 'host.py', 'conservative.py')]
paths.append(directory.parent / 'workflows' / 'deploy-dev.yml')
for path in paths:
with self.subTest(path=path.name):
text = path.read_text()
self.assertNotRegex(text, r'18080|18081|dev-prueba-02|reset_lab|trial_inspect')
self.assertNotRegex(text, r"['\"](?:down|prune|reinstalar|recrear)['\"]")
if __name__ == '__main__':
unittest.main()
-422
View File
@@ -1,422 +0,0 @@
"""Installer behavior with temporary directories, fake Docker commands and Git archives."""
import io
import json
import subprocess
import sys
import tarfile
import tempfile
import types
import unittest
from pathlib import Path, PurePosixPath
from unittest.mock import patch
try:
import fcntl
except ImportError:
sys.modules['fcntl'] = types.SimpleNamespace(flock=lambda *args: None, LOCK_EX=1)
import dev
import host
class InstallerTests(unittest.TestCase):
def test_find_installation_uses_recorded_port(self):
"""Resolve old and new project names; fail if identity is derived from the port."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
for project, port in [('isssteleon-dev-prueba-02', 18080), ('isssteleon-dev-18081', 18081)]:
directory = base / project
directory.mkdir()
for name in ('codigo', 'deploy', 'data'):
(directory / name).mkdir()
host.write_record(directory, {'project': project, 'port': port, 'status': 'installed'})
self.assertEqual(host.find_installation(base, port)['project'], project)
with self.assertRaisesRegex(RuntimeError, 'no installation'):
host.find_installation(base, 18082)
self.assertIsNone(host.find_installation(base, 18082, missing_ok=True))
def test_find_installation_rejects_ambiguous_and_bad_records(self):
"""Reject duplicates and unreadable records, even when the requested port has a match."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
for project in ('isssteleon-old', 'isssteleon-new'):
directory = base / project
directory.mkdir()
for name in ('codigo', 'deploy', 'data'):
(directory / name).mkdir()
host.write_record(directory, {'project': project, 'port': 18080, 'status': 'installed'})
with self.assertRaisesRegex(RuntimeError, 'duplicate recorded port'):
host.find_installation(base, 18080)
(base / 'isssteleon-new' / 'installation.json').write_text('{broken')
with self.assertRaises(ValueError):
host.find_installation(base, 18080)
with self.assertRaises(ValueError):
host.find_installation(base, 18082, missing_ok=True)
def test_host_lookup_reports_an_absent_port_without_reserving_it(self):
"""A missing port returns null without creating a project or a reservation."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
with patch.object(sys, 'argv', ['host.py', str(base), 'lookup', '-', '18081']), \
patch('builtins.print') as output:
host.main()
output.assert_called_once_with('null')
self.assertEqual(list(base.iterdir()), [])
def test_find_installation_rejects_uncertain_status_and_paths(self):
"""Reject interrupted operations and missing persistent paths before an update could run."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
directory = base / 'isssteleon-old'
directory.mkdir()
for name in ('codigo', 'deploy', 'data'):
(directory / name).mkdir()
for status in ('failed', 'updating', 'update_failed'):
host.write_record(directory, {'project': directory.name, 'port': 18080, 'status': status})
with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, 'not installed'):
host.find_installation(base, 18080)
host.write_record(directory, {'project': directory.name, 'port': 18080, 'status': 'installed'})
(directory / 'data').rmdir()
with self.assertRaisesRegex(RuntimeError, 'invalid installation path'):
host.find_installation(base, 18080)
def test_automatic_identity_and_invalid_inputs(self):
"""Normalize valid ports and reject invalid requests before any installation side effect."""
for port, expected in [('18081', 'dev-18081'), ('1024', 'dev-1024'),
('65535', 'dev-65535'), ('01024', 'dev-1024')]:
self.assertEqual(dev.automatic_instance(port), expected)
for port in ('1023', '65536', 'abc', '', ' 1024', '+1024', '001024', '1.5'):
with self.subTest(port=port), patch.object(dev, 'install') as install:
with self.assertRaises(ValueError):
dev.install_auto(port)
install.assert_not_called()
def test_automatic_install_uses_existing_interface(self):
"""Use the shared installation path with a normalized identity and install operation."""
with patch.object(dev, 'install') as install, patch.object(dev, 'start_helper', return_value='helper'), \
patch.object(dev, 'host_action', side_effect=['null', '']), patch.object(dev, 'run', return_value=''):
dev.install_auto('01024')
self.assertEqual(install.call_args.args[:3], ('dev-1024', '01024', 'instalar'))
def test_automatic_dispatch_uses_recorded_identity(self):
"""An existing identity goes to conservative update, never a fresh installation."""
record = {'project': 'isssteleon-dev-prueba-02', 'port': 18080, 'status': 'installed'}
with patch.object(dev, 'start_helper', return_value='helper'), \
patch.object(dev, 'host_action', return_value=json.dumps(record)), \
patch.object(dev, 'update') as update, patch.object(dev, 'install') as install, \
patch.object(dev, 'run'):
dev.install_auto('18080')
update.assert_called_once_with(record, 'helper', dev.ROOT, dev.BASE)
install.assert_not_called()
def test_archive_keeps_reservation_and_original_data(self):
"""Archive only application payloads; fail if data moves or the port becomes free."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
directory = base / 'isssteleon-dev-prueba-02'
directory.mkdir()
for name in ('codigo', 'deploy', 'data'):
(directory / name).mkdir()
(directory / name / 'old').write_text(name)
previous = {'project': directory.name, 'port': 18080, 'status': 'installed'}
operation = 'a' * 32
host.write_record(directory, dict(previous, status='updating', operation_id=operation))
archive = host.archive_installation(base, directory.name, operation, previous)
self.assertTrue((directory / 'installation.json').exists())
self.assertFalse((archive / 'data').exists())
self.assertEqual((directory / 'data' / 'old').read_text(), 'data')
self.assertEqual(json.loads((archive / 'installation.json').read_text()), previous)
with self.assertRaisesRegex(RuntimeError, 'reserved'):
host.reserve(base, 'isssteleon-dev-18080', 18080)
with self.assertRaisesRegex(RuntimeError, 'not installed'):
host.find_installation(base, 18080)
def test_archive_interruption_keeps_record_and_reservation(self):
"""A failed code move retains an updating record and leaves persistent data in place."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
directory = base / 'isssteleon-old'
directory.mkdir()
for name in ('codigo', 'deploy', 'data'):
(directory / name).mkdir()
previous = {'project': directory.name, 'port': 18080, 'status': 'installed'}
operation = 'b' * 32
host.write_record(directory, dict(previous, status='updating', operation_id=operation))
with patch.object(host.os, 'rename', side_effect=OSError('interrupted')):
with self.assertRaises(OSError):
host.archive_installation(base, directory.name, operation, previous)
self.assertEqual(host.read_record(directory)['status'], 'updating')
with self.assertRaises(RuntimeError):
host.reserve(base, 'isssteleon-new', 18080)
def test_container_verification_rejects_foreign_mount_and_wrong_image(self):
"""Only matching project containers may access the installation or be replaced."""
project = 'isssteleon-dev-prueba-02'
record = {'project': project, 'port': 18080, 'images': ['api-tag', 'app-tag']}
data = '/srv/instances/' + project + '/data'
def container(service):
api = service != 'webapp'
return {'Id': service, 'Name': '/' + service,
'Config': {'Labels': {'com.docker.compose.project': project, 'com.docker.compose.service': service}},
'State': {'Status': 'running'}, 'Image': 'api-id' if api else 'app-id',
'HostConfig': {'PortBindings': {} if api else {'80/tcp': [{'HostPort': '18080'}]}},
'Mounts': [{'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}] if api else []}
containers = [container(s) for s in ('webapi', 'webapp', 'indicadores')]
def run(args):
if args[1:3] == ['image', 'inspect']:
return 'api-id' if args[-1] == 'api-tag' else 'app-id'
if args[1] == 'ps':
return 'id1\nid2\nid3\n'
return json.dumps(containers)
with patch.object(dev, 'run', side_effect=run):
self.assertEqual(dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper'),
['indicadores', 'webapi', 'webapp'])
containers.append({'Name': '/other', 'Config': {'Labels': {}}, 'HostConfig': {},
'Mounts': [{'Source': '/srv/instances'}]})
with self.assertRaisesRegex(RuntimeError, 'foreign container'):
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
containers.pop()
containers[0]['NetworkSettings'] = {'Networks': {'default': {'NetworkID': 'owned-network'}}}
containers.append({'Name': '/peer', 'Config': {'Labels': {}}, 'HostConfig': {}, 'Mounts': [],
'NetworkSettings': {'Networks': {'shared': {'NetworkID': 'owned-network'}}}})
with self.assertRaisesRegex(RuntimeError, 'shares the installation network'):
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
containers.pop()
containers[0]['Image'] = 'wrong'
with self.assertRaisesRegex(RuntimeError, 'image does not match'):
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
def test_foreign_port_is_rejected_before_reservation(self):
"""An unrelated container with the requested port is never stopped or overwritten."""
foreign = [{'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': '18081'}]}}}]
def run(args, **kwargs):
if args[1] == 'ps':
return 'foreign-id'
if args[1] == 'inspect':
return json.dumps(foreign)
return ''
with patch.object(dev, 'start_helper', return_value='helper'), \
patch.object(dev, 'host_action', return_value='null'), patch.object(dev, 'run', side_effect=run) as calls, \
patch.object(dev, 'install') as install, patch.object(dev, 'update') as update:
with self.assertRaisesRegex(RuntimeError, 'reserved by another container'):
dev.install_auto('18081')
install.assert_not_called()
update.assert_not_called()
self.assertFalse(any('stop' in c.args[0] for c in calls.call_args_list))
def test_host_reservations_fail_closed(self):
"""Preserve old and partial reservations and reject duplicate ports and identities."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
host.reserve(base, 'isssteleon-dev-prueba-02', 18080)
with self.assertRaisesRegex(RuntimeError, 'reserved by isssteleon-dev-prueba-02'):
host.reserve(base, 'isssteleon-dev-18080', 18080)
with self.assertRaisesRegex(RuntimeError, 'already exists'):
host.reserve(base, 'isssteleon-dev-prueba-02', 18081)
partial = base / 'isssteleon-dev-18081'
partial.mkdir()
with self.assertRaises((OSError, ValueError, RuntimeError)):
host.reserve(base, 'isssteleon-dev-18082', 18082)
self.assertFalse((base / 'isssteleon-dev-18082').exists())
(partial / 'installation.json').write_text('{broken')
with self.assertRaises(ValueError):
host.reserve(base, 'isssteleon-dev-18082', 18082)
def test_interrupted_reservation_blocks_subsequent_requests(self):
"""Keep an interrupted directory and fail closed before reserving another port."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
with patch.object(host, 'write_record', side_effect=OSError('interrupted')):
with self.assertRaises(OSError):
host.reserve(base, 'isssteleon-dev-18081', 18081)
self.assertTrue((base / 'isssteleon-dev-18081').is_dir())
with self.assertRaises(OSError):
host.reserve(base, 'isssteleon-dev-18082', 18082)
def test_atomic_record_replacement_preserves_previous_record(self):
"""Leave the previous complete record when atomic replacement fails."""
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
old = {'project': 'isssteleon-demo', 'port': 18080, 'status': 'preparing'}
host.write_record(directory, old)
with patch.object(host.os, 'replace', side_effect=OSError('interrupted')):
with self.assertRaises(OSError):
host.write_record(directory, dict(old, status='failed'))
self.assertEqual(json.loads((directory / 'installation.json').read_text()), old)
self.assertEqual(list(directory.iterdir()), [directory / 'installation.json'])
def test_existing_compose_resources_reject_reservation(self):
"""Reject any existing Compose resource before creating a host reservation."""
for kind in ('ps', 'network', 'volume'):
with self.subTest(kind=kind), patch.object(dev, 'run', side_effect=lambda args: 'found' if kind in args else ''), \
patch.object(dev, 'host_action') as action:
with self.assertRaisesRegex(RuntimeError, 'Compose project already owns'):
dev.reserve('helper', 'isssteleon-dev-18081', 18081)
action.assert_not_called()
def test_validation(self):
"""Accept valid input and reject unsafe input and unsupported operations."""
self.assertEqual(dev.validate('demo-2', '8080', 'instalar'), ('isssteleon-demo-2', 8080))
for instance, port, op in [('../x', '8080', 'instalar'), ('a--b', '8080', 'instalar'),
('A', '8080', 'instalar'), ('a'*41, '8080', 'instalar'),
('a', '80', 'instalar'), ('a', '65536', 'instalar'),
('a', '8 080', 'instalar'), ('a', '8080', 'actualizar'),
('a', '8080', 'reinstalar')]:
with self.subTest(instance=instance, port=port, operation=op), self.assertRaises(ValueError):
dev.validate(instance, port, op)
def test_configuration_is_instance_specific(self):
"""Generate isolated paths, image tags and four local SQLite URLs."""
with tempfile.TemporaryDirectory() as tmp:
deploy = Path(tmp)
tag = dev.configure(deploy, Path('/srv/demo/data'), 'isssteleon-demo', 'a'*40, 8081)
env = (deploy / '.env').read_text()
self.assertIn('ISSSTELEON_DATOS=' + str(Path('/srv/demo/data')) + '\n', env)
self.assertIn('ISSSTELEON_PUERTO=8081\n', env)
self.assertIn('GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db', env)
self.assertTrue(tag.startswith('isssteleon-demo-aaaaaaaaaaaa-'))
self.assertNotEqual(tag, dev.configure(deploy, Path('/srv/demo/data'), 'isssteleon-demo', 'a'*40, 8081))
def test_export_follows_committed_gitlinks_recursively(self):
"""Export the recorded nested SHA and reject a checkout at another commit."""
def archive(content):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode='w') as tar:
data = content.encode()
info = tarfile.TarInfo('file.txt'); info.size = len(data)
tar.addfile(info, io.BytesIO(data))
return buf.getvalue()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / 'repo'; child = root / 'nested'; dest = Path(tmp) / 'out'
def fake_git(repo, *args, **kwargs):
if args[0] == 'rev-parse': return 'parent\n' if repo == root else 'child\n'
if args[0] == 'archive': return archive('parent' if repo == root else 'child')
return b'160000 commit child\tnested\0' if repo == root else b''
manifest = {}
with patch.object(dev, 'git', side_effect=fake_git):
dev.export_tree(root, 'parent', dest, manifest)
self.assertEqual((dest / 'nested/file.txt').read_text(), 'child')
self.assertEqual(manifest, {'ISSSTELEON': 'parent', 'nested': 'child'})
self.assertEqual(dev.pinned_manifest(root, 'parent'), manifest)
with self.assertRaisesRegex(RuntimeError, 'expected wrong'):
dev.export_tree(child, 'wrong', dest, {})
with self.assertRaisesRegex(RuntimeError, 'expected wrong'):
dev.pinned_manifest(child, 'wrong')
def test_compose_config_validation(self):
"""Reject a changed project, database, mount, image or published port."""
data = Path('/data/instance')
api = {'image': 'isssteleon/webapi:tag', 'volumes': [{'type':'bind','source':str(data),'target':'/data'}],
'environment': {f'{x}_DATABASE_URL':f'sqlite:////data/{x.lower()}.db' for x in ('CACU','CAMA','TEA','GOVERNANCE')}}
config = {'name':'isssteleon-x', 'services': {'webapi':api, 'indicadores':api,
'webapp':{'image':'isssteleon/webapp:tag','ports':[{'published':'8080','target':80}]}}}
dev.verify_config(config, 'isssteleon-x', data, 'tag', 8080)
for change in ('name', 'database', 'mount', 'image', 'port', 'extra_mount', 'privileged'):
altered = json.loads(json.dumps(config))
if change == 'name': altered['name'] = 'isssteleon'
if change == 'database': altered['services']['webapi']['environment']['CACU_DATABASE_URL'] = 'postgres://shared'
if change == 'mount': altered['services']['indicadores']['volumes'][0]['source'] = '/shared'
if change == 'image': altered['services']['webapp']['image'] = 'other'
if change == 'port': altered['services']['webapp']['ports'][0]['published'] = '8081'
if change == 'extra_mount': altered['services']['webapp']['volumes'] = [{'type': 'bind', 'source': '/', 'target': '/host'}]
if change == 'privileged': altered['services']['webapi']['privileged'] = True
with self.subTest(change=change), self.assertRaises(RuntimeError):
dev.verify_config(altered, 'isssteleon-x', data, 'tag', 8080)
def test_helper_uses_existing_host_mount_and_shared_lock(self):
"""Fail if preparation uses an implicit mount or a job-local lock."""
calls = []
def fake_run(args, **kwargs):
calls.append([str(x) for x in args])
return '1' if 'exec' in args else ''
with patch.object(dev, 'run', side_effect=fake_run):
helper = dev.start_helper(PurePosixPath('/srv/workingnarrative-dev'))
self.assertTrue(helper.startswith('isssteleon-prepare-'))
self.assertIn('type=bind,src=/srv/workingnarrative-dev,dst=/host', calls[0])
self.assertIn('fcntl.flock', calls[0][-1])
self.assertIn('/host/.install.lock', calls[0][-1])
def test_install_transfers_and_probes_daemon_paths(self):
"""Fail if persistent data or the SQLite check uses a job-local mount."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / 'repo'; base = PurePosixPath('/srv/workingnarrative-dev'); calls = []
def fake_git(repo, *args, **kwargs):
return 'a'*40 if args[0] == 'rev-parse' else '160000 commit ' + 'b'*40 + '\tISSSTELEON'
def fake_export(repo, sha, dest, manifest):
(dest / 'dist').mkdir(parents=True)
(dest / 'dist/docker-compose.yml').write_text('fixture')
manifest['ISSSTELEON'] = sha
def fake_run(args, **kwargs):
calls.append([str(x) for x in args])
return '{}' if 'config' in args else ''
with patch.object(dev, 'git', side_effect=fake_git), patch.object(dev, 'export_tree', side_effect=fake_export), \
patch.object(dev, 'run', side_effect=fake_run), patch.object(dev, 'start_helper', return_value='helper'), \
patch.object(dev, 'reserve') as reserve, patch.object(dev, 'verify_config', return_value=None), \
patch.object(dev, 'verify_services'), \
patch.object(dev, 'verify_existing_containers'), \
patch.object(dev.conservative, 'controlled_config', return_value={}), \
patch.object(dev.conservative, 'verify_api'), patch.object(dev.conservative, 'guard'), \
patch.object(dev.conservative, 'finish'):
dev.install('demo', '8080', 'instalar', root, base)
reserve.assert_called_once_with('helper', 'isssteleon-demo', 8080)
self.assertTrue(any(c[:2] == ['docker', 'cp'] and c[-1].endswith('/deploy') for c in calls))
probe = next(c for c in calls if '--entrypoint' in c)
self.assertIn('type=bind,src=/srv/workingnarrative-dev/isssteleon-demo/data,dst=/data', probe)
self.assertIn('sqlite3.connect', probe[-1])
self.assertEqual(calls[-1], ['docker', 'rm', '-f', 'helper'])
def test_reservation_failure_removes_helper(self):
"""Fail if a rejected reservation leaves its helper holding the shared lock."""
with patch.object(dev, 'git', side_effect=['a'*40, '160000 commit ' + 'b'*40 + '\tISSSTELEON']), \
patch.object(dev, 'start_helper', return_value='helper'), \
patch.object(dev, 'reserve', side_effect=RuntimeError('reserved')), \
patch.object(dev, 'run') as run:
with self.assertRaisesRegex(RuntimeError, 'reserved'):
dev.install('demo', '8080', 'instalar')
run.assert_called_once_with(['docker', 'rm', '-f', 'helper'])
def test_install_failure_retains_failed_reservation(self):
"""Record a build preparation failure without deleting the reserved directory."""
records = []
def host_action(helper, action, project, payload):
records.append(json.loads(payload))
with patch.object(dev, 'git', side_effect=['a'*40, '160000 commit ' + 'b'*40 + '\tISSSTELEON']), \
patch.object(dev, 'start_helper', return_value='helper'), patch.object(dev, 'reserve') as reserve, \
patch.object(dev, 'host_action', side_effect=host_action), \
patch.object(dev, 'export_tree', side_effect=RuntimeError('export failed')), \
patch.object(dev, 'run') as run:
with self.assertRaisesRegex(RuntimeError, 'export failed'):
dev.install('demo', '8080', 'instalar')
reserve.assert_called_once_with('helper', 'isssteleon-demo', 8080)
self.assertEqual([record['status'] for record in records], ['preparing', 'failed'])
self.assertEqual(records[-1]['port'], 8080)
run.assert_called_once_with(['docker', 'rm', '-f', 'helper'])
def test_http_checks_use_webapp_container(self):
"""Fail if frontend and proxied API checks use the job's loopback."""
calls = []
def fake_run(args):
calls.append(args)
if 'ps' in args: return 'container\n'
if 'inspect' in args: return json.dumps({'Status':'running', 'Health':{'Status':'healthy'}})
return ''
with patch.object(dev, 'run', side_effect=fake_run):
dev.verify_services(['compose'], 8080)
urls = [c[-1] for c in calls if 'wget' in c]
self.assertEqual(urls, ['http://127.0.0.1/health', 'http://127.0.0.1/'])
self.assertTrue(all(c[:2] == ['docker', 'exec'] for c in calls if 'wget' in c))
def test_service_checks_are_independent(self):
"""A missing worker or unhealthy API prevents a successful installation."""
for service in ('webapi', 'webapp', 'indicadores'):
def fake_run(args):
if 'ps' in args:
return '' if args[-1] == service else 'container\n'
return json.dumps({'Status':'running', 'Health':{'Status':'healthy'}})
with self.subTest(service=service), patch.object(dev, 'run', side_effect=fake_run), \
patch.object(dev.time, 'sleep'), patch.object(dev.time, 'monotonic', side_effect=[0, 0, 301]):
with self.assertRaisesRegex(RuntimeError, service): dev.verify_services(['compose'], 8080)
if __name__ == '__main__':
unittest.main()
-201
View File
@@ -1,201 +0,0 @@
"""Validate branch events with synthetic contexts and no deployment or network."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import dev
class DispatchTests(unittest.TestCase):
def event(self, name='dev'):
"""Create a synthetic institutional workflow event for a full commit."""
return {'DISPATCH_REF': 'refs/heads/' + name, 'DISPATCH_REF_NAME': name,
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': 'a' * 40,
'DISPATCH_REPOSITORY': 'ISSSTELEON/WorkingNarrative',
'DISPATCH_SERVER': 'http://10.0.10.41:3000'}
def test_branch_names_and_immutable_sha(self):
"""Fail if valid selected branches do not retain the event SHA and full name."""
for name in ('dev', 'main', 'staging', 'feature/dashboard-unificado'):
with self.subTest(name=name), patch.dict(os.environ, self.event(name)), \
patch.object(dev, 'git', return_value='a' * 40):
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_ref'], 'refs/heads/' + name)
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_sha'], 'a' * 40)
def test_invalid_context_and_changed_checkout(self):
"""Fail if tags, invalid refs, another repository or mismatched SHAs can deploy."""
changes = ({'DISPATCH_REF_TYPE': 'tag'}, {'DISPATCH_REF': 'refs/tags/dev'},
{'DISPATCH_REPOSITORY': 'other/repo'}, {'DISPATCH_SERVER': 'http://example.com'},
{'DISPATCH_SHA': 'abc'}, {'DISPATCH_REF_NAME': 'other'})
for change in changes:
with self.subTest(change=change), patch.dict(os.environ, self.event() | change), \
patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(ValueError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event('bad..name')), patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(subprocess.CalledProcessError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event()), patch.object(dev, 'git', return_value='b' * 40):
with self.assertRaises(RuntimeError):
dev.dispatch_metadata(Path('.'))
def test_submodule_origin_checked_before_fetch(self):
"""Fail if a selected commit can fetch its application from an external origin."""
calls = []
def fake_git(repo, *args, **kwargs):
calls.append(args)
if args[0] == 'ls-tree':
return b'160000 commit ' + b'b' * 40 + b'\tISSSTELEON\0'
if '--get-regexp' in args:
return 'submodule.ISSSTELEON.path ISSSTELEON\n'
if '--get' in args:
return 'https://example.com/other.git\n'
raise AssertionError(args)
with patch.object(dev, 'request_metadata'), patch.object(dev, 'git', side_effect=fake_git):
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin'):
dev.checkout_pinned(Path('.'))
self.assertFalse(any('update' in args for args in calls))
def test_target_branch_validation(self):
"""Fail if refs, hashes or invalid names can replace a branch selection."""
for branch in ('dev', 'staging', 'feature/dashboard-unificado'):
self.assertEqual(dev.validate_branch(branch), branch)
for branch in ('', 'refs/tags/release', '-bad', '@', 'a' * 40, 'bad..name'):
with self.subTest(branch=branch):
with self.assertRaises((ValueError, subprocess.CalledProcessError)):
dev.validate_branch(branch)
def test_effective_origin_accepts_only_exact_institutional_http_urls(self):
"""Reject deceptive or rewritten origins before fetch while accepting checkout's HTTP URL."""
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'
for url, accepted in ((official, True), (official + '.git', True),
(official + '.git.evil', False),
(official.replace('10.0.10.41', '10.0.10.41.evil'), False),
(official.replace('http://', 'http://user:secret@'), False),
(official.replace('http://', 'https://'), False),
('http://example.com/ISSSTELEON/WorkingNarrative', False)):
with self.subTest(url=url):
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return url
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git) as git, \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError if accepted else RuntimeError):
dev.deploy_branch('18083', 'staging', Path('/central'))
self.assertEqual(any(call.args[1:2] == ('fetch',) for call in git.call_args_list), accepted)
install.assert_not_called()
def test_external_git_rewrite_is_rejected_before_fetch(self):
"""Fail if an official literal origin rewritten to another host reaches fetch."""
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(['git', 'init', '-q', tmp], check=True)
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin',
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'], check=True)
env = {'GIT_CONFIG_COUNT': '1', 'GIT_CONFIG_KEY_0': 'url.http://example.com/.insteadOf',
'GIT_CONFIG_VALUE_0': 'http://10.0.10.41:3000/'}
with patch.dict(os.environ, env), patch.object(dev, 'dispatch_metadata'), \
patch.object(dev, 'install_auto') as install:
with self.assertRaisesRegex(RuntimeError, 'origin is not the official repository'):
dev.deploy_branch('18083', 'staging', Path(tmp))
install.assert_not_called()
def test_central_installer_uses_resolved_application_tree(self):
"""Fail if a target without a workflow or with an old installer controls execution."""
for branch in ('dev', 'staging', 'feature/demo'):
with self.subTest(branch=branch):
calls = []
workflow_root = Path('/central')
target_sha = 'b' * 40
def fake_git(repo, *args, **kwargs):
calls.append((repo, args))
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[:2] == ('rev-parse', '--verify'):
return target_sha
if args[:2] == ('rev-parse', 'HEAD'):
return target_sha
return ''
observed = []
def install(port, source, base):
observed.append((port, source, dev.request_metadata(source)))
self.assertNotEqual(source, workflow_root)
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'run'), patch.object(dev, 'checkout_pinned') as checkout, \
patch.object(dev, 'install_auto', side_effect=install):
dev.deploy_branch('18083', branch, workflow_root, Path('/base'))
self.assertEqual(observed[0][2], {'branch': branch, 'workflow_ref': 'refs/heads/dev',
'workflow_sha': 'a' * 40})
self.assertTrue(any(args[0] == 'fetch' and '+refs/heads/' + branch + ':' in args[-1]
for _, args in calls))
checkout.assert_called_once_with(observed[0][1])
def test_real_git_snapshot_is_separate_from_workflow(self):
"""Fail if a moving branch or target deployment script replaces the central installer."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
remote, central = root / 'remote', root / 'central'
remote.mkdir()
central.mkdir()
def command(repo, *args, input=None):
return subprocess.run(['git', '-C', str(repo), *args], input=input,
text=True, capture_output=True, check=True).stdout.strip()
command(remote, 'init', '-q')
command(remote, 'config', 'user.email', 'fixture@example.invalid')
command(remote, 'config', 'user.name', 'Fixture')
(remote / '.gitea/deploy').mkdir(parents=True)
(remote / '.gitea/deploy/dev.py').write_text('untrusted target installer')
command(remote, 'add', '.gitea/deploy/dev.py')
command(remote, 'commit', '-qm', 'target with old installer and no workflow')
original = command(remote, 'rev-parse', 'HEAD')
command(remote, 'branch', 'staging')
(remote / '.gitea/deploy/dev.py').write_text('later branch tip')
command(remote, 'commit', '-qam', 'later commit')
newer = command(remote, 'rev-parse', 'HEAD')
command(central, 'init', '-q')
command(central, 'remote', 'add', 'origin', 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git')
actual_git = dev.git
def routed_git(repo, *args, **kwargs):
if repo == central and args[:3] == ('fetch', '--no-tags', 'origin'):
result = actual_git(repo, 'fetch', '--no-tags', str(remote), *args[3:], **kwargs)
command(remote, 'update-ref', 'refs/heads/staging', newer)
return result
return actual_git(repo, *args, **kwargs)
def inspect(port, source, base):
self.assertEqual(command(source, 'rev-parse', 'HEAD'), original)
self.assertEqual((source / '.gitea/deploy/dev.py').read_text(), 'untrusted target installer')
self.assertFalse((source / '.gitea/workflows/deploy-dev.yml').exists())
self.assertEqual(dev.request_metadata(source)['branch'], 'staging')
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=routed_git), \
patch.object(dev, 'checkout_pinned'), patch.object(dev, 'install_auto', side_effect=inspect) as install:
dev.deploy_branch('18083', 'staging', central, root / 'base')
install.assert_called_once()
self.assertEqual(command(remote, 'rev-parse', 'refs/heads/staging'), newer)
def test_nonexistent_branch_does_not_start_deployment(self):
"""Fail if an absent remote branch falls back to another commit or starts deployment."""
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError):
dev.deploy_branch('18083', 'missing', Path('/central'))
install.assert_not_called()
if __name__ == '__main__':
unittest.main()
+493
View File
@@ -0,0 +1,493 @@
"""Install and clean reinstall flows against an in-memory Docker daemon and a temporary installation host.
Fixtures (see fakedocker.py): `FakeDocker` answers the Docker and Compose commands and keeps containers, volumes,
networks and images; `LocalHost` runs the registry actions on a temporary directory instead of in the locked helper;
reference resolution and checkout are replaced by a controllable `self.commit`, because test_composition.py covers
them against real Git repositories. Each test starts from an empty host.
"""
import contextlib
import io
import json
from pathlib import Path, PurePosixPath
import re
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import composition
import fakedocker
import installer
import proc
import registry
import resources
BASE = PurePosixPath('/srv/dev-test')
SHA_A, SHA_B = 'a' * 40, 'b' * 40
class FlowCase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.registry_dir = Path(self.tmp.name) / 'base'
self.registry_dir.mkdir()
self.docker = fakedocker.FakeDocker(BASE)
self.host = fakedocker.LocalHost(self.registry_dir)
self.commit, self.busy, self.resolutions = SHA_A, set(), 0
for module, name, value in (
(proc, 'run', self.docker.run), (composition, 'resolve_reference', self.resolve),
(composition, 'checkout', self.checkout), (composition, 'export_tree', self.export),
(registry, 'check_port', self.check_port), (installer.time, 'sleep', lambda seconds: None)):
patcher = patch.object(module, name, value)
patcher.start()
self.addCleanup(patcher.stop)
# -- stand-ins -------------------------------------------------------------------------------------
def resolve(self, reference, remote=None):
self.resolutions += 1
return {'reference': reference, 'kind': 'branch', 'commit': self.commit}
def checkout(self, resolved, directory, remote=None):
return {'reference': resolved['reference'], 'kind': resolved['kind'], 'commit': resolved['commit'],
'application': 'c' * 40,
'gitlinks': {'WorkingNarrative': resolved['commit'], 'dev-data': 'd' * 40, 'ISSSTELEON': 'c' * 40,
'WebApi': 'e' * 40, 'WebApp': 'f' * 40, 'models': '1' * 40}}
def export(self, repo, revision, dest, prefix=''):
for name in ('dist/docker-compose.yml', 'WebApi/Dockerfile', 'WebApp/Dockerfile'):
(Path(dest) / name).parent.mkdir(parents=True, exist_ok=True)
(Path(dest) / name).write_text('x')
def check_port(self, port):
if port in self.busy:
raise OSError('address already in use')
# -- operations ------------------------------------------------------------------------------------
def operate(self, operation, port, confirmation='', reference='dev'):
out = io.StringIO()
with contextlib.redirect_stdout(out):
installer.run_operation(operation, str(port), reference, confirmation, base=BASE,
metadata={'workflow_ref': 'refs/heads/dev', 'workflow_sha': SHA_A},
host_factory=self.host)
return out.getvalue()
def token(self, operation, port, reference='dev'):
return re.search(r'confirmacion=(\S+)', self.operate(operation, port, '', reference)).group(1)
def install(self, port):
self.operate('install', port, self.token('install', port))
return registry.lookup(self.registry_dir, port)
def record(self, port):
return registry.lookup(self.registry_dir, port)
def project_containers(self, port):
project = f'isssteleon-dev-{port}'
return {i: c for i, c in self.docker.containers.items()
if c['Config']['Labels'].get('com.docker.compose.project') == project}
class PlanTests(FlowCase):
def test_install_plan_changes_nothing_and_takes_no_lock(self):
"""Fails if planning builds, starts, registers or creates anything, or asks for the write lock."""
output = self.operate('install', 18083)
self.assertIn('confirmacion=instalar-18083-', output)
self.assertEqual(self.docker.mutating(), [])
self.assertEqual(list(self.registry_dir.iterdir()), [])
self.assertEqual(self.host.entered, [False])
self.assertEqual(self.docker.images, {})
def test_reinstall_plan_lists_exact_resources_and_changes_nothing(self):
"""Fails if the plan omits a container, the volume, the network or the directory, or changes anything."""
self.install(18083)
before = (len(self.docker.mutating()), sorted(self.docker.containers))
output = self.operate('reinstall', 18083)
plan = json.loads(output.split('Plan:', 1)[1].split('Nothing was changed')[0])
self.assertEqual({c['service'] for c in plan['resources']['containers']},
{'webapi', 'webapp', 'indicadores', 'notebooks'})
self.assertEqual([v['name'] for v in plan['resources']['volumes']], ['isssteleon-dev-18083_trabajos_notebooks'])
self.assertEqual([n['name'] for n in plan['resources']['networks']], ['isssteleon-dev-18083_default'])
self.assertEqual(plan['directory']['project'], 'isssteleon-dev-18083')
self.assertEqual((len(self.docker.mutating()), sorted(self.docker.containers)), before)
self.assertEqual(self.host.entered[-1], False)
def test_plan_is_bound_to_the_composition(self):
"""Fails if a different commit yields the same confirmation, so an approval would carry over."""
first = self.token('install', 18083)
self.commit = SHA_B
self.assertNotEqual(self.token('install', 18083), first)
def test_plan_is_stable_for_the_same_inputs(self):
"""Fails if the confirmation depends on anything random, so the second run could never match the first."""
self.assertEqual(self.token('install', 18083), self.token('install', 18083))
class InstallTests(FlowCase):
def test_install_on_a_free_port_builds_starts_and_records_everything(self):
"""Fails if the record lacks reference, commits, gitlinks, port, project, images or owner, or any check is skipped."""
record = self.install(18083)
self.assertEqual((record['status'], record['port'], record['project']),
('installed', 18083, 'isssteleon-dev-18083'))
self.assertEqual((record['installer'], record['reference'], record['revision']),
(registry.INSTALLER, 'dev', SHA_A))
self.assertEqual(record['gitlinks']['WebApi'], 'e' * 40)
self.assertEqual(record['gitlinks']['dev-data'], 'd' * 40)
self.assertEqual(len(record['images']), 2)
self.assertEqual(record['verification'], {'health': 'ok', 'api_routes': 1, 'web': 'ok'})
self.assertEqual(len(self.project_containers(18083)), 4)
self.assertTrue((self.registry_dir / 'isssteleon-dev-18083' / 'deploy' / 'docker-compose.yml').exists())
self.assertEqual(self.host.entered[-1], True)
def test_installed_worker_does_not_recalculate_at_start(self):
"""Fails if the persisted composition lets the worker recalculate every domain when it starts."""
self.install(18083)
config = json.loads((self.registry_dir / 'isssteleon-dev-18083' / 'deploy' / 'docker-compose.yml').read_text())
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
def test_wrong_or_stale_confirmation_changes_nothing(self):
"""Fails if a confirmation that is not this plan's, or one for another port or operation, is accepted."""
token = self.token('install', 18083)
for bad in (token[:-1] + ('0' if token[-1] != '0' else '1'), token.replace('instalar', 'reinstalar'),
token.replace('18083', '18084')):
with self.subTest(bad), self.assertRaises((RuntimeError, ValueError)):
self.operate('install', 18083, bad)
self.assertEqual(self.docker.mutating(), [])
self.assertIsNone(self.record(18083))
def test_protected_ports_are_refused_before_anything_is_looked_at(self):
"""Fails if a protected port, reference installations included, can be planned or installed."""
for port in (18087, 4397, 18090, 18096, 18097):
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
self.operate('install', port)
self.assertEqual(self.docker.calls, [])
def test_port_held_by_a_foreign_container_is_refused(self):
"""Fails if a port that another container publishes is treated as free."""
self.docker.add_foreign('someone-else', ports=[18083])
with self.assertRaisesRegex(RuntimeError, 'holds port 18083'):
self.operate('install', 18083)
self.assertEqual(self.docker.mutating(), [])
def test_port_listened_on_by_the_host_is_refused(self):
"""Fails if a port taken by a non-Docker process is treated as free."""
self.busy.add(18083)
with self.assertRaisesRegex(OSError, 'in use'):
self.operate('install', 18083)
self.assertEqual(self.docker.mutating(), [])
def test_registered_port_is_refused_whoever_owns_it(self):
"""Fails if install proceeds over a registered port, a DEV one or not."""
self.install(18083)
with self.assertRaisesRegex(RuntimeError, 'already registered'):
self.operate('install', 18083)
other = self.registry_dir / 'isssteleon-clinic-west'
(other / 'data').mkdir(parents=True)
registry.write_record(other, {'project': 'isssteleon-clinic-west', 'port': 18084, 'status': 'installed'})
with self.assertRaisesRegex(RuntimeError, 'already registered'):
self.operate('install', 18084)
def test_existing_docker_resources_of_the_project_refuse_the_install(self):
"""Fails if a leftover network or volume with the project's name is adopted by a new install."""
self.docker.add_volume('isssteleon-dev-18083_trabajos_notebooks')
with self.assertRaisesRegex(RuntimeError, 'unexpected volume|already holds'):
self.operate('install', 18083)
def test_build_failure_leaves_nothing_registered(self):
"""Fails if a failed image build still reserves the port or creates a directory."""
token = self.token('install', 18083)
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'build failed'))
if a[1] == 'build' else None)
with self.assertRaises(subprocess.CalledProcessError):
self.operate('install', 18083, token)
self.assertEqual(list(self.registry_dir.iterdir()), [])
def test_start_failure_is_recorded_on_the_instance(self):
"""Fails if a failed start leaves the record as installed or without the error and diagnostics."""
token = self.token('install', 18083)
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'cannot start'))
if a[1] == 'compose' and 'up' in a else None)
with self.assertRaises(subprocess.CalledProcessError):
self.operate('install', 18083, token)
record = self.record(18083)
self.assertEqual(record['status'], 'failed')
self.assertIn('cannot start', record['error'])
self.assertIn('ps output', record['diagnostics'])
def test_unhealthy_endpoint_fails_the_install(self):
"""Fails if an installation whose published port does not answer as the platform is marked installed."""
self.host.responses['/health'] = {'status': 200, 'body': '{"status": "starting"}'}
token = self.token('install', 18083)
with self.assertRaisesRegex(RuntimeError, 'health'):
self.operate('install', 18083, token)
self.assertEqual(self.record(18083)['status'], 'failed')
def test_unsafe_composition_is_refused_while_planning(self):
"""Fails if a composition with a privileged service reaches the plan."""
original = fakedocker.compose_config
def unsafe(project, env, notebooks=True):
config = original(project, env, notebooks)
config['services']['webapi']['privileged'] = True
return config
with patch.object(fakedocker, 'compose_config', unsafe), self.assertRaisesRegex(RuntimeError, 'unsafe'):
self.operate('install', 18083)
class ReinstallTests(FlowCase):
def seed_foreign(self):
"""Resources of another installation and unrelated ones that a reinstall of 18083 must not touch."""
self.docker.add_volume('isssteleon-dev-18084_trabajos_notebooks',
{'com.docker.compose.project': 'isssteleon-dev-18084'})
self.docker.add_volume('isssteleon-dev-18083x_data')
net = self.docker.add_network('isssteleon-dev-18084_default', {'com.docker.compose.project': 'isssteleon-dev-18084'})
self.docker.add_foreign('isssteleon-dev-18084-webapp-1', networks=('isssteleon-dev-18084_default',), ports=[18084],
labels={'com.docker.compose.project': 'isssteleon-dev-18084'})
self.docker.add_foreign('unrelated', ports=[9999])
return net
def test_reinstall_replaces_the_instance_and_removes_only_its_resources(self):
"""Fails if a reinstall leaves old containers, data, volume or network, or touches any other resource."""
record = self.install(18083)
data = self.registry_dir / 'isssteleon-dev-18083' / 'data'
(data / 'cacu.db').write_text('synthetic')
self.seed_foreign()
foreign_before = {i for i, c in self.docker.containers.items()
if c['Config']['Labels'].get('com.docker.compose.project') != 'isssteleon-dev-18083'}
old = set(self.project_containers(18083))
old_volume = dict(self.docker.volumes['isssteleon-dev-18083_trabajos_notebooks'])
self.commit = SHA_B
token = self.token('reinstall', 18083)
self.docker.calls.clear()
self.operate('reinstall', 18083, token)
new = self.record(18083)
self.assertEqual((new['status'], new['result'], new['revision']), ('installed', 'reinstalled', SHA_B))
self.assertEqual(new['replaced']['revision'], record['revision'])
self.assertTrue(old.isdisjoint(self.project_containers(18083)))
self.assertEqual(len(self.project_containers(18083)), 4)
self.assertFalse((data / 'cacu.db').exists())
self.assertTrue(foreign_before <= set(self.docker.containers))
for name in ('isssteleon-dev-18084_trabajos_notebooks', 'isssteleon-dev-18083x_data'):
self.assertIn(name, self.docker.volumes)
self.assertEqual(len([n for n in self.docker.networks.values() if n['Name'].startswith('isssteleon-dev-1808')]), 2)
self.assertNotEqual(old_volume, None)
removed = [c for c in self.docker.calls if c[1] in ('stop', 'rm', 'update')]
self.assertTrue(all(c[-1] in old for c in removed), removed)
self.assertEqual([c[3] for c in self.docker.calls if c[1:3] == ['volume', 'rm']],
['isssteleon-dev-18083_trabajos_notebooks'])
def test_no_global_cleanup_command_is_ever_issued(self):
"""Fails if a reinstall issues prune, system, forced removal or compose down."""
self.install(18083)
self.docker.calls.clear()
self.operate('reinstall', 18083, self.token('reinstall', 18083))
for call in self.docker.calls:
self.assertNotIn('prune', call)
self.assertNotIn('system', call[1:2])
self.assertNotIn('down', call)
self.assertNotIn('-f', call[2:3] if call[1] == 'rm' else [])
def test_reinstall_without_a_registered_instance_is_refused(self):
"""Fails if a free or foreign-held port is accepted by reinstall because nothing is registered."""
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
self.operate('reinstall', 18083)
self.docker.add_foreign('someone-else', ports=[18085])
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
self.operate('reinstall', 18085)
self.assertEqual(self.docker.mutating(), [])
def test_protected_ports_are_never_reinstalled_even_when_registered(self):
"""Fails if a record on a protected port, reference installations included, lets a reinstall be planned."""
for port in (18087, 4397, 18090, 18096, 18097):
directory = self.registry_dir / f'isssteleon-dev-{port}'
(directory / 'data').mkdir(parents=True)
registry.write_record(directory, {'project': directory.name, 'port': port, 'status': 'installed',
'installer': registry.INSTALLER, 'revision': SHA_A})
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
self.operate('reinstall', port)
def test_instance_not_proven_to_be_dev_is_refused(self):
"""Fails if a registered instance of another installer, name or state is planned for removal."""
directory = self.registry_dir / 'isssteleon-clinic-west'
(directory / 'data').mkdir(parents=True)
registry.write_record(directory, {'project': directory.name, 'port': 18083, 'status': 'installed',
'revision': SHA_A})
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
self.operate('reinstall', 18083)
self.install(18084)
record = self.record(18084)
for changes, message in (({'installer': 'someone-else'}, 'does not prove'),
({'status': 'update_failed'}, 'not replaceable')):
registry.write_record(self.registry_dir / 'isssteleon-dev-18084', dict(record, **changes))
with self.subTest(changes), self.assertRaisesRegex(RuntimeError, message):
self.operate('reinstall', 18084)
self.assertEqual(self.docker.mutating()[-1][1:2], ['compose'])
def test_earlier_dev_records_are_accepted_when_their_resources_match(self):
"""Fails if instances installed before the owner marker existed can never be reinstalled."""
self.install(18083)
record = self.record(18083)
legacy = {k: v for k, v in record.items() if k not in ('installer', 'plan_digest')}
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', legacy)
self.operate('reinstall', 18083, self.token('reinstall', 18083))
self.assertEqual(self.record(18083)['installer'], registry.INSTALLER)
def test_container_on_an_unrecorded_image_is_not_the_installations_own(self):
"""Fails if a container of the project label running some other image is removed as if it were the instance's."""
self.install(18083)
ident = self.docker.add_foreign('isssteleon-dev-18083-webapp-9', networks=('isssteleon-dev-18083_default',),
labels={'com.docker.compose.project': 'isssteleon-dev-18083',
'com.docker.compose.service': 'webapp'}, image='sha256:other')
with self.assertRaisesRegex(RuntimeError, 'image of the installation record|unexpected name'):
self.operate('reinstall', 18083)
self.assertIn(ident, self.docker.containers)
def test_foreign_container_sharing_storage_volume_network_or_port_refuses_the_plan(self):
"""Fails if a plan is produced while another container can reach the instance's data, jobs or network."""
self.install(18083)
cases = {
'storage': dict(mounts=[{'Type': 'bind', 'Source': '/srv/dev-test', 'Destination': '/x', 'RW': True}]),
'volume': dict(mounts=[{'Type': 'volume', 'Name': 'isssteleon-dev-18083_trabajos_notebooks',
'Destination': '/j', 'RW': True}]),
'network': dict(networks=('isssteleon-dev-18083_default',)),
}
for label, spec in cases.items():
ident = self.docker.add_foreign('reader-' + label, **spec)
with self.subTest(label), self.assertRaisesRegex(RuntimeError, 'shares|holds'):
self.operate('reinstall', 18083)
self.docker.containers.pop(ident)
def test_reference_that_moves_between_plan_and_execution_changes_the_confirmation(self):
"""Fails if an approval given for one commit installs another that the reference moved to."""
self.install(18083)
token = self.token('reinstall', 18083)
self.commit = SHA_B
before = sorted(self.docker.containers)
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
self.operate('reinstall', 18083, token)
self.assertEqual(sorted(self.docker.containers), before)
def test_reference_that_moves_after_the_build_stops_before_removal(self):
"""Fails if the final revalidation does not notice a reference that moved while images were being built."""
self.install(18083)
token = self.token('reinstall', 18083)
self.docker.hooks.append(lambda d, a: setattr(self, 'commit', SHA_B) if a[1] == 'build' else None)
before = sorted(self.docker.containers)
with self.assertRaisesRegex(RuntimeError, 'moved after the plan'):
self.operate('reinstall', 18083, token)
self.assertEqual(sorted(self.docker.containers), before)
self.assertEqual(self.record(18083)['status'], 'installed')
def test_resources_that_change_after_the_build_stop_before_removal(self):
"""Fails if a container that appears on the instance's volume after the plan does not stop the removal."""
self.install(18083)
token = self.token('reinstall', 18083)
count = {'builds': 0}
def intrude(daemon, args):
if args[1] == 'build':
count['builds'] += 1
if count['builds'] == 2:
daemon.add_foreign('late-reader', mounts=[{'Type': 'volume', 'Destination': '/j', 'RW': True,
'Name': 'isssteleon-dev-18083_trabajos_notebooks'}])
self.docker.hooks.append(intrude)
before = {i for i, c in self.docker.containers.items() if c['Name'] != '/late-reader'}
with self.assertRaisesRegex(RuntimeError, 'shares'):
self.operate('reinstall', 18083, token)
self.assertTrue(before <= set(self.docker.containers))
self.assertEqual(self.record(18083)['status'], 'installed')
def test_build_failure_leaves_the_running_instance_untouched(self):
"""Fails if the old instance is removed before the new images are known to build."""
self.install(18083)
token = self.token('reinstall', 18083)
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'build failed'))
if a[1] == 'build' else None)
before = sorted(self.docker.containers)
with self.assertRaises(subprocess.CalledProcessError):
self.operate('reinstall', 18083, token)
self.assertEqual(sorted(self.docker.containers), before)
self.assertEqual(self.record(18083)['status'], 'installed')
def test_failure_while_removing_keeps_the_rest_and_needs_a_new_confirmation(self):
"""Fails if a failed removal loses the record, continues anyway, or lets the old confirmation resume it."""
self.install(18083)
token = self.token('reinstall', 18083)
stops = []
def fail_second_stop(daemon, args):
if args[1] == 'stop':
stops.append(args[2])
if len(stops) == 2:
raise fakedocker.failure(args, 'cannot stop')
self.docker.hooks.append(fail_second_stop)
with self.assertRaisesRegex(RuntimeError, 'removal stopped during containers'):
self.operate('reinstall', 18083, token)
record = self.record(18083)
self.assertEqual(record['status'], 'removing')
self.assertEqual(record['reinstall']['phase'], 'containers')
self.assertIn('cannot stop', record['reinstall']['error'])
self.assertEqual(len(self.project_containers(18083)), 3)
self.assertIn('isssteleon-dev-18083_trabajos_notebooks', self.docker.volumes)
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
self.operate('reinstall', 18083, token)
self.docker.hooks.clear()
self.operate('reinstall', 18083, self.token('reinstall', 18083))
self.assertEqual(self.record(18083)['status'], 'installed')
self.assertEqual(len(self.project_containers(18083)), 4)
def test_volume_replaced_during_the_removal_is_not_deleted(self):
"""Fails if the jobs volume is removed by name after something else recreated it since the plan."""
self.install(18083)
token = self.token('reinstall', 18083)
def recreate(daemon, args):
if args[1] == 'rm':
daemon.volumes['isssteleon-dev-18083_trabajos_notebooks']['CreatedAt'] = '2030-01-01T00:00:00Z'
self.docker.hooks.append(recreate)
with self.assertRaisesRegex(RuntimeError, 'removal stopped during volume.*changed since the plan'):
self.operate('reinstall', 18083, token)
self.assertIn('isssteleon-dev-18083_trabajos_notebooks', self.docker.volumes)
self.assertEqual(self.record(18083)['status'], 'removing')
def test_failure_while_installing_after_removal_is_recorded_and_can_be_retried(self):
"""Fails if a start failure after the removal leaves no record, or blocks the next reinstall."""
self.install(18083)
token = self.token('reinstall', 18083)
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'cannot start'))
if a[1] == 'compose' and 'up' in a else None)
with self.assertRaises(subprocess.CalledProcessError):
self.operate('reinstall', 18083, token)
self.assertEqual(self.record(18083)['status'], 'failed')
self.assertIn('replaced', self.record(18083))
self.docker.hooks.clear()
self.operate('reinstall', 18083, self.token('reinstall', 18083))
self.assertEqual(self.record(18083)['status'], 'installed')
class EntryPointTests(unittest.TestCase):
def test_arguments_are_checked(self):
"""Fails if the command line accepts a missing reference, an unknown command or extra arguments."""
for argv in ([], ['install'], ['install', '18083'], ['purge', '1', '2'], ['install', '1', '2', '3', '4'],
['validate-dispatch', 'x']):
with self.subTest(argv), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(installer.main(argv), 1)
def test_dispatch_identity_is_validated(self):
"""Fails if a dispatch from another repository, server, ref type or SHA is accepted."""
good = {'DISPATCH_REPOSITORY': 'ISSSTELEON/WorkingNarrative', 'DISPATCH_SERVER': 'http://10.0.10.41:3000',
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
'DISPATCH_SHA': SHA_A}
with patch.object(proc, 'run', lambda args, **kw: ''), patch.object(proc, 'git', lambda *a, **k: SHA_A + '\n'):
with patch.dict('os.environ', good):
self.assertEqual(installer.dispatch_metadata()['workflow_sha'], SHA_A)
for key, value in (('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'),
('DISPATCH_REF_TYPE', 'tag'), ('DISPATCH_REF', 'refs/heads/other'),
('DISPATCH_SHA', 'xyz')):
with self.subTest(key), patch.dict('os.environ', {**good, key: value}), self.assertRaises(ValueError):
installer.dispatch_metadata()
if __name__ == '__main__':
unittest.main()
-862
View File
@@ -1,862 +0,0 @@
"""The notebook composition: jobs volume guard, active-run detection, installer checks and updates.
Fixtures: `jobs` builds a jobs volume as a plain directory (finished, pending and partial job folders);
`mlflow` writes a minimal MLflow store with notebook and other runs; `NotebookDeployment` extends the
simulated deployment of `test_conservative` with the `notebooks` service, the `trabajos_notebooks`
volume (a local directory) and the real host, data and notebook guards. No daemon is contacted.
"""
from contextlib import closing
import copy
import json
import os
from pathlib import Path, PurePosixPath
import sqlite3
import stat
import tempfile
import time
import unittest
from unittest.mock import patch
import conservative
import data_guard
import dev
import host
import notebook_guard
from test_conservative import SimulatedDeployment, fixture
POSIX = os.name == 'posix'
VOLUME_KEY = dev.NOTEBOOK_VOLUME
def jobs(root, *, finished=('run-a',), pending=(), partial=()):
"""Create job folders as the WebApi and the runner leave them: finished ones have `result.json`."""
root.mkdir(parents=True, exist_ok=True)
for name in finished:
(root / name / 'trabajo').mkdir(parents=True)
(root / name / 'job.json').write_text('{"run_id": "%s"}' % name)
(root / name / 'result.json').write_text('{"ok": true}')
(root / name / 'page.html').write_text('<p>synthetic</p>')
(root / name / 'trabajo' / 'salida.bin').write_bytes(b'\x00synthetic')
for name in pending:
(root / name).mkdir()
(root / name / 'job.json').write_text('{}')
for name in partial:
(root / name).mkdir()
return root
def mlflow(root, runs):
"""Write `mlflow.db` with MLflow's run and tag columns; `runs` is (id, status, start_ms, kind)."""
with closing(sqlite3.connect(root / 'mlflow.db')) as connection:
connection.executescript(
'CREATE TABLE runs (run_uuid TEXT PRIMARY KEY, status TEXT, lifecycle_stage TEXT, start_time INTEGER);'
'CREATE TABLE tags (key TEXT, value TEXT, run_uuid TEXT, PRIMARY KEY (key, run_uuid));')
for run_id, status, start, kind in runs:
connection.execute('INSERT INTO runs VALUES (?, ?, ?, ?)', (run_id, status, 'active', start))
connection.execute('INSERT INTO tags VALUES (?, ?, ?)', ('experiment', kind, run_id))
connection.commit()
class NotebookGuardTests(unittest.TestCase):
"""The jobs volume guard on local directories."""
def setUp(self):
"""Reserve a private directory for a synthetic volume and its backups."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
def test_activity_classifies_unfinished_and_unknown_entries(self):
"""Pending, partial, incomplete and stray entries are active; finished jobs are not.
Fails if a job without `result.json` or a folder being assembled can be backed up and interrupted."""
root = jobs(self.base / 'volume', finished=('run-a',), pending=('run-b',), partial=('.run-c-x',))
(root / 'run-d').mkdir()
(root / 'stray.txt').write_text('x')
entries = notebook_guard.scan(root)
self.assertEqual(notebook_guard.activity(entries), {
'run-b': 'pending', '.run-c-x': 'assembling', 'run-d': 'incomplete', 'stray.txt': 'unexpected'})
summary = notebook_guard.inspect(jobs(self.base / 'done', finished=('run-a', 'run-e')))
self.assertEqual((summary['active'], summary['jobs']), ([], 2))
def test_backup_round_trip_preserves_content_and_metadata(self):
"""A backup and its restore reproduce every entry, mode and time of the volume.
Fails if the copy drops a file, changes its bytes or loses its metadata, or restores into a
non-empty directory."""
root = jobs(self.base / 'volume', finished=('run-a', 'run-b'))
before = notebook_guard.scan(root)
destination = self.base / 'backup'
destination.mkdir()
result = notebook_guard.backup(root, destination, {'name': 'synthetic'})
self.assertEqual(result['digest'], notebook_guard.state_digest(before))
self.assertEqual(notebook_guard.scan(root), before)
restored = self.base / 'restored'
self.assertEqual(notebook_guard.restore(destination, restored)['digest'], result['digest'])
self.assertEqual(notebook_guard.scan(restored), before)
with self.assertRaisesRegex(RuntimeError, 'not empty'):
notebook_guard.restore(destination, restored)
def test_backup_rejects_active_jobs_and_concurrent_writes(self):
"""No backup is written while a job is pending or when the volume changes during the copy.
Fails if the guard accepts an inconsistent snapshot."""
root = jobs(self.base / 'volume', pending=('run-b',))
destination = self.base / 'backup'
destination.mkdir()
with self.assertRaisesRegex(RuntimeError, 'notebook jobs are active'):
notebook_guard.backup(root, destination, {})
self.assertEqual(list(destination.iterdir()), [])
(root / 'run-b' / 'result.json').write_text('{}')
original = notebook_guard.copy_entries
def copy_and_write(source, target, entries):
original(source, target, entries)
(Path(source) / 'run-b' / 'late.txt').write_text('late')
with patch.object(notebook_guard, 'copy_entries', side_effect=copy_and_write), \
self.assertRaisesRegex(RuntimeError, 'changed while creating the backup'):
notebook_guard.backup(root, destination, {})
self.assertFalse((destination / 'manifest.json').exists())
def test_corrupted_backup_is_rejected(self):
"""Verification and restore read every file against the manifest.
Fails if a changed or missing backup file can be restored."""
root = jobs(self.base / 'volume')
destination = self.base / 'backup'
destination.mkdir()
notebook_guard.backup(root, destination, {})
(destination / 'content' / 'run-a' / 'page.html').write_text('tampered')
with self.assertRaisesRegex(RuntimeError, 'content differs'):
notebook_guard.verify_backup(destination)
with self.assertRaisesRegex(RuntimeError, 'content differs'):
notebook_guard.restore(destination, self.base / 'restored')
self.assertFalse((self.base / 'restored').exists())
@unittest.skipUnless(POSIX, 'symbolic links and FIFOs need a POSIX filesystem')
def test_links_are_kept_and_special_files_rejected(self):
"""A link a notebook planted is copied as a link, never followed; a FIFO stops the backup.
Fails if the guard reads through a link to files outside the volume or blocks on a FIFO."""
root = jobs(self.base / 'volume')
outside = self.base / 'secret'
outside.write_text('host data')
os.symlink(outside, root / 'run-a' / 'trabajo' / 'enlace')
destination = self.base / 'backup'
destination.mkdir()
notebook_guard.backup(root, destination, {})
copied = destination / 'content' / 'run-a' / 'trabajo' / 'enlace'
self.assertTrue(copied.is_symlink())
self.assertEqual(os.readlink(copied), str(outside))
os.mkfifo(root / 'run-a' / 'trabajo' / 'tuberia')
with self.assertRaisesRegex(RuntimeError, 'entry type is unsupported'):
notebook_guard.scan(root)
@unittest.skipUnless(POSIX and hasattr(os, 'geteuid') and os.geteuid() == 0, 'restoring owners needs root')
def test_restore_keeps_the_runner_owner(self):
"""Folders handed to the runner (uid 10001) keep that owner through backup and restore.
Fails if a restored job becomes root-owned, which would stop the runner from writing its result."""
root = jobs(self.base / 'volume')
for path in [root / 'run-a', *(root / 'run-a').rglob('*')]:
os.lchown(path, 10001, 10001)
destination = self.base / 'backup'
destination.mkdir()
notebook_guard.backup(root, destination, {})
restored = self.base / 'restored'
notebook_guard.restore(destination, restored)
self.assertEqual(os.lstat(restored / 'run-a' / 'job.json').st_uid, 10001)
class NotebookRunTests(unittest.TestCase):
"""Active notebook runs read from a synthetic MLflow store."""
def setUp(self):
"""Reserve a private data directory."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.data = Path(self.temp.name)
def test_only_recent_running_notebook_runs_count(self):
"""Running notebook runs within the timeout count; finished, stale and other runs do not.
Fails if a queued run is missed (the update would kill it) or a run MLflow already shows as
interrupted blocks updates forever."""
now = int(time.time() * 1000)
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now), {'active': 0, 'training': 0})
mlflow(self.data, [('queued', 'RUNNING', now - 1000, 'notebook'),
('finished', 'FINISHED', now - 1000, 'notebook'),
('stale', 'RUNNING', now - (3600 + 1801) * 1000, 'notebook'),
('training', 'RUNNING', now - 1000, 'training')])
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now), {'active': 1, 'training': 0})
def test_running_trainings_and_learning_count_within_the_request_window(self):
"""With the API's request timeout, other running runs started within it plus the margin count too.
Fails if a `/train` call or the extraction ranker's background learning, which have no notebook tag, can
be cut off by the update, or a run left running by a crash long ago blocks updates forever."""
now = int(time.time() * 1000)
mlflow(self.data, [('learning', 'RUNNING', now - 5000, 'extraccion'),
('orphan', 'RUNNING', now - (600 + 1801) * 1000, 'training'),
('done', 'FINISHED', now - 5000, 'training'),
('notebook', 'RUNNING', now - 5000, 'notebook')])
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now, request_timeout_s=600),
{'active': 1, 'training': 1})
def test_unexpected_mlflow_schema_is_unverifiable(self):
"""A store without MLflow's run columns cannot prove no run is active.
Fails if the check silently reports zero runs on a schema it does not understand."""
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
connection.execute('CREATE TABLE runs (id INTEGER PRIMARY KEY)')
with self.assertRaisesRegex(RuntimeError, 'unverifiable'):
data_guard.notebook_runs(self.data, 3600, 0)
def test_worker_module_prefers_the_current_queue(self):
"""The runtime action finds the worker module on disk, newest first.
Fails if an image with `webapi.recomputation` is configured with the removed module."""
package = self.data / 'pkg' / 'webapi'
package.mkdir(parents=True)
(package / '__init__.py').write_text('')
spec = type('Spec', (), {'submodule_search_locations': [str(package)]})()
with patch.object(data_guard.importlib.util, 'find_spec', return_value=spec):
with self.assertRaisesRegex(RuntimeError, 'worker module is unavailable'):
data_guard.worker_module()
(package / 'indicadores_vivos.py').write_text('')
self.assertEqual(data_guard.worker_module(), 'webapi.indicadores_vivos')
(package / 'recomputation.py').write_text('')
self.assertEqual(data_guard.worker_module(), 'webapi.recomputation')
def test_recalculation_uses_the_current_queue_methods(self):
"""`RecomputationQueue.take/run/pending` drive the one-shot recalculation.
Fails if the guard still imports `ColaDeRecalculo` from an image that no longer has it."""
calls = []
class Queue:
def take(self, domain):
calls.append(('take', domain))
def run(self, domain):
calls.append(('run', domain))
return {'estado': 'ok'}
def pending(self):
return []
module = type('Module', (), {'RecomputationQueue': Queue})
with patch.object(data_guard, 'worker_module', return_value='webapi.recomputation'), \
patch.object(data_guard.importlib, 'import_module', return_value=module), \
patch.dict(os.environ):
self.assertEqual(data_guard.recalculate({}), {'completed': ['cacu', 'cama', 'tea']})
self.assertEqual(calls, [(step, domain) for domain in ('cacu', 'cama', 'tea') for step in ('take', 'run')])
def test_worker_entrypoint_follows_the_image(self):
"""The controlled worker runs the module the image provides; an unknown one is refused.
Fails if the worker is started with a module the candidate image does not contain."""
config = {'services': {'webapi': {'environment': {}}, 'indicadores': {'environment': {}}}}
result = conservative.controlled_config(copy.deepcopy(config), worker='webapi.recomputation')
self.assertEqual(result['services']['indicadores']['entrypoint'][-1], 'webapi.recomputation')
with self.assertRaisesRegex(RuntimeError, 'unsupported worker module'):
conservative.controlled_config(copy.deepcopy(config), worker='webapi.other')
def compose_config(project, data, tag, port):
"""The effective configuration `docker compose config` prints for `dist/docker-compose.yml`."""
env = {f'{x}_DATABASE_URL': f'sqlite:////data/{x.lower()}.db' for x in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')}
api = {'image': 'isssteleon/webapi:' + tag, 'environment': dict(env),
'volumes': [{'type': 'bind', 'source': str(data), 'target': '/data', 'bind': {}}]}
jobs_mount = {'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos', 'volume': {}}
webapi = copy.deepcopy(api)
webapi['volumes'].append(dict(jobs_mount))
webapi['environment'].update(NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')
return {'name': project, 'services': {
'webapi': webapi, 'indicadores': dict(copy.deepcopy(api), command=['indicadores']),
'notebooks': {'image': 'isssteleon/webapi:' + tag, 'command': ['notebooks'], 'user': '10001:10001',
'network_mode': 'none', 'read_only': True, 'tmpfs': ['/tmp'], 'cap_drop': ['ALL'],
'security_opt': ['no-new-privileges:true'], 'pids_limit': 256,
'environment': {'NOTEBOOK_JOBS_DIR': '/trabajos', 'NOTEBOOK_RENDERER': 'jupyter',
'HOME': '/tmp', 'JUPYTER_RUNTIME_DIR': '/tmp/jupyter'},
'volumes': [dict(jobs_mount)]},
'webapp': {'image': 'isssteleon/webapp:' + tag, 'ports': [{'published': str(port), 'target': 80}]}},
'volumes': {VOLUME_KEY: {'name': project + '_' + VOLUME_KEY}}}
class InstallerCompositionTests(unittest.TestCase):
"""`dev.verify_config` on the notebook composition and its profile-gated service."""
project, data, tag, port = 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080
def verify(self, config):
return dev.verify_config(config, self.project, self.data, self.tag, self.port)
def test_notebook_composition_is_accepted_with_its_volume(self):
"""The real four-service composition passes and reports its project-scoped volume.
Fails if the installer keeps requiring exactly three services or forgets the volume name."""
config = compose_config(self.project, self.data, self.tag, self.port)
for network in ({'name': self.project + '_default'}, {'name': self.project + '_default', 'ipam': {}}):
config['networks'] = {'default': network}
self.assertEqual(self.verify(config), 'isssteleon-x_trabajos_notebooks')
def test_profile_service_is_allowed_only_while_declared_and_isolated(self):
"""`entrenar` may appear with its profile and the API's single data mount, never otherwise.
Fails if an enabled profile can add a service with other mounts, ports or no profile at all."""
config = compose_config(self.project, self.data, self.tag, self.port)
trainer = dict(copy.deepcopy(config['services']['indicadores']), command=['entrenar'], profiles=['entrenar'])
config['services']['entrenar'] = trainer
self.assertEqual(self.verify(config), 'isssteleon-x_trabajos_notebooks')
for change in ('no-profile', 'jobs-mount', 'ports', 'other-service'):
altered = copy.deepcopy(config)
service = altered['services']['entrenar']
if change == 'no-profile':
service.pop('profiles')
if change == 'jobs-mount':
service['volumes'].append({'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos'})
if change == 'ports':
service['ports'] = [{'published': '9000', 'target': 5000}]
if change == 'other-service':
altered['services']['otro'] = dict(service, profiles=['otro'])
with self.subTest(change=change), self.assertRaises(RuntimeError):
self.verify(altered)
def test_notebook_isolation_and_mounts_are_enforced(self):
"""Every mount, namespace and identity setting of the runner and the jobs volume is checked.
Fails if a variation that gives notebooks the database folder, the network, root or a volume
that Compose would not create for this project passes the installer."""
config = compose_config(self.project, self.data, self.tag, self.port)
def runner(altered):
return altered['services']['notebooks']
changes = {
'runner-data': lambda c: runner(c)['volumes'].append(
{'type': 'bind', 'source': str(self.data), 'target': '/data'}),
'runner-network': lambda c: runner(c).update(network_mode='bridge'),
'runner-root': lambda c: runner(c).update(user='0:0'),
'runner-writable': lambda c: runner(c).update(read_only=False),
'runner-caps': lambda c: runner(c).update(cap_drop=[]),
'runner-privileges': lambda c: runner(c).update(security_opt=[]),
'runner-cap-add': lambda c: runner(c).update(cap_add=['SYS_ADMIN']),
'runner-hook': lambda c: runner(c).update(post_start=[{'command': 'true', 'privileged': True}]),
'runner-docker-socket': lambda c: runner(c).update(use_api_socket=True),
'external-network': lambda c: c.update(networks={'default': {'name': 'shared', 'external': True}}),
'runner-entrypoint': lambda c: runner(c).update(entrypoint=['sh']),
'runner-database': lambda c: runner(c)['environment'].update(CACU_DATABASE_URL='sqlite:////data/cacu.db'),
'runner-image': lambda c: runner(c).update(image='python:3.12'),
'jobs-readonly': lambda c: c['services']['webapi']['volumes'][1].update(read_only=True),
'jobs-subpath': lambda c: c['services']['webapi']['volumes'][1].update(volume={'subpath': 'x'}),
'api-without-jobs': lambda c: c['services']['webapi']['volumes'].pop(),
'worker-with-jobs': lambda c: c['services']['indicadores']['volumes'].append(
{'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos'}),
'api-runner-uid': lambda c: c['services']['webapi']['environment'].update(NOTEBOOK_RUNNER_UID='0'),
'external-volume': lambda c: c['volumes'][VOLUME_KEY].update(external=True),
'volume-options': lambda c: c['volumes'][VOLUME_KEY].update(driver_opts={'type': 'none', 'o': 'bind'}),
'volume-name': lambda c: c['volumes'][VOLUME_KEY].update(name='shared'),
'extra-volume': lambda c: c['volumes'].update(otro={'name': 'otro'}),
'missing-runner': lambda c: c['services'].pop('notebooks'),
}
for name, change in changes.items():
altered = copy.deepcopy(config)
change(altered)
with self.subTest(change=name), self.assertRaises(RuntimeError):
self.verify(altered)
def test_three_service_composition_is_still_accepted(self):
"""A composition without notebooks still installs and reports no volume.
Fails if records and updates of existing three-service installations stop being recognized."""
config = compose_config(self.project, self.data, self.tag, self.port)
config['services'].pop('notebooks')
config.pop('volumes')
config['services']['webapi']['volumes'].pop()
self.assertIsNone(self.verify(config))
def volume_inspect(project, **changes):
"""`docker volume inspect` output for a Compose-created jobs volume of `project`."""
item = {'Name': project + '_' + VOLUME_KEY, 'Driver': 'local', 'Scope': 'local', 'Options': None,
'CreatedAt': '2026-11-17T00:00:00Z', 'Mountpoint': '/var/lib/docker/volumes/x/_data',
'Labels': {'com.docker.compose.project': project, 'com.docker.compose.volume': VOLUME_KEY}}
item.update(changes)
return item
class InstallerVolumeTests(unittest.TestCase):
"""Volume identity, reservation and running-container checks with a fake Docker CLI."""
project = 'isssteleon-dev-18081'
def fake(self, volumes, containers=()):
def run(args, **kwargs):
if args[1:3] == ['volume', 'ls'] and '--filter' in args and args[-1].startswith('name='):
return '\n'.join(item['Name'] for item in volumes) + '\n'
if args[1:3] == ['volume', 'ls']:
return ''
if args[1:3] == ['volume', 'inspect']:
return json.dumps([item for item in volumes if item['Name'] == args[-1]])
if args[1:3] == ['image', 'inspect']:
return 'api-id' if args[-1] == 'api-tag' else 'app-id'
if args[1] == 'ps':
return '\n'.join(item['Id'] for item in containers)
if args[1] == 'inspect':
return json.dumps(list(containers))
return ''
return run
def test_volume_identity_requires_compose_ownership(self):
"""Only a local, option-free volume labelled for this project and key is this installation's.
Fails if a hand-made, foreign or bind-backed volume with the expected name is adopted."""
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project)])):
self.assertEqual(dev.notebook_volume_identity(self.project)['name'], self.project + '_' + VOLUME_KEY)
for change in ({'Labels': None}, {'Labels': {'com.docker.compose.project': 'other',
'com.docker.compose.volume': VOLUME_KEY}},
{'Options': {'type': 'none', 'o': 'bind', 'device': '/srv'}}, {'Driver': 'nfs'},
{'Mountpoint': ''}):
with self.subTest(change=change), \
patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, **change)])), \
self.assertRaisesRegex(RuntimeError, 'not verifiable'):
dev.notebook_volume_identity(self.project)
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect('isssteleon-dev-180811')])):
self.assertIsNone(dev.notebook_volume_identity(self.project, missing_ok=True))
with self.assertRaisesRegex(RuntimeError, 'missing'):
dev.notebook_volume_identity(self.project)
def test_reservation_rejects_an_existing_volume_name(self):
"""A fresh installation never starts when a volume with its jobs name already exists.
Fails if Compose would silently adopt an unlabelled or foreign volume for a new installation."""
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, Labels=None)])), \
patch.object(dev, 'host_action') as action, self.assertRaisesRegex(RuntimeError, 'already exists'):
dev.reserve('helper', self.project, 18081)
action.assert_not_called()
def containers(self, data):
"""The four running containers of a notebook installation, as `docker inspect` reports them."""
volume = self.project + '_' + VOLUME_KEY
jobs = {'Type': 'volume', 'Name': volume, 'Source': '/var/lib/docker/volumes/x/_data',
'Destination': '/trabajos', 'RW': True}
bind = {'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}
def item(service, mounts, **host):
return {'Id': service, 'Name': '/' + service, 'Image': 'app-id' if service == 'webapp' else 'api-id',
'State': {'Status': 'running'}, 'Mounts': mounts,
'Config': {'Labels': {'com.docker.compose.project': self.project,
'com.docker.compose.service': service},
'User': '10001:10001' if service == 'notebooks' else ''},
'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': '18081'}]} if service == 'webapp' else {},
**host}}
return [item('webapi', [bind, jobs]), item('indicadores', [bind]), item('webapp', []),
item('notebooks', [jobs], NetworkMode='none', ReadonlyRootfs=True, Privileged=False,
CapDrop=['ALL'], CapAdd=None, SecurityOpt=['no-new-privileges:true'])]
def test_running_notebook_installation_is_verified(self):
"""Four owned containers with the expected mounts and runner isolation pass; deviations fail.
Fails if a foreign container can reach the jobs volume, a one-shot `entrenar` writer is ignored,
or the runner gains the network, a writable root or the data folder."""
base = PurePosixPath('/srv/instances')
data = str(base / self.project / 'data')
record = {'project': self.project, 'port': 18081, 'images': ['api-tag', 'app-tag'],
'notebook_volume': self.project + '_' + VOLUME_KEY}
volumes = [volume_inspect(self.project)]
items = self.containers(data)
isolated = {'Networks': {'none': {'NetworkID': 'daemon-none'}}}
items[3]['NetworkSettings'] = isolated
items.append({'Id': 'other-isolated', 'Name': '/other-isolated', 'NetworkSettings': isolated})
with patch.object(dev, 'run', side_effect=self.fake(volumes, items)):
self.assertEqual(dev.verify_existing_containers(record, base, 'helper'),
['indicadores', 'webapi', 'webapp', 'notebooks'])
def foreign_by_name(items):
items.append({'Id': 'x', 'Name': '/x', 'Config': {'Labels': {}}, 'HostConfig': {},
'Mounts': [{'Type': 'volume', 'Name': record['notebook_volume'],
'Source': '/var/lib/docker/volumes/x/_data'}]})
def foreign_by_path(items):
items.append({'Id': 'y', 'Name': '/y', 'Config': {'Labels': {}}, 'HostConfig': {},
'Mounts': [{'Type': 'bind', 'Source': '/var/lib/docker/volumes'}]})
def trainer(items):
items.append(dict(copy.deepcopy(items[1]), Id='t', Name='/t',
Config={'Labels': {'com.docker.compose.project': self.project,
'com.docker.compose.service': 'entrenar',
'com.docker.compose.oneoff': 'True'}}))
def unexpected_port(items):
items[2]['HostConfig']['PortBindings']['80/tcp'].append({'HostPort': '18087'})
changes = {
'foreign-volume': (foreign_by_name, 'foreign container can access notebook jobs'),
'foreign-path': (foreign_by_path, 'foreign container can access notebook jobs'),
'additional-port': (unexpected_port, 'webapp port does not match'),
'trainer': (trainer, 'one-shot entrenar'),
'runner-network': (lambda items: items[3]['HostConfig'].update(NetworkMode='bridge'), 'isolation'),
'runner-writable': (lambda items: items[3]['HostConfig'].update(ReadonlyRootfs=False), 'isolation'),
'runner-root': (lambda items: items[3]['Config'].update(User='0:0'), 'isolation'),
'runner-data': (lambda items: items[3]['Mounts'].append(items[1]['Mounts'][0]), 'notebooks mount'),
'api-without-jobs': (lambda items: items[0]['Mounts'].pop(), 'webapi data mount'),
'runner-missing': (lambda items: items.pop(3), 'missing Compose project containers'),
}
for name, (change, message) in changes.items():
items = self.containers(data)
change(items)
with self.subTest(change=name), patch.object(dev, 'run', side_effect=self.fake(volumes, items)), \
self.assertRaisesRegex(RuntimeError, message):
dev.verify_existing_containers(record, base, 'helper')
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, Labels=None)],
self.containers(data))), \
self.assertRaisesRegex(RuntimeError, 'not verifiable'):
dev.verify_existing_containers(record, base, 'helper')
def test_service_check_includes_the_runner(self):
"""With notebooks, a missing runner container fails the availability check.
Fails if an installation is recorded as available while notebooks can never run."""
def run(args):
if 'ps' in args:
return '' if args[-1] == 'notebooks' else 'container\n'
return json.dumps({'Status': 'running', 'Health': {'Status': 'healthy'}})
with patch.object(dev, 'run', side_effect=run):
dev.verify_services(['compose'], 8080)
with patch.object(dev, 'run', side_effect=run), patch.object(dev.time, 'sleep'), \
patch.object(dev.time, 'monotonic', side_effect=[0, 0, 301]), \
self.assertRaisesRegex(RuntimeError, 'notebooks'):
dev.verify_services(['compose'], 8080, notebooks=True)
class NotebookDeployment(SimulatedDeployment):
"""The simulated deployment with the notebook runner, its volume and the jobs guard on local paths.
`notebooks_old`/`notebooks_new` choose the installed and candidate compositions."""
def __init__(self, root, contract, record, *, notebooks_old=True, notebooks_new=True):
self.notebooks_old, self.notebooks_new = notebooks_old, notebooks_new
self.old_tag = record['images'][0].removeprefix('isssteleon/webapi:')
super().__init__(root, contract, record)
self.volume = root.parent / 'docker-volume'
self.volume_exists = notebooks_old
self.identity = {'name': record['project'] + '_' + VOLUME_KEY, 'created': '2026-11-17T00:00:00Z',
'mountpoint': '/var/lib/docker/volumes/x/_data'}
if notebooks_old and not self.volume.exists():
jobs(self.volume, finished=('run-a',))
self.running['runner'] = True
self.env.update(NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')
self.after_frontend_stop = None
self.guard_calls = []
def ids(self, notebooks):
return ['worker', 'api', 'app'] + (['runner'] if notebooks else [])
def config(self, env):
config = super().config(env)
if not (self.notebooks_old if env['ISSSTELEON_VERSION'] == self.old_tag else self.notebooks_new):
return config
return dict(config, **{key: value for key, value in compose_config(
self.record['project'], self.root / 'data', env['ISSSTELEON_VERSION'], self.record['port']).items()
if key == 'volumes'}, services=dict(config['services'], **{
'webapi': dict(config['services']['webapi'], volumes=config['services']['webapi']['volumes'] + [
{'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos', 'volume': {}}],
environment=dict(config['services']['webapi']['environment'],
NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')),
'notebooks': compose_config(self.record['project'], self.root / 'data', env['ISSSTELEON_VERSION'],
self.record['port'])['services']['notebooks']}))
def run(self, args, **kwargs):
args = list(map(str, args))
if args[:2] == ['docker', 'inspect'] and '--format' not in args:
self.calls.append(args)
return json.dumps([self.container(ident) for ident in args[2:]])
if 'up' in args and args[-1] == 'notebooks' and not self.finished:
raise AssertionError('the runner cannot start before checked recalculation')
if 'up' in args and args[-1] == 'webapi' and self.notebooks_new and not self.volume_exists:
self.volume.mkdir()
self.volume_exists = True
self.identity['created'] = '2026-11-18T00:00:00Z'
if 'up' in args and args[-1] == 'webapp' and self.fail == 'late-job':
raise AssertionError('the frontend started although jobs changed')
output = super().run(args, **kwargs)
if args[:2] == ['docker', 'stop'] and args[-1] == 'app' and self.after_frontend_stop:
self.after_frontend_stop()
return output
def container(self, ident):
"""`docker inspect` of an original container: the worker runs the module of the old image."""
entrypoints = {
'worker': ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos'],
'api': ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn', '--bind', '0.0.0.0:5000', '--workers', '2',
'--timeout', '600', '--access-logfile', '-', 'webapi:create_app()'],
'app': ['/docker-entrypoint.sh'], 'runner': ['/app/WebApi/docker-entrypoint.sh']}
names = {'worker': 'indicadores', 'api': 'webapi', 'app': 'webapp', 'runner': 'notebooks'}
item = {'Id': ident, 'Image': 'old-image', 'Mounts': [], 'State': {'Running': self.running[ident]},
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}},
'Config': {'Labels': {'com.docker.compose.service': names[ident]},
'Env': [k + '=' + v for k, v in self.env.items()] + ['INDICADORES_AL_INICIAR=0'],
'Entrypoint': entrypoints[ident], 'Cmd': []}}
if ident == 'runner':
item['Config'].update(Cmd=['notebooks'], User='10001:10001')
item['HostConfig'].update(NetworkMode='none', ReadonlyRootfs=True)
return item
def notebook_volume_identity(self, project, *, missing_ok=False, verify=True):
if not self.volume_exists:
if missing_ok:
return None
raise RuntimeError('notebook jobs volume is missing')
return dict(self.identity)
def notebook_guard(self, api, image, action, payload, volume, backup=None):
self.guard_calls.append(action)
if action == 'backup' and self.fail == 'notebook-backup':
raise conservative.UpdateRefusal('notebook jobs backup failed (exit=1)')
if action == 'inspect' and self.fail == 'late-job' and self.finished:
(self.volume / 'run-late').mkdir(exist_ok=True)
if action == 'inspect':
return notebook_guard.inspect(self.volume)
if action == 'backup':
return notebook_guard.backup(self.volume, Path(backup), payload['volume'])
raise AssertionError(action)
def host_action(self, helper, action, project, value):
if action == 'prepare-notebook-backup':
host.notebook_backup_directory(self.root.parent, project, value)
return ''
if action == 'verify-notebook-backup':
return json.dumps(host.verify_notebook_backup(self.root.parent, project, value))
if action == 'verify-restore' and self.fail == 'notebook-restore':
(self.root.parent / '.backups' / project / value / 'notebooks' / 'content' / 'run-a' /
'page.html').write_text('tampered')
return super().host_action(helper, action, project, value)
def verify_existing_containers(self, record, base, helper):
super().verify_existing_containers(record, base, helper)
return self.ids(bool(record.get('notebook_volume')))
class NotebookUpdateTests(unittest.TestCase):
"""Conservative updates of installations with and without the notebook runner."""
def setUp(self):
"""Prepare a synthetic installation and its record, without choosing a composition yet."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base)
def deployment(self, *, notebooks_old=True, notebooks_new=True):
if notebooks_old:
self.record['notebook_volume'] = self.record['project'] + '_' + VOLUME_KEY
host.write_record(self.root, self.record)
self.runtime = NotebookDeployment(self.root, self.contract, self.record,
notebooks_old=notebooks_old, notebooks_new=notebooks_new)
return self.runtime
def execute(self, verify_restore=False):
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'notebook_guard', side_effect=self.runtime.notebook_guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed') as freeze:
try:
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base,
verify_restore=verify_restore)
finally:
self.frozen = freeze.call_args
def stops(self):
return [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'stop']]
def ups(self):
return [args[-1] for args in self.runtime.calls if 'up' in args]
def test_update_backs_up_and_keeps_finished_jobs(self):
"""A notebook installation updates with a verified jobs backup and an untouched volume.
Fails if the daemon receives a helper-local path, the jobs volume is changed or skipped by the backup,
or the runner starts after the frontend."""
runtime = self.deployment()
before = notebook_guard.scan(runtime.volume)
self.execute(verify_restore=True)
record = host.read_record(self.root)
self.assertEqual((record['status'], record['result']), ('installed', 'updated'))
self.assertEqual(record['notebook_volume'], self.record['notebook_volume'])
self.assertEqual(notebook_guard.scan(runtime.volume), before)
backup = Path(record['notebook_backup']['path'])
self.assertEqual(backup, self.base / '.backups' / self.record['project'] / record['operation_id'] / 'notebooks')
self.assertEqual(notebook_guard.verify_backup(backup)['digest'], notebook_guard.state_digest(before))
restored = self.base / '.restores' / self.record['project'] / (record['operation_id'] + '.notebooks')
self.assertEqual(notebook_guard.scan(restored), before)
self.assertEqual(self.stops()[0], 'app')
self.assertEqual(self.ups(), ['webapi', 'indicadores', 'notebooks', 'webapp'])
def test_three_service_installation_gains_an_empty_volume(self):
"""An installation from before notebooks updates; Compose creates the volume and it starts empty.
Fails if the old installation is refused, its update skips the runner, or a new volume with
content is accepted."""
runtime = self.deployment(notebooks_old=False)
self.execute()
record = host.read_record(self.root)
self.assertEqual((record['status'], record['notebook_volume']),
('installed', self.record['project'] + '_' + VOLUME_KEY))
self.assertNotIn('notebook_backup', record)
self.assertEqual(self.ups(), ['webapi', 'indicadores', 'notebooks', 'webapp'])
self.assertEqual(notebook_guard.inspect(runtime.volume)['entries'], 1)
def test_existing_volume_blocks_the_first_notebook_update(self):
"""A volume with the jobs name that predates the update is never adopted.
Fails if a hand-made or leftover volume becomes this installation's jobs folder."""
runtime = self.deployment(notebooks_old=False)
runtime.volume_exists = True
with self.assertRaisesRegex(RuntimeError, 'already exists'):
self.execute()
self.assertEqual(self.stops(), [])
self.assertEqual(host.read_record(self.root), self.record)
def test_dropping_the_volume_and_mismatched_records_are_refused(self):
"""A candidate without notebooks, or a record that disagrees with its composition, stops nothing.
Fails if an update orphans the jobs volume or trusts a record whose layout is ambiguous."""
self.deployment(notebooks_new=False)
with self.assertRaisesRegex(RuntimeError, 'drops the notebook jobs volume'):
self.execute()
self.assertEqual(self.stops(), [])
self.record.pop('notebook_volume')
host.write_record(self.root, self.record)
self.runtime = NotebookDeployment(self.root, self.contract, self.record)
with self.assertRaisesRegex(RuntimeError, 'disagree on notebook jobs'):
self.execute()
self.assertEqual(self.stops(), [])
def test_active_runs_and_unfinished_jobs_refuse_before_stopping(self):
"""Queued runs and pending or half-assembled jobs refuse the update while everything runs.
Fails if an update interrupts notebook work or backs up a volume a runner is writing."""
for case in ('runs', 'pending', 'assembling'):
with self.subTest(case=case), tempfile.TemporaryDirectory() as tmp:
self.base = Path(tmp)
self.root, self.contract, self.record = fixture(self.base)
runtime = self.deployment()
if case == 'runs':
runtime.active_runs = 2
elif case == 'pending':
jobs(runtime.volume, finished=(), pending=('run-b',))
else:
(runtime.volume / '.run-c-1234').mkdir()
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*(queued or running|' + case + ')'):
self.execute()
self.assertEqual(self.stops(), [])
self.assertEqual(host.read_record(self.root), self.record)
self.assertFalse((self.base / '.backups').exists())
def test_run_submitted_while_the_frontend_stops_recovers_originals(self):
"""A run that appears in the stop window aborts the update and restarts the original services.
Fails if the API is stopped under a run that was submitted before the frontend went down."""
runtime = self.deployment()
def submit():
runtime.active_runs = 1
runtime.after_frontend_stop = submit
with self.assertRaisesRegex(RuntimeError, 'during quiescing.*frontend stopped.*queued or running'):
self.execute()
self.assertEqual(self.stops(), ['app'])
record = host.read_record(self.root)
self.assertEqual((record['status'], record['recovery']),
('update_failed', 'original services verified; reconciliation required'))
self.assertTrue(all(runtime.running.values()))
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
def test_notebook_backup_failure_restarts_all_four_originals(self):
"""A failed jobs backup never activates the candidate and restarts the runner with the rest.
Fails if recovery skips the runner, starts it before the API or loses the data backup."""
runtime = self.deployment()
runtime.fail = 'notebook-backup'
with self.assertRaisesRegex(RuntimeError, 'during backup; .*operation=create notebook backup'):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['status'], 'update_failed')
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
self.assertFalse((self.root / '.updates').exists())
starts = [args[-1] for args in runtime.calls if args[:2] == ['docker', 'start']]
self.assertEqual(starts, ['api', 'worker', 'runner', 'app'])
data_guard.verify_backup(Path(record['backup']))
def test_notebook_restore_failure_keeps_old_code(self):
"""A jobs backup that does not restore identically stops the update before activation.
Fails if the isolated restore check ignores the notebook backup."""
runtime = self.deployment()
runtime.fail = 'notebook-restore'
with self.assertRaisesRegex(RuntimeError, 'during restore-verification'):
self.execute(verify_restore=True)
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
self.assertTrue(all(runtime.running.values()))
def test_volume_replaced_during_backup_is_refused(self):
"""A jobs volume recreated between preparation and backup is not backed up.
Fails if the backup could come from a different volume than the one the installation used."""
runtime = self.deployment()
original = runtime.host_action
def replace_volume(helper, action, project, value):
if action == 'prepare-notebook-backup':
runtime.identity['created'] = '2026-11-19T00:00:00Z'
return original(helper, action, project, value)
runtime.host_action = replace_volume
with self.assertRaisesRegex(RuntimeError, 'during backup'):
self.execute()
self.assertNotIn('backup', runtime.guard_calls)
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
def test_jobs_changed_after_activation_keep_the_frontend_down(self):
"""A job folder appearing before the frontend starts freezes the update instead of finishing it.
Fails if the update reports success although the jobs volume differs from its backup."""
runtime = self.deployment()
runtime.fail = 'late-job'
with self.assertRaisesRegex(RuntimeError, 'during notebooks'):
self.execute()
self.assertNotIn('webapp', self.ups())
record = host.read_record(self.root)
self.assertEqual((record['status'], record['notebook_volume']),
('update_failed', self.record['notebook_volume']))
self.assertEqual(self.frozen.args[-1], self.record['notebook_volume'])
class HostNotebookBackupTests(unittest.TestCase):
"""Helper actions that place and check the jobs backup beside the data backup."""
def test_notebook_destination_needs_the_operation_data_backup(self):
"""The jobs destination is created only inside a completed data backup of the same operation.
Fails if a jobs backup can be written for an operation that has no verified data backup."""
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
root, _, record = fixture(base)
operation = 'a' * 32
host.write_record(root, dict(record, status='updating', operation_id=operation))
with self.assertRaisesRegex(RuntimeError, 'data backup is missing'):
host.notebook_backup_directory(base, record['project'], operation)
parent = base / '.backups' / record['project'] / operation
parent.mkdir(parents=True)
(parent / 'manifest.json').write_text('{}')
target = host.notebook_backup_directory(base, record['project'], operation)
self.assertEqual(list(target.iterdir()), [])
with self.assertRaises(FileExistsError):
host.notebook_backup_directory(base, record['project'], operation)
if __name__ == '__main__':
unittest.main()
-510
View File
@@ -1,510 +0,0 @@
"""Storage policy exceptions and writer checks: column order, seeded source mappings, a new MLflow store and
processes or requests that stopping the installation would cut short.
Fixtures: `fixture` (from `test_conservative`) builds four synthetic domain databases; `mappings` adds
`cat_sistema_fuente` and `cat_mapeo` to TEA with one catalog row and one operator row; `mlflow_store` writes the
store MLflow creates on first use, optionally with content. Writer checks use the simulated deployment of
`test_conservative`. No daemon is contacted.
"""
from contextlib import closing
from pathlib import Path
import sqlite3
import tempfile
import unittest
from unittest.mock import patch
import conservative
import data_guard as guard
import dev
import host
from test_conservative import HEADS, SimulatedDeployment, fixture
MAPPINGS = """
CREATE TABLE cat_sistema_fuente (sistema_fuente_id VARCHAR(64) NOT NULL PRIMARY KEY, etiqueta VARCHAR NOT NULL,
fuente_tabla VARCHAR(64), vigente_desde DATE NOT NULL, vigente_hasta DATE);
CREATE TABLE cat_mapeo (mapeo_id INTEGER NOT NULL PRIMARY KEY, sistema_fuente_id VARCHAR(64) NOT NULL,
clase VARCHAR(16) NOT NULL, forma VARCHAR(255) NOT NULL, forma_normalizada VARCHAR(255) NOT NULL,
estudio_id VARCHAR(64), resultado_id VARCHAR(128), valor_id VARCHAR(64), vigente_desde DATE NOT NULL,
vigente_hasta DATE, registrado_por VARCHAR(64) NOT NULL, registrado_en DATETIME NOT NULL, motivo VARCHAR);
INSERT INTO cat_sistema_fuente VALUES ('catalogo', 'Catálogo del proyecto', NULL, '1900-01-01', NULL);
INSERT INTO cat_sistema_fuente VALUES ('laboratorio-x', 'Laboratorio X', NULL, '2025-01-01', NULL);
INSERT INTO cat_mapeo VALUES (1, 'catalogo', 'valor', 'Positivo', 'POSITIVO', NULL, 'estudio.resultado', 'pos',
'1900-01-01', NULL, 'catalogo', '2026-01-01 00:00:00.000000', NULL);
INSERT INTO cat_mapeo VALUES (2, 'laboratorio-x', 'valor', 'Pos +', 'POS +', NULL, 'estudio.resultado', 'pos',
'2025-01-01', NULL, 'operador', '2026-02-01 00:00:00.000000', 'alta manual');
"""
SEED = ("INSERT INTO cat_mapeo VALUES (3, 'catalogo', 'valor', 'Negativo', 'NEGATIVO', NULL, 'estudio.resultado',"
" 'neg', '1900-01-01', NULL, 'catalogo', '2026-03-01 00:00:00.000000', NULL)")
def mappings(root):
"""Add the source mapping tables to TEA and return a contract that includes them."""
with closing(sqlite3.connect(root / 'data' / 'tea.db')) as connection:
connection.executescript(MAPPINGS)
contract = {}
for domain in guard.DOMAINS:
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
contract[domain] = {'head': HEADS[domain], 'known': [HEADS[domain]], 'schema': guard.schema(connection)}
contract['governance']['known'].append('d6b4f0e23a45')
return contract
def run_sql(root, *statements):
with closing(sqlite3.connect(root / 'data' / 'tea.db')) as connection:
for statement in statements:
connection.execute(statement)
connection.commit()
def mlflow_store(path, *extra):
"""The store MLflow 3 creates on first use, plus `extra` statements."""
with closing(sqlite3.connect(path)) as connection:
connection.executescript("""
CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL PRIMARY KEY);
CREATE TABLE workspaces (name VARCHAR(63) NOT NULL PRIMARY KEY, description TEXT,
default_artifact_root TEXT, trace_archival_location TEXT, trace_archival_retention VARCHAR(32));
CREATE TABLE experiments (experiment_id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(256) NOT NULL,
artifact_location VARCHAR(256), lifecycle_stage VARCHAR(32), creation_time BIGINT,
last_update_time BIGINT, workspace VARCHAR(63));
CREATE TABLE runs (run_uuid VARCHAR(32) NOT NULL PRIMARY KEY, status VARCHAR(9));
CREATE TABLE registered_models (name VARCHAR(256) NOT NULL PRIMARY KEY);
CREATE TABLE model_versions (name VARCHAR(256) NOT NULL, version INTEGER NOT NULL,
PRIMARY KEY (name, version));
INSERT INTO alembic_version VALUES ('dc11669786a5');
INSERT INTO workspaces VALUES ('default', 'Default workspace for legacy resources', NULL, NULL, NULL);
INSERT INTO experiments VALUES (0, 'Default', '/app/WebApi/mlruns/0', 'active', 1, 1, 'default');
""")
for statement in extra:
connection.execute(statement)
connection.commit()
class ColumnOrderTests(unittest.TestCase):
"""`same_structure` on in-memory SQLite schemas."""
@staticmethod
def structure(sql):
with closing(sqlite3.connect(':memory:')) as connection:
connection.executescript(sql)
return guard.schema(connection)
BASE = ('CREATE TABLE parent (id INTEGER NOT NULL PRIMARY KEY);'
'CREATE TABLE ordenes (ord_id VARCHAR NOT NULL PRIMARY KEY, ord_pac INTEGER REFERENCES parent (id),'
' {columns}, CHECK (length(ord_id) > 0));'
'CREATE INDEX ix_ordenes_pac ON ordenes (ord_pac);')
def test_only_the_physical_order_of_columns_is_ignored(self):
"""A table whose migration lists its columns in another order than the models still matches.
Fails if the TEA `ordenes_estudio` migration order (date before study type) keeps a fresh installation
from passing the contract."""
models = self.structure(self.BASE.format(columns='ord_tipo VARCHAR, ord_fecha DATE'))
migrated = self.structure(self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR'))
self.assertNotEqual(models, migrated)
self.assertTrue(guard.same_structure(migrated, models))
def test_every_other_structural_difference_still_fails(self):
"""Type, nullability, default, primary key, extra or missing column, index, foreign key and check
differences are still refused.
Fails if ignoring the order hides an incompatible structure."""
models = self.structure(self.BASE.format(columns='ord_tipo VARCHAR, ord_fecha DATE'))
variants = {
'type': self.BASE.format(columns='ord_fecha DATETIME, ord_tipo VARCHAR'),
'nullability': self.BASE.format(columns='ord_fecha DATE NOT NULL, ord_tipo VARCHAR'),
'default': self.BASE.format(columns="ord_fecha DATE DEFAULT '2000-01-01', ord_tipo VARCHAR"),
'extra': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR, ord_extra INTEGER'),
'missing': self.BASE.format(columns='ord_fecha DATE'),
'renamed': self.BASE.format(columns='ord_fecha DATE, ord_tipo_estudio VARCHAR'),
'index': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
'CREATE INDEX ix_ordenes_pac ON ordenes (ord_pac);', 'CREATE INDEX ix_ordenes_pac ON ordenes (ord_fecha);'),
'unique': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
'CREATE INDEX', 'CREATE UNIQUE INDEX'),
'foreign-key': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
' REFERENCES parent (id)', ''),
'check': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace('> 0', '> 1'),
'primary-key': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
'ord_id VARCHAR NOT NULL PRIMARY KEY', 'ord_id VARCHAR NOT NULL'),
}
for name, sql in variants.items():
with self.subTest(change=name):
self.assertFalse(guard.same_structure(self.structure(sql), models))
class SeededMappingTests(unittest.TestCase):
"""`verify_state` on `cat_sistema_fuente` and `cat_mapeo` with a catalog row and an operator row."""
def setUp(self):
"""Create the synthetic installation with source mappings and take the before-recalculation state."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root, _, _ = fixture(Path(self.temp.name))
self.contract = mappings(self.root)
self.data = self.root / 'data'
self.before = guard.storage_state(self.data, self.contract)
def verify(self, derived=True):
return guard.verify_state(self.data, self.contract, self.before, derived=derived)
def test_catalog_seed_rows_may_be_added(self):
"""A recalculation that adds the catalog's own rows for new forms passes.
Fails if a release that adds forms to the catalog can no longer be installed or updated."""
run_sql(self.root, SEED)
self.assertEqual(self.verify()['databases']['tea']['tables']['cat_mapeo']['count'], 3)
def test_stored_rows_never_change(self):
"""Editing, closing or deleting a stored catalog or operator row is refused.
Fails if a recalculation could overwrite or drop a mapping entered from the application."""
changes = {
'edit-operator': "UPDATE cat_mapeo SET valor_id = 'neg' WHERE mapeo_id = 2",
'close-operator': "UPDATE cat_mapeo SET vigente_hasta = '2026-01-01' WHERE mapeo_id = 2",
'close-seed': "UPDATE cat_mapeo SET vigente_hasta = '2026-01-01' WHERE mapeo_id = 1",
'delete-operator': 'DELETE FROM cat_mapeo WHERE mapeo_id = 2',
'edit-system': "UPDATE cat_sistema_fuente SET etiqueta = 'Otro' WHERE sistema_fuente_id = 'laboratorio-x'",
}
for name, statement in changes.items():
with self.subTest(change=name), tempfile.TemporaryDirectory() as tmp:
self.root, _, _ = fixture(Path(tmp))
self.contract = mappings(self.root)
self.data = self.root / 'data'
self.before = guard.storage_state(self.data, self.contract)
run_sql(self.root, statement)
with self.assertRaisesRegex(RuntimeError, 'historical rows changed'):
self.verify()
def test_added_rows_must_carry_the_seed_signature(self):
"""An added row that is not the catalog's own, or repeats a stored form, is refused.
Fails if a recalculation could introduce operator-looking rows or a second mapping for a stored form."""
additions = {
'operator-row': SEED.replace("'catalogo', '2026", "'operador', '2026"),
'other-system': SEED.replace("(3, 'catalogo'", "(3, 'laboratorio-x'"),
'dated-row': SEED.replace("'1900-01-01'", "'2026-01-01'"),
'closed-row': SEED.replace("'1900-01-01', NULL", "'1900-01-01', '2026-01-01'"),
'with-reason': SEED.replace("'2026-03-01 00:00:00.000000', NULL", "'2026-03-01 00:00:00.000000', 'x'"),
'stored-form': SEED.replace("'Negativo', 'NEGATIVO'", "'POSITIVO', 'POSITIVO'"),
'other-source-system': ("INSERT INTO cat_sistema_fuente VALUES ('laboratorio-y', 'Laboratorio Y', NULL,"
" '1900-01-01', NULL)"),
}
for name, statement in additions.items():
with self.subTest(change=name), tempfile.TemporaryDirectory() as tmp:
self.root, _, _ = fixture(Path(tmp))
self.contract = mappings(self.root)
self.data = self.root / 'data'
self.before = guard.storage_state(self.data, self.contract)
run_sql(self.root, statement)
with self.assertRaisesRegex(RuntimeError, "seeded rows are not the catalog's own") as caught:
self.verify()
self.assertEqual(guard.inspection_diagnostic(caught.exception)['reason'], 'seeded_rows_invalid')
def test_additions_outside_a_recalculation_are_refused(self):
"""Before recalculation every table, seeded ones included, must be exactly as backed up.
Fails if the post-start comparison lets the API add mappings before the checked recalculation."""
run_sql(self.root, SEED)
with self.assertRaisesRegex(RuntimeError, 'persistent rows changed in cat_mapeo'):
self.verify(derived=False)
def test_backup_and_restore_keep_operator_mappings(self):
"""The backup of seeded tables restores every stored row, operator ones included.
Fails if seeded tables are left out of the row-level backup comparison."""
destination = Path(self.temp.name) / 'backup'
guard.create_backup(self.data, destination, self.contract, {})
restored = guard.restore_backup(destination, Path(self.temp.name) / 'restored')
self.assertEqual(restored['databases']['tea']['tables']['cat_mapeo'],
self.before['databases']['tea']['tables']['cat_mapeo'])
class MlflowStoreTests(unittest.TestCase):
"""`verify_state` on `mlflow.db` when absent before a recalculation and when already present."""
def setUp(self):
"""Create the synthetic installation, without an MLflow store, and take its state."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root, self.contract, _ = fixture(Path(self.temp.name))
self.data = self.root / 'data'
(self.data / 'mlflow.db').unlink()
self.before = guard.storage_state(self.data, self.contract)
def test_a_new_empty_store_may_appear(self):
"""The empty store the live estimators create on first use passes a derived check.
Fails if a first installation or an installation that never used MLflow cannot recalculate."""
mlflow_store(self.data / 'mlflow.db')
guard.verify_state(self.data, self.contract, self.before, derived=True)
def test_a_new_store_with_content_is_refused(self):
"""A new store with a run, a model, another experiment or workspace, or a changed default is refused.
Fails if a recalculation could register models or runs without the persistence check noticing."""
extras = {
'run': "INSERT INTO runs VALUES ('r1', 'FINISHED')",
'model': "INSERT INTO registered_models VALUES ('cacu-cin2')",
'experiment': "INSERT INTO experiments VALUES (1, 'cacu-x', NULL, 'active', 1, 1, 'default')",
'workspace': "INSERT INTO workspaces VALUES ('otro', NULL, NULL, NULL, NULL)",
'artifact-root': "UPDATE workspaces SET default_artifact_root = '/data/otro'",
'deleted-default': "UPDATE experiments SET lifecycle_stage = 'deleted'",
}
for name, statement in extras.items():
with self.subTest(change=name):
path = self.data / 'mlflow.db'
path.unlink(missing_ok=True)
mlflow_store(path, statement)
with self.assertRaisesRegex(RuntimeError, 'MLflow store created with content') as caught:
guard.verify_state(self.data, self.contract, self.before, derived=True)
self.assertEqual(guard.inspection_diagnostic(caught.exception)['reason'], 'mlflow_store_not_initial')
def test_existing_store_stays_protected(self):
"""A store that existed before may not change, disappear or appear outside a recalculation.
Fails if the creation exception widens to replacing, editing or deleting an existing MLflow store."""
mlflow_store(self.data / 'mlflow.db')
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
guard.verify_state(self.data, self.contract, self.before, derived=False)
before = guard.storage_state(self.data, self.contract)
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
connection.execute("INSERT INTO runs VALUES ('r1', 'FINISHED')")
connection.commit()
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
guard.verify_state(self.data, self.contract, before, derived=True)
(self.data / 'mlflow.db').unlink()
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
guard.verify_state(self.data, self.contract, before, derived=True)
def test_a_new_file_that_is_not_an_mlflow_store_is_refused(self):
"""A non-SQLite file or a store without MLflow's tables under that name is refused.
Fails if any file named `mlflow.db` passes as a new store."""
(self.data / 'mlflow.db').write_bytes(b'not sqlite')
with self.assertRaises(Exception):
guard.verify_state(self.data, self.contract, self.before, derived=True)
(self.data / 'mlflow.db').unlink()
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
connection.execute('CREATE TABLE experiments (experiment_id INTEGER PRIMARY KEY)')
with self.assertRaisesRegex(RuntimeError, 'MLflow store created with content'):
guard.verify_state(self.data, self.contract, self.before, derived=True)
GUNICORN = ('--bind 0.0.0.0:5000 --workers 2 --timeout 600 --access-logfile - webapi:create_app()')
HEALTHCHECK = "python3 -c import urllib.request; urllib.request.urlopen('http://localhost:5000/health', timeout=5)"
# A row of /proc/net/tcp seen in the WebApi image with a client connected from another container.
ESTABLISHED = '02001BAC:1388 03001BAC:C790 01 00000000:00000000 00:00000000 00000000 0 0 198028 1'
class WriterTests(unittest.TestCase):
"""Process and request checks on the original containers."""
def test_service_processes_are_recognized(self):
"""The processes each original container starts itself pass; anything else does not.
Fails if a `docker exec` shell, a one-off training, OCR or a lookalike of the health check can run
while the update stops the container."""
expected = {
'webapi': ['uv run --no-sync gunicorn ' + GUNICORN, '/app/WebApi/.venv/bin/python /app/WebApi/.venv/bin/gunicorn '
+ GUNICORN, '/app/WebApi/.venv/bin/python -m gunicorn ' + GUNICORN, HEALTHCHECK],
'indicadores': ['uv run --no-sync python -m webapi.recomputation',
'/app/WebApi/.venv/bin/python -m webapi.recomputation',
'/app/WebApi/.venv/bin/python -m webapi.indicadores_vivos'],
'notebooks': ['/app/WebApi/.venv/bin/python -m models notebooks serve'],
}
unexpected = {
'webapi': ['sh -c sleep 120', 'sleep 120', '/app/WebApi/.venv/bin/python -m models run cacu cin2_logistic '
'--train', 'tesseract /tmp/page.png stdout -l spa', "python3 -c import os", ''],
'indicadores': ['/app/WebApi/.venv/bin/python -m webapi.orchestration confirm-risks', 'sqlite3 /data/cacu.db'],
'notebooks': ['/app/WebApi/.venv/bin/python -m ipykernel_launcher -f /tmp/k.json'],
}
for service, commands in expected.items():
for command in commands:
with self.subTest(service=service, command=command):
self.assertTrue(conservative.expected_process(service, command, HEALTHCHECK))
for service, commands in unexpected.items():
for command in commands:
with self.subTest(service=service, command=command):
self.assertFalse(conservative.expected_process(service, command, HEALTHCHECK))
self.assertFalse(conservative.expected_process('webapi', HEALTHCHECK, None))
def test_open_requests_are_counted_only_from_outside(self):
"""Established or half-closed connections to port 5000 from another host count; loopback, listening
sockets and other ports do not.
Fails if a request still being served by the API (an import or `/train`) goes unnoticed, or the
container's own health check blocks every update."""
rows = {
ESTABLISHED: 1,
ESTABLISHED.replace(' 01 ', ' 08 '): 1,
'00000000:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000': 0,
'0100007F:1388 0100007F:D2F0 01 00000000:00000000 00:00000000 00000000': 0,
'02001BAC:1F90 03001BAC:C790 01 00000000:00000000 00:00000000 00000000': 0,
'00000000000000000000000001000000:1388 00000000000000000000000001000000:9C40 01 0': 0,
'0000000000000000FFFF00000100007F:1388 0000000000000000FFFF00000100007F:9C40 01 0': 0,
'0000000000000000FFFF00000200A8C0:1388 0000000000000000FFFF00000300A8C0:9C40 08 0': 1,
}
for row, count in rows.items():
fake = type('Api', (), {'run': staticmethod(lambda args, row=row: ' sl local_address rem_address st\n'
' 0: ' + row + '\n')})()
with self.subTest(row=row):
self.assertEqual(conservative.served_requests(fake, 'api'), count)
failing = type('Api', (), {'run': staticmethod(lambda args: (_ for _ in ()).throw(RuntimeError('no cat')))})()
with self.assertRaisesRegex(conservative.UpdateRefusal, 'not verifiable'):
conservative.served_requests(failing, 'api')
class WriterUpdateTests(unittest.TestCase):
"""Conservative updates that meet writers the installation did not start."""
def setUp(self):
"""Prepare a managed synthetic installation with the simulated adapter."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
def execute(self):
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
def stops(self):
return [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'stop']]
def test_exec_process_refuses_before_stopping(self):
"""A process started with `docker exec` in the API refuses the update while everything still runs.
Fails if a one-off writer is killed by the update or its writes reach the backup."""
self.runtime.processes['api'].append('/app/WebApi/.venv/bin/python -m models run cacu cin2_logistic --train')
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*operation=check other writers; 1 process'):
self.execute()
self.assertEqual(self.stops(), [])
self.assertEqual(host.read_record(self.root), self.record)
def test_request_in_flight_after_the_frontend_stops_recovers_originals(self):
"""A request still being served once the frontend is down aborts the update and restarts the originals.
Fails if the API is stopped in the middle of an import or a `/train` call."""
self.runtime.connections.append(ESTABLISHED)
with self.assertRaisesRegex(RuntimeError, 'during quiescing.*operation=check other writers with the '
'frontend stopped; 1 API request'):
self.execute()
self.assertEqual(self.stops(), ['app'])
record = host.read_record(self.root)
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
self.assertTrue(all(self.runtime.running.values()))
def test_running_training_refuses_before_stopping(self):
"""A training or learning run still open in MLflow refuses the update while everything runs.
Fails if the extraction ranker's background learning, which has no request or process of its own, can be
interrupted once its run exists."""
self.runtime.training_runs = 1
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*1 training or learning run'):
self.execute()
self.assertEqual(self.stops(), [])
def test_unreadable_process_list_refuses(self):
"""An unparseable process listing refuses the update instead of assuming no writer.
Fails if a daemon that does not report processes lets the update proceed unchecked."""
original = self.runtime.run
self.runtime.run = lambda args, **kw: '' if list(map(str, args))[:2] == ['docker', 'top'] else original(args, **kw)
with self.assertRaisesRegex(RuntimeError, 'processes are not verifiable'):
self.execute()
self.assertEqual(self.stops(), [])
class MlflowCompatibilityTests(unittest.TestCase):
"""`mlflow_store` on synthetic stores and the update's refusals built on it."""
def setUp(self):
"""Prepare a managed synthetic installation with the simulated adapter."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.root, self.contract, self.record = fixture(self.base)
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
def test_store_revision_and_production_versions_are_read(self):
"""The guard reports the store's revision and its `produccion` aliases, and refuses a store without a
schema revision.
Fails if a production version or an old store goes unnoticed, or an unknown file passes as a store."""
data = self.root / 'data'
(data / 'mlflow.db').unlink()
self.assertEqual(guard.mlflow_store(data), {'exists': False, 'revision': None, 'production': 0})
mlflow_store(data / 'mlflow.db', 'CREATE TABLE registered_model_aliases (alias VARCHAR(256) NOT NULL, '
'version INTEGER NOT NULL, name VARCHAR(256) NOT NULL, PRIMARY KEY (name, alias))')
self.assertEqual(guard.mlflow_store(data), {'exists': True, 'revision': 'dc11669786a5', 'production': 0})
with closing(sqlite3.connect(data / 'mlflow.db')) as connection:
connection.execute("INSERT INTO registered_model_aliases VALUES ('produccion', 1, 'cacu-cin2_mas')")
connection.execute("INSERT INTO registered_model_aliases VALUES ('candidata', 2, 'cacu-cin2_mas')")
connection.commit()
self.assertEqual(guard.mlflow_store(data)['production'], 1)
(data / 'mlflow.db').unlink()
with closing(sqlite3.connect(data / 'mlflow.db')) as connection:
connection.execute('CREATE TABLE runs (id INTEGER PRIMARY KEY)')
with self.assertRaisesRegex(RuntimeError, 'MLflow store is unverifiable'):
guard.mlflow_store(data)
def execute(self):
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
def test_production_version_or_old_store_refuses_before_stopping(self):
"""A store the candidate's MLflow would refuse, or one with a production version, stops the update while
everything still runs.
Fails if the update reaches a recalculation that can only fail after activation."""
for case, store in (('production', {'production': 1}), ('schema', {'revision': '1b5f0d9ad7c1'})):
with self.subTest(case=case):
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
self.runtime.mlflow.update(store)
message = 'version in production' if case == 'production' else 'needs a schema upgrade'
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*check the MLflow store; .*' + message):
self.execute()
self.assertFalse(any(args[:2] == ['docker', 'stop'] for args in self.runtime.calls))
self.assertEqual(host.read_record(self.root), self.record)
def test_absent_store_and_current_store_without_production_update(self):
"""An installation without a store, or with a current one and no production version, updates.
Fails if the MLflow checks block installations that never used models."""
self.runtime.mlflow = {'exists': False, 'revision': None, 'production': 0}
self.execute()
self.assertEqual(host.read_record(self.root)['result'], 'updated')
def test_profile_service_cannot_move_persistent_storage(self):
"""`entrenar` may not point MLflow, reports or indicators outside the managed paths through `.env`.
Fails if a one-off training could keep its model artifacts in the container's own layer."""
from test_notebooks import compose_config
config = compose_config('isssteleon-x', Path('/srv/x/data'), 'tag', 8080)
trainer = dict(config['services']['indicadores'], command=['entrenar'], profiles=['entrenar'])
config['services']['entrenar'] = trainer
self.assertIsNotNone(dev.verify_config(config, 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080))
trainer['environment'] = dict(trainer['environment'], MLFLOW_ARTIFACT_ROOT='/app/WebApi/mlruns')
with self.assertRaisesRegex(RuntimeError, 'unexpected entrenar storage configuration'):
dev.verify_config(config, 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080)
class TransportLimitTests(unittest.TestCase):
"""Size of the scripts passed as one `python -c` argument."""
def test_scripts_fit_one_linux_argument(self):
"""Every guard script, and the helper's combined one, stays under Linux's 128 KiB per-argument limit.
Fails if a guard grows until `docker run`/`docker exec` can no longer start it on the daemon host."""
here = Path(dev.__file__).parent
sizes = {name: len((here / name).read_text(encoding='utf-8').encode()) for name in
('data_guard.py', 'notebook_guard.py', 'host.py')}
helper = sum(sizes.values()) + 4096
self.assertLess(max(*sizes.values(), helper), 120 * 1024, sizes)
if __name__ == '__main__':
unittest.main()
-222
View File
@@ -1,222 +0,0 @@
"""Reconciliation checks using temporary installations, SQLite files and a fake Docker adapter."""
import argparse
from contextlib import closing
import hashlib
import json
from pathlib import Path
import shutil
import sqlite3
import tarfile
import tempfile
import types
import unittest
from unittest.mock import patch
import host
import reconcile
class ReconciliationTests(unittest.TestCase):
def setUp(self):
"""Build a failed managed instance and a five-database isolated recovery fixture."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
self.project = 'isssteleon-example'
self.root = self.base / self.project
for name in ('codigo', 'deploy', 'data'):
(self.root / name).mkdir(parents=True)
self.revision = 'a' * 40
self.operation = 'b' * 32
tag = self.project + '-' + self.revision[:12] + '-suffix'
self.record = {'project': self.project, 'port': 23456, 'status': 'update_failed',
'phase': 'backup', 'revision': self.revision, 'operation_id': self.operation,
'error': 'retained', 'gitlinks': {'ISSSTELEON': 'c' * 40},
'images': ['isssteleon/webapi:' + tag, 'isssteleon/webapp:' + tag]}
host.write_record(self.root, self.record)
self.restored = self.base / 'restored' / 'data'
self.restored.mkdir(parents=True)
for name in reconcile.DATABASES:
with closing(sqlite3.connect(self.restored / name)) as db:
db.execute('CREATE TABLE sample (id INTEGER PRIMARY KEY)')
db.commit()
self.archive = self.base / 'recovery.tar.gz'
with tarfile.open(self.archive, 'w:gz') as tar:
tar.add(self.restored, arcname='data')
self.sha = hashlib.sha256(self.archive.read_bytes()).hexdigest()
self.request = {'port': 23456, 'revision': self.revision, 'operation_id': self.operation}
(self.base / '.install.lock').touch()
def test_check_and_atomic_apply_preserve_failure_metadata(self):
"""Fail if check writes or apply changes any field other than the status."""
before = (self.root / 'installation.json').read_bytes()
result = host.reconcile_record(self.base, self.project, self.request)
self.assertEqual((self.root / 'installation.json').read_bytes(), before)
host.reconcile_record(self.base, self.project,
dict(self.request, record_sha256=result['record_sha256']), apply=True)
self.assertEqual(host.read_record(self.root), dict(self.record, status='installed'))
def test_reject_changed_record_and_activation(self):
"""Fail if stale evidence or partial activation can change a failure record."""
result = host.reconcile_record(self.base, self.project, self.request)
host.write_record(self.root, dict(self.record, error='changed'))
with self.assertRaisesRegex(RuntimeError, 'record changed'):
host.reconcile_record(self.base, self.project,
dict(self.request, record_sha256=result['record_sha256']), apply=True)
(self.root / '.archive' / self.operation).mkdir(parents=True)
with self.assertRaisesRegex(RuntimeError, 'activation'):
host.reconcile_record(self.base, self.project, self.request)
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
def test_reject_wrong_phase_or_identity(self):
"""Fail if post-activation failures or incorrect operator identities are accepted."""
for change in ({'phase': 'api'}, {'status': 'updating'}, {'revision': 'd' * 40},
{'operation_id': 'e' * 32}, {'port': 23457}):
with self.subTest(change=change):
host.write_record(self.root, dict(self.record, **change))
with self.assertRaises(RuntimeError):
host.reconcile_record(self.base, self.project, self.request)
def test_archive_and_isolated_sqlite_evidence(self):
"""Fail if mismatched archive hashes or restored databases pass evidence validation."""
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
with self.assertRaisesRegex(RuntimeError, 'SHA-256'):
reconcile.recovery_evidence(self.archive, self.restored, '0' * 64, self.root)
(self.restored / 'tea.db').write_bytes(b'bad')
with self.assertRaisesRegex(RuntimeError, 'differs'):
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
def test_reject_sqlite_sidecars(self):
"""Fail if immutable SQLite inspection silently ignores an isolated WAL."""
(self.restored / 'tea.db-wal').write_bytes(b'')
with self.assertRaisesRegex(RuntimeError, 'sidecar inventory'):
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
def test_archive_wal_is_used_for_isolated_integrity_check(self):
"""Fail if restored committed WAL rows are omitted from the integrity check."""
source = self.base / 'source' / 'cama.db'
source.parent.mkdir()
with closing(sqlite3.connect(source)) as db:
db.execute('CREATE TABLE witness (value INTEGER)')
db.commit()
db.execute('PRAGMA journal_mode=WAL')
db.execute('PRAGMA wal_autocheckpoint=0')
db.execute('INSERT INTO witness VALUES (42)')
db.commit()
for suffix in ('', '-wal', '-shm'):
shutil.copyfile(Path(str(source) + suffix), self.restored / ('cama.db' + suffix))
with tarfile.open(self.archive, 'w:gz') as tar:
tar.add(self.restored, arcname='data')
digest = hashlib.sha256(self.archive.read_bytes()).hexdigest()
real_connect = sqlite3.connect
observed = []
def connect(path, *args, **kwargs):
connection = real_connect(path, *args, **kwargs)
if Path(path).name == 'cama.db':
observed.append(connection.execute('SELECT value FROM witness').fetchone())
return connection
with patch.object(reconcile.sqlite3, 'connect', side_effect=connect):
reconcile.recovery_evidence(self.archive, self.restored, digest, self.root)
self.assertEqual(observed, [(42,)])
def test_missing_external_attestation_is_rejected_before_helper(self):
"""Fail if an unverified external backup can enter reconciliation."""
args = argparse.Namespace(instance='example', port=23456, indicadores='1' * 64,
webapi='2' * 64, webapp='3' * 64, external_copy_verified=False)
with self.assertRaisesRegex(RuntimeError, 'external backup'):
reconcile.reconcile(args)
def test_orchestration_check_apply_and_identity_rejection(self):
"""Fail if check writes, apply skips validation, or mismatched container IDs are accepted."""
ids = ['1' * 64, '2' * 64, '3' * 64]
args = argparse.Namespace(instance='example', port=23456, indicadores=ids[0],
webapi=ids[1], webapp=ids[2], external_copy_verified=True,
revision=self.revision, operation=self.operation,
backup=self.archive, restored_data=self.restored,
backup_sha256=self.sha, mode='check')
calls = []
config = {'services': {name: {'restart': 'unless-stopped'}
for name in ('indicadores', 'webapi', 'webapp')}}
containers = [{'Config': {'Labels': {'com.docker.compose.service': name}},
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
for name in ('indicadores', 'webapi', 'webapp')]
def action(helper, name, project, payload):
calls.append(name)
return json.dumps(host.reconcile_record(self.base, project, json.loads(payload),
apply=name == 'reconcile-apply'))
api = types.SimpleNamespace(BASE=self.base, ROOT=self.base,
validate=lambda *a: (self.project, 23456), start_helper=lambda base: 'helper',
host_action=action, git=lambda *a: '160000 commit ' + 'c' * 40 + '\tISSSTELEON',
verify_existing_containers=lambda *a: ids, compose=lambda *a: ['compose'],
verify_config=lambda *a: None, verify_services=lambda *a, **kw: None,
run=lambda args: json.dumps(config if 'config' in args else containers) if args != ['docker', 'rm', '-f', 'helper'] else '')
with patch.object(reconcile.conservative, 'read_deployment'), \
patch.object(reconcile.conservative, 'current_environment'), \
patch.object(reconcile.conservative, 'guard', return_value={}):
self.assertEqual(reconcile.reconcile(args, api)['result'], 'eligible')
self.assertNotIn('reconcile-apply', calls)
self.assertEqual(host.read_record(self.root), self.record)
args.mode = 'apply'
self.assertEqual(reconcile.reconcile(args, api)['result'], 'reconciled')
self.assertEqual(host.read_record(self.root), dict(self.record, status='installed'))
host.write_record(self.root, self.record)
args.webapi = '4' * 64
with self.assertRaisesRegex(RuntimeError, 'container IDs'):
reconcile.reconcile(args, api)
self.assertEqual(host.read_record(self.root), self.record)
def test_notebook_installation_needs_its_runner_and_matching_composition(self):
"""A notebook installation reconciles with four original IDs; a missing, extra or inconsistent runner fails.
Fails if a runner can be left out of the identity check, or a record and composition that disagree about
the jobs volume are accepted."""
volume = self.project + '_trabajos_notebooks'
names = ('indicadores', 'webapi', 'webapp', 'notebooks')
ids = [str(n) * 64 for n in range(1, 5)]
config = {'services': {name: {'restart': 'unless-stopped'} for name in names}}
containers = [{'Config': {'Labels': {'com.docker.compose.service': name}},
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
for name in names]
composition = {'volume': volume}
def action(helper, name, project, payload):
return json.dumps(host.reconcile_record(self.base, project, json.loads(payload)))
api = types.SimpleNamespace(BASE=self.base, ROOT=self.base,
validate=lambda *a: (self.project, 23456), start_helper=lambda base: 'helper',
host_action=action, git=lambda *a: '160000 commit ' + 'c' * 40 + '\tISSSTELEON',
verify_existing_containers=lambda *a: ids, compose=lambda *a: ['compose'],
verify_config=lambda *a: composition['volume'], verify_services=lambda *a, **kw: None,
run=lambda args: json.dumps(config if 'config' in args else containers) if args != ['docker', 'rm', '-f', 'helper'] else '')
def attempt(runner):
args = argparse.Namespace(instance='example', port=23456, indicadores=ids[0], webapi=ids[1],
webapp=ids[2], notebooks=runner, external_copy_verified=True,
revision=self.revision, operation=self.operation, backup=self.archive,
restored_data=self.restored, backup_sha256=self.sha, mode='check')
with patch.object(reconcile.conservative, 'read_deployment'), \
patch.object(reconcile.conservative, 'current_environment'), \
patch.object(reconcile.conservative, 'guard', return_value={}):
return reconcile.reconcile(args, api)
host.write_record(self.root, dict(self.record, notebook_volume=volume))
self.assertEqual(attempt(ids[3])['result'], 'eligible')
with self.assertRaisesRegex(RuntimeError, 'runner ID is required'):
attempt(None)
composition['volume'] = None
with self.assertRaisesRegex(RuntimeError, 'disagree on notebook jobs'):
attempt(ids[3])
host.write_record(self.root, self.record)
with self.assertRaisesRegex(RuntimeError, 'runner ID is required'):
attempt(ids[3])
with self.assertRaisesRegex(ValueError, 'distinct full original container IDs'):
attempt(ids[0])
self.assertEqual(host.read_record(self.root), self.record)
if __name__ == '__main__':
unittest.main()
+195
View File
@@ -0,0 +1,195 @@
"""Registry actions on a temporary base directory: ownership, replaceable states and directory removal.
Fixtures: each test makes its own temporary base; `make` writes an installation directory with a record, a
`data` folder and some files, the way the installer leaves one.
"""
import json
import os
from pathlib import Path
import socket
import tempfile
import unittest
import registry
SHA = 'a' * 40
def make(base, port=18083, status='installed', project=None, **extra):
project = project or f'isssteleon-dev-{port}'
directory = Path(base) / project
(directory / 'data').mkdir(parents=True)
(directory / 'data' / 'cacu.db').write_text('synthetic')
record = {'project': project, 'port': port, 'status': status, 'installer': registry.INSTALLER,
'revision': SHA, **extra}
registry.write_record(directory, record)
return directory, record
class RegistryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.base = Path(self.tmp.name)
def test_reserve_creates_the_directory_and_record_and_refuses_a_second_claim(self):
"""Fails if reserve overwrites an existing instance or lets a port be registered twice."""
record = {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'preparing',
'installer': registry.INSTALLER}
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
self.assertEqual(registry.lookup(self.base, 18083)['status'], 'preparing')
self.assertTrue((self.base / 'isssteleon-dev-18083' / 'data').is_dir())
with self.assertRaisesRegex(RuntimeError, 'already exists'):
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
def test_reserve_refuses_a_port_registered_under_another_name(self):
"""Fails if a port already held by a differently named installation can be claimed again."""
make(self.base, 18083, project='isssteleon-clinic-west')
record = {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'preparing',
'installer': registry.INSTALLER}
with self.assertRaisesRegex(RuntimeError, 'registered by another'):
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
def test_reserve_refuses_a_project_that_does_not_match_the_port(self):
"""Fails if an instance name other than isssteleon-dev-<port> can be created."""
record = {'project': 'isssteleon-dev-1', 'port': 18083, 'status': 'preparing', 'installer': registry.INSTALLER}
with self.assertRaisesRegex(RuntimeError, 'invalid project'):
registry.reserve(self.base, 'isssteleon-dev-1', 18083, record)
def test_duplicate_ports_and_bad_records_fail_every_lookup(self):
"""Fails if an ambiguous registry is read as if the requested port were unique."""
make(self.base, 18083)
make(self.base, 18083, project='isssteleon-other')
with self.assertRaisesRegex(RuntimeError, 'duplicate recorded port'):
registry.lookup(self.base, 18084)
def test_ownership_accepts_marker_and_earlier_dev_records_only(self):
"""Fails if a record of another installer, another project name or without a commit proves ownership."""
cases = [
(dict(installer=registry.INSTALLER), 'isssteleon-dev-18083', 'marker'),
(dict(installer=None), 'isssteleon-dev-18083', 'legacy'),
(dict(installer='someone-else'), 'isssteleon-dev-18083', None),
(dict(installer=None, revision='short'), 'isssteleon-dev-18083', None),
(dict(installer=registry.INSTALLER), 'isssteleon-clinic-west', None),
]
for extra, project, expected in cases:
record = {'project': project, 'port': 18083, 'status': 'installed', 'revision': SHA}
record.update({k: v for k, v in extra.items() if v is not None})
if extra.get('installer') is None:
record.pop('installer', None)
with self.subTest(extra=extra, project=project):
self.assertEqual(registry.owned(record, 18083), expected)
def test_identity_refuses_unowned_and_unreplaceable_installations(self):
"""Fails if an installation of another owner, or one mid-update, can be planned for removal."""
make(self.base, 18083, project='isssteleon-clinic-west')
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
registry.identity(self.base, 'isssteleon-clinic-west', 18083)
with self.assertRaisesRegex(RuntimeError, 'missing or linked'):
registry.identity(self.base, 'isssteleon-dev-18083', 18083)
make(self.base, 18084, installer='other')
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
registry.identity(self.base, 'isssteleon-dev-18084', 18084)
for status in ('updating', 'update_failed', 'replacing', 'replace_failed'):
make(self.base, 18090 + len(status), status=status)
with self.subTest(status), self.assertRaisesRegex(RuntimeError, 'not replaceable'):
registry.identity(self.base, f'isssteleon-dev-{18090 + len(status)}', 18090 + len(status))
make(self.base, 18085)
self.assertEqual(registry.identity(self.base, 'isssteleon-dev-18085', 18085)['ownership'], 'marker')
def test_identity_refuses_a_linked_installation_directory(self):
"""Fails if a symlink standing in for the instance directory is followed."""
outside = Path(self.tmp.name) / 'outside'
outside.mkdir()
registry.write_record(outside, {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'installed',
'installer': registry.INSTALLER})
base = self.base / 'base'
base.mkdir()
try:
os.symlink(outside, base / 'isssteleon-dev-18083', target_is_directory=True)
except OSError:
self.skipTest('symlinks are not available')
with self.assertRaisesRegex(RuntimeError, 'missing or linked|invalid instance directory'):
registry.identity(base, 'isssteleon-dev-18083', 18083)
with self.assertRaisesRegex(RuntimeError, 'invalid instance directory'):
registry.lookup(base, 18083)
def test_remove_deletes_the_directory_and_never_follows_links_out(self):
"""Fails if removal deletes what a link inside the data directory points to, or leaves the directory."""
directory, record = make(self.base)
outside = Path(self.tmp.name) / 'keep'
outside.mkdir()
(outside / 'precious.txt').write_text('keep')
try:
os.symlink(outside, directory / 'data' / 'link', target_is_directory=True)
except OSError:
self.skipTest('symlinks are not available')
(directory / 'data' / 'nested').mkdir()
(directory / 'data' / 'nested' / 'file').write_text('x')
plan = registry.identity(self.base, directory.name, 18083)
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
registry.remove(self.base, directory.name, plan, 'abc')
self.assertFalse(directory.exists())
self.assertEqual((outside / 'precious.txt').read_text(), 'keep')
def test_remove_requires_the_removing_mark_of_the_same_plan(self):
"""Fails if a directory not marked by this plan's operation can be deleted."""
directory, record = make(self.base)
plan = registry.identity(self.base, directory.name, 18083)
with self.assertRaisesRegex(RuntimeError, 'not marked as being removed'):
registry.remove(self.base, directory.name, plan, 'abc')
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'other'}))
with self.assertRaisesRegex(RuntimeError, 'not marked as being removed'):
registry.remove(self.base, directory.name, plan, 'abc')
self.assertTrue((directory / 'data' / 'cacu.db').exists())
def test_remove_refuses_a_directory_whose_identity_differs_from_the_plan(self):
"""Fails if a directory that is not the one the plan named (another device or inode) is deleted."""
directory, record = make(self.base)
plan = registry.identity(self.base, directory.name, 18083)
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
for changed in (dict(plan, directory=[0, 0]), dict(plan, ownership='legacy'), dict(plan, project='isssteleon-dev-1')):
with self.subTest(changed), self.assertRaisesRegex(RuntimeError, 'changed since the plan'):
registry.remove(self.base, directory.name, changed, 'abc')
self.assertTrue((directory / 'data' / 'cacu.db').exists())
def test_failed_removal_keeps_the_record_last(self):
"""Fails if the record is deleted before the data, which would hide a half-removed instance."""
directory, record = make(self.base)
plan = registry.identity(self.base, directory.name, 18083)
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
original = os.unlink
calls = []
def failing(path, *args, **kwargs):
calls.append(Path(path).name)
if Path(path).name == 'cacu.db':
raise PermissionError('denied')
return original(path, *args, **kwargs)
os.unlink = failing
try:
with self.assertRaises(PermissionError):
registry.remove(self.base, directory.name, plan, 'abc')
finally:
os.unlink = original
self.assertEqual(registry.read_record(directory)['status'], 'removing')
def test_check_port_fails_while_something_listens(self):
"""Fails if a busy port is reported as free."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('0.0.0.0', 0))
sock.listen()
with self.assertRaises(OSError):
registry.check_port(sock.getsockname()[1])
def test_main_prints_json_for_lookup(self):
"""Fails if the command-line entry stops printing the lookup result as JSON."""
make(self.base)
self.assertEqual(registry.dispatch(self.base, 'lookup', '-', '18083')['port'], 18083)
self.assertIsNone(registry.dispatch(self.base, 'lookup', '-', '18099'))
json.dumps(registry.dispatch(self.base, 'identity', 'isssteleon-dev-18083', json.dumps({'port': 18083})))
if __name__ == '__main__':
unittest.main()
-322
View File
@@ -1,322 +0,0 @@
"""Exercise the fixed laboratory reset with synthetic SQLite storage and fake Docker."""
import copy
import json
import os
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest.mock import patch
import conservative
import data_guard
import dev
import host
import reset_lab_18080 as reset
from test_conservative import fixture, change
OPERATION = 'a28cddb3dbda4ed48db577104c031b31'
CANDIDATE = '9559cb2e36e7c07591808d5e17b004410008b72e'
class Docker:
"""Simulate only the target project's Docker operations and service verification."""
compose = staticmethod(dev.compose)
verify_config = staticmethod(dev.verify_config)
def __init__(self, root, original):
self.root, self.original = root, original
self.calls = []
self.running = False
self.fail_health = False
self.fail_persistence = False
def config(self):
service = {'image': self.original['images'][0], 'restart': 'unless-stopped',
'environment': dict(conservative.PERSISTENT_ENV),
'volumes': [{'type': 'bind', 'source': str(self.root / 'data'), 'target': '/data'}]}
return {'name': reset.PROJECT, 'services': {'webapi': copy.deepcopy(service),
'indicadores': copy.deepcopy(service), 'webapp': {'image': self.original['images'][1],
'restart': 'unless-stopped', 'ports': [{'published': '18080', 'target': 80}]}}}
def run(self, args, **kwargs):
args = list(map(str, args))
self.calls.append(args)
if args[:3] == ['docker', 'image', 'inspect']:
return 'old-app' if 'webapi' in args[-1] else 'old-web'
if 'config' in args:
return json.dumps(self.config())
if args[:2] == ['docker', 'ps']:
return 'api worker web' if '-a' in ''.join(args[2:]) or self.running else ''
if args[:2] == ['docker', 'inspect']:
return json.dumps([{'Id': ident, 'Image': 'old-web' if name == 'webapp' else 'old-app',
'Config': {'Image': self.original['images'][1 if name == 'webapp' else 0],
'Env': [key + '=' + value for key, value in conservative.controlled_config(self.config())['services'][name].get('environment', {}).items()],
'Entrypoint': conservative.controlled_config(self.config())['services'][name].get('entrypoint'),
'Cmd': [],
'Labels': {'com.docker.compose.project': reset.PROJECT,
'com.docker.compose.service': name}},
'State': {'Running': self.running}, 'Mounts': [] if name == 'webapp' else [
{'Type': 'bind', 'Source': str(self.root / 'data'), 'Destination': '/data', 'RW': True}],
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
for ident, name in zip(('api', 'worker', 'web'), ('webapi', 'indicadores', 'webapp'))])
if 'up' in args:
self.running = True
if self.fail_persistence:
change(self.root, 'tea', "UPDATE patient SET value='changed'")
return ''
def verify_services(self, cmd, port):
if self.fail_health:
raise RuntimeError('health failed')
assert port == 18080 and self.running
def verify_existing_containers(self, original, base, helper):
assert original == self.original and self.running
return ['api', 'worker', 'web']
class ResetTests(unittest.TestCase):
def setUp(self):
"""Create one failed lab, its immutable source archive and pre-activation backup."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
root, self.contract, original = fixture(self.base)
self.root = self.base / reset.PROJECT
root.rename(self.root)
self.original = dict(original, project=reset.PROJECT, revision=reset.ORIGINAL)
self.archive = self.root / '.archive' / OPERATION
self.archive.mkdir()
for name in ('codigo', 'deploy'):
shutil.copytree(self.root / name, self.archive / name)
(self.archive / 'deploy' / '.env').write_text('')
(self.archive / 'deploy' / 'docker-compose.yml').write_text('{}')
(self.archive / 'installation.json').write_text(json.dumps(self.original))
self.backup = self.base / '.backups' / reset.PROJECT / OPERATION
self.backup.parent.mkdir(parents=True)
origin = {key: self.original[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images')}
data_guard.create_backup(self.root / 'data', self.backup, self.contract, origin)
self.failed = dict(self.original, status='update_failed', phase='recalculation-and-persistence',
operation_id=OPERATION, target_revision=CANDIDATE,
target_images=[f'isssteleon/{image}:{reset.PROJECT}-{CANDIDATE[:12]}-' + 'a' * 32
for image in ('webapi', 'webapp')],
target_gitlinks={'ISSSTELEON': 'b' * 40},
backup=str(self.backup), archive=str(self.archive))
host.write_record(self.root, self.failed)
change(self.root, 'tea', "UPDATE patient SET value='failed recalculation'")
(self.root / 'codigo' / 'version.txt').write_text('candidate')
self.api = Docker(self.root, self.original)
self.reset = reset.LabReset(self.base, self.api, shutil.copytree, operation=OPERATION)
self.guard = patch.object(conservative, 'guard', return_value=self.contract)
self.guard.start()
self.addCleanup(self.guard.stop)
self.freeze = patch.object(conservative, 'freeze_failed', side_effect=lambda *a: setattr(self.api, 'running', False))
self.freeze.start()
self.addCleanup(self.freeze.stop)
self.host_users = patch.object(reset, 'no_host_users')
self.host_users.start()
self.addCleanup(self.host_users.stop)
self.http = patch.object(reset, 'check_http')
self.http.start()
self.addCleanup(self.http.stop)
def test_check_does_not_change_installation(self):
"""Fail if checking writes to the lab or creates its persistent recovery directory."""
before = reset.tree(self.root)
self.assertIn('eligible', self.reset.run('check'))
self.assertEqual(reset.tree(self.root), before)
self.assertFalse(self.reset.work.exists())
self.assertFalse(any('up' in call for call in self.api.calls))
def add_script_links(self):
"""Add the archived deployment script aliases to both code trees."""
for directory in (self.archive / 'deploy', self.archive / 'codigo' / 'dist'):
directory.mkdir(exist_ok=True)
(directory / 'isssteleon.sh').write_text('#!/bin/sh\n')
try:
for name in ('estado.sh', 'actualizar.sh'):
(directory / name).symlink_to('isssteleon.sh')
except OSError as exc:
self.skipTest('symbolic links unavailable: ' + str(exc))
def test_check_accepts_archived_script_links_without_changes(self):
"""Check accepts relative aliases without changing the archived code or creating work."""
self.add_script_links()
before = [reset.code_tree(self.archive / name) for name in ('codigo', 'deploy')]
self.assertIn('eligible', self.reset.run('check'))
self.assertEqual(before, [reset.code_tree(self.archive / name) for name in ('codigo', 'deploy')])
self.assertFalse(self.reset.work.exists())
@unittest.skipUnless(os.name == 'posix', 'archive copy uses POSIX cp and permissions')
def test_apply_preserves_script_links_and_resume(self):
"""Preparation copies aliases as links and retry validates the preserved trees."""
self.add_script_links()
self.reset.copy = reset.copy_preserved
self.api.fail_health = True
with self.assertRaisesRegex(RuntimeError, 'health failed'):
self.reset.run('apply')
for directory in (self.root / 'deploy', self.root / 'codigo' / 'dist'):
for name in ('estado.sh', 'actualizar.sh'):
self.assertTrue((directory / name).is_symlink())
self.assertEqual(os.readlink(directory / name), 'isssteleon.sh')
self.api.fail_health = False
self.assertIn('recovered', self.reset.run('apply'))
def test_rejects_unsafe_code_links_and_persistent_links(self):
"""Escaping, absolute, dangling and persistent links cannot pass validation."""
self.add_script_links()
directory = self.archive / 'deploy'
link = directory / 'estado.sh'
for destination in ('../../installation.json', str(directory / 'isssteleon.sh'), 'missing'):
link.unlink()
link.symlink_to(destination)
with self.subTest(destination=destination), self.assertRaises(RuntimeError):
self.reset.run('check')
link.unlink()
link.symlink_to('isssteleon.sh')
(self.backup / 'data' / 'alias').symlink_to('tea.db')
with self.assertRaisesRegex(RuntimeError, 'linked persistent'):
self.reset.run('check')
(self.backup / 'data' / 'alias').unlink()
(self.root / 'data' / 'alias').symlink_to('tea.db')
with self.assertRaisesRegex(RuntimeError, 'linked persistent'):
self.reset.run('apply')
self.assertFalse(self.reset.work.exists())
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'FIFO requires POSIX')
def test_rejects_special_code_entries(self):
"""Code validation rejects special files even when no link points to them."""
os.mkfifo(self.archive / 'deploy' / 'pipe')
with self.assertRaisesRegex(RuntimeError, 'special tree entry'):
self.reset.run('check')
def test_apply_restores_all_data_and_preserves_failure(self):
"""Fail if recovery loses incident evidence or installs before checking services/storage."""
self.assertIn('recovered', self.reset.run('apply'))
active = host.read_record(self.root)
self.assertEqual(active['status'], 'installed')
self.assertEqual(active['revision'], reset.ORIGINAL)
self.assertEqual(json.loads((self.reset.work / 'failed-record.json').read_text()), self.failed)
self.assertEqual((self.reset.work / 'failed' / 'codigo' / 'version.txt').read_text(), 'candidate')
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
self.assertEqual(reset.tree(self.root / 'data'), reset.tree(self.backup / 'data'))
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
self.assertIn('gunicorn', config['services']['webapi']['entrypoint'])
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
self.assertEqual((self.root / 'deploy' / 'docker-compose.yml').stat().st_mode,
(self.archive / 'deploy' / 'docker-compose.yml').stat().st_mode)
self.assertEqual(self.reset.run('apply'), 'already recovered')
def test_refuses_corrupt_backup_and_active_writers(self):
"""Fail if corrupt recovery data or active writers can reach the first swap."""
self.api.running = True
with self.assertRaisesRegex(RuntimeError, 'writers'):
self.reset.run('apply')
self.api.running = False
(self.backup / 'data' / 'reportes' / 'imports.jsonl').write_text('corrupt')
with self.assertRaisesRegex(RuntimeError, 'checksum'):
self.reset.run('apply')
self.assertFalse(self.reset.work.exists())
def test_startup_or_persistence_failure_stays_failed(self):
"""Fail if health or protected-data changes are certified as a recovered lab."""
self.api.fail_persistence = True
with self.assertRaisesRegex(RuntimeError, 'contents changed'):
self.reset.run('apply')
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
self.assertFalse((self.reset.work / 'complete').exists())
self.assertFalse(self.api.running)
self.assertTrue((self.reset.work / 'failed' / 'data').is_dir())
preserved = reset.tree(self.reset.work / 'failed')
self.api.fail_persistence = False
self.reset.run('apply')
self.assertEqual(reset.tree(self.reset.work / 'failed'), preserved)
self.assertEqual(len(list(self.reset.work.glob('attempt-data-*'))), 1)
def test_missing_original_image_prevents_preparation(self):
"""Fail if a missing original image reaches persistent preparation or container recreation."""
run = self.api.run
def missing(args, **kwargs):
if list(args)[:3] == ['docker', 'image', 'inspect']:
return ''
return run(args, **kwargs)
self.api.run = missing
with self.assertRaisesRegex(RuntimeError, 'image missing'):
self.reset.run('apply')
self.assertFalse(self.reset.work.exists())
def test_swap_resumes_between_atomic_renames(self):
"""Fail if an interrupted swap overwrites preserved evidence when resumed."""
work = self.base / 'swap'
(work / 'ready' / 'codigo').mkdir(parents=True)
(work / 'failed').mkdir()
(work / 'ready' / 'codigo' / 'version.txt').write_text('restored')
(self.root / 'codigo').rename(work / 'failed' / 'codigo')
reset.swap(self.root, work, 'codigo')
reset.swap(self.root, work, 'codigo')
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'restored')
self.assertEqual((work / 'failed' / 'codigo' / 'version.txt').read_text(), 'candidate')
def test_apply_resumes_after_swap_interruption(self):
"""Fail if a crash between renames prevents resume or overwrites the failed tree."""
rename = os.rename
interrupted = False
def crash(source, target):
nonlocal interrupted
if Path(source) == self.reset.work / 'ready' / 'codigo' and not interrupted:
interrupted = True
raise OSError('simulated interruption')
return rename(source, target)
with patch.object(reset.os, 'rename', side_effect=crash), self.assertRaises(OSError):
self.reset.run('apply')
preserved = reset.tree(self.reset.work / 'failed' / 'codigo')
self.reset.run('apply')
self.assertEqual(reset.tree(self.reset.work / 'failed' / 'codigo'), preserved)
def test_health_failure_can_be_retried_without_losing_evidence(self):
"""Fail if retry after failed startup overwrites the original failed evidence."""
self.api.fail_health = True
with self.assertRaisesRegex(RuntimeError, 'health failed'):
self.reset.run('apply')
preserved = reset.tree(self.reset.work / 'failed')
self.api.fail_health = False
self.reset.run('apply')
self.assertEqual(reset.tree(self.reset.work / 'failed'), preserved)
def test_wrong_incident_and_host_writer_rejected(self):
"""Fail if another incident or an unexcluded host process can trigger recovery."""
with patch.object(reset, 'no_host_users', side_effect=RuntimeError('active host writer')):
with self.assertRaisesRegex(RuntimeError, 'host writer'):
self.reset.run('apply')
host.write_record(self.root, dict(self.failed, operation_id='0' * 32))
with self.assertRaisesRegex(RuntimeError, 'incident identity'):
self.reset.run('apply')
self.assertFalse(self.reset.work.exists())
def test_candidate_revision_matches_incident_evidence(self):
"""Distinct incident revisions pass only when both image tags and evidence agree."""
for operation, revision in ((OPERATION, CANDIDATE),
('8e68804b94f3447089e31467bab75934',
'23ab1cb5f1e57251e8771af49010483d9a824ba3')):
incident = reset.LabReset(self.base, self.api, shutil.copytree, operation=operation)
if operation != OPERATION:
shutil.copytree(self.archive, incident.archive)
shutil.copytree(self.backup, incident.backup)
tag = f'{reset.PROJECT}-{revision[:12]}-' + 'a' * 32
record = dict(self.failed, target_revision=revision,
operation_id=operation, backup=str(incident.backup), archive=str(incident.archive),
target_images=['isssteleon/webapi:' + tag, 'isssteleon/webapp:' + tag])
host.write_record(self.root, record)
self.assertIn('eligible', incident.run('check'))
host.write_record(self.root, dict(record, target_revision='f' * 40))
with self.assertRaisesRegex(RuntimeError, 'candidate evidence'):
incident.run('check')
host.write_record(self.root, dict(self.failed, target_revision='../invalid'))
with self.assertRaisesRegex(RuntimeError, 'candidate revision'):
self.reset.run('check')
if __name__ == '__main__':
unittest.main()
-72
View File
@@ -1,72 +0,0 @@
"""Check pinned metadata against real migrations using temporary empty databases.
Opt in with ISSSTELEON_CONTRACT_SOURCE and the candidate's locked schema packages.
No application engine factory, migration environment or existing database is used.
"""
from contextlib import closing
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
import data_guard
@unittest.skipUnless(os.environ.get('ISSSTELEON_CONTRACT_SOURCE'), 'candidate schema runtime not selected')
class TargetContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Import only Core and migration definitions from the selected source tree."""
cls.source = Path(os.environ['ISSSTELEON_CONTRACT_SOURCE']).resolve()
sys.path[:0] = [str(cls.source / name) for name in ('Core', 'Persistance')]
cls.contract = data_guard.target_contract()
def setUp(self):
"""Apply the real revision functions only to four disposable SQLite databases."""
from alembic.config import Config
from alembic.migration import MigrationContext
from alembic.operations import Operations
from alembic.script import ScriptDirectory
from sqlalchemy import create_engine
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / 'data'
self.root.mkdir()
for domain in data_guard.DOMAINS:
scripts = ScriptDirectory.from_config(Config(str(
self.source / 'Persistance' / 'persistance' / domain / 'alembic.ini')))
engine = create_engine('sqlite:///' + (self.root / (domain + '.db')).as_posix())
try:
with engine.begin() as connection:
with Operations.context(MigrationContext.configure(connection)):
for revision in reversed(list(scripts.walk_revisions())):
revision.module.upgrade()
connection.exec_driver_sql('CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY)')
connection.exec_driver_sql('INSERT INTO alembic_version VALUES (?)',
(self.contract[domain]['head'],))
finally:
engine.dispose()
def test_migrated_schema_matches_candidate_metadata(self):
"""Fail if real baseline/head databases would be refused by the metadata contract."""
for domain in data_guard.DOMAINS:
with self.subTest(domain=domain), closing(data_guard.readonly(self.root / (domain + '.db'))) as db:
self.assertTrue(data_guard.same_structure(data_guard.schema(db), self.contract[domain]['schema']))
data_guard.inspect_databases(self.root, self.contract)
def test_actual_schema_backup_restores_to_an_isolated_directory(self):
"""Fail if schema validation or SQLite backup cannot recover the real pinned structures."""
(self.root / 'witness.bin').write_bytes(b'synthetic persistent artifact')
backup = Path(self.temp.name) / 'backup'
data_guard.create_backup(self.root, backup, self.contract, {'synthetic': True})
restored = Path(self.temp.name) / 'restored'
data_guard.restore_backup(backup, restored)
self.assertEqual((restored / 'witness.bin').read_bytes(), b'synthetic persistent artifact')
if __name__ == '__main__':
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""Pin the safety boundaries of the three DEV workflows using their checked-in YAML.
The fixture is the workflow text; no runner, network, Docker or dispatch is involved. Behaviour of the operations is
covered by test_installer.py and test_dataload.py.
"""
from pathlib import Path
import re
import unittest
WORKFLOWS = Path(__file__).resolve().parents[1] / 'workflows'
INPUTS = {
'deploy-dev.yml': ['puerto', 'referencia', 'confirmacion'],
'reinstall-dev.yml': ['puerto', 'referencia', 'confirmacion'],
'load-dev-data.yml': ['puerto', 'hospital', 'confirmacion'],
}
COMMANDS = {
'deploy-dev.yml': 'installer.py install "$PORT" "$REFERENCE" "$CONFIRMATION"',
'reinstall-dev.yml': 'installer.py reinstall "$PORT" "$REFERENCE" "$CONFIRMATION"',
'load-dev-data.yml': 'installer.py load-data "$PORT" "$HOSPITAL" "$CONFIRMATION"',
}
def text_of(name):
return (WORKFLOWS / name).read_text(encoding='utf-8')
class WorkflowTests(unittest.TestCase):
def test_inputs_are_exactly_those_the_operation_needs(self):
"""Fails if a workflow gains an input (a free-form path, a flag) or loses its confirmation step."""
for name, expected in INPUTS.items():
with self.subTest(name):
text = text_of(name)
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), expected)
self.assertRegex(inputs, r'confirmacion:\n(?: .*\n)*? required: false')
def test_inputs_reach_the_installer_only_through_the_environment(self):
"""Fails if an input is interpolated into a shell command, where a crafted value could run code."""
for name, command in COMMANDS.items():
with self.subTest(name):
text = text_of(name)
self.assertIn(command, text)
for line in text.splitlines():
if line.strip().startswith('run:'):
self.assertNotIn('${{', line)
def test_dispatch_identity_is_verified_before_any_operation(self):
"""Fails if the workflow stops checking the dispatched repository, server and commit before acting."""
for name, command in COMMANDS.items():
with self.subTest(name):
text = text_of(name)
for boundary in ('${{ gitea.ref }}', '${{ gitea.ref_name }}', '${{ gitea.ref_type }}',
'ref: ${{ gitea.sha }}', 'installer.py validate-dispatch'):
self.assertIn(boundary, text)
self.assertLess(text.index('validate-dispatch'), text.index(command))
def test_no_global_cleanup_or_old_routing_in_the_workflows(self):
"""Fails if a workflow acquires a prune, a compose down, a fixed laboratory port or the retired updater."""
for name in INPUTS:
with self.subTest(name):
text = text_of(name)
self.assertNotRegex(text, r'prune|compose down|docker rm|dev\.py|deploy-branch|install-auto')
self.assertNotRegex(text, r'18080|18081|18087|4397')
def test_a_missing_confirmation_is_the_default(self):
"""Fails if a workflow defaults to acting: an empty confirmation must be what a plain run sends."""
for name in INPUTS:
with self.subTest(name):
inputs = text_of(name).split('confirmacion:\n', 1)[1].split('type: string', 1)[0]
self.assertIn("default: ''", inputs)
if __name__ == '__main__':
unittest.main()
+8 -3
View File
@@ -11,9 +11,12 @@ jobs:
runs-on: ubuntu-latest
env:
PR_SHA: ${{ github.event.pull_request.head.sha }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
CACU_DATABASE_URL: 'sqlite:///:memory:'
CAMA_DATABASE_URL: 'sqlite:///:memory:'
TEA_DATABASE_URL: 'sqlite:///:memory:'
@@ -70,9 +73,11 @@ jobs:
shell: bash
run: |
set -e
test -f .gitea/deploy/dev.py
test -f .gitea/deploy/test_dev.py
test -f .gitea/deploy/installer.py
test -f .gitea/deploy/test_installer.py
test -f .gitea/workflows/deploy-dev.yml
test -f .gitea/workflows/reinstall-dev.yml
test -f .gitea/workflows/load-dev-data.yml
test -f .gitea/workflows/deploy-dev-diagnostic.yml
python3 -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
python3 -m unittest discover -s .gitea/deploy-terminal -p 'test_*.py' -v
+4 -1
View File
@@ -5,9 +5,12 @@ jobs:
diagnostic:
runs-on: ubuntu-latest
env:
GIT_CONFIG_COUNT: 1
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
steps:
- uses: actions/checkout@v4
- name: Inspect runner and dependencies
+21 -12
View File
@@ -1,43 +1,52 @@
name: deploy-dev
# Installs a disposable DEV instance on a free port. Without `confirmacion` it only shows the plan and the
# confirmation that approves it; a second run with that confirmation installs. Use `reinstall-dev` to replace an
# existing instance.
on:
workflow_dispatch:
inputs:
puerto:
description: Public WebApp port; create a new instance or conservatively update its existing data
description: Free public port for the new instance
required: true
type: string
rama:
description: WorkingNarrative branch to deploy
referencia:
description: WorkingNarrative branch, tag or full 40-character commit to install
required: true
default: dev
type: string
confirmacion:
description: Leave empty to see the plan; paste the confirmation it prints to install
required: false
default: ''
type: string
jobs:
deploy:
install:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
TARGET_BRANCH: ${{ inputs.rama }}
REFERENCE: ${{ inputs.referencia }}
CONFIRMATION: ${{ inputs.confirmacion }}
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ gitea.sha }}
- name: Verify dispatched revision
run: python3 -B .gitea/deploy/dev.py validate-dispatch
run: python3 -B .gitea/deploy/installer.py validate-dispatch
- name: Diagnose checkout origin
run: python3 -B .gitea/deploy/origin_diagnostic.py
- name: Validate request
run: python3 -B .gitea/deploy/dev.py validate-auto "$PORT"
- name: Resolve branch and install or conservatively update instance
run: python3 -B .gitea/deploy/dev.py deploy-branch "$PORT" "$TARGET_BRANCH"
- name: Plan, or install with the confirmation
run: python3 -B .gitea/deploy/installer.py install "$PORT" "$REFERENCE" "$CONFIRMATION"
+4 -1
View File
@@ -27,9 +27,12 @@ jobs:
REQUESTED_PORT: ${{ inputs.puerto }}
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
RELEASE_TOKEN: ${{ gitea.token }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: url.${{ gitea.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
GIT_CONFIG_KEY_1: url.${{ gitea.server_url }}/alberto/tea.git.insteadOf
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
+43
View File
@@ -0,0 +1,43 @@
name: load-dev-data
# Loads the simulated hospital (dev-data) into an installed, still empty DEV instance through the instance's own
# import API. Without `confirmacion` it only shows the plan and the confirmation that approves it.
on:
workflow_dispatch:
inputs:
puerto:
description: Public port of the DEV instance to load
required: true
type: string
hospital:
description: Simulated hospital as host:port, as the instance's API reaches it
required: true
default: 10.0.10.41:9505
type: string
confirmacion:
description: Leave empty to see the plan; paste the confirmation it prints to load
required: false
default: ''
type: string
jobs:
load:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
HOSPITAL: ${{ inputs.hospital }}
CONFIRMATION: ${{ inputs.confirmacion }}
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ gitea.sha }}
- name: Verify dispatched revision
run: python3 -B .gitea/deploy/installer.py validate-dispatch
- name: Plan, or load with the confirmation
run: python3 -B .gitea/deploy/installer.py load-data "$PORT" "$HOSPITAL" "$CONFIRMATION"
+52
View File
@@ -0,0 +1,52 @@
name: reinstall-dev
# Cleanly replaces a registered DEV instance: removes its containers, notebook jobs volume, network and directory
# (data included), then installs the selected reference. Without `confirmacion` it only shows what would be removed
# and the confirmation that approves exactly that plan.
on:
workflow_dispatch:
inputs:
puerto:
description: Public port of the DEV instance to replace
required: true
type: string
referencia:
description: WorkingNarrative branch, tag or full 40-character commit to install
required: true
default: dev
type: string
confirmacion:
description: Leave empty to see the plan; paste the confirmation it prints to remove and reinstall
required: false
default: ''
type: string
jobs:
reinstall:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
REFERENCE: ${{ inputs.referencia }}
CONFIRMATION: ${{ inputs.confirmacion }}
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
GIT_CONFIG_COUNT: 2
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
steps:
- uses: actions/checkout@v4
with:
ref: ${{ gitea.sha }}
- name: Verify dispatched revision
run: python3 -B .gitea/deploy/installer.py validate-dispatch
- name: Diagnose checkout origin
run: python3 -B .gitea/deploy/origin_diagnostic.py
- name: Plan, or reinstall with the confirmation
run: python3 -B .gitea/deploy/installer.py reinstall "$PORT" "$REFERENCE" "$CONFIRMATION"
+1
View File
@@ -1,3 +1,4 @@
graphify-out
.claude/
samples/
ISSSTELEON-entrega/
+7 -1
View File
@@ -70,6 +70,12 @@ read only when a task points there (§5).
describe the change in their own terms. The link goes the other way:
each WorkingNarrative issue cites the commits and pull requests that
resolve it.
13. **The deployment on port 5310 is not touched.** Its containers
(`sitio-b-*`), volumes (`sitio-b_*`) and images (`sitio-b/*`) hold the
analysed real-data deployment: no `up`, `down`, `restart`, `recreate`,
`load`, import, promote or analysis, and no `docker exec` that writes.
Reading its API (GET requests) is fine. New deployments use another
project name, ports and subnet.
---
@@ -142,7 +148,7 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
one baseline generated from the models, verified upgrade/downgrade/upgrade
on SQLite, MySQL 8, PostgreSQL 16 and SQL Server 2022; older revisions are
gone, so a database stamped with them must start fresh):
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join);
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join) -> `16bf0b0ee3e4` (EEG analysis outputs, `eeg_criterio`) -> `c4306f438b3a` (the four old criterion columns dropped) -> `41694156d3a1` (ADOS-2 association tables) and `c3f6a9e42d53` (risk index date) -> `e8c2a5d47f13` (their join) -> `98dadd777ffd` (`eeg_metrica_zona`);
cacu `b4f2d8c01e23` -> `f89e1f081998`; cama `c5a3e9d12f34` -> `f82b64f43abd` (`cat_sistema_fuente`,
`cat_mapeo`); governance `d6b4f0e23a45` -> `e7c5a1f34b56`. The TEA chain and the join verified
upgrade/downgrade/upgrade on SQLite only.
BIN
View File
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
# Written by build.sh on every build.
requirements.lock
constraints.txt
.image
+35
View File
@@ -0,0 +1,35 @@
# syntax=docker/dockerfile:1.7
# Dask scheduler and workers for ISSSTELEON's TEA EEG batches (age baselines, EEG analysis). Build it with
# ./build.sh, which writes requirements.lock and passes the ISSSTELEON checkout as the `isssteleon` build context.
#
# Only what the workers run: the tea library and the models package its tasks come from, with their dependencies
# at the versions of the platform's lockfile (ISSSTELEON/WebApi/uv.lock). The same base as the platform's image,
# so Python is the one distributed's version check expects.
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:0.13.1 /uv /bin/uv
# One BLAS thread per worker process, as the platform's own local cluster does.
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \
UV_SYSTEM_PYTHON=1 UV_NO_CACHE=1
COPY requirements.lock /opt/isssteleon/requirements.lock
RUN uv pip install -r /opt/isssteleon/requirements.lock
# The workers unpickle models.tea.eeg tasks, which import models, tea, core and persistance.
COPY --from=isssteleon Core /opt/isssteleon/Core
COPY --from=isssteleon Persistance /opt/isssteleon/Persistance
COPY --from=isssteleon Extraction /opt/isssteleon/Extraction
COPY --from=isssteleon models /opt/isssteleon/models
RUN uv pip install --no-deps \
/opt/isssteleon/Core /opt/isssteleon/Persistance /opt/isssteleon/Extraction \
/opt/isssteleon/models/libs/tea /opt/isssteleon/models \
&& python -c "import models.tea.eeg.train, models.tea.eeg.analyze, models.eeg_analysis, tea, distributed; print('distributed', distributed.__version__)"
COPY versions.py /opt/isssteleon/versions.py
RUN useradd --uid 10001 --create-home dask
USER dask
WORKDIR /home/dask
ARG ISSSTELEON_COMMIT=unknown
LABEL org.opencontainers.image.title="isssteleon-dask" isssteleon.commit=$ISSSTELEON_COMMIT
+97
View File
@@ -0,0 +1,97 @@
# Dask cluster for the TEA EEG batches
A Kubernetes Dask cluster (dask-operator `DaskCluster`) that runs ISSSTELEON's TEA EEG work: training the age
baselines on a local reference folder and, if the deployment points at it, the EEG analysis. The image holds only
what those tasks run: the `tea` library and the `models` package, with their dependencies.
| File | What it is |
|---|---|
| `Dockerfile` | the scheduler and worker image |
| `build.sh` | resolves `requirements.lock` against the platform's lockfile, builds, checks versions, pushes |
| `cluster.yaml` | the `isssteleon-eeg` DaskCluster: 10 worker pods (one per machine) x 4 processes, NodePorts 30786 and 30787 |
| `loader.yaml`, `sync-reference.sh` | copy a local EDF folder into the `eeg-data` volume the workers read |
| `deploy.sh` | applies the cluster with the built image and prints the scheduler address |
| `versions.py` | the versions `build.sh` compares between this image and the platform's |
## Why the image is built this way
The platform submits the jobs from its `webapi` container and connects with distributed's version check, which
refuses a scheduler or workers whose dask, distributed, cloudpickle, msgpack, tornado or Python differ. The
workers also unpickle tasks such as `models.tea.eeg.analyze.reference`, which import `models`, `tea`, `core` and
`persistance`. So:
- **The platform's base image**, `python:3.12-slim`, so Python is the one the platform runs.
- **ISSSTELEON's packages** (`Core`, `Persistance`, `Extraction`, `models`, `models/libs/tea`) from the checkout
you build from, which must be the commit the deployment runs. The image tag carries it
(`dask:isssteleon-<commit>`).
- **Their dependencies at the platform's exact versions**: `build.sh` exports `ISSSTELEON/WebApi/uv.lock` as
constraints and resolves the five packages against it, plus bokeh for the scheduler's dashboard. Nothing else is
installed: no S3 client (the workers read local folders), no notebooks, no OCR binaries.
- It runs as an unprivileged user (uid 10001). The loader pod runs as root to write the volume.
## Before the first build
- `uv`, Docker with BuildKit, and `kubectl` pointing at the cluster, which runs the dask-operator.
- The ISSSTELEON checkout next to this folder (`../ISSSTELEON`, submodules checked out), at the deployment's commit.
- Docker on this machine allowed to push to `192.168.20.18:5000` (an `insecure-registries` entry if it is
plain HTTP), and the cluster's nodes allowed to pull from it.
- A `PersistentVolumeClaim` named `eeg-data` that every node can mount: `ReadWriteMany`, since the loader writes
it while workers on several nodes read it.
- The platform's deployment built once (`docker compose up --build -d` in `../manual-deploy`), so `build.sh` can
compare versions with its image.
## Build, load the reference folder, deploy
```sh
cd dask-cluster
./build.sh # resolve, build, compare with the platform, push
```
Put the ages table inside the folder first. Its columns are `archivo` (file name only) and `edad_meses` or
`edad_anos`. Without one, ages come from each EDF's header. For Helsinki HK1K, whose headers have no birth date:
```sh
cp ~/datos/edades-helsinki.csv ~/datos/helsinki/edades.csv
./sync-reference.sh ~/datos/helsinki helsinki # -> /referencia/helsinki on every worker
./deploy.sh # prints DASK_SCHEDULER_ADDRESS=tcp://<node>:30786
```
## Train on the cluster
From `../manual-deploy`, with the address `deploy.sh` printed. The folder is mounted at the same path the
workers see, so the same command also works without the cluster (drop the `-e`):
```sh
docker compose run --rm \
-e DASK_SCHEDULER_ADDRESS=tcp://<node>:30786 \
--entrypoint /app/WebApi/.venv/bin/python \
-v "$HOME/datos/helsinki:/referencia/helsinki:ro" \
webapi -m models run tea eeg --train --environment prod \
--reference-dir /referencia/helsinki --reference-ages /referencia/helsinki/edades.csv \
--reference-name sitio-a --line-hz 50
```
The listing and every study's measurement run on the workers, which read the files from the volume. Training each
baseline on the measured features runs in the `webapi` container and registers in the deployment's MLflow.
Follow it on the dashboard (`http://<node>:30787/status`).
To send the deployment's EEG analysis to the cluster too, set `DASK_SCHEDULER_ADDRESS` in `../manual-deploy/.env`
and restart `webapi` and `indicadores`. Each EDF's bytes travel with its task, so the analysis needs no volume.
## Keep it in step
- **Rebuild after any change to ISSSTELEON** (models, tea, Core, Persistance, the WebApi lockfile), then
`./deploy.sh` again. An image from another commit is refused by the version check or runs old code.
- `./deploy.sh --delete` removes the cluster. The volume and its folders stay.
- Scale with `kubectl scale daskcluster isssteleon-eeg --replicas N` or by editing `replicas`.
## If something fails
| What you see | What to do |
|---|---|
| `ValueError: Mismatched versions found` on the client | the image was built from another ISSSTELEON commit than the deployment: rebuild |
| `no folder /referencia/<name>` from a worker | the folder wasn't synced, or `--reference-dir` names another one: `./sync-reference.sh` |
| `KeyError: 'posterior_rhythm_hz'` while training | no study had an age in 16 to 36 months: check the ages table is in the folder and passed with `--reference-ages` |
| Worker pods `Pending` | not enough memory or CPU per node for 22Gi and 5 CPUs, or the claim can't attach on several nodes |
| `ErrImagePull` | the nodes can't pull from `192.168.20.18:5000` |
| `build.sh` stops on `versions differ` | the platform's image is older or newer than the checkout: rebuild the deployment, or check out its commit |
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Builds the Dask image for ISSSTELEON's EEG batches and pushes it to the cluster's registry: the tea library and the
# models package, with their dependencies at the platform's locked versions.
#
# ./build.sh resolve, build, compare with the platform's webapi image, push
# ./build.sh --no-push the same without pushing
# ./build.sh --resolve-only only write requirements.lock
#
# Environment:
# ISSSTELEON_DIR the ISSSTELEON checkout the platform runs (default: ../ISSSTELEON)
# REGISTRY where the image goes (default: 192.168.20.18:5000)
# WEBAPI_IMAGE the platform's image to compare versions with (default: <COMPOSE_PROJECT_NAME>/webapi:local
# from ../manual-deploy/.env); the comparison is skipped if that image isn't on this machine
#
# Writes requirements.lock, constraints.txt and .image (the tag deploy.sh applies).
set -euo pipefail
cd "$(dirname "$0")"
mode=${1:-push}
ISSSTELEON_DIR=$(realpath "${ISSSTELEON_DIR:-../ISSSTELEON}")
REGISTRY=${REGISTRY:-192.168.20.18:5000}
LOCAL_PACKAGES=(Core Persistance Extraction models/libs/tea models)
for p in "${LOCAL_PACKAGES[@]}"; do
[[ -f "$ISSSTELEON_DIR/$p/pyproject.toml" ]] || { echo "no $p in $ISSSTELEON_DIR (ISSSTELEON_DIR, submodules checked out?)" >&2; exit 1; }
done
commit=$(git -C "$ISSSTELEON_DIR" rev-parse --short HEAD)
if [[ -n "$(git -C "$ISSSTELEON_DIR" status --porcelain --untracked-files=no)" ]]; then
echo "warning: $ISSSTELEON_DIR has uncommitted changes; the image gets them, its tag says $commit-dirty" >&2
commit="$commit-dirty"
fi
echo "== constraints from $ISSSTELEON_DIR/WebApi/uv.lock"
(cd "$ISSSTELEON_DIR/WebApi" && uv export --frozen --no-dev --no-hashes --no-emit-project) \
| grep -v '^-e ' > constraints.txt
echo "== requirements.lock"
input=$(mktemp --suffix=.in)
trap 'rm -f "$input"' EXIT
for p in "${LOCAL_PACKAGES[@]}"; do echo "$ISSSTELEON_DIR/$p"; done > "$input"
# bokeh serves the scheduler's dashboard (port 8787); without it the status page is empty.
echo "bokeh>=3.1" >> "$input"
uv pip compile "$input" --python-version 3.12 --no-header --quiet \
--constraint constraints.txt \
--no-emit-package core --no-emit-package persistance --no-emit-package extraction \
--no-emit-package tea --no-emit-package models \
-o requirements.lock
grep -E '^(dask|distributed|bokeh|numpy|pandas|mne|yasa)==' requirements.lock | tr '\n' ' '; echo
[[ "$mode" == "--resolve-only" ]] && exit 0
image="$REGISTRY/dask:isssteleon-$commit"
echo "== building $image"
docker build --build-context isssteleon="$ISSSTELEON_DIR" --build-arg ISSSTELEON_COMMIT="$commit" -t "$image" .
if [[ -z "${WEBAPI_IMAGE:-}" && -f ../manual-deploy/.env ]]; then
project=$(sed -n 's/^COMPOSE_PROJECT_NAME=//p' ../manual-deploy/.env | tail -1)
[[ -n "$project" ]] && WEBAPI_IMAGE="$project/webapi:local"
fi
if [[ -n "${WEBAPI_IMAGE:-}" ]] && docker image inspect "$WEBAPI_IMAGE" >/dev/null 2>&1; then
echo "== versions against $WEBAPI_IMAGE"
ours=$(docker run --rm "$image" python /opt/isssteleon/versions.py | tail -1)
theirs=$(docker run --rm -i --entrypoint /app/WebApi/.venv/bin/python "$WEBAPI_IMAGE" - < versions.py | tail -1)
python3 - "$ours" "$theirs" <<'EOF'
import json, sys
ours, theirs = (json.loads(a) for a in sys.argv[1:])
bad = []
for k in sorted(set(ours) | set(theirs)):
a, b = ours.get(k), theirs.get(k)
if k == "python":
if a != b:
bad.append(f"python {a} here, {b} in the platform (distributed refuses even a patch difference: "
"rebuild the platform with `docker compose build --pull`, then this image the same day)")
elif a != b:
bad.append(f"{k} {a} here, {b} in the platform")
if bad:
sys.exit("versions differ from the platform:\n " + "\n ".join(bad))
print("same versions as the platform")
EOF
else
echo "warning: no platform image to compare with (WEBAPI_IMAGE); build the deployment first to check" >&2
fi
echo "$image" > .image
if [[ "$mode" == "--no-push" ]]; then
echo "built $image (not pushed)"
exit 0
fi
echo "== pushing $image"
docker push "$image"
echo "pushed $image; next: ./sync-reference.sh <folder> <name>, then ./deploy.sh"
+59
View File
@@ -0,0 +1,59 @@
# The Dask cluster for ISSSTELEON's TEA EEG batches. Apply it with ./deploy.sh, which fills in __IMAGE__.
#
# Workers read reference EDFs from the eeg-data volume, mounted read-only at /referencia: a cohort uploaded with
# `./sync-reference.sh <folder> <name>` is /referencia/<name>, the path given to --reference-dir. The volume is
# shared by every worker on every node, so the claim must be ReadWriteMany (or ReadOnlyMany once loaded).
#
# Its own name and NodePorts, so it runs next to other Dask clusters.
apiVersion: kubernetes.dask.org/v1
kind: DaskCluster
metadata:
name: isssteleon-eeg
spec:
worker:
replicas: 10
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
dask.org/cluster-name: isssteleon-eeg
dask.org/component: worker
containers:
- name: worker
image: __IMAGE__
# One pod per machine (the spread constraint above), 4 worker processes per pod, one thread each, at the
# 4.25 GiB a study needs; 4 x 4.25 GiB fits in 19Gi. To go to 5 per pod, use 22Gi and 5 CPUs.
args: [dask, worker, --name, $(DASK_WORKER_NAME), --nworkers, "4", --nthreads, "1", --memory-limit, 4.25GiB]
resources:
requests: {memory: 19Gi, cpu: "4"}
limits: {memory: 19Gi}
env:
- name: NODE_NAME
valueFrom:
fieldRef: {fieldPath: spec.nodeName}
volumeMounts:
- {name: referencia, mountPath: /referencia, readOnly: true}
volumes:
- name: referencia
persistentVolumeClaim: {claimName: eeg-data, readOnly: true}
scheduler:
spec:
containers:
- name: scheduler
# The same image as the workers: the platform checks the scheduler's versions too.
image: __IMAGE__
args: [dask, scheduler]
ports:
- {name: tcp-comm, containerPort: 8786}
- {name: http-dashboard, containerPort: 8787}
service:
type: NodePort
selector:
dask.org/cluster-name: isssteleon-eeg
dask.org/component: scheduler
ports:
- {name: tcp-comm, port: 8786, targetPort: tcp-comm, nodePort: 30786}
- {name: http-dashboard, port: 8787, targetPort: http-dashboard, nodePort: 30787}
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Applies cluster.yaml with the image ./build.sh pushed, waits for the scheduler and prints the address the
# platform uses.
#
# ./deploy.sh create or update the cluster
# ./deploy.sh --delete remove it
set -euo pipefail
cd "$(dirname "$0")"
name=isssteleon-eeg
if [[ "${1:-}" == "--delete" ]]; then
kubectl delete daskcluster "$name"
exit 0
fi
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
sed "s#__IMAGE__#$IMAGE#g" cluster.yaml | kubectl apply -f -
selector="dask.org/cluster-name=$name,dask.org/component=scheduler"
for _ in $(seq 60); do
kubectl get pod -l "$selector" -o name 2>/dev/null | grep -q . && break
sleep 5
done
kubectl wait --for=condition=Ready pod -l "$selector" --timeout=600s
node=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
port=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="tcp-comm")].nodePort}' 2>/dev/null || echo 30786)
dashboard=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="http-dashboard")].nodePort}' 2>/dev/null || echo 30787)
echo
echo "scheduler: DASK_SCHEDULER_ADDRESS=tcp://$node:${port:-30786}"
echo "dashboard: http://$node:${dashboard:-30787}/status"
echo "workers: kubectl get pods -l dask.org/cluster-name=$name,dask.org/component=worker"
+22
View File
@@ -0,0 +1,22 @@
# A short-lived pod with the eeg-data volume mounted read-write, so sync-reference.sh can copy a local folder
# into it. sync-reference.sh fills in __IMAGE__ and deletes the pod when the copy is done.
apiVersion: v1
kind: Pod
metadata:
name: isssteleon-eeg-loader
labels: {app: isssteleon-eeg-loader}
spec:
restartPolicy: Never
containers:
- name: loader
image: __IMAGE__
# The image runs as an unprivileged user; root here so it can write wherever the volume's owner allows.
securityContext: {runAsUser: 0}
command: [sleep, "86400"]
resources:
requests: {memory: 256Mi, cpu: "250m"}
volumeMounts:
- {name: referencia, mountPath: /referencia}
volumes:
- name: referencia
persistentVolumeClaim: {claimName: eeg-data}
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env bash
# Copies a local folder of reference EDFs into the eeg-data volume, where every worker reads it at
# /referencia/<name>. Put the ages table (`archivo`, `edad_meses` or `edad_anos`) inside the folder first.
#
# ./sync-reference.sh ~/datos/helsinki helsinki
#
# Files already there with the same name are overwritten; nothing is deleted, and files left there by an earlier
# sync don't affect the check, which compares each file of the local folder with its copy. Uses the image in
# .image (or IMAGE) for the short-lived loader pod, so the cluster needs no other image.
set -euo pipefail
cd "$(dirname "$0")"
folder=${1:?usage: sync-reference.sh <local folder> <name>}
name=${2:?usage: sync-reference.sh <local folder> <name>}
[[ -d "$folder" ]] || { echo "no folder $folder" >&2; exit 1; }
[[ "$name" =~ ^[A-Za-z0-9._-]+$ ]] || { echo "name: letters, digits, dot, dash or underscore only" >&2; exit 1; }
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
pod=isssteleon-eeg-loader
local_count=$(find "$folder" -type f -iname '*.edf' | wc -l)
[[ "$local_count" -gt 0 ]] || { echo "no .edf files under $folder" >&2; exit 1; }
find "$folder" -maxdepth 1 -iname '*.csv' | grep -q . || echo "warning: no .csv in $folder: ages will come from the EDF headers" >&2
sed "s#__IMAGE__#$IMAGE#g" loader.yaml | kubectl apply -f -
trap 'rm -f "${server:-}" "${manifest:-}" "${expected:-}"; kill "${server_pid:-}" 2>/dev/null || true; kubectl delete pod "$pod" --wait=false >/dev/null 2>&1 || true' EXIT
kubectl wait --for=condition=Ready "pod/$pod" --timeout=600s
echo "== copying $local_count EDF files from $folder to /referencia/$name"
kubectl exec "$pod" -- mkdir -p "/referencia/$name"
# The bulk data flows over HTTP from this machine: the API server's exec stream is dropped
# mid-transfer often enough that piping a large folder through kubectl exec never finishes.
server=$(mktemp --suffix=.py)
manifest=$(mktemp)
cat > "$server" <<'EOF'
import http.server, pathlib, sys
folder = pathlib.Path(sys.argv[1]).resolve()
manifest = pathlib.Path(sys.argv[2]).read_bytes()
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(folder), **kwargs)
def do_GET(self):
if self.path == "/__manifest":
self.send_response(200)
self.send_header("Content-Length", str(len(manifest)))
self.end_headers()
self.wfile.write(manifest)
return
super().do_GET()
http.server.ThreadingHTTPServer(("0.0.0.0", int(sys.argv[3])), Handler).serve_forever()
EOF
find "$folder" -type f -printf '%P\0' > "$manifest"
port=${SYNC_PORT:-18777}
python3 "$server" "$folder" "$manifest" "$port" >/dev/null 2>&1 &
server_pid=$!
cluster=$(kubectl config view -o jsonpath='{.contexts[?(@.name=="'"$(kubectl config current-context)"'")].context.cluster}')
api=$(kubectl config view -o jsonpath='{.clusters[?(@.name=="'"$cluster"'")].cluster.server}')
api_host=${api#http://}; api_host=${api_host#https://}; api_host=${api_host%%:*}
host_ip=${SYNC_HOST_IP:-$(ip -4 route get "$api_host" | awk '{for (i = 1; i < NF; i++) if ($i == "src") {print $(i + 1); exit}}')}
[[ -n "$host_ip" ]] || { echo "no host IP the pod can reach; set SYNC_HOST_IP" >&2; exit 1; }
python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$port/__manifest', timeout=5)" \
|| { echo "the local HTTP server did not start (is port $port busy?)" >&2; exit 1; }
for attempt in $(seq 1 3); do
if kubectl exec -i "$pod" -- python3 - "/referencia/$name" "http://$host_ip:$port" <<'EOF'; then
import concurrent.futures, pathlib, sys, urllib.parse, urllib.request
dest, base = sys.argv[1], sys.argv[2]
names = [n for n in urllib.request.urlopen(base + "/__manifest", timeout=30).read().decode().split("\0") if n]
def fetch(name):
target = pathlib.Path(dest, name)
target.parent.mkdir(parents=True, exist_ok=True)
url = base + "/" + urllib.parse.quote(name)
error = None
for _ in range(5):
try:
with urllib.request.urlopen(url, timeout=300) as response, open(target, "wb") as out:
while True:
block = response.read(1 << 20)
if not block:
break
out.write(block)
return name, None
except Exception as exc: # the next attempt rewrites the file
error = exc
return name, error
failed = []
with concurrent.futures.ThreadPoolExecutor(8) as pool:
for i, (name, error) in enumerate(pool.map(fetch, names), 1):
if error is not None:
failed.append(name)
if i % 100 == 0:
print(f"{i}/{len(names)}", flush=True)
if failed:
print("failed: " + ", ".join(failed))
sys.exit(1)
print(f"downloaded {len(names)} files")
EOF
break
fi
if [[ $attempt == 3 ]]; then
echo "the download keeps failing" >&2
exit 1
fi
echo "download lost its exec stream, retrying" >&2
done
kill "$server_pid" 2>/dev/null || true
server_pid=
# The workers run as an unprivileged user.
kubectl exec "$pod" -- chmod -R a+rX "/referencia/$name"
# Each local file against its copy, by size: a missing or truncated file fails the sync by name.
expected=$(mktemp)
find "$folder" -type f -printf '%s\t%P\0' > "$expected"
check='
import os, sys
dest, edfs, bad = sys.argv[1], 0, []
for record in sys.stdin.buffer.read().decode().split("\0"):
if not record:
continue
size, name = record.split("\t", 1)
path = os.path.join(dest, name)
got = os.path.getsize(path) if os.path.isfile(path) else None
if got != int(size):
bad.append(f"{name}: missing" if got is None else f"{name}: {got} of {size} bytes")
elif name.lower().endswith(".edf"):
edfs += 1
print(edfs)
print("\n".join(bad))
sys.exit(1 if bad else 0)
'
if ! report=$(kubectl exec -i "$pod" -- python3 -c "$check" "/referencia/$name" < "$expected"); then
echo "these files did not arrive whole:" >&2
tail -n +2 <<< "$report" | head -20 >&2
exit 1
fi
echo "copied: $(head -1 <<< "$report") of $local_count EDF files to /referencia/$name, each at its local size"
echo "train with: --reference-dir /referencia/$name$(find "$folder" -maxdepth 1 -iname '*.csv' -printf ' --reference-ages /referencia/'"$name"'/%f' -quit)"
+20
View File
@@ -0,0 +1,20 @@
"""Prints, as JSON, the versions distributed's version check compares and the ones the EEG numbers depend on.
build.sh runs it in this image and in the platform's webapi image and refuses to push when they differ.
"""
import json
import platform
from importlib.metadata import PackageNotFoundError, version
PACKAGES = ("dask", "distributed", "msgpack", "cloudpickle", "tornado", "toolz", "lz4",
"numpy", "pandas", "scipy", "scikit-learn", "mne", "yasa", "antropy", "meegkit", "fooof", "tea")
def _version(name: str) -> str | None:
try:
return version(name)
except PackageNotFoundError:
return None
print(json.dumps({"python": platform.python_version(), **{p: _version(p) for p in PACKAGES}}, sort_keys=True))
+20
View File
@@ -117,3 +117,23 @@ build, isolated from the server, for development experiments.
opened from a version).
- Only `.ipynb` (nbformat 4) is accepted. Open items in
`docs/ledgers/open-items.md`.
### TEA EEG training and analysis
- `models/models/tea/eeg/model.py` uses `EEG_ANALYSIS_CLUSTER` to select
the runner that measures reference studies. It accepts `auto`, `local`,
`remote`, and `sync`, and falls back to `auto` for `off` or an
unrecognised value. Auto uses `DASK_SCHEDULER_ADDRESS` when configured.
- `python -m models tea analyze --ids 12,34` reanalyses the specified EEGs
regardless of pending status. `--ids` takes comma-separated database
EEG IDs and is mutually exclusive with `--all` and `--limit`.
- `tea.pipeline.cluster_status.ClusterStatus` reports the effective mode
and remote health, including scheduler reachability, worker count,
version compatibility, dashboard status, and reference volume visibility
for the requested cohort.
- `tea.pipeline.run_monitor.RunMonitor` publishes the current phase, counts,
elapsed time, ETA, and recent samples during training and analysis. Dask
runs include task counts and worker CPU and memory. When `RUN_PROGRESS_DIR`
is set, the monitor atomically replaces `progress.json` in that directory.
See the [WebApi routes and detached job lifecycle](webapi.md#tea-eeg-governance).
+35
View File
@@ -61,3 +61,38 @@ Moved from `AGENTS.md` on 2026-11-03.
- WebApp: the flow editor's "Reglas" tab (`connect/components/mapping-rules`)
sets document columns, derived fields and the catalog fallback, and shows
the mapped preview.
### TEA EEG governance
The Gobernanza **TEA · EEG** panel uses these new and extended endpoints.
| Method | Path | Purpose |
|---|---|---|
| GET | `/governance/tea/cluster` | Check the selected cluster mode, scheduler, versions, workers, dashboard, and optional reference cohort. |
| GET | `/governance/tea/reference-cohorts` | List cohorts under `TEA_REFERENCE_ROOT`. |
| POST | `/governance/tea/reference-cohorts/<name>/files` | Upload one EDF or `edades.csv` as multipart `file`. |
| POST | `/governance/model-versions/tea/eeg/train-jobs` | Start training with optional cohort, line frequency, promotion, and cluster settings. |
| GET | `/governance/tea/baselines/export` | Download the baseline ZIP with SHA-256 and version count headers. |
| POST | `/governance/tea/baselines/import` | Import a multipart baseline ZIP and return its hash and imported versions. |
| POST | `/governance/tea/eeg/analyze-jobs` | Start analysis for pending EEGs or select a limit, all EEGs, or explicit IDs. |
| GET | `/governance/tea/eeg/analyze-jobs` | List analysis jobs, newest first. |
| GET | `/governance/tea/eeg/analyze-jobs/<id>` | Read analysis job state and its summary when available. |
| GET | `/governance/tea/jobs/<kind>/<job_id>/progress` | Read the latest training or analysis sample. Returns 404 before the first sample. |
| GET | `/governance/tea/baselines/<scenario>/<version>/metrics` | List metrics with a baseline age curve. |
| GET | `/governance/tea/baselines/<scenario>/<version>/curve` | Read the age percentiles for the requested `metric`. |
| GET | `/governance/tea/eeg` | List EEGs with pagination and analysis status. |
| GET | `/governance/tea/eeg/<eeg_id>/metrics` | Read study age, validity, metric values, z-scores, and outliers. |
| POST | `/governance/tea/eeg/upload` | Validate and import one EDF via the import pipeline, with an optional patient ID. |
| POST | `/governance/tea/eeg/preview` | Analyse one EDF (`edf`) and an optional ADOS-2 PDF (`ados2`) in memory and answer a patient-summary bundle with notices; nothing is stored. |
| GET | `/governance/tea/eeg/summary` | Count EEGs, metrics, outliers, and FHIR view rows. |
| POST | `/reportes/indicadores/tea/recalcular` | Queue a TEA indicator cycle. The contract specifies an optional cluster choice. The current handler queues the cycle using the service configuration. |
Reports, checks, promotion, and training job status use the existing governance
routes. The cluster health endpoint uses the models-side `ClusterStatus`
probe and accepts scheduler addresses from `DASK_SCHEDULER_ADDRESS` and
`TEA_DASK_SCHEDULERS`.
`WebApi/webapi/detached_jobs.py` launches training and analysis as subprocesses
in their own sessions. It records job metadata, stdout, stderr, and exit status
in the job directory and passes that directory to the child as
`RUN_PROGRESS_DIR`. The progress endpoint reads `progress.json` there.
+176 -8
View File
@@ -100,8 +100,8 @@ Left open by the implementation of `plans/kit-exit/tea-redesign.md` (all but the
all the period's children, its event the first F84.0 note. M29 counts the cohort's children only. ADOS-2 items are
the 28 of the old staging (the plan says 29 but its own total of 76 columns has 28); labels of B13 to B18 and D5
wait for the manuals. Codes are the project's: no LOINC or SNOMED until confirmed (§12.9).
- `fhir.resources` (8.3, R4B models) added to WebApi's dev group to validate responses in tests: needs the owner's
approval as a new dependency (§12.9).
- `fhir.resources` (8.3, R4B models) added to WebApi's dev group to validate responses in tests: **approved by the
owner 2026-11-15** as a new dependency (§12.9).
- Patient routes (`EpisodeOfCare`, `$resumen-tea`) are registered only in DEV with the `simulado` tag; alterations
stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`.
@@ -115,16 +115,184 @@ presentation onto one branch:
screens and the `ConceptMap` endpoint of G-GEN-1 are not built.
- The follow-up list exists for CaCu only (`webapi/follow_up/`); the CaMa follow-up tab shows the unavailable state
until a CaMa list is served. Angel's CaMa follow-up and Análisis endpoints (`dashboard-test`) read the kit and a
synthetic reader, so they were not merged.
synthetic reader, so they were not merged. **Ported 2026-11-15**: `webapi/cama_cohort.py`, `cama_runtime.py`,
`cama_analysis.py` and `seguimiento_cama.py` brought in from `dashboard-test`, with `cama_cohort.py`'s three kit
imports (`indicadores_kit.cama.{tablas,consultas.plata,familias.histopatologia_birads.consulta}`) replaced: the
table namespace by `webapi.orchestration.tables.cama.TABLAS` (already the generic replacement), the kit's SQL
select-builders (`mastografias`/`biopsias`) by Python equivalents of the already-committed
`Transformation/models/cama/silver/cama_{mastografias,biopsias}.sql`, and the `BIRADS` code dict by one read off
`core/catalogos/cama.toml`'s `mastografia.resultados.birads` values against the WebApp's `BIRADS_4..6` contract
(`etiquetas-cohorte.ts`). Angel's own test suite (`test_cama_cohort.py`, `test_cama_runtime.py`,
`test_seguimiento_cama.py`, 14 tests) ported with only the same import fix and passes unchanged, which is strong
evidence the port is behaviorally faithful. The WebApp side needed no changes: it was already merged and only
needed the backend to stop 503ing.
- The three CaMa measures Angel added to the kit (`deteccion_histopatologica`, `dias_resultado_diagnostico`,
`histopatologia_birads`, #161) were not ported; the dbt CaMa measures and the invasive-cancer stratifiers are what
the page draws. Re-expressing them in dbt is a separate task.
- `feature/cacu-pim-vigilancia` (models as a Hamilton dataflow, the CIN2+ prevalence-incidence scenario) is
deferred: it predates the cohort move into `models/cohorts` and needs rebasing on the new `dev`.
- The webapi image compiles dbt's manifest for SQLite at build time and, on another engine, at start-up against the
configured databases (`webapi.dbt_manifest`); the start-up path was not exercised against a real MySQL,
PostgreSQL or SQL Server here, and Docker was unavailable on the machine that built the branch.
configured databases (`webapi.dbt_manifest`). **Verified 2026-11-15** against real MySQL (`isssteleon-mysql-test`),
SQL Server (`isssteleon-mssql-test`) and a throwaway PostgreSQL 16 container, each with scratch databases:
`python -m webapi.dbt_manifest` compiled the full manifest (44 models, 39 metrics) on all three and printed the
manifest path, matching the SQLite path's shape. Not yet run: `WebApi/webapi/__init__.py` actually serving `/kpis`
from one of these compiled manifests (only the compile step was exercised, not a full request against it), and
this was outside Docker Compose (the `webapi` service image itself wasn't rebuilt or started against them). Also
found: `Transformation`'s `.venv` only has the `sqlite`+`sqlserver` groups synced, not `postgres`; MySQL needs its
own `.venv-mysql` (`UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql`, undocumented until now) since
dbt-mysql pins dbt-core 1.7 against the others' 1.12.
- TEA's alterations stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`; `fhir.resources` in the WebApi's dev group
still needs the owner's word; suppression and intervals are #73's.
- A risk batch stays `preliminary` until `python -m webapi.orchestration confirm-risks`; the risk route serves
only final batches.
was approved by the owner 2026-11-15; suppression and intervals are #73's.
- A risk batch stays `preliminary` until confirmed or voided (ADR-MD-008); the risk route serves only final batches.
**Built 2026-11-15**: `GET/POST /cacu/riesgos/lotes...` (`webapi/risk_batches.py`, over a new
`CohortRepository.pending_batches`) and a "Lotes de riesgo" tab in Gobernanza, so this is a WebApp action now,
not only `python -m webapi.orchestration confirm-risks`. CaCu only; CaMa and TEA have no risk model to batch yet.
- `models`' CLI `--promote` (the `entrenar` compose profile's last step) set the MLflow alias directly, bypassing
`registry.promote`'s checklist entirely — contradicting its own docstring ("promotion is always a manual step").
**Fixed 2026-11-15**: the CLI now calls `registry.promote` and reports the failing checks instead, same as the
WebApi route. Found on the way: `registry.checks`'s ML-03 only recognized the kit's `armado_id` link, so a
version trained on a dbt cohort (CaCu's path since this integration) could never pass the gate at all; fixed to
also accept the `cohort.source`/`cohort.build` tags a dbt-sourced run carries.
- Consequence of the fix above, found the same day: `docker-entrypoint.sh`'s `entrenar` branch ran
`models run cacu cin2_logistic --export --train --promote` with no `--environment`, defaulting to DEV. Against
the now-gated `--promote`, ML-02 (version tagged for production) would always fail, so `entrenar` as shipped
could never actually put a version into production. **Fixed 2026-11-15**: the command now adds
`--source dbt --manifest "$DBT_MANIFEST" --environment prod`, training and exporting from dbt's cohort instead of
the kit's numbered builds — the only way to name a PROD run's cohort build (ML-03) without knowing its number
ahead of time, and the same tag-based ML-03 path above, so the gate stays portable across environments (no live
lookup of a local build row). Verified piece by piece against existing tests (dbt export through a live session:
`models/tests/test_export_cohort.py::test_the_command_exports_from_dbt_through_the_session`; PROD train + gated
promote from a dbt cohort: `models/tests/cacu/test_cin2_logistic.py::
test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it`), not as one live combined run.
- `entrenar` being a compose command assumed someone, somewhere, has a shell — raised 2026-11-15 as not actually
true (no CLI access at ISSSTELEON, and hospital staff can't be expected to run one either). This put two
questions to the owner: whether `cin2_logistic` is meant to stay a locally-fit model at all (a published,
externally-validated set of coefficients, the way ASCCP's own risk tables work, would need no local training and
make the CLI-access problem moot), and if so, whether to solve the access problem by pre-training offline and
shipping a promoted version, or by moving the trigger from a shell to the browser.
**Decided 2026-11-15: the model stays locally-fit** (`fit()` genuinely estimates its coefficients from the
site's own cohort each time; it is not a candidate for published/external coefficients) **and the owner chose a
UI training trigger over offline pre-training** — the latter ships with no clinical validation against the site
that will use it, and would also need install-time seeding tooling that doesn't exist.
**Built the same day**: `POST /governance/model-versions/<domain>/<scenario>/train`
(`webapi/blueprints/governance.py`) runs the exact same `models.__main__.main` invocation `entrenar` does
(`--export --source dbt --environment prod --train --promote`), over HTTP; 404 for no trainer, 409 for trained
but not promoted (needs reports attached first), 503 with no manifest or an operational failure. A "Entrenar
cin2_logistic" button in Gobernanza's model-versions panel calls it. `entrenar`'s compose command stays as an
equivalent path for whoever does have server access; the manual documents both.
### The `tea` EEG library orchestrated into TEA (`plans/i-added-the-tea-lucky-mccarthy.md`), 2026-11-19
Left open by steps 0 and 1 (the library at `models/libs/tea` @ `9cef555`; the schema it writes):
- The library is installed from the `models/libs/tea` submodule, which stays at `alberto/tea.git`. Deploy and CI
trust that exact origin and read it anonymously over HTTP: if the repository becomes private, CI and deploy
can't fetch it. `models` now needs Python ≥ 3.12, and the WebApi runs on pandas 3.1 / numpy 2.5 (suite unchanged).
- Revision `16bf0b0ee3e4` (`eeg_criterio` and the analysis columns on `eeg`, `eeg_metrica`,
`eeg_metrica_electrodo`) was checked upgrade/downgrade/upgrade with data on SQLite only; MySQL, PostgreSQL and
SQL Server untested (rule 7).
- The four fixed criterion columns of `eeg` (`eeg_canales_amplitud`, `_alta_frecuencia`, `_correlacion`,
`_sin_senal`) are still there: they go in their own revision with the step that moves silver and dbt to
`eeg_valido` / `eeg_criterio`, so the chain stays green in between. Until then `mel_valor` is still read as a z by
the FHIR map, while the dictionary already documents it as the raw value and `mel_z` as the z.
- To confirm with the domain expert: which library feature each metric maps to (`spike_rate_nrem` for
`PICOS_PAROXISTICOS`, `gradient_delta_sueno` for `GRADIENTE_ANTEROPOSTERIOR`, and the N3 spindles while
`DIRECTOR_CLUSTER` has `use_n3=False`).
- Step 2 (`models/models/tea/eeg/`, `models/models/eeg_analysis.py`, `python -m models tea analyze`): no baseline
is registered yet, so every metric is stored with its raw value and null z / `met_fuera` until step 8 trains and
promotes `tea-eeg-<biomarker>[-<stage>]`. Only `cluster="sync"` was run here; a LocalCluster and a remote
scheduler (`DASK_SCHEDULER_ADDRESS`) are the library's own paths, untried from `models`. Only the modern
implementation is supported (the legacy validator has no `checks_of`). On the synthetic studies and with
`DIRECTOR_CLUSTER`, `HUSOS_SUENO_N3` comes out null.
- Step 3 (`analyze_eeg` before `load` in the cycle, `POST /governance/eeg/run`, `EEG_ANALYSIS_CLUSTER`): with the
default `auto` and no `DASK_SCHEDULER_ADDRESS`, the `indicadores` container starts a local Dask cluster sized by
its free memory (4.25 GiB per worker); its memory limit in `docker-compose.yml` wasn't revisited, nor was a Dask
scheduler service added. The analysis in a request is bounded by `limit` (5 by default) against gunicorn's 600 s
timeout. Only `sync` was run here.
- Step 4 (silver, catalog and the quality chain on the analysis's output; revision `c4306f438b3a` drops
`eeg_canales_amplitud`, `_alta_frecuencia`, `_correlacion`, `_sin_senal`; the `tea.EegMetrica` and
`tea.EegMetricaElectrodo` import targets retired): checked on SQLite only. FHIR shows only the numeric
study-wide checks as quality observations, in the shape the WebApp's patient summary validates; the triage level
(text) and the bad channels reach silver and `tea_paciente_eeg_criterios` but not FHIR until the FHIR rework
(steps 6 and 7). `cri_decisivo` isn't carried into silver. dev-data no longer writes any analysis column or
metric row (its `cargar` would have hit the retired targets): until step 7b makes its EDFs long enough for the
library, the DEV EEGs come out not valid and the EEG panels and M29/M30 have nothing good to show. The z, -1/0/+1
and p5/median/p95 are in silver but dbt still scores the metrics with the placeholder references (step 5).
- Step 5 (dbt scores the metrics with the analysis's z, -1/0/+1 and the baseline's p5/median/p95;
`tea_eeg_referencias` and the vars `referencias` and `alteracion_z` removed; the FHIR electrode map now plots each
electrode's z, `valor_z`): this supersedes the TEA redesign's assumption that the metric references live in dbt's
var `tea`. With no baseline in production every metric is `no_evaluable`, so M30 counts no alteration and the
WebApp shows none until step 8 promotes the baselines (and the alterations stay hidden behind
`TEA_ALTERACIONES_VALIDADAS` anyway).
- Step 6 (FHIR): every answer is validated against `fhir.resources` R4B before it leaves (a non-conforming one is a
500 `OperationOutcome`); `fhir-resources>=8.3` is now a main WebApi dependency, as the plan approved. The EEG's
quality observations take the analysis's own shape (`urn:tea:validation` codes, A/N, `electrode` and `decisive`
components), bad channels and the triage level included, and `CodeSystem/tea-eeg-criterio` labels them; the
report adds the analysis's `valid`/`not-valid`. The WebApp's patient summary still filters `eeg.calidad_*` codes
and BUENO/MALO, so its quality panel is empty until step 7. `CapabilityStatement.fhirVersion` stays `4.0.1`: no
validated field differed between R4 and R4B in these resources.
- Step 7 (WebApp aligned with the analysis's output: quality as the analysis's checks with the bad channels,
`sin_analizar`, a missing duration or channel count, the ADOS-2 classifications of module T and an unclassified
one, item codes 7-9, the age group from `$resumen-tea`'s episode, why a metric couldn't be evaluated, the curve's
median, and the EEG filter and summary box by a valid EEG while the alterations are hidden; the status page reads
the new checks; the TEA FHIR fixtures regenerated from the WebApi): `npx ng test` passes (1791 tests) on Node
24.15.0, the CI's version, installed in a scratch folder. The follow-up list's EEG column still says «No disponible» while
the alterations are hidden. The fixtures were regenerated by hand from the WebApi's TEA test database; there's no
script for it in the tree.
- Step 7b (dev-data gives only what the analysis reads: each EEG's story asks for good or bad, with or without
sleep and which metrics are altered, and its EDF draws it, 3.5 min at 256 Hz with 24 channels, the shortest the
library grades `completo` with margin; the hospital inserts its blobs in batches of at most 16 MB): on 30 children
every analysed EEG came out as its story asked. Not run against the MySQL hospital or a deployed platform: about
220 MB of EDFs for 200 children, and the `indicadores` cycle analyses them (minutes per batch). The gradient is
never drawn altered. N3 spindles are found on these EDFs, unlike the earlier synthetic ones.
- Step 8 (`python -m models run tea eeg --train [--promote]`: the age baselines trained on HK1K and registered as
`tea-eeg-<biomarker>[-<stage>]`): tested on a synthetic reference table and synthetic EDFs, not on HK1K. The run
is the owner's: it reads HK1K from the cluster's S3 (`raw/eeg-helsinki/`, the `eeg-reference` extra, keys from
the environment) and must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI` of the deployment,
SQLite inside the webapi container by default); with a remote Dask scheduler the workers need `models` and `tea`
installed, otherwise `cluster=local` measures in the training process. Decision to confirm: a reference cohort
outside the platform (`cohort.source = referencia`, the hash of its listing) satisfies ML-03 for these versions
(`registry.checks`). Promotion still needs the three reports (MLD-01, MLD-01b, MLD-03), which is where the domain
expert's validation goes; `TEA_ALTERACIONES_VALIDADAS` stays a separate switch in the WebApi.
### TEA: ADOS-2 association, zones and the library's spike and spindle changes (2026-11-21)
- The ADOS-2 association (`tea.associations.ados2`, `models tea relate-ados2`, the cycle's `relate_ados2`) writes
every version unvalidated (`rel_validado` 0). Who validates a version, and how the panel shows an unvalidated one,
is the domain expert's decision. On the 62 real EDFs only the ADOS-2 rows were invented, so the associations
there say nothing.
- Legacy `ados2_association` scores only the rows it was fitted on (the research code keeps only those
probabilities); the platform runs modern, which scores any row.
- Spike densities use a count reference (`CountRate`: the reference's aggregate rate and its negative-binomial
dispersion, z from the child's mid-p tail in its own minutes). That method, and the 0.05 cut for `outside`, need
the domain expert's review, like the other baselines.
- Every biomarker module changed version (spikes 0.4.0, spindles 0.2.0, the rest 0.2.0 for the `outside` change),
so every EEG is analysed again, and the baselines must be retrained and promoted with their reports before the
next load. The cluster's image must come from the same ISSSTELEON commit as the deployment
(`dask-cluster/build.sh`; it now adds bokeh for the dashboard).
- `tea_ados2_reactivos.puntaje_algoritmo` now counts 7, 8 and 9 as 0 (the ADOS-2 algorithm's rule), which changes
the domain totals everywhere it is read, not only in the association view. To confirm with the owner.
- A child with two ADOS-2 on the same first date duplicates its rows in `tea_paciente_relacion_ados2`, as before.
- Spindle per-electrode and per-zone densities exist only for the channels the detector searches (no T3-T6, O1,
O2), so `spindle_zone_temporal_*` and `spindle_zone_occipital` are NaN by design.
- Not ported (outside the brief): per-candidate `origen_estado` / `motivo_puerta` from `picos_eventos`, inherited
per-electrode spike densities, and `ventana_de_candidatos`.
- WebApi's suite has 13 failures on this machine that need tesseract, pymssql and the notebook runner; unrelated to
this change.
- The previous deployment's run reported that `models run tea eeg --promote` fails for the EEG baselines ("no such
model"); not looked at here.
- CaCu migration `a1d4e7c20b31` (risk index date, from `dev`) fails on an existing SQLite database that already has
the dbt views: the batch rebuild of `evaluacion_riesgo` stops at `error in view cacu_riesgo_vigilancia: no such
table: main.evaluacion_riesgo`. A fresh database is fine; any SQLite installation upgrading with the views built
hits it. Seen on the manual deployment A (2026-11-22), which was restarted from an empty volume.
- ADOS-2 CSS and classification are now computed by the platform (`tea.scoring`, `models tea score-ados2`, the
cycle's `score_ados2`, `ADOS2_SCORING=off` to skip), and the hospital no longer sends module, algorithm, CSS or
classification (dev-data takes module and algorithm from the PDF through the document source). Open:
- the CSS cut points in `tea/scoring/ados2.py` are approximate, written from memory of the calibrated severity
tables, not transcribed from the manual; they must be replaced with the licensed values (they are data);
- the total is the sum of the items present, so an item read as `S/D` lowers it; the expected items per module and
algorithm are not checked;
- Toddler gets a range of concern and no CSS, and dev-data writes no PDF for a Toddler ADOS-2, so those children
have no module, items or classification after the load;
- the document import was not run end to end with `ado_modulo` and `ado_algoritmo` in the mapping (unit tests
only); Module 2 prints no algorithm, so its `ado_algoritmo` stays empty.
+19 -16
View File
@@ -42,9 +42,9 @@ own import API, the same way a person would connect the hospital in
hospital is left alone unless `repoblar = si`. Check it:
`dev-data/montura/comprobar_hospital.sh dev-data-prueba`.
2. **The platform is newly installed and empty.** WN's `deploy-dev` workflow
(`.gitea/deploy/dev.py install-auto <port>`) creates empty storage only for
a new, unregistered port. A registered port conservatively updates its
existing data. Confirm this is a new installation before loading anything.
installs on a free port, and `reinstall-dev` replaces a DEV instance with a
new, empty one. Neither updates data in place. Confirm the instance is new
before loading anything.
3. **Load it:**
```sh
@@ -74,16 +74,14 @@ uv run --python 3.12 python -m dev_data cargar cacu --api http://10.0.10.41:<por
## As a Gitea action
Loading must be a separate, explicitly requested operation for a confirmed empty
installation. Do not append this step unconditionally after `install-auto`:
that command also updates populated instances. The runner checks out the WN tree with
its submodules (`git submodule update --init --recursive`), which brings
`dev-data` once the submodule is committed. A sketch, not applied:
```yaml
- name: Load the simulated hospital
run: dev-data/montura/cargar.sh "http://10.0.10.41:$PORT"
```
The `load-dev-data` workflow runs this load as a separate, explicitly requested
operation for an installed, still empty DEV instance (`installer.py load-data`,
documented in `.gitea/deploy/README.md`). It builds the loader from the `dev-data`
commit recorded in the instance's installation record, reads the hospital at the
`hospital` input (`host:port`, default `10.0.10.41:9505`), loads `cacu`, `cama` and
`tea` through the instance's published port, and waits for the three indicator
recalculations to end `ok`. It refuses an instance that already has import
attempts or an earlier load.
What it needs:
- the job can use Docker (it already does to build the platform images);
@@ -99,6 +97,12 @@ What it needs:
| CaMa | Paciente, Mastografia, BiopsiaMama, NotaMedica | 1,026 (300 patients) | 0 |
| TEA | Pacientes and nine more | 2,738 (200 patients) | 0 |
Since the EEG analysis moved into the platform (2026-11-19), TEA's hospital
has six tables (no `eeg_metrica` or `eeg_metrica_electrodo`) and each EEG
carries a 3.5-minute EDF of about 2.6 MB (about 220 MB for 200 children), so
the TEA row count above is lower now. The EEG panels and M29/M30 fill only
after the `indicadores` cycle has analysed the EDFs.
Same counts on the empty sandbox `isssteleon-sandbox-his` (18093). The
instance was reinstalled by the workflow afterwards, came back empty, and
`montura/cargar.sh` loaded it again with the same counts.
@@ -113,8 +117,7 @@ instance was reinstalled by the workflow afterwards, came back empty, and
`ISSSTELEON/dev-data` layout; until it is updated, run `poblar.sh` from the
WN checkout.
- Regenerating the hospital (`repoblar = si`) does not replace data already
imported into a deployment. Updating the application keeps those records.
Regeneration requires a separately authorized data operation or a new isolated
installation and load; reusing the port is not a reset mechanism.
imported into a deployment. A clean load needs a reinstall of the DEV instance
(`reinstall-dev`, which removes its data) followed by `load-dev-data`.
- Superseded by #165 once the platform keeps its HIS connection: the
deployment would declare the hospital as a configured source.
+19 -4
View File
@@ -5,18 +5,18 @@
# --- Project ---
# Prefix of every container, network, volume and image. Change it (and the
# ports) to run a second copy next to this one.
COMPOSE_PROJECT_NAME=isssteleon-manual
COMPOSE_PROJECT_NAME=sitio-a
# --- Published ports ---
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
# machine only.
BIND_ADDRESS=0.0.0.0
# The application (nginx: pages and proxy to the API). Open this one.
WEBAPP_PORT=5210
WEBAPP_PORT=5310
# The API, direct.
WEBAPI_PORT=5211
WEBAPI_PORT=5311
# The simulated hospital's MySQL (user/password hospital/hospital).
HOSPITAL_PORT=5212
HOSPITAL_PORT=5312
# --- Simulated hospital contents ---
# Patients generated per project, the generator's seed and reference date.
@@ -26,6 +26,21 @@ N_CAMA=300
SEMILLA=7
REFERENCIA=2026-01-01
TEA_ALTERACIONES_VALIDADAS=1
# Folder of real EDF files, as an absolute path: each file becomes one more TEA
# child (after the N synthetic ones), a confirmed autism case whose only EEG
# carries that file. Empty: only the synthetic EDFs. Changing it needs
# `docker compose down -v` (a populated hospital is left alone).
EDF_CARPETA=/home/milk/datos/edf
DASK_SCHEDULER_ADDRESS=tcp://10.0.10.41:30786
# Gobernanza > TEA · EEG: the dashboard port and worker count the cluster card checks.
TEA_DASK_DASHBOARD_PORT=30787
TEA_DASK_EXPECTED_WORKERS=40
# Folder (in the container) holding one subfolder per reference cohort, and the host folder mounted there.
TEA_REFERENCE_ROOT=/referencia
REFERENCIA_CARPETA=../manual-deploy/referencia
# The indicator cycle leaves the EEGs unanalysed until the baselines are in production: upload them in
# Gobernanza > TEA · EEG, promote, then analyse there. Set to auto to analyse in the cycle as before.
EEG_ANALYSIS_CLUSTER=off
# --- Patient-level views ---
# Any value turns on the routes that return one patient's data (the follow-up
+309
View File
@@ -38,6 +38,41 @@ docker compose down # stop, keep the data
docker compose down -v # stop and delete this project's data
```
## TEA EEGs from real EDF files
Set `EDF_CARPETA` in `.env` to an absolute path holding `.edf` files. On the
next populate, each file becomes one more TEA child after the `N` synthetic
ones (`N-0201`, `N-0202`... with `N=200`), a case the platform counts as autism:
an at-risk M-CHAT, an ADOS-2 classed autism (module 1 or 2, CSS 5 to 10), a
note with F84.0, and one EEG that carries the file. The `N` synthetic children
are the same as without the folder. Left empty, the hospital has only the
synthetic EDFs.
```sh
docker compose down -v # the populate jobs leave a populated hospital alone
docker compose up --build -d
docker compose logs poblar # one line per file: child key and where its age came from
docker compose run --rm --build load
```
Things to know:
- **The age is the file's**: recording start minus birth date in its header.
The child's birth date and EEG date are set to keep it. A header without a
birth date, or with the 01.01.85 "unknown" start, gets an age drawn inside
the cohort, and the log says so.
- **The stored header is rewritten** with the child's key, birth date, EEG
date and `LAB-<key>-1`, so nothing of the original patient reaches the
hospital. The signal is untouched.
- **Size**: a file over 256 MB, or one that isn't an EDF, stops the TEA
populate with its name and writes nothing. The hospital's MySQL takes 1 GB
packets for these rows.
- **The TEA figures move**: the extra confirmed cases raise prevalence, the
M-CHAT positive predictive value and the confirmed counts. `documentos`
writes PDFs only for the `N` synthetic children.
- **A relative `EDF_CARPETA`** resolves from `../dev-data`, not from this
folder; use an absolute path.
## Indicators
The measures are defined in dbt (`../ISSSTELEON/Transformation`). The `webapi`
@@ -79,6 +114,280 @@ Things to know:
- **A change in `Transformation` needs a rebuild** (`up --build -d`) and a
recomputation, as above.
## TEA from the app
The whole baseline flow runs from **Gobernanza → TEA · EEG** in the web app: check the cluster, train the
seven EEG age baselines (or upload a `baselines.zip`), attach the reports, promote, analyse the EEGs and read the
result. No shell is needed after the deployment is up and loaded. The command-line version of the same flow is in
the next section; use it when the app can't do a step.
### The state `load` leaves
With the settings below, `up` and `load` leave the platform with the hospital's TEA children and their EEGs
**unanalysed**: no baseline is in production and the indicator cycle skips the EEG analysis
(`EEG_ANALYSIS_CLUSTER=off`). Resultado shows `EEGs 62, Analizados 0`. Nothing else is needed before the app steps.
```sh
docker compose up --build -d # hospital populated with the real EDFs in EDF_CARPETA
docker compose run --rm --build load # every `rechazadas` must be 0
```
Settings in `.env` (the template is `ISSSTELEON/dist/.env.ejemplo`):
| Setting | Value here | Purpose |
|---|---|---|
| `EDF_CARPETA` | absolute path of the real EDFs | each file becomes one TEA child (see "TEA EEGs from real EDF files"); the `N` synthetic children are left out |
| `DASK_SCHEDULER_ADDRESS` | `tcp://<host>:<port>` | where Remoto runs; empty means no cluster |
| `TEA_DASK_EXPECTED_WORKERS` | `40` | the worker count the cluster card compares with |
| `TEA_DASK_DASHBOARD_PORT` | `30787` | port of the Dask dashboard on the scheduler's host; `TEA_DASK_DASHBOARD_URL` replaces the whole address |
| `TEA_DASK_SCHEDULERS` | optional | extra scheduler addresses the card may check, besides `DASK_SCHEDULER_ADDRESS` |
| `TEA_REFERENCE_ROOT` | `/referencia` | folder in the `webapi` container with one subfolder per reference cohort, for local training and uploads |
| `REFERENCIA_CARPETA` | `../manual-deploy/referencia` | host folder mounted at `/referencia` (relative paths resolve from `../ISSSTELEON`) |
| `EEG_ANALYSIS_CLUSTER` | `off` | `off` leaves the EEG analysis out of the indicator cycle, so the EEGs wait for the baselines. `auto` analyses in the cycle on the cluster (or locally with no scheduler); `local`, `remote` and `sync` force a mode |
| `TEA_REFERENCE_NAME` | optional | default cohort name for a training request that gives none |
Remote runs need the **platform and worker images built the same day** from the same checkout, with the same
Python: Dask refuses a worker whose Python differs even by a patch. Build the platform with
`docker compose build --pull`, then the worker image (`../dask-cluster/build.sh`) and `./deploy.sh`; `build.sh`
stops with that advice when the two differ.
### The steps
| Step | What to do | What you see |
|---|---|---|
| **Clúster** | Pick Auto, Local, Remoto or Sync; the choice applies to Entrenar and Analizar. With Remoto press **Verificar**. | Scheduler, workers (`40 de 40`), versions (`Cliente y trabajadores coinciden`), dashboard, and a button that opens the Dask dashboard. |
| **Datos de referencia** | Only for training on this machine (Local or Sync): upload a cohort's EDFs and its `edades.csv`, or see the cohorts already in `TEA_REFERENCE_ROOT`. | One row per cohort with its EDF count and whether it has ages. |
| **Entrenar** | *Remoto*: type the cohort's path **on the cluster** (`/referencia/helsinki`) and its ages table (`/referencia/helsinki/edades.csv`); choose 50 or 60 Hz. *Local*: pick an uploaded cohort. Leave **Promover al terminar** unticked (promotion needs the reports). Press **Entrenar**. | The run monitor: phase, `done/total`, ETA, CPU and RAM per worker, task counts, and a history. Seven `eeg-*` versions appear when it ends (`223 estudios` on 40 workers took 3 min 16 s). |
| **Líneas base** | **Exportar** downloads `baselines.zip`. **Importar** takes a zip from your computer instead of training, for example `baselines/baselines.zip`. Importing the same versions twice is refused. | The imported versions, or a clear message when they already exist. Wait for it to finish before the next step. |
| **Reportes** | Enter the technical validation, clinical validation and interpretability addresses and apply them to the versions. At least one address is required. | `Reportes aplicados a 7 de 7 versiones.` |
| **Promover** | **Promover todas**. A version missing its reports shows the checks that failed. | `Promovidas 7 de 7.` Promotion applies to the next analysis without restarting anything. |
| **Verificar línea base** | Pick a scenario, version and metric to see its p5–p95 age curve and overlay analysed EEGs. A cohort too small to have curves says so. | The curve and, once EEGs are analysed, where each study falls. |
| **Analizar** | Choose **Pendientes**, **Primeros N** or **EEGs elegidos**, then **Analizar**. **Subir EDF** adds a new study first. Then **Ejecutar ciclo de indicadores** to rebuild the indicator views from the new metrics. | The run monitor again, then `Válidos`, `No válidos`, `Fallidos`. |
| **Resultado** | **Actualizar**. | EEGs, analysed, valid, metrics, metrics with z, high and low, and the FHIR view rows; the state of the TEA indicator cycle. |
Things to know:
- **Every step reads the versions again when you open it**, so a zip imported in Líneas base shows up in Reportes
without reloading the page.
- **Remote training reads the cluster's volume.** The files must already be at `/referencia/<name>` on the workers
(`../dask-cluster/sync-reference.sh <folder> <name>`, step K2). Uploads in Datos de referencia reach only this
machine, so they serve Local and Sync runs.
- **Analysing on Remoto sends the EDFs to the workers**; the monitor may print a harmless Dask warning about the
size of the task graph.
- **A cohort with fewer than about 30 studies per age bin has no curves** and its metrics carry no z; use the
full reference cohort for real results.
- **To go back to analysing inside the cycle**, set `EEG_ANALYSIS_CLUSTER=auto`, recreate `webapi` and
`indicadores`, and ask for a cycle in Analizar. EEGs already analysed without baselines are not re-analysed:
choose **EEGs elegidos** for them.
What still needs the host: building and pushing the worker image (K1), copying reference data to the cluster (K2),
deploying or deleting the cluster (K3), and the dev-data `poblar` and `load` jobs, which fill the simulated hospital
and import it.
## TEA from the command line: EEG age baselines on a Dask cluster
Two copies of this deployment, built from the same folder: **A** (project
`sitio-a`, the one in `.env`) trains the seven EEG age baselines on the Dask
cluster and exports them; **B** (project `sitio-b`) runs the simulated
hospital with the real EDFs, imports and promotes the baselines, then loads.
B's indicator cycle analyses the EEGs on the cluster by itself. Both use the
same ports, so only one runs at a time.
The commands below use these placeholders:
| Placeholder | What it is |
|---|---|
| `<referencia>` | folder of training EDFs plus `edades.csv`, the ages table |
| `<edf>` | folder of EDFs for B's simulated hospital |
| `<scheduler>` | the Dask scheduler, `tcp://<host>:<port>`; its dashboard is at `http://<host>:<port>/status` |
| `$API` | `http://localhost:<WEBAPI_PORT>` |
| `$PY` | `/app/WebApi/.venv/bin/python`, the Python inside the platform image (its entrypoint ignores other commands) |
Set the two variables in the shell first, for example
`API=http://localhost:5210 PY=/app/WebApi/.venv/bin/python`.
Each deployment keeps its data in the volume `<project>_webapi_data`, mounted
at `/data` (`/data/tea.db`, `/data/mlflow.db`). The cluster scripts are in
`../dask-cluster`; its README explains how the worker image is built.
### Once: settings
The containers read their environment from `.env`, shared by A and B. It
needs:
```sh
EDF_CARPETA=<edf>
TEA_ALTERACIONES_VALIDADAS=1
DASK_SCHEDULER_ADDRESS=<scheduler>
```
With the scheduler set, training, the indicator cycle and any manual analysis
run on the cluster, and a TEA cycle needs the cluster up. To run without it,
remove that line and recreate `webapi` and `indicadores`. A also puts the EDF
children in its hospital; that doesn't matter, A is never loaded.
### K. The cluster
```sh
kubectl get daskclusters # Running
curl -s http://<host>:<dashboard-port>/json/counts.json # the expected number of workers
```
Only after a change to ISSSTELEON or to the training data:
```sh
cd ../dask-cluster
WEBAPI_IMAGE=sitio-a/webapi:local ./build.sh # K1: rebuild and push the worker image
./sync-reference.sh <referencia> <name> # K2: copy the training data to the cluster volume
./deploy.sh # K3: start or update the cluster
```
- **K1** must print the same versions as the platform, Python's patch included.
Rebuild the deployments from the same ISSSTELEON commit with
`docker compose build --pull`, and this image the same day, or the version
check refuses the workers. `build.sh` writes the image tag to `.image`, which `deploy.sh`
and `sync-reference.sh` read.
- **K2** puts the files at `/referencia/<name>` in every worker and ends with
`copied: n of n EDF files`, each at its local size; a missing or truncated
file fails it by name. The pod downloads from this machine over HTTP while
it runs, open to the LAN: fine for public reference data, not for patient
EEGs.
### A. Train and export
```sh
docker compose -p sitio-b down # A1: B down, A up
docker compose up -d
until curl -sf $API/health >/dev/null; do sleep 5; done
docker compose exec webapi printenv DASK_SCHEDULER_ADDRESS # <scheduler>
```
```sh
# A2: train the seven baselines on the cluster
docker compose run --rm --entrypoint $PY -v <referencia>:/referencia/<name>:ro \
webapi -m models run tea eeg --train --environment prod \
--reference-dir /referencia/<name> --reference-ages /referencia/<name>/edades.csv \
--reference-name sitio-a --line-hz 50
```
Seven lines, `eeg-…: trained, version N` (or `already trained`). The studies
show on the cluster dashboard while it runs. For a run from scratch, use
`docker compose down -v` in A1; it deletes A's MLflow and data.
```sh
# A3: export, then stop A
mkdir -p baselines
docker compose run --rm --entrypoint $PY -v "$PWD/baselines:/salida" \
webapi -m models tea export-baselines --out /salida/baselines.zip --environment prod
sha256sum baselines/baselines.zip
docker compose down
```
It prints the seven versions and `written: /salida/baselines.zip (sha256 …)`,
the same hash `sha256sum` shows. `down` without `-v` keeps A's MLflow.
### B. Import, promote, load
Every command is `docker compose -p sitio-b`. The baselines must be in
production before `load`.
```sh
docker compose down # B1: A down, B from empty
docker compose -p sitio-b down -v # deletes B's data, never A's
```
```sh
# B2: build, then start, as two steps: in one go it can run the machine out of memory
docker compose -p sitio-b build
docker compose -p sitio-b up -d
until curl -sf $API/health >/dev/null; do sleep 5; done
docker compose -p sitio-b exec webapi printenv DASK_SCHEDULER_ADDRESS
docker compose -p sitio-b logs poblar | head -3 # EDF de /edf: n archivos ...
```
```sh
# B3: import the baselines
docker compose -p sitio-b run --rm -T --entrypoint $PY -v "$PWD/baselines:/salida:ro" \
webapi -m models tea import-baselines /salida/baselines.zip | tee baselines/import-b.txt
```
Seven lines, `eeg-…: imported as version 1`.
```sh
# B4: attach the three reports to each version
sed -nE 's/^([a-z0-9-]+): .* version ([0-9]+)$/\1 \2/p' baselines/import-b.txt |
while read scenario version; do
curl -s -o /dev/null -w "$scenario $version: %{http_code}\n" -X PATCH -H 'Content-Type: application/json' \
-d '{"technical_validation_report_uri": "file:///pendiente/tecnico.pdf",
"clinical_validation_report_uri": "file:///pendiente/clinico.pdf",
"interpretability_report_uri": "file:///pendiente/interpretabilidad.pdf"}' \
"$API/governance/model-versions/tea/$scenario/$version/reports"
done
```
Seven `200` lines. These URIs are placeholders for a test deployment; on a
real installation they point at the domain expert's documents.
```sh
# B5: promote the baselines
docker compose -p sitio-b run --rm --entrypoint $PY webapi -m models run tea eeg --promote --environment prod
```
Seven lines, `version 1 promoted`.
```sh
# B6: load, and let the cycle analyse on the cluster
docker compose -p sitio-b run --rm --build load
docker compose -p sitio-b logs -f indicadores | grep --line-buffered -E 'analyze_eeg|tea: |ERROR'
```
Every `rechazadas` is 0. Then `analyze_eeg: … elementos` while the dashboard
shows the batches, and `tea: ok` when the views are built. This needs
`EEG_ANALYSIS_CLUSTER=auto` in `.env`; with `off` (the default for the app
flow) the cycle leaves the EEGs unanalysed and `analyze_eeg` never appears.
```sh
# B7: check the result
docker compose -p sitio-b exec -T webapi $PY -c "
import sqlite3; c = sqlite3.connect('file:/data/tea.db?mode=ro', uri=True)
print('analysed EEGs, metrics, with z, high, low:', c.execute('select count(distinct met_eeg_id), count(*), sum(met_z is not null), sum(met_fuera = 1), sum(met_fuera = -1) from eeg_metrica').fetchone())
for t in ('tea_paciente_eegs', 'tea_paciente_eeg_metricas'): print(t, c.execute(f'select count(*) from {t}').fetchone()[0])"
```
Most analysed EEGs should have metrics with a z; `H` and `L` in TEA's patient
summary are metrics above or below the age curve (`N/A` are the validation
criteria). In the app, TEA's patient summary shows each metric against its
curve.
### Tear down
```sh
docker compose -p sitio-b down # -v also deletes B's data
(cd ../dask-cluster && ./deploy.sh --delete) # frees the nodes; the training data stays on the volume
```
Before the next TEA load without the cluster, remove `DASK_SCHEDULER_ADDRESS`
from `.env`.
### If something fails
| What you see | Why, and what to do |
|---|---|
| `port is already allocated` on `up` | The other deployment is still up: `docker compose down` (A) or `docker compose -p sitio-b down` (B). |
| `printenv DASK_SCHEDULER_ADDRESS` prints nothing | The line isn't in `.env`, or the container started before it was added. Fix `.env` and recreate `webapi` and `indicadores`. |
| `poblar` says `Sin archivos EDF` | `EDF_CARPETA` is empty. Fix `.env`, then B1 and B2. |
| No alterations in the app after B6 | `curl -s $API/reportes/indicadores`: `en_curso` means the cycle is still running; `error` means read the `indicadores` logs. `TEA_ALTERACIONES_VALIDADAS` must be 1. |
| Metrics without z after the load | The baselines weren't in production when the cycle analysed. Run B5, then `... run --rm --entrypoint $PY webapi -m models tea analyze --all` and request a fresh cycle with `POST /reportes/indicadores/tea/recalcular`. |
| `ValueError: Mismatched versions found` | The worker image comes from another ISSSTELEON commit than the deployment's, or from a Python with another patch number (`python 3.12.15` against `3.12.16`). Rebuild the platform with `docker compose build --pull`, then K1 and K3 the same day. |
| `all predefined address pools have been fully subnetted` | Docker has no free network left because of the other projects on the machine. Remove one you don't need, or give this project a subnet in an extra Compose file, `networks: {default: {ipam: {config: [{subnet: 10.240.77.0/24}]}}}`, any range that `docker network ls` and `ip route` don't use, and add it with `-f docker-compose.yml -f <file>`. |
| `table _alembic_tmp_latest_metrics already exists` | The first start was interrupted while MLflow migrated its database. `down -v` and start again, and wait for `health` before the first request. |
| The cycle or training hangs at the start | The container can't reach the scheduler, or the cluster is down. Check K. |
| `no folder /referencia/<name>` from a worker | The training data isn't on the volume. K2. |
| `KeyError: 'posterior_rhythm_hz'` | No study had an age: `edades.csv` missing from `<referencia>` or not passed with `--reference-ages`. |
| `not promoted, missing: MLD-…` | A report is missing on that version. B4. |
| The machine freezes during B2 | Out of memory. A down, other programs closed, `build` and `up -d` separately. |
| `load` refuses a batch | B wasn't empty. B1 and B2 again. |
## Generate the test documents
```sh
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
eeg-gradient: imported as version 1
eeg-posterior-rhythm: imported as version 1
eeg-spikes: imported as version 1
eeg-spindle-topography-n2: imported as version 1
eeg-spindle-topography-n3: imported as version 1
eeg-spindles-n2: imported as version 1
eeg-spindles-n3: imported as version 1
+4
View File
@@ -56,6 +56,10 @@ services:
--api http://webapp \
--hospital "mysql+pymysql://hospital:hospital@hospital:3306/$$database"
done
echo
echo "Loaded. TEA's EEGs are not analysed until their baselines are in production:"
echo "open the app, Gobernanza > TEA · EEG, train or import baselines.zip, attach the reports,"
echo "promote, then Analizar. README.md, \"TEA from the app\"."
# One-shot: writes the test PDFs of the same patients the hospital holds
# (same seed and reference date) into ./documentos. It needs neither the
+8
View File
@@ -8,8 +8,16 @@ services:
# Without their profile the populate jobs run on every `up`. They leave a
# hospital that already has rows alone.
#
# TEA reads EDF_CARPETA, read-only, as /edf (`poblar tea --edf`). Paths here
# resolve from ../dev-data, so the default is the empty sin-edf folder next to
# this file: no real files, only the synthetic EDFs.
poblar:
profiles: !reset []
environment:
DEV_DATA_EDF: /edf
volumes:
- "${EDF_CARPETA:-../manual-deploy/sin-edf}:/edf:ro"
poblar-cacu:
profiles: !reset []
poblar-cama:
+8
View File
@@ -13,12 +13,20 @@ x-api: &api
services:
webapi:
<<: *api
volumes:
- "${REFERENCIA_CARPETA:-./referencia}:/referencia"
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
indicadores:
<<: *api
# Runs the webapi image this project builds; without this it asks for
# isssteleon/webapi:dev, which nothing here builds.
notebooks:
image: ${COMPOSE_PROJECT_NAME}/webapi:local
pull_policy: never
webapp:
image: ${COMPOSE_PROJECT_NAME}/webapp:local
ports: !override
View File
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

@@ -0,0 +1,94 @@
# CaMa demo: patients and how to reach them
Stack: **http://10.0.10.41:18122** (`cama-dev`, built from `dev` at ISSSTELEON `3743ea6`). Log in, choose **Cáncer de mama**, open the **Análisis de riesgos** tab.
## The patient for Luis's figure: 44574
Luis's reference: `luis-HER2-ge60-III-IV-referencia.png` (subgroup "HER2+ · ≥60 años · estadio III–IV (Alto)", from his stage 05).
- **44574** belongs only to that scenario. Her card opens on it with no menu and draws the same graph in Plotly: title with n and deaths, Kaplan-Meier with its Greenwood band, Weibull, fractional Weibull, and the LR + HBN combined diamonds with bootstrap intervals at 6, 12 and 18 months, over 0 to 24 months.
- **How to reach her:** Análisis de riesgos → Fecha de corte 23/11/2026, Ventana 3 meses, BI-RADS 4B, Grupo de edad 60 a 69 años, Resultado de la biopsia Carcinoma invasor → Consultar → **page 1, row 8**.
- **The numbers are the platform's data, not his file:** SEER as imported, with diagnoses placed in the recruitment window and follow-up cut at 2026-11-21. That gives n = 970, deaths = 227 and diamonds 0.899 / 0.835 / 0.786, against his n = 1,142, deaths = 308 and 0.865 / 0.803 / 0.740. Screenshot: `08-44574-supervivencia.jpg`; the list row: `07-lista-44574.jpg`.
- **Backups for the same scenario:** 121232 (only that scenario; page 1, row 39 with BI-RADS 5 and 60 a 69) and 37346 (post-treatment, that scenario first plus the recurrence panel; see below).
## How to find a patient
1. In **Análisis de riesgos**, set **Fecha de corte = 23/11/2026**. Don't leave the default: the default is today, and on another day the 3-month window moves and the rows shift.
2. **Ventana de meses = 3 meses**, **Registros por página = 50**.
3. Set the filters in the patient's row below, leave the others on **Todos**, and press **Consultar**.
4. The list is sorted by latest mammogram, then by ID. Go to the page, count down to the row, and click the patient's ID to open her card.
5. Scroll down the card:
- **Riesgo de muerte → Análisis de supervivencia** has the survival figure.
- For a post-treatment patient, **Pronóstico y recomendaciones → Análisis de recurrencia** comes first, above it, with its **Factores de riesgo** by horizon.
- **Regresar** goes back to the list with the filters kept.
The figures are Plotly, drawn from Luis's models over the data ingested in the platform:
- **Survival** (SEER pipeline, stage 05):
- Kaplan-Meier with the Greenwood 95 % band;
- Weibull and fractional Weibull fitted on the scenario's deaths;
- the LR + HBN combined points with their bootstrap 95 % intervals at 6, 12 and 18 months.
- **Recurrence** (METABRIC / SCAN-B):
- Kaplan-Meier with its Greenwood band, plus both Weibulls;
- the combined points with bootstrap intervals at 12, 36 and 60 months.
A patient in several scenarios gets a menu; the first one is her default.
## Survival: patients in observation (diagnosed, no treatment yet)
All have **Escenario clínico: En observación**, **Resultado de la biopsia = Carcinoma invasor**, status "Diagnóstico confirmado, sin tratamiento registrado" and priority **Alta**.
| Patient | BI-RADS | Grupo de edad | Page | Row | Rows in list | Survival scenarios | Recurrence |
|---|---|---|---|---|---|---|---|
| **44574** | BI-RADS 4B | 60 a 69 años | 1 | 8 | 108 | only **HER2+ · ≥60 años · estadio III–IV (Alto)**, Luis's reference figure | none (not post-treatment) |
| 121232 | BI-RADS 5 | 60 a 69 años | 1 | 39 | 377 | only HER2+ · ≥60 años · estadio III–IV (Alto) | none |
| 6622 | BI-RADS 5 | 70 años o más | 1 | 41 | 429 | menu: HER2+ · ≥60 · III–IV (Alto), Estadio IV | none |
| 16104 | BI-RADS 5 | 40 a 49 años | 1 | 24 | 175 | menu: < 45 años, Jóvenes (<45) · HER2− | none |
| 29617 | BI-RADS 5 | 50 a 59 años | 2 | 15 | 243 | menu: Estadio I, Triple negativo (HR−/HER2−) · estadio 0–II | none |
| 128524 | BI-RADS 5 | 60 a 69 años | 2 | 21 | 377 | only Estadio I | none |
| 102589 | BI-RADS 4C | 70 años o más | 1 | 15 | 120 | only ≥ 75 años | none |
| 67164 | BI-RADS 4A | 50 a 59 años | 1 | 1 | 96 | **Toda la cohorte** (no stage recorded, so no scenario) | none |
44574's figure on this stack: n = 970, deaths = 227; combined points 0.899 / 0.835 / 0.786 at 6 / 12 / 18 months; Kaplan-Meier 0.904 / 0.830 / 0.770.
## Recurrence: post-treatment patients (survival and recurrence)
Set **Escenario clínico = Post-tratamiento** plus the filters below; leave **Resultado de la biopsia = Todos**. All are "Diagnóstico confirmado, en tratamiento", priority **Baja**. Their card shows both panels: **Análisis de recurrencia** (under Pronóstico y recomendaciones, with its cohort and scenario menu and its **Factores de riesgo** by horizon) and, below it, **Análisis de supervivencia**.
| Patient | BI-RADS | Grupo de edad | Page | Row | Rows in list | Recurrence scenarios (cohort) | Survival scenarios |
|---|---|---|---|---|---|---|---|
| **37346** | BI-RADS 4A | 60 a 69 años | 1 | 4 | 26 | Grado 3 (SCAN-B) | menu: **HER2+ · ≥60 · III–IV (Alto)**, Estadio IV |
| 82947 | BI-RADS 6 | 50 a 59 años | 1 | 1 | 103 | Grado 3 (SCAN-B) | menu: HER2+ · <60 · 0–II (Bajo), Estadio I, HER2+ · 0–II · cirugía conservadora |
| 9582 | BI-RADS 4A | Menores de 40 años | 1 | 1 | 9 | menu: < 45 años (METABRIC), < 45 años (SCAN-B) | menu of 6, starting with Estadio I and < 45 años |
| 52291 | BI-RADS 5 | 70 años o más | 1 | 3 | 139 | menu: ≥ 75 años (METABRIC), Grado 3 (SCAN-B), ≥ 75 años (SCAN-B) | only ≥ 75 años |
| 69458 | BI-RADS 5 | 50 a 59 años | 1 | 1 | 69 | menu: Tumor >50 mm (METABRIC), Grado 3 (SCAN-B), Tumor >50 mm (SCAN-B) | Toda la cohorte |
| 19445 | BI-RADS 5 | Menores de 40 años | 1 | 1 | 16 | menu of 5: < 45 años and Tumor >50 mm (METABRIC); Grado 3, < 45 años and Tumor >50 mm (SCAN-B) | only < 45 años |
## Before the demo
- **Open the stack once, about 15 minutes before:**
- **Análisis de riesgos** with any filter: after a restart of the API the first list takes 3 to 5 minutes, because it builds the follow-up cohort; later ones take seconds.
- One patient card: the first card loads the model's members.
- **Indicadores** loads in under a second; its answers are computed by the indicators cycle.
- **Trazabilidad** shows every month (or semester) since 2000. Its answers were computed ahead on the server for this data, so it draws in about 10 to 20 seconds. The data only fills the last few years, so pick **Semestral** or a recent range in **Periodos a mostrar** before showing it. Screenshot: `09-trazabilidad.jpg`.
- **Don't import data or restart the `indicadores` service before the demo.** A new load starts a recalculation of about 40 minutes, and the history has to be computed again.
## If something looks off
- **Screens slow, or briefly failing:** an import or a restart of the `indicadores` service starts a recalculation of about 40 minutes. The stack is set so a restart alone doesn't start one (`INDICADORES_AL_INICIAR=0`).
- **The rows moved:** check that Fecha de corte is 23/11/2026.
- **"El modelo todavía no tiene la supervivencia de este escenario":** the cycle hasn't finished the scenario points yet. It only shows for "Toda la cohorte" right after a new build.
## Screenshots
All taken on this stack on 2026-11-23.
1. `01-filtros-37346.jpg`: the filters set for 37346 (Fecha de corte 23/11/2026, 3 meses, BI-RADS 4A, 60 a 69 años, Post-tratamiento).
2. `02-lista-37346-fila4.jpg`: the list, with 37346 on row 4.
3. `03-ficha-37346.jpg`: her card's header: status, priority, days from mammogram to diagnosis, mammogram and histopathology.
4. `04-37346-recurrencia.jpg`: recurrence, Grado 3 (SCAN-B): Kaplan-Meier with its Greenwood band, both Weibulls and the combined points at 12, 36 and 60 months.
5. `05-37346-factores-y-supervivencia.jpg`: the scenario's risk factors at 60 months, and the start of the survival panel with her two-scenario menu.
6. `06-37346-supervivencia.jpg`: her survival figure (HER2+ · ≥60 años · estadio III–IV).
7. `07-lista-44574.jpg`: 44574 in the list (BI-RADS 4B, 60 a 69 años, Carcinoma invasor).
8. `08-44574-supervivencia.jpg`: 44574's figure, the one to put next to Luis's `luis-HER2-ge60-III-IV-referencia.png`.
9. `09-trazabilidad.jpg`: Trazabilidad loaded, monthly, all 323 months.
Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

+239
View File
@@ -0,0 +1,239 @@
# CaMa survival and recurrence: from the consolidation branch to `dev`, and a clean redeploy
Written 2026-11-22 at the end of the session that built the consolidation. The next session starts here.
## 1. What the owner wants (non-negotiable)
- **Both CaMa models are exactly Luis's.**
- Survival is his SEER pipeline: stages 01–06, LR+HBN including stage and treatments, his stage-05 subgroup curves and points (`models/cama/seer_survival`).
- Recurrence is his METABRIC/SCAN-B scripts: prep, modeling, factors and calculator (`models/cama/recurrence`).
- No substitute estimator, no pasted images, no numbers made up in the code.
- **Everything runs from data ingested into the platform DB.**
- SEER, METABRIC and SCAN-B go in through the import (UI or `/imports/commit`).
- Synthetic fill (dates, pathways, treatments, recent patients) is allowed for the demo.
- Models never train from bundled CSV/TSV/JSON.
- **The dashboard draws Plotly figures from his models' outputs over the ingested data.**
- The clinical scenario comes from the patient's own data.
- There is a menu only when she fits several scenarios.
- **Scope is CaMa.** TEA and CaCu belong to other people. Only the PDF's shared tab rename ("Análisis de riesgos → Seguimiento") touches every domain.
- **Commits:** one-line subjects, with no Co-Authored-By trailer.
- **Schema:** database agnostic, never edit a migration, no new tables or columns without the owner's OK.
## 2. Where things are
**Branches:** `consolidation/cama-survival-recurrence` is pushed in ISSSTELEON, models, WebApi and WebApp; push was over HTTP with the org token, since SSH keys are refused. Heads at the end of the session:
| Repo | Head | Commits beyond `origin/dev` | `dev` commits it lacks |
|---|---|---|---|
| ISSSTELEON | `60f550c` | 13 | 10 |
| models | `706f751` | 10 | 11 |
| WebApi | `3248324` | 9 | 13 |
| WebApp | `7ab2567` | 7 | 26 |
`dev` moved on during the session, so the first task is merging it back in.
What the branch does, by area:
- **Recurrence:**
- Trains on the total cohort (`cama/cohorte_total`) indexed at the first invasive biopsy: patients whose `pac_fuente` is METABRIC or SCANB, recoded by the dictionary in `recurrence/cohorts.toml`.
- Its bundled TSVs, `source.py` and `steps.py` are removed.
- `cohort_import.py` writes the import files from Luis's TSVs, with `--diagnosis-from`, `--spread-days` and `--censor` to place the diagnoses in the platform's recruitment window and stop follow-up at a given day.
- The patient import schema regained 12 fields the merge had dropped (`pac_fuente`, `pac_pam50`, ...); they exist in Core and in a migration.
- **Survival:**
- `models/cama/survival` (the registered scenario) runs Luis's six stages over the DB members inside training (`development.py`) and publishes his tables and figures.
- The live figure (`live.curves`) draws:
- the Kaplan-Meier, plus Weibull and fractional Weibull fitted on the scenario's own deaths, as in his stage 05;
- his model's points and bootstrap intervals for the scenario.
- The points come from `refresh_subgroups`, run by the indicators cycle over each new build (stages 01 and 05, about 16 minutes on 130k patients). Until that has run, the figure uses the points the version published when it trained.
- Ulises's second survival scenario (`seer_survival` as a model and `/cama/supervivencia`) is retired; the `seer_survival` package stays as Luis's pipeline.
- **Patient card:**
- The survival and recurrence panels show the patient's own scenarios.
- The follow-up row carries a provisional status, priority and mammogram-to-diagnosis days (`webapi/cama_follow_up/listing.py`). Those are demo rules, pending Luis.
- The "Seguimiento" tab rename applies to all domains, as the labels PDF asks.
- **Speed:**
- The live models' labelled members are saved once per build and version (`INDICADORES_DIR/modelos/*.parquet`) and each API worker loads them at start (`WEBAPI_PRECALENTAR_MODELOS=1` in the Dockerfile).
- The CaMa follow-up cohort is cached by revision.
- **dbt:**
- `cama_window.cutoff` moves to 2026-12-31.
- A treatment encounter after the malignant diagnosis counts as post-treatment evidence.
- **Migrations:** a no-op revision `e3b8a6d29f71` joins the two CaMa heads.
**Server** (10.0.10.41, user `admon`; the `cama-trabajo` stack on port 18121):
- **Data** in `~/cama-trabajo/datos`, with backups beside it: `cama-antes-del-corrimiento.db`, `cama-antes-de-rutas.db`, `cama-antes-de-externas.db`, `cama-antes-de-noviembre.db`.
- **Images** are built from `~/cama-consolidado/src`, a copy updated by tarballs, not a git checkout.
- **Models in production:**
- `cama-survival` v3, trained on DB build 3.
- `cama-recurrence` v2, trained on DB build 4.
- Both were **force-promoted** with the alias set directly, because the MLD-01, MLD-01b and MLD-03 reports don't exist.
- **The last two commits are not deployed:** `refresh_subgroups` (WebApi `3248324`, models `706f751`).
- **An indicators cycle was in progress** when the session ended. It was loading 2,000 synthetic patients with mammograms from 2026-11-02 to 11-21, imported through `/imports/commit`.
- **Leftover containers:** `cama-trabajo-survival` and `cama-trabajo-recurrence` (one-off training runs, now exited).
**Data on the server, how it got there** (scripts in `scripts/` here):
- **Imported through `/imports/commit`:**
- METABRIC 2,380 and SCAN-B 8,847 patients (`cargar_externas.py`, from `cohort_import.py` with `--diagnosis-from 2018-01-01 --spread-days 540 --censor 2026-11-21`).
- 2,000 recent screenings (`cargar_nov.py`).
- **The SEER patients (129,562) came with the earlier deploy and were reshaped directly in SQLite:**
- dates shifted to end by 2026-11-21 (`shift.py`);
- pathways built: biopsy order linked to its mammogram, diagnosis note, treatments (`pathway.py`);
- treatments added for 2026 patients (`treatments.py`).
- These scripts write silver and bronze tables directly, which breaks "everything through the import". Redo them as import files for the clean deploy (task 4).
## 3. Tasks for the next session
### Task 1. Merge `dev` into the consolidation branches
1. In each repo, fetch `dev` over HTTP (`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`) and merge `origin/dev` into `consolidation/cama-survival-recurrence`.
2. Order: models, WebApi and WebApp first, then ISSSTELEON with its pins.
3. Resolve conflicts keeping the CaMa work of this branch and `dev`'s everything else. Don't touch TEA or CaCu changes beyond what `dev` has.
4. Check the CaMa migration chain still has one head per domain. If `dev` added CaMa revisions, add a new merge revision; never edit one.
5. Test baselines to compare against. Failures that already existed are not new work, but compare the lists:
- **models** (`uv run pytest -q`): 12 failed, 1 error before this work; the errors seen in TEA and cohort-build tests came from runs overlapping.
- **WebApi** (`uv run pytest -q`): 29 failed, all already failing.
- **WebApi CaMa follow-up tests:** need a compiled manifest: `cd Transformation && uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect --target-path /tmp/dbtc`, then run with `DBT_MANIFEST=/tmp/dbtc/manifest.json`. 37 pass.
- **WebApp** (`npx ng test --watch=false`): 1,881 pass.
6. Push the consolidation branches; that needs the owner's OK each time. Then merge into `dev` only when the owner says so.
**Done when:** the consolidation branches contain `dev` and the test failure lists are no longer than the baselines.
### Task 2. Finish and verify the cycle-computed scenario points
- `development.subgroup_points` (stages 01 and 05 over the current members) has not run end to end. Its test took over 10 minutes because stage 05 gives each subgroup's fractional fit up to 180 seconds (`ks_sub_max_seconds`).
- Add a way to pass the survival budgets (`ks_max_seconds`, `ks_sub_max_seconds`, `n_boot`, `n_boot_sub`) through `[config.desarrollo]`, so the test can use small ones. Then write the test (template in `docs/testing.md`).
- On the server, after deploy, check:
- `INDICADORES_DIR/modelos/cama-survival-v<v>-armado<b>-subgrupos.json` appears after a cycle;
- `/cama/modelo/curvas/consulta` for "HER2+ · ≥60 años · estadio III–IV (Alto)" returns its points.
- Reference values on build 8: n 970, deaths 227, COMB 0.900 / 0.834 / 0.784.
**Done when:** a cycle writes the subgroups file and the figure draws its points.
### Task 3. Replace dev's survival estimator with Luis's stage-04 models (decided 2026-11-22: option a)
The registered `cama/survival` still holds dev's `IntervalSurvival`, an LR+HBN on age, histologic type, grade, ER, PR, HER2, Ki-67 and size, without stage. It is used for:
- placing a patient in her scenarios;
- the points of "Toda la cohorte", when she is in none: about 16% of patients, mostly recent diagnoses with no stage recorded yet.
Per §1 the model should be Luis's. Options:
- **(a)** Register his stage-04 models as the saved model and score from them.
- **(b)** Keep `IntervalSurvival` only for membership and use his stage-05 cohort points (`curva_supervivencia_puntos_LR_HBN.csv`, currently not published as a table) for "Toda la cohorte".
**Done when:** the owner has chosen and the choice is implemented.
**Status (2026-11-23):**
- Done: the figure no longer uses `IntervalSurvival`. Every point it draws, "Toda la cohorte" included, is Luis's stage 05: `subgrupos_puntos` and the cohort table, now published as `cohorte_puntos` and recomputed by the cycle's `refresh_subgroups` (models `674bdc4`, WebApi `1048175`, WebApp `069cc45`).
- Placement never used a model: it reads the patient's age, subtype, stage and surgery (`live.scenario_masks`).
- Deferred by the owner: registering the stage-04 LR and HBN as the saved model. They are binary mortality classifiers on the balanced cohort and give no 6/12/18-month points, so they change nothing on screen; doing it means a retrain of about 1 h 40 min.
### Task 4. Synthetic fill through the import only (later; does not block the redeploy: start from the copied server data, task 5)
1. Rewrite what `shift.py`, `pathway.py` and `treatments.py` did as import files posted to `/imports/commit`:
- mammograms (`cama.Mastografia`);
- biopsies (`cama.BiopsiaMama`);
- notes with the diagnosis, specialty and stage (`cama.NotaMedica`);
- treatments (`cama.TratamientoMama`);
- follow-up (`cama.SeguimientoMama`).
2. **Known gap:** the import doesn't link a biopsy order to the mammogram that led to it (silver `procedimiento.padre_id`); `pathway.py` set it by hand. Fix it as a platform feature: the import can take the mammogram's id or order number. No new columns without the owner.
3. Stage should be filled for diagnosed patients, so they land in a scenario.
**Done when:** a fresh database filled only through the import gives the same screens.
### Task 5. Clean redeploy from `dev` on the server
1. After task 1 is merged into `dev`, build `isssteleon/webapi` and `isssteleon/webapp` from a git checkout of `dev`, not the tarball copy, under a new tag.
2. Copy `~/cama-trabajo/datos` (all domain DBs, `governance.db`, `mlflow.db`, `mlflow-artefactos/`, `cohorts/`, `indicadores/`) into the new stack's data dir and run `alembic upgrade head` (decided 2026-11-22), so the patients and the example IDs stay the same. Rebuilding from scratch (steps 3–4) only once task 4 exists.
3. Load, in order, through the import:
- SEER (`models/cama/seer_survival/seer_import.py`);
- METABRIC and SCAN-B (`cohort_import.py` with the placement flags above, censor = yesterday);
- the synthetic pathway files from task 4.
4. Let the indicators cycle run.
5. Train from the database, one-off containers with `--entrypoint uv` and the stack's env file (the image's entrypoint starts gunicorn otherwise):
- survival: `models run cama survival --export --source dbt --manifest /app/Transformation/target/manifest.json --environment prod --train` (about 1 h 40 min; stage 04 is 70 min);
- recurrence: `models run cama recurrence --export --source dbt --manifest ... --environment prod --train` (about 1 h 20 min).
6. Promote: write the MLD reports so the gate passes, or force the alias only with the owner's OK, saying so.
7. Run a cycle or `webapi.model_analysis.warm('cama')` to leave the members file, then restart the API.
8. Check the screens:
- Seguimiento list up to yesterday;
- patient header (status, priority, days);
- Histopatología card;
- the BI-RADS × histopathology and diagnosis-time indicators;
- survival and recurrence panels for patients in one scenario and in several. Examples on the current data: 44574, 6622, 16104 and 128524.
**Done when:** the screens above work on the new stack.
### Task 6. Open items for the owner and Luis
- Provisional CaMa status and priority rules (`listing.py`, `ESTATUS` and `_prioridad`).
- Figure labels, title and axes: Luis said he would define them.
- "Recomendaciones" is still "no disponibles".
- MLD-01, MLD-01b and MLD-03 reports for both models.
- Whether the CaMa follow-up list needs a search by patient id. It has none: patients are found by filters.
## 4. How to get the CaMa models the way the owner established
**Survival** (`models/cama/survival`, Luis's pipeline in `models/cama/seer_survival`):
1. **Load SEER through the import.**
- `python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR` writes one CSV per bronze entity.
- Post them to `/imports/commit` (`scripts/cargar_externas.py` shows the payload) or load them through "Conectar datos".
- SEER has no calendar dates. Place the diagnoses in the recruitment window, and keep every date on or before yesterday.
2. **Fill what SEER lacks for the demo** through the import as well: mammograms with BI-RADS 4–6, the biopsy order and report, a diagnosis note with stage, and treatments within a year. Stage is what puts a patient in Luis's scenarios.
3. **Let the indicators cycle run.** It builds silver, the views and the `cama/cohorte_total` build.
4. **Train from the database:** `models run cama survival --export --source dbt --manifest $DBT_MANIFEST --environment prod --train`.
- This runs Luis's six stages over the members, with stage and treatments.
- It publishes his tables and figures in `analisis/desarrollo.json`.
- About 1 h 40 min.
5. **Promote:** with the MLD reports, or by setting the alias with the owner's OK.
6. **The dashboard's survival panel** (`/cama/modelo/escenarios` and `/cama/modelo/curvas/consulta`):
- It shows the patient's own scenarios.
- The Plotly figure has the Kaplan-Meier of the scenario's members, and the Weibull and fractional Weibull fitted on their deaths (his stage 05).
- The diamonds and intervals are his model's points for the scenario: from the cycle's `refresh_subgroups` over the current build, or the version's `subgrupos_puntos` until it has run.
- **Check:** the figure must match his stage-05 PNG for the same scenario. On build 8: n 970, deaths 227, diamonds 0.900 / 0.834 / 0.784, Kaplan-Meier 0.904 / 0.830 / 0.770 at 6/12/18 months.
**Recurrence** (`models/cama/recurrence`, Luis's METABRIC/SCAN-B scripts):
1. **Load METABRIC and SCAN-B through the import:**
- `python -m models.cama.recurrence.cohort_import metabric brca_metabric_clinical_data.tsv OUT --diagnosis-from 2018-01-01 --spread-days 540 --censor <yesterday>`, and the same with `scanb scanb_clinical_metadata.txt`.
- Post the ten CSVs with `scripts/cargar_externas.py BASE OUT`. The files are in Luis's folder; they are not in the repo.
- Each patient carries `pac_fuente` (METABRIC or SCANB), which is how each cohort finds its patients.
2. **Let the cycle run, then train:** `models run cama recurrence --export --source dbt --manifest $DBT_MANIFEST --environment prod --train`, about 1 h 20 min.
3. **Promote** as above.
4. **The recurrence panel** (`/cama/modelo/recurrencia?paciente=`):
- It shows the patient's own scenarios (both cohorts, labelled), and a menu only when she is in several.
- The Plotly figure is his calculator's record: Kaplan-Meier and Greenwood band, both Weibulls, and the combined points with bootstrap intervals at 12/36/60 months.
- It shows only for post-treatment patients.
**Running one-off training containers:** use `--entrypoint uv` with the stack's env file and `-w /app/WebApi`; otherwise the image's entrypoint starts gunicorn.
## 5. Example patients on the current server data (cut-off 2026-11-23)
In the Seguimiento tab, leave "Fecha de corte" as it is and set the filters below. Rows are sorted by latest mammogram, then by ID, 50 per page.
| Patient | Ventana | BI-RADS | Grupo de edad | Biopsia | Where | Survival panel shows |
|---|---|---|---|---|---|---|
| 44574 | 3 meses | 4B | 60 a 69 | Carcinoma invasor | page 1, row 8 | only "HER2+ · ≥60 años · estadio III–IV (Alto)", Luis's figure |
| 121232 | 3 meses | 5 | 60 a 69 | Carcinoma invasor | page 1, row 39 | only that same scenario |
| 6622 | 3 meses | 5 | 70 o más | Carcinoma invasor | page 1, row 41 | menu: that scenario and "Estadio IV" |
| 16104 | 3 meses | 5 | 40 a 49 | Carcinoma invasor | page 1, row 24 | menu: "< 45 años", "Jóvenes (<45) · HER2−" |
| 29617 | 3 meses | 5 | 50 a 59 | Carcinoma invasor | page 2, row 15 | menu: "Estadio I", "Triple negativo · estadio 0–II" |
| 128524 | 3 meses | 5 | 60 a 69 | Carcinoma invasor | page 2, row 21 | only "Estadio I" |
| 102589 | 3 meses | 4C | 70 o más | Carcinoma invasor | page 1, row 15 | only "≥ 75 años" |
| 67164 | 3 meses | 4A | 50 a 59 | Carcinoma invasor | — | "Toda la cohorte": no stage recorded, so no scenario |
- All of them are "En observación", with status "Diagnóstico confirmado, sin tratamiento registrado", priority "Alta" and about 30 days from mammogram to diagnosis.
- None is post-treatment, so their recurrence panel doesn't show. Use the "Escenario clínico: Post-tratamiento" filter to find patients with one.
- After a clean redeploy the IDs change. Find equivalents with the same filters, or query the members file: `pd.read_parquet(INDICADORES_DIR/modelos/cama-survival-*.parquet)` with `models.cama.survival.live.scenario_masks`.
## 6. Things that cost time this session
- **SSH:** to Gitea it's refused; use HTTP with the org token for pushes.
- **Server access:**
- SSH to the server is intermittently refused or times out; retry.
- The server can drop off the VPN; check the route (`route -n get 10.0.10.41`).
- **SQLite views:** the indicators worker drops and recreates the views while it runs, so requests can fail transiently.
- **The cohort build is slow:** reading it from the views takes about 6 minutes on 140k patients (`KitBuild.frame`). Never do it per request.
- **IDs:** check synthetic `pac_id_hospital` values against existing ones; 8-digit ids collided.
@@ -0,0 +1,32 @@
"""Loads the METABRIC and SCAN-B import files through the same endpoints "Conectar datos" calls.
Usage: python3 cargar_externas.py BASE_URL FOLDER"""
import base64, csv, json, sys, urllib.error, urllib.request
from pathlib import Path
BASE, FOLDER = sys.argv[1], Path(sys.argv[2])
ORDER = [("pacientes", "cama.Paciente"), ("biopsias", "cama.BiopsiaMama"), ("notas", "cama.NotaMedica"),
("tratamientos", "cama.TratamientoMama"), ("seguimientos", "cama.SeguimientoMama")]
def call(path, body):
req = urllib.request.Request(BASE + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=3600) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")
for cohort in ("metabric", "scanb"):
sources = []
for name, target in ORDER:
path = FOLDER / f"{cohort}_{name}.csv"
header = next(csv.reader(path.open(encoding="utf-8")))
sources.append({"label": path.name, "source_type": "csv", "target": target,
"column_mapping": {c: c for c in header},
"payload": {"file_base64": base64.b64encode(path.read_bytes()).decode()}})
status, result = call("/imports/commit", {"sources": sources, "on_conflict": "reject"})
print(f"{cohort}: HTTP {status}", result.get("error", ""))
for r in result.get("results", []):
print(f" {r['target']:24} total={r['total']} creadas={r['created']} rechazadas={r['rejected']} vinculos={r.get('linked')}")
print(f" audit_id={result.get('audit_id')} recalculo={result.get('indicadores_en_recalculo')}")
@@ -0,0 +1,17 @@
"""Loads new patients and their mammograms through the import, as "Conectar datos" does. Usage: python3 cargar_nov.py BASE FOLDER"""
import base64, csv, json, sys, urllib.error, urllib.request
from pathlib import Path
BASE, FOLDER = sys.argv[1], Path(sys.argv[2])
sources = []
for name, target in (("pacientes", "cama.Paciente"), ("mastografias", "cama.Mastografia")):
path = FOLDER / f"{name}.csv"; header = next(csv.reader(path.open(encoding="utf-8")))
sources.append({"label": path.name, "source_type": "csv", "target": target, "column_mapping": {c: c for c in header},
"payload": {"file_base64": base64.b64encode(path.read_bytes()).decode()}})
req = urllib.request.Request(BASE + "/imports/commit", data=json.dumps({"sources": sources, "on_conflict": "reject"}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=3600) as r: status, result = r.status, json.load(r)
except urllib.error.HTTPError as e: status, result = e.code, json.loads(e.read() or b"{}")
print("HTTP", status, result.get("error", ""))
for r in result.get("results", []): print(f" {r['target']:20} total={r['total']} creadas={r['created']} rechazadas={r['rejected']}")
print("recalculo", result.get("indicadores_en_recalculo"))
@@ -0,0 +1,71 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
c = sqlite3.connect(DB, timeout=300)
print("sqlite", sqlite3.sqlite_version, flush=True)
t = time.time()
def run(label, sql):
n = c.execute(sql).rowcount
print(label, n, round(time.time() - t), flush=True); return n
H = "((a.pac_id * 2654435761) % 1000003)"
c.executescript(f"""
drop table if exists temp.ruta;
create temp table ruta as
select r.pac_id,
r.procedimiento_id as bx_reporte, r.padre_id as bx_orden, r.fecha as d,
date(r.fecha, '-' || (20 + {H.replace('a.', 'r.')} % 20) || ' days') as toma
from procedimiento r where r.estudio_id = 'biopsia' and r.clase = 'reporte';
create index temp.ruta_pac on ruta(pac_id);
alter table temp.ruta add column reporte_mast text;
alter table temp.ruta add column orden text;
alter table temp.ruta add column bx_toma text;
update temp.ruta set reporte_mast = date(toma, '+' || (1 + ((pac_id * 2654435761) % 1000003) % 7) || ' days'),
bx_toma = date(d, '-' || (2 + ((pac_id * 2654435761) % 1000003) % 4) || ' days');
update temp.ruta set orden = date(bx_toma, '-' || (1 + ((pac_id * 2654435761) % 1000003) % 3) || ' days');
""")
print("rutas", c.execute("select count(*), sum(orden <= reporte_mast) from temp.ruta").fetchone())
# mammogram toma, its report and its parts
run("mast toma", "update procedimiento set fecha = (select toma from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='mastografia' and clase='toma'")
run("mast reporte/parte", "update procedimiento set fecha = (select reporte_mast from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='mastografia' and clase in ('reporte','parte')")
# biopsy order (linked to the mammogram that led to it) and sample
run("bx orden", """update procedimiento set fecha = (select orden from temp.ruta r where r.pac_id = procedimiento.pac_id),
padre_id = (select t.procedimiento_id from procedimiento t where t.pac_id = procedimiento.pac_id and t.estudio_id='mastografia' and t.clase='toma')
where estudio_id='biopsia' and clase='orden'""")
run("bx toma", "update procedimiento set fecha = (select bx_toma from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id='biopsia' and clase='toma'")
# bronze, so a reload says the same
run("bronze mast", "update mastografia set mast_fecha_toma = (select toma from temp.ruta r where r.pac_id = mastografia.pac_id), mast_fecha_reporte = (select reporte_mast from temp.ruta r where r.pac_id = mastografia.pac_id)")
run("bronze bx", "update biopsiamama set bx_fecha_solicitud = (select orden from temp.ruta r where r.pac_id = biopsiamama.pac_id), mast_id = (select m.mast_id from mastografia m where m.pac_id = biopsiamama.pac_id)")
# the first note becomes the diagnosis: oncologic surgery, a C50 code from the tumour's site
c.executescript("""
drop table if exists temp.nota1;
create temp table nota1 as select pac_id, min(procedimiento_id) as procedimiento_id from procedimiento where estudio_id='nota_medica' and clase='encuentro' group by pac_id;
create index temp.nota1_p on nota1(procedimiento_id);
""")
run("nota fecha", "update procedimiento set fecha = (select date(d, '+' || (3 + ((pac_id * 2654435761) % 1000003) % 10) || ' days') from temp.ruta r where r.pac_id = procedimiento.pac_id) where procedimiento_id in (select procedimiento_id from temp.nota1)")
c.executescript("""
drop table if exists temp.sitio;
create temp table sitio as
select p.pac_id, min(replace(o.valor_id, '.', '')) as cie
from observacion_clinica o join procedimiento p on p.procedimiento_id = o.procedimiento_id
where o.resultado_id = 'biopsia.localizacion' and o.valor_id like 'C50%' group by p.pac_id;
create index temp.sitio_p on sitio(pac_id);
""")
run("nota cie", "update observacion_clinica set valor_texto = coalesce((select cie from temp.sitio s where s.pac_id = observacion_clinica.pac_id), 'C509') where resultado_id = 'nota_medica.diagnostico' and procedimiento_id in (select procedimiento_id from temp.nota1)")
run("nota especialidad", "update observacion_clinica set valor_id = 'CIRUGIA_ONCOLOGICA', valor_fuente = 'CIRUGIA_ONCOLOGICA' where resultado_id = 'nota_medica.especialidad' and procedimiento_id in (select procedimiento_id from temp.nota1)")
run("bronze nota", """update notamedica set nm_fecha = (select p.fecha from procedimiento p where p.fuente_tabla='notamedica' and p.fuente_id = cast(notamedica.nm_id as text)),
nm_especialidad = 'CIRUGIA_ONCOLOGICA', nm_cie_codigo = 'C509'
where cast(nm_id as text) in (select p.fuente_id from procedimiento p join temp.nota1 n on n.procedimiento_id = p.procedimiento_id)""")
# treatments after the diagnosis, and none that has not happened yet
for estudio, base, span in (("cirugia", 21, 40), ("quimioterapia", 45, 60), ("radioterapia", 90, 90)):
run(estudio, f"update procedimiento set fecha = (select date(d, '+' || ({base} + ((pac_id * 2654435761) % 1000003) % {span}) || ' days') from temp.ruta r where r.pac_id = procedimiento.pac_id) where estudio_id = '{estudio}'")
run("bronze trat", "update tratamientomama set trat_fecha = (select p.fecha from procedimiento p where p.fuente_tabla='tratamientomama' and p.fuente_id = cast(tratamientomama.trat_id as text))")
future = f"select procedimiento_id from procedimiento where fecha > '{Y}'"
run("future obs", f"delete from observacion_clinica where procedimiento_id in ({future})")
run("future trat", f"delete from tratamientomama where trat_fecha > '{Y}'")
run("future notes", f"delete from notamedica where nm_fecha > '{Y}'")
run("future procs", f"delete from procedimiento where fecha > '{Y}'")
c.commit()
for q in ["select clase, estudio_id, min(fecha), max(fecha), count(*) from procedimiento where estudio_id in ('mastografia','biopsia','cirugia') group by 1,2",
"select count(*) from procedimiento o join procedimiento t on t.procedimiento_id = o.padre_id where o.estudio_id='biopsia' and o.clase='orden' and t.clase='toma'"]:
print(c.execute(q).fetchall())
print("done", round(time.time() - t))
@@ -0,0 +1,19 @@
import pickle
from models.io.registry import registry, PRODUCTION_ALIAS, registered_name, PromotionBlocked
from models.io.tracking import TrainingRun
with open("/data/seer_survival.pkl", "rb") as handle:
model = pickle.load(handle)
print(type(model))
run = TrainingRun(domain="cama", scenario="seer_survival", environment="PROD", cohorte_armado_id=2)
run.log_model(model, requirements=["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle", "mpmath"])
version = registry.register_run(run.finish(hyperparameters={"origen": "seer_survival.pkl"}))
print("registered", version)
try:
registry.promote("cama", "seer_survival", version)
print("promoted through the gate")
except PromotionBlocked as blocked:
print("gate:", [(c.name, c.passed) for c in blocked.checks] if hasattr(blocked, "checks") else blocked)
registry.client.set_registered_model_alias(registered_name("cama", "seer_survival"), PRODUCTION_ALIAS, version)
print("alias set directly")
print(registry.resolve("cama", "seer_survival"))
+36
View File
@@ -0,0 +1,36 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
OFF = "(875 + ((pac_id * 48271) % 365))"
c = sqlite3.connect(DB, timeout=120)
c.execute("pragma journal_mode=wal")
t = time.time()
def shift(table, *cols, where=""):
sets = ", ".join(f"{col} = date({col}, '+' || {OFF} || ' days')" for col in cols)
n = c.execute(f"update {table} set {sets} {where}").rowcount
print(table, cols, n, round(time.time() - t))
shift("biopsiamama", "bx_fecha_solicitud", "bx_fecha_reporte")
shift("mastografia", "mast_fecha_toma", "mast_fecha_reporte")
shift("notamedica", "nm_fecha")
shift("paciente", "pac_fecha_nacimiento", "pac_fecha_defuncion")
shift("persona", "fecha_nacimiento", "fecha_defuncion")
shift("periodo_observacion", "fecha_inicio")
shift("procedimiento", "fecha")
shift("tratamientomama", "trat_fecha")
shift("observacion_clinica", "valor_fecha", where="where valor_fecha is not null")
shift("cohorte_miembro", "fecha_indice")
# Nothing after yesterday: a later death is not known yet, a later visit or treatment has not happened.
print("deaths cleared", c.execute(f"update persona set fecha_defuncion = null where fecha_defuncion > '{Y}'").rowcount,
c.execute(f"update paciente set pac_fecha_defuncion = null where pac_fecha_defuncion > '{Y}'").rowcount)
future = f"select procedimiento_id from procedimiento where fecha > '{Y}'"
print("future obs", c.execute(f"delete from observacion_clinica where procedimiento_id in ({future})").rowcount)
print("future children", c.execute(f"update procedimiento set padre_id = null where padre_id in ({future})").rowcount)
print("future procs", c.execute(f"delete from procedimiento where fecha > '{Y}'").rowcount)
print("future notes", c.execute(f"delete from notamedica where nm_fecha > '{Y}'").rowcount)
print("future treatments", c.execute(f"delete from tratamientomama where trat_fecha > '{Y}'").rowcount)
c.commit()
for q in ["select min(fecha), max(fecha) from procedimiento where estudio_id='mastografia'",
"select min(fecha), max(fecha), count(*) from procedimiento",
"select count(fecha_defuncion), max(fecha_defuncion) from persona"]:
print(q, c.execute(q).fetchone())
print("done", round(time.time() - t))
@@ -0,0 +1,44 @@
import sqlite3, time
DB = "/home/admon/cama-trabajo/datos/cama.db"
Y = "2026-11-21"
c = sqlite3.connect(DB, timeout=300)
t = time.time()
rows = c.execute("""
select r.pac_id, r.fecha, r.carga_id, p.pac_id_hospital,
(select o.valor_id from observacion_clinica o where o.procedimiento_id = r.procedimiento_id and o.resultado_id = 'biopsia.lateralidad')
from procedimiento r join paciente p on p.pac_id = r.pac_id
where r.estudio_id = 'biopsia' and r.clase = 'reporte' and r.fecha >= '2026-01-01'
and not exists (select 1 from procedimiento x where x.pac_id = r.pac_id and x.estudio_id in ('cirugia', 'quimioterapia', 'radioterapia'))
""").fetchall()
print("patients without treatment", len(rows), flush=True)
trat_id = c.execute("select max(trat_id) from tratamientomama").fetchone()[0]
proc_id = c.execute("select max(procedimiento_id) from procedimiento").fetchone()[0]
obs_id = c.execute("select max(observacion_id) from observacion_clinica").fetchone()[0]
trats, procs, obs = [], [], []
def add(pac, hosp, carga, estudio, fecha, detalle, lateralidad, results):
global trat_id, proc_id, obs_id
trat_id += 1; proc_id += 1
trats.append((trat_id, pac, hosp, estudio, fecha, detalle, lateralidad))
procs.append((proc_id, "tratamientomama", str(trat_id), carga, pac, estudio, "encuentro", fecha))
for resultado, valor in results:
obs_id += 1
obs.append((obs_id, proc_id, carga, pac, resultado, valor, valor))
for pac, d, carga, hosp, lat in rows:
h = (pac * 2654435761) % 1000003
lat = lat or ("IZQUIERDA" if h % 2 else "DERECHA")
def when(base, span):
f = c.execute("select date(?, ?)", (d, f"+{base + h % span} days")).fetchone()[0]
return f if f <= Y else None
if h % 100 < 85 and (f := when(21, 40)):
tipo = "SEGMENTECTOMIA" if h % 100 < 55 else "MASTECTOMIA_TOTAL"
add(pac, hosp, carga, "cirugia", f, tipo, lat, [("cirugia.tipo_cirugia", tipo), ("cirugia.lateralidad", lat)])
if (h // 7) % 100 < 60 and (f := when(90, 90)):
add(pac, hosp, carga, "radioterapia", f, "ADYUVANTE", lat, [("radioterapia.intencion", "ADYUVANTE")])
if (h // 13) % 100 < 35 and (f := when(45, 60)):
add(pac, hosp, carga, "quimioterapia", f, "ADYUVANTE", lat, [("quimioterapia.intencion", "ADYUVANTE")])
c.executemany("insert into tratamientomama (trat_id, pac_id, pac_id_hospital, trat_tipo, trat_fecha, trat_detalle, trat_lateralidad) values (?,?,?,?,?,?,?)", trats)
c.executemany("insert into procedimiento (procedimiento_id, fuente_tabla, fuente_id, carga_id, pac_id, estudio_id, clase, fecha) values (?,?,?,?,?,?,?,?)", procs)
c.executemany("insert into observacion_clinica (observacion_id, procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) values (?,?,?,?,?,?,?)", obs)
c.commit()
print("inserted", len(trats), len(procs), len(obs), round(time.time() - t), flush=True)
print(c.execute("select substr(fecha,1,7), estudio_id, count(*) from procedimiento where estudio_id in ('cirugia','radioterapia','quimioterapia') and fecha >= '2026-06' group by 1,2").fetchall())
+3 -1
View File
@@ -92,7 +92,9 @@ Evidence:
1. **Engines.** The owner said production is SQL Server and development SQLite (2026-11-07). Rule 2 still lists four
engines; narrowing it widens the options (SQLMesh supports SQL Server; `WITH … INSERT` for in-database writes).
A new DA, not done here.
A new DA, not done here. **Decided 2026-11-15: not narrowed.** The owner confirmed rule 2 stands as written —
SQLite, PostgreSQL, MySQL/MariaDB and SQL Server all stay fully supported. R0.5 (#136) stays open; the
SQLMesh/in-database-write options this would have unlocked aren't pursued.
2. **Views (job 8):** `dbt run` at deployment, or the DDL as a migration.
3. **Where the Measure TOMLs live** once out of the kit.
4. **Whether to keep this slice** as a task branch (it would be `refactor/<issue>-kit-exit-ind1` per rule 10) with an
+1 -1
View File
@@ -49,7 +49,7 @@ cycle not computing in Python) hold.
| #42 R0 dbt project in the tree | R0.1, R0.2 closed; R0.3 and R0.4 above | R0.5 (#136). Close R0 when the owner decides the engines (plan's decision 1); if production is SQL Server only, R0.5 is closed as not needed |
| #59 R7 Kit retirement | no code imports `indicadores_kit`; it is no dependency of the WebApi or `models` | the submodule (`.gitmodules`, pointer); comments that still name it in Persistance and Core (`alembic/env.py`, the domain modules) and in `parametros.toml`'s `fuente` texts; the submodule's own retirement (archive the repo) |
| #58 R5 and #76 to #78 Seguimiento | `estatus_seguimiento` is computed in dbt from inferred procedures and matches the kit (EU13's strata equal the oracle); the follow-up list moved from the kit to the WebApi (`270e229`) | no `mart_cacu_seguimiento`; `/seguimiento` computes in Python, in DEV only, as before. Decide whether R5.2 and R5.3 are still wanted |
| #101 to #104 R6 moves out of the kit | done, with other destinations: the silver load and the table maps went to the WebApi's cycle (R6.1 said Persistance), serving to the WebApi (R6.2), cohorts to `models` (R6.3), the synthetic staging to `WebApi/tests/staging` (R6.4 said Persistance tests) | close R6.2 and R6.3; R6.1 and R6.4 need the owner's word on the destination (`plans/kit-exit/webapi-structure.md` proposes where the cycle's pieces go) |
| #101 to #104 R6 moves out of the kit | done, with other destinations: the silver load and the table maps went to the WebApi's cycle (R6.1 said Persistance), serving to the WebApi (R6.2), cohorts to `models` (R6.3), the synthetic staging to `WebApi/tests/staging` (R6.4 said Persistance tests) | close R6.2 and R6.3; R6.4 still needs the owner's word. **R6.1 decided 2026-11-15: the owner confirmed the current split** — `webapi/orchestration/reference/` keeps reading and validating the TOMLs and building the rows (`catalogs.py`, `age_groups.py`, `dates.py`, `periods.py`); Persistance keeps writing them (the `catalogos`/`registro` edges already do, for catalogs). No move to Persistance; close R6.1 as resolved by the existing split, not as the move the issue originally proposed |
| #95 to #99 R4b.14 to R4b.18, TEA | TEA's schema, imports and EEG stay | the port, `plans/kit-exit/tea-port.md` |
| #94 R4b.13, #100 R4b.19 (risk-band proposals) | | the kit never computed them; they need their cohorts and estimates |
+77
View File
@@ -0,0 +1,77 @@
# TEA EEG analysis on the Dask cluster: what the first runs showed
The age baselines are trained on site and shipped as a bundle (#184), and the platform sends its EEG batches to
the k3s Dask cluster in `dask-cluster/` when `DASK_SCHEDULER_ADDRESS` is set. Two manual deployments tested the
whole procedure on 2026-11-20: A (`sitio-a`) trained the seven baselines on Helsinki HK1K (223 studies aged 16
to 36 months) and exported them; B (`sitio-b`) imported and promoted them and loaded dev-data with 62 real EDFs,
and its indicator cycle analysed them on the cluster (5 pods, 25 workers). The procedure is the runbook "TEA
Cluster Run"; the cluster's files are `dask-cluster/` on `feature/tea-eeg-analysis`.
It works end to end. This plan collects what the runs showed should change.
---
## 1. The analysis doesn't keep the cluster busy
The cycle analysed the 62 EEGs in 404 s. Each EEG takes 30 to 80 s on a worker, so 25 workers should need about
2.5 to 3 minutes. The completion times show why it took 6.7:
| Batch | EEGs | Done (s after start) |
|---|---|---|
| 1 | 16 | 32 - 114 |
| 2 | 16 | 148 - 209 |
| 3 | 16 | 249 - 301 |
| 4 | 14 | 334 - 403 |
`models.eeg_analysis.analyze_pending` (`models/models/eeg_analysis.py`, the batch loop at the end) reads 16 EDFs
from the database, hands them to `tea.pipeline.dask_runner.run` as one graph and waits for all 16 before
reading the next ones. So:
- **9 of 25 workers are idle the whole run**: a batch never has more than 16 tasks.
- **Each batch waits for its slowest recording**, and workers go idle as the fast ones finish.
- **Each batch spends about 30 s before its first result.** The EDF bytes are arguments of `dask.delayed`
calls, so they are pickled into the graph: 427 to 528 MiB per batch ("Sending large graph" from
`distributed/client.py`), held by the scheduler and sent again to the workers.
**Design.** The runner keeps a bounded number of studies in flight (about one per worker thread) and submits the
next as soon as one finishes (`client.submit` and `as_completed`). Large arguments go out of band with
`client.scatter`, so the graph holds only their keys. `analyze_pending` reads each EDF only when its study is
submitted, so the client never holds more than the studies in flight. Synchronous and local-cluster runs keep
working as they do. Target: the 62 EEGs in under 4 minutes on 25 workers, with no large-graph warning.
## 2. Two runs analyse the same EEGs
`analyze_pending` builds its pending list once, before the first batch. After a `load`, the indicator cycle
listed all 62 EEGs as pending and kept analysing them on the laptop's single local worker while a manual run on
the cluster had already analysed them; the patient views stayed empty until the worker was restarted. With the
scheduler in `.env` the cycle itself uses the cluster, which removes the manual run, but two analyses can still
overlap (a cycle and `POST /governance/eeg/run`, or two cycles). Each study should be re-checked against the
current plan, versions and baselines just before it is submitted and skipped if another run finished it.
## 3. Findings from the 43 / 19 result
Investigated read-only on B. The 19 rejected EEGs fail on properties of the recordings, checked against the
EDFs: `clean-windows` below 60% (17), `triage-level` (10), `internal-coverage` below 0.90 from `BAD_ACQ_SKIP`
gaps (3), `usable-scalp` below 12 with every channel saturated (1); one EEG can fail several. The dev-data header
rewrite caused none. The 43 valid EEGs carry deviations against the promoted baselines. What remains:
- **Zero spikes on a flat baseline.** When a child has 0 spikes and the curve is 0 at that age
(p5 = median = p95 = 0), z is 0/0 and stored as null (7 rows on B), the same as "not computed"
(`libs/tea/src/tea/biomarkers/spikes/_baseline.py`, `z_y_posicion`; each biomarker has its own `_baseline.py` with the same function). The convention is a clinical decision.
- **The 60% clean-windows gate.** 8 of the 19 rejections score 45 to 54% clean windows and are triaged usable
for bipolar analyses, yet fail the single gate (`libs/tea/src/tea/validation/rules.py`, `min_clean_pct`).
Whether that is intended for screening is for the clinical lead.
- **MLflow's type-hint warning** on every analysis: `predict` of the library's pyfunc models has no type hints
(`libs/tea/src/tea/serving/model_code/biomarker_model.py`, `plan_model.py`). Harmless; the hints remove it.
## 4. Loading the training data is slow
`dask-cluster/sync-reference.sh` copies at about 10 MB/s. Measured from a worker pod: laptop to pod 106 MiB/s,
reads from the `eeg-data` NFS volume (`192.168.20.10:/srv/nfs/data`) 95 MiB/s. Writes to the volume were not
measured; a synchronous NFS export or the server's disk are the likely limit. With the reference folder trimmed
to the 223 studies in range (1.9 GB) a sync takes about 3 minutes, so this is not urgent.
## What is out of scope
The Dask cluster's own configuration (worker count, memory per study) and the platform's validation thresholds
themselves. Tasks are in [`tasks.md`](tasks.md).
+94
View File
@@ -0,0 +1,94 @@
# Tasks: TEA EEG analysis on the Dask cluster
What [`plan.md`](plan.md) proposes, in the forms of `docs/process.md` §2. The `tea` library is its own repository
(`alberto/tea`, the `models/libs/tea` submodule); a change there is released as a new version and locked by
`models` and the WebApi.
---
## C1. EEG batches keep the cluster busy
Goal: `dev` analyses EEGs on the cluster with every worker busy and no EDF bytes in the task graph.
Description: The runner, its caller and the version lock change together: the new runner alone isn't used, and the caller alone needs the runner. Done when: on the manual deployment with the 62 EDFs and 25 workers, the cycle after a `load` analyses them in under 4 minutes, with no "Sending large graph" warning in the `indicadores` log, and the same 43 valid / 19 not valid as before.
Tasks: T1, T2, T3, T4
Branch: feature/tea-eeg-analysis
Depends on: none
Labels: type/feature priority/p2-normal area/models status/ready
## T1. A streaming Dask runner in the tea library
Goal: `tea.pipeline.dask_runner.run` keeps a bounded number of studies in flight and sends large arguments out of band.
Description: `run` gains a limit of studies in flight (default: the cluster's worker threads) and submits each study with `client.submit`, feeding the next one from `as_completed` as each finishes; `on_result` and `on_error` keep their meaning and order of calls per study. Arguments over a size threshold (EDF bytes) go through `client.scatter` so the task holds only their key. The synchronous scheduler keeps running one study at a time in the process. It doesn't change what a study computes. Done when: a test on a `LocalCluster` shows no more than the limit in flight and every result delivered; a test with a 50 MB argument raises no large-graph warning (warnings captured); the library's existing tests pass.
Context: `plan.md` §1; `models/libs/tea/src/tea/pipeline/dask_runner.py`, `core.py`
Depends on: none
Approval: none
Labels: type/feature priority/p2-normal area/models status/ready model/standard review/light size/m agent-ok
Part of: C1
## T2. analyze_pending streams its studies
Goal: `models.eeg_analysis.analyze_pending` reads each EDF only when its study is submitted and uses the streaming runner.
Description: The fixed batches of 16 go; the studies are handed to the runner as a lazy sequence, so the client holds only the studies in flight. `batch` becomes the limit in flight, defaulting to the runner's. The summary, the rows written and the governance `ExtractionRun` per EEG don't change. Done when: tests with a stub `measure_fn` show every pending EEG written once, at most the limit read from the database at a time, and the same summary as the batched version for the same input.
Context: `plan.md` §1; `models/models/eeg_analysis.py`
Depends on: T1
Approval: none
Labels: type/refactor priority/p2-normal area/models status/ready model/standard review/light size/m agent-ok
Part of: C1
## T3. Skip EEGs another run finished
Goal: Two analyses running at once don't analyse the same EEG twice.
Description: Just before a study is submitted, `analyze_pending` checks again that the EEG is still pending under the current plan, versions and baselines (`pending_ids`' rule) and skips it if not; the summary counts the skipped ones. Done when: a test starts a run over three EEGs, marks one as analysed with the current plan between submissions, and sees it skipped and counted.
Context: `plan.md` §2; `models/models/eeg_analysis.py` (`pending_ids`, `analyze_pending`)
Depends on: T2
Approval: none
Labels: type/bug priority/p2-normal area/models status/ready model/standard review/light size/s agent-ok
Part of: C1
## T4. Release the runner and rebuild the worker image
Goal: The platform and the cluster run the new library version.
Description: `tea` gets a new version with T1; `models` and the WebApi lock it; `dask-cluster/build.sh` builds and pushes the worker image from that commit and `deploy.sh` rolls the cluster. Done when: `build.sh` reports "same versions as the platform" with the new `tea` version, and C1's criterion holds on the manual deployment.
Context: `dask-cluster/README.md`; runbook "TEA Cluster Run" (steps K1, K3, B1 to B7)
Depends on: T1, T2, T3
Approval: pushing the image and the branches (permission per action)
Labels: type/chore priority/p2-normal area/infra status/ready model/small review/light size/s agent-ok
Part of: C1
## D1. Decisions for the clinical lead (`human-only`)
| Id | What is decided |
|---|---|
| D1.1 | The deviation of a metric whose value equals a flat baseline curve (0 spikes where p5 = median = p95 = 0): z = 0 and within range, or not evaluable, or another convention (`plan.md` §3) |
| D1.2 | Whether an EEG with 45 to 54% clean windows, triaged usable for bipolar analyses, is rejected by the single 60% gate (`plan.md` §3) |
Shared labels: `type/spike`, `priority/p2-normal`, `area/models`, `status/ready`, `review/domain-expert`,
`size/s`, `human-only`.
## T5. Apply the flat-curve convention
Goal: A metric equal to a flat baseline curve gets the deviation D1.1 decides, distinguishable from "not computed".
Description: `z_y_posicion` of the spikes biomarker (and of any other whose curve can be flat) returns the decided z and position instead of 0/0; the analysis stores it in `met_z` and `met_fuera`. Done when: a test with value 0 on a curve of zeros gets the decided values, and a test with a missing value still gets null.
Context: `plan.md` §3; `models/libs/tea/src/tea/biomarkers/spikes/_baseline.py` (one `_baseline.py` per biomarker)
Depends on: D1.1
Approval: the convention (D1.1)
Labels: type/bug priority/p2-normal area/models status/blocked model/standard review/required size/s agent-ok
Part of: standalone
## T6. Type hints on the library's pyfunc models
Goal: Loading a baseline no longer warns about missing type hints.
Description: `predict` of the biomarker and plan pyfunc models gets pandas type hints for its input and output. Done when: loading a registered baseline raises no MLflow type-hint warning (warnings captured in a test) and predictions are unchanged.
Context: `plan.md` §3; `models/libs/tea/src/tea/serving/model_code/biomarker_model.py`, `plan_model.py`
Depends on: none
Approval: none
Labels: type/chore priority/p3-low area/models status/ready model/small review/none size/s agent-ok
Part of: standalone
## T7. Find what limits writes to the eeg-data volume
Goal: Know why `sync-reference.sh` copies at 10 MB/s on a gigabit path.
Description: From a pod with `eeg-data` mounted read-write, time writing 1 GiB to a scratch folder as one stream and as 8 parallel streams, then read the NFS export's options and the server's disk throughput. It changes nothing on the server. Done when: the limit is named with its measurement (export option, disk, or network to `192.168.20.10`), the scratch folder is removed, and the recommendation is recorded in `plan.md` §4.
Context: `plan.md` §4; `dask-cluster/sync-reference.sh`, `loader.yaml`
Depends on: none
Approval: writing a scratch folder on the shared volume
Labels: type/spike priority/p3-low area/infra status/ready model/standard review/light size/s agent-ok
Part of: standalone
---
## Issue numbers
Not posted to Gitea yet.
+149
View File
@@ -0,0 +1,149 @@
# TEA EEG in Gobernanza: API contracts
Fixed before any delegate writes code. Backend (`models`, `WebApi`) and frontend (`WebApp`) both work from this file.
All paths are under the WebApi root; all bodies are JSON unless marked multipart. Error bodies keep the existing
`{"error": "<message>"}` shape. User-facing strings in the UI are Spanish; API identifiers are English except existing
ones (`estado`, `codigo`, `salida`, `error`, `iniciado`, which the job states already use).
## Shared types
```ts
type ClusterMode = 'auto' | 'local' | 'remote' | 'sync';
interface ClusterChoice { mode: ClusterMode; scheduler?: string } // scheduler only meaningful for 'remote'
type JobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
```
`remote` without a scheduler (none given and `DASK_SCHEDULER_ADDRESS` unset) answers 400.
## 1. Cluster health
`GET /governance/tea/cluster?mode=<ClusterMode>&scheduler=<addr>` (both optional)
```ts
interface ClusterStatus {
mode: ClusterMode; // effective mode after resolving 'auto'
scheduler: string | null;
reachable: boolean;
workers: number | null;
expected_workers: number | null; // TEA_DASK_EXPECTED_WORKERS
versions_ok: boolean | null;
version_error: string | null;
dashboard_ok: boolean | null;
dashboard_url: string | null; // TEA_DASK_DASHBOARD_URL, else http://<scheduler host>:TEA_DASK_DASHBOARD_PORT/status
reference: { name: string; edfs: number } | null; // seen from a worker; null when not checked
latency_ms: number | null;
error: string | null;
}
```
`scheduler` must equal `DASK_SCHEDULER_ADDRESS` or be in `TEA_DASK_SCHEDULERS` (comma list); otherwise 400.
Local mode reports `reachable: true`, `workers` of the local cluster is not started (null), `dashboard_*` null.
## 2. Reference cohorts
`GET /governance/tea/reference-cohorts` -> `ReferenceCohort[]`
```ts
interface ReferenceCohort { name: string; edfs: number; size_bytes: number; has_ages: boolean; path: string }
```
`POST /governance/tea/reference-cohorts/<name>/files` multipart, field `file` (one `.edf`, or `edades.csv`) ->
`201 {name, file, size_bytes}`. Name matches `[A-Za-z0-9._-]{1,64}`; other extensions 400; path escapes 400.
Root is `TEA_REFERENCE_ROOT` (unset -> the endpoints answer 503 `{"error": ...}`).
## 3. Training with parameters
`POST /governance/model-versions/tea/eeg/train-jobs` (existing route, body now optional)
```ts
interface TeaTrainBody {
reference_name?: string; // cohort folder under TEA_REFERENCE_ROOT, or a label for cluster data
reference_dir?: string; // absolute; must be inside TEA_REFERENCE_ROOT unless cluster.mode is remote
reference_ages?: string;
line_hz?: number; // 50 | 60, default 60
promote?: boolean; // default true (existing behaviour)
cluster?: ClusterChoice;
}
```
Body fields override `TEA_REFERENCE_*`. Response and states are the existing job object plus
`cluster: ClusterChoice | null`. 409 when one is running, as today.
## 4. Baseline bundle
`GET /governance/tea/baselines/export?environment=prod&production=0` -> `application/zip`, headers
`Content-Disposition: attachment; filename=baselines.zip`, `X-Baselines-Sha256: <hex>`, `X-Baselines-Versions: <n>`.
`POST /governance/tea/baselines/import` multipart, field `file` ->
```ts
interface BaselineImport { sha256: string; imported: { scenario: string; version: number }[] }
```
`BundleError` -> 400 (bad zip) or 409 (already imported / conflicting).
## 5. Analysis jobs
`POST /governance/tea/eeg/analyze-jobs`
```ts
interface AnalyzeBody { all?: boolean; limit?: number; ids?: number[]; cluster?: ClusterChoice }
```
-> `202 AnalyzeJob`; `409` if one runs. `GET /governance/tea/eeg/analyze-jobs` -> `AnalyzeJob[]` (newest first),
`GET /governance/tea/eeg/analyze-jobs/<id>` -> `AnalyzeJob`.
```ts
interface AnalyzeJob {
id: string; iniciado: string; estado: JobState; codigo: number | null; salida: string; error: string;
cluster: ClusterChoice | null; ids: number[] | null; summary: AnalyzeSummary | null; // summary once finished
}
interface AnalyzeSummary { pending: number; valid: number; not_valid: number; failed: number }
```
`ids` given -> those EEGs are re-analysed regardless of pending state; unknown id -> 404 at start.
## 6. Run progress (training and analysis, local or remote cluster)
`GET /governance/tea/jobs/<kind>/<job_id>/progress`, `kind` is `train` or `analyze`. 404 before the first sample.
```ts
interface RunProgress {
updated_at: string; // ISO UTC; the UI treats > 10 s old as 'sin señal' while the job is en_curso
phase: string; // 'midiendo' | 'ajustando' | 'registrando' | 'analizando' | ...
done: number; total: number; // studies or EEGs, in the measuring phase
elapsed_s: number;
eta_s: number | null; // null until a rate exists
tasks: { processing: number; waiting: number; memory: number; erred: number } | null;
cluster: { mode: ClusterMode; scheduler: string | null; workers: WorkerSample[]; cpu_pct: number; memory_pct: number } | null;
history: { t: number; done: number; cpu_pct: number; memory_pct: number }[]; // last 120 samples, t = seconds since start
}
interface WorkerSample { name: string; cpu_pct: number; memory_bytes: number; memory_limit: number | null; executing: number; threads: number }
```
`GET /governance/tea/jobs/<kind>/<job_id>/progress` for a job that is not Dask-based returns `cluster: null`, `tasks: null`.
## 7. Baseline check
`GET /governance/tea/baselines/<scenario>/<version>/curve?metric=<name>` ->
```ts
interface BaselineCurve { scenario: string; version: number; metric: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[] }
```
`GET /governance/tea/baselines/<scenario>/<version>/metrics` -> `string[]` (the metric names that have a curve).
`GET /governance/tea/eeg/<eeg_id>/metrics` -> `EegMetrics`:
```ts
interface EegMetrics { eeg_id: number; valid: boolean | null; level: string | null; age_months: number | null;
metrics: { name: string; value: number; z: number | null; outside: -1 | 0 | 1 | null; model: string | null }[] }
```
`GET /governance/tea/eeg` -> `{ id: number; lab_id: string | null; patient_id: number | null; study_date: string | null; valid: boolean | null; analysed: boolean }[]`
(paged: `?limit=200&offset=0`), used for the ticked-list in the analyze step.
## 8. EDF upload
`POST /governance/tea/eeg/upload` multipart: `file` (one `.edf`), optional form field `patient_id` (integer).
-> `201 { eeg_id: number; lab_id: string | null; created: boolean }`. Invalid EDF (MNE cannot open it) -> 400.
Goes through the existing import pipeline (`tea.Eeg`, upsert on `eeg_id_registro_laboratorio`); no new tables.
## 9. Result summary
`GET /governance/tea/eeg/summary` ->
```ts
interface EegSummary { eegs: number; analysed: number; valid: number; not_valid: number; failed: number;
metrics: number; metrics_with_z: number; high: number; low: number;
fhir_eegs: number; fhir_metrics: number } // tea_paciente_eegs / tea_paciente_eeg_metricas
```
## 10. Indicator cycle (existing, plus an optional body)
`POST /reportes/indicadores/tea/recalcular` body `{ cluster?: ClusterChoice }` (optional); `GET /reportes/indicadores`
unchanged (`en_curso | ok | error`...).
## Existing endpoints the UI reuses unchanged
`GET /governance/scenarios`, `GET /governance/training-jobs[/<id>]`, `GET /governance/model-versions?domain=tea`,
`PATCH /governance/model-versions/tea/<scenario>/<version>/reports`, `POST .../promote`, `GET .../checks`.
+75
View File
@@ -0,0 +1,75 @@
# TEA EEG in Gobernanza: tasks
Composite plan. Contracts: `contracts.md`. Each task fits one session and lands on `dev` of its submodule.
Owner: C = Claude, X = Codex, K = Kimi. Order is top to bottom; tasks marked (par) can run in parallel with the previous one.
| # | Task | Repo | Owner | Notes |
|---|---|---|---|---|
| 1 | Detached-job base, training body, cluster choice in `training_jobs.py` | WebApi | X | `start(domain, scenario, body)`; `--cluster`/`--reference-name` in `models run` |
| 2 | Reference cohorts store and endpoints | WebApi | X | `TEA_REFERENCE_ROOT` |
| 3 | Baselines export / import endpoints | WebApi | X | reuses `models/tea/eeg/bundle.py` |
| 4 | Cluster health (`ClusterStatus`) | models, WebApi | X | local cluster in tests |
| 5 | `RunMonitor` and progress endpoint | models, WebApi | C | |
| 6 | Analyze jobs with `ids` | models, WebApi | X | `pending_ids(ids=...)` |
| 7 | EDF upload (`EdfIntake`) after spike | WebApi | C | spike: import commit column mapping |
| 7 | (spike result) | | | `commit_sources([{kind: "edf", target: "tea.Eeg", file_base64, options: {file_name}, column_mapping: {id_registro_laboratorio: eeg_id_registro_laboratorio, fecha_estudio: eeg_fecha_estudio, canales: eeg_canales, duracion_min: eeg_duracion_min, estudio: eeg_estudio}, defaults: {eeg_pac_id}}], on_conflict="upsert")` in `webapi/imports/services/import_service.py`; the connector's `paciente` column is not mapped |
| 8 | Baseline curve / EEG metrics / EEG list / summary endpoints | WebApi | X | |
| 9 | UI scaffolding: tab, stepper, API service, types, `ClusterSelector` | WebApp | K (par with 1) | |
| 10 | UI: cohorts, train, baselines, reports, promote steps | WebApp | K | |
| 11 | UI: `RunMonitorComponent`, analyze, upload, baseline check, result | WebApp | K | after 5-8 |
| 12 | TEA notebook templates | models | C | deferred; spike: does the TEA flow fit `/experiments`? |
| 13 | Docs: README (manual-deploy), `dist/`, `docs/architecture` | all | K | |
| 14 | Restart-free promote check | models, WebApi | C | verify caching first |
## Status (2026-11-22)
| # | State |
|---|---|
| 1 training body and cluster choice | done, tested (+ `EEG_ANALYSIS_CLUSTER` honoured by `models run tea eeg`) |
| 2, 3 cohorts, baselines zip | done, tested |
| 4 cluster health | done, tested; probed against the real schedulers 10.0.10.41:30886 (25 workers) and :30786 (20 workers) |
| 5 run monitor | done, tested (`RUN_PROGRESS_DIR`, `progress.json`, `GET .../jobs/<kind>/<id>/progress`) |
| 6 analyze jobs with ids | done, tested |
| 7 EDF upload | done, tested (`webapi/tea/edf_intake.py`, `POST /governance/tea/eeg/upload`) |
| 8 curves, EEG list/metrics, summary | done, tested |
| 9 UI scaffolding | done, 31 governance specs pass, build ok |
| 10 UI steps (cohorts, train, baselines, reports, promote) | done (Kimi; scenario prefix fixed to `eeg-`) |
| 11 UI monitor card, analyze, upload, baseline check, result | done (Codex), 60 governance specs pass, build ok |
| 12 TEA notebook templates | deferred; spike pending |
| 13 docs | written (README section, dist settings, architecture); recalcular with a cluster choice added in WebApi (`recomputation.py`, `reports.py`) |
| 14 restart-free promote | no change needed: `analyze_pending` builds its `Baselines` per call, so each cycle resolves production anew; only an in-flight cycle keeps the old set |
## End-to-end run (2026-11-23, API only, one local Dask worker, 8 synthetic 4-minute EDFs)
Deployment A trained the seven baselines (job state, progress, ETA, CPU/RAM of the single worker all reported) and exported
`baselines.zip` (sha256 header equals the file's). Deployment B imported it (409 on a repeat, 400 on garbage), took the three
report URIs, promoted all seven, accepted two uploaded EDFs, analysed them by UUID id (2 valid, 0 failed), and answered the
result summary and EEG metrics; the indicator cycle ran with a cluster choice (`ok`). Not covered: the Angular UI in a browser,
a remote-cluster run, and a baseline curve (an 8-study cohort has no age bin with the 30 effective studies a curve needs).
Found and fixed during the run: 2-minute EDFs are not valid studies (use 4 minutes or more); EEG ids are UUID strings, so
`ids` (CLI, API, UI) now takes opaque ids; `TEA_LOCAL_WORKERS` caps a local cluster; the recalculate route now carries the
cluster choice. Open: the monitor keeps the last CPU/RAM/task figures after the cluster closes (they should clear).
## Cluster (2026-11-23)
Both DaskClusters (`test`, `isssteleon-eeg`) were deleted and `isssteleon-eeg` recreated from `dask-cluster/cluster.yaml`:
10 pods (one per k3s-w1..w10) x 4 workers = 40, scheduler NodePort 30786, dashboard 30787, image unchanged.
## Browser run (2026-11-23, headless Chromium, one local worker)
Driven through the UI: cluster check per mode, cohort list, training from a chosen cohort with the live monitor, baselines
export (download) and duplicate import (clear 409 message), reports, promote (7 of 7), baseline check, EDF upload,
analysis by selection (1 valid) and the result step. Found and fixed: a cohort name was never resolved to its folder
(training failed), report fields could be applied blank, RAM readings were unrounded, and a finished training said it was
promoted. Not covered: a remote-cluster run, a baseline curve, the notebook button (shows "Próximamente").
## Remote run and final deployment (2026-11-23)
Platform image rebuilt with `--pull` so its Python (3.12.16) equals the workers'; the worker image was rebuilt from the same
checkout and the cluster rolled onto it. In a throwaway project the app trained the seven baselines on the cluster from
`/referencia/helsinki` (223 studies, 40 workers, 3 min 16 s), exported the zip, promoted, and analysed three real EDFs on
the cluster (3 valid, 9 metrics with z). The existing `manual-deploy/baselines/baselines.zip` also imported, got its reports
and promoted 7 of 7 through the app. Found and fixed: the training form had no ages-table field for cluster-side folders,
and the reports and promote steps kept the version list read when the page opened.
Deployment B (`sitio-b`) was recreated: 62 real EDFs loaded, EEGs unanalysed, no baselines, cycle analysis off.