From 6f0f072d84775a681b2b89d94c253504639a1b64 Mon Sep 17 00:00:00 2001 From: gti Date: Fri, 25 Sep 2026 12:25:53 -0300 Subject: [PATCH] fix: fresh install archives stale state of a previous installation; a fatal Agent loop error stops the service instead of leaving a dead 'Running' one; 1.2.3 Found by uninstall + fresh install on the clean Windows Sandbox: the old agent_state.sqlite identity conflicted with the new enrollment and the service sat idle. Co-Authored-By: Claude Sonnet 5 --- agent/pyproject.toml | 2 +- agent/scripts/run_agent_service.py | 6 ++--- agent/service/gti_agent_windows_service.py | 9 ++++++- agent/src/gti_fiscal_agent/preflight.py | 2 +- agent/tests/test_windows_service_host.py | 7 ++++++ central/app/version.py | 2 +- central/pyproject.toml | 2 +- central/tests/test_health.py | 2 +- deploy/agent-windows/agent.env.template | 2 +- deploy/agent-windows/gti-agent.ps1 | 2 +- .../pilot-construcao.env.example | 2 +- .../profiles/mmmodas.env.example | 2 +- .../agent-windows/profiles/rincao.env.example | 2 +- .../agent-windows/profiles/uniao.env.example | 2 +- deploy/hub/.env.example | 2 +- deploy/hub/docker-compose.prod.yml | 2 +- docs/DEPLOY_HUB.md | 2 +- installer/install_common.py | 16 ++++++++++++ installer/setup_main.py | 1 + release/RELEASE_MANIFEST.json | 8 +++--- release/VERSION | 2 +- tests/test_release_candidate.py | 4 +-- tests/test_zero_touch_installer.py | 25 +++++++++++++++++++ 23 files changed, 81 insertions(+), 25 deletions(-) diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 003a8f1..a43bc65 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "gti-fiscal-agent" -version = "1.2.2" +version = "1.2.3" requires-python = ">=3.10" dependencies = ["httpx>=0.27,<1"] diff --git a/agent/scripts/run_agent_service.py b/agent/scripts/run_agent_service.py index e29cd87..7fb65c0 100644 --- a/agent/scripts/run_agent_service.py +++ b/agent/scripts/run_agent_service.py @@ -106,7 +106,7 @@ class Config: self.poll_interval_seconds = float(env.get("POLL_INTERVAL_SECONDS", "5")) # RTC auto-apply is a SEPARATE switch (default OFF): FIREBIRD_WRITES alone never lets the Agent fill cClassTrib. self.rtc_auto_apply_max_per_job = int(env.get("RTC_AUTO_APPLY_MAX_PER_JOB", str(_rtc_apply.DEFAULT_MAX_PER_JOB))) - self.agent_version = env.get("AGENT_VERSION", "1.2.2") + self.agent_version = env.get("AGENT_VERSION", "1.2.3") self.schema_fingerprint = env.get("SCHEMA_FINGERPRINT", REFERENCE_SCHEMA_V1) self.state_db = env.get("AGENT_STATE_DB", str(AGENT_ROOT / "agent_state.sqlite")) # Pilot write authorization: both must be explicitly set by the installer for @@ -348,7 +348,7 @@ def execute_job(job, config, executor, state, env): "fiscal_context": fiscal_context, "rtc_auto_apply": rtc_apply, "fiscal_mode": getattr(config, "fiscal_mode", None), - "release_version": env.get("AGENT_VERSION") or "1.2.2", + "release_version": env.get("AGENT_VERSION") or "1.2.3", "products_total": len(products), "products_changed": len(to_process), "products_processed": summary["processed"], @@ -506,7 +506,7 @@ def run(config, env, *, max_iterations=None, stopper=None): def enforce_startup_preflight(env): """Full read-only preflight at startup (Hub, auth, Firebird, capabilities, company context, guards). Fail closed.""" from gti_fiscal_agent.preflight import run_preflight - report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.2.2") + report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.2.3") logger.info("startup preflight: %s", json.dumps({k: report[k] for k in ("PREFLIGHT", "blockers", "fiscal_mode", "effective_firebird_writes")}, ensure_ascii=False)) print(json.dumps({"PREFLIGHT": report["PREFLIGHT"], "blockers": report["blockers"]}, ensure_ascii=False)) if report["PREFLIGHT"] != "PASS": diff --git a/agent/service/gti_agent_windows_service.py b/agent/service/gti_agent_windows_service.py index e1acbbf..a74bff6 100644 --- a/agent/service/gti_agent_windows_service.py +++ b/agent/service/gti_agent_windows_service.py @@ -81,7 +81,14 @@ if win32serviceutil is not None: servicemanager.LogErrorMsg("GTIFiscalAgent: startup preflight failed; see the agent log") win32event.SetEvent(self.stop_event) return - agent_service.run(config, os.environ, stopper=self.stop_flag) + try: + agent_service.run(config, os.environ, stopper=self.stop_flag) + except BaseException as error: # noqa: BLE001 - a dead loop must never look like a healthy "Running" service + import logging + logging.getLogger("gti_fiscal_agent").exception("fatal error in the Agent loop; stopping the service") + servicemanager.LogErrorMsg(f"GTIFiscalAgent: fatal error, stopping: {type(error).__name__}: {error}") + self.stop_flag.stop = True + win32event.SetEvent(self.stop_event) def main(): diff --git a/agent/src/gti_fiscal_agent/preflight.py b/agent/src/gti_fiscal_agent/preflight.py index b6991cf..d651936 100644 --- a/agent/src/gti_fiscal_agent/preflight.py +++ b/agent/src/gti_fiscal_agent/preflight.py @@ -9,7 +9,7 @@ import os import sqlite3 from pathlib import Path -AGENT_VERSION_DEFAULT = "1.2.2" +AGENT_VERSION_DEFAULT = "1.2.3" REQUIRED_ENV = ("GTI_HUB_URL", "AGENT_TOKEN", "FIREBIRD_DATABASE_PATH", "FB_USER", "FB_PASSWORD") REQUIRED_CAPABILITIES = ("supports_ncm", "supports_ipi", "supports_cest") FISCAL_MODES = ("DRY_RUN", "AUTO_APPLY") diff --git a/agent/tests/test_windows_service_host.py b/agent/tests/test_windows_service_host.py index 94a4d5d..f4b51a0 100644 --- a/agent/tests/test_windows_service_host.py +++ b/agent/tests/test_windows_service_host.py @@ -56,3 +56,10 @@ def test_main_preserves_pywin32_cli_commands(monkeypatch): service.main() assert called == [service.GTIFiscalAgentService] + + +def test_a_fatal_error_in_the_agent_loop_stops_the_service_instead_of_leaving_a_dead_one_running(): + text = SERVICE_WRAPPER.read_text(encoding="utf-8") + body = text.split("agent_service.run(config, os.environ, stopper=self.stop_flag)", 1)[1].split("def main", 1)[0] + assert "except BaseException" in body and "logger" not in body.split("except BaseException")[0][-40:] # wrapped in try/except + assert "LogErrorMsg" in body and "self.stop_flag.stop = True" in body and "win32event.SetEvent(self.stop_event)" in body diff --git a/central/app/version.py b/central/app/version.py index 96e0de5..9839bde 100644 --- a/central/app/version.py +++ b/central/app/version.py @@ -4,5 +4,5 @@ kept identical to this) and what an AgentRelease row's `version` column holds once published — never a second, independent version number. Fiscal semantics are versioned separately (ENGINE_VERSION/DECISION_VERSION in classification.py, DECISION_ENGINE_VERSION etc.) and are NOT changed by a release bump.""" -GTI_FISCAL_VERSION = "1.2.2" +GTI_FISCAL_VERSION = "1.2.3" API_COMPAT_MAJOR_MINOR = "1.0" # an Agent 1.0.x/1.1.x talks to any Hub 1.0.x diff --git a/central/pyproject.toml b/central/pyproject.toml index 5e97d75..0dc866a 100644 --- a/central/pyproject.toml +++ b/central/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "gti-fiscal-hub" -version = "1.2.2" +version = "1.2.3" requires-python = ">=3.10" dependencies = [ "fastapi>=0.115,<1", diff --git a/central/tests/test_health.py b/central/tests/test_health.py index 5f68fd8..99a3742 100644 --- a/central/tests/test_health.py +++ b/central/tests/test_health.py @@ -17,7 +17,7 @@ def test_health_is_unavailable_when_database_is_down(): def test_version_endpoint_reports_release_and_fiscal_versions(): body = TestClient(create_app(database_probe=lambda: True)).get("/version").json() - assert body["version"] == "1.2.2" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"] + assert body["version"] == "1.2.3" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"] def test_production_refuses_the_dev_token(monkeypatch): diff --git a/deploy/agent-windows/agent.env.template b/deploy/agent-windows/agent.env.template index 7082689..f3a8cc8 100644 --- a/deploy/agent-windows/agent.env.template +++ b/deploy/agent-windows/agent.env.template @@ -19,4 +19,4 @@ FB_PASSWORD= FISCAL_MODE=DRY_RUN FIREBIRD_WRITES=0 POLL_INTERVAL_SECONDS=5 -AGENT_VERSION=1.2.2 +AGENT_VERSION=1.2.3 diff --git a/deploy/agent-windows/gti-agent.ps1 b/deploy/agent-windows/gti-agent.ps1 index c820576..d03a5ad 100644 --- a/deploy/agent-windows/gti-agent.ps1 +++ b/deploy/agent-windows/gti-agent.ps1 @@ -164,7 +164,7 @@ switch ($Command) { "GTI_HUB_URL=$hub", "AGENT_TOKEN=$token", "AGENT_ID=$agentId", "COMPANY_CODE=$code", "COMPANY_CNPJ=$cnpj", "COMPANY_CRT_SOURCE=$crtSource", "FIREBIRD_DATABASE_PATH=$db", "FB_USER=$fbUser", "FB_PASSWORD=$fbPass", - 'FISCAL_MODE=DRY_RUN', 'FIREBIRD_WRITES=0', 'POLL_INTERVAL_SECONDS=5', 'AGENT_VERSION=1.2.2' + 'FISCAL_MODE=DRY_RUN', 'FIREBIRD_WRITES=0', 'POLL_INTERVAL_SECONDS=5', 'AGENT_VERSION=1.2.3' ) Set-Content -Path $EnvFile -Value $lines -Encoding UTF8 } diff --git a/deploy/agent-windows/pilot-construcao.env.example b/deploy/agent-windows/pilot-construcao.env.example index 84f75a4..6ecd525 100644 --- a/deploy/agent-windows/pilot-construcao.env.example +++ b/deploy/agent-windows/pilot-construcao.env.example @@ -19,4 +19,4 @@ FB_PASSWORD= FISCAL_MODE=DRY_RUN FIREBIRD_WRITES=0 POLL_INTERVAL_SECONDS=5 -AGENT_VERSION=1.2.2 +AGENT_VERSION=1.2.3 diff --git a/deploy/agent-windows/profiles/mmmodas.env.example b/deploy/agent-windows/profiles/mmmodas.env.example index 23d605c..825f5a1 100644 --- a/deploy/agent-windows/profiles/mmmodas.env.example +++ b/deploy/agent-windows/profiles/mmmodas.env.example @@ -19,4 +19,4 @@ FB_PASSWORD= FISCAL_MODE=DRY_RUN FIREBIRD_WRITES=0 POLL_INTERVAL_SECONDS=5 -AGENT_VERSION=1.2.2 +AGENT_VERSION=1.2.3 diff --git a/deploy/agent-windows/profiles/rincao.env.example b/deploy/agent-windows/profiles/rincao.env.example index 03fb3c0..82312fb 100644 --- a/deploy/agent-windows/profiles/rincao.env.example +++ b/deploy/agent-windows/profiles/rincao.env.example @@ -19,4 +19,4 @@ FB_PASSWORD= FISCAL_MODE=DRY_RUN FIREBIRD_WRITES=0 POLL_INTERVAL_SECONDS=5 -AGENT_VERSION=1.2.2 +AGENT_VERSION=1.2.3 diff --git a/deploy/agent-windows/profiles/uniao.env.example b/deploy/agent-windows/profiles/uniao.env.example index 00d531e..f345cd3 100644 --- a/deploy/agent-windows/profiles/uniao.env.example +++ b/deploy/agent-windows/profiles/uniao.env.example @@ -19,4 +19,4 @@ FB_PASSWORD= FISCAL_MODE=DRY_RUN FIREBIRD_WRITES=0 POLL_INTERVAL_SECONDS=5 -AGENT_VERSION=1.2.2 +AGENT_VERSION=1.2.3 diff --git a/deploy/hub/.env.example b/deploy/hub/.env.example index 8b30b7c..8dd5fdc 100644 --- a/deploy/hub/.env.example +++ b/deploy/hub/.env.example @@ -1,5 +1,5 @@ # GTI Fiscal Hub — production environment (copy to .env, never commit .env) -GTI_FISCAL_VERSION=1.2.2 +GTI_FISCAL_VERSION=1.2.3 # REQUIRED. URL-safe secret (used inside a connection URL): openssl rand -hex 24 POSTGRES_PASSWORD= diff --git a/deploy/hub/docker-compose.prod.yml b/deploy/hub/docker-compose.prod.yml index 5f48150..e1da566 100644 --- a/deploy/hub/docker-compose.prod.yml +++ b/deploy/hub/docker-compose.prod.yml @@ -36,7 +36,7 @@ services: build: context: ../.. dockerfile: central/Dockerfile - image: gti-fiscal-hub:${GTI_FISCAL_VERSION:-1.2.2} + image: gti-fiscal-hub:${GTI_FISCAL_VERSION:-1.2.3} restart: unless-stopped depends_on: postgres: diff --git a/docs/DEPLOY_HUB.md b/docs/DEPLOY_HUB.md index d6a23f9..e49f65e 100644 --- a/docs/DEPLOY_HUB.md +++ b/docs/DEPLOY_HUB.md @@ -16,7 +16,7 @@ A variável de ambiente `GTI_SSH_PASSWORD`, se existir, tem prioridade. A senha ## Deploy ``` powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1 -powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1 -PublishAgent -Version 1.2.2 +powershell -ExecutionPolicy Bypass -File .\scripts\deploy_hub.ps1 -PublishAgent -Version 1.2.3 ``` Parâmetros: `-Version` (padrão `release/VERSION`), `-PublishAgent`, `-SkipTests`, `-DryRun`. diff --git a/installer/install_common.py b/installer/install_common.py index 6d6c98b..4680074 100644 --- a/installer/install_common.py +++ b/installer/install_common.py @@ -333,3 +333,19 @@ def audit_event(agent_token: str, hub: str, event_type: str, message: str) -> No response.raise_for_status() except Exception: # noqa: BLE001 — best effort only return + + +def archive_stale_state(install: Path) -> list[str]: + """A NEW enrollment (fresh install with a code) means a NEW identity. A state database left behind by a previous installation (uninstall keeps local data) still carries + the old installation_id, which the Agent refuses to mix with the new credential: rename it aside (never delete) so the new installation starts clean.""" + moved = [] + stamp = time.strftime("%Y%m%d-%H%M%S") + for name in ("agent_state.sqlite", "agent_state.sqlite-wal", "agent_state.sqlite-shm", "agent_state.sqlite-journal"): + path = Path(install) / name + if path.exists(): + target = path.with_name(f"{name}.previous-{stamp}") + path.rename(target) + moved.append(target.name) + if moved: + ilog(f"archived state from a previous installation: {', '.join(moved)}") + return moved diff --git a/installer/setup_main.py b/installer/setup_main.py index 8918f3b..46bbe24 100644 --- a/installer/setup_main.py +++ b/installer/setup_main.py @@ -106,6 +106,7 @@ def install_flow(code: str, *, hub: str | None = None, install_dir_path: str | N progress("Instalando o serviço…") extract_payload(install) + common.archive_stale_state(install) started = heartbeat = False service_detail = "" diff --git a/release/RELEASE_MANIFEST.json b/release/RELEASE_MANIFEST.json index c6a60a4..ff77726 100644 --- a/release/RELEASE_MANIFEST.json +++ b/release/RELEASE_MANIFEST.json @@ -1,14 +1,14 @@ { "artifact": "RELEASE_MANIFEST", - "GTI_FISCAL_VERSION": "1.2.2", - "generated_at": "2026-09-25T14:59:09+00:00", + "GTI_FISCAL_VERSION": "1.2.3", + "generated_at": "2026-09-25T15:23:15+00:00", "hub": { - "version": "1.2.2", + "version": "1.2.3", "api_compat": "1.0", "engine_version": "0.3.0", "decision_version": "mission-04c-ipi-ex-split" }, - "agent_version": "1.2.2", + "agent_version": "1.2.3", "fiscal_engine": { "ENGINE_VERSION": "0.3.0", "DECISION_VERSION": "mission-04c-ipi-ex-split", diff --git a/release/VERSION b/release/VERSION index 23aa839..0495c4a 100644 --- a/release/VERSION +++ b/release/VERSION @@ -1 +1 @@ -1.2.2 +1.2.3 diff --git a/tests/test_release_candidate.py b/tests/test_release_candidate.py index bc13c7c..8c6ada9 100644 --- a/tests/test_release_candidate.py +++ b/tests/test_release_candidate.py @@ -14,11 +14,11 @@ sys.path.insert(0, str(ROOT)) def test_versions_are_coherent_across_hub_agent_and_packages(): from central.app.version import GTI_FISCAL_VERSION v = (ROOT / "release" / "VERSION").read_text(encoding="utf-8").strip() - assert v == GTI_FISCAL_VERSION == "1.2.2" + assert v == GTI_FISCAL_VERSION == "1.2.3" pep = v.replace("-rc", "rc") for pp in ("central/pyproject.toml", "agent/pyproject.toml"): assert f'version = "{pep}"' in (ROOT / pp).read_text(encoding="utf-8") - assert '"AGENT_VERSION", "1.2.2"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8") + assert '"AGENT_VERSION", "1.2.3"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8") manifest = ROOT / "release" / "RELEASE_MANIFEST.json" if manifest.exists(): m = json.loads(manifest.read_text(encoding="utf-8")) diff --git a/tests/test_zero_touch_installer.py b/tests/test_zero_touch_installer.py index cc43373..8b943d2 100644 --- a/tests/test_zero_touch_installer.py +++ b/tests/test_zero_touch_installer.py @@ -191,3 +191,28 @@ def test_failed_upgrade_step_restarts_the_existing_service(world, monkeypatch): with pytest.raises(RuntimeError, match="boom"): setup_main.upgrade_flow() assert ("start",) in calls # the Agent was brought back up despite the failure + + +def test_fresh_install_archives_a_state_database_left_by_a_previous_installation(tmp_path, monkeypatch): + """Uninstall keeps local data; a NEW enrollment must not inherit the old installation_id (the Agent refuses the mix and used to sit dead while 'Running').""" + monkeypatch.setenv("GTI_LOG_DIR", str(tmp_path / "logs")) + inst = tmp_path / "inst" + inst.mkdir() + (inst / "agent_state.sqlite").write_bytes(b"old identity") + (inst / "agent_state.sqlite-wal").write_bytes(b"wal") + moved = common.archive_stale_state(inst) + assert len(moved) == 2 and not (inst / "agent_state.sqlite").exists() + assert (inst / moved[0]).read_bytes() in (b"old identity", b"wal") # renamed aside, never deleted + assert common.archive_stale_state(inst) == [] # nothing left to archive + + +def test_install_flow_archives_stale_state_before_starting_the_service(world, monkeypatch): + calls, inst = world + one_db(monkeypatch) + inst.mkdir(parents=True) + (inst / "agent_state.sqlite").write_bytes(b"identity of a previous installation") + order = [] + monkeypatch.setattr(common, "archive_stale_state", lambda d: order.append("archive") or []) + monkeypatch.setattr(common, "start_and_verify", lambda *a, **k: order.append("start") or (True, "RUNNING")) + setup_main.install_flow("AAAA-BBBB-CCCC-DDDD") + assert order == ["archive", "start"]