Skip to content

Add ordered pair format (<</>>) for Relations Model JSON representation#13

Open
konard wants to merge 4 commits into
netkeep80:masterfrom
konard:issue-10-bf572fdeec6d
Open

Add ordered pair format (<</>>) for Relations Model JSON representation#13
konard wants to merge 4 commits into
netkeep80:masterfrom
konard:issue-10-bf572fdeec6d

Conversation

@konard
Copy link
Copy Markdown
Contributor

@konard konard commented Feb 27, 2026

Summary

Implements the second JSON representation format for the Relations Model based on the mathematical triplet-as-nested-ordered-pairs notation, as requested in issue #10.

Problem

The Relations Model currently only supports one JSON format for entities:
```json
{
"$rel": "",
"$obj": "",
"$sub": ""
}
```

Solution

Added a second equivalent format based on the mathematical representation of a triplet as nested ordered pairs: ent = (rel, (obj, sub))

```json
{
"<<": "",
">>": {
"<<": "",
">>": ""
}
}
```

Field mapping between formats

Format 1 (named) Format 2 (ordered pair) Role
$rel << Relation-controller (Controller)
$obj >>/<< Object-model (Model)
$sub >>/>> Subject-view (View)

Changes

  • modules/common/include/vm.rm.h: Added parsing of <</>> ordered pair format in exec_ent(). When a JSON object contains a << key (but not $rel), it is interpreted as the new ordered pair format.
  • doc/relations-model-ru.md: Documented both formats with a comparison table (Russian)
  • doc/relations-model-en.md: Documented both formats with a comparison table (English)
  • modules/console/test/ordered_pair_format.json: Test file for ordered pair format (version entity)
  • modules/console/test/ordered_pair_format_where.json: Test file for ordered pair format (where filter)
  • modules/console/test/main.cpp: Two new test cases verifying the new format works correctly
  • examples/ordered_pair_format.json: Example demonstrating the new format

Test plan

  • Build succeeds without errors
  • All existing tests pass (7/7)
  • New test: testing ordered pair format (<</>>) - version — verifies {"<<": "rmvm/version"} returns "3.0.0"
  • New test: testing ordered pair format (<</>>) - where filter — verifies the full (rel, (obj, sub)) triplet form works with real entity

Fixes #10

🤖 Generated with Claude Code

konard and others added 2 commits February 27, 2026 16:07
Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: netkeep80#10
Implements the second JSON representation format for the Relations Model
based on the mathematical triplet-as-nested-ordered-pairs notation:
  ent = (rel, (obj, sub))

New format uses << and >> keys instead of $rel, $obj, $sub:
  {
    "<<": "<relation-controller>",
    ">>": {
      "<<": "<object-model>",
      ">>": "<subject-view>"
    }
  }

Changes:
- vm.rm.h: Added parsing of << / >> ordered pair format in exec_ent()
- doc/relations-model-ru.md: Document both formats with comparison table
- doc/relations-model-en.md: Document both formats with comparison table
- modules/console/test/: Add test JSON files and test cases
- examples/: Add example showing ordered pair format usage

Closes netkeep80#10

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@konard konard changed the title [WIP] Разработка нового формата представления Модели отношений в JSON Add ordered pair format (<</>>) for Relations Model JSON representation Feb 27, 2026
@konard konard marked this pull request as ready for review February 27, 2026 16:15
@konard
Copy link
Copy Markdown
Contributor Author

konard commented Feb 27, 2026

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $2.629779
  • Calculated by Anthropic: $2.287200 USD
  • Difference: $-0.342579 (-13.03%)
    📎 Log file uploaded as Gist (2278KB)
    🔗 View complete solution draft log

Now working session is ended, feel free to review and add any feedback on the solution draft.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Feb 27, 2026

🔄 Auto-restart 1/3

Detected uncommitted changes from previous run. Starting new session to review and commit them.

Uncommitted files:

?? cpp-files.txt
?? doc-relations.txt
?? find-files.txt
?? git-diff-stat.txt
?? git-diff.txt
?? git-log.txt
?? issue-10-comments.txt
?? issue-10.txt
?? ls-doc.txt
?? ls-root.txt
?? out-arm.txt
?? out-arm2.txt
?? out-arm3.txt
?? out-arm4.txt
?? out-json-def.txt
?? out-relations-en.txt
?? out-relations-ru.txt
?? out-rm.txt
?? pr-13-comments.txt
?? pr-13-review-comments.txt
?? pr-13.txt

Auto-restart will stop after changes are committed or after 2 more iterations. Please wait until working session will end and give your feedback.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Feb 27, 2026

🔄 Auto-restart 1/3 Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $0.418369
  • Calculated by Anthropic: $0.329294 USD
  • Difference: $-0.089075 (-21.29%)
    📎 Log file uploaded as Gist (3107KB)
    🔗 View complete solution draft log

Now working session is ended, feel free to review and add any feedback on the solution draft.

@netkeep80
Copy link
Copy Markdown
Owner

Сделай code review всего проекта.

@konard konard marked this pull request as draft March 20, 2026 01:24
@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

🤖 AI Work Session Started

Starting automated work session at 2026-03-20T01:24:19.924Z

The PR has been converted to draft mode while work is in progress.

This comment marks the beginning of an AI work session. Please wait for the session to finish, and provide your feedback.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

📋 Code Review всего проекта

Выполнен полный обзор кода проекта jsonRVM, включая изменения в PR #13 (ordered pair format).


✅ Что сделано хорошо

  1. Архитектура ядра (vm.rm.h) — элегантная рекурсивная виртуальная машина. Дизайн exec_ent с pattern-matching по типам JSON (string, array, object, primitive) — чистый и расширяемый.

  2. Контекст выполнения (vm_ctx) — иерархическая модель контекстов с rel/obj/sub/ent и родительской ссылкой $ — компактная реализация стекового фрейма для VM.

  3. PR Add ordered pair format (<</>>) for Relations Model JSON representation #13: Ordered pair format — реализация <</>> формата корректна:

    • Правильно интегрирована в цепочку if-else if в exec_ent() (после $ref и $rel, перед lambda-структурой)
    • Корректная обработка отсутствующего >> — obj/sub наследуются из родительского контекста
    • Хорошее покрытие тестами: и простой случай (version), и сложный (where с вложенными $ref)
  4. Документация — обе версии (RU/EN) обновлены синхронно с таблицей соответствия форматов.

  5. Базовый словарь (base.rm.h) — богатый набор встроенных операций: математика, строки, управление потоком, XML/HTML генерация.


⚠️ Замечания и рекомендации

1. Потокобезопасность (Critical)

vm.rm.h:600-627 — параллельное выполнение через std::execution::par:

for_each(std::execution::par, vct.begin(), vct.end(), callctx_thread);

Мьютексы __object_mutex, __array_mutex, __null_mutex защищают только ref_in_json_to (lval-запись). Но exec_ent модифицирует $.rel, $.obj, $.sub без синхронизации. Если параллельные потоки обращаются к общему контексту (а callctx_thread создаёт ctx с $.obj, $.sub из общего родителя), возможны data races.

Рекомендация: Добавить документацию об ограничениях параллельного выполнения, или рассмотреть более строгую синхронизацию.

2. Использование deprecated API (string_utils.h:83-98)

std::wstring_convert<std::codecvt_utf8<wchar_t>>

std::wstring_convert и std::codecvt_utf8 deprecated начиная с C++17. На Linux это ещё работает, но компилятор может выдавать warnings.

Рекомендация: Для Linux-версии (где CP1251 не нужен) достаточно просто передавать строку as-is, что уже и делается в utf8_to_cp1251/cp1251_to_utf8. Функции utf8_to_wstring/wstring_to_utf8 можно убрать если они не используются в Linux-сборке.

3. Двойной #pragma once (string_type.h:33-34)

#pragma once
#pragma once

Незначительно, но дублирование.

4. using namespace std в заголовочном файле (string_utils.h:36)

using namespace std;

using namespace в header-файле загрязняет глобальное пространство имён для всех включающих файлов. Лучше использовать std:: prefix или перенести using внутрь namespace.

5. CMakeLists.txt — несогласованность имён опций (Root CMakeLists.txt:29-32)

option( ENABLE_TEST "Enable integration test target build" OFF )
if( ENABLE_TESTS )  # <-- с "S" на конце!
    add_subdirectory( tests )
endif()

Опция определена как ENABLE_TEST (без S), но проверяется как ENABLE_TESTS (с S). Директория tests/ никогда не будет добавлена.

6. Windows-специфичный путь в main.cpp:87

file_database_t db(".\\");

На Linux обратный слэш не является разделителем пути. Лучше использовать "./".

7. database_api — рекурсивный вызов через CRTP (database_api.h:44-46)

virtual void get_entity(json &ent, const string &ent_id) { this->impl().get_entity(ent, ent_id); }

Если наследник не переопределит get_entity, будет бесконечная рекурсия (impl() вернёт *this, get_entity вызовет себя). Это защищено тем, что impl() может вернуть nullptr exception, но архитектурно неочевидно.

8. Unsafe reinterpret_cast для генерации ID (file_database.h:94, test/main.cpp:66)

ent_id = to_string(reinterpret_cast<size_t>(&ent));

Адрес объекта как ID работает только в рамках одного процесса и не гарантирует уникальность при повторном использовании памяти.

9. Тестовый код — char* вместо const char* (test/main.cpp)

char* fileNameInput = "ordered_pair_format.json";

Присвоение строкового литерала в char* (non-const) deprecated в C++ и вызывает warning на многих компиляторах. Должно быть const char*.

10. Отсутствие CI для сборки/тестов

Проект имеет только CI для Doxygen (GitHub Pages) и Rocq proofs. Нет workflow для сборки C++ кода и запуска тестов. Это означает, что регрессии не будут обнаружены автоматически.

Рекомендация: Добавить GitHub Actions workflow для CMake build + CTest.


📝 По PR #13 конкретно

Реализация ordered pair формата корректна и хорошо интегрирована. Несколько мелких наблюдений:

  1. Приоритет форматов$ref > $rel > << > lambda. Это правильный порядок. Но стоит задокументировать: что произойдёт если объект содержит и $rel, и << одновременно? (Ответ: $rel имеет приоритет — это правильно).

  2. Обработка >> без << — если объект содержит только >> без <<, он попадёт в lambda-ветку (параллельное выполнение). Это корректное поведение, но стоит добавить в документацию.

  3. Тест ordered_pair_format_where.json — хороший тест, использующий $ref внутри ordered pair формата, проверяющий совместимость форматов.


🏁 Итог

Проект имеет чистую архитектуру с оригинальной концепцией VM на JSON. PR #13 добавляет requested feature корректно. Основные области для улучшения: потокобезопасность, CI pipeline, и мелкие issues с кросс-платформенностью.

🤖 Code review выполнен Claude Code

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@konard konard marked this pull request as ready for review March 20, 2026 01:27
@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $4.067607
  • Calculated by Anthropic: $1.543438 USD
  • Difference: $-2.524168 (-62.06%)

🤖 Models used:

  • Tool: Claude
  • Requested: opus
  • Main model: Claude Opus 4.6 (ID: claude-opus-4-6, Anthropic, cutoff: 2025-05)
    📎 Log file uploaded as Gist (750KB)
    🔗 View complete solution draft log

Now working session is ended, feel free to review and add any feedback on the solution draft.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

🔄 Auto-restart 1/3

Detected uncommitted changes from previous run. Starting new session to review and commit or discard them.

Uncommitted files:

?? build-output.log
?? cmake-output.log
?? pr-diff.txt
?? test-output.log

Auto-restart will stop after changes are committed or discarded, or after 2 more iterations. Please wait until working session will end and give your feedback.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

🔄 Auto-restart 1/3 Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $1.130741
  • Calculated by Anthropic: $0.520577 USD
  • Difference: $-0.610163 (-53.96%)

🤖 Models used:

  • Tool: Claude
  • Requested: opus
  • Main model: Claude Opus 4.6 (ID: claude-opus-4-6, Anthropic, cutoff: 2025-05)
    📎 Log file uploaded as Gist (1092KB)
    🔗 View complete solution draft log

Now working session is ended, feel free to review and add any feedback on the solution draft.

@konard
Copy link
Copy Markdown
Contributor Author

konard commented Mar 20, 2026

✅ Ready to merge

This pull request is now ready to be merged:

  • CI workflows exist but were not triggered for this commit
  • No merge conflicts
  • No pending changes

Monitored by hive-mind with --auto-restart-until-mergeable flag

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.

Разработка нового формата представления Модели отношений в JSON

2 participants