diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 4866cf98..2756a4f5 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -23,3 +23,8 @@ objc2 = "=0.6.4" objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSWindow", "NSWorkspace"] } objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSData", "NSDictionary", "NSString", "NSError", "NSException", "NSNotification", "NSOperation", "block2"] } objc2-web-kit = { version = "=0.3.2", default-features = false, features = ["std", "WKWebView", "WKSnapshotConfiguration", "block2"] } + +# Keep build-time macro metadata intact on macOS loaders affected by +# rust-lang/rust#157750. This profile override applies to host build dependencies. +[profile.release.build-override] +debug = true diff --git a/desktop/src/__tests__/hologram-label-placement.test.ts b/desktop/src/__tests__/hologram-label-placement.test.ts index 20838b9a..4fc91af4 100644 --- a/desktop/src/__tests__/hologram-label-placement.test.ts +++ b/desktop/src/__tests__/hologram-label-placement.test.ts @@ -9,7 +9,7 @@ import { parseKnowledgeGraph } from '../knowledge/graph-model'; // pipeline without a WebGL context, real accounts, or a physical window. type Box = { width: number; left: number; top: number; visible: boolean }; type Bounds = { left: number; top: number; right: number; bottom: number }; -type NodeSpec = { id: string; x?: number; y?: number; z?: number }; +type NodeSpec = { id: string; label?: string; x?: number; y?: number; z?: number }; type TestHologram = { render(dt: number): void; refreshOverviewLabels(): void; @@ -97,7 +97,7 @@ function setup( if (opts.zoom) { camera.position.z = 5 / opts.zoom; const zoomNodes = parseKnowledgeGraph({nodes:specs.map(node=>({id:node.id, - label:'실제 자료 ' + node.id, category:opts.globalIds?.includes(node.id)?'topic':'document'})),edges:[]}).nodes; + label:node.label ?? '실제 자료 ' + node.id, category:opts.globalIds?.includes(node.id)?'topic':'document'})),edges:[]}).nodes; // The real view and zoom candidates reference the same typed source nodes. Object.assign(fake, { view: { hops: 0, focusId: opts.focus ?? null, nodes: zoomNodes } }); Object.assign(fake, {desiredCamera:camera.position.clone(), labelFitDistance:5, @@ -112,6 +112,41 @@ function setup( } describe("overview labels in the native hologram projection loop", () => { + it('hides passive career subjects throughout the fitted and far overview', () => { + const specs = [ + { id: 'resume', label: '자소서', x: -.6 }, + { id: 'salary', label: '연봉·복리후생', x: 0 }, + { id: 'recruiting', label: '채용공고·지원시기', x: .6 }, + ]; + for (const zoom of [.3, .55, 1, 1.34, 1.47]) { + const r = setup(specs, { globalIds: specs.map(node => node.id), zoom, width: 1000, height: 600 }); + try { + expect(r.fake.labels.size, `passive labels at ${zoom}x`).toBe(0); + expect(r.accessible.querySelectorAll('button')).toHaveLength(3); + } finally { r.shell.remove(); } + } + }); + + it('reveals career subjects on zoom-in and removes them again on zoom-out', () => { + const specs = [ + { id: 'resume', label: '자소서', x: -.6 }, + { id: 'salary', label: '연봉·복리후생', x: 0 }, + { id: 'recruiting', label: '채용공고·지원시기', x: .6 }, + ]; + const r = setup(specs, { globalIds: specs.map(node => node.id), zoom: 1, width: 1000, height: 600 }); + try { + for (const zoom of [1.85, 1, .55, 2, .3]) { + Object.assign(r.fake, { desiredCamera: new THREE.Vector3(0, 0, 5 / zoom) }); + r.fake.render(1 / 60); + if (zoom > 1.5) { + expect([...r.fake.labels.values()].map(label => label.textContent).sort()).toEqual(specs.map(node => node.label).sort()); + expect([...r.fake.labels.values()].every(label => !label.hidden && Number(label.style.opacity) > 0)).toBe(true); + } else expect(r.fake.labels.size, `passive labels after returning to ${zoom}x`).toBe(0); + expect(r.accessible.querySelectorAll('button')).toHaveLength(3); + } + } finally { r.shell.remove(); } + }); + it('reveals saved titles only after zooming in, with readable topic hierarchy and bounded boxes', () => { const specs=Array.from({length:20},(_,i)=>({id:'n'+i,x:(i%5-2)*.25,y:(Math.floor(i/5)-1.5)*.25})); const topics=specs.slice(0,8).map(n=>n.id); diff --git a/desktop/src/__tests__/hologram-overlay-bounds.test.ts b/desktop/src/__tests__/hologram-overlay-bounds.test.ts new file mode 100644 index 00000000..b8f8533d --- /dev/null +++ b/desktop/src/__tests__/hologram-overlay-bounds.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { KnowledgeHologram } from '../knowledge/hologram'; +import { parseKnowledgeGraph } from '../knowledge/graph-model'; + +// Keep the real constructor/resize/overlay discovery path; no GPU claim. +vi.mock('three', async importOriginal => ({ + ...await importOriginal(), + WebGLRenderer: class { + setPixelRatio() {} setClearColor() {} setSize() {} setViewport() {} + getPixelRatio() { return 1; } dispose() {} render() {} + }, +})); + +type Bounds = { left: number; top: number; right: number; bottom: number }; +type OverlayGeometry = { + labelOverlays: HTMLElement[]; + excludedLabelBounds: Bounds[]; + resize(resetCamera?: boolean): void; +}; +const observed = new Set(); + +afterEach(() => { + document.body.replaceChildren(); + observed.clear(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('knowledge-map status caption exclusion', () => { + it('reserves the actual status HUD and refreshes its measured bounds on layout changes', () => { + vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)); + vi.stubGlobal('cancelAnimationFrame', vi.fn()); + vi.stubGlobal('ResizeObserver', class { + observe(element: Element) { observed.add(element); } + disconnect() {} unobserve() {} + }); + const workspace = document.createElement('section'); + workspace.className = 'knowledge-section'; + workspace.innerHTML = '
ALDEN / KNOWLEDGE COMMAND
'; + document.body.append(workspace); + const canvas = workspace.querySelector('canvas')!; + const shell = workspace.querySelector('.knowledge-hologram-shell')!; + const caption = workspace.querySelector('.knowledge-map-caption')!; + const rect = (left: number, top: number, width: number, height: number) => + ({ left, top, width, height, right: left + width, bottom: top + height, x: left, y: top, toJSON() {} }); + vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue(rect(144, 51, 495, 360)); + vi.spyOn(shell, 'getBoundingClientRect').mockReturnValue(rect(144, 51, 495, 360)); + const captionRect = vi.spyOn(caption, 'getBoundingClientRect').mockReturnValue(rect(154, 380, 304, 13)); + const hologram = new KnowledgeHologram(canvas, parseKnowledgeGraph({ nodes: [], edges: [] }), () => {}, undefined, 'workspace', null); + const geometry = hologram as unknown as OverlayGeometry; + try { + expect(geometry.labelOverlays).toContain(caption); + expect(observed).toContain(caption); + const index = geometry.labelOverlays.indexOf(caption); + expect(geometry.excludedLabelBounds[index]).toEqual({ left: 4, top: 323, right: 320, bottom: 348 }); + captionRect.mockReturnValue(rect(154, 360, 360, 26)); + geometry.resize(false); + expect(geometry.excludedLabelBounds[index]).toEqual({ left: 4, top: 303, right: 376, bottom: 341 }); + caption.hidden = true; + geometry.resize(false); + expect(geometry.excludedLabelBounds[index].right).toBe(geometry.excludedLabelBounds[index].left); + caption.hidden = false; + geometry.resize(false); + expect(geometry.excludedLabelBounds[index]).toEqual({ left: 4, top: 303, right: 376, bottom: 341 }); + } finally { hologram.dispose(); } + }); +}); diff --git a/desktop/src/knowledge/hologram.ts b/desktop/src/knowledge/hologram.ts index 99ed1393..f8dd2489 100644 --- a/desktop/src/knowledge/hologram.ts +++ b/desktop/src/knowledge/hologram.ts @@ -219,7 +219,7 @@ export class KnowledgeHologram { : new ResizeObserver(() => this.resize()); this.resizeObserver?.observe(canvas); const workspace = canvas.closest('.knowledge-section, .alden-panel'); - for (const selector of ['.knowledge-heading, .mini-graph-heading', '.knowledge-focus-card', '.knowledge-hologram-toolbar, .mini-graph-title', '.knowledge-depth-legend']) { + for (const selector of ['.knowledge-heading, .mini-graph-heading', '.knowledge-focus-card', '.knowledge-hologram-toolbar, .mini-graph-title', '.knowledge-depth-legend', '.knowledge-map-caption']) { const overlay = workspace?.querySelector(selector); if (overlay) { this.labelOverlays.push(overlay); this.excludedLabelBounds.push({left:0,top:0,right:0,bottom:0}); this.resizeObserver?.observe(overlay); } } diff --git a/docs/evaluation/annotation-review-publication-20261024.md b/docs/evaluation/annotation-review-publication-20261024.md new file mode 100644 index 00000000..132c42bd --- /dev/null +++ b/docs/evaluation/annotation-review-publication-20261024.md @@ -0,0 +1,88 @@ +# Annotation review publication ownership + +Base source: `3407c08e8e3bdf14b378735bb7048e4398dbaede`. + +Two candidate-review requests could both observe 15 fresh review JSON files, +pass the limit of 16, then publish distinct files. A regression through actual +`create_review` calls in two processes reproduced **17 files**. Atomic rename +published each file safely but did not serialize capacity admission. + +The candidate holds one nonblocking advisory lock across the existing capacity +check, expired-metadata handling, staging and rename. A contender returns the +internal `annotation_review_cache_busy` error; the quality action retains its +existing `quality_annotation_review_unavailable` response. Source verification +and candidate calculation remain outside this short ownership region. The +change does not alter source records, annotations, identity or merge policy. + +The private lock must be a regular, single-link, empty, owner-controlled 0600 +file. Symlinks, hardlinks, directories, nonempty files and shared permissions +are rejected. Its inode remains in place: deleting a lock pathname on release +could let later callers lock another inode while the first is still owned. +Closing its descriptor releases ownership, including after process exit. + +## State and property + +```mermaid +stateDiagram-v2 + [*] --> Prepared + Prepared --> Locked: acquire persistent inode + Prepared --> Busy: another owner + Locked --> Admitted: capacity available + Locked --> Rejected: fresh cache full + Admitted --> Staged: write and fsync metadata + Staged --> Published: atomic rename + Admitted --> Failed: write failure + Staged --> Failed: rename failure + Published --> Released: close descriptor + Rejected --> Released: close descriptor + Failed --> Released: clean staging and close + Locked --> Released: process exit + Busy --> [*] + Released --> [*] +``` + +Writing, fsync and rename are separate operations. The lock prevents another +cooperating publisher from interleaving admission and publication; it does not +turn the whole region into a filesystem transaction. + +| Claim | Evidence and limit | +| --- | --- | +| Starting within capacity, these publishers cannot increase review JSON count beyond the limit. | Actual two-process, 15-existing/cap16 regression; baseline and an unlocked writer both produce 17, guarded source stays at 16. | +| Failure does not permanently retain ownership. | Real process exit while holding the lock, and an injected rename failure, followed by successful normal publication. | +| Contention does not expose source content or damage prior reviews. | Existing public failure contract, original source DB byte comparison, retained existing JSON files and private metadata contract tests. | +| The description is sensitive to the guarded defect. | Disabling the guard in one real writer makes the regression fail; restoring it passes without changing source bytes. | + +A separate bounded interleaving check covered two actors, capacities 1–3 and +every initially valid count (nine cases), with publication, busy/full rejection, +write failure and owner exit. It found the unguarded counterexample and no +guarded capacity violation in those bounds. Both successful publications were +reachable when two slots were available. This is a model check plus real-code +regressions, not an all-input implementation proof. Liveness was not checked. + +Assumptions: publishers share this implementation and the same persistent lock +inode on a supported local filesystem. External folder/lock replacement, +legacy writers, power-loss durability, staging leftovers after a hard crash, +and total folder byte budgets are outside this count-only claim. An already +overfull legacy cache is rejected, not silently repaired or purged. Existing +expired-review handling is unchanged. + +## Verification and delivery boundary + +Related local checks: **114 tests**, comprising 14 annotation-candidate tests, +44 quality-action tests and 56 graph-quality tests, all passed on the pinned +CPython 3.11 runtime. Re-run the producer regressions with the project runtime: + +```sh +python3 -B -m unittest discover -s tests -p test_alden_annotation_candidates.py +``` + +Private baseline failures, mutation/restoration receipts, bounded-model output +and actual-store read-only audit evidence are retained under the task's +`outputs/quality-boundaries-20261024/`. Actual source content is not included in +this document or commit. + +This remains an uninstalled candidate. The original approved review packet +retains its exact bytes; a subsequent applicable source-delta review and +integration gate are still required. Local tests do not attest installation, +native UI, broader graph semantics, deduplication truth or completed external +cross-audit. diff --git a/docs/evaluation/numeric-digit-recall-20261024.md b/docs/evaluation/numeric-digit-recall-20261024.md new file mode 100644 index 00000000..090d877f --- /dev/null +++ b/docs/evaluation/numeric-digit-recall-20261024.md @@ -0,0 +1,33 @@ +# Bare digit recall in collection search and graph pages + +Base: `3407c08e8e3bdf14b378735bb7048e4398dbaede`. This source candidate fixes direct collection search and graph pages missing text such as `100개입니다` for the bare query `100`. Routed retrieval already had an additive digit-lexeme supplement; both paths now share that matcher. Original bodies, source records, IDs, memberships, versions, permissions, and FTS contents are preserved. + +The policy accepts only a bare string of 2–64 ASCII digits. It adds complete matching digit runs after existing FTS results. It does not convert numbers, signs, units, grouped/decimal notation, Unicode digits, or identifiers into equivalent quantities or entities. Existing FTS punctuation matches remain compatible: a query can still return a token from `100,000` or `100.5`. Neither those existing hits nor new lexical candidates establish a numerical claim's truth. Quoted and advanced FTS queries keep their existing behavior. The existing `expand_korean=False` switch disables the direct-search supplement too. + +## Selection and cost + +For direct search, existing FTS results fill the requested limit first. If they already fill it, no body supplement executes. Otherwise, the supplement supplies additional eligible records after token hits. Both stages run in one source-guarded reader transaction. + +For graph pages with offset O and limit L, the ordinary FTS page reads L+1 rows after O. If that page has a lookahead row, the supplement cannot affect its displayed rows or `next`: every FTS hit precedes every supplement hit. If no lookahead exists, a second selection includes the supplement. An exactly full displayed page without lookahead must still check the supplement; a regression covers that boundary. Each selection retains the same permitted/current membership, target/platform/type/relation/time filters and relationship integrity checks. + +An initial candidate always scanned retained bodies. A subsequent SQL count gate still incurred unnecessary candidate materialization. The final candidate keeps the ordinary FTS graph SQL path when its lookahead suffices. The shared final SQL trace matched the baseline in the measured full-prefix graph case. Sparse searches can still require two graph-scope selections and a retained-text scan. This adds no numeric index or schema migration and is not an unbounded scaling claim. Display limits do not bound the amount of text a fallback might inspect. + +## Verification + +- Three new behavioral regressions failed on the base source before the fix. +- Four focused tests cover suffix/embedded digit recall, existing FTS ordering, quote/opt-out compatibility, pagination/lookahead, larger/grouped/decimal/Unicode runs, later occurrences, permitted current membership, time filters and byte/ID/version/FTS-count preservation. The previous Korean-only negative expectation was explicitly updated for the new integer supplement; one-character, Latin and oversized queries retain their negative checks. +- Final related Python checks: **313 tests in 10 fresh pinned-runtime processes**, all passed. This includes collection, retrieval, graph references, messenger access/context, quality, entity projection and content-evidence checks. +- Two actual retained-DB query cases used one normal read-only transaction per baseline/candidate pair. Source hashes were stable during each measurement. Existing selected IDs were retained, membership snapshot hashes matched, SQLite total_changes was 0, and no write was attempted. These cases exercised a full FTS prefix and a missing-number fallback; neither demonstrated additional matches in that live corpus. Positive recall improvement is demonstrated by the isolated regressions. +- These are source/SQLite observations. No new installed runtime, native search interaction, ingestion event, semantic gold, CPU/GPU/battery improvement distribution, or external model audit is attested. + +Rerun the focused contract from the checkout with the pinned Python: + +```sh +"/Users/twoimo/Library/Application Support/openkakao/runtimes/menubar/bin/python3.11" -B -m unittest discover -s tests -p test_alden_korean_search.py +``` + +Private detailed measurements and failure receipts remain under the task's `outputs/numeric-recall-20261024/`; they are not included in the product source commit. + +## Integration boundary + +This candidate is separate from the frozen installed-runtime-to-3407c08 review packet. That packet and its two already approved files retain their original bytes. Current-source external thesis/adversarial/reverse review and installation verification remain incomplete. This follow-up must be included in the applicable subsequent source review and integration checks; the original packet's review cannot certify it by implication. Full ST15 numeric value/unit semantics, independent gold, direct installed search and the remaining Alden requirements stay open. diff --git a/docs/evaluation/realtime-scan-coverage-20261024.md b/docs/evaluation/realtime-scan-coverage-20261024.md new file mode 100644 index 00000000..04daaf1d --- /dev/null +++ b/docs/evaluation/realtime-scan-coverage-20261024.md @@ -0,0 +1,75 @@ +# Realtime target coverage beyond the first 200 + +The input watcher repeatedly selected the first 200 eligible target IDs. With 201 +permitted, enabled targets, the last target was never observed by this watcher, +even after its source changed. Its ordinary collection schedule could still run; +this defect concerns input-triggered collection, not all collection. + +`RealtimeCollection.scan` now walks keyset pages of 200 IDs, committing each page +before continuing. It releases the collection-store read before inspecting files +or writing observation hints. The page size limits temporary ID storage rather +than the supported target set. Existing debounce, coalescing, acknowledgement, +permission, pause, and scheduler publication rules remain in place. A changed +live-policy revision stops traversal before the next page. + +```mermaid +stateDiagram-v2 + [*] --> Unseen + Unseen --> Settling: permitted input observed + Settling --> Settling: signature changes + Settling --> Queued: same signature after settle interval + Queued --> Queued: duplicate observation + Queued --> Processed: scheduler publishes and acknowledges current signature + Processed --> Settling: source signature changes + Settling --> InputError: missing or unsafe input + Queued --> InputError: missing or unsafe input + InputError --> Settling: valid input observed again +``` + +This diagram describes existing observation states, not an implementation proof. +For a fixed eligible registry, the cursor advances past a page only after that +page's observation transaction commits. A later failure leaves earlier pages +durable and the next watch tick starts again from the beginning. Registration or +permission changes during traversal do not have a single snapshot guarantee; +later ticks reconcile them. Scheduler publication gates remain authoritative. + +For N eligible targets, a complete unchanged-registry, unchanged-policy pass has N +eligible ID visits (paused inputs may be skipped) and `ceil(N/200) + 1` page queries, +including the terminal empty query. Each observed target +also performs its existing target lookup, permission lookup, file metadata checks, +and realtime-state lookup/update. At most 200 IDs are held in the scan's page list. +This is not an O(200) memory claim for the entire watcher: `pending()` and scheduler +candidate collections still grow with their respective target sets. There is no +fixed elapsed-time or arbitrarily large-scale realtime guarantee. No production +speedup, FPS, RAM, or battery improvement is claimed. + +Validation uses isolated real SQLite stores and files with a fake dense index: + +- 401 eligible targets span three nonempty pages. The last target publishes its + first version, detects another source change, publishes a second version, then + remains acknowledged without requeue. Other pending hints and all intervals are + preserved. +- A 203-target fixture excludes disabled, denied, and paused targets, including + traversal beyond the first page. +- A controlled policy-revision response stops before page two; a subsequent + normal pass resumes and settles all 201 inputs. This policy-boundary test is + synthetic, not a concurrent OS-policy proof. +- The realtime collection, watch-state, and scheduler suites pass 46 tests. +- The final 401-target regression run with the exact installed scanner method + fails with `200 != 401`. This negative control uses isolated candidate fixture + dependencies; it does not execute a production collector or alter installed + bytes. + +The actual installed app has 43 declared/eligible targets. A read-only observation +found 43 realtime inputs, no input errors or queued hints, and a fresh heartbeat +from its existing collection process. Its separate OSK producer checkpoint was +older, with `collection=pending` and `saved_corpus_ready=false`; the primary GUI +process was not running. The source shows OSK synchronization belongs to the +desktop process, while the launch agent owns collection watching. This separates +the two observations; it neither proves why the GUI exited nor identifies this +200-target defect as the cause of that stale checkpoint. + +This is an uninstalled candidate on frozen source +`3407c08e8e3bdf14b378735bb7048e4398dbaede`. Current-source external review, +integration with the other candidates, canonical build/sign/install, native +background QA, and production-source observation remain separate delivery gates. diff --git a/docs/evaluation/runtime-integration-20261024.md b/docs/evaluation/runtime-integration-20261024.md new file mode 100644 index 00000000..f9eb945b --- /dev/null +++ b/docs/evaluation/runtime-integration-20261024.md @@ -0,0 +1,37 @@ +# Runtime integration candidate + +This branch combines the exact changes from draft PRs 33, 34, and 35 on frozen +`3407c08e8e3bdf14b378735bb7048e4398dbaede`: bare-digit lexical recall, serialized +annotation-review publication, and realtime target traversal past 200 inputs. +The original approved review-plan/source bundle remains immutable; this branch +needs its own delta review and installation evidence. + +The renderer already suppresses passive topic, title, and saved-list captions at +the fitted overview. Two additional render-path tests now pin the reported +career labels: no passive labels from 0.3x through 1.47x, visible labels at 1.85x +and 2x, then no lingering labels on returning to 1x or farther. Keyboard entries +remain present. These tests use synthetic geometry and the real renderer methods, +not a native screenshot or installed-app acceptance. Explicit selection/hover +retains its separate reading behavior. Source changes are not installation proof. + +Building the integrated source exposed a macOS loader failure in release +build-time macro libraries. A cloned library failed with a misaligned LINKEDIT +string table; a fresh target reproduced the failure, so this is not attributed +solely to stale/corrupt cache bytes. The actual dependency graph built with +`profile.release.build-override.debug=true` succeeded. Its newly built +`zerofrom_derive` library loaded, with an 8-byte-aligned string-table offset; the +default-profile library remained rejected with offset modulo 8 equal to 4. + +The Tauri manifest records that build-only override so the canonical build's +input digest includes it. No global Rust configuration, compiler pin, permissions, +model, or installed app is changed. The smaller isolated macro fixture passed +under both profiles; it is explicitly not the failure reproducer. These local +observations are consistent with the [upstream Rust loader defect](https://github.com/rust-lang/rust/issues/157750). +Cargo documents the scope of [build-dependency profile overrides](https://doc.rust-lang.org/cargo/reference/profiles.html#build-dependencies). +This does not establish a universal compiler fix or a runtime performance gain. + +Canonical build receipt/signature/resource verification, background native QA, +current-source external review, installation, and production observation remain +distinct gates. Test and build receipts live in the task's private +`outputs/runtime-integration-20261024/` directory. Nothing here certifies the full +Alden objective, messenger ingestion coverage, semantic gold, or normal release. diff --git a/scripts/alden_annotation_candidates.py b/scripts/alden_annotation_candidates.py index 4b0d4a5c..73b49f0b 100644 --- a/scripts/alden_annotation_candidates.py +++ b/scripts/alden_annotation_candidates.py @@ -1,4 +1,6 @@ """Bounded retained-tag candidate pages; never a tag verdict or merge command.""" +from contextlib import contextmanager +import fcntl import hashlib import math import os @@ -77,6 +79,28 @@ def _load(folder, review_id): return value +@contextmanager +def _publication_lock(folder): + """Keep capacity admission and publication under one cross-process owner.""" + directory=os.open(folder,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW) + fd=None + try: + fd=os.open('.publication.lock',os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW|os.O_NONBLOCK, + 0o600,dir_fd=directory) + meta=os.fstat(fd) + if (not stat.S_ISREG(meta.st_mode) or meta.st_uid!=os.geteuid() + or stat.S_IMODE(meta.st_mode)!=0o600 or meta.st_nlink!=1 or meta.st_size!=0): + raise ValueError('annotation_review_cache_invalid') + try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError:raise ValueError('annotation_review_cache_busy') from None + yield + finally: + # Keep the inode: unlinking it could give another publisher a different + # lock while an existing owner still holds the original descriptor. + if fd is not None:os.close(fd) + os.close(directory) + + def create_review(state_root, scope_dict, report): scope=_scope(scope_dict);store=CollectionStore.open_existing(Path(state_root)) if store is None:raise ValueError('annotation_review_scope_unavailable') @@ -119,20 +143,21 @@ def create_review(state_root, scope_dict, report): raw=encoded(value) if len(raw)>MAX_CACHE_BYTES:raise ValueError('annotation_review_cache_budget') folder=_folder(store,True) - files=list(folder.glob('*.json')) - if len(files)>=MAX_CACHE_FILES: - # Only exact-hash, expired generated metadata can be reclaimed here. - for path in files: - try:_load(folder,path.stem) - except ValueError as error: - if str(error)=='annotation_review_expired':path.unlink() - if len(list(folder.glob('*.json')))>=MAX_CACHE_FILES:raise ValueError('annotation_review_cache_budget') - review_id=digest(raw);fd,temp=tempfile.mkstemp(prefix='.review-',dir=folder) - try: - with os.fdopen(fd,'wb') as f:os.fchmod(f.fileno(),0o600);f.write(raw);f.flush();os.fsync(f.fileno()) - os.replace(temp,folder/(review_id+'.json')) - finally: - if os.path.exists(temp):os.unlink(temp) + with _publication_lock(folder): + files=list(folder.glob('*.json')) + if len(files)>=MAX_CACHE_FILES: + # Only exact-hash, expired generated metadata can be reclaimed here. + for path in files: + try:_load(folder,path.stem) + except ValueError as error: + if str(error)=='annotation_review_expired':path.unlink() + if len(list(folder.glob('*.json')))>=MAX_CACHE_FILES:raise ValueError('annotation_review_cache_budget') + review_id=digest(raw);fd,temp=tempfile.mkstemp(prefix='.review-',dir=folder) + try: + with os.fdopen(fd,'wb') as f:os.fchmod(f.fileno(),0o600);f.write(raw);f.flush();os.fsync(f.fileno()) + os.replace(temp,folder/(review_id+'.json')) + finally: + if os.path.exists(temp):os.unlink(temp) return review_id diff --git a/scripts/alden_collection.py b/scripts/alden_collection.py index 3e132001..1413e84c 100644 --- a/scripts/alden_collection.py +++ b/scripts/alden_collection.py @@ -191,6 +191,24 @@ def normalized_body(value: str) -> str: return unicodedata.normalize("NFC", value).replace("\r\n", "\n").replace("\r", "\n") +_INTEGER_DIGIT_LEXEME = re.compile(r'\d+(?:[.,]+\d+)*') + + +def integer_digit_query(query): + """Bare ASCII digit query only; preserve advanced FTS and formatted values.""" + if not isinstance(query, str): + return None + value = query.strip() + return value if re.fullmatch(r'[0-9]{2,64}', value) else None + + +def integer_digit_matches(label, body, term): + # This is additive lexical recall, not quantity or identifier equivalence. + # Keep grouped/decimal/Unicode runs opaque, exactly as routed retrieval does. + return any(match.group() == term for field in (label, body) + for match in _INTEGER_DIGIT_LEXEME.finditer(field)) + + def korean_literal_plan(query): """Positive literal AND/OR only; advanced FTS keeps its original meaning.""" if not isinstance(query, str) or len(query) > 1024: @@ -1143,11 +1161,30 @@ def search(self, query: str, *, projects: list[str], limit=10, time_from=None, t if value is not None: clauses.append('v.collected_at' + operator + '?');values.append(value) plan = korean_literal_plan(query) if expand_korean else None - if plan: - contains, params = korean_literal_sql(plan) - db.create_function('alden_korean_literal',3, - lambda label,body,word:int(korean_literal_matches(((word,),),label,body)),deterministic=True) - strict, strict_params = korean_literal_sql(plan,'s.label','s.body',numeric_boundaries=True) + integer_term = integer_digit_query(query) if expand_korean else None + token_sql = """WITH search_candidates AS MATERIALIZED ( + SELECT document_id FROM version_search WHERE version_search MATCH ?) + SELECT d.id,v.label,v.body,v.metadata,bm25(version_search) AS rank + FROM version_search JOIN documents d ON d.id=version_search.document_id + JOIN (""" + self._scope_versions(projects, candidates=True) + """) s ON s.document_id=d.id + AND s.current_version=version_search.version_id JOIN versions v ON v.id=s.current_version + WHERE version_search MATCH ? AND d.availability='available' """ + ''.join(' AND ' + c for c in clauses) + ' ORDER BY rank,d.id LIMIT ?' + token_values = (query, *projects, query, *values, limit) + # Token hits always precede the supplement. A complete requested + # result cannot gain anything from scanning retained bodies again. + rows = db.execute(token_sql, token_values).fetchall() if integer_term else None + numeric_full = rows is not None and limit > 0 and len(rows) >= limit + if (plan or integer_term) and not numeric_full: + if integer_term: + contains, params = '(instr(v.label,?)>0 OR instr(v.body,?)>0)', (integer_term, integer_term) + db.create_function('alden_integer_digit', 3, + lambda label,body,word:int(integer_digit_matches(label,body,word)), deterministic=True) + strict, strict_params = 'alden_integer_digit(s.label,s.body,?)=1', (integer_term,) + else: + contains, params = korean_literal_sql(plan) + db.create_function('alden_korean_literal',3, + lambda label,body,word:int(korean_literal_matches(((word,),),label,body)),deterministic=True) + strict, strict_params = korean_literal_sql(plan,'s.label','s.body',numeric_boundaries=True) sql = """WITH search_candidates AS MATERIALIZED ( SELECT document_id FROM version_search WHERE version_search MATCH ? UNION SELECT v.document_id FROM versions v WHERE """ + contains + """), @@ -1165,15 +1202,8 @@ def search(self, query: str, *, projects: list[str], limit=10, time_from=None, t SELECT s.id,s.label,s.body,s.metadata,m.rank FROM matches m JOIN scoped s ON s.id=m.id ORDER BY m.priority,m.rank,m.id LIMIT ?""" rows = db.execute(sql, (query, *params, *projects, *values, query, *strict_params, limit)).fetchall() - else: - rows = db.execute("""WITH search_candidates AS MATERIALIZED ( - SELECT document_id FROM version_search WHERE version_search MATCH ?) - SELECT d.id,v.label,v.body,v.metadata,bm25(version_search) AS rank - FROM version_search JOIN documents d ON d.id=version_search.document_id - JOIN (""" + self._scope_versions(projects, candidates=True) + """) s ON s.document_id=d.id - AND s.current_version=version_search.version_id JOIN versions v ON v.id=s.current_version - WHERE version_search MATCH ? AND d.availability='available' """ + ''.join(' AND ' + c for c in clauses) + ' ORDER BY rank,d.id LIMIT ?', - (query, *projects, query, *values, limit)).fetchall() + elif rows is None: + rows = db.execute(token_sql, token_values).fetchall() results = [] for row in rows: metadata = json.loads(row['metadata']) @@ -1344,10 +1374,12 @@ def incident_scope(current_ids): # All overview outputs share one materialized permitted scope. # LIMIT+1 remains inside SQL, including FTS pages. plan = korean_literal_plan(query) + integer_term = integer_digit_query(query) fts = (' OR '.join(' AND '.join('"' + word + '"' for word in clause) for clause in plan) if plan else ' AND '.join('"' + term.replace('"', '""') + '"' for term in query.split())) picking = ("SELECT s.id FROM version_search JOIN shown s ON s.visible_version=version_search.version_id WHERE version_search MATCH ? ORDER BY bm25(version_search),s.id" if fts else "SELECT s.id FROM shown s LEFT JOIN degrees d ON d.id=s.id ORDER BY COALESCE(d.degree,0) DESC,s.id") + token_picking = picking if overview and not fts: # Interleave real source targets so a large project's hubs # cannot occupy the whole unified overview. No fake links. @@ -1361,11 +1393,18 @@ def incident_scope(current_ids): WHERE alden_sample_rank(v.label, v.body, json_extract(v.metadata,'$.kind')) < 3) WHERE label_copy=1 ORDER BY source_slot,id""" search_cte = cte - if plan: - contains, params = korean_literal_sql(plan) - db.create_function('alden_korean_literal',3, - lambda label,body,word:int(korean_literal_matches(((word,),),label,body)),deterministic=True) - strict, strict_params = korean_literal_sql(plan,numeric_boundaries=True) + if plan or integer_term: + if integer_term: + contains = '(instr(v.label,?)>0 OR instr(v.body,?)>0)' + params = (integer_term, integer_term) + db.create_function('alden_integer_digit', 3, + lambda label,body,word:int(integer_digit_matches(label,body,word)), deterministic=True) + strict, strict_params = 'alden_integer_digit(v.label,v.body,?)=1', (integer_term,) + else: + contains, params = korean_literal_sql(plan) + db.create_function('alden_korean_literal',3, + lambda label,body,word:int(korean_literal_matches(((word,),),label,body)),deterministic=True) + strict, strict_params = korean_literal_sql(plan,numeric_boundaries=True) search_cte += """,token_matches AS MATERIALIZED ( SELECT s.id,bm25(version_search) AS rank FROM version_search JOIN shown s ON s.visible_version=version_search.version_id WHERE version_search MATCH ?), @@ -1376,20 +1415,28 @@ def incident_scope(current_ids): pick_args = [fts, *params, *strict_params, limit+1, offset, limit] else: pick_args = [fts, limit+1, offset, limit] if fts else [limit+1, offset, limit] - overview = search_cte + ",picked AS MATERIALIZED (" + picking + " LIMIT ? OFFSET ?),selected AS MATERIALIZED (SELECT id FROM picked LIMIT ?) " - nodes_json, edges_json, total, total_edges, more, kinds, types, invalid_relations = db.execute(overview + """SELECT - (SELECT json_group_array(json(item)) FROM (SELECT """ + json_node + """ AS item - FROM selected p JOIN shown s ON s.id=p.id JOIN versions v ON v.id=s.visible_version - LEFT JOIN degrees d ON d.id=s.id ORDER BY s.id)), - (SELECT json_group_array(json(item)) FROM (SELECT json_object('id',r.id,'source',r.source,'target',r.target,'type',r.type) AS item - FROM permitted_edges r JOIN selected a ON a.id=r.source JOIN selected b ON b.id=r.target ORDER BY r.id LIMIT """ + ("4096" if overview else "512") + """)), - (SELECT COUNT(*) FROM shown),(SELECT COUNT(*) FROM permitted_edges),(SELECT COUNT(*) FROM picked)>?, - (SELECT json_group_array(kind) FROM (SELECT DISTINCT json_extract(v.metadata,'$.kind') AS kind FROM ranked s - JOIN versions v ON v.id=s.current_version JOIN documents d ON d.id=s.document_id - WHERE s.choice=1 AND d.availability='available' AND kind IS NOT NULL ORDER BY kind LIMIT 128)), - (SELECT json_group_array(type) FROM (SELECT DISTINCT type FROM permitted_relationships ORDER BY type LIMIT 128)), - (SELECT COUNT(*) FROM permitted_relationships WHERE history_bound!=1)""", (*args, *pick_args, limit)).fetchone() - if invalid_relations: raise RuntimeError('collection_relation_integrity') + selections = [(search_cte, picking, pick_args)] + if integer_term: + # A full token page plus lookahead is already final. Keep + # its ordinary SQL path rather than materializing every + # token/body candidate just to discard the supplement. + selections.insert(0, (cte, token_picking, [fts, limit+1, offset, limit])) + for selection_cte, selection, selection_args in selections: + overview = selection_cte + ",picked AS MATERIALIZED (" + selection + " LIMIT ? OFFSET ?),selected AS MATERIALIZED (SELECT id FROM picked LIMIT ?) " + nodes_json, edges_json, total, total_edges, more, kinds, types, invalid_relations = db.execute(overview + """SELECT + (SELECT json_group_array(json(item)) FROM (SELECT """ + json_node + """ AS item + FROM selected p JOIN shown s ON s.id=p.id JOIN versions v ON v.id=s.visible_version + LEFT JOIN degrees d ON d.id=s.id ORDER BY s.id)), + (SELECT json_group_array(json(item)) FROM (SELECT json_object('id',r.id,'source',r.source,'target',r.target,'type',r.type) AS item + FROM permitted_edges r JOIN selected a ON a.id=r.source JOIN selected b ON b.id=r.target ORDER BY r.id LIMIT """ + ("4096" if overview else "512") + """)), + (SELECT COUNT(*) FROM shown),(SELECT COUNT(*) FROM permitted_edges),(SELECT COUNT(*) FROM picked)>?, + (SELECT json_group_array(kind) FROM (SELECT DISTINCT json_extract(v.metadata,'$.kind') AS kind FROM ranked s + JOIN versions v ON v.id=s.current_version JOIN documents d ON d.id=s.document_id + WHERE s.choice=1 AND d.availability='available' AND kind IS NOT NULL ORDER BY kind LIMIT 128)), + (SELECT json_group_array(type) FROM (SELECT DISTINCT type FROM permitted_relationships ORDER BY type LIMIT 128)), + (SELECT COUNT(*) FROM permitted_relationships WHERE history_bound!=1)""", (*args, *selection_args, limit)).fetchone() + if invalid_relations: raise RuntimeError('collection_relation_integrity') + if more: break rows = json.loads(nodes_json) # JSON1 already validates and constructs the same edge JSON. # An affinity caller needs its selected refs, not thousands of diff --git a/scripts/alden_collection_retrieval.py b/scripts/alden_collection_retrieval.py index 7a1d8bf5..d7d6c3a2 100644 --- a/scripts/alden_collection_retrieval.py +++ b/scripts/alden_collection_retrieval.py @@ -9,6 +9,7 @@ import unicodedata from alden_collection import CollectionStore, MAX_RECORD_BYTES, digest, encoded, identity, safe_directory, require_relation_binding, require_collection_source_root, korean_literal_plan, korean_literal_matches, korean_literal_sql +from alden_collection import integer_digit_query as _integer_digit_query, integer_digit_matches as _integer_digit_matches from alden_content_evidence import POLICY as CONTENT_POLICY, content_evidence_class, declared_source_annotations, ANNOTATION_FIELDS from alden_source_text import TEXT_VERSION, project_source_text @@ -21,20 +22,6 @@ CONTEXT_TEXT_POLICY = 'retained-threads-annotation-context-v2' CONVERSATION_CONTEXT_POLICY = 'current-source-excerpt-v1' MAX_CONTEXT_ANCHORS = 2 -_DIGIT_LEXEME = re.compile(r'\d+(?:[.,]+\d+)*') - - -def _integer_digit_query(query): - value=query.strip() - return value if re.fullmatch(r'[0-9]{2,64}',value) else None - - -def _integer_digit_matches(label, body, term): - # Supplement literal digit runs only. No int/float, sign, unit, grouping or - # Unicode value conversion; a formatted numeric run stays one opaque token. - return any(match.group()==term for field in (label,body) for match in _DIGIT_LEXEME.finditer(field)) - - def _verified_conversation_excerpt(proof, value): """Validate a trusted source owner's bounded response against the selected fact.""" if not isinstance(value, dict): diff --git a/scripts/alden_realtime_collection.py b/scripts/alden_realtime_collection.py index ad5cf0a1..402c9c7e 100644 --- a/scripts/alden_realtime_collection.py +++ b/scripts/alden_realtime_collection.py @@ -100,27 +100,34 @@ def signature(target): return hashlib.sha256(json.dumps([str(path), stamps], separators=(',', ':')).encode()).hexdigest() def scan(self, store, *, paused=lambda _id: False, now=None): - if not self.policy()['enabled']: return 0 + policy = self.policy() + if not policy['enabled']: return 0 now = time.time() if now is None else now - with store.database() as source: - ids = [r[0] for r in source.execute('''SELECT t.id FROM targets t WHERE t.enabled=1 AND - EXISTS(SELECT 1 FROM target_projects p WHERE p.target_id=t.id AND p.permission!='denied') ORDER BY t.id LIMIT 200''')] - with self.database(write=True) as db: - for target_id in ids: - if paused(target_id): continue - try: signature, error = self.signature(store.target(target_id)), None - except (OSError, KeyError, ValueError) as exc: - signature, error = None, str(exc) if str(exc).startswith('collection_realtime_') else 'collection_realtime_input_unavailable' - row = db.execute('SELECT * FROM inputs WHERE target_id=?', (target_id,)).fetchone() - if row is None: - db.execute('INSERT INTO inputs VALUES(?,?,?,NULL,NULL,NULL,NULL,?)', (target_id, signature, now, error)) - elif error: - if row['error'] != error: db.execute('UPDATE inputs SET error=? WHERE target_id=?', (error, target_id)) - elif row['seen'] != signature or row['error']: - db.execute('UPDATE inputs SET seen=?,stable_since=?,error=NULL WHERE target_id=?', (signature, now, target_id)) - elif now - row['stable_since'] >= SETTLE_SECONDS and signature != row['processed'] and signature != row['queued']: - db.execute('UPDATE inputs SET queued=?,queued_at=COALESCE(queued_at,?) WHERE target_id=?', (signature, now, target_id)) - return len(ids) + after, scanned = '', 0 + while True: + # The page size bounds temporary IDs, not the supported target set. + # Release the source read before observing files or writing hints. + with store.database() as source: + ids = [r[0] for r in source.execute('''SELECT t.id FROM targets t WHERE t.id>? AND t.enabled=1 AND + EXISTS(SELECT 1 FROM target_projects p WHERE p.target_id=t.id AND p.permission!='denied') + ORDER BY t.id LIMIT 200''', (after,))] + if not ids or self.policy() != policy: return scanned + with self.database(write=True) as db: + for target_id in ids: + if paused(target_id): continue + try: signature, error = self.signature(store.target(target_id)), None + except (OSError, KeyError, ValueError) as exc: + signature, error = None, str(exc) if str(exc).startswith('collection_realtime_') else 'collection_realtime_input_unavailable' + row = db.execute('SELECT * FROM inputs WHERE target_id=?', (target_id,)).fetchone() + if row is None: + db.execute('INSERT INTO inputs VALUES(?,?,?,NULL,NULL,NULL,NULL,?)', (target_id, signature, now, error)) + elif error: + if row['error'] != error: db.execute('UPDATE inputs SET error=? WHERE target_id=?', (error, target_id)) + elif row['seen'] != signature or row['error']: + db.execute('UPDATE inputs SET seen=?,stable_since=?,error=NULL WHERE target_id=?', (signature, now, target_id)) + elif now - row['stable_since'] >= SETTLE_SECONDS and signature != row['processed'] and signature != row['queued']: + db.execute('UPDATE inputs SET queued=?,queued_at=COALESCE(queued_at,?) WHERE target_id=?', (signature, now, target_id)) + after, scanned = ids[-1], scanned + len(ids) def pending(self): if not self.policy()['enabled']: return {} diff --git a/tests/test_alden_annotation_candidates.py b/tests/test_alden_annotation_candidates.py index 583a61e3..d2877d2d 100644 --- a/tests/test_alden_annotation_candidates.py +++ b/tests/test_alden_annotation_candidates.py @@ -10,8 +10,10 @@ from pathlib import Path import shutil import stat +import subprocess import sys from tempfile import TemporaryDirectory +import threading import time import unittest from unittest.mock import patch @@ -21,6 +23,7 @@ from alden_collection import CollectionStore, digest, identity from alden_graph_quality import audit_annotations from alden_annotation_candidates import create_review, read_review +import alden_annotation_candidates as candidates class AnnotationCandidateContractTests(unittest.TestCase): @@ -101,6 +104,144 @@ def _review(self, scope=None, projects=("one",)): self.assertTrue(review_id) return scope, report, review_id + def test_concurrent_review_publications_respect_the_shared_file_budget(self): + self._seed_groups(1, first_members=3) + report = self._scan() + existing = {create_review(self.root, self.PROJECT_SCOPE, report) + for _ in range(candidates.MAX_CACHE_FILES - 1)} + self.assertEqual(len(existing), candidates.MAX_CACHE_FILES - 1) + folder = self.store.root / 'annotation-reviews' + previous = {identity: hashlib.sha256((folder / (identity + '.json')).read_bytes()).hexdigest() + for identity in existing} + report_path = self.root / 'owned-candidate-report.json' + report_path.write_text(json.dumps(report)) + paused, release = threading.Event(), threading.Event() + original_mkstemp = candidates.tempfile.mkstemp + published, failures = [], [] + + def pause_before_publication(*args, **kwargs): + paused.set() + if not release.wait(10): + raise AssertionError('owned publisher was not released') + return original_mkstemp(*args, **kwargs) + + def publish(): + try: + published.append(create_review(self.root, self.PROJECT_SCOPE, report)) + except Exception as error: + failures.append(error) + + program = """ +import json,sys +from pathlib import Path +sys.path.insert(0,sys.argv[1]) +from alden_annotation_candidates import create_review +try: + review=create_review(Path(sys.argv[2]),{'scope':'project','project':'one'}, + json.loads(Path(sys.argv[3]).read_text())) + print(json.dumps({'review_id':review})) +except ValueError as error: + print(json.dumps({'error':str(error)})) +""" + with patch('alden_annotation_candidates.tempfile.mkstemp', side_effect=pause_before_publication): + owner = threading.Thread(target=publish) + owner.start() + try: + self.assertTrue(paused.wait(3), 'first publisher did not reach the real write boundary') + contender = subprocess.run( + [sys.executable, '-B', '-c', program, + str(Path(__file__).resolve().parents[1] / 'scripts'), + str(self.root), str(report_path)], + capture_output=True, text=True, timeout=5, + ) + finally: + release.set() + owner.join(5) + self.assertFalse(owner.is_alive(), 'owned publisher leaked') + self.assertEqual(failures, []) + self.assertEqual(len(published), 1) + self.assertLessEqual(len(list(folder.glob('*.json'))), candidates.MAX_CACHE_FILES) + self.assertEqual(contender.returncode, 0, contender.stderr) + self.assertEqual(json.loads(contender.stdout), {'error': 'annotation_review_cache_busy'}) + self.assertTrue(all((folder / (identity + '.json')).is_file() for identity in existing)) + self.assertEqual({identity: hashlib.sha256((folder / (identity + '.json')).read_bytes()).hexdigest() + for identity in existing}, previous) + # The owner released its guard. An ordinary full-cache error must not + # leave subsequent publishers permanently busy. + with self.assertRaisesRegex(ValueError, '^annotation_review_cache_budget$'): + create_review(self.root, self.PROJECT_SCOPE, report) + + def test_process_exit_releases_publication_ownership_without_removing_the_lock_inode(self): + self._seed_groups(1, first_members=3) + report = self._scan() + folder = self.store.root / 'annotation-reviews' + folder.mkdir(mode=0o700) + program = """ +import os,sys +from pathlib import Path +sys.path.insert(0,sys.argv[1]) +from alden_annotation_candidates import _publication_lock +with _publication_lock(Path(sys.argv[2])): + os._exit(0) +""" + owner = subprocess.run( + [sys.executable, '-B', '-c', program, + str(Path(__file__).resolve().parents[1] / 'scripts'), str(folder)], + capture_output=True, text=True, timeout=5, + ) + self.assertEqual(owner.returncode, 0, owner.stderr) + lock = folder / '.publication.lock' + identity = (lock.stat().st_dev, lock.stat().st_ino) + review_id = create_review(self.root, self.PROJECT_SCOPE, report) + self.assertTrue((folder / (review_id + '.json')).is_file()) + self.assertEqual((lock.stat().st_dev, lock.stat().st_ino), identity) + self.assertEqual(lock.read_bytes(), b'') + self.assertEqual(stat.S_IMODE(lock.stat().st_mode), 0o600) + + def test_unsafe_publication_lock_objects_never_publish_or_modify_their_targets(self): + self._seed_groups(1, first_members=3) + report = self._scan() + folder = self.store.root / 'annotation-reviews' + folder.mkdir(mode=0o700) + lock = folder / '.publication.lock' + outside = self.root / 'untouched-lock-target' + outside.write_bytes(b'') + outside.chmod(0o600) + for kind in ('symlink', 'hardlink', 'directory', 'nonempty', 'shared_permissions'): + with self.subTest(kind=kind): + if kind == 'symlink': + lock.symlink_to(outside) + elif kind == 'hardlink': + lock.hardlink_to(outside) + elif kind == 'directory': + lock.mkdir(mode=0o700) + else: + lock.write_bytes(b'not-a-lock' if kind == 'nonempty' else b'') + lock.chmod(0o644 if kind == 'shared_permissions' else 0o600) + try: + with self.assertRaises((OSError, ValueError)): + create_review(self.root, self.PROJECT_SCOPE, report) + self.assertEqual(list(folder.glob('*.json')), []) + self.assertEqual(outside.read_bytes(), b'') + self.assertEqual(stat.S_IMODE(outside.stat().st_mode), 0o600) + finally: + if lock.is_dir() and not lock.is_symlink(): + lock.rmdir() + else: + lock.unlink() + + def test_failed_publication_cleans_staging_and_releases_ownership(self): + self._seed_groups(1, first_members=3) + report = self._scan() + with patch('alden_annotation_candidates.os.replace', side_effect=OSError('owned write failure')): + with self.assertRaisesRegex(OSError, 'owned write failure'): + create_review(self.root, self.PROJECT_SCOPE, report) + folder = self.store.root / 'annotation-reviews' + self.assertEqual(list(folder.glob('*.json')), []) + self.assertEqual(list(folder.glob('.review-*')), []) + review_id = create_review(self.root, self.PROJECT_SCOPE, report) + self.assertTrue((folder / (review_id + '.json')).is_file()) + @staticmethod def _query(scope, review_id, *, offset=0, group=None): query = {**scope, "review_id": review_id, "offset": offset} diff --git a/tests/test_alden_graph_quality_action.py b/tests/test_alden_graph_quality_action.py index 7b177b48..d301b0ae 100644 --- a/tests/test_alden_graph_quality_action.py +++ b/tests/test_alden_graph_quality_action.py @@ -43,6 +43,21 @@ class QualityActionContractTests(unittest.TestCase): + def test_busy_annotation_publication_returns_existing_public_failure_contract(self): + from alden_annotation_candidates import _publication_lock + self.store.ingest(self.target(), [{'platform':'graph','original_id':'owned-lock-fixture', + 'label':'Synthetic evidence','text':'Synthetic body retained during a busy review.'}]) + folder=self.store.root/'annotation-reviews' + folder.mkdir(mode=0o700) + query=json.dumps({'scope':'project','project':'one','include_annotation_review':True}) + before=self.store.path.read_bytes() + with _publication_lock(folder): + result=action.read_action(self.root,query) + self.assert_error(result,'quality_annotation_review_unavailable',mode='project',project='one') + self.assertEqual(list(folder.glob('*.json')),[]) + self.assertEqual(self.store.path.read_bytes(),before) + self.assertTrue(action.read_action(self.root,query)['ok']) + def test_empty_body_is_counted_without_hiding_title_or_mutating_source(self): self.store.ingest(self.target(), [ {'platform': 'graph', 'original_id': 'only-title', 'label': '찾을 수 있는 영상 제목', 'text': ''}, diff --git a/tests/test_alden_korean_search.py b/tests/test_alden_korean_search.py index e9febce1..f4507423 100644 --- a/tests/test_alden_korean_search.py +++ b/tests/test_alden_korean_search.py @@ -8,6 +8,7 @@ import sys from tempfile import TemporaryDirectory import unittest +from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) @@ -15,6 +16,85 @@ class KoreanSearchRegressionTests(unittest.TestCase): + def test_full_token_prefix_skips_supplement_but_keeps_graph_lookahead(self): + from alden_collection import integer_digit_matches + target = self.target() + self.store.ingest(target, [self.record('token-a', '수량은 100 입니다.'), + self.record('token-b', '수량은 100 입니다.'), + self.record('unit', '수량은 100개입니다.')]) + with patch('alden_collection.integer_digit_matches', side_effect=AssertionError('unexpected body scan')): + self.assertEqual(len(self.search_ids('100', limit=1)), 1) + page = self.store.graph_page(projects=['one'], query='100', limit=1) + self.assertEqual(len(page['nodes']), 1) + self.assertEqual(page['next'], 1) + # Exactly filling a displayed page is insufficient: the suffix match + # must still establish that another page exists. + with patch('alden_collection.integer_digit_matches', wraps=integer_digit_matches) as match: + page = self.store.graph_page(projects=['one'], query='100', limit=2) + self.assertTrue(match.called) + self.assertEqual(page['next'], 2) + + def test_bare_integer_keeps_fts_order_then_adds_complete_digit_runs(self): + target = self.target() + self.store.ingest(target, [ + self.record('token', '보관 수량은 100 입니다.'), + self.record('unit', '보관 수량은 100개입니다.'), + self.record('identifier', '기록 ID100x를 확인합니다.'), + self.record('larger', '보관 수량은 1000개입니다.'), + self.record('leading', '보관 수량은 0100개입니다.'), + self.record('grouped', '보관 수량은 100,000개입니다.'), + self.record('decimal', '보관 수량은 100.5개입니다.'), + self.record('unicode-prefix', '보관 수량은 ١100개입니다.'), + ]) + # Preserve existing FTS candidates/ranking, including its punctuation + # tokenization. This supplement does not interpret signs/units/values. + original = self.search_ids('100', expand_korean=False, limit=20) + self.assertIn(identity('graph', 'grouped'), original) + self.assertIn(identity('graph', 'decimal'), original) + expected = set(original) | {identity('graph', 'unit'), identity('graph', 'identifier')} + ranked = self.search_ids('100', limit=20) + self.assertEqual(set(ranked), expected) + self.assertEqual(ranked[:len(original)], original) + self.assertEqual(self.search_ids('100', limit=len(original)), original) + self.assertEqual(self.search_ids('"100"', limit=20), original) + pages = [self.store.graph_page(projects=['one'], query='100', limit=1, offset=i) + for i in range(len(expected))] + self.assertEqual([p['nodes'][0]['id'] for p in pages], ranked) + self.assertEqual([p['next'] for p in pages], list(range(1, len(expected))) + [None]) + + def test_integer_supplement_uses_current_permitted_membership_and_time(self): + allowed = self.target('allowed') + foreign = self.target('foreign', project='two') + denied = self.target('denied', permission='denied') + removed = self.target('removed') + self.store.ingest(allowed, [self.record('shared', '보관 수량은 100개입니다.')]) + self.store.ingest(foreign, [self.record('shared', '보관 수량은 1000개입니다.')]) + self.store.ingest(denied, [self.record('hidden', '보관 수량은 100개입니다.')]) + row = self.record('deleted', '보관 수량은 100개입니다.') + self.store.ingest(removed, [row], complete_snapshot=True, + source_revision=digest(encoded([row])), source_order=1) + self.store.ingest(removed, [], complete_snapshot=True, + source_revision=digest(encoded([])), source_order=2) + expected = [identity('graph', 'shared')] + self.assertEqual(self.search_ids('100'), expected) + self.assertEqual(self.graph_ids('100'), expected) + self.assertEqual(self.search_ids('100', project='two'), []) + self.assertEqual(self.graph_ids('100', project='two'), []) + self.assertEqual(self.search_ids('100', time_from=10**10), []) + self.assertEqual(self.graph_ids('100', until=1), []) + + def test_integer_queries_preserve_source_bytes_and_later_digit_occurrences(self): + target = self.target() + text = '보관 수량은 1000개 이후 100개입니다.\t\t \n 원문 간격 유지 ' + raw = {'text': text, 'value': '100', 'unit': '개'} + self.store.ingest(target, [self.record('unchanged', text, raw=raw)]) + baseline = self.persisted_source_state() + expected = [identity('graph', 'unchanged')] + for query in ('100', '1000'): + self.assertEqual(self.search_ids(query), expected) + self.assertEqual(self.graph_ids(query), expected) + self.assertEqual(self.persisted_source_state(), baseline) + def test_numeric_literals_do_not_match_larger_values_and_check_later_occurrences(self): target = self.target() self.store.ingest(target, [ @@ -150,18 +230,23 @@ def test_advanced_fts_not_column_prefix_and_near_are_not_expanded(self): with self.subTest(query=query): self.assertEqual(set(self.search_ids(query)), {identity("graph", name) for name in names}) - def test_literal_bounds_and_korean_requirement(self): + def test_literal_bounds_and_korean_or_integer_requirement(self): target = self.target() self.store.ingest(target, [ self.record("numeric", "이자리35년336"), self.record("length", "앞" + "가" * 65 + "뒤"), self.record("latin", "prefixABCtoken") ]) - for query in ("년", "35", "ABC", "가" * 65): + for query in ("년", "3", "ABC", "가" * 65): with self.subTest(query=query, api="search"): self.assertEqual(self.search_ids(query), []) with self.subTest(query=query, api="graph_page"): self.assertEqual(self.graph_ids(query), []) + numeric = [identity('graph', 'numeric')] + self.assertEqual(self.search_ids('35'), numeric) + self.assertEqual(self.graph_ids('35'), numeric) + self.assertEqual(self.search_ids('35', expand_korean=False), []) + self.assertEqual(self.search_ids('"35"'), []) expected = [identity("graph", "length")] self.assertEqual(self.search_ids("가" * 64), expected) self.assertEqual(self.graph_ids("가" * 64), expected) diff --git a/tests/test_alden_realtime_collection.py b/tests/test_alden_realtime_collection.py index 2de66008..63bf4a22 100644 --- a/tests/test_alden_realtime_collection.py +++ b/tests/test_alden_realtime_collection.py @@ -45,6 +45,64 @@ def cycle(self, **changes): return self.scheduler.cycle(collector=collect_target, capturer=capture_source, indexer=changes.pop('indexer', lambda *a, **kw: {'state': 'ready'}), **changes) + def test_input_after_first_200_targets_is_collected_and_requeued_on_change(self): + eligible = {self.target} + for number in range(400): + eligible.add(self.store.register(platform='graph', original_id=f'large-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600)) + with self.store.database() as db: + tail = db.execute('SELECT id FROM targets ORDER BY id DESC LIMIT 1').fetchone()[0] + self.enable() + self.assertEqual(self.live.scan(self.store, now=100), 401) + self.assertEqual(self.live.scan(self.store, now=103), 401) + queued = self.live.pending() + self.assertEqual(set(queued), eligible) + self.assertEqual(self.cycle(target_id=tail)['attempts'][0]['state'], 'complete') + self.assertEqual(set(self.live.pending()), eligible - {tail}) + self.write('200개 뒤 대상의 새 원문') + self.queue(200) + self.assertNotEqual(self.live.pending()[tail]['queued'], queued[tail]['queued']) + self.assertEqual(self.cycle(target_id=tail)['attempts'][0]['state'], 'complete') + with self.store.database() as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM versions').fetchone()[0], 2) + self.assertEqual(db.execute('SELECT COUNT(*) FROM targets WHERE interval_seconds=21600').fetchone()[0], 401) + self.live.scan(self.store, now=210) + self.assertNotIn(tail, self.live.pending()) + + def test_page_traversal_keeps_disabled_denied_and_paused_targets_out(self): + eligible = {self.target} + for number in range(202): + eligible.add(self.store.register(platform='graph', original_id=f'scoped-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600)) + disabled, denied, paused = sorted(eligible)[:3] + with self.store.database() as db: + db.execute('UPDATE targets SET enabled=0 WHERE id=?', (disabled,)) + db.execute("UPDATE target_projects SET permission='denied' WHERE target_id=?", (denied,)) + self.scheduler.pause(True, paused) + self.enable(); self.queue() + self.assertEqual(set(self.live.pending()), eligible - {disabled, denied, paused}) + with self.live.database() as db: + observed = {row[0] for row in db.execute('SELECT target_id FROM inputs')} + self.assertEqual(observed, eligible - {disabled, denied, paused}) + + def test_live_policy_revision_change_stops_before_next_page(self): + for number in range(200): + self.store.register(platform='graph', original_id=f'policy-live-{number}', + kind='graph_source', label='fixture', projects=['allowed'], + config={'adapter': 'source-graph', 'path': str(self.source)}, interval_seconds=21600) + self.enable() + with patch.object(self.live, 'policy', side_effect=[ + {'enabled': True, 'revision': 1}, {'enabled': True, 'revision': 1}, + {'enabled': False, 'revision': 2}]): + self.assertEqual(self.live.scan(self.store, now=100), 200) + with self.live.database() as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM inputs').fetchone()[0], 200) + self.assertEqual(self.live.scan(self.store, now=103), 201) + self.assertEqual(self.live.scan(self.store, now=106), 201) + self.assertEqual(len(self.live.pending()), 201) + def test_default_read_is_side_effect_free_and_policy_cas_is_recoverable(self): self.assertFalse(self.live.policy()['enabled']) self.assertFalse(self.live.path.exists())