Skip to content

JS: пересобирать alpha occurrence на текущей подложке - #483

Merged
lemone112 merged 6 commits into
mainfrom
agent/v3-alpha-occurrence-recheck
Jul 28, 2026
Merged

JS: пересобирать alpha occurrence на текущей подложке#483
lemone112 merged 6 commits into
mainfrom
agent/v3-alpha-occurrence-recheck

Conversation

@lemone112

@lemone112 lemone112 commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Что изменено

  • adaptTheme хранит для каждого физического occurrence исходный sRGB8 и alpha, а не только composite старого solve.
  • Для каждого текущего backdrop translucent occurrence заново композитится Core-оператором __over; смешанные наборы проверяются в исходном порядке без ложного shared-foreground batch.
  • Opaque-only путь сохраняет существующий packed batch.
  • Документация синхронизирована с реальным canvas-контрактом; удалён выдуманный fallback.
  • Boundary benchmark измеряет реальный набор solid+alpha occurrence и использует доказанно admissible cache-miss corpus.

Почему

Старый controller повторно проверял frozen compositeHex, вычисленный на solve-backdrop. После изменения backdrop это уже не физический цвет translucent occurrence, поэтому runtime мог пропустить реальный breach или сообщить ложный.

Граница среза

Это bounded safety bridge для текущего legacy JS runtime, не V3 Program API. Публичная поверхность не расширена. Текущий WASM DTO допускает alpha только в (0, 1]; alpha=0 появится только сквозным atomic PaintValue в Program, без forged JS-only состояния.

Проверки

  • exact head cb51c5a поверх main@2404938;
  • git range-diff: 5/5 патчей сохранены при rebase;
  • npm 11.9.0: 274 passed, 0 failed;
  • npm run typecheck;
  • npm run release:verify: clean archive reproduced and verified;
  • cache-miss anti-vacuum: 4097 уникальных допустимых фонов + отдельный typed Conflict для #1099FF;
  • независимый hostile-review и CI завершаются на этом exact head.

Summary by CodeRabbit

  • Документация

    • Обновлено описание API проверки контраста для наборов образцов и поведения adaptTheme.
    • Документирована опция canvas для прозрачных корней.
  • Улучшения

    • Повышена точность адаптации тем с прозрачными и смешанными цветами.
    • При отсутствии явного непрозрачного canvas полностью прозрачные фоны теперь корректно получают статус Unknown.
    • Улучшена обработка и проверка данных при повторной оценке контраста.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 29 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: a744d313-65cc-4d33-b151-ad973c65e32f

📥 Commits

Reviewing files that changed from the base of the PR and between 2404938 and f616382.

📒 Files selected for processing (9)
  • packages/colors/README.md
  • packages/colors/adapt-theme.js
  • packages/colors/bench/misses.mjs
  • packages/colors/bench/occurrences.mjs
  • packages/colors/bench/wasm-boundary.bench.mjs
  • packages/colors/test/adapt-theme-translucent.test.mjs
  • packages/colors/test/adapt-theme.test.mjs
  • packages/colors/test/hotpath-parity.test.mjs
  • packages/colors/test/public-api-cleanup.test.mjs

Walkthrough

Изменён recheck-поток adaptTheme: translucent occurrences теперь материализуются на текущем фоне, а batch API применяется только для непрозрачных значений. Обновлены бенчмарки, тесты и документация опций canvas и recheckContrastMulti.

Changes

Адаптивная проверка контрастности

Layer / File(s) Summary
Occurrence-based recheck в adaptTheme
packages/colors/adapt-theme.js
recheckOccurrences заменяет прежние recheck-структуры; translucent значения вычисляются через __over, а batch-путь используется только при полной непрозрачности.
Бенчмарки и cache-miss corpus
packages/colors/bench/*, packages/colors/test/hotpath-parity.test.mjs
Бенчмарки используют materialized occurrences, opaque batch-сценарии и кольцо фоновых cache-miss значений.
Проверки translucent recheck
packages/colors/test/adapt-theme*.test.mjs
Тесты проверяют materialization, batch/per-sample маршрутизацию, порядок occurrences, malformed evidence и сохранение состояния.
Публичные опции и контракт документации
packages/colors/README.md, packages/colors/test/public-api-cleanup.test.mjs
Документированы canvas, Unknown для прозрачного корня и finite-sample поведение recheckContrastMulti; добавлены соответствующие проверки.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant adaptTheme
  participant recheckSamples
  participant __over
  participant Engine
  adaptTheme->>recheckSamples: передаёт recheckOccurrences
  recheckSamples->>__over: материализует translucent occurrence
  recheckSamples->>Engine: вызывает recheckContrast или recheckContrastMulti
  Engine-->>recheckSamples: возвращает значения Lc
Loading

Possibly related PRs

  • Labpics-Team/lab-colors#350: связан с передачей полной evidence-модели ResolvedOccurrence в downstream recheck.
  • Labpics-Team/lab-colors#357: добавляет WASM-экспорт __over, используемый для materialization translucent occurrences.
  • Labpics-Team/lab-colors#364: связан с поведением Unknown и опцией canvas для полностью прозрачных корней.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно отражает основное изменение: пересборку translucent alpha occurrence на текущей подложке.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/v3-alpha-occurrence-recheck

Comment @coderabbitai help to get the list of available commands.

@lemone112
lemone112 marked this pull request as ready for review July 28, 2026 01:55

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Проверьте точный head cb51c5a; публичная граница не расширена, alpha occurrence должен рематериализоваться отдельно для каждого текущего backdrop.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

@lemone112 Запускаю полный повторный review PR #483 на точном head cb51c5a, с отдельной проверкой неизменности публичной границы и рематериализации каждого translucent alpha occurrence для каждого текущего backdrop.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 14 minutes.

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Повторный exact-head запрос после rate-limit. Head неизменен: cb51c5a; независимый hostile-review не нашёл blocker.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

@lemone112 Запускаю полный повторный review PR #483 на exact head cb51c5a, включая проверку неизменности публичной границы и отдельной рематериализации translucent alpha occurrence для каждого текущего backdrop.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 11 minutes.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Exact-head gate: проверьте неизменный head cb51c5a39bcf1875818e0afc99640ae6da4e21c3. Нужен содержательный review восьми изменённых файлов; предыдущие ответы были только rate-limit-заглушками.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

@lemone112 Принято. Запускаю содержательный полный review PR #483 только при совпадении exact HEAD cb51c5a39bcf1875818e0afc99640ae6da4e21c3.

Проверю все восемь изменённых файлов, в частности:

  • отсутствие расширения публичной границы;
  • отдельную рематериализацию каждого translucent occurrence на каждом текущем backdrop;
  • порядок mixed occurrence и отсутствие ложного shared-foreground batching;
  • сохранение packed batch для opaque-only пути;
  • соответствие документации реальному canvas-контракту;
  • корректность benchmark/corpus и тестового покрытия.

🐇🔍

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 24 seconds.

@lemone112

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Повтор после указанного вами окна (24 seconds). Exact head по-прежнему cb51c5a39bcf1875818e0afc99640ae6da4e21c3; прошу выполнить содержательный review, а не rate-limit acknowledgement.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

@lemone112 Принято. Запускаю содержательный полный review PR #483 только при совпадении HEAD с cb51c5a39bcf1875818e0afc99640ae6da4e21c3.

Проверка охватит все восемь изменённых файлов: сохранение публичной границы, отдельную рематериализацию каждого translucent occurrence для каждого текущего backdrop, порядок mixed-наборов, opaque packed-path, документацию canvas-контракта и benchmark/corpus.

🐇🔍

✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/colors/adapt-theme.js`:
- Around line 438-440: Document the new buffer-lifetime contract for the
reusable foregroundRow passed to recheckContrast: add a comment at this call
site stating that the Uint32Array is valid only during the synchronous
invocation and must not be retained, cached, or accessed asynchronously. Update
the recheckContrast description in the README with the same constraint.

In `@packages/colors/bench/misses.mjs`:
- Around line 5-9: Update the source matching and capacity parsing in the
benchmark so it accepts Rust declarations with optional pub visibility, flexible
whitespace, digit separators, and trailing comments. Normalize digit separators
before converting the captured value to Number, while preserving the existing
safe-integer and RGB24_MAX validation in the capacity check.

In `@packages/colors/bench/wasm-boundary.bench.mjs`:
- Around line 153-154: Update the benchmark flow around recheckOpaqueMulti3 and
its corresponding per-role output to skip the opaque batch capability ×3
scenario whenever OPAQUE_FGSW.length === 0. Preserve the existing execution and
division behavior for non-empty opaque batches, and apply the same guard to the
additional referenced occurrence.
- Around line 124-131: Update materializeOccurrences to mirror adaptTheme’s
INVALID_RGB24 sentinel check after __over: when compositing returns the
sentinel, preserve the typed rejection behavior instead of writing the invalid
value into row or the computation fingerprint; retain the existing direct
sourceRgb24 path for fully opaque occurrences.

In `@packages/colors/test/adapt-theme.test.mjs`:
- Around line 3937-3949: Update the test “mixed occurrence rows preserve order
and materialize alpha per backdrop” to assert the exact set of backdrops present
in replay.rechecks, rather than only checking rechecks.length >= 2. Derive the
checked backdrops from replay.rechecks and compare them with the declared
`#000000` and `#FFFFFF` samples, while preserving the existing row and resolves
assertions.

In `@packages/colors/test/hotpath-parity.test.mjs`:
- Around line 236-248: Replace the source-text assertions in the test “the
boundary benchmark measures the shipping mixed occurrence path” with behavioral
coverage. Extract materializeOccurrences and OCCURRENCES construction into a
shared module beside misses.mjs, import that module in the benchmark and test,
and add direct assertions that an alpha occurrence on two different backdrops
produces two distinct words while an opaque occurrence produces the same word.
- Line 270: Update the test loop around colors.resolveTheme to explicitly assert
that each background in ring is admissible, catching resolution failures and
reporting the specific background that caused the failure instead of allowing an
unhandled exception. Preserve the existing dark-theme resolution behavior for
every ring entry.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: b7ad1b49-be35-4cb4-a0d7-7814260d293a

📥 Commits

Reviewing files that changed from the base of the PR and between 2404938 and cb51c5a.

📒 Files selected for processing (8)
  • packages/colors/README.md
  • packages/colors/adapt-theme.js
  • packages/colors/bench/misses.mjs
  • packages/colors/bench/wasm-boundary.bench.mjs
  • packages/colors/test/adapt-theme-translucent.test.mjs
  • packages/colors/test/adapt-theme.test.mjs
  • packages/colors/test/hotpath-parity.test.mjs
  • packages/colors/test/public-api-cleanup.test.mjs

Comment thread packages/colors/adapt-theme.js
Comment thread packages/colors/bench/misses.mjs Outdated
Comment thread packages/colors/bench/wasm-boundary.bench.mjs Outdated
Comment thread packages/colors/bench/wasm-boundary.bench.mjs Outdated
Comment thread packages/colors/test/adapt-theme.test.mjs
Comment thread packages/colors/test/hotpath-parity.test.mjs Outdated
Comment thread packages/colors/test/hotpath-parity.test.mjs Outdated

Copy link
Copy Markdown
Collaborator Author

Все 7 замечаний проверены и закрыты в exact head f61638223fcca02deeb6493b60f645e24b30a3d1.

Единственное уточнение к предложенному oracle: runtime законно выполняет два полных прохода по samples — current recheck и candidate-admission recheck. Поэтому тест фиксирует точную последовательность [black, white, black, white], а не ошибочное «ровно один раз».

Проверки exact head локально: 275/275 package tests, targeted 4/4, typecheck, pinned npm 11.9 release verification и реальный boundary benchmark; fingerprints сохранились 658c7482 / b1b5ba0e. Независимый read-only review: PASS.

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

Повторный exact-head review после закрытия всех 7 доказанных замечаний. Head: f61638223fcca02deeb6493b60f645e24b30a3d1; unresolved threads: 0.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

expected='f61638223fcca02deeb6493b60f645e24b30a3d1'
actual="$(git rev-parse HEAD)"
printf 'HEAD=%s\nEXPECTED=%s\nMATCH=%s\n' "$actual" "$expected" "$([ "$actual" = "$expected" ] && echo yes || echo no)"

base="$(git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD main)"
printf '\nBASE=%s\nCHANGED_FILES:\n' "$base"
git diff --name-status "$base"...HEAD

printf '\nDIFF_STAT:\n'
git diff --stat "$base"...HEAD

printf '\nOUTLINES:\n'
for file in \
  packages/colors/adapt-theme.js \
  packages/colors/bench/misses.mjs \
  packages/colors/bench/wasm-boundary.bench.mjs \
  packages/colors/test/adapt-theme-translucent.test.mjs \
  packages/colors/test/adapt-theme.test.mjs \
  packages/colors/test/hotpath-parity.test.mjs \
  packages/colors/test/public-api-cleanup.test.mjs
do
  if [ -f "$file" ]; then
    printf '\n--- %s ---\n' "$file"
    ast-grep outline "$file" --items all 2>/dev/null || true
  fi
done

Length of output: 8529


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='2404938f47a32af887c5b811dee280fbac64169e'

printf '%s\n' '=== CHANGED HUNKS: runtime, public surface, docs ==='
git diff --unified=80 "$base"...HEAD -- \
  packages/colors/adapt-theme.js \
  packages/colors/README.md \
  packages/colors/test/public-api-cleanup.test.mjs

printf '%s\n' '=== NEW BENCHMARK HELPERS ==='
ast-grep outline packages/colors/bench/occurrences.mjs --items all
cat -n packages/colors/bench/occurrences.mjs
printf '%s\n' '=== CHANGED HUNKS: benchmark helpers ==='
git diff --unified=80 "$base"...HEAD -- \
  packages/colors/bench/misses.mjs \
  packages/colors/bench/occurrences.mjs \
  packages/colors/bench/wasm-boundary.bench.mjs

printf '%s\n' '=== CHANGED TEST HUNKS ==='
git diff --unified=30 "$base"...HEAD -- \
  packages/colors/test/adapt-theme-translucent.test.mjs \
  packages/colors/test/adapt-theme.test.mjs \
  packages/colors/test/hotpath-parity.test.mjs

printf '%s\n' '=== PUBLIC EXPORTS / OPTIONS REFERENCES ==='
ast-grep outline packages/colors/index.js --items all 2>/dev/null || true
rg -n -C 3 --glob '*.js' --glob '*.mjs' \
  'adaptTheme\s*\(|recheckContrastMulti\s*\(|recheckContrast\s*\(|recheckOccurrences|benchmarkOccurrencesFromRoles|fallback|canvas' \
  packages/colors

Length of output: 150079


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '=== adapt-theme: recheck selection/materialization ==='
sed -n '330,475p' packages/colors/adapt-theme.js
printf '%s\n' '=== adapt-theme: candidate occurrence admission ==='
sed -n '530,720p' packages/colors/adapt-theme.js
printf '%s\n' '=== adapt-theme: tick/glow dispatch ==='
sed -n '1035,1110p' packages/colors/adapt-theme.js

printf '%s\n' '=== occurrences helper ==='
cat -n packages/colors/bench/occurrences.mjs
printf '%s\n' '=== cache-miss helper ==='
cat -n packages/colors/bench/misses.mjs

printf '%s\n' '=== README exact diff ==='
git diff --unified=30 2404938f47a32af887c5b811dee280fbac64169e...HEAD -- packages/colors/README.md
printf '%s\n' '=== public export exact diff ==='
git diff --unified=10 2404938f47a32af887c5b811dee280fbac64169e...HEAD -- packages/colors/index.js packages/colors/package.json

printf '%s\n' '=== runtime references to legacy role/composite inputs ==='
rg -n -C 2 'recheckRoles|recheckFgs|compositeHex|compositeLc|recheckOccurrences' \
  packages/colors/adapt-theme.js

printf '%s\n' '=== test names added on this exact head ==='
git diff --unified=0 2404938f47a32af887c5b811dee280fbac64169e...HEAD -- packages/colors/test \
  | rg '^\+test\(' || true

Length of output: 37943


@lemone112 Провёл содержательный review exact HEAD f61638223fcca02deeb6493b60f645e24b30a3d1блокирующих или actionable замечаний не нашёл.

Проверено:

  • Фактический scope — 9 файлов, включая новый packages/colors/bench/occurrences.mjs.
  • Публичные exports и package.json не менялись; canvas документирует уже существующий контракт, а fabricated fallback удалён из API-документации.
  • adaptTheme хранит source sRGB8 + opacity occurrence и для каждого translucent occurrence вызывает __over(..., currentBackdrop) заново перед каждым recheckContrast.
  • compositeHex не используется как runtime foreground; compositeLc остаётся только baseline-метрикой.
  • Mixed-наборы сохраняют порядок occurrence и не используют shared-foreground batching.
  • recheckContrastMulti остаётся только для полностью opaque (opacity === 1) набора.
  • Два полных прохода по samples — текущая проверка и candidate-admission — корректны; тест фиксирует последовательность [black, white, black, white].
  • Benchmark helper и cache-miss ring согласованы с заявленной физикой и проверяются тестами.

Независимо запускать тесты в read-only sandbox я не мог; это соответствует предоставленным вами результатам package/targeted/typecheck/release/benchmark verification.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 29 minutes.

@lemone112
lemone112 merged commit b2f1fbc into main Jul 28, 2026
10 checks passed
@lemone112
lemone112 deleted the agent/v3-alpha-occurrence-recheck branch July 28, 2026 02:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant