Compare commits

..

14 Commits

Author SHA1 Message Date
Angel Capetillo Zavala e0e8d2671e Update breast analysis integration 2026-11-14 08:12:36 -06:00
Angel Capetillo Zavala a1d402ccb5 Record local dashboard environment recovery 2026-11-13 18:31:56 -06:00
Angel Capetillo Zavala 132b85053e Record patient identity integration 2026-11-13 18:24:39 -06:00
Angel Capetillo Zavala 92d3a65797 Clarify Linux validation before deployment 2026-11-13 15:47:10 -06:00
Angel Capetillo Zavala c39d20b0cd Pin the breast dashboard merge 2026-11-13 15:46:28 -06:00
Angel Capetillo Zavala f6b9896147 Record verified breast dashboard composition 2026-11-13 15:44:51 -06:00
Angel Capetillo Zavala 8d628417f3 Record breast dashboard integration candidate 2026-11-13 15:18:24 -06:00
Angel Capetillo Zavala 5e4ed74e99 Update ISSSTELEON for CaMa analysis 2026-11-13 14:36:52 -06:00
Angel Capetillo Zavala b550d18fb3 Update ISSSTELEON 2026-11-13 00:02:26 -06:00
Angel Capetillo Zavala 3669f4a298 Update breast cancer follow-up application 2026-11-12 22:40:59 -06:00
Angel Capetillo Zavala 62d41bcab4 Pin CaMa dashboard presentation 2026-11-12 13:21:07 -06:00
Angel Capetillo Zavala f9ff0d5927 Pin the integrated CaMa dashboard-test release 2026-11-12 12:17:34 -06:00
Angel Capetillo Zavala 829c548913 chore(submodules): update ISSSTELEON dashboard-test composition 2026-11-12 02:15:41 -06:00
Angel Capetillo Zavala 367e40a9fc Pin application composition for dashboard testing 2026-11-11 20:45:57 -06:00
112 changed files with 5875 additions and 7912 deletions
@@ -5,38 +5,26 @@ import subprocess
import sys
from pathlib import Path
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "WebApi", "WebApp")
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "indicadores_kit", "WebApi", "WebApp")
IMPACT = {
"Core": {"Core", "Persistance", "Transformation", "models", "WebApi"},
"Persistance": {"Persistance", "Transformation", "models", "WebApi"},
"Core": {"Core", "Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
"Persistance": {"Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
"Extraction": {"Extraction", "models", "WebApi"},
"Transformation": {"Transformation", "Persistance", "models", "WebApi"},
"models": {"models", "WebApi"},
"indicadores_kit": {"indicadores_kit", "WebApi"},
"WebApi": {"WebApi"},
"WebApp": {"WebApp"},
}
# Gitlinks whose removal is a recognized structural change, with the checks covering the code that took over
# their jobs. Adding, replacing or re-adding them still requires a manual mapping.
RETIRED_GITLINKS = {
"ISSSTELEON/indicadores_kit": {"Transformation", "models", "WebApi"},
}
# 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"}
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"}
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"}
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
def deploy_file(path):
return path in DEPLOY_FILES or (path.startswith(('.gitea/deploy/', '.gitea/deploy-terminal/'))
and path.endswith('.py'))
return path in DEPLOY_FILES or (path.startswith('.gitea/deploy/') and path.endswith('.py'))
def git(repo, *args):
@@ -58,17 +46,6 @@ def documentation(path):
return path.lower().endswith((".md", ".rst"))
def retired_removal(full, path, left, right, after):
"""Whether a retired gitlink is removed and nothing takes its place in the candidate tree."""
return (full in RETIRED_GITLINKS and left is not None and left[0] == "160000" and right is None
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()):
@@ -78,14 +55,6 @@ def compare(repo, old, new, prefix, changed):
full = f"{prefix}/{path}" if prefix else path
if (left and left[0] == "160000") or (right and right[0] == "160000"):
print(f"Changed submodule: {full}: {left} -> {right}")
if retired_removal(full, path, left, right, after):
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
@@ -106,11 +75,7 @@ def select(changed):
selected = set()
for path in 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 parts[0] != "ISSSTELEON":
if deploy_file(path) or path in PROBE_FILES:
continue
if path in CI_SELF_TESTED:
+5 -143
View File
@@ -2,7 +2,6 @@
import importlib.util
import os
import re
import shutil
import subprocess
import sys
@@ -10,7 +9,7 @@ import tempfile
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select_checks.py"))
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select.py"))
selector = importlib.util.module_from_spec(spec)
spec.loader.exec_module(selector)
@@ -28,15 +27,13 @@ class SelectionTests(unittest.TestCase):
"""Deployment Python modules select installer checks without application suites."""
self.assertEqual(selector.select(selector.DEPLOY_FILES), set())
self.assertTrue(selector.deploy_file('.gitea/deploy/new.py'))
self.assertTrue(selector.deploy_file('.gitea/deploy-terminal/install.py'))
self.assertEqual(selector.select({".gitea/deploy/new.py"}), set())
self.assertEqual(selector.select({".gitea/deploy-terminal/install.py"}), set())
self.assertEqual(selector.select({".gitea/deploy/unknown.txt"}), set(selector.CHECKS))
self.assertEqual(selector.select(selector.DEPLOY_FILES | {"ISSSTELEON/WebApp/a"}), {"WebApp"})
def test_host_script_selects_deploy_checks(self):
"""A host-only change selects installer tests without selecting application suites."""
changed = {'.gitea/deploy/registry.py'}
changed = {'.gitea/deploy/host.py'}
self.assertTrue(changed & selector.DEPLOY_FILES)
self.assertEqual(selector.select(changed), set())
@@ -64,10 +61,9 @@ class SelectionTests(unittest.TestCase):
def test_report_rejects_failed_check(self):
"""The workflow's actual reporting script returns failure for a failed selected check."""
git = shutil.which("git")
bash = shutil.which("bash")
if os.name == "nt" and git:
bash = Path(git).parents[1] / "bin" / "bash.exe"
if not bash and os.name == "nt":
bash = r"C:\Program Files\Git\bin\bash.exe"
if not bash or not Path(bash).exists():
self.fail("bash is required to test the workflow report")
workflow = Path(__file__).parents[1] / "workflows" / "ci.yml"
@@ -77,7 +73,7 @@ class SelectionTests(unittest.TestCase):
script = "\n".join(line[10:] for line in block.splitlines())
for outcome, expected in (("failure", 1), ("skipped", 1), ("success", 0)):
env = {**os.environ, "CORE": outcome, "CORE_REQUIRED": "true"}
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "WEBAPI", "WEBAPP"):
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "INDICADORES", "WEBAPI", "WEBAPP"):
env[name] = "skipped"
env[name + "_REQUIRED"] = "false"
result = subprocess.run([bash, "-c", script], env=env, capture_output=True, text=True)
@@ -194,140 +190,6 @@ class SelectionTests(unittest.TestCase):
self.assertEqual({name for name in selector.CHECKS if values[name] == "true"},
{"WebApp", "WebApi"})
def kit_history(self, root, final):
"""Build an outer repo whose ISSSTELEON child holds the kit gitlink, then apply `final` to the child.
Returns the outer commits before and after; `final(run, child)` stages the candidate change."""
child = root / "ISSSTELEON"
child.mkdir()
def run(repo, *args):
return subprocess.check_output(["git", "-C", str(repo), *args], stderr=subprocess.DEVNULL)
def commit(repo, name):
run(repo, "commit", "-qm", name)
return run(repo, "rev-parse", "HEAD").decode().strip()
for repo in (root, child):
run(repo, "init", "-q")
run(repo, "config", "user.email", "ci@example.invalid")
run(repo, "config", "user.name", "CI")
(child / "README.md").write_text("tree", encoding="utf-8")
run(child, "add", "README.md")
run(child, "update-index", "--add", "--cacheinfo", "160000," + "1" * 40 + ",indicadores_kit")
run(child, "update-index", "--add", "--cacheinfo", "160000," + "2" * 40 + ",other_kit")
commit(child, "base")
run(root, "add", "ISSSTELEON")
old = commit(root, "base")
final(run, child)
commit(child, "candidate")
run(root, "add", "ISSSTELEON")
return old, commit(root, "candidate")
def test_retired_kit_removal_is_recognized(self):
"""Removing the retired kit gitlink selects its successors' checks.
Fails if the selector stops recognizing the known removal (CI rejects every PR that carries it)
or maps it to the kit's own suite, which no longer exists in the candidate tree."""
with tempfile.TemporaryDirectory() as temp:
old, new = self.kit_history(Path(temp), lambda run, child: run(
child, "update-index", "--force-remove", "indicadores_kit"))
changes = set()
selector.compare(Path(temp), old, new, "", changes)
self.assertEqual(changes, {"ISSSTELEON/indicadores_kit"})
self.assertEqual(selector.select(changes), {"Transformation", "models", "WebApi"})
self.assertNotIn("indicadores_kit", selector.CHECKS)
def test_other_structural_gitlink_changes_still_fail(self):
"""Replacing the kit with files, re-pointing a different gitlink's removal or adding one stays fatal.
Fails if the retired-gitlink exception is widened to arbitrary structural changes."""
def replace(run, child):
run(child, "update-index", "--force-remove", "indicadores_kit")
(child / "indicadores_kit").mkdir()
(child / "indicadores_kit" / "code.py").write_text("pass", encoding="utf-8")
run(child, "add", "indicadores_kit/code.py")
def remove_other(run, child):
run(child, "update-index", "--force-remove", "other_kit")
def add(run, child):
run(child, "update-index", "--add", "--cacheinfo", "160000," + "3" * 40 + ",new_kit")
for name, final in (("replace", replace), ("remove-other", remove_other), ("add", add)):
with self.subTest(change=name), tempfile.TemporaryDirectory() as temp:
old, new = self.kit_history(Path(temp), final)
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.
Fails if the retired entry starts acting as a component mapping for new files."""
self.assertEqual(selector.select({"ISSSTELEON/indicadores_kit/code.py"}), set(selector.CHECKS))
def test_workflow_runs_exactly_the_selectable_checks(self):
"""Every selectable check has a workflow step and the workflow reads no retired output.
Fails if a check is added to `CHECKS` without a step, or a step still waits on a check the selector no
longer emits (a retired component would then be silently skipped or fail on a missing folder)."""
workflow = (Path(__file__).parents[1] / "workflows" / "ci.yml").read_text(encoding="utf-8")
outputs = set(re.findall(r"steps\.select\.outputs\.([A-Za-z_]+)", workflow))
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(),
*selector.ADDED_GITLINKS.values()]:
self.assertLessEqual(impacted, set(selector.CHECKS))
def test_webapi_step_serves_the_compiled_dbt_manifest(self):
"""The WebApi step compiles dbt's manifest and exports it before pytest runs.
The measures and the indicator cycle are defined in the manifest's compiled SQL, which `dbt parse` does not
produce. Fails if the step stops compiling it, compiles it without exporting `DBT_MANIFEST`, or exports it
after pytest has started (the suite would then skip its manifest tests or raise on the missing variable)."""
workflow = (Path(__file__).parents[1] / "workflows" / "ci.yml").read_text(encoding="utf-8")
step = workflow.split(" - name: WebApi pytest\n", 1)[1].split(" - name:", 1)[0]
compile_at = step.index("dbt compile")
export_at = step.index('export DBT_MANIFEST="$RUNNER_TEMP/dbt-manifest/manifest.json"')
self.assertIn("--no-introspect", step)
self.assertIn('--target-path "$RUNNER_TEMP/dbt-manifest"', step)
self.assertIn('test -s "$RUNNER_TEMP/dbt-manifest/manifest.json"', step)
self.assertLess(compile_at, export_at)
self.assertLess(export_at, step.index("pytest -q"))
def test_conflict_and_outdated_head(self):
"""Divergent conflicting commits fail the merge and fail the ancestry requirement."""
with tempfile.TemporaryDirectory() as temp:
+2 -8
View File
@@ -146,14 +146,8 @@ npm run build -- --configuration production
```
The service commands use `.venv/bin/gunicorn` on `127.0.0.1:<API port>`,
`.venv/bin/python -m <worker>` with the worker module the release contains
(`webapi.recomputation`, or `webapi.indicadores_vivos` in older releases; a release
with neither is refused), and a dedicated nginx process for the Angular production files and proxy.
For `webapi.recomputation`, preparation builds the SQLite dbt manifest using the `sqlite` dependency group in the
bundled `Transformation/` project and supplies it to the API and worker through `DBT_MANIFEST`.
There is no isolated notebook runner:
the services set `NOTEBOOK_EXECUTOR=contenedor` without a jobs folder, so an
uploaded notebook fails instead of running inside the API process. The nginx process listens on the
`.venv/bin/python -m webapi.indicadores_vivos`, and a dedicated nginx process
for the Angular production files and proxy. The nginx process listens on the
requested public port. The four domain databases, MLflow database and
artifacts, reports, indicator queue and nginx temporary files are under the new
instance's `data/`. No Docker volume, database, compose project or existing
+1 -2
View File
@@ -10,8 +10,7 @@ import tempfile
import source
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'Transformation', 'WebApi', 'WebApp', 'models',
'indicadores_kit'}
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'WebApi', 'WebApp', 'models', 'indicadores_kit'}
def safe_member(member):
+10 -49
View File
@@ -23,11 +23,9 @@ DIGEST = re.compile(r'^[0-9a-f]{64}$')
SAFE_PATH = re.compile(r'^/[A-Za-z0-9_./-]+$')
DOCKER_ROOT = Path('/srv/workingnarrative-dev')
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
# Indicator worker modules a bundle may hold, newest first.
WORKER_MODULES = ('webapi.recomputation', 'webapi.indicadores_vivos')
INSTALLER_FILES = {'install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp', 'ISSSTELEON/models'}
LEGACY_LINKS = REQUIRED_LINKS | {'ISSSTELEON/indicadores_kit'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp',
'ISSSTELEON/models', 'ISSSTELEON/indicadores_kit'}
def validate_record(record):
@@ -50,7 +48,7 @@ def validate_record(record):
or any(not isinstance(value, str) or not DIGEST.fullmatch(value) for value in files.values())):
raise ValueError('invalid installer file manifest')
links = record.get('gitlinks')
if (not isinstance(links, dict) or set(links) not in (REQUIRED_LINKS, LEGACY_LINKS)
if (not isinstance(links, dict) or set(links) != REQUIRED_LINKS
or any(not isinstance(value, str) or not SHA.fullmatch(value) for value in links.values())):
raise ValueError('unsupported or incomplete gitlinks')
if not isinstance(record.get('installer_ref'), str) or not record['installer_ref'].startswith('refs/heads/'):
@@ -159,24 +157,11 @@ def extract_bundle(archive_path, target):
shutil.copyfileobj(source_stream, out, 1024 * 1024)
os.chmod(dest, 0o755 if member.mode & 0o111 else 0o644)
app = target / 'application'
required = ['WebApi/pyproject.toml', 'WebApi/uv.lock', 'WebApp/package.json', 'WebApp/package-lock.json']
required = ['WebApi/pyproject.toml', 'WebApi/uv.lock', 'WebApi/webapi/indicadores_vivos.py',
'WebApp/package.json', 'WebApp/package-lock.json']
required += [f'Persistance/persistance/{domain}/alembic.ini' for domain in DOMAINS]
if any(not (app / path).is_file() for path in required):
raise ValueError('bundle lacks required locked application components')
worker = worker_module(app)
if worker == 'webapi.recomputation' and any(not (app / 'Transformation' / name).is_file() for name in
('pyproject.toml', 'dbt_project.yml', 'profiles.yml')):
raise ValueError('bundle lacks the Transformation project')
return worker
def worker_module(app):
"""The indicator worker module the bundled WebApi provides."""
for module in WORKER_MODULES:
path = app / 'WebApi' / (module.replace('.', '/') + '.py')
if path.is_file() and not path.is_symlink():
return module
raise ValueError('bundle lacks required locked application components')
def atomic_record(path, record):
@@ -198,9 +183,7 @@ def environment(base):
'MLFLOW_ARTIFACT_ROOT': str(data / 'mlflow-artifacts'),
'MLFLOW_DISABLE_TELEMETRY': 'true', 'DO_NOT_TRACK': 'true',
'MLFLOW_DISABLE_AGENT_HINT': '1', 'WEBAPI_REPORT_DIR': str(data / 'reportes'),
'INDICADORES_DIR': str(data / 'indicadores'),
# No isolated notebook runner exists here: notebook runs fail instead of running in the API process.
'NOTEBOOK_EXECUTOR': 'contenedor'}
'INDICADORES_DIR': str(data / 'indicadores')}
for domain in DOMAINS:
result[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
return result
@@ -231,24 +214,7 @@ print('Verified four new isolated SQLite migration targets')
run([uv, 'run', '--no-sync', 'python', '-c', code, data], app / 'WebApi', env)
def compile_sqlite_manifest(uv, app, env, data):
"""Build the bundle's dbt measure manifest against isolated SQLite targets."""
transformation = app / 'Transformation'
output = data / 'dbt'
schemas = output / 'schemas'
schemas.mkdir(parents=True)
dbt_env = dict(env, DBT_SCHEMA_DIR=str(schemas))
dbt_env.update({domain.upper() + '_DB_PATH': str(data / (domain + '.db')) for domain in DOMAINS})
run([uv, 'sync', '--only-group', 'sqlite'], transformation, dbt_env)
run([uv, 'run', '--no-sync', 'dbt', 'compile', '--profiles-dir', '.', '--profile', 'cacu', '--target', 'sqlite',
'--no-introspect', '--target-path', output], transformation, dbt_env)
manifest = output / 'manifest.json'
if not manifest.is_file() or manifest.is_symlink():
raise ValueError('compiled dbt manifest is missing')
env.update(DBT_MANIFEST=str(manifest), TRANSFORMATION_DIR=str(transformation))
def systemd_unit(base, account, service, api_port, nginx, worker):
def systemd_unit(base, account, service, api_port, nginx):
work = base / 'application' / 'WebApi'
binary = work / '.venv' / 'bin'
name = base.name
@@ -259,7 +225,7 @@ def systemd_unit(base, account, service, api_port, nginx, worker):
common += f'After={name}-api.service\nRequires={name}-api.service\n'
command = {
'api': f'{binary}/gunicorn --bind 127.0.0.1:{api_port} --workers 2 --timeout 600 --access-logfile - webapi:create_app()',
'worker': f'{binary}/python -m {worker}',
'worker': f'{binary}/python -m webapi.indicadores_vivos',
'web': f'{nginx} -c {base}/nginx.conf -p {base}/',
}[service]
directory = base if service == 'web' else work
@@ -294,7 +260,7 @@ def prepare(parent, record, archive_path, expected_digest, api_port, account, ex
try:
atomic_record(metadata, state)
(base / 'data').mkdir(mode=0o700)
worker = extract_bundle(archive_path, base)
extract_bundle(archive_path, base)
app = base / 'application'
env = environment(base)
for domain in DOMAINS:
@@ -319,18 +285,13 @@ def prepare(parent, record, archive_path, expected_digest, api_port, account, ex
if target.is_symlink() or target.resolve().parent != (base / 'data').resolve() or target.stat().st_size != 0:
raise ValueError('migration target is not a new isolated database: ' + domain)
run([tools['uv'], 'run', '--no-sync', 'alembic', '-c', app / 'Persistance' / 'persistance' / domain / 'alembic.ini', 'upgrade', 'head'], app / 'WebApi', env)
if worker == 'webapi.recomputation':
state.update(phase='compiling_measure_manifest')
atomic_record(metadata, state)
compile_sqlite_manifest(tools['uv'], app, env, base / 'data')
service_env = {k: v for k, v in env.items() if k not in ('PATH', 'LANG', 'npm_config_cache', 'UV_CACHE_DIR')}
(base / 'service.env').write_text(''.join(f'{key}={value}\n' for key, value in sorted(service_env.items())), encoding='utf-8')
(base / 'nginx.conf').write_text(nginx_conf(base, port, api_port), encoding='utf-8')
units = base / 'units'
units.mkdir(mode=0o750)
for service in ('api', 'worker', 'web'):
(units / f'{base.name}-{service}.service').write_text(
systemd_unit(base, account, service, api_port, tools['nginx'], worker), encoding='utf-8')
(units / f'{base.name}-{service}.service').write_text(systemd_unit(base, account, service, api_port, tools['nginx']), encoding='utf-8')
run([tools['nginx'], '-t', '-c', base / 'nginx.conf', '-p', str(base) + '/'], base, env)
state.update(status='prepared', phase='awaiting_systemd_activation', prepared_at=int(time.time()))
atomic_record(metadata, state)
+6 -9
View File
@@ -6,15 +6,12 @@ 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': 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',
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
SHA = re.compile(r'^[0-9a-f]{40}$')
@@ -78,7 +75,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 = ORIGINS[full]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + ORIGINS[full] + '.git'
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}',
-71
View File
@@ -69,81 +69,10 @@ class InstallerTests(unittest.TestCase):
domain = next(part for part in install.DOMAINS if part in str(args[-3]))
self.assertTrue(env[domain.upper() + '_DATABASE_URL'].replace('\\', '/').endswith('/data/' + domain + '.db'))
(self.root / 'isssteleon-native-18090' / 'data' / (domain + '.db')).write_bytes(b'migrated')
if 'dbt' in args:
(Path(args[-1]) / 'manifest.json').write_text('{}', encoding='utf-8')
def prepare(self, api_port=28090):
return install.prepare(self.root, self.record, self.bundle, self.digest, api_port, self.account, self.hostname, self.tools)
def rebundle(self, workers, *, transformation=True):
"""Rewrite the fixture with the requested worker files and its current dbt project, if present."""
with tarfile.open(self.bundle, 'r:gz') as archive:
members = [(m, archive.extractfile(m).read()) for m in archive.getmembers()
if not m.name.startswith('application/WebApi/webapi/')]
with tarfile.open(self.bundle, 'w:gz') as archive:
for member, content in members:
archive.addfile(member, io.BytesIO(content))
for worker in workers:
info = tarfile.TarInfo(f'application/WebApi/webapi/{worker}.py')
archive.addfile(info, io.BytesIO(b''))
if transformation and 'recomputation' in workers:
for name in ('pyproject.toml', 'dbt_project.yml', 'profiles.yml'):
archive.addfile(tarfile.TarInfo(f'application/Transformation/{name}'), io.BytesIO(b''))
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
self.record['bundle_sha256'] = self.digest
def test_worker_unit_runs_the_bundled_queue_module(self):
"""The worker unit runs `webapi.recomputation` when the release has it, the older module otherwise.
Fails if a current release is refused for lacking the removed module, or the unit names a module the
bundle does not contain."""
self.rebundle(['recomputation', 'indicadores_vivos'])
self.prepare()
worker = (self.root / 'isssteleon-native-18090' / 'units' / 'isssteleon-native-18090-worker.service').read_text()
self.assertIn('-m webapi.recomputation\n', worker)
base = self.root / 'isssteleon-native-18090'
service_env = (base / 'service.env').read_text()
self.assertIn(f'DBT_MANIFEST={base / "data" / "dbt" / "manifest.json"}\n', service_env)
args, directory, env = next(call for call in self.calls if 'dbt' in call[0])
self.assertIn('--no-introspect', args)
self.assertEqual(directory, base / 'application' / 'Transformation')
self.assertEqual(env['CAMA_DB_PATH'], str(base / 'data' / 'cama.db'))
def test_modern_worker_requires_transformation_project(self):
"""Reject a current bundle missing dbt inputs before running builds or migrations."""
self.rebundle(['recomputation'], transformation=False)
with self.assertRaisesRegex(ValueError, 'lacks the Transformation project'):
self.prepare()
self.assertEqual(self.calls, [])
def test_release_gitlinks_support_both_known_shapes(self):
"""Keep the kit optional for older releases and fail if any other link appears or is missing."""
for paths in (install.REQUIRED_LINKS, install.LEGACY_LINKS):
self.record['gitlinks'] = dict.fromkeys(paths, 'd' * 40)
install.validate_record(self.record)
for paths in (install.REQUIRED_LINKS - {'ISSSTELEON/models'}, install.REQUIRED_LINKS | {'ISSSTELEON/other'}):
self.record['gitlinks'] = dict.fromkeys(paths, 'd' * 40)
with self.assertRaisesRegex(ValueError, 'unsupported or incomplete gitlinks'):
install.validate_record(self.record)
def test_release_without_a_worker_module_is_refused(self):
"""A release with neither worker module stops before any service units are created.
Fails if the native installer prepares units for a worker that cannot start."""
self.rebundle([])
with self.assertRaisesRegex(ValueError, 'lacks required locked application components'):
self.prepare()
self.assertFalse((self.root / 'isssteleon-native-18090' / 'units').exists())
def test_notebooks_never_run_in_the_api_process(self):
"""The native services select the isolated notebook executor, which has no jobs folder here.
Fails if an uploaded notebook could run unsandboxed in the API process of a native installation."""
self.prepare()
service_env = (self.root / 'isssteleon-native-18090' / 'service.env').read_text()
self.assertIn('NOTEBOOK_EXECUTOR=contenedor\n', service_env)
self.assertNotIn('NOTEBOOK_JOBS_DIR', service_env)
def test_new_installation_prepares_locked_build_migrations_and_units(self):
"""A new instance must use locked builds, four isolated databases and three inactive unit files."""
result = self.prepare()
-36
View File
@@ -65,42 +65,6 @@ 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):
+7 -7
View File
@@ -1,5 +1,6 @@
"""Protect the manual workflow's deployment chain and Docker independence."""
from pathlib import Path
import subprocess
import re
import unittest
@@ -8,7 +9,7 @@ WORKFLOW = ROOT / '.gitea' / 'workflows' / 'deploy-terminal-release.yml'
class WorkflowTests(unittest.TestCase):
"""Inspect the checked-in native workflow and its commands."""
"""The current checkout provides the uncommitted workflow and the Docker baseline."""
def test_workflow_dispatch_builds_and_executes_host_deployment(self):
"""A manual dispatch must resolve first and invoke the automated host helper."""
text = WORKFLOW.read_text(encoding='utf-8')
@@ -29,12 +30,11 @@ class WorkflowTests(unittest.TestCase):
self.assertIn('secrets.NATIVE_KNOWN_HOSTS', text)
self.assertNotIn('sudo ', text)
def test_native_workflow_does_not_call_docker_installer(self):
"""Fail if the native workflow invokes Docker or delegates to the DEV installer."""
text = WORKFLOW.read_text(encoding='utf-8')
self.assertNotIn('.gitea/deploy/', text)
self.assertNotIn('deploy-dev.yml', text)
self.assertNotRegex(text, r'(?m)^\s*docker\s+')
def test_existing_docker_workflow_is_not_modified(self):
"""The independent deployment must not alter the Docker workflow or its installers."""
result = subprocess.run(['git', '-C', str(ROOT), 'diff', '--quiet', 'HEAD', '--',
'.gitea/workflows/deploy-dev.yml', '.gitea/deploy'], check=False)
self.assertEqual(result.returncode, 0)
if __name__ == '__main__':
+22 -78
View File
@@ -1,83 +1,27 @@
# What was exercised, and what was not
# General DEV workflow integration
Status of the disposable DEV installer (`installer.py`, `dataload.py`). See [README.md](README.md) for use.
`.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).
## Capabilities of the retired updater and where each went
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.
The conservative updater, its recovery tools and the data guards were removed after checking, one by one, that
nothing else needs them:
Run the deployment and selector suites from the repository root:
| 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. |
```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
```
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.
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.
+398 -133
View File
@@ -1,155 +1,420 @@
# Disposable DEV instances
# DEV installation and conservative updates
Two manual workflows manage throwaway DEV instances of ISSSTELEON on the Docker host:
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.
| Workflow | Does |
## 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 |
| --- | --- |
| `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. |
| 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. |
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.
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.
## Using them
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
```
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.
### Install
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 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.
### Reinstall
The instance must be proven to be a DEV one of this installer before anything is planned:
- 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 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.
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).
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.
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.
### Inspecting an instance
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:
```sh
cat /srv/workingnarrative-dev/isssteleon-dev-<puerto>/installation.json
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
```
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`.
### Central workflow and application branch
## Prerequisites
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.
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.
`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.
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.
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.
## Tests
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.
## Four distinct operations
| 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. |
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.
## Prerequisites and supported origins
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.
Only a valid `installed` record with all three matching, running containers 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.
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 `ColaDeRecalculo.correr` once for CaCu, CaMa and TEA, without `migrar`.
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.
## 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:
```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"
```
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.
### Reconcile a manually recovered pre-activation failure
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.
`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.
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:
```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_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.
`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.
## Limits
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.
- 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.
## Remaining limits before institutional use
## Loading simulated data (optional, after an install)
- 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.
- 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.
`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.
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.
+48
View File
@@ -0,0 +1,48 @@
# 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
@@ -1,240 +0,0 @@
"""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)
+542
View File
@@ -0,0 +1,542 @@
"""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
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',
})
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',
}
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
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):
"""Keep the worker idle until the checked one-shot recalculation has completed."""
api = config['services']['webapi']
worker = config['services']['indicadores']
for service in (api, worker):
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'] = []
worker['working_dir'] = '/app/WebApi'
worker['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']
worker['command'] = []
worker['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 verify_api(api, cmd, data, image, *, timeout=300):
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':
mounts = item.get('Mounts', [])
if (item.get('Image') != expected or len(mounts) != 1
or mounts[0].get('Source') != str(data) or mounts[0].get('Destination') != '/data'
or mounts[0].get('Type') != 'bind' or mounts[0].get('RW') is not True
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):
progress = progress or (lambda phase: None)
verify_api(api, cmd, data, image)
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'])
progress('frontend')
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapp'])
return after
def freeze_failed(api, cmd, project, data):
"""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]))
for item in items:
labels = item.get('Config', {}).get('Labels') or {}
if (labels.get('com.docker.compose.project') != project
or labels.get('com.docker.compose.service') not in ('webapi', 'webapp', 'indicadores')):
raise RuntimeError('failed container ownership is uncertain')
if labels['com.docker.compose.service'] != 'webapp':
mounts = item.get('Mounts', [])
if (len(mounts) != 1 or mounts[0].get('Type') != 'bind'
or mounts[0].get('Source') != str(data) or mounts[0].get('Destination') != '/data'):
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):
"""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') != ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']
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')
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, 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'])
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
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:')
api.verify_config(old_config, project, data, old_tag, port)
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])
api.verify_services(previous_cmd, port)
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)
config = controlled_config(json.loads(api.run([*cmd, 'config', '--format', 'json'])))
api.verify_config(config, project, data, tag, port)
persist_config(deploy, config)
phase = 'compatibility'
contract = guard(api, images[0], 'contract', {})
initial = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract}, data)
prepared_bytes = sum(p.stat().st_size for tree in (source, deploy)
for p in tree.rglob('*') if p.is_file())
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'),
migrations='none-pending', recalculation='not-started')
def save():
api.host_action(helper, 'save', project, json.dumps(current))
save()
phase = 'quiescing'
for container in old_ids:
api.run(['docker', 'update', '--restart=no', container])
api.run(['docker', 'stop', container])
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')
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})))
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'])
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)
current['phase'] = phase = 'availability'
save()
api.verify_services(cmd, port)
api.verify_existing_containers(dict(record, images=images), 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')
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', 'frontend', 'availability'):
try:
freeze_failed(api, cmd, project, data)
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'):
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)
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 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:
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
+554
View File
@@ -0,0 +1,554 @@
"""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 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',
}
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',
}
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 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(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'
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 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 'exact')
if domain == 'governance':
mode = 'exact'
value_hash, row_hashes, count = hashlib.sha256(), Counter(), 0
for row in connection.execute(query):
encoded = json.dumps(row, default=lambda v: {'blob_sha256': hashlib.sha256(v).hexdigest()},
ensure_ascii=True, separators=(',', ':')).encode()
hashed = hashlib.sha256(encoded).hexdigest()
value_hash.update(hashed.encode())
if mode == 'append':
row_hashes[hashed] += 1
count += 1
result[table] = {'mode': mode, 'count': count, 'sha256': value_hash.hexdigest()}
if mode == 'append':
result[table]['rows'] = dict(row_hashes)
return result
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'] == 'append':
require(not (Counter(prior['rows']) - Counter(current['rows'])),
domain + ': historical rows changed in ' + table)
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 == '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 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'
from webapi.indicadores_vivos import ColaDeRecalculo
stage = 'initialize'
queue = ColaDeRecalculo()
completed = []
for domain in DOMAINS:
if domain == 'governance':
continue
stage = 'enqueue'
queue.tomar(domain)
stage = 'execute'
result = queue.correr(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 queue.pendientes(), 'unexpected pending recalculations')
return {'completed': completed}
except Exception as exc:
exc.recalculation_stage = stage
exc.inspection_domain = domain
raise
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'])
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] == 'inspect':
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
@@ -1,283 +0,0 @@
"""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
+557
View File
@@ -0,0 +1,557 @@
#!/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')
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', 'python:3.12-slim', '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}')
host_action(helper, 'reserve', project, str(port))
def host_action(helper, action, *args):
script = Path(__file__).with_name('host.py').read_text(encoding='utf-8')
guard = Path(__file__).with_name('data_guard.py').read_text(encoding='utf-8')
prefix = ("import sys, types\n"
"module = types.ModuleType('data_guard')\n"
"sys.modules['data_guard'] = module\n"
f"exec({guard!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 verify_config(config, project, data, tag, port):
if config.get('name') != project:
raise RuntimeError('effective Compose project name does not match')
services = config.get('services', {})
if set(services) != {'webapi', 'webapp', 'indicadores'}:
raise RuntimeError('unexpected Compose services')
for name, service in services.items():
if (service.get('privileged') or service.get('network_mode') == 'host'
or service.get('pid') == 'host' or service.get('devices')):
raise RuntimeError(f'unsafe Compose service: {name}')
for name in ('webapi', 'indicadores'):
service = services[name]
if service.get('image') != f'isssteleon/webapi:{tag}':
raise RuntimeError(f'unexpected {name} image')
volumes = service.get('volumes', [])
if len(volumes) != 1 or not any(v.get('type') == 'bind' and v.get('source') == str(data) and v.get('target') == '/data'
and not v.get('read_only') for v in volumes):
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 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')
def verify_services(cmd, port, timeout=300):
deadline = time.monotonic() + timeout
last = 'services did not start'
while time.monotonic() < deadline:
try:
for service in ('webapi', 'webapp', 'indicadores'):
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)
config = conservative.controlled_config(
json.loads(run([*cmd, 'config', '--format', 'json'])), migrate_on_start=True)
verify_config(config, project, data, tag, port)
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'])
conservative.verify_api(sys.modules[__name__], cmd, data, record['images'][0])
contract = conservative.guard(sys.modules[__name__], record['images'][0], 'contract', {})
before = conservative.guard(sys.modules[__name__], record['images'][0], 'state',
{'data': '/data', 'contract': contract}, data)
record['phase'] = 'recalculation-and-persistence'
save()
conservative.finish(sys.modules[__name__], cmd, record['images'][0], deploy, data, contract, before)
verify_services(cmd, port)
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 verify_existing_containers(record, base, helper):
"""Reject unexpected containers, image identities, mounts and port owners."""
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')
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')
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}')
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 service not in ('webapi', 'webapp', 'indicadores') 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')
if service in ('webapi', 'indicadores'):
if len(mounts) != 1 or not any(m.get('Type') == 'bind' and m.get('Source') == data and m.get('Destination') == '/data'
and m.get('RW') is True for m in mounts):
raise RuntimeError(f'{service} data mount does not match')
if bindings:
raise RuntimeError(f'{service} publishes an unexpected port')
elif mounts or set(bindings) != {'80/tcp'} or not any(str(b.get('HostPort')) == str(port) for b in (bindings.get('80/tcp') or [])):
raise RuntimeError('webapp port does not match')
found[service] = item['Id']
if set(found) != {'webapi', 'webapp', 'indicadores'}:
raise RuntimeError('missing Compose project containers')
own_networks = {network.get('NetworkID')
for item in containers if item.get('Id') in found.values()
for network in item.get('NetworkSettings', {}).get('Networks', {}).values()
if 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', {})
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')]
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_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:
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)
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
@@ -0,0 +1,30 @@
#!/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
@@ -1,277 +0,0 @@
"""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
@@ -1,84 +0,0 @@
"""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'])
+327
View File
@@ -0,0 +1,327 @@
"""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
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 verify_isolated_restore(base, project, operation):
"""Restore the operation backup to a new private location and verify it."""
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)
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 == '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
@@ -1,529 +0,0 @@
#!/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())
-21
View File
@@ -1,21 +0,0 @@
"""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)
+157
View File
@@ -0,0 +1,157 @@
#!/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')
ids = [args.indicadores, args.webapi, args.webapp]
if len(set(ids)) != 3 or any(not re.fullmatch(r'[0-9a-f]{64}', value) for value in ids):
raise ValueError('three distinct full original container IDs are required')
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']
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']))
api.verify_config(config, project, api.BASE / project / 'data', images[0].split(':', 1)[1], port)
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)
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('--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
@@ -1,232 +0,0 @@
"""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()
+409
View File
@@ -0,0 +1,409 @@
#!/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:')
self.api.verify_config(config, PROJECT, self.root / 'data', tag, 18080)
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
@@ -1,240 +0,0 @@
"""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
@@ -1,131 +0,0 @@
"""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()
+925
View File
@@ -0,0 +1,925 @@
"""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.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', '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):
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 == '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
@@ -1,342 +0,0 @@
"""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()
+281
View File
@@ -0,0 +1,281 @@
"""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'), 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
@@ -0,0 +1,40 @@
"""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()
+421
View File
@@ -0,0 +1,421 @@
"""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'), 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
@@ -0,0 +1,201 @@
"""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
@@ -1,493 +0,0 @@
"""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()
+173
View File
@@ -0,0 +1,173 @@
"""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)
if __name__ == '__main__':
unittest.main()
-195
View File
@@ -1,195 +0,0 @@
"""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
@@ -0,0 +1,322 @@
"""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
@@ -0,0 +1,72 @@
"""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.assertEqual(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
@@ -1,75 +0,0 @@
"""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()
+14 -16
View File
@@ -11,12 +11,9 @@ jobs:
runs-on: ubuntu-latest
env:
PR_SHA: ${{ github.event.pull_request.head.sha }}
GIT_CONFIG_COUNT: 2
GIT_CONFIG_COUNT: 1
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:'
@@ -64,23 +61,20 @@ jobs:
run: python3 -m unittest discover -s .gitea/ci -p 'test_*.py' -v
- name: Select checks
id: select
run: python3 .gitea/ci/select_checks.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
run: python3 .gitea/ci/select.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
- name: Test Docker probe
if: steps.select.outputs.probe == 'true'
run: python3 -m unittest discover -s .gitea/probe -p 'test_*.py' -v
- name: Test DEV and terminal installers
- name: Test DEV installer
if: steps.select.outputs.deploy == 'true'
shell: bash
run: |
set -e
test -f .gitea/deploy/installer.py
test -f .gitea/deploy/test_installer.py
test -f .gitea/deploy/dev.py
test -f .gitea/deploy/test_dev.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
- uses: astral-sh/setup-uv@v5
if: steps.select.outputs.python == 'true'
- uses: actions/setup-node@v4
@@ -136,6 +130,12 @@ jobs:
continue-on-error: true
working-directory: ISSSTELEON/models
run: uv run --python 3.12 pytest -q -rs
- name: indicadores_kit pytest
id: indicadores
if: steps.select.outputs.indicadores_kit == 'true'
continue-on-error: true
working-directory: ISSSTELEON/indicadores_kit
run: uv run --python 3.12 pytest -q -rs
- name: WebApi pytest
id: webapi
if: steps.select.outputs.WebApi == 'true'
@@ -143,10 +143,6 @@ jobs:
working-directory: ISSSTELEON/WebApi
run: |
tesseract --list-langs | grep -qx spa
# The measures and the cycle read dbt's compiled manifest (`DBT_MANIFEST`); `dbt parse` leaves no SQL in it.
(cd ../Transformation && uv run --python 3.12 dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect --target-path "$RUNNER_TEMP/dbt-manifest")
test -s "$RUNNER_TEMP/dbt-manifest/manifest.json"
export DBT_MANIFEST="$RUNNER_TEMP/dbt-manifest/manifest.json"
uv sync --python 3.12 --extra sql-drivers
uv run --python 3.12 pytest -q -rs
- name: WebApp install, build and tests
@@ -167,6 +163,7 @@ jobs:
EXTRACTION: ${{ steps.extraction.outcome }}
TRANSFORMATION: ${{ steps.transformation.outcome }}
MODELS: ${{ steps.models.outcome }}
INDICADORES: ${{ steps.indicadores.outcome }}
WEBAPI: ${{ steps.webapi.outcome }}
WEBAPP: ${{ steps.webapp.outcome }}
CORE_REQUIRED: ${{ steps.select.outputs.Core }}
@@ -174,11 +171,12 @@ jobs:
EXTRACTION_REQUIRED: ${{ steps.select.outputs.Extraction }}
TRANSFORMATION_REQUIRED: ${{ steps.select.outputs.Transformation }}
MODELS_REQUIRED: ${{ steps.select.outputs.models }}
INDICADORES_REQUIRED: ${{ steps.select.outputs.indicadores_kit }}
WEBAPI_REQUIRED: ${{ steps.select.outputs.WebApi }}
WEBAPP_REQUIRED: ${{ steps.select.outputs.WebApp }}
run: |
failed=0
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS WEBAPI WEBAPP; do
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS INDICADORES WEBAPI WEBAPP; do
result=${!name:-skipped}
required_var=${name}_REQUIRED
required=${!required_var:-}
+1 -4
View File
@@ -5,12 +5,9 @@ jobs:
diagnostic:
runs-on: ubuntu-latest
env:
GIT_CONFIG_COUNT: 2
GIT_CONFIG_COUNT: 1
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
+12 -21
View File
@@ -1,52 +1,43 @@
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: Free public port for the new instance
description: Public WebApp port; create a new instance or conservatively update its existing data
required: true
type: string
referencia:
description: WorkingNarrative branch, tag or full 40-character commit to install
rama:
description: WorkingNarrative branch to deploy
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:
install:
deploy:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
REFERENCE: ${{ inputs.referencia }}
CONFIRMATION: ${{ inputs.confirmacion }}
TARGET_BRANCH: ${{ inputs.rama }}
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_COUNT: 1
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/installer.py validate-dispatch
run: python3 -B .gitea/deploy/dev.py validate-dispatch
- name: Diagnose checkout origin
run: python3 -B .gitea/deploy/origin_diagnostic.py
- name: Plan, or install with the confirmation
run: python3 -B .gitea/deploy/installer.py install "$PORT" "$REFERENCE" "$CONFIRMATION"
- 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"
+1 -4
View File
@@ -27,12 +27,9 @@ jobs:
REQUESTED_PORT: ${{ inputs.puerto }}
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
RELEASE_TOKEN: ${{ gitea.token }}
GIT_CONFIG_COUNT: 2
GIT_CONFIG_COUNT: 1
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
@@ -1,43 +0,0 @@
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
@@ -1,52 +0,0 @@
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"
-4
View File
@@ -1,4 +0,0 @@
graphify-out
.claude/
samples/
ISSSTELEON-entrega/
+26 -35
View File
@@ -49,14 +49,25 @@ read only when a task points there (§5).
notes or sessions, and nothing from this repo (rule 12). No filler either: don't
restate what the code says, don't open with "This function...", no
hedging, no notes addressed to a reviewer, no emojis.
10. **Tasks fit in one session; work happens directly on `dev`.** A
10. **Tasks fit in one session; work happens on branches off `dev`.** A
task is sized so one session can finish it. Work that doesn't fit is a
composite issue listing its tasks. `dev` is the integration branch, in
this repo and in every submodule, and work happens directly on it, in
every repo it touches; no task or working branches.
this repo and in every submodule, and work happens on one of two kinds of
branch off it:
- a task branch, for a standalone task or a whole composite, named
`<type>/<issue>-<slug>` after that issue with `<type>` from its `type/`
label (for example `feature/12-timeline-repository`), merged once;
- a working branch, for a line of work that spans several issues (for
example `feature/model-proto`), with the same name in every repo it
touches; it's merged into `dev` after each completed task, and work
continues on it.
In this repo each commit cites its issue (`(#124)`); in the deliverable
tree it doesn't (rule 12), and the issue cites the commit instead.
Pushing to `dev` needs explicit permission every time.
tree it doesn't (rule 12), and the issue cites the commit and the pull
request instead. Nothing is committed directly on
`dev`. Pushing a branch needs explicit permission every time. Pull
requests into `dev` are opened by a person in the Gitea UI, or by an
agent when the owner asks for that specific pull request; agents never
approve or merge them.
11. **Every test says why it exists.** Each test module says what it covers
and which fixtures it uses; each fixture says what data it sets up; each
test says, in its docstring, what behaviour it pins down and which change
@@ -70,12 +81,6 @@ 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.
---
@@ -99,14 +104,14 @@ ISSSTELEON/ (outer) this WorkingNarrative repo: AGENTS.md, reference PD
├── models/ submodule: train/predict interface, cohorts, registry, OCR jobs
├── WebApi/ submodule: Flask API (also holds `webapi.orquestacion`, the Hamilton-based ETL graph)
├── WebApp/ submodule: Angular 22 + Material
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080) + indicadores + notebooks (isolated notebook runner)
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080)
```
Commands below are given relative to the inner `ISSSTELEON/` checkout (where
actual development happens) unless noted otherwise; `../` reaches this outer
repo's own files (`../e2e/`, `../docs_desarrollo-2.pdf`, etc.).
Dependencies (uv path deps): WebApi → Persistance, models[notebooks], Extraction ·
Dependencies (uv path deps): WebApi → Persistance, models[export], Extraction ·
models → Persistance, Extraction · Persistance → Core · Extraction → (no
internal deps). Each Python package has its own `uv` env: `cd <pkg> && uv run pytest -q`.
@@ -118,21 +123,11 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
## 3. Git state of the local working tree
- **`dev` is where work happens**, in this repo and in every submodule
(`WebApi`, `WebApp`, `models`), all on the `ISSSTELEON` org Gitea: each
piece of work lands directly on `dev` (rule 10). Other branches are not
used for new work. `indicadores_kit` is no longer a submodule: its jobs
live in `Transformation/`, the WebApi and `models` (kit exit, 2026-11-15);
the repo stays on Gitea for its notebooks.
- **Changes flow `dev` → `staging` → `main`.** Changes are made directly on
`dev`, then passed on to `staging`, and finally to `main`, which is what
is handed off for installation. `staging` and `main` are never worked on
directly, so `dev` must always contain both; the pending alignment is in
`docs/ledgers/open-items.md`.
- When SSH to Gitea is refused, the repos can still be read over HTTP
without credentials (read-only):
`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`
(`<repo>`: `WorkingNarrative`, `ISSSTELEON`, `WebApi`, `WebApp`, `models`).
Pushing still needs SSH or a token.
(`WebApi`, `WebApp`, `models`, `indicadores_kit`), all on the `ISSSTELEON`
org Gitea: each piece of work is a branch off `dev`, merged back by a pull
request (rule 10). Other branches are not used for new work. In
`indicadores_kit`, `origin` is our org copy; `upstream` is the external
fork (read-only).
- This file lives outside the submodule, in the outer WorkingNarrative repo
(`ISSSTELEON/../AGENTS.md`) — versioned there instead of the prior
gitignored-local-notes setup, so it has real history and isn't lost on a
@@ -148,10 +143,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) -> `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.
- tea `a3e1c7b90d12`, cacu `b4f2d8c01e23`, cama `c5a3e9d12f34`, governance `d6b4f0e23a45` -> `e7c5a1f34b56`
---
@@ -161,7 +153,7 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
never a `human-only` one. Read its **Done when** criteria and the
documents its **Context** field names.
- A task fits in one session; bigger work is a composite issue whose tasks
all land on `dev` (rule 10). Whatever the task doesn't resolve
share one branch off `dev` (rule 10). Whatever the task doesn't resolve
goes to a ledger in `docs/ledgers/` and is cited in the issue; the task
doesn't grow to absorb it.
- Finish by moving the issue to `status/needs-review` with the evidence
@@ -185,9 +177,8 @@ Read these only when a task points there (its `area/*` label or its **Context**
| What | Where |
|---|---|
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (the retired kit; measures now live in `Transformation/`, see `webapi.md`), `other.md` |
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (indicator computation), `other.md` |
| Live testing against real infrastructure | `docs/operations/`: `local-dashboard.md`, `fork-source.md`, `mysql-tunnel.md`, `docker-engines.md`, `seed-pipeline-verify.md`, `browser.md`, `dev-data-ingest.md` |
| Plans and decisions | `plans/` |
| What the contract promises against what exists | `docs/scope-status.md` |
| How to test and run each package | `docs/testing.md` |
| History of past sessions | `docs/history/sessions.md` (the original §6, §7, §8.1, §9 and §10 of this file) |
BIN
View File
Binary file not shown.
-4
View File
@@ -1,4 +0,0 @@
# Written by build.sh on every build.
requirements.lock
constraints.txt
.image
-35
View File
@@ -1,35 +0,0 @@
# 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
@@ -1,97 +0,0 @@
# 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
@@ -1,90 +0,0 @@
#!/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
@@ -1,59 +0,0 @@
# 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
@@ -1,33 +0,0 @@
#!/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
@@ -1,22 +0,0 @@
# 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
@@ -1,150 +0,0 @@
#!/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
@@ -1,20 +0,0 @@
"""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))
+14 -108
View File
@@ -7,122 +7,28 @@ Moved from `AGENTS.md` on 2026-11-03.
Package `Extraction/extraction/`:
- `readers/` — `DocumentReader` + `@register_reader`; `PdfReader` (text
layer, Tesseract on pages without one, embedded image detection),
`ImageReader` (PNG/JPG/multi-page TIFF), `TextReader` (fallback: plain
text, one line per newline). `combine_pages` builds one PDF from pages of
several PDFs.
- Text layer: glyphs drawn several times a fraction of a point apart
(fake bold) are deduplicated (`dedupe_chars`); every line keeps its
words with their horizontal extent (`document.Line.words`).
- OCR: a page that is mostly one scanned image is OCRed unless its text
layer is substantial (a scanner may stamp a header over the scan); a
page read with low confidence is retried at the orientation Tesseract's
OSD detects. OCR lines carry word positions too.
`ImageReader` (PNG/JPG/multi-page TIFF). `combine_pages` builds one PDF
from pages of several PDFs.
- `segmentation.py` — `Segmenter` subclasses: `auto`, `document`, `pages`
(N per record), `key` (new record when the patient id changes; pages
without id continue the previous record).
- `nlp/` — `FieldSpec` (kind, labels, choices, pattern, scan_free_text,
multiline); extractors `LabeledValueExtractor`, `PatternExtractor`,
`FreeTextMentionExtractor` (catalog terms in narrative, NegEx-style
negation). Vocabulary of captions and clinical terms in
`nlp/vocabulary.py` (extend there, no code changes); schema descriptions
also become captions, without a leading item code or what follows a
colon.
- Layout handling, all general (no form-specific rules): several captions
on one line; captions on one row with their values on the next, read
per column from word positions; item numbers (`3.-`, `b)`) belong to the
caption they precede and end the value before them; a value ends at a
wide horizontal gap once it has started; abbreviated captions (`Fech.`)
and dropped connectors (`de`, `del`) still match; a caption may run on a
few words before its colon; a label right after a connector is the tail
of a longer caption naming something else; an integer field never reads
a date.
- `nlp/discovery.py::discover_captions` — captions no `FieldSpec` claims,
found anywhere a known label could be (several per line, numbered,
heading a column) and read by the same extractor through temporary
specs.
- `template.py` — lines in the top or bottom margin that repeat (digits
exact, letters OCR-tolerant) on documents of two or more different
patients are the issuer's letterhead or footer; `DocumentExtractor`
re-extracts the affected records without them. A header repeated only
across one patient's documents is kept.
- `records.py` — `DocumentExtractor` and `RecordMerger` (same key across
multiline); extractors `LabeledValueExtractor` (captions, multi-field
lines, value under the label, fuzzy OCR-tolerant labels),
`PatternExtractor`, `FreeTextMentionExtractor` (catalog terms in
narrative, NegEx-style negation). Vocabulary of captions and clinical
terms in `nlp/vocabulary.py` (extend there, no code changes).
- `records.py` — `DocumentExtractor` and `RecordMerger` (same patient across
pages/files, most confident value wins, confident disagreements become
`FieldConflict`). `extract(..., source_fields=, record_keys=)`: values a
structured source hands over per document (trusted over the page,
including the key) and the record each document joins (documents sharing
one merge; others stay apart even for the same patient).
`ExtractedRecord.discovered` carries the captions no spec claimed.
`FieldConflict`).
- WebApi side: `connectors/document.py` + `schemas/field_specs.py` (field
specs derived from the target schema). Each row carries `documento` (the
record's pages as one PDF), mappable to a file column, and every
discovered caption as a column of its own. Corrections from the UI travel
as `overrides`; `include_pattern`/`exclude_pattern` keep or leave out
documents by their text; unreadable documents are listed in `skipped`
instead of failing the batch. Results cached per worker.
- Documents stored in columns of any tabular source (SQL table or query,
CSV, Excel, JSON): `connectors/document_columns.py::DocumentColumns`
(document columns; `name_by`, `group_by` and `fields` as a column, a
list of columns or a derived rule). Cells may hold the file as binary,
hex or base64 text (`document_bytes`). Used by a `document` source's
`sql` payload and by any import source's `documents` (see webapi.md).
- `schemas/catalog_matching.py` + `services/catalog_commit_service.py`:
opt-in per source (`catalog_fallback: true`). A discovered caption is
fuzzy-matched (`rapidfuzz`) against the project's catalog
(`core/catalogos/<proyecto>.toml`); only captions the catalog already
knows are written, straight into `procedimiento`/`observacion`, tagged
with the sentinel `fuente_tabla` `catalogo_abierto`. The import path never
mints catalog entries (the catalog is versioned with the code);
unmatched captions are counted, and the import report lists unused
captions without their values (webapi.md).
record's pages as one PDF), mappable to a file column. Corrections from
the UI travel as `overrides`. Results cached per worker for repeated calls.
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
source line and page, conflicts, image thumbnails, editable values,
document filters; each value's assertion when it isn't affirmed, the
other candidates as one-click picks, a warning on off-topic records).
- Narrative layer (2026-11-13), all in `Extraction/` (`README.md` there has
the method and references for VAR-04/VARM-05):
- `nlp/context.py`: ConText/NegEx assertions (negated, hypothetical,
historical, uncertain, presumed) with form-style answers after a mention
(`Término: NO`) and a caption without its answer read as asserting
nothing; sections from standalone headings (clinical, description,
result, history, reference text), a caption with content qualifying only
its line. Labels' values are only qualified by clinical and history
sections, so a footer date under an interpretation guide still counts.
- `FieldSpec` gained `anchors` (a generic answer like "POSITIVO" needs its
concept before it), `severity` (most severe affirmed value wins),
`negated_value` ("sin actividad epileptiforme" -> 0) and `unit`
(`MeasurementExtractor`, ranges give their midpoint). Vocabulary for all
of them, EEG terms (ACNS), narrative BI-RADS, Bethesda/LAST terms and
section headings and triggers is in `nlp/vocabulary.py`.
- `ocr_fold`: OCR look-alikes collapsed on both sides, as a fallback for
labels and choices on OCR lines only.
- Subject check: `DocumentExtractor(subject=, foreign=)` from
`vocabulary.SUBJECTS` keyed by table name (`__table__.name`, e.g.
`citologiacervical`). Only positive evidence gates: a record naming a
foreign subject and not its own fills nothing; values held back from an
off-topic segment come back if its merged record is on topic.
- Every candidate is kept (`ExtractedRecord.candidates`) with features
(no document text); `nlp/ranking.py` picks one: `HeuristicRanker`
(confidence, with hypothetical and off-topic vetoed) or `LearnedRanker`
(online logistic regression, AdaGrad + L2, blended with the heuristic
until `TRUST_EXAMPLES`; the rules' vetoes hold until then).
- `models/io/extraction_ranker.py` versions each domain's ranker as
`<domain>-extraccion` (DEV version per batch, five routines, saved
model). WebApi learns in line: `commit_sources` ->
`review_learning.learn_from_reviews` (background, one worker) from
records with `overrides` (corrected fields plus the rest as accepted).
`python -m webapi.nlp evaluate|train` scores against / trains from an
answer key (leave-one-document-out estimate first).
- The connector fills the entity's `*_nlp_version` column with
`extraction <version> + extraccion:<n>`; the review report carries
`alternatives`, `on_topic` and `nlp_version`.
- Development set: six real CaCu documents (cytology forms, HPV PCR
reports, scanned biopsies) kept outside every repository; answer key in
the session scratch only. Rules alone went from P 0.65 / R 0.85 to
1.00 / 1.00 on them, and the leave-one-out ranker estimate is 1.00; both
are fit on the same documents the rules were adjusted to.
- Limits: images are located and shown, not classified, and only stored
inside the record's PDF; the template rule needs at least two patients'
documents in the batch.
source line and page, conflicts, image thumbnails, editable values).
- Limits: NLP is rule-based (no trained model); images are located and
shown, not classified, and only stored inside the record's PDF.
### 5.4 EEG (TEA)
+1 -5
View File
@@ -1,10 +1,6 @@
# indicadores-kit
Moved from `AGENTS.md` on 2026-11-03. **Retired on 2026-11-15:** the kit is no longer a submodule or a
dependency. Its measures are dbt semantic models in `Transformation/`, answered on request by the WebApi as FHIR
MeasureReports (`webapi/kpis.py`, `webapi/fhir/`); its silver load, reference tables and follow-up list are in
`webapi/orchestration/` and `webapi/follow_up/`; its cohorts are in `models/cohorts/`. What follows describes the
division of labor that still holds and the kit as it was.
Moved from `AGENTS.md` on 2026-11-03.
### 5.6a Indicator computation — division of labor (clarified by the owner, 2026-10-19)
+16 -123
View File
@@ -14,126 +14,19 @@ Moved from `AGENTS.md` on 2026-11-03.
### 5.5 Model versioning and cohorts (ML/MLD/EL)
Versions, runs and their files live in MLflow; the cohorts a model trains on
are the kit's builds (`cohorte_armado`) or dbt's, exported to Parquet files.
- `models/models/io/tracking.py`: `TrainingRun`, one MLflow run per training.
It links the cohort build (ML-03), tags DEV/PROD (ML-02) and the git commit,
saves the model (`log_model`, `modelo_sha`; PROD refuses a class defined in a
notebook) and records each routine around training while it runs
(`log_routine(kind, record)` → `rutinas/<KIND>.json`, counts and settings,
never rows). `ROUTINE_KINDS` are the five of §5 of the requirements:
MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES,
CONFIANZA_SALIDA (`Core/core/governance/enums.py::ArtifactKind`, plus
OTRO for any other file the run keeps). `run_files`/`run_file` list and
download a run's files; a folder downloads as a zip.
- `models/models/io/registry.py`: `registry`. Status is derived
(desarrollo/candidata/produccion/retirada); `checks()` gates promotion:
ML-02, ML-03, MLD-01 (metrics, technical report), MLD-01b, MLD-03, **ML-01a
(all five routine records, written by the run) and ML-01b (the saved
model)**. Only what the training run itself wrote counts: nothing can be
uploaded to a version. `lineage()` returns every file of the run and the
routine records; `artifact()` downloads one (ML-01b).
- `models/models/cacu/cin2_logistic/model.py`: Hamilton nodes `sampling`,
`missing_data`, `analytic_method`, `class_balance`, `output_confidence`
(and `routines`, which gathers them) record what this training did:
the temporal split, missing predictors as the `(none)` category,
coefficients, class counts (no reweighting) and a calibration table.
- Routes: `/governance/model-versions*` (list, register, reports, lineage,
checks, promote, retire) and
`GET /governance/model-versions/<d>/<s>/<v>/artifacts/<path>` (download).
WebApp version dialog: checklist, cohort, the five routines (recorded or
missing, each viewable), the run's files as downloads, reports, and
"Probar en un notebook".
- Removed 2026-11-13: uploading a file of any kind to a version (it let a
hand-picked file satisfy ML-01b), and the ONNX checkpoint support with it
(`ONNX_CHECKPOINT`, `inspect_onnx_metadata`, the `export` extra). Nothing
produced an ONNX file and predictions never used one.
### 5.6 Notebooks run on the server (ML-01a, ML-04, ML-05)
A Jupyter notebook uploaded from the WebApp runs against one exported cohort
build, isolated from the server, for development experiments.
- `models/models/pipelines/experiment.py`: `start` creates an MLflow run in
`<domain>-<scenario>/experimentos`, tagged with the notebook's name and
content hash, the build's file (`cohort_reference`), the chosen version and
the code version, and stores the notebook without outputs. `execute` hands
the job to an executor, then stores the page (`report/<name>.html`), what
was imported (`importado.json`) and, if it failed, `error.txt`; the run is
tagged `sandbox: contenedor|local`. Status: en_curso, terminado, fallido,
interrumpido (running past `NOTEBOOK_JOB_TIMEOUT` + 30 min).
- `models/models/io/notebook_jobs.py`: the job folder
(`<NOTEBOOK_JOBS_DIR>/<run_id>/`: `notebook.ipynb`, a copy of the build's
file `cohorte.parquet`, the chosen version's saved model `model/`,
`job.json`), assembled aside and renamed into place, and handed to
`NOTEBOOK_RUNNER_UID`. `run_job` runs it on the `python3` kernel with an
environment built from the job alone: the build's file, `MODEL_PATH`, an
MLflow store inside the job (`mlflow.db`, `artefactos/`), every
`*_DATABASE_URL` set to `sqlite://`, HOME and temp folders inside the job;
writes `page.html` and `result.json`. Executors (`EXECUTORS`,
`register_executor`): `local` runs it in the API's process (development,
unisolated); `contenedor` leaves it for the runner and waits
(`NOTEBOOK_JOB_TIMEOUT`, 6 h). `NOTEBOOK_EXECUTOR` picks one; the default is
`contenedor` when `NOTEBOOK_JOBS_DIR` is set. `serve` (`python -m models
notebooks serve`) is the runner's loop; a job is claimed by creating
`en_curso/` in it.
- `models/models/io/notebook_import.py`: copies what the notebook trained
into the platform's MLflow. Only `<domain>-<scenario>` experiments of the
job's domain; each run becomes a new DEV run with the real cohort tags,
`notebook.run_id`, the code version and a recomputed `modelo_sha`
(`kit.armado_id` and the notebook's own `modelo_sha` are dropped); versions
come across as DEV, never with an alias. The store is opened from a copy,
files are walked without following links and must sit inside the job
(`read_job_file`, `inside`), and `NOTEBOOK_MAX_IMPORT_MB` (500) caps them.
All of it exists because the trusted side reads files an untrusted
notebook wrote.
- `models/models/notebook.py`: the API inside a notebook. `experiment()` →
`.cohort()`, `.lineage()`, `.model()` (the job's copy, `MODEL_PATH`),
`.training_run()` (a DEV `TrainingRun` linked to the build),
`.register(run)`.
- `models/models/io/rendering.py`: renderers as classes (`RENDERERS`,
`register_renderer`): `quarto`, and `jupyter` (`nbclient` + `nbconvert`,
the `notebooks` extra, which WebApi installs). `NOTEBOOK_RENDERER` picks
one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT`
(1800 s per cell).
- `models/models/io/storage.py`: `exported_builds(root, domain)` and
`build_file(root, url, source, build)`, read from the files alone.
- Deployment: service `notebooks` in `docker-compose.yml` and
`dist/docker-compose.yml`, the webapi image with command `notebooks`
(`WebApi/docker-entrypoint.sh`): `network_mode: none`, `read_only`, tmpfs
`/tmp`, user 10001, `cap_drop: ALL`, `no-new-privileges`, memory/CPU/PID
limits, only the jobs volume at `/trabajos`. webapi mounts the same volume
at the same path (the import checks paths as the runner wrote them) with
`NOTEBOOK_JOBS_DIR=/trabajos` and `NOTEBOOK_RUNNER_UID=10001`.
- WebApi (`webapi/blueprints/governance.py`): `GET /governance/cohort-files`,
`GET|POST /governance/experiments` (multipart `file`, `domain`, `scenario`,
`url`, `source`, `build`, `version?`; 202, executed in a thread pool,
`WEBAPI_NOTEBOOK_WORKERS`, default 1),
`GET /governance/experiments/<run_id>`, `.../page` (served with
`Content-Security-Policy: sandbox`), `.../artifacts/<path>`.
- WebApp: Gobernanza tab "Notebooks" (`experiments-panel`, polls while a run
is in progress, flags "Sin aislar" runs) and `notebook-run-dialog` (also
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).
- Governance DB tables (`Core/core/governance/`): ExtractionRun,
CohortVersion, CohortMember, CohortExclusion, CohortExclusionCount,
ModelVersion, ModelArtifact, ModelPrediction.
- `models/models/registry.py` — `ModelRegistry`: register, attach reports,
upload artifacts (checksummed, ONNX validated), status derived
(desarrollo/candidata/produccion/retirada), `checks()` gates promotion
(ML-02, ML-03, MLD-01, MLD-01b, MLD-03, ML-01b), retire, lineage, compare.
- `models/models/cohort.py` — `CohortBuilder`, `ExclusionCriterion`,
`@register_cohort_builder`. **No concrete builders exist**: clinical
criteria are not defined in the requirements document, so production
promotion is impossible until a scenario is registered.
- `models/models/prediction.py` — `PredictionService` persists predictions
tagged with the active version.
- Routes `/governance/model-versions*`, `/governance/artifacts/<id>/download`,
`/governance/cohort-scenarios`, `/governance/cohort-versions`. WebApp
model-version detail dialog and cohort build menu.
-72
View File
@@ -23,76 +23,4 @@ Moved from `AGENTS.md` on 2026-11-03.
`merge_duplicates` (opt-in, `merge_duplicates: true` on `/imports/commit`)
combines rows of different sources sharing a natural key **before**
validation (first source wins, disagreements reported as warnings).
- **SQL sources** — `server.host` tolerates pasted forms (`host\instance`,
`host,port`, `host:port`, JDBC/URI strings); a named instance without a
port is left for the server to resolve. A user query is wrapped as a
derived table, so a trailing `ORDER BY` that no TOP/LIMIT/OFFSET needs is
dropped (SQL Server refuses it there). Every preview lists, in
`document_columns`, the columns whose cells hold files.
- **Mapping beyond one-to-one** — an import source may carry, besides
`column_mapping` and `defaults`:
- `derived`: `{field: rule}` computed from source columns
(`imports/mapping/derived.py`; one `Derivation` class per operation plus
`@register_derivation`): `column`, `concat`, `template`, `split`,
`coalesce`, `extract`, `map`, with an optional `case`. Short forms: a
column name or a list of columns. `GET /imports/derivations` describes
them, and the WebApp builds its forms from it.
- `documents`: columns holding documents (`DocumentColumns`, see
extraction.md), with `group_by`, `name_by`, `fields`, `file_field` and
the extraction settings. Values the mapping takes from the row's own
columns are trusted over the page; then mapping and `derived` run again
over each record's namespace (the rows' columns plus every field and
caption its documents print), and extracted fields fill what's left.
Rows without documents pass through mapped.
- `catalog_fallback: true` to opt in to the catalog path (extraction.md).
- Order: mapping and `derived` (one field can't be fed by both), document
extraction, then `defaults` for anything still empty.
- **Previews** — `POST /imports/mapped-preview` (`{source, limit}`: rows as
they would be written); `POST /imports/sources/document/columns` (a source
with `documents`: its columns plus the documents' fields and captions, as
a preview with suggestions); `POST /imports/sources/document/extract`
also takes `{source}` to review a mapping's documents.
- **Import report (Bitácora de cargas)** — `imports/audit.py`, counts and
shapes only, never record values. Per source it also lists the captions
its documents print that nothing used (`etiquetas_sin_usar`, captions
with how many records print them, from `WEBAPI_REPORT_MIN_COUNT` up;
`etiquetas_sin_usar_poco_frecuentes` counts the rest).
- Routes in `webapi/blueprints/imports.py`; `GET /api` lists every route.
- 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.
-19
View File
@@ -2892,22 +2892,3 @@ code, given it adds a service to operate/secure? Lean toward only doing
this if MLflow's web UI becomes independently useful for the team (e.g.
browsing experiments/artifacts outside this app), not for the code
reduction alone.
## 11. Indicator recompute moved from polling to a filesystem watch, 2026-11-13
`WebApi/webapi/indicadores_vivos.py`'s loop used to just sleep for
`INDICADORES_INTERVALO_S` (default 20s) between checks of the
`pendiente/<dominio>` marker directory. Replaced the sleep with a
`watchdog` observer on that directory: any marker write now wakes the loop
immediately (verified in a standalone smoke test: pickup in well under a
second against a 100s fallback interval), and `INDICADORES_INTERVALO_S`
stays only as a safety net for a missed or coalesced filesystem event, not
the normal reaction time. `ColaDeRecalculo`'s marker/state semantics
(`solicitar`/`tomar`/`atender`, the coalescing of requests that arrive
mid-run) are unchanged; only how the loop wakes up moved. `watchdog` added
as a WebApi dependency (`uv add watchdog`, pure Python, inotify on Linux).
This is the live mechanism G-DBT-3 (`docs/ledgers/grooming.md`) describes
as "it drops a marker and the `indicadores` service runs the domain's
cycle" — that description still holds; only the wake-up trigger inside it
changed, not the cycle itself.
-28
View File
@@ -62,31 +62,3 @@ Something went wrong or was surprising while doing a task. Format and plan codes
- **Decides:** owner.
- **Decision:** 2026-11-05, owner: no past-date rebuilds for now, drop it from the export; a dbt snapshot may
replace it in the future.
### I-DBT-3. `cin2_logistic.predictors()` crashes the whole training run on a cohort member with a biopsy but no citología — high · open
- **What happens:** `predictors()` builds each member's index sample from `citologia` rows only
(`model.py`, lines ~61-68): `sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] ==
cohort["fecha_indice"])]`, grouped by `pac_id`. For a cohort that includes a member with a `biopsia`
row but no `citologia` row at all, `sample` comes back empty; the following
`cohort.merge(sample, left_on="pac_id", right_index=True)` degenerates, and the resulting frame's
implicit index ends up also named `pac_id` on top of the `pac_id` column already there. The later
`pivot_table(index="pac_id", columns="tipo", values="valor_codigo", ...)` then raises
`ValueError: 'pac_id' is both an index level and a column label, which is ambiguous`, which is
unhandled and kills the whole run — not just that member's row.
- **Evidence:** `docker compose ... run --rm entrenar` against a CaCu cohort containing one member with
a `BiopsiaCervical` row (imported through the "documents in columns" connector) and no
`CitologiaCervical` row for that patient. Full traceback bottoms out at
`models/models/cacu/cin2_logistic/model.py:68`, in `predictors`, inside the `pivot_table` call.
- **Consequence:** a cohort build with even one biopsy-only member (plausible: direct referral,
partial/migrated history, a document-column import that only carries pathology results) blocks
`entrenar` entirely for every member, not just that one. The model can't be trained at all until the
offending member is removed from the cohort or the code tolerates the empty-sample case.
- **Proposal:** make the empty-`sample` case produce `MISSING` predictors for that member instead of a
malformed frame, e.g. reset the index after the merge (`results = cohort.merge(sample, left_on="pac_id",
right_index=True).reset_index(drop=True)`) before the `pivot_table` call, or build `wide` from an
explicit left-join against `members["pac_id"]` so a member with zero sample rows still gets a row of
`MISSING` rather than disappearing and corrupting the frame's index naming. Add a unit test with a
cohort containing one biopsy-only, no-citología member to pin this down.
- **Decides:** owner (models package).
- **Decision:**
-43
View File
@@ -293,46 +293,3 @@ Proposals that come up while doing a task and aren't resolved inside it. Each on
from the indicator catalog and the gold YAML; one Hamilton node per indicator reads that declaration,
as a MetricFlow `ratio` metric would.
- **Issue:** #162
## G-GEN-1. Source terminology as catalog tables, editable from the UI
- **Where:** `Core/core/catalogos/<dominio>.toml` (`codigos_hospital`, `etiquetas_fuente`, `alias`), the silver
load's enum maps, `WebApi/webapi/orchestration/reference/source_mapping.py` (the mapping's rules) and
`observacion_clinica.valor_fuente`.
- **What happens:** how a lab provider or a medical-record header writes our codes lives in the catalog's TOML
and in code. A provider change (new captions, spellings or test codes) needs a commit, a release and a deploy,
and a deploy would overwrite any change made outside git.
- **What it conflicts with:** rule 4 (two new tables); rule 2 (versioning has to work on every engine, so SQL
Server's temporal tables can only be an add-on).
- **Proposal:**
1. Our codes (`cat_estudio`, `cat_resultado`, `cat_valor`) stay in the TOML, reviewed in git.
2. How each source writes them moves to two tables, the database being their system of record:
`cat_sistema_fuente` (who sends the data, by `fuente_tabla` and validity dates) and `cat_mapeo` (FHIR's
ConceptMap: `clase` estudio, etiqueta or valor; the form and its normalized form; target; validity;
`registrado_por`, `registrado_en`, `motivo`). Append-only; a deploy only inserts missing seed rows.
3. The mapping is a partial, non-injective function `(system, resultado_id, normalized form, date) -> valor_id`
into `cat_valor`. `source_mapping.check_function` already enforces it on the TOML; the UI and the API
apply it on every save. `source_mapping.resolve` is the remap's rule: no mapping or two disagreeing
mappings give no code, and the observation goes back to the out-of-catalog queue.
4. A remap step on every cycle and on demand rewrites only `valor_id` where the code changes, under a
`carga` of its own (`conocida_en` keeps reports cut before it reproducible). A new caption or study code
needs a re-extraction or a reload instead.
5. A queue screen (source text with no code), a mappings screen per system, a curator role, and a
`ConceptMap` endpoint.
6. Versioning: validity dates in the table (what the pipeline reads, every engine); in production SQL Server,
system-versioned temporal tables on both tables for the edit audit, a SQL Server-only revision that's a
no-op elsewhere.
- **Open questions:** where a report records the mappings it used (`toml_sha`, `huella` or `parametros`);
mappings per system only or also global; whether the temporal tables are in scope now.
- **Evidence:** draft and SQLite demo in `mock/borradores/catalogo-mapeo/` (`PROPUESTA.md`, `01_tablas.sql`,
`02_demo.py`): seeding from the TOML changes 0 stored observations; a new lab's 5 unmapped spellings land in
the queue and, once mapped and remapped, reach dbt's timeline, the stratifiers and the invasive-cancer event
unchanged.
- **Found in:** #163 (CaMa values read from reports), 2026-11-13.
- **Status:** approved by the owner on 2026-11-13 and implemented on `feature/163-source-terminology` (every
repository rebased on `dev`): ISSSTELEON `66c4ba5` (Core tables), `74eb5a4` (a revision per domain),
`14dff24` (`SourceMappingRepository`), `d6e2c68` (dbt's `vigencias_sin_traslape` on `cat_mapeo`),
`72d092d` (pointers); WebApi `64d3d72` (`source_mapping`: `check_function`, `resolve`), `73cbf0c` (seeding in
the `catalogs` step, `register` checking the function on write). Layers 1 (write check), 2 (`UNIQUE` and
check constraints) and 3 (dbt test) are in; pandera is left for a bulk import of mappings. Still open: loads
read the TOML's aliases, not `cat_mapeo`; the remap step; the UI screens; the `ConceptMap` endpoint;
migrations verified on SQLite only.
+3 -284
View File
@@ -11,288 +11,7 @@ Moved from `AGENTS.md` §5.7 on 2026-11-03. Each item can become an issue.
- No authentication/authorization on WebApi; SQL credentials travel from the
browser on each call (mitigated by `SqlSourcePolicy`).
- Cross-field validation rules not implemented in the import schemas.
- Document NLP (narrative layer and learned ranker, see
`docs/architecture/extraction.md`), still open:
- Only measured on six real CaCu documents, the same ones the rules were
adjusted on; a held-out set (ideally 30+ per report type, with an answer
key written by someone else) is needed for an honest score. EEG,
mammography and breast biopsy vocabulary has never seen a real report.
- The ranker trained on those six lives only in a scratch MLflow store;
on the server it starts empty until `python -m webapi.nlp train` is run
with a key, or reviewers correct imports.
- `<domain>-extraccion` versions can't pass ML-03 (no cohort: they learn
from documents), so they can't be promoted; extraction uses the latest
DEV version. Needs a decision on how governance treats this model.
- Learning runs in one background thread per WebApi process; with several
gunicorn workers two batches can continue the same version and both
register, the second not including the first's examples.
- A correction teaches only if made in the review dialog before
committing (it travels as `overrides`); fixing a value later in the
database teaches nothing.
- No pretrained Spanish clinical model; it would be one more
`FieldExtractor` whose candidates the ranker weighs, once a held-out
set exists to show it helps.
- Colposcopy (Reid, Swede) has no columns, so it stays as text.
- No trained NLP model (options discussed: pretrained Spanish clinical
model as an extra `FieldExtractor`, plus learning from review corrections;
needs real anonymized reports to evaluate).
- Possible DICOM connector for mammograms (`pydicom`, fits `mast_dicom_blob`).
- A source may hold a biopsy and the cytology that led to it as separate
orders with nothing linking them (no shared id in the rows or in the
documents). The CaCu confirmation indicator only counts the biopsy a
cytology originated (`BiopsiaCervical.cit_id`), so such biopsies read as
"sin biopsia aún". Option: a general import rule that fills a link with
the same patient's latest record of the parent kind dated on or before
the child's date; needs a decision on the rule and its time window.
- Which printed date counts as a cytology's sampling date is a per-source
mapping choice (request or reception date), not code.
- `documents.group_by` takes the source's own columns (or rules over
them), not values read from the documents.
- A user query starting with `WITH` can't be wrapped as a derived table on
SQL Server (`connectors/sql.py::_text_subquery`).
- Compose ports and the `ng serve` proxy target are fixed in
`docker-compose.yml` and `WebApp/proxy.conf.json`; neither reads an env
var yet.
- The template-line rule (`Extraction/extraction/template.py`) needs at
least two patients' documents in one batch; a single document still
reads its letterhead.
- Branch alignment, as of 2026-11-13: `dev` was pushed in all six repos
and contains `staging` and `main` everywhere, except that
`WorkingNarrative`'s `main` keeps one merge commit with identical content.
`staging` and `main` are behind `dev` until the next promotion. SSH to
Gitea refuses the local key; pushes went over HTTP with the API token.
- Notebooks run in the `notebooks` container (no network, read-only system,
uid 10001, no capabilities, only the jobs volume), and what they train is
imported by trusted code (`models.io.notebook_import`). Still open:
- The app has no login, so anyone who reaches it can upload a notebook,
and its page (which may print cohort rows) is readable by anyone.
- The container was validated with `docker compose config` and tested as a
separate process, not yet started as a real container.
- Local development (`NOTEBOOK_EXECUTOR=local`, the default without
`NOTEBOOK_JOBS_DIR`) runs notebooks unisolated in the API's process; runs
say so (`sandbox: local`, "Sin aislar" in the WebApp).
- A WebApi worker that restarts while waiting leaves its run "en curso"
until it shows as "interrumpido" (job timeout + 30 min) and its job
folder behind; nothing picks the result up again.
- A version registered over `POST /governance/model-versions` has no routine
records or saved model, so it fails ML-01a/ML-01b and can't be promoted;
production versions come only from training code in `models`.
- ML-01b is met by downloading a run's files; there is no portable model
export (ONNX support was removed 2026-11-13 as unused).
- The notebook tab needs exported cohort builds on the server
(`python -m models cohorts export ...`), and the WebApi image must be
rebuilt to get the Jupyter libraries (`models[notebooks]`).
- `cin2_logistic`'s routine records (`model.py`) are the only real ones;
any new model has to add its own five, or it can't be promoted.
### TEA redesign (#163, branch `feature/163-tea-redesign` off `refactor/kit-exit`), 2026-11-12
Left open by the implementation of `plans/kit-exit/tea-redesign.md` (all but the WebApp):
- §12.6 not done: CaCu's risk as `RiskAssessment`, imports as `transaction` Bundles with `AuditEvent` and
`Provenance`, OCR jobs as `Task`, and CaCu's follow-up list as `EpisodeOfCare`. The old routes stay; removing
them, and `/<domain>/indicadores`, needs the owner (§12.9).
- §12.2: suppression (`data-absent-reason: masked`) and confidence intervals wait for #73.
- The new Alembic revision (`f2b6d1e8c934`) was checked upgrade/downgrade/upgrade on SQLite only; MySQL,
PostgreSQL and SQL Server untested (rule 7). `dbt build --select tea` passed on SQLite only; the SQL Server 2016
VM and `e2e/sqlserver2016` (piece 11 of `tea-port.md`) not run. `tea_meses_cumplidos` has a separate `floor` path
for the other engines, untested there.
- Assumptions to confirm: the metric references live in dbt's var `tea` (an ephemeral model), not a seed, because
the cycle doesn't run `dbt seed`; effect texts and electrode positions are in `WebApi/webapi/fhir/tea_eeg.toml`.
An EEG without any criterion written is `SIN_ANALIZAR`, a third category of M29 (the §10 question). M25's units are
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: **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`.
### Kit exit integrated on `dev` (branch `feature/kit-exit-integration`), 2026-11-15
Left open by bringing `feature/163-source-terminology`, `feature/163-tea-redesign` and the CaMa dashboard's
presentation onto one branch:
- `cat_mapeo` is seeded by the `catalogs` step but no load reads it yet: the CaMa silver load still takes captions
and aliases from the catalog's TOML (`webapi/orchestration/reference/catalogs.py`); the remap step, the mappings
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. **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`). **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
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.
@@ -0,0 +1,198 @@
# CaMa dashboard integration coordination
## Patient identity follow-up — 2026-11-13 (proposal for Claude)
Remote tips were checked: WorkingNarrative `92d3a65797b1a07c0bd3bd737f9af967acc876ee`, ISSSTELEON `ec6d3e6cd7b8126423664b694ff40c479ceb1613`, WebApi `8b47f1522de0efd29f6c66c4b13df48f51bf8381`, WebApp `2e0938628c85fae76fc41384edfd887c808cf53b`, kit `f4be01b3127588e98c02ff96822098138bd5b1f5`. The `feature/seguimiento-pac-id` tips are kit `23957cc8d2ee9176e5800bc0ab3cd7ea31408a41`, WebApi `854720066fb4e14f171f0c4a0034be5fd96a5623`, WebApp `bfbd11beae578beb483c46ee5052f1efbc6b3ba1`; no such branch exists in the two parent repositories. The kit branch returns `str(pac_id)` under the legacy name `id_seudonimo`, WebApi removes the salt argument, and WebApp uses that value for CaCu risk. These are not ancestors of the dashboard tips. Their intent needs integration without reverting CaMa work.
`pac_id` is the staging patient primary key, copied to each domain's indicator `persona` and used by cohort/risk records. It is stable within the retained domain database; it is not proven globally unique across CaCu, CaMa and TEA databases or installations. `pac_id_hospital` is a separate source identifier; do not expose it or equate independently assigned domain IDs. TEA redesign has its own `pacientes.pac_id` and patient-linked records; an episode or order is not a patient identity. Preserve domain context and any episode identifier separately.
TEA redesign WebApi `461d651` currently emits a salted pseudonym as both FHIR `Patient.id` and `EpisodeOfCare.id`; the episode references that patient and the summary endpoint resolves the pseudonym against the cohort. That shared value reflects the current one-row-per-child projection, not proof that patient and episode are the same entity. A future migration must update references and lookup together, retain compatibility for existing FHIR clients, and avoid assuming one episode per patient forever.
The CaMa token is currently checked by `patient_access()` on list, detail and export; it is therefore an access gate as well as a proxy credential, not a pseudonym secret. No common authentication hook was found in the current WebApi tree. The nginx injection grants access to callers of that proxy rather than identifying a user. Removing it requires an explicit common boundary or a clearly scoped synthetic-only access decision; do not silently open patient endpoints while removing the secret. The normal installer retains `.env`; `deploy-dev` renders and persists a controlled Compose and overrides the WebApi entrypoint with gunicorn. A missing or invalid secret/token with the synthetic switch set raises in `create_app`, so it can prevent `/health`; this is a code-based failure mode, not a diagnosis of 18080 without its logs.
Proposed executable contract for review: in source-backed CaMa list rows use `pac_id: "42"` (decimal string), and advertise the same key in `columnas`; `GET /cama/pacientes/42` with the exact `cohorte`, `escenario`, `revision`, `corte`, `meses` and filters returns the selected row as `item`; export with the same context returns that row with the same `pac_id`. Do not derive identity from a row index, page, cutoff, filter or revision. A changed revision returns 409 before resolving the patient. For CaCu, reconcile the existing `id_seudonimo` compatibility field and the `GET /cacu/pacientes/42/riesgo` consumer with a source-backed `pac_id`; for TEA keep patient and episode separately scoped and do not invent IDs when its source cannot provide one. This is a proposal, not yet an agreed or implemented contract. Claude: please confirm field types, transition handling and UI ownership, and record the final WebApp SHA and tests here.
Codex isolated work in `C:/dev/patient-identity`: kit cherry-pick `7237e36` and WebApi cherry-pick `2ca8623` port the CaCu branch pair while retaining the old CaCu field name. WebApi draft `eeb55c4` emits CaMa `pac_id` as described, uses the shared database reader, and keeps the token gate fail-closed until access is resolved. These are drafts, not publishable gitlinks. Claude: please adapt and test the WebApp against this proposed CaMa field and the CaCu risk consumer, then record your final SHA. Keep TEA's FHIR Patient and EpisodeOfCare references internally consistent when that branch is integrated later.
Further local checks: 16 kit follow-up tests and 25 WebApi CaMa/CaCu tests passed (WebApi tests used the Windows-only lock shim). On a disposable synthetic SQLite copy via a loopback test proxy, `/health` succeeded; all 43 CaMa rows reconciled across seven-row pages, each patient detail and the full export, while an earlier cutoff was empty. The test proxy injects its own token and does not validate the image, nginx or the deploy-generated Compose. Port 18080 on `10.0.10.41` did not accept a connection from this machine; no host logs have been inspected.
An unsuppressed six-row BI-RADS filtered export was also a subset of the unfiltered export with identical rows; an obsolete revision returned 409.
The current isolated backend draft also passed 90 CaCu/TEA indicator regression tests with that same Windows-only shim. It does not establish browser, Linux container, authorization, deployment or retained-configuration acceptance.
If the Action rejects an already unhealthy installation before activation, it has not performed a deployment: inspect the installation record, service state and WebApi logs on the daemon host without printing environment values. Identify the last known healthy Compose, image IDs and matching configuration in the retained deployment or the relevant `.archive/<operation>/deploy`; verify its `/data` bind points to the existing instance data and recover those services with the operator's approved procedure. Do not reinstall, reseed or restore a database over live storage. Check `/health`, image identity, mounts and data integrity before retrying. If a previous update reached `update_failed` or `updating`, preserve its record and use the documented recovery/reconciliation procedure appropriate to its recorded phase; do not simply change the status to bypass the guard. A previously healthy Compose alone is insufficient if the candidate already modified persistent data: validate the backup and compatibility first.
The previous token/secret and host-acceptance instructions below describe the old candidate and are superseded for planning by the identity follow-up; they are not evidence of the new composition. Local Docker is unavailable and `127.0.0.1:18080` did not answer in the sandbox; host logs and image validation remain unverified.
Status: in progress. This is not a release or deployment approval.
The integrated WebApp is at `http://127.0.0.1:51850/indicadores/cama`, against the synthetic API at port 51849. Both ports answered on 2026-11-13. WebApp `2e0938628c85fae76fc41384edfd887c808cf53b` merges Claude's `0acee49de2098b2f9d06607f7d374091a5f4b764` with the integration containing proxy commit `c06cce20dfe2718f0a009a8c0af4a58d12b5671a` and the contract fixes; its tree is identical to tested commit `3783505dbdbbda340560f78d5b77d8707fd91bd4`. Use cutoff `2026-11-13` for data and `2026-10-20` for the pre-load empty cohort. The Linux image test remains outstanding.
Local commits: WebApi `7bc214b50c4b151f3e6cc818e2860971407943ac` (identity) and `8b47f1522de0efd29f6c66c4b13df48f51bf8381` (reader and follow-up); WebApp `2e0938628c85fae76fc41384edfd887c808cf53b`; ISSSTELEON `ec6d3e6cd7b8126423664b694ff40c479ceb1613` pins both. These are prepared for child-first publication. Run the isolated Linux image check below before updating 18080.
## Executable integration endpoint for Claude
The loopback-only synthetic test proxy is `http://127.0.0.1:51849`. It runs this checkout's WebApi against `C:/dev/CaMa-Lote1-dashboard/integration-data/cama.sqlite`, a separate SQLite backup. It supplies a temporary access token on the server side; Angular must not send or store that token. The pseudonym key is retained separately in `integration-data/pseudonym-secret`. Do not use this proxy as a production access boundary. Port 5059 belongs to a different server and must not be used for this test.
To restart in PowerShell, from `C:/dev/CaMa-Lote1-dashboard/WebApi`:
```powershell
$env:PYTHONPATH='C:\dev\CaMa-Lote1-dashboard\WebApi'
$env:PYTHONUTF8='1'
& C:\dev\ISSSTELEON-CaMa-TEA-DEV\ISSSTELEON\WebApi\.venv\Scripts\python.exe examples\serve_cama_integration.py --database C:\dev\CaMa-Lote1-dashboard\integration-data\cama.sqlite --secret-file C:\dev\CaMa-Lote1-dashboard\integration-data\pseudonym-secret --port 51849
```
Proxy `/cama`, `/cacu`, `/tea` and the other API routes from the Angular dev server to that endpoint. `GET /cama/analisis/indicadores?corte=2026-11-13` returns six visible BI-RADS groups; `GET /cama/seguimiento?corte=2026-11-13&meses=0` returns 43 rows. The original 37 historical rows have been supplemented in this disposable copy with six invented recent mammograms, so the ordinary three-month window returns six rows. Their load timestamp is synthetic, taken from the existing test load. The added rows do not alter the stored indicator reports; those reports must not be interpreted as recalculated from these added records. The local fixture script is `C:/dev/CaMa-Lote1-dashboard/integration-data/add_recent.py`. `corte=2026-10-20&meses=0` returns an empty unfiltered page because the load was later.
List replies include `cohorte`, `revision`, `escenario`, cutoff, window, filters, columns, pagination and rows. For detail and export quote the returned context with the same cutoff, window and filters: `/cama/pacientes/<id>?cohorte=cama_birads_v1&escenario=diagnostico&revision=<revision>&corte=2026-11-13&meses=0` and `/cama/seguimiento/exportacion` with the same query. The detail's `item` is exactly the selected list row; export has `total_items` and `items`. Every row includes the clinical report dates and separate `*_carga_inicio` provenance timestamps. No priority or follow-up status is inferred from an incomplete record.
The integrated WebApp is served at `http://127.0.0.1:51850` with its API paths proxied to 51849. To restart it from `C:/dev/CaMa-Lote1-dashboard/WebApp`, run `& C:\dev\tools\node-v24.21.0\node.exe node_modules\@angular\cli\bin\ng.js serve --host 127.0.0.1 --port 51850 --proxy-config C:\dev\CaMa-Lote1-dashboard\integration-data\proxy.json`. Run `python e2e/cama_followup_probe.py` from this repository to check HTTP reconciliation through that proxy. On this copy, the probe reconciles the regular six-row window, all pages, detail and export, then an unsuppressed Analysis group and an early empty cutoff. The nine CaMa measures returned data rows for `2025-S1`; the BI-RADS matrix returned 36 cells. These HTTP checks do not replace visual inspection or downloaded-file acceptance.
On the final integrated checkout the production Angular build passed and a focused run passed 145 tests for cohort, selection, labels, record and exports. A separate run passed 97 tests for domain switching, filters, catalogs and indicator panels. The current WebApi passed 13 focused cohort/runtime tests; the prior same-SHA CaCu/TEA regression passed 101 tests. The local installer simulation passed 49 tests. A static check confirms the Compose token wiring and nginx template paths, but does not prove nginx substitution or Linux container startup.
Browser result relayed by the user from Claude: the revised three-month habitual view showed six records and whole-cohort view 43. Table and XLSX identifiers matched in order, and the eight-page PDF preserved that order. All six Analysis groups opened the record and exported files matching the table, with focus returned to “Ver pacientes”. The pre-load empty state disabled exports. Resumen and Histórico loaded four values and eight figures. At 360 px the five views had no horizontal scrolling. CaCu and TEA opened their three sections, though this integration copy does not provide their data. Claude's validated working-tree changes were integrated locally; the 404 unavailable message was added afterwards and is covered by a focused automated test. Linux container validation remains outstanding.
## Composition
On 2026-11-13 the remote `dashboard-test` tips matched WebApi `1d5f1e0cc4c92d0184160191952afea07449bcc7`, WebApp `2b0f6dfbed3e4162a7c96c1a417897c7a1dc9bb5`, ISSSTELEON `8c9949ff3590d8407900281323d6224a6d2688c0`, and WorkingNarrative `5e4ed74e99b3f2f9762e9c1af9940b4c0773bff7`. The parent gitlinks match these child tips. Lote 1 is published on these branches; that does not establish what is deployed on port 18080. WebApp `features/cama-mock` was inspected at `c076e1e7a99c5937866560b0bb832578b4fa56b7`.
## Contract and ownership
- Backend owns the cohort, eligibility, cutoff, links, availability, revision, authorization, suppression and provenance. Angular owns presentation labels and exports from the server's selected rows; it must preserve codes for filters. The existing cohort endpoint returns raw BI-RADS and age codes, and Angular's `etiquetarCohorte` supplies display labels. `biopsia_fecha` in this contract is the report date, not a specimen date. `biopsia` is the source histopathology code, not a validated clinical diagnosis label.
- The existing CaMa catalog confirms display labels for `BENIGNO` → `Benigno`, `CARCINOMA_IN_SITU` → `Carcinoma in situ`, `CARCINOMA_INVASOR` → `Carcinoma invasor`, and `DESCONOCIDO` → `Desconocido`. The WebApp now applies them to cohort rows and retains the original as `biopsia_codigo`, so the table, patient card and files use the same display value. Unknown source values stay unchanged. Clinical and load dates retain distinct meanings.
- `GET /cama/analisis/indicadores` needs `corte` and returns a revision. Both regular follow-up and Analysis use the configured reader and the same selection logic. Regular follow-up returns a revision; for subsequent pages, detail and export send that context with the same cutoff, window and filters. A changed revision is 409; small filtered selections, including empty ones, are 403. An empty unfiltered cohort is 200. The threshold is five.
- The habitual CaMa view initially requests the three-month window without a revision; the server supplies the cutoff and cohort context, which the client retains for subsequent pages and exports. The user can select the whole cohort (`meses=0`). A 404 or 503 is displayed as unavailable and never triggers a switch to another source. A 409 on a habitual list retries the same query once without the old revision; a repeated 409 is shown. A selected group from Analysis retains its original revision and requires refreshing the analysis after 409. The patient card uses the selected list row and its announced column labels; it keeps that row, cutoff and selection while open and on return. It does not call the detail endpoint. Backend detail remains available and is checked independently against the same selection.
- The source is current silver procedures and observations, with clinical dates and load timestamps checked against the UTC cutoff. The order must link biopsy and selected mammogram and belong to the same patient. Silver does not preserve overwritten versions, so this is not a reproducible historical snapshot. A report can exist before its result is available. Provenance fields are load timestamps, not clinical event dates. Do not label them as clinical dates.
- On the read-only local synthetic fallback `C:/dev/ISSSTELEON-CaMa-TEA-DEV/F4D2-evidence/cama-local-fallback.sqlite`, the cutoff 2026-10-20 yields zero cohort rows: its three loads began on 2026-11-12 UTC. At 2026-12-31 the reader yields 37 rows. An empty page at an earlier cutoff is therefore not evidence of an empty database. This is a reader check, not an end-to-end dashboard test.
- Patient routes require a server-side access callback; a revision is not a credential. The configured reader is currently explicitly synthetic. The example's token is a test mechanism, not an authorization policy for real patients. Do not embed it in Angular or expose patient endpoints without an equivalent server-side access boundary.
## Remote mock inventory
| Capability | Source and rule needed | Status |
| --- | --- | --- |
| Resumen C2 breakdowns | Published `estrato`, category cells and labels; counts or percentage of each stratum only when its total is known. Suppressed and missing cells remain distinct. | Angular implementation exists in the remote mock; real capabilities and measures need reconciliation. |
| Curves | `/analisis`, `/analisis/resultados`; cohort membership, event, start, censoring, competing event, horizon and estimator, plus suppression at risk-set level. | Event and censoring definitions and adequate longitudinal source not verified; do not fabricate KM/CIF or intervals. |
| Heatmap | `/analisis/subgrupos`; two distinct variables, estimator, horizon, cell populations and events, suppression and crossed tests. | Same definitions and source unresolved; no supported endpoint yet. |
| Cohort diagnosis | Population/events, median follow-up, model checks, statistical validation and registered versus assumed variables from the same result. | Depends on the unresolved analysis and model definitions. |
| Individual Timeline View | No matching UI or proposal was found in WebApp remote `c076e1e` or Claude's `7971a49`; the generic patient detail has a medical history table. | `cama_linea_de_tiempo` is absent from the isolated synthetic database and its inspected backup, and WebApi's image does not build dbt. Its macro chooses an observation's load date without also checking its procedure's load and joins observations without a patient equality check. The view exposes source IDs. Verify the actual view on 18080, provide reproducible creation and cross-engine identity/knowledge tests, define which source identifiers are safe to expose, and identify Claude's UI proposal before implementing an endpoint. |
## Integration and acceptance still needed
- Backend: finish validation of both follow-up entry points, including unavailable results, provenance, identity, cutoff and links against the integration database. Verify whether complementary suppression is required before publishing intersecting breakdowns.
- Claude / Angular: exercise the final contract through regular follow-up and Analysis, including empty and suppressed selections, readable labels, biopsy report date, source vocabulary and provenance; verify detail, PDF and XLSX use the exact selected rows. Share the final WebApp SHA and tests with backend before parent gitlinks are updated.
- Startup: normal `create_app` now enables the synthetic reader only when `CAMA_COHORT_SYNTHETIC=1` and a stable pseudonym secret and a separate URL-safe access token are configured. The proposed nginx template overwrites the incoming token header with its own container environment value. This grants access to anyone who can reach the proxy and is intended exclusively for the isolated synthetic instance, not real clinical data. The Compose change supplies the token to nginx without putting it in Angular. This image configuration has not yet been built or tested with Docker here. The conservative update retains the prior `.env`; it does not provision these settings automatically. Before the Action, an operator with host access must verify the port identifies the intended synthetic instance, add the three values privately to its retained `.env` without changing the data path, and retain the same secret on future updates. Check file permissions and never print the values. Validate the actual image and proxy before declaring the update ready.
- Acceptance: the local API reconciliation and Claude's browser checks are recorded above. Verify the isolated Linux image and the existing 18080 installation record, backups and update guards on the host. Never replace or reseed its database as part of the update.
## Host acceptance after the composition is ready
1. On labserver, first build the candidate WebApi and WebApp images from the fully checked-out, pinned `ISSSTELEON` tree and run `dist/docker-compose.yml` under a separate Compose project and unused port, with an independently backed-up synthetic SQLite dataset and its own private `.env` and data directory. The `.env` must set `ISSSTELEON_VERSION`, `ISSSTELEON_DATOS`, `ISSSTELEON_PUERTO`, the four database URLs, `CAMA_COHORT_SYNTHETIC=1`, and independent stable `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` values. Run `docker compose config -q`, start the isolated services, then perform the `nginx -t`, direct-403 and proxied-200 checks below using that isolated Compose project and port. Verify the same pseudonym before and after a restart and check CaMa measures. This is the missing Linux image and token-injection validation; do not use the 18080 data directory as the isolated target.
2. Verify that port 18080 maps to one `installed` record for the intended synthetic instance and retain its existing data and configuration. Back up and verify the current instance using the conservative update workflow; never install a fresh instance over its data. Check that no schema migration is pending.
3. Provision `CAMA_COHORT_SYNTHETIC=1`, `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` privately in that instance's retained deployment `.env`. Generate two independent cryptographically random hex strings of at least 32 characters, retain the pseudonym secret for all later deployments, and do not print either value or commit them. The proxy token enables all clients that can reach that proxy, so this configuration is only for the synthetic environment. Confirm the file remains accessible only to the deployment account. The update copies retained configuration forward; it does not create the secrets itself.
4. After all candidate commits are validated and published child-first, dispatch `WorkingNarrative` → `deploy-dev` on ref `dashboard-test` with `puerto=18080` and `rama=dashboard-test`. Capture the resolved SHA and check it against the final outer gitlink. The update must complete its backup and integrity checks; investigate any failure instead of reinstalling or replacing the database.
5. Confirm `/health` through the WebApp proxy and check the actual nginx container uses the proposed template and the configured server-side token without displaying the token. Request `/cama/analisis/indicadores?corte=<current-date>` and `/cama/seguimiento?corte=<current-date>&meses=3`; the actual counts depend on the preserved instance. Exercise an earlier cutoff, an unsuppressed analysis group, its follow-up list, detail, PDF/XLSX and return navigation. Check Resumen and Histórico measures and CaCu/TEA. Do not assume the local six synthetic cases or local 43-row count exist on 18080.
In the verified instance's retained `deploy` directory, the operator can check the rendered container and direct API boundary without printing credentials:
```sh
docker compose --env-file .env -f docker-compose.yml ps
docker compose --env-file .env -f docker-compose.yml exec -T webapp nginx -t
docker compose --env-file .env -f docker-compose.yml exec -T webapp sh -c 'wget -S -O /dev/null "http://webapi:5000/cama/seguimiento?corte=2026-11-13&meses=3" 2>&1 | grep "HTTP/.* 403"'
curl -fsS http://127.0.0.1:18080/health
curl -fsS 'http://127.0.0.1:18080/cama/analisis/indicadores?corte=2026-11-13'
curl -fsS -o /dev/null -w 'Seguimiento HTTP %{http_code}\n' 'http://127.0.0.1:18080/cama/seguimiento?corte=2026-11-13&meses=3'
```
The direct request must return 403 and the proxied follow-up must return 200, or an explicitly explained suppression response for a small nonempty group. Use a cutoff that includes the actual instance's load timestamps, then one before them; do not infer either timestamp from the local fixture. Check pseudonym stability across a restart by comparing a selected ID privately, and do not print the ID or the secret. These are post-deployment checks, not evidence that the Linux image has already been validated.
## Patient and episode identity (Claude, WebApp)
Status: implemented in WebApp worktree `C:/dev/ISSSTELEON-WebApp-identity`, branch `feature/claude-identity-contract`, based on `dashboard-test` `2e09386`; final SHA at the end of this section. The audit below describes the sources as they were before the backend decision.
### What each domain sends today
| Domain | Key on the row that opens the card | Patient identity | Episode |
| --- | --- | --- | --- |
| CaMa (`dashboard-test`, WebApi `8b47f15`) | `id_seudonimo`: full HMAC-SHA256 hex, prefix `cama:`, secret from `CAMA_COHORT_SECRET`. 43 rows, 43 distinct ids on the integration API (`meses=0`). | same value | none. The cohort keeps one row per patient (latest mammogram with a BI-RADS report, then BI-RADS 4 to 6), so a patient never appears twice in one cohort. The selected mammogram is only implied by `mastografia_fecha` and `toma_carga_inicio`. A later cutoff can change which mammogram a given `id_seudonimo` stands for; only `revision` detects it. |
| CaCu (`dashboard-test` kit) | `id_seudonimo` = `"P-" + sha256(sal:pac_id)[:10]`, default salt `dev-simulado` (`SEGUIMIENTO_SAL`). | same value | none: the list groups by `pac_id`. |
| CaCu risk (`GET /cacu/pacientes/<int:pac_id>/riesgo`) | needs the integer `pac_id`, which the list never returns. | `pac_id` | none |
| TEA (branch `feature/163-tea-redesign` in WebApp and WebApi; not in `dashboard-test`) | `EpisodeOfCare.id`, shown as `id_seudonimo`; the card opens `Patient/<id>/$resumen-tea`. | `Patient.id` | `EpisodeOfCare.id`. The server sets both to the same pseudonym (one episode per child, keyed by `pac_id`). |
Verified on 2026-11-13 against `127.0.0.1:51849`: CaMa list, uniqueness above. `/cacu/seguimiento` answers 500 and `/tea/seguimiento` 404 on this copy (no CaCu data, no TEA routes), so those two cannot be exercised end to end here. `GET /cacu/pacientes/P-ABCDEF1234/riesgo` answers 404 because the route only accepts an integer.
### Findings
1. `id_seudonimo` means three different things: a secret-keyed HMAC (CaMa), a 40-bit salted hash with a public default salt (CaCu), and, on WebApi `feature/seguimiento-pac-id` (`8547200`, drops the salt from the CaCu list), apparently the raw `pac_id`. The WebApp commit `bfbd11b` on `feature/seguimiento-pac-id` sends the list's `id_seudonimo` to `/cacu/pacientes/<pac_id>/riesgo`. That works only if the list returns `pac_id`; with the pseudonym contract it silently shows "no disponible" because of the 404. I have not checked the kit side of `8547200`. Showing `pac_id` conflicts with the CaMa note "do not expose `str(pac_id)`" and with the label «Identificador seudónimo».
2. TEA's WebApp maps an episode row with `id_seudonimo = episode.id`, matches included resources by `subject.reference === episode.id`, and opens the patient card with the same value. This is correct only while episode id equals patient id. A patient with two episodes would open one card for both rows, collide on `data-patient` focus selectors, and match the wrong included resources.
3. No list row in any domain carries an episode key, and no endpoint returns two rows for one patient, so "one patient, several episodes" cannot be produced from the current data. Angular keys rows, selection, focus return and exports on `id_seudonimo` alone.
### Questions answered by the backend decision
See the backend decision below: patient key is `pac_id`, no client or server invents an episode key, CaCu risk uses `pac_id`, TEA is not part of this change.
### Backend decision for this integration (Codex)
The requested direction is to retire `id_seudonimo` from the new source-backed path. Use decimal-string `pac_id` for the patient, scoped by domain and retained database; it is the platform staging key copied into the indicator `persona`, not the hospital identifier and not a global identity. Do not create a new HMAC or require a pseudonym secret. In CaMa the list, announced columns, patient card and exports use `pac_id`; the detail route uses that same value and exact selection context. The draft implementation and test proxy are documented above. A cutoff can select a different mammogram for the same patient; `revision` detects cohort changes, and the card must retain the selected row and context.
For CaCu, the ported existing branch temporarily returns the decimal patient key in legacy `id_seudonimo`; the current `/cacu/pacientes/<int:pac_id>/riesgo` is the correct risk route. This changes the legacy field's value, so consumers must refresh their list and discard saved old hashes instead of interpreting them as IDs. For the new contract we will add `pac_id` with the same decimal string, keeping the legacy field only as a migration alias for existing consumers; WebApp should prefer `pac_id` and never route a hash to risk. Do not expose `pac_id_hospital`.
Do not synthesize `id_episodio` from a patient or from a date. CaMa currently publishes one selected mammogram per patient and has no supported episode API in this contract; retain the selected row and context. TEA is not being merged in this task: keep its existing FHIR pseudonym behavior until its own integration, while designing the client to distinguish `EpisodeOfCare.id` from the patient reference and not assuming equality. An actual source-backed episode identifier and its lifecycle need a separate contract when multiple episodes are supported. This answers questions 1–5: no invented episode key or CaMa HMAC; risk uses `pac_id`; TEA remains a later integration; no new CaCu salted hash.
Claude: please implement CaMa `pac_id` and the CaCu migration behavior, preserve TEA's current path, and record your final WebApp SHA and tests. Backend will add the CaCu `pac_id` field and retain the alias for transition.
The CaCu addition is now in kit `778088b` and its WebApi contract test in `06dd74c`; 16 kit and 11 WebApi follow-up tests passed (the latter with the Windows lock shim). The WebApi SHA includes the earlier CaMa draft `eeb55c4`. These remain isolated pending integration.
WebApi `6d32115` adds a passing full-app startup test with retained `CAMA_COHORT_SYNTHETIC=1`, absent obsolete secret and invalid token: `/health` succeeds and patient access remains denied. The three runtime tests pass with the Windows lock shim.
The current isolated WebApi tip is `9c0e03f` (removes an obsolete example-only switch); kit remains `778088b`. Core, Persistance and Extraction trees used by the local test environment match the candidate's pinned trees.
The isolated kit, WebApi, ISSSTELEON and WorkingNarrative worktrees use the local branch `feature/patient-identity-dashboard`; none has been pushed. The WebApp is Claude's separate worktree and branch.
For Claude's browser integration, the new backend is temporarily available at `http://127.0.0.1:51869` on the disposable CaMa data copy, without a token. Use cutoff `2026-11-13`, `meses=0` for 43 rows or the regular three-month window. This loopback server does not include CaCu or TEA data and is not a deployment boundary.
The models repository was also checked: it has no `feature/seguimiento-pac-id` or `dashboard-test` remote branch; TEA points to models `c50c3a081e9e592f710da5a87ccf31629cb03c8a`. The operator confirmed Docker is unavailable for now; proceed with local work and leave the real Compose/image update test outstanding.
The operator explicitly authorized the synthetic composition to use the same patient-route exposure as CaCu, without the CaMa-specific token. Codex is removing the token and Compose injection; no common authentication hook exists in the current WebApi. Claude: please remove the CaMa token nginx template/injection from your WebApp change as well. The optional access callback may still be supplied by a future common boundary. This changes the earlier fail-closed draft described above.
The loopback server on `51869` has been restarted with this updated no-token backend. Its sample data and identity contract are unchanged. CaCu list-to-risk identity was also exercised against a seeded patient: all four patient-risk tests passed with the Windows lock shim.
The no-token WebApi change is now committed at `46eb3df`; 14 focused CaMa tests passed with the Windows lock shim and the loopback server returned `/health` and 43 follow-up rows without a token. These checks do not validate Linux Compose or nginx. The optional callback remains usable when a common boundary is configured.
Review note for Claude: the current uncommitted `PAC_ID` validator permits at most 18 digits. SQLite integer primary keys can have 19 decimal digits; these identifiers are transported as strings, so please accept the source-supported 19-digit range and test it without converting to a JavaScript number.
The current WebApi tip is `1d8cd264b80cabaa7c2aa63e029a1e95a5db272f`; its last commit only clarifies the optional access callback documentation. ISSSTELEON's isolated index has the WebApi and kit gitlinks and Compose cleanup staged, pending Claude's WebApp SHA before committing the complete composition.
WebApi now ends at `10f0c59975647acc3d55c2d17dee6112ec6f9595`: a configured but non-callable optional access callback denies access instead of being ignored. Four focused follow-up tests passed with the Windows lock shim, and the staged ISSSTELEON gitlink has been updated.
The isolated WorkingNarrative `test_conservative.py` suite passed 49 mocked installer/update tests, including retained configuration handling. Its simulated messages about port 18080 are not a deployment or a Docker test. The actual Compose generated by `deploy-dev` and the retained-configuration update remain untested on Linux.
### WebApp implementation (Claude)
Final WebApp SHA: `3b246b4f1f94b4b4259816da5824d8a9a02f2d22` on `feature/claude-identity-contract` (local, not pushed). It is `dashboard-test` `2e09386` plus three commits: `edb868f` (the risk-by-`pac_id` commit of `feature/seguimiento-pac-id`, cherry-picked), `caf5f95` (the token and nginx template removed) and the identity change.
Contract the client implements:
- A row identifies its patient by `pac_id`, a decimal string (`0` or no leading zero, at most 18 digits), or by the legacy `id_seudonimo` (any non-empty string). `pac_id` wins when both are present, so the alias that CaCu rows carry during the migration is never used as the key. A `pac_id` that is not a decimal string (a JSON number, a padded value, a hash) makes the row invalid; the client does not fall back to `id_seudonimo`.
- A page whose rows repeat a patient, or identify patients by different fields, is not drawn, and a list read for a file that does so is refused. The same check runs over the concatenated pages of an export, so a patient on two pages stops the export.
- CaMa and every domain that uses the generic follow-up table: the link, the card, the PDF of the card and the columns of the table and the XLSX/PDF follow the announced `columnas`; the label comes from the server («Identificador de paciente»). The card keeps the clicked row, cut-off and selection; the client does not call the detail endpoint and does not infer a different mammogram for the same patient.
- CaCu: the table and card use `pac_id` when the row has it, labelled «Identificador de paciente», and the legacy «Identificador seudónimo» otherwise. The risk route `GET /cacu/pacientes/<pac_id>/riesgo` is requested only for a row with `pac_id`; a row with only `id_seudonimo` shows «Riesgo individual no disponible» and makes no request, because the value may be a hash. A 404 is "no risk data".
- No `id_episodio` and no episode key of any kind: the client has none and the backend decision defers it. TEA is untouched; its FHIR client still reads `EpisodeOfCare.id` and `Patient` as the same pseudonym and will need its own change before a patient can have several episodes.
- Transition: a response with only `id_seudonimo` renders exactly as before; verified against the integration API in legacy mode.
- Token: `Dockerfile` and `nginx.conf` are back to copying `nginx.conf` as the server config, with no `X-Cama-Cohort-Token` header and no environment substitution. The client never held a token.
- Demonstration records added in a CaCu record are kept per patient identifier. The legacy synthetic detail provider is looked up by `id_seudonimo`; a `pac_id` row has no synthetic detail and shows the unavailable state.
Validated:
- Against Codex's no-token backend at `127.0.0.1:51869` (dev server on 51851, cut-off `2026-11-13`): the regular three-month list returned 6 rows equal to the API in order; the whole cohort with 10 per page returned 43 rows on 5 pages, 43 distinct `pac_id`, equal to the API in order; the XLSX parsed from the downloaded blob had the header «Identificador de paciente» and the same 43 ids in the same order, and every row's cell text equalled the table's. The PDF generated with 4 pages; its text was not extracted, so the PDF order is covered by the document-definition tests and by being built from the same rows as the XLSX. From Analysis, the BI-RADS 5 group opened 12 rows over two pages equal to the API with the `birads` filter; the card for a row on page 2 showed that row's `pac_id`; focus returned to the control used; the XLSX had the 12 ids in the same order. Backend detail returned 200 and the export 43 rows with the same context; an earlier cut-off returned an empty cohort.
- Against the same API through a test-only forwarder that rewrites `pac_id` back to `id_seudonimo`: legacy rows rendered and opened with the legacy label.
- CaCu and TEA: the integration API has no data for either (`/cacu/seguimiento` answers 500, `/tea/seguimiento` 404), so the browser check only shows that both domains open their sections and report the unavailable data. The CaCu follow-up, record, risk and registration code paths are covered by their unit tests, which pass.
- `ng build` (production) passes. The full WebApp suite ran 1628 tests: 1624 passed and 4 failed. Three failures are the same at `2e09386`: the header title in `indicadores-cama-oportunidad.spec.ts`, and two 404-state tests in `indicadores-seguimiento-tabla.spec.ts` that still expect the pending message the unavailable-cohort message replaced. The fourth, `app.spec.ts` (`/conectar`), failed once under load and passed when run alone. New tests are in `paciente-identidad.spec.ts`; the older specs were adapted where they read `id_seudonimo`.
Still open: the Linux image and nginx, the PDF text order from a rendered file, CaCu with real data, and the two stale 404 specs.
### Integrated local composition
Codex integrated Claude's exact WebApp `3b246b4f1f94b4b4259816da5824d8a9a02f2d22` and added `01d6e71f07a4833248cabc4ee18be21da22f37e8`, which accepts 19-digit SQLite integer IDs as strings. The focused identity suite passed 15 tests. ISSSTELEON `3b442d89a2c1e5d924be5949c34d3c1b6a985af8` pins WebApp `01d6e71f07a4833248cabc4ee18be21da22f37e8`, WebApi `10f0c59975647acc3d55c2d17dee6112ec6f9595`, and kit `778088b91024e71380bc8fe696140cd45b3dacb5`, and removes the obsolete Compose token environment entries. These commits are local and not yet deployed. The WebApp findings and outstanding checks immediately above remain applicable.
Publish child-first only after review: kit, WebApi, WebApp, ISSSTELEON, then WorkingNarrative. The operator handles publication and deployment. Before 18080, validate the actual `deploy-dev` generated Compose and a retained-configuration update on an isolated Linux Docker host; retain the existing data and use the recovery guidance above if the current installation is unhealthy. The browser and mocked installer evidence here does not replace those checks.
The earlier `51850` development server held a file in the shared `node_modules` after an interrupted install. With the operator's request, its PID was verified and stopped; `npm ci --no-audit --no-fund` completed in `C:/dev/ISSSTELEON-WebApp-CaMa-Lote1`, the linked WebApp's server was restarted on `51850`, and both `/indicadores/cama` and proxied `/health` returned 200. The Angular development build succeeded. This repairs the local integration environment only; it does not validate the Linux image or port 18080.
+16 -19
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
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.
(`.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.
3. **Load it:**
```sh
@@ -74,14 +74,16 @@ uv run --python 3.12 python -m dev_data cargar cacu --api http://10.0.10.41:<por
## As a Gitea action
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.
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"
```
What it needs:
- the job can use Docker (it already does to build the platform images);
@@ -97,12 +99,6 @@ 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.
@@ -117,7 +113,8 @@ 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. A clean load needs a reinstall of the DEV instance
(`reinstall-dev`, which removes its data) followed by `load-dev-data`.
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.
- Superseded by #165 once the platform keeps its HIS connection: the
deployment would declare the hospital as a configured source.
-68
View File
@@ -1,68 +0,0 @@
# What is promised, what we have, what is missing
Checked on 2026-11-13 against `Alcance_proyecto.pdf` (modules and the
deliverables list) and `docs_desarrollo-2.pdf` (requirement IDs), reading
the code rather than the notes. Hand-off is 2026-11-30. Status: **done**,
**partial** or **missing**. Items that depend on the client's data or
clinical decisions say so; they need negotiating, not just code.
## Contract deliverables
| Deliverable | Status | What exists / what is missing |
|---|---|---|
| Structured, integrated, cleaned database apart from the source systems | **done** | Four engine-agnostic databases (CaCu, CaMa, TEA, governance), versioned cohort builds. |
| Data integration layer through web services (APIs) | **done** | "Conectar datos": SQL, Excel/CSV, PDF tables, clinical documents, EEG, documents stored in columns; validation, merge, import log. |
| NLP modules | **partial** | Field extraction from forms and free text: captions and layout, ConText/NegEx assertions, sections, anchors, severity, measurements, OCR tolerance, subject check, review dialog; a learned candidate ranker that learns from review corrections (`<domain>-extraccion`); `python -m webapi.nlp evaluate/train`. Missing: a held-out evaluation set; EEG, mammography and breast biopsy vocabulary tested on real reports; colposcopy (Reid, Swede) has no columns. |
| Breast cancer (CaMa) risk model | **missing** | `models/cama` holds only its package docstring. Needs data and outcome definition from the client. |
| TEA diagnostic model from EEG alterations | **missing** | EDF files are read and validated (amendment done) and the report's EEG findings can be extracted; no signal features, no model. Needs data. |
| CaCu progression risk model | **done (one scenario)** | `cin2_logistic`: routines recorded, estimate, risks stored with model provenance. Risk cut-offs (immediate / priority / scheduled) undefined, so the risk-band indicator is hidden. |
| CaCu survival model (OS/DFS, Kaplan-Meier at 1/3/5 years) | **missing** | Only a draft survival chart contract in the indicators kit. Needs follow-up and death data. |
| Interactive dashboards with each module's indicators | **partial** | Indicator pages per domain; no PDF/XLS export of indicators (only the import log downloads), no heatmap, no single combined view. |
| User manual | **partial** | `dist/MANUAL.md` covers installation, operation and the import flow; not every screen. |
| Technical manual | **partial** | Preliminary design specification PDF, package READMEs (`Extraction/README.md` documents the NLP method and references), architecture notes; no final consolidated document. |
| Project closure letter | n/a | Administrative. |
## Modules
| Module | Status | Notes |
|---|---|---|
| M00 Configuración: login, 2FA, password change, lockout, access, profiles, users | **missing** | No authentication at all; the biggest security gap (anyone who reaches the app can import data and run notebooks). |
| M00 Parametrización, catálogos generales | **partial** | Catalogs and parameters exist as versioned files (`core/catalogos/*.toml`, `parametros.toml`); no screens to edit them. |
| M01 CaMa: BI-RADS indicators | **done** | BI-RADS 4/5, confirmation, biopsies, time to diagnosis. |
| M01 CaMa: risk calculator, heatmap, PDF/XLS reports, individual profiles, model | **missing** | Risk band only as a proposal. |
| M01 CaMa: mammogram images | **partial** | Images embedded in reports are located and stored; no DICOM connector. |
| M02 TEA: % with/without EEG, evaluation, confirmation, screening-to-diagnosis | **done** | |
| M02 TEA: % normal vs abnormal EEG, correlation with severity | **missing** | The extraction to fill `eeg_anormalidad_presente` and the conclusion category now exists; the indicators don't. |
| M02 TEA: EEG model | **missing** | |
| M03 CaCu: cytology distribution, histopathology confirmation, screening-to-diagnosis time, risk model | **done** | |
| M03 CaCu: diagnosis-to-treatment time, survival, cut-offs, incidence/prevalence against state data, individual profiles | **missing** | |
| M04 Integrated dashboard with PDF/XLS | **partial** | Per-domain pages only. |
## Requirements document
| IDs | Status | Notes |
|---|---|---|
| VAR-01..03, VARM-01..04a | **done** | OCR with confidence, status, main and alternative method, review flag. |
| VAR-04, VARM-05 (document the extraction method) | **done** | `Extraction/README.md`: method and references; the evaluation command. A held-out score is still missing. |
| VAR-07, VAR-08, VAR-09 | **done** | Transformation descriptions, source and dates at load, results persisted. |
| IND-01..03 | **done** | |
| EL-01..07 | **done** | Versioned builds with hash, per-criterion exclusion counts. |
| ML-01a, ML-01b | **done** | Five routine records written by training; run files downloadable. |
| ML-02, ML-03 | **done** | DEV/PROD tags; cohort link. The extraction ranker can't meet ML-03 (no cohort), so it can't be promoted: decision pending. |
| ML-04, ML-05 | **done, unverified** | Read-only access; notebooks isolated in the `notebooks` container, never started as a real container. |
| MLD-01, MLD-01b | **done** | Promotion checks for technical and clinical validation reports. |
| MLD-03 (weights and OR/HR shown) | **partial** | Coefficients recorded in the METODO_ANALITICO routine; not shown on screen, the check only asks for a report link. |
| MLD-4, MLD-5 | **done** | Estimates carry their version and are stored with it. |
| TRIPOD 20b/20c | **partial** | EDA report covers part of it. |
## What code alone can still close before 2026-11-30
1. Minimal login, users and profiles (or a documented plan).
2. PDF/XLS export of the indicator pages.
3. Coefficients and OR on the model version screen (MLD-03).
4. A user manual for every screen.
5. Run the notebook container for real; rebuild the WebApi image.
Everything else on the missing list (CaMa and TEA models, survival, risk
cut-offs, incidence against state data, a held-out NLP set) needs data or
clinical decisions from the client and should be raised as a dependency.
+4 -4
View File
@@ -5,10 +5,10 @@ Moved from `AGENTS.md` §4 on 2026-11-03.
```bash
(cd Core && uv run pytest -q) # 18 (2 skip)
(cd Persistance && uv run pytest -q) # 18 (1 skip)
(cd Extraction && uv run pytest -q) # 83 (OCR tests need tesseract + spa and osd data)
(cd models && uv run pytest -q) # 180 (real Jupyter kernels and a runner process in tests/pipelines/test_experiment.py)
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 497 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
(cd WebApp && npx ng test --watch=false && npx ng build) # 1248 (a few specs, mostly indicadores, time out under heavy load; pass alone)
(cd Extraction && uv run pytest -q) # 31 (OCR tests need tesseract + spa data)
(cd models && uv run pytest -q) # 41
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 417 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
(cd WebApp && npx ng test --watch=false && npx ng build) # 1235 (a few vendored indicadores specs time out under heavy load; pass alone)
```
If a package's `.venv` has stale absolute paths baked into its entry-point
+46
View File
@@ -0,0 +1,46 @@
"""Check follow-up reconciliation through an isolated synthetic test proxy."""
import argparse
import json
from urllib.parse import urlencode
from urllib.request import urlopen
def read(base, path, params):
with urlopen(base.rstrip('/') + path + '?' + urlencode(params), timeout=30) as response:
return json.load(response)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base', default='http://127.0.0.1:51850')
parser.add_argument('--cutoff', default='2026-11-13')
parser.add_argument('--before-load', default='2026-10-20')
args = parser.parse_args()
aggregate = read(args.base, '/cama/analisis/indicadores', {'corte': args.cutoff})
first = read(args.base, '/cama/seguimiento', {'corte': args.cutoff, 'meses': 3, 'page_size': 2})
assert first['paginacion']['total_items'] >= 5, 'Recent synthetic window is not populated'
context = {key: first[key] for key in ('cohorte', 'escenario', 'revision')}
query = {'corte': args.cutoff, 'meses': 3, **context}
pages = [read(args.base, '/cama/seguimiento', {**query, 'page_size': 2, 'page': page})
for page in range(1, first['paginacion']['total_pages'] + 1)]
rows = [row for page in pages for row in page['items']]
exported = read(args.base, '/cama/seguimiento/exportacion', query)
assert len(rows) == first['paginacion']['total_items'] and exported['items'] == rows
for row in rows:
detail = read(args.base, '/cama/pacientes/' + row['id_seudonimo'], query)
assert detail['item'] == row
group = next(group for group in aggregate['grupos'] if not group['suprimido'])
cohort_query = {'corte': args.cutoff, 'meses': 0, 'birads': group['codigo'],
**{key: aggregate[key] for key in context}}
cohort = read(args.base, '/cama/seguimiento', cohort_query)
cohort_export = read(args.base, '/cama/seguimiento/exportacion', cohort_query)
assert cohort['paginacion']['total_items'] == group['n'] == cohort_export['total_items']
early = read(args.base, '/cama/seguimiento', {'corte': args.before_load, 'meses': 0})
assert early['items'] == [] and early['paginacion']['total_items'] == 0
print('Regular pages, detail and export agree; Analysis group and export agree; pre-load cohort is empty.')
if __name__ == '__main__':
main()
-26
View File
@@ -1,26 +0,0 @@
# TEA FHIR synthetic browser check
Run from a WorkingNarrative checkout whose ISSSTELEON and WebApp gitlinks include the local TEA changes. The script creates a temporary SQLite database from `WebApi/tests/staging/tea.py`; it never imports production data. `DEV_REVISION` enables the simulated patient routes. It serves the Angular build and the real Flask API on a temporary loopback port and closes them after the check.
Prerequisites: Python 3.12, uv, Node and npm, a Chromium-compatible browser, and Playwright available to Node. Install the WebApi dev dependencies and build WebApp. Generate the dbt manifest from this exact Transformation tree:
```sh
cd ISSSTELEON/Transformation
uv run dbt compile --profiles-dir . --profile tea
cd ../WebApi
uv sync --locked
cd ../WebApp
npm ci
npm run build
cd ../..
```
Set `PLAYWRIGHT_PATH` to the installed Playwright module and `BROWSER_PATH` to the browser executable when the defaults in `verify.cjs` do not exist. Then run:
```sh
ISSSTELEON/WebApi/.venv/bin/python e2e/tea-fhir/serve_and_verify.py
```
On Windows use `ISSSTELEON\WebApi\.venv\Scripts\python.exe`. The harness supplies a Windows-only `fcntl` stub that raises if locking is used; it does not verify lock behaviour. `DBT_MANIFEST` is set to `Transformation/target/manifest.json` in the harness before Flask starts. For the API outside the harness, the file must be available inside the API environment at the path set in `DBT_MANIFEST`, and the cycle must create the definitions and event views in the domain database. Migrations alone do not do this. The WebApi image compiles the manifest from `Transformation` while it builds and sets `DBT_MANIFEST` to it (SQLite's SQL); the `indicadores` service runs the cycle after each import.
The browser check covers M28, history, filters, paging, the patient's identity, ADOS-2 and EEG, returning with focus, a partial record and a simulated FHIR 404. Patient selection races and absent/masked values are covered by the focused Angular tests. No EEG alteration validation switch is enabled.
-49
View File
@@ -1,49 +0,0 @@
import os
import subprocess
import sys
import tempfile
import threading
import types
from pathlib import Path
root = Path(__file__).resolve().parents[2]
api = root / 'ISSSTELEON' / 'WebApi'
sys.path[:0] = [str(api), str(api / 'tests')]
if os.name == 'nt':
fcntl = types.ModuleType('fcntl')
def unavailable(*args):
raise RuntimeError('fcntl locking is unavailable in this Windows test')
fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_UN = unavailable, 2, 8
sys.modules['fcntl'] = fcntl
os.environ['DEV_REVISION'] = 'pruebas'
os.environ['DBT_MANIFEST'] = str(root / 'ISSSTELEON' / 'Transformation' / 'target' / 'manifest.json')
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
from conftest import base_de
from flask import send_from_directory
from werkzeug.serving import make_server
from webapi import create_app
with tempfile.TemporaryDirectory(prefix='tea-e2e-') as directory:
base = base_de('tea', Path(directory))
base.run('catalogs', 'load', 'views', 'registry', 'definitions', 'event_models', allow_undecided=True)
app = create_app()
static = root / 'ISSSTELEON' / 'WebApp' / 'dist' / 'WebApp' / 'browser'
@app.get('/indicadores/tea')
def page():
return send_from_directory(static, 'index.html')
@app.get('/<path:filename>')
def assets(filename):
return send_from_directory(static, filename)
server = make_server('127.0.0.1', 0, app)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
subprocess.run(['node', str(root / 'e2e' / 'tea-fhir' / 'verify.cjs'), str(server.server_port)], check=True, timeout=90)
finally:
server.shutdown()
thread.join()
base.motor.dispose()
from persistance.db import get_tea_engine
get_tea_engine().dispose()
-70
View File
@@ -1,70 +0,0 @@
const { chromium } = require(process.env.PLAYWRIGHT_PATH || 'C:/Users/angel/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
(async () => {
const browser = await chromium.launch({ executablePath: process.env.BROWSER_PATH || 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });
try {
const page = await browser.newPage();
const root = `http://127.0.0.1:${process.argv[2]}`;
await page.goto(`${root}/indicadores/tea`);
const m28 = page.locator('article').filter({ has: page.getByRole('heading', { name: 'Casos por estatus' }) });
await m28.getByText('6', { exact: true }).waitFor();
for (const [name, count] of [['Solo M-CHAT','2'], ['Hasta evaluación psicológica','1'], ['Hasta evaluación neuropediátrica','1'], ['Con EEG','2']]) {
const row = m28.locator('dl div').filter({ hasText: name });
if (await row.locator('dd').innerText() !== count) throw new Error(`M28 ${name}`);
}
console.log('M28: 6 casos y cuatro etapas');
await page.getByRole('button', { name: 'Histórico' }).click();
await page.getByRole('heading', { name: 'Casos por estatus' }).first().waitFor();
if (await page.locator('article').count() !== 3) throw new Error('Histórico no devolvió tres periodos');
await page.getByRole('button', { name: 'Seguimiento', exact: true }).click();
await page.getByLabel('Fecha de corte').fill('2025-12-31');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('6 episodios', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Siguiente' }).click();
await page.getByText('Página 2', { exact: true }).waitFor();
if (await page.locator('tbody tr').count() !== 1) throw new Error('Paginación incorrecta');
await page.getByRole('button', { name: 'Anterior' }).click();
await page.getByText('Página 1', { exact: true }).waitFor();
await page.getByLabel('Edad al M-CHAT').selectOption('16_23');
await page.locator('select[name=status]').selectOption('finished');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('1 episodios', { exact: true }).waitFor();
const button = page.getByRole('button', { name: 'Abrir ficha' });
const patient = await button.getAttribute('data-patient');
await button.click();
await page.getByRole('heading', { name: 'Ficha del paciente' }).waitFor();
await page.getByLabel('Ficha del paciente').getByText(patient, { exact: true }).waitFor();
await page.getByText('Fecha: 2025-05-20').waitFor();
await page.getByText('Calidad: Buena').waitFor();
await page.getByText('Puntaje de severidad (CSS)', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
if (await page.getByLabel('Edad al M-CHAT').inputValue() !== '16_23') throw new Error('Filtro perdido');
await page.waitForFunction(() => document.activeElement?.getAttribute('data-patient') !== null);
console.log('Histórico, filtros, paginación, ficha correcta y retorno con foco');
await page.locator('select[name=status]').selectOption('active');
await page.getByLabel('Edad al M-CHAT').selectOption('');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('4 episodios', { exact: true }).waitFor();
const ids = await page.locator('button[data-patient]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-patient')));
let partial = null;
for (const id of ids) {
const res = await page.request.get(`${root}/tea/fhir/Patient/${id}/$resumen-tea`);
const body = await res.json();
if (!body.entry.some(e => e.resource.resourceType === 'DiagnosticReport')) { partial = id; break; }
}
if (!partial) throw new Error('No se encontró ficha parcial');
await page.locator(`button[data-patient="${partial}"]`).click();
await page.getByText('Sin información de EEG.').waitFor();
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
await page.locator('input[name=cssMin]').fill('100');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('No hay episodios para la selección.').waitFor();
await page.locator('input[name=cssMin]').fill('');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('4 episodios', { exact: true }).waitFor();
await page.route('**/tea/fhir/Patient/*/$resumen-tea', route => route.fulfill({ status: 404, contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'OperationOutcome', issue: [{ code: 'not-found', diagnostics: 'Paciente no encontrado' }] }) }));
await page.locator(`button[data-patient="${partial}"]`).click();
await page.getByRole('alert').getByText('Paciente no encontrado').waitFor();
console.log('Ficha parcial y OperationOutcome 404');
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exit(1); });
-61
View File
@@ -1,61 +0,0 @@
# Settings for the manual deployment (docker-compose.yml in this folder). Docker
# Compose reads it for the values below, and the webapi and indicadores
# containers receive it as their environment.
# --- 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=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=5310
# The API, direct.
WEBAPI_PORT=5311
# The simulated hospital's MySQL (user/password hospital/hospital).
HOSPITAL_PORT=5312
# --- Simulated hospital contents ---
# Patients generated per project, the generator's seed and reference date.
N=200
N_CACU=300
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
# lists, TEA's patient summary). They exist for simulated data only: leave it
# unset on a platform that holds real patients.
DEV_REVISION=manual-deploy
# --- Platform (same variables as ISSSTELEON/.env.example) ---
# Target databases. Unset, each is a SQLite file in this project's
# webapi_data volume.
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
# WEBAPI_MAX_UPLOAD_MB=200
# WEBAPI_WORKERS=2
# WEBAPI_TIMEOUT=600
# EXTRACTION_OCR_LANG=spa+eng
-1
View File
@@ -1 +0,0 @@
documentos/
-443
View File
@@ -1,443 +0,0 @@
# Manual deployment
The whole platform plus the simulated hospital in one Compose project, built
from the two checkouts next to this folder (`../ISSSTELEON` and `../dev-data`).
Everything here is simulated data.
Run every command from this folder.
## What it starts
| Service | What it is | Published on |
|---|---|---|
| `webapp` | the Angular app behind nginx, which also proxies the API | `WEBAPP_PORT` |
| `webapi`, `indicadores` | the Flask API and the indicator recomputation | `WEBAPI_PORT` |
| `hospital` | MySQL playing the hospital system (`hospital`, `hospital_cacu`, `hospital_cama`) | `HOSPITAL_PORT` |
| `poblar`, `poblar-cacu`, `poblar-cama` | one-shot jobs that generate the hospital's data on `up` | |
| `load` | one-shot job that imports the hospital into the platform | |
| `documentos` | one-shot job that writes the test PDFs | |
Ports, bind address and project name come from `.env`. Change
`COMPOSE_PROJECT_NAME` and the three ports to run a second copy on the same
machine.
## Bring it up and load it
```sh
docker compose up --build -d # platform and hospital; the hospital is populated
docker compose run --rm --build load # import the hospital into the platform
```
`load` prints one line per table (`leídas, nuevas, actualizadas, rechazadas`);
every `rechazadas` should be 0. It needs an empty platform: the hospital's ids
travel with the rows, so a second load is refused without writing anything.
To load again, run `docker compose down -v` first.
```sh
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`
image compiles them into a manifest while it builds and sets `DBT_MANIFEST` to
it; without that variable the API has no measure routes and the pages answer
"No fue posible cargar los indicadores". Check it with:
```sh
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5210/tea/fhir/Measure # 200
```
After `load`, the `indicadores` service recomputes each project on its own
(it polls every 20 seconds, and a project takes from seconds to a few
minutes). Until it finishes, the pages have no figures. Its state per project:
```sh
curl -s http://localhost:5210/reportes/indicadores # "estado": "ok" when done
docker compose logs -f indicadores
```
A platform that was loaded before the image had the manifest keeps its data
but has nothing computed. Rebuild and ask for the recomputation, once per
project:
```sh
docker compose up --build -d
for p in cacu cama tea; do curl -s -X POST "http://localhost:5210/$p/fhir/Measure/\$recalcular"; done
```
Things to know:
- **The manifest's SQL is SQLite's**, the default engine here. With
`*_DATABASE_URL` on another engine, compile the manifest with that dbt
target (`../ISSSTELEON/Transformation/profiles.yml`), mount it in `webapi`
and `indicadores`, and set `DBT_MANIFEST` to its path.
- **Patient-level pages need `DEV_REVISION`** (set in `.env`): the follow-up
lists and TEA's patient summary are served only with it, because they are
meant for simulated data.
- **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
docker compose run --rm --build documentos
```
It writes PDFs of the same patients the hospital holds into `./documentos`
(ignored by git). It doesn't need the platform or the hospital to be up: the
documents come from the same generator, seed (`SEMILLA`) and reference date
(`REFERENCIA`) as the hospital's rows, so a patient key in a PDF is a patient
key in the hospital.
| Folder | Documents | How many |
|---|---|---|
| `documentos/cacu/` | CaCu records, one per cytology (`CACU-0002-C1`), 3 to 7 pages: order, cover, cytology form and, when the history has them, HPV result, colposcopy note, pathology report and the note that resolves the cytology | the first `N_DOCUMENTOS_CACU` patients (20) |
| `documentos/tea/` | the ADOS-2 score summary of the psychological evaluation, one page per child with module 1, 2 or 3 (`N-0001-ADOS2`) | all `N` children (200) |
Each record has its own folder:
- CaCu: `<key>_limpio.pdf` (text), `<key>_escaneado.pdf` (every page an
image, no text layer, to exercise OCR), the page images and field masks,
and `ground_truth.json` / `.csv` with each field's value and its box in
both PDFs.
- TEA: `<key>.pdf` with selectable text, not scanned, and its `ground_truth`.
`indice.json` in each folder lists the records.
Things to know:
- **CaCu is heavy by design.** Every page is rasterised and degraded: 12
patients took 28 seconds and 35 MB for 76 pages on the development machine.
Twenty patients give around 30 records; all 300 give 442 records and 1,800
pages, so expect several minutes and close to 1 GB. Raise it for one run
with `N_DOCUMENTOS_CACU=300 docker compose run --rm --build documentos`.
- **Module 3 is rare.** With seed 7 the first child with ADOS-2 module 3 is
number 247, so a hospital of 200 children has none. To see one, generate
with `N=250` or more; those documents have no row in a 200-child hospital.
- **What matches the hospital.** Patient key, dates, cytology and HPV results,
biopsy grade, ICD-10 codes and each ADOS-2 item score are the hospital's.
Names, doctors, vital signs and the wording of notes exist only in the
documents. The ADOS-2 totals add only the items of the child's module; the
platform adds every item the hospital row has, so its totals can be higher.
- **The files belong to root**, because the container writes them. Delete the
folder with `sudo rm -rf documentos`.
- Nothing here loads these PDFs into the platform; `load` only imports the
hospital's tables.
The same documents without Docker, from `../dev-data`:
```sh
uv run python -m dev_data documentos cacu --referencia 2026-01-01 --salida datos/expedientes
uv run python -m dev_data documentos tea --referencia 2026-01-01 --salida datos/ados2
```
Binary file not shown.
-7
View File
@@ -1,7 +0,0 @@
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
-84
View File
@@ -1,84 +0,0 @@
# Manual deployment of the whole platform plus the simulated hospital, built
# from the two checkouts next to this folder (../ISSSTELEON and ../dev-data).
# Ports, bind address and project name come from .env, so several copies can
# run on one machine without touching each other or the other deployments.
#
# docker compose up --build -d # platform + hospital, hospital populated
# docker compose run --rm --build load # import the hospital into the platform
# docker compose run --rm --build documentos # write the test PDFs to ./documentos
# docker compose down # stop, keep the data
# docker compose down -v # stop and delete this project's data
#
# Run from this folder. `load` needs an empty platform: the hospital's ids
# travel with the rows, so a second load is refused without writing anything.
# To load again, `down -v` first. README.md has the whole walkthrough.
include:
- path:
- ../ISSSTELEON/docker-compose.yml
- platform.override.yml
project_directory: ../ISSSTELEON
env_file: .env
- path:
- ../dev-data/compose.prueba.yml
- hospital.override.yml
project_directory: ../dev-data
env_file: .env
services:
# One-shot: imports the three projects through the platform's import API.
# Inside the project network the API is the webapp proxy and the hospital
# is reached by service name, as the webapi container sees it.
load:
build:
context: ..
dockerfile: dev-data/Dockerfile
profiles: [load]
depends_on:
webapi:
condition: service_healthy
webapp:
condition: service_started
poblar:
condition: service_completed_successfully
poblar-cacu:
condition: service_completed_successfully
poblar-cama:
condition: service_completed_successfully
entrypoint: ["sh", "-c"]
command:
- |
set -eu
for pair in cacu:hospital_cacu cama:hospital_cama tea:hospital; do
project="$${pair%%:*}"
database="$${pair#*:}"
echo "== $$project"
uv run --frozen --no-dev python -m dev_data cargar "$$project" \
--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
# platform nor the hospital. CaCu pages are rasterised and degraded, which
# is slow and large, so its count is separate from the hospital's.
documentos:
build:
context: ..
dockerfile: dev-data/Dockerfile
profiles: [documentos]
volumes:
- ./documentos:/documentos
entrypoint: ["sh", "-c"]
command:
- |
set -eu
uv run --frozen --no-dev python -m dev_data documentos cacu \
--n "${N_DOCUMENTOS_CACU:-20}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
--salida /documentos/cacu
uv run --frozen --no-dev python -m dev_data documentos tea \
--n "${N:-200}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
--salida /documentos/tea
-24
View File
@@ -1,24 +0,0 @@
# Applied over ../dev-data/compose.prueba.yml. The platform reaches the
# hospital by service name; the published port is only for inspecting it
# from outside with a MySQL client.
services:
hospital:
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${HOSPITAL_PORT:-29505}:3306"
# 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:
profiles: !reset []
-33
View File
@@ -1,33 +0,0 @@
# Applied over ../ISSSTELEON/docker-compose.yml. Paths here resolve from
# ../ISSSTELEON.
#
# Images are tagged per project so a build here doesn't replace the
# isssteleon/*:dev images other deployments run. The containers read
# manual-deploy/.env instead of ISSSTELEON/.env, so a .env left in the source
# tree never points this stack at another deployment's databases.
x-api: &api
image: ${COMPOSE_PROJECT_NAME}/webapi:local
env_file: !override
- ../manual-deploy/.env
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
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPP_PORT:-28080}:80"
View File
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

@@ -1,94 +0,0 @@
# 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.

Before

Width:  |  Height:  |  Size: 100 KiB

-239
View File
@@ -1,239 +0,0 @@
# 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.
@@ -1,32 +0,0 @@
"""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')}")
@@ -1,17 +0,0 @@
"""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"))

Some files were not shown because too many files have changed in this diff Show More