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 <noreply@anthropic.com>
This commit is contained in:
gti
2026-09-25 12:25:53 -03:00
co-authored by Claude Sonnet 5
parent 2e5598ce9c
commit 6f0f072d84
23 changed files with 81 additions and 25 deletions
+1 -1
View File
@@ -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"]
+3 -3
View File
@@ -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":
+8 -1
View File
@@ -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():
+1 -1
View File
@@ -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")
+7
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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",
+1 -1
View File
@@ -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):
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
}
@@ -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
@@ -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
@@ -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
@@ -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
+1 -1
View File
@@ -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=
+1 -1
View File
@@ -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:
+1 -1
View File
@@ -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`.
+16
View File
@@ -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
+1
View File
@@ -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 = ""
+4 -4
View File
@@ -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",
+1 -1
View File
@@ -1 +1 @@
1.2.2
1.2.3
+2 -2
View File
@@ -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"))
+25
View File
@@ -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"]