Merge tea/parity into P3.5 (ingest-memory, gate wait)

This commit is contained in:
2026-11-28 16:32:11 -06:00
7 changed files with 88 additions and 17 deletions
+45 -10
View File
@@ -4,6 +4,9 @@ reference, never the content; `read` and the analyses fetch the content by hash,
catalog `file` field holds the hash in silver."""
import hashlib
import tempfile
from collections.abc import Callable, Iterable
from pathlib import Path
import dlt
from sqlalchemy import LargeBinary, Text, inspect, text
@@ -13,6 +16,7 @@ from persistance.destination import engine, platform
TABLE = "files"
COLUMNS = {"key": {"data_type": "text"}, "content": {"data_type": "binary"}}
BATCH_BYTES = 64 * 1024**2 # files written per load: bounds what one load holds in memory
def key(content: bytes) -> str:
@@ -21,23 +25,34 @@ def key(content: bytes) -> str:
class Collector:
"""A dlt map that replaces each binary value of a row with its hash, keeping the
content to store once the load is done (`keep`)."""
content to store once the load is done (`keep`). Contents wait on disk, not in memory: a
source of EEG signals carries gigabytes."""
def __init__(self):
self.found: dict[str, bytes] = {}
self._dir = tempfile.TemporaryDirectory(prefix="files-")
self.found: dict[str, Path] = {}
def __call__(self, row: dict) -> dict:
out = {}
for name, value in row.items():
if isinstance(value, bytes | bytearray | memoryview):
value = bytes(value)
self.found[found := key(value)] = value
found = key(value)
if found not in self.found:
path = Path(self._dir.name) / found
path.write_bytes(value)
self.found[found] = path
value = found
out[name] = value
return out
def keep(self) -> None:
keep(self.found)
try:
_store({k: p.read_bytes for k, p in self.found.items()})
finally:
self.close()
def close(self) -> None:
self._dir.cleanup()
def reference_type(sql_type: TypeEngine) -> TypeEngine:
@@ -57,11 +72,31 @@ def known(keys: set[str]) -> set[str]:
def keep(contents: dict[str, bytes]) -> None:
"""Contents by hash, each written once."""
new = [{"key": k, "content": c} for k, c in contents.items() if k not in known(set(contents))]
if new:
resource = dlt.resource(new, name=TABLE, primary_key="key", columns=COLUMNS,
write_disposition="merge") # fmt: skip
dlt.pipeline(TABLE, destination=platform(), dataset_name="bronze").run(resource)
_store({k: (lambda c=c: c) for k, c in contents.items()})
def _store(contents: dict[str, Callable[[], bytes]]) -> None:
"""The contents (each read only when its batch is written) the platform does not keep
yet, in loads of about BATCH_BYTES each."""
already = known(set(contents))
batch, size = [], 0
for k, read in contents.items():
if k in already:
continue
data = read()
batch.append({"key": k, "content": data})
size += len(data)
if size >= BATCH_BYTES:
_load(batch)
batch, size = [], 0
if batch:
_load(batch)
def _load(rows: Iterable[dict]) -> None:
resource = dlt.resource(list(rows), name=TABLE, primary_key="key", columns=COLUMNS,
write_disposition="merge") # fmt: skip
dlt.pipeline(TABLE, destination=platform(), dataset_name="bronze").run(resource)
def content(key: str) -> bytes | None:
+5 -2
View File
@@ -76,8 +76,11 @@ def run_source(pipeline_id: str, node: Source):
made.apply_hints(primary_key=node.primary_key)
keyed = any(c.get("primary_key") for c in made.compute_table_schema()["columns"].values())
made.apply_hints(write_disposition="merge" if keyed else "replace")
loaded = _pipeline(table(pipeline_id, node.id)).run(made)
collected.keep()
try:
loaded = _pipeline(table(pipeline_id, node.id)).run(made)
collected.keep()
finally:
collected.close()
return loaded
+1 -1
Submodule WebApi updated: 70c9506b97...2131ff60a5
+1 -1
Submodule WebApp updated: b3e5a69783...38ece960f9
+1 -1
Submodule models updated: 3950b3c1f5...c6c55e0ffe
+4 -2
View File
@@ -146,7 +146,8 @@
"ord_pac_id",
"ord_tipo_estudio",
"ord_pdf_blob"
]
],
"chunk_size": 4
}
},
{
@@ -313,7 +314,8 @@
"eeg_fecha_estudio",
"eeg_id_registro_laboratorio",
"eeg_estudio"
]
],
"chunk_size": 4
}
},
{
+31
View File
@@ -0,0 +1,31 @@
import hashlib
import sys
def test_collected_files_wait_on_disk_and_are_kept_in_batches(fresh_platform):
"""A source's binary values wait on disk (not in memory) until the load is done, then go
to bronze.files in loads of about BATCH_BYTES, once each; the waiting folder is removed."""
fresh_platform.run(
sys.executable,
"-c",
"""
from pathlib import Path
from persistance import files
files.BATCH_BYTES = 10 # every file is its own load
collected = files.Collector()
rows = [collected({"id": i, "blob": bytes([i]) * 20}) for i in range(3)]
rows.append(collected({"id": 9, "blob": memoryview(bytes([0]) * 20)})) # same content as id 0
assert all(isinstance(r["blob"], str) for r in rows)
assert all(isinstance(p, Path) and p.exists() for p in collected.found.values())
assert len(collected.found) == 3
folder = next(iter(collected.found.values())).parent
collected.keep()
assert not folder.exists()
files.keep({files.key(bytes([1]) * 20): bytes([1]) * 20}) # already kept: written once
""",
)
expected = sorted(hashlib.sha256(bytes([i]) * 20).hexdigest() for i in range(3))
assert [k for (k,) in fresh_platform.query("select key from bronze.files order by key")] == (
expected
)