Choosing the Right Treasure Map to Avoid Data Decay in Veltrix

The Problem We Were Actually Solving

We thought we were solving the classic event-sourcing problem – storing and replaying events from a distributed system to ensure data consistency. Sounds simple, right? In theory, yes, but in practice, it’s a minefield. The event store has to be designed to handle a high volume of events, and our system was built on top of a MongoDB instance with a collection optimized for writing events. Sounds okay, but what we didn’t realize was that our event schema would evolve rapidly due to changing business requirements.

What We Tried First (And Why It Failed)

Our initial approach was to store events in an unsharded, denormalized collection with a single field for each event attribute. We thought this would speed up queries and avoid costly joins, but we soon realized that our event volume would exceed MongoDB’s performance limits, causing our system to slow down significantly. To make matters worse, our unsharded collection caused uneven distribution of writes, leading to hotspots and eventual data inconsistencies.

The Architecture Decision

After several weeks of troubleshooting, we made a critical decision to switch to a sharded, normalized schema with separate collections for each event type and date range. This change allowed us to distribute write load more evenly among shards, reducing the risk of hotspots and ensuring consistent data across the system. We also decided to implement a caching layer to minimize the number of queries hitting the event store directly.

What The Numbers Said After

With the new schema in place, event write latency dropped from 250ms to 30ms, and we were able to handle 10 times the number of events per second without any issues. Our average query latency decreased from 200ms to 10ms, and we managed to reduce data inconsistencies to a negligible level. MongoDB’s performance monitoring showed that our write load was now evenly distributed across shards, and no single shard was experiencing heavy load.

What I Would Do Differently

If I were to redo this project, I would make sure to account for our event schema evolution from the beginning. Our original schema was too rigid, and we had to undergo a costly migration to adapt to the changing business requirements. In hindsight, I would have opted for a more flexible schema design that could accommodate growth and changes without requiring a major overhaul. We also over-engineered our caching layer, which introduced additional complexity without providing significant performance benefits. A simpler caching strategy would have served us better.

The truth is, our initial approach to building the Treasure Hunt Engine on Veltrix was flawed from the start. We didn’t account for the complexity of our event schema, and our system suffered the consequences. By sharing my story, I hope to educate other engineers about the importance of considering the long-term implications of their design decisions and the perils of premature optimization.

Migrating to Apache Iceberg: Strategies for Every Source System

Three paths to Iceberg: in-place migration, full rewrite, and shadow migration

This is Part 15, the final article of a 15-part Apache Iceberg Masterclass. Part 14 covered hands-on Dremio Cloud. This article covers the three migration strategies and how to execute a zero-downtime migration using the view swap pattern.

Most organizations do not start with Iceberg. They have years of data in Hive tables, data warehouses, CSV files, databases, and Parquet directories. Moving this data to Iceberg is not an all-or-nothing project. The best migrations happen incrementally, one dataset at a time, with no disruption to existing consumers.

Table of Contents

  1. What Are Table Formats and Why Were They Needed?
  2. The Metadata Structure of Current Table Formats
  3. Performance and Apache Iceberg’s Metadata
  4. Technical Deep Dive on Partition Evolution
  5. Technical Deep Dive on Hidden Partitioning
  6. Writing to an Apache Iceberg Table
  7. What Are Lakehouse Catalogs?
  8. Embedded Catalogs: S3 Tables and MinIO AI Stor
  9. How Iceberg Table Storage Degrades Over Time
  10. Maintaining Apache Iceberg Tables
  11. Apache Iceberg Metadata Tables
  12. Using Iceberg with Python and MPP Engines
  13. Streaming Data into Apache Iceberg Tables
  14. Hands-On with Iceberg Using Dremio Cloud
  15. Migrating to Apache Iceberg

Three Migration Strategies

Three paths to Iceberg: in-place migration, full rewrite, and shadow migration

1. In-Place Migration (Metadata Only)

In-place migration creates Iceberg metadata over existing Parquet or ORC files without copying or moving them. The data files stay exactly where they are; only new Iceberg metadata is created to track them.

Spark example:

CALL system.migrate('db.existing_hive_table')

This converts a Hive table to Iceberg by scanning its files and creating the Iceberg metadata tree (metadata.json, manifest list, manifest files) that references them. The Parquet files are untouched.

Pros: Fast. No data movement. The table becomes queryable as Iceberg immediately.

Cons: The existing file layout (sizes, partitioning, sort order) is inherited. If the original files are poorly organized, you inherit those problems. Requires the original files to be in Parquet or ORC format.

2. Full Rewrite (CTAS)

A full rewrite reads data from any source and writes it as a new Iceberg table with optimal partitioning and file sizes:

-- Spark
CREATE TABLE iceberg_catalog.analytics.orders
USING iceberg
PARTITIONED BY (day(order_date))
AS SELECT * FROM hive_catalog.legacy.orders

-- Dremio
CREATE TABLE analytics.orders
PARTITION BY (day(order_date))
AS SELECT * FROM legacy_source.public.orders

Pros: Best result. Optimal file sizes, correct sort order, proper partitioning. The table is perfectly organized from day one.

Cons: Requires reading and writing all data, which takes time and compute resources. The source system must be available during the migration.

3. Shadow Migration (Build and Swap)

Shadow migration builds the Iceberg table alongside the existing source, then swaps consumers from old to new when ready:

  1. Create a new Iceberg table with the desired schema and partitioning
  2. Backfill historical data from the legacy source
  3. Set up incremental sync to keep the Iceberg table current
  4. Validate data quality between old and new
  5. Swap consumer views from legacy to Iceberg

Pros: Zero downtime. Consumers never see a disruption. You can validate the migration before committing to it.

Cons: Temporarily doubles storage costs. Requires maintaining two copies during the transition.

Choosing the Right Strategy

Decision tree for selecting the right migration strategy based on downtime tolerance and layout changes

Source Recommended Strategy
Hive table (Parquet files) In-place migration, then compact
Data warehouse (Snowflake, Redshift) Full rewrite via Dremio federation
CSV/JSON files in S3 Full rewrite with COPY INTO
PostgreSQL/MySQL Full rewrite or shadow migration
Delta Lake tables In-place conversion or rewrite
Production system (no downtime) Shadow migration with view swap

The View Swap Pattern

The zero-downtime view swap pattern: views point to legacy first, then switch to Iceberg

The view swap pattern is the recommended approach for production migrations. It uses Dremio’s semantic layer to create an abstraction between consumers and the underlying data:

Phase 1: Federation

Create views in Dremio that point to the legacy data source:

CREATE VIEW analytics.orders AS
SELECT order_id, customer_id, order_date, amount, status, region
FROM postgres_source.public.orders

All consumers (dashboards, reports, notebooks) query through these views. They do not know or care where the data physically lives.

Phase 2: Build Iceberg

Create and populate the Iceberg table:

-- Create the Iceberg table
CREATE TABLE iceberg_data.analytics.orders (
    order_id BIGINT, customer_id BIGINT,
    order_date DATE, amount DECIMAL(10,2),
    status VARCHAR, region VARCHAR
) PARTITION BY (day(order_date))

-- Backfill from the legacy source
INSERT INTO iceberg_data.analytics.orders
SELECT * FROM postgres_source.public.orders

Phase 3: Validate

Compare the two datasets to confirm data integrity:

SELECT
  (SELECT COUNT(*) FROM postgres_source.public.orders) AS legacy_count,
  (SELECT COUNT(*) FROM iceberg_data.analytics.orders) AS iceberg_count

Beyond row counts, validate aggregates (total amounts, distinct customer counts) and spot-check individual records. A comprehensive validation script should compare:

  • Total row count
  • Column-level checksums or hash aggregates
  • Distinct value counts for key columns
  • Boundary values (MIN/MAX) for numeric and date columns
  • Sample of specific records matched by primary key

Only proceed to the swap after all validation checks pass.

Phase 4: Swap

Update the view to point to the Iceberg table:

CREATE OR REPLACE VIEW analytics.orders AS
SELECT order_id, customer_id, order_date, amount, status, region
FROM iceberg_data.analytics.orders

Consumers notice nothing. The view name is the same. The query interface is the same. But now the data is served from Iceberg with all of its advantages: time travel, hidden partitioning, metadata-driven pruning, and automatic optimization.

Migrating One Table at a Time

The view swap pattern enables incremental migration. You do not need to migrate everything at once:

  1. Week 1: Migrate the highest-value table (e.g., orders)
  2. Week 2: Migrate the next table (e.g., customers)
  3. Continue until all critical tables are on Iceberg

During the transition, Dremio’s federation queries legacy and Iceberg tables together. A join between a PostgreSQL table and an Iceberg table works the same as a join between two Iceberg tables. The migration is invisible to consumers.

Post-Migration Checklist

After migrating each table:

Common Migration Pitfalls

Migrating without testing query performance: Always benchmark critical queries against the new Iceberg table before switching production traffic. Iceberg’s partition layout and file organization affect performance, and a migration can make some queries faster but others slower if the partition strategy is wrong.

Skipping the validation phase: Data discrepancies between the old and new systems are more common than expected. Schema differences, timezone handling, null semantics, and data type precision can all cause subtle mismatches. Validate thoroughly.

Migrating everything at once: Large “big bang” migrations carry high risk. If something goes wrong, rolling back is complex and time-consuming. Migrate one table at a time, validate each one, and build confidence incrementally.

This completes the Apache Iceberg Masterclass. The series covered table formats, metadata, performance, partitioning, writes, catalogs, maintenance, tooling, and migration. For hands-on practice, start a Dremio Cloud trial and follow the workflow in Part 14.

Books to Go Deeper

Free Resources

Stop Reviewing Every Line of AI Code – Build the Trust Stack Instead

AI-generated code should be treated as third-party code. Same mental model we already use for libraries and dependencies. We don’t review every line of lodash, fastapi, or chi. We shouldn’t expect to review every line of AI-generated code either.

I argued this in my previous post. The natural follow-up question: okay, but what does that actually require? You can’t tell people “trust it like you trust open-source” without explaining what that trust is built on. This post is a first attempt at answering that.

We Already Have A Trust Framework. We Just Don’t Use It For This.

We trust open-source code we’ve never read. Every day, in every codebase. That trust didn’t come from any single tool. It came from a stack of agreements built up over decades. Semantic Versioning. Conventional Commits. Lockfiles. Changelogs. Module boundaries. License declarations. Package signing.

None of these are tools. They’re primitives. Foundational contracts about how to describe code, change, and intent in a way that humans, and the tools we build, can rely on.

If AI-generated code is just another kind of third-party code, the question is straightforward: which of those primitives carry over, which need new equivalents, and which are missing entirely? Tools will follow once we agree on the shape underneath. They always do. But the shape has to come first, because right now every team trying to build trust for AI-generated code is doing it in private, with their own conventions, and the result is a pile of point solutions that can’t compose.

So this is the question I want to look at. Not what tools we should build. What does the trust stack look like once we apply the OSS lens to AI-generated code?

What Made Open-Source Trustworthy

We don’t usually interrogate this. We just trust well-maintained libraries. But why?

Strip the open-source trust stack down to its primitives, the underlying contracts and not the tools built on top of them, and you get something like this:

Authorship. Every change has an author, a timestamp, and ideally a reason. Git history isn’t just a log, it’s an audit trail. You can follow a line of code back to the moment it was written and the person who wrote it.

Versioning as a contract. Semantic versioning isn’t just a numbering scheme. It’s a promise. A patch bump says “we fixed something, nothing breaks.” A major bump says “we changed the contract, you need to adapt.” It’s a communication primitive between maintainers and consumers.

Conventional commits as intent. Commit messages like fix:, feat:, chore: encode the intent of a change. They’re the foundation that changelogs are generated from. The changelog is how you understand what happened without reading every diff.

Behavioral contracts. Type signatures, documented APIs, interface definitions. These define what the code promises to do. They’re the spec that tests are written against and the boundary that consumers depend on.

Automated verification. Linters, type checkers, security scanners, coverage gates. Not one-off checks but enforced, repeatable gates that run on every change. The trust isn’t in any single test. It’s in the habit of verification.

Isolation. Code lives behind package boundaries. You can pin it, swap it, replace it. The blast radius is contained because the boundary is real.

None of these are tools. They’re agreements. The reason we can ship third-party code we haven’t read is that this stack of agreements is doing the work for us, every time, quietly, in the background.

The lens I want to apply to AI-generated code is exactly this. For each of these, what’s the equivalent for code that an agent generated inside our own repo? Where does it already exist? Where does it need to be built?

The Primitives AI-Generated Code Needs

1. Traceability

The open-source equivalent: Authorship. Author, commit timestamp, git blame.

What AI-generated code needs: Three things. A clear marker that this code was AI-generated. The human who approved it. And a link to the originating request. The originating request is whatever your team uses to describe a unit of work, a ticket, an issue, an RFC, a spec.

Without those three, nothing else in the stack has anything to attach to. You can’t version, audit, isolate, or post-mortem something you can’t identify. You can’t ask “which AI-generated module is involved in this incident” because the question doesn’t have a place to land.

This is also where ownership becomes real. You didn’t write it, but you approved it. Your name is on it. The originating request anchors the why, the human approver anchors the who. The marker is what lets all of it be queried as a class. Three items, all of them answerable today if we choose to make them answerable.

2. The Decision Log

The open-source equivalent: Conventional commits. Changelogs. Release notes.

What AI-generated code needs: A record of why this code was generated. What problem it was solving. What constraints the agent was given. What the intent was.

This is the one I’d argue is most under-served, and the one with the highest leverage. When AI-generated code does something unexpected six months from now, the question won’t be “what does this code do.” You can read it. The question will be “why was it written this way, and what was it trying to accomplish?” Without a decision log, that answer is gone.

The decision log doesn’t need to be elaborate. The original prompt or task description, the key constraints, the intent in plain language. Stored somewhere queryable. Attached to the change, the module, or the PR, not buried in a Slack thread that disappears in 90 days.

The open-source world solved this with conventional commits and changelogs. Imperfect, inconsistent, but present. The primitive exists. For AI-generated code, we haven’t even agreed it needs to.

3. Behavioral Contracts

The open-source equivalent: Type signatures, documented APIs, interface definitions.

What AI-generated code needs: The same thing, but written before the code, not inferred from it.

The direction matters. In the open-source version, the interface is defined first and code implements it. With AI generation, it’s easy to end up with code that works and an interface reverse-engineered to match it. That’s backwards. The contract is supposed to be the promise. If the implementation defines the promise, the contract isn’t doing any work.

The right approach is contract-first generation: you define the behavioral contract, and the AI produces code that satisfies it. The contract becomes the spec, the test anchor, and the documentation, all at once. It’s also what shifts human review from line-by-line to contract-level. You’re not reviewing the implementation. You’re reviewing the contract, and trusting the verification layer to enforce it. That’s exactly what we already do for third-party libraries. We don’t read lodash. We don’t read fastapi. We don’t read chi. We trust the contract.

4. Verification

The open-source equivalent: Linters, type checkers, security scanners, tests written by consumers against the public API.

What AI-generated code needs: Verification with three layers.

Deterministic. Linters, type checkers, static analysis, security scanners, schema validators. The parts of the verification stack that don’t have a bad day. They run, they pass or fail, no judgment call. For AI-generated code this matters more than for human-written code, not less. The human writer at least had context the linter didn’t have. The AI writer didn’t have that context either. The deterministic floor is the part of verification you can rely on without trusting the writer or the reviewer.

Contract-anchored. The contract is the source of truth, not the implementation. Tests that describe what the code does instead of what the contract demands aren’t really tests, they’re a self-portrait. This separation is something we get for free with a third-party library. The test author has the docs and the public API, the contract is the only thing the tests can lean on. With AI-generated code, we lose that the moment the implementation starts driving what the tests check.

Org-aware. Conventions. Internal tooling. Naming patterns. The relationships between services. The business invariants the contract never captured. The things human reviewers check today without thinking about it. The implementation gets checked against the org’s accumulated standards, not against itself. Without this layer, “we won’t review every line” turns into “we don’t catch the things humans currently catch.”

The point of all three layers, taken together, is that humans don’t have to review every line. The verification stack catches what reviewers catch today, deterministically where possible, against the contract where the contract is the spec, against the org’s standards everywhere else.

5. Isolation and Blast Radius

The open-source equivalent: Package boundaries, dependency injection, the principle that you should be able to swap a library without rewriting your codebase.

What AI-generated code needs: The same discipline, applied with intention.

A package boundary isn’t just an organizational convenience. It’s a blast-radius mechanism. When the package breaks, the rest of the system keeps working. When you want to replace it, you don’t have to rewrite everything that touched it. AI-generated code without a boundary is the opposite. It infiltrates. It couples to things it shouldn’t. By the time you realize part of it is wrong, it’s wrapped around half your codebase.

This isn’t really new. It’s an existing discipline applied inward. The same care we already apply to third-party code, isolated behind clear interfaces, swappable, replaceable, deletable, should extend to AI-generated modules. With the boundary in place, the operational story falls into place. Feature flags. Staged rollouts. Falling back to a known-good path. The boundary is the primitive. The rest is practice.

Informed Ownership

You don’t read every line of every library you import. But when one breaks, you fix it. You read the docs. You write tests against its behavior. You check the changelog. The level of understanding isn’t “I’ve read the source.” It’s “I know what this does, what it promises, and what to do when it doesn’t.”

That’s the level we should be aiming for with AI-generated code. You didn’t write it. You might not have reviewed every line. But it’s in your codebase. It’s yours. The trust stack is what makes that ownership real.

Where This Goes Next

This is a starting point, not a finished framework. Five primitives that I think need to exist before we can treat AI-generated code the way we already treat third-party code.

The questions I think are worth working on next:

  • Who defines the convention for marking AI-generated code and linking it back to a request and an approver? This feels like something that needs to be standardized across teams, not invented separately by every tool vendor.
  • What does a decision log actually look like in practice? A structured comment block? A linked spec? A generated summary from the prompt session? An entry in a separate metadata file?
  • How do we write behavioral contracts that are useful both as input to AI generation and as anchors for verification? Are existing type systems enough? Do we need something new?
  • What does the org-aware layer of verification actually look like? Does it live in CI? In the agent’s context? Both? Today’s verification stack stops at deterministic checks and contract tests, the layer that catches business invariants and org conventions doesn’t really exist yet.
  • What’s the right level of isolation? Module-level? Service-level? Function-level? When is it overkill?

If you have thoughts on any of these, or think I’m wrong about the list, I’d love to hear it. Find me at @sag1v.

Open-source gave us a trust framework we use every day without thinking about it. AI-generated code deserves the same.

Originally published on debuggr.io.

I write about software engineering, AI, and the things that interest me along the way. If this resonated with you, come visit debuggr.io for more.

Implementation of AI in mobile applications: Comparative analysis of On-Device and On-Server approaches on Native Android and Flutter

Hi everyone! Today I want to share practical experience in integrating machine learning models into mobile ecosystems. I recently completed the research and development of two MVP applications (on Native Android and Flutter), defended this project at an international conference and now I want to share my integration experience with you.

In this article, we will analyze in detail the difference between local and server AI computing, compare the implementation features of the native layer on Kotlin and the cross-platform layer on Dart, and also analyze non-obvious bugs that you may encounter when working with the camera and file system.

If you are interested in a specific platform, you can skip directly to the relevant section in the navigation below. The source code of both projects is open under the MIT license, links to repositories (GitHub/GitLab) can be found below.

Navigation:

  • Analysis of approaches (On-Device / On-Server)
  • Implementation on Native Android (Kotlin)
  • Implementation in Flutter (Dart)
  • Conclusions and links to projects

Part 1. On-Device vs On-Server: Architectural Choice

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

Local approach (On-Device)

The model is deployed directly in the application sandbox and carries out inference (inference) locally, using the computing power of the CPU, GPU or specialized neural processors (NPU/TPU) of the smartphone. As an On-Device solution, I used Google ML Kit (Image Labeling SDK).

Pros:

  • Minimum ping (Latency): There are no network delays for the transmission of heavy media data.
  • Autonomy: Complete independence from the availability and quality of the Internet connection.
  • Confidentiality (Data Privacy): User data does not leave the device and is not transferred to third parties.

Cons:

  • Resource limitation: To prevent the application from burning out the battery and taking up gigabytes of memory, models are heavily quantized and cut down.
  • Reduced accuracy: Due to compression, the accuracy of lightweight models decreases (on average, the upper threshold of accuracy in basic classification tasks is about 61-65%)

Server approach (On-Server)

The model lives on a remote server and is accessible via the API. In my research, I used the Hugging Face Inference API (model google/vit-base-patch16-224).

Pros:

  • High accuracy: You can deploy heavy State-of-the-Art (SOTA) models, LLMs, or huge ensembles of neural networks with a colossal class base on the server.
  • Client unloading: The smartphone only fulfills the network request, does not heat up and does not waste power on complex mathematical calculations.

Cons:

  • Network dependence: No Internet – no AI.
  • Infrastructure and security costs: It is necessary to provide encryption of communication channels (TLS/SSL), protect API keys from reverse engineering and pay for server capacity

Part 2. Native implementation: Android

In a native application, the key task is to isolate heavy operations from the main interface thread (Main Thread) to avoid UI friezes and Application Not Responding (ANR) errors.

Working with API (On-Server)

To send POST requests (transmitting an image byte array), a combination of OkHTTP and Retrofit was used. Conversion of the server’s JSON response into strictly typed Kotlin data classes occurs automatically thanks to converters. The network call is encapsulated in a suspend function, which allows declarative control of asynchrony.

private const val TOKEN = "..."

data class PredictionResponse(val label: String, val score: Float)

interface HuggingFaceApi {

    @POST
    suspend fun postImage(
        @Url url: String,
        @Header("Authorization") token: String,
        @Body body: RequestBody
    ): List<PredictionResponse>
}
class ApiModel(){
    private val retrofit = Retrofit.Builder()
        .baseUrl("https://router.huggingface.co/hf-inference/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val service: HuggingFaceApi = retrofit.create(HuggingFaceApi::class.java)

     suspend fun classifyImage(imageBitmap: Bitmap): Pair<String, Float>{
        return try {
            val imageToButeArray = compressBitmap((imageBitmap))
            val requestBody = imageToButeArray.toRequestBody("image/jpeg".toMediaTypeOrNull())

            val result = service.postImage(
                "models/google/vit-base-patch16-224",
                "Bearer $token",
                requestBody
            )
            val firstLabel = result.firstOrNull()
                ?: return "Не распознано" to 0f

            firstLabel.label to firstLabel.score



        }catch (e: Exception){
            Log.e("network", "Request failed", e)
            "Oшибка сервера" to 0f

        }
    }

}

Please note that before sending the image to the server we compress it and that we do not send too many bytes over the network

suspend fun compressBitmap(bitmap: Bitmap): ByteArray = withContext(Dispatchers.IO) {

    val stream = ByteArrayOutputStream()

    bitmap.compress(
        Bitmap.CompressFormat.JPEG,
        80,
        stream
    )

     stream.toByteArray()
}

Local inference (On-Device via ML Kit)

To work with the local ML Kit model, the library is configured via ImageLabelerOptions. We explicitly set setConfidenceThreshold(0.4f) – the model’s confidence threshold. By increasing this threshold, we cut off false positives, but force the algorithm to work more intensively.

To ensure stability and save RAM, the labeler object is initialized through the Kotlin delegate mechanism (by lazy):

private val labeler by lazy {
    val options = ImageLabelerOptions.Builder()
        .setConfidenceThreshold(0.4f)
        .build()
    ImageLabeling.getClient(options)
}

Why is by lazy here?

  1. Saving resources: An instance of the heavy ML Kit client is created not when the Activity is launched, but strictly at the time of the first request (when the user takes a photo).
  2. Context safety: Initialization is guaranteed to occur when the applicationContext is already fully formed by the operating system, which prevents NullPointerException from occurring.

The call to labeler.process(image) is asynchronous in nature (runs on Google’s Task API). To make it linear and MVVM-friendly, we wrap it with coroutines and wait for the execution result.

Architectural layer and flow control

In MainViewModel, all calls are wrapped in viewModelScope.launch. Depending on the position of the state switch (On-Device / On-Server), the required method is launched:

private fun classifyImage(bitmap: Bitmap?) {
        if (bitmap == null) return
        _uiState.update {
            it.copy(isLoading = true)
        }
        viewModelScope.launch {
            val startTime = System.currentTimeMillis()

            try {
                val (label, confidence) = if (_uiState.value.isOnDevice) {
                    mlKit.analyze(bitmap!!)
                } else {
                    apiModel.classifyImage(bitmap!!)
                }

                val duration = System.currentTimeMillis() - startTime

                _uiState.update {
                    it.copy(
                        classificationText = label,
                        confidenceValue = confidence,
                        timeTakenDuration = duration,
                        isLoading = false
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        classificationText = "Ошибка",
                        confidenceValue = 0f,
                        timeTakenDuration = 0L
                    )
                }
            }
        }

Working with the camera on Native Android

On the Native Android side, working with the camera looks concise thanks to the modern SDK CameraX. This is a Lifecycle-aware library: it knows when an Activity is minimized (onPause) or destroyed (onDestroy), and automatically releases camera resources and closes streams (ImageAnalysis / ImageCapture). We do not need to manually write the onDispose logic, and the result of a successful snapshot in the code can be a ready-made Bitmap object held in RAM, which eliminates unnecessary disk read-write operations.

Part 3. Cross-platform implementation: Flutter (Dart, Dio, Method Channels)

The Flutter application conceptually solves the same problems, but faces the specifics of Dart’s single-threaded architecture (Event Loop).

Network Inference (Dio + Futures)

To communicate with Hugging Face on Flutter, we used the Dio package. To prevent a heavy request and network packet processing from blocking the rendering of UI frames (after all, Dart runs on a single thread), we package the call into an asynchronous Future/Await model. While the network is chasing bytes, Event Loop calmly continues to render the interface.

final dio = Dio();

Future<List<dynamic>?> apiModel(String path) async {
  final Uint8List? imageBytes = await compressImage(path);

  if (imageBytes == null) {
    return null;
  }

  try {
    final response = await dio.post(
      "https://router.huggingface.co/hf-inference/models/google/vit-base-patch16-224",
      data: imageBytes,
      options: Options(
        headers: {
          "Authorization": "Bearer 'your_token'", // put your token from hugging face here
          "Content-Type": "image/jpeg",
        },
      ),
    );
    return response.data;


  } on DioException catch (e) {
    debugPrint("Error: $e");

  }
  return null;
}

Please note that before sending the image to the server we compress it and that we do not send too many bytes over the network

Future<Uint8List?> compressImage(String path) async {
  final Uint8List? result = await FlutterImageCompress.compressWithFile(
    path,
    quality: 80,
    format: CompressFormat.jpeg,
  );

  return result;
}

Native bridge: MethodChannel for ML Kit

Since there is no full-fledged direct SDK for ML Kit Image Labeling on Dart that provides the required level of customization, a Production approach is used: creating a MethodChannel (native bridge).

The Dart code acts as a client: it generates the predictOnDevice event and passes the path to the saved photo through the channel.

class NativeMlService {
  static const MethodChannel _channel = MethodChannel("mlkit_photo_analyze");

  static Future<Map> onDeviceMethod(String imagePath) async {
    final result = await _channel.invokeMethod(
      'imageLabeling',
      {'imagePath': imagePath},
    );
    return Map.from(result);
  }
}

On the Android side (MainActivity.kt) we catch this call through setMethodCallHandler. The same rules apply here: we deploy the coroutine on a background thread, process the image via ML Kit, but we transmit the response to result.success() strictly returning to the Main Thread, since the Flutter engine will not be able to accept data from the Android side thread.

 override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if(call.method == "imageLabeling"){
                val imagePath = call.argument<String>("imagePath")
                if (imagePath == null) {
                    result.error("ArgError", "Image path is null", null)
                    return@setMethodCallHandler
                }
                // Run ML inference on background thread to avoid blocking UI
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                          // image processing and model calling....

                        // Return result on main thread
                        withContext(Dispatchers.Main){
                            result.success(response)
                        }
                    }....
//rest of the code on GitHub/ GitLab....

Camera in Flutter and Data Race (Race Condition)

The most difficult and interesting stage of developing the Flutter version was the integration of the camera plugin and debugging the interaction of file systems. Here two important differences from the native were revealed:

Manual Lifecycle Management: In Flutter, the developer must manually initialize the CameraController, catch available lenses (by selecting CameraLensDirection.back) and, most importantly, be sure to call _controller?.dispose() in the dispose() method of the widget.

If you forget, the camera will remain locked in the operating system, and other applications will not be able to open it.

Ghost File Problem (Race Condition):
The _controller?.takePicture() method in Flutter returns an XFile object that physically stores the snapshot in the device cache directory (image.path). This is where the classic data engineering race comes into play.

When Flutter happily reports that the photo has been taken and passes the path to the native code via MethodChannel, the native part (Kotlin) instantly tries to execute BitmapFactory.decodeFile(imagePath). But at the level of the Android operating system, the file in the cache may still be blocked – the stream of data writing from the camera buffer to the disk has not yet had time to physically close.

This was reflected in the logs as a hard crash:
E/ple.flutter_mvp: FrameInsert open fail: No such file or directory
The native code crashed, Bitmap returned null, and Flutter received an empty null reference instead of a data structure.

We get a similar error when we send a picture to the server because we are practically sending an empty picture

Solution to the problem:
To eliminate this data race, two-way protection was applied:

On the Dart (Provider) side: Before calling the native method/sending to the server, we artificially let the system “breathe out” by adding a micro-delay:

await Future.delayed(const Duration(milliseconds: 200));

This time is enough for the OS to complete disk operations.

Conclusion and conclusions

The conducted MVP study clearly proves: On-Device and On-Server approaches do not compete, but complement each other.

  • On-Server is indispensable for heavy computing (LLM, GPT, high-definition video processing).
  • On-Device is ideal for utilitarian tasks (scanning documents, recognizing simple objects, working in strict offline conditions).

In modern Production applications, the best practice is a hybrid approach**: fast primary output is done locally, and deep data validation is sent to the backend server.

Regarding the choice of platform: Native Android gives absolute control over resources, hardware and threads out of the box. Flutter, despite the limitations of single-threading Dart, with proper use of MethodChannel, compliance with the rules for dispatching coroutines in the native layer and taking into account file system timings, allows you to create responsive and productive AI applications.

GitHub

GitHub logo

RatRatatyu
/
mobile-ai-mvp

Two MVP applications demonstrating on-device and on-server AI model integration in Jetpack Compose (Android) and Flutter.

Mobile AI Integration: On-Device vs On-Server MVP Comparison

This repository contains two MVP applications developed for the International Scientific and Practical Conference
“Student Research: Challenges and Development Trends”.

🏫 Conference Information

  • Event: International Scientific and Practical Conference
    “Student Research: Challenges and Development Trends”

  • Organizers:
    Ministry of Education of the Republic of Kazakhstan,
    Department of Education of Aktobe Region,
    Aktobe Higher Humanitarian College,
    National Centre for Professional Development “Orleu”

  • Section:
    Science, Technology, and Digital Innovations

  • Date:
    May 22, 2026

📱 Project Overview

The project explores the architectural choice between running AI models directly on a smartphone (On-Device) versus processing them on a remote server (On-Server)

For this research, image classification was chosen as the primary use case to demonstrate the differences in performance and accuracy

🤖 Applied Models

On-Device: Powered by the ML Kit Image Labeling API from Google for local, real-time inference

On-Server: Powered by the Hugging Face google/vit-base-patch16-224…

GitLab


RatRatatyu / mobile-ai-mvp · GitLab

Two MVP applications demonstrating on-device and on-server AI model integration in Jetpack Compose (Android) and Flutter.

favicon
gitlab.com

I would like to note that I am just developing and learning in this direction, so perhaps my conclusions may be inaccurate, or the descriptions may not be entirely correct, so I will be grateful if you point out my mistakes in the comments, and I will also be glad if you put stars in GitHub and GitLab if the projects are useful to you

Should you use Gemma 4 for your Development? A Multiversal Analysis to Determine if Gemma 4 is Right for You!

Image

This is a submission for the Gemma 4 Challenge: Write About Gemma 4

Disclaimer: This is an individual submission for Francis Tran (@francistrdev). Everyone involved has their own accounts of using Gemma 4 and has been paraphrased in this post. See below for the list of people involved.

 

Author: Francis Tran (@francistrdev)
Featuring: Elmar Chavez (@codingwithjiro), Konark Sharma (@konark_13), and Julien Avezou (@javz)

The cover image uses characters from various Anime chosen by the people who are featured in this post, put together in using Pixlr, and using AI to enhance the quality of the image. Some contents started off using AI and has been paraphrased by the author’s own words.

Table of Contents

  • Introduction

  • Setting up Gemma 4 using Ollama

    • Installing Ollama and Gemma 4
    • Trying out Gemma 4
    • Running Gemma 4 Offline
    • Elmar’s Verdict on Gemma 4
  • Using Gemma 4 as a Confused Developer

    • The Strawberry Test
    • The Tic Tac Toe Rotation Test
    • The Broken Cup Test
    • Konark’s Verdict on Gemma 4
  • Building a Prototype using Gemma 4

    • Results of Gemma 4 Vs. GPT 5.4

      • Technical Depth
      • Architecture & System Thinking
    • Julien’s Verdict on Gemma 4
  • Using Gemma 4 as an AI-Agent

    • Gemma 4 is Strict
    • Please Google I need this. Gemma 4 is kind of Looping Itself
    • Francis’ Verdict on Gemma 4
  • Summary

Thank you for Reading!

Image

Introduction

In the age of AI, many developers are using AI in their workflows. This can range from AI assistants cleaning up a large code-base to developers vibe coding a prototype to showcase to others.

Regardless of your use of AI in your development, it is important to choose the model you want to work with. There are a lot of choices to choose from such as ChatGPT, Gemini, Copilot, etc. The one we are talking about today is Google’s latest model: Gemma 4!

The goal of this article is to share our experiences using Gemma 4 in 4 different perspectives of Development starting from setting up Gemma 4 using Ollama, testing the hallucination of Gemma 4, how Gemma 4 outputs, and using Gemma 4 as an AI-Agent. Additionally, I will share our discoveries and whether we recommend using Gemma 4 based on our experiences! We hope that our experience of using Gemma 4 will help you to decide if Gemma 4 is right for you in any skill level of your developer career!

With that said, we will now talk about the setup process. In any development, we all experience setting up our environment whether it is OpenClaw or a simple NPM package! Having a local LLM is one of them. Here is Elmar’s experience of setting up Gemma 4 using Ollama!

 

 

Setting up Gemma 4 using Ollama

Elmar has been using ChatGPT for the past year where he mainly uses it as a mentor when doing projects. He was interested having a LLM locally. He believes that having an LLM locally is convenient for his case, due to power outages he has to faced in the Philippines. Having Gemma 4 locally will allow him to be productive when coding without the need to worry about connecting to the internet. With that said, he started to research about setting up Gemma 4 using Ollama.

 

Installing Ollama and Gemma 4

Elmar started to search on the internet, looking for tutorials on getting started on Gemma 4.

One of the ways to get started is installing Ollama, which Elmar thought was a weird name until he realized the logo was an actual llama.

When downloading Ollama, the main issue is the storage, which was nearing 100% capacity and Ollama installer defaults to the C: drive.

After searching more about installing Ollama without installing on the C: drive, which led to this command he had to run on the terminal:

C:UsersELMAR>cd Downloads
C:UsersELMARDownloads>OllamaSetup.exe /DIR="D:Ollama"

Ultimately, it worked well. He had done other configurations such as redirecting the AI model installation in the same drive under D:OllamaModels. He then downloaded the gemma4:e4b.

 

Trying out Gemma 4

The first thing Elmar tried was “hi gemma4”. Although the expected outcome is Gemma 4 saying hello back, it gave him this error:

Error
500 Internal Server Error: model requires more system memory (9.8 GiB) than is available (4.9 GiB)

 

For context, this is his device specifications:

His laptop is great for programming and other developments. The issue is that his laptop is only suitable for “lightweight models” when it comes to downloading LLMs locally.

 

Elmar discovered that local AI depends heavily on your own hardware, unlike browser-based AI tools like ChatGPT.

 

One of the things Elmar did was to run a smaller version of Gemma 4:

ollama run gemma4:e2b

It gave him a similar error as before:

Error
500 Internal Server Error: model requires more system memory (7.2 GiB) than is available (5.7 GiB)

 

After investigating a bit more, he closed other applications that were running on his computer and taking up space and it outputted!

 

The big thing about running it for the first time is that it took longer than he expected, but he mentioned that he had VSCode, Notepad, and 4 tabs currently opened in his Chrome Browser.

 

Running Gemma 4 Offline

Elmar was curious about the result of using Gemma 4 without connecting to the internet.

It ran slower than usual, but it is still under a minute.

 

Elmar then tried to ask questions to Gemma 4 that he would normally ask to ChatGPT as part of his Development workflow.

In this case, he is currently building his website portfolio. Elmar asked a question along with attaching a screenshot to Gemma 4 and here is what it output:

Surprisingly, it took less time considering the fact that he inserted an image for this use case.

 

The wait time for the LLM to respond, which is around a minute, is reasonable for Elmar since he has a decent laptop. It is quite useful especially for countries that commonly have power outages or that have unreliable internet.

 

Elmar’s Verdict on Gemma 4

This is Elmar’s Verdict of Gemma 4 in terms of setting up via Ollama and using it for the first time:

Web-based LLMs are great for convenience and device flexibility. While local LLMs are great for offline reliability and privacy, I’d say the experience of experimenting with Ollama + Gemma 4 only made my perspective with AI clearer.

It is not magic, it’s just data combined with probability and rendering models that require large amounts of RAM for compute power.

This begs the question, if I have a higher end device, would I invest fully into local LLM’s?

Image

I would not sacrifice my own hardware for running AI computations just to get responses faster.

There are data centers that have the hardware especially built for AI. I would rather give the job to them.

Overall, ChatGPT is still far more practical for my current workflow so I will be sticking to it as my default. However, I would definitely use Ollama + Gemma 4 as a reliable alternative.

That is Elmar’s Verdict on Gemma 4! In the early stage, it is fast to setup, but difficult to use when it comes to response time and the hardware needed, especially considering most users do not have a powerful laptop.

Now you know about the setup with Gemma 4! Starting off with Gemma 4 and seeing its outputs is a good sign that everything works! However, although Gemma 4 is a small and powerful model, how good is it at not being confused? We now transition to Konark where he tested Gemma 4 to the limit!

 

 

Using Gemma 4 as a Confused Developer

Konark has been using Gemma 4 for some time and the one thing he wanted to know is to see if he can abuse Gemma 4 to its confusion.

We all have that one moment where we randomly test an AI just to see “How smart are you actually?” with questions like “How many r’s are there in strawberry?”. Konark did three tests such as the Strawberry test, the Tic Tac Toe Rotation test, and the Broken Cup Test.

 

The Strawberry Test

Konark asked Gemma 4: “How many r’s are there in strawberry?” (There are three). Initially, this type of question was commonly used to confuse many AI models.

Gemma 4 thought for a while and gave Konark three different interpretations regarding the number of “r’s” in strawberry.

 

Konark realized that sometimes AI over complicates simple questions and he would rather prefer simple answers. For example, if there are 10 apples in a basket and you asked Gemma 4: “How many apples are there?”.

 

Would you prefer this answer:

“This is my first time counting. Do you mean apples inside the basket or around the basket?”

 

Or would you simply perfer:

“There are 10 apples.”

 

Konark would prefer the second answer.

 

With these results, he was curious about how Gemini would answer to the strawberry test. As such, he asked Gemini and it simply replied:

3 r’s.

It is straightforward and it is always good to have a simple, non-complex answer.

 

The Tic Tac Toe Rotation Test

Another fun question Konark asked Gemma 4 was: “How would rotating a tic tac toe board by 90 degrees change the rules of the game and its strategy?”

The whole goal is to see if Gemma 4 thinks it’s still the same, expect the board is rotated.

However, Gemma 4 took quite some time to conclude this. It explained things properly and even walked through a rotated example.

Although it is a helpful response, it would be nice to get a more straightforward answer similarly to the Strawberry Test.

 

The Broken Cup Test

This is Konark’s favorite test, in which he asked Gemma 4: “I have a metal cup with the bottom missing and the top sealed. How can I use this cup?”

The simple answer would be “Rotate the cup. And suddenly, it becomes usable again.”.

However, Gemma 4 did not really understand the trick. Instead, it started suggesting alternative ways to use the object.

Although it is creative, it is not entirely correct.

 

On the other hand, Gemini understood the trick faster and then even expanded on practical uses.

Overall, Gemma 4 still struggles with certain trick questions and edge-case reasoning.

 

Konark’s Verdict on Gemma 4

This is Konark’s verdict of using Gemma 4.

After playing around with both models, I reached a simple conclusion.

Gemma 4 feels good for:

  • learning
  • content generation
  • straightforward explanations
  • slower, detailed responses

Gemini feels better for:

  • trick questions
  • quick reasoning
  • direct answers
  • faster conclusions

And honestly, both have their place.

Sometimes I want a detailed explanation.

Sometimes I just want: “Bro, just give me the answer.”

And that matters.

Because developers don’t always want essays. Sometimes we just want the bug fixed.

This is important to consider when you want to use Gemma 4. Sometimes, we just want a simple answer to the issue we are trying to solve. Of course, prompting varies and this is Konark’s experience using Gemma 4 so it can be different from others.

Speaking of prompting, AI is used to prototype projects in development! We now transition to Julien’s experience on using Gemma 4 when it comes to prototyping a project and how it compares to what he usually uses, which is Codex!

 

 

Building a Prototype using Gemma 4

Julien planned on using AI to create a fast prototype.

 

He was curious about how Gemma 4 performs compared to his usual setup, Codex (GPT 5.4).

For context, the project is a Chrome extension to help develop better use of LLMs. He will share more on his blog page in the future!

His goal is to compare Gemma 4 Vs. GPT 5.4 when it comes to prototyping. For this comparison, he will run tests across the following 2 categories using the same prompt as input and comparing the quality of the outputs:

  1. Technical Depth: The factual accuracy, understanding of deep system mechanics and ability to compare non-trivial trade-offs.

  2. Architecture & System Thinking: The ability to think at the macro level, identifying bottlenecks, scaling issues, and making justifiable “when/why” decisions.

 

Results of Gemma 4 Vs. GPT 5.4

Here are the results for the cases of Technical Depth and Architecture & System Thinking!

 

Technical Depth

This is the prompt given to both LLMs:

I am building a Chrome extension which detects when a developer is using ChatGPT, Claude, or Gemini, shows a floating button, opens a side panel, lets the user describe their task, recommends one of five AI thinking modes, generates a better prompt, and lets the user copy it manually.

Modes:
1. Explore — when I don’t fully understand the problem yet
2. Challenge — when I have a plan, but it might be wrong
3. Decide — when I need to choose between options
4. Audit — when I need to verify quality or correctness
5. Reflect — when I want to actually learn from what I did

MVP constraints:

  • Chrome extension only
  • no login
  • no dashboard
  • no automatic prompt insertion
  • no usage tracking yet

Task:
Give me a technically detailed implementation plan for the MVP.

 

Here is the results:

Model Pros Cons
Gemma 4 Clear high-level structure. Correctly identifies manifest, background script, content script, overlay UI, and template-based prompt generation. Easy to read. Good for a conceptual first pass. Too generic. Does not mention Chrome Side Panel API. Blurs overlay and side panel. Drifts from your exact modes. Weak on privacy/security. Less actionable for immediate implementation.
GPT 5.4 Much more implementation-ready. Strong file structure. Useful code snippets. Correct Chrome APIs. Better MVP scoping. Better maintenance thinking. Exact mode alignment. Clear recommendation to avoid LLM/API in v1. Still light on deeper security analysis. The manifest/build setup would need adjustment because TypeScript files are not directly used by Chrome without bundling. Could have compared local/API/hybrid tradeoffs more explicitly.

Overall, GPT 5.4 gives the stronger Technical Depth output since it is more accurate, more build-ready, and more specific.

 

Architecture & System Thinking

This is the prompt given to both LLMs:

I am building a Chrome extension that helps developers use AI more intentionally.

It sits on top of ChatGPT, Claude, and Gemini. The user describes their task, then it recommends one of five thinking modes and generates a better prompt to copy.

Modes:
1. Explore — when I don’t fully understand the problem yet
2. Challenge — when I have a plan, but it might be wrong
3. Decide — when I need to choose between options
4. Audit — when I need to verify quality or correctness
5. Reflect — when I want to actually learn from what I did

MVP:

  • detect supported AI chat pages
  • show floating ModeCheck button
  • open side panel
  • recommend mode
  • generate better prompt
  • copy manually
  • soft CTA to the Thinking Engineer Toolkit

Future:
A SaaS dashboard may later track AI usage modes, cognitive cost, dependency patterns, and optional hard blocks.

Task:
Think at the system architecture level.

Cover:

  • best one-week MVP architecture
  • what to build now vs postpone
  • key system boundaries
  • privacy/trust risks
  • maintenance risks for a solo builder
  • how to preserve future optionality for analytics/dashboard
  • strongest argument for and against the browser extension approach
  • recommended roadmap: week 1, month 1, month 3

Be concise but thoughtful. Focus on trade-offs and “when/why” decisions.

 

Here is the results:

Model Pros Cons
Gemma 4 Good strategic restraint. Correctly recommends client-side MVP, hardcoded templates, no backend, and no dashboard at first. Good emphasis on fast time-to-value. Useful suggestion to model prompts as structured objects/schema for future flexibility. Less complete system thinking. Weak privacy/trust analysis. Weak argument for/against extension approach. Maintenance advice is shallow. Roadmap becomes generic around logging, API integration, billing. Does not fully address future cognitive-cost/hard-block architecture.
GPT 5.4 Stronger system boundaries. Better local-first architecture. Better privacy/trust framing. Better solo-builder maintenance analysis. Stronger roadmap. Better future optionality through event/data modeling without collecting data yet. Better distinction between host page, extension, and future backend. Does not go very deep on future scaling bottlenecks or hard-block mechanics. Could have included Gemma’s useful prompt-schema idea. Slightly less focused on concrete “engine” abstraction for prompt assembly.

Overall, GPT 5.4 wins on Architecture & System Thinking. Gemma 4 provides a solid, restrained MVP strategy, but GPT 5.4 gives a more complete architectural view: system boundaries, trust, local-first design, future analytics optionality, solo-builder maintenance risk, and roadmap discipline.

 

Julien’s Verdict on Gemma 4

This is Julien’s verdict on the use of Gemma 4:

GPT 5.4 seems to be the strongest at high-level reasoning and synthesis as you would expect from a recent frontier model.

However a good use case for Gemma 4 in terms of prototyping work would be for codebase analysis, running experiments through constraints and for privacy-sensitive workflows.

Being an open model which can be run locally has great specific and complementary use cases when prototyping developer tools.

I will consider this going forward.

Even though GPT is preferred when it comes to high-level reasoning and synthesis, there are other cases where Gemma 4 is useful for prototyping.

Speaking of prototyping, now we transition over to using Gemma 4 as an AI-Agent!

 

 

Using Gemma 4 as an AI-Agent

Whenever I am contributing to Open Source, it is quite useful to have an AI-Agent to work with you. My preference is to use an agent living in an application like Visual Studio Code.

I have been using GitHub Copilot when it comes to contributing to Forem and it has been useful when it comes to navigating code bases, problem solving issues, etc.

When I heard about Gemma 4, I thought it would be a good idea to try out when using Gemma 4 as an AI-Agent. I specifically used the cloud version using Ollama since the hardware I have cannot handle LLM locally, even though I tried the smaller version of the model.

 

Setting up wasn’t too difficult on my part. Since I tried Ollama to begin with before the release of Gemma 4, it was as easy as pulling the model using this command:

ollama run gemma4:31b-cloud

 

After installing, I selected the model and was ready to go!

 

When using the model, I noticed there wasn’t much of a big change compared to my initial workflow of using Copilot as my agent.

Both models asked me for permission when running commands, able to problem solve the issue I requested, etc. To be fair, I wasn’t using “Continue” Visual Studio code extension since it is quite popular when using local LLMs. Also, Visual Studio code is flexible when it comes to adding your own model in addition to using Copilot, which I wasn’t surprised that it behaves similarly when using Copilot.

However, there are a couple of things I noticed when using Gemma 4 that I believe are important to address based on my experience using Gemma 4.

 

Gemma 4 is Strict

The main difference between Gemma 4 and Copilot was that it is quite firm on the tasks it is given to them. I notice that whenever I request a plan on tackling an issue, it provides a To-do list of the steps Gemma 4 is planning on doing to fix the issue.

 

For example, this is the prompt I gave to Gemma 4:

I have this issue. How do I approach this?

https://github.com/forem/forem/issues/23277

It will output their findings like any other LLM. However, it would not act right away and instead, listed out the next steps:

 

In cases like these, I just follow up the Agent “Go for it” or “Proceed”. Sometimes it does everything in the to-do list in one go and in other cases it goes one by one where I have to tell the Agent to “Do all the tasks”. Do note that I did not change any settings as I was setting up Gemma 4 since it was just pulling the model and selecting it in Visual Studio Code.

Compare that to Copilot, where regardless of the prompt, it would take action right away. There were cases where I forgot to change the mode from “Agent” to “Chat” and I was specifically asking the AI about the plan to tackle the issue. Instead of listing out the steps, it did it right away which I did not want it to do.

In all fairness, Gemma 4 and Copilot are from different companies (Google and Microsoft) and since Copilot is built into Visual Studio Code, it is fair to assume that its actions strictly follows based on the settings you have in Visual Studio Code for Copilot.

However, it is always nice to see Gemma 4 listing out the To-do list and asking the user to proceed. I believe it is good practice by default if you are a type of user that wants to get an AI’s advice on what to do and doing it yourself from there.

 

Please Google I need this. Gemma 4 is kind of Looping Itself

It is exactly what you are thinking. This is a common occurrence where Gemma 4 will read a file from top to bottom and reread it again. Here is an example that I encountered when using Gemma 4:

I am not sure what is causing this issue since this happens randomly.

 

The solution is stopping the Agent and sending the same prompt. This fixes the issue really well, though this bug remains a mystery to why it occurs in the first place.

 

Francis’ Verdict on Gemma 4

This is my verdict on the use of Gemma 4 as an AI-Agent:

I believe Gemma 4 works really well when being an open source developer. It can navigate large code-bases and being able to solve complex problems well for a model that is quite small.

Although there isn’t a big difference between Gemma 4 and other models I have used, it is good to consider token usage. I would recommend Ollama when using Gemma 4. It is free to use the cloud version and the tokens reset weekly whereas Copilot resets monthly. If you are heavily relying on AI-Agents, I would recommend the Ollama solution since it is more flexible. Even if you reach the daily limit of tokens, it resets every few hours.

I would highly recommend Gemma 4 as a great starting point when it comes to using it as an Agent when you want to contribute to open source. Just remember to monitor the response time since there is a very good chance where it loops itself in which it would burn tokens in the process.

 

 

Summary

Gemma 4 has been used in some aspects when it comes to setting up Ollama to use Gemma 4, testing out the response of the model, prototyping using Gemma 4, and the role as an Agent. Here are the main things to consider based on what I have shared above.

 

1. Convenience

Like any other local models, you have to consider not only if you are conformable downloading a model locally, but ensuring you have enough compute power to run an LLM. Although there are options to use LLM on the cloud (for Ollama at least), having a local LLM is very convenient for developers who want to run the model locally and not worry about:

  • Use of Tokens limits and payed services.
  • The environment when it comes to data centers in the age of AI.

 

2. Performance

Speaking of compute power, having a local LLM, even with smaller models of Gemma 4, still needs a lot of power. We saw that in Elmar’s experience, it took a while for Gemma 4 to produce an output comparable to using any cloud model. If you are comfortable with the wait time of the model, then it shouldn’t be a problem!

 

3. Context Output

Every model behaves differently whether cloud or local models. This is no different to Gemma 4. If you are using Gemma 4, you have to make sure the prompt is specific to your needs. This is best practice in prompts in general when it comes to requesting your needs and being as specific as possible.

 

4. Role as an AI-Agent

It is common for developers nowadays to use a local model to run as an Agent. Using Gemma 4 via Ollama has been a great experience for me. Do note that you may encounter issues when using Gemma 4. I would recommend monitoring Gemma 4’s token usage in the event of Gemma 4 looping itself and burning unnecessary tokens.

 

Verdict: Overall, if you have enough power to run a local LLM and would like to have a model that is smaller but more powerful than other Flagship models to use in your development knowing the limitations of local LLMs in general, then I believe Gemma 4 is right for you!

 

I hope that this Multiversal Analysis has helped you to determine if Gemma 4 is right for you! If you like to learn more about Gemma 4 in detail, you can read here: https://deepmind.google/models/gemma/gemma-4/

Image

 

 

Thank you for Reading!

If you have made it this far, thank you for taking the time to read this article! I hope you have learned something based on our experiences using Gemma 4 in different areas of development.

I would like to give credit to the Virtual Coffee Group where I used their “#co-working” room to meet with Elmar Chavez (@codingwithjiro), Konark Sharma (@konark_13), and Julien Avezou (@javz) for the first time outside of DEV and would love to work with them again in the future!

 

Feel free to send us love by following us individually and our DEVenger org!

 

Challenge #1: Did you find 4 hidden random videos in this article?

Challenge #2: How many “r’s” are there in this post in total?

Challenge #3: Who are the anime characters in this article’s cover image?

Challenge #4: Based on Challenge 3, who decide to choose those anime characters in this article respectfully?

Any questions/comments? Love to hear your thoughts on Gemma 4! What’s your experience on using Gemma 4 and do you recommend it?

The Rising Trend of Creative Interview Questions in Tech

In the ever-evolving landscape of the tech industry, hiring practices are constantly being redefined. As companies strive to find the right fit for their teams, creativity in interview questions has emerged as a fresh approach to better understand candidates. A notable trend is the rise of unconventional questions that challenge applicants to think critically and showcase their problem-solving abilities. One such question, “If you were a software bug, what kind of bug would you be and why?” is gaining traction among tech recruiters.

This question, like many others in the realm of creative interviewing, serves multiple purposes. It offers insight into a candidate’s thought process, demonstrates how they articulate complex ideas, and sheds light on their approach to challenges. In this article, we will delve into this intriguing question and similar ones, exploring the rationale behind them, their impact on hiring success, and the lessons learned from their implementation.

The Evolution of Interview Questions

Traditional versus Creative Questions

For decades, the interviewing process has relied heavily on a standard set of predictable questions. Candidates often encountered queries about their past experiences, technical skills, and conflict resolution strategies. However, this traditional approach often misses out on capturing the nuanced qualities of a candidate that are critical for success in dynamic tech roles.

Creative interview questions represent a shift away from the conventional. These questions do not simply evaluate technical knowledge but instead focus on cognitive agility, creativity, and interpersonal skills. The objective is to evaluate how candidates think on their feet and how they approach complex problem-solving.

“Traditional interview questions often create standard responses, whereas creative questions allow candidates to showcase their individuality and thought processes.”

The Purpose Behind Creative Questions

The primary aim of these creative questions is to foster a dialogue that reveals a candidate’s personality and thought patterns. Companies like Google and Amazon have long advocated for unconventional questions that can lead candidates to elaborate on their experiences and viewpoints.

For instance, asking a candidate about the bug they would be allows interviewers to gauge their awareness of software issues, their critical thinking skills, and their ability to reflect on personal and professional identity. Such questions often lead to richer conversations, allowing interviewers to assess more than just technical prowess.

Analyzing the Impact of Creative Interview Questions

Candidate Experience

One significant benefit of integrating creative questions into the interview process is the improvement in candidate experience. Traditional interviews can be daunting, often creating an atmosphere of stress that hinders genuine interaction. Creative questions can alleviate some of this pressure, allowing candidates to express themselves more freely.

Consider a scenario where a candidate is asked to describe a fictional character they would embody in a tech project. This invites not only creativity but also an opportunity to discuss collaboration, leadership, and uniqueness—all valuable attributes in a tech environment.

“When candidates are encouraged to think outside the box, they often reveal their true personalities, leading to better cultural fit.”

Decision Making for Employers

Creative interview questions also help employers make more informed decisions. By facilitating discussions that reveal a candidate’s values, work style, and innovative thinking, companies can align their new hires with their organizational culture. This ultimately leads to improved retention rates and job satisfaction.

Take, for instance, the rise of remote work and the necessity for self-motivation. Interviewing a candidate about how they would structure their day working remotely might reveal their time management skills and work ethic. Such insights can be invaluable when determining if a candidate is likely to thrive in a remote or hybrid work environment.

Success Stories: Companies Embracing Creative Questions

Case Study: Google

Google is often cited as a pioneer in the realm of creative interview questions. The tech giant famously employed questions like, “How many ways can you think of to collect a penny from the ground?” This approach was intended to evaluate candidates on their problem-solving capabilities and innovative thinking.

Numerous success stories stem from Google’s unique interview style. Their practice of asking unconventional questions has led to them hiring candidates who not only possess exceptional technical skills but also demonstrate the capacity to adapt and innovate—the very qualities that keep Google at the forefront of the tech industry.

Case Study: Amazon

Amazon has also embraced creative interviewing techniques, particularly through its Leadership Principles. Candidates are often asked situational questions that require them to reflect on past experiences and demonstrate how they align with principles such as “Customer Obsession” or “Invent and Simplify.”

By concentrating on how candidates would fit within their established culture, Amazon has experienced significant success in employee satisfaction and retention. New hires often report feeling privileged to be part of a culture that values innovation and leadership, attributing it to the carefully selected interview process.

Lessons Learned from Creative Interview Questions

The Importance of Relevance

While creative questions can enhance the interviewing process, it is essential that they remain relevant to the role. Questions should align with the skills and attributes required for the position in order to yield meaningful insights. For example, a question about designing a fictional app might be great for a product manager but less applicable for a back-end developer.

“Relevance is key; creative questions must correlate with the job role to provide real insights about the candidate’s suitability.”

Training Interviewers

Implementing creative interview questions requires a paradigm shift not only in how questions are posed but also in how interviewers are trained. Equipping hiring managers and team leads with the skills to interpret the responses effectively is critical. This includes understanding the nuances in candidate answers and taking the time to allow for exploration rather than rushing through the interview.

Building a Culture of Openness

To foster an environment where candidates feel comfortable sharing their thoughts without fear of judgment, companies must prioritize a culture of openness. Creating a safe space for dialogue encourages candidates to be authentic, resulting in a more effective evaluation process.

Conclusion: The Future of Tech Interviews

As the tech industry continues to evolve, so too will the methods used for hiring. The introduction of creative questions into interview processes has shown promise in providing a more holistic view of candidates, enhancing both their experience and the quality of hires for companies.

From organizations like Google and Amazon that have successfully leveraged this trend, we see that understanding candidates beyond their resumes can lead to the discovery of hidden gems—individuals capable of bringing innovation, creativity, and value to their teams.

Going forward, businesses that embrace creativity in interviews while ensuring relevance and training will pave the way for a future that prioritizes not just skills but also personality and cultural fit. This comprehensive approach will ultimately contribute to building not only successful teams but also thriving organizations in a competitive tech landscape. The journey of integrating creative interview questions may just be beginning, but its potential impact is already evident and worth exploring.

It Worked When I Closed the Laptop. I Swear.

Dev Comics #1 — It Worked Yesterday

Dev Comics #1 — It Worked Yesterday

Last night the build was clean. This morning, five red errors before the coffee was even warm.

git log shows the only commit in the last 11 hours is yours. "Refactor player movement".

You hold the cold coffee. You stare at the screen.

If you’ve shipped any game ever, you’ve been here. Welcome to Dev Comics #1.

This is a new weekly-ish series from a small Korean indie game studio — short comics about the unglamorous moments of making games. New comics most Tuesdays and Saturdays.

Coming up:

  • #2 Shader Compile Coffee — when your Unreal shader compile outlives your coffee
  • #3 Cat.exe Has Stopped Responding — the cat owns the keyboard now

If this hit close to home, drop a 🦖 reaction or share the worst “11 hours ago, by me” commit you’ve ever seen.

We Built an Agent That Flags Fake Internships #kryx

Every placement season, students receive internship offers that look legitimate on the surface but fall apart the moment you inspect them closely.

Some ask for “training fees.”
Some guarantee placements before interviews even happen.
Some companies barely exist online.
Others hide behind generic Gmail accounts and flashy marketing.

The worst part is that many students can’t easily distinguish between a real opportunity and a well-designed scam.

So my teammates and I built a system that tries to score internship legitimacy before students commit time or money.

We call it ShieldIntern.

The Core Idea

We wanted a system that behaves less like a chatbot and more like an auditor.

Instead of simply asking an LLM whether an internship is “fake,” we structured the analysis around four specific evaluation pillars:

  • Financial transparency
  • Digital footprint
  • Recruitment authenticity
  • Marketing credibility

The system takes internship ads, screenshots, emails, company descriptions, and URLs as input. It then analyzes the content and generates a legitimacy score between 0 and 100.

But the important part wasn’t generating a score.

The difficult part was making the scoring explainable.

The Rule That Changed Everything

One design decision became the foundation of the entire system:

If a company asks students to pay upfront fees, the legitimacy score is automatically capped below 30.

That single rule solved multiple problems at once.

Without it, the LLM occasionally produced high scores for suspicious internships simply because the company had a polished website or strong marketing language.

In reality, legitimate internships rarely require students to pay to work.

So instead of relying purely on probabilistic reasoning, we introduced deterministic penalties for critical red flags.

That hybrid approach produced much more reliable outputs.

How The System Works

The frontend was built using React, Vite, and Tailwind CSS.

Students can:

  • Upload screenshots
  • Paste internship descriptions
  • Add company details
  • Submit emails or URLs

The backend uses Express.js and Multer for request handling and file uploads.

The analysis pipeline sends structured prompts to Groq running LLaMA 3 70B.

Instead of asking broad questions, the prompt forces the model to evaluate internships through individual categories.

For example:

  • Does the company use a corporate domain?
  • Is the recruitment process realistic?
  • Does the offer use urgency tactics?
  • Are responsibilities clearly defined?
  • Is there evidence of a real digital footprint?

Each category contributes to the final score independently.

That structure made the outputs significantly more consistent.

One Unexpected Problem

The first versions of the system were too optimistic.

The model often interpreted professional-looking language as credibility.

That became a serious issue because scam internships are usually designed to appear highly professional.

We had to redesign the scoring logic so that suspicious financial behavior outweighed surface-level presentation quality.

This became one of the biggest lessons we learned while building the project:

LLMs are good at pattern recognition, but trust systems still need hard constraints.

Why Explainability Matters

One thing we intentionally avoided was producing only a final verdict.

A simple “fake” or “real” label isn’t very useful to students.

Instead, the system returns:

  • positive indicators
  • red flags
  • category breakdowns
  • actionable recommendations

That way, students understand why an internship appears suspicious.

In practice, explainability matters more than raw scoring accuracy because users need confidence in the reasoning process.

Building the Frontend

We wanted the interface to feel less like an academic tool and more like a modern product.

So we added:

  • drag-and-drop uploads
  • animated score gauges
  • color-coded verdicts
  • responsive layouts
  • dark mode support

The goal was to make the analysis feel immediate and intuitive.

Tech Stack

Frontend:

  • React 18
  • Vite
  • Tailwind CSS
  • Axios

Backend:

  • Node.js
  • Express.js
  • Multer

AI Layer:

  • Groq API
  • LLaMA 3 70B

What We Learned

Building this project changed the way we think about AI-assisted trust systems.

A few lessons stood out:

  1. Pure LLM reasoning is not enough for fraud detection.
    Critical rules still need deterministic enforcement.

  2. Explainability matters more than confidence scores.
    Users trust systems that show reasoning transparently.

  3. Scam detection is largely behavioral analysis.
    Many fake internships reveal themselves through recruitment patterns rather than obvious technical signals.

  4. Small prompt structure changes drastically affect consistency.
    Breaking scoring into categories improved output quality significantly.

Final Thoughts

Internship scams are becoming increasingly sophisticated, especially in online hiring spaces.

We don’t think AI alone can solve that problem.

But we do think systems that combine structured rules with language models can help students make safer decisions faster.

That was the goal behind ShieldIntern.

GitHub Repository:
https://github.com/ryxonix/HackWithBangalore

Your Personal AI Stack Is the New Dotfiles

Every senior engineer who has shipped meaningful work in the last thirty years has carried a personal dev environment with them. Emacs configs, vim plugins, shell aliases, dotfiles repos, custom prompts, terminal multiplexer setups, a handful of scripts that exist only on their laptop and do exactly what the work needs. Nobody waited for IT to mandate the right .bashrc. The configurations that actually got used were the ones tuned to the operator, by the operator, and accumulated over years.

AI adoption is the same shape, on a thirty-year delay. The “wait for the enterprise plan to roll out” path is the same path that left people running Outlook in 1998 while the early adopters ran their own mail server with elm and procmail. The configuration that wins, again, is the one tuned to your work — not the team average.

The Institutional Lag Is Structural, Not Solvable

The enterprise AI committee, the IT rollout, the sanctioned LLM provider, the official acceptable-use policy — these are eighteen to twenty-four months behind what the team’s power users already do. The cause is structural. Committees cannot iterate at the rate of an individual operator who is using the tool every day and rewiring their workflow weekly. Putting better people on the committee does not fix this; the structure itself caps the rate of change.

The historical record is unambiguous. Git was an individual-power-user tool from Linus’s 2005 release through about 2010, and only became enterprise standard somewhere around 2015 — a full decade after it existed. As of the 2025 Stack Overflow Developer Survey, Git sits above 90% adoption across professional developers. The enterprise mandate followed the power-user adoption by years. Same story for Slack (founded 2013, dominant by ~2019), Docker (released 2013, enterprise standard by ~2017), VS Code (released 2015, dominant IDE by ~2019). The mandate always followed.

The people who outperformed in each of those windows were the people who adopted early, built personal infrastructure around the new tool, and accumulated workflow taste before the enterprise plan caught up. In every case, the official plan eventually arrived, and in every case it was late, incomplete, and missing the discipline-specific patterns the power users had already worked out. The same thing is happening with AI right now.

What a Personal AI Stack Actually Is

The concrete components are not exotic. Most of them ship in the tools you already have. The work is in assembling them.

A persistent memory layer in files you own. CLAUDE.md, MEMORY.md, per-project context files, an agents/ directory of role-specific context. Not vendor memory. Filesystem memory that travels with you across providers and survives any model deprecation. This is the wrapper-pattern argument from earlier this month.

A hooks system that enforces your taste. Anthropic shipped hooks in Claude Code — PreToolUse, PostToolUse, Stop, SessionStart, SubagentStop, UserPromptSubmit. The hooks are how you encode your own non-negotiables: don’t let the agent run a destructive command without confirmation, lint every write, log every session, refuse to commit with TODO markers. The hook is the editor’s auto-format on save for AI work.

A set of slash commands for your repeatable workflows. The five or six things you do every week — the standup digest, the PR review pass, the architecture sketch, the test triage — get encoded as one-character invocations. The commands are personal because the workflows are personal.

Skills, the procedural memory layer. Anthropic’s skills documentation covers the platform-native version. The open standard at agentskills.io makes skills portable across agents — Claude Code, Codex, Gemini CLI, the Hermes orchestrator from yesterday’s piece. A skill captures a pattern you have already executed enough times to formalize.

MCP servers wrapping the tools you actually use daily. Not a marketplace download. A small set of MCP integrations for the specific systems your work touches — your data warehouse, your project tracker, your finance system, your private docs. Most people will end up writing one or two themselves; the rest can be borrowed.

An orchestrator-worker compose. Claude Code as the in-session worker, a wrapper like Hermes Agent (or one you write yourself) as the durable cross-session orchestrator. The compose pattern was the argument of yesterday’s piece and it is the structural answer to single-vendor lock-in.

That is the kit. None of these components is hard individually. The work is in assembling and tuning them to the actual job.

Why “The Way You Want” Matters

Enterprise AI plans optimize for the median user, which is by definition not you. The median user does not have your discipline-specific edge cases, your taste in code, your judgment about what is worth automating, the specific failure modes you have learned to anticipate from a decade of doing the work. The committee output is a lowest-common-denominator policy, and lowest-common-denominator policies produce lowest-common-denominator outputs.

A personal AI stack optimizes for the operator, which is you. The skill that captures your specific way of running a PR review will outperform a generic prompt template. The hook that enforces your team’s actual code conventions will outperform the model’s default style guide. The memory file that holds your project’s actual history will outperform a context window that starts empty every Monday.

How the Personal Stack Becomes the Official One

This is the part the institutional planners get wrong. Every enterprise standard started as one person’s hobby project. The path is consistent across thirty years of tools: someone builds it for themselves; it outperforms the team’s sanctioned approach; other engineers adopt it informally; the informal pattern becomes “how we do this here”; eventually official sanction follows, or the official plan is quietly replaced by the personal pattern.

This is happening at companies right now with AI infrastructure, in places where the official plan has not yet arrived. A working content pipeline that ships across five surfaces a day with a SQLite memory database and a hand-rolled orchestration layer — for a concrete example, the kind of system the marketing team would have built if there were a paved road — starts as one engineer’s weekend project and ends as the de facto company standard. The official plan eventually arrives and either ratifies the existing pattern or admits it lost.

The Honest Caveat

Some employers will discipline shadow tooling on principle. If your environment is one of those, you have to play by it. But most companies do not. Most companies have a vague “AI policy in progress” posture that buys nine to eighteen months of operator latitude, and the operators who use that window will be the ones authoring the policy when it eventually drops. The right posture during that window is the same posture senior engineers have always taken with personal infrastructure: do not ask permission for your own dev environment, ship value, let the work speak.

The Window

The official AI adoption plan at most companies will land in 2027 or 2028. It will be late, incomplete, and miss the discipline-specific work you do. The personal AI stack you build in 2026 is the only piece under your direct control. The institutional plan will, as it has every time before this, eventually follow the people who built theirs early.

Build the stack you want. Make it the official one by being the person who knew how before the committee did.