@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.1
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 +27 -0
- package/bin/tmct.mjs +61 -0
- package/package.json +14 -2
- package/src/adapters/memory/backends-exports.mjs +8 -0
- package/src/adapters/memory/core.mjs +812 -175
- package/src/adapters/memory/corpus-bands.mjs +155 -0
- package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
- package/src/adapters/memory/row-backend-dynamo.mjs +315 -0
- package/src/adapters/memory/row-backend-memory.mjs +85 -0
- package/src/adapters/memory/row-backend.mjs +162 -0
- package/src/adapters/memory/rows.mjs +328 -0
- package/src/adapters/memory/shacl.mjs +24 -0
- package/src/adapters/memory/systemic-failure.mjs +28 -0
- package/src/adapters/research-queue-store.mjs +215 -32
- package/src/domain/ask.mjs +341 -75
- package/src/domain/cli-verbs.mjs +17 -0
- package/src/domain/fact-phrase.mjs +40 -0
- package/src/domain/news-feed.mjs +42 -4
- package/src/domain/phrase-exports.mjs +4 -0
- package/src/domain/retrieval-marker.mjs +120 -0
- package/src/domain/retrieval-modes.mjs +13 -0
- package/src/domain/retrieval-plan.mjs +224 -0
- package/src/services/chat-session.mjs +36 -9
- package/src/services/chat.mjs +73 -16
- package/src/services/corpus-loader.mjs +222 -0
- package/src/services/extract-facts.mjs +244 -33
- package/src/services/init.mjs +15 -5
- package/src/services/news.mjs +4 -2
- package/src/services/subgraph-retrieval.mjs +332 -0
- package/src/surfaces/web/http-row-backend.mjs +150 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +134 -131
- package/src/surfaces/web/news-browser-entry.mjs +6 -2
- package/src/tools/handlers/tmct-ingest.mjs +3 -1
- package/src/tools/memory-backend-conformance.mjs +238 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// corpus-bands.mjs — shared read-only reference partitions that live beside
|
|
2
|
+
// session rows in the same table: band naming, the manifest shape, and the
|
|
3
|
+
// wire row a band fact projects onto.
|
|
4
|
+
//
|
|
5
|
+
// A band lives at partition key `corpus:<band>`, sort key
|
|
6
|
+
// `<rowClass>#<term>#<rowKey>` for a fact row, `manifest` for the band's own
|
|
7
|
+
// bookkeeping row. `corpus:<band>` is not a UUIDv4, so it can never collide
|
|
8
|
+
// with a session key and no session route can address it — the only reads
|
|
9
|
+
// a band partition gets are the deliberate, term-scoped corpus read a turn
|
|
10
|
+
// issues (corpus-loader.mjs's `queryBandTerm`), never a session's own row
|
|
11
|
+
// traffic.
|
|
12
|
+
//
|
|
13
|
+
// Bands are written once, by the credentialed loader (corpus-loader.mjs),
|
|
14
|
+
// and never mutated afterward except by a full reload or clear: nothing on
|
|
15
|
+
// the public API path ever calls putRows against a `corpus:` partition.
|
|
16
|
+
//
|
|
17
|
+
// The term Query itself lives in corpus-loader.mjs, not here: this module is
|
|
18
|
+
// an adapters-layer module (pure naming/shape, no store calls), and the one
|
|
19
|
+
// Query implementation this whole surface shares
|
|
20
|
+
// (subgraph-retrieval.mjs's termQueryOverDocumentClient) is a services-layer
|
|
21
|
+
// module — an adapter may not import upward into services (see
|
|
22
|
+
// test/estate/import-layers.test.mjs).
|
|
23
|
+
|
|
24
|
+
import { normFactTerm, factIdForTriple } from "../../domain/hash.mjs";
|
|
25
|
+
import { assertValidRow } from "./row-backend.mjs";
|
|
26
|
+
|
|
27
|
+
export const BAND_PARTITION_PREFIX = "corpus:";
|
|
28
|
+
export const MANIFEST_SORT_KEY = "manifest";
|
|
29
|
+
|
|
30
|
+
/** The three bands this plan ships a build pipeline and a loader for. */
|
|
31
|
+
export const FIRST_CLASS_BANDS = Object.freeze([
|
|
32
|
+
"wikidata-slice",
|
|
33
|
+
"wordnet-complete",
|
|
34
|
+
"conceptnet-full",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
// Reserved so the partition name is spoken for; no pipeline for it ships
|
|
38
|
+
// here. Its own design doc covers the band when it lands.
|
|
39
|
+
export const RESERVED_BAND_NAMES = Object.freeze(["simplewiki-derived"]);
|
|
40
|
+
|
|
41
|
+
/** The licence and attribution notice each first-class band's content
|
|
42
|
+
* carries — a property of the band's identity, not of any one load, so the
|
|
43
|
+
* loader reads it from here rather than taking it as a per-invocation flag.
|
|
44
|
+
* `notice` is a repo-relative path to the human-readable attribution file;
|
|
45
|
+
* null when the licence carries no attribution burden. */
|
|
46
|
+
export const BAND_LICENSES = Object.freeze({
|
|
47
|
+
"wikidata-slice": Object.freeze({ license: "CC0-1.0", notice: null }),
|
|
48
|
+
"wordnet-complete": Object.freeze({ license: "CC-BY-4.0", notice: "corpus/wordnet/LICENSE-NOTICE" }),
|
|
49
|
+
"conceptnet-full": Object.freeze({ license: "CC-BY-SA-4.0", notice: "corpus/conceptnet/conceptnet-full.NOTICE" }),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** `{license, notice}` for `band`, or both null when the band carries no
|
|
53
|
+
* entry here (a consumer's own band, outside the three first-class ones). */
|
|
54
|
+
export function bandLicenseInfo(band) {
|
|
55
|
+
return BAND_LICENSES[band] ?? { license: null, notice: null };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `corpus:<band>` — the partition key every band's rows and manifest share. */
|
|
59
|
+
export function bandPartitionKey(band) {
|
|
60
|
+
if (!band || typeof band !== "string") throw new TypeError("bandPartitionKey needs a non-empty band name");
|
|
61
|
+
return `${BAND_PARTITION_PREFIX}${band}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** True when `pk` names a band partition rather than a session. A session key
|
|
65
|
+
* is always a UUIDv4, which never starts with this prefix, so this check is
|
|
66
|
+
* exactly the one the public route enforcement (§3.13) rests on. */
|
|
67
|
+
export function isBandPartitionKey(pk) {
|
|
68
|
+
return typeof pk === "string" && pk.startsWith(BAND_PARTITION_PREFIX);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The band name inside a partition key, or null when `pk` is not one. */
|
|
72
|
+
export function bandNameFromPartitionKey(pk) {
|
|
73
|
+
return isBandPartitionKey(pk) ? pk.slice(BAND_PARTITION_PREFIX.length) : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `<rowClass>#<term>#<rowKey>` — the same sort-key layout session fact rows
|
|
77
|
+
* use (§3.3), so a term read is one `begins_with` Query regardless of which
|
|
78
|
+
* partition it targets. */
|
|
79
|
+
export function bandSortKeyForRow(rowClass, term, rowKey) {
|
|
80
|
+
return `${rowClass}#${term}#${rowKey}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The manifest a band load writes last: what the loader reads back to
|
|
84
|
+
* decide "unchanged", and what a citation names as the band's version. */
|
|
85
|
+
export function buildBandManifest({ band, version = 1, rowCount, loadedAt, sourceDigest, license = null, notice = null }) {
|
|
86
|
+
if (!band) throw new TypeError("buildBandManifest needs a band name");
|
|
87
|
+
if (!Number.isInteger(rowCount) || rowCount < 0) throw new TypeError("buildBandManifest needs a non-negative integer rowCount");
|
|
88
|
+
if (!loadedAt) throw new TypeError("buildBandManifest needs loadedAt");
|
|
89
|
+
if (!sourceDigest) throw new TypeError("buildBandManifest needs sourceDigest");
|
|
90
|
+
return { band, version, rowCount, loadedAt, sourceDigest, license, notice };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// A fixed instant, not wall-clock time: a pipeline run over the same source
|
|
94
|
+
// data must produce byte-identical rows, and a fact's own attributes carry no
|
|
95
|
+
// authored date a corpus dump names. The manifest's `loadedAt` (stamped by
|
|
96
|
+
// the loader, not the pipeline) is what actually says how fresh a band is.
|
|
97
|
+
export const BAND_ROW_INSTANT = "2026-01-01T00:00:00.000Z";
|
|
98
|
+
|
|
99
|
+
// The trust prior corpus-sourced facts get everywhere else in the store
|
|
100
|
+
// (src/domain/memory/trust.mjs's SOURCE_PRIOR.corpus) — stamped directly
|
|
101
|
+
// here rather than recomputed, since a band row is never read back through
|
|
102
|
+
// appendFacts' own trust pipeline.
|
|
103
|
+
const CORPUS_TRUST_SCORE = "0.7";
|
|
104
|
+
|
|
105
|
+
/** One band fact as the wire row a build pipeline emits and the loader
|
|
106
|
+
* writes: `{rowKey, rowClass, term, json}`, no `pk`/`sk` — those are the
|
|
107
|
+
* loader's job to add at write time, from `band` and this row's own
|
|
108
|
+
* `rowClass#term#rowKey`. `provenance` is the full `corpus:<name> ...`
|
|
109
|
+
* provenance string (§3.13: no new provenance grammar), and `ord` numbers
|
|
110
|
+
* the row within one pipeline run so a later assembly can reconstruct a
|
|
111
|
+
* stable order.
|
|
112
|
+
*
|
|
113
|
+
* Throws (via `assertValidRow`) when the projected row would be malformed
|
|
114
|
+
* or over the per-row cap — a build pipeline should let that stop the run
|
|
115
|
+
* rather than emit a row the loader would only reject later. */
|
|
116
|
+
export function bandFactRow({ subject, predicate, object, provenance = "", band, ord = 0 }) {
|
|
117
|
+
const term = normFactTerm(subject);
|
|
118
|
+
const sourceId = `src:corpus:${band}`;
|
|
119
|
+
const rowKey = `${factIdForTriple(subject, predicate, object)}@${sourceId}`;
|
|
120
|
+
const individual = {
|
|
121
|
+
id: rowKey,
|
|
122
|
+
label: `${subject} ${predicate} ${object}`,
|
|
123
|
+
class: "Fact",
|
|
124
|
+
derived_from: [],
|
|
125
|
+
mentions: [],
|
|
126
|
+
attributes: [
|
|
127
|
+
{ prop: "rdf:type", key: "type", value: "rdf:Statement" },
|
|
128
|
+
{ prop: "rdf:subject", key: "subject", value: subject },
|
|
129
|
+
{ prop: "rdf:predicate", key: "predicate", value: predicate },
|
|
130
|
+
{ prop: "rdf:object", key: "object", value: object },
|
|
131
|
+
{ prop: "mgx:createdAt", key: "createdAt", value: BAND_ROW_INSTANT },
|
|
132
|
+
{ prop: "mgx:sourceId", key: "sourceId", value: sourceId },
|
|
133
|
+
{ prop: "mgx:factProvenance", key: "provenance", value: provenance },
|
|
134
|
+
{
|
|
135
|
+
prop: "mgx:hasProseTokens",
|
|
136
|
+
key: "prose_tokens",
|
|
137
|
+
value: [...new Set(`${subject} ${object} ${predicate}`.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))].sort().join(" "),
|
|
138
|
+
},
|
|
139
|
+
{ prop: "mgx:trustScore", key: "trustScore", value: CORPUS_TRUST_SCORE },
|
|
140
|
+
{
|
|
141
|
+
prop: "mgx:trustInputs",
|
|
142
|
+
key: "trustInputs",
|
|
143
|
+
value: JSON.stringify({ sourceType: "corpus", sourceId, createdAt: BAND_ROW_INSTANT }),
|
|
144
|
+
},
|
|
145
|
+
{ prop: "mgx:updatedAt", key: "updatedAt", value: BAND_ROW_INSTANT },
|
|
146
|
+
],
|
|
147
|
+
};
|
|
148
|
+
const row = {
|
|
149
|
+
rowKey,
|
|
150
|
+
rowClass: "fact",
|
|
151
|
+
term,
|
|
152
|
+
json: JSON.stringify({ ord, individual }),
|
|
153
|
+
};
|
|
154
|
+
return assertValidRow(row, { provenance });
|
|
155
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// dynamo-circuit-breaker.mjs — guards the turn surface's corpus band Queries
|
|
2
|
+
// against a struggling table. Lambda invocations share nothing, so the state
|
|
3
|
+
// a breaker would normally hold in a local variable lives instead in one
|
|
4
|
+
// shared item read and written through the same document client every
|
|
5
|
+
// corpus Query already uses: partition `_meta`, sort key `breaker#corpus`.
|
|
6
|
+
// A conditional write settles every race between concurrent invocations —
|
|
7
|
+
// whichever write lands first wins the state transition, and every loser's
|
|
8
|
+
// write fails its own condition and falls back to the same skip its read
|
|
9
|
+
// would have given it anyway.
|
|
10
|
+
//
|
|
11
|
+
// The machine has three states. Closed lets a turn retrieve; a systemic
|
|
12
|
+
// failure adds to a count inside a fixed window, and crossing a fixed
|
|
13
|
+
// threshold opens the breaker. Open skips retrieval outright until a fixed
|
|
14
|
+
// cooldown elapses, at which point exactly one turn — the winner of the
|
|
15
|
+
// closed-to-half-open race — runs a single bounded probe before every other
|
|
16
|
+
// turn resumes skipping. The probe's own outcome decides closed or open
|
|
17
|
+
// again.
|
|
18
|
+
//
|
|
19
|
+
// Every decision comes back as `{ mode, probe, report }`. `mode` is the same
|
|
20
|
+
// flag the retrieval layer's own honesty marker reads, imported rather than
|
|
21
|
+
// re-minted here so a breaker skip and a bandless skip read identically to
|
|
22
|
+
// an answer. `report(outcome)` is the one call a caller makes once retrieval
|
|
23
|
+
// (or the skip) is over; it is a no-op when `mode` was the skip mode, since
|
|
24
|
+
// there was nothing to report.
|
|
25
|
+
//
|
|
26
|
+
// The clock is injected (default `Date.now`) so window rollover, cooldown
|
|
27
|
+
// expiry and the conditional-write races are all reproducible without a
|
|
28
|
+
// real wall clock.
|
|
29
|
+
|
|
30
|
+
import { isSystemicFailure } from "./systemic-failure.mjs";
|
|
31
|
+
import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "../../domain/retrieval-modes.mjs";
|
|
32
|
+
|
|
33
|
+
const SDK_MODULE_SPECIFIER = "@aws-sdk/lib-dynamodb";
|
|
34
|
+
|
|
35
|
+
export const CORPUS_BREAKER_KIND = "tmct.dynamo-corpus-breaker@1";
|
|
36
|
+
export const CORPUS_BREAKER_PARTITION_KEY = "_meta";
|
|
37
|
+
export const CORPUS_BREAKER_SORT_KEY = "breaker#corpus";
|
|
38
|
+
|
|
39
|
+
export const CORPUS_BREAKER_DEFAULTS = Object.freeze({
|
|
40
|
+
failureThreshold: 5,
|
|
41
|
+
windowMs: 60_000,
|
|
42
|
+
cooldownMs: 60_000,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const DEFAULT_ATTRIBUTE_NAMES = Object.freeze({ pk: "pk", sk: "sk" });
|
|
46
|
+
|
|
47
|
+
const STATE_CLOSED = "closed";
|
|
48
|
+
const STATE_OPEN = "open";
|
|
49
|
+
const STATE_HALF_OPEN = "half-open";
|
|
50
|
+
|
|
51
|
+
let sdkPromise = null;
|
|
52
|
+
async function loadDynamoCommands() {
|
|
53
|
+
if (!sdkPromise) {
|
|
54
|
+
sdkPromise = import(SDK_MODULE_SPECIFIER).catch((cause) => {
|
|
55
|
+
sdkPromise = null;
|
|
56
|
+
throw new Error(`the corpus breaker needs "${SDK_MODULE_SPECIFIER}" (>=3) installed alongside tmct: ${cause.message}`, { cause });
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return sdkPromise;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isConditionalCheckFailure(error) {
|
|
63
|
+
return error?.name === "ConditionalCheckFailedException";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** How many systemic failures does this outcome carry? Accepts whatever
|
|
67
|
+
* shape a caller has to hand: a bare number, an aggregate retrieval
|
|
68
|
+
* metrics object (or `{ metrics }` wrapping one) carrying its own
|
|
69
|
+
* `systemicFailures` count, or a single raw error from one bounded probe
|
|
70
|
+
* read — classified with the retrieval layer's own rule so a query that
|
|
71
|
+
* merely returned nothing never counts against the breaker. */
|
|
72
|
+
export function failureCountFromOutcome(outcome) {
|
|
73
|
+
if (outcome == null) return 0;
|
|
74
|
+
if (typeof outcome === "number") return outcome;
|
|
75
|
+
if (typeof outcome.systemicFailures === "number") return outcome.systemicFailures;
|
|
76
|
+
if (outcome.metrics && typeof outcome.metrics.systemicFailures === "number") return outcome.metrics.systemicFailures;
|
|
77
|
+
if ("error" in outcome) return isSystemicFailure(outcome.error) ? 1 : 0;
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createDynamoCorpusBreaker({
|
|
82
|
+
client,
|
|
83
|
+
tableName,
|
|
84
|
+
clock = Date.now,
|
|
85
|
+
attributeNames = DEFAULT_ATTRIBUTE_NAMES,
|
|
86
|
+
failureThreshold = CORPUS_BREAKER_DEFAULTS.failureThreshold,
|
|
87
|
+
windowMs = CORPUS_BREAKER_DEFAULTS.windowMs,
|
|
88
|
+
cooldownMs = CORPUS_BREAKER_DEFAULTS.cooldownMs,
|
|
89
|
+
} = {}) {
|
|
90
|
+
if (!client) throw new TypeError("createDynamoCorpusBreaker needs a client (an @aws-sdk/lib-dynamodb DynamoDBDocumentClient)");
|
|
91
|
+
if (!tableName) throw new TypeError("createDynamoCorpusBreaker needs a tableName");
|
|
92
|
+
|
|
93
|
+
const names = { ...DEFAULT_ATTRIBUTE_NAMES, ...attributeNames };
|
|
94
|
+
const key = { [names.pk]: CORPUS_BREAKER_PARTITION_KEY, [names.sk]: CORPUS_BREAKER_SORT_KEY };
|
|
95
|
+
|
|
96
|
+
function stateFromItem(item) {
|
|
97
|
+
if (!item) return { state: STATE_CLOSED, failures: 0, windowStart: null, openedAt: null };
|
|
98
|
+
return {
|
|
99
|
+
state: item.state ?? STATE_CLOSED,
|
|
100
|
+
failures: typeof item.failures === "number" ? item.failures : 0,
|
|
101
|
+
windowStart: typeof item.windowStart === "number" ? item.windowStart : null,
|
|
102
|
+
openedAt: typeof item.openedAt === "number" ? item.openedAt : null,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The breaker's current state, read consistently. Exposed for narration
|
|
107
|
+
* and tests; deciding a turn's own retrieval plan goes through `decide`,
|
|
108
|
+
* never this alone, since a read with no accompanying write is not a
|
|
109
|
+
* transition. */
|
|
110
|
+
async function readState() {
|
|
111
|
+
const { GetCommand } = await loadDynamoCommands();
|
|
112
|
+
const result = await client.send(new GetCommand({ TableName: tableName, Key: key, ConsistentRead: true }));
|
|
113
|
+
return stateFromItem(result.Item);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const noopReport = async () => {};
|
|
117
|
+
|
|
118
|
+
/** Adds `failureCount` systemic failures to the current window, creating
|
|
119
|
+
* the item on its first failure ever. A window that has already aged out
|
|
120
|
+
* resets to this failure alone rather than adding to a stale total.
|
|
121
|
+
* Crossing the threshold opens the breaker; losing that race to another
|
|
122
|
+
* invocation is not an error, it is the point of the condition. */
|
|
123
|
+
async function recordSystemicFailure(failureCount) {
|
|
124
|
+
const { UpdateCommand } = await loadDynamoCommands();
|
|
125
|
+
const now = clock();
|
|
126
|
+
const windowFloor = now - windowMs;
|
|
127
|
+
let updatedFailures;
|
|
128
|
+
try {
|
|
129
|
+
const result = await client.send(new UpdateCommand({
|
|
130
|
+
TableName: tableName,
|
|
131
|
+
Key: key,
|
|
132
|
+
UpdateExpression: "SET windowStart = if_not_exists(windowStart, :now), #state = if_not_exists(#state, :closed) ADD failures :failureCount",
|
|
133
|
+
ConditionExpression: "attribute_not_exists(windowStart) OR windowStart > :windowFloor",
|
|
134
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
135
|
+
ExpressionAttributeValues: {
|
|
136
|
+
":now": now, ":closed": STATE_CLOSED, ":failureCount": failureCount, ":windowFloor": windowFloor,
|
|
137
|
+
},
|
|
138
|
+
ReturnValues: "UPDATED_NEW",
|
|
139
|
+
}));
|
|
140
|
+
updatedFailures = result.Attributes?.failures ?? failureCount;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (!isConditionalCheckFailure(error)) throw error;
|
|
143
|
+
const result = await client.send(new UpdateCommand({
|
|
144
|
+
TableName: tableName,
|
|
145
|
+
Key: key,
|
|
146
|
+
UpdateExpression: "SET failures = :failureCount, windowStart = :now",
|
|
147
|
+
ExpressionAttributeValues: { ":failureCount": failureCount, ":now": now },
|
|
148
|
+
ReturnValues: "UPDATED_NEW",
|
|
149
|
+
}));
|
|
150
|
+
updatedFailures = result.Attributes?.failures ?? failureCount;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (updatedFailures < failureThreshold) return;
|
|
154
|
+
try {
|
|
155
|
+
await client.send(new UpdateCommand({
|
|
156
|
+
TableName: tableName,
|
|
157
|
+
Key: key,
|
|
158
|
+
UpdateExpression: "SET #state = :open, openedAt = :now",
|
|
159
|
+
ConditionExpression: "#state = :closed",
|
|
160
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
161
|
+
ExpressionAttributeValues: { ":open": STATE_OPEN, ":closed": STATE_CLOSED, ":now": now },
|
|
162
|
+
}));
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (!isConditionalCheckFailure(error)) throw error;
|
|
165
|
+
// another invocation already opened it from the same window's count
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Settles the one probe a half-open breaker allows: success closes it and
|
|
170
|
+
* clears the failure count, a systemic failure reopens it with a fresh
|
|
171
|
+
* cooldown. The condition guards against a caller reporting the same
|
|
172
|
+
* probe twice; a second report finds the state already moved on and is
|
|
173
|
+
* ignored rather than thrown. */
|
|
174
|
+
async function resolveProbe(failed) {
|
|
175
|
+
const { UpdateCommand } = await loadDynamoCommands();
|
|
176
|
+
const now = clock();
|
|
177
|
+
const transition = failed
|
|
178
|
+
? {
|
|
179
|
+
UpdateExpression: "SET #state = :open, openedAt = :now",
|
|
180
|
+
ExpressionAttributeValues: { ":open": STATE_OPEN, ":halfOpen": STATE_HALF_OPEN, ":now": now },
|
|
181
|
+
}
|
|
182
|
+
: {
|
|
183
|
+
UpdateExpression: "SET #state = :closed, failures = :zero",
|
|
184
|
+
ExpressionAttributeValues: { ":closed": STATE_CLOSED, ":halfOpen": STATE_HALF_OPEN, ":zero": 0 },
|
|
185
|
+
};
|
|
186
|
+
try {
|
|
187
|
+
await client.send(new UpdateCommand({
|
|
188
|
+
TableName: tableName,
|
|
189
|
+
Key: key,
|
|
190
|
+
UpdateExpression: transition.UpdateExpression,
|
|
191
|
+
ConditionExpression: "#state = :halfOpen",
|
|
192
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
193
|
+
ExpressionAttributeValues: transition.ExpressionAttributeValues,
|
|
194
|
+
}));
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (!isConditionalCheckFailure(error)) throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The race an open breaker's cooldown resolves: every invocation past
|
|
201
|
+
* cooldown tries this same conditional write, keyed to the exact
|
|
202
|
+
* `openedAt` it read, and only the first one lands. Everyone else's
|
|
203
|
+
* condition fails — the state moved to half-open, or on to closed, or
|
|
204
|
+
* reopened under a newer `openedAt` — and they skip like any other
|
|
205
|
+
* reader of a breaker that is not closed. */
|
|
206
|
+
async function attemptHalfOpenTransition(openedAt) {
|
|
207
|
+
const { UpdateCommand } = await loadDynamoCommands();
|
|
208
|
+
try {
|
|
209
|
+
await client.send(new UpdateCommand({
|
|
210
|
+
TableName: tableName,
|
|
211
|
+
Key: key,
|
|
212
|
+
UpdateExpression: "SET #state = :halfOpen",
|
|
213
|
+
ConditionExpression: "#state = :open AND openedAt = :openedAt",
|
|
214
|
+
ExpressionAttributeNames: { "#state": "state" },
|
|
215
|
+
ExpressionAttributeValues: { ":halfOpen": STATE_HALF_OPEN, ":open": STATE_OPEN, ":openedAt": openedAt },
|
|
216
|
+
}));
|
|
217
|
+
return true;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (!isConditionalCheckFailure(error)) throw error;
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Decides this turn's retrieval plan and hands back the one call needed
|
|
225
|
+
* to close the loop afterward. `mode` is what the answer's retrieval
|
|
226
|
+
* payload carries; `probe` marks the single winning call that must bound
|
|
227
|
+
* itself to one read instead of the turn's usual plan. */
|
|
228
|
+
async function decide() {
|
|
229
|
+
const current = await readState();
|
|
230
|
+
|
|
231
|
+
if (current.state === STATE_CLOSED) {
|
|
232
|
+
return {
|
|
233
|
+
mode: SUPPLEMENTED_MODE,
|
|
234
|
+
probe: false,
|
|
235
|
+
report: async (outcome) => {
|
|
236
|
+
const failureCount = failureCountFromOutcome(outcome);
|
|
237
|
+
if (failureCount > 0) await recordSystemicFailure(failureCount);
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (current.state === STATE_OPEN) {
|
|
243
|
+
const now = clock();
|
|
244
|
+
if (current.openedAt == null || now - current.openedAt < cooldownMs) {
|
|
245
|
+
return { mode: SEED_SESSION_MODE, probe: false, report: noopReport };
|
|
246
|
+
}
|
|
247
|
+
const won = await attemptHalfOpenTransition(current.openedAt);
|
|
248
|
+
if (!won) return { mode: SEED_SESSION_MODE, probe: false, report: noopReport };
|
|
249
|
+
return {
|
|
250
|
+
mode: SUPPLEMENTED_MODE,
|
|
251
|
+
probe: true,
|
|
252
|
+
report: async (outcome) => { await resolveProbe(failureCountFromOutcome(outcome) > 0); },
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// half-open: every reader that did not itself win the transition above
|
|
257
|
+
// skips, including a fresh decide() call that finds it already half-open
|
|
258
|
+
return { mode: SEED_SESSION_MODE, probe: false, report: noopReport };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
kind: CORPUS_BREAKER_KIND,
|
|
263
|
+
decide,
|
|
264
|
+
readState,
|
|
265
|
+
};
|
|
266
|
+
}
|