Rickesh commited on
Commit
829dbce
·
verified ·
1 Parent(s): 67dd5e2

Upload folder using huggingface_hub

Browse files
ctxstream/src/backend.cpp ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Minimal HTTP/1.1 client + just enough JSON to talk to a local model server.
2
+ // No libcurl, no JSON library: the request shape is fixed and only three fields
3
+ // are read back, so a dependency would cost more than it saves.
4
+ #include "ctxstream.hpp"
5
+
6
+ #include <netdb.h>
7
+ #include <netinet/in.h>
8
+ #include <sys/socket.h>
9
+ #include <sys/types.h>
10
+ #include <unistd.h>
11
+
12
+ #include <cstring>
13
+ #include <sstream>
14
+ #include <string>
15
+
16
+ namespace ctxstream {
17
+
18
+ static std::string json_escape(const std::string& s) {
19
+ std::string o;
20
+ o.reserve(s.size() + 32);
21
+ for (unsigned char c : s) {
22
+ switch (c) {
23
+ case '"': o += "\\\""; break;
24
+ case '\\': o += "\\\\"; break;
25
+ case '\n': o += "\\n"; break;
26
+ case '\r': o += "\\r"; break;
27
+ case '\t': o += "\\t"; break;
28
+ case '\b': o += "\\b"; break;
29
+ case '\f': o += "\\f"; break;
30
+ default:
31
+ if (c < 0x20) {
32
+ char buf[8];
33
+ std::snprintf(buf, sizeof buf, "\\u%04x", c);
34
+ o += buf;
35
+ } else {
36
+ o += static_cast<char>(c);
37
+ }
38
+ }
39
+ }
40
+ return o;
41
+ }
42
+
43
+ // Unescape a JSON string body (the model's reply). Handles the escapes we emit
44
+ // and the \uXXXX that servers produce; non-ASCII code points are passed through
45
+ // as UTF-8.
46
+ static std::string json_unescape(const std::string& s) {
47
+ std::string o;
48
+ o.reserve(s.size());
49
+ for (std::size_t i = 0; i < s.size(); ++i) {
50
+ if (s[i] != '\\' || i + 1 >= s.size()) { o += s[i]; continue; }
51
+ const char n = s[++i];
52
+ switch (n) {
53
+ case 'n': o += '\n'; break;
54
+ case 't': o += '\t'; break;
55
+ case 'r': o += '\r'; break;
56
+ case 'b': o += '\b'; break;
57
+ case 'f': o += '\f'; break;
58
+ case '"': o += '"'; break;
59
+ case '\\': o += '\\'; break;
60
+ case '/': o += '/'; break;
61
+ case 'u': {
62
+ if (i + 4 >= s.size()) break;
63
+ const unsigned cp =
64
+ std::stoul(s.substr(i + 1, 4), nullptr, 16);
65
+ i += 4;
66
+ if (cp < 0x80) {
67
+ o += static_cast<char>(cp);
68
+ } else if (cp < 0x800) {
69
+ o += static_cast<char>(0xC0 | (cp >> 6));
70
+ o += static_cast<char>(0x80 | (cp & 0x3F));
71
+ } else {
72
+ o += static_cast<char>(0xE0 | (cp >> 12));
73
+ o += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
74
+ o += static_cast<char>(0x80 | (cp & 0x3F));
75
+ }
76
+ break;
77
+ }
78
+ default: o += n;
79
+ }
80
+ }
81
+ return o;
82
+ }
83
+
84
+ // Extract "key":"..." respecting backslash escapes.
85
+ static bool json_string_field(const std::string& body, const std::string& key,
86
+ std::string* out) {
87
+ const std::string needle = "\"" + key + "\"";
88
+ std::size_t p = body.find(needle);
89
+ if (p == std::string::npos) return false;
90
+ p = body.find(':', p + needle.size());
91
+ if (p == std::string::npos) return false;
92
+ while (p < body.size() && (body[++p] == ' ' || body[p] == '\t')) {}
93
+ if (p >= body.size() || body[p] != '"') return false;
94
+ const std::size_t start = ++p;
95
+ for (; p < body.size(); ++p) {
96
+ if (body[p] == '\\') { ++p; continue; }
97
+ if (body[p] == '"') break;
98
+ }
99
+ if (p >= body.size()) return false;
100
+ *out = json_unescape(body.substr(start, p - start));
101
+ return true;
102
+ }
103
+
104
+ static long json_number_field(const std::string& body, const std::string& key,
105
+ long fallback = 0) {
106
+ const std::string needle = "\"" + key + "\"";
107
+ std::size_t p = body.find(needle);
108
+ if (p == std::string::npos) return fallback;
109
+ p = body.find(':', p + needle.size());
110
+ if (p == std::string::npos) return fallback;
111
+ ++p;
112
+ while (p < body.size() && (body[p] == ' ' || body[p] == '\t')) ++p;
113
+ const std::size_t start = p;
114
+ while (p < body.size() && (std::isdigit(static_cast<unsigned char>(body[p])) ||
115
+ body[p] == '-' || body[p] == '.')) ++p;
116
+ if (p == start) return fallback;
117
+ try { return std::stol(body.substr(start, p - start)); }
118
+ catch (...) { return fallback; }
119
+ }
120
+
121
+ static bool http_post(const BackendOptions& opt, const std::string& payload,
122
+ std::string* response, std::string* err) {
123
+ addrinfo hints{};
124
+ hints.ai_family = AF_UNSPEC;
125
+ hints.ai_socktype = SOCK_STREAM;
126
+ addrinfo* res = nullptr;
127
+ const std::string port = std::to_string(opt.port);
128
+ if (getaddrinfo(opt.host.c_str(), port.c_str(), &hints, &res) != 0 || !res) {
129
+ *err = "getaddrinfo failed for " + opt.host + ":" + port;
130
+ return false;
131
+ }
132
+
133
+ int fd = -1;
134
+ for (addrinfo* a = res; a; a = a->ai_next) {
135
+ fd = ::socket(a->ai_family, a->ai_socktype, a->ai_protocol);
136
+ if (fd < 0) continue;
137
+ timeval tv{opt.timeout_sec, 0};
138
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
139
+ setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
140
+ if (::connect(fd, a->ai_addr, a->ai_addrlen) == 0) break;
141
+ ::close(fd);
142
+ fd = -1;
143
+ }
144
+ freeaddrinfo(res);
145
+ if (fd < 0) { *err = "connect failed to " + opt.host + ":" + port; return false; }
146
+
147
+ std::ostringstream req;
148
+ req << "POST " << opt.path << " HTTP/1.1\r\n"
149
+ << "Host: " << opt.host << ":" << opt.port << "\r\n"
150
+ << "Content-Type: application/json\r\n"
151
+ << "Content-Length: " << payload.size() << "\r\n"
152
+ << "Connection: close\r\n\r\n"
153
+ << payload;
154
+ const std::string raw = req.str();
155
+
156
+ for (std::size_t sent = 0; sent < raw.size();) {
157
+ const ssize_t n = ::send(fd, raw.data() + sent, raw.size() - sent, 0);
158
+ if (n <= 0) { ::close(fd); *err = "send failed"; return false; }
159
+ sent += static_cast<std::size_t>(n);
160
+ }
161
+
162
+ std::string all;
163
+ char buf[16384];
164
+ for (;;) {
165
+ const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
166
+ if (n < 0) { ::close(fd); *err = "recv timeout/error"; return false; }
167
+ if (n == 0) break;
168
+ all.append(buf, static_cast<std::size_t>(n));
169
+ }
170
+ ::close(fd);
171
+
172
+ const std::size_t hdr = all.find("\r\n\r\n");
173
+ if (hdr == std::string::npos) { *err = "malformed HTTP response"; return false; }
174
+ *response = all.substr(hdr + 4);
175
+ return true;
176
+ }
177
+
178
+ Completion complete(const BackendOptions& opt, const std::string& system_prompt,
179
+ const std::string& user_prompt) {
180
+ Completion c;
181
+ std::ostringstream body;
182
+ body << "{\"model\":\"" << json_escape(opt.model) << "\","
183
+ << "\"stream\":false,"
184
+ << "\"options\":{\"num_ctx\":" << opt.num_ctx
185
+ << ",\"num_predict\":" << opt.num_predict
186
+ << ",\"temperature\":0},"
187
+ << "\"messages\":[";
188
+ if (!system_prompt.empty()) {
189
+ body << "{\"role\":\"system\",\"content\":\"" << json_escape(system_prompt)
190
+ << "\"},";
191
+ }
192
+ body << "{\"role\":\"user\",\"content\":\"" << json_escape(user_prompt)
193
+ << "\"}]}";
194
+
195
+ std::string resp;
196
+ if (!http_post(opt, body.str(), &resp, &c.error)) return c;
197
+
198
+ std::string err;
199
+ if (json_string_field(resp, "error", &err) && !err.empty()) {
200
+ c.error = "server: " + err;
201
+ return c;
202
+ }
203
+ if (!json_string_field(resp, "content", &c.text)) {
204
+ c.error = "no content field in response: " + resp.substr(0, 200);
205
+ return c;
206
+ }
207
+ c.prompt_tokens = json_number_field(resp, "prompt_eval_count");
208
+ c.output_tokens = json_number_field(resp, "eval_count");
209
+ c.ok = true;
210
+ return c;
211
+ }
212
+
213
+ bool looks_truncated(std::size_t prompt_chars, long prompt_tokens) {
214
+ if (prompt_tokens <= 0) return false; // server did not report; cannot judge
215
+ // Deliberately loose: no real tokenizer reaches 5 chars/token, so this fires
216
+ // only on gross clipping (measured: 50,000 tokens sent, 16,387 processed),
217
+ // never on tokenizer variance.
218
+ return static_cast<std::size_t>(prompt_tokens) < prompt_chars / 5;
219
+ }
220
+
221
+ } // namespace ctxstream
ctxstream/src/codegraph.cpp ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code graph: scan a repo, find symbols and file-to-file edges, then segment
2
+ // along that structure instead of along character offsets.
3
+ //
4
+ // Deliberately lexical, not a parser. A real parse (tree-sitter, clang) is a
5
+ // dependency and a build burden, and the segmentation only needs to know where
6
+ // a symbol starts and which files reference which. Heuristics that are right
7
+ // most of the time produce better segments than exact offsets would, because
8
+ // the consumer is a language model reading the text anyway.
9
+ #include "ctxstream.hpp"
10
+
11
+ #include <algorithm>
12
+ #include <cctype>
13
+ #include <filesystem>
14
+ #include <fstream>
15
+ #include <map>
16
+ #include <regex>
17
+ #include <set>
18
+ #include <sstream>
19
+
20
+ namespace fs = std::filesystem;
21
+
22
+ namespace ctxstream {
23
+
24
+ static std::string lang_of(const std::string& ext) {
25
+ static const std::map<std::string, std::string> m = {
26
+ {".c", "c"}, {".h", "c"}, {".cpp", "cpp"}, {".cc", "cpp"},
27
+ {".hpp", "cpp"}, {".hh", "cpp"}, {".cxx", "cpp"},
28
+ {".py", "python"}, {".pyi", "python"},
29
+ {".js", "js"}, {".mjs", "js"}, {".ts", "ts"}, {".tsx", "ts"},
30
+ {".go", "go"}, {".rs", "rust"}, {".java", "java"},
31
+ {".rb", "ruby"}, {".sh", "shell"}, {".bash", "shell"},
32
+ {".cs", "csharp"}, {".kt", "kotlin"}, {".swift", "swift"},
33
+ {".php", "php"}, {".lua", "lua"}, {".m", "objc"},
34
+ };
35
+ const auto it = m.find(ext);
36
+ return it == m.end() ? std::string() : it->second;
37
+ }
38
+
39
+ static bool looks_binary(const std::string& head) {
40
+ for (unsigned char c : head) {
41
+ if (c == 0) return true;
42
+ }
43
+ return false;
44
+ }
45
+
46
+ static std::string read_file(const fs::path& p, std::size_t cap, bool* too_big) {
47
+ std::error_code ec;
48
+ const auto sz = fs::file_size(p, ec);
49
+ if (!ec && sz > cap) { *too_big = true; return {}; }
50
+ std::ifstream in(p, std::ios::binary);
51
+ if (!in) return {};
52
+ std::ostringstream ss;
53
+ ss << in.rdbuf();
54
+ return ss.str();
55
+ }
56
+
57
+ // One pattern per language family. Captures the symbol name in group 1.
58
+ static const std::vector<std::pair<std::regex, NodeKind>>& defs_for(
59
+ const std::string& lang) {
60
+ static const std::vector<std::pair<std::regex, NodeKind>> c_like = {
61
+ {std::regex(R"(^\s*(?:class)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
62
+ {std::regex(R"(^\s*(?:struct)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
63
+ // return-type name(...) at line start, not a call or control keyword
64
+ {std::regex(R"(^[A-Za-z_][A-Za-z0-9_:<>,\s\*&]*\s[\*&]?([A-Za-z_][A-Za-z0-9_]*)\s*\([^;]*\)\s*(?:const)?\s*\{)"),
65
+ NodeKind::Function},
66
+ };
67
+ static const std::vector<std::pair<std::regex, NodeKind>> python = {
68
+ {std::regex(R"(^\s*class\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
69
+ {std::regex(R"(^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
70
+ };
71
+ static const std::vector<std::pair<std::regex, NodeKind>> js_like = {
72
+ {std::regex(R"(^\s*(?:export\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Class},
73
+ {std::regex(R"(^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Function},
74
+ {std::regex(R"(^\s*(?:export\s+)?const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\()"), NodeKind::Function},
75
+ };
76
+ static const std::vector<std::pair<std::regex, NodeKind>> go_like = {
77
+ {std::regex(R"(^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
78
+ {std::regex(R"(^\s*type\s+([A-Za-z_][A-Za-z0-9_]*)\s+struct)"), NodeKind::Struct},
79
+ };
80
+ static const std::vector<std::pair<std::regex, NodeKind>> rust_like = {
81
+ {std::regex(R"(^\s*(?:pub\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
82
+ {std::regex(R"(^\s*(?:pub\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
83
+ };
84
+ static const std::vector<std::pair<std::regex, NodeKind>> none;
85
+ if (lang == "c" || lang == "cpp" || lang == "java" || lang == "csharp") return c_like;
86
+ if (lang == "python") return python;
87
+ if (lang == "js" || lang == "ts") return js_like;
88
+ if (lang == "go") return go_like;
89
+ if (lang == "rust") return rust_like;
90
+ return none;
91
+ }
92
+
93
+ // #include "x.h" / import x / from x import / require('x')
94
+ static std::vector<std::string> imports_of(const std::string& text,
95
+ const std::string& lang) {
96
+ static const std::regex inc_c(R"(^\s*#\s*include\s*[\"<]([^\">]+)[\">])");
97
+ static const std::regex imp_py(R"(^\s*(?:from\s+([A-Za-z0-9_.]+)\s+import|import\s+([A-Za-z0-9_.]+)))");
98
+ static const std::regex imp_js(R"((?:from\s*[\"']([^\"']+)[\"']|require\(\s*[\"']([^\"']+)[\"']\s*\)))");
99
+ std::vector<std::string> out;
100
+ std::istringstream in(text);
101
+ std::string line;
102
+ while (std::getline(in, line)) {
103
+ std::smatch m;
104
+ if ((lang == "c" || lang == "cpp") && std::regex_search(line, m, inc_c)) {
105
+ out.push_back(m[1].str());
106
+ } else if (lang == "python" && std::regex_search(line, m, imp_py)) {
107
+ out.push_back(m[1].matched ? m[1].str() : m[2].str());
108
+ } else if ((lang == "js" || lang == "ts") && std::regex_search(line, m, imp_js)) {
109
+ out.push_back(m[1].matched ? m[1].str() : m[2].str());
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ CodeGraph scan_repo(const std::string& root, const ScanOptions& opt) {
116
+ CodeGraph g;
117
+ g.root = root;
118
+ const std::set<std::string> excluded(opt.exclude_dirs.begin(),
119
+ opt.exclude_dirs.end());
120
+ // path (as written in imports) -> file id, for edge resolution
121
+ std::map<std::string, int> by_stem;
122
+ std::vector<std::string> texts;
123
+
124
+ std::error_code ec;
125
+ auto it = fs::recursive_directory_iterator(
126
+ root,
127
+ opt.follow_symlinks ? fs::directory_options::follow_directory_symlink
128
+ : fs::directory_options::skip_permission_denied,
129
+ ec);
130
+ if (ec) return g;
131
+
132
+ for (fs::recursive_directory_iterator end; it != end; it.increment(ec)) {
133
+ if (ec) { ec.clear(); continue; }
134
+ const fs::path p = it->path();
135
+ if (it->is_directory(ec)) {
136
+ if (excluded.count(p.filename().string())) it.disable_recursion_pending();
137
+ continue;
138
+ }
139
+ if (!it->is_regular_file(ec)) continue;
140
+ const std::string lang = lang_of(p.extension().string());
141
+ if (lang.empty()) continue;
142
+
143
+ bool too_big = false;
144
+ const std::string text = read_file(p, opt.max_file_bytes, &too_big);
145
+ const std::string rel = fs::relative(p, root, ec).string();
146
+ if (too_big) { g.skipped.emplace_back(rel, "over max_file_bytes"); continue; }
147
+ if (text.empty()) { g.skipped.emplace_back(rel, "empty or unreadable"); continue; }
148
+ if (looks_binary(text.substr(0, 512))) {
149
+ g.skipped.emplace_back(rel, "binary");
150
+ continue;
151
+ }
152
+
153
+ FileNode f;
154
+ f.id = static_cast<int>(g.files.size());
155
+ f.path = rel;
156
+ f.language = lang;
157
+ f.bytes = text.size();
158
+ g.files.push_back(f);
159
+ texts.push_back(text);
160
+ by_stem[p.filename().string()] = f.id;
161
+ by_stem[p.stem().string()] = f.id;
162
+ }
163
+
164
+ // Symbols
165
+ for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
166
+ const auto& pats = defs_for(g.files[fi].language);
167
+ if (pats.empty()) continue;
168
+ const std::string& text = texts[fi];
169
+ std::size_t off = 0;
170
+ int line_no = 0;
171
+ std::istringstream in(text);
172
+ std::string line;
173
+ while (std::getline(in, line)) {
174
+ ++line_no;
175
+ for (const auto& [re, kind] : pats) {
176
+ std::smatch m;
177
+ if (std::regex_search(line, m, re)) {
178
+ SymbolNode s;
179
+ s.id = static_cast<int>(g.symbols.size());
180
+ s.kind = kind;
181
+ s.name = m[1].str();
182
+ s.file = static_cast<int>(fi);
183
+ s.line = line_no;
184
+ s.offset = off;
185
+ g.symbols.push_back(s);
186
+ g.files[fi].symbols++;
187
+ break;
188
+ }
189
+ }
190
+ off += line.size() + 1;
191
+ }
192
+ }
193
+
194
+ // Edges from imports/includes, resolved by filename or stem.
195
+ std::set<std::pair<int, int>> seen;
196
+ for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
197
+ for (const std::string& imp : imports_of(texts[fi], g.files[fi].language)) {
198
+ fs::path ip(imp);
199
+ for (const std::string& key : {ip.filename().string(), ip.stem().string()}) {
200
+ const auto hit = by_stem.find(key);
201
+ if (hit == by_stem.end() || hit->second == static_cast<int>(fi)) continue;
202
+ if (!seen.insert({static_cast<int>(fi), hit->second}).second) break;
203
+ g.edges.push_back({static_cast<int>(fi), hit->second, EdgeKind::Includes});
204
+ break;
205
+ }
206
+ }
207
+ }
208
+ return g;
209
+ }
210
+
211
+ std::string graph_summary(const CodeGraph& g) {
212
+ std::map<std::string, int> per_lang;
213
+ std::size_t bytes = 0;
214
+ for (const auto& f : g.files) { per_lang[f.language]++; bytes += f.bytes; }
215
+ std::ostringstream o;
216
+ o << "files=" << g.files.size() << " symbols=" << g.symbols.size()
217
+ << " edges=" << g.edges.size() << " bytes=" << bytes
218
+ << " skipped=" << g.skipped.size() << " langs=";
219
+ bool first = true;
220
+ for (const auto& [l, n] : per_lang) {
221
+ o << (first ? "" : ",") << l << ":" << n;
222
+ first = false;
223
+ }
224
+ return o.str();
225
+ }
226
+
227
+ // Dependency-first ordering: a file appears after the files it includes, so a
228
+ // segment carrying a caller has a decent chance of following its callee. Cycles
229
+ // are broken arbitrarily rather than dropped -- coverage matters more than order.
230
+ static std::vector<int> topo_order(const CodeGraph& g) {
231
+ const int n = static_cast<int>(g.files.size());
232
+ std::vector<std::vector<int>> out(n);
233
+ std::vector<int> indeg(n, 0);
234
+ for (const auto& e : g.edges) {
235
+ if (e.from == e.to) continue;
236
+ out[e.to].push_back(e.from); // dependency -> dependent
237
+ indeg[e.from]++;
238
+ }
239
+ std::vector<int> ready, order;
240
+ for (int i = 0; i < n; ++i) {
241
+ if (indeg[i] == 0) ready.push_back(i);
242
+ }
243
+ std::vector<bool> done(n, false);
244
+ while (!ready.empty()) {
245
+ const int v = ready.back();
246
+ ready.pop_back();
247
+ if (done[v]) continue;
248
+ done[v] = true;
249
+ order.push_back(v);
250
+ for (int w : out[v]) {
251
+ if (--indeg[w] == 0) ready.push_back(w);
252
+ }
253
+ }
254
+ for (int i = 0; i < n; ++i) {
255
+ if (!done[i]) order.push_back(i); // cycle members
256
+ }
257
+ return order;
258
+ }
259
+
260
+ std::vector<Segment> plan_codebase(const CodeGraph& g, const ManifestOptions& opt,
261
+ std::string* packed_text) {
262
+ packed_text->clear();
263
+ std::vector<Segment> segs;
264
+ if (g.files.empty()) return segs;
265
+
266
+ // Pack files in dependency order into one buffer with explicit headers, so
267
+ // the model always knows which file a fragment came from, then cut segments
268
+ // on file boundaries.
269
+ struct Placed { std::size_t start, end; };
270
+ std::vector<Placed> placed;
271
+ placed.reserve(g.files.size());
272
+
273
+ for (int fi : topo_order(g)) {
274
+ const FileNode& f = g.files[fi];
275
+ std::error_code ec;
276
+ std::ifstream in(fs::path(g.root) / f.path, std::ios::binary);
277
+ std::ostringstream ss;
278
+ ss << in.rdbuf();
279
+ const std::size_t start = packed_text->size();
280
+ *packed_text += "\n===== FILE " + f.path + " (" + f.language + ") =====\n";
281
+ *packed_text += ss.str();
282
+ placed.push_back({start, packed_text->size()});
283
+ }
284
+
285
+ // Greedy: accumulate whole files until the next one would overflow.
286
+ int index = 0;
287
+ std::size_t seg_start = 0;
288
+ for (std::size_t i = 0; i < placed.size(); ++i) {
289
+ const std::size_t seg_end = placed[i].end;
290
+ const bool last = (i + 1 == placed.size());
291
+ const std::size_t next_end = last ? seg_end : placed[i + 1].end;
292
+
293
+ if (last || next_end - seg_start > opt.segment_chars) {
294
+ Segment s;
295
+ s.index = index++;
296
+ s.offset = seg_start;
297
+ s.length = seg_end - seg_start;
298
+ s.overlap_prefix = 0;
299
+ segs.push_back(s);
300
+ seg_start = seg_end;
301
+ }
302
+ }
303
+
304
+ // A single file larger than a segment still has to be split; fall back to
305
+ // line-boundary cutting inside it rather than dropping it.
306
+ std::vector<Segment> final_segs;
307
+ for (const Segment& s : segs) {
308
+ if (s.length <= opt.segment_chars) { final_segs.push_back(s); continue; }
309
+ const std::string sub = packed_text->substr(s.offset, s.length);
310
+ for (Segment inner : plan(sub, opt)) {
311
+ inner.offset += s.offset;
312
+ final_segs.push_back(inner);
313
+ }
314
+ }
315
+ for (std::size_t i = 0; i < final_segs.size(); ++i) {
316
+ final_segs[i].index = static_cast<int>(i);
317
+ }
318
+ return final_segs;
319
+ }
320
+
321
+ } // namespace ctxstream
ctxstream/src/ctxstream.hpp ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ctxstream -- treat an oversized context like a video stream.
2
+ //
3
+ // The failure this exists to fix, measured on a 4B model over a 261,226-token
4
+ // corpus on a 6GB card: the model swept every segment correctly and then, asked
5
+ // which label was least common, replied "Status: beta, Status: delta, Status:
6
+ // gamma, Status: alpha". It listed the candidates instead of selecting. Earlier
7
+ // runs with more segments combined 65 partial counts wrongly.
8
+ //
9
+ // Both failures are the same mistake in the harness, not the model: a language
10
+ // model was asked to plan a traversal and to aggregate arithmetic. Streaming
11
+ // splits those out.
12
+ //
13
+ // manifest segments planned in code, up front, deterministic
14
+ // buffer N segments in flight, latency hidden behind compute
15
+ // decode model sees ONE segment, emits STRUCTURED records, never prose
16
+ // reduce aggregation in code, over parsed records
17
+ //
18
+ // The model's only job is extraction from a window it comfortably fits.
19
+ #pragma once
20
+
21
+ #include <cstdint>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ namespace ctxstream {
26
+
27
+ // ---------------------------------------------------------------- manifest
28
+
29
+ struct Segment {
30
+ int index = 0;
31
+ std::size_t offset = 0;
32
+ std::size_t length = 0;
33
+ // Segments may overlap so a record straddling a boundary is seen whole by at
34
+ // least one segment. The reducer dedupes on record identity.
35
+ std::size_t overlap_prefix = 0;
36
+ };
37
+
38
+ struct ManifestOptions {
39
+ // Sized to what the serving model actually fits, not what it advertises.
40
+ // Measured: gemma4:e4b holds 32,768 tokens in 3.3GB on a 6GB card.
41
+ std::size_t segment_chars = 60000;
42
+ std::size_t overlap_chars = 400;
43
+ // Prefer splitting on a record boundary within this slack of the target, so
44
+ // segments do not cut a row in half.
45
+ std::size_t boundary_slack = 4000;
46
+ std::string record_delim = "\n";
47
+ };
48
+
49
+ // Deterministic. No model call. Runs before anything is dispatched, which is
50
+ // the point: the plan cannot be wrong in a way the model has to recover from.
51
+ std::vector<Segment> plan(const std::string& text, const ManifestOptions& opt);
52
+
53
+ std::string segment_text(const std::string& text, const Segment& s);
54
+
55
+ // ---------------------------------------------------------------- codegraph
56
+ //
57
+ // A codebase is not a character stream. Cutting it every N chars splits
58
+ // functions, separates a call from its definition, and hands the model
59
+ // fragments no human would review. When the input is a directory, the default
60
+ // path is: scan -> graph -> segment along graph structure -> stream.
61
+
62
+ enum class NodeKind { File, Function, Class, Struct, Other };
63
+
64
+ struct SymbolNode {
65
+ int id = 0;
66
+ NodeKind kind = NodeKind::Other;
67
+ std::string name;
68
+ int file = 0; // index into CodeGraph::files
69
+ int line = 0;
70
+ std::size_t offset = 0;
71
+ std::size_t length = 0;
72
+ };
73
+
74
+ enum class EdgeKind { Includes, References };
75
+
76
+ struct GraphEdge {
77
+ int from = 0; // file index
78
+ int to = 0; // file index
79
+ EdgeKind kind = EdgeKind::Includes;
80
+ };
81
+
82
+ struct FileNode {
83
+ int id = 0;
84
+ std::string path; // relative to the scanned root
85
+ std::string language;
86
+ std::size_t bytes = 0;
87
+ int symbols = 0;
88
+ };
89
+
90
+ struct CodeGraph {
91
+ std::string root;
92
+ std::vector<FileNode> files;
93
+ std::vector<SymbolNode> symbols;
94
+ std::vector<GraphEdge> edges;
95
+ // Files skipped and why, so a sweep can never silently miss part of the
96
+ // repo and still report a confident answer.
97
+ std::vector<std::pair<std::string, std::string>> skipped;
98
+ };
99
+
100
+ struct ScanOptions {
101
+ std::size_t max_file_bytes = 2u * 1024 * 1024;
102
+ std::vector<std::string> exclude_dirs = {
103
+ ".git", "node_modules", "build", "dist", "__pycache__", ".venv",
104
+ "venv", "target", ".mypy_cache", ".pytest_cache", "vendor"};
105
+ bool follow_symlinks = false;
106
+ };
107
+
108
+ CodeGraph scan_repo(const std::string& root, const ScanOptions& opt);
109
+
110
+ // Segments that respect the graph: a file is never split mid-symbol, and files
111
+ // are ordered so that a file follows the ones it includes wherever the include
112
+ // graph is acyclic. Large files fall back to symbol-boundary splitting.
113
+ std::vector<Segment> plan_codebase(const CodeGraph& g,
114
+ const ManifestOptions& opt,
115
+ std::string* packed_text);
116
+
117
+ std::string graph_summary(const CodeGraph& g);
118
+
119
+ // ---------------------------------------------------------------- backend
120
+
121
+ struct Completion {
122
+ std::string text;
123
+ long prompt_tokens = 0; // 0 when the server does not report it
124
+ long output_tokens = 0;
125
+ bool ok = false;
126
+ std::string error;
127
+ };
128
+
129
+ struct BackendOptions {
130
+ std::string host = "127.0.0.1";
131
+ int port = 11434;
132
+ std::string model = "gemma4:e4b";
133
+ std::string path = "/api/chat"; // native route: honours num_ctx AND reports
134
+ // prompt_eval_count. The OpenAI-compatible
135
+ // route silently ignores num_ctx.
136
+ int num_ctx = 32768;
137
+ int num_predict = 1024;
138
+ int timeout_sec = 900;
139
+ };
140
+
141
+ Completion complete(const BackendOptions& opt,
142
+ const std::string& system_prompt,
143
+ const std::string& user_prompt);
144
+
145
+ // Guard against the failure that produced a confident answer from a fragment:
146
+ // a server that quietly clips the prompt and never says so. Returns true when
147
+ // the reported prompt token count is implausibly small for what was sent.
148
+ bool looks_truncated(std::size_t prompt_chars, long prompt_tokens);
149
+
150
+ // ---------------------------------------------------------------- pipeline
151
+
152
+ struct SegmentResult {
153
+ int index = 0;
154
+ std::string raw; // exactly what the model returned
155
+ bool ok = false;
156
+ bool truncated = false;
157
+ std::string error;
158
+ long prompt_tokens = 0;
159
+ long output_tokens = 0;
160
+ double seconds = 0.0;
161
+ };
162
+
163
+ struct PipelineOptions {
164
+ // Segments in flight. Buffering, in the video sense: keeps the model busy
165
+ // while the next prompt is being assembled.
166
+ int concurrency = 2;
167
+ int max_retries = 2;
168
+ bool verbose = true;
169
+ };
170
+
171
+ // Streams every segment through the model. Returns results in segment order.
172
+ // Never aggregates, never interprets -- that is the reducer's job.
173
+ std::vector<SegmentResult> stream(const std::string& text,
174
+ const std::vector<Segment>& segments,
175
+ const std::string& extract_prompt,
176
+ const BackendOptions& backend,
177
+ const PipelineOptions& pipe);
178
+
179
+ // ---------------------------------------------------------------- reduce
180
+
181
+ // One parsed record from a segment. The extraction prompt asks for
182
+ // "<key>\t<count>" lines, which is cheap for a small model to emit correctly
183
+ // and unambiguous to parse -- unlike prose summaries.
184
+ struct Record {
185
+ std::string key;
186
+ double value = 0.0;
187
+ };
188
+
189
+ std::vector<Record> parse_records(const std::string& raw);
190
+
191
+ struct Tally {
192
+ std::vector<std::pair<std::string, double>> sorted; // ascending by value
193
+ double total = 0.0;
194
+ int parsed_records = 0;
195
+ int unparsed_lines = 0;
196
+ };
197
+
198
+ // Sums per key across every segment. This is the step the model kept getting
199
+ // wrong; here it is a loop.
200
+ Tally tally(const std::vector<SegmentResult>& results);
201
+
202
+ // Answer construction is chosen explicitly, after the sweep -- not improvised
203
+ // by the model mid-traversal.
204
+ enum class Answer { Least, Most, Total, List };
205
+
206
+ std::string construct(const Tally& t, Answer how, const std::string& label = "Answer");
207
+
208
+ } // namespace ctxstream
ctxstream/src/main.cpp ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ctxstream.hpp"
2
+
3
+ #include <chrono>
4
+ #include <cstdio>
5
+ #include <cstring>
6
+ #include <filesystem>
7
+ #include <fstream>
8
+ #include <iostream>
9
+ #include <sstream>
10
+ #include <string>
11
+
12
+ namespace fs = std::filesystem;
13
+ using namespace ctxstream;
14
+
15
+ static void usage() {
16
+ std::fprintf(stderr,
17
+ "ctxstream -- stream an oversized context past a small model, reduce in code.\n\n"
18
+ "Usage:\n"
19
+ " ctxstream --input <file|dir> --extract <prompt> [options]\n\n"
20
+ "A directory input builds a code graph first and segments along it.\n\n"
21
+ "Options:\n"
22
+ " --input PATH file, or directory for codebase mode\n"
23
+ " --extract PROMPT what each fragment should emit as <key>\\t<number>\n"
24
+ " --answer MODE least | most | total | list (default: list)\n"
25
+ " --label TEXT answer label (default: Answer)\n"
26
+ " --model NAME ollama model (default: gemma4:e4b)\n"
27
+ " --host H --port P model server (default: 127.0.0.1:11434)\n"
28
+ " --num-ctx N per-call window (default: 32768)\n"
29
+ " --segment-chars N fragment size (default: 60000)\n"
30
+ " --concurrency N fragments in flight (default: 2)\n"
31
+ " --plan-only print the plan and exit, no model calls\n"
32
+ " --graph-only print the code graph and exit\n"
33
+ " --quiet suppress progress\n");
34
+ }
35
+
36
+ static std::string slurp(const fs::path& p) {
37
+ std::ifstream in(p, std::ios::binary);
38
+ std::ostringstream ss;
39
+ ss << in.rdbuf();
40
+ return ss.str();
41
+ }
42
+
43
+ int main(int argc, char** argv) {
44
+ std::string input, extract, answer_mode = "list", label = "Answer";
45
+ BackendOptions backend;
46
+ ManifestOptions manifest;
47
+ PipelineOptions pipe;
48
+ bool plan_only = false, graph_only = false;
49
+
50
+ for (int i = 1; i < argc; ++i) {
51
+ const std::string a = argv[i];
52
+ auto next = [&]() -> std::string {
53
+ return (i + 1 < argc) ? argv[++i] : std::string();
54
+ };
55
+ if (a == "--input") input = next();
56
+ else if (a == "--extract") extract = next();
57
+ else if (a == "--answer") answer_mode = next();
58
+ else if (a == "--label") label = next();
59
+ else if (a == "--model") backend.model = next();
60
+ else if (a == "--host") backend.host = next();
61
+ else if (a == "--port") backend.port = std::stoi(next());
62
+ else if (a == "--num-ctx") backend.num_ctx = std::stoi(next());
63
+ else if (a == "--segment-chars") manifest.segment_chars = std::stoul(next());
64
+ else if (a == "--concurrency") pipe.concurrency = std::stoi(next());
65
+ else if (a == "--plan-only") plan_only = true;
66
+ else if (a == "--graph-only") graph_only = true;
67
+ else if (a == "--quiet") pipe.verbose = false;
68
+ else if (a == "-h" || a == "--help") { usage(); return 0; }
69
+ else { std::fprintf(stderr, "unknown option: %s\n", a.c_str()); usage(); return 2; }
70
+ }
71
+ if (input.empty()) { usage(); return 2; }
72
+
73
+ std::error_code ec;
74
+ if (!fs::exists(input, ec)) {
75
+ std::fprintf(stderr, "no such input: %s\n", input.c_str());
76
+ return 2;
77
+ }
78
+
79
+ std::string text;
80
+ std::vector<Segment> segments;
81
+ const bool codebase = fs::is_directory(input, ec);
82
+
83
+ if (codebase) {
84
+ // Default path for a repo: graph first, then segment along it.
85
+ const CodeGraph g = scan_repo(input, ScanOptions{});
86
+ std::fprintf(stderr, "[ctxstream] graph %s\n", graph_summary(g).c_str());
87
+ for (const auto& [p, why] : g.skipped) {
88
+ std::fprintf(stderr, "[ctxstream] skipped %s (%s)\n", p.c_str(), why.c_str());
89
+ }
90
+ if (graph_only) {
91
+ for (const auto& f : g.files) {
92
+ std::printf("FILE\t%s\t%s\t%zu\t%d\n", f.path.c_str(),
93
+ f.language.c_str(), f.bytes, f.symbols);
94
+ }
95
+ for (const auto& s : g.symbols) {
96
+ std::printf("SYM\t%s\t%s:%d\n", s.name.c_str(),
97
+ g.files[s.file].path.c_str(), s.line);
98
+ }
99
+ for (const auto& e : g.edges) {
100
+ std::printf("EDGE\t%s\t->\t%s\n", g.files[e.from].path.c_str(),
101
+ g.files[e.to].path.c_str());
102
+ }
103
+ return 0;
104
+ }
105
+ if (g.files.empty()) {
106
+ std::fprintf(stderr, "no source files found under %s\n", input.c_str());
107
+ return 1;
108
+ }
109
+ segments = plan_codebase(g, manifest, &text);
110
+ } else {
111
+ text = slurp(input);
112
+ if (text.empty()) { std::fprintf(stderr, "empty input\n"); return 1; }
113
+ segments = plan(text, manifest);
114
+ }
115
+
116
+ std::fprintf(stderr, "[ctxstream] %zu chars -> %zu segments (<=%zu chars each)\n",
117
+ text.size(), segments.size(), manifest.segment_chars);
118
+ if (plan_only) {
119
+ for (const auto& s : segments) {
120
+ std::printf("SEG\t%d\t%zu\t%zu\n", s.index, s.offset, s.length);
121
+ }
122
+ return 0;
123
+ }
124
+ if (extract.empty()) {
125
+ std::fprintf(stderr, "--extract is required unless --plan-only/--graph-only\n");
126
+ return 2;
127
+ }
128
+
129
+ const auto t0 = std::chrono::steady_clock::now();
130
+ const std::vector<SegmentResult> results =
131
+ stream(text, segments, extract, backend, pipe);
132
+
133
+ int failed = 0;
134
+ for (const auto& r : results) {
135
+ if (!r.ok) ++failed;
136
+ }
137
+ const Tally t = tally(results);
138
+
139
+ Answer how = Answer::List;
140
+ if (answer_mode == "least") how = Answer::Least;
141
+ else if (answer_mode == "most") how = Answer::Most;
142
+ else if (answer_mode == "total") how = Answer::Total;
143
+
144
+ const double secs = std::chrono::duration<double>(
145
+ std::chrono::steady_clock::now() - t0).count();
146
+ std::fprintf(stderr,
147
+ "[ctxstream] failed=%d/%zu records=%d unparsed_lines=%d keys=%zu %.1fs\n",
148
+ failed, results.size(), t.parsed_records, t.unparsed_lines,
149
+ t.sorted.size(), secs);
150
+
151
+ // A partial sweep must never be reported as a clean answer.
152
+ if (failed) {
153
+ std::fprintf(stderr,
154
+ "[ctxstream] REFUSING a headline answer: %d segment(s) failed, "
155
+ "so every key is undercounted. Fix and rerun, or use --answer list.\n",
156
+ failed);
157
+ if (how != Answer::List) return 1;
158
+ }
159
+
160
+ std::cout << construct(t, how, label) << std::endl;
161
+ return 0;
162
+ }
ctxstream/src/manifest.cpp ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ctxstream.hpp"
2
+
3
+ #include <algorithm>
4
+
5
+ namespace ctxstream {
6
+
7
+ // Walk back from the target cut to the nearest record delimiter, so a segment
8
+ // never ends mid-row. A row split across two segments is counted twice or not
9
+ // at all, and both are silent corruption of the tally.
10
+ static std::size_t snap_to_boundary(const std::string& text, std::size_t target,
11
+ const ManifestOptions& opt) {
12
+ if (target >= text.size()) return text.size();
13
+ const std::size_t floor =
14
+ target > opt.boundary_slack ? target - opt.boundary_slack : 0;
15
+ const std::size_t hit = text.rfind(opt.record_delim, target);
16
+ if (hit != std::string::npos && hit >= floor) {
17
+ return hit + opt.record_delim.size();
18
+ }
19
+ // No delimiter within slack: the data is not row-shaped, cut where asked.
20
+ return target;
21
+ }
22
+
23
+ std::vector<Segment> plan(const std::string& text, const ManifestOptions& opt) {
24
+ std::vector<Segment> out;
25
+ if (text.empty() || opt.segment_chars == 0) return out;
26
+
27
+ std::size_t pos = 0;
28
+ int index = 0;
29
+ while (pos < text.size()) {
30
+ const std::size_t want = std::min(pos + opt.segment_chars, text.size());
31
+ const std::size_t end = snap_to_boundary(text, want, opt);
32
+ // snap_to_boundary can land at or before pos on pathological input
33
+ // (a single row longer than the segment); force progress.
34
+ const std::size_t stop = end > pos ? end : want;
35
+
36
+ Segment s;
37
+ s.index = index++;
38
+ s.overlap_prefix = std::min(pos, opt.overlap_chars);
39
+ s.offset = pos - s.overlap_prefix;
40
+ s.length = stop - s.offset;
41
+ out.push_back(s);
42
+
43
+ if (stop >= text.size()) break;
44
+ pos = stop;
45
+ }
46
+ return out;
47
+ }
48
+
49
+ std::string segment_text(const std::string& text, const Segment& s) {
50
+ if (s.offset >= text.size()) return {};
51
+ return text.substr(s.offset, std::min(s.length, text.size() - s.offset));
52
+ }
53
+
54
+ } // namespace ctxstream
ctxstream/src/pipeline.cpp ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ctxstream.hpp"
2
+
3
+ #include <atomic>
4
+ #include <chrono>
5
+ #include <cstdio>
6
+ #include <mutex>
7
+ #include <thread>
8
+ #include <vector>
9
+
10
+ namespace ctxstream {
11
+
12
+ // The extraction contract. Kept short and mechanical on purpose: a small model
13
+ // asked for prose produces prose that no parser can trust, and prose is exactly
14
+ // what broke the aggregation in the Python harness this replaces.
15
+ static const char* kExtractSystem =
16
+ "You extract structured data from one fragment of a larger corpus.\n"
17
+ "Rules:\n"
18
+ "1. Output ONLY lines of the form <key><TAB><number>. Nothing else.\n"
19
+ "2. No preamble, no explanation, no markdown, no totals.\n"
20
+ "3. Count only what is present in THIS fragment. Do not guess about the rest.\n"
21
+ "4. If nothing matches, output exactly: NONE";
22
+
23
+ std::vector<SegmentResult> stream(const std::string& text,
24
+ const std::vector<Segment>& segments,
25
+ const std::string& extract_prompt,
26
+ const BackendOptions& backend,
27
+ const PipelineOptions& pipe) {
28
+ std::vector<SegmentResult> results(segments.size());
29
+ if (segments.empty()) return results;
30
+
31
+ std::atomic<std::size_t> next{0};
32
+ std::atomic<int> done{0}, failed{0};
33
+ std::mutex log_mu;
34
+ const auto t0 = std::chrono::steady_clock::now();
35
+
36
+ // "Buffer depth" in the video sense: this many segments decoding at once.
37
+ const int workers =
38
+ std::max(1, std::min<int>(pipe.concurrency, static_cast<int>(segments.size())));
39
+
40
+ auto worker = [&] {
41
+ for (;;) {
42
+ const std::size_t i = next.fetch_add(1);
43
+ if (i >= segments.size()) return;
44
+
45
+ const Segment& seg = segments[i];
46
+ const std::string body = segment_text(text, seg);
47
+ const std::string prompt =
48
+ extract_prompt + "\n\n--- FRAGMENT " + std::to_string(seg.index + 1) +
49
+ " of " + std::to_string(segments.size()) + " ---\n" + body;
50
+
51
+ SegmentResult r;
52
+ r.index = seg.index;
53
+ const auto s0 = std::chrono::steady_clock::now();
54
+
55
+ for (int attempt = 0; attempt <= pipe.max_retries; ++attempt) {
56
+ const Completion c = complete(backend, kExtractSystem, prompt);
57
+ if (!c.ok) { r.error = c.error; continue; }
58
+ r.prompt_tokens = c.prompt_tokens;
59
+ r.output_tokens = c.output_tokens;
60
+ // A server that clipped the prompt will answer confidently from
61
+ // the part it kept. Never accept that as a segment result.
62
+ if (looks_truncated(prompt.size(), c.prompt_tokens)) {
63
+ r.truncated = true;
64
+ r.error = "server processed " + std::to_string(c.prompt_tokens) +
65
+ " tokens of a " + std::to_string(prompt.size()) +
66
+ "-char prompt";
67
+ break;
68
+ }
69
+ r.raw = c.text;
70
+ r.ok = true;
71
+ r.error.clear();
72
+ break;
73
+ }
74
+
75
+ r.seconds = std::chrono::duration<double>(
76
+ std::chrono::steady_clock::now() - s0).count();
77
+ results[i] = r;
78
+
79
+ const int d = ++done;
80
+ if (!r.ok) ++failed;
81
+ if (pipe.verbose) {
82
+ std::lock_guard<std::mutex> lk(log_mu);
83
+ const double elapsed = std::chrono::duration<double>(
84
+ std::chrono::steady_clock::now() - t0).count();
85
+ const double eta = d ? elapsed / d * (segments.size() - d) : 0.0;
86
+ // Failures first: a climbing error count must be visible within
87
+ // seconds, not discovered after the run.
88
+ std::fprintf(stderr,
89
+ "[ctxstream] failed=%d %d/%zu seg=%d %.1fs eta=%.1fm\n",
90
+ failed.load(), d, segments.size(), r.index, r.seconds,
91
+ eta / 60.0);
92
+ }
93
+ }
94
+ };
95
+
96
+ std::vector<std::thread> pool;
97
+ pool.reserve(workers);
98
+ for (int i = 0; i < workers; ++i) pool.emplace_back(worker);
99
+ for (auto& t : pool) t.join();
100
+
101
+ if (pipe.verbose && failed) {
102
+ std::fprintf(stderr, "[ctxstream] WARNING: %d/%zu segments failed\n",
103
+ failed.load(), segments.size());
104
+ }
105
+ return results;
106
+ }
107
+
108
+ } // namespace ctxstream
ctxstream/src/reduce.cpp ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ctxstream.hpp"
2
+
3
+ #include <algorithm>
4
+ #include <cctype>
5
+ #include <map>
6
+ #include <sstream>
7
+
8
+ namespace ctxstream {
9
+
10
+ static std::string trim(const std::string& s) {
11
+ std::size_t a = 0, b = s.size();
12
+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
13
+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
14
+ return s.substr(a, b - a);
15
+ }
16
+
17
+ static bool to_number(const std::string& s, double* out) {
18
+ if (s.empty()) return false;
19
+ std::string clean;
20
+ for (char c : s) {
21
+ if (c != ',' && c != '_') clean += c; // 1,234 and 1_234
22
+ }
23
+ try {
24
+ std::size_t used = 0;
25
+ const double v = std::stod(clean, &used);
26
+ if (used != clean.size()) return false;
27
+ *out = v;
28
+ return true;
29
+ } catch (...) {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ std::vector<Record> parse_records(const std::string& raw) {
35
+ std::vector<Record> out;
36
+ std::istringstream in(raw);
37
+ std::string line;
38
+ while (std::getline(in, line)) {
39
+ const std::string t = trim(line);
40
+ if (t.empty() || t == "NONE") continue;
41
+
42
+ // Split on the last tab, else the last run of whitespace, else a colon.
43
+ // Keys legitimately contain spaces ("Spatial Relationship"), which is
44
+ // exactly the case a naive \S+ split truncated in the previous harness.
45
+ std::size_t cut = t.rfind('\t');
46
+ if (cut == std::string::npos) {
47
+ const std::size_t colon = t.rfind(':');
48
+ const std::size_t space = t.find_last_of(" ");
49
+ cut = (colon != std::string::npos && colon > space) ? colon : space;
50
+ }
51
+ if (cut == std::string::npos || cut == 0) continue;
52
+
53
+ double v = 0.0;
54
+ if (!to_number(trim(t.substr(cut + 1)), &v)) continue;
55
+ const std::string key = trim(t.substr(0, cut));
56
+ if (key.empty()) continue;
57
+ out.push_back({key, v});
58
+ }
59
+ return out;
60
+ }
61
+
62
+ Tally tally(const std::vector<SegmentResult>& results) {
63
+ Tally out;
64
+ std::map<std::string, double> sums;
65
+ for (const SegmentResult& r : results) {
66
+ if (!r.ok) continue; // a failed segment contributes nothing, silently
67
+ // dropping it would understate every key
68
+ const std::vector<Record> recs = parse_records(r.raw);
69
+ out.parsed_records += static_cast<int>(recs.size());
70
+ // Count lines the model produced that no parser could use, so a model
71
+ // ignoring the output contract is visible rather than just quiet.
72
+ int lines = 0;
73
+ std::istringstream in(r.raw);
74
+ std::string l;
75
+ while (std::getline(in, l)) {
76
+ if (!trim(l).empty() && trim(l) != "NONE") ++lines;
77
+ }
78
+ out.unparsed_lines += std::max(0, lines - static_cast<int>(recs.size()));
79
+ for (const Record& rec : recs) {
80
+ sums[rec.key] += rec.value;
81
+ out.total += rec.value;
82
+ }
83
+ }
84
+ out.sorted.assign(sums.begin(), sums.end());
85
+ std::sort(out.sorted.begin(), out.sorted.end(),
86
+ [](const auto& a, const auto& b) {
87
+ if (a.second != b.second) return a.second < b.second;
88
+ return a.first < b.first; // stable, reproducible ties
89
+ });
90
+ return out;
91
+ }
92
+
93
+ static std::string fmt(double v) {
94
+ std::ostringstream o;
95
+ if (v == static_cast<long long>(v)) o << static_cast<long long>(v);
96
+ else o << v;
97
+ return o.str();
98
+ }
99
+
100
+ std::string construct(const Tally& t, Answer how, const std::string& label) {
101
+ if (t.sorted.empty()) return label + ": NONE";
102
+ switch (how) {
103
+ case Answer::Least:
104
+ return label + ": " + t.sorted.front().first;
105
+ case Answer::Most:
106
+ return label + ": " + t.sorted.back().first;
107
+ case Answer::Total:
108
+ return label + ": " + fmt(t.total);
109
+ case Answer::List: {
110
+ std::ostringstream o;
111
+ for (const auto& [k, v] : t.sorted) o << k << "\t" << fmt(v) << "\n";
112
+ return o.str();
113
+ }
114
+ }
115
+ return label + ": NONE";
116
+ }
117
+
118
+ } // namespace ctxstream