dsh-keys-manager 0.2.9 → 0.2.11

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/lib/domain.d.ts CHANGED
@@ -125,8 +125,10 @@ export interface StateDocument {
125
125
  }>;
126
126
  }
127
127
  /** One plan window projected into an account row. */
128
+ /** The plan windows a card can render; the one declaration every layer imports. */
129
+ export type QuotaWindowId = 'session' | 'week';
128
130
  export interface QuotaWindowView {
129
- id: 'session' | 'week';
131
+ id: QuotaWindowId;
130
132
  /** Share of the window already used, `0`..`1`. */
131
133
  usedFraction: number;
132
134
  /** Reset time as epoch milliseconds. */
@@ -141,6 +143,11 @@ export interface QuotaView {
141
143
  fetchedAt: number;
142
144
  /** True when the windows are last-good data served behind a failed probe. */
143
145
  stale?: boolean;
146
+ /**
147
+ * Set on `absent`: `no-probe` = this route has no usage endpoint at all,
148
+ * `reported-nothing` = a probe ran and the vendor reported no usage.
149
+ */
150
+ absentCause?: 'no-probe' | 'reported-nothing';
144
151
  windows: QuotaWindowView[];
145
152
  }
146
153
  /** Public key row returned to the UI (no credential reference or value). */
@@ -245,6 +252,8 @@ export interface TransportAccountView {
245
252
  status: TransportAccountStatus;
246
253
  /** Derived from {@link status}: true only while it is `'active'`. */
247
254
  active: boolean;
255
+ /** Latest cached plan usage; absent until a quota refresh ran for this route. */
256
+ quota?: QuotaView;
248
257
  }
249
258
  /** One model row a transport route can advertise. */
250
259
  export interface TransportCatalogModel {
package/lib/index.d.ts CHANGED
@@ -779,6 +779,8 @@ export declare class KeysManagerService {
779
779
  * `run` queue and no state flush.
780
780
  */
781
781
  removeTransportAccount(route: string): Promise<StateView>;
782
+ /** Drop the cached usage snapshot for one transport scope. */
783
+ private dropTransportQuota;
782
784
  /** The route's removal epoch; absent means never removed. */
783
785
  private transportGenerationOf;
784
786
  /**
@@ -1588,10 +1590,22 @@ export declare class KeysManagerService {
1588
1590
  quotaRefresh(provider: string): Promise<StateView>;
1589
1591
  /** One provider's quota cache, created on first use. */
1590
1592
  private quotaCache;
1593
+ /** The listed transport row for a route id, refreshing the rows once if needed. */
1594
+ private transportRowOf;
1591
1595
  /**
1592
- * Refresh one row, resolving its credential first. TTL, backoff and
1593
- * single-flight live in the cache, so two concurrent refreshes of the same
1594
- * row share one probe.
1596
+ * Refresh one transport route's usage.
1597
+ *
1598
+ * The grant is read-only: no rotation, no repair, no write-back. A record
1599
+ * that is missing or unparseable means "this account's usage is managed
1600
+ * natively" — never a sign-in prompt. The cache is keyed by the scope, so a
1601
+ * transport snapshot can never collide with a pool route's cache (D2).
1602
+ */
1603
+ private refreshTransportQuota;
1604
+ /**
1605
+ * Refresh one row. The credential is resolved INSIDE the cache loader, so a
1606
+ * fresh entry (TTL hit or in-flight fellow) performs no credential read at
1607
+ * all (`I-000296`); TTL, backoff and single-flight live in the cache, so two
1608
+ * concurrent refreshes of the same row share one read and one probe.
1595
1609
  */
1596
1610
  private refreshQuotaRow;
1597
1611
  /**
@@ -1604,20 +1618,46 @@ export declare class KeysManagerService {
1604
1618
  */
1605
1619
  private quotaCredential;
1606
1620
  /**
1607
- * A readable pool grant for one row, `undefined` when no usable record exists,
1608
- * or `unreadable` when the read itself failed. The distinction matters: only
1609
- * a foreign route may fall back to the projection after a failed read.
1621
+ * A readable pool grant for one row (`undefined` when no usable record
1622
+ * exists), or `transient` when the store itself kept failing.
1623
+ *
1624
+ * One retry covers a momentarily locked store (D2). A missing or invalid
1625
+ * record is a deterministic fact; a read that throws twice is not — the row
1626
+ * must report a transient failure, never an auth one.
1610
1627
  */
1611
1628
  private readGrantCredential;
1612
1629
  /**
1613
1630
  * The provider's live projection as a quota credential.
1614
1631
  *
1615
- * A record that exists but cannot be read (wrong kind, unrecognized payload)
1616
- * or a read that throws is classified `natively-managed`, never `missing`: we
1617
- * cannot prove no account serves the route, and claiming otherwise is exactly
1618
- * the false "sign in again" this plan removes.
1632
+ * A record that exists but carries no readable grant (wrong kind, unrecognized
1633
+ * payload) is classified `natively-managed`, never `missing`: we cannot prove
1634
+ * no account serves the route, and claiming otherwise is exactly the false
1635
+ * "sign in again" this plan removes. A read that keeps THROWING is different —
1636
+ * it is retried once, then reported as `transient` (`error`), because a store
1637
+ * failure says nothing about the credential.
1619
1638
  */
1620
1639
  private projectionQuotaCredential;
1640
+ /**
1641
+ * One row's cached quota windows for ranking (issue #22): a read-only peek,
1642
+ * never a probe. A row with no snapshot simply ranks as unknown.
1643
+ */
1644
+ private quotaWindowsOf;
1645
+ /** The quota tier of one key (`0`/`1` are the sticky-safe tiers). */
1646
+ private quotaTierOf;
1647
+ /**
1648
+ * Whether a sticky binding may hold for this request (D3).
1649
+ *
1650
+ * The binding yields only to an actual quota signal: when no selectable key
1651
+ * of the route reports usable quota, every candidate ranks unknown (tier 2)
1652
+ * and the route must keep its pre-ranking sticky behaviour byte for byte.
1653
+ */
1654
+ private stickyBindingHolds;
1655
+ /**
1656
+ * The next selectable key in quota order, skipping ids already tried and
1657
+ * advancing the cursor past whatever it picks — the same cursor contract
1658
+ * `pickRoundRobin` keeps for the unranked path.
1659
+ */
1660
+ private pickRanked;
1621
1661
  /** Project the cached quota of one row; a pure memory read, never a probe. */
1622
1662
  private quotaViewFor;
1623
1663
  /**
package/lib/index.js CHANGED
@@ -17,7 +17,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
17
17
  import { createHash, randomBytes } from 'node:crypto';
18
18
  import { CURSOR_ROUTE, cursorCatalogModels } from 'dsh-llm-omp-transports';
19
19
  import * as transportModule from 'dsh-llm-omp-transports';
20
- import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown, bindingKey, classifyOAuthFailure, isSelectable, markKeySuccess, markKeyUsed, normalizeSettings, patchSettings, pickHealthyExcluding, pickRoundRobin, shouldFailover, statusOfKey, statusOfProvider, validateKeyInput, validateKeyPatch, } from './core.js';
20
+ import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown, bindingKey, classifyOAuthFailure, isSelectable, markKeySuccess, markKeyUsed, normalizeSettings, patchSettings, pickHealthyExcluding, pickRoundRobin, quotaRank, rankCandidates, shouldFailover, statusOfKey, statusOfProvider, validateKeyInput, validateKeyPatch, } from './core.js';
21
21
  import { signInCapable, signInProvider } from './oauth/providers.js';
22
22
  import { SignInCancelledError, runSignIn } from './oauth/signin.js';
23
23
  import { EXTRA_PROVIDER_MAP, EXTRA_PROVIDERS } from './providers.js';
@@ -38,6 +38,8 @@ const ORIGINAL = Symbol.for('cordis.original');
38
38
  * only writer allowed while `shutdownRequested` is up.
39
39
  */
40
40
  const PRE_CLOSE_RESTORE = Symbol('keys-manager.pre-close restore');
41
+ /** Rows one quota refresh probes at once (`I-000296`). */
42
+ const QUOTA_PROBE_CONCURRENCY = 4;
41
43
  const MAX_SWITCHES = 6;
42
44
  const ATTEMPT_TTL_MS = 60 * 60 * 1000;
43
45
  /** A retry pin only lives for this long; an expired pin is treated as absent. */
@@ -466,6 +468,42 @@ function missingHeaders(declared, stored) {
466
468
  }
467
469
  return missing;
468
470
  }
471
+ /**
472
+ * Whether the credential a probe just used is already expired.
473
+ *
474
+ * The grant payload's expiry wins: it describes the token the vendor actually
475
+ * saw, while the row timestamp can lag behind a rotation. The row value is only
476
+ * a fallback for payloads without a usable expiry — never a "fresh" guess.
477
+ * A missing or unusable value counts as NOT expired (the conservative label).
478
+ */
479
+ function credentialExpired(key, now, payloadExpiresAt) {
480
+ const payloadExpiry = usableExpiry(payloadExpiresAt);
481
+ if (payloadExpiry !== undefined)
482
+ return payloadExpiry <= now;
483
+ const rowExpiry = usableExpiry(key.oauth?.expiresAt);
484
+ return rowExpiry !== undefined && rowExpiry <= now;
485
+ }
486
+ /** Read a transport grant payload; `undefined` when it is not usable. */
487
+ function readTransportGrant(record) {
488
+ if (record?.kind !== 'grant')
489
+ return undefined;
490
+ const payload = record.payload;
491
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload))
492
+ return undefined;
493
+ const fields = payload;
494
+ if (typeof fields.access !== 'string' || fields.access.length === 0)
495
+ return undefined;
496
+ return {
497
+ access: fields.access,
498
+ ...(typeof fields.expires === 'number' && Number.isFinite(fields.expires) ? { expires: fields.expires } : {}),
499
+ ...(typeof fields.orgId === 'string' && fields.orgId.length > 0 ? { orgId: fields.orgId } : {}),
500
+ ...(typeof fields.region === 'string' && fields.region.length > 0 ? { region: fields.region } : {}),
501
+ };
502
+ }
503
+ /** A payload/row expiry value this manager can reason about, or `undefined`. */
504
+ function usableExpiry(value) {
505
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
506
+ }
469
507
  /** Public, secret-free key row. */
470
508
  function publicKey(key, now, projectedAccountId, quota) {
471
509
  return {
@@ -2304,6 +2342,9 @@ export class KeysManagerService {
2304
2342
  }
2305
2343
  if (outcome.status === 'authorized') {
2306
2344
  this.finishLoginAttempt(attempt, 'ready');
2345
+ // A new grant is a new account: the cached usage belonged to the
2346
+ // previous credential, so the next read must probe again.
2347
+ this.dropTransportQuota(flow.key);
2307
2348
  void this.refreshTransportAccounts();
2308
2349
  return;
2309
2350
  }
@@ -2366,9 +2407,17 @@ export class KeysManagerService {
2366
2407
  await pending.settled;
2367
2408
  }
2368
2409
  await records.deleteRecord(flow.key);
2410
+ // The snapshot under this scope describes the account that just went away;
2411
+ // keeping it would show the previous account's numbers for one TTL.
2412
+ this.dropTransportQuota(flow.key);
2369
2413
  await this.refreshTransportAccounts();
2370
2414
  return this.buildState();
2371
2415
  }
2416
+ /** Drop the cached usage snapshot for one transport scope. */
2417
+ dropTransportQuota(scope) {
2418
+ this.quotaCaches.get(scope)?.retain(scope, undefined);
2419
+ this.quotaCaches.delete(scope);
2420
+ }
2372
2421
  /** The route's removal epoch; absent means never removed. */
2373
2422
  transportGenerationOf(route) {
2374
2423
  return this.transportRemovals.get(route) ?? 0;
@@ -6414,7 +6463,11 @@ export class KeysManagerService {
6414
6463
  pausedKeyCount: allKeys.filter(key => key.status === 'paused').length,
6415
6464
  bindingsCount: Object.keys(this.store.state.sessionBindings).length,
6416
6465
  warnings,
6417
- transportAccounts: this.transportRows.map(row => ({ ...row })),
6466
+ transportAccounts: this.transportRows.map(row => {
6467
+ // Same projection the pool rows get; the cache key is the row's scope.
6468
+ const quota = this.quotaViewFor(row.scope, row.scope);
6469
+ return quota === undefined ? { ...row } : { ...row, quota };
6470
+ }),
6418
6471
  };
6419
6472
  }
6420
6473
  /**
@@ -6445,12 +6498,35 @@ export class KeysManagerService {
6445
6498
  // Own-property lookup: `store.provider` indexes a plain object, so a
6446
6499
  // prototype key would answer a function instead of a record.
6447
6500
  const record = Object.hasOwn(this.store.providers, provider) ? this.store.provider(provider) : undefined;
6448
- if (record === undefined)
6501
+ if (record === undefined) {
6502
+ // Not a pi-ai pool route: a transport route (`llm-omp-transports/<id>`)
6503
+ // keeps its grant on the transports package's own scope, so the usage read
6504
+ // resolves that record instead of a pool row (D2).
6505
+ const transport = await this.transportRowOf(provider);
6506
+ if (transport !== undefined) {
6507
+ await this.refreshTransportQuota(provider, transport);
6508
+ return this.buildState();
6509
+ }
6510
+ // A released provider keeps no snapshots: nothing would ever read them
6511
+ // again, and a re-adoption must start from a clean slate.
6512
+ this.quotaCaches.get(provider)?.retain(provider, undefined);
6513
+ this.quotaCaches.delete(provider);
6449
6514
  return this.buildState();
6515
+ }
6450
6516
  const cache = this.quotaCache(provider);
6517
+ // Rows deleted since the last refresh must not linger in the cache either.
6518
+ cache.retain(provider, new Set(record.keys.map(key => key.id)));
6451
6519
  // The cache classifies probe failures; allSettled is the second line of
6452
6520
  // defence so one rejected row can never reject the RPC.
6453
- await Promise.allSettled(record.keys.map(key => this.refreshQuotaRow(provider, cache, key)));
6521
+ // At most QUOTA_PROBE_CONCURRENCY rows run at once (`I-000296`): a wide
6522
+ // pool must not open a dozen vendor connections in one gesture.
6523
+ const queue = [...record.keys];
6524
+ const workers = Array.from({ length: Math.min(QUOTA_PROBE_CONCURRENCY, queue.length) }, async () => {
6525
+ for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
6526
+ await this.refreshQuotaRow(provider, cache, next);
6527
+ }
6528
+ });
6529
+ await Promise.allSettled(workers);
6454
6530
  return this.buildState();
6455
6531
  }
6456
6532
  /** One provider's quota cache, created on first use. */
@@ -6462,14 +6538,97 @@ export class KeysManagerService {
6462
6538
  this.quotaCaches.set(provider, cache);
6463
6539
  return cache;
6464
6540
  }
6541
+ /** The listed transport row for a route id, refreshing the rows once if needed. */
6542
+ async transportRowOf(provider) {
6543
+ const listed = this.transportRows.find(row => row.id === provider);
6544
+ if (listed !== undefined)
6545
+ return listed;
6546
+ // The card may be opened before the first transport pass; one read pass is
6547
+ // cheap and keeps this path consistent with what the UI lists.
6548
+ await this.refreshTransportAccounts();
6549
+ return this.transportRows.find(row => row.id === provider);
6550
+ }
6551
+ /**
6552
+ * Refresh one transport route's usage.
6553
+ *
6554
+ * The grant is read-only: no rotation, no repair, no write-back. A record
6555
+ * that is missing or unparseable means "this account's usage is managed
6556
+ * natively" — never a sign-in prompt. The cache is keyed by the scope, so a
6557
+ * transport snapshot can never collide with a pool route's cache (D2).
6558
+ */
6559
+ async refreshTransportQuota(provider, row) {
6560
+ const cache = this.quotaCache(row.scope);
6561
+ await cache.get(row.scope, row.scope, async () => {
6562
+ const records = this.credentialRecords();
6563
+ if (records === undefined) {
6564
+ return {
6565
+ status: 'natively-managed',
6566
+ fetchedAt: 0,
6567
+ windows: [],
6568
+ reason: 'no credential store to read the transport grant',
6569
+ };
6570
+ }
6571
+ let record;
6572
+ try {
6573
+ record = await records.readRecord(row.scope);
6574
+ }
6575
+ catch {
6576
+ // A store that cannot be read is transient, exactly like the pool path.
6577
+ return {
6578
+ status: 'error',
6579
+ fetchedAt: 0,
6580
+ windows: [],
6581
+ reason: 'the transport grant could not be read',
6582
+ };
6583
+ }
6584
+ const grant = readTransportGrant(record);
6585
+ if (grant === undefined) {
6586
+ return {
6587
+ status: 'natively-managed',
6588
+ fetchedAt: 0,
6589
+ windows: [],
6590
+ reason: 'the transport grant is not readable by this plugin',
6591
+ };
6592
+ }
6593
+ const snapshot = await resolveQuota(provider, {
6594
+ token: grant.access,
6595
+ ...(grant.orgId === undefined ? {} : { orgId: grant.orgId }),
6596
+ ...(grant.region === undefined ? {} : { region: grant.region }),
6597
+ ...(this.quotaFetch === undefined ? {} : { fetch: this.quotaFetch }),
6598
+ });
6599
+ // An expired stored token cannot be refreshed from here, so a refusal is
6600
+ // "a model request will fix this", not a sign-in prompt.
6601
+ const grantExpiry = usableExpiry(grant.expires);
6602
+ if (snapshot.status === 'unauthorized' && grantExpiry !== undefined && grantExpiry <= Date.now()) {
6603
+ return {
6604
+ status: 'natively-managed',
6605
+ fetchedAt: snapshot.fetchedAt,
6606
+ windows: [],
6607
+ reason: 'the stored transport credential expired and only a model request refreshes it',
6608
+ };
6609
+ }
6610
+ return snapshot;
6611
+ });
6612
+ }
6465
6613
  /**
6466
- * Refresh one row, resolving its credential first. TTL, backoff and
6467
- * single-flight live in the cache, so two concurrent refreshes of the same
6468
- * row share one probe.
6614
+ * Refresh one row. The credential is resolved INSIDE the cache loader, so a
6615
+ * fresh entry (TTL hit or in-flight fellow) performs no credential read at
6616
+ * all (`I-000296`); TTL, backoff and single-flight live in the cache, so two
6617
+ * concurrent refreshes of the same row share one read and one probe.
6469
6618
  */
6470
6619
  async refreshQuotaRow(provider, cache, key) {
6471
- const credential = await this.quotaCredential(provider, key);
6472
6620
  await cache.get(provider, key.id, async () => {
6621
+ const credential = await this.quotaCredential(provider, key);
6622
+ if (credential.kind === 'transient') {
6623
+ // A store that kept failing is "could not read usage now", never an
6624
+ // auth fact: `error` keeps the last-good numbers on display.
6625
+ return {
6626
+ status: 'error',
6627
+ fetchedAt: 0,
6628
+ windows: [],
6629
+ reason: 'the credential store could not be read',
6630
+ };
6631
+ }
6473
6632
  if (credential.kind === 'natively-managed') {
6474
6633
  // The route is served by a DSH-managed projection we cannot read. That
6475
6634
  // is not "your pool credential is invalid": the honest state keeps the
@@ -6508,6 +6667,19 @@ export class KeysManagerService {
6508
6667
  reason: 'the serving projection credential was refused',
6509
6668
  };
6510
6669
  }
6670
+ // A pool-sourced 401 with a stored token that has already expired is a
6671
+ // refresh problem, not a sign-in prompt: re-signing-in this row cannot
6672
+ // help, and pi-ai only refreshes on model traffic (D1).
6673
+ if (credential.source === 'pool'
6674
+ && snapshot.status === 'unauthorized'
6675
+ && credentialExpired(key, Date.now(), credential.expiresAt)) {
6676
+ return {
6677
+ status: 'natively-managed',
6678
+ fetchedAt: snapshot.fetchedAt,
6679
+ windows: [],
6680
+ reason: 'the stored credential expired and only a model request refreshes it',
6681
+ };
6682
+ }
6511
6683
  return snapshot;
6512
6684
  });
6513
6685
  }
@@ -6524,9 +6696,13 @@ export class KeysManagerService {
6524
6696
  const own = await this.readGrantCredential(key.oauth?.grantRef, key.oauth?.accountId);
6525
6697
  if (own !== undefined && own.kind === 'credential')
6526
6698
  return own;
6699
+ // A store that kept throwing says nothing about this credential: report
6700
+ // the transient class instead of falling back to another account or
6701
+ // claiming the grant is unreadable.
6702
+ if (own !== undefined && own.kind === 'transient')
6703
+ return { kind: 'transient' };
6527
6704
  // Only a route this manager already classifies as foreign may borrow the
6528
- // projection's credential. Without the gate a transient credential-store
6529
- // error would pair this row's identity with another account's usage.
6705
+ // projection's credential; anything else keeps its own row's identity.
6530
6706
  if (!this.foreignProjections.has(provider))
6531
6707
  return { kind: 'missing' };
6532
6708
  return this.projectionQuotaCredential(provider);
@@ -6537,58 +6713,121 @@ export class KeysManagerService {
6537
6713
  : { kind: 'credential', source: 'pool', token: probe.hit.value };
6538
6714
  }
6539
6715
  /**
6540
- * A readable pool grant for one row, `undefined` when no usable record exists,
6541
- * or `unreadable` when the read itself failed. The distinction matters: only
6542
- * a foreign route may fall back to the projection after a failed read.
6716
+ * A readable pool grant for one row (`undefined` when no usable record
6717
+ * exists), or `transient` when the store itself kept failing.
6718
+ *
6719
+ * One retry covers a momentarily locked store (D2). A missing or invalid
6720
+ * record is a deterministic fact; a read that throws twice is not — the row
6721
+ * must report a transient failure, never an auth one.
6543
6722
  */
6544
6723
  async readGrantCredential(grantRef, accountId) {
6545
6724
  const records = this.credentialRecords();
6546
6725
  if (grantRef === undefined || grantRef.length === 0 || records === undefined)
6547
6726
  return undefined;
6548
- try {
6549
- const record = await records.readRecord(grantRef);
6550
- if (record === undefined || record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
6551
- return undefined;
6552
- return {
6553
- kind: 'credential',
6554
- source: 'pool',
6555
- token: record.payload.access,
6556
- ...(accountId === undefined ? {} : { accountId }),
6557
- };
6558
- }
6559
- catch {
6560
- return { kind: 'unreadable' };
6727
+ for (let attempt = 0; attempt < 2; attempt += 1) {
6728
+ try {
6729
+ const record = await records.readRecord(grantRef);
6730
+ if (record === undefined || record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
6731
+ return undefined;
6732
+ const expires = usableExpiry(record.payload.expires);
6733
+ return {
6734
+ kind: 'credential',
6735
+ source: 'pool',
6736
+ token: record.payload.access,
6737
+ ...(accountId === undefined ? {} : { accountId }),
6738
+ ...(expires === undefined ? {} : { expiresAt: expires }),
6739
+ };
6740
+ }
6741
+ catch {
6742
+ // Try once more; the second throw is reported as transient below.
6743
+ }
6561
6744
  }
6745
+ return { kind: 'transient' };
6562
6746
  }
6563
6747
  /**
6564
6748
  * The provider's live projection as a quota credential.
6565
6749
  *
6566
- * A record that exists but cannot be read (wrong kind, unrecognized payload)
6567
- * or a read that throws is classified `natively-managed`, never `missing`: we
6568
- * cannot prove no account serves the route, and claiming otherwise is exactly
6569
- * the false "sign in again" this plan removes.
6750
+ * A record that exists but carries no readable grant (wrong kind, unrecognized
6751
+ * payload) is classified `natively-managed`, never `missing`: we cannot prove
6752
+ * no account serves the route, and claiming otherwise is exactly the false
6753
+ * "sign in again" this plan removes. A read that keeps THROWING is different —
6754
+ * it is retried once, then reported as `transient` (`error`), because a store
6755
+ * failure says nothing about the credential.
6570
6756
  */
6571
6757
  async projectionQuotaCredential(provider) {
6572
6758
  const records = this.credentialRecords();
6573
6759
  if (records === undefined)
6574
6760
  return { kind: 'missing' };
6575
- try {
6576
- const record = await records.readRecord(`${OAUTH_GRANT_RECORD_SCOPE}/${provider}`);
6577
- if (record === undefined)
6578
- return { kind: 'missing' };
6579
- if (record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
6580
- return { kind: 'natively-managed' };
6581
- const accountId = record.payload.accountId;
6582
- return {
6583
- kind: 'credential',
6584
- source: 'projection',
6585
- token: record.payload.access,
6586
- ...(typeof accountId === 'string' && accountId.length > 0 ? { accountId } : {}),
6587
- };
6588
- }
6589
- catch {
6590
- return { kind: 'natively-managed' };
6761
+ for (let attempt = 0; attempt < 2; attempt += 1) {
6762
+ try {
6763
+ const record = await records.readRecord(`${OAUTH_GRANT_RECORD_SCOPE}/${provider}`);
6764
+ if (record === undefined)
6765
+ return { kind: 'missing' };
6766
+ if (record.kind !== 'grant' || !isOAuthGrantPayload(record.payload))
6767
+ return { kind: 'natively-managed' };
6768
+ const accountId = record.payload.accountId;
6769
+ const expires = usableExpiry(record.payload.expires);
6770
+ return {
6771
+ kind: 'credential',
6772
+ source: 'projection',
6773
+ token: record.payload.access,
6774
+ ...(typeof accountId === 'string' && accountId.length > 0 ? { accountId } : {}),
6775
+ ...(expires === undefined ? {} : { expiresAt: expires }),
6776
+ };
6777
+ }
6778
+ catch {
6779
+ // Same one-retry rule as the pool read.
6780
+ }
6591
6781
  }
6782
+ return { kind: 'transient' };
6783
+ }
6784
+ /**
6785
+ * One row's cached quota windows for ranking (issue #22): a read-only peek,
6786
+ * never a probe. A row with no snapshot simply ranks as unknown.
6787
+ */
6788
+ quotaWindowsOf(provider, keyId) {
6789
+ const snapshot = this.quotaCaches.get(provider)?.peek(provider, keyId);
6790
+ // Ranking refuses anything the display path would not trust as live: a
6791
+ // non-`ok` state carries no quota fact, and a last-good snapshot kept
6792
+ // behind a failed probe must not outrank a fresh read for up to a day.
6793
+ if (snapshot === undefined || snapshot.status !== 'ok' || snapshot.stale === true)
6794
+ return undefined;
6795
+ return snapshot.windows;
6796
+ }
6797
+ /** The quota tier of one key (`0`/`1` are the sticky-safe tiers). */
6798
+ quotaTierOf(provider, keyId, now) {
6799
+ return quotaRank(this.quotaWindowsOf(provider, keyId), now).tier;
6800
+ }
6801
+ /**
6802
+ * Whether a sticky binding may hold for this request (D3).
6803
+ *
6804
+ * The binding yields only to an actual quota signal: when no selectable key
6805
+ * of the route reports usable quota, every candidate ranks unknown (tier 2)
6806
+ * and the route must keep its pre-ranking sticky behaviour byte for byte.
6807
+ */
6808
+ stickyBindingHolds(providerId, provider, bound, now) {
6809
+ // (a) A binding that still has usable quota keeps the session.
6810
+ if (this.quotaTierOf(providerId, bound.id, now) <= 1)
6811
+ return true;
6812
+ // (b) The genuine no-quota-signal route: EVERY selectable key ranks
6813
+ // unknown (tier 2), so the pre-ranking sticky behaviour applies unchanged.
6814
+ // A tier-3 binding yields here as soon as any sibling reports real usage.
6815
+ return provider.keys.every(candidate => !isSelectable(candidate, now) || this.quotaTierOf(providerId, candidate.id, now) === 2);
6816
+ }
6817
+ /**
6818
+ * The next selectable key in quota order, skipping ids already tried and
6819
+ * advancing the cursor past whatever it picks — the same cursor contract
6820
+ * `pickRoundRobin` keeps for the unranked path.
6821
+ */
6822
+ pickRanked(provider, now, tried) {
6823
+ const ranked = rankCandidates(provider, now, keyId => this.quotaWindowsOf(provider.provider, keyId));
6824
+ const chosen = ranked.find(candidate => tried?.has(candidate.id) !== true);
6825
+ if (chosen === undefined)
6826
+ return undefined;
6827
+ const index = provider.keys.findIndex(candidate => candidate.id === chosen.id);
6828
+ if (index >= 0)
6829
+ provider.cursor = (index + 1) % provider.keys.length;
6830
+ return chosen;
6592
6831
  }
6593
6832
  /** Project the cached quota of one row; a pure memory read, never a probe. */
6594
6833
  quotaViewFor(provider, keyId) {
@@ -6601,6 +6840,9 @@ export class KeysManagerService {
6601
6840
  status: snapshot.status,
6602
6841
  fetchedAt: snapshot.fetchedAt,
6603
6842
  ...(snapshot.stale === true ? { stale: true } : {}),
6843
+ // Why an `absent` read is empty travels with it: the card must not read
6844
+ // "this route has no usage endpoint" as "the read failed" (#62).
6845
+ ...(snapshot.absentCause === undefined ? {} : { absentCause: snapshot.absentCause }),
6604
6846
  windows: snapshot.windows.map(window => ({
6605
6847
  id: window.id,
6606
6848
  usedFraction: window.usedFraction,
@@ -8037,12 +8279,12 @@ export class KeysManagerService {
8037
8279
  const binding = this.store.binding(sessionId, providerId);
8038
8280
  if (binding !== undefined) {
8039
8281
  const bound = provider.keys.find(candidate => candidate.id === binding.keyId);
8040
- if (isSelectable(bound, now))
8282
+ if (isSelectable(bound, now) && this.stickyBindingHolds(providerId, provider, bound, now))
8041
8283
  key = bound;
8042
8284
  }
8043
8285
  }
8044
8286
  if (key === undefined)
8045
- key = pickRoundRobin(provider, now);
8287
+ key = this.pickRanked(provider, now);
8046
8288
  const tryCandidate = async (candidate) => {
8047
8289
  if (candidate === undefined)
8048
8290
  return undefined;
@@ -8068,7 +8310,7 @@ export class KeysManagerService {
8068
8310
  const selected = await tryCandidate(key);
8069
8311
  if (selected !== undefined)
8070
8312
  return selected;
8071
- key = pickRoundRobin(provider, now, tried);
8313
+ key = this.pickRanked(provider, now, tried);
8072
8314
  }
8073
8315
  // A previously missing key may have been restored in the credential store.
8074
8316
  // Re-probe those candidates when no healthy key remains; a transient read