Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
05a0f0c
polis-topic-names: one model call that names a run's topics, every fa…
colinmegill Nov 24, 2026
99e6bab
jobs: the child passes --namer to a full run only when its configurat…
colinmegill Nov 24, 2026
35c349b
delphi: a run given a namer names its topics in one call, or keeps it…
colinmegill Nov 24, 2026
0086330
delphi image: build and carry polis-topic-names beside polis-topic-map
colinmegill Nov 24, 2026
712d558
jobs: child.rs keeps the workspace's rustfmt (edition 2024) import order
colinmegill Nov 24, 2026
4dadd30
Merge topic-names/model-client into topic-names/naming-step
colinmegill Nov 24, 2026
189b777
delphi shadow: a run can name a finished keyword run's topics (names_…
colinmegill Nov 24, 2026
35a70c6
delphi: a test of one conversation's keyword run and its Haiku and So…
colinmegill Nov 24, 2026
ef88c15
polis-topic-names: the independent review's small corrections
colinmegill Nov 24, 2026
ffd9ccb
delphi: a scratch-file failure in the naming step keeps the keyword l…
colinmegill Nov 24, 2026
02e5b25
polis-topic-names: nothing a reply holds reaches names.json or the lo…
colinmegill Nov 24, 2026
20e21e8
delphi: the naming step's record and its names always agree, and its …
colinmegill Nov 24, 2026
78c3778
Merge topic-names/model-client into topic-names/naming-step
colinmegill Nov 24, 2026
70e2133
Merge topic-names/naming-step into topic-names/names-of
colinmegill Nov 24, 2026
29467f1
delphi: the named-run tests read each run's record from the pipe and …
colinmegill Nov 24, 2026
98be5df
delphi: a names file that cannot be read has the scratch reason, and …
colinmegill Nov 24, 2026
17885cc
delphi: the naming tests find their queue-rs inputs in the Delphi tes…
colinmegill Nov 24, 2026
3db643b
delphi: a naming record that does not arrive fails the run, and a sto…
colinmegill Nov 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions .github/workflows/queue-rs-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ name: queue-rs

# Build, lint and test the queue-rs workspace: the polis-queue/1 adapter and
# the polis-jobs daemon (job `queue-rs`), the polis-api route server with
# its nginx routing switch (job `polis-api`), and the topic map generator
# (job `polis-topic-map`). The integration tests run against a throwaway
# PostgreSQL 17 service container with the repository's migration chain,
# 000023 (the Delphi job table) included.
# its nginx routing switch (job `polis-api`), the topic map generator
# (job `polis-topic-map`) and the topic namer (job `polis-topic-names`). The
# integration tests run against a throwaway PostgreSQL 17 service container
# with the repository's migration chain, 000023 (the Delphi job table) included.
on:
pull_request:
paths:
Expand Down Expand Up @@ -241,6 +241,16 @@ jobs:
persist-credentials: false
- name: Run polis-topic-map checks
run: make check-polis-topic-map
polis-topic-names:
name: topic namer build, clippy and offline tests
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Run polis-topic-names checks
run: make check-polis-topic-names
job-graphs:
name: Per-step job graph core
runs-on: ubuntu-24.04
Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,10 @@ check-polis-migrate: ## Run polis-migrate checks
check-polis-topic-map: ## Run the topic map generator's checks
@bash ci/local/polis-topic-map.sh

.PHONY: check-polis-topic-names
check-polis-topic-names: ## Run the topic namer's checks (offline, no model call)
@bash ci/local/polis-topic-names.sh

.PHONY: check-job-graphs
check-job-graphs: ## Run job-graphs checks
@bash ci/local/job-graphs.sh
Expand Down
7 changes: 5 additions & 2 deletions ci/local/delphi-python.sh
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,8 @@ fi
# input is present under /app/projgate. Recordings tests also load the packer
# and its digest helper from ci/; representative payload tests import the box
# planner/gate and their helpers from this same root; light-shadow triage tests
# import the compare/triage modules.
# import the compare/triage modules; the topic naming tests read the topic map's
# Bowling Green layout and a saved Sonnet reply from queue-rs.
compose exec -T delphi mkdir -p /app/projgate
# Iterate a captured list: `docker compose exec` inside a while-read loop drains
# the piped stdin and truncates the list.
Expand All @@ -243,7 +244,9 @@ for rel in $inputs \
ci/private_cert/image_admission.py ci/probe_box/receipt.py \
ci/probe_box/contracts.py ci/probe_box/light_shadow.py ci/probe_box/light_shadow_queries.py \
ci/private_cert/images/light_shadow_compare.py ci/private_cert/images/light_shadow_triage.py \
ci/private_cert/images/recipe.py scripts/run-import-dry-run.py; do
ci/private_cert/images/recipe.py scripts/run-import-dry-run.py \
queue-rs/polis-topic-map/tests/fixtures/bg2050/proximity.json \
queue-rs/polis-topic-names/tests/fixtures/replies/bg2050/sonnet-default-r1.json; do
compose exec -T delphi mkdir -p "/app/projgate/$(dirname "$rel")" </dev/null
compose cp "$rel" "delphi:/app/projgate/$rel" </dev/null || die "failed to copy scan input: $rel"
done
Expand Down
12 changes: 12 additions & 0 deletions ci/local/polis-topic-names.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
. "$(dirname "$0")/runtime.sh"

(
cd "$CHECK_ROOT/queue-rs"
rustup show active-toolchain
cargo fmt -p polis-topic-names --check
cargo clippy --locked -p polis-topic-names --all-targets -- -D warnings
# Every test is offline: the model call goes to a local HTTP stub, and the
# saved replies of the public fixtures in polis-topic-names/tests/fixtures.
cargo test --locked -p polis-topic-names
)
13 changes: 10 additions & 3 deletions delphi/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ COPY --from=queue-rs . .
# polis-topic-map, the topic map's generator, is built beside them: a run
# whose daemon sets DELPHI_TOPIC_MAP_DOCUMENT=1 calls it to store its map
# (polismath/delphi_storage/topic_map.py); `polis-topic-map from-run` makes
# the map of a run stored before that.
# the map of a run stored before that. polis-topic-names, the topic namer,
# is built beside them too: a run given --namer calls it to name its topics
# (umap_narrative/topic_namer.py).
RUN --mount=type=cache,target=/src/target,id=delphi-polis-jobs-target \
cargo build --release --locked -p polis-queue-adapter -p polis-topic-map \
--bin polis-jobs --bin polis-delphi-shadow --bin polis-topic-map \
cargo build --release --locked -p polis-queue-adapter -p polis-topic-map -p polis-topic-names \
--bin polis-jobs --bin polis-delphi-shadow --bin polis-topic-map --bin polis-topic-names \
&& cp target/release/polis-jobs /polis-jobs \
&& cp target/release/polis-delphi-shadow /polis-delphi-shadow \
&& cp target/release/polis-topic-map /polis-topic-map \
&& cp target/release/polis-topic-names /polis-topic-names \
&& test -x /polis-topic-names \
&& /polis-jobs --version && /polis-delphi-shadow --version \
&& /polis-topic-map 2>&1 | grep -q "polis-topic-map store"

Expand Down Expand Up @@ -168,6 +172,9 @@ COPY --from=polis-jobs /polis-delphi-shadow /usr/local/bin/polis-delphi-shadow
# The topic map's generator. Nothing runs it unless a run's daemon sets
# DELPHI_TOPIC_MAP_DOCUMENT=1.
COPY --from=polis-jobs /polis-topic-map /usr/local/bin/polis-topic-map
# The topic namer. Nothing runs it unless a run is given --namer, and no
# admission gives one yet.
COPY --from=polis-jobs /polis-topic-names /usr/local/bin/polis-topic-names

# Copy source code from builder stage (already built into the package)
COPY --from=builder /app/polismath/ ./polismath/
Expand Down
30 changes: 27 additions & 3 deletions delphi/polismath/job_child/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,35 @@ def topic_model_name() -> Optional[str]:
or "claude-haiku-4-5-20251001")


def full_pipeline_models() -> Dict[str, Any]:
def named_topic_model(naming: Dict[str, Any]) -> str:
"""The topic model of a run whose job named a namer, from how its naming
ended (umap_narrative/topic_namer.py's record): the model when it named
the topics, else ``keywords``: a run that kept its keyword labels is
never recorded under the model it asked for."""
namer = naming.get("namer") if isinstance(naming, dict) else None
if naming.get("outcome") == "named" and isinstance(namer, dict) and isinstance(namer.get("model"), str):
return namer["model"]
return "keywords"


def naming_cost(naming: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""The manifest's cost of a full run. Without a namer it is today's
(unknown: the provider batches are not observed). With one, the tokens
the naming's one call used, when it was answered."""
def count(key):
value = naming.get(key) if isinstance(naming, dict) else None
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None

return {"llm_tokens_in": count("tokens_in"), "llm_tokens_out": count("tokens_out"),
"provider_batches": None}


def full_pipeline_models(naming: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""The models of a full pipeline run, as its output manifest names them:
run_delphi.py writes this into the manifest, and the topic map step
(polismath/delphi_storage/topic_map.py) into the map's provenance, so the
two never disagree."""
two never disagree. ``naming`` is how a run whose job named a namer ended
its naming (None for every other run, whose models are what they were)."""
from polismath import embedding_model
# The clustering run_pipeline.py runs: UMAP and EVoC from the default seed.
from umap_narrative.numerical_stages import CLUSTER_MODEL, DEFAULT_SEED
Expand All @@ -366,7 +390,7 @@ def full_pipeline_models() -> Dict[str, Any]:
# The model run_pipeline.py loads, named from the same environment and
# lock: repo@revision:384.
"embed": embedding_model.resolve().model,
"topic": topic_model_name(),
"topic": topic_model_name() if naming is None else named_topic_model(naming),
"narrative": None,
"cluster": CLUSTER_MODEL,
"cluster_seed": DEFAULT_SEED,
Expand Down
141 changes: 141 additions & 0 deletions delphi/polismath/job_child/names_of.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""The source of a run that names another run's topics (the frame's ``names_of``).

A named run takes the layout and the clusters of a finished keyword run of the
same conversation and comment rule and only names them. Before the child
starts, polis-jobs reads the source run's two families from its stored
results in Postgres (``queue-rs/src/jobs/names_of.rs``), checks each against
the batch and digest the source's run record names, and writes their codec
files into the attempt directory; the frame names them::

"names_of": {"schema": "polis-jobs.names-of/1", "job_id": ..., "run_id": ...,
"batch_id": ..., "families": {"Delphi_UMAPGraph": {"file": ..., "sha256": ...},
"Delphi_CommentHierarchicalClusterAssignments": {...}}}

This module reads them back: the source's rows, to be copied into the named
run's own batch unchanged, and the layout they hold (comment ids, 2D positions,
cluster labels per layer), from which the named run recomputes keywords and
sample comments. Nothing here reads a file an earlier run left on a box: the
files are this attempt's, written from Postgres. Outside the daemon, or with a
frame that names no source, :func:`load` is None and nothing changes.
"""
from __future__ import annotations

import hashlib
import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional

import numpy as np

from polismath.delphi_storage.codec import decode_family, to_python

SCHEMA = "polis-jobs.names-of/1"
FRAME_ENV = "DELPHI_FRAME"
POSITIONS = "Delphi_UMAPGraph"
ASSIGNMENTS = "Delphi_CommentHierarchicalClusterAssignments"
FAMILIES = (POSITIONS, ASSIGNMENTS)


class SourceError(ValueError):
"""The frame names a source whose files are not what it says."""


@dataclass
class Source:
job_id: str
run_id: str
batch_id: str
# family -> the source's rows, as boto3-resource values (codec.to_python)
rows: Dict[str, List[Dict[str, Any]]] = field(default_factory=dict)
comment_ids: List[int] = field(default_factory=list)
document_map: Any = None
cluster_layers: List[Any] = field(default_factory=list)


def _native(tagged: Dict[str, Any]) -> Dict[str, Any]:
return {name: to_python(av) for name, av in tagged.items()}


def layout(positions: List[Dict[str, Any]], assignments: List[Dict[str, Any]]):
"""(comment ids ascending, positions N x 2, cluster labels per layer) from
the two families' native rows. A node is the edge from a comment to itself;
every other edge is skipped. A layer is kept up to the last one any comment
is assigned in; an unassigned comment at a kept layer is -1 (noise)."""
nodes = {}
for row in positions:
source, target = row.get("source_id"), row.get("target_id")
if source is None or int(source) != int(target):
continue
p = row.get("position") or {}
if int(source) in nodes or "x" not in p or "y" not in p:
raise SourceError(f"{POSITIONS}: an unreadable node for comment {source}")
nodes[int(source)] = (float(p["x"]), float(p["y"]))
clusters = {}
for row in assignments:
tid = int(row["comment_id"])
if tid in clusters:
raise SourceError(f"{ASSIGNMENTS}: two rows for comment {tid}")
layers = {}
for name, value in row.items():
if name.startswith("layer") and name.endswith("_cluster_id") and value is not None:
layers[int(name[len("layer"):-len("_cluster_id")])] = int(value)
clusters[tid] = layers
if not nodes or set(nodes) != set(clusters):
raise SourceError("the source's positions and assignments are not of the same comments")
comment_ids = sorted(nodes)
count = 1 + max((layer for ls in clusters.values() for layer, c in ls.items() if c >= 0),
default=-1)
if count < 1:
raise SourceError("the source assigns no comment to any topic")
document_map = np.array([nodes[t] for t in comment_ids], dtype=float)
cluster_layers = [np.array([clusters[t].get(layer, -1) for t in comment_ids], dtype=int)
for layer in range(count)]
return comment_ids, document_map, cluster_layers


def from_frame(frame: Dict[str, Any], frame_path: str) -> Optional[Source]:
entry = frame.get("names_of")
if entry is None:
return None
if not isinstance(entry, dict) or entry.get("schema") != SCHEMA:
raise SourceError("the frame's names_of is not polis-jobs.names-of/1")
base = Path(frame_path).parent
source = Source(job_id=str(entry.get("job_id")), run_id=str(entry.get("run_id")),
batch_id=str(entry.get("batch_id")))
for name in FAMILIES:
f = (entry.get("families") or {}).get(name) or {}
try:
data = (base / str(f.get("file"))).read_bytes()
except OSError as e:
raise SourceError(f"{name}: the source's file is unreadable: {e}") from e
if hashlib.sha256(data).hexdigest() != f.get("sha256"):
raise SourceError(f"{name}: the source's file is not the digest the frame names")
family, items = decode_family(data)
if family != name:
raise SourceError(f"{name}: the file holds {family}")
source.rows[name] = [_native(item) for item in items]
source.comment_ids, source.document_map, source.cluster_layers = layout(
source.rows[POSITIONS], source.rows[ASSIGNMENTS])
return source


def load(environ: Optional[Dict[str, str]] = None) -> Optional[Source]:
"""The source this process's frame (``DELPHI_FRAME``) names; None outside
the daemon or when the frame names none."""
environ = os.environ if environ is None else environ
frame_path = environ.get(FRAME_ENV, "").strip()
if not frame_path:
return None
try:
frame = json.loads(Path(frame_path).read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
raise SourceError(f"{FRAME_ENV} is unreadable: {e}") from e
return from_frame(frame, frame_path)


def not_shown(source: Source, selected, texts: Dict[int, str]) -> List[int]:
"""The source's comments that the run's own selection no longer keeps, or
that have no text: if any, no comment text of this layout may reach a model."""
return [t for t in source.comment_ids if t not in selected or not (texts.get(t) or "").strip()]
38 changes: 32 additions & 6 deletions delphi/polismath/step_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
import threading
import time
from contextlib import contextmanager
from typing import Any, Dict, Iterator, List, Optional
from typing import Any, Dict, Iterator, List, Optional, Sequence

SWITCH = "DELPHI_STEP_LOG"
PREFIX = "delphi_step/1"
Expand Down Expand Up @@ -200,16 +200,42 @@ def step(name: str, **facts: Any) -> Iterator[Dict[str, Any]]:
_record.append(dict(data, step=name, status=status, seconds=seconds))


def run_child(name: str, command: List[str], **facts: Any) -> int:
# How long an interrupted run waits for its child to stop on SIGTERM.
STOP_SECONDS = 30.0


def _stop(proc: "subprocess.Popen") -> None:
try:
proc.terminate()
proc.wait(timeout=STOP_SECONDS)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()


def run_child(name: str, command: List[str], pass_fds: Sequence[int] = (), **facts: Any) -> int:
"""Run a child process to completion and return its exit code. With the
switch on, also print the step line with the child's exact peak (wait4)."""
if not enabled():
switch on, also print the step line with the child's exact peak (wait4).
``pass_fds``: descriptors the child keeps (a naming run's record pipe);
without them the child is started exactly as before. With them, a child
whose wait is interrupted (this process's SIGTERM) is stopped and reaped
before the interruption goes on: SIGTERM, then SIGKILL after
``STOP_SECONDS``."""
extra = {"pass_fds": tuple(pass_fds)} if pass_fds else {}
if not pass_fds and not enabled():
return subprocess.run(command).returncode
start = time.monotonic()
proc = subprocess.Popen(command)
_, status, usage = os.wait4(proc.pid, 0)
proc = subprocess.Popen(command, **extra)
try:
_, status, usage = os.wait4(proc.pid, 0)
except BaseException:
if pass_fds:
_stop(proc)
raise
code = os.waitstatus_to_exitcode(status)
proc.returncode = code
if not enabled():
return code
raw = usage.ru_maxrss
peak = raw / (1024.0 * 1024.0) if sys.platform == "darwin" else raw / 1024.0
emit(name, status="ok" if code == 0 else "failed", seconds=round(time.monotonic() - start, 3),
Expand Down
Loading
Loading