ruvnet/RuView · critical · Error

brain line ${index + 1}: exceeds 16 KiB

Error message

brain line ${index + 1}: exceeds 16 KiB

What it means

The AuthenticationMiddleware.dispatch catch-all (auth.py:215) converts any unexpected exception raised during request authentication into HTTP 500 'Authentication service error'. The original exception is logged as 'Authentication middleware error: {e}' but never surfaced to the client. It fires only for exceptions that are neither AuthenticationError nor AuthorizationError.

Source

Thrown at harness/homecore/src/brain.js:76

  }
  if (!Array.isArray(record.tags) || record.tags.some((tag) => typeof tag !== 'string')) {
    errors.push('tags must be strings');
  }
  if ((record.content || '').length > 8192) errors.push('content exceeds 8192 characters');
  if ((record.title || '').length > 200) errors.push('title exceeds 200 characters');
  if (canonical && record.reviewed !== true) errors.push('canonical records must be reviewed');
  const combined = `${record.title || ''}\n${record.content || ''}`;
  if (SECRET.test(combined)) errors.push('record appears to contain a secret');
  if (INJECTION.test(combined)) errors.push('record contains instruction-like prompt injection');
  return errors;
}

export function loadBrain(path = CORPUS_PATH) {
  const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
  if (Buffer.byteLength(raw) > 1_048_576) throw new Error('brain corpus exceeds 1 MiB');
  const records = raw.split('\n').filter(Boolean).map((line, index) => {
    if (Buffer.byteLength(line) > 16_384) {
      throw new Error(`brain line ${index + 1}: exceeds 16 KiB`);
    }
    let record;
    try {
      record = JSON.parse(line);
    } catch (error) {
      throw new Error(`brain line ${index + 1}: ${error.message}`);
    }
    const errors = validateBrainRecord(record, { canonical: true });
    if (errors.length) throw new Error(`brain line ${index + 1}: ${errors.join('; ')}`);
    return Object.freeze(record);
  });
  if (records.length > 1000) throw new Error('brain corpus exceeds 1000 records');
  const ids = new Set();
  for (const record of records) {
    if (ids.has(record.id)) throw new Error(`duplicate brain id: ${record.id}`);
    ids.add(record.id);
  }
  return { records, digest: sha256(raw), bytes: Buffer.byteLength(raw) };

View on GitHub (pinned to 4685618388)

Solutions

  1. Read the server log and find the 'Authentication middleware error: ...' line - fix that root cause, not the 500 itself
  2. Verify the src.api.middleware.auth module (token_blacklist) imports cleanly: python -c "from src.api.middleware.auth import token_blacklist"
  3. Ensure user records always contain username/email/roles/is_active keys so the user-info dict construction cannot KeyError
  4. Add a regression test covering the failing request path once the cause is known
Defensive patterns

Strategy: try-catch

Validate before calling

import importlib

def auth_dependencies_importable() -> bool:
    """The lazy blacklist import inside verify_token must resolve."""
    try:
        importlib.import_module("src.api.middleware.auth")
        return True
    except ImportError:
        return False

Try / catch

# Server-side: this 500 means a bug, not a client problem.
try:
    response = client.get("/api/x", headers=auth_headers)
except HTTPError:
    if response.status_code == 500 and response.json()["detail"] == "Authentication service error":
        check_server_log_for("Authentication middleware error")
    raise

Prevention

When it happens

Trigger: A bug inside _authenticate_request's non-auth code paths (e.g. a malformed user record making user['roles'] raise KeyError); failure while instantiating dependencies during middleware init; an ImportError in the lazy 'from src.api.middleware.auth import token_blacklist' import inside verify_token blowing up as a generic exception.

Common situations: Deploying where src.api.middleware.auth (the blacklist module) is missing or shadowed; corrupted/partial user records (missing 'roles' key) hitting _add_auth_headers; upgrading a dependency that changes an internal API used by the middleware.

Related errors


AI-assisted analysis of ruvnet/RuView@4685618388 (2026-08-16). Data as JSON: /api/errors/965615e5b69f0016. Report an issue: GitHub.