memhouse 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -11
- package/bin/memhouse.js +129 -122
- package/memhouse/DESIGN.md +29 -30
- package/memhouse/delivery/PROMPT.md +7 -9
- package/memhouse/delivery/kernel-install.md +14 -29
- package/memhouse/delivery/plugin/skills/search/SKILL.md +25 -38
- package/memhouse/delivery/plugin/skills/sessions/SKILL.md +15 -28
- package/memhouse/delivery/plugin/skills/sql/SKILL.md +23 -36
- package/memhouse/host.js +1 -1
- package/memhouse/house/HOUSE.md +74 -0
- package/memhouse/house/house.js +165 -0
- package/memhouse/{per-member/schema-member.sql.tpl → house/schema.sql.tpl} +8 -11
- package/memhouse/resume.js +1 -1
- package/memhouse/server/queries.js +8 -2
- package/memhouse/shipper/ship.js +24 -30
- package/package.json +1 -1
- package/memhouse/per-member/INSTALL.md +0 -228
- package/memhouse/per-member/PLAN.md +0 -174
- package/memhouse/per-member/PROVISIONING.md +0 -177
- package/memhouse/per-member/README.md +0 -48
- package/memhouse/per-member/SCHEMA.md +0 -120
- package/memhouse/per-member/SHARING.md +0 -149
- package/memhouse/per-member/provision.js +0 -297
- package/memhouse/per-member/rooms.js +0 -252
- package/memhouse/per-member/schema-merge.sql.tpl +0 -24
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// mem — provision one member's rooms and grants. Idempotent; also the schema-rollout hook.
|
|
3
|
-
//
|
|
4
|
-
// provision.js --member <name> [--merge] [--owner-grants]
|
|
5
|
-
//
|
|
6
|
-
// Run as the OWNER. Steps, all IF NOT EXISTS / re-runnable:
|
|
7
|
-
// 1. create the member's three rooms from schema-member.sql.tpl
|
|
8
|
-
// 2. grant the member their own three rooms, TWO statements each: MEMBER_PRIVS (not
|
|
9
|
-
// re-grantable), then `SELECT WITH GRANT OPTION`. The split is the point —
|
|
10
|
-
// MEMBER_PRIVS is exactly what the shipper uses and nothing that DEFINES an object,
|
|
11
|
-
// and attaching grant-option to `SELECT` alone makes a share read-only by
|
|
12
|
-
// construction. It is deliberately NOT `ALL`: that includes CREATE TABLE on the
|
|
13
|
-
// member's own room name, which lets them replace the room with a Merge over every
|
|
14
|
-
// member's and double the others' rows in the team room. See rooms.js.
|
|
15
|
-
//
|
|
16
|
-
// THREE ROOMS, not four objects: the session rollup is a saved query over these
|
|
17
|
-
// same rooms, not a stored view, so it needs no object and no grant of its own.
|
|
18
|
-
// 3. --merge: create/refresh the three Merge rooms, borrowing this member's columns
|
|
19
|
-
// 4. grant the member SELECT on whichever Merge rooms exist — a Merge reduces to the
|
|
20
|
-
// rooms the caller can already read, so this is what makes the team room fail
|
|
21
|
-
// CLOSED rather than deny outright
|
|
22
|
-
//
|
|
23
|
-
// Grants are explicit, per room, and NEVER `ON mem.*` — a member who can read the whole
|
|
24
|
-
// house can read every other member's rooms, which would make this a shared house with
|
|
25
|
-
// longer table names. No wildcards are used anywhere; the only pattern in the design is
|
|
26
|
-
// the Merge regex, anchored on a fixed room type.
|
|
27
|
-
//
|
|
28
|
-
// Env: MEM_URL / MEM_USER / MEM_PASSWORD / MEM_DB, falling back to MEMHOUSE_*. URL and
|
|
29
|
-
// USER are REQUIRED — see the note at cfg. MEM_DB defaults to 'mem'.
|
|
30
|
-
|
|
31
|
-
const fs = require('fs');
|
|
32
|
-
const crypto = require('crypto');
|
|
33
|
-
const path = require('path');
|
|
34
|
-
// Named, not thrown as a raw MODULE_NOT_FOUND with a require stack. This runs as a
|
|
35
|
-
// SUBPROCESS of `memhouse install`, after the admin path has already created a ClickHouse
|
|
36
|
-
// user — so its failure mode is a half-provisioned house, and "Cannot find module" plus a
|
|
37
|
-
// stack trace is the least useful thing to print at that moment. Seen for real in a
|
|
38
|
-
// checkout where `npm install` had not been run.
|
|
39
|
-
let createClient, ClickHouseLogLevel;
|
|
40
|
-
try { ({ createClient, ClickHouseLogLevel } = require('@clickhouse/client')); }
|
|
41
|
-
catch {
|
|
42
|
-
console.error("provision.js: dependency '@clickhouse/client' is not installed.");
|
|
43
|
-
console.error(` From a checkout: npm install --prefix ${path.join(__dirname, '..', '..')}`);
|
|
44
|
-
console.error(` From an npm install: ${require('./rooms').installCommand()}`);
|
|
45
|
-
process.exit(2);
|
|
46
|
-
}
|
|
47
|
-
const { ROOM_TYPES, mergeRooms, assertUsableMember, MEMBER_PRIVS, MEMBER_PROFILE, MEMBER_PROFILE_SETTINGS } = require('./rooms');
|
|
48
|
-
|
|
49
|
-
const args = process.argv.slice(2);
|
|
50
|
-
const flag = (n) => args.includes(`--${n}`);
|
|
51
|
-
const opt = (n, d = null) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i + 1] : d; };
|
|
52
|
-
|
|
53
|
-
// Defaults MUST match what the shipper and CLI use, or an operator who overrides only
|
|
54
|
-
// the thing that differs — a password, say — silently provisions rooms in a house the
|
|
55
|
-
// product never reads, or fails to authenticate as a user that does not exist.
|
|
56
|
-
//
|
|
57
|
-
// Which is why there is no default URL or user any more, here either. This file CREATES
|
|
58
|
-
// USERS AND GRANTS; pointing it at a guessed http://localhost:8123 as memhouse_root aims
|
|
59
|
-
// the most privileged operation in the product at whatever house happens to be listening.
|
|
60
|
-
// Observed: running it with no env at all made an authentication attempt against the
|
|
61
|
-
// pilot's own ClickHouse.
|
|
62
|
-
const cfg = {
|
|
63
|
-
url: process.env.MEM_URL || process.env.MEMHOUSE_URL,
|
|
64
|
-
username: process.env.MEM_USER || process.env.MEMHOUSE_USER,
|
|
65
|
-
password: process.env.MEM_PASSWORD || process.env.MEMHOUSE_PASSWORD || '',
|
|
66
|
-
database: process.env.MEM_DB || process.env.MEMHOUSE_DB || 'mem',
|
|
67
|
-
};
|
|
68
|
-
if (!cfg.url || !cfg.username) {
|
|
69
|
-
console.error('provision.js: no house given. Set MEM_URL and MEM_USER (or MEMHOUSE_URL/MEMHOUSE_USER).');
|
|
70
|
-
console.error(' This creates users and grants — it will not guess http://localhost:8123 as memhouse_root.');
|
|
71
|
-
process.exit(2);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Statements are split on ';' at end of line — the templates contain no ';' inside a
|
|
75
|
-
// statement body, and keeping the splitter dumb keeps the templates readable.
|
|
76
|
-
function statements(sql) {
|
|
77
|
-
return sql
|
|
78
|
-
.split(/;\s*$/m)
|
|
79
|
-
.map((s) => s.replace(/^\s*--.*$/gm, '').trim())
|
|
80
|
-
.filter(Boolean);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Which of the three Merge rooms actually exist — a member may be provisioned first. */
|
|
84
|
-
async function mergeRoomsPresent(client, database) {
|
|
85
|
-
const names = Object.values(mergeRooms());
|
|
86
|
-
const rs = await client.query({
|
|
87
|
-
query: `SELECT name FROM system.tables WHERE database = {db:String} AND name IN ({names:Array(String)}) ORDER BY name`,
|
|
88
|
-
query_params: { db: database, names },
|
|
89
|
-
format: 'JSONEachRow',
|
|
90
|
-
});
|
|
91
|
-
return (await rs.json()).map((r) => r.name);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function main() {
|
|
95
|
-
const member = opt('member');
|
|
96
|
-
if (!member) { console.error('usage: provision.js --member <name> [--merge]'); process.exit(2); }
|
|
97
|
-
assertUsableMember(member);
|
|
98
|
-
|
|
99
|
-
const here = __dirname;
|
|
100
|
-
|
|
101
|
-
// Create the house with a client that has NOT selected it — on a fresh server the
|
|
102
|
-
// database does not exist yet, and selecting it fails before it can be created.
|
|
103
|
-
// See the note in shipper/ship.js: the driver's ERROR-level dump buries every
|
|
104
|
-
// refusal this file prints. MEMHOUSE_DEBUG=1 restores it.
|
|
105
|
-
const quiet = { level: process.env.MEMHOUSE_DEBUG ? ClickHouseLogLevel.DEBUG : ClickHouseLogLevel.OFF };
|
|
106
|
-
const bootstrap = createClient({ ...cfg, database: '', log: quiet });
|
|
107
|
-
await bootstrap.command({ query: `CREATE DATABASE IF NOT EXISTS ${cfg.database}` });
|
|
108
|
-
await bootstrap.close();
|
|
109
|
-
|
|
110
|
-
console.log(`[mem] provisioning in ${cfg.url} database '${cfg.database}' as '${cfg.username}'`);
|
|
111
|
-
const client = createClient({ ...cfg, log: quiet, clickhouse_settings: { async_insert: 0 } });
|
|
112
|
-
|
|
113
|
-
// 0. the member themselves.
|
|
114
|
-
//
|
|
115
|
-
// This file never created the ClickHouse user, so the path `memhouse install` prints and
|
|
116
|
-
// INSTALL.md repeats — `provision.js --member <name> --merge` — created three rooms and
|
|
117
|
-
// then died on `There is no role \`<name>\` in \`user directories\``, leaving orphan rooms
|
|
118
|
-
// that nothing removes and that the --merge step then folded into all_sessions. It also
|
|
119
|
-
// ignored --member-password. The documented second-member path did not work at all.
|
|
120
|
-
const existing = await client.query({
|
|
121
|
-
query: `SELECT name FROM system.users WHERE name = {n:String}`,
|
|
122
|
-
query_params: { n: member }, format: 'JSONEachRow',
|
|
123
|
-
});
|
|
124
|
-
if ((await existing.json()).length === 0) {
|
|
125
|
-
const pw = opt('member-password') || crypto.randomBytes(24).toString('base64url');
|
|
126
|
-
await client.command({ query: `CREATE USER ${member} IDENTIFIED BY '${pw.replace(/'/g, "\\'")}'` });
|
|
127
|
-
console.log(`[mem] created ClickHouse user '${member}'`);
|
|
128
|
-
if (!opt('member-password')) {
|
|
129
|
-
console.log(`[mem] password for '${member}': ${pw}`);
|
|
130
|
-
console.log('[mem] shown once — hand it over, or pass --member-password next time');
|
|
131
|
-
}
|
|
132
|
-
console.log(`[mem] they finish with: memhouse install --url ${cfg.url} --db ${cfg.database} --user ${member} --password '…'`);
|
|
133
|
-
} else if (flag('user-just-created')) {
|
|
134
|
-
// The caller made it moments ago and has already said so. Saying "already exists"
|
|
135
|
-
// here contradicts the line above it, and does so using the exact phrase that
|
|
136
|
-
// elsewhere means "someone else owns this handle, refusing" — which reads as a
|
|
137
|
-
// warning in the middle of a successful first install.
|
|
138
|
-
console.log(`[mem] using the ClickHouse user '${member}' just created — provisioning rooms`);
|
|
139
|
-
} else {
|
|
140
|
-
// NOT "already exists". That phrase is what the identity-takeover REFUSAL says, so
|
|
141
|
-
// reading it here — during a successful provision, and especially while resuming a
|
|
142
|
-
// first install that failed after CREATE USER — reads as a warning that someone else
|
|
143
|
-
// owns the handle. Both branches of this if now describe a success, in plain words.
|
|
144
|
-
console.log(`[mem] using the existing ClickHouse user '${member}' — provisioning rooms`);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
// 1. rooms
|
|
148
|
-
const tpl = fs.readFileSync(path.join(here, 'schema-member.sql.tpl'), 'utf-8');
|
|
149
|
-
const roomSql = statements(tpl.replaceAll('{{MEMBER}}', member));
|
|
150
|
-
for (const q of roomSql) {
|
|
151
|
-
// allow_experimental_full_text_index: a no-op on 26.x, required on 25.x for the
|
|
152
|
-
// messages text indexes.
|
|
153
|
-
await client.command({ query: q, clickhouse_settings: { allow_experimental_full_text_index: 1 } });
|
|
154
|
-
}
|
|
155
|
-
// CREATE TABLE IF NOT EXISTS is a no-op on an existing room, so re-running provision.js
|
|
156
|
-
// over a room that has DRIFTED left it lossy while printing "rooms ready". The owner's
|
|
157
|
-
// route has to heal as well as create — it is the one route that always holds the rights.
|
|
158
|
-
{
|
|
159
|
-
const { templateColumns } = require('../shipper/ship');
|
|
160
|
-
const want = templateColumns(tpl);
|
|
161
|
-
for (const ty of ROOM_TYPES) {
|
|
162
|
-
const room = `${ty}_${member}`;
|
|
163
|
-
const rs = await client.query({
|
|
164
|
-
query: 'SELECT name FROM system.columns WHERE database = {d:String} AND table = {n:String}',
|
|
165
|
-
query_params: { d: cfg.database, n: room }, format: 'JSONEachRow',
|
|
166
|
-
});
|
|
167
|
-
const have = new Set((await rs.json()).map((r) => r.name));
|
|
168
|
-
if (!have.size) continue;
|
|
169
|
-
for (const c of (want[ty] || [])) {
|
|
170
|
-
if (have.has(c.name)) continue;
|
|
171
|
-
await client.command({
|
|
172
|
-
query: `ALTER TABLE ${cfg.database}.${room} ADD COLUMN IF NOT EXISTS ${c.name} ${c.type}`,
|
|
173
|
-
clickhouse_settings: { allow_experimental_full_text_index: 1 },
|
|
174
|
-
});
|
|
175
|
-
console.log(`[mem] added missing column ${room}.${c.name}`);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
console.log(`[mem] rooms ready for '${member}': ${ROOM_TYPES.map((t) => `${t}_${member}`).join(', ')}`);
|
|
180
|
-
|
|
181
|
-
// 2. grants — two statements per room, and the split is the point.
|
|
182
|
-
//
|
|
183
|
-
// ALL, NOT re-grantable: the member owns their room outright, DROP and TRUNCATE
|
|
184
|
-
// included, because it is their memory to destroy. It also covers the mutation
|
|
185
|
-
// privileges the shipper needs without naming them — the shipper clears a session's
|
|
186
|
-
// rows before re-inserting, and which of ALTER UPDATE / ALTER DELETE a server demands
|
|
187
|
-
// varies by version (`DELETE FROM` is a lightweight delete, implemented as
|
|
188
|
-
// `ALTER TABLE … UPDATE _row_exists = 0`, so 25.11 wants ALTER UPDATE where 26.7 wanted
|
|
189
|
-
// ALTER DELETE). Granting one and not the other produces a pass that fails elsewhere.
|
|
190
|
-
//
|
|
191
|
-
// SELECT, re-grantable: a share is READ-ONLY BY CONSTRUCTION rather than by convention.
|
|
192
|
-
// `GRANT ALL … WITH GRANT OPTION` expands to 45 privileges on 26.7 — DROP TABLE,
|
|
193
|
-
// TRUNCATE, CREATE ROW POLICY, SYSTEM DROP REPLICA among them — and every one of those
|
|
194
|
-
// would become something a member could hand to a colleague while meaning "let them
|
|
195
|
-
// read my sessions". Measured: with this split, `GRANT SELECT … TO bob` succeeds and
|
|
196
|
-
// `GRANT DROP TABLE … TO bob` is refused 497.
|
|
197
|
-
// NOT `GRANT ALL`. On 26.7 that expands to 45 privileges including CREATE TABLE **on
|
|
198
|
-
// the member's own room name** — which means a member owns the NAME, not just the data,
|
|
199
|
-
// and can put any engine behind it. Measured on both versions:
|
|
200
|
-
//
|
|
201
|
-
// DROP TABLE messages_alice; -- allowed
|
|
202
|
-
// CREATE TABLE messages_alice AS all_messages
|
|
203
|
-
// ENGINE = Merge('<db>','^messages_'); -- allowed
|
|
204
|
-
//
|
|
205
|
-
// `all_messages` is Merge(db,'^messages_'), so it then contains a Merge over its own
|
|
206
|
-
// namespace and every OTHER member's rows are counted twice in the team room: a house
|
|
207
|
-
// reading alice 6030 / bob 2401 / carol 12 became bob 4802 / carol 24, silently, no
|
|
208
|
-
// error. Confidentiality survives — the Merge still narrows by grants, so alice reads
|
|
209
|
-
// nothing new — but integrity does not, and a team-wide number is the whole point of
|
|
210
|
-
// the room. SCHEMA.md already records the same failure reached by accident; this is the
|
|
211
|
-
// same failure reachable on purpose by any member.
|
|
212
|
-
//
|
|
213
|
-
// So: the privileges the shipper actually uses, and nothing that lets a member define
|
|
214
|
-
// an object. ALTER UPDATE and ALTER DELETE both, because `DELETE FROM` is a lightweight
|
|
215
|
-
// delete implemented as `ALTER TABLE … UPDATE _row_exists = 0` and which of the two a
|
|
216
|
-
// server demands varies by version (25.11 wants UPDATE where 26.7 wanted DELETE).
|
|
217
|
-
// ALTER ADD COLUMN for ensureSchema's rollout. No CREATE TABLE, no DROP TABLE, no
|
|
218
|
-
// TRUNCATE: the admin who provisioned the room is the one who can replace it.
|
|
219
|
-
//
|
|
220
|
-
// SELECT is re-grantable so a share is READ-ONLY BY CONSTRUCTION rather than by
|
|
221
|
-
// convention — `GRANT SELECT … TO bob` succeeds, `GRANT DROP TABLE … TO bob` is 497.
|
|
222
|
-
for (const t of ROOM_TYPES) {
|
|
223
|
-
const room = `${cfg.database}.${t}_${member}`;
|
|
224
|
-
await client.command({ query: `GRANT ${MEMBER_PRIVS} ON ${room} TO ${member}` });
|
|
225
|
-
await client.command({ query: `GRANT SELECT ON ${room} TO ${member} WITH GRANT OPTION` });
|
|
226
|
-
}
|
|
227
|
-
console.log(`[mem] granted ${MEMBER_PRIVS} on 3 rooms to '${member}'; SELECT is the only re-grantable one`);
|
|
228
|
-
|
|
229
|
-
// 2b. A settings profile with CEILINGS, not just defaults.
|
|
230
|
-
//
|
|
231
|
-
// Every isolation test passed on confidentiality and none existed for availability: a
|
|
232
|
-
// member could `SETTINGS max_memory_usage=100000000000`, `max_execution_time=0` and
|
|
233
|
-
// `max_threads=64` on a shared house, and take the server down for everyone. The
|
|
234
|
-
// constraint form (`MAX`) is what makes it a ceiling — a plain default is advisory and a
|
|
235
|
-
// member simply overrides it, which is what they were doing.
|
|
236
|
-
//
|
|
237
|
-
// Generous on purpose: a full re-ship of a large house is a big INSERT, and the point is
|
|
238
|
-
// to stop one member exhausting the box, not to make honest work fail.
|
|
239
|
-
// CREATE ... OR REPLACE, which this used, DETACHES every user already assigned to the
|
|
240
|
-
// profile. One shared profile plus a replace on every provision meant that adding a
|
|
241
|
-
// second member silently stripped the first member's ceilings — measured: provision
|
|
242
|
-
// kyle, then provision lena, and `SHOW CREATE USER kyle` no longer carries the profile
|
|
243
|
-
// at all. In a three-member house only the most recently provisioned member had any
|
|
244
|
-
// limit, and nothing said so.
|
|
245
|
-
//
|
|
246
|
-
// CREATE IF NOT EXISTS + ALTER updates the same object in place and keeps every existing
|
|
247
|
-
// assignment, so one provision now brings ALL members up to the current settings —
|
|
248
|
-
// which is also what makes the async_insert pin reach members provisioned earlier.
|
|
249
|
-
// SETTINGS NONE first, because ALTER only upserts what it lists: a setting dropped from
|
|
250
|
-
// MEMBER_PROFILE_SETTINGS in a later version would otherwise stay enforced forever on
|
|
251
|
-
// every upgraded house, and anything an operator had added to a profile of the same name
|
|
252
|
-
// would survive too. Clearing then applying gives the same absolute state OR REPLACE had,
|
|
253
|
-
// without its detachment.
|
|
254
|
-
//
|
|
255
|
-
// The gap between the two statements is admin-only and sub-second — but it is not
|
|
256
|
-
// self-healing: a crash or a dropped connection between them leaves the profile EMPTY,
|
|
257
|
-
// so every member is unbounded until someone provisions again. Nothing here notices, and
|
|
258
|
-
// `doctor` does not check the profile. Re-run provision if one dies mid-way.
|
|
259
|
-
try {
|
|
260
|
-
await client.command({ query: `CREATE SETTINGS PROFILE IF NOT EXISTS ${MEMBER_PROFILE}` });
|
|
261
|
-
await client.command({ query: `ALTER SETTINGS PROFILE ${MEMBER_PROFILE} SETTINGS NONE` });
|
|
262
|
-
await client.command({ query: `ALTER SETTINGS PROFILE ${MEMBER_PROFILE} SETTINGS ${MEMBER_PROFILE_SETTINGS}` });
|
|
263
|
-
await client.command({ query: `ALTER USER ${member} SETTINGS PROFILE '${MEMBER_PROFILE}'` });
|
|
264
|
-
console.log(`[mem] settings profile '${MEMBER_PROFILE}' applied to '${member}' (memory, time and thread ceilings)`);
|
|
265
|
-
} catch (e) {
|
|
266
|
-
// A server where the admin cannot create profiles still gets a working member; say so
|
|
267
|
-
// rather than failing the provision.
|
|
268
|
-
console.log(`[mem] note: could not apply the '${MEMBER_PROFILE}' settings profile — ${e.message}`);
|
|
269
|
-
console.log('[mem] the member works, but nothing bounds their query resources on this server');
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// 3. Merge rooms
|
|
273
|
-
if (flag('merge')) {
|
|
274
|
-
const mtpl = fs.readFileSync(path.join(here, 'schema-merge.sql.tpl'), 'utf-8');
|
|
275
|
-
for (const q of statements(mtpl.replaceAll('{{TEMPLATE_MEMBER}}', member))) {
|
|
276
|
-
await client.command({ query: q });
|
|
277
|
-
}
|
|
278
|
-
console.log('[mem] merge rooms ready: all_sessions, all_messages, all_tool_calls');
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// 4. Merge-room grants. Broad on purpose, and safe for the reason the whole layout
|
|
282
|
-
// rests on: a Merge table reduces to the underlying rooms the CALLER holds grants for.
|
|
283
|
-
// Measured on 25.11 — bob with SELECT on all_messages and nothing on messages_alice
|
|
284
|
-
// reads his own row and none of alice's, with `_table` showing only messages_bob, and
|
|
285
|
-
// no error. Withholding this grant does not make anything safer; it makes the team
|
|
286
|
-
// room deny outright instead of failing closed, which is a different and worse thing.
|
|
287
|
-
const merged = await mergeRoomsPresent(client, cfg.database);
|
|
288
|
-
for (const room of merged) {
|
|
289
|
-
await client.command({ query: `GRANT SELECT ON ${cfg.database}.${room} TO ${member}` });
|
|
290
|
-
}
|
|
291
|
-
if (merged.length) console.log(`[mem] granted SELECT on ${merged.join(', ')} to '${member}'`);
|
|
292
|
-
else console.log('[mem] no merge rooms yet — run once with --merge to create them');
|
|
293
|
-
|
|
294
|
-
await client.close();
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
main().catch((e) => { console.error(`[mem] provision failed: ${e.message}`); process.exit(1); });
|
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
// Room-name resolution.
|
|
2
|
-
//
|
|
3
|
-
// Every member owns their rooms, named TYPE-FIRST: `sessions_<member>`,
|
|
4
|
-
// `messages_<member>`, `tool_calls_<member>`. Type-first is what lets the Merge rooms
|
|
5
|
-
// anchor on a fixed room type (`^sessions_`) and never match themselves.
|
|
6
|
-
//
|
|
7
|
-
// THIS IS THE ONLY LAYOUT. There was a shared one — three rooms named `sessions`,
|
|
8
|
-
// `messages`, `tool_calls`, with row policies narrowing each caller to their own rows —
|
|
9
|
-
// and it is gone. A shared read is a Merge room plus a GRANT, which is strictly less
|
|
10
|
-
// machinery than a policy that has to be right on every table and every read path; and
|
|
11
|
-
// isolation by absent grant fails closed, where a row policy fails open the moment one is
|
|
12
|
-
// missing.
|
|
13
|
-
//
|
|
14
|
-
// The member is never supplied by the caller — it is read back from the server with
|
|
15
|
-
// currentUser(), the same value the rooms' user_id column is stamped with. A client that
|
|
16
|
-
// could name its own member could write into someone else's rooms.
|
|
17
|
-
//
|
|
18
|
-
// `sessions_v` IS A SAVED QUERY, NOT A ROOM. It was briefly a stored view, which cost a
|
|
19
|
-
// name inside the `^sessions_` namespace the Merge rooms select on (silently merged into
|
|
20
|
-
// `all_sessions`, doubling every count), a fourth grant per member, and a fourth object to
|
|
21
|
-
// provision, roll forward and drop. A saved query is substituted with the caller's own
|
|
22
|
-
// room names and runs under the caller's credential, so it inherits their grants and
|
|
23
|
-
// raises no view-ownership question at all.
|
|
24
|
-
|
|
25
|
-
const ROOM_TYPES = ['sessions', 'messages', 'tool_calls'];
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* What a member is granted on their own rooms. ONE definition, because there are two paths
|
|
29
|
-
* that provision a house — provision.js and `install --print-sql` — and when only the first
|
|
30
|
-
* was narrowed the second went on emitting `GRANT ALL` for a release. GRANT ALL includes
|
|
31
|
-
* CREATE TABLE **on the member's own room name**, so a member owns the name rather than the
|
|
32
|
-
* data and can replace the room with a Merge over everyone's, doubling other members' rows
|
|
33
|
-
* in the team room.
|
|
34
|
-
*
|
|
35
|
-
* ALTER UPDATE and ALTER DELETE both: `DELETE FROM` is a lightweight delete implemented as
|
|
36
|
-
* `ALTER TABLE … UPDATE _row_exists = 0`, and which of the two a server demands varies by
|
|
37
|
-
* version. ALTER ADD COLUMN for ensureSchema's rollout. Nothing that defines an object.
|
|
38
|
-
*/
|
|
39
|
-
const MEMBER_PRIVS = 'SELECT, INSERT, ALTER UPDATE, ALTER DELETE, ALTER ADD COLUMN, OPTIMIZE';
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Resource ceilings for a member, as a settings profile.
|
|
43
|
-
*
|
|
44
|
-
* Here for the same reason MEMBER_PRIVS is here: there are two paths that provision a
|
|
45
|
-
* house — provision.js and `install --print-sql` — and a change made to one of them and
|
|
46
|
-
* not the other has now happened eight times. Anything a member is GIVEN belongs in this
|
|
47
|
-
* file, so both paths read the same definition.
|
|
48
|
-
*
|
|
49
|
-
* MIN..MAX, not CONST and not MAX alone.
|
|
50
|
-
*
|
|
51
|
-
* A plain default is advisory — a member writes `SETTINGS max_memory_usage = …` on their
|
|
52
|
-
* query and overrides it. MAX alone is not enough either: in ClickHouse **0 means
|
|
53
|
-
* unlimited** for these, and 0 satisfies any MAX, so `SETTINGS max_memory_usage = 0`
|
|
54
|
-
* removed the ceiling entirely. MIN 1 closes that.
|
|
55
|
-
*
|
|
56
|
-
* CONST closes it too and was tried first — but CONST refuses EVERY change, including the
|
|
57
|
-
* server's own. `rawQuery` in memhouse/server/queries.js pins max_result_rows and
|
|
58
|
-
* max_execution_time to protect the dashboard from an unbounded query, and under CONST
|
|
59
|
-
* those pins were refused with Code 452, so /api/query returned an error for every input
|
|
60
|
-
* on any house provisioned after that change. A ceiling has to stop a member RAISING the
|
|
61
|
-
* limit while still letting anyone LOWER it.
|
|
62
|
-
*
|
|
63
|
-
* max_memory_usage is per QUERY; max_memory_usage_for_user bounds the member across
|
|
64
|
-
* concurrent queries, without which N parallel queries x the per-query ceiling is
|
|
65
|
-
* unbounded.
|
|
66
|
-
*
|
|
67
|
-
* Limits are generous on purpose: the point is to stop one member exhausting a shared
|
|
68
|
-
* server, not to make an honest full re-ship fail — a 20M-row scan runs inside them.
|
|
69
|
-
*
|
|
70
|
-
* KNOWN GAP, deliberately not closed here: ALTER UPDATE, ALTER DELETE and OPTIMIZE are in
|
|
71
|
-
* MEMBER_PRIVS and execute in the background merge pool, where these per-query settings do
|
|
72
|
-
* not apply. A member looping `OPTIMIZE … FINAL` on a large room can still load the box.
|
|
73
|
-
* Bounding that needs server-level merge-pool configuration, which is the operator's, not
|
|
74
|
-
* something a per-member profile can express.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* The global-install command that will actually work HERE.
|
|
78
|
-
*
|
|
79
|
-
* Every site that printed `npm install -g memhouse --allow-scripts=better-sqlite3` printed
|
|
80
|
-
* a line that fails with EACCES on any distro-packaged Node, because the global prefix is
|
|
81
|
-
* root-owned — measured on a clean Ubuntu machine, exit 243, including as step 1 of
|
|
82
|
-
* `prompt --install`, which advertises itself as rendered for this machine. The README
|
|
83
|
-
* learned this; eight code sites had not.
|
|
84
|
-
*
|
|
85
|
-
* `sudo` is right for exactly one of the two causes and makes the other worse, and what
|
|
86
|
-
* tells them apart is who owns the prefix — so look, rather than guess.
|
|
87
|
-
*/
|
|
88
|
-
function installCommand() {
|
|
89
|
-
const base = 'npm install -g memhouse --allow-scripts=better-sqlite3';
|
|
90
|
-
try {
|
|
91
|
-
const { execFileSync } = require('child_process');
|
|
92
|
-
const prefix = execFileSync('npm', ['prefix', '-g'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
93
|
-
const st = require('fs').statSync(prefix);
|
|
94
|
-
if (st.uid !== process.getuid()) return `sudo ${base}`;
|
|
95
|
-
} catch { /* npm not on PATH, or an unreadable prefix: fall through to the plain form */ }
|
|
96
|
-
return base;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const MEMBER_PROFILE = 'memhouse_member';
|
|
100
|
-
const MEMBER_PROFILE_SETTINGS = [
|
|
101
|
-
'max_memory_usage = 8000000000 MIN 1 MAX 8000000000',
|
|
102
|
-
'max_memory_usage_for_user = 16000000000 MIN 1 MAX 16000000000',
|
|
103
|
-
'max_execution_time = 600 MIN 1 MAX 600',
|
|
104
|
-
'max_threads = 16 MIN 1 MAX 16',
|
|
105
|
-
'max_result_rows = 10000000 MIN 1 MAX 10000000',
|
|
106
|
-
// Provenance, pinned server-side rather than trusted to every client.
|
|
107
|
-
//
|
|
108
|
-
// `user_id MATERIALIZED currentUser()` is what records who wrote a row — but a
|
|
109
|
-
// MATERIALIZED column is computed during the INSERT, and an ASYNC insert flushes
|
|
110
|
-
// outside that context: measured on 25.11.9.34, `async_insert=1` stores user_id as the
|
|
111
|
-
// EMPTY STRING while a sync insert on the same table stamps correctly. An unattributed
|
|
112
|
-
// row is invisible to every identity-bound path at once, including its own owner's
|
|
113
|
-
// `reset`.
|
|
114
|
-
//
|
|
115
|
-
// The shipper already passes async_insert=0 on every insert, so memhouse itself was
|
|
116
|
-
// never the risk. The risk is everything ELSE holding a member credential — an agent
|
|
117
|
-
// following the /memhouse:sql skill, a migration script, a psql-habit one-liner. CONST
|
|
118
|
-
// makes the house refuse (SETTING_CONSTRAINT_VIOLATION) instead of silently accepting
|
|
119
|
-
// rows nobody owns, which is the difference between a guarantee and a convention.
|
|
120
|
-
// `doctor` still checks for blank user_id — that stays, as the detector for rows
|
|
121
|
-
// written before this profile existed.
|
|
122
|
-
'async_insert = 0 CONST',
|
|
123
|
-
].join(', ');
|
|
124
|
-
|
|
125
|
-
// ClickHouse usernames are permissive; room names are not. Refuse anything that would
|
|
126
|
-
// need quoting or could change how a Merge regex or a name-splitter reads.
|
|
127
|
-
function assertUsableMember(member) {
|
|
128
|
-
if (typeof member !== 'string' || !/^[A-Za-z][A-Za-z0-9_]*$/.test(member)) {
|
|
129
|
-
throw new Error(`cannot build room names for user '${member}': expected [A-Za-z][A-Za-z0-9_]*`);
|
|
130
|
-
}
|
|
131
|
-
// The reservation lives HERE, not only in the CLI, because provision.js is the admin
|
|
132
|
-
// entry point INSTALL.md sends you to for a second member — and it went as far as
|
|
133
|
-
// creating sessions_root/messages_root/tool_calls_root before dying on the grant,
|
|
134
|
-
// leaving three orphan rooms nothing removes. Case-insensitive: Root and ROOT are the
|
|
135
|
-
// same account. `default` is deliberately NOT reserved — a poor member name, but a real
|
|
136
|
-
// one that existing houses are built on.
|
|
137
|
-
if (member.toLowerCase() === 'root') {
|
|
138
|
-
throw new Error("'root' cannot be a member: it is a container artefact, not a person");
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* The session rollup, as SQL text rather than a name.
|
|
144
|
-
*
|
|
145
|
-
* Two properties are load bearing: the join is a LEFT JOIN, so a session with no messages
|
|
146
|
-
* still appears with zero aggregates instead of vanishing from every count; and
|
|
147
|
-
* `join_use_nulls = 1` makes the unmatched message columns NULL so `coalesce` yields true
|
|
148
|
-
* zeros rather than counting the placeholder row.
|
|
149
|
-
*
|
|
150
|
-
* BOTH ARE NOW CARRIED BY THE TEXT ITSELF — `FINAL` on each room and a trailing
|
|
151
|
-
* `SETTINGS join_use_nulls = 1`. It used to depend on the caller passing `final=1` and
|
|
152
|
-
* `join_use_nulls=1`, on the belief that a subquery cannot carry its own SETTINGS. It can
|
|
153
|
-
* (verified on 26.7 and 25.11), and the belief was expensive: every consumer that forgot
|
|
154
|
-
* the settings silently counted each message once per undeleted ReplacingMergeTree
|
|
155
|
-
* version. Measured right after a `ship --full` — 2x, and 3x three ships later. It does
|
|
156
|
-
* not self-heal; the error grows with each pass until a merge happens to collapse the
|
|
157
|
-
* parts. `memhouse sessions-query > q.sql` lost the warning entirely, because it was
|
|
158
|
-
* printed on stderr as a SQL comment that never reached the SQL.
|
|
159
|
-
*
|
|
160
|
-
* Passing final=1 as well is harmless, so READ_SETTINGS stays as it is for direct room
|
|
161
|
-
* reads, which still need it.
|
|
162
|
-
*/
|
|
163
|
-
function sessionsRollup({ sessions, messages }) {
|
|
164
|
-
return `(
|
|
165
|
-
SELECT
|
|
166
|
-
s.session_id AS session_id,
|
|
167
|
-
any(s.source) AS source,
|
|
168
|
-
any(s.host) AS host,
|
|
169
|
-
any(s.name) AS name,
|
|
170
|
-
any(s.mode) AS mode,
|
|
171
|
-
any(s.folder) AS folder,
|
|
172
|
-
any(s.project) AS project,
|
|
173
|
-
any(s.git_branch) AS git_branch,
|
|
174
|
-
s.user_id AS user_id,
|
|
175
|
-
any(s.created_at) AS created_at,
|
|
176
|
-
any(s.last_updated_at) AS last_updated_at,
|
|
177
|
-
min(m.ts) AS started,
|
|
178
|
-
max(m.ts) AS ended,
|
|
179
|
-
coalesce(dateDiff('second', min(m.ts), max(m.ts)), 0) AS duration_sec,
|
|
180
|
-
count(m.seq) AS total_msgs,
|
|
181
|
-
countIf(m.role = 'user') AS user_msgs,
|
|
182
|
-
countIf(m.role = 'assistant') AS assistant_msgs,
|
|
183
|
-
countIf(m.is_subagent) AS subagent_msgs,
|
|
184
|
-
groupUniqArrayIf(m.model, m.model NOT IN ('', '<synthetic>')) AS models,
|
|
185
|
-
coalesce(sum(m.input_tokens), 0) AS input_tokens,
|
|
186
|
-
coalesce(sum(m.output_tokens), 0) AS output_tokens,
|
|
187
|
-
coalesce(sum(m.cache_read_tokens), 0) AS cache_read_tokens,
|
|
188
|
-
coalesce(sum(m.cache_write_tokens), 0) AS cache_write_tokens,
|
|
189
|
-
coalesce(sumIf(length(m.text), m.role = 'user'), 0) AS user_chars,
|
|
190
|
-
coalesce(sumIf(length(m.text), m.role = 'assistant'), 0) AS assistant_chars,
|
|
191
|
-
coalesce(substring(argMinIf(m.text, m.seq, m.role = 'user' AND m.text != ''), 1, 200), '') AS first_prompt
|
|
192
|
-
FROM ${sessions} AS s FINAL
|
|
193
|
-
LEFT JOIN ${messages} AS m FINAL ON m.session_id = s.session_id AND m.user_id = s.user_id
|
|
194
|
-
GROUP BY s.session_id, s.user_id
|
|
195
|
-
SETTINGS join_use_nulls = 1
|
|
196
|
-
)`;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* The settings every read needs. `final` collapses ReplacingMergeTree versions;
|
|
201
|
-
* `join_use_nulls` is what the rollup's coalesce depends on.
|
|
202
|
-
*/
|
|
203
|
-
const READ_SETTINGS = { final: 1, join_use_nulls: 1 };
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* Names, given the member the server reported. Shared by every caller so the two
|
|
207
|
-
* transports in the tree (@clickhouse/client and the CLI's raw fetch) cannot drift into
|
|
208
|
-
* two different naming rules.
|
|
209
|
-
*
|
|
210
|
-
* `sessions_v` is the rollup as SQL text, usable in the same `FROM ... AS c` position a
|
|
211
|
-
* view name would occupy — which is what lets the read layer treat it as just another
|
|
212
|
-
* resolved name.
|
|
213
|
-
*/
|
|
214
|
-
function roomNames(member, user = member) {
|
|
215
|
-
assertUsableMember(member);
|
|
216
|
-
const out = { member, user };
|
|
217
|
-
for (const t of ROOM_TYPES) out[t] = `${t}_${member}`;
|
|
218
|
-
out.sessions_v = sessionsRollup(out);
|
|
219
|
-
return out;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
async function currentUser(client) {
|
|
223
|
-
const rs = await client.query({ query: 'SELECT currentUser() AS u', format: 'JSONEachRow' });
|
|
224
|
-
const rows = await rs.json();
|
|
225
|
-
const u = rows[0] && rows[0].u;
|
|
226
|
-
if (!u) throw new Error('could not determine currentUser()');
|
|
227
|
-
return u;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* Resolve the rooms for whoever this client is connected as.
|
|
232
|
-
* Returns { sessions, messages, tool_calls, sessions_v, member, user }.
|
|
233
|
-
*
|
|
234
|
-
* `user` is the identity the server reports. Writers need the value itself, not just the
|
|
235
|
-
* name it produces — see ship.js's delete, which must BIND the user rather than call
|
|
236
|
-
* currentUser() inside a mutation, where it is not evaluated in the caller's context.
|
|
237
|
-
*/
|
|
238
|
-
async function resolveRooms(client) {
|
|
239
|
-
const user = await currentUser(client);
|
|
240
|
-
return roomNames(user, user);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/** The three Merge rooms — team-wide read paths, owner-managed. */
|
|
244
|
-
function mergeRooms() {
|
|
245
|
-
return { sessions: 'all_sessions', messages: 'all_messages', tool_calls: 'all_tool_calls' };
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
module.exports = {
|
|
249
|
-
MEMBER_PRIVS, installCommand, MEMBER_PROFILE, MEMBER_PROFILE_SETTINGS,
|
|
250
|
-
ROOM_TYPES, READ_SETTINGS, assertUsableMember,
|
|
251
|
-
sessionsRollup, roomNames, currentUser, resolveRooms, mergeRooms,
|
|
252
|
-
};
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
-- mem — the Merge rooms. Owner-managed, created once per house.
|
|
2
|
-
--
|
|
3
|
-
-- Team-wide reads. Each is a regex over room names anchored on the ROOM TYPE, so it
|
|
4
|
-
-- matches member rooms only and can never match itself (`^messages_` does not match
|
|
5
|
-
-- `all_messages`).
|
|
6
|
-
--
|
|
7
|
-
-- Three measured properties this relies on (ClickHouse 26.7.1):
|
|
8
|
-
-- * fails closed on permissions — a caller sees only the underlying rooms they hold
|
|
9
|
-
-- grants for, with no leak and no error, so these can be granted broadly —
|
|
10
|
-
-- * auto-discovers rooms created after them, so member onboarding needs no DDL here —
|
|
11
|
-
-- * tolerates schema drift, returning a column's default for rooms lacking it — which
|
|
12
|
-
-- is what makes schema rollout progressive. Merge REJECTS mutations, so a new column
|
|
13
|
-
-- is added with ADD COLUMN, on the Merge room FIRST.
|
|
14
|
-
--
|
|
15
|
-
-- {{TEMPLATE_MEMBER}} is any existing member — the Merge room borrows its column list.
|
|
16
|
-
|
|
17
|
-
CREATE TABLE IF NOT EXISTS all_sessions AS sessions_{{TEMPLATE_MEMBER}}
|
|
18
|
-
ENGINE = Merge(currentDatabase(), '^sessions_');
|
|
19
|
-
|
|
20
|
-
CREATE TABLE IF NOT EXISTS all_messages AS messages_{{TEMPLATE_MEMBER}}
|
|
21
|
-
ENGINE = Merge(currentDatabase(), '^messages_');
|
|
22
|
-
|
|
23
|
-
CREATE TABLE IF NOT EXISTS all_tool_calls AS tool_calls_{{TEMPLATE_MEMBER}}
|
|
24
|
-
ENGINE = Merge(currentDatabase(), '^tool_calls_');
|