"""Every SQLite table the daemon creates has one transfer classification. A session move copies only the tables owner `transfer.gleam` modules declare. A new table that holds session or workspace rows but has no `transfer.Table` or `transfer.Excluded` declaration would silently stay behind on the source daemon. No end-to-end run installs and fills every owner's schema, so this reads the schema from the production Marmot snapshot, without a build or daemon. """ from __future__ import annotations import re import sqlite3 import unittest from contextlib import closing from functools import cache from pathlib import Path ROOT = Path(__file__).resolve().parents[2] # Albedo's own sources and each workspace package's, where the SDK lives. SOURCES = [ ROOT / "apps/albedo/src", *sorted(ROOT.glob("packages/*/src")), *sorted(ROOT.glob("extensions/*/src")), ] def gleam_sources() -> list[Path]: return sorted(path for root in SOURCES for path in root.rglob("*.gleam")) def schemas() -> set[str]: """Compare declarations with actual user tables, excluding SQLite internals.""" with closing(sqlite3.connect(":memory:")) as db: db.executescript((ROOT / "tools/marmot/schema.sql").read_text()) return { name for _, name, kind, *_ in db.execute("PRAGMA main.table_list") if kind == "table" and not name.startswith("sqlite_") } _TOKEN = re.compile( r'\s+|//[^\n]*|"(?:[^"\\]|\\.)*"|<>|\d+|[A-Za-z_][\w]*(?:/[A-Za-z_]\w*)*|.', re.S ) _TYPES = ROOT / "packages/albedo_sdk/src/albedo_sdk/transfer.gleam" def _tokens(source: str) -> list[str]: return [ token for token in _TOKEN.findall(source) if token.strip() and not token.startswith("//") ] def _imported(tokens: list[str]) -> set[str]: """Constructors `import albedo_sdk/transfer.{...}` brings in unqualified.""" names: set[str] = set() for index, token in enumerate(tokens): if token == "albedo_sdk/transfer" and tokens[index - 1] == "import": if tokens[index + 1 : index + 3] == [".", "{"]: at = index + 3 while tokens[at] != "}": if tokens[at] in ("Table", "Excluded") and tokens[at - 1] != "type": names.add(tokens[at]) at += 1 return names @cache def imported_string(module: str, name: str) -> str: path = next( root / f"{module}.gleam" for root in SOURCES if (root / f"{module}.gleam").is_file() ) reader = _Declarations(path) if name not in reader.consts: raise AssertionError(f"{module}.{name} is not a string constant") return reader.consts[name] class _Declarations: """Resolve literal and imported constants in transfer declarations.""" def __init__(self, path: Path): self.path = str(path.relative_to(ROOT)) self.tokens = _tokens(path.read_text()) self.consts: dict[str, str] = {} self.at = 0 self.modules = { module.rsplit("/", 1)[-1]: module for idx, module in enumerate(self.tokens) if idx and self.tokens[idx - 1] == "import" } starts = { self.tokens[index + 1]: index + 2 for index, token in enumerate(self.tokens) if token == "const" } # Passes until nothing new resolves: a const may name a later one. while True: resolved = len(self.consts) for name, start in starts.items(): self.at = start + 2 if self.tokens[start] == ":" else start if name in self.consts or self.tokens[self.at] != "=": continue self.at += 1 try: self.consts[name] = self._string() except AssertionError: continue if len(self.consts) == resolved: break def _fail(self, wanted: str) -> AssertionError: found = " ".join(self.tokens[self.at : self.at + 6]) return AssertionError(f"{self.path}: expected {wanted}, found {found!r}") def _take(self, token: str) -> None: if self.tokens[self.at] != token: raise self._fail(repr(token)) self.at += 1 def _string(self) -> str: parts = [] while True: token = self.tokens[self.at] if token.startswith('"'): parts.append(token[1:-1].replace('\\"', '"').replace("\\\\", "\\")) elif token in self.modules and self.tokens[self.at + 1] == ".": parts.append( imported_string(self.modules[token], self.tokens[self.at + 2]) ) self.at += 2 elif token in self.consts: parts.append(self.consts[token]) else: raise self._fail("a string literal or string constant") self.at += 1 if self.tokens[self.at : self.at + 1] != ["<>"]: return "".join(parts) self.at += 1 def _label(self, name: str) -> None: if self.tokens[self.at] == name and self.tokens[self.at + 1] == ":": self.at += 2 def _argument(self, name: str, read): self._label(name) value = read() if self.tokens[self.at] == ",": self.at += 1 return value def _int(self) -> int: token = self.tokens[self.at] if not token.isdigit(): raise self._fail("an int literal") self.at += 1 return int(token) def calls(self): unqualified = _imported(self.tokens) for index, token in enumerate(self.tokens): if token not in ("Table", "Excluded") or self.tokens[index + 1] != "(": continue qualified = self.tokens[index - 2 : index] == ["transfer", "."] if not qualified and token not in unqualified: raise AssertionError( f"{self.path}: {token}( is not albedo_sdk/transfer's" ) self.at = index + 2 if token == "Table": entry = ( self._argument("name", self._string), self._argument("version", self._int), self._argument("filter_sql", self._string), ) else: entry = ( self._argument("name", self._string), self._argument("reason", self._string), ) self._take(")") yield token, entry def declarations() -> tuple[dict[str, list], dict[str, list]]: tables: dict[str, list] = {} excluded: dict[str, list] = {} for path in gleam_sources(): if path == _TYPES: continue if path.name != "transfer.gleam": tokens = _tokens(path.read_text()) built = any( tokens[index : index + 3] == ["transfer", "."] + [name] and tokens[index + 3 : index + 4] == ["("] for index in range(len(tokens)) for name in ("Table", "Excluded") ) if built or _imported(tokens): raise AssertionError( f"{path.relative_to(ROOT)} declares transfer tables outside a transfer.gleam" ) continue reader = _Declarations(path) for kind, entry in reader.calls(): if kind == "Table": name, version, filter_sql = entry tables.setdefault(name, []).append((version, filter_sql, reader.path)) else: excluded.setdefault(entry[0], []).append((entry[1], reader.path)) return tables, excluded class TransferCoverageTest(unittest.TestCase): def test_every_table_is_declared_once(self): schema = schemas() tables, excluded = declarations() declared = list(tables) + list(excluded) twice = sorted( name for name in set(declared) if len(tables.get(name, [])) + len(excluded.get(name, [])) > 1 ) self.assertEqual(twice, [], "tables declared more than once") missing = sorted(set(schema) - set(declared)) self.assertEqual( missing, [], "tables with no transfer.Table or transfer.Excluded" ) unknown = sorted(set(declared) - set(schema)) self.assertEqual( unknown, [], "transfer declarations for tables nothing creates" ) def test_filters_are_scoped(self): tables, _ = declarations() for name, entries in tables.items(): _, filter_sql, source = entries[0] with self.subTest(table=name, source=source): self.assertRegex(filter_sql, r"\btransfer_(?:scope|workspace)\b") self.assertNotRegex(filter_sql, r"'[0-9a-f]{8,}'", "literal ids") def test_reasons_are_given(self): _, excluded = declarations() for name, entries in excluded.items(): self.assertTrue( entries[0][0].strip(), f"{name} is excluded without a reason" ) if __name__ == "__main__": unittest.main()