From 2fe2a83004cb0946d2dec62021367df660070481 Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 12:26:16 +1000 Subject: [PATCH] =?UTF-8?q?fix(ext):=20=D0=91=D0=98=D0=9C-=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D1=8C=D0=BC=D0=B0=20=D0=BA=D0=B0=D1=87=D0=B0=D1=82=D1=8C?= =?UTF-8?q?=20=D0=BF=D0=BE=20filePath=20(guid=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D0=B0),=20=D0=BD=D0=B5=20=D0=BF=D0=BE=20guid=20=D1=83=D0=B7?= =?UTF-8?q?=D0=BB=D0=B0=20=D0=B4=D0=B5=D1=80=D0=B5=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Живой обход поймал: у БИМ-узла NormLegalDocPublished guid — это идентичность УЗЛА дерева, а скачивание идёт по ОТДЕЛЬНОМУ guid файла в поле filePath. pull_bim качал по guid узла → 403 Forbidden на все письма. Проверено вживую: download по filePath → PDF 3.96МБ, по guid узла → 403. Снапшот по-прежнему кладём под guid узла (стабильная идентичность письма для инкрементального дедупа), но GetFileContent зовём с filePath. Регресс-тест проверяет, что download зовётся с filePath, а не с node guid. Co-Authored-By: Claude Opus 4.8 (1M context) --- ext_pull.py | 11 ++++++++--- tests/test_ext_pull.py | 24 ++++++++++++++---------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/ext_pull.py b/ext_pull.py index 1e06e88..6496ad1 100644 --- a/ext_pull.py +++ b/ext_pull.py @@ -192,13 +192,18 @@ def pull_bim(refetch_all: bool = False) -> list[dict]: dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"] if not refetch_all and (dest_dir / "meta.json").exists(): continue # уже качали это письмо — не дёргаем гос-API повторно + file_guid = d.get("filePath") # у БИМ-узла guid — это ИДЕНТИЧНОСТЬ узла дерева, а скачивание + if not file_guid: # идёт по ОТДЕЛЬНОМУ guid файла (filePath). guid узла → 403. + failed += 1 + print(f" ✗ БИМ-письмо {d.get('name') or d['guid']}: нет filePath", file=sys.stderr) + continue try: with tempfile.TemporaryDirectory() as td: - tmp = Path(td) / _safe_name(Path(str(d.get("filePath") or "")).name, "letter.pdf") - fc.download_by_guid(d["guid"], tmp, expect_min_size=500) + tmp = Path(td) / "letter.pdf" # filePath — guid, не имя; письма-индексы это PDF + fc.download_by_guid(file_guid, tmp, expect_min_size=500) meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}", - url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}") + url=fc.BASE + f"/api/values/GetFileContent/{file_guid}") except ext_fetch.FetchError as e: # одно «ядовитое» письмо (удалено上游→HTML, битое) НЕ должно навсегда блокировать # хвост корпуса: инкрементальный skip иначе застревал бы на нём каждый прогон. diff --git a/tests/test_ext_pull.py b/tests/test_ext_pull.py index 49426c8..6eeecb7 100644 --- a/tests/test_ext_pull.py +++ b/tests/test_ext_pull.py @@ -64,26 +64,30 @@ def test_pull_salary_saves_json(monkeypatch, tmp_path): assert json.loads(snap.read_text())["items"][0]["code"] == "1-100-1" -def test_pull_bim_poison_letter_skipped_tail_downloaded(monkeypatch, tmp_path): - """Одно «ядовитое» письмо (FetchError) НЕ блокирует хвост: L2 качается, а частичный сбой - сигналится PartialPullError (несёт успехи) → ненулевой exit у CLI. Fable-фикс #2/(a).""" +def test_pull_bim_downloads_by_filepath_not_node_guid(monkeypatch, tmp_path): + """БИМ качается по filePath (guid ФАЙЛА), НЕ по guid УЗЛА дерева — тот даёт 403 (реальный баг, + пойман на живом обходе). Плюс: ядовитое письмо пропускается, хвост докачан, частичный сбой → + PartialPullError (exit 1). Ключ снапшота — по guid узла (стабильная идентичность письма).""" import ext_fetch monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path)) monkeypatch.setattr(fc, "bim_leaf_docs", lambda client=None: [ - {"guid": "L1", "name": "битое", "filePath": "/1.pdf"}, - {"guid": "L2", "name": "ок", "filePath": "/2.pdf"}]) + {"guid": "node1", "name": "битое", "filePath": "file1"}, + {"guid": "node2", "name": "ок", "filePath": "file2"}]) + called = [] def dl(guid, dest, client=None, expect_min_size=500): - if guid == "L1": - raise ext_fetch.FetchError("удалено上游 → HTML") + called.append(guid) + if guid == "file1": + raise ext_fetch.FetchError("403 Forbidden") Path(dest).write_bytes(b"PDF-" + b"z" * 600) return {"path": str(dest), "size": 604, "sha256": es.sha256_file(dest)} monkeypatch.setattr(fc, "download_by_guid", dl) import pytest with pytest.raises(ep.PartialPullError) as ei: ep.pull_bim() - assert [r["key"] for r in ei.value.results] == ["bim/L2"] # хвост докачан - assert (tmp_path / "snapshots/fgis/bim_letters/L2/meta.json").exists() - assert ep._drain(ep.pull_bim) == 1 # CLI видит ненулевой exit + assert set(called) == {"file1", "file2"} # по filePath, НЕ по node guid + assert [r["key"] for r in ei.value.results] == ["bim/node2"] # ключ по guid узла + assert (tmp_path / "snapshots/fgis/bim_letters/node2/meta.json").exists() + assert ep._drain(ep.pull_bim) == 1 # CLI видит ненулевой exit def test_solo_run_creates_missing_ext_dir(monkeypatch, tmp_path):