@jc_stack/ez-library 0.1.0-beta.19 → 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 +5 -0
- package/ez-plugin.json +1 -1
- package/package.json +1 -1
- package/src/store.mjs +31 -4
- package/test/library.test.mjs +41 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
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
|
+
|
|
3
8
|
## 0.1.0-beta.19
|
|
4
9
|
|
|
5
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.
|
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.
|
|
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
package/src/store.mjs
CHANGED
|
@@ -83,13 +83,37 @@ export async function initialize(root) {
|
|
|
83
83
|
return root;
|
|
84
84
|
}
|
|
85
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.
|
|
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).
|
|
87
90
|
const LOCK_WAIT_MS = 60_000;
|
|
88
91
|
const OWNERLESS_GRACE_MS = 1_000;
|
|
92
|
+
const PROCESS_ID = randomUUID();
|
|
89
93
|
async function lockOwner(lock) {
|
|
90
94
|
try { return JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')); }
|
|
91
95
|
catch (e) { if (e.code === 'ENOENT' || e instanceof SyntaxError) return null; throw e; }
|
|
92
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
|
+
}
|
|
93
117
|
async function acquire(lock, signal) {
|
|
94
118
|
const started = Date.now();
|
|
95
119
|
let ownerless = null;
|
|
@@ -97,17 +121,20 @@ async function acquire(lock, signal) {
|
|
|
97
121
|
signal?.throwIfAborted();
|
|
98
122
|
try {
|
|
99
123
|
await fs.mkdir(lock, { mode: 0o700 });
|
|
100
|
-
try { await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid, host: hostname(), at: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }); }
|
|
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' }); }
|
|
101
125
|
catch (e) { await fs.rmdir(lock); throw e; }
|
|
102
126
|
return;
|
|
103
127
|
} catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
104
128
|
const owner = await lockOwner(lock);
|
|
105
|
-
if (owner?.
|
|
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
|
+
}
|
|
106
133
|
ownerless = owner ? null : ownerless ?? Date.now();
|
|
107
134
|
if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
|
|
108
135
|
fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
|
|
109
136
|
if (Date.now() - started >= LOCK_WAIT_MS)
|
|
110
|
-
fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation`);
|
|
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)`, () => '')}`);
|
|
111
138
|
await sleep(100 + Math.random() * 150, undefined, { signal });
|
|
112
139
|
}
|
|
113
140
|
}
|
package/test/library.test.mjs
CHANGED
|
@@ -156,6 +156,47 @@ test('a live writer is waited for instead of failing BUSY', async t => {
|
|
|
156
156
|
await assert.rejects(fs.stat(lock), code('ENOENT'));
|
|
157
157
|
});
|
|
158
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
|
+
|
|
159
200
|
test('an aborted wait gives up without taking the lock', async t => {
|
|
160
201
|
const root = await fixture(t); const lock = path.join(root, '.writer-lock');
|
|
161
202
|
await fs.mkdir(lock);
|