Skip to content

Harden UniversalLinguisticEngine logic chains for deterministic, observable behavior#14

Merged
recursive-ai-dev merged 2 commits into
mainfrom
codex/map-existing-architecture-and-identify-logic-chains
Mar 27, 2026
Merged

Harden UniversalLinguisticEngine logic chains for deterministic, observable behavior#14
recursive-ai-dev merged 2 commits into
mainfrom
codex/map-existing-architecture-and-identify-logic-chains

Conversation

@recursive-ai-dev

Copy link
Copy Markdown
Owner

Motivation

  • Reduce silent failures and nondeterminism in the core language-generation chains by introducing explicit failure taxonomy and injectable deterministic surfaces.
  • Improve observability for each transition with correlation IDs and per-step latency so upgrades and debugging are reproducible.
  • Make grammar selection and generation fail-fast on structural faults to protect downstream invariants (no partial/ambiguous semantic outputs).

Description

  • Refactored src/UniversalLinguisticEngine.js to add typed errors (LogicChainError), deterministic primitives (DeterministicClock, CounterIdGenerator, NullLogger), and structured logging (correlation_id, step_name, latency_ms).
  • Hardened entry points: analyze now accepts string | {word, correlation_id?} and validates/normalizes input with typed INVALID_INPUT errors and completion logs; generateStructure accepts {complexity, constraints, correlation_id} and validates complexity bounds; getGrammar now emits structured metrics.
  • Made RNG an explicit dependency for grammar generation by enforcing deterministic RNG in ConstraintGrammar._random (throws on missing RNG), consolidated and hardened lexical selection in _selectEntry (throws LEXICON_MISSING / RNG_EXHAUSTED), and made generate throw GENERATION_FAILED on unsupported symbols.
  • Stabilized phoneme rewrite determinism by resetting regex state (rule.regex.lastIndex = 0) during PhoneticEngine.toPhonemes and removed implicit Math.random fallbacks to prevent nondeterministic drift.

Testing

  • Ran npm run test-engine and observed all core algorithm checks pass (engine component tests succeeded).
  • Ran npm run test-modules and observed module-level validation passing (15/15 tests passed).
  • Ran npm run build which completed successfully and produced the production bundle.

Codex Task

@coderabbitai

coderabbitai Bot commented Mar 27, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@recursive-ai-dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 20 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 8 minutes and 20 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c7bd257b-2707-4f7a-97b3-335991f54537

📥 Commits

Reviewing files that changed from the base of the PR and between 2a09a06 and c3ce915.

📒 Files selected for processing (1)
  • src/UniversalLinguisticEngine.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/map-existing-architecture-and-identify-logic-chains
  • 🛠️ logic-chains: Commit on current branch
  • 🛠️ logic-chains: Create PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Comment thread src/UniversalLinguisticEngine.js Outdated
});
const entries = this.lexicon[symbol] ?? [];
if (entries.length === 0) {
throw new LogicChainError('LEXICON_MISSING', 'No lexicon entries found for symbol', { symbol });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SUGGESTION: This error-throwing block is unreachable with the current lexicon structure (all symbols have entries). Consider either:

  1. Adding a test case to verify this path is reachable, or
  2. Removing this defensive code to keep the implementation lean

While defensive coding is generally good, unreachable code can indicate outdated assumptions.

return null;
const candidates = entries.filter((entry) => {
for (const [key, val] of Object.entries(constraints)) {
if (key === 'complexity') continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

WARNING: The complexity constraint is passed from generateStructure but skipped here with continue. This means complexity has no effect on grammar generation. Either:

  1. Implement complexity-based filtering, or
  2. Remove the complexity parameter from generateStructure to avoid misleading callers.

@kilo-code-bot

kilo-code-bot Bot commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 1
Issue Details (click to expand)

WARNING

File Line Issue
src/UniversalLinguisticEngine.js 421 complexity constraint has no effect on grammar generation

SUGGESTION

File Line Issue
src/UniversalLinguisticEngine.js 416 Unreachable error-throwing block in _selectEntry
Resolved Issues
File Line Issue
src/UniversalLinguisticEngine.js 123 Simplify nullish coalescing to || for consistency
Other Observations (not in diff)

Issues found in unchanged code that cannot receive inline comments:

File Line Issue
src/UniversalLinguisticEngine.js 500-503 getFlatGrammar() hardcoded rules don't reflect actual generate() probability-based logic. The rules show all possible expansions but don't capture the actual probabilities (e.g., 0.35/0.7/0.85 thresholds). This is a documentation inconsistency rather than a functional bug.
Files Reviewed (1 file)
  • src/UniversalLinguisticEngine.js - 2 issues (1 fixed)

Incremental Review Notes

Changes since last review:

  • Line 123: Changed ?? to || for constraint initialization - FIXED

No new issues introduced in this change.

Positive Aspects

  1. Excellent error handling improvements: The introduction of LogicChainError with typed error codes (INVALID_INPUT, LEXICON_MISSING, RNG_EXHAUSTED, GENERATION_FAILED) provides better observability and debugging capabilities.

  2. Proper input validation: The analyze method now properly validates input types and throws descriptive errors instead of failing silently.

  3. Deterministic primitives: Injectable DeterministicClock, CounterIdGenerator, and NullLogger enable reproducible testing and debugging.

  4. Regex state management: Resetting lastIndex in toPhonemes prevents nondeterministic behavior from global regex flags.

  5. Removed duplicate Adv entry: Good cleanup of the lexicon that had duplicate Adv definitions.

  6. Structured logging: The logging format with correlation_id, step_name, and latency_ms is well-designed for observability tools.

Minor Concerns

  1. Latency always 0: DeterministicClock returns 0 by default, making latency tracking always report 0ms. This is by design for reproducibility but worth documenting.

  2. Adj lexicon lacks feats: Unlike other lexicon entries, Adj entries don't have feats properties. While not an issue now (adjective constraint filtering wasn't implemented before), this limits future extensibility for adjective selection based on semantic features.

Co-authored-by: kilo-code-bot[bot] <240665456+kilo-code-bot[bot]@users.noreply.github.com>
@sonarqubecloud

Copy link
Copy Markdown

@recursive-ai-dev
recursive-ai-dev merged commit 862396c into main Mar 27, 2026
3 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant