local-label-queue / queue.mjs
WideChaos's picture
Publish Local Label Queue 0.1.0
d806877 verified
Raw History Blame Contribute Delete
13 kB
/* Full-inventory annotation state and portable, locally verified checkpoints. */
export const VERSION = "0.1.0";
export const STATUSES = Object.freeze(["unlabelled", "labelled", "abstained"]);
const FILTERS = ["all", ...STATUSES];
const verifiedCheckpoints = new WeakSet();
const whitespace =
/^[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/gu;
const trim = (text) => text.replace(whitespace, "");
const clone = (value) => JSON.parse(JSON.stringify(value));
function freeze(value) {
if (value && typeof value === "object") {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
function exactKeys(value, keys) {
return (
value &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value).length === keys.length &&
keys.every((k) => Object.hasOwn(value, k))
);
}
function scalar(text) {
for (const c of text) {
const n = c.codePointAt(0);
if (n >= 0xd800 && n <= 0xdfff) return false;
}
return true;
}
function validString(value, max) {
return (
typeof value === "string" &&
value.length <= max &&
scalar(value) &&
trim(value).length > 0
);
}
export function parseTaxonomy(raw) {
if (typeof raw !== "string") throw Error("Enter one label per line.");
return validateTaxonomy(raw.split("\n").map(trim).filter(Boolean));
}
function validateTaxonomy(labels) {
if (
!Array.isArray(labels) ||
labels.length < 2 ||
labels.length > 9 ||
labels.some((l) => !validString(l, 64) || trim(l) !== l) ||
new Set(labels).size !== labels.length
) {
throw Error(
"Use 2–9 distinct, trimmed Unicode labels, up to 64 UTF-16 units each.",
);
}
return labels.slice();
}
export function normalizeInventory(value) {
if (!exactKeys(value, ["taxonomy", "items"]))
throw Error("Inventory needs exactly taxonomy and items.");
const taxonomy = validateTaxonomy(value.taxonomy);
if (
!Array.isArray(value.items) ||
value.items.length < 1 ||
value.items.length > 1000
) {
throw Error("Use 1–1,000 inventory records.");
}
const ids = new Set();
const items = value.items.map((r, i) => {
if (
!exactKeys(r, ["id", "group", "text"]) ||
!validString(r.id, 128) ||
!(r.group === null || validString(r.group, 128)) ||
!validString(r.text, 16384)
) {
throw Error(
`Record ${i + 1} needs a valid id, group (string or null) and text.`,
);
}
if (ids.has(r.id)) throw Error(`Record ${i + 1} has a duplicate id.`);
ids.add(r.id);
return { id: r.id, group: r.group, text: r.text };
});
return { taxonomy, items };
}
export function parseSetup(raw, taxonomyText) {
if (
typeof raw !== "string" ||
raw.length > 1048576 ||
new TextEncoder().encode(raw).length > 1048576
) {
throw Error("Setup JSONL exceeds 1 MiB UTF-8.");
}
let lines = raw.split("\n");
if (raw.endsWith("\n")) lines.pop();
const items = [];
let blank = 0;
for (const [i, line] of lines.entries()) {
if (!trim(line)) {
blank++;
continue;
}
if (items.length >= 1000) throw Error("Setup exceeds 1,000 records.");
try {
items.push(JSON.parse(line));
} catch {
throw Error(`Invalid JSON on line ${i + 1}.`);
}
}
return {
inventory: normalizeInventory({
taxonomy: parseTaxonomy(taxonomyText),
items,
}),
blank_lines_ignored: blank,
};
}
export async function sha256(text) {
if (!globalThis.crypto?.subtle)
throw Error("Use HTTPS or localhost for checkpoint digests.");
const result = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(text),
);
return Array.from(new Uint8Array(result), (b) =>
b.toString(16).padStart(2, "0"),
).join("");
}
function validRevision(n) {
return Number.isInteger(n) && n >= 0 && n <= 1000000000;
}
function validateAnnotations(rows, inventory) {
if (!Array.isArray(rows) || rows.length !== inventory.items.length)
throw Error("Checkpoint must keep one annotation per inventory id.");
const known = new Set(inventory.items.map((r) => r.id)),
found = new Map();
for (const row of rows) {
if (
!exactKeys(row, ["id", "status", "label"]) ||
!known.has(row.id) ||
found.has(row.id) ||
!STATUSES.includes(row.status) ||
(row.status === "labelled"
? !inventory.taxonomy.includes(row.label)
: row.label !== null)
) {
throw Error(
"Checkpoint has a missing, duplicate, foreign or invalid annotation.",
);
}
found.set(row.id, { id: row.id, status: row.status, label: row.label });
}
return inventory.items.map((r) => found.get(r.id));
}
class Session {
#annotations;
#history = [];
#revision;
#savedRevision;
#filter;
#activeId;
constructor(
inventory,
digest,
annotations,
revision = 0,
savedRevision = null,
) {
Object.defineProperty(this, "inventory", {
value: freeze(clone(inventory)),
});
Object.defineProperty(this, "inventoryHash", { value: digest });
this.#annotations = new Map(annotations.map((a) => [a.id, { ...a }]));
this.#revision = revision;
this.#savedRevision = savedRevision;
this.#filter = "all";
this.#activeId =
inventory.items.find(
(r) => this.#annotations.get(r.id).status === "unlabelled",
)?.id ?? inventory.items[0].id;
}
get revision() {
return this.#revision;
}
get savedRevision() {
return this.#savedRevision;
}
get filter() {
return this.#filter;
}
get activeId() {
return this.#activeId;
}
annotation(id) {
const row = this.#annotations.get(id);
if (!row) throw Error("Unknown inventory id.");
return { ...row };
}
visibleIds() {
return this.inventory.items
.filter(
(r) =>
this.#filter === "all" ||
this.#annotations.get(r.id).status === this.#filter,
)
.map((r) => r.id);
}
setFilter(filter) {
if (!FILTERS.includes(filter)) throw Error("Unknown queue filter.");
this.#filter = filter;
if (!this.visibleIds().includes(this.#activeId))
this.#activeId = this.visibleIds()[0] ?? null;
}
select(id) {
if (!this.visibleIds().includes(id))
throw Error("Record is not visible under this filter.");
this.#activeId = id;
}
navigate(direction) {
if (direction !== 1 && direction !== -1)
throw Error("Use previous or next.");
const ids = this.visibleIds(),
index = ids.indexOf(this.#activeId);
if (!ids.length) {
this.#activeId = null;
return;
}
const next =
index < 0
? direction === 1
? 0
: ids.length - 1
: Math.max(0, Math.min(ids.length - 1, index + direction));
this.#activeId = ids[next];
}
#bump() {
if (this.#revision >= 1000000000)
throw Error(
"Revision limit reached. Export the current checkpoint; further decisions are blocked.",
);
this.#revision++;
}
decide(status, label = null, id = this.#activeId) {
if (!this.#annotations.has(id))
throw Error("Choose a current record first.");
if (
!STATUSES.includes(status) ||
(status === "labelled"
? !this.inventory.taxonomy.includes(label)
: label !== null)
)
throw Error("Invalid annotation decision.");
const prior = this.#annotations.get(id);
if (prior.status === status && prior.label === label) return false;
this.#bump();
this.#history.push({ ...prior });
if (this.#history.length > 20) this.#history.shift();
this.#annotations.set(id, { id, status, label });
this.#activeId = id;
if (status !== "unlabelled") {
const start = this.inventory.items.findIndex((r) => r.id === id);
let next = null;
for (let d = 1; d <= this.inventory.items.length; d++) {
const candidate =
this.inventory.items[(start + d) % this.inventory.items.length].id;
if (this.#annotations.get(candidate).status === "unlabelled") {
next = candidate;
break;
}
}
if (next !== null) {
if (!this.visibleIds().includes(next)) this.#filter = "all";
this.#activeId = next;
} else if (!this.visibleIds().includes(id)) this.#activeId = null;
} else if (!this.visibleIds().includes(id)) this.#activeId = null;
return true;
}
undo() {
if (!this.#history.length) return false;
this.#bump();
const prior = this.#history.pop();
this.#annotations.set(prior.id, prior);
this.#filter = "all";
this.#activeId = prior.id;
return true;
}
get undoCount() {
return this.#history.length;
}
get dirty() {
return this.#savedRevision !== this.#revision;
}
markDownloaded(revision) {
if (revision !== this.#revision) return false;
this.#savedRevision = revision;
return true;
}
summary() {
const counts = { unlabelled: 0, labelled: 0, abstained: 0 };
const labels = new Map(this.inventory.taxonomy.map((l) => [l, 0]));
for (const row of this.#annotations.values()) {
counts[row.status]++;
if (row.status === "labelled")
labels.set(row.label, labels.get(row.label) + 1);
}
const total = this.inventory.items.length;
return {
total,
...counts,
reviewed: counts.labelled + counts.abstained,
reviewed_fraction: (counts.labelled + counts.abstained) / total,
unknown_group_records: this.inventory.items.filter(
(r) => r.group === null,
).length,
labels: [...labels].map(([label, count]) => ({ label, count })),
};
}
payload() {
if (!validRevision(this.#revision)) throw Error("Invalid revision.");
return {
schema_version: 1,
tool_version: VERSION,
inventory: clone(this.inventory),
inventory_sha256: this.inventoryHash,
annotations: this.inventory.items.map((r) => this.annotation(r.id)),
revision: this.#revision,
};
}
annotationJSONL() {
return (
this.inventory.items
.map((r) =>
JSON.stringify({
...r,
status: this.annotation(r.id).status,
label: this.annotation(r.id).label,
}),
)
.join("\n") + "\n"
);
}
}
export async function createSession(inventory) {
const accepted = normalizeInventory(inventory);
const hash = await sha256(JSON.stringify(accepted));
return new Session(
accepted,
hash,
accepted.items.map((r) => ({
id: r.id,
status: "unlabelled",
label: null,
})),
);
}
export async function exportCheckpoint(session) {
const payload = session.payload(); // Capture the revision before the first await.
const contentHash = await sha256(JSON.stringify(payload));
return freeze({ ...payload, content_sha256: contentHash });
}
export async function readCheckpoint(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.byteLength > 4 * 1048576)
throw Error("Checkpoint must be UTF-8 and at most 4 MiB.");
let raw;
try {
raw = JSON.parse(
new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes),
);
} catch {
throw Error("Checkpoint is not valid UTF-8 JSON.");
}
if (
!exactKeys(raw, [
"schema_version",
"tool_version",
"inventory",
"inventory_sha256",
"annotations",
"revision",
"content_sha256",
]) ||
raw.schema_version !== 1 ||
raw.tool_version !== VERSION ||
!validRevision(raw.revision) ||
typeof raw.inventory_sha256 !== "string" ||
!/^[a-f0-9]{64}$/.test(raw.inventory_sha256) ||
typeof raw.content_sha256 !== "string" ||
!/^[a-f0-9]{64}$/.test(raw.content_sha256)
)
throw Error("Unsupported checkpoint schema, version or revision.");
const inventory = normalizeInventory(raw.inventory);
const annotations = validateAnnotations(raw.annotations, inventory);
if ((await sha256(JSON.stringify(inventory))) !== raw.inventory_sha256)
throw Error("Checkpoint inventory checksum does not match.");
const payload = {
schema_version: 1,
tool_version: VERSION,
inventory,
inventory_sha256: raw.inventory_sha256,
annotations,
revision: raw.revision,
};
if ((await sha256(JSON.stringify(payload))) !== raw.content_sha256)
throw Error("Checkpoint content checksum does not match.");
const accepted = freeze({ ...payload, content_sha256: raw.content_sha256 });
verifiedCheckpoints.add(accepted);
return accepted;
}
export function sessionFromCheckpoint(checkpoint) {
if (!verifiedCheckpoints.has(checkpoint))
throw Error("Verify the checkpoint bytes before restoring.");
return new Session(
checkpoint.inventory,
checkpoint.inventory_sha256,
checkpoint.annotations,
checkpoint.revision,
checkpoint.revision,
);
}