dsh-delete-session 0.2.7 → 0.2.9

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/src/index.js CHANGED
@@ -638,10 +638,25 @@ async function flushAndDetach(ctx, sessionId) {
638
638
  // lease asynchronously (session/disposed starts a persistence retirement), so
639
639
  // the probe is retried with a short backoff before the request is refused -
640
640
  // in practice the first click then succeeds without forcing anything.
641
- // The backoff is short (200ms x 12 = ~2.2s worst case) so a batch containing
642
- // live sessions stays responsive while the lease retirement lands.
641
+ // A live session is the common case: detaching releases the write lease through
642
+ // an asynchronous retirement, so the FIRST probe almost always finds it busy.
643
+ // A flat 200ms delay therefore charged every live delete ~200ms before it even
644
+ // started. The wait is now exponential — 20, 40, 80, 160, then the old 200ms —
645
+ // which lands the typical case in ~20-40ms and keeps the ceiling unchanged
646
+ // (total wait is shorter than 12 x 200ms, never longer).
643
647
  const BUSY_RETRY_ATTEMPTS = 12
644
- const BUSY_RETRY_DELAY_MS = 200
648
+ const BUSY_RETRY_BASE_MS = 20
649
+ const BUSY_RETRY_MAX_MS = 200
650
+
651
+ /**
652
+ * How long to wait before retry `attempt` (1-based).
653
+ * @param attempt - the retry about to happen.
654
+ * @returns milliseconds to sleep.
655
+ */
656
+ function busyBackoff(attempt) {
657
+ const step = BUSY_RETRY_BASE_MS * 2 ** Math.max(0, attempt - 1)
658
+ return Math.min(step, BUSY_RETRY_MAX_MS)
659
+ }
645
660
 
646
661
  function sleep(ms) {
647
662
  return new Promise((resolve) => setTimeout(resolve, ms))
@@ -670,7 +685,7 @@ async function assertNoActiveWriter(ctx, sessionId) {
670
685
  }
671
686
  }
672
687
  if (!busy) return true
673
- if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(BUSY_RETRY_DELAY_MS)
688
+ if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(busyBackoff(attempt))
674
689
  }
675
690
  throw new HttpError(409, 'busy', 'session is currently open in DSH')
676
691
  }
@@ -686,6 +701,10 @@ async function assertNoActiveWriter(ctx, sessionId) {
686
701
  // 8), so 6 keeps a ~33% gain over 4 while staying below the saturation knee
687
702
  // and limiting the number of simultaneous lease-probe loops.
688
703
  const BATCH_CONCURRENCY = 6
704
+ // The lease probe is a few milliseconds of waiting, not I/O: it can run wider
705
+ // than the file sweep without adding load, and that width is the whole point of
706
+ // phase 2 of the batch pipeline.
707
+ const BATCH_PROBE_CONCURRENCY = 16
689
708
 
690
709
  let workspaceLock = Promise.resolve()
691
710
  function withWorkspaceLock(fn) {
@@ -752,29 +771,39 @@ async function detachFromWorkspace(ctx, sessionId) {
752
771
 
753
772
  // --- core delete -------------------------------------------------------------
754
773
 
755
- async function deleteSession(ctx, sessionId, options) {
756
- if (!SESSION_ID_RE.test(sessionId)) {
757
- throw new HttpError(400, 'invalid', 'invalid session id')
758
- }
759
- // Undoable by default: only an explicit `recycle: false` sends the files to a
760
- // plain removal instead of the system trash.
774
+ /**
775
+ * Phase 1 - stop everything that writes to a session and flush its log.
776
+ * Cheap and independent per session, so a batch runs these together.
777
+ */
778
+ async function stopSession(ctx, sessionId) {
779
+ await quiesceAgent(ctx, sessionId)
780
+ return flushAndDetach(ctx, sessionId)
781
+ }
782
+
783
+ /** Phase 2 - wait for the write lease. The waits of different sessions overlap. */
784
+ async function requireWritable(ctx, sessionId) {
785
+ await assertNoActiveWriter(ctx, sessionId)
786
+ }
787
+
788
+ /**
789
+ * Phase 3 - retire the files, verify, drop the workspace accounting, then take
790
+ * the ticked child sessions with it.
791
+ *
792
+ * Children stay sequential and last: one failure never takes the parent result
793
+ * down with it, because the parent is what the user clicked.
794
+ *
795
+ * @returns `{ removed, caches, workspaceDetached, children }`.
796
+ */
797
+ async function retireSession(ctx, sessionId, options, stopResult) {
761
798
  const recycle = options === undefined || options === null || options.recycle !== false
762
- // Subagent sessions are sessions of their own; the ones the caller ticked are
763
- // taken with their parent. Anything that is not a well-formed id is dropped
764
- // here, before it reaches the filesystem.
765
799
  const childSessionIds = options !== undefined && options !== null && Array.isArray(options.childSessionIds)
766
800
  ? options.childSessionIds
767
801
  .filter((id) => typeof id === 'string' && SESSION_ID_RE.test(id))
768
802
  .filter((id) => bareSessionId(id) !== bareSessionId(sessionId))
769
803
  : []
770
- const stopped = await quiesceAgent(ctx, sessionId)
771
- const { flushed, detached } = await flushAndDetach(ctx, sessionId)
772
- await assertNoActiveWriter(ctx, sessionId)
804
+ const flushed = stopResult !== undefined && stopResult !== null && stopResult.flushed === true
805
+ const detached = stopResult !== undefined && stopResult !== null && stopResult.detached === true
773
806
 
774
- // Retire the on-disk directories first, then the cache rows. With the Recycle
775
- // Bin switch on (the default) they are staged and the shell moves them to the
776
- // bin in the background; switched off, they are removed outright — that is what
777
- // the dialog promises in that state.
778
807
  const { removed, caches } = await retireSessionFiles(sessionId, recycle)
779
808
 
780
809
  const sp = ctx.get('sessionPersistence')
@@ -794,8 +823,6 @@ async function deleteSession(ctx, sessionId, options) {
794
823
  throw new HttpError(404, 'not-found', 'session not found')
795
824
  }
796
825
 
797
- // Children last, and one failure never takes the parent result down with it:
798
- // the parent is what the user clicked, so that click has to land.
799
826
  const children = []
800
827
  for (const childId of childSessionIds) {
801
828
  try {
@@ -823,17 +850,105 @@ async function deleteSession(ctx, sessionId, options) {
823
850
  }
824
851
  }
825
852
 
853
+ return { removed, caches, workspaceDetached, children }
854
+ }
855
+
856
+ /**
857
+ * Delete one session: the three phases in order. Kept as the single-session
858
+ * entry point, and expressed in the same phase helpers the batch uses so the two
859
+ * can never drift apart.
860
+ */
861
+ async function deleteSession(ctx, sessionId, options) {
862
+ if (!SESSION_ID_RE.test(sessionId)) {
863
+ throw new HttpError(400, 'invalid', 'invalid session id')
864
+ }
865
+ const stopResult = await stopSession(ctx, sessionId)
866
+ await requireWritable(ctx, sessionId)
867
+ const result = await retireSession(ctx, sessionId, options, stopResult)
826
868
  return {
827
- removed,
828
- caches,
829
- stopped,
830
- flushed,
831
- detached,
832
- workspaceDetached,
833
- children,
869
+ removed: result.removed,
870
+ caches: result.caches,
871
+ stopped: stopResult !== undefined && stopResult.flushed !== undefined,
872
+ flushed: stopResult.flushed,
873
+ detached: stopResult.detached,
874
+ workspaceDetached: result.workspaceDetached,
875
+ children: result.children,
834
876
  }
835
877
  }
836
878
 
879
+ /**
880
+ * Delete many sessions as three overlapping phases:
881
+ *
882
+ * 1. stop and flush every session (bounded, but the work is tiny)
883
+ * 2. probe every write lease (wide: these are the 20-40ms waits, and they only
884
+ * overlap if nothing queues behind the retire workers)
885
+ * 3. retire files, verify, detach accounting, take children (bounded)
886
+ *
887
+ * The old shape ran all three phases inside each session, six at a time, so a
888
+ * batch of live sessions paid its lease waits in waves. One failing session never
889
+ * takes the batch down: it comes back as `{ ok: false }`.
890
+ *
891
+ * @returns one `{ sessionId, ok, removed }` (or `{ ok: false, code, error }`) per id.
892
+ */
893
+ async function deleteSessions(ctx, sessionIds, options) {
894
+ const valid = []
895
+ const rejected = []
896
+ for (const sessionId of sessionIds) {
897
+ if (SESSION_ID_RE.test(sessionId)) valid.push(sessionId)
898
+ else rejected.push({ sessionId, ok: false, code: 'invalid', error: 'invalid session id' })
899
+ }
900
+
901
+ // Phase 1: stop + flush. A failure here is that session's failure only.
902
+ const stopped = new Map()
903
+ const stopErrors = new Map()
904
+ await runWithConcurrency(valid, BATCH_CONCURRENCY, async (sessionId) => {
905
+ try {
906
+ stopped.set(sessionId, await stopSession(ctx, sessionId))
907
+ } catch (error) {
908
+ stopErrors.set(sessionId, error)
909
+ }
910
+ })
911
+
912
+ // Phase 2: lease probe, wide. Sessions that never stopped are not probed.
913
+ const unready = new Map()
914
+ const ready = valid.filter((sessionId) => !stopErrors.has(sessionId))
915
+ await runWithConcurrency(ready, BATCH_PROBE_CONCURRENCY, async (sessionId) => {
916
+ try {
917
+ await requireWritable(ctx, sessionId)
918
+ } catch (error) {
919
+ unready.set(sessionId, error)
920
+ }
921
+ })
922
+
923
+ // Phase 3: retire what is clear to go.
924
+ const results = []
925
+ const swept = valid.filter((sessionId) => !stopErrors.has(sessionId) && !unready.has(sessionId))
926
+ const retired = new Map()
927
+ const retireErrors = new Map()
928
+ await runWithConcurrency(swept, BATCH_CONCURRENCY, async (sessionId) => {
929
+ try {
930
+ retired.set(sessionId, await retireSession(ctx, sessionId, options, stopped.get(sessionId)))
931
+ } catch (error) {
932
+ retireErrors.set(sessionId, error)
933
+ }
934
+ })
935
+
936
+ for (const sessionId of valid) {
937
+ const error = stopErrors.get(sessionId) || unready.get(sessionId) || retireErrors.get(sessionId)
938
+ if (error !== undefined) {
939
+ results.push({
940
+ sessionId,
941
+ ok: false,
942
+ code: error instanceof HttpError ? error.code : 'internal',
943
+ error: String((error && error.message) || error),
944
+ })
945
+ continue
946
+ }
947
+ results.push({ sessionId, ok: true, removed: retired.get(sessionId).removed })
948
+ }
949
+
950
+ return [...results, ...rejected]
951
+ }
837
952
  /**
838
953
  * Take one session off the disk: its directories and its cache rows, then any
839
954
  * directory the drain recreated. Shared by the parent and every child, so a
@@ -2097,21 +2212,9 @@ export function apply(ctx) {
2097
2212
  // sessions run in parallel and the workspace accounting mutation is
2098
2213
  // serialized inside deleteSession, so a batch can never interleave two
2099
2214
  // deletions of the same storage.
2100
- const results = await runWithConcurrency(sessionIds, BATCH_CONCURRENCY, async (sessionId) => {
2101
- try {
2102
- const result = await deleteSession(ctx, sessionId, {
2103
- recycle: body.recycle !== false,
2104
- childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2105
- })
2106
- return { sessionId, ok: true, removed: result.removed }
2107
- } catch (error) {
2108
- return {
2109
- sessionId,
2110
- ok: false,
2111
- code: error instanceof HttpError ? error.code : 'internal',
2112
- error: String((error && error.message) || error),
2113
- }
2114
- }
2215
+ const results = await deleteSessions(ctx, sessionIds, {
2216
+ recycle: body.recycle !== false,
2217
+ childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2115
2218
  })
2116
2219
  const deleted = results.filter((item) => item.ok).length
2117
2220
  sendJson(res, 200, { ok: true, results, deleted, failed: results.length - deleted })
@@ -2152,6 +2255,9 @@ export const internals = {
2152
2255
  resolveQuarantineRoot,
2153
2256
  removeForever,
2154
2257
  deleteSession,
2258
+ deleteSessions,
2259
+ busyBackoff,
2260
+ BUSY_RETRY_ATTEMPTS,
2155
2261
  retirePaths,
2156
2262
  retireTargets,
2157
2263
  listSessionHeaders,
@@ -1471,4 +1471,103 @@ test('a small session is not flagged as truncated', async () => {
1471
1471
  const result = await internals.collectSessionPaths(events, 'C:/ws', new Map())
1472
1472
 
1473
1473
  assert.equal(result.overflow, false)
1474
- })
1474
+ })
1475
+
1476
+ // --- delete speed: backoff schedule and phase pipeline ---------------------
1477
+
1478
+ test('the lease probe backs off exponentially instead of waiting 200ms flat', () => {
1479
+ const schedule = []
1480
+ for (let attempt = 1; attempt <= internals.BUSY_RETRY_ATTEMPTS; attempt += 1) {
1481
+ schedule.push(internals.busyBackoff(attempt))
1482
+ }
1483
+
1484
+ // A live session's first probe is almost always busy (detach releases the lease
1485
+ // asynchronously), so the first retry is what the user actually feels.
1486
+ assert.equal(schedule[0], 20, 'first retry after 20ms, not 200ms')
1487
+ assert.equal(schedule[1], 40)
1488
+ assert.equal(schedule[2], 80)
1489
+ assert.equal(schedule[3], 160)
1490
+ assert.equal(schedule[4], 200, 'capped at the old flat delay')
1491
+
1492
+ // The ceiling must not grow: total wait stays no worse than the flat version.
1493
+ const total = schedule.reduce((a, b) => a + b, 0)
1494
+ const flat = (internals.BUSY_RETRY_ATTEMPTS - 1) * 200
1495
+ assert.equal(total <= flat, true, 'total ' + total + 'ms vs flat ' + flat + 'ms')
1496
+ })
1497
+
1498
+ test('a batch stops every session before it probes any lease', async () => {
1499
+ // Phase pipeline: stop-and-flush all → probe all → retire all. The point is that
1500
+ // the 20-40ms lease waits of different sessions overlap instead of queueing
1501
+ // behind the bounded retire workers.
1502
+ const stoppedAtProbe = []
1503
+ // A session id has two accepted spellings, so `flush` runs twice per session.
1504
+ // The property under test is "every session was stopped", not "every call".
1505
+ const stoppedIds = new Set()
1506
+ const ctx = {
1507
+ get(name) {
1508
+ if (name === 'sessionPersistence') {
1509
+ return {
1510
+ open: async (sessionId) => {
1511
+ stoppedAtProbe.push({ sessionId, stopCount: stoppedIds.size })
1512
+ return { close: async () => {} }
1513
+ },
1514
+ }
1515
+ }
1516
+ if (name === 'sessions') {
1517
+ return {
1518
+ get: (variant) => ({ id: variant }),
1519
+ flush: async (live) => {
1520
+ stoppedIds.add(String(live.id).replace(/^session-/, ''))
1521
+ },
1522
+ store: { get: () => undefined },
1523
+ }
1524
+ }
1525
+ return undefined
1526
+ },
1527
+ }
1528
+
1529
+ const ids = []
1530
+ for (let i = 0; i < 4; i += 1) {
1531
+ const id = `session-0000000${i}-0000-4000-8000-0000000000${i}0`
1532
+ ids.push(id)
1533
+ plantSession(id)
1534
+ }
1535
+
1536
+ const results = await internals.deleteSessions(ctx, ids, { recycle: false })
1537
+
1538
+ assert.equal(results.length, 4, 'one result per session')
1539
+ assert.deepEqual(results.map((r) => r.ok), [true, true, true, true], 'all deleted')
1540
+
1541
+ // Every probe must see that all four sessions were already stopped. The old
1542
+ // per-session pipeline probed the first session while the others were still
1543
+ // flushing, so this is the property that proves the phases were batched.
1544
+ for (const entry of stoppedAtProbe) {
1545
+ assert.equal(entry.stopCount, ids.length, 'session ' + entry.sessionId + ' probed after every stop')
1546
+ }
1547
+ })
1548
+
1549
+ test('one failing session does not take the rest of the batch down', async () => {
1550
+ const good = 'session-00000001-0000-4000-8000-000000000010'
1551
+ const bad = 'session-00000002-0000-4000-8000-000000000020'
1552
+ plantSession(good)
1553
+
1554
+ const ctx = {
1555
+ get(name) {
1556
+ if (name !== 'sessionPersistence') return undefined
1557
+ return {
1558
+ open: async (sessionId) => {
1559
+ if (sessionId === bad) throw new Error('held by an active writer forever')
1560
+ return { close: async () => {} }
1561
+ },
1562
+ stat: async () => undefined,
1563
+ }
1564
+ },
1565
+ }
1566
+
1567
+ const results = await internals.deleteSessions(ctx, [good, bad], { recycle: false })
1568
+
1569
+ const byId = new Map(results.map((r) => [r.sessionId, r]))
1570
+ assert.equal(byId.get(good).ok, true, 'the healthy session still goes')
1571
+ assert.equal(byId.get(bad).ok, false, 'the stuck one reports failure')
1572
+ assert.equal(byId.get(bad).code, 'busy')
1573
+ })