Skip to content
107 changes: 75 additions & 32 deletions src/localizer/adapters/storage/sqlite_tm.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from __future__ import annotations

import json
import sqlite3
from contextlib import contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from hashlib import sha256
from pathlib import Path, PurePosixPath
from typing import Iterable, Iterator, Optional, Sequence, Tuple
from typing import Iterable, Iterator, Mapping, Optional, Sequence, Tuple


SCHEMA_VERSION = 2
Expand Down Expand Up @@ -391,55 +392,97 @@ def retire_human_entries(self, identities: Sequence[str]) -> int:
)
return cursor.rowcount

@staticmethod
def row_revision_token(row: Mapping[str, object]) -> str:
"""Stable token for a full TM row before-image, independent of column order."""
encoded = json.dumps(
dict(row), sort_keys=True, ensure_ascii=False, separators=(",", ":")
).encode("utf-8")
return sha256(encoded).hexdigest()

def retire_stale_formal_entries(
self,
entries: Sequence[TMEntry],
*,
expected_identities: Optional[Sequence[str]] = None,
expected_rows: Optional[Mapping[str, str]] = None,
) -> int:
"""归档并删除源文指纹已变化的 formal,让当前资源接管坐标。
"""Retire only genuinely stale formal rows, archiving exact source history.

调用方必须先向操作者展示候选并取得明确确认。删除条件在同一事务里
重新校验 ``is_formal`` 和旧指纹,避免预览后 TM 发生变化时误删新结果。

旧 formal 会按 ``(stable_identity, source_fingerprint)`` 保存到精确历史层。
这样正式服/测试服或其他并行源在同一坐标上往返时,回到旧源文可以直接
命中当时已经验证过的译文,而不是把“最后执行的源”误当成唯一基线。
The same historical-exact eligibility rule as preflight is rechecked
under BEGIN IMMEDIATE. Dashboard confirmations can additionally bind
each approved identity to the complete preflight row before-image.
A mismatch rolls back both the source-history archive and the deletion.
"""
candidates = {
entry.stable_identity: entry.source_fingerprint
for entry in entries
if entry.stable_identity and entry.source_fingerprint
}
if not candidates:
return 0
removed = 0
candidates: dict[str, TMEntry] = {}
for entry in entries:
if not entry.stable_identity or not entry.source_fingerprint:
continue
previous = candidates.get(entry.stable_identity)
if (
previous is not None
and previous.source_fingerprint != entry.source_fingerprint
):
raise TMGuardError(
f"conflicting source fingerprints for {entry.stable_identity}"
)
candidates[entry.stable_identity] = entry

expected = (
{str(value) for value in expected_identities if value}
if expected_identities is not None
else None
)
if expected_rows is not None:
if expected is None or set(expected_rows) != expected:
raise TMGuardError("stale formal before-images do not match approved identities")

now = datetime.now(timezone.utc).isoformat()
with self.transaction() as connection:
for identity, current_fingerprint in candidates.items():
row = connection.execute(
"SELECT * FROM tm_entries WHERE stable_identity = ? "
"AND is_formal = 1 AND source_fingerprint <> ?",
(identity, current_fingerprint),
).fetchone()
# Reuse the exact preview predicate *inside* the write transaction;
# a reusable historical source must never be retired.
# Retirement arguments describe the *requested source*, not the
# authority of the current stored row. Callers may pass a future
# formal TMEntry (existing API/tests); normalize only for the
# eligibility query, keeping the preflight predicate unchanged.
requested = tuple(
replace(entry, is_formal=False) for entry in candidates.values()
)
eligible = set(self.stale_formal_identities(requested))
if expected is not None and eligible != expected:
raise RuntimeError(
"stale formal candidates changed during retirement: "
f"eligible {len(eligible)}/{len(expected)}; transaction rolled back"
)

rows = self.rows_for(sorted(eligible))
for identity in sorted(eligible):
row = rows.get(identity)
if row is None:
continue
raise RuntimeError(
f"stale formal row disappeared: {identity}; transaction rolled back"
)
if expected_rows is not None and (
self.row_revision_token(row) != expected_rows[identity]
):
raise RuntimeError(
f"stale formal row changed since confirmation: {identity}; "
"transaction rolled back; run preflight again"
)

self._archive_formal_row(connection, row, now)
cursor = connection.execute(
"DELETE FROM tm_entries "
"WHERE stable_identity = ? AND is_formal = 1 "
"AND source_fingerprint <> ?",
(identity, current_fingerprint),
"AND source_fingerprint = ?",
(identity, row["source_fingerprint"]),
)
removed += cursor.rowcount
if expected_identities is not None:
expected = {str(value) for value in expected_identities if value}
if removed != len(expected):
if cursor.rowcount != 1:
raise RuntimeError(
f"stale formal candidates changed during retirement: "
f"removed {removed}/{len(expected)}; transaction rolled back"
f"stale formal row changed during retirement: {identity}; "
"transaction rolled back"
)
return removed
return len(eligible)

def restore_rows(self, snapshots: Sequence[dict]) -> int:
"""撤销专用:按前像还原。快照的 `row` 为 None 表示当时这个坐标没有行。
Expand Down
9 changes: 8 additions & 1 deletion src/localizer/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,14 @@ def review_retire(
finally:
destination.close()
result["backup"] = str(backup_path)
result["removed"] = tm.retire_stale_formal_entries(candidates)
result["removed"] = tm.retire_stale_formal_entries(
[entry for entry in candidates if entry.stable_identity in identities],
expected_identities=identities,
expected_rows={
identity: tm.row_revision_token(rows[identity])
for identity in identities
},
)
result["applied"] = True
typer.echo(json.dumps(result, ensure_ascii=False, indent=2))

Expand Down
32 changes: 26 additions & 6 deletions src/localizer/web/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,22 +330,41 @@ def confirm_stale(self, payload: Mapping[str, Any]) -> dict:
"configuration changed; run preflight again"
)
preview = self._stale_formal_preview(config, plan)
expected = set(
(previous.get("confirmation") or {}).get("identities") or ()
) if run_id else set(
(preflight.get("stale_formal") or {}).get("identities") or ()
confirmation = (
previous.get("confirmation") or {}
if run_id
else preflight.get("stale_formal") or {}
)
expected = set(confirmation.get("identities") or ())
actual = set(preview["identities"])
if expected and actual != expected:
# Even an empty expected set must not authorize newly observed rows.
if actual != expected:
raise ValueError("stale formal candidates changed; inspect and confirm again")

approved_rows = {
item["stable_identity"]: item["old_row_token"]
for item in confirmation.get("entries") or ()
if item.get("stable_identity") and item.get("old_row_token")
}
if set(approved_rows) != expected:
raise ValueError(
"stale formal confirmation has no complete TM row snapshot; "
"run a new preflight and confirm again"
)

backup_path = None
removed = 0
if actual:
approved_entries = [
entry for entry in self._plan_entries(plan)
if entry.stable_identity in actual
]
backup_path = self._backup_tm(config, run_id or preflight_id)
with SQLiteTranslationMemory(config.tm.database) as tm:
removed = tm.retire_stale_formal_entries(
self._plan_entries(plan), expected_identities=actual
approved_entries,
expected_identities=actual,
expected_rows=approved_rows,
)

audit = {
Expand Down Expand Up @@ -463,6 +482,7 @@ def _stale_formal_preview(self, config: ProjectConfig, plan) -> dict:
"old_source": old.get("source_text"),
"new_source": new.source_text,
"old_translation": old.get("translation"),
"old_row_token": SQLiteTranslationMemory.row_revision_token(old),
}
)
return {
Expand Down
141 changes: 141 additions & 0 deletions tests/test_task_identity_and_resume.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@
"""
from __future__ import annotations

import io
import json
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from dataclasses import replace
from hashlib import sha256
from pathlib import Path
from types import SimpleNamespace
Expand Down Expand Up @@ -321,6 +324,144 @@ def plan(self):
self.assertNotIn(unit.stable_identity, tm.rows_for([unit.stable_identity]))


def _mixed_stale_and_history(self):
"""Synthetic plan: one new fingerprint and one valid sibling history hit."""
config = _config(self.root)
a = TranslationUnit(
project_id="game", adapter_id="gettext",
relative_path="gui/menu.mo", logical_key="a", source_text="a-new",
source_locale="ru-RU", target_locale="zh-Hans",
)
b = TranslationUnit(
project_id="game", adapter_id="gettext",
relative_path="gui/menu.mo", logical_key="b", source_text="b-history",
source_locale="ru-RU", target_locale="zh-Hans",
)

def formal(unit, source, translation):
return TMEntry(
stable_identity=unit.stable_identity, project_id="game",
adapter_id="gettext", relative_path="gui/menu.mo",
logical_key=unit.logical_key, source_text=source,
source_fingerprint=sha256(source.encode("utf-8")).hexdigest(),
translation=translation, origin="machine",
review_state="unreviewed", match_scope="coordinate_exact",
quality_state="passed", is_formal=True,
)

old_a = formal(a, "a-old", "A old")
history_b = formal(b, "b-history", "B history")
current_b = formal(b, "b-current", "B current")
with SQLiteTranslationMemory(config.tm.database) as tm:
tm.upsert(old_a)
tm.upsert(history_b)
tm.retire_stale_formal_entries(
[current_b], expected_identities=[b.stable_identity]
)
tm.upsert(current_b)

plan = SimpleNamespace(
fingerprint="mixed-plan",
resources=(SimpleNamespace(units=(a, b)),),
as_dict=lambda: {
"plan_fingerprint": "mixed-plan", "files_total": 1,
"files_pending": 1, "extracted_units": 2, "tm_hits": 1,
"embedded_translations": 0, "pending_units": 1,
"filtered_units": 0, "by_match_scope": {}, "files": [],
},
)

class Runner:
def __init__(self, _config):
pass

def plan(self):
return plan

service = TaskService(config, runner_factory=Runner)
self.addCleanup(service.shutdown)
return config, a, b, old_a, current_b, plan, service

def test_web_confirm_mixed_stale_and_exact_history(self) -> None:
config, a, b, old_a, current_b, _plan, service = self._mixed_stale_and_history()
preflight = service.preflight({
"version": "1", "source_path": str(self.root / "game"), "mode": "preview"
})
self.assertEqual([a.stable_identity], preflight["stale_formal"]["identities"])
self.assertIn("old_row_token", preflight["stale_formal"]["entries"][0])
response = service.confirm_stale({"preflight_id": preflight["preflight_id"]})
self.assertEqual(1, response["removed"])
with SQLiteTranslationMemory(config.tm.database) as tm:
rows = tm.rows_for([a.stable_identity, b.stable_identity])
self.assertNotIn(a.stable_identity, rows)
self.assertEqual(
current_b.source_fingerprint, rows[b.stable_identity]["source_fingerprint"]
)
self.assertEqual(
"B history",
tm.lookup(
b.stable_identity,
source_fingerprint=sha256(b"b-history").hexdigest(),
).translation,
)

def test_web_confirm_refuses_changed_row_after_preflight(self) -> None:
config, a, b, old_a, _current_b, _plan, service = self._mixed_stale_and_history()
preflight = service.preflight({
"version": "1", "source_path": str(self.root / "game"), "mode": "preview"
})
with SQLiteTranslationMemory(config.tm.database) as tm:
tm.upsert(replace(old_a, translation="later edit"))
with self.assertRaisesRegex(RuntimeError, "changed since confirmation"):
service.confirm_stale({"preflight_id": preflight["preflight_id"]})
with SQLiteTranslationMemory(config.tm.database) as tm:
self.assertEqual(
"later edit", tm.rows_for([a.stable_identity])[a.stable_identity][
"translation"
]
)

def test_web_old_confirmation_requires_new_preflight(self) -> None:
_config, a, _b, _old_a, _current_b, _plan, service = (
self._mixed_stale_and_history()
)
preflight = service.preflight({
"version": "1", "source_path": str(self.root / "game"), "mode": "preview"
})
service._preflights[preflight["preflight_id"]]["stale_formal"]["entries"][0].pop(
"old_row_token"
)
with self.assertRaisesRegex(ValueError, "run a new preflight"):
service.confirm_stale({"preflight_id": preflight["preflight_id"]})

def test_cli_apply_uses_previewed_subset(self) -> None:
from localizer.cli.main import review_retire

config, a, b, _old_a, current_b, plan, _service = (
self._mixed_stale_and_history()
)
output = io.StringIO()
with mock.patch(
"localizer.cli.main.load_project_config", return_value=config
), mock.patch("localizer.cli.main.ProjectRunner") as runner:
runner.return_value.plan.return_value = plan
with redirect_stdout(output):
review_retire(
Path("synthetic.yaml"), stale=True, variant=None,
apply=True, backup=self.root / "cli-tm-backup.sqlite",
)
report = json.loads(output.getvalue())
self.assertEqual(1, report["stale_formal"])
self.assertEqual(1, report["removed"])
self.assertTrue(Path(report["backup"]).is_file())
with SQLiteTranslationMemory(config.tm.database) as tm:
rows = tm.rows_for([a.stable_identity, b.stable_identity])
self.assertNotIn(a.stable_identity, rows)
self.assertEqual(
current_b.source_fingerprint, rows[b.stable_identity]["source_fingerprint"]
)


class ResumeGateTests(_Case):
"""R15:中断态的运行必须能复用自己的 checkpoint。"""

Expand Down
Loading
Loading