--- sahdated-1.1.1-served.py +++ sahdated-1.1.2.py @@ -85,7 +85,17 @@ # is now the SAME catchable `Undated`, and it names the file and the I/O error. (b) `producers` was # missing from the module's own usage line, so the subcommand list was incomplete in the one place a # new caller looks. -VERSION = "sahdated/1.1.1" +# +# 1.1.2 (job 2940, route 148): the two recognition gaps #1549 measured, closed with regression tests +# (test_recognition_2940.py: 5 GAP tests fail on 1.1.1, pass here). (a) A refused record that carries +# an instant-shaped field outside INSTANT_FIELDS (`fetched_at`) is still refused, and the refusal and +# `audit` now name the near miss. (b) `producers` scopes guard evidence to the site's window with +# comments and string contents removed, and counts an instant KEY WRITTEN there (`"at": ...`, +# `x["covered_at"] = ...`) over the full INSTANT_FIELDS list (1.1.1 used 3 names on the write side and +# 9 on the read side). A helper call is a `routed` site; a dumps inside print()/json.loads() is +# `not-a-write`; an exemption naming such a line is REDUNDANT, not stale. Known residual: the key +# need not belong to the object dumped (a window, not dataflow). +VERSION = "sahdated/1.1.2" # The field names that count as naming an instant. Deliberately a LIST and not one name: this # project already writes `at`, `covered_at` and `observed_at`, and a gate that only knows its own @@ -136,6 +146,23 @@ if dt is not None: return f, record[f], dt return None, None, None + + +# 1.1.2: a field that LOOKS like an instant but is not on the accepted list. The gate still refuses +# the record (widening the list silently would let any `*_at` through), but the refusal names the +# near miss so the writer can be fixed in one step. Found live in job 2926: a fetch script wrote +# `fetched_at`, the record audit called its records undated while `producers` called the writer +# guarded -- two halves of one contract disagreeing about the same file. +NEAR_MISS_NAME = re.compile(r"(?:^|_)(?:at|time|ts|timestamp|date|datetime|when)$", re.I) + + +def near_misses(record): + """[(field, value)] for instant-shaped fields OUTSIDE INSTANT_FIELDS whose value parses.""" + if not isinstance(record, dict): + return [] + return [(k, record[k]) for k in sorted(record) + if isinstance(k, str) and k not in INSTANT_FIELDS and NEAR_MISS_NAME.search(k) + and parse_instant(record[k]) is not None] def stamp_of(now=None): @@ -226,6 +253,10 @@ if isinstance(self.record, dict) and self.record.get(f) is not None] why = ("%s=%r is present but is not a usable instant" % broken[0] if broken else "names no instant field (%s)" % ", ".join(INSTANT_FIELDS)) + nm = near_misses(self.record) + if nm and not broken: + why += ("; NEAR MISS: it carries %s, an instant-shaped field outside the accepted " + "list -- rename it at the writer" % ", ".join("%s=%r" % kv for kv in nm)) raise Undated("%s %s: it cannot be read as current" % (path, why)) def as_json(self): @@ -350,9 +381,14 @@ - dt).total_seconds(), 1)}) continue hit, ev = cited(p, ops_dirs) + nm = near_misses(rec) + why = (("served by this run (%s): exempt, its bytes are published" % ev) if hit + else "no instant field and never served: stamp it") + if nm: + why += ("; NEAR MISS %s: an instant-shaped field outside the accepted list (fix the " + "writer's spelling)" % ", ".join(k for k, _ in nm)) out.append({"path": p, "status": "undated-cited" if hit else "undated-fixable", - "why": ("served by this run (%s): exempt, its bytes are published" % ev) if hit - else "no instant field and never served: stamp it"}) + "why": why, "near_miss": [k for k, _ in nm]}) return out @@ -368,7 +404,79 @@ GUARD_EVIDENCE = ("write_dated(", "sahdated.write(", "sahdated import", "import sahdated") INSTANT_NAME = ("covered_at", "written_at", "observed_at") +# 1.1.2: evidence is scoped to the SITE, not the file. 1.1.1 computed `guarded` once from the whole +# file text, so a READ of an instant field (`rec.get("observed_at")`) or a COMMENT naming one bought +# every write in the file the compliant verdict (#1549 P2/P2b). A site is now guarded only when, in +# its own window with comments removed, the instant is WRITTEN as a key -- `"covered_at": ...` in a +# literal or `x["covered_at"] = ...` -- or the dated helper is called. +INSTANT_KEY_WRITE = re.compile(r"""["'](?:%s)["']\s*(?::|\]\s*=(?!=))""" % "|".join(INSTANT_FIELDS)) +# 1.1.2: a call of the dated helper is itself a write site, reported as `routed`. In 1.1.1 it left +# no site at all (#1549 P3), so "this tree writes nothing" and "every write is routed" printed the +# same thing. +ROUTED_SITE = re.compile(r"(?:\bwrite_dated|\bsahdated\.write)\s*\(") + + +# 1.1.2: sites that serialise JSON but write no file. 1.1.1 counted them as write sites and hid them +# behind the whole-file guard; #1549's census found 8 of 18 sites were stdout prints and 3 of 34 deep +# copies. They are reported as `not-a-write` so they are visible but open nothing. +NOT_A_WRITE = re.compile(r"(?:\bprint\s*\(.*json\.dumps?\s*\(|json\.loads\s*\(\s*json\.dumps\s*\()") + + +def _no_write_lines(text): + """Lines holding a json.dump(s) call nested inside print(...) or json.loads(...), by syntax tree + (a multi-line print puts the dumps on a continuation line the line regex cannot see).""" + import ast + try: + tree = ast.parse(text) + except (SyntaxError, ValueError): + return set() + def name(f): + if isinstance(f, ast.Name): + return f.id + if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name): + return f.value.id + "." + f.attr + return None + out = set() + for node in ast.walk(tree): + if isinstance(node, ast.Call) and name(node.func) in ("print", "json.loads"): + for sub in ast.walk(node): + if sub is not node and isinstance(sub, ast.Call) and name(sub.func) in ("json.dump", "json.dumps"): + out.add(sub.lineno) + return out + + +def _views(text): + """Two line-aligned views of Python source: comments removed (strings kept, for instant KEYS), + and comments removed with string CONTENTS blanked (for call sites -- a `json.dumps(` inside a + docstring or a fixture string is not a call). Falls back to a `#` split if tokenize fails.""" + import tokenize + lines = text.splitlines() + keep = [list(l) for l in lines] + blank = [list(l) for l in lines] + try: + toks = list(tokenize.generate_tokens(io.StringIO(text).readline)) + except (tokenize.TokenError, SyntaxError, IndentationError): + cut = [l.split("#", 1)[0] for l in lines] + return cut, cut + for t in toks: + if t.type not in (tokenize.COMMENT, tokenize.STRING): + continue + (r0, c0), (r1, c1) = t.start, t.end + for r in range(r0, r1 + 1): + if r - 1 >= len(lines): + break + a = c0 if r == r0 else 0 + b = c1 if r == r1 else len(lines[r - 1]) + if t.type == tokenize.STRING: + a, b = (a + 1, b - 1) if r0 == r1 else (a, b) + for c in range(a, min(b, len(blank[r - 1]))): + blank[r - 1][c] = " " + if t.type == tokenize.COMMENT: + keep[r - 1][c] = " " + return ["".join(l) for l in keep], ["".join(l) for l in blank] + + def producers(paths, exempt=None, guard_window=25): """Which files WRITE a JSON record, and whether the write can be undated. @@ -383,7 +491,7 @@ go quiet). An exemption that matches NOTHING is reported STALE rather than kept: a stale exemption is a licence nobody is watching. """ - rows, hits = [], {} + rows, hits, redundant = [], {}, [] for p in paths: try: text = io.open(p, encoding="utf-8", errors="replace").read() @@ -391,16 +499,38 @@ rows.append({"path": p, "status": "unreadable", "why": str(exc)}) continue lines = text.splitlines() - guarded = any(ev in text for ev in GUARD_EVIDENCE) or any(n in text for n in INSTANT_NAME) + code, calls = _views(text) + nowrite = _no_write_lines(text) for n, line in enumerate(lines, 1): - if not WRITE_SITE.search(line): + if ROUTED_SITE.search(calls[n - 1]) and not calls[n - 1].lstrip().startswith("def "): + rows.append({"path": p, "line": n, "text": line.strip()[:120], "status": "routed", + "evidence": "the dated helper writes here", "exempt": None}) continue - near = "\n".join(lines[max(0, n - guard_window):n]) + if not WRITE_SITE.search(calls[n - 1]): + continue + if NOT_A_WRITE.search(calls[n - 1]) or n in nowrite: + row = {"path": p, "line": n, "text": line.strip()[:120], "status": "not-a-write", + "evidence": "stdout print or JSON round-trip copy", "exempt": None} + # An exemption written under 1.1.1 for such a line is now REDUNDANT, not stale: it still + # names a real site, the site simply no longer needs a licence. + for e in (exempt or {}).get("exempt", []): + if p.replace(os.sep, "/").endswith(e.get("path", "").replace("\\", "/")) \ + and e.get("contains") and e["contains"] in line: + row["exempt_redundant"] = {"why": e.get("why"), "contains": e["contains"]} + hits[id(e)] = hits.get(id(e), 0) + 1 + if e not in redundant: + redundant.append(e) + break + rows.append(row) + continue + near = "\n".join(code[max(0, n - guard_window):n]) routed = any(ev in near for ev in GUARD_EVIDENCE) + keyed = bool(INSTANT_KEY_WRITE.search(near)) row = {"path": p, "line": n, "text": line.strip()[:120], - "status": "guarded" if (routed or guarded) else "unguarded", + "status": "guarded" if (routed or keyed) else "unguarded", "evidence": "calls the dated helper" if routed else - ("file names an instant field" if guarded else None), + ("writes an instant key within %d lines" % guard_window if keyed + else None), "exempt": None} for e in (exempt or {}).get("exempt", []): tail = e.get("path", "") @@ -414,9 +544,9 @@ stale = [e for e in (exempt or {}).get("exempt", []) if not hits.get(id(e))] open_sites = [r for r in rows if r.get("status") == "unguarded"] return {"tool": "sahdated.producers", "version": VERSION, "sites": rows, - "unguarded": open_sites, "stale_exemptions": stale, + "unguarded": open_sites, "stale_exemptions": stale, "redundant_exemptions": redundant, "counts": {s: len([r for r in rows if r.get("status") == s]) - for s in ("guarded", "exempt", "unguarded", "unreadable")}, + for s in ("guarded", "routed", "not-a-write", "exempt", "unguarded", "unreadable")}, "caveat": "text-level finder: an unrecognised writer is reported unguarded, never missed"} @@ -582,9 +712,10 @@ # The routed file dumps nothing itself -- the helper dumps for it -- so the honest assertion # is that it contributes NO site, not that it "is not unguarded", which was vacuously true (the # check this replaced passed without testing anything, the same shape the census selftest ate). - chk("a generator that lets the helper write has NO site at all", - not [r for r in res["sites"] if r["path"].endswith("routed.py")], - [r["text"] for r in res["sites"]]) + chk("a generator that lets the helper write reports a ROUTED site (1.1.2; 1.1.1 reported none, " + "so 'no writes' and 'all routed' looked alike)", + [r["status"] for r in res["sites"] if r["path"].endswith("routed.py")] == ["routed"], + [(r["text"], r["status"]) for r in res["sites"]]) hand = os.path.join(td, "hand.py") with io.open(hand, "w", encoding="utf-8") as fh: fh.write("import json\nrec = {'rows': rows, 'covered_at': '2026-09-23T00:00:00Z'}\n" @@ -691,9 +822,11 @@ return 3 res = producers(found, ex) for r in res["sites"]: - if r["status"] != "guarded": + if r["status"] not in ("guarded", "routed", "not-a-write"): print("%-9s %s:%d %s" % (r["status"], r["path"], r["line"], (r["exempt"] or {}).get("why") or r["text"])) + for e in res.get("redundant_exemptions", []): + print("REDUNDANT exemption names a not-a-write site: %s %r" % (e.get("path"), e.get("contains"))) for e in res["stale_exemptions"]: print("STALE exemption matches nothing: %s %r" % (e.get("path"), e.get("contains"))) print("%d write site(s) in %d file(s): %s" %