Skip to content

fix: online players count #3904

Open
eduwx wants to merge 2 commits intoopentibiabr:mainfrom
eduwx:fix-update-players-online
Open

fix: online players count #3904
eduwx wants to merge 2 commits intoopentibiabr:mainfrom
eduwx:fix-update-players-online

Conversation

@eduwx
Copy link
Copy Markdown

@eduwx eduwx commented Apr 3, 2026

Description

This PR fixes a log spam irregularity in the Game::updatePlayersOnline function where the server would repeatedly complain about failing to update the players online when the player count was exactly 0.

The executeWithinTransaction lambda was hitting false inside the iteration block because there were no players to map/update, throwing an unintended [error] continuously onto the server logs. Added a safety condition allowing it to exit returning true gracefully if no operation was strictly needed, alongside an extra safety check for validating the Database result before fetching getNumber<int>.

Behaviour

Actual

When having an empty test server or exactly 0 players online, the server console keeps periodically spamming:
[error] [Game::updatePlayersOnline] Failed to update players online.

Expected

The server skips updating the database and fails gracefully when the player pool is empty without spamming log errors, recognizing that returning true inside an empty operation pool is a valid transaction scenario.

Fixes # (if there's an issue number, add it here, otherwise you can leave blank or delete this line)

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested

The server was natively compiled and executed on a Kubuntu Desktop system. Stayed running in the idle loop with a clean and loaded OTBM database configuration without establishing any client connections. The log spam ceased completely while the server ran flawlessly.

  • Server boot & idle monitoring tracking active logs.

Test Configuration:

  • Server Version: 3.4.2 (Canary Latest)
  • Client: None connected.
  • Operating System: Kubuntu Linux

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I checked the PR checks reports
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works

Summary by CodeRabbit

  • Bug Fixes

    • Made online player status handling more robust by validating query results and ensuring cleanup only runs when appropriate.
  • Chores

    • Updated development configuration to include previously ignored temporary and plan files so they are now tracked.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 3, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 38b43d67-bdac-4c64-8523-7216c93689e1

📥 Commits

Reviewing files that changed from the base of the PR and between df9cc8c and 58ea388.

📒 Files selected for processing (2)
  • .gitignore
  • src/game/game.cpp
💤 Files with no reviewable changes (1)
  • .gitignore
✅ Files skipped from review due to trivial changes (1)
  • src/game/game.cpp

📝 Walkthrough

Walkthrough

Removed two .gitignore patterns (/plan, /enc_temp_folder) and simplified Game::updatePlayersOnline by removing the changesMade flag, adding null-checks for DB query results, conditioning DELETE on result existence and count, and making the transaction handler always return true.

Changes

Cohort / File(s) Summary
VCS ignore list
/.gitignore
Removed ignore entries for /plan and /enc_temp_folder.
Game logic
src/game/game.cpp
Refactored Game::updatePlayersOnline: removed changesMade flag, added null-safety before using query result, only DELETEs when result exists and count > 0, and the transaction now always returns true.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nibble through the commit tonight,
Two ignores gone, the DB checks light.
No flags to chase, no nulls to fear,
The transaction hums, steady and clear. 🐇✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: online players count' is directly related to the main change: fixing a log-spam bug in Game::updatePlayersOnline by correcting error handling when the player count is zero.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/game/game.cpp`:
- Around line 11310-11314: The code is treating a null `result` from `SELECT
COUNT(*)` as success; change the `players_online` refresh logic so a null
`result` is treated as a read failure (do not proceed to delete on failed read),
log or propagate the error, and ensure the caller return (the unconditional
`true` at the other location) reflects failure when the read or subsequent
`g_database().executeQuery("DELETE FROM `players_online`;")` fails; specifically
update the block that checks `result`/`getNumber<int>("count")` and the
surrounding flow so `!result` triggers an error path (and the function returns
false or bubbles the error) and only when `count > 0` and the delete query
succeeds do you consider the refresh successful (use the result of
`g_database().executeQuery` to decide success).
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 897a4d08-d262-40af-8e4a-33a5990b0356

📥 Commits

Reviewing files that changed from the base of the PR and between cf383cd and df9cc8c.

📒 Files selected for processing (2)
  • .gitignore
  • src/game/game.cpp

Copy link
Copy Markdown
Contributor

@vllsystems vllsystems left a comment

Choose a reason for hiding this comment

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

Before:
image

After:

Image

@majestyotbr majestyotbr changed the title Fix online players count fix: online players count Apr 3, 2026
Copy link
Copy Markdown
Contributor

@beats-dh beats-dh left a comment

Choose a reason for hiding this comment

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

Code Review

Problema Original

Quando o servidor não tem jogadores online, result->getNumber<int>("count") é chamado sem verificar se result é nulo (possível crash/UB). Além disso, a lambda retornava false via changesMade quando não havia mudanças, fazendo executeWithinTransaction retornar false e gerando spam de [error] Failed to update players online — mesmo sendo um cenário válido.

O null-check adicionado no result é correto e necessário. Porém, existem alguns problemas na abordagem atual:


1. return true incondicional mascara falhas reais

A remoção de changesMade e o return true incondicional fazem com que qualquer falha de DB (ex: stmt.execute(), executeQuery()) seja ignorada — a transação é commitada e reportada como sucesso mesmo sem ter feito nada.

O problema original era apenas que changesMade ficava false no cenário legítimo de "nenhum jogador online e nenhum registro stale". A correção deveria distinguir entre "nada a fazer (sucesso)" e "operação falhou (erro)".

Sugestão para o branch m_players.empty():

if (m_players.empty()) {
    auto result = g_database().storeQuery("SELECT COUNT(*) AS count FROM players_online;");
    if (!result) {
        return false; // Query falhou de verdade
    }
    int count = result->getNumber<int>("count");
    if (count > 0) {
        return g_database().executeQuery("DELETE FROM `players_online`;");
    }
    return true; // Nenhum registro stale — sucesso legítimo
}

E para o branch else, verificar retornos das operações de DB:

if (!stmt.execute()) {
    return false;
}
// ...
if (!g_database().executeQuery(cleanupQuery.str())) {
    return false;
}
return true;

2. Resultado nulo de storeQuery ignorado silenciosamente

Quando result é nullptr (query falhou), o código atual simplesmente pula o bloco e retorna true. Isso significa que dados stale em players_online nunca seriam limpos, e o sistema reportaria sucesso. Deveria retornar false para sinalizar a falha.

3. .gitignore fora de escopo

As adições de canary-debug e .vscode/launch.json são mudanças de ambiente local que não têm relação com o fix de players online. Recomendo separar em outro commit/PR para manter o histórico limpo.


Resumo

Aspecto Avaliação
Null-check no result ✅ Correto e necessário
return true incondicional ❌ Mascara falhas reais de DB
Falha de query silenciosa ⚠️ Deveria retornar false
.gitignore no mesmo PR ⚠️ Fora de escopo

O PR resolve o sintoma (log spam) mas a abordagem de return true incondicional troca um problema visível (logs) por um invisível (falhas silenciosas). Sugiro retornar true apenas nos cenários legitimamente "sem ação necessária" e propagar false quando operações de DB falharem.


Generated by Claude Code

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 4, 2026

Ellectroma added a commit to Ellectroma/canary_fork that referenced this pull request Apr 4, 2026
Resolved conflict in .gitignore: kept HEAD's /plan, /enc_temp_folder, and
staticdatahouse.dat entries which PR opentibiabr#3904 predated.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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.

4 participants