<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Tyutin on Medium]]></title>
        <description><![CDATA[Stories by Alexander Tyutin on Medium]]></description>
        <link>https://medium.com/@alexander.tyutin?source=rss-22d3d3a90fc3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WLEnuSKRs5GWN4G-VRojkw.png</url>
            <title>Stories by Alexander Tyutin on Medium</title>
            <link>https://medium.com/@alexander.tyutin?source=rss-22d3d3a90fc3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:00:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexander.tyutin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Git Autocompletion not Working on MacOS]]></title>
            <link>https://medium.com/@alexander.tyutin/git-autocompletion-not-working-on-macos-536da574591b?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/536da574591b</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[zsh]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Thu, 21 May 2026 04:34:49 GMT</pubDate>
            <atom:updated>2026-05-21T04:34:49.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Some time ago I moved on another MacBook and found that git autocompletion was not working there (Tahoe 26).</p><p>I was frustrating and reading long manuals about fixing the problem. But thanks the <a href="https://stackoverflow.com/questions/24513873/git-tab-completion-not-working-in-zsh-on-mac">old article on StackOverflow</a> I fixed the problem just in one line:</p><pre>echo &#39;autoload -Uz compinit &amp;&amp; compinit&#39; &gt;&gt; ~/.zshrc &amp;&amp; . ~/.zshrc</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=536da574591b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini Thinking: How “Brainy” Models Unexpectedly Blew My Budget]]></title>
            <link>https://medium.com/@alexander.tyutin/gemini-thinking-how-brainy-models-unexpectedly-blew-my-budget-9414d72447b4?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9414d72447b4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 08:01:32 GMT</pubDate>
            <atom:updated>2026-04-13T08:01:32.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="How gemini thinking was spending my money" src="https://cdn-images-1.medium.com/max/1024/1*num6KUerEO5hFry237dfUQ.png" /></figure><p>Recently, Google notified me that the <strong>Gemini 2.0</strong> models I was using are retiring. This was disappointing because my <a href="https://t.me/oqytu_bot">charity project for Technovation Girls</a>, worked perfectly and very cheaply on those models.</p><figure><img alt="gemini 2.0 retirement letter" src="https://cdn-images-1.medium.com/max/800/0*jguZ9nEstUxKWEJJ.png" /></figure><p>I had to find a replacement. While Google recommended <strong>Gemini 3.0</strong>, those models are still in “preview”. Since my project needs high stability, I chose the <strong>Gemini 2.5</strong> family, which is already in “General Availability”.</p><h3>The Surprise: Why is it so Slow and Expensive?</h3><p>Switching was easy because I built my platform to handle model changes and fallbacks automatically. I simply updated my allowed models list and set <strong>gemini-2.5-flash-lite</strong> as the primary choice.</p><p>However, I was shocked by the results:</p><ul><li>Requests took much longer to finish.</li><li>The quality was barely better.</li><li><strong>Token usage exploded</strong>.</li><li>I saw a massive “system overhead” in my logs.</li></ul><p><strong>Before:</strong></p><figure><img alt="ai gateway tokens logging" src="https://cdn-images-1.medium.com/max/262/0*CQCUiPRvzjRUJ4K4.png" /></figure><p><strong>After:</strong></p><figure><img alt="ai gateway tokens counting" src="https://cdn-images-1.medium.com/max/326/0*Vh3twI6_GMu-NAWj.png" /></figure><h3>The Cause: “Thinking” by Default</h3><p>After digging into the documentation, I found the reason: <strong>all Gemini 2.5 models are “thinking” models</strong>. By default, they use as many tokens as possible to “reason” before answering.</p><p>My project worked great without this extra thinking. The slight quality boost was not worth the massive increase in latency and cost. I had to find a way to stop the model from thinking “on my dime”.</p><h3>The Technical Hurdle</h3><p>I <a href="https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking">discovered</a> that different models have different minimum “thinking budgets”. Surprisingly, <strong>gemini-2.5-flash-lite</strong> has a higher minimum budget (512 tokens) than the more powerful <strong>gemini-2.5-flash</strong> (only 1 token!).</p><p>ModelMin Thinking Budget<strong>Gemini 2.5 Flash Lite</strong>512 tokens<strong>Gemini 2.5 Flash</strong>1 token<strong>Gemini 2.5 Pro</strong>128 tokens</p><p>To fix this, I had to expand my code to calculate and limit these budgets during fallbacks. I also had to handle the new text constants (MINIMAL, MEDIUM, HIGH) used by the Gemini 3.x models.</p><pre>&quot;gemini-2.5-flash-lite&quot;: {<br>           &quot;model_page&quot;: f&quot;{_MODEL_GEMINI_DOCS_BASE}/gemini/2-5-flash-lite&quot;,<br>           &quot;is_thinking&quot;: True,<br>           &quot;grounding_rag&quot;: True,<br>           &quot;grounding_google_search&quot;: True,<br>           &quot;count_tokens&quot;: True,<br>           &quot;supports_thinking_level&quot;: False,<br>           &quot;supports_thinking_budget&quot;: True,<br>           &quot;min_thinking_budget&quot;: 512,<br>           &quot;outputs&quot;: [&quot;text&quot;],<br>       },<br>&quot;gemini-2.5-flash&quot;: {<br>           &quot;model_page&quot;: f&quot;{_MODEL_GEMINI_DOCS_BASE}/gemini/2-5-flash&quot;,<br>           &quot;is_thinking&quot;: True,<br>           &quot;grounding_rag&quot;: True,<br>           &quot;grounding_google_search&quot;: True,<br>           &quot;count_tokens&quot;: True,<br>           &quot;supports_thinking_level&quot;: False,<br>           &quot;supports_thinking_budget&quot;: True,<br>           &quot;min_thinking_budget&quot;: 1,<br>           &quot;outputs&quot;: [&quot;text&quot;],<br>       },<br>&quot;gemini-2.5-pro&quot;: {<br>           &quot;model_page&quot;: f&quot;{_MODEL_GEMINI_DOCS_BASE}/gemini/2-5-pro&quot;,<br>           &quot;is_thinking&quot;: True,<br>           &quot;grounding_rag&quot;: True,<br>           &quot;grounding_google_search&quot;: True,<br>           &quot;count_tokens&quot;: True,<br>           &quot;supports_thinking_level&quot;: False,<br>           &quot;supports_thinking_budget&quot;: True,<br>           &quot;min_thinking_budget&quot;: 128,<br>           &quot;outputs&quot;: [&quot;text&quot;],<br>       },</pre><h3>The Result</h3><p>I finally switched to <strong>gemini-2.5-flash</strong> with a strict limit of <strong>50 thinking tokens</strong>.</p><figure><img alt="ai gateway tokens economy" src="https://cdn-images-1.medium.com/max/296/0*BgbjTMLC0yzVXsR1.png" /></figure><p>Now, response speeds are back up and costs are back down. It was a lot of unexpected work for a “simple” upgrade, but everything is running smoothly again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9414d72447b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Links: Antigravity, Gemini, Google Cloud Platform]]></title>
            <link>https://medium.com/@alexander.tyutin/useful-links-antigravity-gemini-google-cloud-platform-88370e23962b?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/88370e23962b</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[google-antigravity]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 11:21:39 GMT</pubDate>
            <atom:updated>2026-04-16T13:37:07.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Cp3Hs1zqYMGbHfCK9y8cw.png" /><figcaption>Useful Links: Antigravity, Gemini, Google Cloud Platform</figcaption></figure><h3>Antigravity</h3><ul><li><a href="https://github.com/harikrishna8121999/antigravity-workflows/tree/main">Antigravity Workflows</a> by <a href="https://github.com/harikrishna8121999">harikrishna8121999</a> — A collection of intelligent workflows that teach AI coding assistants how to perform tasks — without assuming your tech stack.</li><li><a href="https://github.com/BehiSecc/VibeSec-Skill">VibeSec-Skill</a> by <a href="https://github.com/BehiSecc">BehiSecc</a> — An AI skill that brings 5+ years of bug bounty hunting experience directly into your AI coding workflow — so LLM models write secure code from the start.</li><li><a href="https://dev.to/gdg/ai-powered-repository-security-check-with-antigravity-workflow-5hee">AI-Powered Repository Security Check with Antigravity Workflow</a> — Article and video demo about Antigravity workflow for automated repository security check.</li><li><a href="https://dev.to/gdg/antigravity-my-approach-to-deliver-the-most-assured-value-for-the-least-money-3iip">Antigravity: My Approach to Deliver the Most Assured Value for the Least Money</a> — Description of an assured AI-assisted development process.</li><li><a href="https://dev.to/alexandertyutin/using-opencode-as-a-fallback-agent-for-antigravity-37oo">Using OpenCode as a fallback agent for Antigravity</a> — Short story how the <a href="https://opencode.ai/">OpenCode</a> can be connected to Antigravity without any problems.</li><li><a href="https://dev.to/gdg/architecture-documentation-as-a-first-class-engineering-asset-4a1j">Architecture Documentation as a First-Class Engineering Asset </a>— How I extremely improved quality of code by automated research with Antigravity agent and generated comprehensive architecture documentation during my daily physical exercises.</li></ul><h3>AI Governance</h3><ul><li><a href="https://dev.to/whitehatd/i-checked-13-top-open-source-repos-9-have-zero-ai-agent-config-51k0">crag</a> — Very promising utility which intents to automate AI configs creation based on the repo content.</li></ul><h3>Gemini / Vertex</h3><ul><li><a href="https://dev.to/gdg/gemini-thinking-how-new-brainy-models-unexpectedly-blew-my-budget-1c85">Gemini Thinking: How “Brainy” Models Unexpectedly Blew My Budget </a>— Story about saving tokens by managing thinking budget on thinking models.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88370e23962b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered Repository Security Check with Antigravity Workflow]]></title>
            <link>https://medium.com/@alexander.tyutin/ai-powered-repository-security-check-with-antigravity-workflow-8408eb4d9269?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8408eb4d9269</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[google-antigravity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devsecops]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 07:29:46 GMT</pubDate>
            <atom:updated>2026-04-06T10:04:23.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc_Hm-CNckCEe108tpTJmg.png" /><figcaption>AI-Powered Repository Security Check with Antigravity Workflow</figcaption></figure><p>When teams want to “move fast and break things,” security is often the first thing they forget. I’ve seen a lot over 15 years in the industry. My approach is simple: follow the <strong>Pareto Principle (80/20)</strong>. You want 80% of the security results with just 20% of the work.</p><p>In the AI era, that 20% of work can look like a single command.</p><p>Here is how we built the <a href="https://antigravity.google/docs/rules-workflows">Antigravity workflow</a> that checks the whole repository for security issues in several minutes. It does not cost much and does not use up all the AI’s context window.</p><p>Short video demo made on a real repository:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX0a_hwPxTS8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX0a_hwPxTS8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FX0a_hwPxTS8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/08f9accc398dd88d1cc63796a2381f1b/href">https://medium.com/media/08f9accc398dd88d1cc63796a2381f1b/href</a></iframe><h3>The Initial Stack</h3><p>To get a clear picture of a repository’s health, one tool is not enough. We use a combination of proven, open-source scanners for the beginning:</p><ol><li><a href="https://github.com/gitleaks/gitleaks"><strong>Gitleaks</strong></a>: To find secrets like API keys and tokens.</li><li><a href="https://github.com/semgrep/semgrep"><strong>Semgrep</strong></a>: For SCA and SAST to find bad code patterns and supply chain issues.</li><li><a href="https://github.com/bridgecrewio/checkov"><strong>Checkov</strong></a>: To check IaC security (Docker, Terraform, Kubernetes).</li><li><a href="https://github.com/google/osv-scanner"><strong>OSV-Scanner</strong></a>: For SCA scan.</li></ol><p>Inspecting their results manually takes a lot of time. And if you just send all their raw output directly to an AI, it becomes very expensive and confusing.</p><h3>Token Economy</h3><p>For a security review, the AI doesn’t need to see every test that passed. It doesn’t need to see the full abstract syntax tree. It only needs to know <strong>what is broken, where it is, and why it matters.</strong></p><p>We use jq to remove the extra noise. This minifying step is very important for <strong>Token Economy</strong>.</p><p>To increase the token savings the command (workflow) may be ran with the cheapest Gemini 3 Flash. It is more than enough to receive a high-quality base report. Then the report may be reviewed with more powered models like Gemini 3.1 Pro.</p><h3>Example: Minifying Results</h3><p>Instead of a huge JSON file per tool, we make it small and simple. For example, here are the exact commands we use to make the results smaller:</p><pre>1. `jq &#39;[.[] | {rule: .RuleID, file: .File, line: .StartLine}]&#39; gitleaks-raw.json &gt; gitleaks-min.json`<br>2. `jq &#39;[.results[] | {rule: .check_id, file: .path, line: .start.line, severity: .extra.severity}]&#39; semgrep-raw.json &gt; semgrep-min.json`<br>3. `jq &#39;if type==&quot;array&quot; then map(.results.failed_checks[]) else .results.failed_checks end | [.[]? | {rule: .check_id, file: .file_path, line: .file_line_range}]&#39; checkov-raw.json &gt; checkov-min.json`<br>4. `jq &#39;[.results[]?.packages[]?.vulnerabilities[]? | {rule: .id, file: .package.name, line: &quot;N/A&quot;, severity: ((.database_specific.severity) // &quot;N/A&quot;)}]&#39; osv-raw.json &gt; osv-min.json`</pre><p>By making the data 90% smaller, the AI stays focused on real problems. This makes the check much cheaper.</p><pre>% ls -lh .security-artifacts | awk &#39;{print $5, $9}&#39;<br><br>6.3K checkov-min.json<br>2.6M checkov-rev-004-security-20260401-201110.json<br>2.4K gitleaks-min.json<br>19K gitleaks-rev-004-security-20260401-161824.json<br>19K gitleaks-rev-004-security-20260401-201110.json<br>107B osv-min-rev-001-security-20260406-110805.json<br>11K osv-raw-rev-001-security-20260406-110805.json<br>4.3K semgrep-min.json<br>61K semgrep-rev-004-security-20260401-161824.json<br>38K semgrep-rev-004-security-20260401-201110.json</pre><h3>The “One Command” Workflow</h3><p>We put all these steps into one Antigravity slash command: /review-security-repo.</p><p>When we run it, the agent does exactly this:</p><ul><li><strong>Identifies the environment</strong>: Checks for tools like semgrep, gitleaks, checkov, osv-scannerand jq.</li><li><strong>Executes Raw Scans</strong>: Runs the scanners to get raw logs.</li><li><strong>Applies Minification</strong>: Uses jq to strip massive metadata.</li><li><strong>Synthesizes Findings</strong>: Only reads the small files (gitleaks-min.json, semgrep-min.json, checkov-min.json, osv-min.json).</li><li><strong>Performs Review</strong>: Checks high-risk files to find complex problems that static tools miss.</li><li><strong>Generates an Actionable Report</strong>: Uses a strict Markdown structure instead of a generic summary.</li></ul><h3>Report Structure Snippet</h3><p>The workflow forces the AI to output exactly what we need, like this:</p><pre>### [Severity] - [Vulnerability Name/Rule ID]<br>- **Tool Source:** [Semgrep / Gitleaks / Checkov / Manual Architectural Review]<br>- **Location:** `[File Name]:[Line Number]`<br>- **Business Impact:** [Why this matters]<br>- **Remediation:** <br>  [Actionable, copy-paste code or config fix]</pre><h3>Why This Works</h3><ul><li><strong>Repeatability</strong>: Anyone on the team can check security without being an expert.</li><li><strong>Audit Trail</strong>: Every raw and minified report is moved to .security-artifacts/ so we can track the history.</li><li><strong>Reduced Hallucinations</strong>: Because we give AI only the exact scanner results and small code pieces, it gives real fixes without making things up.</li></ul><h3>Full Workflow Code</h3><p>If you want to try this yourself, here is the complete code for the /review-security-repo workflow:</p><pre>---<br>description: &quot;Security review of the repo&quot;<br>---- <br>Get the current branch name and current timestamp (format: YYYYMMDD-HHMMSS). Define output file as `security-review-[branch-name]-[timestamp].md`.<br>- Check for a `venv` (or `.venv`) directory in the repository root. If found, use its binaries.<br>- Verify if `semgrep`, `gitleaks`, `checkov`, and `jq` are installed. If missing, prompt for installation and pause until confirmed.<br>- Execute local security scanners to capture raw audit trails:<br>  1. `gitleaks detect --source . -v --report-format json --report-path gitleaks-raw.json`<br>  2. `semgrep scan --config auto --json --output semgrep-raw.json`<br>  3. `checkov -d . --quiet --skip-path venv -o json &gt; checkov-raw.json`<br>  4. `osv-scanner -r . --format json &gt; osv-raw.json || true`<br>- Execute `jq` to strip massive metadata, passed checks, and AST dumps, keeping only critical fields to save context tokens:<br>  1. `jq &#39;[.[] | {rule: .RuleID, file: .File, line: .StartLine}]&#39; gitleaks-raw.json &gt; gitleaks-min.json`<br>  2. `jq &#39;[.results[] | {rule: .check_id, file: .path, line: .start.line, severity: .extra.severity}]&#39; semgrep-raw.json &gt; semgrep-min.json`<br>  3. `jq &#39;if type==&quot;array&quot; then map(.results.failed_checks[]) else .results.failed_checks end | [.[]? | {rule: .check_id, file: .file_path, line: .file_line_range}]&#39; checkov-raw.json &gt; checkov-min.json`<br>  4. `jq &#39;[.results[]?.packages[]?.vulnerabilities[]? | {rule: .id, file: .package.name, line: &quot;N/A&quot;, severity: ((.database_specific.severity) // &quot;N/A&quot;)}]&#39; osv-raw.json &gt; osv-min.json`<br>- Read ONLY `gitleaks-min.json`, `semgrep-min.json`, `checkov-min.json`, `osv-min.json`. Filter out false positives based on repository context.<br>- Analyze high-risk architectural files strictly for logical flaws and cross-service least-privilege violations that static tools cannot understand.<br>- Generate the report in `security-review-[branch-name]-[timestamp].md`. DO NOT output generic summary tables. You MUST output an exhaustive, itemized list.<br>- Use the following strict Markdown structure for the report:<br>  ## Executive Summary<br>  [Brief overview of the branch&#39;s security posture]<br>  ## Detailed Findings<br>  [Iterate through EVERY validated finding. For each finding, output:]<br>  ### [Severity] - [Vulnerability Name/Rule ID]<br>  - **Tool Source:** [Semgrep / Gitleaks / Checkov / Manual Architectural Review]<br>  - **Location:** `[File Name]:[Line Number]`<br>  - **Business Impact:** [Why this matters]<br>  - **Remediation:** <br>    [Actionable, copy-paste code or config fix]<br><br>- Create a `.security-artifacts/` directory if it does not exist. Ensure `.security-artifacts/` is appended to `.gitignore`.<br>- Move and rename both raw and minified reports to `.security-artifacts/` to preserve the complete historical audit trail:<br>  - `gitleaks-raw.json` -&gt; `.security-artifacts/gitleaks-raw-[branch-name]-[timestamp].json`<br>  - `semgrep-raw.json` -&gt; `.security-artifacts/semgrep-raw-[branch-name]-[timestamp].json`<br>  - `checkov-raw.json` -&gt; `.security-artifacts/checkov-raw-[branch-name]-[timestamp].json`<br>  - `osv-raw.json` -&gt; `.security-artifacts/osv-raw-[branch-name]-[timestamp].json`<br>  - `gitleaks-min.json` -&gt; `.security-artifacts/gitleaks-min-[branch-name]-[timestamp].json`<br>  - `semgrep-min.json` -&gt; `.security-artifacts/semgrep-min-[branch-name]-[timestamp].json`<br>  - `checkov-min.json` -&gt; `.security-artifacts/checkov-min-[branch-name]-[timestamp].json`<br>  - `osv-min.json` -&gt; `.security-artifacts/osv-min-[branch-name]-[timestamp].json`<br>- Exit execution.</pre><h3>What’s Next?</h3><p><strong>What tools are missing from your perfect “One Command” security check?</strong> Will be happy to receive opinions on how to further optimize the token economy while expanding the security coverage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8408eb4d9269" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Antigravity: My Approach to Deliver the Most Assured Value for the Least Money]]></title>
            <link>https://medium.com/@alexander.tyutin/antigravity-my-approach-to-deliver-the-most-assured-value-for-the-least-money-eaf661a2a26d?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaf661a2a26d</guid>
            <category><![CDATA[antigravity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 06:08:41 GMT</pubDate>
            <atom:updated>2026-04-01T06:08:41.798Z</atom:updated>
            <content:encoded><![CDATA[<p>As I’m not a professional developer but a guy who needs to use automation to get things done, I follow one main rule: keep it simple. Overengineering hurts. I use the Pareto rule — spend 20% of the effort to get 80% of the result.</p><p>When I use AI agents like Antigravity, my goal is not to let the AI write complex code that no one can read. My goal is to build simple, secure features fast. At the same time, I control costs by saving tokens. Here is the exact workflow I use.</p><h3>The Token Economy Strategy</h3><p>LLM tokens cost money. Using a smart, expensive model just to fix code spaces is not worth the cost. I change models based on how hard the task is.</p><ul><li><strong>High-Tier Models:</strong> They are for the big tasks: planning architecture, writing complex business logic, checking security, and counting cloud costs.</li><li><strong>Low-Tier Models:</strong> These folks are for simple tasks: fixing syntax errors, aligning code to Pylint, and writing standard code pieces.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*2fF5Tv3YQVl4Wx8a.png" /></figure><h3>Task Decomposition &amp; In-Repo Architecture</h3><p>Large prompts can break LLMs. If a prompt has too much text, the AI gets confused and wastes tokens. To stop this, I break every task into small, separate pieces so the AI only sees what it needs.</p><p>I store all architecture plans and tasks inside the code repository (for example, ./docs). This keeps the instructions very close to the code for the AI.</p><p>Every task I write uses this strict four-part structure:</p><ol><li><strong>Idea:</strong> The main business or tech goal. <em>Why it matters:</em> It proves the task is useful before I spend tokens for delivering a code to review.</li><li><strong>Plan:</strong> The technical blueprint. <em>Why it matters:</em> It locks down the plan, keeps security high, and stops the AI from inventing bad solutions.</li><li><strong>What Was Done:</strong> A short log of the work. <em>Why it matters:</em> It gives future AI tasks a quick summary, so the AI does not have to read every code file again.</li><li><strong>Debt:</strong> A list of any technical shortcuts or “crutches” used to save time. <em>Why it matters:</em> Hidden debt ruins the project. <strong>Important: My custom Quality Gate checks this section. If it finds unapproved shortcuts in the code, it blocks the release completely.</strong></li></ol><h3>System Instructions for the AI</h3><p>To keep the AI agent aligned with the goals, I pass strict system instructions on every run. It never lets the model guess my coding standards. Here are the core rules enforced:</p><ul><li><strong>No Crutches:</strong> Any “crutch” or technical shortcut must be approved by me. Then, the AI must document it as technical debt in the project files.</li><li><strong>No Inventing Wheels:</strong> I try hard to avoid this. If a working approach already exists in another project, the AI reuses it.</li><li><strong>Learn from the Past:</strong> When building a new service, the AI must check the old tech debt to avoid repeating past mistakes.</li><li><strong>Simple Code Only:</strong> The code structure should just use standard classes. I avoid “genius-level” extreme one-line code tricks or overwhelming structures.</li><li><strong>Maintainability First:</strong> A middle-level, part-time developer must be able to read and maintain the code.</li></ul><h3>The Core Workflow</h3><p>Every feature goes through a step-by-step process. I’m trying to keep security and simplicity as the main focus at each step.</p><h3>1. Plan &amp; Plan Review</h3><p><em>Using a High-Tier Model.</em></p><ul><li><strong>Plan:</strong> Defining the code structure, the security rules, the cost limits, etc. I make sure not to add to old technical debt.</li><li><strong>Review:</strong> I look at the plan with a “fresh eye.” I do not start coding until the plan is clear with main code snippets planned.</li></ul><h3>2. Code &amp; Code Review</h3><p><em>Using a Low or Mid-Tier Model for code and Mid or High-Tier Model for review.</em></p><ul><li><strong>Code:</strong> Implement the code exactly as planned. Use clear classes and avoid complex, one-line code tricks. A middle-level developer must be able to maintain it easily.</li><li><strong>Review:</strong> Make sure the code matches the rest of the project. I prefer another “person” to check it before I call it done.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SomxHwWYC2ulwIQQ.png" /></figure><h3>3. Lint &amp; Quality Gate</h3><p><em>Using Free External Tools &amp; A Custom Nanoservice.</em></p><ul><li><strong>Lint:</strong> I do not pay LLMs to fix missing spaces. I use free tools like autopep8, ruff, and pylint to save tokens.</li><li><strong>Quality Gate:</strong> I built a simple nanoservice using the Vertex API. It checks the code changes against the main branch. It works like an automatic review from the CTO, CISO, and CFO. It checks every line for good architecture, proper security access, and cost impact before the code goes to production. <strong>Why is it so important?</strong> The Quality Gate is not overwhelmed by the full chat history inside the IDE. Its &quot;fresh eye&quot; often finds architectural and coding flaws that were missed by the IDE models, even after 6 to 9 rounds of review.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Oh1dJCT5GFx5iPkI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*sSSb0A0JjqoZm_Za.png" /></figure><h3>The Bottom Line</h3><p>AI coding is not magic. In my experience, it requires a strict testing gate, smart model swapping, and simple design. By owning the process and letting the AI act as a typist, it is possible to ship secure code fast. I share this approach for an open discussion on how we can build better automation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf661a2a26d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NCALayer не работает на MacOS]]></title>
            <link>https://medium.com/@alexander.tyutin/ncalayer-%D0%BD%D0%B5-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82-%D0%BD%D0%B0-macos-e49a3ed8f4a2?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49a3ed8f4a2</guid>
            <category><![CDATA[ncalayer]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[pain]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[manuals]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 09:39:55 GMT</pubDate>
            <atom:updated>2025-12-26T09:48:31.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8YpP3KmvxzmD3odP.png" /></figure><p>Редко, но очень больно, на ровном месте перестаёт работать NCALayer. Ошибок нет, программа запущена, браузеры её не видят.</p><p>Долго гуглю, пробую варианты, потом что-то да срабатывает. Решил записывать, что помогает, потому что каждый раз таблетка разная.</p><h3>1. Удаление файла ncalayer.der</h3><ol><li>Выйти из NCALayer.</li><li>Выполнить команды в консоли:</li></ol><pre>cd ~/Library<br>cd Application\ Support<br>cd NCALayer<br>mv ncalayer.der ncalayer.der.bak</pre><p>3. Запустить NCALayer.</p><p><a href="https://pki.gov.kz/forum/4-dlya-polzovatelej-nuts-rk/4028-ncalayer-ne-zapuskaetsya-limit=6&amp;start=48.html">Источник</a></p><h3>P.S. Документы</h3><ol><li><a href="https://pki.gov.kz/docs/nl_ru/macosx/">Инструкция с pki.gov.kz</a>.</li><li><a href="https://pki.gov.kz/docs/nl_ru/issues/">Официальный troubleshooting</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49a3ed8f4a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Passed PCA+PCNE+PCSE this year]]></title>
            <link>https://medium.com/@alexander.tyutin/passed-pca-pcne-pcse-this-year-e2f566a385df?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f566a385df</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-developer-group]]></category>
            <category><![CDATA[technovation]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 12:05:36 GMT</pubDate>
            <atom:updated>2025-12-23T12:05:36.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Professional Cloud Architect, Professional Cloud Network Engineer and Professional Cloud Security Engineer badges." src="https://cdn-images-1.medium.com/max/1024/1*Q25QDeY5k8Q40vHkxZ7AVA.png" /><figcaption>PCA+PCNE+PCSE</figcaption></figure><p>This year I’ve got a triade:</p><ul><li>PCA — Professional Cloud Architect.</li><li>PCNE — Professional Cloud Network Engineer.</li><li>PCE — Professional Cloud Security Engineer.</li></ul><p>This was an interesting learning journey. I already had 15 years experience at security field but this year I decided to document it through certificates and decided to made it through GCP certifications. Why:</p><ul><li>Worked a lot closely with GCP for last several years.</li><li>Became GDG Organizer this year.</li><li>Ran a charity project using GCP credits for infrastructure.</li><li>Got 2 vouchers for taking Google Exams.</li></ul><h3>Small Recap</h3><ul><li><strong>Security</strong> — Very close to my infrastructure experience. General security background + work experience seem enough to pass. I have been certified as SSCP (by ISC2) many years ago and was learning CISSP course.</li><li><strong>Network</strong> — Awful but funny. A lot of questions like “You have 5 pieces of shit and 3 wooden sticks. Build high-throughoutput low-latency cost-effective easy-to-manage solution and try to save wooden sticks for future tasks”. Decided to take this exam just because of solid hardware networking background and it was interesting to understand the difference between the hardware and cloud networking.</li><li><strong>Architect</strong> — Very interesting but it doesn’t seem for me the work infrastructure experience will be enough for it. Because a lot of concepts are utilizing Cloud Build+Cloud Run, a bit of GKE, and a bit of Compute Engine. So my graal here was the charity project for Technovation Girls Kazakhstan chapter. I’m trying to bring some help to children in their first steps in STEM and also decided to make it using Cloud-First approach over the GCP infrastructure.</li><li><strong>A lot of questions about AI</strong> (Security and Architect). As I know from some emails of a learning group the renewal exam contains much more percentage of AI questions. So it seems there is no way to not learn/use/explore the AI. The AI is not the future. It is our reality.</li></ul><p><strong>Resources which helped me to prepare for exams</strong></p><ul><li><a href="https://gdg.community.dev/gdg-almaty/"><strong>Participation in a local Google Developer Group</strong></a>. It gave me Google Developer Program Premium tier along with an exam voucher (used for PCNE) and USD500 credits for GCP (used to run a charity project which helped to prepare for PCA).</li><li><a href="https://cloud.google.com/innovators/getcertified?hl=en"><strong>Google Cloud Innovators Get Certified program</strong></a>. It gave me a voucher for taking the PCA exam.</li><li><a href="https://www.skills.google/"><strong>Google Skills platform</strong></a>. A lot of labs to try technologies. Free with Google Developer Program Premium tier or literally free in case of entering the Google Cloud Innovators Get Certified cohort.</li><li><a href="https://notebooklm.google.com/"><strong>Notebook LM</strong></a>. It was quite boring to learn just by PDFs from the Google Skills. So I was regularly putting there some PDFs about a specified technology or processes and receiving audio and video podcasts, reports, mindmaps, etc.</li><li><a href="https://technovation.kz/"><strong>Technovation Girls Kazakhstan</strong></a>. Great invaluable project which aims to help schoolgirls to make their first steps in STEM. But also there is a lot of challenges for mentors (who are volunteering there). And those challenges made me moving toward the exams.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f566a385df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Google Cloud Model Armor in Python (and avoid the Common Pitfalls)]]></title>
            <link>https://medium.com/@alexander.tyutin/how-to-implement-google-cloud-model-armor-in-python-and-avoid-the-common-pitfalls-27d4a00a59f4?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d4a00a59f4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-security]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[model-armor]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 17:52:12 GMT</pubDate>
            <atom:updated>2025-12-10T17:57:04.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image for the article." src="https://cdn-images-1.medium.com/max/1024/1*s5_5AGQiw9BsdAXJE-y3TQ.png" /></figure><p>Building Agentic AI is fun until users start trying to break it. Whether it’s <strong>Prompt Injection</strong>, <strong>Jailbreaking</strong>, or simply trying to get your bot to say something it shouldn’t, managing user input is a security nightmare.</p><p>Google Cloud’s <strong>Model Armor</strong> is a new managed service that acts as a safety firewall. It sanitizes <strong>user prompts</strong> before they reach your model <em>and</em> checks model responses, giving you full-spectrum protection.</p><p>While the specific documentation is growing, getting it to work in Python took a bit of trial and error. Here is a working guide on how to integrate Model Armor into your Python application, based on real-world debugging.</p><h3><strong>Installation</strong></h3><p>Grab the official client library:</p><pre>pip install google-cloud-modelarmor</pre><h3><strong>Prerequisites</strong></h3><p>Before writing code, ensure you have:</p><ol><li><strong>Created a Template</strong>: In the Google Cloud Console (Model Armor section), create a template (e.g., my-first-template) in your desired region (e.g., us-central1).</li><li><strong>IAM Permissions</strong>: The Service Account running your code needs the <strong>Model Armor User</strong> role (roles/modelarmor.user). Without this, you will get 403 errors.</li></ol><h3>The Code</h3><p>Here is the minimal, robust implementation.</p><h4><strong>The “Regional Endpoint” Trap</strong></h4><p>The most common issue developers face is a 403 Permission Denied or 404 Not Found error. This happens because Model Armor resources (like Templates) represent regional resources, but the default client connects to the <em>global</em> endpoint.</p><p>You <strong>must</strong> configure the client to talk to the specific regional endpoint (e.g., modelarmor.us-central1.rep.googleapis.com). You can check available regions and endpoints on the official <a href="https://docs.cloud.google.com/model-armor/reference/rest?rep_location=us-central1#regional-service-endpoint">Model Armor Troubleshooting page</a>.</p><pre>import os<br>from google.cloud import modelarmor_v1<br>from google.api_core import client_options<br><br># Configuration<br>PROJECT_ID = &quot;your-project-id&quot;<br>REGION = &quot;us-central1&quot;<br>TEMPLATE_ID = &quot;my-first-template&quot;<br><br>def get_armor_client():<br>    &quot;&quot;&quot;<br>    Initializes the Model Armor client with the correct REGIONAL endpoint.<br>    Crucial: The default global endpoint will often fail for regional templates.<br>    &quot;&quot;&quot;<br>    # unexpected keyword argument &#39;name&#39; or 403 errors often stem from <br>    # hitting the wrong endpoint or using the wrong client configuration.<br>    <br>    # Correct Endpoint Format: modelarmor.REGION.rep.googleapis.com<br>    api_endpoint = f&quot;modelarmor.{REGION}.rep.googleapis.com&quot;<br>    <br>    opts = client_options.ClientOptions(api_endpoint=api_endpoint)<br>    return modelarmor_v1.ModelArmorClient(client_options=opts)<br><br>def inspect_prompt(text: str):<br>    client = get_armor_client()<br>    <br>    # Full resource name for the template<br>    template_name = f&quot;projects/{PROJECT_ID}/locations/{REGION}/templates/{TEMPLATE_ID}&quot;<br>    <br>    # Wrap arguments in a Request object<br>    request = modelarmor_v1.SanitizeUserPromptRequest(<br>        name=template_name,<br>        user_prompt_data=modelarmor_v1.DataItem(text=text)<br>    )<br><br>    try:<br>        response = client.sanitize_user_prompt(request=request)<br>        <br>        # Check the result<br>        result = response.sanitization_result<br>        if result.filter_match_state == modelarmor_v1.FilterMatchState.MATCH_FOUND:<br>            print(f&quot;⚠️ Blocked! Reason: {result}&quot;)<br>            return False<br>        <br>        print(&quot;✅ Safe to proceed.&quot;)<br>        return True<br><br>    except Exception as e:<br>        print(f&quot;Error checking prompt: {e}&quot;)<br>        # Best practice: Fail open (allow) or closed depending on your risk profile<br>        return True<br><br>def verify_response(text: str):<br>    &quot;&quot;&quot;<br>    Checks the LLM&#39;s response for PII or harmful content.<br>    &quot;&quot;&quot;<br>    client = get_armor_client()<br>    template_name = f&quot;projects/{PROJECT_ID}/locations/{REGION}/templates/{TEMPLATE_ID}&quot;<br>    <br>    request = modelarmor_v1.SanitizeModelResponseRequest(<br>        name=template_name,<br>        model_response_data=modelarmor_v1.DataItem(text=text)<br>    )<br><br>    try:<br>        response = client.sanitize_model_response(request=request)<br>        result = response.sanitization_result<br>        if result.filter_match_state == modelarmor_v1.FilterMatchState.MATCH_FOUND:<br>            print(f&quot;⚠️ Response Blocked! Reason: {result}&quot;)<br>            return False<br>            <br>        print(&quot;✅ Response is safe.&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error verifying response: {e}&quot;)<br>        return True</pre><h3><strong>Key Takeaways</strong></h3><ol><li><strong>Use </strong><strong>ClientOptions</strong>: Always set the api_endpoint to match your template’s region. The format is modelarmor.REGION.rep.googleapis.com.</li><li><strong>Request Objects</strong>: Use SanitizeUserPromptRequest for inputs and SanitizeModelResponseRequest for outputs. Don’t just pass keywords.</li><li><strong>Permissions</strong>: Ensure your runtime identity has roles/modelarmor.user.</li><li><strong>Full Loop Safety</strong>: Don’t just check inputs. Checking responses protects you if your model gets tricked or hallucinates something unsafe.</li></ol><p>Happy safe prompting!</p><h3>Further reading</h3><ul><li><a href="https://docs.cloud.google.com/model-armor">Official Model Armor documentation</a>.</li><li><a href="https://docs.cloud.google.com/model-armor/reference/rest?rep_location=global">Official Model Armor API documentation</a>.</li><li><a href="https://docs.cloud.google.com/python/docs/reference/google-cloud-modelarmor/latest">Python client for Model Armor API page</a>.</li><li><a href="https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-modelarmor/samples/generated_samples">A lot of Model Armor usage samples from Google</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d4a00a59f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running a Production-Ready Webhook Telegram Bot on Google Cloud Run: A Security-First Approach]]></title>
            <link>https://medium.com/@alexander.tyutin/running-a-production-ready-webhook-telegram-bot-on-google-cloud-run-a-security-first-approach-57b589ff8e48?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/57b589ff8e48</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-build]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 14:03:07 GMT</pubDate>
            <atom:updated>2025-12-04T14:03:07.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image for Running a Production-Ready Webhook Telegram Bot on Google Cloud Run: A Security-First Approach" src="https://cdn-images-1.medium.com/max/1024/1*IqlWB5eDRxI-KhPpgVpYIA.png" /><figcaption>Small research during an interesting project.</figcaption></figure><h3><strong>Introduction</strong></h3><p>Building a Telegram bot is straightforward, but running it securely and efficiently in production requires careful consideration. In this guide, I’ll walk you through deploying a webhook-based Telegram bot on Google Cloud Run, focusing on three critical aspects: asynchronous operations, resource management, and security hardening.</p><p>This isn’t just theory — it’s a battle-tested approach refined through real-world deployment challenges.</p><h3><strong>Why Cloud Run?</strong></h3><p>Cloud Run offers serverless container execution with:</p><ul><li><strong>Pay-per-use pricing</strong>: You only pay when handling requests.</li><li><strong>Auto-scaling</strong>: From 0 to N instances based on load.</li><li><strong>Managed infrastructure</strong>: No server maintenance.</li><li><strong>Built-in security</strong>: IAM, Secret Manager integration, VPC support</li></ul><p>For a Telegram bot receiving sporadic messages, this translates to near-zero costs during idle periods.</p><h3><strong>Architecture Overview</strong></h3><pre>Telegram API → Cloud Run (Webhook) → Bot Application<br>                        ↓<br>                 Cloud Logging<br>                 Secret Manager</pre><h3><strong>Key Design Decisions:</strong></h3><ol><li><strong>Webhook over polling</strong>: More efficient, no constant connections.</li><li><strong>Async framework</strong>: Quart + python-telegram-bot for non-blocking I/O.</li><li><strong>Minimal container</strong>: Single-layer Docker image &lt;200MB.</li><li><strong>Authorization-first</strong>: Filter requests before processing.</li></ol><h3><strong>Part 1: Asynchronous Operations</strong></h3><p><strong>The Challenge</strong></p><p>Cloud Run containers must start quickly and handle requests efficiently. Synchronous operations block the event loop, wasting resources and increasing latency.</p><p><strong>The Solution: Quart + Async Handlers</strong></p><p><strong>Why Quart?</strong> It’s Flask’s async cousin — familiar syntax, native async support.</p><pre># main.py<br>from quart import Quart, request, jsonify<br>from telegram import Update<br>from telegram.ext import Application, CommandHandler, MessageHandler, filters<br><br>app = Quart(__name__)<br>bot_app = None<br><br>@app.before_serving<br>async def startup():<br>  &quot;&quot;&quot;Initialize bot once at container startup&quot;&quot;&quot;<br>  global bot_app<br>  bot_app = Application.builder().token(TOKEN).build()<br><br>  # Register handlers<br>  bot_app.add_handler(CommandHandler(&quot;start&quot;, start_handler))<br>  bot_app.add_handler(MessageHandler(filters.TEXT, message_handler))<br><br>  # Initialize connection to Telegram<br>  await bot_app.initialize()<br><br>@app.route(&quot;/webhook&quot;, methods=[&#39;POST&#39;])<br>async def webhook():<br>  &quot;&quot;&quot;Handle incoming Telegram updates&quot;&quot;&quot;<br>  data = await request.get_json(force=True)<br>  update = Update.de_json(data, bot_app.bot)<br><br>  # Process asynchronously<br>  await bot_app.process_update(update)<br>  return jsonify({&#39;status&#39;: &#39;ok&#39;})</pre><p><strong>Critical Pattern:</strong> Initialize the bot application <strong>once</strong> at startup ( @app.before_serving), not per request. This reuses the HTTP connection pool and avoids event loop conflicts.</p><h4><strong>Preventing Backlog Processing</strong></h4><p>When a container restarts, Telegram may send old queued updates. Process them and you’ll spam users with outdated responses.</p><pre>from datetime import datetime, timezone<br><br>@app.route(&quot;/webhook&quot;, methods=[&#39;POST&#39;])<br>async def webhook():<br>  data = await request.get_json(force=True)<br>  update = Update.de_json(data, bot_app.bot)<br><br>  # Reject old updates<br>  if update.effective_message:<br>    msg = update.effective_message<br>    event_date = msg.edit_date or msg.date<br>    age = (datetime.now(timezone.utc) - event_date).total_seconds()<br><br>    if age &gt; 120: # Ignore messages older than 2 minutes<br>      logger.warning(f&quot;Skipping old update {update.update_id} (age: {age:.1f}s)&quot;)<br>      return jsonify({&#39;status&#39;: &#39;ok&#39;, &#39;skipped&#39;: &#39;too_old&#39;})<br><br>  await bot_app.process_update(update)<br>  return jsonify({&#39;status&#39;: &#39;ok&#39;})</pre><h3><strong>Part 2: Resource Management</strong></h3><p><strong>Minimal Container Footprint</strong></p><p>Cloud Run charges for CPU and memory. Every MB counts.</p><p><strong>Dockerfile:</strong></p><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br># Single-layer copy for efficiency<br>COPY requirements.txt main.py cloud_logger.py auth.py config.py ./<br><br>RUN pip install - no-cache-dir -r requirements.txt<br><br># Cloud Run sets PORT automatically<br>CMD exec uvicorn main:app - host 0.0.0.0 - port $PORT - workers 1</pre><p><strong>Key optimizations:</strong></p><ul><li>python:3.11-slim : 50% smaller than full image.</li><li>--no-cache-dir : Removes pip cache (~100MB saved).</li><li>Single COPY layer: Faster builds.</li><li>exec uvicorn : Proper signal handling for graceful shutdown.</li></ul><h4><strong>Cloud Run Configuration</strong></h4><pre># cloudbuild.yaml (excerpt)<br>...<br>gcloud run deploy my-bot \<br> - memory=128Mi \ # Minimal for simple bots<br> - concurrency=1 \ # One request per container (webhook pattern)<br> - min-instances=0 \ # Scale to zero when idle<br> - max-instances=2 \ # Prevent runaway costs<br> - cpu=0.08 \ # Fractional CPU (80m)<br> - timeout=60s<br>...</pre><p><strong>Why concurrency=1?</strong> Telegram webhooks are sequential per chat. Multiple concurrent requests would just queue internally. Save resources by limiting to 1.</p><h4><strong>Smart Caching with Cloud Build</strong></h4><p>Rebuilding on every code change wastes time and money. Hash-based caching to the rescue:</p><pre># Calculate hash of source files only<br>SOURCE_HASH=$(find . -type f \( -name &quot;*.py&quot; -o -name &quot;requirements.txt&quot; \) \<br>-exec sha256sum {} \; | sort | sha256sum | cut -c1–12)<br><br>IMAGE_URI=&quot;region-docker.pkg.dev/project/repo/bot:${SOURCE_HASH}&quot;<br><br># Check if image exists<br>if docker manifest inspect $IMAGE_URI &gt; /dev/null 2&gt;&amp;1; then<br>  echo &quot;Image exists, skipping build&quot;<br>else<br>  docker build -t $IMAGE_URI .<br>  docker push $IMAGE_URI<br>fi</pre><p><strong>Result:</strong> Documentation changes don’t trigger rebuilds. Only code changes do.</p><h3><strong>Part 3: Security Hardening</strong></h3><p><strong>Layer 1: Webhook Secret Validation</strong></p><p>Telegram sends a custom header with each webhook request. Validate it <strong>before</strong> processing.</p><pre>@app.route(&quot;/webhook&quot;, methods=[&#39;POST&#39;])<br>async def webhook():<br>  # Validate secret token<br>  token = request.headers.get(&#39;X-Telegram-Bot-Api-Secret-Token&#39;)<br><br>  if token != SECRET_TOKEN:<br>    return jsonify({&#39;error&#39;: &#39;Unauthorized&#39;}), 401<br>  <br>  # Process update…</pre><p><strong>Setup:</strong></p><pre># Generate strong secret<br>SECRET=$(openssl rand -hex 32)<br><br># Set webhook with secret<br>curl -X POST &quot;https://api.telegram.org/bot${BOT_TOKEN}/setWebhook&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &quot;{\&quot;url\&quot;: \&quot;https://your-service.run.app/webhook\&quot;, \&quot;secret_token\&quot;: \&quot;${SECRET}\&quot;}&quot;</pre><p><strong>Layer 2: User/Group Authorization</strong></p><p>If you do not want everybody to use the bot implement allowlisting:</p><pre># config.py<br>ALLOWED_USER_IDS = [<br>  123456789, # Your Telegram user ID<br>]<br><br>ALLOWED_GROUP_IDS = [<br>  -987654321, # Your group chat ID<br>]<br><br><br># auth.py<br>from telegram import Update<br><br>def is_authorized(update: Update) -&gt; bool:<br>  user = update.effective_user<br>  chat = update.effective_chat<br><br>  if user and user.id in ALLOWED_USER_IDS:<br>    if chat and chat.id in ALLOWED_GROUP_IDS:<br>      return True<br><br>  logger.warning(f&quot;Unauthorized: User {user.id}, Chat {chat.id}&quot;)<br>  return False<br><br><br># main.py<br>async def message_handler(update: Update, context):<br>  if not is_authorized(update):<br>    return # Silently ignore<br>  <br>  # Process message…</pre><p><strong>Finding IDs:</strong> Send /start to your bot and check logs, or use @userinfobot on Telegram.</p><h3><strong>Layer 3: Secret Manager Integration</strong></h3><p>Never hardcode credentials. Use Google Secret Manager.</p><pre># cloudbuild.yaml<br>gcloud run deploy my-bot \<br> - service-account=bot-runtime-sa@project.iam.gserviceaccount.com \<br> - set-secrets=TELEGRAM_BOT_TOKEN=TELEGRAM_BOT_TOKEN:latest,\<br>WEBHOOK_SECRET_TOKEN=WEBHOOK_SECRET_TOKEN:latest</pre><p><strong>Required IAM permissions:</strong></p><pre># Runtime service account<br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:bot-runtime-sa@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/secretmanager.secretAccessor&quot;<br><br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:bot-runtime-sa@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/logging.logWriter&quot;<br><br># Cloud Build deployer service account<br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:cloudbuild-deployer@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/run.developer&quot;<br><br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:cloudbuild-deployer@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/iam.serviceAccountUser&quot;<br><br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:cloudbuild-deployer@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/artifactregistry.writer&quot;<br><br>gcloud projects add-iam-policy-binding PROJECT_ID \<br> --member=&quot;serviceAccount:cloudbuild-deployer@PROJECT_ID.iam.gserviceaccount.com&quot; \<br> --role=&quot;roles/logging.logWriter&quot;</pre><h3><strong>Layer 4: Obfuscated Webhook Path</strong></h3><p>Don’t use /webhook. Use a SHA-256 hash to prevent scanning:</p><pre>WEBHOOK_PATH=&quot;/$(echo -n &quot;my-secret-salt&quot; | sha256sum | cut -c1–32)&quot;<br># Result: /a1b2c3d4e5f6…</pre><p>Store in Secret Manager and reference in your app:</p><pre>WEBHOOK_PATH = os.environ.get(&quot;WEBHOOK_PATH&quot;, &quot;/webhook&quot;)<br><br>@app.route(WEBHOOK_PATH, methods=[&#39;POST&#39;])<br>async def webhook():<br>  # …</pre><h3><strong>Layer 5: Cloud Logging with Custom Format</strong></h3><p>Centralized logging is critical for security monitoring and debugging.</p><pre># cloud_logger.py<br>import logging<br>import os<br>from google.cloud import logging as cloudlogging<br><br>LOG_FORMAT = &#39;[%(asctime)s] [%(levelname)s] [%(name)s] [%(filename)s:%(lineno)d] %(message)s&#39;<br><br>def get_logger():<br>  logger = logging.getLogger(&quot;cloudLogger&quot;)<br>  logger.setLevel(logging.INFO)<br>  <br>  # Use Cloud Logging in production<br>  if os.getenv(&quot;ENVIRONMENT&quot;) == &quot;production&quot;:<br>    try:<br>      log_client = cloudlogging.Client()<br>      handler = log_client.get_default_handler()<br>      handler.setFormatter(logging.Formatter(LOG_FORMAT))<br>      logger.addHandler(handler)<br>      return logger<br>    except Exception as e:<br>      print(f&quot;Cloud Logging failed: {e}&quot;)<br><br>  # Fallback to local logging<br>  handler = logging.StreamHandler()<br>  handler.setFormatter(logging.Formatter(LOG_FORMAT))<br>  logger.addHandler(handler)<br>  <br>  return logger<br><br>logger = get_logger()</pre><p><strong>Why custom format?</strong> Cloud Logging’s default format lacks file/line info. This format gives you full context for debugging.</p><h3><strong>Bonus: Group Chat Privacy Mode</strong></h3><p>By default, bots in groups only receive:</p><ul><li>Messages starting with /command .</li><li>Messages mentioning @bot_name .</li><li>Replies to bot messages.</li></ul><p>To receive <strong>all</strong> messages (for monitoring/analytics):</p><ol><li>Open BotFather.</li><li>/mybots → Select your bot.</li><li><strong>Bot Settings</strong> → <strong>Group Privacy</strong> → <strong>Turn off </strong>.</li><li>Remove and re-add bot to groups.</li></ol><p>Then implement routing:</p><pre># Custom filter for mentions<br>class BotMentionFilter(filters.MessageFilter):<br><br>  def filter(self, message):<br>    if not message.text or not message.entities:<br>      return False<br>    return any(e.type == &quot;mention&quot; for e in message.entities)<br><br>bot_mention_filter = BotMentionFilter()<br><br># Route mentions to active handler<br>bot_app.add_handler(MessageHandler(<br>  filters.TEXT &amp; bot_mention_filter &amp; ~filters.COMMAND,<br>  handle_mention<br>))<br><br># Route regular messages to passive handler<br>bot_app.add_handler(MessageHandler(<br>  filters.TEXT &amp; ~bot_mention_filter &amp; ~filters.COMMAND,<br>  handle_regular_message<br>))</pre><h3><strong>Deployment Pipeline</strong></h3><p>Automate everything with Cloud Build:</p><pre># cloudbuild.yaml<br><br>steps:<br>- id: &#39;build-and-push&#39;<br>  name: &#39;gcr.io/cloud-builders/docker&#39;<br>  entrypoint: bash<br>  args:<br>    - &#39;-c&#39;<br>    - |<br>      SOURCE_HASH=$(find . -type f \( -name &quot;*.py&quot; -o -name &quot;requirements.txt&quot; -o -name &quot;Dockerfile&quot; \) \<br>      -exec sha256sum {} \; | sort | sha256sum | cut -c1–12)<br>      IMAGE_URI=&quot;YOUR_REGION_HERE-docker.pkg.dev/$PROJECT_ID/repo/bot:$$SOURCE_HASH&quot;<br>      if docker manifest inspect $$IMAGE_URI &gt; /dev/null 2&gt;&amp;1; then<br>        echo &quot;Image exists, skipping build&quot;<br>      else<br>        docker build -t $$IMAGE_URI .<br>        docker push $$IMAGE_URI<br>      fi<br>      echo -n &quot;$$IMAGE_URI&quot; &gt; _IMAGE_NAME<br><br>  - id: &#39;deploy&#39;<br>    name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>    entrypoint: bash<br>    args:<br>    - &#39;-c&#39;<br>    - |<br>      gcloud run deploy my-bot \<br>       - image=$(cat _IMAGE_NAME) \<br>       - region=YOUR_REGION_HERE \<br>       - memory=128Mi \<br>       - concurrency=1 \<br>       - min-instances=0 \<br>       - max-instances=2 \<br>       - cpu=0.08 \<br>       - service-account=bot-runtime-sa@$PROJECT_ID.iam.gserviceaccount.com \<br>       - set-env-vars=ENVIRONMENT=production \<br>       - set-secrets=TELEGRAM_BOT_TOKEN=TELEGRAM_BOT_TOKEN:latest,\<br>      WEBHOOK_SECRET_TOKEN=WEBHOOK_SECRET_TOKEN:latest,\<br>      WEBHOOK_PATH=WEBHOOK_PATH:latest<br><br>serviceAccount: &#39;projects/$PROJECT_ID/serviceAccounts/cloudbuild-deployer@$PROJECT_ID.iam.gserviceaccount.com&#39;</pre><p><strong>Trigger:</strong> Push to main branch.</p><h3><strong>Testing Locally</strong></h3><pre># Install dependencies<br>pip install -r requirements.txt<br><br># Set environment variables<br>export TELEGRAM_BOT_TOKEN=&quot;your_token&quot;<br>export WEBHOOK_SECRET_TOKEN=&quot;your_secret&quot;<br>export WEBHOOK_PATH=&quot;/webhook&quot;<br>export ENVIRONMENT=&quot;local&quot;<br><br># Run<br>python main.py<br><br># Set webhook (use ngrok for local testing)<br>ngrok http 8080<br>curl -X POST &quot;https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &quot;{\&quot;url\&quot;: \&quot;https://your-ngrok-url.ngrok.io${WEBHOOK_PATH}\&quot;, \&quot;secret_token\&quot;: \&quot;${WEBHOOK_SECRET_TOKEN}\&quot;}&quot;</pre><h3><strong>Common Pitfalls</strong></h3><h4><strong>1. Event Loop Conflicts</strong></h4><p><strong>Problem: </strong>RuntimeError: Event loop is closed</p><p><strong>Solution:</strong> Don’t create new event loops. Use Quart’s async context and initialize bot once at startup.</p><h4><strong>2. Memory Leaks</strong></h4><p><strong>Problem:</strong> Container OOM after hours of operation</p><p><strong>Solution:</strong> Ensure proper cleanup in @app.after_serving:</p><pre>@app.after_serving<br>async def shutdown():<br>  if bot_app:<br>    await bot_app.shutdown()</pre><h4><strong>Conclusion</strong></h4><p>Running a Telegram bot on Cloud Run combines serverless efficiency with enterprise-grade security. The key takeaways:</p><ol><li><strong>Async everywhere</strong>: Quart + python-telegram-bot for non-blocking I/O.</li><li><strong>Minimal resources</strong>: 128Mi memory, fractional CPU, scale-to-zero.</li><li><strong>Defense in depth</strong>: Webhook secrets, user authorization, Secret Manager, obfuscated paths.</li><li><strong>Observability</strong>: Cloud Logging with custom format for debugging</li></ol><p>This architecture handles thousands of messages/day while costing like a coffee per month. The same patterns scale to complex bots with AI integrations, database operations, and external API calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57b589ff8e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crutch Factory— Conditional build in Cloud build on specified file changes]]></title>
            <link>https://medium.com/@alexander.tyutin/crutch-factory-conditional-build-in-cloud-build-on-specified-file-changes-a266644632f2?source=rss-22d3d3a90fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a266644632f2</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-build]]></category>
            <dc:creator><![CDATA[Alexander Tyutin]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 17:01:09 GMT</pubDate>
            <atom:updated>2025-11-27T17:01:39.861Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Conditional build in Cloud build on specified file changes</strong></h3><figure><img alt="Funny image with crutch." src="https://cdn-images-1.medium.com/max/1024/1*tkbxKSGPk_V1L83SUagmAA.jpeg" /></figure><p>Cloud Build is a powerful tool for CI/CD, but out of the box, it can be a bit “eager.” If you configure it to run on every push to your main branch, it will faithfully rebuild your Docker images every single time — even if you only changed a README file, updated a comment in your cloudbuild.yaml, or tweaked a memory limit setting.</p><p>This redundancy isn’t just annoying; it costs money and slows down your deployment pipeline.</p><p>In my recent project, I faced exactly this issue. I wanted to tweak deployment configurations (like memory limits or environment variables) without waiting 2 minutes for a Docker build that produced the exact same image as the last run.</p><p>Here is how I optimized my Cloud Build pipeline to <strong>skip the build step</strong> if the application code hasn’t changed, reducing pipeline duration from <strong>1m 32s</strong> to just <strong>42s</strong>.</p><h4><strong>The Strategy: Content-Based Hashing</strong></h4><p>Instead of tagging images with the standard $BUILD_ID or $COMMIT_SHA (which change on every run or commit), we tag the image with a <strong>hash of the actual source code</strong>.</p><p>If the code ( *.py, Dockerfile, requirements.txt) hasn’t changed, the hash remains the same. If the hash is the same, the image already exists in the registry, and we can skip the build entirely.</p><h4><strong>The Implementation</strong></h4><p>We need to replace the standard `docker build` step with a shell script that performs the logic.</p><h4><strong>1. The Smart Build Step</strong></h4><p>In your `cloudbuild.yaml`, replace your build step with this:</p><pre>  - name: &#39;gcr.io/cloud-builders/docker&#39;<br>    entrypoint: &#39;bash&#39;<br>    args:<br>      - &#39;-c&#39;<br>      - |<br>        # Calculate hash of relevant source files<br>        # This ignores changes to cloudbuild.yaml, .md files, etc.<br>        SOURCE_HASH=$(find . -type f \( -name &quot;*.py&quot; -o -name &quot;requirements.txt&quot; -o -name &quot;Dockerfile&quot; \) -exec sha256sum {} \; | sort | sha256sum | cut -d&#39; &#39; -f1 | cut -c1-12)<br>        <br>        echo &quot;Calculated Source Hash: $$SOURCE_HASH&quot;<br>        <br>        IMAGE_URI=&quot;$REGION-docker.pkg.dev/$PROJECT_ID/$DOCKER_REPO/my-cloud-run-app-image:$$SOURCE_HASH&quot;<br>        LATEST_URI=&quot;$REGION-docker.pkg.dev/$PROJECT_ID/$DOCKER_REPO/my-cloud-run-app-image:latest&quot;<br>        <br>        # Save image name for the deploy step<br>        echo -n &quot;$$IMAGE_URI&quot; &gt; _IMAGE_NAME<br>        <br>        echo &quot;Checking if image exists: $$IMAGE_URI&quot;<br>        <br>        if docker manifest inspect $$IMAGE_URI &gt; /dev/null 2&gt;&amp;1; then<br>          echo &quot;✅ Image $$IMAGE_URI already exists. Skipping build.&quot;<br>        else<br>          echo &quot;🚀 Image not found. Building...&quot;<br>          docker build -t $$IMAGE_URI -t $$LATEST_URI .<br>          docker push $$IMAGE_URI<br>          docker push $$LATEST_URI<br>        fi<br>    id: &#39;build-and-push&#39;</pre><h4><strong>2. The Dynamic Deployment Step</strong></h4><p>Since we don’t know the image tag ahead of time (it’s calculated dynamically), we can’t hardcode it in the deployment step. We need to read it from the _IMAGE_NAME file we created earlier.</p><pre>  - name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>    entrypoint: &#39;bash&#39;<br>    args:<br>      - &#39;-c&#39;<br>      - |<br>        IMAGE_NAME=$$(cat _IMAGE_NAME)<br>        echo &quot;Deploying image: $$IMAGE_NAME&quot;<br>        <br>        gcloud run deploy my-cloud-run-app \<br>          --image=$$IMAGE_NAME \<br>          --region=$REGION \<br>          ...<br>          --project=$PROJECT_ID<br>    id: &#39;deploy-run-service&#39;<br>    waitFor: [&#39;build-and-push&#39;]</pre><h4><strong>The “Gotcha”: Escaping Variables</strong></h4><p>You might notice the double dollar signs ( $$SOURCE_HASH, $$IMAGE_URI). This is crucial!</p><p>Cloud Build tries to substitute variables like $PROJECT_ID before running the step. If you use a single dollar sign for your shell variables (like $$SOURCE_HASH), Cloud Build will try to replace them, fail to find a substitution, and crash your build with an error like:</p><pre>invalid value for &#39;build.substitutions&#39;: key in the template &quot;SOURCE_HASH&quot; is not a valid built-in substitution</pre><p>Using $$tells Cloud Build to treat it as a literal $character, allowing the bash shell to handle the variable.</p><h4><strong>The Result</strong></h4><p>By implementing this logic, the pipeline behavior changed dramatically:</p><p>1. <strong>First Run (Code Change):</strong> The script calculates a new hash, sees the image is missing, builds it, pushes it, and deploys. <strong>Time: ~1m 30s</strong>.</p><p>2. <strong>Second Run (Config Change):</strong> I updated the memory limit in cloudbuild.yaml. The script calculated the <em>same</em> hash, found the image in the registry, skipped the build, and went straight to deployment. <strong>Time: 42s</strong>.</p><p>This simple optimization cuts feedback loops in half and saves on build minutes, keeping your pipeline lean and cost-effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a266644632f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>