mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-05 03:08:19 +00:00
src/openultrasast/source.py replaces the copies in semantic/functions.py, plane/tasks/repo_facts.py, learn/features.py, learn/excerpt.py and plane/tasks/verify.py. Two engines share one sentinel (<module>), one DECLARATION/KEYWORDS/RESERVED set and one alias map: the parser engine (ranges, enclosing, bounds, call_sites, callers_of, facts_for) for the scorer, the overlay and the hunter's annotations; the line-pattern engine (declared_functions, enclosing_at, function_span, function_bounds, the brace matcher) that labels, features, roles, excerpts and plane facts were built on. learn no longer imports plane.tasks. Frozen records that store the old sentinel are mapped on read (module_function). Gate: labels rebuilt before and after are identical, 7,921 rows, after sentinel normalisation (benchmarks/measurements/2026-10-13-source-module- label-diff/record.json). 490 targeted tests pass; 3,312 collect. Net: 657 lines deleted, 212 added. benchmarks/unseen keeps <global> for its own frozen manifests. Co-Authored-By: Claude Fable 5.1 <[email protected]>
234 lines
9.6 KiB
Python
234 lines
9.6 KiB
Python
"""`repo-facts`: the memory layer of the service plane (ai-service-plane, Requirement 5.1 / 5.2).
|
|
|
|
Source text only, no model, no git. For every product file: the functions it defines; and for every candidate
|
|
function, the call sites in *other* product files (path, 1-based line, enclosing function), capped at 40 and
|
|
sorted. The unit of work is one file (Requirement 2.2): a row goes to `units.jsonl` as each file finishes and
|
|
a restart skips the rows already there. `facts.json` is assembled from the rows and is byte-identical across
|
|
runs over the same tree; `summary.json` is written last and says `done` only when every unit finished.
|
|
|
|
The declaration patterns follow `benchmarks/independent/sink_candidates.py`, extended to Java, Go and Ruby;
|
|
the product filter follows `model_sinks.py` plus the `[[layout]]` facts (`model.layout`) for the languages that
|
|
declare them.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import traceback
|
|
from collections.abc import Mapping, Sequence
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import yaml
|
|
|
|
from ...preprocess import detect_language
|
|
from ...source import ( # noqa: F401 (re-exported: generate, remember and the tests import them from here)
|
|
DECLARATION,
|
|
KEYWORDS,
|
|
MODULE_FUNCTION,
|
|
_declared_name,
|
|
_digest,
|
|
declared_functions,
|
|
)
|
|
from ...source import call_sites_in as call_sites
|
|
from ...source import enclosing_at as enclosing
|
|
from ...source import product_paths as product_files
|
|
|
|
CALLERS_CAP = 40
|
|
|
|
|
|
DECLARATION["typescript"] = DECLARATION["javascript"]
|
|
|
|
|
|
class TaskFailed(RuntimeError):
|
|
"""A crash inside `run` that has already been recorded in `summary.json` (status `failed`, traceback)."""
|
|
|
|
|
|
def _read_lines(path: Path) -> list[str]:
|
|
return path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
|
|
|
|
def _candidate_names(candidates: Sequence[Mapping[str, Any]]) -> list[str]:
|
|
return sorted({str(c["function"]) for c in candidates if c.get("function")})
|
|
|
|
|
|
def _load_units(units_path: Path, digest: str) -> dict[str, dict[str, Any]]:
|
|
"""Rows already in `units.jsonl` that were computed for the same candidate set (Requirement 2.2)."""
|
|
rows: dict[str, dict[str, Any]] = {}
|
|
if not units_path.is_file():
|
|
return rows
|
|
for raw in units_path.read_text(encoding="utf-8").splitlines():
|
|
if not raw.strip():
|
|
continue
|
|
try:
|
|
row = json.loads(raw)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if isinstance(row, dict) and row.get("digest") == digest and isinstance(row.get("path"), str):
|
|
rows[row["path"]] = row
|
|
return rows
|
|
|
|
|
|
def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
|
|
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
|
|
|
|
def write_summary(output_dir: Path, *, status: str, units_done: int, units_total: int, **extra: Any) -> dict[str, Any]:
|
|
"""The task contract's `summary.json`: `done` is refused unless every unit finished."""
|
|
if status == "done" and units_done != units_total:
|
|
status = "failed"
|
|
extra.setdefault("reason", f"{units_done} of {units_total} units finished")
|
|
summary: dict[str, Any] = {
|
|
"status": status,
|
|
"units_done": units_done,
|
|
"units_total": units_total,
|
|
"usd": None,
|
|
"calls": 0,
|
|
"usage": {},
|
|
"model": None,
|
|
**extra,
|
|
}
|
|
_write_json(output_dir / "summary.json", summary)
|
|
return summary
|
|
|
|
|
|
def assemble_facts(
|
|
rows: Mapping[str, Mapping[str, Any]], candidates: Sequence[Mapping[str, Any]], cap: int = CALLERS_CAP
|
|
) -> dict[str, Any]:
|
|
"""`facts.json` from the per-file rows: functions per file, and per candidate the callers in other files."""
|
|
files = {path: {"functions": list(row.get("functions", ()))} for path, row in sorted(rows.items())}
|
|
by_name: dict[str, list[dict[str, Any]]] = {}
|
|
for path, row in sorted(rows.items()):
|
|
for call in row.get("calls", ()):
|
|
by_name.setdefault(str(call["function"]), []).append(
|
|
{"path": path, "line": int(call["line"]), "enclosing": str(call.get("enclosing", MODULE_FUNCTION))}
|
|
)
|
|
callers: dict[str, list[dict[str, Any]]] = {}
|
|
for candidate in sorted(candidates, key=lambda c: (str(c["path"]), str(c["function"]))):
|
|
path, name = str(candidate["path"]), str(candidate["function"])
|
|
sites = sorted(
|
|
(site for site in by_name.get(name, ()) if site["path"] != path), key=lambda s: (s["path"], s["line"], s["enclosing"])
|
|
)
|
|
callers[f"{path}::{name}"] = sites[:cap]
|
|
return {
|
|
"files": files,
|
|
"callers": callers,
|
|
"counts": {
|
|
"files": len(files),
|
|
"functions": sum(len(f["functions"]) for f in files.values()),
|
|
"candidates": len(callers),
|
|
"callers": sum(len(v) for v in callers.values()),
|
|
},
|
|
}
|
|
|
|
|
|
def run(workspace: Path, output_dir: Path, candidates: list[dict[str, Any]] | None = None, image: str | None = None) -> dict[str, Any]:
|
|
"""Compute the facts for ``workspace`` into ``output_dir``; returns the written summary.
|
|
|
|
``candidates`` rows are ``{"path", "function"}`` (workspace-relative POSIX path). ``None`` means every
|
|
function every product file defines. A `units.jsonl` row from an earlier run over the same candidate set
|
|
is reused, not recomputed. ``image`` (the runner image, from `AX_TASK_YAML`) goes into the summary: the
|
|
`remember` task keys the facts row by the image the facts were computed on.
|
|
"""
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
units_path = output_dir / "units.jsonl"
|
|
files = product_files(workspace)
|
|
languages = {p: detect_language(p) for p in files}
|
|
wanted: list[dict[str, Any]]
|
|
if candidates is None:
|
|
wanted = [
|
|
{"path": p.relative_to(workspace).as_posix(), "function": name}
|
|
for p in files
|
|
for name in declared_functions(_read_lines(p), languages[p])
|
|
]
|
|
else:
|
|
wanted = [{"path": str(c["path"]), "function": str(c["function"])} for c in candidates]
|
|
names = _candidate_names(wanted)
|
|
digest = _digest(names)
|
|
present = {p.relative_to(workspace).as_posix() for p in files}
|
|
rows = {path: row for path, row in _load_units(units_path, digest).items() if path in present}
|
|
try:
|
|
with units_path.open("a", encoding="utf-8") as sink:
|
|
for path in files:
|
|
relative = path.relative_to(workspace).as_posix()
|
|
if relative in rows:
|
|
continue
|
|
lines = _read_lines(path)
|
|
row: dict[str, Any] = {
|
|
"path": relative,
|
|
"language": languages[path],
|
|
"digest": digest,
|
|
"functions": declared_functions(lines, languages[path]),
|
|
"calls": call_sites(lines, languages[path], names),
|
|
}
|
|
sink.write(json.dumps(row, sort_keys=True) + "\n")
|
|
sink.flush()
|
|
rows[relative] = row
|
|
except Exception as exc:
|
|
write_summary(
|
|
output_dir, status="failed", units_done=len(rows), units_total=len(files), reason=str(exc), traceback=traceback.format_exc()
|
|
)
|
|
raise TaskFailed(str(exc)) from exc
|
|
facts = assemble_facts(rows, wanted)
|
|
_write_json(output_dir / "facts.json", facts)
|
|
extra = {"image": image} if image else {}
|
|
return write_summary(output_dir, status="done", units_done=len(rows), units_total=len(files), **extra)
|
|
|
|
|
|
def _load_candidates(path: str | None) -> list[dict[str, Any]] | None:
|
|
if not path:
|
|
return None
|
|
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
rows = payload.get("candidates", []) if isinstance(payload, dict) else payload
|
|
if not isinstance(rows, list):
|
|
raise ValueError(f"{path}: candidates must be a list of {{path, function}} rows")
|
|
return [{"path": str(row["path"]), "function": str(row["function"])} for row in rows]
|
|
|
|
|
|
def main(environ: Mapping[str, str] | None = None) -> int:
|
|
"""Entrypoint under the task contract: `OUSAST_WORKSPACE_DIR`, `OUSAST_OUTPUT_DIR`, optional
|
|
`OUSAST_INPUT_CANDIDATES` (a JSON file). Exit 0 when done, 2 when failed; a crash still leaves a
|
|
`summary.json` with the traceback."""
|
|
env = environ if environ is not None else os.environ
|
|
output_dir = Path(env.get("OUSAST_OUTPUT_DIR") or "")
|
|
try:
|
|
if not env.get("OUSAST_OUTPUT_DIR"):
|
|
raise ValueError("OUSAST_OUTPUT_DIR is not set")
|
|
workspace = Path(env.get("OUSAST_WORKSPACE_DIR") or "")
|
|
if not env.get("OUSAST_WORKSPACE_DIR") or not workspace.is_dir():
|
|
raise ValueError(f"OUSAST_WORKSPACE_DIR is not a directory: {workspace}")
|
|
task = yaml.safe_load(env.get("AX_TASK_YAML") or "{}")
|
|
image = str((task.get("spec") or {}).get("image") or "") if isinstance(task, dict) else ""
|
|
summary = run(workspace, output_dir, _load_candidates(env.get("OUSAST_INPUT_CANDIDATES")), image or None)
|
|
except TaskFailed as exc:
|
|
print(f"repo-facts failed: {exc}", file=sys.stderr)
|
|
return 2
|
|
except Exception as exc:
|
|
if env.get("OUSAST_OUTPUT_DIR"):
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
write_summary(output_dir, status="failed", units_done=0, units_total=0, reason=str(exc), traceback=traceback.format_exc())
|
|
print(f"repo-facts failed: {exc}", file=sys.stderr)
|
|
return 2
|
|
return 0 if summary["status"] == "done" else 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|
|
|
|
|
|
__all__ = [
|
|
"CALLERS_CAP",
|
|
"DECLARATION",
|
|
"TaskFailed",
|
|
"assemble_facts",
|
|
"call_sites",
|
|
"declared_functions",
|
|
"enclosing",
|
|
"main",
|
|
"product_files",
|
|
"run",
|
|
"write_summary",
|
|
]
|