Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Стек вызовов в информации об ошибке фонового задания #1487

Merged
merged 3 commits into from
Jan 17, 2025

Conversation

sfaqer
Copy link
Contributor

@sfaqer sfaqer commented Jan 14, 2025

  1. Добавлен стек вызовов в информацию об ошибке фонового задания
  2. В КоллекцияКадровСтекаВызовов добавлен метод Количество()
  3. КоллекцияКадровСтекаВызовов сделана индексированной коллекцией

Summary by CodeRabbit

  • New Features

    • Enhanced error handling with additional context in exceptions.
    • Added ability to count and access stack frames programmatically.
    • Improved execution frame retrieval mechanism to ensure accurate local variable access.
  • Tests

    • Introduced a new test to validate call stack information in error scenarios.

These updates enhance error reporting and stack trace management capabilities, providing users with better insights during exceptions.

Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request introduces enhancements to error handling and stack trace management in the OneScript library. The changes focus on improving exception context capture, adding stack trace collection capabilities, and modifying the machine instance to create full call stacks. These modifications provide more detailed debugging information by enriching error handling mechanisms and enabling better introspection of execution frames.

Changes

File Change Summary
src/OneScript.StandardLibrary/Tasks/BackgroundTask.cs Enhanced error handling by capturing execution frames in ScriptException
src/ScriptEngine/Machine/Contexts/StackTraceCollectionContext.cs Added methods and properties for stack frame counting and indexed access
src/ScriptEngine/Machine/MachineInstance.cs Updated GetExecutionFrames() to create and cache full call stack
tests/tasks.os Added new test procedure to verify call stack information in error scenarios

Possibly related PRs

Poem

🐰 A Rabbit's Tale of Stack and Trace

In code's deep warren, frames unfurl,
Exceptions dance, their secrets swirl,
With context rich and debug might,
Our script now leaps to greater height!

🔍✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 985c65d and 21ca850.

📒 Files selected for processing (4)
  • src/OneScript.StandardLibrary/Tasks/BackgroundTask.cs (1 hunks)
  • src/ScriptEngine/Machine/Contexts/StackTraceCollectionContext.cs (2 hunks)
  • src/ScriptEngine/Machine/MachineInstance.cs (1 hunks)
  • tests/tasks.os (2 hunks)
🔇 Additional comments (5)
src/ScriptEngine/Machine/Contexts/StackTraceCollectionContext.cs (2)

33-40: LGTM! Well-documented Count() method.

The implementation is clean and the XML documentation clearly describes the purpose and return value.


48-48: LGTM! IsIndexed property enables frame access by index.

The property correctly indicates that the collection supports indexed access.

src/OneScript.StandardLibrary/Tasks/BackgroundTask.cs (1)

114-114: LGTM! Enhanced error information with call stack.

The change correctly captures the execution frames during exception handling, improving error diagnostics.

Run the following script to verify the integration with MachineInstance:

✅ Verification successful

Verified: GetExecutionFrames integration is correct and consistent

The method is properly integrated with MachineInstance and follows the established patterns for error handling and debugging across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that MachineInstance.GetExecutionFrames() is called during exception handling.

# Test: Search for other usages of GetExecutionFrames() to ensure consistent error handling.
rg -A 5 $'GetExecutionFrames'

Length of output: 2262

tests/tasks.os (1)

268-282: LGTM! Comprehensive test coverage for call stack in error information.

The test thoroughly validates:

  • Stack trace collection type
  • Number of frames
  • Frame details including method name, line number, and module name
src/ScriptEngine/Machine/MachineInstance.cs (1)

2454-2454: LGTM! Ensures call stack is populated before access.

The change correctly ensures that the full call stack is created before being returned, supporting the enhanced error reporting functionality.

2. В КоллекцияКадровСтекаВызовов добавлен метод Количество()
3. КоллекцияКадровСтекаВызовов сделана индексированной коллекцией
@sfaqer sfaqer force-pushed the feature/bgTasksCallStack branch from 21ca850 to 01b44b5 Compare January 14, 2025 05:35
@@ -2451,6 +2451,7 @@ private IValue PopRawValue()

public IList<ExecutionFrameInfo> GetExecutionFrames()
{
CreateFullCallstack();
Copy link
Owner

Choose a reason for hiding this comment

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

Вот это кажется перформанс критикал будет. На каждый конверт из ссылки в сырое значение делать стек...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Я не совсем понимаю о чём ты говоришь.
image

Вот в приведённых вызовах который из это "конверт из ссылки в сырое значение" ?

Copy link
Owner

Choose a reason for hiding this comment

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

Прошу прощения, тупанул. UI гитхаба скрывает то, что написано выше, и отображает серым, а там метод PopRawValue. И я подумал, что мы в этот опкод добавили CreateFullStack

Copy link

@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: 0

🧹 Nitpick comments (1)
tests/tasks.os (1)

275-290: Consider making the test more robust.

While the test implementation is functional, there are a few areas that could be improved:

  1. The hard-coded line number 45 makes the test fragile. If ПроцедураСИсключением is modified, this test will break.
  2. The assumption of exactly one frame in the stack trace might be too restrictive.
  3. Missing verification of error state before accessing the stack trace.

Consider this improved implementation:

 Процедура ТестДолжен_ПроверитьЧтоВИнформацииОбОшибкеЕстьСтекВызовов() Экспорт

 	Задание = ФоновыеЗадания.Выполнить(ЭтотОбъект, "ПроцедураСИсключением");
 	Задание.ОжидатьЗавершения();
+
+	юТест.ПроверитьРавенство(СостояниеФоновогоЗадания.ЗавершеноАварийно, Задание.Состояние);
 
 	СтекВызовов = Задание.ИнформацияОбОшибке.ПолучитьСтекВызовов();
 
 	юТест.ПроверитьТип(СтекВызовов, "КоллекцияКадровСтекаВызовов");
 
-	юТест.ПроверитьРавенство(СтекВызовов.Количество(), 1);
+	юТест.ПроверитьБольшеИлиРавно(СтекВызовов.Количество(), 1);
 
 	юТест.ПроверитьРавенство(СтекВызовов[0].Метод, "ПроцедураСИсключением");
-	юТест.ПроверитьРавенство(СтекВызовов[0].НомерСтроки, 45);
+	юТест.ПроверитьЗаполненность(СтекВызовов[0].НомерСтроки);
 	юТест.ПроверитьРавенство(СтекВызовов[0].ИмяМодуля, ТекущийСценарий().Источник);
 
 КонецПроцедуры
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01b44b5 and aa8a930.

📒 Files selected for processing (1)
  • tests/tasks.os (2 hunks)
🔇 Additional comments (2)
tests/tasks.os (2)

27-27: LGTM!

The new test is properly added to the test list, following the existing naming convention.


280-280: Verify stack trace collection functionality.

Let's ensure that the stack trace collection is properly implemented in the codebase.

✅ Verification successful

Stack trace collection implementation verified

The stack trace collection is properly implemented in the core ExceptionInfoContext and consistently used across debug adapter, runtime engine, and test infrastructure. The implementation handles both successful and failure cases appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of stack trace collection in error handling.

# Check for the stack trace collection method implementation
ast-grep --pattern 'ПолучитьСтекВызовов'

# Check for stack trace usage in error handling
rg -l "ПолучитьСтекВызовов|GetStackTrace" -g "*.{cs,os}"

Length of output: 417


Script:

#!/bin/bash
# Check the implementation of stack trace collection in ExceptionInfoContext
rg -A 10 "ПолучитьСтекВызовов|GetStackTrace" src/ScriptEngine/Machine/Contexts/ExceptionInfoContext.cs

Length of output: 577

@@ -2451,6 +2451,7 @@ private IValue PopRawValue()

public IList<ExecutionFrameInfo> GetExecutionFrames()
{
CreateFullCallstack();
Copy link
Owner

Choose a reason for hiding this comment

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

Прошу прощения, тупанул. UI гитхаба скрывает то, что написано выше, и отображает серым, а там метод PopRawValue. И я подумал, что мы в этот опкод добавили CreateFullStack

@EvilBeaver
Copy link
Owner

@sfaqer просьба пофиксить вот эти 2 теста https://build.oscript.io/blue/organizations/jenkins/1Script/detail/PR-1487/3/tests

…фонового задания, НомерСтроки теперь проверяется на заполненность, чтобы тест не падал при добавлении новых тестов.
Copy link

@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: 0

🧹 Nitpick comments (1)
tests/tasks.os (1)

275-290: Consider enhancing test coverage with complex call stacks.

The current test verifies a simple call stack with one frame. Consider adding test cases that verify:

  1. Nested method calls resulting in deeper call stacks
  2. Additional frame properties if available in the КадрСтекаВызовов type

Example enhancement:

+Процедура ВложеннаяПроцедура() Экспорт
+    ВызватьИсключение "Ошибка из вложенной процедуры";
+КонецПроцедуры
+
+Процедура ПроцедураСВложеннымИсключением() Экспорт
+    ВложеннаяПроцедура();
+КонецПроцедуры
+
 Процедура ТестДолжен_ПроверитьЧтоВИнформацииОбОшибкеЕстьСтекВызовов() Экспорт
-    Задание = ФоновыеЗадания.Выполнить(ЭтотОбъект, "ПроцедураСИсключением");
+    // Проверка простого стека вызовов
+    Задание = ФоновыеЗадания.Выполнить(ЭтотОбъект, "ПроцедураСИсключением");
     Задание.ОжидатьЗавершения();
 
     СтекВызовов = Задание.ИнформацияОбОшибке.ПолучитьСтекВызовов();
@@ ... @@
+    // Проверка вложенного стека вызовов
+    Задание = ФоновыеЗадания.Выполнить(ЭтотОбъект, "ПроцедураСВложеннымИсключением");
+    Задание.ОжидатьЗавершения();
+
+    СтекВызовов = Задание.ИнформацияОбОшибке.ПолучитьСтекВызовов();
+    юТест.ПроверитьРавенство(СтекВызовов.Количество(), 2);
+    юТест.ПроверитьРавенство(СтекВызовов[0].Метод, "ВложеннаяПроцедура");
+    юТест.ПроверитьРавенство(СтекВызовов[1].Метод, "ПроцедураСВложеннымИсключением");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa8a930 and 6ae2564.

📒 Files selected for processing (1)
  • tests/tasks.os (2 hunks)
🔇 Additional comments (2)
tests/tasks.os (2)

27-27: LGTM!

The test registration follows the established naming convention and is appropriately grouped with other error-related tests.


275-290: LGTM! Well-structured test implementation.

The test is well-implemented with comprehensive assertions covering the call stack type, frame count, and frame properties.

@sfaqer
Copy link
Contributor Author

sfaqer commented Jan 16, 2025

@sfaqer просьба пофиксить вот эти 2 теста https://build.oscript.io/blue/organizations/jenkins/1Script/detail/PR-1487/3/tests

image

=)

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.

2 participants