Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 19bea78585 | |||
| 774ec67117 | |||
| a7de3ad653 | |||
| 85f8f112c5 | |||
| d433931c54 | |||
| f3f0588d59 | |||
| 3696970331 | |||
| 675ebffc09 | |||
| 7fc0d8ff31 | |||
| d83940c966 | |||
| f11efe9bb0 | |||
| 3db4f1f8f8 | |||
| 79c7d36756 | |||
| 8615395304 | |||
| d6244ebb6e | |||
| 3bd2ebf505 | |||
| e0c7643dba | |||
| ae3f6c89fa | |||
| f296760c9b | |||
| a820c7c2bf | |||
| 415873c767 | |||
| a9b8623bc5 | |||
| 50034dd471 | |||
| 22331edfe6 | |||
| 7dfb4df498 | |||
| 541a8114c7 | |||
| 8a7ed7669d | |||
| 52f378a625 | |||
| 26dd5b8a01 | |||
| 35544fc98a | |||
| f9560aee8c | |||
| 74af823764 | |||
| 23708bfff9 | |||
| 7a08c0b335 | |||
| 35df57fcec | |||
| a495fc2852 | |||
| dadd7249fa | |||
| 4a47d5f965 | |||
| 2cfa573204 | |||
| bcff4d495d | |||
| 285575bfce | |||
| e7617dd8ea | |||
| cd89c1192a | |||
| ad9ab50ff2 | |||
| e8d19e88e1 | |||
| c3760309aa | |||
| 91f3b9942a | |||
| ddbca8e1e2 | |||
| 0da1bb6a8f | |||
| 8ec9c86d10 |
@@ -5,26 +5,32 @@ import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "indicadores_kit", "WebApi", "WebApp")
|
||||
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "WebApi", "WebApp")
|
||||
IMPACT = {
|
||||
"Core": {"Core", "Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
|
||||
"Persistance": {"Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
|
||||
"Core": {"Core", "Persistance", "Transformation", "models", "WebApi"},
|
||||
"Persistance": {"Persistance", "Transformation", "models", "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"},
|
||||
}
|
||||
DEPLOY_FILES = {".gitea/deploy/dev.py", ".gitea/deploy/host.py", ".gitea/deploy/test_dev.py",
|
||||
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/deploy-dev-diagnostic.yml"}
|
||||
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/deploy-dev-diagnostic.yml",
|
||||
".gitea/workflows/deploy-terminal-release.yml"}
|
||||
PROBE_FILES = {".gitea/probe/README.md", ".gitea/probe/docker_probe.py", ".gitea/probe/test_docker_probe.py",
|
||||
".gitea/workflows/docker-persistence-probe.yml"}
|
||||
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
|
||||
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/select_checks.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
|
||||
|
||||
|
||||
def deploy_file(path):
|
||||
return path in DEPLOY_FILES or (path.startswith('.gitea/deploy/') and path.endswith('.py'))
|
||||
return path in DEPLOY_FILES or (path.startswith(('.gitea/deploy/', '.gitea/deploy-terminal/'))
|
||||
and path.endswith('.py'))
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
@@ -46,6 +52,12 @@ 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 compare(repo, old, new, prefix, changed):
|
||||
before, after = entries(repo, old), entries(repo, new)
|
||||
for path in sorted(before.keys() | after.keys()):
|
||||
@@ -55,6 +67,10 @@ 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 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
|
||||
@@ -75,7 +91,9 @@ def select(changed):
|
||||
selected = set()
|
||||
for path in changed:
|
||||
parts = path.split("/")
|
||||
if parts[0] != "ISSSTELEON":
|
||||
if path in RETIRED_GITLINKS:
|
||||
selected.update(RETIRED_GITLINKS[path])
|
||||
elif parts[0] != "ISSSTELEON":
|
||||
if deploy_file(path) or path in PROBE_FILES:
|
||||
continue
|
||||
if path in CI_SELF_TESTED:
|
||||
+109
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -9,7 +10,7 @@ import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select.py"))
|
||||
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select_checks.py"))
|
||||
selector = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(selector)
|
||||
|
||||
@@ -27,7 +28,9 @@ 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"})
|
||||
|
||||
@@ -61,9 +64,10 @@ 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 not bash and os.name == "nt":
|
||||
bash = r"C:\Program Files\Git\bin\bash.exe"
|
||||
if os.name == "nt" and git:
|
||||
bash = Path(git).parents[1] / "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"
|
||||
@@ -73,7 +77,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", "INDICADORES", "WEBAPI", "WEBAPP"):
|
||||
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "WEBAPI", "WEBAPP"):
|
||||
env[name] = "skipped"
|
||||
env[name + "_REQUIRED"] = "false"
|
||||
result = subprocess.run([bash, "-c", script], env=env, capture_output=True, text=True)
|
||||
@@ -190,6 +194,107 @@ 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_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()]:
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# Native release deployment
|
||||
|
||||
This manual-dispatch workflow prepares and deploys a published Release to
|
||||
`10.0.10.41` using native Ubuntu processes. A successful run means it has
|
||||
resolved the tag, transferred the pinned application source, prepared the
|
||||
instance, started three supervised user services, verified local health and
|
||||
confirmed that the runner can reach WebApp and the proxied API at
|
||||
`http://10.0.10.41:<puerto>/`. It then checks the service states once more.
|
||||
The intermediate bundle remains in the job workspace; no manual download,
|
||||
transfer, installation or activation is required per deployment.
|
||||
|
||||
The installer revision comes from the selected workflow branch, normally
|
||||
`dev`; the application revision comes exclusively from the tag. It is not
|
||||
restricted to `dev`, `staging` or `main`. The first intended test is a
|
||||
published Release for the operator-selected `staging` commit on port `18090`.
|
||||
No Release, tag, deployment or infrastructure change is created by this work.
|
||||
|
||||
## Architecture and prerequisites
|
||||
|
||||
An isolated non-root deployment account connects to the host over SSH with a
|
||||
dedicated key and a verified host key. It owns an isolated installation parent
|
||||
and runs its own `systemd --user` manager, with lingering enabled once by the
|
||||
operator. The account must not have Docker, sudo, wheel or root group
|
||||
membership; it must have no other administrative grants or capabilities. It
|
||||
can execute commands and write within its own permissions, so the private key
|
||||
is sensitive even though it does not confer root access. SSH key `restrict`
|
||||
options can disable forwarding and interactive PTY access; they do not prevent
|
||||
the account from executing arbitrary commands as itself.
|
||||
|
||||
The workflow uses no `sudo` and never changes the existing runner or Docker
|
||||
configuration. The operator confirmed that `ubuntu-latest`, `ubuntu-24.04` and
|
||||
`ubuntu-22.04` jobs use `docker://docker.gitea.com/runner-images` as configured
|
||||
in `/etc/act_runner/config.yaml`. The application itself runs as native user
|
||||
services on the host. The job must be able to reach Gitea, SSH on labserver, and the
|
||||
application's public port; these are required for the final checks. The host
|
||||
must provide Python >=3.12, uv, compatible Node/npm, nginx with
|
||||
`/etc/nginx/mime.types`, Tesseract and `spa`/`eng` language data. The inspected
|
||||
application container uses Node 22. The account must be able to reach any
|
||||
required package registries, and uv, npm, nginx and Tesseract must be on its
|
||||
noninteractive SSH PATH. `systemd --user`, its D-Bus runtime and the
|
||||
sandbox options in the units must work on the target Ubuntu configuration.
|
||||
User services explicitly use `PrivateUsers=true` with filesystem sandboxing;
|
||||
this requires unprivileged user namespaces to be available. Depending on the
|
||||
host, sandbox settings may fail or be ineffective; validate their effective
|
||||
behavior before relying on them. Availability and compatibility have not been
|
||||
demonstrated by local tests.
|
||||
|
||||
The operator reports that `admon` has interactive sudo and that the runner is
|
||||
an `act-runner` host process. `admon` is a member of Docker and sudo groups and
|
||||
must not be the deployment/service account. No assumption is made about runner
|
||||
sudo access. Use `admon` for the one-time authorized setup, not as the runtime
|
||||
identity or as an Action credential.
|
||||
|
||||
## One-time operator setup
|
||||
|
||||
Only after authorization for physical changes, an administrator should:
|
||||
|
||||
1. Provision a dedicated non-root account with a real home and a shell capable
|
||||
of the SSH commands and SFTP used here. Verify it has no Docker,
|
||||
administrative, custom sudoers or capability grants. The installer rejects
|
||||
the standard privileged groups but cannot detect every possible grant.
|
||||
2. Create an isolated parent directory outside `/srv/workingnarrative-dev`
|
||||
and all existing installation/data paths; give only that account the needed
|
||||
access. For a new directory an administrator may use, for example,
|
||||
`sudo mkdir /srv/workingnarrative-native`, followed by a reviewed `chown`
|
||||
and `chmod 0750` for the chosen account. Do not overwrite or reassign an
|
||||
existing directory without a separate review.
|
||||
3. Provision an SSH deployment key for that account through the authorized
|
||||
channel. Restrict its `authorized_keys` entry appropriately and verify the
|
||||
server host-key fingerprint independently. Do not store the `admon` password
|
||||
or enable passwordless sudo. Confirm SSH and SFTP work for this account.
|
||||
4. Enable lingering once with `sudo loginctl enable-linger <account>`. Confirm
|
||||
the account's user manager and `/run/user/<uid>/bus` are available. This is
|
||||
needed so services survive the SSH session and start after reboot. Confirm
|
||||
that the required systemd user-service sandbox options work; the deployment
|
||||
fails closed if its manager or services cannot start.
|
||||
5. Configure the following Gitea Actions variables and secrets through the
|
||||
authorized administrative process. No credentials are provisioned here.
|
||||
|
||||
| Kind | Name | Value |
|
||||
|---|---|---|
|
||||
| Variable | `NATIVE_ACCOUNT` | Dedicated deployment/service account |
|
||||
| Variable | `NATIVE_SSH_PORT` | SSH port for the host |
|
||||
| Variable | `NATIVE_HOSTNAME` | Exact hostname returned by the host |
|
||||
| Variable | `NATIVE_PARENT` | Existing dedicated absolute parent directory |
|
||||
| Secret | `NATIVE_SSH_KEY` | Dedicated account's private key, in full |
|
||||
| Secret | `NATIVE_KNOWN_HOSTS` | Independently verified SSH known-hosts entry |
|
||||
|
||||
The job writes the key and known-hosts data to temporary files with a private
|
||||
umask and removes them on normal shell exit. Use a trusted runner and its
|
||||
secret controls; abrupt termination may prevent cleanup. The Gitea job token must have read access to the published Release and all
|
||||
private application submodules. Configure only the required cross-repository
|
||||
read access through the authorized Gitea administration process. The resolver
|
||||
passes the job token to Git as an HTTP header scoped to the institutional
|
||||
repository namespace; it does not embed credentials in repository URLs.
|
||||
|
||||
## Running a deployment
|
||||
|
||||
After review, integration and one-time setup, the operator may publish the
|
||||
Release pointing to the selected application commit. In Gitea, dispatch
|
||||
`deploy-terminal-release` from the reviewed installer branch and supply the
|
||||
exactly three inputs: published `tag`, public `puerto` (default `18090`) and
|
||||
loopback `puerto_api` (default `28090`). Both ports must be integers in
|
||||
`1024..65535`, distinct and available on the host. This is a new-install-only
|
||||
workflow. It rejects an existing instance, unit path or occupied port rather
|
||||
than updating or overwriting it. Choose a different free API port when another
|
||||
native instance already uses the requested value.
|
||||
|
||||
The Action performs these steps:
|
||||
|
||||
1. Validate the institutional event, origin and published Release, fetch the
|
||||
exact tag, peel it to a commit and check that neither tag nor Release changed.
|
||||
2. Check out only recognized institutional application gitlinks at their
|
||||
committed SHAs, independently of branch heads. Archive committed application
|
||||
components and record tag, release ID, tag object, application and installer
|
||||
commits, gitlinks, installer file hashes and bundle digest.
|
||||
3. Connect to the configured host with strict SSH host-key checking. Check the
|
||||
hostname, account, groups, user manager and lingering, create a unique
|
||||
account-owned staging directory, and transfer the bundle and reviewed
|
||||
installer. The requested API port is included in the release record and
|
||||
checked against the value passed to the remote installer. The job does not copy any files into system-wide systemd paths.
|
||||
4. Exclusively create `NATIVE_PARENT/isssteleon-native-<puerto>`, check both
|
||||
ports, install Python and Node dependencies using the release's lockfiles,
|
||||
and compile Angular. Create four new SQLite files and validate the effective
|
||||
Persistance URLs and empty isolated files before running Alembic.
|
||||
5. Generate three units in the instance, link them exclusively into the
|
||||
account's user-unit directory, reload its user manager, and enable/start the
|
||||
API, indicator worker and nginx. There is no privileged operation per run.
|
||||
6. Verify the three units, direct and proxied `/health`, Angular root and SPA
|
||||
fallback on the host. From the runner check the public root and proxied API
|
||||
on `10.0.10.41:<puerto>`, then recheck the host services. Any failure makes
|
||||
the Action fail; a successful external check is recorded on the host.
|
||||
|
||||
Preparation uses the selected release's equivalents of these commands:
|
||||
|
||||
```sh
|
||||
# application/WebApi
|
||||
uv sync --locked --no-dev --extra sql-drivers
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/cacu/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/cama/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/tea/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/governance/alembic.ini upgrade head
|
||||
# application/WebApp
|
||||
npm ci
|
||||
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
|
||||
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
|
||||
Docker installer is used or modified.
|
||||
|
||||
`installation.json` records identity, paths, service names, both requested ports, phases,
|
||||
status and health checks. User services use `default.target`, restart on
|
||||
failure and write to the user journal. For example, under the service account:
|
||||
|
||||
```sh
|
||||
systemctl --user status isssteleon-native-18090-{api,worker,web}.service
|
||||
journalctl --user -u isssteleon-native-18090-api.service -u isssteleon-native-18090-worker.service -u isssteleon-native-18090-web.service
|
||||
```
|
||||
|
||||
The helper explicitly sets `XDG_RUNTIME_DIR` and `DBUS_SESSION_BUS_ADDRESS`
|
||||
for noninteractive SSH. An operator's interactive session may also need these
|
||||
set for `systemctl --user` and `journalctl --user`. The host-local checks do
|
||||
not prove that the indicator worker completed a calculation or exercise
|
||||
clinical workflows; perform an authorized functional smoke test separately.
|
||||
|
||||
## Failure handling and validation
|
||||
|
||||
A failed build, migration, activation or health check makes the job fail.
|
||||
Instance files and databases are retained for inspection; no retry automatically
|
||||
reuses or migrates them. Failed activation attempts to disable/stop only the
|
||||
newly linked user units and records failure; any links left by systemd remain
|
||||
for inspection. If that stop
|
||||
itself fails, the operator must inspect the user manager; no global cleanup is
|
||||
performed. A public HTTP failure is reported back into the instance record when
|
||||
SSH remains available. If SSH fails while reporting, the job log is authoritative
|
||||
about that failure. Recovery, deletion or updates require a separate review.
|
||||
|
||||
Automated local tests use temporary Git repositories and bundles, mock SSH and
|
||||
systemd subprocesses, and exercise a real local port conflict. The observed
|
||||
staging application trees were exported and extracted from cached objects.
|
||||
These tests do not prove that user systemd, nginx, package downloads, real
|
||||
migrations, SSH, or the Gitea Actions context work on Ubuntu. Validate the full
|
||||
path in a disposable Ubuntu environment and complete the authorized one-time
|
||||
setup before requesting a physical test. The operator must check the actual
|
||||
public and loopback port availability and dedicated paths before that test.
|
||||
|
||||
The inspected local `dev` base was `e8d19e88e1022953f5714cf891129adfe992d3f7`;
|
||||
the older `91f3b9942a9df390da3435267c7131fe7464240c` was a historical local
|
||||
reference. The observed `staging` commit was
|
||||
`234c45c10ad901e75907d56b5443ecbc619af342` with application gitlink
|
||||
`f6d00f51f30cc5482c1711082f8656f2b3d9cd30`. A later selected commit must be
|
||||
reviewed against its own commands, migrations and gitlinks before publication.
|
||||
|
||||
A future `release: { types: [published] }` trigger is intentionally absent.
|
||||
After the manual workflow is validated, design and test event-specific tag
|
||||
handling and a trusted installer revision before enabling automatic publication
|
||||
triggers.
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Activate only this prepared instance through the account's user systemd manager."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import install
|
||||
|
||||
|
||||
def manager_environment(account):
|
||||
import pwd
|
||||
install.validate_service_account(account)
|
||||
entry = pwd.getpwuid(os.geteuid())
|
||||
home = Path(entry.pw_dir)
|
||||
if (not home.is_absolute() or home.resolve() != home or not home.is_dir()
|
||||
or home.stat().st_uid != os.geteuid() or home.stat().st_mode & 0o022):
|
||||
raise ValueError('service account home must be owned by the account and not group/world writable')
|
||||
runtime = Path('/run/user') / str(os.geteuid())
|
||||
bus = runtime / 'bus'
|
||||
if (runtime.is_symlink() or not runtime.is_dir() or runtime.stat().st_uid != os.geteuid()
|
||||
or bus.is_symlink() or not bus.exists() or not stat.S_ISSOCK(bus.stat().st_mode)):
|
||||
raise ValueError('user systemd runtime or D-Bus socket is unavailable')
|
||||
return {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'), 'HOME': str(home),
|
||||
'XDG_RUNTIME_DIR': str(runtime), 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=' + str(runtime / 'bus')}
|
||||
|
||||
|
||||
def command(args, env, *, check=True):
|
||||
return subprocess.run(args, env=env, capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def units_directory(home):
|
||||
"""Create account-owned systemd configuration without traversing symlinks."""
|
||||
current = Path(home)
|
||||
for part in ('.config', 'systemd', 'user'):
|
||||
current = current / part
|
||||
try:
|
||||
current.mkdir(mode=0o700)
|
||||
except FileExistsError:
|
||||
pass
|
||||
if current.is_symlink() or not current.is_dir() or current.stat().st_uid != os.geteuid() or current.stat().st_mode & 0o022:
|
||||
raise ValueError('unsafe user systemd unit directory: ' + str(current))
|
||||
return current
|
||||
|
||||
|
||||
def activate(instance, record, env):
|
||||
"""Link and start only fresh instance units; retain data and failure evidence."""
|
||||
base = Path(instance)
|
||||
install.validate_record(record)
|
||||
if (record.get('status') != 'prepared' or Path(record.get('base', '')) != base
|
||||
or base.is_symlink() or base.resolve() != base):
|
||||
raise ValueError('instance is not a freshly prepared installation')
|
||||
port = record['public_port']
|
||||
names = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
if record.get('services') != names or base.name != f'isssteleon-native-{port}':
|
||||
raise ValueError('invalid service identity')
|
||||
linger = command(['loginctl', 'show-user', record['account'], '--property=Linger', '--value'], env)
|
||||
if linger.stdout.strip().lower() != 'yes':
|
||||
raise ValueError('user lingering is not enabled; one-time operator setup is required')
|
||||
command(['systemctl', '--user', 'show-environment'], env)
|
||||
unit_dir = units_directory(env['HOME'])
|
||||
for name in names:
|
||||
source = base / 'units' / name
|
||||
dest = unit_dir / name
|
||||
if source.is_symlink() or not source.is_file() or dest.exists() or dest.is_symlink():
|
||||
raise ValueError('missing source or existing unit path: ' + name)
|
||||
state = command(['systemctl', '--user', 'show', name, '--property=LoadState', '--value'], env)
|
||||
if state.stdout.strip() != 'not-found':
|
||||
raise ValueError('systemd unit already exists: ' + name)
|
||||
record.update(status='activating', phase='linking_user_units', unit_directory=str(unit_dir))
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
linked = []
|
||||
try:
|
||||
for name in names:
|
||||
os.symlink(base / 'units' / name, unit_dir / name)
|
||||
linked.append(name)
|
||||
command(['systemctl', '--user', 'daemon-reload'], env)
|
||||
record.update(phase='starting_user_units')
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
for name in names:
|
||||
command(['systemctl', '--user', 'enable', '--now', name], env)
|
||||
record.update(status='started', phase='awaiting_health', started_at=int(time.time()))
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
return record
|
||||
except BaseException as exc:
|
||||
if linked:
|
||||
try:
|
||||
command(['systemctl', '--user', 'disable', '--now', *linked], env, check=False)
|
||||
except OSError:
|
||||
pass
|
||||
record.update(status='activation_failed', phase='activation_failed', error=type(exc).__name__)
|
||||
try:
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('instance', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
base = args.instance
|
||||
if not base.is_absolute() or base.is_symlink() or base.resolve() != base:
|
||||
raise ValueError('instance path must be absolute and not symlinked')
|
||||
path = base / 'installation.json'
|
||||
if path.is_symlink():
|
||||
raise ValueError('symlinked installation record')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
install.validate_record(record)
|
||||
install.check_installer_files(Path(__file__).resolve().parent, record)
|
||||
result = activate(base, record, manager_environment(record['account']))
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
||||
print('Activation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export exact committed application trees as a guarded release bundle."""
|
||||
import hashlib
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
import source
|
||||
|
||||
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'Transformation', 'WebApi', 'WebApp', 'models',
|
||||
'indicadores_kit'}
|
||||
|
||||
|
||||
def safe_member(member):
|
||||
path = PurePosixPath(member.name)
|
||||
return (not path.is_absolute() and member.name not in ('', '.')
|
||||
and all(part not in ('', '.', '..') for part in path.parts)
|
||||
and '\\' not in member.name and (member.isdir() or member.isfile()))
|
||||
|
||||
|
||||
def export(checkout, manifest, output):
|
||||
"""Export each verified commit, excluding Git metadata and untracked files."""
|
||||
checkout, output = Path(checkout), Path(output)
|
||||
seen = set()
|
||||
with output.open('xb') as raw, gzip.GzipFile(fileobj=raw, mode='wb', filename='', mtime=0) as zipped, tarfile.open(fileobj=zipped, mode='w:', format=tarfile.PAX_FORMAT) as bundle:
|
||||
for full, sha in sorted(manifest.items(), key=lambda item: (item[0].count('/'), item[0])):
|
||||
repo = checkout / full
|
||||
if source.git(repo, 'rev-parse', 'HEAD') != sha:
|
||||
raise ValueError('source checkout changed: ' + full)
|
||||
prefix = PurePosixPath('application') / PurePosixPath(full).relative_to('ISSSTELEON')
|
||||
with tempfile.TemporaryFile() as stream:
|
||||
subprocess.run(['git', '-C', str(repo), 'archive', '--format=tar', sha], stdout=stream, check=True)
|
||||
stream.seek(0)
|
||||
with tarfile.open(fileobj=stream, mode='r:') as archive:
|
||||
for member in archive:
|
||||
if full == 'ISSSTELEON' and PurePosixPath(member.name).parts[0] not in APPLICATION_COMPONENTS:
|
||||
continue
|
||||
if not safe_member(member):
|
||||
raise ValueError('unsafe Git archive member: ' + member.name)
|
||||
name = str(prefix / member.name)
|
||||
if name in seen:
|
||||
if member.isdir():
|
||||
continue
|
||||
raise ValueError('overlapping archive member: ' + name)
|
||||
seen.add(name)
|
||||
member.name = name
|
||||
member.uid = member.gid = 0
|
||||
member.uname = member.gname = ''
|
||||
member.mode = (0o755 if member.isdir() or member.mode & 0o111 else 0o644)
|
||||
bundle.addfile(member, archive.extractfile(member) if member.isfile() else None)
|
||||
digest = hashlib.sha256()
|
||||
with output.open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def write_record(path, record):
|
||||
with Path(path).open('x', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, indent=2, sort_keys=True)
|
||||
stream.write('\n')
|
||||
@@ -0,0 +1,389 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare a new isolated native instance; never activate privileged services."""
|
||||
import argparse
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import bundle
|
||||
|
||||
NAME = re.compile(r'^[a-z_][a-z0-9_-]{0,30}$')
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
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'}
|
||||
|
||||
|
||||
def validate_record(record):
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError('invalid release record')
|
||||
if (not isinstance(record.get('tag'), str) or not record['tag'] or len(record['tag']) > 255
|
||||
or any(ord(c) < 32 for c in record['tag']) or type(record.get('release_id')) is not int
|
||||
or record['release_id'] <= 0 or type(record.get('public_port')) is not int
|
||||
or not 1024 <= record['public_port'] <= 65535
|
||||
or type(record.get('api_port')) is not int or not 1024 <= record['api_port'] <= 65535
|
||||
or record['api_port'] == record['public_port']):
|
||||
raise ValueError('invalid release identity or port')
|
||||
if any(not isinstance(record.get(k), str) or not SHA.fullmatch(record[k])
|
||||
for k in ('application_sha', 'installer_sha', 'tag_object')):
|
||||
raise ValueError('invalid commit identity')
|
||||
if not isinstance(record.get('bundle_sha256'), str) or not DIGEST.fullmatch(record['bundle_sha256']):
|
||||
raise ValueError('invalid bundle digest')
|
||||
files = record.get('installer_files')
|
||||
if (not isinstance(files, dict) or set(files) != INSTALLER_FILES
|
||||
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)
|
||||
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/'):
|
||||
raise ValueError('invalid installer reference')
|
||||
|
||||
|
||||
def digest(path):
|
||||
value = hashlib.sha256()
|
||||
with open(path, 'rb') as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
value.update(block)
|
||||
return value.hexdigest()
|
||||
|
||||
|
||||
|
||||
def check_installer_files(directory, record):
|
||||
for name, expected in record['installer_files'].items():
|
||||
file = Path(directory) / name
|
||||
if file.is_symlink() or not file.is_file() or digest(file) != expected:
|
||||
raise ValueError('installer file differs from release record: ' + name)
|
||||
|
||||
|
||||
|
||||
def validate_service_account(account):
|
||||
"""Reject root and accounts with common administrative or Docker groups."""
|
||||
import grp
|
||||
import pwd
|
||||
if not NAME.fullmatch(account) or os.geteuid() == 0:
|
||||
raise ValueError('a non-root service account is required')
|
||||
entry = pwd.getpwuid(os.geteuid())
|
||||
if entry.pw_name != account:
|
||||
raise ValueError('preparation must run as the selected service account')
|
||||
groups = set(os.getgroups()) | set(os.getgrouplist(account, entry.pw_gid))
|
||||
groups.update((entry.pw_gid, os.getegid()))
|
||||
privileged = {0}
|
||||
for name in ('docker', 'sudo', 'wheel'):
|
||||
try:
|
||||
privileged.add(grp.getgrnam(name).gr_gid)
|
||||
except KeyError:
|
||||
pass
|
||||
if groups & privileged:
|
||||
raise ValueError('service account belongs to a privileged administrative or Docker group')
|
||||
|
||||
|
||||
|
||||
def require_private_parent(parent):
|
||||
"""Reject installation parents that other accounts can replace or modify."""
|
||||
metadata = parent.stat()
|
||||
if metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022:
|
||||
raise ValueError('installation parent must be owned by the service account and not group/world writable')
|
||||
|
||||
|
||||
def validate_parent(parent):
|
||||
parent = Path(parent)
|
||||
if not parent.is_absolute() or not SAFE_PATH.fullmatch(str(parent)) or not parent.is_dir():
|
||||
raise ValueError('parent must be an existing absolute path without whitespace or shell metacharacters')
|
||||
if parent.resolve() != parent:
|
||||
raise ValueError('parent and its ancestors must not be symlinks or contain dot components')
|
||||
destination = parent / 'instance'
|
||||
if destination == DOCKER_ROOT or DOCKER_ROOT in destination.parents or destination in DOCKER_ROOT.parents:
|
||||
raise ValueError('native installation must be separate from the Docker deployment')
|
||||
require_private_parent(parent)
|
||||
return parent
|
||||
|
||||
|
||||
def check_port(port, public):
|
||||
if type(port) is not int or not 1024 <= port <= 65535:
|
||||
raise ValueError('ports must be between 1024 and 65535')
|
||||
families = [(socket.AF_INET, '0.0.0.0' if public else '127.0.0.1')]
|
||||
if socket.has_ipv6:
|
||||
families.append((socket.AF_INET6, '::' if public else '::1'))
|
||||
for family, address in families:
|
||||
try:
|
||||
with socket.socket(family, socket.SOCK_STREAM) as sock:
|
||||
if family == socket.AF_INET6:
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
||||
sock.bind((address, port))
|
||||
except OSError as exc:
|
||||
if exc.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL) and family == socket.AF_INET6:
|
||||
continue
|
||||
raise ValueError(f'port {port} is unavailable: {exc}') from exc
|
||||
|
||||
|
||||
def extract_bundle(archive_path, target):
|
||||
"""Extract regular files only into a new directory; reject links and duplicates."""
|
||||
target = Path(target)
|
||||
seen = set()
|
||||
total = 0
|
||||
with tarfile.open(archive_path, 'r:gz') as archive:
|
||||
for member in archive:
|
||||
if not bundle.safe_member(member):
|
||||
raise ValueError('unsafe archive member')
|
||||
path = PurePosixPath(member.name)
|
||||
if not path.parts or path.parts[0] != 'application' or member.name in seen:
|
||||
raise ValueError('invalid or duplicate archive member')
|
||||
seen.add(member.name)
|
||||
total += member.size
|
||||
if total > 4 * 1024 ** 3 or len(seen) > 250000:
|
||||
raise ValueError('archive exceeds extraction limits')
|
||||
dest = target.joinpath(*path.parts)
|
||||
if member.isdir():
|
||||
dest.mkdir(parents=True, exist_ok=True, mode=0o755)
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
|
||||
with archive.extractfile(member) as source_stream, dest.open('xb') as out:
|
||||
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 += [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):
|
||||
temporary = path.with_suffix('.tmp')
|
||||
with temporary.open('x', 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(temporary, path)
|
||||
|
||||
|
||||
def environment(base):
|
||||
data = base / 'data'
|
||||
result = {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'),
|
||||
'HOME': str(data), 'LANG': 'C.UTF-8', 'UV_CACHE_DIR': str(data / 'uv-cache'),
|
||||
'npm_config_cache': str(data / 'npm-cache'),
|
||||
'MLFLOW_TRACKING_URI': 'sqlite:///' + str(data / 'mlflow.db'),
|
||||
'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'}
|
||||
for domain in DOMAINS:
|
||||
result[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
|
||||
return result
|
||||
|
||||
|
||||
def run(args, cwd, env):
|
||||
subprocess.run([str(arg) for arg in args], cwd=cwd, env=env, check=True)
|
||||
|
||||
|
||||
|
||||
def verify_database_targets(uv, app, env, data):
|
||||
"""Check the selected application's effective settings before any migration."""
|
||||
code = """import os, sys
|
||||
from pathlib import Path
|
||||
from sqlalchemy.engine import make_url
|
||||
from persistance.settings import settings
|
||||
base = Path(sys.argv[1]).resolve()
|
||||
for domain in ('cacu', 'cama', 'tea', 'governance'):
|
||||
expected = base / (domain + '.db')
|
||||
url = getattr(settings, domain + '_database_url')
|
||||
parsed = make_url(url)
|
||||
if (url != os.environ[domain.upper() + '_DATABASE_URL'] or parsed.drivername != 'sqlite'
|
||||
or not parsed.database or Path(parsed.database) != expected or expected.is_symlink()
|
||||
or expected.resolve().parent != base or not expected.is_file() or expected.stat().st_size != 0):
|
||||
raise SystemExit('effective migration destination rejected: ' + domain)
|
||||
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):
|
||||
work = base / 'application' / 'WebApi'
|
||||
binary = work / '.venv' / 'bin'
|
||||
name = base.name
|
||||
common = f'''[Unit]\nDescription=ISSSTELEON native {service} {name}\nAfter=network.target\n'''
|
||||
if service == 'worker':
|
||||
common += f'After={name}-api.service\nRequires={name}-api.service\n'
|
||||
if service == 'web':
|
||||
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}',
|
||||
'web': f'{nginx} -c {base}/nginx.conf -p {base}/',
|
||||
}[service]
|
||||
directory = base if service == 'web' else work
|
||||
return common + f'''\n[Service]\nType=simple\nWorkingDirectory={directory}\nEnvironmentFile={base}/service.env\nExecStart={command}\nRestart=on-failure\nRestartSec=5\nNoNewPrivileges=true\nPrivateUsers=true\nPrivateTmp=true\nProtectSystem=strict\nReadWritePaths={base}/data\n\n[Install]\nWantedBy=default.target\n'''
|
||||
|
||||
|
||||
def nginx_conf(base, port, api_port):
|
||||
data = base / 'data'
|
||||
return f'''worker_processes 1;\ndaemon off;\npid {data}/nginx.pid;\nerror_log stderr;\nevents {{ worker_connections 1024; }}\nhttp {{\n include /etc/nginx/mime.types;\n default_type application/octet-stream;\n access_log /dev/stdout;\n client_body_temp_path {data}/nginx-client;\n proxy_temp_path {data}/nginx-proxy;\n fastcgi_temp_path {data}/nginx-fastcgi;\n uwsgi_temp_path {data}/nginx-uwsgi;\n scgi_temp_path {data}/nginx-scgi;\n server {{\n listen {port};\n server_name _;\n root {base}/application/WebApp/dist/WebApp/browser;\n client_max_body_size 270m;\n location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {{\n proxy_pass http://127.0.0.1:{api_port};\n proxy_set_header Host $host;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 600s;\n }}\n location ~* \\.(js|css)$ {{ add_header Cache-Control "public, max-age=31536000, immutable"; try_files $uri =404; }}\n location / {{ add_header Cache-Control "no-cache"; try_files $uri $uri/ /index.html; }}\n }}\n}}\n'''
|
||||
|
||||
|
||||
def prepare(parent, record, archive_path, expected_digest, api_port, account, expected_hostname, tools):
|
||||
"""Create a fresh instance; failure retains its data and prevents retries over it."""
|
||||
validate_record(record)
|
||||
if (not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', expected_hostname)
|
||||
or socket.gethostname().lower() != expected_hostname.lower()):
|
||||
raise ValueError('host identity does not match the explicitly expected hostname')
|
||||
parent = validate_parent(parent)
|
||||
validate_service_account(account)
|
||||
if expected_digest != record['bundle_sha256'] or digest(archive_path) != expected_digest:
|
||||
raise ValueError('bundle digest does not match the independently supplied digest and record')
|
||||
port = record['public_port']
|
||||
if type(api_port) is not int or api_port != record['api_port']:
|
||||
raise ValueError('API port does not match the validated release request')
|
||||
check_port(port, True)
|
||||
check_port(api_port, False)
|
||||
base = parent / f'isssteleon-native-{port}'
|
||||
base.mkdir(mode=0o750) # exclusive; no update or reuse
|
||||
state = dict(record, status='preparing', phase='reserved', base=str(base), api_port=api_port,
|
||||
account=account, hostname=expected_hostname, services=[f'{base.name}-{part}.service' for part in ('api', 'worker', 'web')])
|
||||
metadata = base / 'installation.json'
|
||||
try:
|
||||
atomic_record(metadata, state)
|
||||
(base / 'data').mkdir(mode=0o700)
|
||||
worker = extract_bundle(archive_path, base)
|
||||
app = base / 'application'
|
||||
env = environment(base)
|
||||
for domain in DOMAINS:
|
||||
path = base / 'data' / (domain + '.db')
|
||||
with path.open('xb'):
|
||||
pass
|
||||
os.chmod(path, 0o600)
|
||||
state.update(phase='dependencies')
|
||||
atomic_record(metadata, state)
|
||||
run([tools['uv'], 'sync', '--locked', '--no-dev', '--extra', 'sql-drivers'], app / 'WebApi', env)
|
||||
run([tools['npm'], 'ci'], app / 'WebApp', env)
|
||||
run([tools['npm'], 'run', 'build', '--', '--configuration', 'production'], app / 'WebApp', env)
|
||||
if not (app / 'WebApp' / 'dist' / 'WebApp' / 'browser' / 'index.html').is_file():
|
||||
raise ValueError('Angular distribution index is missing')
|
||||
state.update(phase='verifying_migration_targets')
|
||||
atomic_record(metadata, state)
|
||||
verify_database_targets(tools['uv'], app, env, base / 'data')
|
||||
state.update(phase='migrations')
|
||||
atomic_record(metadata, state)
|
||||
for domain in DOMAINS:
|
||||
target = base / 'data' / (domain + '.db')
|
||||
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')
|
||||
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)
|
||||
return state
|
||||
except BaseException as exc:
|
||||
state.update(status='failed', error=type(exc).__name__)
|
||||
try:
|
||||
atomic_record(metadata, state)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def available_tools():
|
||||
result = {}
|
||||
for name in ('uv', 'npm', 'nginx', 'tesseract'):
|
||||
path = shutil.which(name)
|
||||
if not path or not SAFE_PATH.fullmatch(path):
|
||||
raise ValueError('missing or unsafe executable path: ' + name)
|
||||
result[name] = path
|
||||
languages = subprocess.run([result['tesseract'], '--list-langs'], capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
if not {'spa', 'eng'} <= set(languages):
|
||||
raise ValueError('Tesseract requires spa and eng language data')
|
||||
if not Path('/etc/nginx/mime.types').is_file():
|
||||
raise ValueError('nginx mime.types is missing')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--record', required=True, type=Path)
|
||||
parser.add_argument('--bundle', required=True, type=Path)
|
||||
parser.add_argument('--bundle-sha256', required=True)
|
||||
parser.add_argument('--parent', required=True, type=Path)
|
||||
parser.add_argument('--api-port', required=True, type=int)
|
||||
parser.add_argument('--account', required=True)
|
||||
parser.add_argument('--expected-hostname', required=True)
|
||||
args = parser.parse_args()
|
||||
if sys.platform != 'linux':
|
||||
parser.error('native installation requires Linux')
|
||||
try:
|
||||
if Path('/.dockerenv').exists() or Path('/run/.containerenv').exists():
|
||||
raise ValueError('run preparation on the selected host, not inside a container')
|
||||
record = json.loads(args.record.read_text(encoding='utf-8'))
|
||||
validate_record(record)
|
||||
check_installer_files(Path(__file__).resolve().parent, record)
|
||||
result = prepare(args.parent, record, args.bundle, args.bundle_sha256, args.api_port, args.account, args.expected_hostname, available_tools())
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, json.JSONDecodeError) as exc:
|
||||
print('Native preparation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy and verify a release through an explicitly configured non-root SSH account."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
import time
|
||||
import urllib.error
|
||||
|
||||
import verify
|
||||
|
||||
import install
|
||||
|
||||
FILES = ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py', 'release-record.json', 'release-source.tar.gz')
|
||||
HOST = re.compile(r'^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$')
|
||||
|
||||
|
||||
def ssh_options(identity, known_hosts):
|
||||
return ['-i', str(identity), '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
|
||||
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(known_hosts)]
|
||||
|
||||
|
||||
def remote_command(arguments):
|
||||
return shlex.join([str(part) for part in arguments])
|
||||
|
||||
|
||||
|
||||
def check_public(host, port, timeout=90):
|
||||
"""Require the runner to reach both the application and proxied API."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
status, body = verify.request(f'http://{host}:{port}/health')
|
||||
health = json.loads(body)
|
||||
index_status, index = verify.request(f'http://{host}:{port}/')
|
||||
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok' or index_status != 200 or not index:
|
||||
raise ValueError('public HTTP or proxied API health check failed')
|
||||
return
|
||||
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError('public endpoint is unavailable: ' + str(exc)) from exc
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def prepare(bundle_dir, digest, host, port, account, expected_hostname, parent, api_port, identity, known_hosts):
|
||||
"""Use pinned host keys and create a unique staging directory without elevated privileges."""
|
||||
bundle_dir = Path(bundle_dir).resolve()
|
||||
identity, known_hosts = Path(identity).resolve(), Path(known_hosts).resolve()
|
||||
if (not HOST.fullmatch(host) or not HOST.fullmatch(expected_hostname) or not install.NAME.fullmatch(account)
|
||||
or account == 'root' or not 1 <= port <= 65535 or not identity.is_file() or not known_hosts.is_file()
|
||||
or not install.SAFE_PATH.fullmatch(parent) or parent == '/' or '..' in Path(parent).parts):
|
||||
raise ValueError('invalid explicit SSH endpoint, host key, account or parent')
|
||||
files = [bundle_dir / name for name in FILES]
|
||||
if any(not item.is_file() or item.is_symlink() for item in files):
|
||||
raise ValueError('bundle or installer file is missing or symlinked')
|
||||
record = json.loads((bundle_dir / 'release-record.json').read_text(encoding='utf-8'))
|
||||
install.validate_record(record)
|
||||
install.check_installer_files(bundle_dir, record)
|
||||
if digest != record['bundle_sha256'] or install.digest(bundle_dir / 'release-source.tar.gz') != digest:
|
||||
raise ValueError('bundle checksum mismatch')
|
||||
if type(api_port) is not int or api_port != record['api_port']:
|
||||
raise ValueError('API port does not match the validated release request')
|
||||
ssh, scp = shutil.which('ssh'), shutil.which('scp')
|
||||
if not ssh or not scp:
|
||||
raise ValueError('ssh and scp are required')
|
||||
endpoint = account + '@' + host
|
||||
stage = parent.rstrip('/') + '/.release-' + uuid.uuid4().hex
|
||||
options = ssh_options(identity, known_hosts)
|
||||
# Check identity and containment remotely before making any files.
|
||||
guard = '''import grp,os,pathlib,pwd,socket,subprocess,sys
|
||||
parent,stage,account,host=sys.argv[1:]
|
||||
p=pathlib.Path(parent)
|
||||
resolved=p.resolve(strict=True)
|
||||
docker=pathlib.Path('/srv/workingnarrative-dev')
|
||||
entry=pwd.getpwuid(os.geteuid())
|
||||
if str(resolved)!=parent or not p.is_dir() or p.stat().st_uid!=os.geteuid() or p.stat().st_mode & 0o022 or docker==resolved or docker in resolved.parents or socket.gethostname().lower()!=host.lower() or os.geteuid()==0 or entry.pw_name!=account:
|
||||
raise SystemExit('remote identity or parent rejected')
|
||||
groups=set(os.getgroups()) | set(os.getgrouplist(account,entry.pw_gid)) | {entry.pw_gid,os.getegid()}
|
||||
privileged={0}
|
||||
for name in ('docker','sudo','wheel'):
|
||||
try:
|
||||
privileged.add(grp.getgrnam(name).gr_gid)
|
||||
except KeyError:
|
||||
pass
|
||||
if groups & privileged:
|
||||
raise SystemExit('remote service account has privileged group membership')
|
||||
runtime=pathlib.Path('/run/user') / str(os.geteuid())
|
||||
if not runtime.is_dir() or not (runtime / 'bus').exists():
|
||||
raise SystemExit('user manager runtime is unavailable')
|
||||
env=dict(os.environ, HOME=entry.pw_dir, XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(runtime / 'bus'))
|
||||
linger=subprocess.run(['loginctl','show-user',account,'--property=Linger','--value'],env=env,text=True,capture_output=True,check=True)
|
||||
if linger.stdout.strip().lower() != 'yes':
|
||||
raise SystemExit('user lingering is not enabled')
|
||||
subprocess.run(['systemctl','--user','show-environment'],env=env,capture_output=True,check=True)
|
||||
os.mkdir(stage,0o700)
|
||||
'''
|
||||
subprocess.run([ssh, *options, '-p', str(port), endpoint,
|
||||
remote_command(['python3', '-c', guard, parent, stage, account, expected_hostname])], check=True)
|
||||
print('Remote staging directory:', stage, flush=True)
|
||||
subprocess.run([scp, *options, '-P', str(port), *map(str, files), endpoint + ':' + stage + '/'], check=True)
|
||||
command = ['python3', stage + '/install.py', '--record', stage + '/release-record.json',
|
||||
'--bundle', stage + '/release-source.tar.gz', '--bundle-sha256', digest,
|
||||
'--parent', parent, '--account', account, '--expected-hostname', expected_hostname,
|
||||
'--api-port', str(api_port)]
|
||||
subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(command)], check=True)
|
||||
instance = parent.rstrip('/') + '/isssteleon-native-' + str(record['public_port'])
|
||||
def remote_run(args, check=True):
|
||||
return subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(args)], check=check)
|
||||
remote_run(['python3', stage + '/activate.py', instance])
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--wait-seconds', '180'])
|
||||
try:
|
||||
check_public(host, record['public_port'])
|
||||
except (OSError, ValueError) as exc:
|
||||
try:
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'failed', '--wait-seconds', '0'], check=False)
|
||||
except OSError:
|
||||
pass
|
||||
raise exc
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'ok', '--wait-seconds', '0'])
|
||||
return stage
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--bundle-dir', required=True, type=Path)
|
||||
parser.add_argument('--bundle-sha256', required=True)
|
||||
parser.add_argument('--host', required=True)
|
||||
parser.add_argument('--ssh-port', required=True, type=int)
|
||||
parser.add_argument('--account', required=True)
|
||||
parser.add_argument('--expected-hostname', required=True)
|
||||
parser.add_argument('--parent', required=True)
|
||||
parser.add_argument('--api-port', required=True, type=int)
|
||||
parser.add_argument('--identity', required=True, type=Path)
|
||||
parser.add_argument('--known-hosts', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
prepare(args.bundle_dir, args.bundle_sha256, args.host, args.ssh_port, args.account,
|
||||
args.expected_hostname, args.parent, args.api_port, args.identity, args.known_hosts)
|
||||
print('Native deployment is active and public HTTP checks passed.')
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
||||
print('Remote preparation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve a published institutional release without deploying it."""
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import source
|
||||
import bundle
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SERVER = 'http://10.0.10.41:3000'
|
||||
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
|
||||
ORIGIN = SERVER + '/' + REPOSITORY + '.git'
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return subprocess.run(['git', '-C', str(root), *args], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
def validate_tag(tag):
|
||||
if not tag or tag.startswith(('-', 'refs/')) or re.fullmatch(r'[0-9a-fA-F]{40}', tag):
|
||||
raise ValueError('tag must be an unambiguous tag name')
|
||||
subprocess.run(['git', 'check-ref-format', 'refs/tags/' + tag], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return tag
|
||||
|
||||
|
||||
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 dispatch(root, env):
|
||||
ref, name, sha = (env.get('DISPATCH_REF', ''), env.get('DISPATCH_REF_NAME', ''), env.get('DISPATCH_SHA', ''))
|
||||
if (env.get('DISPATCH_REPOSITORY') != REPOSITORY or env.get('DISPATCH_SERVER', '').rstrip('/') != SERVER
|
||||
or env.get('DISPATCH_REF_TYPE') != 'branch' or not name or ref != 'refs/heads/' + name
|
||||
or not SHA.fullmatch(sha)):
|
||||
raise ValueError('invalid workflow dispatch identity')
|
||||
subprocess.run(['git', 'check-ref-format', ref], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
if git(root, 'rev-parse', 'HEAD') != sha or git(root, 'remote', 'get-url', 'origin') not in (ORIGIN, ORIGIN.removesuffix('.git')):
|
||||
raise ValueError('workflow checkout identity mismatch')
|
||||
return {'installer_ref': ref, 'installer_sha': sha}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def release(tag, token):
|
||||
if not token:
|
||||
raise ValueError('Gitea token is required')
|
||||
url = SERVER + '/api/v1/repos/' + REPOSITORY + '/releases/tags/' + urllib.parse.quote(tag, safe='')
|
||||
req = urllib.request.Request(url, headers={'Authorization': 'token ' + token, 'Accept': 'application/json'})
|
||||
with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as response:
|
||||
data = json.load(response)
|
||||
if (not isinstance(data, dict) or type(data.get('id')) is not int or data['id'] <= 0
|
||||
or data.get('tag_name') != tag or data.get('draft') is not False
|
||||
or not data.get('published_at')):
|
||||
raise ValueError('tag does not identify a published release')
|
||||
return {'release_id': data['id'], 'tag': tag}
|
||||
|
||||
|
||||
def resolve(root, tag, port, api_port, env):
|
||||
validate_tag(tag)
|
||||
port = validate_port(port)
|
||||
api_port = validate_port(api_port)
|
||||
if port == api_port:
|
||||
raise ValueError('public and API ports must differ')
|
||||
installer = dispatch(root, env)
|
||||
first = release(tag, env.get('RELEASE_TOKEN', ''))
|
||||
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
|
||||
try:
|
||||
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + tag + ':' + ref)
|
||||
object_sha = git(root, 'rev-parse', '--verify', ref)
|
||||
commit = git(root, 'rev-parse', '--verify', ref + '^{commit}')
|
||||
if not SHA.fullmatch(object_sha) or not SHA.fullmatch(commit):
|
||||
raise ValueError('invalid fetched tag object or commit')
|
||||
# A remote tag changed during resolution must not be silently accepted.
|
||||
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
|
||||
if lines != [object_sha + '\trefs/tags/' + tag]:
|
||||
raise ValueError('remote tag changed during resolution')
|
||||
if release(tag, env.get('RELEASE_TOKEN', '')) != first:
|
||||
raise ValueError('release changed during resolution')
|
||||
return dict(first, **installer, tag_object=object_sha, application_sha=commit, public_port=port, api_port=api_port)
|
||||
finally:
|
||||
git(root, 'update-ref', '-d', ref)
|
||||
|
||||
|
||||
|
||||
def prepare_source(root, record, output=None):
|
||||
"""Fetch the same tag again into a disposable checkout and verify gitlinks."""
|
||||
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
|
||||
try:
|
||||
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + record['tag'] + ':' + ref)
|
||||
if (git(root, 'rev-parse', '--verify', ref) != record['tag_object']
|
||||
or git(root, 'rev-parse', '--verify', ref + '^{commit}') != record['application_sha']):
|
||||
raise ValueError('tag changed before source preparation')
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-release-') as temporary:
|
||||
checkout = Path(temporary)
|
||||
subprocess.run(['git', 'init', '--quiet', str(checkout)], check=True)
|
||||
git(checkout, 'fetch', '--no-tags', str(root), ref)
|
||||
git(checkout, 'checkout', '--quiet', '--detach', record['application_sha'])
|
||||
if git(checkout, 'rev-parse', 'HEAD') != record['application_sha']:
|
||||
raise ValueError('application checkout mismatch')
|
||||
manifest = source.checkout_pinned(checkout)
|
||||
if output is not None:
|
||||
record['bundle_sha256'] = bundle.export(checkout, manifest, output)
|
||||
return manifest
|
||||
finally:
|
||||
git(root, 'update-ref', '-d', ref)
|
||||
|
||||
|
||||
|
||||
|
||||
def installer_manifest(root, sha):
|
||||
"""Bind exported installer scripts to the dispatched committed revision."""
|
||||
manifest = {}
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
relative = '.gitea/deploy-terminal/' + name
|
||||
committed = subprocess.run(['git', '-C', str(root), 'show', sha + ':' + relative],
|
||||
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
|
||||
if (Path(root) / relative).read_bytes() != committed:
|
||||
raise ValueError('installer file differs from dispatched revision: ' + name)
|
||||
manifest[name] = hashlib.sha256(committed).hexdigest()
|
||||
return manifest
|
||||
|
||||
|
||||
def revalidate(root, record, token):
|
||||
"""Fail if the tag or publication changed while the bundle was being built."""
|
||||
tag = validate_tag(record['tag'])
|
||||
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
|
||||
if lines != [record['tag_object'] + '\trefs/tags/' + tag]:
|
||||
raise ValueError('remote tag changed before bundle publication')
|
||||
if release(tag, token) != {'tag': tag, 'release_id': record['release_id']}:
|
||||
raise ValueError('release changed before bundle publication')
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
record = resolve(ROOT, os.environ.get('REQUESTED_TAG', ''), os.environ.get('REQUESTED_PORT', ''),
|
||||
os.environ.get('REQUESTED_API_PORT', ''), os.environ)
|
||||
output = Path(os.environ.get('RELEASE_OUTPUT', 'release-source.tar.gz'))
|
||||
record['installer_files'] = installer_manifest(ROOT, record['installer_sha'])
|
||||
record['gitlinks'] = prepare_source(ROOT, record, output)
|
||||
revalidate(ROOT, record, os.environ.get('RELEASE_TOKEN', ''))
|
||||
bundle.write_record(output.with_name('release-record.json'), record)
|
||||
print(json.dumps(record, sort_keys=True), flush=True)
|
||||
print('Release bundle prepared for automated native deployment.', flush=True)
|
||||
return 0
|
||||
except (ValueError, subprocess.CalledProcessError, OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
print('Release resolution failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check out only institutional application gitlinks at their committed SHAs."""
|
||||
import os
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ORIGINS = {
|
||||
'ISSSTELEON': 'ISSSTELEON',
|
||||
'ISSSTELEON/WebApi': 'WebApi',
|
||||
'ISSSTELEON/WebApp': 'WebApp',
|
||||
'ISSSTELEON/models': 'models',
|
||||
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
|
||||
}
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
|
||||
|
||||
def git(repo, *args, binary=False):
|
||||
env = os.environ.copy()
|
||||
token = env.get('RELEASE_TOKEN')
|
||||
if token:
|
||||
try:
|
||||
count = int(env.get('GIT_CONFIG_COUNT', '0'))
|
||||
except ValueError as exc:
|
||||
raise ValueError('invalid inherited Git configuration count') from exc
|
||||
if not 0 <= count < 32:
|
||||
raise ValueError('invalid inherited Git configuration count')
|
||||
encoded = base64.b64encode(('x-access-token:' + token).encode()).decode('ascii')
|
||||
env['GIT_CONFIG_KEY_' + str(count)] = 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader'
|
||||
env['GIT_CONFIG_VALUE_' + str(count)] = 'AUTHORIZATION: basic ' + encoded
|
||||
env['GIT_CONFIG_COUNT'] = str(count + 1)
|
||||
env['GIT_TERMINAL_PROMPT'] = '0'
|
||||
result = subprocess.run(['git', '-C', str(repo), *args], check=True, env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=not binary)
|
||||
return result.stdout if binary else result.stdout.strip()
|
||||
|
||||
|
||||
def gitlinks(repo):
|
||||
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
|
||||
links = {}
|
||||
for entry in entries.split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, name = entry.split(b'\t', 1)
|
||||
mode, kind, sha = meta.decode('ascii').split()
|
||||
if mode != '160000':
|
||||
continue
|
||||
path = os.fsdecode(name)
|
||||
if (kind != 'commit' or not SHA.fullmatch(sha) or path.startswith('/')
|
||||
or any(part in ('', '.', '..') for part in path.split('/')) or '\\' in path):
|
||||
raise ValueError('unsafe gitlink entry')
|
||||
links[path] = sha
|
||||
return links
|
||||
|
||||
|
||||
def checkout_pinned(root):
|
||||
"""Ignore unrelated top-level submodules; reject unknown application origins."""
|
||||
root = Path(root)
|
||||
outer = gitlinks(root)
|
||||
if 'ISSSTELEON' not in outer:
|
||||
raise ValueError('application gitlink is missing')
|
||||
manifest = {}
|
||||
|
||||
def visit(repo, path, prefix, sha):
|
||||
full = prefix + '/' + path if prefix else path
|
||||
if full not in ORIGINS:
|
||||
raise ValueError('unrecognized application gitlink: ' + full)
|
||||
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
|
||||
matches = []
|
||||
for line in config.splitlines():
|
||||
parts = line.split(None, 1)
|
||||
if len(parts) == 2 and parts[1] == path:
|
||||
matches.append(parts[0][len('submodule.'):-len('.path')])
|
||||
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
|
||||
raise ValueError('ambiguous submodule mapping: ' + full)
|
||||
name = matches[0]
|
||||
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + ORIGINS[full] + '.git'
|
||||
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}',
|
||||
'submodule', 'update', '--init', '--checkout', '--', path)
|
||||
child = repo / path
|
||||
if git(child, 'rev-parse', 'HEAD') != sha:
|
||||
raise ValueError('gitlink checkout mismatch: ' + full)
|
||||
manifest[full] = sha
|
||||
for nested, child_sha in gitlinks(child).items():
|
||||
visit(child, nested, full, child_sha)
|
||||
|
||||
visit(root, 'ISSSTELEON', '', outer['ISSSTELEON'])
|
||||
return manifest
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Test user-service activation and failure handling with isolated unit directories."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import activate
|
||||
import install
|
||||
|
||||
|
||||
class ActivationTests(unittest.TestCase):
|
||||
"""Temporary files and a mocked user manager stand in for systemd and the host."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name).resolve()
|
||||
self.base = self.root / 'isssteleon-native-18090'
|
||||
self.base.mkdir()
|
||||
(self.base / 'data').mkdir()
|
||||
(self.base / 'data' / 'cacu.db').write_bytes(b'existing')
|
||||
(self.base / 'units').mkdir()
|
||||
self.names = [f'isssteleon-native-18090-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
for name in self.names:
|
||||
(self.base / 'units' / name).write_text('[Service]\n', encoding='utf-8')
|
||||
self.unit_dir = self.root / 'user-units'
|
||||
self.unit_dir.mkdir()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': 'd' * 64, 'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
|
||||
'gitlinks': {name: 'f' * 40 for name in install.REQUIRED_LINKS},
|
||||
'status': 'prepared', 'base': str(self.base), 'api_port': 28090,
|
||||
'account': 'wnnative', 'services': self.names}
|
||||
(self.base / 'installation.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
self.commands = []
|
||||
self.env = {'HOME': str(self.root)}
|
||||
|
||||
def fake_command(self, args, env, check=True):
|
||||
self.commands.append(args)
|
||||
if args[0] == 'loginctl': return types.SimpleNamespace(stdout='yes\n', returncode=0)
|
||||
if '--property=LoadState' in args: return types.SimpleNamespace(stdout='not-found\n', returncode=0)
|
||||
return types.SimpleNamespace(stdout='', returncode=0)
|
||||
|
||||
def fake_symlink(self, source, dest):
|
||||
Path(dest).write_text(str(source), encoding='utf-8')
|
||||
|
||||
def run_activate(self):
|
||||
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=self.fake_command), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
|
||||
return activate.activate(self.base, self.record, self.env)
|
||||
|
||||
def test_starts_only_new_user_units(self):
|
||||
"""Activation enables the three instance units in the user manager without root operations."""
|
||||
result = self.run_activate()
|
||||
self.assertEqual(result['status'], 'started')
|
||||
enabled = [cmd for cmd in self.commands if 'enable' in cmd]
|
||||
self.assertEqual(len(enabled), 3)
|
||||
self.assertTrue(all(cmd[:2] == ['systemctl', '--user'] for cmd in enabled))
|
||||
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
|
||||
def test_existing_unit_is_never_replaced(self):
|
||||
"""An existing user unit must stop activation without modifying the existing unit or data."""
|
||||
existing = self.unit_dir / self.names[0]
|
||||
existing.write_text('keep', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): self.run_activate()
|
||||
self.assertEqual(existing.read_text(), 'keep')
|
||||
self.assertFalse(any('enable' in cmd for cmd in self.commands))
|
||||
|
||||
def test_linger_is_required(self):
|
||||
"""A user manager without lingering must fail before creating or starting a unit."""
|
||||
def no_linger(args, env, check=True):
|
||||
return types.SimpleNamespace(stdout='no\n', returncode=0)
|
||||
with patch.object(activate, 'command', side_effect=no_linger), patch.object(activate, 'units_directory') as units:
|
||||
with self.assertRaises(ValueError): activate.activate(self.base, self.record, self.env)
|
||||
units.assert_not_called()
|
||||
|
||||
def test_start_failure_stops_only_new_units_and_keeps_data(self):
|
||||
"""A failed startup must mark failure and stop the newly linked units while retaining data."""
|
||||
def fail_start(args, env, check=True):
|
||||
if 'enable' in args and args[-1].endswith('-worker.service'):
|
||||
raise subprocess.CalledProcessError(1, args)
|
||||
return self.fake_command(args, env, check)
|
||||
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=fail_start), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
|
||||
with self.assertRaises(subprocess.CalledProcessError): activate.activate(self.base, self.record, self.env)
|
||||
state = json.loads((self.base / 'installation.json').read_text())
|
||||
self.assertEqual(state['status'], 'activation_failed')
|
||||
self.assertTrue(any(cmd[:4] == ['systemctl', '--user', 'disable', '--now'] for cmd in self.commands))
|
||||
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Verify bundles export committed trees, excluding working files and Git metadata."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import bundle
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
return subprocess.run(['git', '-C', str(repo), *args], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
class BundleTests(unittest.TestCase):
|
||||
"""Two small temporary Git repositories model the application and a pinned child."""
|
||||
def test_export_uses_git_objects_and_pinned_nested_checkout(self):
|
||||
"""Uncommitted changes and untracked files cannot enter a release archive."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
app = root / 'ISSSTELEON'
|
||||
child = app / 'WebApi'
|
||||
for repo in (app, child):
|
||||
repo.mkdir(parents=True, exist_ok=True)
|
||||
git(repo, 'init', '--quiet')
|
||||
git(repo, 'config', 'user.name', 'Fixture')
|
||||
git(repo, 'config', 'user.email', 'fixture@example.invalid')
|
||||
tracked = repo / ('Core/tracked.txt' if repo == app else 'tracked.txt')
|
||||
tracked.parent.mkdir(parents=True, exist_ok=True)
|
||||
tracked.write_text('committed', encoding='utf-8')
|
||||
git(repo, 'add', str(tracked.relative_to(repo)))
|
||||
git(repo, 'commit', '-m', 'fixture')
|
||||
manifest = {'ISSSTELEON': git(app, 'rev-parse', 'HEAD'), 'ISSSTELEON/WebApi': git(child, 'rev-parse', 'HEAD')}
|
||||
(child / 'tracked.txt').write_text('modified', encoding='utf-8')
|
||||
(child / 'private.txt').write_text('untracked', encoding='utf-8')
|
||||
output = root / 'bundle.tar.gz'
|
||||
sha = bundle.export(root, manifest, output)
|
||||
self.assertEqual(sha, hashlib.sha256(output.read_bytes()).hexdigest())
|
||||
duplicate = root / 'duplicate.tar.gz'
|
||||
self.assertEqual(bundle.export(root, manifest, duplicate), sha)
|
||||
self.assertEqual(output.read_bytes(), duplicate.read_bytes())
|
||||
with tarfile.open(output) as archive:
|
||||
self.assertEqual(archive.extractfile('application/WebApi/tracked.txt').read(), b'committed')
|
||||
self.assertNotIn('application/WebApi/private.txt', archive.getnames())
|
||||
self.assertFalse(any('.git/' in name for name in archive.getnames()))
|
||||
|
||||
def test_unknown_checkout_is_rejected(self):
|
||||
"""A child checkout at a different SHA cannot be archived under a recorded gitlink."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo = Path(tmp) / 'ISSSTELEON'
|
||||
repo.mkdir()
|
||||
git(repo, 'init', '--quiet')
|
||||
git(repo, 'config', 'user.name', 'Fixture')
|
||||
git(repo, 'config', 'user.email', 'fixture@example.invalid')
|
||||
(repo / 'file').write_text('data', encoding='utf-8')
|
||||
git(repo, 'add', 'file')
|
||||
git(repo, 'commit', '-m', 'fixture')
|
||||
with self.assertRaises(ValueError):
|
||||
bundle.export(Path(tmp), {'ISSSTELEON': '0' * 40}, Path(tmp) / 'out.tar.gz')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Test isolated preparation and health verification with temporary release bundles and fake commands."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import install
|
||||
import verify
|
||||
|
||||
|
||||
class InstallerTests(unittest.TestCase):
|
||||
"""A temporary directory represents an empty dedicated installation parent."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.bundle = self.root / 'release.tar.gz'
|
||||
with tarfile.open(self.bundle, 'w:gz') as archive:
|
||||
files = [('application/WebApi/pyproject.toml', b'[project]'),
|
||||
('application/WebApi/uv.lock', b''),
|
||||
('application/WebApi/webapi/indicadores_vivos.py', b''),
|
||||
('application/WebApp/package.json', b'{}'),
|
||||
('application/WebApp/package-lock.json', b'{}')]
|
||||
files += [(f'application/Persistance/persistance/{domain}/alembic.ini', b'')
|
||||
for domain in install.DOMAINS]
|
||||
for name, content in files:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(content)
|
||||
archive.addfile(info, io.BytesIO(content))
|
||||
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': self.digest,
|
||||
'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
|
||||
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS}}
|
||||
self.account = 'wnnative'
|
||||
self.hostname = socket.gethostname()
|
||||
self.tools = {'uv': '/usr/bin/uv', 'npm': '/usr/bin/npm', 'nginx': '/usr/sbin/nginx'}
|
||||
self.calls = []
|
||||
self.real_check_port = install.check_port
|
||||
self.real_validate_parent = install.validate_parent
|
||||
self.real_validate_service_account = install.validate_service_account
|
||||
self.patches = [patch.object(install, 'validate_parent', return_value=self.root),
|
||||
patch.object(install, 'validate_service_account'),
|
||||
patch.object(install.os, 'geteuid', return_value=1234, create=True),
|
||||
patch.dict(sys.modules, {'pwd': types.SimpleNamespace(getpwuid=lambda uid: types.SimpleNamespace(pw_name=self.account))}),
|
||||
patch.object(install, 'check_port'), patch.object(install, 'run', side_effect=self.fake_run)]
|
||||
for item in self.patches:
|
||||
item.start()
|
||||
self.addCleanup(item.stop)
|
||||
|
||||
def fake_run(self, args, cwd, env):
|
||||
self.calls.append((list(map(str, args)), Path(cwd), dict(env)))
|
||||
if args[1:3] == ['run', 'build']:
|
||||
index = Path(cwd) / 'dist' / 'WebApp' / 'browser' / 'index.html'
|
||||
index.parent.mkdir(parents=True)
|
||||
index.write_text('app', encoding='utf-8')
|
||||
if 'alembic' in args:
|
||||
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()
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
self.assertEqual(result['status'], 'prepared')
|
||||
self.assertEqual([item[0][1:3] for item in self.calls[:3]], [['sync', '--locked'], ['ci'], ['run', 'build']])
|
||||
self.assertEqual(sum('alembic' in args for args, _, _ in self.calls), 4)
|
||||
guard_index = next(i for i, (args, _, _) in enumerate(self.calls) if args[1:4] == ['run', '--no-sync', 'python'])
|
||||
first_migration = next(i for i, (args, _, _) in enumerate(self.calls) if 'alembic' in args)
|
||||
self.assertLess(guard_index, first_migration)
|
||||
for domain in install.DOMAINS:
|
||||
self.assertEqual((base / 'data' / (domain + '.db')).read_bytes(), b'migrated')
|
||||
self.assertEqual(len(list((base / 'units').glob('*.service'))), 3)
|
||||
api = (base / 'units' / 'isssteleon-native-18090-api.service').read_text()
|
||||
worker = (base / 'units' / 'isssteleon-native-18090-worker.service').read_text()
|
||||
self.assertIn('127.0.0.1:28090', api)
|
||||
self.assertNotIn('User=', api)
|
||||
self.assertIn('WantedBy=default.target', api)
|
||||
self.assertIn('PrivateUsers=true', api)
|
||||
self.assertIn('webapi.indicadores_vivos', worker)
|
||||
self.assertIn('proxy_pass http://127.0.0.1:28090', (base / 'nginx.conf').read_text())
|
||||
self.assertFalse(any('systemctl' in args for args, _, _ in self.calls))
|
||||
|
||||
def test_custom_api_port_reaches_configuration_record_and_health_checks(self):
|
||||
"""The selected API port must drive loopback Gunicorn, nginx, metadata and verification."""
|
||||
self.record['api_port'] = 31001
|
||||
result = self.prepare(31001)
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
self.assertEqual(result['api_port'], 31001)
|
||||
self.assertEqual(json.loads((base / 'installation.json').read_text())['api_port'], 31001)
|
||||
self.assertIn('127.0.0.1:31001', (base / 'units' / 'isssteleon-native-18090-api.service').read_text())
|
||||
self.assertIn('proxy_pass http://127.0.0.1:31001', (base / 'nginx.conf').read_text())
|
||||
urls = []
|
||||
def request(url):
|
||||
urls.append(url)
|
||||
return 200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>'
|
||||
verify.check(dict(result, status='started'), command=lambda *a, **k: types.SimpleNamespace(returncode=0), get=request)
|
||||
self.assertIn('http://127.0.0.1:31001/health', urls)
|
||||
self.assertIn('http://127.0.0.1:18090/health', urls)
|
||||
|
||||
def test_api_port_mismatch_stops_before_creating_instance(self):
|
||||
"""A changed API port must not override the port recorded in the validated release request."""
|
||||
with self.assertRaises(ValueError): self.prepare(31001)
|
||||
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_existing_instance_is_never_overwritten_or_migrated(self):
|
||||
"""A repeated installation must reject the existing directory and preserve data."""
|
||||
self.prepare()
|
||||
marker = self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db'
|
||||
before = marker.read_bytes()
|
||||
call_count = len(self.calls)
|
||||
with self.assertRaises(FileExistsError):
|
||||
self.prepare()
|
||||
self.assertEqual(marker.read_bytes(), before)
|
||||
self.assertEqual(len(self.calls), call_count)
|
||||
|
||||
def test_digest_mismatch_and_port_conflict_stop_before_reservation(self):
|
||||
"""Wrong source integrity or occupied ports must not create an installation directory."""
|
||||
with self.assertRaises(ValueError):
|
||||
install.prepare(self.root, self.record, self.bundle, '0' * 64, 28090, self.account, self.hostname, self.tools)
|
||||
with patch.object(install, 'check_port', side_effect=ValueError('occupied')):
|
||||
with self.assertRaises(ValueError): self.prepare()
|
||||
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
|
||||
|
||||
def test_partial_failure_preserves_data_and_rejects_retry(self):
|
||||
"""A build error must leave a failed record and data rather than erase or reuse it."""
|
||||
with patch.object(install, 'run', side_effect=RuntimeError('build failed')):
|
||||
with self.assertRaises(RuntimeError): self.prepare()
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
state = json.loads((base / 'installation.json').read_text())
|
||||
self.assertEqual(state['status'], 'failed')
|
||||
self.assertTrue((base / 'data' / 'cacu.db').exists())
|
||||
with self.assertRaises(FileExistsError): self.prepare()
|
||||
|
||||
def test_effective_target_guard_executes_and_rejects_mismatch(self):
|
||||
"""The guard must inspect effective settings in a separate Python process without migrating files."""
|
||||
data = self.root / 'guard-data'
|
||||
data.mkdir()
|
||||
for domain in install.DOMAINS:
|
||||
(data / (domain + '.db')).touch()
|
||||
env = dict(os.environ)
|
||||
env.update(install.environment(self.root))
|
||||
for domain in install.DOMAINS:
|
||||
env[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
|
||||
captured = []
|
||||
with patch.object(install, 'run', side_effect=lambda args, cwd, env: captured.append(args)):
|
||||
install.verify_database_targets('/usr/bin/uv', self.root, env, data)
|
||||
code = captured[0][-2]
|
||||
bootstrap = """import os, sys, types
|
||||
root = types.ModuleType('persistance')
|
||||
settings_module = types.ModuleType('persistance.settings')
|
||||
settings_module.settings = types.SimpleNamespace(**{d + '_database_url': os.environ[d.upper() + '_DATABASE_URL'] for d in ('cacu','cama','tea','governance')})
|
||||
if os.environ.get('FIXTURE_MISMATCH'):
|
||||
settings_module.settings.cacu_database_url = 'sqlite:////outside/data.db'
|
||||
sys.modules['persistance'] = root
|
||||
sys.modules['persistance.settings'] = settings_module
|
||||
sqlalchemy = types.ModuleType('sqlalchemy')
|
||||
engine = types.ModuleType('sqlalchemy.engine')
|
||||
engine.make_url = lambda url: types.SimpleNamespace(drivername='sqlite', database=url[len('sqlite:///'):])
|
||||
sys.modules['sqlalchemy'] = sqlalchemy
|
||||
sys.modules['sqlalchemy.engine'] = engine
|
||||
"""
|
||||
ok = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
|
||||
self.assertEqual(ok.returncode, 0, ok.stderr)
|
||||
mismatch = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=dict(env, FIXTURE_MISMATCH='1'), capture_output=True)
|
||||
self.assertNotEqual(mismatch.returncode, 0)
|
||||
(data / 'tea.db').write_bytes(b'existing')
|
||||
occupied = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
|
||||
self.assertNotEqual(occupied.returncode, 0)
|
||||
self.assertEqual((data / 'tea.db').read_bytes(), b'existing')
|
||||
|
||||
def test_effective_target_guard_failure_blocks_all_migrations(self):
|
||||
"""An application settings mismatch must stop the installer before any Alembic command."""
|
||||
def reject_guard(args, cwd, env):
|
||||
self.fake_run(args, cwd, env)
|
||||
if args[1:4] == ['run', '--no-sync', 'python']:
|
||||
raise RuntimeError('effective database URL mismatch')
|
||||
with patch.object(install, 'run', side_effect=reject_guard), self.assertRaises(RuntimeError):
|
||||
self.prepare()
|
||||
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
|
||||
record = json.loads((self.root / 'isssteleon-native-18090' / 'installation.json').read_text())
|
||||
self.assertEqual(record['phase'], 'verifying_migration_targets')
|
||||
self.assertEqual(record['status'], 'failed')
|
||||
|
||||
def test_migration_rejects_nonempty_target(self):
|
||||
"""Unexpected existing database contents must stop migrations rather than touch the data."""
|
||||
def inject(args, cwd, env):
|
||||
self.fake_run(args, cwd, env)
|
||||
if args[1:3] == ['run', 'build']:
|
||||
(self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').write_bytes(b'existing')
|
||||
with patch.object(install, 'run', side_effect=inject), self.assertRaises(ValueError): self.prepare()
|
||||
self.assertEqual((self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
|
||||
|
||||
def test_install_parent_must_be_private_and_account_owned(self):
|
||||
"""A parent writable by another account cannot hold a trusted fresh installation."""
|
||||
for owner, mode in [(9999, 0o750), (1234, 0o770), (1234, 0o757)]:
|
||||
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=owner, st_mode=mode))
|
||||
with self.subTest(owner=owner, mode=mode), self.assertRaises(ValueError):
|
||||
install.require_private_parent(parent)
|
||||
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=1234, st_mode=0o750))
|
||||
install.require_private_parent(parent)
|
||||
|
||||
def test_privileged_service_group_memberships_are_rejected(self):
|
||||
"""Reject Docker, sudo and root group membership even for non-root accounts."""
|
||||
user = types.SimpleNamespace(pw_name=self.account, pw_gid=1001)
|
||||
fake_pwd = types.SimpleNamespace(getpwuid=lambda uid: user)
|
||||
fake_grp = types.SimpleNamespace(getgrnam=lambda name: types.SimpleNamespace(gr_gid={'docker': 998, 'sudo': 27, 'wheel': 10}[name]))
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001, 998], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
with self.assertRaises(ValueError): install.validate_service_account(self.account)
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[27], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
with self.assertRaises(ValueError): install.validate_service_account(self.account)
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
install.validate_service_account(self.account)
|
||||
|
||||
def test_host_mismatch_and_docker_root_are_rejected(self):
|
||||
"""An unexpected host or Docker data parent cannot receive an installation."""
|
||||
with self.assertRaises(ValueError):
|
||||
install.prepare(self.root, self.record, self.bundle, self.digest, 28090, self.account, 'different-host', self.tools)
|
||||
parent = self.root / 'docker'
|
||||
parent.mkdir()
|
||||
import re
|
||||
real_validate_parent = self.real_validate_parent
|
||||
with patch.object(install, 'SAFE_PATH', re.compile(r'^.+$')), patch.object(install, 'DOCKER_ROOT', parent), patch.object(install, 'validate_parent', wraps=real_validate_parent):
|
||||
with self.assertRaises(ValueError): install.validate_parent(parent)
|
||||
self.assertFalse((parent / 'isssteleon-native-18090').exists())
|
||||
|
||||
def test_archive_rejects_traversal_and_links(self):
|
||||
"""Archive extraction must reject paths and links that escape the fresh instance."""
|
||||
for name, member_type in [('../escape', tarfile.REGTYPE), ('application/link', tarfile.SYMTYPE)]:
|
||||
path = self.root / ('bad-' + str(member_type[0]) + '.tar.gz')
|
||||
with tarfile.open(path, 'w:gz') as archive:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = member_type
|
||||
if member_type == tarfile.SYMTYPE: info.linkname = '/tmp'
|
||||
archive.addfile(info)
|
||||
with self.subTest(name=name), self.assertRaises(ValueError):
|
||||
install.extract_bundle(path, self.root / 'extract')
|
||||
self.assertFalse((self.root / 'escape').exists())
|
||||
|
||||
def test_socket_conflict_detection(self):
|
||||
"""A real loopback listener must prevent the installer from using the same API port."""
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('127.0.0.1', 0))
|
||||
listener.listen()
|
||||
with patch.object(install, 'check_port', wraps=self.real_check_port):
|
||||
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], False)
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('0.0.0.0', 0))
|
||||
listener.listen()
|
||||
with patch.object(install, 'check_port', wraps=self.real_check_port):
|
||||
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], True)
|
||||
|
||||
def test_failed_verification_is_recorded_and_can_be_retried(self):
|
||||
"""A startup failure remains visible in the record and permits another health check."""
|
||||
record = dict(self.prepare(), status='started')
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
(base / 'installation.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
with patch.object(sys, 'argv', ['verify.py', str(base), '--wait-seconds', '0']), patch.object(verify.activate, 'manager_environment', return_value={}), patch.object(verify, 'check', side_effect=ValueError('service failed')):
|
||||
self.assertEqual(verify.main(), 1)
|
||||
record = json.loads((base / 'installation.json').read_text())
|
||||
self.assertEqual(record['status'], 'verification_failed')
|
||||
self.assertIn('service failed', record['health']['error'])
|
||||
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
|
||||
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
|
||||
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
|
||||
|
||||
def test_health_requires_all_services_and_spa_fallback(self):
|
||||
"""Health fails if a unit is inactive or proxy and SPA checks do not match."""
|
||||
record = dict(self.prepare(), status='started')
|
||||
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
|
||||
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
|
||||
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
|
||||
with self.assertRaises(ValueError):
|
||||
verify.check(record, command=lambda *a, **k: types.SimpleNamespace(returncode=3), get=get)
|
||||
with self.assertRaises(ValueError):
|
||||
verify.check(record, command=ok, get=lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else url.encode()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Test explicit, pinned-key SSH preparation with synthetic artifacts and no network."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import install
|
||||
import remote
|
||||
|
||||
|
||||
class RemoteTests(unittest.TestCase):
|
||||
"""Local fake files and mocked processes represent an authorized operator channel."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.dir = self.root / 'bundle'
|
||||
self.dir.mkdir()
|
||||
for name in install.INSTALLER_FILES:
|
||||
(self.dir / name).write_bytes(('content:' + name).encode())
|
||||
(self.dir / 'release-source.tar.gz').write_bytes(b'archive')
|
||||
self.sha = hashlib.sha256(b'archive').hexdigest()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': self.sha,
|
||||
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS},
|
||||
'installer_files': {name: install.digest(self.dir / name) for name in install.INSTALLER_FILES}}
|
||||
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
self.key = self.root / 'identity'
|
||||
self.known = self.root / 'known_hosts'
|
||||
self.key.write_text('fixture')
|
||||
self.known.write_text('fixture')
|
||||
|
||||
def call(self, host='10.0.10.41', account='wnnative', api_port=28090):
|
||||
return remote.prepare(self.dir, self.sha, host, 22, account, 'labserver',
|
||||
'/srv/workingnarrative-native', api_port, self.key, self.known)
|
||||
|
||||
def test_only_explicit_nonprivileged_ssh_and_pinned_host_keys(self):
|
||||
"""Preparation uses strict host-key checks and never invokes sudo or systemctl."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public') as public:
|
||||
stage = self.call()
|
||||
self.assertTrue(stage.startswith('/srv/workingnarrative-native/.release-'))
|
||||
self.assertEqual(run.call_count, 6)
|
||||
public.assert_called_once_with('10.0.10.41', 18090)
|
||||
for call in run.call_args_list:
|
||||
args = call.args[0]
|
||||
self.assertIn('StrictHostKeyChecking=yes', args)
|
||||
self.assertIn('BatchMode=yes', args)
|
||||
self.assertNotIn('sudo', args)
|
||||
self.assertNotIn('systemctl', args)
|
||||
self.assertIn('install.py', str(run.call_args_list[2]))
|
||||
self.assertIn('activate.py', str(run.call_args_list[3]))
|
||||
self.assertIn('--public-result ok', str(run.call_args_list[-1]))
|
||||
|
||||
def test_requested_api_port_is_transferred_and_mismatch_rejected(self):
|
||||
"""SSH must pass the exact recorded API port and reject any altered value before connection."""
|
||||
with patch.object(remote.subprocess, 'run') as run:
|
||||
with self.assertRaises(ValueError): self.call(api_port=31001)
|
||||
run.assert_not_called()
|
||||
self.record['api_port'] = 31001
|
||||
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public'):
|
||||
self.call(api_port=31001)
|
||||
self.assertIn('--api-port 31001', str(run.call_args_list[2]))
|
||||
|
||||
def test_bad_endpoint_or_tampered_installer_never_connects(self):
|
||||
"""Unsafe endpoint syntax or altered installer scripts must fail before SSH."""
|
||||
with patch.object(remote.subprocess, 'run') as run:
|
||||
with self.assertRaises(ValueError): self.call(host='host;evil')
|
||||
with self.assertRaises(ValueError): self.call(account='root')
|
||||
(self.dir / 'install.py').write_text('tampered', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): self.call()
|
||||
run.assert_not_called()
|
||||
|
||||
def test_public_failure_fails_action_and_records_failure(self):
|
||||
"""An unreachable public endpoint must report failure instead of a successful deployment."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public', side_effect=ValueError('unreachable')):
|
||||
with self.assertRaises(ValueError): self.call()
|
||||
self.assertIn('--public-result failed', str(run.call_args_list[-1]))
|
||||
self.assertFalse(run.call_args_list[-1].kwargs['check'])
|
||||
|
||||
def test_activation_failure_prevents_public_success(self):
|
||||
"""A failed service activation must stop before any public health check."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=[None, None, None, subprocess.CalledProcessError(1, 'ssh')]), patch.object(remote, 'check_public') as public:
|
||||
with self.assertRaises(subprocess.CalledProcessError): self.call()
|
||||
public.assert_not_called()
|
||||
|
||||
def test_public_probe_rejects_bad_health(self):
|
||||
"""The public endpoint must serve both the WebApp and a healthy proxied API."""
|
||||
responses = [(200, b'{"status":"ok"}'), (200, b'<html>app</html>')]
|
||||
with patch.object(remote.verify, 'request', side_effect=responses):
|
||||
remote.check_public('10.0.10.41', 18090, timeout=0)
|
||||
with patch.object(remote.verify, 'request', side_effect=[(200, b'{"status":"bad"}'), (200, b'app')]):
|
||||
with self.assertRaises(ValueError): remote.check_public('10.0.10.41', 18090, timeout=0)
|
||||
|
||||
def test_failed_remote_identity_check_never_uploads(self):
|
||||
"""A failed remote guard must prevent copying or executing the installer."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'ssh')) as run:
|
||||
with self.assertRaises(subprocess.CalledProcessError): self.call()
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Exercise release identity and fail-closed behavior using temporary Git repositories and fake API responses."""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location('resolve', Path(__file__).with_name('resolve.py'))
|
||||
resolver = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(resolver)
|
||||
|
||||
|
||||
def command(*args, cwd):
|
||||
return subprocess.run(args, cwd=cwd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
class ResolutionTests(unittest.TestCase):
|
||||
"""A bare local origin stands in for the institutional repository."""
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
root = Path(self.temp.name)
|
||||
self.origin = root / 'origin.git'
|
||||
self.repo = root / 'repo'
|
||||
command('git', 'init', '--bare', str(self.origin), cwd=root)
|
||||
command('git', 'init', str(self.repo), cwd=root)
|
||||
command('git', 'config', 'user.name', 'Test', cwd=self.repo)
|
||||
command('git', 'config', 'user.email', 'test@example.invalid', cwd=self.repo)
|
||||
(self.repo / 'file').write_text('test', encoding='utf-8')
|
||||
command('git', 'add', 'file', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'initial', cwd=self.repo)
|
||||
self.sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
command('git', 'remote', 'add', 'origin', str(self.origin), cwd=self.repo)
|
||||
command('git', 'tag', '-a', 'v1', '-m', 'release', cwd=self.repo)
|
||||
command('git', 'push', 'origin', 'refs/tags/v1', cwd=self.repo)
|
||||
self.env = {'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
|
||||
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': self.sha,
|
||||
'DISPATCH_REPOSITORY': resolver.REPOSITORY, 'DISPATCH_SERVER': resolver.SERVER,
|
||||
'RELEASE_TOKEN': 'test'}
|
||||
|
||||
def test_annotated_tag_resolves_to_commit_and_preserves_installer_identity(self):
|
||||
"""Peeling must return the commit while retaining the distinct tag object and installer revision."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['installer_sha'], self.sha)
|
||||
self.assertNotEqual(record['tag_object'], self.sha)
|
||||
self.assertEqual(record['release_id'], 7)
|
||||
self.assertEqual(record['public_port'], 18090)
|
||||
self.assertEqual(record['api_port'], 28090)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_invalid_or_missing_tags_and_ports_fail(self):
|
||||
"""Invalid inputs and absent remote refs must fail before they can identify a deployment."""
|
||||
for tag in ('', '-x', 'refs/tags/v1', 'bad..tag', 'a' * 40):
|
||||
with self.subTest(tag=tag), self.assertRaises((ValueError, subprocess.CalledProcessError)):
|
||||
resolver.validate_tag(tag)
|
||||
for port in ('0', '65536', 'abc'):
|
||||
with self.subTest(port=port), self.assertRaises(ValueError):
|
||||
resolver.validate_port(port)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'missing'}):
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
resolver.resolve(self.repo, 'missing', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_custom_public_and_api_ports_are_recorded(self):
|
||||
"""The release record must retain both operator-selected ports without replacing either default."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18123', '31001', self.env)
|
||||
self.assertEqual(record['public_port'], 18123)
|
||||
self.assertEqual(record['api_port'], 31001)
|
||||
|
||||
def test_both_requested_ports_are_validated_before_release_lookup(self):
|
||||
"""Invalid, privileged, oversized or equal ports must fail before any network access."""
|
||||
requests = [('0', '28090'), ('65536', '28090'), ('18090', '0'),
|
||||
('18090', '65536'), ('18090', 'abc'), ('18090', '18090')]
|
||||
with patch.object(resolver, 'dispatch') as dispatch, patch.object(resolver, 'release') as release:
|
||||
for public, api in requests:
|
||||
with self.subTest(public=public, api=api), self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', public, api, self.env)
|
||||
dispatch.assert_not_called()
|
||||
release.assert_not_called()
|
||||
|
||||
def test_wrong_identity_is_rejected(self):
|
||||
"""External repository, server and checkout identities cannot authorize resolution."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)):
|
||||
for key, value in [('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'), ('DISPATCH_SHA', '0' * 40)]:
|
||||
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||
resolver.dispatch(self.repo, dict(self.env, **{key: value}))
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.dispatch(self.repo, self.env)
|
||||
|
||||
def test_release_change_fails_and_cleans_temporary_ref(self):
|
||||
"""A changed release cannot pass the second check and failure removes its temporary ref."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', side_effect=[{'release_id': 7, 'tag': 'v1'}, {'release_id': 8, 'tag': 'v1'}]):
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_source_preparation_uses_selected_commit_in_a_disposable_tree(self):
|
||||
"""Source preparation must retain the installer checkout and discard temporary application files."""
|
||||
tag_object = command('git', 'rev-parse', 'refs/tags/v1', cwd=self.repo)
|
||||
record = {'tag': 'v1', 'tag_object': tag_object, 'application_sha': self.sha}
|
||||
captured = []
|
||||
def inspect(checkout):
|
||||
captured.append(checkout)
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=checkout), self.sha)
|
||||
return {'ISSSTELEON': 'a' * 40}
|
||||
with patch.object(resolver.source, 'checkout_pinned', side_effect=inspect):
|
||||
self.assertEqual(resolver.prepare_source(self.repo, record), {'ISSSTELEON': 'a' * 40})
|
||||
self.assertFalse(captured[0].exists())
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), self.sha)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_source_preparation_rejects_changed_tag(self):
|
||||
"""A tag that changes between resolution and source checkout cannot reach submodule preparation."""
|
||||
record = {'tag': 'v1', 'tag_object': '0' * 40, 'application_sha': self.sha}
|
||||
with patch.object(resolver.source, 'checkout_pinned') as checkout:
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.prepare_source(self.repo, record)
|
||||
checkout.assert_not_called()
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_remote_tag_change_fails_closed(self):
|
||||
"""A tag moved after fetch must not be used even if the release remains published."""
|
||||
original_git = resolver.git
|
||||
def changed_git(root, *args):
|
||||
if args[0] == 'ls-remote':
|
||||
return '0' * 40 + '\trefs/tags/v1'
|
||||
return original_git(root, *args)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver, 'git', side_effect=changed_git):
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_application_and_installer_commits_are_independent(self):
|
||||
"""A release can point to an older commit without changing the installer checkout."""
|
||||
(self.repo / 'file').write_text('installer', encoding='utf-8')
|
||||
command('git', 'commit', '-am', 'installer', cwd=self.repo)
|
||||
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
env = dict(self.env, DISPATCH_SHA=installer_sha)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18090', '28090', env)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['installer_sha'], installer_sha)
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), installer_sha)
|
||||
|
||||
def test_installer_files_match_dispatched_commit(self):
|
||||
"""Every transferred installer script must be the committed installer revision."""
|
||||
directory = self.repo / '.gitea' / 'deploy-terminal'
|
||||
directory.mkdir(parents=True)
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
(directory / name).write_bytes(('fixture ' + name).encode())
|
||||
command('git', 'add', '.gitea', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'installer', cwd=self.repo)
|
||||
sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
self.assertEqual(len(resolver.installer_manifest(self.repo, sha)), 6)
|
||||
(directory / 'install.py').write_text('modified', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): resolver.installer_manifest(self.repo, sha)
|
||||
|
||||
def test_manual_workflow_prepares_bundle_and_release_record(self):
|
||||
"""A manual dispatch must publish the resolved identity and source digest together."""
|
||||
directory = self.repo / '.gitea' / 'deploy-terminal'
|
||||
directory.mkdir(parents=True)
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
(directory / name).write_bytes(('fixture ' + name).encode())
|
||||
command('git', 'add', '.gitea', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'installer', cwd=self.repo)
|
||||
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
output = self.repo.parent / 'artifact' / 'release-source.tar.gz'
|
||||
output.parent.mkdir()
|
||||
env = dict(self.env, DISPATCH_SHA=installer_sha, REQUESTED_TAG='v1', REQUESTED_PORT='18090', REQUESTED_API_PORT='28090', RELEASE_OUTPUT=str(output))
|
||||
links = {'ISSSTELEON': 'a' * 40}
|
||||
def export(checkout, manifest, path):
|
||||
Path(path).write_bytes(b'fixture bundle')
|
||||
return 'd' * 64
|
||||
with patch.object(resolver, 'ROOT', self.repo), patch.object(resolver, 'ORIGIN', str(self.origin)), patch.dict(os.environ, env), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver.source, 'checkout_pinned', return_value=links), patch.object(resolver.bundle, 'export', side_effect=export):
|
||||
self.assertEqual(resolver.main(), 0)
|
||||
record = json.loads((output.parent / 'release-record.json').read_text())
|
||||
self.assertEqual(record['installer_sha'], installer_sha)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['api_port'], 28090)
|
||||
self.assertEqual(record['gitlinks'], links)
|
||||
self.assertEqual(record['bundle_sha256'], 'd' * 64)
|
||||
self.assertEqual(len(record['installer_files']), 6)
|
||||
|
||||
def test_publication_is_rechecked_after_packaging(self):
|
||||
"""A release or tag changed during archive creation must not produce an artifact record."""
|
||||
record = {'tag': 'v1', 'tag_object': 'a' * 40, 'release_id': 7}
|
||||
with patch.object(resolver, 'git', return_value='b' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release') as release:
|
||||
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
|
||||
release.assert_not_called()
|
||||
with patch.object(resolver, 'git', return_value='a' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release', return_value={'tag': 'v1', 'release_id': 8}):
|
||||
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
|
||||
|
||||
def test_release_metadata_must_be_published_and_match_tag(self):
|
||||
"""Drafts, missing publication times and mismatched tags must not qualify as published releases."""
|
||||
class Response:
|
||||
def __init__(self, data): self.data = json.dumps(data).encode()
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): pass
|
||||
def read(self, *args): return self.data
|
||||
class Opener:
|
||||
def __init__(self, data): self.data = data
|
||||
def open(self, req, timeout): return Response(self.data)
|
||||
good = {'id': 1, 'tag_name': 'v1', 'draft': False, 'published_at': '2026-01-01T00:00:00Z'}
|
||||
for change in ({'draft': True}, {'published_at': None}, {'tag_name': 'v2'}, {'id': True}):
|
||||
with self.subTest(change=change), patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(dict(good, **change))):
|
||||
with self.assertRaises(ValueError): resolver.release('v1', 'token')
|
||||
with patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(good)):
|
||||
self.assertEqual(resolver.release('v1', 'token')['release_id'], 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Check pinned application traversal with synthetic Git-tree and configuration fixtures."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
import os
|
||||
import types
|
||||
from unittest.mock import patch
|
||||
import source
|
||||
|
||||
|
||||
class SourceTests(unittest.TestCase):
|
||||
"""A mocked Git interface models one outer and one nested application repository."""
|
||||
def setUp(self):
|
||||
self.a, self.b = 'a' * 40, 'b' * 40
|
||||
self.outer = Path('/fixture')
|
||||
self.application = self.outer / 'ISSSTELEON'
|
||||
self.api = self.application / 'WebApi'
|
||||
self.calls = []
|
||||
|
||||
def fake_git(self, repo, *args, binary=False):
|
||||
repo = Path(repo)
|
||||
self.calls.append((repo, args))
|
||||
if args[:1] == ('ls-tree',):
|
||||
if repo == self.outer:
|
||||
return (f'160000 commit {self.a}\tISSSTELEON\0' + f'160000 commit {self.b}\tdev-data\0').encode()
|
||||
if repo == self.application:
|
||||
return f'160000 commit {self.b}\tWebApi\0'.encode()
|
||||
return b''
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
|
||||
return 'submodule.ISSSTELEON.path ISSSTELEON' if repo == self.outer else 'submodule.WebApi.path WebApi'
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
|
||||
name = 'ISSSTELEON' if repo == self.outer else 'WebApi'
|
||||
return 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + name + '.git'
|
||||
if args[:2] == ('rev-parse', 'HEAD'):
|
||||
return self.a if repo == self.application else self.b
|
||||
return ''
|
||||
|
||||
def test_institutional_git_auth_is_scoped_and_not_in_command(self):
|
||||
"""Private nested Git fetches use a host-scoped job token without exposing it in arguments."""
|
||||
env = {'RELEASE_TOKEN': 'fixture-token', 'GIT_CONFIG_COUNT': '1',
|
||||
'GIT_CONFIG_KEY_0': 'url.http://10.0.10.41:3000/ISSSTELEON/.insteadOf',
|
||||
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/'}
|
||||
with patch.dict(os.environ, env, clear=True), patch.object(source.subprocess, 'run', return_value=types.SimpleNamespace(stdout='result')) as run:
|
||||
self.assertEqual(source.git(self.outer, 'status'), 'result')
|
||||
args, kwargs = run.call_args
|
||||
self.assertNotIn('fixture-token', str(args))
|
||||
self.assertEqual(kwargs['env']['GIT_CONFIG_COUNT'], '2')
|
||||
self.assertEqual(kwargs['env']['GIT_CONFIG_KEY_1'], 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader')
|
||||
self.assertEqual(kwargs['env']['GIT_TERMINAL_PROMPT'], '0')
|
||||
|
||||
def test_nested_links_are_pinned_and_unrelated_tree_is_ignored(self):
|
||||
"""Traverse the application link and its nested link without touching dev-data."""
|
||||
with patch.object(source, 'git', side_effect=self.fake_git):
|
||||
result = source.checkout_pinned(self.outer)
|
||||
self.assertEqual(result, {'ISSSTELEON': self.a, 'ISSSTELEON/WebApi': self.b})
|
||||
self.assertFalse(any('dev-data' in str(args) for _, args in self.calls if '--checkout' in args))
|
||||
self.assertTrue(all('--checkout' in args for _, args in self.calls if 'update' in args))
|
||||
|
||||
def test_external_origin_is_rejected(self):
|
||||
"""An external submodule URL must fail before Git can initialize it."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
|
||||
return 'https://outside.invalid/repo.git'
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
self.assertFalse(any('--checkout' in args for _, args in self.calls))
|
||||
|
||||
def test_wrong_nested_checkout_is_rejected(self):
|
||||
"""A nested checkout that differs from its gitlink must stop preparation."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if Path(repo) == self.api and args[:2] == ('rev-parse', 'HEAD'):
|
||||
return 'c' * 40
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
|
||||
def test_unknown_nested_gitlink_is_rejected(self):
|
||||
"""Unrecognized nested repositories must never be initialized implicitly."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if Path(repo) == self.application and args[:1] == ('ls-tree',):
|
||||
return f'160000 commit {self.b}\tUnknown\0'.encode()
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Protect the manual workflow's deployment chain and Docker independence."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
WORKFLOW = ROOT / '.gitea' / 'workflows' / 'deploy-terminal-release.yml'
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""Inspect the checked-in native workflow and its commands."""
|
||||
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')
|
||||
self.assertIn('workflow_dispatch:', text)
|
||||
inputs = text.split(' inputs:', 1)[1].split('\njobs:', 1)[0]
|
||||
self.assertEqual(set(re.findall(r'^ ([a-z_]+):$', inputs, re.MULTILINE)), {'tag', 'puerto', 'puerto_api'})
|
||||
self.assertRegex(inputs, r"puerto_api:\s+description:[^\n]+\s+required: true\s+default: '28090'")
|
||||
self.assertNotIn('release:', text)
|
||||
self.assertIn('tag:', text)
|
||||
self.assertIn('puerto:', text)
|
||||
self.assertIn('puerto_api:', text)
|
||||
self.assertIn('inputs.puerto_api', text)
|
||||
self.assertIn('--api-port "$REQUESTED_API_PORT"', text)
|
||||
self.assertNotIn('NATIVE_API_PORT', text)
|
||||
self.assertLess(text.index('resolve.py'), text.index('remote.py \\'))
|
||||
self.assertIn('--host 10.0.10.41', text)
|
||||
self.assertIn('secrets.NATIVE_SSH_KEY', text)
|
||||
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+')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify native unit state, API health and Angular routing after activation."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import install
|
||||
import activate
|
||||
|
||||
|
||||
def request(url):
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url, timeout=5) as response:
|
||||
return response.status, response.read(1024 * 1024)
|
||||
|
||||
|
||||
def check(record, command=subprocess.run, get=request, manager_env=None):
|
||||
install.validate_record(record)
|
||||
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
|
||||
raise ValueError('installation is not prepared')
|
||||
port = record['public_port']
|
||||
api = record.get('api_port')
|
||||
expected = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
if record.get('services') != expected or type(api) is not int or api == port or not 1024 <= api <= 65535:
|
||||
raise ValueError('invalid installed service metadata')
|
||||
for unit in expected:
|
||||
result = command(['systemctl', '--user', 'is-active', '--quiet', unit], check=False, capture_output=True, env=manager_env)
|
||||
if result.returncode:
|
||||
raise ValueError('service is not active: ' + unit)
|
||||
for url in (f'http://127.0.0.1:{api}/health', f'http://127.0.0.1:{port}/health'):
|
||||
status, body = get(url)
|
||||
health = json.loads(body)
|
||||
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok':
|
||||
raise ValueError('API health check failed: ' + url)
|
||||
status, index = get(f'http://127.0.0.1:{port}/')
|
||||
route_status, route = get(f'http://127.0.0.1:{port}/native-health-route')
|
||||
if status != 200 or route_status != 200 or not index or index != route:
|
||||
raise ValueError('Angular distribution or SPA fallback failed')
|
||||
return {'services': expected, 'api_health': 'ok', 'proxy_health': 'ok', 'spa_fallback': 'ok'}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('instance', type=Path)
|
||||
parser.add_argument('--wait-seconds', type=int, default=90)
|
||||
parser.add_argument('--public-result', choices=('ok', 'failed'))
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.wait_seconds <= 300:
|
||||
parser.error('wait-seconds must be between 0 and 300')
|
||||
record = None
|
||||
path = None
|
||||
tracked = False
|
||||
try:
|
||||
path = args.instance.resolve() / 'installation.json'
|
||||
if args.instance.is_symlink() or path.is_symlink():
|
||||
raise ValueError('symlinked installation or metadata')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if Path(record.get('base', '')) != args.instance.resolve():
|
||||
raise ValueError('installation path does not match record')
|
||||
install.validate_record(record)
|
||||
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
|
||||
raise ValueError('installation is not prepared')
|
||||
tracked = True
|
||||
if args.public_result == 'failed':
|
||||
raise ValueError('external HTTP check failed from the Actions runner')
|
||||
manager_env = activate.manager_environment(record['account'])
|
||||
deadline = time.monotonic() + args.wait_seconds
|
||||
while True:
|
||||
try:
|
||||
checks = check(record, manager_env=manager_env)
|
||||
break
|
||||
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError('health verification failed: ' + str(exc)) from exc
|
||||
time.sleep(2)
|
||||
if args.public_result == 'ok':
|
||||
checks['public_http'] = 'ok'
|
||||
record.update(status='healthy' if args.public_result == 'ok' else 'local_healthy',
|
||||
phase='running' if args.public_result == 'ok' else 'awaiting_external_health',
|
||||
health=checks, verified_at=int(time.time()))
|
||||
install.atomic_record(path, record)
|
||||
print(json.dumps(checks, indent=2, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
if tracked:
|
||||
record.update(status='verification_failed', phase='verification_failed',
|
||||
health={'result': 'failed', 'error': str(exc)}, verified_at=int(time.time()))
|
||||
try:
|
||||
install.atomic_record(path, record)
|
||||
except OSError:
|
||||
pass
|
||||
print('Verification failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,7 +1,8 @@
|
||||
# General DEV workflow integration
|
||||
|
||||
`.gitea/workflows/deploy-dev.yml` accepts only `puerto` on `dev`. It checks out
|
||||
the dispatched SHA and recursive application gitlinks, then routes an unregistered
|
||||
`.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
|
||||
|
||||
+176
-56
@@ -1,6 +1,6 @@
|
||||
# DEV installation and conservative updates
|
||||
|
||||
The manual `deploy-dev` workflow accepts `puerto` on `dev`. An unregistered,
|
||||
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
|
||||
@@ -11,9 +11,10 @@ to resetting or recreating storage.
|
||||
|
||||
## Operator quick start
|
||||
|
||||
After the reviewed change reaches `dev`, open repository **Actions → deploy-dev →
|
||||
Run workflow**, select **dev**, enter only **puerto**, then inspect the run's SHA
|
||||
and final log. The same action installs a free port or updates its registered
|
||||
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.
|
||||
|
||||
@@ -31,7 +32,7 @@ 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.
|
||||
|
||||
Successful records contain `status=installed`, `revision`, `gitlinks`, `images`
|
||||
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.
|
||||
@@ -50,65 +51,46 @@ for path in pathlib.Path('/srv/workingnarrative-dev').glob('*/installation.json'
|
||||
if len(matches) != 1:
|
||||
raise SystemExit('Expected exactly one registered installation; inspect the registry')
|
||||
record = matches[0]
|
||||
keys = ('project', 'port', 'status', 'phase', 'result', 'revision', 'gitlinks', 'images',
|
||||
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
|
||||
```
|
||||
|
||||
### Dispatch when the UI does not offer dev
|
||||
### Central workflow and application branch
|
||||
|
||||
Read-only API checks on 2026-11-10 confirmed Gitea **1.26.2**, repository default
|
||||
branch **main**, and Actions enabled. Anonymous workflow metadata returned 401;
|
||||
authenticated UI visibility and dispatch were not tested. Do not dispatch `main`
|
||||
or the old resetting workflow to work around the UI. Keep the general workflow's
|
||||
`refs/heads/dev` guard.
|
||||
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.
|
||||
|
||||
An authorized operator can use the official
|
||||
[workflow dispatch endpoint](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
|
||||
with filename `deploy-dev.yml`, `ref=dev` and only the `puerto` input. Gitea's
|
||||
[v1.26.2 implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go)
|
||||
resolves that branch's commit and reads the workflow from it. This supports using
|
||||
the API independently of default-branch UI discovery; it is source-based evidence,
|
||||
not a dispatch performed against this server.
|
||||
`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.
|
||||
|
||||
**This submits a real deployment. Use only after review/merge and explicit
|
||||
authorization for the intended environment and port.** Set `PORT` and provide
|
||||
`GITEA_TOKEN` through the operator's private environment, then run:
|
||||
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.
|
||||
|
||||
```sh
|
||||
python3 -B - "$PORT" <<'PY'
|
||||
import json, os, sys, urllib.request
|
||||
port = sys.argv[1]
|
||||
if not port.isascii() or not port.isdigit() or not 1024 <= int(port) <= 65535:
|
||||
raise SystemExit('Invalid public port')
|
||||
request = urllib.request.Request(
|
||||
'http://10.0.10.41:3000/api/v1/repos/ISSSTELEON/WorkingNarrative/actions/workflows/deploy-dev.yml/dispatches',
|
||||
data=json.dumps({'ref': 'dev', 'inputs': {'puerto': port}}).encode(),
|
||||
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN'], 'Content-Type': 'application/json'},
|
||||
method='POST')
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
print('Dispatch HTTP status:', response.status)
|
||||
PY
|
||||
```
|
||||
|
||||
Use an account/token with the repository's required Actions write access. An HTTP
|
||||
success only confirms dispatch acceptance: open the resulting run in Actions,
|
||||
verify `ref=dev`, the captured SHA and the intended port, then read its final
|
||||
result and installation record. A 401/403 requires access correction; a 404 may
|
||||
mean the workflow/ref is unavailable. Do not remove the branch guard or retry
|
||||
against another branch. The Action checks out its captured SHA, verifies HEAD,
|
||||
and initializes only recursive `ISSSTELEON` gitlinks; unrelated `dev-data` is not
|
||||
required to deploy.
|
||||
|
||||
Local validation, review scope and a proposed disposable-environment trial are in
|
||||
[INTEGRATION.md](INTEGRATION.md). Do not use existing installations for fault injection.
|
||||
|
||||
The checkout follows the dispatched WorkingNarrative commit and every recursive
|
||||
gitlink. Source export rejects mismatching submodule checkouts. Builds include
|
||||
WebApp, WebApi, Core, Persistance, Extraction, indicadores_kit, models and other
|
||||
application trees at those pins. No `submodule update --remote` is used.
|
||||
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
|
||||
|
||||
@@ -134,7 +116,7 @@ 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
|
||||
Only a valid `installed` record with all expected containers matching and running is
|
||||
eligible. Checks cover project/service labels, actual image IDs, published port,
|
||||
exact writable `/data` binds and effective configuration against the running
|
||||
API/worker environment. Foreign overlapping mounts, port owners and peers on the
|
||||
@@ -212,7 +194,10 @@ historical bridge. Other engines/transitions need separate reviewed support.
|
||||
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`.
|
||||
7. Run the image's worker queue once for CaCu, CaMa and TEA, without the migration
|
||||
step: `RecomputationQueue.run` (`webapi.recomputation`), or `ColaDeRecalculo.correr`
|
||||
(`webapi.indicadores_vivos`) in images that predate it; the `runtime` guard action
|
||||
reports which one the candidate has and the controlled worker uses the same module.
|
||||
Consume old markers, require `estado=ok` for all three and no pending markers.
|
||||
Check preservation with declared derived changes allowed. Start the regular
|
||||
worker with `INDICADORES_AL_INICIAR=0`, then the frontend.
|
||||
@@ -234,6 +219,121 @@ including MLflow storage/artifacts and import logs, must remain unchanged. Worke
|
||||
views may be rebuilt. Metadata contains hashes/counts and per-row multiplicities
|
||||
for append-only history, without copying raw records into deployment metadata.
|
||||
|
||||
Three narrower rules come from what the current release does on real storage:
|
||||
|
||||
- Schema contract: each table's columns are compared by name. A migration may
|
||||
create them in another order than the models declare (TEA `ordenes_estudio`
|
||||
lists `ord_fecha` before `ord_tipo_estudio`); every access names its columns
|
||||
(ORM repositories, import schemas, silver loaders, dbt models). Name, type,
|
||||
nullability, default and primary-key position of every column, and every
|
||||
index, foreign key and check, must still match exactly.
|
||||
- Source mappings (`cat_sistema_fuente`, `cat_mapeo`) are written by the
|
||||
application (`register`, `close`) and seeded by the `catalogs` step, which only
|
||||
adds the catalog's missing forms and never changes a stored row. During a
|
||||
recalculation every stored row, seeded or entered by an operator, must survive
|
||||
byte for byte (closing one changes it, so it is refused). An added row must be
|
||||
the catalog's own: system `catalogo`, `registrado_por=catalogo`, valid from
|
||||
1900-01-01, open-ended, without `motivo`, for a form no stored row has; a new
|
||||
source system other than `catalogo` is refused. Outside a recalculation any
|
||||
change is refused.
|
||||
- `mlflow.db` may appear during a recalculation only when it was absent and is the
|
||||
store MLflow creates on first use: one schema version, the `Default`
|
||||
experiment (id 0, active, workspace `default`), at most the `default` workspace
|
||||
with no artifact root or archival settings, and every other table empty. An
|
||||
existing store still may not change or disappear; an MLflow release that needs
|
||||
a schema upgrade therefore stays refused.
|
||||
|
||||
## Notebook runner and its jobs volume
|
||||
|
||||
A composition with the `notebooks` service also declares the `trabajos_notebooks`
|
||||
volume, created by Compose as `<project>_trabajos_notebooks` and mounted at
|
||||
`/trabajos` in `webapi` and `notebooks` only. It holds job folders in transit: the
|
||||
API assembles `.<run>-*`, renames it to `<run>/` with `job.json`, the runner adds
|
||||
`result.json`, and the API imports the result into MLflow under `data/` and deletes
|
||||
the folder. Finished folders remain only with `NOTEBOOK_KEEP_JOBS` or after a crash.
|
||||
Queued runs exist only in the API process and as `RUNNING` MLflow runs.
|
||||
|
||||
| Installed / candidate | Behavior |
|
||||
| --- | --- |
|
||||
| Three services / three services | Unchanged procedure. |
|
||||
| Three services / notebooks | Refused if any volume already has the jobs name. Compose creates it when the API starts; it must carry this project's labels and be empty. |
|
||||
| Notebooks / notebooks | The record's `notebook_volume`, the retained composition and the running containers must agree. The volume is backed up, verified and compared again before the frontend starts. |
|
||||
| Notebooks / three services | Refused before stopping; the volume would be orphaned. |
|
||||
|
||||
Checks added to every notebook installation:
|
||||
|
||||
- Composition: exactly `webapi`, `indicadores`, `notebooks`, `webapp`, plus the
|
||||
profile-gated `entrenar` only when `docker compose config` lists it (its profile is
|
||||
enabled, for example by `COMPOSE_PROFILES` in the retained `.env`) with the API
|
||||
image and the single data bind. Nothing starts `entrenar`. The runner has the
|
||||
candidate WebApi image, `command: [notebooks]`, user `10001:10001`, no network,
|
||||
a read-only root, `cap_drop: ALL`, `no-new-privileges`, no ports and only the
|
||||
jobs volume; the only top-level volume is the jobs volume with no driver, options
|
||||
or `external`.
|
||||
- Identity: `docker volume inspect` must report the expected name, the `local`
|
||||
driver and scope, no options, and the labels `com.docker.compose.project=<project>`
|
||||
and `com.docker.compose.volume=trabajos_notebooks`. Compose itself adopts an
|
||||
unlabelled volume with that name without an error, so a first installation also
|
||||
refuses any existing volume with it.
|
||||
- Running containers: four owned containers with the expected mounts and runner
|
||||
isolation; any other container that mounts the volume or its mount point, and any
|
||||
one-shot (`docker compose run`) container of the project, such as `entrenar`, is
|
||||
refused.
|
||||
- Activity, before stopping anything, again once the frontend (the only published
|
||||
port) has stopped, and after all writers stop: no `RUNNING` notebook run in
|
||||
`mlflow.db` started within `NOTEBOOK_JOB_TIMEOUT` plus 30 minutes, and no job
|
||||
folder that is being assembled, lacks `job.json` or `result.json`, or is not a
|
||||
folder. A store whose `runs`/`tags` columns are not MLflow's is unverifiable and refused.
|
||||
|
||||
Every update, with or without notebooks, also refuses other writers in the
|
||||
original `indicadores`, `webapi` and `notebooks` containers, before stopping
|
||||
anything and again once the frontend has stopped:
|
||||
|
||||
- Processes (`docker top`): only what each container starts itself is accepted:
|
||||
Gunicorn serving `webapi:create_app()` (directly or under `uv run`) and the
|
||||
container's own `CMD` health check in `webapi`, `python -m <worker module>` in
|
||||
`indicadores`, `python -m models notebooks serve` in `notebooks`. A `docker exec`
|
||||
shell or job, `python -m models run ... --train`, OCR (`tesseract`), a notebook
|
||||
kernel or a worker still starting up refuses the update.
|
||||
- Requests (once the frontend is down, so no new one can arrive): any connection to
|
||||
port 5000 from outside the API container that is established or that the API has
|
||||
not closed yet (`/proc/net/tcp`, `tcp6`), which is how an import, OCR or a
|
||||
`/governance/model-versions/.../train` call still being served shows up. Loopback
|
||||
connections, the health check's, are ignored.
|
||||
- MLflow runs: besides notebook runs, any other `RUNNING` run started within the
|
||||
API's `WEBAPI_TIMEOUT` (600 s by default) plus 30 minutes refuses the update. That
|
||||
is how a training or the extraction ranker's learning shows up; the learning runs
|
||||
in a background thread of the API after an import has answered, with no request
|
||||
and no process of its own. An older running run is taken as one a crash cut off.
|
||||
|
||||
The MLflow store is checked too, before stopping and after quiescing:
|
||||
|
||||
- Its schema revision must be the candidate MLflow's head. MLflow refuses to open
|
||||
an older store ("out-of-date database schema") and updates never upgrade it, so
|
||||
an update to a newer MLflow is refused until that upgrade is decided separately.
|
||||
- No registered model may have a version under the `produccion` alias. With one,
|
||||
the recalculation's live estimators export a cohort file to `data/cohorts/` and
|
||||
store a risk batch (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), which the
|
||||
persistence check protects because those tables also hold the confirmations made
|
||||
in the application. Without this check the update would fail after activation.
|
||||
|
||||
MLflow artifacts live under `data/mlflow-artefactos/<experiment>/`: every
|
||||
experiment the platform creates takes `MLFLOW_ARTIFACT_ROOT`, which the image sets,
|
||||
the controlled configuration enforces for `webapi` and `indicadores` and the
|
||||
installer requires of `entrenar` when its `.env` sets it. They are in the data
|
||||
backup and its restore. MLflow's own `Default` experiment points at
|
||||
`/app/WebApi/mlruns/0`, in the container layer; no platform code logs to it.
|
||||
|
||||
The jobs backup runs after the data backup, in the candidate image as root with
|
||||
the volume read-only, no network and only `CHOWN`, `DAC_OVERRIDE` and `FOWNER`. It
|
||||
walks with `lstat`, keeps links as links and refuses FIFOs, sockets and devices. It
|
||||
writes `.backups/<project>/<operation>/notebooks/content/` and `manifest.json`
|
||||
(every entry's type, mode, owner, mtime and SHA-256) and fails if the volume changes
|
||||
during the copy. The helper verifies it again; `verify_restore` also restores it
|
||||
to `.restores/<project>/<operation>.notebooks`. To restore by hand into an empty
|
||||
volume, run `notebook_guard.py restore` with the backup read-only at `/respaldo`
|
||||
and the volume at `/restaurado`, as root, with services stopped.
|
||||
|
||||
## Failures and recovery
|
||||
|
||||
No automatic image rollback or live data restore occurs. A failure after quiescing
|
||||
@@ -429,6 +529,26 @@ A later real dispatch requires separate authorization.
|
||||
actual worker completion, containment and restart/recovery need the isolated
|
||||
physical trial. Backup preserves file contents/modes/timestamps; ACLs, security
|
||||
labels and original uid/gid restoration need separate recovery validation.
|
||||
- Writer checks are samples, not a proof of inactivity: they see processes inside
|
||||
the installation containers, requests that reach the API over the network and
|
||||
running MLflow runs. Not detected: a writer outside the containers (root on the
|
||||
host; other containers with the data path or the jobs volume are refused), a
|
||||
loopback client, the extraction learning before its run is created (while it
|
||||
loads the previous ranker), a running run older than the request window, and the
|
||||
indicator worker's cycle, whose writes are derived and redone by the checked
|
||||
recalculation. `docker stop` gives a container 10 s before killing it, while
|
||||
Gunicorn would wait 30 s for requests. An interrupted learning step loses that
|
||||
batch's training (the corrections stay in the import) and can leave a run
|
||||
`RUNNING` with partial artifacts; SQLite transactions keep every database
|
||||
consistent and the backup is taken after the stop. Proving inactivity would need
|
||||
a maintenance mode in the application itself.
|
||||
- `reconcile.py` accepts the notebook runner's original ID (`--notebooks`) and
|
||||
requires it exactly for installations whose record has `notebook_volume`. It
|
||||
does not re-verify the notebook backup, which only a pre-activation failure
|
||||
leaves and which the update never writes back.
|
||||
- The jobs backup has run against real Docker volumes on Docker Desktop, not on the
|
||||
institutional daemon host; its bind destination under the deployment base and its
|
||||
disk usage there need the isolated physical trial.
|
||||
- Backups remain on the daemon host. Off-host replication, encryption, retention,
|
||||
confidential log handling and disaster recovery remain operator responsibilities.
|
||||
Simulated tests alone do not establish institutional deployment safety.
|
||||
|
||||
+361
-44
@@ -10,6 +10,8 @@ import uuid
|
||||
import shutil
|
||||
import sqlite3
|
||||
|
||||
import data_guard
|
||||
|
||||
INSPECTION_REASONS = frozenset({
|
||||
'persistent_directory_invalid', 'linked_persistent_entry', 'special_persistent_entry',
|
||||
'database_missing_or_linked', 'contract_domains_invalid', 'migration_version_unavailable',
|
||||
@@ -20,6 +22,8 @@ INSPECTION_REASONS = frozenset({
|
||||
'directory_identity_changed', 'directory_disappeared', 'database_identity_changed',
|
||||
'audit_log_disappeared', 'audit_history_changed', 'auxiliary_integrity_failed',
|
||||
'protected_rows_changed', 'historical_rows_changed', 'persistent_file_changed',
|
||||
'worker_module_unavailable', 'notebook_runs_unverifiable', 'seeded_rows_invalid', 'mlflow_store_not_initial',
|
||||
'mlflow_store_unverifiable',
|
||||
})
|
||||
INSPECTION_TYPES = frozenset({'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
|
||||
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
|
||||
@@ -37,6 +41,18 @@ PERSISTENT_ENV = {
|
||||
}
|
||||
|
||||
|
||||
NOTEBOOK_JOB_TIMEOUT = 6 * 3600
|
||||
NOTEBOOK_REASONS = frozenset({
|
||||
'notebook jobs are active', 'notebook jobs changed while creating the backup',
|
||||
'notebook backup differs from the volume', 'notebook job entry type is unsupported',
|
||||
'notebook job entry changed type', 'notebook jobs root is missing or linked',
|
||||
'notebook backup destination is missing or linked', 'notebook backup destination is not empty',
|
||||
'notebook backup manifest is invalid', 'notebook backup manifest is inconsistent',
|
||||
'notebook backup content differs', 'notebook backup directory is invalid',
|
||||
'notebook restore differs from the backup',
|
||||
})
|
||||
|
||||
|
||||
def failure_detail(exc):
|
||||
"""Describe subprocess failures without exposing their potentially sensitive output."""
|
||||
if not isinstance(exc, subprocess.CalledProcessError):
|
||||
@@ -120,6 +136,194 @@ def recalculation_step(step, operation):
|
||||
raise RecalculationFailure(step, 'error type=' + kind) from None
|
||||
|
||||
|
||||
class UpdateRefusal(RuntimeError):
|
||||
"""A check of notebook work or other writers that refused the update; its message carries counts and
|
||||
categories only."""
|
||||
|
||||
|
||||
def notebook_detail(exc):
|
||||
if not isinstance(exc, subprocess.CalledProcessError):
|
||||
return 'error type=' + type(exc).__name__
|
||||
detail = 'exit=' + str(exc.returncode)
|
||||
for line in (exc.stderr if isinstance(exc.stderr, str) else '').splitlines():
|
||||
if line.startswith('WN_NOTEBOOK_DIAGNOSTIC='):
|
||||
try:
|
||||
diagnostic = json.loads(line.partition('=')[2])
|
||||
except ValueError:
|
||||
break
|
||||
if isinstance(diagnostic, dict) and diagnostic.get('type') in INSPECTION_TYPES | {'FileExistsError'}:
|
||||
detail += ', error type=' + diagnostic['type']
|
||||
if isinstance(diagnostic, dict) and diagnostic.get('reason') in NOTEBOOK_REASONS:
|
||||
detail += ', reason=' + diagnostic['reason']
|
||||
break
|
||||
return detail
|
||||
|
||||
|
||||
def notebook_guard(api, image, action, payload, volume, backup=None):
|
||||
"""Run the jobs volume guard as root in the candidate image, with the volume always read-only.
|
||||
|
||||
Root reads files a notebook made unreadable; a backup also needs to restore their owners."""
|
||||
script = Path(__file__).with_name('notebook_guard.py').read_text(encoding='utf-8')
|
||||
args = ['docker', 'run', '--rm', '-i', '--pull', 'never', '--network', 'none', '--read-only',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev', '--user', '0:0', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges:true', '--env', 'PYTHONDONTWRITEBYTECODE=1', '--env', 'HOME=/tmp',
|
||||
'--mount', f'type=volume,src={volume},dst=/trabajos,readonly,volume-nocopy']
|
||||
if backup is None:
|
||||
args += ['--cap-add', 'DAC_READ_SEARCH']
|
||||
else:
|
||||
args += ['--cap-add', 'DAC_OVERRIDE', '--cap-add', 'CHOWN', '--cap-add', 'FOWNER',
|
||||
'--mount', f'type=bind,src={backup},dst=/respaldo']
|
||||
args += ['--entrypoint', '/app/WebApi/.venv/bin/python', image, '-B', '-c', script, action]
|
||||
try:
|
||||
return json.loads(api.run(args, stdin=json.dumps(payload)))
|
||||
except Exception as exc:
|
||||
raise UpdateRefusal('notebook jobs ' + action + ' failed (' + notebook_detail(exc) + ')') from None
|
||||
|
||||
|
||||
def notebook_timeout(api, ids):
|
||||
"""The API's notebook job timeout and request timeout, which bound how long a run it started stays running."""
|
||||
items = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
env = next(environment(item) for item in items
|
||||
if item['Config']['Labels']['com.docker.compose.service'] == 'webapi')
|
||||
values = {'timeout': env.get('NOTEBOOK_JOB_TIMEOUT', str(NOTEBOOK_JOB_TIMEOUT)),
|
||||
'request_timeout': env.get('WEBAPI_TIMEOUT', '600')}
|
||||
if any(not value.isdigit() or int(value) < 1 for value in values.values()):
|
||||
raise RuntimeError('notebook job timeout is not verifiable')
|
||||
return {key: int(value) for key, value in values.items()}
|
||||
|
||||
|
||||
def notebook_activity(api, image, data, volume, timeouts, *, quiesced=False):
|
||||
"""Reject queued, running or half-assembled notebook work and running trainings or learning steps; return the
|
||||
jobs volume summary, if any."""
|
||||
runs = guard(api, image, 'notebook-runs', {'data': '/data', **timeouts,
|
||||
'now': int(time.time() * 1000), 'quiesced': quiesced}, data)
|
||||
if any(type(runs.get(key)) is not int or runs[key] < 0 for key in ('active', 'training')):
|
||||
raise RuntimeError('notebook run status is not verifiable')
|
||||
if runs['active']:
|
||||
raise UpdateRefusal(str(runs['active']) + ' notebook run(s) are queued or running; retry when they finish')
|
||||
if runs['training']:
|
||||
raise UpdateRefusal(str(runs['training']) + ' training or learning run(s) are running in MLflow; retry when '
|
||||
'they finish')
|
||||
if volume is None:
|
||||
return None
|
||||
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, volume)
|
||||
if jobs['active']:
|
||||
raise UpdateRefusal('notebook jobs volume holds unfinished jobs (' + ', '.join(jobs['active'])
|
||||
+ '); retry when they finish or inspect them manually')
|
||||
return jobs
|
||||
|
||||
|
||||
API_PORT = 5000
|
||||
|
||||
|
||||
def expected_process(service, command, healthcheck):
|
||||
"""Whether a process of an original container is its own service, as its entrypoint or image starts it.
|
||||
|
||||
Anything else (a `docker exec` shell, a one-off `python -m models`, an OCR or notebook kernel subprocess) may
|
||||
be writing data or doing work that stopping the container would cut short."""
|
||||
tokens = command.split()
|
||||
if not tokens:
|
||||
return False
|
||||
if service == 'webapi':
|
||||
return command == healthcheck or (tokens[-1] == 'webapi:create_app()'
|
||||
and any(token.endswith('gunicorn') for token in tokens[:4]))
|
||||
if service == 'indicadores':
|
||||
return any(tokens[-2:] == ['-m', module] for module in data_guard.WORKERS)
|
||||
if service == 'notebooks':
|
||||
return tokens[-4:] == ['-m', 'models', 'notebooks', 'serve']
|
||||
return False
|
||||
|
||||
|
||||
def container_processes(api, container):
|
||||
lines = api.run(['docker', 'top', container, '-eo', 'pid,args']).splitlines()
|
||||
if not lines or lines[0].split()[:2] != ['PID', 'COMMAND']:
|
||||
raise UpdateRefusal('installation processes are not verifiable')
|
||||
return [line.split(None, 1)[1] if len(line.split(None, 1)) == 2 else '' for line in lines[1:] if line.strip()]
|
||||
|
||||
|
||||
def loopback(address):
|
||||
"""Whether a `/proc/net/tcp` or `tcp6` address (host byte order, hexadecimal) is a loopback one."""
|
||||
if len(address) == 8:
|
||||
return address[6:8] == '7F'
|
||||
if len(address) == 32:
|
||||
return (address == '00000000000000000000000001000000'
|
||||
or (address[:24] == '0000000000000000FFFF0000' and address[30:32] == '7F'))
|
||||
return False
|
||||
|
||||
|
||||
def served_requests(api, container):
|
||||
"""Connections to the API port from outside the container that are open or that the API has not closed yet,
|
||||
which is a request still being served. Once the frontend is stopped no new one can arrive."""
|
||||
try:
|
||||
table = api.run(['docker', 'exec', container, 'cat', '/proc/net/tcp', '/proc/net/tcp6'])
|
||||
except Exception:
|
||||
raise UpdateRefusal('open API requests are not verifiable') from None
|
||||
count = 0
|
||||
for line in table.splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) < 4 or fields[0] == 'sl' or ':' not in fields[1] or ':' not in fields[2]:
|
||||
continue
|
||||
port = fields[1].rpartition(':')[2]
|
||||
# 01 ESTABLISHED, 08 CLOSE_WAIT: the client may have gone, the request handler has not finished.
|
||||
if int(port, 16) == API_PORT and fields[3] in ('01', '08') and not loopback(fields[2].rpartition(':')[0]):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def writer_activity(api, ids, *, requests):
|
||||
"""Reject processes the original containers did not start themselves and, with `requests`, API requests still
|
||||
being served (an import, OCR or a `/train` call)."""
|
||||
items = {item['Id']: item for item in json.loads(api.run(['docker', 'inspect', *ids]))}
|
||||
unexpected = 0
|
||||
for index, service in ((0, 'indicadores'), (1, 'webapi'), (3, 'notebooks')):
|
||||
if index >= len(ids):
|
||||
continue
|
||||
test = ((items.get(ids[index], {}).get('Config') or {}).get('Healthcheck') or {}).get('Test') or []
|
||||
healthcheck = ' '.join(test[1:]) if test[:1] == ['CMD'] else None
|
||||
unexpected += sum(not expected_process(service, command, healthcheck)
|
||||
for command in container_processes(api, ids[index]))
|
||||
if unexpected:
|
||||
raise UpdateRefusal(str(unexpected) + ' process(es) the installation did not start run in its containers '
|
||||
'(docker exec, a one-off job, OCR or a notebook kernel); retry when they finish')
|
||||
if requests:
|
||||
served = served_requests(api, ids[1])
|
||||
if served:
|
||||
raise UpdateRefusal(str(served) + ' API request(s) are still being served; retry when they finish')
|
||||
|
||||
|
||||
def mlflow_compatibility(api, image, data, *, quiesced=False):
|
||||
"""Refuse an MLflow store the candidate cannot open without a schema upgrade, or one with a production
|
||||
version: the recalculation would then store risk batches and export cohort files, which the persistence
|
||||
check treats as protected (they mix derived rows with confirmations made in the application)."""
|
||||
store = guard(api, image, 'mlflow-store', {'data': '/data', 'quiesced': quiesced}, data)
|
||||
if not store['exists']:
|
||||
return store
|
||||
if [store['revision']] != guard(api, image, 'mlflow-heads', {})['heads']:
|
||||
raise UpdateRefusal('the MLflow store needs a schema upgrade, which updates do not apply')
|
||||
if store['production']:
|
||||
raise UpdateRefusal(str(store['production']) + ' registered model(s) have a version in production; the '
|
||||
'recalculation would store risk batches and cohort files outside the derived state')
|
||||
return store
|
||||
|
||||
|
||||
def verify_notebook_jobs(api, image, project, identity, digest):
|
||||
"""Require the same volume and contents, before the frontend lets anyone submit a notebook."""
|
||||
if api.notebook_volume_identity(project) != identity:
|
||||
raise RuntimeError('notebook jobs volume identity changed')
|
||||
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, identity['name'])
|
||||
if jobs['digest'] != digest or jobs['active']:
|
||||
raise RuntimeError('notebook jobs changed during activation')
|
||||
|
||||
|
||||
def verify_new_notebook_volume(api, image, project):
|
||||
"""A volume Compose created for this project with no job in it yet."""
|
||||
identity = api.notebook_volume_identity(project)
|
||||
jobs = notebook_guard(api, image, 'inspect', {'root': '/trabajos'}, identity['name'])
|
||||
if jobs['entries'] != 1:
|
||||
raise RuntimeError('new notebook jobs volume is not empty')
|
||||
return {'identity': identity, 'digest': jobs['digest']}
|
||||
|
||||
|
||||
def guard(api, image, action, payload, data=None, *, writable=False):
|
||||
"""Run inspection in the candidate image, overriding every application entrypoint."""
|
||||
script = Path(__file__).with_name('data_guard.py').read_text(encoding='utf-8')
|
||||
@@ -175,11 +379,14 @@ def write_configuration(api, deploy, data, record, revision, original_env):
|
||||
return tag
|
||||
|
||||
|
||||
def controlled_config(config, *, migrate_on_start=False):
|
||||
"""Keep the worker idle until the checked one-shot recalculation has completed."""
|
||||
def controlled_config(config, *, migrate_on_start=False, worker='webapi.indicadores_vivos'):
|
||||
"""Keep the worker idle until the checked one-shot recalculation has completed.
|
||||
|
||||
`worker` is the image's worker module (`runtime` guard action)."""
|
||||
if worker not in data_guard.WORKERS:
|
||||
raise RuntimeError('unsupported worker module')
|
||||
api = config['services']['webapi']
|
||||
worker = config['services']['indicadores']
|
||||
for service in (api, worker):
|
||||
for service in (api, config['services']['indicadores']):
|
||||
service['environment'] = dict(service.get('environment', {}), **PERSISTENT_ENV)
|
||||
if any(not isinstance(value, str) for value in service['environment'].values()):
|
||||
raise RuntimeError('all candidate environment values must be resolved strings')
|
||||
@@ -195,10 +402,11 @@ def controlled_config(config, *, migrate_on_start=False):
|
||||
'--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'
|
||||
service = config['services']['indicadores']
|
||||
service['working_dir'] = '/app/WebApi'
|
||||
service['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', worker]
|
||||
service['command'] = []
|
||||
service['environment']['INDICADORES_AL_INICIAR'] = '0'
|
||||
return config
|
||||
|
||||
|
||||
@@ -217,7 +425,17 @@ def persist_config(deploy, config):
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def verify_api(api, cmd, data, image, *, timeout=300):
|
||||
def api_mounts(mounts, data, notebook_volume):
|
||||
"""Whether the API has exactly its data bind and, with notebooks, the jobs volume."""
|
||||
wanted = [{'Type': 'bind', 'Source': str(data), 'Destination': '/data', 'RW': True}]
|
||||
if notebook_volume:
|
||||
wanted.append({'Type': 'volume', 'Name': notebook_volume, 'Destination': '/trabajos', 'RW': True})
|
||||
shapes = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
|
||||
'Destination', 'RW')} for mount in mounts]
|
||||
return len(shapes) == len(wanted) and all(mount in shapes for mount in wanted)
|
||||
|
||||
|
||||
def verify_api(api, cmd, data, image, *, timeout=300, notebook_volume=None):
|
||||
deadline = time.monotonic() + timeout
|
||||
expected = api.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
|
||||
while time.monotonic() < deadline:
|
||||
@@ -225,10 +443,8 @@ def verify_api(api, cmd, data, image, *, timeout=300):
|
||||
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
|
||||
if (item.get('Image') != expected
|
||||
or not api_mounts(item.get('Mounts', []), data, notebook_volume)
|
||||
or any(environment(item).get(k) != v for k, v in PERSISTENT_ENV.items())):
|
||||
raise RuntimeError('updated API storage or image identity differs')
|
||||
return
|
||||
@@ -236,9 +452,13 @@ def verify_api(api, cmd, data, image, *, timeout=300):
|
||||
raise RuntimeError('updated API did not become healthy')
|
||||
|
||||
|
||||
def finish(api, cmd, image, deploy, data, contract, before, progress=None):
|
||||
def finish(api, cmd, image, deploy, data, contract, before, progress=None, *, notebook_volume=None,
|
||||
before_frontend=None):
|
||||
"""Recalculate under persistence checks, then start the worker, the notebook runner and the frontend.
|
||||
|
||||
`before_frontend` runs while no request can reach the API yet."""
|
||||
progress = progress or (lambda phase: None)
|
||||
verify_api(api, cmd, data, image)
|
||||
verify_api(api, cmd, data, image, notebook_volume=notebook_volume)
|
||||
guard(api, image, 'verify', {'data': '/data', 'contract': contract, 'before': before}, data, writable=True)
|
||||
progress('recalculation-and-persistence')
|
||||
def load_configuration():
|
||||
@@ -258,27 +478,38 @@ def finish(api, cmd, image, deploy, data, contract, before, progress=None):
|
||||
writable=True))
|
||||
progress('worker')
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'indicadores'])
|
||||
if notebook_volume:
|
||||
progress('notebooks')
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'notebooks'])
|
||||
if before_frontend:
|
||||
before_frontend()
|
||||
progress('frontend')
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapp'])
|
||||
return after
|
||||
|
||||
|
||||
def freeze_failed(api, cmd, project, data):
|
||||
def freeze_failed(api, cmd, project, data, notebook_volume=None):
|
||||
"""Stop only verified instance containers; retain them and all storage for recovery."""
|
||||
ids = api.run([*cmd, 'ps', '-a', '-q']).splitlines()
|
||||
if not ids:
|
||||
return
|
||||
items = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
services = ('webapi', 'webapp', 'indicadores') + (('notebooks',) if notebook_volume else ())
|
||||
jobs = {'Type': 'volume', 'Name': notebook_volume, 'Destination': '/trabajos'}
|
||||
for item in items:
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
if (labels.get('com.docker.compose.project') != project
|
||||
or labels.get('com.docker.compose.service') not in ('webapi', 'webapp', 'indicadores')):
|
||||
service = labels.get('com.docker.compose.service')
|
||||
if labels.get('com.docker.compose.project') != project or service not in services:
|
||||
raise RuntimeError('failed container ownership is uncertain')
|
||||
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')
|
||||
mounts = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
|
||||
'Destination')} for mount in item.get('Mounts', [])]
|
||||
wanted = {'webapi': [{'Type': 'bind', 'Source': str(data), 'Destination': '/data'}]
|
||||
+ ([jobs] if notebook_volume else []),
|
||||
'indicadores': [{'Type': 'bind', 'Source': str(data), 'Destination': '/data'}],
|
||||
'notebooks': [jobs]}
|
||||
if service != 'webapp' and (len(mounts) != len(wanted[service])
|
||||
or any(mount not in mounts for mount in wanted[service])):
|
||||
raise RuntimeError('failed container storage is uncertain')
|
||||
for container in ids:
|
||||
api.run(['docker', 'update', '--restart=no', container])
|
||||
api.run(['docker', 'stop', container])
|
||||
@@ -291,7 +522,7 @@ def container_snapshot(api, ids):
|
||||
return items
|
||||
|
||||
|
||||
def recover_original(api, record, helper, base, ids, original, previous_cmd, initial):
|
||||
def recover_original(api, record, helper, base, ids, original, previous_cmd, initial, volume_identity=None):
|
||||
"""Restart only the original containers after confirming their retained state."""
|
||||
current = container_snapshot(api, ids)
|
||||
for old, item in zip(original, current):
|
||||
@@ -315,10 +546,20 @@ def recover_original(api, record, helper, base, ids, original, previous_cmd, ini
|
||||
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']
|
||||
if (worker_config.get('Entrypoint') not in [['/app/WebApi/.venv/bin/python', '-m', module]
|
||||
for module in data_guard.WORKERS]
|
||||
or worker_config.get('Cmd') not in (None, [])
|
||||
or environment(current[0]).get('INDICADORES_AL_INICIAR') != '0'):
|
||||
raise RuntimeError('original worker restart entrypoint is not verified safe')
|
||||
if len(ids) == 4:
|
||||
runner = current[3]
|
||||
if not runner.get('State', {}).get('Running') and (
|
||||
runner['Config'].get('Cmd') != ['notebooks'] or runner['Config'].get('User') != '10001:10001'
|
||||
or runner.get('HostConfig', {}).get('NetworkMode') != 'none'
|
||||
or runner.get('HostConfig', {}).get('ReadonlyRootfs') is not True):
|
||||
raise RuntimeError('original notebook runner is not verified isolated')
|
||||
if api.notebook_volume_identity(record['project']) != volume_identity:
|
||||
raise RuntimeError('original notebook jobs volume changed')
|
||||
image = record['images'][0]
|
||||
contract = guard(api, image, 'contract', {})
|
||||
all_stopped = all(item.get('State', {}).get('Running') is False for item in current)
|
||||
@@ -332,12 +573,12 @@ def recover_original(api, record, helper, base, ids, original, previous_cmd, ini
|
||||
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):
|
||||
for index in ((1, 0, 3, 2) if len(ids) == 4 else (1, 0, 2)):
|
||||
if not current[index].get('State', {}).get('Running'):
|
||||
api.run(['docker', 'start', ids[index]])
|
||||
if api.verify_existing_containers(record, base, helper) != ids:
|
||||
raise RuntimeError('original container identities changed after restart')
|
||||
api.verify_services(previous_cmd, record['port'])
|
||||
api.verify_services(previous_cmd, record['port'], notebooks=len(ids) == 4)
|
||||
for old, item in zip(original, container_snapshot(api, ids)):
|
||||
if (item.get('HostConfig', {}).get('RestartPolicy')
|
||||
!= old.get('HostConfig', {}).get('RestartPolicy')):
|
||||
@@ -354,12 +595,15 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
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()
|
||||
expected = api.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
|
||||
getattr(api, 'verify_target_revision', lambda revision: None)(revision)
|
||||
expected = api.git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
|
||||
old_ids = api.verify_existing_containers(record, base, helper)
|
||||
phase = 'preparing'
|
||||
current = None
|
||||
operation_step = None
|
||||
volume = old_volume = volume_identity = None
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-update-') as tmp:
|
||||
directory = Path(tmp)
|
||||
source, deploy, old_deploy = directory / 'codigo', directory / 'deploy', directory / 'old-deploy'
|
||||
@@ -369,7 +613,11 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
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)
|
||||
old_volume = api.verify_config(old_config, project, data, old_tag, port)
|
||||
if old_volume != record.get('notebook_volume'):
|
||||
raise UpdateRefusal('retained composition and installation record disagree on notebook jobs')
|
||||
if old_volume:
|
||||
volume_identity = api.notebook_volume_identity(project)
|
||||
current_environment(api, old_ids, old_config)
|
||||
if revision == record['revision']:
|
||||
phase = 'same-revision-verification'
|
||||
@@ -381,13 +629,13 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
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)
|
||||
verify_api(api, previous_cmd, data, record['images'][0], notebook_volume=old_volume)
|
||||
api.verify_services(previous_cmd, port, notebooks=bool(old_volume))
|
||||
if api.verify_existing_containers(record, base, helper) != old_ids:
|
||||
raise RuntimeError('installation containers changed during verification')
|
||||
operation_step = 'record verified no-op'
|
||||
api.host_action(helper, 'save', project, json.dumps(dict(
|
||||
record, result='unchanged', verification='complete')))
|
||||
record, **metadata, result='unchanged', verification='complete')))
|
||||
print(f'Unchanged {project} on port {port} at {revision}; verification complete')
|
||||
return
|
||||
manifest = {}
|
||||
@@ -398,14 +646,31 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
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)
|
||||
runtime = guard(api, images[0], 'runtime', {})
|
||||
config = controlled_config(json.loads(api.run([*cmd, 'config', '--format', 'json'])),
|
||||
worker=runtime['worker'])
|
||||
volume = api.verify_config(config, project, data, tag, port)
|
||||
if old_volume and not volume:
|
||||
raise UpdateRefusal('candidate composition drops the notebook jobs volume; unsupported')
|
||||
if volume and not old_volume and api.notebook_volume_identity(
|
||||
project, missing_ok=True, verify=False) is not None:
|
||||
raise UpdateRefusal('a volume named ' + volume + ' already exists and was not created by this '
|
||||
'installation')
|
||||
persist_config(deploy, config)
|
||||
phase = 'compatibility'
|
||||
contract = guard(api, images[0], 'contract', {})
|
||||
initial = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract}, data)
|
||||
operation_step = 'check notebook activity'
|
||||
timeout = notebook_timeout(api, old_ids)
|
||||
jobs = notebook_activity(api, images[0], data, old_volume, timeout)
|
||||
operation_step = 'check other writers'
|
||||
writer_activity(api, old_ids, requests=False)
|
||||
operation_step = 'check the MLflow store'
|
||||
mlflow_compatibility(api, images[0], data)
|
||||
operation_step = None
|
||||
prepared_bytes = sum(p.stat().st_size for tree in (source, deploy)
|
||||
for p in tree.rglob('*') if p.is_file())
|
||||
prepared_bytes += (jobs['bytes'] if jobs else 0) * (2 if verify_restore else 1)
|
||||
api.host_action(helper, 'update-space-restore' if verify_restore else 'update-space',
|
||||
project, str(prepared_bytes))
|
||||
operation_step = 'prepare backup destinations in helper'
|
||||
@@ -418,6 +683,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
operation = uuid.uuid4().hex
|
||||
current = dict(record, status='updating', operation_id=operation, phase='quiescing',
|
||||
target_revision=revision, target_images=images, target_gitlinks=manifest,
|
||||
target_branch=metadata.get('branch'), target_notebook_volume=volume,
|
||||
migrations='none-pending', recalculation='not-started')
|
||||
|
||||
def save():
|
||||
@@ -425,9 +691,17 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
|
||||
save()
|
||||
phase = 'quiescing'
|
||||
for container in old_ids:
|
||||
# The frontend publishes the only port, so once it stops no notebook can be submitted.
|
||||
frontend = old_ids[2]
|
||||
for container in [frontend] + [ident for ident in old_ids if ident != frontend]:
|
||||
api.run(['docker', 'update', '--restart=no', container])
|
||||
api.run(['docker', 'stop', container])
|
||||
if container == frontend:
|
||||
operation_step = 'check notebook activity with the frontend stopped'
|
||||
notebook_activity(api, images[0], data, old_volume, timeout)
|
||||
operation_step = 'check other writers with the frontend stopped'
|
||||
writer_activity(api, old_ids, requests=True)
|
||||
operation_step = None
|
||||
for container in old_ids:
|
||||
state = json.loads(api.run(['docker', 'inspect', '--format', '{{json .State}}', container]))
|
||||
if state.get('Running') is not False:
|
||||
@@ -443,10 +717,34 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
operation_step = 'compare storage identity and schema'
|
||||
if quiesced != initial:
|
||||
raise RuntimeError('storage identity or schema changed during preparation')
|
||||
operation_step = 'check notebook activity after quiescing'
|
||||
jobs = notebook_activity(api, images[0], data, old_volume, timeout, quiesced=True)
|
||||
operation_step = 'check the MLflow store after quiescing'
|
||||
mlflow_compatibility(api, images[0], data, quiesced=True)
|
||||
origin = {key: record[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images') if key in record}
|
||||
operation_step = 'create and verify backup in helper'
|
||||
backup = json.loads(api.host_action(helper, 'backup', project, json.dumps({
|
||||
'operation_id': operation, 'contract': contract, 'origin': origin})))
|
||||
expected_jobs = None
|
||||
if old_volume:
|
||||
operation_step = 'prepare notebook backup destination in helper'
|
||||
api.host_action(helper, 'prepare-notebook-backup', project, operation)
|
||||
# The helper creates the directory under /host. Docker resolves binds on the daemon host.
|
||||
target = str(base / '.backups' / project / operation / 'notebooks')
|
||||
operation_step = 'verify notebook jobs volume identity'
|
||||
if api.notebook_volume_identity(project) != volume_identity:
|
||||
raise RuntimeError('notebook jobs volume identity changed during preparation')
|
||||
operation_step = 'create notebook backup'
|
||||
created = notebook_guard(api, images[0], 'backup', {
|
||||
'root': '/trabajos', 'destination': '/respaldo', 'volume': volume_identity}, old_volume, target)
|
||||
operation_step = 'verify notebook backup in helper'
|
||||
verified = json.loads(api.host_action(helper, 'verify-notebook-backup', project, operation))
|
||||
if not created['digest'] == verified['digest'] == jobs['digest']:
|
||||
raise RuntimeError('notebook backup does not match the quiesced volume')
|
||||
expected_jobs = jobs['digest']
|
||||
current['notebook_backup'] = {'path': target, 'volume': old_volume, 'digest': expected_jobs}
|
||||
operation_step = 'save notebook backup record'
|
||||
save()
|
||||
if verify_restore:
|
||||
current['phase'] = phase = 'restore-verification'
|
||||
current['restore_check'] = str(base / '.restores' / project / operation)
|
||||
@@ -466,6 +764,13 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
save()
|
||||
# No pending migrations are supported; the direct entrypoint cannot run Alembic.
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
|
||||
if volume and not old_volume:
|
||||
created = verify_new_notebook_volume(api, images[0], project)
|
||||
volume_identity, expected_jobs = created['identity'], created['digest']
|
||||
elif volume and api.notebook_volume_identity(project) != volume_identity:
|
||||
raise RuntimeError('notebook jobs volume identity changed during activation')
|
||||
check_jobs = (lambda: verify_notebook_jobs(api, images[0], project, volume_identity, expected_jobs)
|
||||
) if volume else None
|
||||
|
||||
def progress(next_phase):
|
||||
nonlocal phase
|
||||
@@ -476,31 +781,40 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
current['recalculation'] = 'complete'
|
||||
save()
|
||||
|
||||
finish(api, cmd, images[0], deploy, data, contract, backup['state'], progress)
|
||||
finish(api, cmd, images[0], deploy, data, contract, backup['state'], progress,
|
||||
notebook_volume=volume, before_frontend=check_jobs)
|
||||
current['phase'] = phase = 'availability'
|
||||
save()
|
||||
api.verify_services(cmd, port)
|
||||
api.verify_existing_containers(dict(record, images=images), base, helper)
|
||||
api.verify_services(cmd, port, notebooks=bool(volume))
|
||||
target_record = dict(record, images=images, notebook_volume=volume)
|
||||
if not volume:
|
||||
target_record.pop('notebook_volume')
|
||||
api.verify_existing_containers(target_record, base, helper)
|
||||
guard(api, images[0], 'verify',
|
||||
{'data': '/data', 'contract': contract, 'before': backup['state'], 'derived': True}, data)
|
||||
current.update(status='installed', revision=revision, gitlinks=manifest, images=images,
|
||||
phase='complete', result='updated', recalculation='complete', verification='complete')
|
||||
if volume:
|
||||
current['notebook_volume'] = volume
|
||||
current.update(metadata)
|
||||
current.pop('error', None)
|
||||
save()
|
||||
print(f'Updated {project} on port {port} at {revision}')
|
||||
except Exception as exc:
|
||||
failure_record_unavailable = False
|
||||
if current is not None:
|
||||
if phase in ('api', 'recalculation-and-persistence', 'worker', 'frontend', 'availability'):
|
||||
if phase in ('api', 'recalculation-and-persistence', 'worker', 'notebooks', 'frontend',
|
||||
'availability'):
|
||||
try:
|
||||
freeze_failed(api, cmd, project, data)
|
||||
freeze_failed(api, cmd, project, data, volume)
|
||||
except Exception:
|
||||
current['quarantine'] = 'incomplete; inspect owned containers before recovery'
|
||||
current.update(status='update_failed', phase=phase,
|
||||
error='Update failed; preserve storage and inspect recovery metadata.',
|
||||
recovery='manual; never restore over live data automatically')
|
||||
# Retain original provenance; target references remain separate for recovery.
|
||||
for key in ('revision', 'gitlinks', 'images'):
|
||||
for key in ('revision', 'gitlinks', 'images', 'notebook_volume'):
|
||||
current.pop(key, None)
|
||||
if key in record:
|
||||
current[key] = record[key]
|
||||
if phase in ('quiescing', 'backup', 'restore-verification'):
|
||||
@@ -510,7 +824,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
failure_record_unavailable = True
|
||||
try:
|
||||
recover_original(api, record, helper, base, old_ids, original_containers,
|
||||
previous_cmd, initial)
|
||||
previous_cmd, initial, volume_identity)
|
||||
current['recovery'] = 'original services verified; reconciliation required'
|
||||
except Exception:
|
||||
current['recovery'] = 'incomplete; inspect original services before reconciliation'
|
||||
@@ -522,11 +836,14 @@ def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
else:
|
||||
api.host_action(helper, 'save', project, json.dumps(current))
|
||||
detail = ''
|
||||
if phase in ('compatibility', 'same-revision-verification') and isinstance(exc, GuardFailure):
|
||||
if isinstance(exc, UpdateRefusal):
|
||||
detail = ('; operation=' + operation_step if operation_step else '') + '; ' + str(exc)
|
||||
elif phase in ('compatibility', 'same-revision-verification') and isinstance(exc, GuardFailure):
|
||||
detail = '; ' + str(exc)
|
||||
elif phase == 'same-revision-verification':
|
||||
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
|
||||
if phase in ('compatibility', 'backup', 'restore-verification') and operation_step:
|
||||
if (phase in ('compatibility', 'backup', 'restore-verification') and operation_step
|
||||
and not isinstance(exc, UpdateRefusal)):
|
||||
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
|
||||
if operation_step == 'inspect quiesced storage' and isinstance(exc, GuardFailure):
|
||||
detail = '; operation=' + operation_step + '; ' + str(exc)
|
||||
|
||||
+240
-14
@@ -8,6 +8,7 @@ from collections import Counter
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import importlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -44,6 +45,10 @@ INSPECTION_REASONS = {
|
||||
'indicator audit log disappeared': 'audit_log_disappeared',
|
||||
'indicator audit history changed': 'audit_history_changed',
|
||||
'auxiliary SQLite integrity check failed': 'auxiliary_integrity_failed',
|
||||
'worker module is unavailable': 'worker_module_unavailable',
|
||||
'MLflow run status is unverifiable': 'notebook_runs_unverifiable',
|
||||
'MLflow store created with content': 'mlflow_store_not_initial',
|
||||
'MLflow store is unverifiable': 'mlflow_store_unverifiable',
|
||||
}
|
||||
INSPECTION_ERROR_TYPES = {'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
|
||||
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
|
||||
@@ -57,6 +62,32 @@ MUTABLE = {
|
||||
'cat_estrato_valor', 'cat_measure', 'cat_measure_resultado',
|
||||
'cat_measure_valor', 'cat_measure_grupo', 'cat_measure_estrato',
|
||||
}
|
||||
# Tables the recalculation's `catalogs` step only adds to (`SourceMappingRepository.ensure_system` and `seed`):
|
||||
# the catalog's own source system and its mappings, in force since 1900-01-01 and never changing a stored row.
|
||||
# The application adds and closes the other rows, so every row already stored must survive unchanged, and an
|
||||
# added row must carry these values and a form no stored row has.
|
||||
SEEDED = {
|
||||
'cat_sistema_fuente': {'sistema_fuente_id': 'catalogo', 'fuente_tabla': None, 'vigente_desde': '1900-01-01',
|
||||
'vigente_hasta': None},
|
||||
'cat_mapeo': {'sistema_fuente_id': 'catalogo', 'registrado_por': 'catalogo', 'vigente_desde': '1900-01-01',
|
||||
'vigente_hasta': None, 'motivo': None},
|
||||
}
|
||||
SEEDED_FORM = {
|
||||
'cat_sistema_fuente': ('sistema_fuente_id',),
|
||||
'cat_mapeo': ('sistema_fuente_id', 'clase', 'resultado_id', 'estudio_id', 'forma_normalizada'),
|
||||
}
|
||||
# MLflow's store under /data: the live estimators open the registry, which creates an empty store when absent.
|
||||
MLFLOW_STORE = 'mlflow.db'
|
||||
# The registered-model alias of the version in production (`models.io.registry`).
|
||||
PRODUCTION_ALIAS = 'produccion'
|
||||
# Worker modules an image may provide, newest first, with their queue class and its methods
|
||||
# (take a marker, run a domain, list pending markers).
|
||||
WORKERS = {
|
||||
'webapi.recomputation': ('RecomputationQueue', 'take', 'run', 'pending'),
|
||||
'webapi.indicadores_vivos': ('ColaDeRecalculo', 'tomar', 'correr', 'pendientes'),
|
||||
}
|
||||
# A notebook run still marked RUNNING this long after its job timeout is shown as interrupted.
|
||||
NOTEBOOK_STALE_MARGIN_S = 1800
|
||||
APPEND_ONLY = {
|
||||
'carga', 'measure_report', 'measure_report_unidad',
|
||||
'measure_report_unidad_estrato', 'cohorte_armado', 'cohorte_miembro',
|
||||
@@ -174,6 +205,18 @@ def schema(connection):
|
||||
return result
|
||||
|
||||
|
||||
def same_structure(actual, expected):
|
||||
"""Whether two `schema` results match, apart from the physical order of each table's columns.
|
||||
|
||||
A migration that creates a table lists its columns in its own order; the models may declare another. Every
|
||||
other column property (name, type, nullability, default, primary-key position) and every index, foreign key
|
||||
and check still has to match exactly."""
|
||||
def by_name(structure):
|
||||
return {table: dict(metadata, columns=sorted(metadata['columns'], key=lambda column: column[0]))
|
||||
for table, metadata in structure.items()}
|
||||
return by_name(actual) == by_name(expected)
|
||||
|
||||
|
||||
def target_contract():
|
||||
"""Create only in-memory reference schemas using the candidate's own metadata."""
|
||||
from alembic.config import Config
|
||||
@@ -228,7 +271,8 @@ def inspect_databases(root, contract, *, rows=False, quiesced=False):
|
||||
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(same_structure(actual, expected['schema']),
|
||||
domain + ': structure differs from the candidate')
|
||||
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
|
||||
domain + ': SQLite integrity check failed')
|
||||
require(not connection.execute('PRAGMA foreign_key_check').fetchall(),
|
||||
@@ -277,6 +321,8 @@ def inspection_diagnostic(exc):
|
||||
reason = 'historical_rows_changed'
|
||||
elif message.startswith('persistent file changed: '):
|
||||
reason = 'persistent_file_changed'
|
||||
elif message.startswith('seeded rows are not the catalog'):
|
||||
reason = 'seeded_rows_invalid'
|
||||
kind = type(exc).__name__
|
||||
kind = kind if kind in INSPECTION_ERROR_TYPES else 'Other'
|
||||
sqlite_name = getattr(exc, 'sqlite_errorname', None)
|
||||
@@ -287,30 +333,94 @@ def inspection_diagnostic(exc):
|
||||
return {'reason': reason, 'domain': domain, 'type': kind, 'sqlite': sqlite_name, 'errno': number}
|
||||
|
||||
|
||||
def row_hash(row):
|
||||
encoded = json.dumps(row, default=lambda v: {'blob_sha256': hashlib.sha256(v).hexdigest()},
|
||||
ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def table_state(connection, domain):
|
||||
result = {}
|
||||
for table, metadata in schema(connection).items():
|
||||
keys = [column[0] for column in sorted(metadata['columns'], key=lambda c: c[4]) if column[4]]
|
||||
require(keys, 'tables without primary keys are unsupported')
|
||||
query = 'SELECT * FROM ' + quote(table) + ' ORDER BY ' + ','.join(map(quote, keys))
|
||||
mode = ('mutable' if table in MUTABLE else 'append' if table in APPEND_ONLY else 'exact')
|
||||
mode = ('mutable' if table in MUTABLE else 'append' if table in APPEND_ONLY
|
||||
else 'seeded' if table in SEEDED else 'exact')
|
||||
if domain == 'governance':
|
||||
mode = 'exact'
|
||||
value_hash, row_hashes, count = hashlib.sha256(), Counter(), 0
|
||||
for row in connection.execute(query):
|
||||
encoded = json.dumps(row, default=lambda v: {'blob_sha256': hashlib.sha256(v).hexdigest()},
|
||||
ensure_ascii=True, separators=(',', ':')).encode()
|
||||
hashed = hashlib.sha256(encoded).hexdigest()
|
||||
hashed = row_hash(row)
|
||||
value_hash.update(hashed.encode())
|
||||
if mode == 'append':
|
||||
if mode in ('append', 'seeded'):
|
||||
row_hashes[hashed] += 1
|
||||
count += 1
|
||||
result[table] = {'mode': mode, 'count': count, 'sha256': value_hash.hexdigest()}
|
||||
if mode == 'append':
|
||||
if mode in ('append', 'seeded'):
|
||||
result[table]['rows'] = dict(row_hashes)
|
||||
return result
|
||||
|
||||
|
||||
def verify_seeded(path, domain, table, retained):
|
||||
"""Rows not among `retained` (hashes of the rows stored before) must be the catalog's own seed rows."""
|
||||
message = domain + ': seeded rows are not the catalog\'s own in ' + table
|
||||
with closing(readonly(path)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
cursor = connection.execute('SELECT * FROM ' + quote(table))
|
||||
names = [column[0] for column in cursor.description]
|
||||
signature, form = SEEDED[table], SEEDED_FORM[table]
|
||||
require(set(signature) | set(form) <= set(names), message)
|
||||
kept, added = set(), []
|
||||
for row in cursor:
|
||||
record = dict(zip(names, row))
|
||||
if row_hash(row) in retained:
|
||||
kept.add(tuple(record[column] for column in form))
|
||||
else:
|
||||
added.append(record)
|
||||
forms = [tuple(record[column] for column in form) for record in added]
|
||||
require(all(record[column] == value for record in added for column, value in signature.items()), message)
|
||||
require(len(set(forms)) == len(forms) and not set(forms) & kept, message)
|
||||
return len(added)
|
||||
|
||||
|
||||
def initial_mlflow_store(path):
|
||||
"""Whether `path` is the empty store MLflow creates on first use: its schema version, the `Default` experiment,
|
||||
the `default` workspace of MLflow 3 stores and nothing else."""
|
||||
with closing(readonly(path)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
|
||||
'auxiliary SQLite integrity check failed')
|
||||
tables = [name for (name,) in connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
|
||||
if not {'alembic_version', 'experiments', 'runs', 'registered_models', 'model_versions'} <= set(tables):
|
||||
return False
|
||||
for table in tables:
|
||||
rows = connection.execute('SELECT * FROM ' + quote(table)).fetchall()
|
||||
if table == 'alembic_version':
|
||||
if len(rows) != 1:
|
||||
return False
|
||||
elif table == 'experiments':
|
||||
columns = [row[1] for row in connection.execute('PRAGMA table_info(experiments)')]
|
||||
if len(rows) != 1 or not {'experiment_id', 'name', 'lifecycle_stage'} <= set(columns):
|
||||
return False
|
||||
experiment = dict(zip(columns, rows[0]))
|
||||
if ((experiment['experiment_id'], experiment['name'], experiment['lifecycle_stage']) != (
|
||||
0, 'Default', 'active') or experiment.get('workspace', 'default') != 'default'):
|
||||
return False
|
||||
elif table == 'workspaces':
|
||||
columns = [row[1] for row in connection.execute('PRAGMA table_info(workspaces)')]
|
||||
if len(rows) != 1 or 'name' not in columns:
|
||||
return False
|
||||
workspace = dict(zip(columns, rows[0]))
|
||||
if workspace['name'] != 'default' or any(
|
||||
value is not None for key, value in workspace.items() if key not in ('name', 'description')):
|
||||
return False
|
||||
elif rows:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_sqlite(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return stream.read(16) == b'SQLite format 3\x00'
|
||||
@@ -358,9 +468,11 @@ def verify_state(root, contract, before, *, derived=False):
|
||||
current = new['tables'][table]
|
||||
if derived and prior['mode'] == 'mutable':
|
||||
continue
|
||||
if derived and prior['mode'] == 'append':
|
||||
if derived and prior['mode'] in ('append', 'seeded'):
|
||||
require(not (Counter(prior['rows']) - Counter(current['rows'])),
|
||||
domain + ': historical rows changed in ' + table)
|
||||
if prior['mode'] == 'seeded' and Counter(current['rows']) - Counter(prior['rows']):
|
||||
verify_seeded(Path(root) / (domain + '.db'), domain, table, set(prior['rows']))
|
||||
else:
|
||||
require(current == prior, domain + ': persistent rows changed in ' + table)
|
||||
permitted = {'indicadores/estado.json', 'indicadores/.estado.lock',
|
||||
@@ -368,6 +480,9 @@ def verify_state(root, contract, before, *, derived=False):
|
||||
for name in before['files'].keys() | after['files'].keys():
|
||||
if derived and name in permitted:
|
||||
continue
|
||||
if derived and name == MLFLOW_STORE and name not in before['files']:
|
||||
require(initial_mlflow_store(Path(root) / name), 'MLflow store created with content')
|
||||
continue
|
||||
if derived and name == 'reportes/indicadores.jsonl':
|
||||
if name in before['files']:
|
||||
path = Path(root) / name
|
||||
@@ -470,6 +585,17 @@ def restore_backup(source, destination):
|
||||
return actual
|
||||
|
||||
|
||||
def worker_module():
|
||||
"""The image's worker module, found on disk without importing the application package."""
|
||||
spec = importlib.util.find_spec('webapi')
|
||||
require(spec is not None and spec.submodule_search_locations, 'worker module is unavailable')
|
||||
for module in WORKERS:
|
||||
name = module.split('.', 1)[1] + '.py'
|
||||
if any((Path(location) / name).is_file() for location in spec.submodule_search_locations):
|
||||
return module
|
||||
raise RuntimeError('worker module is unavailable')
|
||||
|
||||
|
||||
def recalculate(environment):
|
||||
"""Run each domain once and retain only safe failure context."""
|
||||
stage, domain = 'environment', 'none'
|
||||
@@ -479,22 +605,23 @@ def recalculate(environment):
|
||||
'invalid resolved worker environment')
|
||||
os.environ.update(environment)
|
||||
stage = 'import'
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
module = worker_module()
|
||||
name, take, run, pending = WORKERS[module]
|
||||
stage = 'initialize'
|
||||
queue = ColaDeRecalculo()
|
||||
queue = getattr(importlib.import_module(module), name)()
|
||||
completed = []
|
||||
for domain in DOMAINS:
|
||||
if domain == 'governance':
|
||||
continue
|
||||
stage = 'enqueue'
|
||||
queue.tomar(domain)
|
||||
getattr(queue, take)(domain)
|
||||
stage = 'execute'
|
||||
result = queue.correr(domain)
|
||||
result = getattr(queue, run)(domain)
|
||||
stage = 'domain_result'
|
||||
require(isinstance(result, dict) and result.get('estado') == 'ok', 'indicator recalculation failed')
|
||||
completed.append(domain)
|
||||
domain, stage = 'none', 'pending'
|
||||
require(not queue.pendientes(), 'unexpected pending recalculations')
|
||||
require(not getattr(queue, pending)(), 'unexpected pending recalculations')
|
||||
return {'completed': completed}
|
||||
except Exception as exc:
|
||||
exc.recalculation_stage = stage
|
||||
@@ -502,6 +629,96 @@ def recalculate(environment):
|
||||
raise
|
||||
|
||||
|
||||
def notebook_runs(root, timeout_s, now_ms, *, request_timeout_s=None, quiesced=False):
|
||||
"""Count notebook runs MLflow still holds as running and not yet stale (`models.pipelines.experiment`), and,
|
||||
with `request_timeout_s`, the other running runs started within that time plus the same margin.
|
||||
|
||||
A notebook run is queued or executing in the API process from its creation until it is terminated, so a
|
||||
positive count means stopping the API would interrupt it. The other runs are trainings and the extraction
|
||||
ranker's learning (`models.io.extraction_ranker.learn`, a background thread after an import); a request or
|
||||
a learning step ends well within the API's request timeout, so an older running one was cut off before."""
|
||||
path = Path(root) / 'mlflow.db'
|
||||
require(type(timeout_s) is int and timeout_s > 0 and type(now_ms) is int, 'invalid notebook run window')
|
||||
require(request_timeout_s is None or (type(request_timeout_s) is int and request_timeout_s > 0),
|
||||
'invalid notebook run window')
|
||||
if not path.exists() and not path.is_symlink():
|
||||
return {'active': 0, 'training': 0}
|
||||
|
||||
def count(immutable):
|
||||
with closing(readonly(path, immutable=immutable)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
tables = {name: {row[1] for row in connection.execute('PRAGMA table_info(' + quote(name) + ')')}
|
||||
for (name,) in connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('runs', 'tags')")}
|
||||
if not tables:
|
||||
return {'active': 0, 'training': 0}
|
||||
require(tables.get('runs', set()) >= {'run_uuid', 'status', 'lifecycle_stage', 'start_time'}
|
||||
and tables.get('tags', set()) >= {'run_uuid', 'key', 'value'},
|
||||
'MLflow run status is unverifiable')
|
||||
notebook = ("EXISTS (SELECT 1 FROM tags t WHERE t.run_uuid = r.run_uuid AND t.key = 'experiment'"
|
||||
" AND t.value = 'notebook')")
|
||||
running = ("SELECT count(*) FROM runs r WHERE r.status = 'RUNNING' AND r.lifecycle_stage = 'active'"
|
||||
" AND (r.start_time IS NULL OR r.start_time >= ?) AND ")
|
||||
limit = now_ms - (timeout_s + NOTEBOOK_STALE_MARGIN_S) * 1000
|
||||
result = {'active': connection.execute(running + notebook, (limit,)).fetchone()[0], 'training': 0}
|
||||
if request_timeout_s is not None:
|
||||
limit = now_ms - (request_timeout_s + NOTEBOOK_STALE_MARGIN_S) * 1000
|
||||
result['training'] = connection.execute(running + 'NOT ' + notebook, (limit,)).fetchone()[0]
|
||||
return result
|
||||
|
||||
try:
|
||||
return count(False)
|
||||
except sqlite3.OperationalError as exc:
|
||||
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
|
||||
if (not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN'
|
||||
or any(p.exists() or p.is_symlink() for p in sidecars)):
|
||||
raise RuntimeError('MLflow run status is unverifiable') from None
|
||||
return count(True)
|
||||
|
||||
|
||||
def mlflow_store(root, *, quiesced=False):
|
||||
"""The MLflow store's schema revision and how many registered models have a version in production.
|
||||
|
||||
MLflow refuses to open a store whose schema is older than its own, and with a production version the
|
||||
recalculation's live estimators export a cohort file and store a risk batch."""
|
||||
path = Path(root) / MLFLOW_STORE
|
||||
if not path.exists() and not path.is_symlink():
|
||||
return {'exists': False, 'revision': None, 'production': 0}
|
||||
|
||||
def read(immutable):
|
||||
with closing(readonly(path, immutable=immutable)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
tables = {name for (name,) in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
||||
require('alembic_version' in tables, 'MLflow store is unverifiable')
|
||||
versions = connection.execute('SELECT version_num FROM alembic_version').fetchall()
|
||||
require(len(versions) == 1, 'MLflow store is unverifiable')
|
||||
production = 0
|
||||
if 'registered_model_aliases' in tables:
|
||||
production = connection.execute('SELECT count(*) FROM registered_model_aliases WHERE alias = ?',
|
||||
(PRODUCTION_ALIAS,)).fetchone()[0]
|
||||
return {'exists': True, 'revision': versions[0][0], 'production': production}
|
||||
|
||||
try:
|
||||
return read(False)
|
||||
except sqlite3.OperationalError as exc:
|
||||
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
|
||||
if (not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN'
|
||||
or any(p.exists() or p.is_symlink() for p in sidecars)):
|
||||
raise RuntimeError('MLflow store is unverifiable') from None
|
||||
return read(True)
|
||||
|
||||
|
||||
def mlflow_heads():
|
||||
"""The schema revisions this image's MLflow expects, from its own migration scripts."""
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
import mlflow.store.db_migrations as migrations
|
||||
|
||||
config = Config()
|
||||
config.set_main_option('script_location', os.path.dirname(migrations.__file__))
|
||||
return {'heads': sorted(ScriptDirectory.from_config(config).get_heads())}
|
||||
|
||||
|
||||
def silent_recalculate(environment):
|
||||
"""Keep library stdout out of the machine-readable response."""
|
||||
sys.stdout.flush()
|
||||
@@ -531,6 +748,15 @@ def main():
|
||||
derived=payload.get('derived', False))
|
||||
elif action == 'recalculate':
|
||||
result = silent_recalculate(payload['environment'])
|
||||
elif action == 'mlflow-store':
|
||||
result = mlflow_store(payload['data'], quiesced=payload.get('quiesced', False))
|
||||
elif action == 'mlflow-heads':
|
||||
result = mlflow_heads()
|
||||
elif action == 'runtime':
|
||||
result = {'worker': worker_module()}
|
||||
elif action == 'notebook-runs':
|
||||
result = notebook_runs(payload['data'], payload['timeout'], payload['now'],
|
||||
request_timeout_s=payload.get('request_timeout'), quiesced=payload.get('quiesced', False))
|
||||
else:
|
||||
raise RuntimeError('unsupported guard action')
|
||||
print(json.dumps(result))
|
||||
@@ -540,7 +766,7 @@ if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'inspect':
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ('inspect', 'state', 'notebook-runs', 'runtime', 'mlflow-store', 'mlflow-heads'):
|
||||
print('WN_INSPECT_DIAGNOSTIC=' + json.dumps(inspection_diagnostic(exc)), file=sys.stderr)
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'recalculate':
|
||||
diagnostic = inspection_diagnostic(exc)
|
||||
|
||||
+320
-43
@@ -20,6 +20,19 @@ import conservative
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = Path('/srv/workingnarrative-dev')
|
||||
# The image of the locked helper container; it only needs Python's standard library.
|
||||
HELPER_IMAGE = 'python:3.12-slim'
|
||||
BASE_SERVICES = ('webapi', 'webapp', 'indicadores')
|
||||
NOTEBOOK_SERVICE = 'notebooks'
|
||||
NOTEBOOK_VOLUME = 'trabajos_notebooks'
|
||||
NOTEBOOK_JOBS = '/trabajos'
|
||||
NOTEBOOK_USER = '10001:10001'
|
||||
# Declared services that Compose leaves inactive unless their profile is enabled; never started here.
|
||||
PROFILE_SERVICES = ('entrenar',)
|
||||
|
||||
|
||||
def notebook_volume_name(project):
|
||||
return f'{project}_{NOTEBOOK_VOLUME}'
|
||||
|
||||
|
||||
def validate_port(port):
|
||||
@@ -56,6 +69,127 @@ 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()
|
||||
@@ -111,7 +245,7 @@ with open('/host/.install.lock', 'a') as lock:
|
||||
"""
|
||||
try:
|
||||
run(['docker', 'run', '-d', '--network', 'host', '--name', name, '--mount',
|
||||
f'type=bind,src={base},dst=/host', 'python:3.12-slim', 'python3', '-c', script])
|
||||
f'type=bind,src={base},dst=/host', HELPER_IMAGE, 'python3', '-c', script])
|
||||
deadline = time.monotonic() + 300
|
||||
while time.monotonic() < deadline:
|
||||
if helper_exec(name, "import os; print(int(os.path.exists('/tmp/locked')))").strip() == '1':
|
||||
@@ -133,16 +267,45 @@ def reserve(helper, project, port):
|
||||
('volumes', ['docker', 'volume', 'ls', '-q'])]:
|
||||
if run([*args, '--filter', f'label=com.docker.compose.project={project}']).strip():
|
||||
raise RuntimeError(f'Compose project already owns {kind}: {project}')
|
||||
# Compose silently adopts an existing volume with the expected name, whoever created it.
|
||||
if notebook_volume_identity(project, missing_ok=True, verify=False) is not None:
|
||||
raise RuntimeError(f'a volume named {notebook_volume_name(project)} already exists')
|
||||
host_action(helper, 'reserve', project, str(port))
|
||||
|
||||
|
||||
def notebook_volume_identity(project, *, missing_ok=False, verify=True):
|
||||
"""The Compose-created local volume holding this installation's notebook jobs, or None if absent."""
|
||||
name = notebook_volume_name(project)
|
||||
if name not in run(['docker', 'volume', 'ls', '-q', '--filter', 'name=' + name]).split():
|
||||
if missing_ok:
|
||||
return None
|
||||
raise RuntimeError('notebook jobs volume is missing')
|
||||
items = json.loads(run(['docker', 'volume', 'inspect', name]))
|
||||
if not verify:
|
||||
return {'name': name}
|
||||
if len(items) != 1:
|
||||
raise RuntimeError('notebook jobs volume identity is not verifiable')
|
||||
volume = items[0]
|
||||
labels = volume.get('Labels') or {}
|
||||
mountpoint = volume.get('Mountpoint')
|
||||
if (volume.get('Name') != name or volume.get('Driver') != 'local' or volume.get('Scope') != 'local'
|
||||
or volume.get('Options') or labels.get('com.docker.compose.project') != project
|
||||
or labels.get('com.docker.compose.volume') != NOTEBOOK_VOLUME
|
||||
or not isinstance(mountpoint, str) or not mountpoint.startswith('/')
|
||||
or not isinstance(volume.get('CreatedAt'), str) or not volume['CreatedAt']):
|
||||
raise RuntimeError('notebook jobs volume identity is not verifiable')
|
||||
return {'name': name, 'created': volume['CreatedAt'], 'mountpoint': posixpath.normpath(mountpoint)}
|
||||
|
||||
|
||||
def host_action(helper, action, *args):
|
||||
"""Run a host action with its guard modules in the locked helper."""
|
||||
script = Path(__file__).with_name('host.py').read_text(encoding='utf-8')
|
||||
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")
|
||||
prefix = "import sys, types\n"
|
||||
for name in ('data_guard', 'notebook_guard'):
|
||||
source = Path(__file__).with_name(name + '.py').read_text(encoding='utf-8')
|
||||
prefix += (f"module = types.ModuleType({name!r})\n"
|
||||
f"sys.modules[{name!r}] = module\n"
|
||||
f"exec({source!r}, module.__dict__)\n")
|
||||
return helper_exec(helper, prefix + script, '/host', action, *args[:-1], '-', stdin=str(args[-1]))
|
||||
|
||||
|
||||
@@ -159,23 +322,55 @@ def configure(deploy, data, project, revision, port):
|
||||
return tag
|
||||
|
||||
|
||||
def unsafe_service(service):
|
||||
namespaces = [str(service.get(key, '')) for key in ('network_mode', 'pid', 'ipc', 'userns_mode', 'cgroup')]
|
||||
unmanaged = {'privileged', 'devices', 'device_cgroup_rules', 'cap_add', 'volumes_from', 'use_api_socket',
|
||||
'post_start', 'pre_stop', 'develop', 'secrets', 'configs', 'external_links'}
|
||||
return (any(service.get(key) for key in unmanaged)
|
||||
or any(value == 'host' or value.startswith(('container:', 'service:')) for value in namespaces))
|
||||
|
||||
|
||||
def data_mount(volume, data):
|
||||
return (volume.get('type') == 'bind' and volume.get('source') == str(data) and volume.get('target') == '/data'
|
||||
and not volume.get('read_only'))
|
||||
|
||||
|
||||
def jobs_mount(volume):
|
||||
return (volume.get('type') == 'volume' and volume.get('source') == NOTEBOOK_VOLUME
|
||||
and volume.get('target') == NOTEBOOK_JOBS and not volume.get('read_only')
|
||||
and volume.get('volume') in (None, {}))
|
||||
|
||||
|
||||
def verify_config(config, project, data, tag, port):
|
||||
"""Check the effective composition; return its notebook jobs volume name, or None without notebooks."""
|
||||
if config.get('name') != project:
|
||||
raise RuntimeError('effective Compose project name does not match')
|
||||
services = config.get('services', {})
|
||||
if set(services) != {'webapi', 'webapp', 'indicadores'}:
|
||||
notebooks = NOTEBOOK_SERVICE in services
|
||||
required = set(BASE_SERVICES) | ({NOTEBOOK_SERVICE} if notebooks else set())
|
||||
declared = {name for name in services if name in PROFILE_SERVICES and services[name].get('profiles') == [name]}
|
||||
if set(services) - declared != required:
|
||||
raise RuntimeError('unexpected Compose services')
|
||||
volume = notebook_volume_name(project) if notebooks else None
|
||||
if (config.get('volumes') or {}) != ({NOTEBOOK_VOLUME: {'name': volume}} if notebooks else {}):
|
||||
raise RuntimeError('unexpected Compose volumes')
|
||||
networks = config.get('networks') or {}
|
||||
if networks:
|
||||
default = networks.get('default') or {}
|
||||
if (set(networks) != {'default'} or default.get('name') != project + '_default'
|
||||
or set(default) - {'name', 'ipam'} or default.get('ipam')):
|
||||
raise RuntimeError('unexpected Compose networks')
|
||||
for name, service in services.items():
|
||||
if (service.get('privileged') or service.get('network_mode') == 'host'
|
||||
or service.get('pid') == 'host' or service.get('devices')):
|
||||
if unsafe_service(service):
|
||||
raise RuntimeError(f'unsafe Compose service: {name}')
|
||||
for name in ('webapi', 'indicadores'):
|
||||
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', [])
|
||||
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):
|
||||
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')
|
||||
@@ -183,6 +378,24 @@ def verify_config(config, project, data, tag, port):
|
||||
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
|
||||
if env.get(f'{domain}_DATABASE_URL') != f'sqlite:////data/{domain.lower()}.db':
|
||||
raise RuntimeError(f'unexpected {name} database configuration')
|
||||
# Unset, the image's own values apply (MLflow, reports and indicators under /data); set, they must match.
|
||||
if any(key in env and env[key] != value for key, value in conservative.PERSISTENT_ENV.items()):
|
||||
raise RuntimeError(f'unexpected {name} storage configuration')
|
||||
if notebooks:
|
||||
env = services['webapi'].get('environment', {})
|
||||
if env.get('NOTEBOOK_JOBS_DIR') != NOTEBOOK_JOBS or env.get('NOTEBOOK_RUNNER_UID') != NOTEBOOK_USER.split(':')[0]:
|
||||
raise RuntimeError('unexpected webapi notebook configuration')
|
||||
runner = services[NOTEBOOK_SERVICE]
|
||||
env = runner.get('environment', {})
|
||||
if (runner.get('image') != f'isssteleon/webapi:{tag}' or runner.get('command') != ['notebooks']
|
||||
or runner.get('entrypoint') or runner.get('user') != NOTEBOOK_USER
|
||||
or runner.get('network_mode') != 'none' or runner.get('read_only') is not True
|
||||
or 'ALL' not in (runner.get('cap_drop') or [])
|
||||
or 'no-new-privileges:true' not in (runner.get('security_opt') or [])
|
||||
or runner.get('ports') or len(runner.get('volumes', [])) != 1
|
||||
or not jobs_mount(runner['volumes'][0]) or env.get('NOTEBOOK_JOBS_DIR') != NOTEBOOK_JOBS
|
||||
or any('/data' in str(value) for value in env.values())):
|
||||
raise RuntimeError('unexpected notebooks isolation')
|
||||
if services['webapp'].get('image') != f'isssteleon/webapp:{tag}':
|
||||
raise RuntimeError('unexpected webapp image')
|
||||
if services['webapp'].get('volumes'):
|
||||
@@ -190,14 +403,15 @@ def verify_config(config, project, data, tag, port):
|
||||
ports = services['webapp'].get('ports', [])
|
||||
if len(ports) != 1 or str(ports[0].get('published')) != str(port) or int(ports[0].get('target', 0)) != 80:
|
||||
raise RuntimeError('unexpected webapp port')
|
||||
return volume
|
||||
|
||||
|
||||
def verify_services(cmd, port, timeout=300):
|
||||
def verify_services(cmd, port, timeout=300, *, notebooks=False):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = 'services did not start'
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
for service in ('webapi', 'webapp', 'indicadores'):
|
||||
for service in BASE_SERVICES + ((NOTEBOOK_SERVICE,) if notebooks else ()):
|
||||
ids = run([*cmd, 'ps', '-q', service]).splitlines()
|
||||
if len(ids) != 1:
|
||||
raise RuntimeError(f'{service}: expected one running container')
|
||||
@@ -220,7 +434,9 @@ def verify_services(cmd, port, timeout=300):
|
||||
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()
|
||||
expected = git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
|
||||
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)
|
||||
@@ -229,7 +445,8 @@ def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
|
||||
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'}
|
||||
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing',
|
||||
**metadata}
|
||||
def save():
|
||||
host_action(helper, 'save', project, json.dumps(record))
|
||||
cmd = None
|
||||
@@ -251,23 +468,34 @@ def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
|
||||
run(['docker', 'run', '--rm', '--mount', f'type=bind,src={data},dst=/data',
|
||||
'--entrypoint', 'python3', record['images'][0], '-c', probe])
|
||||
cmd = compose(project, deploy)
|
||||
runtime = conservative.guard(sys.modules[__name__], record['images'][0], 'runtime', {})
|
||||
config = conservative.controlled_config(
|
||||
json.loads(run([*cmd, 'config', '--format', 'json'])), migrate_on_start=True)
|
||||
verify_config(config, project, data, tag, port)
|
||||
json.loads(run([*cmd, 'config', '--format', 'json'])), migrate_on_start=True,
|
||||
worker=runtime['worker'])
|
||||
volume = verify_config(config, project, data, tag, port)
|
||||
if volume:
|
||||
record['notebook_volume'] = volume
|
||||
conservative.persist_config(deploy, config)
|
||||
copy_to_host(helper, deploy / 'docker-compose.yml', project, 'deploy/docker-compose.yml')
|
||||
record['status'] = 'starting'
|
||||
record['phase'] = 'initial-migration-and-api'
|
||||
save()
|
||||
run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
|
||||
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',
|
||||
api = sys.modules[__name__]
|
||||
conservative.verify_api(api, cmd, data, record['images'][0], notebook_volume=volume)
|
||||
check_jobs = None
|
||||
if volume:
|
||||
jobs = conservative.verify_new_notebook_volume(api, record['images'][0], project)
|
||||
check_jobs = lambda: conservative.verify_notebook_jobs(api, record['images'][0], project,
|
||||
jobs['identity'], jobs['digest'])
|
||||
contract = conservative.guard(api, record['images'][0], 'contract', {})
|
||||
before = conservative.guard(api, record['images'][0], 'state',
|
||||
{'data': '/data', 'contract': contract}, data)
|
||||
record['phase'] = 'recalculation-and-persistence'
|
||||
save()
|
||||
conservative.finish(sys.modules[__name__], cmd, record['images'][0], deploy, data, contract, before)
|
||||
verify_services(cmd, port)
|
||||
conservative.finish(api, cmd, record['images'][0], deploy, data, contract, before,
|
||||
notebook_volume=volume, before_frontend=check_jobs)
|
||||
verify_services(cmd, port, notebooks=bool(volume))
|
||||
verify_existing_containers(record, base, helper)
|
||||
record['status'] = 'installed'
|
||||
record['result'] = 'installed'
|
||||
@@ -295,12 +523,25 @@ def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
|
||||
run(['docker', 'rm', '-f', helper])
|
||||
|
||||
|
||||
def record_volume(record):
|
||||
"""The notebook jobs volume an installation record declares; a record without one predates notebooks."""
|
||||
volume = record.get('notebook_volume')
|
||||
if volume is not None and volume != notebook_volume_name(record['project']):
|
||||
raise RuntimeError('installation record names an unexpected notebook jobs volume')
|
||||
return volume
|
||||
|
||||
|
||||
def verify_existing_containers(record, base, helper):
|
||||
"""Reject unexpected containers, image identities, mounts and port owners."""
|
||||
"""Reject unexpected containers, image identities, mounts, volume owners and port owners.
|
||||
|
||||
Returns the container IDs as indicadores, webapi, webapp and, with notebooks, the runner."""
|
||||
project, port = record['project'], record['port']
|
||||
images = record.get('images')
|
||||
if not isinstance(images, list) or len(images) != 2 or not all(isinstance(x, str) for x in images):
|
||||
raise RuntimeError('installation image record is missing')
|
||||
volume = record_volume(record)
|
||||
jobs = notebook_volume_identity(project) if volume else None
|
||||
expected_services = BASE_SERVICES + ((NOTEBOOK_SERVICE,) if volume else ())
|
||||
image_ids = [run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip() for image in images]
|
||||
if not all(image_ids):
|
||||
raise RuntimeError('recorded image not found')
|
||||
@@ -309,6 +550,7 @@ def verify_existing_containers(record, base, helper):
|
||||
found = {}
|
||||
root = posixpath.normpath(str(base / project))
|
||||
data = posixpath.join(root, 'data')
|
||||
data_bind = {'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}
|
||||
for item in containers:
|
||||
name = item.get('Name', '').lstrip('/')
|
||||
if name == helper:
|
||||
@@ -324,41 +566,62 @@ def verify_existing_containers(record, base, helper):
|
||||
overlap = source == root or source.startswith(root + '/') or root.startswith(source.rstrip('/') + '/')
|
||||
if overlap and not own:
|
||||
raise RuntimeError(f'foreign container can access installation: {name}')
|
||||
if not own and (mount.get('Name') == notebook_volume_name(project) or (jobs and (
|
||||
source == jobs['mountpoint'] or source.startswith(jobs['mountpoint'] + '/')
|
||||
or jobs['mountpoint'].startswith(source.rstrip('/') + '/')))):
|
||||
raise RuntimeError(f'foreign container can access notebook jobs: {name}')
|
||||
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
|
||||
if not own and any(str(b.get('HostPort')) == str(port) for values in bindings.values() for b in (values or [])):
|
||||
raise RuntimeError(f'foreign container reserves port {port}: {name}')
|
||||
if not own:
|
||||
continue
|
||||
service = labels.get('com.docker.compose.service')
|
||||
if service not in ('webapi', 'webapp', 'indicadores') or service in found:
|
||||
if labels.get('com.docker.compose.oneoff') == 'True' or service in PROFILE_SERVICES:
|
||||
raise RuntimeError(f'one-shot {service} container is present; remove it once it has finished')
|
||||
if service not in expected_services or service in found:
|
||||
raise RuntimeError('unexpected container in Compose project')
|
||||
if item.get('State', {}).get('Status') != 'running':
|
||||
raise RuntimeError(f'{service} is not running')
|
||||
expected = image_ids[1 if service == 'webapp' else 0]
|
||||
if item.get('Image') != expected:
|
||||
raise RuntimeError(f'{service} image does not match installation record')
|
||||
jobs_volume = {'Type': 'volume', 'Name': volume, 'Destination': NOTEBOOK_JOBS, 'RW': True}
|
||||
shapes = [{key: mount.get(key) for key in ('Type', 'Name' if mount.get('Type') == 'volume' else 'Source',
|
||||
'Destination', 'RW')} for mount in mounts]
|
||||
if service in ('webapi', 'indicadores'):
|
||||
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):
|
||||
wanted = [data_bind] + ([jobs_volume] if volume and service == 'webapi' else [])
|
||||
if len(shapes) != len(wanted) or any(mount not in shapes for mount in wanted):
|
||||
raise RuntimeError(f'{service} data mount does not match')
|
||||
if bindings:
|
||||
raise RuntimeError(f'{service} publishes an unexpected port')
|
||||
elif 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')
|
||||
elif service == NOTEBOOK_SERVICE:
|
||||
host = item.get('HostConfig', {})
|
||||
if shapes != [jobs_volume] or bindings:
|
||||
raise RuntimeError('notebooks mount does not match')
|
||||
if (host.get('NetworkMode') != 'none' or host.get('ReadonlyRootfs') is not True or host.get('Privileged')
|
||||
or 'ALL' not in (host.get('CapDrop') or []) or host.get('CapAdd')
|
||||
or 'no-new-privileges:true' not in (host.get('SecurityOpt') or [])
|
||||
or item.get('Config', {}).get('User') != NOTEBOOK_USER):
|
||||
raise RuntimeError('notebooks isolation does not match')
|
||||
else:
|
||||
published = bindings.get('80/tcp') or []
|
||||
if (mounts or set(bindings) != {'80/tcp'} or not published
|
||||
or any(str(binding.get('HostPort')) != str(port) for binding in published)):
|
||||
raise RuntimeError('webapp port does not match')
|
||||
found[service] = item['Id']
|
||||
if set(found) != {'webapi', 'webapp', 'indicadores'}:
|
||||
if set(found) != set(expected_services):
|
||||
raise RuntimeError('missing Compose project containers')
|
||||
own_networks = {network.get('NetworkID')
|
||||
for item in containers if item.get('Id') in found.values()
|
||||
for network in item.get('NetworkSettings', {}).get('Networks', {}).values()
|
||||
if network.get('NetworkID')}
|
||||
for name, network in (item.get('NetworkSettings', {}).get('Networks') or {}).items()
|
||||
if name != 'none' and network.get('NetworkID')}
|
||||
for item in containers:
|
||||
if item.get('Id') in found.values() or item.get('Name', '').lstrip('/') == helper:
|
||||
continue
|
||||
networks = item.get('NetworkSettings', {}).get('Networks', {})
|
||||
networks = item.get('NetworkSettings', {}).get('Networks') or {}
|
||||
if any(network.get('NetworkID') in own_networks for network in networks.values()):
|
||||
raise RuntimeError('foreign container shares the installation network')
|
||||
return [found[name] for name in ('indicadores', 'webapi', 'webapp')]
|
||||
return [found[name] for name in ('indicadores', 'webapi', 'webapp', NOTEBOOK_SERVICE) if name in found]
|
||||
|
||||
|
||||
def update(record, helper, root=ROOT, base=BASE, *, verify_restore=False):
|
||||
@@ -366,6 +629,18 @@ def update(record, helper, root=ROOT, base=BASE, *, verify_restore=False):
|
||||
verify_restore=verify_restore)
|
||||
|
||||
|
||||
def install_free_port(port, root, base, helper):
|
||||
"""Install a new instance on a port no record or container holds, under the caller's helper lock."""
|
||||
normalized = validate_port(port)
|
||||
ids = run(['docker', 'ps', '-aq', '--no-trunc']).splitlines()
|
||||
for item in json.loads(run(['docker', 'inspect', *ids])) if ids else []:
|
||||
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
|
||||
if any(str(b.get('HostPort')) == str(normalized) for values in bindings.values() for b in (values or [])):
|
||||
raise RuntimeError(f'port {normalized} is reserved by another container')
|
||||
host_action(helper, 'check-port', '-', str(normalized))
|
||||
install(automatic_instance(port), port, 'instalar', root, base, helper=helper)
|
||||
|
||||
|
||||
def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
|
||||
"""Route under the shared lock after checking any caller-specific record precondition."""
|
||||
normalized = validate_port(port)
|
||||
@@ -375,13 +650,7 @@ def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
|
||||
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)
|
||||
install_free_port(port, root, base, helper)
|
||||
else:
|
||||
update(record, helper, root, base)
|
||||
finally:
|
||||
@@ -390,11 +659,19 @@ def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto'])
|
||||
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 in ('validate-auto', 'install-auto'):
|
||||
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]
|
||||
|
||||
+24
-1
@@ -12,6 +12,7 @@ import sys
|
||||
import tempfile
|
||||
|
||||
import data_guard
|
||||
import notebook_guard
|
||||
|
||||
|
||||
def write_record(directory, record):
|
||||
@@ -156,14 +157,32 @@ def backup_installation(base, project, payload):
|
||||
return {'path': str(destination), 'state': manifest['state']}
|
||||
|
||||
|
||||
def notebook_backup_directory(base, project, operation):
|
||||
"""Create the empty notebook jobs destination inside an existing operation backup."""
|
||||
operation_directory(base, project, operation)
|
||||
parent = base / '.backups' / project / operation
|
||||
if parent.is_symlink() or not parent.is_dir() or not (parent / 'manifest.json').is_file():
|
||||
raise RuntimeError('operation data backup is missing')
|
||||
target = parent / 'notebooks'
|
||||
target.mkdir(mode=0o700)
|
||||
return target
|
||||
|
||||
|
||||
def verify_notebook_backup(base, project, operation):
|
||||
operation_directory(base, project, operation)
|
||||
return notebook_guard.verify_backup(base / '.backups' / project / operation / 'notebooks')
|
||||
|
||||
|
||||
def verify_isolated_restore(base, project, operation):
|
||||
"""Restore the operation backup to a new private location and verify it."""
|
||||
"""Restore the operation backup, with its notebook jobs if it has them, to new private locations."""
|
||||
operation_directory(base, project, operation)
|
||||
source = base / '.backups' / project / operation
|
||||
restores = private_directory(base / '.restores')
|
||||
project_restores = private_directory(restores / project)
|
||||
destination = project_restores / operation
|
||||
data_guard.restore_backup(source, destination)
|
||||
if (source / 'notebooks').exists() or (source / 'notebooks').is_symlink():
|
||||
notebook_guard.restore(source / 'notebooks', project_restores / (operation + '.notebooks'))
|
||||
return destination
|
||||
|
||||
|
||||
@@ -287,6 +306,10 @@ def main():
|
||||
prepare_backup(base, project, json.loads(value)['verify_restore'])
|
||||
elif action == 'verify-restore':
|
||||
print(verify_isolated_restore(base, project, value))
|
||||
elif action == 'prepare-notebook-backup':
|
||||
notebook_backup_directory(base, project, value)
|
||||
elif action == 'verify-notebook-backup':
|
||||
print(json.dumps(verify_notebook_backup(base, project, value)))
|
||||
elif action == 'stage':
|
||||
print(stage_installation(base, project, value))
|
||||
elif action == 'activate':
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Inspect, back up and restore the notebook jobs volume without following links.
|
||||
|
||||
The volume holds the job folders the WebApi hands to the notebook runner
|
||||
(`models.io.notebook_jobs`): `<run_id>/` with `job.json`, then `result.json`
|
||||
once the runner finishes; `.<run_id>-*` while a job is being assembled. Its
|
||||
contents are written by untrusted notebooks, so every walk uses `lstat`, links
|
||||
are stored and restored as links, and any other special file is rejected.
|
||||
Standard library only: it runs both in the locked helper and in the candidate
|
||||
image.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
FORMAT = 1
|
||||
JOB_FILE, RESULT_FILE = 'job.json', 'result.json'
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def file_digest(path):
|
||||
result = hashlib.sha256()
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
|
||||
with os.fdopen(descriptor, 'rb') as stream:
|
||||
require(stat.S_ISREG(os.fstat(stream.fileno()).st_mode), 'notebook job entry changed type')
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
result.update(chunk)
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def describe(path):
|
||||
info = os.lstat(path)
|
||||
entry = {'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid,
|
||||
'mtime_ns': info.st_mtime_ns}
|
||||
if stat.S_ISDIR(info.st_mode):
|
||||
entry['type'] = 'dir'
|
||||
elif stat.S_ISREG(info.st_mode):
|
||||
entry.update(type='file', size=info.st_size, sha256=file_digest(path))
|
||||
elif stat.S_ISLNK(info.st_mode):
|
||||
entry.update(type='link', target=os.readlink(path))
|
||||
else:
|
||||
raise RuntimeError('notebook job entry type is unsupported')
|
||||
return entry
|
||||
|
||||
|
||||
def scan(root):
|
||||
"""Every entry below `root` keyed by its relative POSIX path; the root itself is `.`."""
|
||||
root = Path(root)
|
||||
require(stat.S_ISDIR(os.lstat(root).st_mode), 'notebook jobs root is missing or linked')
|
||||
entries = {'.': describe(root)}
|
||||
pending = [root]
|
||||
while pending:
|
||||
directory = pending.pop()
|
||||
with os.scandir(directory) as listing:
|
||||
for item in listing:
|
||||
path = Path(item.path)
|
||||
name = path.relative_to(root).as_posix()
|
||||
entries[name] = describe(path)
|
||||
if entries[name]['type'] == 'dir':
|
||||
pending.append(path)
|
||||
return dict(sorted(entries.items()))
|
||||
|
||||
|
||||
def state_digest(entries):
|
||||
return hashlib.sha256(json.dumps(entries, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def activity(entries):
|
||||
"""Top-level entries that show a job being assembled, waiting or running, or anything unrecognized."""
|
||||
active = {}
|
||||
for name, entry in entries.items():
|
||||
if name == '.' or '/' in name:
|
||||
continue
|
||||
if name.startswith('.'):
|
||||
active[name] = 'assembling'
|
||||
elif entry['type'] != 'dir':
|
||||
active[name] = 'unexpected'
|
||||
elif entries.get(name + '/' + JOB_FILE, {}).get('type') != 'file':
|
||||
active[name] = 'incomplete'
|
||||
elif entries.get(name + '/' + RESULT_FILE, {}).get('type') != 'file':
|
||||
active[name] = 'pending'
|
||||
return active
|
||||
|
||||
|
||||
def inspect(root):
|
||||
entries = scan(root)
|
||||
active = activity(entries)
|
||||
return {'digest': state_digest(entries), 'entries': len(entries),
|
||||
'bytes': sum(entry.get('size', 0) for entry in entries.values()),
|
||||
'jobs': sum(1 for name in entries if name != '.' and '/' not in name),
|
||||
'active': sorted(set(active.values()))}
|
||||
|
||||
|
||||
def copy_entries(source, target, entries):
|
||||
"""Recreate `entries` from `source` under the existing empty `target` with their metadata."""
|
||||
source, target = Path(source), Path(target)
|
||||
for name, entry in entries.items():
|
||||
if name == '.':
|
||||
continue
|
||||
origin, destination = source / name, target / name
|
||||
if entry['type'] == 'dir':
|
||||
os.mkdir(destination, 0o700)
|
||||
elif entry['type'] == 'link':
|
||||
os.symlink(entry['target'], destination)
|
||||
else:
|
||||
descriptor = os.open(origin, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
|
||||
with os.fdopen(descriptor, 'rb') as reader:
|
||||
require(stat.S_ISREG(os.fstat(reader.fileno()).st_mode), 'notebook job entry changed type')
|
||||
output = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0),
|
||||
0o600)
|
||||
with os.fdopen(output, 'wb') as writer:
|
||||
for chunk in iter(lambda: reader.read(1024 * 1024), b''):
|
||||
writer.write(chunk)
|
||||
writer.flush()
|
||||
os.fsync(writer.fileno())
|
||||
# Metadata goes last: creating an entry would change its parent's mtime.
|
||||
for name in entries:
|
||||
entry = entries[name]
|
||||
path = target if name == '.' else target / name
|
||||
link = entry['type'] == 'link'
|
||||
if not link:
|
||||
os.chmod(path, entry['mode'])
|
||||
os.utime(path, ns=(entry['mtime_ns'], entry['mtime_ns']), follow_symlinks=not link)
|
||||
if hasattr(os, 'chown'):
|
||||
os.chown(path, entry['uid'], entry['gid'], follow_symlinks=not link)
|
||||
|
||||
|
||||
def empty_directory(path):
|
||||
path = Path(path)
|
||||
require(stat.S_ISDIR(os.lstat(path).st_mode), 'notebook backup destination is missing or linked')
|
||||
require(not any(path.iterdir()), 'notebook backup destination is not empty')
|
||||
return path
|
||||
|
||||
|
||||
def backup(root, destination, volume):
|
||||
"""Copy idle jobs to `destination/content` and verify their manifest against the quiesced volume."""
|
||||
destination = empty_directory(destination)
|
||||
before = scan(root)
|
||||
require(not activity(before), 'notebook jobs are active')
|
||||
content = destination / 'content'
|
||||
os.mkdir(content, 0o700)
|
||||
copy_entries(root, content, before)
|
||||
require(scan(root) == before, 'notebook jobs changed while creating the backup')
|
||||
require(scan(content) == before, 'notebook backup differs from the volume')
|
||||
manifest = {'format': FORMAT, 'volume': volume, 'digest': state_digest(before), 'entries': before}
|
||||
descriptor = os.open(destination / 'manifest.json', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
|
||||
json.dump(manifest, stream, sort_keys=True)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return verify_backup(destination)
|
||||
|
||||
|
||||
def verify_backup(destination):
|
||||
destination = Path(destination)
|
||||
require(stat.S_ISDIR(os.lstat(destination).st_mode), 'notebook backup directory is invalid')
|
||||
manifest = json.loads((destination / 'manifest.json').read_text(encoding='utf-8'))
|
||||
require(manifest.get('format') == FORMAT and isinstance(manifest.get('entries'), dict),
|
||||
'notebook backup manifest is invalid')
|
||||
require(state_digest(manifest['entries']) == manifest['digest'], 'notebook backup manifest is inconsistent')
|
||||
require(scan(destination / 'content') == manifest['entries'], 'notebook backup content differs')
|
||||
return {'digest': manifest['digest'], 'volume': manifest['volume'], 'entries': len(manifest['entries'])}
|
||||
|
||||
|
||||
def restore(source, target):
|
||||
"""Restore a verified backup into an empty directory, a new isolated one or an empty volume root."""
|
||||
verify_backup(source)
|
||||
manifest = json.loads((Path(source) / 'manifest.json').read_text(encoding='utf-8'))
|
||||
target = Path(target)
|
||||
if not os.path.lexists(target):
|
||||
os.mkdir(target, 0o700)
|
||||
empty_directory(target)
|
||||
copy_entries(Path(source) / 'content', target, manifest['entries'])
|
||||
require(scan(target) == manifest['entries'], 'notebook restore differs from the backup')
|
||||
return {'digest': manifest['digest']}
|
||||
|
||||
|
||||
def main():
|
||||
action, payload = sys.argv[1], json.load(sys.stdin)
|
||||
if action == 'inspect':
|
||||
result = inspect(payload['root'])
|
||||
elif action == 'backup':
|
||||
result = backup(payload['root'], payload['destination'], payload['volume'])
|
||||
elif action == 'verify':
|
||||
result = verify_backup(payload['destination'])
|
||||
elif action == 'restore':
|
||||
result = restore(payload['source'], payload['target'])
|
||||
else:
|
||||
raise RuntimeError('unsupported notebook guard action')
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
reason = str(exc) if isinstance(exc, RuntimeError) and str(exc).startswith('notebook') else ''
|
||||
print('WN_NOTEBOOK_DIAGNOSTIC=' + json.dumps({'type': type(exc).__name__, 'reason': reason}),
|
||||
file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Report sanitized checkout URL comparisons without contacting a remote."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
|
||||
SSH = 'ssh://git@10.0.10.41:2222/ISSSTELEON/WorkingNarrative.git'
|
||||
SERVER = 'http://10.0.10.41:3000'
|
||||
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
|
||||
|
||||
|
||||
def describe(value):
|
||||
"""Return fixed labels and comparisons, never any part of the input."""
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
scheme = parsed.scheme if parsed.scheme in ('http', 'https', 'ssh') else 'other'
|
||||
return {'exact_http': value == OFFICIAL,
|
||||
'exact_http_without_git': value == OFFICIAL.removesuffix('.git'), 'exact_ssh': value == SSH,
|
||||
'scheme': scheme, 'official_host': parsed.hostname == '10.0.10.41',
|
||||
'official_http_port': parsed.port == 3000,
|
||||
'official_ssh_port': parsed.port == 2222,
|
||||
'repository_path': parsed.path == '/ISSSTELEON/WorkingNarrative.git',
|
||||
'repository_path_without_git': parsed.path == '/ISSSTELEON/WorkingNarrative',
|
||||
'userinfo_present': parsed.username is not None or parsed.password is not None,
|
||||
'query_or_fragment': bool(parsed.query or parsed.fragment)}
|
||||
except ValueError:
|
||||
return {'invalid_url': True}
|
||||
|
||||
|
||||
def git_values(*args):
|
||||
result = subprocess.run(['git', *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True, encoding='utf-8', errors='replace', check=False)
|
||||
return result.stdout.splitlines() if result.returncode == 0 else []
|
||||
|
||||
|
||||
def main():
|
||||
literal = git_values('config', '--get-all', 'remote.origin.url')
|
||||
effective = git_values('remote', 'get-url', '--all', 'origin')
|
||||
github = os.environ.get('GITHUB_SERVER_URL', '')
|
||||
gitea = os.environ.get('GITEA_SERVER_URL', '')
|
||||
result = {'literal_origin': [describe(url) for url in literal],
|
||||
'effective_origin': [describe(url) for url in effective],
|
||||
'origin_rewritten': literal != effective,
|
||||
'github_server_is_official': github.rstrip('/') == SERVER,
|
||||
'gitea_server_is_official': gitea.rstrip('/') == SERVER,
|
||||
'server_variables_equal': bool(github and gitea) and github.rstrip('/') == gitea.rstrip('/'),
|
||||
'event_server_is_official': os.environ.get('DISPATCH_SERVER', '').rstrip('/') == SERVER,
|
||||
'event_repository_is_official': os.environ.get('DISPATCH_REPOSITORY') == REPOSITORY}
|
||||
print('Checkout origin diagnostic:', json.dumps(result, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -81,9 +81,11 @@ def recovery_evidence(archive, restored, expected, installation):
|
||||
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')
|
||||
runner = getattr(args, 'notebooks', None)
|
||||
ids = [args.indicadores, args.webapi, args.webapp] + ([runner] if runner else [])
|
||||
if len(set(ids)) != len(ids) or any(not re.fullmatch(r'[0-9a-f]{64}', value) for value in ids):
|
||||
raise ValueError('distinct full original container IDs are required: indicadores, webapi, webapp and, '
|
||||
'with notebooks, the runner')
|
||||
if not args.external_copy_verified:
|
||||
raise RuntimeError('operator must attest the external backup copy was verified')
|
||||
lock = api.BASE / '.install.lock'
|
||||
@@ -94,6 +96,8 @@ def reconcile(args, api=dev):
|
||||
request = {'port': port, 'revision': args.revision, 'operation_id': args.operation}
|
||||
result = json.loads(api.host_action(helper, 'reconcile-check', project, json.dumps(request)))
|
||||
record = result['record']
|
||||
if bool(record.get('notebook_volume')) != bool(runner):
|
||||
raise RuntimeError('the notebook runner ID is required exactly for installations with notebooks')
|
||||
expected_tag_prefix = project + '-' + args.revision[:12] + '-'
|
||||
images = record.get('images', [])
|
||||
if (len(images) != 2 or not images[0].startswith('isssteleon/webapi:' + expected_tag_prefix)
|
||||
@@ -110,7 +114,9 @@ def reconcile(args, api=dev):
|
||||
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)
|
||||
volume = api.verify_config(config, project, api.BASE / project / 'data', images[0].split(':', 1)[1], port)
|
||||
if volume != record.get('notebook_volume'):
|
||||
raise RuntimeError('retained composition and installation record disagree on notebook jobs')
|
||||
conservative.current_environment(api, ids, config)
|
||||
containers = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
for item in containers:
|
||||
@@ -119,7 +125,7 @@ def reconcile(args, api=dev):
|
||||
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)
|
||||
api.verify_services(cmd, port, timeout=1, notebooks=bool(runner))
|
||||
contract = conservative.guard(api, images[0], 'contract', {})
|
||||
conservative.guard(api, images[0], 'state', {'data': '/data', 'contract': contract},
|
||||
api.BASE / project / 'data')
|
||||
@@ -143,6 +149,7 @@ def main():
|
||||
'backup', 'backup-sha256', 'restored-data'):
|
||||
parser.add_argument('--' + name, required=True)
|
||||
parser.add_argument('--port', required=True, type=int)
|
||||
parser.add_argument('--notebooks', help='original notebook runner container ID, for installations with notebooks')
|
||||
parser.add_argument('--external-copy-verified', action='store_true')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
|
||||
@@ -252,7 +252,8 @@ class LabReset:
|
||||
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 self.api.verify_config(config, PROJECT, self.root / 'data', tag, 18080) is not None:
|
||||
raise RuntimeError('the laboratory reset supports only the three-service composition')
|
||||
if any(set(service) & {'post_start', 'pre_stop', 'develop', 'secrets', 'configs',
|
||||
'volumes_from', 'external_links', 'use_api_socket'}
|
||||
for service in config['services'].values()):
|
||||
|
||||
@@ -400,6 +400,16 @@ class SimulatedDeployment:
|
||||
self.mount_changed = False
|
||||
self.finished = False
|
||||
self.running = {name: True for name in ('worker', 'api', 'app')}
|
||||
self.active_runs = self.training_runs = 0
|
||||
# What the `mlflow-store` guard reports about data/mlflow.db.
|
||||
self.mlflow = {'exists': True, 'revision': 'dc11669786a5', 'production': 0}
|
||||
gunicorn = ('/app/WebApi/.venv/bin/python -m gunicorn --bind 0.0.0.0:5000 --workers 2 --timeout 600 '
|
||||
'--access-logfile - webapi:create_app()')
|
||||
# What `docker top` lists per original container, and the API's `/proc/net/tcp` rows past the header.
|
||||
self.processes = {'worker': ['/app/WebApi/.venv/bin/python -m webapi.indicadores_vivos'],
|
||||
'api': [gunicorn, gunicorn], 'app': [],
|
||||
'runner': ['/app/WebApi/.venv/bin/python -m models notebooks serve']}
|
||||
self.connections = []
|
||||
self.configure = dev.configure
|
||||
self.compose = dev.compose
|
||||
self.verify_config = dev.verify_config
|
||||
@@ -435,6 +445,12 @@ class SimulatedDeployment:
|
||||
def run(self, args, **kwargs):
|
||||
args = list(map(str, args))
|
||||
self.calls.append(args)
|
||||
if args[:2] == ['docker', 'top']:
|
||||
rows = [f'{pid} {command}' for pid, command in enumerate(self.processes[args[2]], 100)]
|
||||
return '\n'.join(['PID COMMAND', *rows]) + '\n'
|
||||
if args[:2] == ['docker', 'exec'] and '/proc/net/tcp' in args:
|
||||
rows = [f' {n}: {row}' for n, row in enumerate(self.connections)]
|
||||
return '\n'.join([' sl local_address rem_address st tx_queue rx_queue', *rows]) + '\n'
|
||||
if args[:2] == ['docker', 'build'] and self.fail == 'build':
|
||||
raise RuntimeError('synthetic build failure')
|
||||
if 'config' in args:
|
||||
@@ -506,7 +522,7 @@ class SimulatedDeployment:
|
||||
raise RuntimeError('data mount does not match')
|
||||
return ['worker', 'api', 'app']
|
||||
|
||||
def verify_services(self, cmd, port):
|
||||
def verify_services(self, cmd, port, notebooks=False):
|
||||
record = host.read_record(self.root)
|
||||
if not self.finished and record['status'] != 'update_failed' and record['revision'] != self.revision:
|
||||
raise RuntimeError('worker completion was not verified')
|
||||
@@ -514,6 +530,14 @@ class SimulatedDeployment:
|
||||
def guard(self, api, image, action, payload, data=None, **kwargs):
|
||||
if action == 'contract':
|
||||
return self.contract
|
||||
if action == 'runtime':
|
||||
return {'worker': 'webapi.recomputation'}
|
||||
if action == 'notebook-runs':
|
||||
return {'active': self.active_runs, 'training': self.training_runs}
|
||||
if action == 'mlflow-store':
|
||||
return dict(self.mlflow)
|
||||
if action == 'mlflow-heads':
|
||||
return {'heads': ['dc11669786a5']}
|
||||
if action == 'inspect':
|
||||
return guard.inspect_databases(self.root / 'data', self.contract)
|
||||
if action == 'verify':
|
||||
|
||||
@@ -88,6 +88,28 @@ class AutomaticDeploymentTests(unittest.TestCase):
|
||||
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()
|
||||
@@ -236,9 +258,11 @@ class AutomaticDeploymentTests(unittest.TestCase):
|
||||
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, 'guard', return_value={'worker': 'webapi.recomputation'}), \
|
||||
patch.object(conservative, 'verify_api'), \
|
||||
patch.object(conservative, 'finish') as finish, patch.object(dev, 'verify_services'), \
|
||||
patch.object(dev, 'verify_existing_containers') as verify:
|
||||
dev.install_auto(str(port), Path('/synthetic-source'), base)
|
||||
@@ -247,6 +271,7 @@ class AutomaticDeploymentTests(unittest.TestCase):
|
||||
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)
|
||||
|
||||
@@ -10,20 +10,18 @@ import unittest
|
||||
|
||||
|
||||
class GeneralWorkflowTests(unittest.TestCase):
|
||||
def test_dispatch_uses_only_port_and_exact_dev_checkout(self):
|
||||
"""Fail if deployment accepts unpinned source or bypasses the dev-only dispatch guard."""
|
||||
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'])
|
||||
for boundary in ('test "$DISPATCH_REF" = refs/heads/dev', 'ref: ${{ github.sha }}',
|
||||
'test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"',
|
||||
'dev.py validate-auto "$PORT"',
|
||||
'git submodule update --init --recursive ISSSTELEON',
|
||||
'dev.py install-auto "$PORT"'):
|
||||
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('refs/heads/dev'), text.index('actions/checkout'))
|
||||
self.assertLess(text.index('git rev-parse HEAD'), text.index('validate-auto'))
|
||||
self.assertLess(text.index('validate-auto'), text.index('git submodule update'))
|
||||
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):
|
||||
|
||||
@@ -350,7 +350,8 @@ class InstallerTests(unittest.TestCase):
|
||||
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, 'reserve') as reserve, patch.object(dev, 'verify_config', return_value=None), \
|
||||
patch.object(dev, 'verify_services'), \
|
||||
patch.object(dev, 'verify_existing_containers'), \
|
||||
patch.object(dev.conservative, 'controlled_config', return_value={}), \
|
||||
patch.object(dev.conservative, 'verify_api'), patch.object(dev.conservative, 'guard'), \
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,862 @@
|
||||
"""The notebook composition: jobs volume guard, active-run detection, installer checks and updates.
|
||||
|
||||
Fixtures: `jobs` builds a jobs volume as a plain directory (finished, pending and partial job folders);
|
||||
`mlflow` writes a minimal MLflow store with notebook and other runs; `NotebookDeployment` extends the
|
||||
simulated deployment of `test_conservative` with the `notebooks` service, the `trabajos_notebooks`
|
||||
volume (a local directory) and the real host, data and notebook guards. No daemon is contacted.
|
||||
"""
|
||||
|
||||
from contextlib import closing
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import sqlite3
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import conservative
|
||||
import data_guard
|
||||
import dev
|
||||
import host
|
||||
import notebook_guard
|
||||
from test_conservative import SimulatedDeployment, fixture
|
||||
|
||||
POSIX = os.name == 'posix'
|
||||
VOLUME_KEY = dev.NOTEBOOK_VOLUME
|
||||
|
||||
|
||||
def jobs(root, *, finished=('run-a',), pending=(), partial=()):
|
||||
"""Create job folders as the WebApi and the runner leave them: finished ones have `result.json`."""
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
for name in finished:
|
||||
(root / name / 'trabajo').mkdir(parents=True)
|
||||
(root / name / 'job.json').write_text('{"run_id": "%s"}' % name)
|
||||
(root / name / 'result.json').write_text('{"ok": true}')
|
||||
(root / name / 'page.html').write_text('<p>synthetic</p>')
|
||||
(root / name / 'trabajo' / 'salida.bin').write_bytes(b'\x00synthetic')
|
||||
for name in pending:
|
||||
(root / name).mkdir()
|
||||
(root / name / 'job.json').write_text('{}')
|
||||
for name in partial:
|
||||
(root / name).mkdir()
|
||||
return root
|
||||
|
||||
|
||||
def mlflow(root, runs):
|
||||
"""Write `mlflow.db` with MLflow's run and tag columns; `runs` is (id, status, start_ms, kind)."""
|
||||
with closing(sqlite3.connect(root / 'mlflow.db')) as connection:
|
||||
connection.executescript(
|
||||
'CREATE TABLE runs (run_uuid TEXT PRIMARY KEY, status TEXT, lifecycle_stage TEXT, start_time INTEGER);'
|
||||
'CREATE TABLE tags (key TEXT, value TEXT, run_uuid TEXT, PRIMARY KEY (key, run_uuid));')
|
||||
for run_id, status, start, kind in runs:
|
||||
connection.execute('INSERT INTO runs VALUES (?, ?, ?, ?)', (run_id, status, 'active', start))
|
||||
connection.execute('INSERT INTO tags VALUES (?, ?, ?)', ('experiment', kind, run_id))
|
||||
connection.commit()
|
||||
|
||||
|
||||
class NotebookGuardTests(unittest.TestCase):
|
||||
"""The jobs volume guard on local directories."""
|
||||
|
||||
def setUp(self):
|
||||
"""Reserve a private directory for a synthetic volume and its backups."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
|
||||
def test_activity_classifies_unfinished_and_unknown_entries(self):
|
||||
"""Pending, partial, incomplete and stray entries are active; finished jobs are not.
|
||||
|
||||
Fails if a job without `result.json` or a folder being assembled can be backed up and interrupted."""
|
||||
root = jobs(self.base / 'volume', finished=('run-a',), pending=('run-b',), partial=('.run-c-x',))
|
||||
(root / 'run-d').mkdir()
|
||||
(root / 'stray.txt').write_text('x')
|
||||
entries = notebook_guard.scan(root)
|
||||
self.assertEqual(notebook_guard.activity(entries), {
|
||||
'run-b': 'pending', '.run-c-x': 'assembling', 'run-d': 'incomplete', 'stray.txt': 'unexpected'})
|
||||
summary = notebook_guard.inspect(jobs(self.base / 'done', finished=('run-a', 'run-e')))
|
||||
self.assertEqual((summary['active'], summary['jobs']), ([], 2))
|
||||
|
||||
def test_backup_round_trip_preserves_content_and_metadata(self):
|
||||
"""A backup and its restore reproduce every entry, mode and time of the volume.
|
||||
|
||||
Fails if the copy drops a file, changes its bytes or loses its metadata, or restores into a
|
||||
non-empty directory."""
|
||||
root = jobs(self.base / 'volume', finished=('run-a', 'run-b'))
|
||||
before = notebook_guard.scan(root)
|
||||
destination = self.base / 'backup'
|
||||
destination.mkdir()
|
||||
result = notebook_guard.backup(root, destination, {'name': 'synthetic'})
|
||||
self.assertEqual(result['digest'], notebook_guard.state_digest(before))
|
||||
self.assertEqual(notebook_guard.scan(root), before)
|
||||
restored = self.base / 'restored'
|
||||
self.assertEqual(notebook_guard.restore(destination, restored)['digest'], result['digest'])
|
||||
self.assertEqual(notebook_guard.scan(restored), before)
|
||||
with self.assertRaisesRegex(RuntimeError, 'not empty'):
|
||||
notebook_guard.restore(destination, restored)
|
||||
|
||||
def test_backup_rejects_active_jobs_and_concurrent_writes(self):
|
||||
"""No backup is written while a job is pending or when the volume changes during the copy.
|
||||
|
||||
Fails if the guard accepts an inconsistent snapshot."""
|
||||
root = jobs(self.base / 'volume', pending=('run-b',))
|
||||
destination = self.base / 'backup'
|
||||
destination.mkdir()
|
||||
with self.assertRaisesRegex(RuntimeError, 'notebook jobs are active'):
|
||||
notebook_guard.backup(root, destination, {})
|
||||
self.assertEqual(list(destination.iterdir()), [])
|
||||
(root / 'run-b' / 'result.json').write_text('{}')
|
||||
original = notebook_guard.copy_entries
|
||||
|
||||
def copy_and_write(source, target, entries):
|
||||
original(source, target, entries)
|
||||
(Path(source) / 'run-b' / 'late.txt').write_text('late')
|
||||
|
||||
with patch.object(notebook_guard, 'copy_entries', side_effect=copy_and_write), \
|
||||
self.assertRaisesRegex(RuntimeError, 'changed while creating the backup'):
|
||||
notebook_guard.backup(root, destination, {})
|
||||
self.assertFalse((destination / 'manifest.json').exists())
|
||||
|
||||
def test_corrupted_backup_is_rejected(self):
|
||||
"""Verification and restore read every file against the manifest.
|
||||
|
||||
Fails if a changed or missing backup file can be restored."""
|
||||
root = jobs(self.base / 'volume')
|
||||
destination = self.base / 'backup'
|
||||
destination.mkdir()
|
||||
notebook_guard.backup(root, destination, {})
|
||||
(destination / 'content' / 'run-a' / 'page.html').write_text('tampered')
|
||||
with self.assertRaisesRegex(RuntimeError, 'content differs'):
|
||||
notebook_guard.verify_backup(destination)
|
||||
with self.assertRaisesRegex(RuntimeError, 'content differs'):
|
||||
notebook_guard.restore(destination, self.base / 'restored')
|
||||
self.assertFalse((self.base / 'restored').exists())
|
||||
|
||||
@unittest.skipUnless(POSIX, 'symbolic links and FIFOs need a POSIX filesystem')
|
||||
def test_links_are_kept_and_special_files_rejected(self):
|
||||
"""A link a notebook planted is copied as a link, never followed; a FIFO stops the backup.
|
||||
|
||||
Fails if the guard reads through a link to files outside the volume or blocks on a FIFO."""
|
||||
root = jobs(self.base / 'volume')
|
||||
outside = self.base / 'secret'
|
||||
outside.write_text('host data')
|
||||
os.symlink(outside, root / 'run-a' / 'trabajo' / 'enlace')
|
||||
destination = self.base / 'backup'
|
||||
destination.mkdir()
|
||||
notebook_guard.backup(root, destination, {})
|
||||
copied = destination / 'content' / 'run-a' / 'trabajo' / 'enlace'
|
||||
self.assertTrue(copied.is_symlink())
|
||||
self.assertEqual(os.readlink(copied), str(outside))
|
||||
os.mkfifo(root / 'run-a' / 'trabajo' / 'tuberia')
|
||||
with self.assertRaisesRegex(RuntimeError, 'entry type is unsupported'):
|
||||
notebook_guard.scan(root)
|
||||
|
||||
@unittest.skipUnless(POSIX and hasattr(os, 'geteuid') and os.geteuid() == 0, 'restoring owners needs root')
|
||||
def test_restore_keeps_the_runner_owner(self):
|
||||
"""Folders handed to the runner (uid 10001) keep that owner through backup and restore.
|
||||
|
||||
Fails if a restored job becomes root-owned, which would stop the runner from writing its result."""
|
||||
root = jobs(self.base / 'volume')
|
||||
for path in [root / 'run-a', *(root / 'run-a').rglob('*')]:
|
||||
os.lchown(path, 10001, 10001)
|
||||
destination = self.base / 'backup'
|
||||
destination.mkdir()
|
||||
notebook_guard.backup(root, destination, {})
|
||||
restored = self.base / 'restored'
|
||||
notebook_guard.restore(destination, restored)
|
||||
self.assertEqual(os.lstat(restored / 'run-a' / 'job.json').st_uid, 10001)
|
||||
|
||||
|
||||
class NotebookRunTests(unittest.TestCase):
|
||||
"""Active notebook runs read from a synthetic MLflow store."""
|
||||
|
||||
def setUp(self):
|
||||
"""Reserve a private data directory."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.data = Path(self.temp.name)
|
||||
|
||||
def test_only_recent_running_notebook_runs_count(self):
|
||||
"""Running notebook runs within the timeout count; finished, stale and other runs do not.
|
||||
|
||||
Fails if a queued run is missed (the update would kill it) or a run MLflow already shows as
|
||||
interrupted blocks updates forever."""
|
||||
now = int(time.time() * 1000)
|
||||
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now), {'active': 0, 'training': 0})
|
||||
mlflow(self.data, [('queued', 'RUNNING', now - 1000, 'notebook'),
|
||||
('finished', 'FINISHED', now - 1000, 'notebook'),
|
||||
('stale', 'RUNNING', now - (3600 + 1801) * 1000, 'notebook'),
|
||||
('training', 'RUNNING', now - 1000, 'training')])
|
||||
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now), {'active': 1, 'training': 0})
|
||||
|
||||
def test_running_trainings_and_learning_count_within_the_request_window(self):
|
||||
"""With the API's request timeout, other running runs started within it plus the margin count too.
|
||||
|
||||
Fails if a `/train` call or the extraction ranker's background learning, which have no notebook tag, can
|
||||
be cut off by the update, or a run left running by a crash long ago blocks updates forever."""
|
||||
now = int(time.time() * 1000)
|
||||
mlflow(self.data, [('learning', 'RUNNING', now - 5000, 'extraccion'),
|
||||
('orphan', 'RUNNING', now - (600 + 1801) * 1000, 'training'),
|
||||
('done', 'FINISHED', now - 5000, 'training'),
|
||||
('notebook', 'RUNNING', now - 5000, 'notebook')])
|
||||
self.assertEqual(data_guard.notebook_runs(self.data, 3600, now, request_timeout_s=600),
|
||||
{'active': 1, 'training': 1})
|
||||
|
||||
def test_unexpected_mlflow_schema_is_unverifiable(self):
|
||||
"""A store without MLflow's run columns cannot prove no run is active.
|
||||
|
||||
Fails if the check silently reports zero runs on a schema it does not understand."""
|
||||
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
|
||||
connection.execute('CREATE TABLE runs (id INTEGER PRIMARY KEY)')
|
||||
with self.assertRaisesRegex(RuntimeError, 'unverifiable'):
|
||||
data_guard.notebook_runs(self.data, 3600, 0)
|
||||
|
||||
def test_worker_module_prefers_the_current_queue(self):
|
||||
"""The runtime action finds the worker module on disk, newest first.
|
||||
|
||||
Fails if an image with `webapi.recomputation` is configured with the removed module."""
|
||||
package = self.data / 'pkg' / 'webapi'
|
||||
package.mkdir(parents=True)
|
||||
(package / '__init__.py').write_text('')
|
||||
spec = type('Spec', (), {'submodule_search_locations': [str(package)]})()
|
||||
with patch.object(data_guard.importlib.util, 'find_spec', return_value=spec):
|
||||
with self.assertRaisesRegex(RuntimeError, 'worker module is unavailable'):
|
||||
data_guard.worker_module()
|
||||
(package / 'indicadores_vivos.py').write_text('')
|
||||
self.assertEqual(data_guard.worker_module(), 'webapi.indicadores_vivos')
|
||||
(package / 'recomputation.py').write_text('')
|
||||
self.assertEqual(data_guard.worker_module(), 'webapi.recomputation')
|
||||
|
||||
def test_recalculation_uses_the_current_queue_methods(self):
|
||||
"""`RecomputationQueue.take/run/pending` drive the one-shot recalculation.
|
||||
|
||||
Fails if the guard still imports `ColaDeRecalculo` from an image that no longer has it."""
|
||||
calls = []
|
||||
|
||||
class Queue:
|
||||
def take(self, domain):
|
||||
calls.append(('take', domain))
|
||||
|
||||
def run(self, domain):
|
||||
calls.append(('run', domain))
|
||||
return {'estado': 'ok'}
|
||||
|
||||
def pending(self):
|
||||
return []
|
||||
|
||||
module = type('Module', (), {'RecomputationQueue': Queue})
|
||||
with patch.object(data_guard, 'worker_module', return_value='webapi.recomputation'), \
|
||||
patch.object(data_guard.importlib, 'import_module', return_value=module), \
|
||||
patch.dict(os.environ):
|
||||
self.assertEqual(data_guard.recalculate({}), {'completed': ['cacu', 'cama', 'tea']})
|
||||
self.assertEqual(calls, [(step, domain) for domain in ('cacu', 'cama', 'tea') for step in ('take', 'run')])
|
||||
|
||||
def test_worker_entrypoint_follows_the_image(self):
|
||||
"""The controlled worker runs the module the image provides; an unknown one is refused.
|
||||
|
||||
Fails if the worker is started with a module the candidate image does not contain."""
|
||||
config = {'services': {'webapi': {'environment': {}}, 'indicadores': {'environment': {}}}}
|
||||
result = conservative.controlled_config(copy.deepcopy(config), worker='webapi.recomputation')
|
||||
self.assertEqual(result['services']['indicadores']['entrypoint'][-1], 'webapi.recomputation')
|
||||
with self.assertRaisesRegex(RuntimeError, 'unsupported worker module'):
|
||||
conservative.controlled_config(copy.deepcopy(config), worker='webapi.other')
|
||||
|
||||
|
||||
def compose_config(project, data, tag, port):
|
||||
"""The effective configuration `docker compose config` prints for `dist/docker-compose.yml`."""
|
||||
env = {f'{x}_DATABASE_URL': f'sqlite:////data/{x.lower()}.db' for x in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')}
|
||||
api = {'image': 'isssteleon/webapi:' + tag, 'environment': dict(env),
|
||||
'volumes': [{'type': 'bind', 'source': str(data), 'target': '/data', 'bind': {}}]}
|
||||
jobs_mount = {'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos', 'volume': {}}
|
||||
webapi = copy.deepcopy(api)
|
||||
webapi['volumes'].append(dict(jobs_mount))
|
||||
webapi['environment'].update(NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')
|
||||
return {'name': project, 'services': {
|
||||
'webapi': webapi, 'indicadores': dict(copy.deepcopy(api), command=['indicadores']),
|
||||
'notebooks': {'image': 'isssteleon/webapi:' + tag, 'command': ['notebooks'], 'user': '10001:10001',
|
||||
'network_mode': 'none', 'read_only': True, 'tmpfs': ['/tmp'], 'cap_drop': ['ALL'],
|
||||
'security_opt': ['no-new-privileges:true'], 'pids_limit': 256,
|
||||
'environment': {'NOTEBOOK_JOBS_DIR': '/trabajos', 'NOTEBOOK_RENDERER': 'jupyter',
|
||||
'HOME': '/tmp', 'JUPYTER_RUNTIME_DIR': '/tmp/jupyter'},
|
||||
'volumes': [dict(jobs_mount)]},
|
||||
'webapp': {'image': 'isssteleon/webapp:' + tag, 'ports': [{'published': str(port), 'target': 80}]}},
|
||||
'volumes': {VOLUME_KEY: {'name': project + '_' + VOLUME_KEY}}}
|
||||
|
||||
|
||||
class InstallerCompositionTests(unittest.TestCase):
|
||||
"""`dev.verify_config` on the notebook composition and its profile-gated service."""
|
||||
|
||||
project, data, tag, port = 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080
|
||||
|
||||
def verify(self, config):
|
||||
return dev.verify_config(config, self.project, self.data, self.tag, self.port)
|
||||
|
||||
def test_notebook_composition_is_accepted_with_its_volume(self):
|
||||
"""The real four-service composition passes and reports its project-scoped volume.
|
||||
|
||||
Fails if the installer keeps requiring exactly three services or forgets the volume name."""
|
||||
config = compose_config(self.project, self.data, self.tag, self.port)
|
||||
for network in ({'name': self.project + '_default'}, {'name': self.project + '_default', 'ipam': {}}):
|
||||
config['networks'] = {'default': network}
|
||||
self.assertEqual(self.verify(config), 'isssteleon-x_trabajos_notebooks')
|
||||
|
||||
def test_profile_service_is_allowed_only_while_declared_and_isolated(self):
|
||||
"""`entrenar` may appear with its profile and the API's single data mount, never otherwise.
|
||||
|
||||
Fails if an enabled profile can add a service with other mounts, ports or no profile at all."""
|
||||
config = compose_config(self.project, self.data, self.tag, self.port)
|
||||
trainer = dict(copy.deepcopy(config['services']['indicadores']), command=['entrenar'], profiles=['entrenar'])
|
||||
config['services']['entrenar'] = trainer
|
||||
self.assertEqual(self.verify(config), 'isssteleon-x_trabajos_notebooks')
|
||||
for change in ('no-profile', 'jobs-mount', 'ports', 'other-service'):
|
||||
altered = copy.deepcopy(config)
|
||||
service = altered['services']['entrenar']
|
||||
if change == 'no-profile':
|
||||
service.pop('profiles')
|
||||
if change == 'jobs-mount':
|
||||
service['volumes'].append({'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos'})
|
||||
if change == 'ports':
|
||||
service['ports'] = [{'published': '9000', 'target': 5000}]
|
||||
if change == 'other-service':
|
||||
altered['services']['otro'] = dict(service, profiles=['otro'])
|
||||
with self.subTest(change=change), self.assertRaises(RuntimeError):
|
||||
self.verify(altered)
|
||||
|
||||
def test_notebook_isolation_and_mounts_are_enforced(self):
|
||||
"""Every mount, namespace and identity setting of the runner and the jobs volume is checked.
|
||||
|
||||
Fails if a variation that gives notebooks the database folder, the network, root or a volume
|
||||
that Compose would not create for this project passes the installer."""
|
||||
config = compose_config(self.project, self.data, self.tag, self.port)
|
||||
|
||||
def runner(altered):
|
||||
return altered['services']['notebooks']
|
||||
|
||||
changes = {
|
||||
'runner-data': lambda c: runner(c)['volumes'].append(
|
||||
{'type': 'bind', 'source': str(self.data), 'target': '/data'}),
|
||||
'runner-network': lambda c: runner(c).update(network_mode='bridge'),
|
||||
'runner-root': lambda c: runner(c).update(user='0:0'),
|
||||
'runner-writable': lambda c: runner(c).update(read_only=False),
|
||||
'runner-caps': lambda c: runner(c).update(cap_drop=[]),
|
||||
'runner-privileges': lambda c: runner(c).update(security_opt=[]),
|
||||
'runner-cap-add': lambda c: runner(c).update(cap_add=['SYS_ADMIN']),
|
||||
'runner-hook': lambda c: runner(c).update(post_start=[{'command': 'true', 'privileged': True}]),
|
||||
'runner-docker-socket': lambda c: runner(c).update(use_api_socket=True),
|
||||
'external-network': lambda c: c.update(networks={'default': {'name': 'shared', 'external': True}}),
|
||||
'runner-entrypoint': lambda c: runner(c).update(entrypoint=['sh']),
|
||||
'runner-database': lambda c: runner(c)['environment'].update(CACU_DATABASE_URL='sqlite:////data/cacu.db'),
|
||||
'runner-image': lambda c: runner(c).update(image='python:3.12'),
|
||||
'jobs-readonly': lambda c: c['services']['webapi']['volumes'][1].update(read_only=True),
|
||||
'jobs-subpath': lambda c: c['services']['webapi']['volumes'][1].update(volume={'subpath': 'x'}),
|
||||
'api-without-jobs': lambda c: c['services']['webapi']['volumes'].pop(),
|
||||
'worker-with-jobs': lambda c: c['services']['indicadores']['volumes'].append(
|
||||
{'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos'}),
|
||||
'api-runner-uid': lambda c: c['services']['webapi']['environment'].update(NOTEBOOK_RUNNER_UID='0'),
|
||||
'external-volume': lambda c: c['volumes'][VOLUME_KEY].update(external=True),
|
||||
'volume-options': lambda c: c['volumes'][VOLUME_KEY].update(driver_opts={'type': 'none', 'o': 'bind'}),
|
||||
'volume-name': lambda c: c['volumes'][VOLUME_KEY].update(name='shared'),
|
||||
'extra-volume': lambda c: c['volumes'].update(otro={'name': 'otro'}),
|
||||
'missing-runner': lambda c: c['services'].pop('notebooks'),
|
||||
}
|
||||
for name, change in changes.items():
|
||||
altered = copy.deepcopy(config)
|
||||
change(altered)
|
||||
with self.subTest(change=name), self.assertRaises(RuntimeError):
|
||||
self.verify(altered)
|
||||
|
||||
def test_three_service_composition_is_still_accepted(self):
|
||||
"""A composition without notebooks still installs and reports no volume.
|
||||
|
||||
Fails if records and updates of existing three-service installations stop being recognized."""
|
||||
config = compose_config(self.project, self.data, self.tag, self.port)
|
||||
config['services'].pop('notebooks')
|
||||
config.pop('volumes')
|
||||
config['services']['webapi']['volumes'].pop()
|
||||
self.assertIsNone(self.verify(config))
|
||||
|
||||
|
||||
def volume_inspect(project, **changes):
|
||||
"""`docker volume inspect` output for a Compose-created jobs volume of `project`."""
|
||||
item = {'Name': project + '_' + VOLUME_KEY, 'Driver': 'local', 'Scope': 'local', 'Options': None,
|
||||
'CreatedAt': '2026-11-17T00:00:00Z', 'Mountpoint': '/var/lib/docker/volumes/x/_data',
|
||||
'Labels': {'com.docker.compose.project': project, 'com.docker.compose.volume': VOLUME_KEY}}
|
||||
item.update(changes)
|
||||
return item
|
||||
|
||||
|
||||
class InstallerVolumeTests(unittest.TestCase):
|
||||
"""Volume identity, reservation and running-container checks with a fake Docker CLI."""
|
||||
|
||||
project = 'isssteleon-dev-18081'
|
||||
|
||||
def fake(self, volumes, containers=()):
|
||||
def run(args, **kwargs):
|
||||
if args[1:3] == ['volume', 'ls'] and '--filter' in args and args[-1].startswith('name='):
|
||||
return '\n'.join(item['Name'] for item in volumes) + '\n'
|
||||
if args[1:3] == ['volume', 'ls']:
|
||||
return ''
|
||||
if args[1:3] == ['volume', 'inspect']:
|
||||
return json.dumps([item for item in volumes if item['Name'] == args[-1]])
|
||||
if args[1:3] == ['image', 'inspect']:
|
||||
return 'api-id' if args[-1] == 'api-tag' else 'app-id'
|
||||
if args[1] == 'ps':
|
||||
return '\n'.join(item['Id'] for item in containers)
|
||||
if args[1] == 'inspect':
|
||||
return json.dumps(list(containers))
|
||||
return ''
|
||||
return run
|
||||
|
||||
def test_volume_identity_requires_compose_ownership(self):
|
||||
"""Only a local, option-free volume labelled for this project and key is this installation's.
|
||||
|
||||
Fails if a hand-made, foreign or bind-backed volume with the expected name is adopted."""
|
||||
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project)])):
|
||||
self.assertEqual(dev.notebook_volume_identity(self.project)['name'], self.project + '_' + VOLUME_KEY)
|
||||
for change in ({'Labels': None}, {'Labels': {'com.docker.compose.project': 'other',
|
||||
'com.docker.compose.volume': VOLUME_KEY}},
|
||||
{'Options': {'type': 'none', 'o': 'bind', 'device': '/srv'}}, {'Driver': 'nfs'},
|
||||
{'Mountpoint': ''}):
|
||||
with self.subTest(change=change), \
|
||||
patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, **change)])), \
|
||||
self.assertRaisesRegex(RuntimeError, 'not verifiable'):
|
||||
dev.notebook_volume_identity(self.project)
|
||||
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect('isssteleon-dev-180811')])):
|
||||
self.assertIsNone(dev.notebook_volume_identity(self.project, missing_ok=True))
|
||||
with self.assertRaisesRegex(RuntimeError, 'missing'):
|
||||
dev.notebook_volume_identity(self.project)
|
||||
|
||||
def test_reservation_rejects_an_existing_volume_name(self):
|
||||
"""A fresh installation never starts when a volume with its jobs name already exists.
|
||||
|
||||
Fails if Compose would silently adopt an unlabelled or foreign volume for a new installation."""
|
||||
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, Labels=None)])), \
|
||||
patch.object(dev, 'host_action') as action, self.assertRaisesRegex(RuntimeError, 'already exists'):
|
||||
dev.reserve('helper', self.project, 18081)
|
||||
action.assert_not_called()
|
||||
|
||||
def containers(self, data):
|
||||
"""The four running containers of a notebook installation, as `docker inspect` reports them."""
|
||||
volume = self.project + '_' + VOLUME_KEY
|
||||
jobs = {'Type': 'volume', 'Name': volume, 'Source': '/var/lib/docker/volumes/x/_data',
|
||||
'Destination': '/trabajos', 'RW': True}
|
||||
bind = {'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}
|
||||
|
||||
def item(service, mounts, **host):
|
||||
return {'Id': service, 'Name': '/' + service, 'Image': 'app-id' if service == 'webapp' else 'api-id',
|
||||
'State': {'Status': 'running'}, 'Mounts': mounts,
|
||||
'Config': {'Labels': {'com.docker.compose.project': self.project,
|
||||
'com.docker.compose.service': service},
|
||||
'User': '10001:10001' if service == 'notebooks' else ''},
|
||||
'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': '18081'}]} if service == 'webapp' else {},
|
||||
**host}}
|
||||
return [item('webapi', [bind, jobs]), item('indicadores', [bind]), item('webapp', []),
|
||||
item('notebooks', [jobs], NetworkMode='none', ReadonlyRootfs=True, Privileged=False,
|
||||
CapDrop=['ALL'], CapAdd=None, SecurityOpt=['no-new-privileges:true'])]
|
||||
|
||||
def test_running_notebook_installation_is_verified(self):
|
||||
"""Four owned containers with the expected mounts and runner isolation pass; deviations fail.
|
||||
|
||||
Fails if a foreign container can reach the jobs volume, a one-shot `entrenar` writer is ignored,
|
||||
or the runner gains the network, a writable root or the data folder."""
|
||||
base = PurePosixPath('/srv/instances')
|
||||
data = str(base / self.project / 'data')
|
||||
record = {'project': self.project, 'port': 18081, 'images': ['api-tag', 'app-tag'],
|
||||
'notebook_volume': self.project + '_' + VOLUME_KEY}
|
||||
volumes = [volume_inspect(self.project)]
|
||||
items = self.containers(data)
|
||||
isolated = {'Networks': {'none': {'NetworkID': 'daemon-none'}}}
|
||||
items[3]['NetworkSettings'] = isolated
|
||||
items.append({'Id': 'other-isolated', 'Name': '/other-isolated', 'NetworkSettings': isolated})
|
||||
with patch.object(dev, 'run', side_effect=self.fake(volumes, items)):
|
||||
self.assertEqual(dev.verify_existing_containers(record, base, 'helper'),
|
||||
['indicadores', 'webapi', 'webapp', 'notebooks'])
|
||||
|
||||
def foreign_by_name(items):
|
||||
items.append({'Id': 'x', 'Name': '/x', 'Config': {'Labels': {}}, 'HostConfig': {},
|
||||
'Mounts': [{'Type': 'volume', 'Name': record['notebook_volume'],
|
||||
'Source': '/var/lib/docker/volumes/x/_data'}]})
|
||||
|
||||
def foreign_by_path(items):
|
||||
items.append({'Id': 'y', 'Name': '/y', 'Config': {'Labels': {}}, 'HostConfig': {},
|
||||
'Mounts': [{'Type': 'bind', 'Source': '/var/lib/docker/volumes'}]})
|
||||
|
||||
def trainer(items):
|
||||
items.append(dict(copy.deepcopy(items[1]), Id='t', Name='/t',
|
||||
Config={'Labels': {'com.docker.compose.project': self.project,
|
||||
'com.docker.compose.service': 'entrenar',
|
||||
'com.docker.compose.oneoff': 'True'}}))
|
||||
|
||||
def unexpected_port(items):
|
||||
items[2]['HostConfig']['PortBindings']['80/tcp'].append({'HostPort': '18087'})
|
||||
|
||||
changes = {
|
||||
'foreign-volume': (foreign_by_name, 'foreign container can access notebook jobs'),
|
||||
'foreign-path': (foreign_by_path, 'foreign container can access notebook jobs'),
|
||||
'additional-port': (unexpected_port, 'webapp port does not match'),
|
||||
'trainer': (trainer, 'one-shot entrenar'),
|
||||
'runner-network': (lambda items: items[3]['HostConfig'].update(NetworkMode='bridge'), 'isolation'),
|
||||
'runner-writable': (lambda items: items[3]['HostConfig'].update(ReadonlyRootfs=False), 'isolation'),
|
||||
'runner-root': (lambda items: items[3]['Config'].update(User='0:0'), 'isolation'),
|
||||
'runner-data': (lambda items: items[3]['Mounts'].append(items[1]['Mounts'][0]), 'notebooks mount'),
|
||||
'api-without-jobs': (lambda items: items[0]['Mounts'].pop(), 'webapi data mount'),
|
||||
'runner-missing': (lambda items: items.pop(3), 'missing Compose project containers'),
|
||||
}
|
||||
for name, (change, message) in changes.items():
|
||||
items = self.containers(data)
|
||||
change(items)
|
||||
with self.subTest(change=name), patch.object(dev, 'run', side_effect=self.fake(volumes, items)), \
|
||||
self.assertRaisesRegex(RuntimeError, message):
|
||||
dev.verify_existing_containers(record, base, 'helper')
|
||||
with patch.object(dev, 'run', side_effect=self.fake([volume_inspect(self.project, Labels=None)],
|
||||
self.containers(data))), \
|
||||
self.assertRaisesRegex(RuntimeError, 'not verifiable'):
|
||||
dev.verify_existing_containers(record, base, 'helper')
|
||||
|
||||
def test_service_check_includes_the_runner(self):
|
||||
"""With notebooks, a missing runner container fails the availability check.
|
||||
|
||||
Fails if an installation is recorded as available while notebooks can never run."""
|
||||
def run(args):
|
||||
if 'ps' in args:
|
||||
return '' if args[-1] == 'notebooks' else 'container\n'
|
||||
return json.dumps({'Status': 'running', 'Health': {'Status': 'healthy'}})
|
||||
with patch.object(dev, 'run', side_effect=run):
|
||||
dev.verify_services(['compose'], 8080)
|
||||
with patch.object(dev, 'run', side_effect=run), patch.object(dev.time, 'sleep'), \
|
||||
patch.object(dev.time, 'monotonic', side_effect=[0, 0, 301]), \
|
||||
self.assertRaisesRegex(RuntimeError, 'notebooks'):
|
||||
dev.verify_services(['compose'], 8080, notebooks=True)
|
||||
|
||||
|
||||
class NotebookDeployment(SimulatedDeployment):
|
||||
"""The simulated deployment with the notebook runner, its volume and the jobs guard on local paths.
|
||||
|
||||
`notebooks_old`/`notebooks_new` choose the installed and candidate compositions."""
|
||||
|
||||
def __init__(self, root, contract, record, *, notebooks_old=True, notebooks_new=True):
|
||||
self.notebooks_old, self.notebooks_new = notebooks_old, notebooks_new
|
||||
self.old_tag = record['images'][0].removeprefix('isssteleon/webapi:')
|
||||
super().__init__(root, contract, record)
|
||||
self.volume = root.parent / 'docker-volume'
|
||||
self.volume_exists = notebooks_old
|
||||
self.identity = {'name': record['project'] + '_' + VOLUME_KEY, 'created': '2026-11-17T00:00:00Z',
|
||||
'mountpoint': '/var/lib/docker/volumes/x/_data'}
|
||||
if notebooks_old and not self.volume.exists():
|
||||
jobs(self.volume, finished=('run-a',))
|
||||
self.running['runner'] = True
|
||||
self.env.update(NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')
|
||||
self.after_frontend_stop = None
|
||||
self.guard_calls = []
|
||||
|
||||
def ids(self, notebooks):
|
||||
return ['worker', 'api', 'app'] + (['runner'] if notebooks else [])
|
||||
|
||||
def config(self, env):
|
||||
config = super().config(env)
|
||||
if not (self.notebooks_old if env['ISSSTELEON_VERSION'] == self.old_tag else self.notebooks_new):
|
||||
return config
|
||||
return dict(config, **{key: value for key, value in compose_config(
|
||||
self.record['project'], self.root / 'data', env['ISSSTELEON_VERSION'], self.record['port']).items()
|
||||
if key == 'volumes'}, services=dict(config['services'], **{
|
||||
'webapi': dict(config['services']['webapi'], volumes=config['services']['webapi']['volumes'] + [
|
||||
{'type': 'volume', 'source': VOLUME_KEY, 'target': '/trabajos', 'volume': {}}],
|
||||
environment=dict(config['services']['webapi']['environment'],
|
||||
NOTEBOOK_JOBS_DIR='/trabajos', NOTEBOOK_RUNNER_UID='10001')),
|
||||
'notebooks': compose_config(self.record['project'], self.root / 'data', env['ISSSTELEON_VERSION'],
|
||||
self.record['port'])['services']['notebooks']}))
|
||||
|
||||
def run(self, args, **kwargs):
|
||||
args = list(map(str, args))
|
||||
if args[:2] == ['docker', 'inspect'] and '--format' not in args:
|
||||
self.calls.append(args)
|
||||
return json.dumps([self.container(ident) for ident in args[2:]])
|
||||
if 'up' in args and args[-1] == 'notebooks' and not self.finished:
|
||||
raise AssertionError('the runner cannot start before checked recalculation')
|
||||
if 'up' in args and args[-1] == 'webapi' and self.notebooks_new and not self.volume_exists:
|
||||
self.volume.mkdir()
|
||||
self.volume_exists = True
|
||||
self.identity['created'] = '2026-11-18T00:00:00Z'
|
||||
if 'up' in args and args[-1] == 'webapp' and self.fail == 'late-job':
|
||||
raise AssertionError('the frontend started although jobs changed')
|
||||
output = super().run(args, **kwargs)
|
||||
if args[:2] == ['docker', 'stop'] and args[-1] == 'app' and self.after_frontend_stop:
|
||||
self.after_frontend_stop()
|
||||
return output
|
||||
|
||||
def container(self, ident):
|
||||
"""`docker inspect` of an original container: the worker runs the module of the old image."""
|
||||
entrypoints = {
|
||||
'worker': ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos'],
|
||||
'api': ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn', '--bind', '0.0.0.0:5000', '--workers', '2',
|
||||
'--timeout', '600', '--access-logfile', '-', 'webapi:create_app()'],
|
||||
'app': ['/docker-entrypoint.sh'], 'runner': ['/app/WebApi/docker-entrypoint.sh']}
|
||||
names = {'worker': 'indicadores', 'api': 'webapi', 'app': 'webapp', 'runner': 'notebooks'}
|
||||
item = {'Id': ident, 'Image': 'old-image', 'Mounts': [], 'State': {'Running': self.running[ident]},
|
||||
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}},
|
||||
'Config': {'Labels': {'com.docker.compose.service': names[ident]},
|
||||
'Env': [k + '=' + v for k, v in self.env.items()] + ['INDICADORES_AL_INICIAR=0'],
|
||||
'Entrypoint': entrypoints[ident], 'Cmd': []}}
|
||||
if ident == 'runner':
|
||||
item['Config'].update(Cmd=['notebooks'], User='10001:10001')
|
||||
item['HostConfig'].update(NetworkMode='none', ReadonlyRootfs=True)
|
||||
return item
|
||||
|
||||
def notebook_volume_identity(self, project, *, missing_ok=False, verify=True):
|
||||
if not self.volume_exists:
|
||||
if missing_ok:
|
||||
return None
|
||||
raise RuntimeError('notebook jobs volume is missing')
|
||||
return dict(self.identity)
|
||||
|
||||
def notebook_guard(self, api, image, action, payload, volume, backup=None):
|
||||
self.guard_calls.append(action)
|
||||
if action == 'backup' and self.fail == 'notebook-backup':
|
||||
raise conservative.UpdateRefusal('notebook jobs backup failed (exit=1)')
|
||||
if action == 'inspect' and self.fail == 'late-job' and self.finished:
|
||||
(self.volume / 'run-late').mkdir(exist_ok=True)
|
||||
if action == 'inspect':
|
||||
return notebook_guard.inspect(self.volume)
|
||||
if action == 'backup':
|
||||
return notebook_guard.backup(self.volume, Path(backup), payload['volume'])
|
||||
raise AssertionError(action)
|
||||
|
||||
def host_action(self, helper, action, project, value):
|
||||
if action == 'prepare-notebook-backup':
|
||||
host.notebook_backup_directory(self.root.parent, project, value)
|
||||
return ''
|
||||
if action == 'verify-notebook-backup':
|
||||
return json.dumps(host.verify_notebook_backup(self.root.parent, project, value))
|
||||
if action == 'verify-restore' and self.fail == 'notebook-restore':
|
||||
(self.root.parent / '.backups' / project / value / 'notebooks' / 'content' / 'run-a' /
|
||||
'page.html').write_text('tampered')
|
||||
return super().host_action(helper, action, project, value)
|
||||
|
||||
def verify_existing_containers(self, record, base, helper):
|
||||
super().verify_existing_containers(record, base, helper)
|
||||
return self.ids(bool(record.get('notebook_volume')))
|
||||
|
||||
|
||||
class NotebookUpdateTests(unittest.TestCase):
|
||||
"""Conservative updates of installations with and without the notebook runner."""
|
||||
|
||||
def setUp(self):
|
||||
"""Prepare a synthetic installation and its record, without choosing a composition yet."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
|
||||
def deployment(self, *, notebooks_old=True, notebooks_new=True):
|
||||
if notebooks_old:
|
||||
self.record['notebook_volume'] = self.record['project'] + '_' + VOLUME_KEY
|
||||
host.write_record(self.root, self.record)
|
||||
self.runtime = NotebookDeployment(self.root, self.contract, self.record,
|
||||
notebooks_old=notebooks_old, notebooks_new=notebooks_new)
|
||||
return self.runtime
|
||||
|
||||
def execute(self, verify_restore=False):
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'notebook_guard', side_effect=self.runtime.notebook_guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed') as freeze:
|
||||
try:
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base,
|
||||
verify_restore=verify_restore)
|
||||
finally:
|
||||
self.frozen = freeze.call_args
|
||||
|
||||
def stops(self):
|
||||
return [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'stop']]
|
||||
|
||||
def ups(self):
|
||||
return [args[-1] for args in self.runtime.calls if 'up' in args]
|
||||
|
||||
def test_update_backs_up_and_keeps_finished_jobs(self):
|
||||
"""A notebook installation updates with a verified jobs backup and an untouched volume.
|
||||
|
||||
Fails if the daemon receives a helper-local path, the jobs volume is changed or skipped by the backup,
|
||||
or the runner starts after the frontend."""
|
||||
runtime = self.deployment()
|
||||
before = notebook_guard.scan(runtime.volume)
|
||||
self.execute(verify_restore=True)
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual((record['status'], record['result']), ('installed', 'updated'))
|
||||
self.assertEqual(record['notebook_volume'], self.record['notebook_volume'])
|
||||
self.assertEqual(notebook_guard.scan(runtime.volume), before)
|
||||
backup = Path(record['notebook_backup']['path'])
|
||||
self.assertEqual(backup, self.base / '.backups' / self.record['project'] / record['operation_id'] / 'notebooks')
|
||||
self.assertEqual(notebook_guard.verify_backup(backup)['digest'], notebook_guard.state_digest(before))
|
||||
restored = self.base / '.restores' / self.record['project'] / (record['operation_id'] + '.notebooks')
|
||||
self.assertEqual(notebook_guard.scan(restored), before)
|
||||
self.assertEqual(self.stops()[0], 'app')
|
||||
self.assertEqual(self.ups(), ['webapi', 'indicadores', 'notebooks', 'webapp'])
|
||||
|
||||
def test_three_service_installation_gains_an_empty_volume(self):
|
||||
"""An installation from before notebooks updates; Compose creates the volume and it starts empty.
|
||||
|
||||
Fails if the old installation is refused, its update skips the runner, or a new volume with
|
||||
content is accepted."""
|
||||
runtime = self.deployment(notebooks_old=False)
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual((record['status'], record['notebook_volume']),
|
||||
('installed', self.record['project'] + '_' + VOLUME_KEY))
|
||||
self.assertNotIn('notebook_backup', record)
|
||||
self.assertEqual(self.ups(), ['webapi', 'indicadores', 'notebooks', 'webapp'])
|
||||
self.assertEqual(notebook_guard.inspect(runtime.volume)['entries'], 1)
|
||||
|
||||
def test_existing_volume_blocks_the_first_notebook_update(self):
|
||||
"""A volume with the jobs name that predates the update is never adopted.
|
||||
|
||||
Fails if a hand-made or leftover volume becomes this installation's jobs folder."""
|
||||
runtime = self.deployment(notebooks_old=False)
|
||||
runtime.volume_exists = True
|
||||
with self.assertRaisesRegex(RuntimeError, 'already exists'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_dropping_the_volume_and_mismatched_records_are_refused(self):
|
||||
"""A candidate without notebooks, or a record that disagrees with its composition, stops nothing.
|
||||
|
||||
Fails if an update orphans the jobs volume or trusts a record whose layout is ambiguous."""
|
||||
self.deployment(notebooks_new=False)
|
||||
with self.assertRaisesRegex(RuntimeError, 'drops the notebook jobs volume'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
self.record.pop('notebook_volume')
|
||||
host.write_record(self.root, self.record)
|
||||
self.runtime = NotebookDeployment(self.root, self.contract, self.record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'disagree on notebook jobs'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
|
||||
def test_active_runs_and_unfinished_jobs_refuse_before_stopping(self):
|
||||
"""Queued runs and pending or half-assembled jobs refuse the update while everything runs.
|
||||
|
||||
Fails if an update interrupts notebook work or backs up a volume a runner is writing."""
|
||||
for case in ('runs', 'pending', 'assembling'):
|
||||
with self.subTest(case=case), tempfile.TemporaryDirectory() as tmp:
|
||||
self.base = Path(tmp)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
runtime = self.deployment()
|
||||
if case == 'runs':
|
||||
runtime.active_runs = 2
|
||||
elif case == 'pending':
|
||||
jobs(runtime.volume, finished=(), pending=('run-b',))
|
||||
else:
|
||||
(runtime.volume / '.run-c-1234').mkdir()
|
||||
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*(queued or running|' + case + ')'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
self.assertFalse((self.base / '.backups').exists())
|
||||
|
||||
def test_run_submitted_while_the_frontend_stops_recovers_originals(self):
|
||||
"""A run that appears in the stop window aborts the update and restarts the original services.
|
||||
|
||||
Fails if the API is stopped under a run that was submitted before the frontend went down."""
|
||||
runtime = self.deployment()
|
||||
|
||||
def submit():
|
||||
runtime.active_runs = 1
|
||||
|
||||
runtime.after_frontend_stop = submit
|
||||
with self.assertRaisesRegex(RuntimeError, 'during quiescing.*frontend stopped.*queued or running'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), ['app'])
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual((record['status'], record['recovery']),
|
||||
('update_failed', 'original services verified; reconciliation required'))
|
||||
self.assertTrue(all(runtime.running.values()))
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
|
||||
def test_notebook_backup_failure_restarts_all_four_originals(self):
|
||||
"""A failed jobs backup never activates the candidate and restarts the runner with the rest.
|
||||
|
||||
Fails if recovery skips the runner, starts it before the API or loses the data backup."""
|
||||
runtime = self.deployment()
|
||||
runtime.fail = 'notebook-backup'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during backup; .*operation=create notebook backup'):
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
|
||||
self.assertFalse((self.root / '.updates').exists())
|
||||
starts = [args[-1] for args in runtime.calls if args[:2] == ['docker', 'start']]
|
||||
self.assertEqual(starts, ['api', 'worker', 'runner', 'app'])
|
||||
data_guard.verify_backup(Path(record['backup']))
|
||||
|
||||
def test_notebook_restore_failure_keeps_old_code(self):
|
||||
"""A jobs backup that does not restore identically stops the update before activation.
|
||||
|
||||
Fails if the isolated restore check ignores the notebook backup."""
|
||||
runtime = self.deployment()
|
||||
runtime.fail = 'notebook-restore'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during restore-verification'):
|
||||
self.execute(verify_restore=True)
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
self.assertTrue(all(runtime.running.values()))
|
||||
|
||||
def test_volume_replaced_during_backup_is_refused(self):
|
||||
"""A jobs volume recreated between preparation and backup is not backed up.
|
||||
|
||||
Fails if the backup could come from a different volume than the one the installation used."""
|
||||
runtime = self.deployment()
|
||||
original = runtime.host_action
|
||||
|
||||
def replace_volume(helper, action, project, value):
|
||||
if action == 'prepare-notebook-backup':
|
||||
runtime.identity['created'] = '2026-11-19T00:00:00Z'
|
||||
return original(helper, action, project, value)
|
||||
|
||||
runtime.host_action = replace_volume
|
||||
with self.assertRaisesRegex(RuntimeError, 'during backup'):
|
||||
self.execute()
|
||||
self.assertNotIn('backup', runtime.guard_calls)
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
|
||||
def test_jobs_changed_after_activation_keep_the_frontend_down(self):
|
||||
"""A job folder appearing before the frontend starts freezes the update instead of finishing it.
|
||||
|
||||
Fails if the update reports success although the jobs volume differs from its backup."""
|
||||
runtime = self.deployment()
|
||||
runtime.fail = 'late-job'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during notebooks'):
|
||||
self.execute()
|
||||
self.assertNotIn('webapp', self.ups())
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual((record['status'], record['notebook_volume']),
|
||||
('update_failed', self.record['notebook_volume']))
|
||||
self.assertEqual(self.frozen.args[-1], self.record['notebook_volume'])
|
||||
|
||||
|
||||
class HostNotebookBackupTests(unittest.TestCase):
|
||||
"""Helper actions that place and check the jobs backup beside the data backup."""
|
||||
|
||||
def test_notebook_destination_needs_the_operation_data_backup(self):
|
||||
"""The jobs destination is created only inside a completed data backup of the same operation.
|
||||
|
||||
Fails if a jobs backup can be written for an operation that has no verified data backup."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
root, _, record = fixture(base)
|
||||
operation = 'a' * 32
|
||||
host.write_record(root, dict(record, status='updating', operation_id=operation))
|
||||
with self.assertRaisesRegex(RuntimeError, 'data backup is missing'):
|
||||
host.notebook_backup_directory(base, record['project'], operation)
|
||||
parent = base / '.backups' / record['project'] / operation
|
||||
parent.mkdir(parents=True)
|
||||
(parent / 'manifest.json').write_text('{}')
|
||||
target = host.notebook_backup_directory(base, record['project'], operation)
|
||||
self.assertEqual(list(target.iterdir()), [])
|
||||
with self.assertRaises(FileExistsError):
|
||||
host.notebook_backup_directory(base, record['project'], operation)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Exercise sanitized origin diagnostics using temporary Git repositories."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import origin_diagnostic as diagnostic
|
||||
|
||||
|
||||
class OriginDiagnosticTests(unittest.TestCase):
|
||||
def test_url_classification_never_returns_input(self):
|
||||
"""Fail if credentials or deceptive URLs appear in the diagnostic output."""
|
||||
for url in ('http://secret:password@10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git',
|
||||
'http://10.0.10.41.evil:3000/ISSSTELEON/WorkingNarrative.git',
|
||||
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git.evil'):
|
||||
with self.subTest(url=url):
|
||||
result = diagnostic.describe(url)
|
||||
self.assertFalse(result['exact_http'])
|
||||
self.assertNotIn(url, json.dumps(result))
|
||||
self.assertNotIn('password', json.dumps(result))
|
||||
self.assertTrue(diagnostic.describe(diagnostic.OFFICIAL)['exact_http'])
|
||||
self.assertTrue(diagnostic.describe(diagnostic.SSH)['exact_ssh'])
|
||||
|
||||
def test_real_git_rewrite_is_detected_without_disclosing_credentials(self):
|
||||
"""Fail if Git URL rewriting is missed or a configured credential is logged."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
subprocess.run(['git', 'init', '-q', tmp], check=True)
|
||||
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin', diagnostic.SSH], check=True)
|
||||
env = os.environ.copy()
|
||||
env.update({'GIT_CONFIG_COUNT': '1',
|
||||
'GIT_CONFIG_KEY_0': 'url.http://secret:password@10.0.10.41:3000/ISSSTELEON/.insteadOf',
|
||||
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/',
|
||||
'DISPATCH_SERVER': diagnostic.SERVER, 'DISPATCH_REPOSITORY': diagnostic.REPOSITORY})
|
||||
result = subprocess.run([sys.executable, '-B', str(Path(diagnostic.__file__).resolve())],
|
||||
cwd=tmp, env=env, text=True, capture_output=True, check=True)
|
||||
self.assertNotIn('secret', result.stdout + result.stderr)
|
||||
self.assertNotIn('password', result.stdout + result.stderr)
|
||||
data = json.loads(result.stdout.split(': ', 1)[1])
|
||||
self.assertTrue(data['literal_origin'][0]['exact_ssh'])
|
||||
self.assertTrue(data['effective_origin'][0]['userinfo_present'])
|
||||
self.assertTrue(data['origin_rewritten'])
|
||||
self.assertTrue(data['event_repository_is_official'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,510 @@
|
||||
"""Storage policy exceptions and writer checks: column order, seeded source mappings, a new MLflow store and
|
||||
processes or requests that stopping the installation would cut short.
|
||||
|
||||
Fixtures: `fixture` (from `test_conservative`) builds four synthetic domain databases; `mappings` adds
|
||||
`cat_sistema_fuente` and `cat_mapeo` to TEA with one catalog row and one operator row; `mlflow_store` writes the
|
||||
store MLflow creates on first use, optionally with content. Writer checks use the simulated deployment of
|
||||
`test_conservative`. No daemon is contacted.
|
||||
"""
|
||||
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import conservative
|
||||
import data_guard as guard
|
||||
import dev
|
||||
import host
|
||||
from test_conservative import HEADS, SimulatedDeployment, fixture
|
||||
|
||||
MAPPINGS = """
|
||||
CREATE TABLE cat_sistema_fuente (sistema_fuente_id VARCHAR(64) NOT NULL PRIMARY KEY, etiqueta VARCHAR NOT NULL,
|
||||
fuente_tabla VARCHAR(64), vigente_desde DATE NOT NULL, vigente_hasta DATE);
|
||||
CREATE TABLE cat_mapeo (mapeo_id INTEGER NOT NULL PRIMARY KEY, sistema_fuente_id VARCHAR(64) NOT NULL,
|
||||
clase VARCHAR(16) NOT NULL, forma VARCHAR(255) NOT NULL, forma_normalizada VARCHAR(255) NOT NULL,
|
||||
estudio_id VARCHAR(64), resultado_id VARCHAR(128), valor_id VARCHAR(64), vigente_desde DATE NOT NULL,
|
||||
vigente_hasta DATE, registrado_por VARCHAR(64) NOT NULL, registrado_en DATETIME NOT NULL, motivo VARCHAR);
|
||||
INSERT INTO cat_sistema_fuente VALUES ('catalogo', 'Catálogo del proyecto', NULL, '1900-01-01', NULL);
|
||||
INSERT INTO cat_sistema_fuente VALUES ('laboratorio-x', 'Laboratorio X', NULL, '2025-01-01', NULL);
|
||||
INSERT INTO cat_mapeo VALUES (1, 'catalogo', 'valor', 'Positivo', 'POSITIVO', NULL, 'estudio.resultado', 'pos',
|
||||
'1900-01-01', NULL, 'catalogo', '2026-01-01 00:00:00.000000', NULL);
|
||||
INSERT INTO cat_mapeo VALUES (2, 'laboratorio-x', 'valor', 'Pos +', 'POS +', NULL, 'estudio.resultado', 'pos',
|
||||
'2025-01-01', NULL, 'operador', '2026-02-01 00:00:00.000000', 'alta manual');
|
||||
"""
|
||||
SEED = ("INSERT INTO cat_mapeo VALUES (3, 'catalogo', 'valor', 'Negativo', 'NEGATIVO', NULL, 'estudio.resultado',"
|
||||
" 'neg', '1900-01-01', NULL, 'catalogo', '2026-03-01 00:00:00.000000', NULL)")
|
||||
|
||||
|
||||
def mappings(root):
|
||||
"""Add the source mapping tables to TEA and return a contract that includes them."""
|
||||
with closing(sqlite3.connect(root / 'data' / 'tea.db')) as connection:
|
||||
connection.executescript(MAPPINGS)
|
||||
contract = {}
|
||||
for domain in guard.DOMAINS:
|
||||
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
|
||||
contract[domain] = {'head': HEADS[domain], 'known': [HEADS[domain]], 'schema': guard.schema(connection)}
|
||||
contract['governance']['known'].append('d6b4f0e23a45')
|
||||
return contract
|
||||
|
||||
|
||||
def run_sql(root, *statements):
|
||||
with closing(sqlite3.connect(root / 'data' / 'tea.db')) as connection:
|
||||
for statement in statements:
|
||||
connection.execute(statement)
|
||||
connection.commit()
|
||||
|
||||
|
||||
def mlflow_store(path, *extra):
|
||||
"""The store MLflow 3 creates on first use, plus `extra` statements."""
|
||||
with closing(sqlite3.connect(path)) as connection:
|
||||
connection.executescript("""
|
||||
CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL PRIMARY KEY);
|
||||
CREATE TABLE workspaces (name VARCHAR(63) NOT NULL PRIMARY KEY, description TEXT,
|
||||
default_artifact_root TEXT, trace_archival_location TEXT, trace_archival_retention VARCHAR(32));
|
||||
CREATE TABLE experiments (experiment_id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(256) NOT NULL,
|
||||
artifact_location VARCHAR(256), lifecycle_stage VARCHAR(32), creation_time BIGINT,
|
||||
last_update_time BIGINT, workspace VARCHAR(63));
|
||||
CREATE TABLE runs (run_uuid VARCHAR(32) NOT NULL PRIMARY KEY, status VARCHAR(9));
|
||||
CREATE TABLE registered_models (name VARCHAR(256) NOT NULL PRIMARY KEY);
|
||||
CREATE TABLE model_versions (name VARCHAR(256) NOT NULL, version INTEGER NOT NULL,
|
||||
PRIMARY KEY (name, version));
|
||||
INSERT INTO alembic_version VALUES ('dc11669786a5');
|
||||
INSERT INTO workspaces VALUES ('default', 'Default workspace for legacy resources', NULL, NULL, NULL);
|
||||
INSERT INTO experiments VALUES (0, 'Default', '/app/WebApi/mlruns/0', 'active', 1, 1, 'default');
|
||||
""")
|
||||
for statement in extra:
|
||||
connection.execute(statement)
|
||||
connection.commit()
|
||||
|
||||
|
||||
class ColumnOrderTests(unittest.TestCase):
|
||||
"""`same_structure` on in-memory SQLite schemas."""
|
||||
|
||||
@staticmethod
|
||||
def structure(sql):
|
||||
with closing(sqlite3.connect(':memory:')) as connection:
|
||||
connection.executescript(sql)
|
||||
return guard.schema(connection)
|
||||
|
||||
BASE = ('CREATE TABLE parent (id INTEGER NOT NULL PRIMARY KEY);'
|
||||
'CREATE TABLE ordenes (ord_id VARCHAR NOT NULL PRIMARY KEY, ord_pac INTEGER REFERENCES parent (id),'
|
||||
' {columns}, CHECK (length(ord_id) > 0));'
|
||||
'CREATE INDEX ix_ordenes_pac ON ordenes (ord_pac);')
|
||||
|
||||
def test_only_the_physical_order_of_columns_is_ignored(self):
|
||||
"""A table whose migration lists its columns in another order than the models still matches.
|
||||
|
||||
Fails if the TEA `ordenes_estudio` migration order (date before study type) keeps a fresh installation
|
||||
from passing the contract."""
|
||||
models = self.structure(self.BASE.format(columns='ord_tipo VARCHAR, ord_fecha DATE'))
|
||||
migrated = self.structure(self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR'))
|
||||
self.assertNotEqual(models, migrated)
|
||||
self.assertTrue(guard.same_structure(migrated, models))
|
||||
|
||||
def test_every_other_structural_difference_still_fails(self):
|
||||
"""Type, nullability, default, primary key, extra or missing column, index, foreign key and check
|
||||
differences are still refused.
|
||||
|
||||
Fails if ignoring the order hides an incompatible structure."""
|
||||
models = self.structure(self.BASE.format(columns='ord_tipo VARCHAR, ord_fecha DATE'))
|
||||
variants = {
|
||||
'type': self.BASE.format(columns='ord_fecha DATETIME, ord_tipo VARCHAR'),
|
||||
'nullability': self.BASE.format(columns='ord_fecha DATE NOT NULL, ord_tipo VARCHAR'),
|
||||
'default': self.BASE.format(columns="ord_fecha DATE DEFAULT '2000-01-01', ord_tipo VARCHAR"),
|
||||
'extra': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR, ord_extra INTEGER'),
|
||||
'missing': self.BASE.format(columns='ord_fecha DATE'),
|
||||
'renamed': self.BASE.format(columns='ord_fecha DATE, ord_tipo_estudio VARCHAR'),
|
||||
'index': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
|
||||
'CREATE INDEX ix_ordenes_pac ON ordenes (ord_pac);', 'CREATE INDEX ix_ordenes_pac ON ordenes (ord_fecha);'),
|
||||
'unique': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
|
||||
'CREATE INDEX', 'CREATE UNIQUE INDEX'),
|
||||
'foreign-key': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
|
||||
' REFERENCES parent (id)', ''),
|
||||
'check': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace('> 0', '> 1'),
|
||||
'primary-key': self.BASE.format(columns='ord_fecha DATE, ord_tipo VARCHAR').replace(
|
||||
'ord_id VARCHAR NOT NULL PRIMARY KEY', 'ord_id VARCHAR NOT NULL'),
|
||||
}
|
||||
for name, sql in variants.items():
|
||||
with self.subTest(change=name):
|
||||
self.assertFalse(guard.same_structure(self.structure(sql), models))
|
||||
|
||||
|
||||
class SeededMappingTests(unittest.TestCase):
|
||||
"""`verify_state` on `cat_sistema_fuente` and `cat_mapeo` with a catalog row and an operator row."""
|
||||
|
||||
def setUp(self):
|
||||
"""Create the synthetic installation with source mappings and take the before-recalculation state."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root, _, _ = fixture(Path(self.temp.name))
|
||||
self.contract = mappings(self.root)
|
||||
self.data = self.root / 'data'
|
||||
self.before = guard.storage_state(self.data, self.contract)
|
||||
|
||||
def verify(self, derived=True):
|
||||
return guard.verify_state(self.data, self.contract, self.before, derived=derived)
|
||||
|
||||
def test_catalog_seed_rows_may_be_added(self):
|
||||
"""A recalculation that adds the catalog's own rows for new forms passes.
|
||||
|
||||
Fails if a release that adds forms to the catalog can no longer be installed or updated."""
|
||||
run_sql(self.root, SEED)
|
||||
self.assertEqual(self.verify()['databases']['tea']['tables']['cat_mapeo']['count'], 3)
|
||||
|
||||
def test_stored_rows_never_change(self):
|
||||
"""Editing, closing or deleting a stored catalog or operator row is refused.
|
||||
|
||||
Fails if a recalculation could overwrite or drop a mapping entered from the application."""
|
||||
changes = {
|
||||
'edit-operator': "UPDATE cat_mapeo SET valor_id = 'neg' WHERE mapeo_id = 2",
|
||||
'close-operator': "UPDATE cat_mapeo SET vigente_hasta = '2026-01-01' WHERE mapeo_id = 2",
|
||||
'close-seed': "UPDATE cat_mapeo SET vigente_hasta = '2026-01-01' WHERE mapeo_id = 1",
|
||||
'delete-operator': 'DELETE FROM cat_mapeo WHERE mapeo_id = 2',
|
||||
'edit-system': "UPDATE cat_sistema_fuente SET etiqueta = 'Otro' WHERE sistema_fuente_id = 'laboratorio-x'",
|
||||
}
|
||||
for name, statement in changes.items():
|
||||
with self.subTest(change=name), tempfile.TemporaryDirectory() as tmp:
|
||||
self.root, _, _ = fixture(Path(tmp))
|
||||
self.contract = mappings(self.root)
|
||||
self.data = self.root / 'data'
|
||||
self.before = guard.storage_state(self.data, self.contract)
|
||||
run_sql(self.root, statement)
|
||||
with self.assertRaisesRegex(RuntimeError, 'historical rows changed'):
|
||||
self.verify()
|
||||
|
||||
def test_added_rows_must_carry_the_seed_signature(self):
|
||||
"""An added row that is not the catalog's own, or repeats a stored form, is refused.
|
||||
|
||||
Fails if a recalculation could introduce operator-looking rows or a second mapping for a stored form."""
|
||||
additions = {
|
||||
'operator-row': SEED.replace("'catalogo', '2026", "'operador', '2026"),
|
||||
'other-system': SEED.replace("(3, 'catalogo'", "(3, 'laboratorio-x'"),
|
||||
'dated-row': SEED.replace("'1900-01-01'", "'2026-01-01'"),
|
||||
'closed-row': SEED.replace("'1900-01-01', NULL", "'1900-01-01', '2026-01-01'"),
|
||||
'with-reason': SEED.replace("'2026-03-01 00:00:00.000000', NULL", "'2026-03-01 00:00:00.000000', 'x'"),
|
||||
'stored-form': SEED.replace("'Negativo', 'NEGATIVO'", "'POSITIVO', 'POSITIVO'"),
|
||||
'other-source-system': ("INSERT INTO cat_sistema_fuente VALUES ('laboratorio-y', 'Laboratorio Y', NULL,"
|
||||
" '1900-01-01', NULL)"),
|
||||
}
|
||||
for name, statement in additions.items():
|
||||
with self.subTest(change=name), tempfile.TemporaryDirectory() as tmp:
|
||||
self.root, _, _ = fixture(Path(tmp))
|
||||
self.contract = mappings(self.root)
|
||||
self.data = self.root / 'data'
|
||||
self.before = guard.storage_state(self.data, self.contract)
|
||||
run_sql(self.root, statement)
|
||||
with self.assertRaisesRegex(RuntimeError, "seeded rows are not the catalog's own") as caught:
|
||||
self.verify()
|
||||
self.assertEqual(guard.inspection_diagnostic(caught.exception)['reason'], 'seeded_rows_invalid')
|
||||
|
||||
def test_additions_outside_a_recalculation_are_refused(self):
|
||||
"""Before recalculation every table, seeded ones included, must be exactly as backed up.
|
||||
|
||||
Fails if the post-start comparison lets the API add mappings before the checked recalculation."""
|
||||
run_sql(self.root, SEED)
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent rows changed in cat_mapeo'):
|
||||
self.verify(derived=False)
|
||||
|
||||
def test_backup_and_restore_keep_operator_mappings(self):
|
||||
"""The backup of seeded tables restores every stored row, operator ones included.
|
||||
|
||||
Fails if seeded tables are left out of the row-level backup comparison."""
|
||||
destination = Path(self.temp.name) / 'backup'
|
||||
guard.create_backup(self.data, destination, self.contract, {})
|
||||
restored = guard.restore_backup(destination, Path(self.temp.name) / 'restored')
|
||||
self.assertEqual(restored['databases']['tea']['tables']['cat_mapeo'],
|
||||
self.before['databases']['tea']['tables']['cat_mapeo'])
|
||||
|
||||
|
||||
class MlflowStoreTests(unittest.TestCase):
|
||||
"""`verify_state` on `mlflow.db` when absent before a recalculation and when already present."""
|
||||
|
||||
def setUp(self):
|
||||
"""Create the synthetic installation, without an MLflow store, and take its state."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root, self.contract, _ = fixture(Path(self.temp.name))
|
||||
self.data = self.root / 'data'
|
||||
(self.data / 'mlflow.db').unlink()
|
||||
self.before = guard.storage_state(self.data, self.contract)
|
||||
|
||||
def test_a_new_empty_store_may_appear(self):
|
||||
"""The empty store the live estimators create on first use passes a derived check.
|
||||
|
||||
Fails if a first installation or an installation that never used MLflow cannot recalculate."""
|
||||
mlflow_store(self.data / 'mlflow.db')
|
||||
guard.verify_state(self.data, self.contract, self.before, derived=True)
|
||||
|
||||
def test_a_new_store_with_content_is_refused(self):
|
||||
"""A new store with a run, a model, another experiment or workspace, or a changed default is refused.
|
||||
|
||||
Fails if a recalculation could register models or runs without the persistence check noticing."""
|
||||
extras = {
|
||||
'run': "INSERT INTO runs VALUES ('r1', 'FINISHED')",
|
||||
'model': "INSERT INTO registered_models VALUES ('cacu-cin2')",
|
||||
'experiment': "INSERT INTO experiments VALUES (1, 'cacu-x', NULL, 'active', 1, 1, 'default')",
|
||||
'workspace': "INSERT INTO workspaces VALUES ('otro', NULL, NULL, NULL, NULL)",
|
||||
'artifact-root': "UPDATE workspaces SET default_artifact_root = '/data/otro'",
|
||||
'deleted-default': "UPDATE experiments SET lifecycle_stage = 'deleted'",
|
||||
}
|
||||
for name, statement in extras.items():
|
||||
with self.subTest(change=name):
|
||||
path = self.data / 'mlflow.db'
|
||||
path.unlink(missing_ok=True)
|
||||
mlflow_store(path, statement)
|
||||
with self.assertRaisesRegex(RuntimeError, 'MLflow store created with content') as caught:
|
||||
guard.verify_state(self.data, self.contract, self.before, derived=True)
|
||||
self.assertEqual(guard.inspection_diagnostic(caught.exception)['reason'], 'mlflow_store_not_initial')
|
||||
|
||||
def test_existing_store_stays_protected(self):
|
||||
"""A store that existed before may not change, disappear or appear outside a recalculation.
|
||||
|
||||
Fails if the creation exception widens to replacing, editing or deleting an existing MLflow store."""
|
||||
mlflow_store(self.data / 'mlflow.db')
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
|
||||
guard.verify_state(self.data, self.contract, self.before, derived=False)
|
||||
before = guard.storage_state(self.data, self.contract)
|
||||
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
|
||||
connection.execute("INSERT INTO runs VALUES ('r1', 'FINISHED')")
|
||||
connection.commit()
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
(self.data / 'mlflow.db').unlink()
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent file changed: mlflow.db'):
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
|
||||
def test_a_new_file_that_is_not_an_mlflow_store_is_refused(self):
|
||||
"""A non-SQLite file or a store without MLflow's tables under that name is refused.
|
||||
|
||||
Fails if any file named `mlflow.db` passes as a new store."""
|
||||
(self.data / 'mlflow.db').write_bytes(b'not sqlite')
|
||||
with self.assertRaises(Exception):
|
||||
guard.verify_state(self.data, self.contract, self.before, derived=True)
|
||||
(self.data / 'mlflow.db').unlink()
|
||||
with closing(sqlite3.connect(self.data / 'mlflow.db')) as connection:
|
||||
connection.execute('CREATE TABLE experiments (experiment_id INTEGER PRIMARY KEY)')
|
||||
with self.assertRaisesRegex(RuntimeError, 'MLflow store created with content'):
|
||||
guard.verify_state(self.data, self.contract, self.before, derived=True)
|
||||
|
||||
|
||||
GUNICORN = ('--bind 0.0.0.0:5000 --workers 2 --timeout 600 --access-logfile - webapi:create_app()')
|
||||
HEALTHCHECK = "python3 -c import urllib.request; urllib.request.urlopen('http://localhost:5000/health', timeout=5)"
|
||||
# A row of /proc/net/tcp seen in the WebApi image with a client connected from another container.
|
||||
ESTABLISHED = '02001BAC:1388 03001BAC:C790 01 00000000:00000000 00:00000000 00000000 0 0 198028 1'
|
||||
|
||||
|
||||
class WriterTests(unittest.TestCase):
|
||||
"""Process and request checks on the original containers."""
|
||||
|
||||
def test_service_processes_are_recognized(self):
|
||||
"""The processes each original container starts itself pass; anything else does not.
|
||||
|
||||
Fails if a `docker exec` shell, a one-off training, OCR or a lookalike of the health check can run
|
||||
while the update stops the container."""
|
||||
expected = {
|
||||
'webapi': ['uv run --no-sync gunicorn ' + GUNICORN, '/app/WebApi/.venv/bin/python /app/WebApi/.venv/bin/gunicorn '
|
||||
+ GUNICORN, '/app/WebApi/.venv/bin/python -m gunicorn ' + GUNICORN, HEALTHCHECK],
|
||||
'indicadores': ['uv run --no-sync python -m webapi.recomputation',
|
||||
'/app/WebApi/.venv/bin/python -m webapi.recomputation',
|
||||
'/app/WebApi/.venv/bin/python -m webapi.indicadores_vivos'],
|
||||
'notebooks': ['/app/WebApi/.venv/bin/python -m models notebooks serve'],
|
||||
}
|
||||
unexpected = {
|
||||
'webapi': ['sh -c sleep 120', 'sleep 120', '/app/WebApi/.venv/bin/python -m models run cacu cin2_logistic '
|
||||
'--train', 'tesseract /tmp/page.png stdout -l spa', "python3 -c import os", ''],
|
||||
'indicadores': ['/app/WebApi/.venv/bin/python -m webapi.orchestration confirm-risks', 'sqlite3 /data/cacu.db'],
|
||||
'notebooks': ['/app/WebApi/.venv/bin/python -m ipykernel_launcher -f /tmp/k.json'],
|
||||
}
|
||||
for service, commands in expected.items():
|
||||
for command in commands:
|
||||
with self.subTest(service=service, command=command):
|
||||
self.assertTrue(conservative.expected_process(service, command, HEALTHCHECK))
|
||||
for service, commands in unexpected.items():
|
||||
for command in commands:
|
||||
with self.subTest(service=service, command=command):
|
||||
self.assertFalse(conservative.expected_process(service, command, HEALTHCHECK))
|
||||
self.assertFalse(conservative.expected_process('webapi', HEALTHCHECK, None))
|
||||
|
||||
def test_open_requests_are_counted_only_from_outside(self):
|
||||
"""Established or half-closed connections to port 5000 from another host count; loopback, listening
|
||||
sockets and other ports do not.
|
||||
|
||||
Fails if a request still being served by the API (an import or `/train`) goes unnoticed, or the
|
||||
container's own health check blocks every update."""
|
||||
rows = {
|
||||
ESTABLISHED: 1,
|
||||
ESTABLISHED.replace(' 01 ', ' 08 '): 1,
|
||||
'00000000:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000': 0,
|
||||
'0100007F:1388 0100007F:D2F0 01 00000000:00000000 00:00000000 00000000': 0,
|
||||
'02001BAC:1F90 03001BAC:C790 01 00000000:00000000 00:00000000 00000000': 0,
|
||||
'00000000000000000000000001000000:1388 00000000000000000000000001000000:9C40 01 0': 0,
|
||||
'0000000000000000FFFF00000100007F:1388 0000000000000000FFFF00000100007F:9C40 01 0': 0,
|
||||
'0000000000000000FFFF00000200A8C0:1388 0000000000000000FFFF00000300A8C0:9C40 08 0': 1,
|
||||
}
|
||||
for row, count in rows.items():
|
||||
fake = type('Api', (), {'run': staticmethod(lambda args, row=row: ' sl local_address rem_address st\n'
|
||||
' 0: ' + row + '\n')})()
|
||||
with self.subTest(row=row):
|
||||
self.assertEqual(conservative.served_requests(fake, 'api'), count)
|
||||
failing = type('Api', (), {'run': staticmethod(lambda args: (_ for _ in ()).throw(RuntimeError('no cat')))})()
|
||||
with self.assertRaisesRegex(conservative.UpdateRefusal, 'not verifiable'):
|
||||
conservative.served_requests(failing, 'api')
|
||||
|
||||
|
||||
class WriterUpdateTests(unittest.TestCase):
|
||||
"""Conservative updates that meet writers the installation did not start."""
|
||||
|
||||
def setUp(self):
|
||||
"""Prepare a managed synthetic installation with the simulated adapter."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
|
||||
def execute(self):
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
|
||||
|
||||
def stops(self):
|
||||
return [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'stop']]
|
||||
|
||||
def test_exec_process_refuses_before_stopping(self):
|
||||
"""A process started with `docker exec` in the API refuses the update while everything still runs.
|
||||
|
||||
Fails if a one-off writer is killed by the update or its writes reach the backup."""
|
||||
self.runtime.processes['api'].append('/app/WebApi/.venv/bin/python -m models run cacu cin2_logistic --train')
|
||||
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*operation=check other writers; 1 process'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_request_in_flight_after_the_frontend_stops_recovers_originals(self):
|
||||
"""A request still being served once the frontend is down aborts the update and restarts the originals.
|
||||
|
||||
Fails if the API is stopped in the middle of an import or a `/train` call."""
|
||||
self.runtime.connections.append(ESTABLISHED)
|
||||
with self.assertRaisesRegex(RuntimeError, 'during quiescing.*operation=check other writers with the '
|
||||
'frontend stopped; 1 API request'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), ['app'])
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
|
||||
self.assertTrue(all(self.runtime.running.values()))
|
||||
|
||||
def test_running_training_refuses_before_stopping(self):
|
||||
"""A training or learning run still open in MLflow refuses the update while everything runs.
|
||||
|
||||
Fails if the extraction ranker's background learning, which has no request or process of its own, can be
|
||||
interrupted once its run exists."""
|
||||
self.runtime.training_runs = 1
|
||||
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*1 training or learning run'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
|
||||
def test_unreadable_process_list_refuses(self):
|
||||
"""An unparseable process listing refuses the update instead of assuming no writer.
|
||||
|
||||
Fails if a daemon that does not report processes lets the update proceed unchecked."""
|
||||
original = self.runtime.run
|
||||
self.runtime.run = lambda args, **kw: '' if list(map(str, args))[:2] == ['docker', 'top'] else original(args, **kw)
|
||||
with self.assertRaisesRegex(RuntimeError, 'processes are not verifiable'):
|
||||
self.execute()
|
||||
self.assertEqual(self.stops(), [])
|
||||
|
||||
|
||||
class MlflowCompatibilityTests(unittest.TestCase):
|
||||
"""`mlflow_store` on synthetic stores and the update's refusals built on it."""
|
||||
|
||||
def setUp(self):
|
||||
"""Prepare a managed synthetic installation with the simulated adapter."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
|
||||
def test_store_revision_and_production_versions_are_read(self):
|
||||
"""The guard reports the store's revision and its `produccion` aliases, and refuses a store without a
|
||||
schema revision.
|
||||
|
||||
Fails if a production version or an old store goes unnoticed, or an unknown file passes as a store."""
|
||||
data = self.root / 'data'
|
||||
(data / 'mlflow.db').unlink()
|
||||
self.assertEqual(guard.mlflow_store(data), {'exists': False, 'revision': None, 'production': 0})
|
||||
mlflow_store(data / 'mlflow.db', 'CREATE TABLE registered_model_aliases (alias VARCHAR(256) NOT NULL, '
|
||||
'version INTEGER NOT NULL, name VARCHAR(256) NOT NULL, PRIMARY KEY (name, alias))')
|
||||
self.assertEqual(guard.mlflow_store(data), {'exists': True, 'revision': 'dc11669786a5', 'production': 0})
|
||||
with closing(sqlite3.connect(data / 'mlflow.db')) as connection:
|
||||
connection.execute("INSERT INTO registered_model_aliases VALUES ('produccion', 1, 'cacu-cin2_mas')")
|
||||
connection.execute("INSERT INTO registered_model_aliases VALUES ('candidata', 2, 'cacu-cin2_mas')")
|
||||
connection.commit()
|
||||
self.assertEqual(guard.mlflow_store(data)['production'], 1)
|
||||
(data / 'mlflow.db').unlink()
|
||||
with closing(sqlite3.connect(data / 'mlflow.db')) as connection:
|
||||
connection.execute('CREATE TABLE runs (id INTEGER PRIMARY KEY)')
|
||||
with self.assertRaisesRegex(RuntimeError, 'MLflow store is unverifiable'):
|
||||
guard.mlflow_store(data)
|
||||
|
||||
def execute(self):
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
|
||||
|
||||
def test_production_version_or_old_store_refuses_before_stopping(self):
|
||||
"""A store the candidate's MLflow would refuse, or one with a production version, stops the update while
|
||||
everything still runs.
|
||||
|
||||
Fails if the update reaches a recalculation that can only fail after activation."""
|
||||
for case, store in (('production', {'production': 1}), ('schema', {'revision': '1b5f0d9ad7c1'})):
|
||||
with self.subTest(case=case):
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
self.runtime.mlflow.update(store)
|
||||
message = 'version in production' if case == 'production' else 'needs a schema upgrade'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during compatibility.*check the MLflow store; .*' + message):
|
||||
self.execute()
|
||||
self.assertFalse(any(args[:2] == ['docker', 'stop'] for args in self.runtime.calls))
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_absent_store_and_current_store_without_production_update(self):
|
||||
"""An installation without a store, or with a current one and no production version, updates.
|
||||
|
||||
Fails if the MLflow checks block installations that never used models."""
|
||||
self.runtime.mlflow = {'exists': False, 'revision': None, 'production': 0}
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root)['result'], 'updated')
|
||||
|
||||
def test_profile_service_cannot_move_persistent_storage(self):
|
||||
"""`entrenar` may not point MLflow, reports or indicators outside the managed paths through `.env`.
|
||||
|
||||
Fails if a one-off training could keep its model artifacts in the container's own layer."""
|
||||
from test_notebooks import compose_config
|
||||
config = compose_config('isssteleon-x', Path('/srv/x/data'), 'tag', 8080)
|
||||
trainer = dict(config['services']['indicadores'], command=['entrenar'], profiles=['entrenar'])
|
||||
config['services']['entrenar'] = trainer
|
||||
self.assertIsNotNone(dev.verify_config(config, 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080))
|
||||
trainer['environment'] = dict(trainer['environment'], MLFLOW_ARTIFACT_ROOT='/app/WebApi/mlruns')
|
||||
with self.assertRaisesRegex(RuntimeError, 'unexpected entrenar storage configuration'):
|
||||
dev.verify_config(config, 'isssteleon-x', Path('/srv/x/data'), 'tag', 8080)
|
||||
|
||||
|
||||
class TransportLimitTests(unittest.TestCase):
|
||||
"""Size of the scripts passed as one `python -c` argument."""
|
||||
|
||||
def test_scripts_fit_one_linux_argument(self):
|
||||
"""Every guard script, and the helper's combined one, stays under Linux's 128 KiB per-argument limit.
|
||||
|
||||
Fails if a guard grows until `docker run`/`docker exec` can no longer start it on the daemon host."""
|
||||
here = Path(dev.__file__).parent
|
||||
sizes = {name: len((here / name).read_text(encoding='utf-8').encode()) for name in
|
||||
('data_guard.py', 'notebook_guard.py', 'host.py')}
|
||||
helper = sum(sizes.values()) + 4096
|
||||
self.assertLess(max(*sizes.values(), helper), 120 * 1024, sizes)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -169,5 +169,54 @@ class ReconciliationTests(unittest.TestCase):
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
|
||||
def test_notebook_installation_needs_its_runner_and_matching_composition(self):
|
||||
"""A notebook installation reconciles with four original IDs; a missing, extra or inconsistent runner fails.
|
||||
|
||||
Fails if a runner can be left out of the identity check, or a record and composition that disagree about
|
||||
the jobs volume are accepted."""
|
||||
volume = self.project + '_trabajos_notebooks'
|
||||
names = ('indicadores', 'webapi', 'webapp', 'notebooks')
|
||||
ids = [str(n) * 64 for n in range(1, 5)]
|
||||
config = {'services': {name: {'restart': 'unless-stopped'} for name in names}}
|
||||
containers = [{'Config': {'Labels': {'com.docker.compose.service': name}},
|
||||
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
|
||||
for name in names]
|
||||
composition = {'volume': volume}
|
||||
|
||||
def action(helper, name, project, payload):
|
||||
return json.dumps(host.reconcile_record(self.base, project, json.loads(payload)))
|
||||
|
||||
api = types.SimpleNamespace(BASE=self.base, ROOT=self.base,
|
||||
validate=lambda *a: (self.project, 23456), start_helper=lambda base: 'helper',
|
||||
host_action=action, git=lambda *a: '160000 commit ' + 'c' * 40 + '\tISSSTELEON',
|
||||
verify_existing_containers=lambda *a: ids, compose=lambda *a: ['compose'],
|
||||
verify_config=lambda *a: composition['volume'], verify_services=lambda *a, **kw: None,
|
||||
run=lambda args: json.dumps(config if 'config' in args else containers) if args != ['docker', 'rm', '-f', 'helper'] else '')
|
||||
|
||||
def attempt(runner):
|
||||
args = argparse.Namespace(instance='example', port=23456, indicadores=ids[0], webapi=ids[1],
|
||||
webapp=ids[2], notebooks=runner, external_copy_verified=True,
|
||||
revision=self.revision, operation=self.operation, backup=self.archive,
|
||||
restored_data=self.restored, backup_sha256=self.sha, mode='check')
|
||||
with patch.object(reconcile.conservative, 'read_deployment'), \
|
||||
patch.object(reconcile.conservative, 'current_environment'), \
|
||||
patch.object(reconcile.conservative, 'guard', return_value={}):
|
||||
return reconcile.reconcile(args, api)
|
||||
|
||||
host.write_record(self.root, dict(self.record, notebook_volume=volume))
|
||||
self.assertEqual(attempt(ids[3])['result'], 'eligible')
|
||||
with self.assertRaisesRegex(RuntimeError, 'runner ID is required'):
|
||||
attempt(None)
|
||||
composition['volume'] = None
|
||||
with self.assertRaisesRegex(RuntimeError, 'disagree on notebook jobs'):
|
||||
attempt(ids[3])
|
||||
host.write_record(self.root, self.record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'runner ID is required'):
|
||||
attempt(ids[3])
|
||||
with self.assertRaisesRegex(ValueError, 'distinct full original container IDs'):
|
||||
attempt(ids[0])
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -55,7 +55,7 @@ class TargetContractTests(unittest.TestCase):
|
||||
"""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'])
|
||||
self.assertTrue(data_guard.same_structure(data_guard.schema(db), self.contract[domain]['schema']))
|
||||
data_guard.inspect_databases(self.root, self.contract)
|
||||
|
||||
def test_actual_schema_backup_restores_to_an_isolated_directory(self):
|
||||
|
||||
+8
-11
@@ -61,11 +61,11 @@ jobs:
|
||||
run: python3 -m unittest discover -s .gitea/ci -p 'test_*.py' -v
|
||||
- name: Select checks
|
||||
id: select
|
||||
run: python3 .gitea/ci/select.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
|
||||
run: python3 .gitea/ci/select_checks.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 installer
|
||||
- name: Test DEV and terminal installers
|
||||
if: steps.select.outputs.deploy == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -75,6 +75,7 @@ jobs:
|
||||
test -f .gitea/workflows/deploy-dev.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
|
||||
@@ -130,12 +131,6 @@ 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,6 +138,10 @@ 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
|
||||
@@ -163,7 +162,6 @@ 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 }}
|
||||
@@ -171,12 +169,11 @@ 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 INDICADORES WEBAPI WEBAPP; do
|
||||
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS WEBAPI WEBAPP; do
|
||||
result=${!name:-skipped}
|
||||
required_var=${name}_REQUIRED
|
||||
required=${!required_var:-}
|
||||
|
||||
@@ -7,29 +7,37 @@ on:
|
||||
description: Public WebApp port; create a new instance or conservatively update its existing data
|
||||
required: true
|
||||
type: string
|
||||
rama:
|
||||
description: WorkingNarrative branch to deploy
|
||||
required: true
|
||||
default: dev
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PORT: ${{ inputs.puerto }}
|
||||
DISPATCH_REF: ${{ github.ref }}
|
||||
DISPATCH_SHA: ${{ github.sha }}
|
||||
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: 1
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
steps:
|
||||
- name: Require dev branch
|
||||
run: test "$DISPATCH_REF" = refs/heads/dev
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Verify dispatched revision
|
||||
run: test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"
|
||||
run: python3 -B .gitea/deploy/dev.py validate-dispatch
|
||||
- name: Diagnose checkout origin
|
||||
run: python3 -B .gitea/deploy/origin_diagnostic.py
|
||||
- name: Validate request
|
||||
run: python3 -B .gitea/deploy/dev.py validate-auto "$PORT"
|
||||
- name: Checkout pinned submodules
|
||||
run: git submodule update --init --recursive ISSSTELEON
|
||||
- name: Install or conservatively update instance
|
||||
run: python3 -B .gitea/deploy/dev.py install-auto "$PORT"
|
||||
- name: Resolve branch and install or conservatively update instance
|
||||
run: python3 -B .gitea/deploy/dev.py deploy-branch "$PORT" "$TARGET_BRANCH"
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
name: deploy-terminal-release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Published release tag
|
||||
required: true
|
||||
type: string
|
||||
puerto:
|
||||
description: Public WebApp port
|
||||
required: true
|
||||
default: '18090'
|
||||
type: string
|
||||
puerto_api:
|
||||
description: Internal loopback WebApi port
|
||||
required: true
|
||||
default: '28090'
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
RELEASE_OUTPUT: release-output/release-source.tar.gz
|
||||
REQUESTED_TAG: ${{ inputs.tag }}
|
||||
REQUESTED_PORT: ${{ inputs.puerto }}
|
||||
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
|
||||
RELEASE_TOKEN: ${{ gitea.token }}
|
||||
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/
|
||||
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:
|
||||
fetch-depth: 0
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Prepare release bundle
|
||||
run: |
|
||||
mkdir release-output
|
||||
python3 -B .gitea/deploy-terminal/resolve.py
|
||||
cp .gitea/deploy-terminal/{install.py,activate.py,verify.py,remote.py,bundle.py,source.py,README.md} release-output/
|
||||
- name: Install, activate and verify native services
|
||||
env:
|
||||
NATIVE_ACCOUNT: ${{ vars.NATIVE_ACCOUNT }}
|
||||
NATIVE_SSH_PORT: ${{ vars.NATIVE_SSH_PORT }}
|
||||
NATIVE_HOSTNAME: ${{ vars.NATIVE_HOSTNAME }}
|
||||
NATIVE_PARENT: ${{ vars.NATIVE_PARENT }}
|
||||
NATIVE_SSH_KEY: ${{ secrets.NATIVE_SSH_KEY }}
|
||||
NATIVE_KNOWN_HOSTS: ${{ secrets.NATIVE_KNOWN_HOSTS }}
|
||||
run: |
|
||||
set -eu
|
||||
: "${NATIVE_ACCOUNT:?Missing NATIVE_ACCOUNT}"
|
||||
: "${NATIVE_SSH_PORT:?Missing NATIVE_SSH_PORT}"
|
||||
: "${NATIVE_HOSTNAME:?Missing NATIVE_HOSTNAME}"
|
||||
: "${NATIVE_PARENT:?Missing NATIVE_PARENT}"
|
||||
: "${REQUESTED_API_PORT:?Missing puerto_api}"
|
||||
: "${NATIVE_SSH_KEY:?Missing NATIVE_SSH_KEY}"
|
||||
: "${NATIVE_KNOWN_HOSTS:?Missing NATIVE_KNOWN_HOSTS}"
|
||||
umask 077
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -f "$scratch/key" "$scratch/known_hosts"; rmdir "$scratch"' EXIT
|
||||
printf '%s\n' "$NATIVE_SSH_KEY" > "$scratch/key"
|
||||
printf '%s\n' "$NATIVE_KNOWN_HOSTS" > "$scratch/known_hosts"
|
||||
checksum=$(python3 -c 'import json; print(json.load(open("release-output/release-record.json"))["bundle_sha256"])')
|
||||
python3 -B release-output/remote.py \
|
||||
--bundle-dir release-output --bundle-sha256 "$checksum" \
|
||||
--host 10.0.10.41 --ssh-port "$NATIVE_SSH_PORT" \
|
||||
--account "$NATIVE_ACCOUNT" --expected-hostname "$NATIVE_HOSTNAME" \
|
||||
--parent "$NATIVE_PARENT" --api-port "$REQUESTED_API_PORT" \
|
||||
--identity "$scratch/key" --known-hosts "$scratch/known_hosts"
|
||||
@@ -0,0 +1,3 @@
|
||||
graphify-out
|
||||
.claude/
|
||||
samples/
|
||||
@@ -49,25 +49,14 @@ 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 on branches off `dev`.** A
|
||||
10. **Tasks fit in one session; work happens directly on `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 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.
|
||||
this repo and in every submodule, and work happens directly on it, in
|
||||
every repo it touches; no task or working branches.
|
||||
In this repo each commit cites its issue (`(#124)`); in the deliverable
|
||||
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.
|
||||
tree it doesn't (rule 12), and the issue cites the commit instead.
|
||||
Pushing to `dev` needs explicit permission every time.
|
||||
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
|
||||
@@ -104,14 +93,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)
|
||||
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080) + indicadores + notebooks (isolated notebook runner)
|
||||
```
|
||||
|
||||
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[export], Extraction ·
|
||||
Dependencies (uv path deps): WebApi → Persistance, models[notebooks], Extraction ·
|
||||
models → Persistance, Extraction · Persistance → Core · Extraction → (no
|
||||
internal deps). Each Python package has its own `uv` env: `cd <pkg> && uv run pytest -q`.
|
||||
|
||||
@@ -123,11 +112,21 @@ 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`, `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).
|
||||
(`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.
|
||||
- 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
|
||||
@@ -143,7 +142,10 @@ 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`, cacu `b4f2d8c01e23`, cama `c5a3e9d12f34`, governance `d6b4f0e23a45` -> `e7c5a1f34b56`
|
||||
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join);
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -153,7 +155,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
|
||||
share one branch off `dev` (rule 10). Whatever the task doesn't resolve
|
||||
all land on `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
|
||||
@@ -177,8 +179,9 @@ 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` (indicator computation), `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` (the retired kit; measures now live in `Transformation/`, see `webapi.md`), `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) |
|
||||
|
||||
+1
-1
Submodule ISSSTELEON updated: f6d00f51f3...aa840b9f31
+1
-1
Submodule dev-data updated: 57023b6cfb...3dea0ad641
+107
-30
@@ -7,45 +7,122 @@ 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). `combine_pages` builds one PDF
|
||||
from pages of several PDFs.
|
||||
`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.
|
||||
- `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` (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
|
||||
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
|
||||
pages/files, most confident value wins, confident disagreements become
|
||||
`FieldConflict`). `ExtractedRecord.discovered` also carries every caption
|
||||
no known `FieldSpec` claimed (`nlp/discovery.py::discover_captions`).
|
||||
- `readers/text.py` — `TextReader`, the fallback in `FALLBACK_READERS`:
|
||||
content that's neither a PDF nor an image, read as plain text (one page,
|
||||
one line per newline) as long as it decodes as one, instead of being
|
||||
rejected as an unsupported format.
|
||||
`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.
|
||||
- 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. Corrections from
|
||||
the UI travel as `overrides`. Results cached per worker for repeated calls.
|
||||
A `document` source's `payload` may carry `sql` (a connection, `table` or
|
||||
`query`, `column`, `key_column`) instead of `files`: one document per
|
||||
row, the named column read as its bytes (a `varbinary(max)` PDF) or, via
|
||||
`TextReader`, as plain text — the same connector and extraction either way.
|
||||
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`:
|
||||
a discovered caption is fuzzy-matched (`rapidfuzz`) against the project's
|
||||
catalog (`core/catalogos/<proyecto>.toml`); a close enough etiqueta reuses
|
||||
that `resultado_id`, otherwise one is minted
|
||||
(`indicadores_kit.registry.catalogos.add_resultado`) and synced. Written
|
||||
straight into `procedimiento`/`observacion` (no staging row for these),
|
||||
tagged with the sentinel `fuente_tabla` `catalogo_abierto` so it reads
|
||||
apart from every staging-derived row.
|
||||
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).
|
||||
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
|
||||
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.
|
||||
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.
|
||||
|
||||
### 5.4 EEG (TEA)
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
# indicadores-kit
|
||||
|
||||
Moved from `AGENTS.md` on 2026-11-03.
|
||||
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.
|
||||
|
||||
### 5.6a Indicator computation — division of labor (clarified by the owner, 2026-10-19)
|
||||
|
||||
|
||||
+103
-16
@@ -14,19 +14,106 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
|
||||
### 5.5 Model versioning and cohorts (ML/MLD/EL)
|
||||
|
||||
- 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.
|
||||
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`.
|
||||
|
||||
@@ -23,4 +23,41 @@ 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.
|
||||
|
||||
@@ -2892,3 +2892,22 @@ 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.
|
||||
|
||||
@@ -62,3 +62,31 @@ 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:**
|
||||
|
||||
@@ -293,3 +293,46 @@ 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.
|
||||
|
||||
+116
-3
@@ -11,7 +11,120 @@ 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.
|
||||
- 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).
|
||||
- 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.
|
||||
- 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: needs the owner's
|
||||
approval 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.
|
||||
- The three CaMa measures Angel added to the kit (`deteccion_histopatologica`, `dias_resultado_diagnostico`,
|
||||
`histopatologia_birads`, #161) were not ported; the dbt CaMa measures and the invasive-cancer stratifiers are what
|
||||
the page draws. Re-expressing them in dbt is a separate task.
|
||||
- `feature/cacu-pim-vigilancia` (models as a Hamilton dataflow, the CIN2+ prevalence-incidence scenario) is
|
||||
deferred: it predates the cohort move into `models/cohorts` and needs rebasing on the new `dev`.
|
||||
- The webapi image compiles dbt's manifest for SQLite at build time and, on another engine, at start-up against the
|
||||
configured databases (`webapi.dbt_manifest`); the start-up path was not exercised against a real MySQL,
|
||||
PostgreSQL or SQL Server here, and Docker was unavailable on the machine that built the branch.
|
||||
- TEA's alterations stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`; `fhir.resources` in the WebApi's dev group
|
||||
still needs the owner's word; suppression and intervals are #73's.
|
||||
- A risk batch stays `preliminary` until `python -m webapi.orchestration confirm-risks`; the risk route serves
|
||||
only final batches.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# 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
@@ -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) # 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)
|
||||
(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)
|
||||
```
|
||||
|
||||
If a package's `.venv` has stale absolute paths baked into its entry-point
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,49 @@
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
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); });
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# 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=isssteleon-manual
|
||||
|
||||
# --- Published ports ---
|
||||
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
|
||||
# machine only.
|
||||
BIND_ADDRESS=0.0.0.0
|
||||
# The application (nginx: pages and proxy to the API). Open this one.
|
||||
WEBAPP_PORT=5210
|
||||
# The API, direct.
|
||||
WEBAPI_PORT=5211
|
||||
# The simulated hospital's MySQL (user/password hospital/hospital).
|
||||
HOSPITAL_PORT=5212
|
||||
|
||||
# --- 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
|
||||
|
||||
# --- 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
|
||||
@@ -0,0 +1 @@
|
||||
documentos/
|
||||
@@ -0,0 +1,134 @@
|
||||
# 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
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
## 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
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
# 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
|
||||
|
||||
# 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
|
||||
@@ -0,0 +1,16 @@
|
||||
# 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.
|
||||
poblar:
|
||||
profiles: !reset []
|
||||
poblar-cacu:
|
||||
profiles: !reset []
|
||||
poblar-cama:
|
||||
profiles: !reset []
|
||||
@@ -0,0 +1,25 @@
|
||||
# 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
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
|
||||
|
||||
indicadores:
|
||||
<<: *api
|
||||
|
||||
webapp:
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapp:local
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPP_PORT:-28080}:80"
|
||||
@@ -0,0 +1,306 @@
|
||||
# TEA redesign: what was added, and the state machines in the code
|
||||
|
||||
Implementation of `WorkingNarrative/plans/kit-exit/tea-redesign.md` (all but the WebApp), 2026-11-12.
|
||||
|
||||
- **Where:** `/home/admon/alberto/WorkingNarrative/ISSSTELEON`, branch `feature/163-tea-redesign` in ISSSTELEON,
|
||||
WebApi, models and indicadores_kit, cut from `refactor/kit-exit` (the plan builds on its dbt semantic layer and
|
||||
measure engine, which `dev` doesn't have). WebApp untouched.
|
||||
- **State:** nothing committed (AGENTS.md rule 1). Open items are recorded in
|
||||
`WorkingNarrative/docs/ledgers/open-items.md`, which is modified in the outer repo, on `main`.
|
||||
- **Size:** ISSSTELEON 13 files changed (+528 −1385) plus 30 new; WebApi 37 changed (+475 −793) plus 18 new;
|
||||
models 2; indicadores_kit 2.
|
||||
|
||||
---
|
||||
|
||||
## 1. Additions and changes, by layer
|
||||
|
||||
### 1.1 Bronze: TEA staging (Core, Persistance)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `Core/core/tea/models.py` | Rewritten: 8 tables instead of 10, 76 columns instead of 275. `pacientes`, `ordenes_estudio`, `mchat`, `ados2` (28 items, constant `ADOS2_ITEMS`), `evaluacion_neuropediatrica`, `eeg` (EDF, channels, duration, sleep, 5 quality criteria), `eeg_metrica`, `eeg_metrica_electrodo` |
|
||||
| `Core/core/tea/enums.py` | Trimmed to `TipoEstudio` (ADOS2, NEUROPEDIATRIA, EEG) with aliases, `ModuloAdos2`, `ClasificacionAdos2` with aliases, `MetricaEeg`, `ELECTRODOS_10_20` |
|
||||
| `Core/spec/tablas_TEA.md` | Data dictionary rewritten for the 8 tables (Spanish, as before) |
|
||||
| `Core/core/catalogos/tea.toml` | Rewritten: studies `mchat`, `ados2` (module, algorithm, CSS, classification, 28 items with labels), `evaluacion_neuropediatrica` (ICD-10), `eeg` (sleep, channels, duration, 5 criteria, 5 metrics), `orden` |
|
||||
| `Core/tests/test_models.py` | TEA's table set |
|
||||
| `Persistance/persistance/tea/alembic/versions/f2b6d1e8c934_tea_staging_by_study.py` | **New revision** after the baseline: creates the 6 new tables, drops the 8 old ones, drops the unused columns of `pacientes` and `ordenes_estudio` (keeping their rows) and maps the old study codes to the new ones; downgrade restores everything with generic types. Round trip checked on SQLite; `alembic check` clean |
|
||||
| `Persistance/persistance/tea/__init__.py` | Repositories for the 8 tables |
|
||||
| `Persistance/persistance/edges/silver/procedures.py` | An observation whose procedure isn't in silver is skipped and counted (it used to raise `KeyError`) |
|
||||
| `Persistance/persistance/edges/gold/history.py` | `group_counts`: a stored answer's units per group (for M30) |
|
||||
|
||||
### 1.2 Import (WebApi)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/imports/schemas/tea/` | New: `mchat.py`, `ados2.py`, `evaluacion_neuropediatrica.py` (ICD-10 with or without the dot), `eeg.py`, `eeg_metrica.py`, `eeg_metrica_electrodo.py`. `pacientes.py` and `ordenes_estudio.py` rewritten. The 8 old schemas deleted |
|
||||
| `webapi/imports/schemas/coercion.py` | `Bounded(kind, low, high)`: numbers out of range are a validation error (M-CHAT 0–20, CSS 1–10, items 0–3, channels) |
|
||||
| `webapi/imports/schemas/registry.py` | TEA's 8 targets (`tea.Mchat`, `tea.Ados2`, `tea.EvaluacionNeuropediatrica`, `tea.Eeg`, `tea.EegMetrica`, `tea.EegMetricaElectrodo`, …) |
|
||||
| `webapi/imports/connectors/edf.py` | Shaped for `tea.Eeg`: lab id, patient, date, channels, duration and the file |
|
||||
|
||||
### 1.3 Silver (WebApi orchestration)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/orchestration/silver/tea.py` | **New**: TEA's `DESDE_STAGING`: order → `orden` of the study it asks for; M-CHAT → `toma`; ADOS-2 and note → `encuentro`; EEG → `toma`; metric → observation on its EEG's `toma`; electrode value → `parte` of the EEG |
|
||||
| `webapi/orchestration/silver/procedures.py` | Two generic additions to `DeStaging`: `juntas` (columns from another staging row by key, null-filled when missing) and `observa_en` (observations on another row's procedure); result templates can name content columns (`eeg.{metrica}`) |
|
||||
| `webapi/orchestration/tables/tea.py` | **New**: TEA's `TablasKit` and `COHORTES` |
|
||||
| `tables/__init__.py`, `orchestration/__main__.py`, `recomputation.py`, `webapi/__init__.py` | `tea` added to the domain lists; the KPI and FHIR blueprints registered for TEA |
|
||||
| `webapi/orchestration/reference/parametros.toml` | The 18 TEA keys of §7.2 removed; `tea.cohorte.ventanas` set to the page's windows (16–23, 24–29, 30–36) |
|
||||
|
||||
### 1.4 dbt (Transformation)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `dbt_project.yml` | Var `tea`: ages, `dias_por_mes`, `ventanas`, `cie_tea: [F840]`, `alteracion_z`, quality thresholds and the metric reference ranges (placeholders until validated) |
|
||||
| `macros/tea.sql` | **New**: `tea_meses_cumplidos` (per engine), `tea_grupo_edad`, `tea_criterio_bueno`, `tea_despues` (no `GREATEST` on SQL Server 2016) |
|
||||
| `models/tea/silver/tea_linea_de_tiempo.yml` | 29 sources → 5 (mchat, ados2, evaluacion_neuropediatrica, eeg, orden) |
|
||||
| `models/tea/silver/` (ephemeral, new) | `tea_mchat`, `tea_ados2`, `tea_ados2_reactivos`, `tea_neuropediatria`, `tea_eegs`, `tea_eeg_referencias`, `tea_eeg_metricas`, `tea_eeg_electrodos`, `tea_cohorte`, `tea_hitos` (each child's step dates and when they became known) |
|
||||
| `models/tea/gold/eventos/` (views, new) | `tea_pasos` (M28), `tea_diagnosticos` (M23, M24, M21, M22), `tea_casos` (M26, M27, M25), `tea_eegs_periodo` (M29), `tea_alteraciones` (M30), each with its semantic model and metrics |
|
||||
| `models/tea/gold/seguimiento/` (views, new) | `tea_seguimiento`, `tea_paciente_ados2`, `tea_paciente_eegs`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`, marked `lee_la_webapi` so the cycle creates them |
|
||||
|
||||
### 1.5 The ten measures
|
||||
|
||||
| Measure | Event model | Scoring | Construct |
|
||||
|---|---|---|---|
|
||||
| M28 `casos_por_estado` | `tea_pasos` | composition (C2) | status at the period's end |
|
||||
| M23 `pacientes_evaluados` | `tea_diagnosticos` | composition, admits CONFIRMADO and EN_PROCESO | status at the period's end |
|
||||
| M24 `confirmacion_diagnostico` | `tea_diagnosticos` | proportion with `denominator-exclusion` (SIN_TEA) | status + `grupo_edad` column stratum |
|
||||
| M21 / M22 `diagnosticados_con/sin_eeg` | `tea_diagnosticos` | proportion | status + EEG reached (or not) by the period's end + stratum |
|
||||
| M26 / M27 / M25 day counts | `tea_casos` | continuous variable | status; a value only if the interval ended by the period's end |
|
||||
| M29 `calidad_eeg` | `tea_eegs_periodo` | composition by exam | events in the period |
|
||||
| M30 `resultado_eeg` | `tea_alteraciones` | proportion + one group per alteration | several groups |
|
||||
|
||||
### 1.6 Measure engine (WebApi)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/metrics.py` | `StatusAtEnd` (`meta.poblacion`): each unit that entered by the period's end and hadn't left before its start, with its highest-order row dated by the end and known by the cut-offs; `ReachedByEnd` (`meta.al_fin`); column stratum (`tipo: columna`); `Group` (`meta.grupos`) answered one by one and stored by group; exclusion count (`meta.exclusion`); `meta` kept on the definition |
|
||||
| `webapi/compositions.py`, `webapi/durations.py` | Take `StatusAtEnd`; a duration's value must have ended before the period's end |
|
||||
| `webapi/orchestration/semantic_layer.py` | The publication catalog lists M30's groups and the exclusion population; the cycle creates the `lee_la_webapi` views |
|
||||
|
||||
### 1.7 FHIR R4 (WebApi, new package `webapi/fhir/`)
|
||||
|
||||
| File | What it serves |
|
||||
|---|---|
|
||||
| `common.py` | `application/fhir+json`, `OperationOutcome`, searchset with `self`/`next`/`previous`, `_count` (≤200) and `_offset`, the `simulado` tag, canonical URLs |
|
||||
| `measures.py` | `Measure` from each metric's meta (title, description, scoring, populations with their dbt metric, strata, period types, figures, category labels and colors); `MeasureReport` with an absolute canonical, `group.code`, codings, C2 as `cohort` with categories as a stratifier (`stratum.component` with strata), several groups, exclusion, durations with `measure-population-exclusion`. FHIR ids use `-` instead of `_` |
|
||||
| `terminology.py`, `tea_eeg.toml` | `CodeSystem`s: the domain's catalog, stages, diagnostic results, EEG quality, metrics with their effect texts, 10-20 electrodes, age groups; `ValueSet/tea-alteracion` |
|
||||
| `tea.py` | Seguimiento as `EpisodeOfCare` (+ `CarePlan`, `Patient`, M-CHAT, `Condition`, EEG `Procedure` + `DiagnosticReport` + quality observations); metric and electrode observations; ADOS-2 with components; the `$resumen-tea` collection |
|
||||
| `__init__.py` | `/<domain>/fhir/`: `metadata`, `Measure`, `Measure/<id>`, `$evaluate-measure`, `MeasureReport` search (`periodo`, or `tipo-periodo` + `period=ge/le`), `POST Measure/$recalcular`, `CodeSystem`; for TEA in DEV: `EpisodeOfCare` (filters `status`, `date`, `etapa`, `fecha-etapa`, `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; `_include`), `EpisodeOfCare/$resumen-eeg`, `Patient/<pseudonym>/$resumen-tea`, `ValueSet/tea-alteracion` |
|
||||
|
||||
- **Alterations:** hidden until `TEA_ALTERACIONES_VALIDADAS=1`. That covers M30, the alteration filter, the normal/abnormal split and the metric and electrode observations.
|
||||
- **Old routes:** `/<domain>/indicadores` stays as it is.
|
||||
|
||||
### 1.8 Tests (WebApi)
|
||||
|
||||
| File | What it covers |
|
||||
|---|---|
|
||||
| `tests/staging/tea.py` | **New** fixture: seven children, one per rule of the chain |
|
||||
| `tests/test_tea_measures.py` | **New**, 48 cases: the ten measures by month and semester, event and knowledge cut-offs, M30 read back from the history |
|
||||
| `tests/test_fhir_tea.py` | **New**, 19 cases: every response checked against FHIR models |
|
||||
| `tests/test_fhir_measures.py` | **New**: CaCu's and CaMa's measures in FHIR |
|
||||
| `conftest.py`, `test_orquestacion_*`, `test_imports_*`, `test_new_sources.py`, `test_schemas*.py`, `test_source_ids.py` | TEA added to the cycle tests and moved to the new tables |
|
||||
| `pyproject.toml`, `uv.lock` | `fhir.resources` 8.3 in the dev group (needs the owner's approval) |
|
||||
|
||||
Results:
|
||||
- WebApi: 404 passed, 10 failed (tesseract and the SQL Server driver are missing; the same 10 fail without these changes).
|
||||
- Core: 18 passed. Persistance: 48 passed.
|
||||
- `dbt build --select tea` passes on SQLite.
|
||||
|
||||
### 1.9 Removed
|
||||
|
||||
- `models/models/tea/` (empty stub).
|
||||
- `indicadores_kit/scripts/equivalencia_tea.py` (it imported kit code that no longer exists) and its README mentions.
|
||||
- The sentence in `models/cohorts/cama/screening.py` that cited the retired TEA cohort.
|
||||
- The 8 old TEA import schemas and the §7.2 parameters.
|
||||
|
||||
---
|
||||
|
||||
## 2. State machines, as the code implements them
|
||||
|
||||
Nothing stores a state: each state is derived from dated facts at a date. For the measures that date is the
|
||||
period's end, under the question's event and knowledge cut-offs; for Seguimiento and the summary it's the cut-off
|
||||
(by default, today).
|
||||
|
||||
### 2.1 A child's screening
|
||||
|
||||
**Source:** `models/tea/silver/tea_cohorte.sql`, `tea_hitos.sql`, `gold/eventos/tea_pasos.sql`; `webapi/metrics.py`
|
||||
(`StatusAtEnd`); `webapi/fhir/tea.py` (`Episode`).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16–36 months
|
||||
[*] --> SOLO_MCHAT: first M-CHAT at 16–36 months, or no birth date
|
||||
SOLO_MCHAT --> PSICOLOGIA: first ADOS-2
|
||||
PSICOLOGIA --> NEUROPEDIATRIA: first neuropediatrics note (any diagnosis)
|
||||
NEUROPEDIATRIA --> EEG: first good-quality EEG
|
||||
EEG --> COMPLETADO: end of the period of that EEG
|
||||
FUERA_DE_COHORTE --> [*]
|
||||
COMPLETADO --> [*]
|
||||
```
|
||||
|
||||
| Rule | In the code |
|
||||
|---|---|
|
||||
| Who enters | `tea_cohorte.en_cohorte = 1`: completed months at the first M-CHAT (days / 30.4375, rounded to one decimal, truncated) between 16 and 36, or unknown age (`grupo_edad = 'sin_dato'`) |
|
||||
| Steps go in order | `tea_despues(previous, own)`: a step is dated by the later of its first fact and the previous step, and is null without the previous one. An EEG before the note counts from the note's date |
|
||||
| What was known at a date | `tea_versiones`: one version of the child per load that brought one of its facts. `tea_cohorte` and `tea_hitos` have one row per child and version, built from the facts known by it, so the first M-CHAT, ADOS-2, note and good EEG are the first known then. The engine takes each child's latest version by the knowledge cut-off (`meta.version_conocida`) |
|
||||
| Entry and exit | `ingreso` = first M-CHAT; `salida` = the EEG step (null if never reached) |
|
||||
| Who a period counts | `ingreso < period end` and not (`salida` before the period's start, dated by the event cut-off and known by the knowledge cut-off) |
|
||||
| A period's category | The highest-order step (`paso_orden` 1–4) dated before the period's end and known by the cut-offs |
|
||||
| No exit | Without a good EEG in the chain (no ADOS-2, no note, only bad EEGs) the child stays in every period |
|
||||
| Seguimiento | `Episode`: stage = furthest step dated by the cut-off, `fecha_etapa` its date, `pendientes` the rest. `EpisodeOfCare.status` is `finished` once the EEG step is reached by the cut-off, `active` before. The `date=ge…` window leaves out episodes finished before it |
|
||||
|
||||
Stage codes in the code: `SOLO_MCHAT`, `PSICOLOGIA`, `NEUROPEDIATRIA`, `EEG` (the page's codes). `COMPLETADO` and
|
||||
`FUERA_DE_COHORTE` are never stored: the first is "not counted after the period of the exit", the second
|
||||
"filtered out by `en_cohorte`".
|
||||
|
||||
### 2.2 The diagnostic result
|
||||
|
||||
**Source:** `tea_neuropediatria.sql` (`es_tea`: ICD-10 without the dot, exactly in `cie_tea`), `tea_hitos.sql`
|
||||
(`fecha_tea`, `fecha_sin_tea`), `gold/eventos/tea_diagnosticos.sql`; `Episode.diagnosis`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> EN_PROCESO: first M-CHAT
|
||||
EN_PROCESO --> SIN_TEA: first note without F84.0
|
||||
EN_PROCESO --> CONFIRMADO: first note with F84.0
|
||||
SIN_TEA --> CONFIRMADO: a later note with F84.0
|
||||
```
|
||||
|
||||
| State | Order | Counted in |
|
||||
|---|---|---|
|
||||
| `EN_PROCESO` | 1 | M23 (in process), M24 denominator |
|
||||
| `SIN_TEA` | 2 | M24 `denominator-exclusion`; out of M23; still in the screening |
|
||||
| `CONFIRMADO` | 3 | M23, M24 numerator and denominator, base of M21/M22, event of M25 |
|
||||
|
||||
- **Highest order wins:** at each date the state is the one of highest order, so `CONFIRMADO` is final. A note without F84.0 after it changes nothing.
|
||||
- **Within the chain:** a note counts from the psychology step on, so a F84.0 note without the ADOS-2 leaves the child in process (child 5 in the fixture). F84 without its subcode is `SIN_TEA`.
|
||||
- **Seguimiento:** `diagnostico_tea` is `true` with a F84.0 note by the cut-off, `false` with notes but none with F84.0, and `null` without a note.
|
||||
|
||||
### 2.3 One EEG's quality
|
||||
|
||||
**Source:** `tea_eegs.sql`, `tea_paciente_eegs.sql` (`<criterion>_bueno` per criterion), thresholds in var
|
||||
`tea.calidad`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_ANALIZAR: loaded, no criterion written
|
||||
SIN_ANALIZAR --> BUENO: every criterion within its threshold
|
||||
SIN_ANALIZAR --> MALO: some criterion missing or over its threshold
|
||||
BUENO --> MALO: re-analysis or new thresholds
|
||||
MALO --> BUENO: re-analysis or new thresholds
|
||||
```
|
||||
|
||||
| State | `valido` | Feeds |
|
||||
|---|---|---|
|
||||
| `SIN_ANALIZAR` | 0 | M29 (third category); moves nothing else |
|
||||
| `BUENO` | 1 | M29; may become the study EEG and complete the chain |
|
||||
| `MALO` | 0 | M29; no result, its alterations don't count |
|
||||
|
||||
- **Recomputed, never stored:** the quality is recomputed from the criteria on every answer, so new thresholds in var `tea` move EEGs between `BUENO` and `MALO`.
|
||||
- **A missing criterion counts as bad** once any criterion has been written.
|
||||
|
||||
### 2.4 A child's study EEG
|
||||
|
||||
**Source:** `tea_hitos.primer_bueno` (for the measures), `Episode.study_eeg` (for Seguimiento and the summary, at the
|
||||
cut-off).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_EEG
|
||||
SIN_EEG --> SOLO_MALOS: a bad or unanalysed EEG
|
||||
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
|
||||
```
|
||||
|
||||
| State | Shown | Alterations |
|
||||
|---|---|---|
|
||||
| `SIN_EEG` | No EEG | None |
|
||||
| `SOLO_MALOS` | The latest EEG, `conclusionCode` MALO and «no es válido para el estudio» | None |
|
||||
| `CON_EEG_DEL_ESTUDIO` | The first good EEG (two on the same day: the first written) | That EEG's, once each; M30 counts it in its period |
|
||||
|
||||
- **Not tied to the chain:** the study EEG is the first good EEG whether or not the chain reached it. Child 5 has a study EEG and M30 counts it, but its chain never reaches the EEG step.
|
||||
- **Same event as the chain's end only when the note is there:** entering `CON_EEG_DEL_ESTUDIO` moves the screening (§2.1) to `EEG` only if the neuropediatrics note already exists; otherwise the EEG step is dated by the note when it arrives.
|
||||
|
||||
### 2.5 A metric of the EEG
|
||||
|
||||
**Source:** `tea_eeg_metricas.sql`: age group at the EEG, reference range from `tea_eeg_referencias` (var
|
||||
`tea.referencias`), mean = middle of the range, SD = a quarter of its width.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> no_evaluable: null value, or no reference for the age
|
||||
[*] --> normal: |z| < alteracion_z
|
||||
[*] --> aumentado: z ≥ alteracion_z
|
||||
[*] --> disminuido: z ≤ −alteracion_z
|
||||
```
|
||||
|
||||
- **Used in:** `tea_alteraciones` (M30 and its groups), `Episode.alterations`, and the metric observations (`interpretation` H, L or N, or `dataAbsentReason` for `no_evaluable`).
|
||||
- **Only a good EEG counts:** a bad EEG's metrics are stored but never read as alterations.
|
||||
|
||||
### 2.6 Showing the alterations
|
||||
|
||||
**Source:** `webapi/fhir/tea.py` (`alterations_validated`); the M30 metric's `meta.requiere_validacion`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PROVISIONAL
|
||||
PROVISIONAL --> VALIDADO: TEA_ALTERACIONES_VALIDADAS=1
|
||||
VALIDADO --> PROVISIONAL: variable removed
|
||||
```
|
||||
|
||||
| State | FHIR answers |
|
||||
|---|---|
|
||||
| `PROVISIONAL` | No M30 (`Measure` 404); `alteracion` filter refused (403); `$resumen-eeg` gives only `con_eeg_valido` / `sin_eeg_valido`; `resultado-eeg` only `valido` / `sin-eeg-valido`; no metric or electrode observations |
|
||||
| `VALIDADO` | Everything: M30, the filter, `normales`/`anormales`/`por_alteracion`, metrics and electrodes |
|
||||
|
||||
In the code it's an environment variable, so it can go back to `PROVISIONAL`. The plan wants that to need the domain
|
||||
expert, which is a process rule, not a code one.
|
||||
|
||||
### 2.7 A measure's answer for a period
|
||||
|
||||
**Source:** `webapi/metrics.py` (`key_of`, `answer`), `persistance/edges/gold/history.py` (`find`, `record`,
|
||||
`counts`, `group_counts`).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_RESPUESTA
|
||||
SIN_RESPUESTA --> RESPONDIDA: first question (computed and recorded)
|
||||
RESPONDIDA --> RESPONDIDA: same key again (read from the history)
|
||||
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off) or a new definition
|
||||
```
|
||||
|
||||
- **The key:** measure, version, metric, period, both cut-offs, rule values and strata, hashed with SHA-256.
|
||||
- **An old cut-off keeps its answer:** asked as of an earlier load, a child is read in the version known then, so a
|
||||
later load with earlier-dated facts doesn't change it.
|
||||
- **Why a new load means a new answer:** by default the knowledge cut-off is the start of the last load, so a new load is a new key. A change to dbt's models or to var `tea` changes the model's checksum or version, and so the answer.
|
||||
- **The old answer stays** in the history.
|
||||
|
||||
### 2.8 One staging row through the silver load
|
||||
|
||||
**Source:** `webapi/orchestration/silver/procedures.py`, `persistance/edges/silver/procedures.py`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> DESCARTADA: study code outside the catalog
|
||||
[*] --> NUEVO: logical key not in silver
|
||||
[*] --> HUERFANO: no patient and no parent (e.g. electrode without its metric)
|
||||
NUEVO --> SIN_CAMBIO: same row loaded again
|
||||
SIN_CAMBIO --> CAMBIADO: a column or observation changed
|
||||
CAMBIADO --> SIN_CAMBIO: loaded again without changes
|
||||
```
|
||||
|
||||
- **Counted in `carga`:** new, changed and unchanged procedures; discards and orphans by reason.
|
||||
- **`observa_en` rows** (EEG metrics) give no procedure of their own: their observations go on the EEG's `toma`, and are skipped and logged when that EEG isn't in silver.
|
||||
|
||||
### 2.9 Where the code differs from the plan's §13
|
||||
|
||||
- **The first good EEG.** In §13.4 the study EEG and the one that completes the chain are the same event. In the
|
||||
code the study EEG is the first good one overall, while the chain's EEG step is dated by the later of it and the
|
||||
note. A child with a good EEG but no ADOS-2 has a study EEG (M30, the summary) but never leaves the screening,
|
||||
and its note doesn't confirm it either: it stays in process.
|
||||
- **`SIN_ANALIZAR` in M29.** It shows as its own category; this was the open question in §10.
|
||||
- **The alteration switch.** It is an environment variable and can go back to `PROVISIONAL`.
|
||||
- **Without a birth date.** The child is in the cohort with `sin_dato`, as §5 says, whereas the §13.1 diagram only
|
||||
draws «16 to 36 months».
|
||||
@@ -0,0 +1,671 @@
|
||||
# TEA redesign: a trimmed schema, the new definitions and the unused indicators removed
|
||||
|
||||
Proposal, 2026-11-10, for the owner. It replaces the parts of [`tea-port.md`](tea-port.md) that port the kit's TEA
|
||||
as it is: the ten staging tables, the five measures M21 to M25 with their October definitions, and R01. Nothing here
|
||||
is implemented yet.
|
||||
|
||||
The target is what the TEA page shows today in the WebApp and the mock API: indicators M21 to M30, the period
|
||||
summary, Histórico, Seguimiento and the patient summary. Their definitions are the team's (#indicadores-tea,
|
||||
10 Nov 2026). Everything the page doesn't need is dropped, from staging to gold.
|
||||
|
||||
---
|
||||
|
||||
## 1. The definitions this design serves
|
||||
|
||||
- **The cohort** is the children whose first M-CHAT was at 16 to 36 completed months (owner, 2026-11-11).
|
||||
- **A period counts every cohort child who is in the screening during it**: entered by the period's end (first M-CHAT
|
||||
on or before it) and not finished before the period's start, whether or not anything of theirs happened in the
|
||||
period.
|
||||
- **A child leaves after completing the chain** (owner, 2026-11-11). The period of their good-quality EEG is the last
|
||||
one that counts them, with stage EEG; from the next period on they're no longer pending and don't appear.
|
||||
- **A child who never gets a good EEG stays in the screening** (owner, 2026-11-11): one with a neuropediatrics note
|
||||
without F84.0, one who stops coming back, one who ages past 36 months. They're counted in every period from their
|
||||
entry on, so M22 and the in-process counts of M23 and M28 grow with them.
|
||||
- **Each child's stage in a period is the furthest step reached by the period's end**: the steps dated on or before
|
||||
it and known at the report's cut-off. Steps go in order (M-CHAT, psychology note (ADOS-2), neuropediatrics note,
|
||||
good-quality EEG) and each needs the previous one. A child can be in process in one period and further on in a
|
||||
later one.
|
||||
- Example, by month: ADOS-2 in September, nothing in October, good EEG in December. September and October count the
|
||||
child at the psychology stage (a neuropediatrics note in November would make November's stage neuropediatrics);
|
||||
December counts them at EEG; from January on they no longer appear.
|
||||
- These rules hold for M28, M23, M24, M21 and M22. M29 and M30 count the EEG of the period instead (table below).
|
||||
- **The day counts (M26, M27, M25) take the period's children whose interval ended on or before the period's end**
|
||||
(owner, 2026-11-11). A child's days repeat in every period that counts them; the others count as without event.
|
||||
- **Only a good-quality EEG counts as an EEG**, everywhere except M29. An EEG is bad when any of its quality criteria
|
||||
is; a bad EEG has no result and its alterations don't count.
|
||||
- **A patient's alterations are those of their first good-quality EEG** (owner, 2026-11-11). Later EEGs, good or
|
||||
bad, don't change them. Each alteration counts once per patient; a patient can have several, so the alterations
|
||||
don't add up. The first good EEG is also the one that completes the chain.
|
||||
- **The age group is the age at the patient's first M-CHAT** (owner, 2026-11-10): from `pac_fecha_nacimiento` to
|
||||
that date, in completed months (days / 30.4375, rounded to one decimal, then truncated, as the kit does), placed in
|
||||
the page's windows: 16 to 23, 24 to 29 and 30 to 36 months. It is one value per patient, the same in every period
|
||||
they are counted in, and it also decides who is in the cohort. The EEG reference ranges are the exception: they take the age at the EEG date.
|
||||
|
||||
| Measure | Contract | Unit | What it counts | EEG analysis |
|
||||
|---|---|---|---|---|
|
||||
| M28 `casos_por_estado` | C2 | patient | The cohort children entered by the period's end, by their stage at that end | Yes: the EEG stage counts only a graded, good EEG |
|
||||
| M21 `diagnosticados_con_eeg` | C1 | patient | Of the confirmed (F84.0 by neuropediatrics), those with a good EEG; stratified by age group | Yes: a good EEG is the numerator |
|
||||
| M22 `diagnosticados_sin_eeg` | C1 | patient | The complement of M21 | Yes: the complement of M21 |
|
||||
| M23 `pacientes_evaluados` | C2 | patient | Confirmed, and in process (no neuropediatrics note yet); a note without F84.0 doesn't count | Indirectly: who is counted (a child leaves after their first good EEG) |
|
||||
| M24 `confirmacion_diagnostico` | C1 | patient | Confirmed out of confirmed plus in process; stratified by age group | Indirectly: who is counted |
|
||||
| M26 `dias_mchat_ados2` | C3r | patient | Days from the M-CHAT to the psychology note | Indirectly: who is counted |
|
||||
| M27 `dias_ados2_diagnostico` | C3r | patient | Days from the psychology note to the neuropediatrics note | Indirectly: who is counted |
|
||||
| M25 `dias_mchat_diagnostico` | C3r | patient | Days from the M-CHAT to the F84.0 note | Indirectly: who is counted |
|
||||
| M29 `calidad_eeg` | C2 | exam | The period's EEG, good or bad | Yes: the quality rating |
|
||||
| M30 `resultado_eeg` | C1 | patient | Of the patients whose first good EEG falls in the period, those with any alteration in it; one group per alteration | Yes: the quality and the alterations |
|
||||
|
||||
The out-of-protocol rule (M-CHAT of 2 or less, or ADOS-2 «no espectro») and the 30 days between ADOS-2 and EEG are
|
||||
gone.
|
||||
|
||||
These definitions hold over the earlier ones of #128 to #131 (owner, 2026-11-10). A confirmation is F84.0 exactly:
|
||||
F84 without the subcode doesn't count, so `cie_tea` is `[F840]`.
|
||||
|
||||
### What depends on the EEG analysis
|
||||
|
||||
The EEG analysis reads each EDF and writes its quality criteria, channels, duration, sleep, metrics and electrode
|
||||
values back to bronze. Whatever reads a good EEG, or its metrics, waits for it; those rows are tagged **[EEG
|
||||
analysis]** below.
|
||||
|
||||
- **Stored by it:** in `eeg`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min` and the five criteria; all of
|
||||
`eeg_metrica` and `eeg_metrica_electrodo` (§2), and their silver observations (§3).
|
||||
- **Derived from it:** the EEG's quality and validity (`tea_eegs`), its metrics against the references
|
||||
(`tea_eeg_metricas`) (§4), and the gold models that use them: `tea_pasos` (the EEG step), `tea_eegs_periodo` and
|
||||
`tea_alteraciones` (§5).
|
||||
- **Measures:** M29 and M30 directly; M28, M21 and M22 through the EEG stage; M23, M24, M25, M26 and M27 through who
|
||||
is counted, since a child leaves after their first good EEG (the table's last column).
|
||||
- **Seguimiento and the patient summary (§6):** `etapa`, `fecha_etapa`, `pendientes`, `fecha_eeg`, `calidad_eeg`,
|
||||
`alteraciones_eeg` and `alteraciones`, the EEG summary and its alteration filter; the summary's quality panel,
|
||||
alterations and map.
|
||||
- **FHIR (§12.3):** the quality, metric and electrode `Observation`s, and the report's `conclusionCode`.
|
||||
|
||||
What doesn't: the M-CHAT, the ADOS-2, the neuropediatrics note and the orders, and the age group.
|
||||
|
||||
---
|
||||
|
||||
## 2. Bronze: TEA staging (Core, Alembic)
|
||||
|
||||
Eight tables replace the current ten; 76 columns instead of 275. Each study table holds one kind of study, so the
|
||||
instrument and specialty columns go. Prefixes follow the schema's convention.
|
||||
|
||||
| Table | Columns |
|
||||
|---|---|
|
||||
| `pacientes` | `pac_id` PK, `pac_id_hospital`, `pac_fecha_nacimiento` |
|
||||
| `ordenes_estudio` | `ord_id` PK, `ord_pac_id`, `ord_id_hospital` (bounded, indexed: the merge key), `ord_tipo_estudio` (`ADOS2`, `NEUROPEDIATRIA`, `EEG`), `ord_fecha` |
|
||||
| `mchat` | `mch_id` PK, `mch_pac_id`, `mch_ord_id` (usually null), `mch_fecha`, `mch_puntaje` (0 to 20) |
|
||||
| `ados2` | `ado_id` PK, `ado_pac_id`, `ado_ord_id`, `ado_fecha`, `ado_modulo`, `ado_algoritmo`, `ado_css` (1 to 10), `ado_clasificacion`, and the 29 item columns `ado_sa_a2` … `ado_sa_b18`, `ado_rrb_a3` … `ado_rrb_d5` (0 to 3) |
|
||||
| `evaluacion_neuropediatrica` | `neu_id` PK, `neu_pac_id`, `neu_ord_id`, `neu_fecha`, `neu_cie_codigo` |
|
||||
| `eeg` | `eeg_id` PK, `eeg_pac_id`, `eeg_ord_id`, `eeg_id_registro_laboratorio` (bounded, indexed), `eeg_fecha_estudio`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min`, `eeg_canales_amplitud`, `eeg_canales_alta_frecuencia`, `eeg_canales_correlacion`, `eeg_canales_sin_senal`, `eeg_ruido_linea_db`, `eeg_estudio` (`FileBlob`, the EDF) **[EEG analysis]** |
|
||||
| `eeg_metrica` | `met_id` PK, `met_eeg_id`, `met_codigo` (`RITMO_POSTERIOR`, `HUSOS_SUENO_N2`, `HUSOS_SUENO_N3`, `PICOS_PAROXISTICOS`, `GRADIENTE_ANTEROPOSTERIOR`), `met_valor` (null: not evaluable) **[EEG analysis]** |
|
||||
| `eeg_metrica_electrodo` | `mel_id` PK, `mel_met_id`, `mel_electrodo`, `mel_valor` **[EEG analysis]** |
|
||||
|
||||
Notes:
|
||||
- The ADOS-2 domain subtotals and total aren't stored: they're sums of the items' algorithm scores, which is what the
|
||||
WebApp checks. `ado_algoritmo` is new: within a module it depends on the language level (item A1), which no
|
||||
column holds.
|
||||
- `eeg_utilizable` goes: a valid EEG is a good one, and quality comes from the five criteria. The EEG processing
|
||||
(EDF to criteria, metrics and electrode values) writes `eeg_canales`, `eeg_duracion_min`, the criteria and the two
|
||||
metric tables; nothing downstream opens the EDF.
|
||||
- Only measured values are stored. The z-score and the state of a metric come from reference ranges by age group,
|
||||
which are still pending medical review (§5).
|
||||
|
||||
---
|
||||
|
||||
## 3. Silver: the generic tables (Python load, `webapi/orchestration/silver/tea.py`)
|
||||
|
||||
Eight `DeStaging` instead of ten, into `procedimiento` and `observacion_clinica`:
|
||||
|
||||
| Bronze | `procedimiento` (study, class, parent) | `observacion_clinica` |
|
||||
|---|---|---|
|
||||
| `pacientes` | `persona` (`sexo` null) | |
|
||||
| `ordenes_estudio` | `orden`, study from `ord_tipo_estudio` | |
|
||||
| `mchat` | `mchat`, `toma`, its order if any | `mchat.puntaje` |
|
||||
| `ados2` | `ados2`, `encuentro`, its order | `ados2.modulo`, `ados2.algoritmo`, `ados2.clasificacion`, `ados2.css`, `ados2.sa_a2` … `ados2.rrb_d5` |
|
||||
| `evaluacion_neuropediatrica` | `evaluacion_neuropediatrica`, `encuentro`, its order | `evaluacion_neuropediatrica.diagnostico` (ICD-10, `F840`) |
|
||||
| `eeg` | `eeg`, `toma`, its order | `eeg.con_sueno`, `eeg.canales`, `eeg.duracion_min`, `eeg.calidad_amplitud`, `eeg.calidad_alta_frecuencia`, `eeg.calidad_correlacion`, `eeg.calidad_sin_senal`, `eeg.calidad_linea` **[EEG analysis]** |
|
||||
| `eeg_metrica` | results of the EEG `toma` | `eeg.ritmo_posterior`, `eeg.husos_sueno_n2`, `eeg.husos_sueno_n3`, `eeg.picos_paroxisticos`, `eeg.gradiente_anteroposterior` **[EEG analysis]** |
|
||||
| `eeg_metrica_electrodo` | `eeg`, `parte` per electrode (`codigo_fuente` = the electrode), parent the EEG | `eeg.<metrica>` **[EEG analysis]** |
|
||||
|
||||
- The catalog (`core/catalogos/tea.toml`) holds these studies and results; each ADOS-2 item's label and domain live in
|
||||
`cat_resultado`, so the patient summary takes them from there.
|
||||
- `tea_linea_de_tiempo.yml` goes from 29 sources to five: `mchat`, `ados2`, `evaluacion_neuropediatrica`, `eeg` and
|
||||
`orden`.
|
||||
|
||||
---
|
||||
|
||||
## 4. dbt silver (`models/tea/silver/`, ephemeral)
|
||||
|
||||
| Model | Grain | Columns |
|
||||
|---|---|---|
|
||||
| `tea_mchat` | M-CHAT | `procedimiento_id`, `pac_id`, `fecha_mchat`, `puntaje`, `carga_id` |
|
||||
| `tea_ados2` | ADOS-2 | `fecha_ados2`, `modulo`, `algoritmo`, `css`, `clasificacion`, `carga_id` |
|
||||
| `tea_ados2_reactivos` | ADOS-2 × item | `dominio`, `reactivo`, `puntaje`, `puntaje_algoritmo` |
|
||||
| `tea_neuropediatria` | note | `fecha_nota`, `cie_codigo`, `es_tea` (in `cie_tea`), `carga_id` |
|
||||
| `tea_eegs` | EEG | `fecha_eeg`, `con_sueno`, `canales`, `duracion_min`, the five criteria, `calidad` (`BUENO` or `MALO`), `valido` **[EEG analysis]** |
|
||||
| `tea_eeg_metricas` | EEG × metric | `valor`, age group at the EEG, `ref_min`, `ref_max`, `valor_z`, `estado` **[EEG analysis]** |
|
||||
|
||||
---
|
||||
|
||||
## 5. dbt gold (`models/tea/gold/eventos/`) and rules
|
||||
|
||||
| Event model | Grain | Measures |
|
||||
|---|---|---|
|
||||
| `tea_pasos` | patient × step reached, with `paso_orden`, `fecha`, `conocida_en`, `es_tea`, `grupo_edad` | M28, M23, M24, M21, M22 **[EEG analysis]** |
|
||||
| `tea_casos` | patient: the date and `conocida_en` of each step | M26, M27, M25 |
|
||||
| `tea_eegs_periodo` | EEG (`basis: examen`) | M29 **[EEG analysis]** |
|
||||
| `tea_alteraciones` | patient with a good EEG: their first good EEG's date, `conocida_en` and one flag per alteration found in it | M30 **[EEG analysis]** |
|
||||
|
||||
The age group is a stratum, as in CaCu: M21, M22 and M24 publish `TOTAL` with one `grupo_edad` per patient (age at the first M-CHAT, §1) in
|
||||
`measure_report_unidad_estrato` (breakdown and filter), which is the shape the WebApp already reads
|
||||
(`estrato=grupo_edad`). The windows are the page's: 16 to 23, 24 to 29 and 30 to 36 months. A child outside them is not
|
||||
in the cohort and isn't counted; `SIN_DATO` is left for a child without a birth date. This settles the groups-versus-strata question of `tea-port.md`.
|
||||
|
||||
Two constructs the engine doesn't have yet:
|
||||
- **Status at the period's end.** The population is every unit that entered on or before the period's end and
|
||||
hadn't left before its start (its last step dated before the period), not the units with an event inside the
|
||||
period; the category is the furthest step dated on or before that end.
|
||||
CaMa's measures count events dated inside the period, and `elige: mas_grave` chooses only among the period's
|
||||
rows.
|
||||
- **Several groups in one measure**, for M30 only: one group per alteration. The alterations can't be a stratum:
|
||||
`measure_report_unidad_estrato` holds one value per unit, and a patient can have several. The API turns the groups
|
||||
into the stratified rows the WebApp reads (`estrato=alteracion`, figure `fig_c1_barras_alteracion`).
|
||||
|
||||
Rules, as var `tea` in `dbt_project.yml`: `ventanas` (the page's three windows; the kit's 24 to 30 and 31 to 36 go),
|
||||
`edad_min_meses`, `edad_max_meses`, `dias_por_mes`,
|
||||
`cie_tea: [F840]`, `alteracion_z: 2` and the quality thresholds. Seeds: the metric references by age group, the
|
||||
electrode positions and the effect texts.
|
||||
|
||||
---
|
||||
|
||||
## 6. Seguimiento and the patient summary
|
||||
|
||||
As CaCu's (R5): views the WebApi reads, materialized as views because they leave dbt.
|
||||
- `tea_seguimiento`, one row per patient, with dates so the WebApi applies the window and the cut-off: `grupo_edad` (at the
|
||||
first M-CHAT), `fecha_eeg` and `calidad_eeg` (the study's EEG, see below), `mchat`, `css_ados2`, `modulo_ados2`,
|
||||
`alteraciones_eeg` and `alteraciones` (both from the first good EEG, as M30), `etapa`,
|
||||
`fecha_etapa` (the date of the step that set the stage), `diagnostico_tea` (from `neu_cie_codigo`, not from the CSS
|
||||
as the mock fakes it) and `pendientes`.
|
||||
- Every EEG column of the list is about the EEG the study uses, the same one as M30 and the patient summary (owner,
|
||||
2026-11-11): the first good-quality EEG, with `calidad_eeg` `bueno`. A patient without one shows their latest EEG
|
||||
with `calidad_eeg` `malo`, no result and no alterations; a patient without any EEG shows none. `ultimo_eeg` becomes
|
||||
`fecha_eeg`, as it's no longer always the latest.
|
||||
- The list can be filtered by the stage date (owner, 2026-11-11): `etapa_desde` and `etapa_hasta`, inclusive, on
|
||||
`fecha_etapa`, combined with the other filters (`etapa`, age group, M-CHAT, CSS, EEG result, alteration).
|
||||
- The patient summary reads `tea_ados2`, `tea_ados2_reactivos`, `tea_eegs`, `tea_eeg_metricas` and the electrode
|
||||
values; the WebApp draws the region z-scores and the map from the electrode values (§12.3).
|
||||
- The summary shows the EEG the study uses: the patient's first good-quality EEG (owner, 2026-11-11), with its date,
|
||||
quality criteria, alterations and maps, the same EEG M30 and Seguimiento's alterations read. A patient without a
|
||||
good EEG has no EEG in the study; the summary keeps showing their latest EEG with the warning that it isn't valid
|
||||
(owner, 2026-11-11).
|
||||
- Until the metric reference ranges, effect texts and quality thresholds are validated by the domain expert, every
|
||||
alteration stays hidden (owner, 2026-11-11): M30, Seguimiento's alteration columns, filter and EEG summary, and the
|
||||
summary's alterations panel and map. The quality (M29, the quality panel) and the stages still show. The
|
||||
electrode values are stored either way (§2), so the map comes back with the validation.
|
||||
|
||||
---
|
||||
|
||||
## 7. Removing the unused indicators
|
||||
|
||||
The page shows M21 to M30 and nothing else. Everything below is removed, not ported.
|
||||
|
||||
### 7.1 Indicators
|
||||
|
||||
| What | Where | Action |
|
||||
|---|---|---|
|
||||
| K01 to K08, M02, M04, M05, M10, M12, M12b, M15, M17, M18, M19 (18 TOMLs, already retired) | `indicadores_kit/tea/retirados/` | Not converted to dbt (R4b) and not carried into Transformation; deleted with the kit (R7) |
|
||||
| R01 `riesgo_banda` (proposal) and the TEA screening cohort it reads | `indicadores_kit/tea/propuestas/r01_riesgo_banda/`, `tea/cohortes/tamizaje.py`, `cohorte_tamizaje.toml` | Dropped. Its predictors (APGAR, NICU, maternal history, hearing test) leave staging with this design |
|
||||
| The kit's M21 to M25 as they are (CSS-based M21 and M22, M23 by sex, M24 over notes, M25 over the evaluation's date) | `indicadores_kit/tea/familias/` | Not ported: rewritten from §1. Their `casos.toml` don't apply |
|
||||
| TEA risk prediction | WebApi `POST /tea/predict`; mock `respuestas/tea/predict.POST.json`; `models/models/tea` | Out of scope while no TEA model is planned; the WebApp doesn't call it |
|
||||
|
||||
### 7.2 Parameters that go with them
|
||||
|
||||
Not carried from `parametros.toml` into var `tea` (D10):
|
||||
|
||||
| Key | Used only by |
|
||||
|---|---|
|
||||
| `tea.riesgos.horizonte_banda` | R01 |
|
||||
| `tea.cohorte.plazo_ados2_eeg_dias` | the 30-day rule, removed |
|
||||
| `tea.poblacion.css_min_tea` | the kit's M21 and M22 |
|
||||
| `tea.diagnostico.instrumentos_mchat` | the kit's M25; M-CHAT now has its own table |
|
||||
| `tea.instrumentos.informantes_ramos`, `tea.instrumentos.informantes_otros`, `tea.ramos.areas` | RAMOS (M12) |
|
||||
| `tea.atencion.plazo_referencia_evaluacion_dias` | K01 |
|
||||
| `tea.parto.apgar_corte` | M17 |
|
||||
| `tea.antecedentes_maternos.*` (four rules) | the maternal history load |
|
||||
| `tea.catalogos.sexo`, `.resultado_mchat`, `.interpretacion_ramos`, `.grado_hipoacusia`, `.apgar_5min` | M02 and M23 by sex, M05, M12, M15, M17 |
|
||||
|
||||
Kept: `tea.cohorte.edad_min_meses`, `edad_max_meses`, `dias_por_mes`, `ventanas` (with the page's windows), `tea.diagnostico.cie_tea`,
|
||||
`tea.supresion.activa`, `tea.presentacion.*`, `tea.catalogos.sin_dato`, `tea.observacion.inicio_datos`.
|
||||
|
||||
### 7.3 WebApp leftovers
|
||||
|
||||
The retired ids survive only in test data: `indicadores.synthetic-fixtures.ts` (18 entries), and the specs
|
||||
`indicador-catalog-card.spec.ts` (K05), `indicadores-search.spec.ts` (M02) and `indicadores-page.spec.ts` (K01,
|
||||
M02). In the two single-indicator specs they become current ids (M29, M24). The synthetic TEA catalog keeps its
|
||||
shapes under neutral ids and titles (`TEA_SINT_01` to `TEA_SINT_18`): with the real M21 to M30 the page starts the
|
||||
TEA summary's KPI requests, which the navigation and page specs don't expect, and those specs test the generic
|
||||
page. Done on the mock's branch `features/tea-plan-sync` (§11.5).
|
||||
|
||||
### 7.4 Plan and issues
|
||||
|
||||
| Item | Action |
|
||||
|---|---|
|
||||
| R4b.19 [#100](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/100) (TEA `r01_riesgo_banda`) | Close as not planned |
|
||||
| R3.3 [#81](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/81) (TEA screening cohort) | Close as not planned |
|
||||
| R4b.14 to R4b.18 (#95 to #99) | Retitle to the new M21 to M25; drop "equality against the kit's snapshot" from their Done when |
|
||||
| [#128](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/128) to [#131](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/131) (kit fixes to M21 to M25) | Close as superseded by §1: they change kit code that isn't ported, and the owner chose the 10 Nov definitions over theirs, F84 without the subcode included |
|
||||
| [#163](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/163) (TEA port to dbt's semantic layer) | Rewrite from this plan: eight `DeStaging`, ten measures, hand-written cases instead of `kit_oracle_tea.json` |
|
||||
| R1.1 [#48](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/48) (parameters from YAML) | Exclude the `[tea.*]` keys of §7.2 from its equality check against the kit's `def_parametro` |
|
||||
| New | One issue each for M26 to M30, Seguimiento and the patient summary |
|
||||
| `plans/kit-exit/oracle/kit_tea.json` and its use in `tea-port.md` (piece 8) | Retired: the new definitions are proven with hand-written cases, not against the kit |
|
||||
|
||||
---
|
||||
|
||||
## 8. Order
|
||||
|
||||
1. Owner approvals (§9), then the bronze revision, import schemas and catalog.
|
||||
2. Silver load, table map, domain lists and synthetic staging (as `tea-port.md` pieces 1 to 4, with §3).
|
||||
3. dbt silver and var `tea`; `dbt build --select tea` on SQLite and on the SQL Server 2016 VM.
|
||||
4. M29 (no new construct), then M26, M27 and M25.
|
||||
5. Status at the period's end: M28 and M23.
|
||||
6. The `grupo_edad` stratum: M24, M21 and M22.
|
||||
7. Several groups per measure: M30.
|
||||
8. `tea_seguimiento` and the patient summary views, and their WebApi endpoints; the WebApp changes of §11.
|
||||
9. The removals of §7 that aren't already done by not porting: parameters, WebApp test data, issues.
|
||||
|
||||
## 9. Approvals
|
||||
|
||||
| What | `AGENTS.md` rule |
|
||||
|---|---|
|
||||
| New TEA staging tables and columns, and dropping the current ones | 4 |
|
||||
| A new Alembic revision instead of the baseline (or a new baseline) | 3 |
|
||||
| Dropping R01 and the TEA screening cohort | owner |
|
||||
|
||||
## 10. Open questions
|
||||
|
||||
None left for the owner (decided 2026-11-11: §1 for the children who never finish and the day counts, §2 and §6 for
|
||||
the electrode values, §6 for the unvalidated references and the patient without a good EEG, §11.1 for the period
|
||||
picker). For the domain expert: the reference ranges, effect texts and quality thresholds (§6), and the LOINC and
|
||||
SNOMED codes marked *to confirm* (§12.3).
|
||||
|
||||
Arising from the state machines (§13.3), for the EEG analysis: how an EEG still waiting for its analysis
|
||||
(`SIN_ANALIZAR`) shows in M29 (a third category, or left out until analysed).
|
||||
|
||||
---
|
||||
|
||||
## 11. WebApp: what changes from `dev`
|
||||
|
||||
The TEA page the plan serves is the WebApp of the mock: branch `features/tea-mock` at `ca511ff` (10 Nov; the remote
|
||||
still has `53edec8`). Against WebApp `dev` (`f4d2a3e`, 30 Oct, the commit ISSSTELEON `dev` pins) it is 21 commits
|
||||
ahead and one behind, about 63 files, +3,000 and -1,150 lines, mostly under `src/app/features/indicadores/`. §11.6
|
||||
has the branches it has to meet on the way to `dev`.
|
||||
|
||||
### 11.1 Changes for every domain
|
||||
|
||||
| Change | Files |
|
||||
|---|---|
|
||||
| One period at a time: the multi-period selector of Resumen becomes a single-period select, for CaCu and CaMa too | `indicador-period-filters.*`, `indicadores-page.*` |
|
||||
| A graphic-indicator selector with an «Ir» link replaces the floating navigation panel (also closes #5) | `indicadores-page.*`; `indicadores-navegacion-panel.*` removed |
|
||||
| Highlight buttons for the groups and categories of a figure | `indicadores-highlight.ts`, `indicador-figure-card.*`, `indicador-figure-panel.ts` |
|
||||
| A C1 donut by stratum | `indicadores-c1-donut.ts` |
|
||||
| Catalog items can name the tabs that show them (`vistas`); C1 cards can carry their own explanatory line (`c1Info`); C2 cards keep their category counts (`categorias`) | `indicadores.models.ts`, `indicadores-kpi.ts` |
|
||||
| `alteracion` admitted as a stratum next to `grupo_edad`, `estatus_seguimiento` and `citologia_alto_grado` | `indicadores.service.ts` |
|
||||
| The follow-up query grows the fields `grupo_edad`, `mchat`, `css`, `etapa`, `alteracion` | `cacu-seguimiento.models.ts` |
|
||||
|
||||
The single-period select stays TEA-only (owner, 2026-11-11): CaCu and CaMa keep the multi-period picker.
|
||||
|
||||
### 11.2 TEA only
|
||||
|
||||
| Feature | Files |
|
||||
|---|---|
|
||||
| Tabs Resumen, Histórico, Seguimiento, Datos y definiciones | `indicadores-page.ts` (`TEA_SECTIONS`) |
|
||||
| Histórico: each indicator over time, with custom periods chosen by year | `indicadores-historico.ts`, `indicadores-historico-figures.ts`, `indicadores-historico-periodos.ts` |
|
||||
| The period summary paragraph, built from the hidden KPI cards | `tea-resumen-periodo.ts`, `indicadores-kpi.ts` (`KPI_RESUMEN_TEA`) |
|
||||
| C2 donut with groups drawn both rings at once; one-ring donut for C2 without groups | `indicadores-tea-c2.ts` |
|
||||
| M30's figure: one bar per alteration, shares that don't add up (`fig_c1_barras_alteracion`) | `indicadores-tea-alteraciones.ts` (new, untracked) |
|
||||
| Seguimiento: filters by EEG result, age group, M-CHAT band, CSS band, stage and alteration; EEG summary of all matching patients; stage and pending steps per patient | `tea-seguimiento.service.ts`, `indicadores-tracking.*` |
|
||||
| Patient summary: ADOS-2 with domains and items, EEG quality by criteria (good or bad), alterations with reference, z-score and effects, topographic map per alteration | `tea-paciente-resumen.*` |
|
||||
|
||||
### 11.3 What the backend must serve for it
|
||||
|
||||
| Route | Contract |
|
||||
|---|---|
|
||||
| `GET /tea/indicadores` | The ten ids of §1, with `estratos` (`grupo_edad` for M21, M22, M24; `alteracion` for M30), `figuras` (`fig_c1_barras_edad`, `fig_c1_barras_apiladas_edad`, `fig_c1_barras_alteracion`, `fig_c2_barras`, `fig_c2_donas`, `fig_c3r_caja`), `tipos_periodo` and `vistas` |
|
||||
| `GET /tea/indicadores/<id>/datos` | `?periodos=` with several periods (Histórico) and `?estrato=grupo_edad` or `alteracion`; C2 categories with label and color; M29 and M30 as in §1 |
|
||||
| `GET /tea/indicadores/<id>/metadatos` | As CaCu's |
|
||||
| `GET /tea/seguimiento` | `meses`, `corte`, `page`, `page_size`, `alteraciones_eeg`, `grupo_edad`, `mchat_min`/`mchat_max`, `css_min`/`css_max`, `etapa`, `alteracion`; each item with the fields of §6; `tipos_alteracion` and `resumen_eeg` (`normales`, `anormales`, `sin_eeg_valido`, `por_alteracion`) |
|
||||
| `GET /tea/seguimiento/<id_seudonimo>` | `ados2` (module, algorithm, domains with items, total, classification, CSS, level) and `eeg` (date, duration, channels, quality and criteria, alterations, maps on shared axes); the pseudonym resolved as in #168 |
|
||||
|
||||
### 11.4 Mock-only parts to replace
|
||||
|
||||
- The TEA Seguimiento and the patient summary accept only `simulado: true`, as CaCu's list does. WebApi `dev` now
|
||||
registers the follow-up and patient-risk routes in every environment (`0cbe390`, 9 Nov), so the WebApp's
|
||||
`simulado` guard is what keeps real data out; lifting it needs the owner's OK.
|
||||
- «Datos de ejemplo» badges on the EEG quality and alterations panels, and «TEA (mock)» comments: the alterations
|
||||
are hidden until the reference ranges and effects are validated (§6), and the badges go then.
|
||||
- The retired ids in the WebApp's test data (§7.3).
|
||||
|
||||
### 11.5 Not in the WebApp yet
|
||||
|
||||
Done in the mock (mock `features/tea-historico`, ISSSTELEON and WebApp `features/tea-mock`): everything in this list
|
||||
except the last two items, plus the indicator generator on the cohort rule of §1 (first good EEG, a bad EEG repeated,
|
||||
leaving after the period of the good one) and the indicator texts.
|
||||
|
||||
- **The patient summary's EEG.** The mock builds the summary from the latest EEG (`ultimo_eeg` in
|
||||
`generar_tea_detalle.py`); it changes to the first good EEG (§6), and the panel says which EEG it is and its date.
|
||||
- **Seguimiento's EEG columns.** `ultimo_eeg` is renamed `fecha_eeg` and holds the study's EEG (§6), in
|
||||
`tea-seguimiento.service.ts` (type and validation), `indicadores-tracking.html` (the «Último EEG» header becomes
|
||||
«EEG del estudio») and the mock's list and generator.
|
||||
- **Seguimiento: the stage date.** A `fecha_etapa` column and a date-range filter on it (`etapa_desde`, `etapa_hasta`),
|
||||
in `tea-seguimiento.service.ts` (type, validation, query), `indicadores-tracking.*` (column, filter) and the
|
||||
mock's list.
|
||||
- **The cohort rule of §1.** The period summary still says «tuvieron algún paso del tamizaje… según su etapa a la
|
||||
fecha de corte», and the mock generator (`generar_tea_casos.py`, `cohorte()`) counts the children with a step in
|
||||
the period at their stage at the cut-off. Both change to the children in the screening during the period, at their
|
||||
stage at its end, leaving after the period of their good EEG.
|
||||
- **The single-period select, TEA only.** The mock WebApp gives every domain one period at a time; CaCu and CaMa get
|
||||
their multi-period picker back (§11.1).
|
||||
- **Alterations hidden until validated.** M30, Seguimiento's alteration columns, filter and EEG summary, and the
|
||||
summary's alterations panel and map stay hidden behind one switch until the references are validated (§6).
|
||||
|
||||
### 11.6 Branches on the way to `dev`
|
||||
|
||||
Checked 2026-11-11 against the Gitea remotes.
|
||||
|
||||
| Branch | Where it stands | What it means for TEA |
|
||||
|---|---|---|
|
||||
| WebApp `dev` (`f4d2a3e`) | One commit the mock lacks: the bitácora page, self-hosted fonts and icons, install-package fixes (reportes, governance, connect) | Merging it into the TEA branch conflicts only in `src/styles.scss` |
|
||||
| `features/cama-mock` (`502fc96`, 9 Nov) | Built on `features/tea-mock` at `53edec8`, plus 22 commits: CaMa on TEA's tabs, the domain menu in the header, the institutional look, general filters in one compact row, search and «Fijar indicador» only from five indicators, cards with a value without «Disponible» | It holds the TEA page except `ca511ff`. Merging `ca511ff` into it conflicts in `cacu-seguimiento.models.ts`, `indicadores-kpi.ts` and `indicadores.service.ts`; eleven more shared files merge cleanly. It also conflicts with `dev` in `src/styles.scss` |
|
||||
| `refactor/kit-exit` (`62cdb25`, 8 Nov) | `dev` plus three commits: a separate KPIs page (`/kpis`) that draws CaCu's measures from FHIR `MeasureReport` bundles | No file in common with the TEA branch, but the contract clashes (§11.7) |
|
||||
|
||||
Order: push `ca511ff`, merge it into `features/cama-mock` (three conflicts), bring `dev` in (`styles.scss`), and merge
|
||||
the result into `dev` by pull request.
|
||||
|
||||
### 11.7 The contract gap with `refactor/kit-exit`
|
||||
|
||||
The TEA page reads the kit's serving contract: `GET /<domain>/indicadores` as a catalog (title, contract, figures,
|
||||
strata), `/indicadores/<id>/datos` with rows per period and stratum, and `/metadatos`. The WebApi on
|
||||
`refactor/kit-exit` (`c430a5b`) serves only `GET /<domain>/indicadores`, as a list of measures (`id`, `url`,
|
||||
`version`, `scoring`), and `GET /<domain>/indicadores/<measure_id>`, a FHIR `MeasureReport`. The same URL means two
|
||||
different things, and nothing serves `/datos` or `/metadatos`, for TEA, CaCu or CaMa.
|
||||
|
||||
One of the two has to give, and it's the owner's decision (#132 point 3 asks for one generic contract):
|
||||
1. **The pages read `MeasureReport`**, as `/kpis` does: the Resumen, Histórico and strata code reads FHIR groups and
|
||||
stratifiers. The catalog fields the page needs (titles, figures, strata, `vistas`, colors, notes) come from the
|
||||
measures' `meta` in dbt. Largest WebApp change; one contract.
|
||||
2. **The WebApi adds the page's contract over the measures**: `/datos` and `/metadatos` built from the dbt measures,
|
||||
and the catalog under a URL that doesn't clash with the measure list. No WebApp change; two contracts.
|
||||
|
||||
Planned: option 1 (owner, 2026-11-11). The WebApi side is §12. On the WebApp side, the indicator page (Resumen,
|
||||
Histórico, the KPI cards and the period summary) reads `Measure` and `MeasureReport` the way `/kpis` already does,
|
||||
and §11.3's `/datos` and `/metadatos` go. Seguimiento and the patient summary move to FHIR too (§12.4, §12.5).
|
||||
|
||||
---
|
||||
|
||||
## 12. WebApi: answering in FHIR
|
||||
|
||||
Every route the TEA page reads, and the rest of the WebApi, gets its FHIR R4 equivalent. Reference: the WebApi on
|
||||
`refactor/kit-exit` (`c430a5b`), which already answers each measure as a `Bundle` of `MeasureReport`s
|
||||
(`webapi/kpis.py`, `metrics.py`, `compositions.py`, `durations.py`). Codes marked *to confirm* need the domain
|
||||
expert: LOINC or SNOMED where one exists, the project's code system otherwise.
|
||||
|
||||
### 12.1 Conventions for every route
|
||||
|
||||
| Point | Today | FHIR |
|
||||
|---|---|---|
|
||||
| Base | Routes under `/<domain>/…`, `/reportes`, `/imports`, `/governance` | One FHIR endpoint per domain database: `/<domain>/fhir/`, FHIR R4 (4.0.1), JSON, `application/fhir+json` |
|
||||
| What the server offers | `GET /api` lists routes | `GET /<domain>/fhir/metadata`: a `CapabilityStatement` with the resources, search parameters and operations below |
|
||||
| Errors | `{"error": "…"}` | `OperationOutcome` (severity, code, Spanish `diagnostics`), same HTTP statuses |
|
||||
| Lists and paging | `items` with `paginacion` (`page`, `page_size`, `total_items`, `total_pages`) | `Bundle` `searchset` with `total` and `link` (`self`, `next`, `previous`); `_count` (at most 200) and the server's paging links |
|
||||
| Patient identity | `id_seudonimo` in the body; `pac_id` in the CaCu risk route | `Patient.id` is the salted pseudonym everywhere; `pac_id` and `pac_id_hospital` never leave; references are `Patient/<pseudonym>`, resolved as in #168 |
|
||||
| Simulated data | `simulado: true` in the body | A `meta.tag` on every resource (system `https://isssteleon.org/fhir/CodeSystem/etiqueta`, code `simulado`); the WebApp guard reads the tag |
|
||||
| Catalogs | `cat_estudio`, `cat_resultado`, `cat_valor`, the TOML catalogs | `CodeSystem` and `ValueSet` resources under `https://isssteleon.org/fhir/`, generated from `core/catalogos/tea.toml`; external systems where they apply: ICD-10 (`http://hl7.org/fhir/sid/icd-10`), observation interpretation (`H`, `L`, `N`), `data-absent-reason` |
|
||||
| Extensions | Three, for cut-offs and the history entry | Each one with a `StructureDefinition` published under `https://isssteleon.org/fhir/StructureDefinition/` |
|
||||
| Checking | Shape checks in the WebApp | Every response checked against FHIR R4 in the WebApi tests, with a FHIR model library or the HL7 validator (a new dependency: owner's approval) |
|
||||
|
||||
### 12.2 Measures
|
||||
|
||||
| Today | FHIR |
|
||||
|---|---|
|
||||
| `GET /<domain>/indicadores`: `{id, url, version, scoring}` | `GET /<domain>/fhir/Measure`: a `Bundle` of `Measure` resources, replacing the page's catalog and `/metadatos`. Title, description, scoring, `group` with each population's `description` (what #2 asks), `stratifier` definitions, `improvementNotation`, and extensions for figures, `vistas`, period types, category labels and colors. Built from each metric's `meta` in dbt |
|
||||
| `GET /<domain>/indicadores/<measure_id>?periodos=…` | One period: `GET /<domain>/fhir/Measure/<id>/$evaluate-measure?periodStart=…&periodEnd=…` (the standard operation), returning one `MeasureReport`. Several periods (Histórico): `GET /<domain>/fhir/MeasureReport?measure=<canonical>&period=…`, a `searchset` with one report per period. `corte_evento` and `corte_conocimiento` stay as custom parameters of both |
|
||||
| `GET /reportes/indicadores` (stored reports) | `GET /<domain>/fhir/MeasureReport` with `measure`, `period` and `date` search; the history entry stays an extension |
|
||||
| `POST /reportes/indicadores/<dominio>/recalcular` | `POST /<domain>/fhir/Measure/$recalcular`, a custom operation returning an `OperationOutcome` |
|
||||
| Domains in the `kpis_blueprint` loop | `tea` added (`tea-port.md` piece 3), with TEA's metrics in the manifest |
|
||||
|
||||
The `MeasureReport` itself:
|
||||
|
||||
| Point | Today | Change |
|
||||
|---|---|---|
|
||||
| `measure` | `tea/M21_…\|0.3.0`, not a URL | An absolute canonical (`https://isssteleon.org/fhir/Measure/<measure_id>\|<version>`), the same one the `Measure` carries |
|
||||
| Scoring of a C2 | `composition`, which isn't a FHIR scoring | `cohort`: the units counted as the initial population, with the categories as a stratifier |
|
||||
| Groups | One group, identified only by `id` | `group.code` on each, and several groups per report where the measure has them (M30: `TOTAL` plus one per alteration) |
|
||||
| Stratifier and stratum identity | `code: [{text}]`, `value: {text}` | Codings: the stratifier's code (`grupo_edad`, the C2's category), and each value with its catalog system, code and display |
|
||||
| C2 with strata | Each stratum's counts summed across categories | `stratum.component` holds the category inside each stratum value, so a breakdown by both survives |
|
||||
| Suppression | Absent | Suppressed counts and scores carry no value and the `data-absent-reason` extension (`masked`); depends on #73 |
|
||||
| Confidence interval | Absent | Lower and upper bounds as extensions of `measureScore`; depends on #73 |
|
||||
| Proportion score | A fraction, without unit | Kept as a fraction (0 to 1), stated in the `Measure`; the WebApp multiplies for display |
|
||||
| Exclusions | Not reported | `denominator-exclusion` with its count where the measure excludes (M24's neuropediatrics notes without F84.0) |
|
||||
| Durations | Median with `q1` and `q3` extensions | Kept; the excluded (no value at the cut-off) as their own population count |
|
||||
|
||||
The engine, for TEA's definitions. These are §5's constructs; the engine that answers them is this WebApi code, not dbt.
|
||||
|
||||
| Construct | Today | Change |
|
||||
|---|---|---|
|
||||
| Age stratum | Kinds `edad_al_inicio_del_periodo`, `linea_de_tiempo_al_inicio_del_periodo`, `del_elegido` | A kind that reads a column of the event model (`grupo_edad`, the age at the first M-CHAT, §1). Age at the period's start contradicts §1 |
|
||||
| Status at the period's end (M28, M23, M24, M21, M22) | Units with a fact dated inside the period | A population rule in `meta`: units entered on or before the period's end and not left before its start; the category is the furthest step dated on or before that end |
|
||||
| Several groups (M30) | `MeasureDefinition.group` is one string | A list of groups, each with its filter, answered and serialized one by one |
|
||||
| Unit of M29 | `basis` of the existing measures | `examen` (oro has no `estudio`) |
|
||||
|
||||
### 12.3 TEA's clinical data as FHIR resources
|
||||
|
||||
What Seguimiento and the patient summary show, read from silver (§3), each kind of fact as its resource:
|
||||
|
||||
| TEA fact | Resource | Content |
|
||||
|---|---|---|
|
||||
| Child | `Patient` | `id` the pseudonym; `birthDate` at month precision; no identifiers, no name |
|
||||
| Order | `ServiceRequest` | `code` the study (ADOS-2, neuropediatrics, EEG); `authoredOn`; `subject` |
|
||||
| M-CHAT | `Observation` | `code` M-CHAT-R/F total (LOINC *to confirm*); `valueInteger` 0 to 20; `effectiveDateTime`; `basedOn` its order if any |
|
||||
| ADOS-2 | `Observation` | `code` ADOS-2 (*to confirm*); `component`s for module, algorithm, CSS, classification, the two domain totals and the 29 items (item codes in the project's `CodeSystem`, labels and domains there); `effectiveDateTime`; `basedOn` |
|
||||
| Neuropediatrics note | `Encounter` and `Condition` | The visit (`serviceType` neuropediatrics, `period`); its diagnosis as a `Condition` (`code` ICD-10, `F840` for TEA, `encounter`, `recordedDate`) |
|
||||
| EEG | `Procedure` and `DiagnosticReport` | The recording as a `Procedure` (`code` electroencephalography, SNOMED *to confirm*); its result as a `DiagnosticReport` (`effectiveDateTime`, `result` the observations below, `conclusionCode` good or bad quality). The EDF as a `Media` with its `Binary`, served only where the file may leave |
|
||||
| EEG quality criteria | `Observation` | One per criterion (`valueInteger` channels or `valueQuantity` dB), `interpretation` good or bad; members of the report **[EEG analysis]** |
|
||||
| EEG metric (alteration) | `Observation` | One per metric: `valueQuantity` with its unit; `referenceRange` for the child's age group at the EEG; `interpretation` `H` (aumentado), `L` (disminuido) or `N`; `dataAbsentReason` when it can't be evaluated (no sleep). The z-score as a `component`. Effect texts live in the `CodeSystem` of the metrics, not in each observation **[EEG analysis]** |
|
||||
| Electrode values | `Observation` | One per metric, a `component` per electrode (`code` the 10-20 electrode, `valueQuantity` the z-score). The WebApp draws the map and the regions from them (#132); `mapas` and `ejes_mapa` leave the API **[EEG analysis]** |
|
||||
|
||||
### 12.4 Seguimiento
|
||||
|
||||
The follow-up list is each child's screening as an `EpisodeOfCare`, which already has the cohort's entry and exit:
|
||||
|
||||
| Field today | FHIR |
|
||||
|---|---|
|
||||
| The row | `EpisodeOfCare`: `patient`, `period.start` the first M-CHAT, `period.end` the first good EEG, `status` `active` while pending and `finished` after it |
|
||||
| `etapa`, `fecha_etapa` | `type` the stage (project `CodeSystem`), and an extension with the stage's date |
|
||||
| `pendientes` | A `CarePlan` per episode, one `activity` per step with its `status` (`completed`, `not-started`) and date |
|
||||
| `grupo_edad`, `mchat`, `css_ados2`, `modulo_ados2`, `diagnostico_tea`, `fecha_eeg`, `calidad_eeg`, `alteraciones_eeg`, `alteraciones` | Included resources (`_include`): the `Patient`, the M-CHAT and ADOS-2 `Observation`s, the `Condition` and the EEG `DiagnosticReport` with its metrics; the age group as an extension of the episode |
|
||||
| Filters | Search parameters on `EpisodeOfCare`: `status`, `date` (the window and the cut-off), `etapa`, `fecha-etapa` (`ge`, `le`: the stage-date filter of §6), `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; each declared as a `SearchParameter` |
|
||||
| `resumen_eeg`, `tipos_alteracion` | `GET /tea/fhir/EpisodeOfCare/$resumen-eeg` with the same filters, returning `Parameters` (normal, abnormal, without a valid EEG, count per alteration); the alteration types are the metrics' `ValueSet` |
|
||||
|
||||
`GET /tea/fhir/EpisodeOfCare?…&_include=…` replaces `GET /tea/seguimiento`. CaCu's follow-up list (`/cacu/seguimiento`)
|
||||
moves to the same shape.
|
||||
|
||||
### 12.5 The patient summary
|
||||
|
||||
`GET /tea/fhir/Patient/<pseudonym>/$resumen-tea` replaces `GET /tea/seguimiento/<id_seudonimo>`: a `Bundle` of type
|
||||
`collection` with the `Patient`, the ADOS-2 `Observation` and the EEG the study uses (the first good one, §6) as its
|
||||
`DiagnosticReport` with the quality, metric and electrode `Observation`s. A patient without a good EEG gets their latest
|
||||
one, with `conclusionCode` bad quality. The ADOS-2 domain bars, the CSS level and the map are drawn by the WebApp from
|
||||
those resources.
|
||||
|
||||
### 12.6 The rest of the WebApi
|
||||
|
||||
| Route family | FHIR |
|
||||
|---|---|
|
||||
| `GET /cacu/pacientes/<pac_id>/riesgo` | `RiskAssessment` (`subject` the pseudonym, `prediction` one per horizon with `probabilityDecimal` and `whenRange`, `basis` the observations used, `method` the model version); cohort membership as a `Group` (the build) with the patient as a member |
|
||||
| `POST /<domain>/predict` | `POST /<domain>/fhir/RiskAssessment/$predict`, returning a `RiskAssessment`. Out for TEA (§7.1) |
|
||||
| `GET /reportes/importaciones`, `/importaciones/descarga` | `AuditEvent` per import (who, when, what, outcome) and `Provenance` on the resources it wrote; the download as a `Binary` |
|
||||
| `POST /imports/commit` | The rows written as a `transaction` `Bundle` of the resources above; uploaded documents as `DocumentReference` with their `Binary`. `POST /imports/validate` maps to `$validate` |
|
||||
| `/imports/connectors`, `/targets`, `/sources/…` (previews, SQL browsing, PDF regions) | Not FHIR: tooling for the import screen, kept as an admin API outside `/<domain>/fhir/` |
|
||||
| `GET /data/<target>` | Not FHIR: raw staging rows. Kept as admin, or removed once imports are checked through the resources |
|
||||
| `/governance/model-versions/…` | Not FHIR (no resource fits a model registry); admin API. A model version used in a prediction is cited from `RiskAssessment.method` |
|
||||
| `/governance/ocr/…` | OCR jobs as `Task` (`status`, `input` the document, `output` the rows); corrections stay admin |
|
||||
| `GET /health` | Unchanged, outside FHIR |
|
||||
|
||||
### 12.7 What it means for the WebApp
|
||||
|
||||
Every reader changes with its route: the indicator page and `/kpis` read `Measure` and `MeasureReport` (§11.7);
|
||||
Seguimiento reads `EpisodeOfCare` bundles with their includes and paging links; the patient summary reads the
|
||||
`$resumen-tea` bundle and draws the ADOS-2 bars and the EEG map itself; CaCu's patient record reads `RiskAssessment`;
|
||||
errors arrive as `OperationOutcome`; the `simulado` guard reads `meta.tag`. §11.3 and §11.5 describe the page as it
|
||||
reads today; this section is where it ends.
|
||||
|
||||
### 12.8 Order
|
||||
|
||||
1. Conventions: the `/<domain>/fhir/` base, `CapabilityStatement`, `OperationOutcome`, the `simulado` tag, the
|
||||
`CodeSystem`s, and response checking in the tests.
|
||||
2. Measures: `Measure`, `$evaluate-measure`, the `MeasureReport` search, canonical URLs, codings, `cohort` for C2,
|
||||
`stratum.component`.
|
||||
3. The engine constructs for TEA (column stratum, status at the period's end, several groups), with TEA's measures.
|
||||
4. TEA's clinical resources (§12.3), then Seguimiento as `EpisodeOfCare` and the patient summary operation.
|
||||
5. Suppression and intervals, with #73.
|
||||
6. The rest (§12.6): `RiskAssessment`, `AuditEvent` and `Provenance`, imports as `transaction`, OCR `Task`s.
|
||||
|
||||
Each step changes what the WebApp, `/kpis` and the CaCu and CaMa answers receive: their readers and the frozen answers
|
||||
of `tests/test_*_measures.py` move with it.
|
||||
|
||||
### 12.9 Approvals
|
||||
|
||||
| What | `AGENTS.md` rule |
|
||||
|---|---|
|
||||
| A FHIR model or validation library in the WebApi | new dependency |
|
||||
| Routes moved under `/<domain>/fhir/` and the old ones removed | owner |
|
||||
| Codes from LOINC and SNOMED (licensing of SNOMED in Mexico) | owner and domain expert |
|
||||
|
||||
---
|
||||
|
||||
## 13. State machines
|
||||
|
||||
The rules of §1 and §6 define these machines. The stored data are dated facts (M-CHAT, ADOS-2, notes, EEG and their
|
||||
analysis); every state below is derived from them at a date: the end of a period for the measures, the cut-off for
|
||||
Seguimiento. Nothing stores a state, so a late fact moves the state back in time when it's loaded.
|
||||
|
||||
### 13.1 A child's screening
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16 to 36 months
|
||||
[*] --> MCHAT: first M-CHAT at 16 to 36 months
|
||||
MCHAT --> PSICOLOGIA: psychology note (ADOS-2)
|
||||
PSICOLOGIA --> NEUROPEDIATRIA: neuropediatrics note
|
||||
NEUROPEDIATRIA --> EEG: first good-quality EEG
|
||||
EEG --> COMPLETADO: end of the period of that EEG
|
||||
FUERA_DE_COHORTE --> [*]
|
||||
COMPLETADO --> [*]
|
||||
```
|
||||
|
||||
| From | Event (dated fact) | To |
|
||||
|---|---|---|
|
||||
| (start) | First M-CHAT at 16 to 36 completed months | `MCHAT` |
|
||||
| (start) | First M-CHAT outside that range | `FUERA_DE_COHORTE`: never counted |
|
||||
| `MCHAT` | Psychology note (ADOS-2) | `PSICOLOGIA` |
|
||||
| `PSICOLOGIA` | Neuropediatrics note, with any diagnosis | `NEUROPEDIATRIA` |
|
||||
| `NEUROPEDIATRIA` | First good-quality EEG | `EEG` |
|
||||
| `EEG` | The end of the period of that EEG | `COMPLETADO`: no longer counted |
|
||||
|
||||
- Steps go in order; a fact whose previous step is missing doesn't move the child (an EEG before the
|
||||
neuropediatrics note leaves them where they are until the note arrives).
|
||||
- A bad EEG, an EEG still waiting for analysis (§13.3), a later EEG and a second note don't move the child.
|
||||
- Without a good EEG a child never leaves (§1): `MCHAT`, `PSICOLOGIA` and `NEUROPEDIATRIA` have no exit.
|
||||
- **How a period reads it:** a child is counted in a period when their state at its end is `MCHAT`, `PSICOLOGIA`,
|
||||
`NEUROPEDIATRIA` or `EEG` and they weren't `COMPLETADO` at its start; the category of M28 is that state.
|
||||
- **Seguimiento:** `etapa` is the state at the cut-off, `fecha_etapa` the date of the fact that set it, `pendientes`
|
||||
the steps after it. In FHIR it's the `EpisodeOfCare` (`active` until `COMPLETADO`, then `finished`) with its
|
||||
`CarePlan` (§12.4).
|
||||
|
||||
### 13.2 The diagnostic result
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> EN_PROCESO: in the screening, no neuropediatrics note
|
||||
EN_PROCESO --> CONFIRMADO: note with F84.0
|
||||
EN_PROCESO --> SIN_TEA: note without F84.0
|
||||
SIN_TEA --> CONFIRMADO: a later note with F84.0
|
||||
```
|
||||
|
||||
| State | Meaning | Counted in |
|
||||
|---|---|---|
|
||||
| `EN_PROCESO` | No neuropediatrics note by the date | M23 (in process), M24 denominator |
|
||||
| `CONFIRMADO` | Some neuropediatrics note with F84.0 by the date | M23 (confirmed), M24 numerator and denominator, M21 and M22 base, M25 |
|
||||
| `SIN_TEA` | Notes, none with F84.0 | M24 exclusions; out of M23; still in the screening (§13.1) |
|
||||
|
||||
`CONFIRMADO` is final: a later note without F84.0 doesn't undo it. It runs beside §13.1, not after it: the
|
||||
neuropediatrics note moves both.
|
||||
|
||||
### 13.3 One EEG study
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_ANALIZAR: EDF or report loaded
|
||||
SIN_ANALIZAR --> BUENO: analysis, every criterion good
|
||||
SIN_ANALIZAR --> MALO: analysis, some criterion bad
|
||||
BUENO --> [*]
|
||||
MALO --> [*]
|
||||
```
|
||||
|
||||
| State | Meaning | What it feeds **[EEG analysis]** |
|
||||
|---|---|---|
|
||||
| `SIN_ANALIZAR` | Loaded, criteria not written yet | M29 can't grade it; it doesn't move §13.1 or §13.4 |
|
||||
| `BUENO` | Every quality criterion within its threshold | M29 (good); may become the study EEG (§13.4) |
|
||||
| `MALO` | Some criterion out of its threshold | M29 (bad); no result, no alterations |
|
||||
|
||||
A new analysis of the same EEG (new thresholds) can move it between `BUENO` and `MALO`; the states above it are
|
||||
derived again on the next answer. How `SIN_ANALIZAR` shows in M29 is open (§10).
|
||||
|
||||
### 13.4 The patient's study EEG
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_EEG
|
||||
SIN_EEG --> SOLO_MALOS: a bad EEG
|
||||
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
|
||||
```
|
||||
|
||||
| State | Shown in Seguimiento and the summary | Alterations |
|
||||
|---|---|---|
|
||||
| `SIN_EEG` | No EEG | None |
|
||||
| `SOLO_MALOS` | The latest EEG, `calidad_eeg` `malo`, marked not valid | None |
|
||||
| `CON_EEG_DEL_ESTUDIO` | The first good EEG, `calidad_eeg` `bueno` | That EEG's, once per alteration; M30 counts it in its period |
|
||||
|
||||
Entering `CON_EEG_DEL_ESTUDIO` is the same event that moves §13.1 to `EEG`, when the neuropediatrics note is there.
|
||||
|
||||
### 13.5 Showing the alterations
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PROVISIONAL
|
||||
PROVISIONAL --> VALIDADO: domain expert validates references, effects and thresholds
|
||||
```
|
||||
|
||||
| State | Shown |
|
||||
|---|---|
|
||||
| `PROVISIONAL` | Quality (M29, the quality panel) and the stages; every alteration hidden (§6) |
|
||||
| `VALIDADO` | Everything, without the «Datos de ejemplo» badges |
|
||||
|
||||
A change to the references after validation goes back through the domain expert; the switch doesn't return to
|
||||
`PROVISIONAL` on its own.
|
||||
|
||||
### 13.6 A measure's answer for a period
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_RESPUESTA
|
||||
SIN_RESPUESTA --> RESPONDIDA: first request after a load
|
||||
RESPONDIDA --> RESPONDIDA: same question again (read from the history)
|
||||
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off)
|
||||
```
|
||||
|
||||
The WebApi answers each measure and period on request and keeps the answer by its knowledge cut-off (the start of
|
||||
the last load, §12.2). A new load opens a new cut-off: the next request computes again, and the old answer stays in
|
||||
the history. A change to dbt's models or to var `tea` is a new definition and also computes again.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user