@jc_stack/ez-library 0.1.0-beta.18 → 0.1.0-beta.20

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.20
4
+
5
+ - Reclaim a writer lock left by a dead process on the same host. The lock owner now records a per-process id; a same-host lock whose pid no longer exists, or that names this process's pid without its id (a restarted container reusing pid and hostname), is removed. Reclaimers take turns under an exclusive mutex and remove the lock only if it still names the same dead owner, so concurrent callers never take over a live lock. Before this, a restarted resident worker read the dead writer's lock as its own and failed `BUSY` on every cycle until the lock was removed by hand. Locks from other hosts, locks without an owner and an unreadable owner pid still fail closed; a reclaim mutex left by a crash makes writers wait and fail `BUSY` naming it. Same hostname is taken to mean the same pid namespace (Docker's default).
6
+ - Requires Ez core 0.1.0-beta.50 or newer (unchanged).
7
+
8
+ ## 0.1.0-beta.19
9
+
10
+ - Writers wait up to 60 seconds for a live holder of the Library writer lock (named in its `owner` file) instead of failing `BUSY` at once, so concurrent agent writes and the resident sync no longer fail on a brief overlap. A lock without an owner still fails closed after a one-second grace; a lock held by the same process fails at once; the resident worker stops waiting when told to stop.
11
+ - Requires Ez core 0.1.0-beta.50 or newer (unchanged).
12
+
3
13
  ## 0.1.0-beta.18
4
14
 
5
15
  - Reuse unchanged file digests in the resident sync worker: inventory scans skip rereading files whose device, inode, size, mtime and ctime are unchanged, and the text mirror rewrites only changed files and skips fetch, push and verification when the remote head already matches. Idle sync cycles no longer hash every original twice per minute.
package/README.md CHANGED
@@ -153,7 +153,7 @@ The named `data` volume contains `/state/files`, `settings.json`, `operations`,
153
153
 
154
154
  Stop the plugin before an operator takes a volume snapshot using an existing backup tool. Preserve originals, settings, receipts and history together. QMD indexes/models are rebuildable. Uninstall removes the deployment and registry binding but preserves volumes. Account revocation is a separate action in the provider's plugin/account. See [release and rollback practices](docs/releasing.md).
155
155
 
156
- An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
156
+ Library writers take `/state/.writer-lock` in turn: a command waits up to 60 seconds for a live writer (named in the lock's `owner` file) before returning `BUSY`, and a lock without an owner returns `BUSY` after a one-second grace. An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
157
157
 
158
158
  ## Development
159
159
 
package/ez-plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.18",
4
+ "version": "0.1.0-beta.20",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
6
  "example": "library search 'quarterly budget' --all --limit 5",
7
7
  "commands": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.18",
3
+ "version": "0.1.0-beta.20",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
package/src/store.mjs CHANGED
@@ -3,6 +3,8 @@ import { createReadStream, createWriteStream, constants } from 'node:fs';
3
3
  import { pipeline } from 'node:stream/promises';
4
4
  import { Transform } from 'node:stream';
5
5
  import path from 'node:path';
6
+ import { hostname } from 'node:os';
7
+ import { setTimeout as sleep } from 'node:timers/promises';
6
8
  import { createHash, randomUUID } from 'node:crypto';
7
9
 
8
10
  export class LibraryError extends Error {
@@ -80,15 +82,68 @@ export async function initialize(root) {
80
82
  }
81
83
  return root;
82
84
  }
83
- export async function locked(root, fn) {
85
+ // A live writer records itself in the lock and others wait for it briefly. A lock
86
+ // with no owner is an interrupted operation and fails closed. A lock owned on this
87
+ // host by a process that no longer exists is reclaimed: a restarted container keeps
88
+ // its hostname and often its pid, so pid + host alone would match the dead writer.
89
+ // Same hostname is taken to mean the same pid namespace (Docker's default).
90
+ const LOCK_WAIT_MS = 60_000;
91
+ const OWNERLESS_GRACE_MS = 1_000;
92
+ const PROCESS_ID = randomUUID();
93
+ async function lockOwner(lock) {
94
+ try { return JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')); }
95
+ catch (e) { if (e.code === 'ENOENT' || e instanceof SyntaxError) return null; throw e; }
96
+ }
97
+ function alive(pid) {
98
+ if (!Number.isInteger(pid) || pid <= 0) return true; // unreadable owner: fail closed
99
+ if (pid === process.pid) return false; // our pid, but not our PROCESS_ID: a previous process
100
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; }
101
+ }
102
+ // Reclaimers take turns under an exclusive mutex and remove the lock only if it still
103
+ // names the same dead owner. A dead owner's lock cannot change while it exists, and
104
+ // nothing else removes it, so the check holds until removal. Returns whether it
105
+ // removed the lock; otherwise the caller waits as for a live holder, so a mutex left
106
+ // by a crash ends in BUSY naming it.
107
+ async function reclaim(lock, dead) {
108
+ const mutex = `${lock}.reclaim`;
109
+ try { await fs.mkdir(mutex, { mode: 0o700 }); } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
110
+ try {
111
+ const owner = await lockOwner(lock);
112
+ if (!owner || !['pid', 'host', 'id', 'at'].every(k => owner[k] === dead[k])) return false;
113
+ await fs.rm(path.join(lock, 'owner'), { force: true }); await fs.rmdir(lock);
114
+ return true;
115
+ } finally { await fs.rmdir(mutex); }
116
+ }
117
+ async function acquire(lock, signal) {
118
+ const started = Date.now();
119
+ let ownerless = null;
120
+ for (;;) {
121
+ signal?.throwIfAborted();
122
+ try {
123
+ await fs.mkdir(lock, { mode: 0o700 });
124
+ try { await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid, host: hostname(), id: PROCESS_ID, at: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }); }
125
+ catch (e) { await fs.rmdir(lock); throw e; }
126
+ return;
127
+ } catch (e) { if (e.code !== 'EEXIST') throw e; }
128
+ const owner = await lockOwner(lock);
129
+ if (owner?.host === hostname()) {
130
+ if (owner.id === PROCESS_ID) fail('BUSY', 'Writer lock is held by this process');
131
+ if (!alive(owner.pid) && await reclaim(lock, owner)) continue;
132
+ }
133
+ ownerless = owner ? null : ownerless ?? Date.now();
134
+ if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
135
+ fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
136
+ if (Date.now() - started >= LOCK_WAIT_MS)
137
+ fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation${await fs.stat(`${lock}.reclaim`).then(() => ` (an interrupted reclaim also left ${lock}.reclaim)`, () => '')}`);
138
+ await sleep(100 + Math.random() * 150, undefined, { signal });
139
+ }
140
+ }
141
+ export async function locked(root, fn, { signal } = {}) {
84
142
  root = await rootDir(root, true);
85
143
  const lock = path.join(root, '.writer-lock');
86
- await fs.mkdir(lock, { mode: 0o700 }).catch(e => {
87
- if (e.code === 'EEXIST') fail('BUSY', 'Writer lock exists; confirm no command is active before recovering an interrupted operation');
88
- throw e;
89
- });
144
+ await acquire(lock, signal);
90
145
  try { return await fn(await initialize(root)); }
91
- finally { await fs.rmdir(lock); }
146
+ finally { await fs.rm(path.join(lock, 'owner'), { force: true }); await fs.rmdir(lock); }
92
147
  }
93
148
  async function opened(file, read) {
94
149
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -27,11 +27,11 @@ while (!stopping) {
27
27
  const enabled = config?.mode === 'two-way' || (config?.backend === 'git' && config.mode === 'pull-only');
28
28
  if (!enabled && (config || mirror?.mode !== 'one-way')) {
29
29
  due.delete(name);
30
- if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
30
+ if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex, { signal: controller.signal });
31
31
  continue;
32
32
  }
33
33
  if ((due.get(name) || 0) <= Date.now()) {
34
- try { await syncRun(selected, root); }
34
+ try { await syncRun(selected, root, { signal: controller.signal }); }
35
35
  finally { due.set(name, Date.now() + (config?.intervalSeconds || 60) * 1000); }
36
36
  }
37
37
  interval = Math.min(interval, Math.max(1, ((due.get(name) || 0) - Date.now()) / 1000));
package/src/sync.mjs CHANGED
@@ -142,7 +142,7 @@ export async function syncPolicy(root, { expected, mode, intervalSeconds = 60 })
142
142
  });
143
143
  }
144
144
 
145
- export async function syncRun(root, stateRoot = root) {
145
+ export async function syncRun(root, stateRoot = root, { signal } = {}) {
146
146
  return locked(root, async root => {
147
147
  await prepare(root);
148
148
  const config = await readJSON(location(root));
@@ -172,5 +172,5 @@ export async function syncRun(root, stateRoot = root) {
172
172
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
173
173
  if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'GitHub text mirror pending: ' + status.textMirror.error.message);
174
174
  return status;
175
- });
175
+ }, { signal });
176
176
  }
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { Readable } from 'node:stream';
7
7
  import { spawnSync } from 'node:child_process';
8
- import { put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
8
+ import { locked, put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
9
9
  import { qmdEnvironment } from '../src/cli.mjs';
10
10
 
11
11
  const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
@@ -144,6 +144,68 @@ test('writer lock is fail-closed, including stale-looking locks', async t => {
144
144
  assert((await fs.stat(path.join(root, '.writer-lock'))).isDirectory());
145
145
  });
146
146
 
147
+ test('a live writer is waited for instead of failing BUSY', async t => {
148
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
149
+ await fs.mkdir(lock);
150
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
151
+ const release = new Promise(resolve => setTimeout(async () => {
152
+ await fs.rm(path.join(lock, 'owner')); await fs.rmdir(lock); resolve();
153
+ }, 600));
154
+ await save(root, 'after wait');
155
+ await release;
156
+ await assert.rejects(fs.stat(lock), code('ENOENT'));
157
+ });
158
+
159
+ test('a lock left by a dead process on this host is reclaimed, including a restart that reuses our pid', async t => {
160
+ const { hostname } = await import('node:os');
161
+ for (const pid of [process.pid, 2 ** 22 + 7]) {
162
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
163
+ await fs.mkdir(lock);
164
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
165
+ assert.equal(await locked(root, () => 'ran'), 'ran');
166
+ await assert.rejects(fs.stat(lock), code('ENOENT'));
167
+ }
168
+ });
169
+
170
+ test('concurrent processes reclaim one dead lock without overlapping writers', async t => {
171
+ const { hostname } = await import('node:os');
172
+ const { spawn } = await import('node:child_process');
173
+ const store = new URL('../src/store.mjs', import.meta.url).href;
174
+ const child = `const { locked } = await import(${JSON.stringify(store)}); const fs = await import('node:fs/promises');
175
+ await locked(process.argv[1], async () => { const f = process.argv[1] + '/in'; await fs.writeFile(f, '', { flag: 'wx' });
176
+ await new Promise(r => setTimeout(r, 30)); await fs.rm(f); });`;
177
+ for (let round = 0; round < 5; round++) {
178
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
179
+ await fs.mkdir(lock);
180
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: 2 ** 22 + 7, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
181
+ const codes = await Promise.all(Array.from({ length: 4 }, () => new Promise(resolve =>
182
+ spawn(process.execPath, ['--input-type=module', '-e', child, root], { stdio: 'inherit' }).on('exit', resolve))));
183
+ assert.deepEqual(codes, [0, 0, 0, 0]);
184
+ await assert.rejects(fs.stat(lock), code('ENOENT'));
185
+ await assert.rejects(fs.stat(`${lock}.reclaim`), code('ENOENT'));
186
+ }
187
+ });
188
+
189
+ test('a reclaim mutex left by a crash makes writers wait, not spin', async t => {
190
+ const { hostname } = await import('node:os');
191
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
192
+ await fs.mkdir(lock); await fs.mkdir(`${lock}.reclaim`);
193
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: 2 ** 22 + 7, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
194
+ const cpu = process.cpuUsage();
195
+ await assert.rejects(locked(root, () => assert.fail('must not run'), { signal: AbortSignal.timeout(1000) }), { name: 'AbortError' });
196
+ const used = process.cpuUsage(cpu); assert((used.user + used.system) / 1000 < 400, 'waiting must sleep between attempts');
197
+ assert((await fs.stat(lock)).isDirectory());
198
+ });
199
+
200
+ test('an aborted wait gives up without taking the lock', async t => {
201
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
202
+ await fs.mkdir(lock);
203
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
204
+ const controller = new AbortController(); setTimeout(() => controller.abort(), 300);
205
+ await assert.rejects(locked(root, () => assert.fail('must not run'), { signal: controller.signal }), { name: 'AbortError' });
206
+ assert.equal(JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')).host, 'other');
207
+ });
208
+
147
209
  test('list honors prefix and a bounded result size', async t => {
148
210
  const root = await fixture(t); await save(root, 'a');
149
211
  await put(root, 'notes/second.md', input('b'), { key: 'b', expected: 'new' });